diff --git a/lib/mayaUsd/base/debugCodes.cpp b/lib/mayaUsd/base/debugCodes.cpp index d290ae438e..9ac5276ea9 100644 --- a/lib/mayaUsd/base/debugCodes.cpp +++ b/lib/mayaUsd/base/debugCodes.cpp @@ -21,16 +21,13 @@ PXR_NAMESPACE_OPEN_SCOPE TF_REGISTRY_FUNCTION(TfDebug) { - TF_DEBUG_ENVIRONMENT_SYMBOL(PXRUSDMAYA_REGISTRY, - "UsdMaya registration for usd types."); - TF_DEBUG_ENVIRONMENT_SYMBOL(PXRUSDMAYA_DIAGNOSTICS, - "Debugging of the the diagnostics batching system in UsdMaya."); - TF_DEBUG_ENVIRONMENT_SYMBOL(PXRUSDMAYA_TRANSLATORS, - "Debugging of translators."); - TF_DEBUG_ENVIRONMENT_SYMBOL(USDMAYA_PROXYSHAPEBASE, - "Base proxy shape evaluation"); - TF_DEBUG_ENVIRONMENT_SYMBOL(USDMAYA_PROXYACCESSOR, - "Debugging of the evaluation for mixed data models."); + TF_DEBUG_ENVIRONMENT_SYMBOL(PXRUSDMAYA_REGISTRY, "UsdMaya registration for usd types."); + TF_DEBUG_ENVIRONMENT_SYMBOL( + PXRUSDMAYA_DIAGNOSTICS, "Debugging of the the diagnostics batching system in UsdMaya."); + TF_DEBUG_ENVIRONMENT_SYMBOL(PXRUSDMAYA_TRANSLATORS, "Debugging of translators."); + TF_DEBUG_ENVIRONMENT_SYMBOL(USDMAYA_PROXYSHAPEBASE, "Base proxy shape evaluation"); + TF_DEBUG_ENVIRONMENT_SYMBOL( + USDMAYA_PROXYACCESSOR, "Debugging of the evaluation for mixed data models."); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/base/debugCodes.h b/lib/mayaUsd/base/debugCodes.h index 9209ee46e2..b2b2fcc755 100644 --- a/lib/mayaUsd/base/debugCodes.h +++ b/lib/mayaUsd/base/debugCodes.h @@ -16,8 +16,8 @@ #ifndef PXRUSDMAYA_DEBUGCODES_H #define PXRUSDMAYA_DEBUGCODES_H -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -26,8 +26,7 @@ TF_DEBUG_CODES( PXRUSDMAYA_DIAGNOSTICS, PXRUSDMAYA_TRANSLATORS, USDMAYA_PROXYSHAPEBASE, - USDMAYA_PROXYACCESSOR -); + USDMAYA_PROXYACCESSOR); PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/commands/baseExportCommand.cpp b/lib/mayaUsd/commands/baseExportCommand.cpp index 01a9ffde4f..7386d87a40 100644 --- a/lib/mayaUsd/commands/baseExportCommand.cpp +++ b/lib/mayaUsd/commands/baseExportCommand.cpp @@ -16,19 +16,19 @@ // #include "baseExportCommand.h" -#include +#include +#include #include -#include -#include #include #include #include +#include #include +#include -#include -#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -40,115 +40,122 @@ MSyntax MayaUSDExportCommand::createSyntax() // These flags correspond to entries in // UsdMayaJobExportArgs::GetDefaultDictionary. - syntax.addFlag(kMergeTransformAndShapeFlag, - UsdMayaJobExportArgsTokens->mergeTransformAndShape.GetText(), - MSyntax::kBoolean); - syntax.addFlag(kExportInstancesFlag, - UsdMayaJobExportArgsTokens->exportInstances.GetText(), - MSyntax::kBoolean); - syntax.addFlag(kExportRefsAsInstanceableFlag, - UsdMayaJobExportArgsTokens->exportRefsAsInstanceable.GetText(), - MSyntax::kBoolean); - syntax.addFlag(kExportDisplayColorFlag, - UsdMayaJobExportArgsTokens->exportDisplayColor.GetText(), - MSyntax::kBoolean); - syntax.addFlag(kShadingModeFlag, - UsdMayaJobExportArgsTokens->shadingMode.GetText(), - MSyntax::kString); - syntax.addFlag(kConvertMaterialsToFlag, - UsdMayaJobExportArgsTokens->convertMaterialsTo.GetText(), - MSyntax::kString); - syntax.addFlag(kMaterialsScopeNameFlag, - UsdMayaJobExportArgsTokens->materialsScopeName.GetText(), - MSyntax::kString); - syntax.addFlag(kExportUVsFlag, - UsdMayaJobExportArgsTokens->exportUVs.GetText(), - MSyntax::kBoolean); - syntax.addFlag(kExportMaterialCollectionsFlag, - UsdMayaJobExportArgsTokens->exportMaterialCollections - .GetText(), - MSyntax::kBoolean); - syntax.addFlag(kMaterialCollectionsPathFlag, - UsdMayaJobExportArgsTokens->materialCollectionsPath.GetText(), - MSyntax::kString); - syntax.addFlag(kExportCollectionBasedBindingsFlag, - UsdMayaJobExportArgsTokens->exportCollectionBasedBindings - .GetText(), - MSyntax::kBoolean); - syntax.addFlag(kNormalizeNurbsFlag, - UsdMayaJobExportArgsTokens->normalizeNurbs.GetText() , - MSyntax::kBoolean); - syntax.addFlag(kExportColorSetsFlag, - UsdMayaJobExportArgsTokens->exportColorSets.GetText(), - MSyntax::kBoolean); - syntax.addFlag(kStripNamespacesFlag, - UsdMayaJobExportArgsTokens->stripNamespaces.GetText(), - MSyntax::kBoolean); - syntax.addFlag(kEulerFilterFlag, - UsdMayaJobExportArgsTokens->eulerFilter.GetText(), - MSyntax::kBoolean); - syntax.addFlag(kDefaultMeshSchemeFlag, - UsdMayaJobExportArgsTokens->defaultMeshScheme.GetText(), - MSyntax::kString); - syntax.addFlag(kDefaultUSDFormatFlag, - UsdMayaJobExportArgsTokens->defaultUSDFormat.GetText(), - MSyntax::kString); - syntax.addFlag(kExportVisibilityFlag, - UsdMayaJobExportArgsTokens->exportVisibility.GetText(), - MSyntax::kBoolean); - syntax.addFlag(kExportReferenceObjectsFlag, - UsdMayaJobExportArgsTokens->exportReferenceObjects.GetText(), - MSyntax::kBoolean); - syntax.addFlag(kExportSkelsFlag, - UsdMayaJobExportArgsTokens->exportSkels.GetText(), - MSyntax::kString); - syntax.addFlag(kExportSkinFlag, - UsdMayaJobExportArgsTokens->exportSkin.GetText(), - MSyntax::kString); - syntax.addFlag(kParentScopeFlag, - UsdMayaJobExportArgsTokens->parentScope.GetText(), - MSyntax::kString); - syntax.addFlag(kRenderableOnlyFlag, - UsdMayaJobExportArgsTokens->renderableOnly.GetText(), - MSyntax::kNoArg); - syntax.addFlag(kDefaultCamerasFlag, - UsdMayaJobExportArgsTokens->defaultCameras.GetText(), - MSyntax::kNoArg); - syntax.addFlag(kRenderLayerModeFlag, - UsdMayaJobExportArgsTokens->renderLayerMode.GetText(), - MSyntax::kString); - syntax.addFlag(kKindFlag, - UsdMayaJobExportArgsTokens->kind.GetText(), - MSyntax::kString); - syntax.addFlag(kCompatibilityFlag, - UsdMayaJobExportArgsTokens->compatibility.GetText(), - MSyntax::kString); - - syntax.addFlag(kChaserFlag, - UsdMayaJobExportArgsTokens->chaser.GetText(), - MSyntax::kString); + syntax.addFlag( + kMergeTransformAndShapeFlag, + UsdMayaJobExportArgsTokens->mergeTransformAndShape.GetText(), + MSyntax::kBoolean); + syntax.addFlag( + kExportInstancesFlag, + UsdMayaJobExportArgsTokens->exportInstances.GetText(), + MSyntax::kBoolean); + syntax.addFlag( + kExportRefsAsInstanceableFlag, + UsdMayaJobExportArgsTokens->exportRefsAsInstanceable.GetText(), + MSyntax::kBoolean); + syntax.addFlag( + kExportDisplayColorFlag, + UsdMayaJobExportArgsTokens->exportDisplayColor.GetText(), + MSyntax::kBoolean); + syntax.addFlag( + kShadingModeFlag, UsdMayaJobExportArgsTokens->shadingMode.GetText(), MSyntax::kString); + syntax.addFlag( + kConvertMaterialsToFlag, + UsdMayaJobExportArgsTokens->convertMaterialsTo.GetText(), + MSyntax::kString); + syntax.addFlag( + kMaterialsScopeNameFlag, + UsdMayaJobExportArgsTokens->materialsScopeName.GetText(), + MSyntax::kString); + syntax.addFlag( + kExportUVsFlag, UsdMayaJobExportArgsTokens->exportUVs.GetText(), MSyntax::kBoolean); + syntax.addFlag( + kExportMaterialCollectionsFlag, + UsdMayaJobExportArgsTokens->exportMaterialCollections.GetText(), + MSyntax::kBoolean); + syntax.addFlag( + kMaterialCollectionsPathFlag, + UsdMayaJobExportArgsTokens->materialCollectionsPath.GetText(), + MSyntax::kString); + syntax.addFlag( + kExportCollectionBasedBindingsFlag, + UsdMayaJobExportArgsTokens->exportCollectionBasedBindings.GetText(), + MSyntax::kBoolean); + syntax.addFlag( + kNormalizeNurbsFlag, + UsdMayaJobExportArgsTokens->normalizeNurbs.GetText(), + MSyntax::kBoolean); + syntax.addFlag( + kExportColorSetsFlag, + UsdMayaJobExportArgsTokens->exportColorSets.GetText(), + MSyntax::kBoolean); + syntax.addFlag( + kStripNamespacesFlag, + UsdMayaJobExportArgsTokens->stripNamespaces.GetText(), + MSyntax::kBoolean); + syntax.addFlag( + kEulerFilterFlag, UsdMayaJobExportArgsTokens->eulerFilter.GetText(), MSyntax::kBoolean); + syntax.addFlag( + kDefaultMeshSchemeFlag, + UsdMayaJobExportArgsTokens->defaultMeshScheme.GetText(), + MSyntax::kString); + syntax.addFlag( + kDefaultUSDFormatFlag, + UsdMayaJobExportArgsTokens->defaultUSDFormat.GetText(), + MSyntax::kString); + syntax.addFlag( + kExportVisibilityFlag, + UsdMayaJobExportArgsTokens->exportVisibility.GetText(), + MSyntax::kBoolean); + syntax.addFlag( + kExportReferenceObjectsFlag, + UsdMayaJobExportArgsTokens->exportReferenceObjects.GetText(), + MSyntax::kBoolean); + syntax.addFlag( + kExportSkelsFlag, UsdMayaJobExportArgsTokens->exportSkels.GetText(), MSyntax::kString); + syntax.addFlag( + kExportSkinFlag, UsdMayaJobExportArgsTokens->exportSkin.GetText(), MSyntax::kString); + syntax.addFlag( + kParentScopeFlag, UsdMayaJobExportArgsTokens->parentScope.GetText(), MSyntax::kString); + syntax.addFlag( + kRenderableOnlyFlag, UsdMayaJobExportArgsTokens->renderableOnly.GetText(), MSyntax::kNoArg); + syntax.addFlag( + kDefaultCamerasFlag, UsdMayaJobExportArgsTokens->defaultCameras.GetText(), MSyntax::kNoArg); + syntax.addFlag( + kRenderLayerModeFlag, + UsdMayaJobExportArgsTokens->renderLayerMode.GetText(), + MSyntax::kString); + syntax.addFlag(kKindFlag, UsdMayaJobExportArgsTokens->kind.GetText(), MSyntax::kString); + syntax.addFlag( + kCompatibilityFlag, UsdMayaJobExportArgsTokens->compatibility.GetText(), MSyntax::kString); + + syntax.addFlag(kChaserFlag, UsdMayaJobExportArgsTokens->chaser.GetText(), MSyntax::kString); syntax.makeFlagMultiUse(UsdMayaJobExportArgsTokens->chaser.GetText()); - syntax.addFlag(kChaserArgsFlag, - UsdMayaJobExportArgsTokens->chaserArgs.GetText(), - MSyntax::kString, MSyntax::kString, MSyntax::kString); + syntax.addFlag( + kChaserArgsFlag, + UsdMayaJobExportArgsTokens->chaserArgs.GetText(), + MSyntax::kString, + MSyntax::kString, + MSyntax::kString); syntax.makeFlagMultiUse(UsdMayaJobExportArgsTokens->chaserArgs.GetText()); - syntax.addFlag(kMelPerFrameCallbackFlag, - UsdMayaJobExportArgsTokens->melPerFrameCallback.GetText(), - MSyntax::kNoArg); - syntax.addFlag(kMelPostCallbackFlag, - UsdMayaJobExportArgsTokens->melPostCallback.GetText(), - MSyntax::kNoArg); - syntax.addFlag(kPythonPerFrameCallbackFlag, - UsdMayaJobExportArgsTokens->pythonPerFrameCallback.GetText(), - MSyntax::kString); - syntax.addFlag(kPythonPostCallbackFlag, - UsdMayaJobExportArgsTokens->pythonPostCallback.GetText(), - MSyntax::kString); - syntax.addFlag(kVerboseFlag, - UsdMayaJobExportArgsTokens->verbose.GetText(), - MSyntax::kNoArg); + syntax.addFlag( + kMelPerFrameCallbackFlag, + UsdMayaJobExportArgsTokens->melPerFrameCallback.GetText(), + MSyntax::kNoArg); + syntax.addFlag( + kMelPostCallbackFlag, + UsdMayaJobExportArgsTokens->melPostCallback.GetText(), + MSyntax::kNoArg); + syntax.addFlag( + kPythonPerFrameCallbackFlag, + UsdMayaJobExportArgsTokens->pythonPerFrameCallback.GetText(), + MSyntax::kString); + syntax.addFlag( + kPythonPostCallbackFlag, + UsdMayaJobExportArgsTokens->pythonPostCallback.GetText(), + MSyntax::kString); + syntax.addFlag(kVerboseFlag, UsdMayaJobExportArgsTokens->verbose.GetText(), MSyntax::kNoArg); // These are additional flags under our control. syntax.addFlag(kFrameRangeFlag, kFrameRangeFlagLong, MSyntax::kDouble, MSyntax::kDouble); @@ -172,134 +179,128 @@ MSyntax MayaUSDExportCommand::createSyntax() return syntax; } -void* MayaUSDExportCommand::creator() -{ - return new MayaUSDExportCommand(); -} +void* MayaUSDExportCommand::creator() { return new MayaUSDExportCommand(); } /* virtual */ -std::unique_ptr MayaUSDExportCommand::initializeWriteJob(const PXR_NS::UsdMayaJobExportArgs & args) +std::unique_ptr +MayaUSDExportCommand::initializeWriteJob(const PXR_NS::UsdMayaJobExportArgs& args) { return std::unique_ptr(new UsdMaya_WriteJob(args)); } -MStatus MayaUSDExportCommand::doIt(const MArgList & args) -{ -try +MStatus MayaUSDExportCommand::doIt(const MArgList& args) { - MStatus status; + try { + MStatus status; - MArgDatabase argData(syntax(), args, &status); + MArgDatabase argData(syntax(), args, &status); - // Check that all flags were valid - if (status != MS::kSuccess) { - return status; - } + // Check that all flags were valid + if (status != MS::kSuccess) { + return status; + } - // Read all of the dictionary args first. - const VtDictionary userArgs = UsdMayaUtil::GetDictionaryFromArgDatabase( + // Read all of the dictionary args first. + const VtDictionary userArgs = UsdMayaUtil::GetDictionaryFromArgDatabase( argData, UsdMayaJobExportArgs::GetDefaultDictionary()); - // Now read all of the other args that are specific to this command. - bool append = false; - std::string fileName; + // Now read all of the other args that are specific to this command. + bool append = false; + std::string fileName; - if (argData.isFlagSet(kAppendFlag)) { - argData.getFlagArgument(kAppendFlag, 0, append); - } - - if (argData.isFlagSet(kFileFlag)) - { - // Get the value - MString tmpVal; - argData.getFlagArgument(kFileFlag, 0, tmpVal); + if (argData.isFlagSet(kAppendFlag)) { + argData.getFlagArgument(kAppendFlag, 0, append); + } - // resolve the path into an absolute path - MFileObject absoluteFile; - absoluteFile.setRawFullName(tmpVal); - absoluteFile.setRawFullName( absoluteFile.resolvedFullName() ); // Make sure an absolute path - fileName = absoluteFile.resolvedFullName().asChar(); + if (argData.isFlagSet(kFileFlag)) { + // Get the value + MString tmpVal; + argData.getFlagArgument(kFileFlag, 0, tmpVal); + + // resolve the path into an absolute path + MFileObject absoluteFile; + absoluteFile.setRawFullName(tmpVal); + absoluteFile.setRawFullName( + absoluteFile.resolvedFullName()); // Make sure an absolute path + fileName = absoluteFile.resolvedFullName().asChar(); + + if (fileName.empty()) { + fileName = tmpVal.asChar(); + } + } else { + TF_RUNTIME_ERROR("-file not specified."); + return MS::kFailure; + } if (fileName.empty()) { - fileName = tmpVal.asChar(); + return MS::kFailure; } - } - else { - TF_RUNTIME_ERROR("-file not specified."); - return MS::kFailure; - } - - if (fileName.empty()) { - return MS::kFailure; - } - // If you provide a frame range we consider this an anim - // export even if start and end are the same - GfInterval timeInterval; - if (argData.isFlagSet(kFrameRangeFlag)) { - double startTime = 1; - double endTime = 1; - argData.getFlagArgument(kFrameRangeFlag, 0, startTime); - argData.getFlagArgument(kFrameRangeFlag, 1, endTime); - if (startTime > endTime) { - // If the user accidentally set start > end, resync to the closed - // interval with the single start point. - timeInterval = GfInterval(startTime); + // If you provide a frame range we consider this an anim + // export even if start and end are the same + GfInterval timeInterval; + if (argData.isFlagSet(kFrameRangeFlag)) { + double startTime = 1; + double endTime = 1; + argData.getFlagArgument(kFrameRangeFlag, 0, startTime); + argData.getFlagArgument(kFrameRangeFlag, 1, endTime); + if (startTime > endTime) { + // If the user accidentally set start > end, resync to the closed + // interval with the single start point. + timeInterval = GfInterval(startTime); + } else { + // Use the user's interval as-is. + timeInterval = GfInterval(startTime, endTime); + } + } else { + // No animation, so empty interval. + timeInterval = GfInterval(); } - else { - // Use the user's interval as-is. - timeInterval = GfInterval(startTime, endTime); + + double frameStride = 1.0; + if (argData.isFlagSet(kFrameStrideFlag)) { + argData.getFlagArgument(kFrameStrideFlag, 0, frameStride); } - } else { - // No animation, so empty interval. - timeInterval = GfInterval(); - } - double frameStride = 1.0; - if (argData.isFlagSet(kFrameStrideFlag)) { - argData.getFlagArgument(kFrameStrideFlag, 0, frameStride); - } + std::set frameSamples; + unsigned int numFrameSamples = argData.numberOfFlagUses(kFrameSampleFlag); + for (unsigned int i = 0; i < numFrameSamples; ++i) { + MArgList tmpArgList; + argData.getFlagArgumentList(kFrameSampleFlag, i, tmpArgList); + frameSamples.insert(tmpArgList.asDouble(0)); + } - std::set frameSamples; - unsigned int numFrameSamples = argData.numberOfFlagUses(kFrameSampleFlag); - for (unsigned int i = 0; i < numFrameSamples; ++i) { - MArgList tmpArgList; - argData.getFlagArgumentList(kFrameSampleFlag, i, tmpArgList); - frameSamples.insert(tmpArgList.asDouble(0)); - } + MSelectionList objSelList; + UsdMayaUtil::MDagPathSet dagPaths; + bool exportSelected = argData.isFlagSet(kSelectionFlag); + if (!exportSelected) { + argData.getObjects(objSelList); + } + UsdMayaUtil::GetFilteredSelectionToExport(exportSelected, objSelList, dagPaths); + + const std::vector timeSamples + = UsdMayaWriteUtil::GetTimeSamples(timeInterval, frameSamples, frameStride); + UsdMayaJobExportArgs jobArgs + = UsdMayaJobExportArgs::CreateFromDictionary(userArgs, dagPaths, timeSamples); + + unsigned int numFilteredTypes = argData.numberOfFlagUses(kFilterTypesFlag); + for (unsigned int i = 0; i < numFilteredTypes; i++) { + MArgList tmpArgList; + argData.getFlagArgumentList(kFilterTypesFlag, i, tmpArgList); + jobArgs.AddFilteredTypeName(tmpArgList.asString(0)); + } - MSelectionList objSelList; - UsdMayaUtil::MDagPathSet dagPaths; - bool exportSelected = argData.isFlagSet(kSelectionFlag); - if (!exportSelected) { - argData.getObjects(objSelList); - } - UsdMayaUtil::GetFilteredSelectionToExport(exportSelected, objSelList, dagPaths); - - const std::vector timeSamples = UsdMayaWriteUtil::GetTimeSamples( - timeInterval, frameSamples, frameStride); - UsdMayaJobExportArgs jobArgs = UsdMayaJobExportArgs::CreateFromDictionary( - userArgs, dagPaths, timeSamples); - - unsigned int numFilteredTypes = argData.numberOfFlagUses(kFilterTypesFlag); - for (unsigned int i=0; i < numFilteredTypes; i++) { - MArgList tmpArgList; - argData.getFlagArgumentList(kFilterTypesFlag, i, tmpArgList); - jobArgs.AddFilteredTypeName(tmpArgList.asString(0)); - } + std::unique_ptr writeJob = initializeWriteJob(jobArgs); + if (!writeJob || !writeJob->Write(fileName, append)) { + return MS::kFailure; + } - std::unique_ptr writeJob = initializeWriteJob(jobArgs); - if (!writeJob || !writeJob->Write(fileName, append)) { + return MS::kSuccess; + } // end of try block + catch (std::exception& e) { + TF_RUNTIME_ERROR("std::exception encountered: %s", e.what()); return MS::kFailure; } - - return MS::kSuccess; -} // end of try block -catch (std::exception & e) -{ - TF_RUNTIME_ERROR("std::exception encountered: %s", e.what()); - return MS::kFailure; -} } // end of function -} // MAYAUSD_NS_DEF +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/commands/baseExportCommand.h b/lib/mayaUsd/commands/baseExportCommand.h index ec3d2178db..7dab0dce1b 100644 --- a/lib/mayaUsd/commands/baseExportCommand.h +++ b/lib/mayaUsd/commands/baseExportCommand.h @@ -18,20 +18,19 @@ #define MAYA_EXPORT_COMMAND_H #include +#include #include -#include - #include -#include +#include namespace MAYAUSD_NS_DEF { class MAYAUSD_CORE_PUBLIC MayaUSDExportCommand : public MPxCommand { - public: +public: // // Command flags are a mix of Arg Tokens defined in writeJob.h // and some that are defined by this command itself. @@ -95,16 +94,16 @@ class MAYAUSD_CORE_PUBLIC MayaUSDExportCommand : public MPxCommand static constexpr auto kFrameRangeFlagLong = "frameRange"; MStatus doIt(const MArgList& args) override; - bool isUndoable () const override { return false; }; - - static MSyntax createSyntax(); - static void* creator(); + bool isUndoable() const override { return false; }; - protected: - virtual std::unique_ptr initializeWriteJob(const PXR_NS::UsdMayaJobExportArgs &); + static MSyntax createSyntax(); + static void* creator(); +protected: + virtual std::unique_ptr + initializeWriteJob(const PXR_NS::UsdMayaJobExportArgs&); }; -} +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/mayaUsd/commands/baseImportCommand.cpp b/lib/mayaUsd/commands/baseImportCommand.cpp index f2f34f8933..a87f92d26b 100644 --- a/lib/mayaUsd/commands/baseImportCommand.cpp +++ b/lib/mayaUsd/commands/baseImportCommand.cpp @@ -16,60 +16,61 @@ // #include "baseImportCommand.h" -#include +#include +#include +#include #include #include #include +#include #include #include -#include -#include -#include -#include +#include PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { /* static */ -MSyntax -MayaUSDImportCommand::createSyntax() +MSyntax MayaUSDImportCommand::createSyntax() { MSyntax syntax; // These flags correspond to entries in // UsdMayaJobImportArgs::GetDefaultDictionary. - syntax.addFlag(kShadingModeFlag, - UsdMayaJobImportArgsTokens->shadingMode.GetText(), - MSyntax::kString, MSyntax::kString); + syntax.addFlag( + kShadingModeFlag, + UsdMayaJobImportArgsTokens->shadingMode.GetText(), + MSyntax::kString, + MSyntax::kString); syntax.makeFlagMultiUse(kShadingModeFlag); - syntax.addFlag(kPreferredMaterialFlag, - UsdMayaJobImportArgsTokens->preferredMaterial.GetText(), - MSyntax::kString); - syntax.addFlag(kAssemblyRepFlag, - UsdMayaJobImportArgsTokens->assemblyRep.GetText(), - MSyntax::kString); - syntax.addFlag(kImportInstancesFlag, - UsdMayaJobImportArgsTokens->importInstances.GetText(), - MSyntax::kString); - syntax.addFlag(kMetadataFlag, - UsdMayaJobImportArgsTokens->metadata.GetText(), - MSyntax::kString); + syntax.addFlag( + kPreferredMaterialFlag, + UsdMayaJobImportArgsTokens->preferredMaterial.GetText(), + MSyntax::kString); + syntax.addFlag( + kAssemblyRepFlag, UsdMayaJobImportArgsTokens->assemblyRep.GetText(), MSyntax::kString); + syntax.addFlag( + kImportInstancesFlag, + UsdMayaJobImportArgsTokens->importInstances.GetText(), + MSyntax::kString); + syntax.addFlag(kMetadataFlag, UsdMayaJobImportArgsTokens->metadata.GetText(), MSyntax::kString); syntax.makeFlagMultiUse(kMetadataFlag); - syntax.addFlag(kApiSchemaFlag, - UsdMayaJobImportArgsTokens->apiSchema.GetText(), - MSyntax::kString); + syntax.addFlag( + kApiSchemaFlag, UsdMayaJobImportArgsTokens->apiSchema.GetText(), MSyntax::kString); syntax.makeFlagMultiUse(kApiSchemaFlag); - syntax.addFlag(kExcludePrimvarFlag, - UsdMayaJobImportArgsTokens->excludePrimvar.GetText(), - MSyntax::kString); + syntax.addFlag( + kExcludePrimvarFlag, + UsdMayaJobImportArgsTokens->excludePrimvar.GetText(), + MSyntax::kString); syntax.makeFlagMultiUse(kExcludePrimvarFlag); - syntax.addFlag(kUseAsAnimationCacheFlag, - UsdMayaJobImportArgsTokens->useAsAnimationCache.GetText(), - MSyntax::kBoolean); + syntax.addFlag( + kUseAsAnimationCacheFlag, + UsdMayaJobImportArgsTokens->useAsAnimationCache.GetText(), + MSyntax::kBoolean); // These are additional flags under our control. syntax.addFlag(kFileFlag, kFileFlagLong, MSyntax::kString); @@ -89,22 +90,18 @@ MayaUSDImportCommand::createSyntax() } /* static */ -void* -MayaUSDImportCommand::creator() -{ - return new MayaUSDImportCommand(); -} +void* MayaUSDImportCommand::creator() { return new MayaUSDImportCommand(); } /* virtual */ -std::unique_ptr MayaUSDImportCommand::initializeReadJob(const MayaUsd::ImportData & data, - const UsdMayaJobImportArgs & args) +std::unique_ptr MayaUSDImportCommand::initializeReadJob( + const MayaUsd::ImportData& data, + const UsdMayaJobImportArgs& args) { return std::unique_ptr(new UsdMaya_ReadJob(data, args)); } /* virtual */ -MStatus -MayaUSDImportCommand::doIt(const MArgList & args) +MStatus MayaUSDImportCommand::doIt(const MArgList& args) { MStatus status; @@ -116,10 +113,8 @@ MayaUSDImportCommand::doIt(const MArgList & args) } // Get dictionary values. - const VtDictionary userArgs = - UsdMayaUtil::GetDictionaryFromArgDatabase( - argData, - UsdMayaJobImportArgs::GetDefaultDictionary()); + const VtDictionary userArgs = UsdMayaUtil::GetDictionaryFromArgDatabase( + argData, UsdMayaJobImportArgs::GetDefaultDictionary()); std::string mFileName; if (argData.isFlagSet(kFileFlag)) { @@ -131,9 +126,9 @@ MayaUSDImportCommand::doIt(const MArgList & args) // Use the usd resolver for validation (but save the unresolved) if (ArGetResolver().Resolve(mFileName).empty()) { TF_RUNTIME_ERROR( - "File '%s' does not exist, or could not be resolved. " - "Exiting.", - mFileName.c_str()); + "File '%s' does not exist, or could not be resolved. " + "Exiting.", + mFileName.c_str()); return MS::kFailure; } @@ -146,8 +141,7 @@ MayaUSDImportCommand::doIt(const MArgList & args) } std::string mPrimPath; - if (argData.isFlagSet(kPrimPathFlag)) - { + if (argData.isFlagSet(kPrimPathFlag)) { // Get the value MString tmpVal; argData.getFlagArgument(kPrimPathFlag, 0, tmpVal); @@ -156,9 +150,8 @@ MayaUSDImportCommand::doIt(const MArgList & args) // Add variant (variantSet, variant). Multi-use SdfVariantSelectionMap mVariants; - unsigned int nbFlags = argData.numberOfFlagUses(kVariantFlag); - for (unsigned int i=0; i < nbFlags; ++i) - { + unsigned int nbFlags = argData.numberOfFlagUses(kVariantFlag); + for (unsigned int i = 0; i < nbFlags; ++i) { MArgList tmpArgList; status = argData.getFlagArgumentList(kVariantFlag, i, tmpArgList); // Get the value @@ -184,20 +177,17 @@ MayaUSDImportCommand::doIt(const MArgList & args) } timeInterval = GfInterval(startTime, endTime); - } - else { + } else { timeInterval = GfInterval::GetFullInterval(); } - } - else { + } else { timeInterval = GfInterval(); } - UsdMayaJobImportArgs jobArgs = - UsdMayaJobImportArgs::CreateFromDictionary( - userArgs, - /* importWithProxyShapes = */ false, - timeInterval); + UsdMayaJobImportArgs jobArgs = UsdMayaJobImportArgs::CreateFromDictionary( + userArgs, + /* importWithProxyShapes = */ false, + timeInterval); MayaUsd::ImportData importData(mFileName); importData.setRootVariantSelections(std::move(mVariants)); @@ -217,29 +207,24 @@ MayaUSDImportCommand::doIt(const MArgList & args) MDagPath dagPath; status = selList.getDagPath(0, dagPath); if (status != MS::kSuccess) { - TF_RUNTIME_ERROR( - "Invalid path '%s' for -parent.", - tmpVal.asChar()); + TF_RUNTIME_ERROR("Invalid path '%s' for -parent.", tmpVal.asChar()); return MS::kFailure; } - _readJob->SetMayaRootDagPath( dagPath ); + _readJob->SetMayaRootDagPath(dagPath); } } // Execute the command std::vector addedDagPaths; - bool success = _readJob->Read(&addedDagPaths); + bool success = _readJob->Read(&addedDagPaths); if (success) { - TF_FOR_ALL(iter, addedDagPaths) { - appendToResult(iter->fullPathName()); - } + TF_FOR_ALL(iter, addedDagPaths) { appendToResult(iter->fullPathName()); } } return (success) ? MS::kSuccess : MS::kFailure; } /* virtual */ -MStatus -MayaUSDImportCommand::redoIt() +MStatus MayaUSDImportCommand::redoIt() { if (!_readJob) { return MS::kFailure; @@ -251,8 +236,7 @@ MayaUSDImportCommand::redoIt() } /* virtual */ -MStatus -MayaUSDImportCommand::undoIt() +MStatus MayaUSDImportCommand::undoIt() { if (!_readJob) { return MS::kFailure; @@ -263,5 +247,4 @@ MayaUSDImportCommand::undoIt() return (success) ? MS::kSuccess : MS::kFailure; } - -} +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/commands/baseImportCommand.h b/lib/mayaUsd/commands/baseImportCommand.h index ba2b6f289a..05031adc83 100644 --- a/lib/mayaUsd/commands/baseImportCommand.h +++ b/lib/mayaUsd/commands/baseImportCommand.h @@ -18,18 +18,17 @@ #define MAYA_IMPORT_COMMAND_H #include - -#include +#include #include -#include +#include namespace MAYAUSD_NS_DEF { class MAYAUSD_CORE_PUBLIC MayaUSDImportCommand : public MPxCommand { - public: +public: // // Command flags are a mix of Arg Tokens defined in readJob.h // and some that are defined by this command itself. @@ -52,7 +51,7 @@ class MAYAUSD_CORE_PUBLIC MayaUSDImportCommand : public MPxCommand // Short and Long forms of flags defined by this command itself: static constexpr auto kFileFlag = "f"; - static constexpr auto kFileFlagLong = "file"; + static constexpr auto kFileFlagLong = "file"; static constexpr auto kParentFlag = "p"; static constexpr auto kParentFlagLong = "parent"; static constexpr auto kReadAnimDataFlag = "ani"; @@ -69,19 +68,19 @@ class MAYAUSD_CORE_PUBLIC MayaUSDImportCommand : public MPxCommand MStatus doIt(const MArgList& args) override; MStatus redoIt() override; MStatus undoIt() override; - bool isUndoable() const override { return true; }; + bool isUndoable() const override { return true; }; static MSyntax createSyntax(); - static void* creator(); + static void* creator(); - protected: - virtual std::unique_ptr initializeReadJob(const MayaUsd::ImportData &, - const UsdMayaJobImportArgs &); +protected: + virtual std::unique_ptr + initializeReadJob(const MayaUsd::ImportData&, const UsdMayaJobImportArgs&); - private: +private: std::unique_ptr _readJob; }; -} +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/mayaUsd/commands/baseListShadingModesCommand.cpp b/lib/mayaUsd/commands/baseListShadingModesCommand.cpp index 4376edf349..ef06867361 100644 --- a/lib/mayaUsd/commands/baseListShadingModesCommand.cpp +++ b/lib/mayaUsd/commands/baseListShadingModesCommand.cpp @@ -15,13 +15,13 @@ // #include "baseListShadingModesCommand.h" -#include - #include #include -#include +#include + #include +#include #include #include #include @@ -33,48 +33,48 @@ namespace MAYAUSD_NS_DEF { TF_DEFINE_PRIVATE_TOKENS( _tokens, - ((NoneOption, "none")) - ((NoneNiceName, "None")) - ((NoneExportDescription, "No material data gets exported.")) - ((NoneImportDescription, - "Stop the search for materials. Can signal that no materials are to be" - " imported when used alone.")) -); + ((NoneOption, + "none"))((NoneNiceName, "None"))((NoneExportDescription, "No material data gets exported."))( + (NoneImportDescription, + "Stop the search for materials. Can signal that no materials are to be" + " imported when used alone."))); namespace { - std::pair _GetOptions(const MString& niceName, bool isExport) { - TfToken niceToken(niceName.asChar()); +std::pair _GetOptions(const MString& niceName, bool isExport) +{ + TfToken niceToken(niceName.asChar()); - TfToken shadingMode, convertMaterialsTo; - if (niceToken == _tokens->NoneNiceName) { - return std::make_pair(_tokens->NoneOption, convertMaterialsTo); - } + TfToken shadingMode, convertMaterialsTo; + if (niceToken == _tokens->NoneNiceName) { + return std::make_pair(_tokens->NoneOption, convertMaterialsTo); + } - for (auto const& e : (isExport ? UsdMayaShadingModeRegistry::ListExporters() - : UsdMayaShadingModeRegistry::ListImporters())) { - if (niceToken == (isExport ? UsdMayaShadingModeRegistry::GetExporterNiceName(e) - : UsdMayaShadingModeRegistry::GetImporterNiceName(e))) { - shadingMode = e; - break; - } + for (auto const& e : + (isExport ? UsdMayaShadingModeRegistry::ListExporters() + : UsdMayaShadingModeRegistry::ListImporters())) { + if (niceToken + == (isExport ? UsdMayaShadingModeRegistry::GetExporterNiceName(e) + : UsdMayaShadingModeRegistry::GetImporterNiceName(e))) { + shadingMode = e; + break; } - if (shadingMode.IsEmpty()) { - for (auto const& r : UsdMayaShadingModeRegistry::ListMaterialConversions()) { - auto const& info = UsdMayaShadingModeRegistry::GetMaterialConversionInfo(r); - if (niceToken == info.niceName - && (isExport ? info.hasExporter : info.hasImporter)) { - shadingMode = UsdMayaShadingModeTokens->useRegistry; - convertMaterialsTo = r; - } + } + if (shadingMode.IsEmpty()) { + for (auto const& r : UsdMayaShadingModeRegistry::ListMaterialConversions()) { + auto const& info = UsdMayaShadingModeRegistry::GetMaterialConversionInfo(r); + if (niceToken == info.niceName && (isExport ? info.hasExporter : info.hasImporter)) { + shadingMode = UsdMayaShadingModeTokens->useRegistry; + convertMaterialsTo = r; } } - return std::make_pair(shadingMode, convertMaterialsTo); } + return std::make_pair(shadingMode, convertMaterialsTo); } +} // namespace -MStatus -MayaUSDListShadingModesCommand::doIt(const MArgList& args) { - MStatus status; +MStatus MayaUSDListShadingModesCommand::doIt(const MArgList& args) +{ + MStatus status; MArgDatabase argData(syntax(), args, &status); if (status != MS::kSuccess) { @@ -132,7 +132,7 @@ MayaUSDListShadingModesCommand::doIt(const MArgList& args) { .c_str()); appendToResult(_tokens->NoneNiceName.GetText()); } else if (argData.isFlagSet("exportOptions")) { - MString niceName; + MString niceName; status = argData.getFlagArgument("exportOptions", 0, niceName); if (status != MS::kSuccess) { return status; @@ -150,7 +150,7 @@ MayaUSDListShadingModesCommand::doIt(const MArgList& args) { } setResult(options); } else if (argData.isFlagSet("importOptions")) { - MString niceName; + MString niceName; status = argData.getFlagArgument("importOptions", 0, niceName); if (status != MS::kSuccess) { return status; @@ -193,8 +193,7 @@ MayaUSDListShadingModesCommand::doIt(const MArgList& args) { auto const& info = UsdMayaShadingModeRegistry::GetMaterialConversionInfo(materialConversion); setResult( - isExport ? info.exportDescription.GetText() - : info.importDescription.GetText()); + isExport ? info.exportDescription.GetText() : info.importDescription.GetText()); } } else if (argData.isFlagSet("findExportName") || argData.isFlagSet("findImportName")) { const bool isExport = argData.isFlagSet("findExportName"); @@ -229,8 +228,8 @@ MayaUSDListShadingModesCommand::doIt(const MArgList& args) { return MS::kSuccess; } -MSyntax -MayaUSDListShadingModesCommand::createSyntax() { +MSyntax MayaUSDListShadingModesCommand::createSyntax() +{ MSyntax syntax; syntax.addFlag("-ex", "-export", MSyntax::kNoArg); syntax.addFlag("-im", "-import", MSyntax::kNoArg); @@ -247,8 +246,6 @@ MayaUSDListShadingModesCommand::createSyntax() { return syntax; } -void* MayaUSDListShadingModesCommand::creator() { - return new MayaUSDListShadingModesCommand(); -} +void* MayaUSDListShadingModesCommand::creator() { return new MayaUSDListShadingModesCommand(); } -} // MAYAUSD_NS_DEF +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/commands/baseListShadingModesCommand.h b/lib/mayaUsd/commands/baseListShadingModesCommand.h index a1e172433c..9be7687e02 100644 --- a/lib/mayaUsd/commands/baseListShadingModesCommand.h +++ b/lib/mayaUsd/commands/baseListShadingModesCommand.h @@ -28,12 +28,12 @@ class MAYAUSD_CORE_PUBLIC MayaUSDListShadingModesCommand : public MPxCommand { public: MStatus doIt(const MArgList& args) override; - bool isUndoable () const override { return false; }; + bool isUndoable() const override { return false; }; - static MSyntax createSyntax(); - static void* creator(); + static MSyntax createSyntax(); + static void* creator(); }; -} +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/mayaUsd/commands/editTargetCommand.cpp b/lib/mayaUsd/commands/editTargetCommand.cpp index cafd4cfc3e..a321583c81 100644 --- a/lib/mayaUsd/commands/editTargetCommand.cpp +++ b/lib/mayaUsd/commands/editTargetCommand.cpp @@ -39,7 +39,8 @@ void reportError(const MString& errorString) { MGlobal::displayError(errorString namespace MAYAUSD_NS_DEF { namespace Impl { -class SetEditTarget { +class SetEditTarget +{ public: bool doIt(UsdStagePtr stage) { @@ -76,10 +77,7 @@ class SetEditTarget { const char EditTargetCommand::commandName[] = "mayaUsdEditTarget"; // plug-in callback to create the command object -void* EditTargetCommand::creator() -{ - return static_cast(new EditTargetCommand()); -} +void* EditTargetCommand::creator() { return static_cast(new EditTargetCommand()); } // plug-in callback to register the command syntax MSyntax EditTargetCommand::createSyntax() diff --git a/lib/mayaUsd/commands/editTargetCommand.h b/lib/mayaUsd/commands/editTargetCommand.h index 44b67d43fa..1636012b0c 100644 --- a/lib/mayaUsd/commands/editTargetCommand.h +++ b/lib/mayaUsd/commands/editTargetCommand.h @@ -29,35 +29,42 @@ namespace Impl { class SetEditTarget; } -class EditTargetCommand : public MPxCommand { +class EditTargetCommand : public MPxCommand +{ public: // plugin registration requirements MAYAUSD_CORE_PUBLIC static const char commandName[]; - + MAYAUSD_CORE_PUBLIC - static void* creator(); - + static void* creator(); + MAYAUSD_CORE_PUBLIC - static MSyntax createSyntax(); + static MSyntax createSyntax(); // MPxCommand callbacks MAYAUSD_CORE_PUBLIC MStatus doIt(const MArgList& argList) override; - + MAYAUSD_CORE_PUBLIC MStatus undoIt() override; - + MAYAUSD_CORE_PUBLIC MStatus redoIt() override; - + MAYAUSD_CORE_PUBLIC - bool isUndoable() const override; + bool isUndoable() const override; private: MStatus parseArgs(const MArgList& argList); - enum class Mode { kCreate, kEdit, kQuery } _cmdMode = Mode::kCreate; + enum class Mode + { + kCreate, + kEdit, + kQuery + } _cmdMode + = Mode::kCreate; bool isEdit() const { return _cmdMode == Mode::kEdit; } bool isQuery() const { return _cmdMode == Mode::kQuery; } diff --git a/lib/mayaUsd/commands/layerEditorCommand.cpp b/lib/mayaUsd/commands/layerEditorCommand.cpp index e17f1fffb4..84288f82b3 100644 --- a/lib/mayaUsd/commands/layerEditorCommand.cpp +++ b/lib/mayaUsd/commands/layerEditorCommand.cpp @@ -50,9 +50,18 @@ namespace MAYAUSD_NS_DEF { namespace Impl { -enum class CmdId { kInsert, kRemove, kReplace, kDiscardEdit, kClearLayer, kAddAnonLayer }; +enum class CmdId +{ + kInsert, + kRemove, + kReplace, + kDiscardEdit, + kClearLayer, + kAddAnonLayer +}; -class BaseCmd { +class BaseCmd +{ public: BaseCmd(CmdId id) : _cmdId(id) @@ -88,10 +97,13 @@ void BaseCmd::holdOnPathIfDirty(SdfLayerHandle layer, std::string path) void BaseCmd::holdOntoSubLayers(SdfLayerHandle layer) { const std::vector& sublayers = layer->GetSubLayerPaths(); - for (auto path : sublayers) { holdOnPathIfDirty(layer, path); } + for (auto path : sublayers) { + holdOnPathIfDirty(layer, path); + } } -class InsertRemoveSubPathBase : public BaseCmd { +class InsertRemoveSubPathBase : public BaseCmd +{ public: int _index = -1; std::string _subPath; @@ -149,7 +161,7 @@ class InsertRemoveSubPathBase : public BaseCmd { return true; } static bool validateUndoIndex(SdfLayerHandle layer, int index) - { // allow re-inserting at the last index + 1, but -1 should have been changed to 0 + { // allow re-inserting at the last index + 1, but -1 should have been changed to 0 return !(index < 0 || index > (int)layer->GetNumSubLayerPaths()); } @@ -166,7 +178,8 @@ class InsertRemoveSubPathBase : public BaseCmd { } }; -class InsertSubPath : public InsertRemoveSubPathBase { +class InsertSubPath : public InsertRemoveSubPathBase +{ public: InsertSubPath() : InsertRemoveSubPathBase(CmdId::kInsert) @@ -174,7 +187,8 @@ class InsertSubPath : public InsertRemoveSubPathBase { } }; -class RemoveSubPath : public InsertRemoveSubPathBase { +class RemoveSubPath : public InsertRemoveSubPathBase +{ public: RemoveSubPath() : InsertRemoveSubPathBase(CmdId::kRemove) @@ -182,7 +196,8 @@ class RemoveSubPath : public InsertRemoveSubPathBase { } }; -class ReplaceSubPath : public BaseCmd { +class ReplaceSubPath : public BaseCmd +{ public: ReplaceSubPath() : BaseCmd(CmdId::kReplace) @@ -216,7 +231,8 @@ class ReplaceSubPath : public BaseCmd { std::string _oldPath, _newPath; }; -class AddAnonSubLayer : public InsertRemoveSubPathBase { +class AddAnonSubLayer : public InsertRemoveSubPathBase +{ public: AddAnonSubLayer() : InsertRemoveSubPathBase(CmdId::kAddAnonLayer) {}; @@ -228,27 +244,25 @@ class AddAnonSubLayer : public InsertRemoveSubPathBase { // on redo, we want to put back that same identifier, for later commands if (_anonIdentifier.empty()) { _anonLayer = SdfLayer::CreateAnonymous(_anonName); - _anonIdentifier = _anonLayer->GetIdentifier(); - } + _anonIdentifier = _anonLayer->GetIdentifier(); + } _subPath = _anonIdentifier; _index = 0; _cmdResult = _subPath; return InsertRemoveSubPathBase::doIt(layer); } - bool undoIt(SdfLayerHandle layer) override - { - return InsertRemoveSubPathBase::undoIt(layer); - } + bool undoIt(SdfLayerHandle layer) override { return InsertRemoveSubPathBase::undoIt(layer); } std::string _anonName; protected: PXR_NS::SdfLayerRefPtr _anonLayer; - std::string _anonIdentifier; + std::string _anonIdentifier; }; -class BackupLayerBase : public BaseCmd { +class BackupLayerBase : public BaseCmd +{ // commands that need to backup the whole layer for undo public: BackupLayerBase(CmdId id) @@ -288,7 +302,8 @@ class BackupLayerBase : public BaseCmd { PXR_NS::SdfLayerRefPtr _backupLayer; }; -class DiscardEdit : public BackupLayerBase { +class DiscardEdit : public BackupLayerBase +{ public: DiscardEdit() : BackupLayerBase(CmdId::kDiscardEdit) @@ -296,7 +311,8 @@ class DiscardEdit : public BackupLayerBase { } }; -class ClearLayer : public BackupLayerBase { +class ClearLayer : public BackupLayerBase +{ public: ClearLayer() : BackupLayerBase(CmdId::kClearLayer) diff --git a/lib/mayaUsd/commands/layerEditorCommand.h b/lib/mayaUsd/commands/layerEditorCommand.h index 0de63b87c5..e2b098a136 100644 --- a/lib/mayaUsd/commands/layerEditorCommand.h +++ b/lib/mayaUsd/commands/layerEditorCommand.h @@ -32,7 +32,8 @@ namespace Impl { class BaseCmd; } -class MAYAUSD_CORE_PUBLIC LayerEditorCommand : public MPxCommand { +class MAYAUSD_CORE_PUBLIC LayerEditorCommand : public MPxCommand +{ public: // plugin registration requirements static const char commandName[]; @@ -48,7 +49,13 @@ class MAYAUSD_CORE_PUBLIC LayerEditorCommand : public MPxCommand { private: MStatus parseArgs(const MArgList& argList); - enum class Mode { Create, Edit, Query } _cmdMode = Mode::Create; + enum class Mode + { + Create, + Edit, + Query + } _cmdMode + = Mode::Create; bool isEdit() const { return _cmdMode == Mode::Edit; } bool isQuery() const { return _cmdMode == Mode::Query; } diff --git a/lib/mayaUsd/fileio/chaser/chaser.cpp b/lib/mayaUsd/fileio/chaser/chaser.cpp index 5b92794d70..b0b044a713 100644 --- a/lib/mayaUsd/fileio/chaser/chaser.cpp +++ b/lib/mayaUsd/fileio/chaser/chaser.cpp @@ -17,26 +17,22 @@ PXR_NAMESPACE_OPEN_SCOPE -bool -UsdMayaChaser::ExportDefault() +bool UsdMayaChaser::ExportDefault() { // Do nothing by default. return true; } -bool -UsdMayaChaser::ExportFrame(const UsdTimeCode& time) +bool UsdMayaChaser::ExportFrame(const UsdTimeCode& time) { // Do nothing by default. return true; } -bool -UsdMayaChaser::PostExport() +bool UsdMayaChaser::PostExport() { // Do nothing by default. return true; } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/chaser/chaser.h b/lib/mayaUsd/fileio/chaser/chaser.h index 0c8f9ff839..3b5c8647f9 100644 --- a/lib/mayaUsd/fileio/chaser/chaser.h +++ b/lib/mayaUsd/fileio/chaser/chaser.h @@ -16,13 +16,13 @@ #ifndef PXRUSDMAYA_CHASER_H #define PXRUSDMAYA_CHASER_H -#include +#include + #include #include +#include #include -#include - PXR_NAMESPACE_OPEN_SCOPE TF_DECLARE_REF_PTRS(UsdMayaChaser); @@ -71,7 +71,6 @@ class UsdMayaChaser : public TfRefBase virtual bool PostExport(); }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/chaser/chaserRegistry.cpp b/lib/mayaUsd/fileio/chaser/chaserRegistry.cpp index e79372562e..59c2d451cd 100644 --- a/lib/mayaUsd/fileio/chaser/chaserRegistry.cpp +++ b/lib/mayaUsd/fileio/chaser/chaserRegistry.cpp @@ -15,30 +15,26 @@ // #include "chaserRegistry.h" -#include +#include +#include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE UsdMayaChaserRegistry::FactoryContext::FactoryContext( - const UsdStagePtr& stage, - const DagToUsdMap& dagToUsdMap, - const UsdMayaJobExportArgs& jobArgs) + const UsdStagePtr& stage, + const DagToUsdMap& dagToUsdMap, + const UsdMayaJobExportArgs& jobArgs) : _stage(stage) , _dagToUsdMap(dagToUsdMap) , _jobArgs(jobArgs) { } -UsdStagePtr -UsdMayaChaserRegistry::FactoryContext::GetStage() const -{ - return _stage; -} +UsdStagePtr UsdMayaChaserRegistry::FactoryContext::GetStage() const { return _stage; } const UsdMayaChaserRegistry::FactoryContext::DagToUsdMap& UsdMayaChaserRegistry::FactoryContext::GetDagToUsdMap() const @@ -46,8 +42,7 @@ UsdMayaChaserRegistry::FactoryContext::GetDagToUsdMap() const return _dagToUsdMap; } -const UsdMayaJobExportArgs& -UsdMayaChaserRegistry::FactoryContext::GetJobArgs() const +const UsdMayaJobExportArgs& UsdMayaChaserRegistry::FactoryContext::GetJobArgs() const { return _jobArgs; } @@ -56,38 +51,28 @@ TF_INSTANTIATE_SINGLETON(UsdMayaChaserRegistry); std::map _factoryRegistry; -bool -UsdMayaChaserRegistry::RegisterFactory( - const std::string& name, - FactoryFn fn) +bool UsdMayaChaserRegistry::RegisterFactory(const std::string& name, FactoryFn fn) { - TF_DEBUG(PXRUSDMAYA_REGISTRY).Msg( - "Registering chaser '%s'.\n", name.c_str()); + TF_DEBUG(PXRUSDMAYA_REGISTRY).Msg("Registering chaser '%s'.\n", name.c_str()); auto ret = _factoryRegistry.insert(std::make_pair(name, fn)); if (ret.second) { - UsdMaya_RegistryHelper::AddUnloader([name]() { - _factoryRegistry.erase(name); - }); + UsdMaya_RegistryHelper::AddUnloader([name]() { _factoryRegistry.erase(name); }); } return ret.second; } UsdMayaChaserRefPtr -UsdMayaChaserRegistry::Create( - const std::string& name, - const FactoryContext& context) const +UsdMayaChaserRegistry::Create(const std::string& name, const FactoryContext& context) const { TfRegistryManager::GetInstance().SubscribeTo(); if (UsdMayaChaserRegistry::FactoryFn fn = _factoryRegistry[name]) { return TfCreateRefPtr(fn(context)); - } - else { + } else { return TfNullPtr; } } -std::vector -UsdMayaChaserRegistry::GetAllRegisteredChasers() const +std::vector UsdMayaChaserRegistry::GetAllRegisteredChasers() const { std::vector ret; for (const auto& p : _factoryRegistry) { @@ -97,20 +82,13 @@ UsdMayaChaserRegistry::GetAllRegisteredChasers() const } // static -UsdMayaChaserRegistry& -UsdMayaChaserRegistry::GetInstance() +UsdMayaChaserRegistry& UsdMayaChaserRegistry::GetInstance() { return TfSingleton::GetInstance(); } -UsdMayaChaserRegistry::UsdMayaChaserRegistry() -{ -} - -UsdMayaChaserRegistry::~UsdMayaChaserRegistry() -{ -} +UsdMayaChaserRegistry::UsdMayaChaserRegistry() { } +UsdMayaChaserRegistry::~UsdMayaChaserRegistry() { } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/chaser/chaserRegistry.h b/lib/mayaUsd/fileio/chaser/chaserRegistry.h index abc5700689..7739df8991 100644 --- a/lib/mayaUsd/fileio/chaser/chaserRegistry.h +++ b/lib/mayaUsd/fileio/chaser/chaserRegistry.h @@ -16,18 +16,18 @@ #ifndef PXRUSDMAYA_CHASER_REGISTRY_H #define PXRUSDMAYA_CHASER_REGISTRY_H -#include +#include +#include +#include +#include -#include #include #include #include +#include #include -#include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -45,22 +45,22 @@ TF_DECLARE_WEAK_PTRS(UsdMayaChaserRegistry); class UsdMayaChaserRegistry : public TfWeakBase { public: - - /// \brief Holds data that can be accessed when constructing a + /// \brief Holds data that can be accessed when constructing a /// \p UsdMayaChaser object. /// /// This class allows plugin code to only know about the context object /// during construction and only need to know about the data it is needs to - /// construct. - class FactoryContext { + /// construct. + class FactoryContext + { public: typedef UsdMayaUtil::MDagPathMap DagToUsdMap; MAYAUSD_CORE_PUBLIC FactoryContext( - const UsdStagePtr& stage, - const DagToUsdMap& dagToUsdMap, - const UsdMayaJobExportArgs& jobArgs); + const UsdStagePtr& stage, + const DagToUsdMap& dagToUsdMap, + const UsdMayaJobExportArgs& jobArgs); /// \brief Returns the exported stage. /// @@ -84,27 +84,23 @@ class UsdMayaChaserRegistry : public TfWeakBase const UsdMayaJobExportArgs& GetJobArgs() const; private: - UsdStagePtr _stage; - const DagToUsdMap& _dagToUsdMap; + UsdStagePtr _stage; + const DagToUsdMap& _dagToUsdMap; const UsdMayaJobExportArgs& _jobArgs; }; - typedef std::function FactoryFn; + typedef std::function FactoryFn; - /// \brief Register a chaser factory. + /// \brief Register a chaser factory. /// /// Please use the \p PXRUSDMAYA_DEFINE_CHASER_FACTORY instead of calling /// this directly. MAYAUSD_CORE_PUBLIC - bool RegisterFactory( - const std::string& name, - FactoryFn fn); + bool RegisterFactory(const std::string& name, FactoryFn fn); /// \brief Creates a chaser using the factoring registered to \p name. MAYAUSD_CORE_PUBLIC - UsdMayaChaserRefPtr Create( - const std::string& name, - const FactoryContext& context) const; + UsdMayaChaserRefPtr Create(const std::string& name, const FactoryContext& context) const; /// \brief Returns the names of all registered chasers. MAYAUSD_CORE_PUBLIC @@ -122,14 +118,15 @@ class UsdMayaChaserRegistry : public TfWeakBase /// \brief define a factory for the chaser \p name. the \p contextArgName will /// be type \p UsdMayaChaserRegistry::FactoryContext . The following code /// block should return a \p UsdMayaChaser*. There are no guarantees about -/// the lifetime of \p contextArgName. -#define PXRUSDMAYA_DEFINE_CHASER_FACTORY(name, contextArgName) \ -static UsdMayaChaser* _ChaserFactory_##name(const UsdMayaChaserRegistry::FactoryContext&); \ -TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaChaserRegistry, name) {\ - UsdMayaChaserRegistry::GetInstance().RegisterFactory(#name, &_ChaserFactory_##name); \ -}\ -UsdMayaChaser* _ChaserFactory_##name(const UsdMayaChaserRegistry::FactoryContext& contextArgName) - +/// the lifetime of \p contextArgName. +#define PXRUSDMAYA_DEFINE_CHASER_FACTORY(name, contextArgName) \ + static UsdMayaChaser* _ChaserFactory_##name(const UsdMayaChaserRegistry::FactoryContext&); \ + TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaChaserRegistry, name) \ + { \ + UsdMayaChaserRegistry::GetInstance().RegisterFactory(#name, &_ChaserFactory_##name); \ + } \ + UsdMayaChaser* _ChaserFactory_##name( \ + const UsdMayaChaserRegistry::FactoryContext& contextArgName) PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/fallbackPrimReader.cpp b/lib/mayaUsd/fileio/fallbackPrimReader.cpp index 89b234da66..5f958d9253 100644 --- a/lib/mayaUsd/fileio/fallbackPrimReader.cpp +++ b/lib/mayaUsd/fileio/fallbackPrimReader.cpp @@ -15,20 +15,18 @@ // #include "fallbackPrimReader.h" -#include - #include +#include + PXR_NAMESPACE_OPEN_SCOPE -UsdMaya_FallbackPrimReader::UsdMaya_FallbackPrimReader( - const UsdMayaPrimReaderArgs& args) +UsdMaya_FallbackPrimReader::UsdMaya_FallbackPrimReader(const UsdMayaPrimReaderArgs& args) : UsdMayaPrimReader(args) { } -bool -UsdMaya_FallbackPrimReader::Read(UsdMayaPrimReaderContext* context) +bool UsdMaya_FallbackPrimReader::Read(UsdMayaPrimReaderContext* context) { const UsdPrim& usdPrim = _GetArgs().GetUsdPrim(); if (usdPrim.HasAuthoredTypeName() && !usdPrim.IsA()) { @@ -37,24 +35,22 @@ UsdMaya_FallbackPrimReader::Read(UsdMayaPrimReaderContext* context) return false; } - MObject parentNode = context->GetMayaNode( - usdPrim.GetPath().GetParentPath(), true); + MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); MStatus status; MObject mayaNode; return UsdMayaTranslatorUtil::CreateDummyTransformNode( - usdPrim, - parentNode, - /*importTypeName*/ false, - _GetArgs(), - context, - &status, - &mayaNode); + usdPrim, + parentNode, + /*importTypeName*/ false, + _GetArgs(), + context, + &status, + &mayaNode); } /* static */ -UsdMayaPrimReaderRegistry::ReaderFactoryFn -UsdMaya_FallbackPrimReader::CreateFactory() +UsdMayaPrimReaderRegistry::ReaderFactoryFn UsdMaya_FallbackPrimReader::CreateFactory() { return [](const UsdMayaPrimReaderArgs& args) { return std::make_shared(args); diff --git a/lib/mayaUsd/fileio/fallbackPrimReader.h b/lib/mayaUsd/fileio/fallbackPrimReader.h index d3dc4ac842..c1d383ba49 100644 --- a/lib/mayaUsd/fileio/fallbackPrimReader.h +++ b/lib/mayaUsd/fileio/fallbackPrimReader.h @@ -23,7 +23,8 @@ PXR_NAMESPACE_OPEN_SCOPE /// This is a special prim reader that is used whenever a typeless prim or prim /// with unknown types is encountered when traversing USD. -class UsdMaya_FallbackPrimReader : public UsdMayaPrimReader { +class UsdMaya_FallbackPrimReader : public UsdMayaPrimReader +{ public: UsdMaya_FallbackPrimReader(const UsdMayaPrimReaderArgs& args); diff --git a/lib/mayaUsd/fileio/functorPrimReader.cpp b/lib/mayaUsd/fileio/functorPrimReader.cpp index 1715ee4a3f..40fde14b49 100644 --- a/lib/mayaUsd/fileio/functorPrimReader.cpp +++ b/lib/mayaUsd/fileio/functorPrimReader.cpp @@ -18,23 +18,22 @@ PXR_NAMESPACE_OPEN_SCOPE UsdMaya_FunctorPrimReader::UsdMaya_FunctorPrimReader( - const UsdMayaPrimReaderArgs& args, + const UsdMayaPrimReaderArgs& args, UsdMayaPrimReaderRegistry::ReaderFn readerFn) - : UsdMayaPrimReader(args), _readerFn(readerFn) + : UsdMayaPrimReader(args) + , _readerFn(readerFn) { } -bool -UsdMaya_FunctorPrimReader::Read(UsdMayaPrimReaderContext* context) +bool UsdMaya_FunctorPrimReader::Read(UsdMayaPrimReaderContext* context) { TF_VERIFY(context); return _readerFn(_GetArgs(), context); } /* static */ -UsdMayaPrimReaderSharedPtr -UsdMaya_FunctorPrimReader::Create( - const UsdMayaPrimReaderArgs& args, +UsdMayaPrimReaderSharedPtr UsdMaya_FunctorPrimReader::Create( + const UsdMayaPrimReaderArgs& args, UsdMayaPrimReaderRegistry::ReaderFn readerFn) { return std::make_shared(args, readerFn); @@ -42,12 +41,9 @@ UsdMaya_FunctorPrimReader::Create( /* static */ UsdMayaPrimReaderRegistry::ReaderFactoryFn -UsdMaya_FunctorPrimReader::CreateFactory( - UsdMayaPrimReaderRegistry::ReaderFn readerFn) +UsdMaya_FunctorPrimReader::CreateFactory(UsdMayaPrimReaderRegistry::ReaderFn readerFn) { - return [=](const UsdMayaPrimReaderArgs& args) { - return Create(args, readerFn); - }; + return [=](const UsdMayaPrimReaderArgs& args) { return Create(args, readerFn); }; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/functorPrimReader.h b/lib/mayaUsd/fileio/functorPrimReader.h index 5a7aca1344..f6484b5dc1 100644 --- a/lib/mayaUsd/fileio/functorPrimReader.h +++ b/lib/mayaUsd/fileio/functorPrimReader.h @@ -16,16 +16,16 @@ #ifndef PXRUSDMAYA_FUNCTORPRIMREADER_H #define PXRUSDMAYA_FUNCTORPRIMREADER_H -#include - -#include - #include #include #include #include #include +#include + +#include + PXR_NAMESPACE_OPEN_SCOPE /// \class UsdMaya_FunctorPrimReader @@ -35,18 +35,15 @@ PXR_NAMESPACE_OPEN_SCOPE class UsdMaya_FunctorPrimReader final : public UsdMayaPrimReader { public: - UsdMaya_FunctorPrimReader( - const UsdMayaPrimReaderArgs&, - UsdMayaPrimReaderRegistry::ReaderFn); + UsdMaya_FunctorPrimReader(const UsdMayaPrimReaderArgs&, UsdMayaPrimReaderRegistry::ReaderFn); bool Read(UsdMayaPrimReaderContext* context) override; - static UsdMayaPrimReaderSharedPtr Create( - const UsdMayaPrimReaderArgs&, - UsdMayaPrimReaderRegistry::ReaderFn readerFn); + static UsdMayaPrimReaderSharedPtr + Create(const UsdMayaPrimReaderArgs&, UsdMayaPrimReaderRegistry::ReaderFn readerFn); static UsdMayaPrimReaderRegistry::ReaderFactoryFn - CreateFactory(UsdMayaPrimReaderRegistry::ReaderFn readerFn); + CreateFactory(UsdMayaPrimReaderRegistry::ReaderFn readerFn); private: UsdMayaPrimReaderRegistry::ReaderFn _readerFn; diff --git a/lib/mayaUsd/fileio/functorPrimWriter.cpp b/lib/mayaUsd/fileio/functorPrimWriter.cpp index 88f7ea4482..73e5c97609 100644 --- a/lib/mayaUsd/fileio/functorPrimWriter.cpp +++ b/lib/mayaUsd/fileio/functorPrimWriter.cpp @@ -15,15 +15,6 @@ // #include "functorPrimWriter.h" -#include - -#include - -#include -#include -#include -#include - #include #include #include @@ -31,34 +22,38 @@ #include #include +#include +#include +#include +#include + +#include + +#include + PXR_NAMESPACE_OPEN_SCOPE UsdMaya_FunctorPrimWriter::UsdMaya_FunctorPrimWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx, - UsdMayaPrimWriterRegistry::WriterFn plugFn) : - UsdMayaTransformWriter(depNodeFn, usdPath, jobCtx), - _plugFn(plugFn), - _exportsGprims(false), - _pruneChildren(false) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx, + UsdMayaPrimWriterRegistry::WriterFn plugFn) + : UsdMayaTransformWriter(depNodeFn, usdPath, jobCtx) + , _plugFn(plugFn) + , _exportsGprims(false) + , _pruneChildren(false) { } /* virtual */ -UsdMaya_FunctorPrimWriter::~UsdMaya_FunctorPrimWriter() -{ -} +UsdMaya_FunctorPrimWriter::~UsdMaya_FunctorPrimWriter() { } /* virtual */ -void -UsdMaya_FunctorPrimWriter::Write(const UsdTimeCode& usdTime) +void UsdMaya_FunctorPrimWriter::Write(const UsdTimeCode& usdTime) { UsdMayaTransformWriter::Write(usdTime); - const UsdMayaPrimWriterArgs args( - GetDagPath(), - _GetExportArgs().exportRefsAsInstanceable); + const UsdMayaPrimWriterArgs args(GetDagPath(), _GetExportArgs().exportRefsAsInstanceable); UsdMayaPrimWriterContext ctx(usdTime, GetUsdPath(), GetUsdStage()); @@ -70,33 +65,20 @@ UsdMaya_FunctorPrimWriter::Write(const UsdTimeCode& usdTime) } /* virtual */ -bool -UsdMaya_FunctorPrimWriter::ExportsGprims() const -{ - return _exportsGprims; -} +bool UsdMaya_FunctorPrimWriter::ExportsGprims() const { return _exportsGprims; } /* virtual */ -bool -UsdMaya_FunctorPrimWriter::ShouldPruneChildren() const -{ - return _pruneChildren; -} +bool UsdMaya_FunctorPrimWriter::ShouldPruneChildren() const { return _pruneChildren; } /* virtual */ -const SdfPathVector& -UsdMaya_FunctorPrimWriter::GetModelPaths() const -{ - return _modelPaths; -} +const SdfPathVector& UsdMaya_FunctorPrimWriter::GetModelPaths() const { return _modelPaths; } /* static */ -UsdMayaPrimWriterSharedPtr -UsdMaya_FunctorPrimWriter::Create( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx, - UsdMayaPrimWriterRegistry::WriterFn plugFn) +UsdMayaPrimWriterSharedPtr UsdMaya_FunctorPrimWriter::Create( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx, + UsdMayaPrimWriterRegistry::WriterFn plugFn) { return UsdMayaPrimWriterSharedPtr( new UsdMaya_FunctorPrimWriter(depNodeFn, usdPath, jobCtx, plugFn)); @@ -104,15 +86,11 @@ UsdMaya_FunctorPrimWriter::Create( /* static */ UsdMayaPrimWriterRegistry::WriterFactoryFn -UsdMaya_FunctorPrimWriter::CreateFactory( - UsdMayaPrimWriterRegistry::WriterFn fn) +UsdMaya_FunctorPrimWriter::CreateFactory(UsdMayaPrimWriterRegistry::WriterFn fn) { - return [=](const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) { - return Create(depNodeFn, usdPath, jobCtx, fn); - }; + return [=](const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) { return Create(depNodeFn, usdPath, jobCtx, fn); }; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/functorPrimWriter.h b/lib/mayaUsd/fileio/functorPrimWriter.h index 1270ca371c..2779aa1d04 100644 --- a/lib/mayaUsd/fileio/functorPrimWriter.h +++ b/lib/mayaUsd/fileio/functorPrimWriter.h @@ -16,18 +16,18 @@ #ifndef PXRUSDMAYA_FUNCTOR_PRIM_WRITER_H #define PXRUSDMAYA_FUNCTOR_PRIM_WRITER_H -#include - -#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE @@ -41,36 +41,34 @@ class UsdMaya_FunctorPrimWriter final : public UsdMayaTransformWriter { public: UsdMaya_FunctorPrimWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx, - UsdMayaPrimWriterRegistry::WriterFn plugFn); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx, + UsdMayaPrimWriterRegistry::WriterFn plugFn); ~UsdMaya_FunctorPrimWriter() override; - void Write(const UsdTimeCode& usdTime) override; - bool ExportsGprims() const override; - bool ShouldPruneChildren() const override; + void Write(const UsdTimeCode& usdTime) override; + bool ExportsGprims() const override; + bool ShouldPruneChildren() const override; const SdfPathVector& GetModelPaths() const override; static UsdMayaPrimWriterSharedPtr Create( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx, - UsdMayaPrimWriterRegistry::WriterFn plugFn); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx, + UsdMayaPrimWriterRegistry::WriterFn plugFn); static UsdMayaPrimWriterRegistry::WriterFactoryFn - CreateFactory(UsdMayaPrimWriterRegistry::WriterFn plugFn); + CreateFactory(UsdMayaPrimWriterRegistry::WriterFn plugFn); private: UsdMayaPrimWriterRegistry::WriterFn _plugFn; - bool _exportsGprims; - bool _pruneChildren; - SdfPathVector _modelPaths; + bool _exportsGprims; + bool _pruneChildren; + SdfPathVector _modelPaths; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/importData.cpp b/lib/mayaUsd/fileio/importData.cpp index b9810c2aa1..2efff042e2 100644 --- a/lib/mayaUsd/fileio/importData.cpp +++ b/lib/mayaUsd/fileio/importData.cpp @@ -26,161 +26,119 @@ namespace MAYAUSD_NS_DEF { constexpr const char* kRootPrimPath = "/"; ImportData::ImportData() - : fLoadSet(UsdStage::InitialLoadSet::LoadAll) - , fRootPrimPath(kRootPrimPath) - , fPrimsInScopeCount(0) - , fSwitchedVariantCount(0) + : fLoadSet(UsdStage::InitialLoadSet::LoadAll) + , fRootPrimPath(kRootPrimPath) + , fPrimsInScopeCount(0) + , fSwitchedVariantCount(0) { } ImportData::ImportData(const std::string& f) - : fLoadSet(UsdStage::InitialLoadSet::LoadAll) - , fRootPrimPath(kRootPrimPath) - , fFilename(f) - , fPrimsInScopeCount(0) - , fSwitchedVariantCount(0) + : fLoadSet(UsdStage::InitialLoadSet::LoadAll) + , fRootPrimPath(kRootPrimPath) + , fFilename(f) + , fPrimsInScopeCount(0) + , fSwitchedVariantCount(0) { } /*static*/ ImportData& ImportData::instance() { - static ImportData sImportData; - return sImportData; + static ImportData sImportData; + return sImportData; } /*static*/ -const ImportData& ImportData::cinstance() -{ - return instance(); -} +const ImportData& ImportData::cinstance() { return instance(); } void ImportData::clearData() { - fLoadSet = UsdStage::InitialLoadSet::LoadAll; - UsdStagePopulationMask tmpPopMask; - fPopMask.swap(tmpPopMask); - fRootVariants.clear(); - fPrimVariants.clear(); - fFilename.clear(); - fRootPrimPath = kRootPrimPath; - fPrimsInScopeCount = 0; - fSwitchedVariantCount =0; + fLoadSet = UsdStage::InitialLoadSet::LoadAll; + UsdStagePopulationMask tmpPopMask; + fPopMask.swap(tmpPopMask); + fRootVariants.clear(); + fPrimVariants.clear(); + fFilename.clear(); + fRootPrimPath = kRootPrimPath; + fPrimsInScopeCount = 0; + fSwitchedVariantCount = 0; } bool ImportData::empty() const { - // If we don't have a filename set then we are empty. - return fFilename.empty(); + // If we don't have a filename set then we are empty. + return fFilename.empty(); } -const std::string& ImportData::filename() const -{ - return fFilename; -} +const std::string& ImportData::filename() const { return fFilename; } void ImportData::setFilename(const std::string& f) { - // If the input filename doesn't match what we have stored (empty or not) we - // clear the data because it doesn't belong to the new file. - if (fFilename != f) - clearData(); - fFilename = f; + // If the input filename doesn't match what we have stored (empty or not) we + // clear the data because it doesn't belong to the new file. + if (fFilename != f) + clearData(); + fFilename = f; } -const std::string& ImportData::rootPrimPath() const -{ - return fRootPrimPath; -} +const std::string& ImportData::rootPrimPath() const { return fRootPrimPath; } -void ImportData::setRootPrimPath(const std::string& primPath) -{ - fRootPrimPath = primPath; -} +void ImportData::setRootPrimPath(const std::string& primPath) { fRootPrimPath = primPath; } -bool ImportData::hasPopulationMask() const -{ - return !fPopMask.IsEmpty(); -} +bool ImportData::hasPopulationMask() const { return !fPopMask.IsEmpty(); } -const UsdStagePopulationMask& ImportData::stagePopulationMask() const -{ - return fPopMask; -} +const UsdStagePopulationMask& ImportData::stagePopulationMask() const { return fPopMask; } -void ImportData::setStagePopulationMask(const UsdStagePopulationMask& mask) -{ - fPopMask = mask; -} +void ImportData::setStagePopulationMask(const UsdStagePopulationMask& mask) { fPopMask = mask; } void ImportData::setStagePopulationMask(UsdStagePopulationMask&& mask) { - fPopMask = std::move(mask); + fPopMask = std::move(mask); } -UsdStage::InitialLoadSet ImportData::stageInitialLoadSet() const -{ - return fLoadSet; -} +UsdStage::InitialLoadSet ImportData::stageInitialLoadSet() const { return fLoadSet; } -void ImportData::setStageInitialLoadSet(UsdStage::InitialLoadSet loadSet) -{ - fLoadSet = loadSet; -} +void ImportData::setStageInitialLoadSet(UsdStage::InitialLoadSet loadSet) { fLoadSet = loadSet; } bool ImportData::hasVariantSelections() const { - return !(fRootVariants.empty() && fPrimVariants.empty()); + return !(fRootVariants.empty() && fPrimVariants.empty()); } -const SdfVariantSelectionMap& ImportData::rootVariantSelections() const -{ - return fRootVariants; -} +const SdfVariantSelectionMap& ImportData::rootVariantSelections() const { return fRootVariants; } const ImportData::PrimVariantSelections& ImportData::primVariantSelections() const { - return fPrimVariants; + return fPrimVariants; } void ImportData::setRootVariantSelections(const SdfVariantSelectionMap& vars) { - fRootVariants = vars; + fRootVariants = vars; } void ImportData::setRootVariantSelections(SdfVariantSelectionMap&& vars) { - fRootVariants = std::move(vars); + fRootVariants = std::move(vars); } void ImportData::setPrimVariantSelections(const PrimVariantSelections& vars) { - fPrimVariants = vars; + fPrimVariants = vars; } void ImportData::setPrimVariantSelections(PrimVariantSelections&& vars) { - fPrimVariants = std::move(vars); + fPrimVariants = std::move(vars); } -void ImportData::setPrimsInScopeCount(int count) -{ - fPrimsInScopeCount = count; -} +void ImportData::setPrimsInScopeCount(int count) { fPrimsInScopeCount = count; } -void ImportData::setSwitchedVariantCount(int count) -{ - fSwitchedVariantCount = count; -} +void ImportData::setSwitchedVariantCount(int count) { fSwitchedVariantCount = count; } -int ImportData::primsInScopeCount() const -{ - return fPrimsInScopeCount; -} +int ImportData::primsInScopeCount() const { return fPrimsInScopeCount; } -int ImportData::switchedVariantCount() const -{ - return fSwitchedVariantCount; -} +int ImportData::switchedVariantCount() const { return fSwitchedVariantCount; } -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/fileio/importData.h b/lib/mayaUsd/fileio/importData.h index bd32f76f7e..70062ce92a 100644 --- a/lib/mayaUsd/fileio/importData.h +++ b/lib/mayaUsd/fileio/importData.h @@ -16,14 +16,14 @@ #pragma once -#include -#include +#include #include #include #include -#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -31,111 +31,111 @@ namespace MAYAUSD_NS_DEF { /*! * \brief Singleton class to hold USD UI import data. -*/ + */ class MAYAUSD_CORE_PUBLIC ImportData { public: - //! typedef std::map - //! \brief Variant selections mapped for prims. - //! Key = USD prim path, Value = Variant selections - typedef std::map PrimVariantSelections; - - //! \return The import data singleton instance. - static ImportData& instance(); - static const ImportData& cinstance(); - - //! Constructor (allows creating ImportData on stack without singleton instance). - ImportData(); - ImportData(const std::string& f); - - //@{ - //! No copy or move constructor/assignment. - ImportData(const ImportData&) = delete; - ImportData& operator=(const ImportData&) = delete; - ImportData(ImportData&&) = delete; - ImportData& operator=(ImportData&&) = delete; - //@} - - //! Clears all the stored data. - void clearData(); - - //! \return Is this import data empty? - bool empty() const; - - //! \return The filename associated with this import data. - const std::string& filename() const; - - //! Set the filename associated with this import data. - void setFilename(const std::string& f); - - //! \return The root prim path to use when importing. - const std::string& rootPrimPath() const; - - //! Set the root prim path to use for import. - void setRootPrimPath(const std::string& primPath); - - //! \return True if the USD population mask is not empty. - bool hasPopulationMask() const; - - //! \return The USD population mask of the stage to use for import. - const UsdStagePopulationMask& stagePopulationMask() const; - - //@{ - //! Set the USD population mask of the stage to use for import. - //! Both 'copy' and 'move' operations are supported. To use the move version - //! call it with std::move(x). - void setStagePopulationMask(const UsdStagePopulationMask& mask); - void setStagePopulationMask(UsdStagePopulationMask&& mask); - //@} - - //! \return The USD initial load set of the stage to use for import. - UsdStage::InitialLoadSet stageInitialLoadSet() const; - - //! Set the USD initial load set of the stage to use for import. - void setStageInitialLoadSet(UsdStage::InitialLoadSet loadSet); - - //! \return True if the USD variant selections is not empty. - bool hasVariantSelections() const; - - //! \return The USD variant selections (for the root prim) of the stage to use for import. - const SdfVariantSelectionMap& rootVariantSelections() const; - - //! \return The USD variant selections (for individual prims) of the stage to use for import. - const PrimVariantSelections& primVariantSelections() const; - - //! Set the USD variant selections (for the root prim) of the stage to use for import. - //! Both 'copy' and 'move' operations are supported. To use the move version - //! call it with std::move(x). - void setRootVariantSelections(const SdfVariantSelectionMap& vars); - void setRootVariantSelections(SdfVariantSelectionMap&& vars); - - //! Set the USD variant selections (for individual prims) of the stage to use for import. - //! Both 'copy' and 'move' operations are supported. To use the move version - //! call it with std::move(x). - void setPrimVariantSelections(const PrimVariantSelections& vars); - void setPrimVariantSelections(PrimVariantSelections&& vars); - - //@{ - //! Set and get the number of prims to be imported and the number of prims within that scope - //! that had a variant changed from what is currently set in the USD file. - //! These values are stored here as a way of communicating choices made between the various - //! Import options UI, and are used for display purposes only. - void setPrimsInScopeCount(int count); - void setSwitchedVariantCount(int count); - int primsInScopeCount() const; - int switchedVariantCount() const; - //@} + //! typedef std::map + //! \brief Variant selections mapped for prims. + //! Key = USD prim path, Value = Variant selections + typedef std::map PrimVariantSelections; + + //! \return The import data singleton instance. + static ImportData& instance(); + static const ImportData& cinstance(); + + //! Constructor (allows creating ImportData on stack without singleton instance). + ImportData(); + ImportData(const std::string& f); + + //@{ + //! No copy or move constructor/assignment. + ImportData(const ImportData&) = delete; + ImportData& operator=(const ImportData&) = delete; + ImportData(ImportData&&) = delete; + ImportData& operator=(ImportData&&) = delete; + //@} + + //! Clears all the stored data. + void clearData(); + + //! \return Is this import data empty? + bool empty() const; + + //! \return The filename associated with this import data. + const std::string& filename() const; + + //! Set the filename associated with this import data. + void setFilename(const std::string& f); + + //! \return The root prim path to use when importing. + const std::string& rootPrimPath() const; + + //! Set the root prim path to use for import. + void setRootPrimPath(const std::string& primPath); + + //! \return True if the USD population mask is not empty. + bool hasPopulationMask() const; + + //! \return The USD population mask of the stage to use for import. + const UsdStagePopulationMask& stagePopulationMask() const; + + //@{ + //! Set the USD population mask of the stage to use for import. + //! Both 'copy' and 'move' operations are supported. To use the move version + //! call it with std::move(x). + void setStagePopulationMask(const UsdStagePopulationMask& mask); + void setStagePopulationMask(UsdStagePopulationMask&& mask); + //@} + + //! \return The USD initial load set of the stage to use for import. + UsdStage::InitialLoadSet stageInitialLoadSet() const; + + //! Set the USD initial load set of the stage to use for import. + void setStageInitialLoadSet(UsdStage::InitialLoadSet loadSet); + + //! \return True if the USD variant selections is not empty. + bool hasVariantSelections() const; + + //! \return The USD variant selections (for the root prim) of the stage to use for import. + const SdfVariantSelectionMap& rootVariantSelections() const; + + //! \return The USD variant selections (for individual prims) of the stage to use for import. + const PrimVariantSelections& primVariantSelections() const; + + //! Set the USD variant selections (for the root prim) of the stage to use for import. + //! Both 'copy' and 'move' operations are supported. To use the move version + //! call it with std::move(x). + void setRootVariantSelections(const SdfVariantSelectionMap& vars); + void setRootVariantSelections(SdfVariantSelectionMap&& vars); + + //! Set the USD variant selections (for individual prims) of the stage to use for import. + //! Both 'copy' and 'move' operations are supported. To use the move version + //! call it with std::move(x). + void setPrimVariantSelections(const PrimVariantSelections& vars); + void setPrimVariantSelections(PrimVariantSelections&& vars); + + //@{ + //! Set and get the number of prims to be imported and the number of prims within that scope + //! that had a variant changed from what is currently set in the USD file. + //! These values are stored here as a way of communicating choices made between the various + //! Import options UI, and are used for display purposes only. + void setPrimsInScopeCount(int count); + void setSwitchedVariantCount(int count); + int primsInScopeCount() const; + int switchedVariantCount() const; + //@} private: - UsdStagePopulationMask fPopMask; - UsdStage::InitialLoadSet fLoadSet; - SdfVariantSelectionMap fRootVariants; - PrimVariantSelections fPrimVariants; - std::string fRootPrimPath; - std::string fFilename; - - int fPrimsInScopeCount; - int fSwitchedVariantCount; + UsdStagePopulationMask fPopMask; + UsdStage::InitialLoadSet fLoadSet; + SdfVariantSelectionMap fRootVariants; + PrimVariantSelections fPrimVariants; + std::string fRootPrimPath; + std::string fFilename; + + int fPrimsInScopeCount; + int fSwitchedVariantCount; }; -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/fileio/instancedNodeWriter.cpp b/lib/mayaUsd/fileio/instancedNodeWriter.cpp index a446bce032..6dd0508d94 100644 --- a/lib/mayaUsd/fileio/instancedNodeWriter.cpp +++ b/lib/mayaUsd/fileio/instancedNodeWriter.cpp @@ -15,32 +15,30 @@ // #include "instancedNodeWriter.h" -#include -#include - -#include -#include -#include +#include +#include +#include #include #include #include #include -#include -#include -#include +#include +#include +#include + +#include +#include PXR_NAMESPACE_OPEN_SCOPE /// Assuming that \p instance1 and \p instance2 are instances of one another, /// replaces the prefix \p instance1 in \p dagPath with \p instance2. -static -MDagPath -_ReplaceInstancePrefix( - const MDagPath& dagPath, - const MDagPath& instance1, - const MDagPath& instance2) +static MDagPath _ReplaceInstancePrefix( + const MDagPath& dagPath, + const MDagPath& instance1, + const MDagPath& instance2) { // Early out if the prefixes are the same (no replacement necessary). if (instance1 == instance2) { @@ -79,9 +77,7 @@ _ReplaceInstancePrefix( } } if (!found) { - TF_CODING_ERROR( - "Couldn't find '%s' under its parent", - curPath.fullPathName().asChar()); + TF_CODING_ERROR("Couldn't find '%s' under its parent", curPath.fullPathName().asChar()); return MDagPath(); } } @@ -96,8 +92,7 @@ _ReplaceInstancePrefix( const unsigned int i = *it; if (i >= curPath.childCount()) { TF_CODING_ERROR( - "Child index %u is invalid for '%s'", - i, curPath.fullPathName().asChar()); + "Child index %u is invalid for '%s'", i, curPath.fullPathName().asChar()); return MDagPath(); } curPath.push(curPath.child(i)); @@ -107,11 +102,11 @@ _ReplaceInstancePrefix( } UsdMaya_InstancedNodeWriter::UsdMaya_InstancedNodeWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdInstancePath, - UsdMayaWriteJobContext& ctx) : - UsdMayaPrimWriter(depNodeFn, usdInstancePath, ctx), - _exportsGprims(false) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdInstancePath, + UsdMayaWriteJobContext& ctx) + : UsdMayaPrimWriter(depNodeFn, usdInstancePath, ctx) + , _exportsGprims(false) { const MDagPath& mayaInstancePath(GetDagPath()); if (!TF_VERIFY( @@ -123,9 +118,7 @@ UsdMaya_InstancedNodeWriter::UsdMaya_InstancedNodeWriter( _usdPrim = GetUsdStage()->DefinePrim(usdInstancePath); if (!TF_VERIFY( - _usdPrim, - "Could not define UsdPrim at path '%s'\n", - usdInstancePath.GetText())) { + _usdPrim, "Could not define UsdPrim at path '%s'\n", usdInstancePath.GetText())) { return; } @@ -140,8 +133,7 @@ UsdMaya_InstancedNodeWriter::UsdMaya_InstancedNodeWriter( return; } - _usdPrim.GetReferences().AddReference( - SdfReference(std::string(), referencePath)); + _usdPrim.GetReferences().AddReference(SdfReference(std::string(), referencePath)); _usdPrim.SetInstanceable(true); // Get the Maya DAG path corresponding to our "instance master" root. @@ -150,8 +142,7 @@ UsdMaya_InstancedNodeWriter::UsdMaya_InstancedNodeWriter( MDagPath::getAllPathsTo(mayaInstancePath.node(), allInstances); if (allInstances.length() == 0) { TF_CODING_ERROR( - "'%s' should have at least one path", - mayaInstancePath.fullPathName().asChar()); + "'%s' should have at least one path", mayaInstancePath.fullPathName().asChar()); return; } const MDagPath dagMasterRootPath = allInstances[0]; @@ -159,7 +150,7 @@ UsdMaya_InstancedNodeWriter::UsdMaya_InstancedNodeWriter( // Loop through our prim writers and compute cached data. std::vector::const_iterator begin; std::vector::const_iterator end; - const MDagPath path = GetDagPath(); + const MDagPath path = GetDagPath(); if (_writeJobCtx._GetInstanceMasterPrimWriters(path, &begin, &end)) { for (auto it = begin; it != end; ++it) { const UsdMayaPrimWriterSharedPtr writer = *it; @@ -172,21 +163,19 @@ UsdMaya_InstancedNodeWriter::UsdMaya_InstancedNodeWriter( // All of the subtree model paths are our model paths. const SdfPathVector& writerModelPaths = writer->GetModelPaths(); _modelPaths.insert( - _modelPaths.begin(), - writerModelPaths.begin(), - writerModelPaths.end()); + _modelPaths.begin(), writerModelPaths.begin(), writerModelPaths.end()); // Replace prefixes to obtain DAG-USD path mapping. - const UsdMayaUtil::MDagPathMap& writerMapping = - writer->GetDagToUsdPathMapping(); + const UsdMayaUtil::MDagPathMap& writerMapping + = writer->GetDagToUsdPathMapping(); for (const std::pair& pair : writerMapping) { const MDagPath& dagPathInMaster = pair.first; - const SdfPath& usdPathInMaster = pair.second; + const SdfPath& usdPathInMaster = pair.second; - const MDagPath& dagProxyPath = _ReplaceInstancePrefix( - dagPathInMaster, dagMasterRootPath, mayaInstancePath); - const SdfPath& usdProxyPath = usdPathInMaster.ReplacePrefix( - referencePath, usdInstancePath); + const MDagPath& dagProxyPath + = _ReplaceInstancePrefix(dagPathInMaster, dagMasterRootPath, mayaInstancePath); + const SdfPath& usdProxyPath + = usdPathInMaster.ReplacePrefix(referencePath, usdInstancePath); _dagToUsdPaths[dagProxyPath] = usdProxyPath; } } @@ -194,38 +183,21 @@ UsdMaya_InstancedNodeWriter::UsdMaya_InstancedNodeWriter( } /* virtual */ -bool -UsdMaya_InstancedNodeWriter::ExportsGprims() const -{ - return _exportsGprims; -} +bool UsdMaya_InstancedNodeWriter::ExportsGprims() const { return _exportsGprims; } /* virtual */ -bool -UsdMaya_InstancedNodeWriter::ShouldPruneChildren() const -{ - return true; -} +bool UsdMaya_InstancedNodeWriter::ShouldPruneChildren() const { return true; } /* virtual */ -const SdfPathVector& -UsdMaya_InstancedNodeWriter::GetModelPaths() const -{ - return _modelPaths; -} +const SdfPathVector& UsdMaya_InstancedNodeWriter::GetModelPaths() const { return _modelPaths; } /* virtual */ -const UsdMayaUtil::MDagPathMap& -UsdMaya_InstancedNodeWriter::GetDagToUsdPathMapping() const +const UsdMayaUtil::MDagPathMap& UsdMaya_InstancedNodeWriter::GetDagToUsdPathMapping() const { return _dagToUsdPaths; } /* virtual */ -void -UsdMaya_InstancedNodeWriter::Write(const UsdTimeCode& /* usdTime */) -{ -} - +void UsdMaya_InstancedNodeWriter::Write(const UsdTimeCode& /* usdTime */) { } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/instancedNodeWriter.h b/lib/mayaUsd/fileio/instancedNodeWriter.h index 2006901e83..86a0cf212d 100644 --- a/lib/mayaUsd/fileio/instancedNodeWriter.h +++ b/lib/mayaUsd/fileio/instancedNodeWriter.h @@ -16,17 +16,17 @@ #ifndef PXRUSDMAYA_INSTANCED_NODE_WRITER_H #define PXRUSDMAYA_INSTANCED_NODE_WRITER_H -#include - -#include +#include +#include +#include #include #include #include -#include -#include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE @@ -36,28 +36,25 @@ class UsdMaya_InstancedNodeWriter : public UsdMayaPrimWriter { public: UsdMaya_InstancedNodeWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdInstancePath, - UsdMayaWriteJobContext& ctx); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdInstancePath, + UsdMayaWriteJobContext& ctx); - bool ExportsGprims() const override; - bool ShouldPruneChildren() const override; - const SdfPathVector& GetModelPaths() const override; - const UsdMayaUtil::MDagPathMap& - GetDagToUsdPathMapping() const override; - void Write(const UsdTimeCode& usdTime) override; + bool ExportsGprims() const override; + bool ShouldPruneChildren() const override; + const SdfPathVector& GetModelPaths() const override; + const UsdMayaUtil::MDagPathMap& GetDagToUsdPathMapping() const override; + void Write(const UsdTimeCode& usdTime) override; private: UsdMayaWriteJobContext::_ExportAndRefPaths _masterPaths; // All of the data below is cached when we construct/obtain prim writers. - bool _exportsGprims; - std::vector _modelPaths; + bool _exportsGprims; + std::vector _modelPaths; UsdMayaUtil::MDagPathMap _dagToUsdPaths; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/jobs/jobArgs.cpp b/lib/mayaUsd/fileio/jobs/jobArgs.cpp index 96160470b0..8c094d036e 100644 --- a/lib/mayaUsd/fileio/jobs/jobArgs.cpp +++ b/lib/mayaUsd/fileio/jobs/jobArgs.cpp @@ -15,13 +15,8 @@ // #include "jobArgs.h" -#include -#include - -#include -#include -#include -#include +#include +#include #include #include @@ -30,61 +25,59 @@ #include #include #include -#include -#include #include #include +#include +#include #include -#include -#include +#include +#include +#include +#include -PXR_NAMESPACE_OPEN_SCOPE +#include +#include +PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PUBLIC_TOKENS(UsdMayaTranslatorTokens, - PXRUSDMAYA_TRANSLATOR_TOKENS); +TF_DEFINE_PUBLIC_TOKENS(UsdMayaTranslatorTokens, PXRUSDMAYA_TRANSLATOR_TOKENS); -TF_DEFINE_PUBLIC_TOKENS(UsdMayaJobExportArgsTokens, - PXRUSDMAYA_JOB_EXPORT_ARGS_TOKENS); +TF_DEFINE_PUBLIC_TOKENS(UsdMayaJobExportArgsTokens, PXRUSDMAYA_JOB_EXPORT_ARGS_TOKENS); -TF_DEFINE_PUBLIC_TOKENS(UsdMayaJobImportArgsTokens, - PXRUSDMAYA_JOB_IMPORT_ARGS_TOKENS); +TF_DEFINE_PUBLIC_TOKENS(UsdMayaJobImportArgsTokens, PXRUSDMAYA_JOB_IMPORT_ARGS_TOKENS); TF_DEFINE_PRIVATE_TOKENS( _usdExportInfoScope, - (UsdMaya) - (UsdExport) -); + (UsdMaya)(UsdExport)); TF_DEFINE_PRIVATE_TOKENS( _usdImportInfoScope, - (UsdMaya) - (UsdImport) -); - + (UsdMaya)(UsdImport)); /// Extracts a bool at \p key from \p userArgs, or false if it can't extract. -static bool -_Boolean(const VtDictionary& userArgs, const TfToken& key) +static bool _Boolean(const VtDictionary& userArgs, const TfToken& key) { if (!VtDictionaryIsHolding(userArgs, key)) { - TF_CODING_ERROR("Dictionary is missing required key '%s' or key is " - "not bool type", key.GetText()); + TF_CODING_ERROR( + "Dictionary is missing required key '%s' or key is " + "not bool type", + key.GetText()); return false; } return VtDictionaryGet(userArgs, key); } /// Extracts a string at \p key from \p userArgs, or "" if it can't extract. -static std::string -_String(const VtDictionary& userArgs, const TfToken& key) +static std::string _String(const VtDictionary& userArgs, const TfToken& key) { if (!VtDictionaryIsHolding(userArgs, key)) { - TF_CODING_ERROR("Dictionary is missing required key '%s' or key is " - "not string type", key.GetText()); + TF_CODING_ERROR( + "Dictionary is missing required key '%s' or key is " + "not string type", + key.GetText()); return std::string(); } return VtDictionaryGet(userArgs, key); @@ -93,11 +86,10 @@ _String(const VtDictionary& userArgs, const TfToken& key) /// Extracts a token at \p key from \p userArgs. /// If the token value is not either \p defaultToken or one of the /// \p otherTokens, then returns \p defaultToken instead. -static TfToken -_Token( - const VtDictionary& userArgs, - const TfToken& key, - const TfToken& defaultToken, +static TfToken _Token( + const VtDictionary& userArgs, + const TfToken& key, + const TfToken& defaultToken, const std::vector& otherTokens) { const TfToken tok(_String(userArgs, key)); @@ -110,17 +102,19 @@ _Token( // Empty token will silently be promoted to default value. // Warning for non-empty tokens that don't match. if (tok != defaultToken && !tok.IsEmpty()) { - TF_WARN("Value '%s' is not allowed for flag '%s'; using fallback '%s' " - "instead", - tok.GetText(), key.GetText(), defaultToken.GetText()); + TF_WARN( + "Value '%s' is not allowed for flag '%s'; using fallback '%s' " + "instead", + tok.GetText(), + key.GetText(), + defaultToken.GetText()); } return defaultToken; } /// Extracts an absolute path at \p key from \p userArgs, or the empty path if /// it can't extract. -static SdfPath -_AbsolutePath(const VtDictionary& userArgs, const TfToken& key) +static SdfPath _AbsolutePath(const VtDictionary& userArgs, const TfToken& key) { const std::string s = _String(userArgs, key); // Assume that empty strings are empty paths. (This might be an error case.) @@ -131,33 +125,33 @@ _AbsolutePath(const VtDictionary& userArgs, const TfToken& key) SdfPath path(s); if (path.IsAbsolutePath()) { return path; - } - else { + } else { return SdfPath::AbsoluteRootPath().AppendPath(path); } } /// Extracts an vector from the vector at \p key in \p userArgs. /// Returns an empty vector if it can't convert the entire value at \p key into -/// a vector. +/// a vector. template -static std::vector -_Vector(const VtDictionary& userArgs, const TfToken& key) +static std::vector _Vector(const VtDictionary& userArgs, const TfToken& key) { // Check that vector exists. if (!VtDictionaryIsHolding>(userArgs, key)) { - TF_CODING_ERROR("Dictionary is missing required key '%s' or key is " - "not vector type", key.GetText()); + TF_CODING_ERROR( + "Dictionary is missing required key '%s' or key is " + "not vector type", + key.GetText()); return std::vector(); } // Check that vector is correctly-typed. - std::vector vals = - VtDictionaryGet>(userArgs, key); - if (!std::all_of(vals.begin(), vals.end(), - [](const VtValue& v) { return v.IsHolding(); })) { - TF_CODING_ERROR("Vector at dictionary key '%s' contains elements of " - "the wrong type", key.GetText()); + std::vector vals = VtDictionaryGet>(userArgs, key); + if (!std::all_of(vals.begin(), vals.end(), [](const VtValue& v) { return v.IsHolding(); })) { + TF_CODING_ERROR( + "Vector at dictionary key '%s' contains elements of " + "the wrong type", + key.GetText()); return std::vector(); } @@ -171,11 +165,10 @@ _Vector(const VtDictionary& userArgs, const TfToken& key) /// Convenience function that takes the result of _Vector and converts it to a /// TfToken::Set. -static TfToken::Set -_TokenSet(const VtDictionary& userArgs, const TfToken& key) +static TfToken::Set _TokenSet(const VtDictionary& userArgs, const TfToken& key) { const std::vector vec = _Vector(userArgs, key); - TfToken::Set result; + TfToken::Set result; for (const std::string& s : vec) { result.insert(TfToken(s)); } @@ -188,14 +181,13 @@ _TokenSet(const VtDictionary& userArgs, const TfToken& key) static std::map _ChaserArgs(const VtDictionary& userArgs, const TfToken& key) { - const std::vector> chaserArgs = - _Vector>(userArgs, key); + const std::vector> chaserArgs + = _Vector>(userArgs, key); std::map result; for (const std::vector& argTriple : chaserArgs) { if (argTriple.size() != 3) { - TF_CODING_ERROR( - "Each chaser arg must be a triple (chaser, arg, value)"); + TF_CODING_ERROR("Each chaser arg must be a triple (chaser, arg, value)"); return std::map(); } @@ -247,14 +239,12 @@ _shadingModesImportArgs(const VtDictionary& userArgs, const TfToken& key) // Do not validate second parameter if not in a useRegistry scenario. } - result.push_back(UsdMayaJobImportArgs::ShadingMode{shadingMode, convertMaterialFrom}); + result.push_back(UsdMayaJobImportArgs::ShadingMode { shadingMode, convertMaterialFrom }); } return result; } -static -TfToken -_GetMaterialsScopeName(const std::string& materialsScopeName) +static TfToken _GetMaterialsScopeName(const std::string& materialsScopeName) { const TfToken defaultMaterialsScopeName = UsdUtilsGetMaterialsScopeName(); @@ -279,155 +269,112 @@ _GetMaterialsScopeName(const std::string& materialsScopeName) } UsdMayaJobExportArgs::UsdMayaJobExportArgs( - const VtDictionary& userArgs, + const VtDictionary& userArgs, const UsdMayaUtil::MDagPathSet& dagPaths, - const std::vector& timeSamples) : - compatibility( - _Token(userArgs, - UsdMayaJobExportArgsTokens->compatibility, - UsdMayaJobExportArgsTokens->none, - { - UsdMayaJobExportArgsTokens->appleArKit - })), - defaultMeshScheme( - _Token(userArgs, - UsdMayaJobExportArgsTokens->defaultMeshScheme, - UsdGeomTokens->catmullClark, - { - UsdGeomTokens->loop, - UsdGeomTokens->bilinear, - UsdGeomTokens->none - })), - defaultUSDFormat( - _Token(userArgs, - UsdMayaJobExportArgsTokens->defaultUSDFormat, - UsdUsdcFileFormatTokens->Id, - { - UsdUsdaFileFormatTokens->Id - })), - eulerFilter( - _Boolean(userArgs, UsdMayaJobExportArgsTokens->eulerFilter)), - excludeInvisible( - _Boolean(userArgs, UsdMayaJobExportArgsTokens->renderableOnly)), - exportCollectionBasedBindings( - _Boolean(userArgs, - UsdMayaJobExportArgsTokens->exportCollectionBasedBindings)), - exportColorSets( - _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportColorSets)), - exportDefaultCameras( - _Boolean(userArgs, UsdMayaJobExportArgsTokens->defaultCameras)), - exportDisplayColor( - _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportDisplayColor)), - exportInstances( - _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportInstances)), - exportMaterialCollections( - _Boolean(userArgs, - UsdMayaJobExportArgsTokens->exportMaterialCollections)), - exportMeshUVs( - _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportUVs)), - exportNurbsExplicitUV( - _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportUVs)), - exportReferenceObjects( - _Boolean(userArgs, - UsdMayaJobExportArgsTokens->exportReferenceObjects)), - exportRefsAsInstanceable( - _Boolean(userArgs, - UsdMayaJobExportArgsTokens->exportRefsAsInstanceable)), - exportSkels( - _Token(userArgs, - UsdMayaJobExportArgsTokens->exportSkels, - UsdMayaJobExportArgsTokens->none, - { - UsdMayaJobExportArgsTokens->auto_, - UsdMayaJobExportArgsTokens->explicit_ - })), - exportSkin( - _Token(userArgs, - UsdMayaJobExportArgsTokens->exportSkin, - UsdMayaJobExportArgsTokens->none, - { - UsdMayaJobExportArgsTokens->auto_, - UsdMayaJobExportArgsTokens->explicit_ - })), - exportVisibility( - _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportVisibility)), - materialCollectionsPath( - _AbsolutePath(userArgs, - UsdMayaJobExportArgsTokens->materialCollectionsPath)), - materialsScopeName( - _GetMaterialsScopeName( - _String(userArgs, - UsdMayaJobExportArgsTokens->materialsScopeName))), - mergeTransformAndShape( - _Boolean(userArgs, - UsdMayaJobExportArgsTokens->mergeTransformAndShape)), - normalizeNurbs( - _Boolean(userArgs, UsdMayaJobExportArgsTokens->normalizeNurbs)), - stripNamespaces( - _Boolean(userArgs, - UsdMayaJobExportArgsTokens->stripNamespaces)), - parentScope( - _AbsolutePath(userArgs, UsdMayaJobExportArgsTokens->parentScope)), - renderLayerMode( - _Token(userArgs, - UsdMayaJobExportArgsTokens->renderLayerMode, - UsdMayaJobExportArgsTokens->defaultLayer, - { - UsdMayaJobExportArgsTokens->currentLayer, - UsdMayaJobExportArgsTokens->modelingVariant - })), - rootKind( - _String(userArgs, UsdMayaJobExportArgsTokens->kind)), - shadingMode( - _Token(userArgs, - UsdMayaJobExportArgsTokens->shadingMode, - UsdMayaShadingModeTokens->none, - UsdMayaShadingModeRegistry::ListExporters())), - convertMaterialsTo( - _Token(userArgs, - UsdMayaJobExportArgsTokens->convertMaterialsTo, - UsdImagingTokens->UsdPreviewSurface, - UsdMayaShadingModeRegistry::ListMaterialConversions())), - verbose( - _Boolean(userArgs, UsdMayaJobExportArgsTokens->verbose)), - - chaserNames( - _Vector(userArgs, UsdMayaJobExportArgsTokens->chaser)), - allChaserArgs( - _ChaserArgs(userArgs, UsdMayaJobExportArgsTokens->chaserArgs)), - - melPerFrameCallback( - _String(userArgs, UsdMayaJobExportArgsTokens->melPerFrameCallback)), - melPostCallback( - _String(userArgs, UsdMayaJobExportArgsTokens->melPostCallback)), - pythonPerFrameCallback( - _String(userArgs, - UsdMayaJobExportArgsTokens->pythonPerFrameCallback)), - pythonPostCallback( - _String(userArgs, UsdMayaJobExportArgsTokens->pythonPostCallback)), - - dagPaths(dagPaths), - timeSamples(timeSamples) + const std::vector& timeSamples) + : compatibility(_Token( + userArgs, + UsdMayaJobExportArgsTokens->compatibility, + UsdMayaJobExportArgsTokens->none, + { UsdMayaJobExportArgsTokens->appleArKit })) + , defaultMeshScheme(_Token( + userArgs, + UsdMayaJobExportArgsTokens->defaultMeshScheme, + UsdGeomTokens->catmullClark, + { UsdGeomTokens->loop, UsdGeomTokens->bilinear, UsdGeomTokens->none })) + , defaultUSDFormat(_Token( + userArgs, + UsdMayaJobExportArgsTokens->defaultUSDFormat, + UsdUsdcFileFormatTokens->Id, + { UsdUsdaFileFormatTokens->Id })) + , eulerFilter(_Boolean(userArgs, UsdMayaJobExportArgsTokens->eulerFilter)) + , excludeInvisible(_Boolean(userArgs, UsdMayaJobExportArgsTokens->renderableOnly)) + , exportCollectionBasedBindings( + _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportCollectionBasedBindings)) + , exportColorSets(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportColorSets)) + , exportDefaultCameras(_Boolean(userArgs, UsdMayaJobExportArgsTokens->defaultCameras)) + , exportDisplayColor(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportDisplayColor)) + , exportInstances(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportInstances)) + , exportMaterialCollections( + _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportMaterialCollections)) + , exportMeshUVs(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportUVs)) + , exportNurbsExplicitUV(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportUVs)) + , exportReferenceObjects(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportReferenceObjects)) + , exportRefsAsInstanceable( + _Boolean(userArgs, UsdMayaJobExportArgsTokens->exportRefsAsInstanceable)) + , exportSkels(_Token( + userArgs, + UsdMayaJobExportArgsTokens->exportSkels, + UsdMayaJobExportArgsTokens->none, + { UsdMayaJobExportArgsTokens->auto_, UsdMayaJobExportArgsTokens->explicit_ })) + , exportSkin(_Token( + userArgs, + UsdMayaJobExportArgsTokens->exportSkin, + UsdMayaJobExportArgsTokens->none, + { UsdMayaJobExportArgsTokens->auto_, UsdMayaJobExportArgsTokens->explicit_ })) + , exportVisibility(_Boolean(userArgs, UsdMayaJobExportArgsTokens->exportVisibility)) + , materialCollectionsPath( + _AbsolutePath(userArgs, UsdMayaJobExportArgsTokens->materialCollectionsPath)) + , materialsScopeName( + _GetMaterialsScopeName(_String(userArgs, UsdMayaJobExportArgsTokens->materialsScopeName))) + , mergeTransformAndShape(_Boolean(userArgs, UsdMayaJobExportArgsTokens->mergeTransformAndShape)) + , normalizeNurbs(_Boolean(userArgs, UsdMayaJobExportArgsTokens->normalizeNurbs)) + , stripNamespaces(_Boolean(userArgs, UsdMayaJobExportArgsTokens->stripNamespaces)) + , parentScope(_AbsolutePath(userArgs, UsdMayaJobExportArgsTokens->parentScope)) + , renderLayerMode(_Token( + userArgs, + UsdMayaJobExportArgsTokens->renderLayerMode, + UsdMayaJobExportArgsTokens->defaultLayer, + { UsdMayaJobExportArgsTokens->currentLayer, + UsdMayaJobExportArgsTokens->modelingVariant })) + , rootKind(_String(userArgs, UsdMayaJobExportArgsTokens->kind)) + , shadingMode(_Token( + userArgs, + UsdMayaJobExportArgsTokens->shadingMode, + UsdMayaShadingModeTokens->none, + UsdMayaShadingModeRegistry::ListExporters())) + , convertMaterialsTo(_Token( + userArgs, + UsdMayaJobExportArgsTokens->convertMaterialsTo, + UsdImagingTokens->UsdPreviewSurface, + UsdMayaShadingModeRegistry::ListMaterialConversions())) + , verbose(_Boolean(userArgs, UsdMayaJobExportArgsTokens->verbose)) + , + + chaserNames(_Vector(userArgs, UsdMayaJobExportArgsTokens->chaser)) + , allChaserArgs(_ChaserArgs(userArgs, UsdMayaJobExportArgsTokens->chaserArgs)) + , + + melPerFrameCallback(_String(userArgs, UsdMayaJobExportArgsTokens->melPerFrameCallback)) + , melPostCallback(_String(userArgs, UsdMayaJobExportArgsTokens->melPostCallback)) + , pythonPerFrameCallback(_String(userArgs, UsdMayaJobExportArgsTokens->pythonPerFrameCallback)) + , pythonPostCallback(_String(userArgs, UsdMayaJobExportArgsTokens->pythonPostCallback)) + , + + dagPaths(dagPaths) + , timeSamples(timeSamples) { } -std::ostream& -operator <<(std::ostream& out, const UsdMayaJobExportArgs& exportArgs) +std::ostream& operator<<(std::ostream& out, const UsdMayaJobExportArgs& exportArgs) { out << "compatibility: " << exportArgs.compatibility << std::endl << "defaultMeshScheme: " << exportArgs.defaultMeshScheme << std::endl << "defaultUSDFormat: " << exportArgs.defaultUSDFormat << std::endl << "eulerFilter: " << TfStringify(exportArgs.eulerFilter) << std::endl << "excludeInvisible: " << TfStringify(exportArgs.excludeInvisible) << std::endl - << "exportCollectionBasedBindings: " << TfStringify(exportArgs.exportCollectionBasedBindings) << std::endl + << "exportCollectionBasedBindings: " + << TfStringify(exportArgs.exportCollectionBasedBindings) << std::endl << "exportColorSets: " << TfStringify(exportArgs.exportColorSets) << std::endl << "exportDefaultCameras: " << TfStringify(exportArgs.exportDefaultCameras) << std::endl << "exportDisplayColor: " << TfStringify(exportArgs.exportDisplayColor) << std::endl << "exportInstances: " << TfStringify(exportArgs.exportInstances) << std::endl - << "exportMaterialCollections: " << TfStringify(exportArgs.exportMaterialCollections) << std::endl + << "exportMaterialCollections: " << TfStringify(exportArgs.exportMaterialCollections) + << std::endl << "exportMeshUVs: " << TfStringify(exportArgs.exportMeshUVs) << std::endl << "exportNurbsExplicitUV: " << TfStringify(exportArgs.exportNurbsExplicitUV) << std::endl - << "exportRefsAsInstanceable: " << TfStringify(exportArgs.exportRefsAsInstanceable) << std::endl + << "exportRefsAsInstanceable: " << TfStringify(exportArgs.exportRefsAsInstanceable) + << std::endl << "exportSkels: " << TfStringify(exportArgs.exportSkels) << std::endl << "exportSkin: " << TfStringify(exportArgs.exportSkin) << std::endl << "exportVisibility: " << TfStringify(exportArgs.exportVisibility) << std::endl @@ -461,7 +408,7 @@ operator <<(std::ostream& out, const UsdMayaJobExportArgs& exportArgs) out << "chaserNames (" << exportArgs.chaserNames.size() << ")" << std::endl; for (const std::string& chaserName : exportArgs.chaserNames) { - out << " " << chaserName << std::endl; + out << " " << chaserName << std::endl; } out << "allChaserArgs (" << exportArgs.allChaserArgs.size() << ")" << std::endl; @@ -470,8 +417,8 @@ operator <<(std::ostream& out, const UsdMayaJobExportArgs& exportArgs) out << " " << chaserIter.first << std::endl; for (const auto& argIter : chaserIter.second) { - out << " Arg Name: " << argIter.first - << ", Value: " << argIter.second << std::endl; + out << " Arg Name: " << argIter.first << ", Value: " << argIter.second + << std::endl; } } @@ -479,35 +426,28 @@ operator <<(std::ostream& out, const UsdMayaJobExportArgs& exportArgs) } /* static */ -UsdMayaJobExportArgs -UsdMayaJobExportArgs::CreateFromDictionary( - const VtDictionary& userArgs, - const UsdMayaUtil::MDagPathSet& dagPaths, - const std::vector& timeSamples) +UsdMayaJobExportArgs UsdMayaJobExportArgs::CreateFromDictionary( + const VtDictionary& userArgs, + const UsdMayaUtil::MDagPathSet& dagPaths, + const std::vector& timeSamples) { return UsdMayaJobExportArgs( - VtDictionaryOver(userArgs, GetDefaultDictionary()), - dagPaths, - timeSamples); + VtDictionaryOver(userArgs, GetDefaultDictionary()), dagPaths, timeSamples); } /* static */ -const VtDictionary& -UsdMayaJobExportArgs::GetDefaultDictionary() +const VtDictionary& UsdMayaJobExportArgs::GetDefaultDictionary() { - static VtDictionary d; + static VtDictionary d; static std::once_flag once; std::call_once(once, []() { // Base defaults. d[UsdMayaJobExportArgsTokens->chaser] = std::vector(); d[UsdMayaJobExportArgsTokens->chaserArgs] = std::vector(); - d[UsdMayaJobExportArgsTokens->compatibility] = - UsdMayaJobExportArgsTokens->none.GetString(); + d[UsdMayaJobExportArgsTokens->compatibility] = UsdMayaJobExportArgsTokens->none.GetString(); d[UsdMayaJobExportArgsTokens->defaultCameras] = false; - d[UsdMayaJobExportArgsTokens->defaultMeshScheme] = - UsdGeomTokens->catmullClark.GetString(); - d[UsdMayaJobExportArgsTokens->defaultUSDFormat] = - UsdUsdcFileFormatTokens->Id.GetString(); + d[UsdMayaJobExportArgsTokens->defaultMeshScheme] = UsdGeomTokens->catmullClark.GetString(); + d[UsdMayaJobExportArgsTokens->defaultUSDFormat] = UsdUsdcFileFormatTokens->Id.GetString(); d[UsdMayaJobExportArgsTokens->eulerFilter] = false; d[UsdMayaJobExportArgsTokens->exportCollectionBasedBindings] = false; d[UsdMayaJobExportArgsTokens->exportColorSets] = true; @@ -516,16 +456,14 @@ UsdMayaJobExportArgs::GetDefaultDictionary() d[UsdMayaJobExportArgsTokens->exportMaterialCollections] = false; d[UsdMayaJobExportArgsTokens->exportReferenceObjects] = false; d[UsdMayaJobExportArgsTokens->exportRefsAsInstanceable] = false; - d[UsdMayaJobExportArgsTokens->exportSkin] = - UsdMayaJobExportArgsTokens->none.GetString(); - d[UsdMayaJobExportArgsTokens->exportSkels] = - UsdMayaJobExportArgsTokens->none.GetString(); + d[UsdMayaJobExportArgsTokens->exportSkin] = UsdMayaJobExportArgsTokens->none.GetString(); + d[UsdMayaJobExportArgsTokens->exportSkels] = UsdMayaJobExportArgsTokens->none.GetString(); d[UsdMayaJobExportArgsTokens->exportUVs] = true; d[UsdMayaJobExportArgsTokens->exportVisibility] = true; d[UsdMayaJobExportArgsTokens->kind] = std::string(); d[UsdMayaJobExportArgsTokens->materialCollectionsPath] = std::string(); - d[UsdMayaJobExportArgsTokens->materialsScopeName] = - UsdUtilsGetMaterialsScopeName().GetString(); + d[UsdMayaJobExportArgsTokens->materialsScopeName] + = UsdUtilsGetMaterialsScopeName().GetString(); d[UsdMayaJobExportArgsTokens->melPerFrameCallback] = std::string(); d[UsdMayaJobExportArgsTokens->melPostCallback] = std::string(); d[UsdMayaJobExportArgsTokens->mergeTransformAndShape] = true; @@ -534,21 +472,20 @@ UsdMayaJobExportArgs::GetDefaultDictionary() d[UsdMayaJobExportArgsTokens->pythonPerFrameCallback] = std::string(); d[UsdMayaJobExportArgsTokens->pythonPostCallback] = std::string(); d[UsdMayaJobExportArgsTokens->renderableOnly] = false; - d[UsdMayaJobExportArgsTokens->renderLayerMode] = - UsdMayaJobExportArgsTokens->defaultLayer.GetString(); - d[UsdMayaJobExportArgsTokens->shadingMode] = - UsdMayaShadingModeTokens->useRegistry.GetString(); - d[UsdMayaJobExportArgsTokens->convertMaterialsTo] = - UsdImagingTokens->UsdPreviewSurface.GetString(); + d[UsdMayaJobExportArgsTokens->renderLayerMode] + = UsdMayaJobExportArgsTokens->defaultLayer.GetString(); + d[UsdMayaJobExportArgsTokens->shadingMode] + = UsdMayaShadingModeTokens->useRegistry.GetString(); + d[UsdMayaJobExportArgsTokens->convertMaterialsTo] + = UsdImagingTokens->UsdPreviewSurface.GetString(); d[UsdMayaJobExportArgsTokens->stripNamespaces] = false; d[UsdMayaJobExportArgsTokens->verbose] = false; // plugInfo.json site defaults. // The defaults dict should be correctly-typed, so enable // coerceToWeakerOpinionType. - const VtDictionary site = - UsdMaya_RegistryHelper::GetComposedInfoDictionary( - _usdExportInfoScope->allTokens); + const VtDictionary site + = UsdMaya_RegistryHelper::GetComposedInfoDictionary(_usdExportInfoScope->allTokens); VtDictionaryOver(site, &d, /*coerceToWeakerOpinionType*/ true); }); @@ -557,11 +494,10 @@ UsdMayaJobExportArgs::GetDefaultDictionary() void UsdMayaJobExportArgs::AddFilteredTypeName(const MString& typeName) { - MNodeClass cls(typeName); + MNodeClass cls(typeName); unsigned int id = cls.typeId().id(); if (id == 0) { - TF_WARN("Given excluded node type '%s' does not exist; ignoring", - typeName.asChar()); + TF_WARN("Given excluded node type '%s' does not exist; ignoring", typeName.asChar()); return; } _filteredTypeIds.insert(id); @@ -571,15 +507,18 @@ void UsdMayaJobExportArgs::AddFilteredTypeName(const MString& typeName) MString queryCommand("nodeType -isTypeName -derived "); queryCommand += typeName; MStringArray inheritedTypes; - MStatus status = MGlobal::executeCommand(queryCommand, inheritedTypes, false, false); + MStatus status = MGlobal::executeCommand(queryCommand, inheritedTypes, false, false); if (!status) { - TF_WARN("Error querying derived types for '%s': %s", - typeName.asChar(), status.errorString().asChar()); + TF_WARN( + "Error querying derived types for '%s': %s", + typeName.asChar(), + status.errorString().asChar()); return; } - for (unsigned int i=0; i < inheritedTypes.length(); ++i) { - if (inheritedTypes[i].length() == 0) continue; + for (unsigned int i = 0; i < inheritedTypes.length(); ++i) { + if (inheritedTypes[i].length() == 0) + continue; id = MNodeClass(inheritedTypes[i]).typeId().id(); if (id == 0) { // Unfortunately, the returned list will often include weird garbage, like @@ -593,76 +532,63 @@ void UsdMayaJobExportArgs::AddFilteredTypeName(const MString& typeName) UsdMayaJobImportArgs::UsdMayaJobImportArgs( const VtDictionary& userArgs, - const bool importWithProxyShapes, - const GfInterval& timeInterval) : - assemblyRep( - _Token(userArgs, - UsdMayaJobImportArgsTokens->assemblyRep, - UsdMayaJobImportArgsTokens->Collapsed, - { - UsdMayaJobImportArgsTokens->Full, - UsdMayaJobImportArgsTokens->Import, - UsdMayaJobImportArgsTokens->Unloaded - })), - excludePrimvarNames( - _TokenSet(userArgs, UsdMayaJobImportArgsTokens->excludePrimvar)), - includeAPINames( - _TokenSet(userArgs, UsdMayaJobImportArgsTokens->apiSchema)), - includeMetadataKeys( - _TokenSet(userArgs, UsdMayaJobImportArgsTokens->metadata)), - shadingModes( - _shadingModesImportArgs(userArgs, UsdMayaJobImportArgsTokens->shadingMode)), - preferredMaterial( - _Token(userArgs, - UsdMayaJobImportArgsTokens->preferredMaterial, - UsdMayaPreferredMaterialTokens->none, - UsdMayaPreferredMaterialTokens->allTokens)), - importInstances( - _Boolean(userArgs, - UsdMayaJobImportArgsTokens->importInstances)), - useAsAnimationCache( - _Boolean(userArgs, - UsdMayaJobImportArgsTokens->useAsAnimationCache)), - - importWithProxyShapes(importWithProxyShapes), - timeInterval(timeInterval) + const bool importWithProxyShapes, + const GfInterval& timeInterval) + : assemblyRep(_Token( + userArgs, + UsdMayaJobImportArgsTokens->assemblyRep, + UsdMayaJobImportArgsTokens->Collapsed, + { UsdMayaJobImportArgsTokens->Full, + UsdMayaJobImportArgsTokens->Import, + UsdMayaJobImportArgsTokens->Unloaded })) + , excludePrimvarNames(_TokenSet(userArgs, UsdMayaJobImportArgsTokens->excludePrimvar)) + , includeAPINames(_TokenSet(userArgs, UsdMayaJobImportArgsTokens->apiSchema)) + , includeMetadataKeys(_TokenSet(userArgs, UsdMayaJobImportArgsTokens->metadata)) + , shadingModes(_shadingModesImportArgs(userArgs, UsdMayaJobImportArgsTokens->shadingMode)) + , preferredMaterial(_Token( + userArgs, + UsdMayaJobImportArgsTokens->preferredMaterial, + UsdMayaPreferredMaterialTokens->none, + UsdMayaPreferredMaterialTokens->allTokens)) + , importInstances(_Boolean(userArgs, UsdMayaJobImportArgsTokens->importInstances)) + , useAsAnimationCache(_Boolean(userArgs, UsdMayaJobImportArgsTokens->useAsAnimationCache)) + , + + importWithProxyShapes(importWithProxyShapes) + , timeInterval(timeInterval) { } -TfToken -UsdMayaJobImportArgs::GetMaterialConversion() const { +TfToken UsdMayaJobImportArgs::GetMaterialConversion() const +{ return shadingModes.empty() ? TfToken() : shadingModes.front().materialConversion; } /* static */ UsdMayaJobImportArgs UsdMayaJobImportArgs::CreateFromDictionary( const VtDictionary& userArgs, - const bool importWithProxyShapes, - const GfInterval& timeInterval) + const bool importWithProxyShapes, + const GfInterval& timeInterval) { return UsdMayaJobImportArgs( - VtDictionaryOver(userArgs, GetDefaultDictionary()), - importWithProxyShapes, - timeInterval); + VtDictionaryOver(userArgs, GetDefaultDictionary()), importWithProxyShapes, timeInterval); } /* static */ const VtDictionary& UsdMayaJobImportArgs::GetDefaultDictionary() { - static VtDictionary d; + static VtDictionary d; static std::once_flag once; std::call_once(once, []() { // Base defaults. - d[UsdMayaJobImportArgsTokens->assemblyRep] = - UsdMayaJobImportArgsTokens->Collapsed.GetString(); + d[UsdMayaJobImportArgsTokens->assemblyRep] + = UsdMayaJobImportArgsTokens->Collapsed.GetString(); d[UsdMayaJobImportArgsTokens->apiSchema] = std::vector(); d[UsdMayaJobImportArgsTokens->excludePrimvar] = std::vector(); - d[UsdMayaJobImportArgsTokens->metadata] = - std::vector({ - VtValue(SdfFieldKeys->Hidden.GetString()), - VtValue(SdfFieldKeys->Instanceable.GetString()), - VtValue(SdfFieldKeys->Kind.GetString()) - }); + d[UsdMayaJobImportArgsTokens->metadata] + = std::vector({ VtValue(SdfFieldKeys->Hidden.GetString()), + VtValue(SdfFieldKeys->Instanceable.GetString()), + VtValue(SdfFieldKeys->Kind.GetString()) }); d[UsdMayaJobImportArgsTokens->shadingMode] = std::vector { VtValue( std::vector { VtValue(UsdMayaShadingModeTokens->useRegistry.GetString()), VtValue(UsdImagingTokens->UsdPreviewSurface.GetString()) }) }; @@ -674,17 +600,15 @@ const VtDictionary& UsdMayaJobImportArgs::GetDefaultDictionary() // plugInfo.json site defaults. // The defaults dict should be correctly-typed, so enable // coerceToWeakerOpinionType. - const VtDictionary site = - UsdMaya_RegistryHelper::GetComposedInfoDictionary( - _usdImportInfoScope->allTokens); + const VtDictionary site + = UsdMaya_RegistryHelper::GetComposedInfoDictionary(_usdImportInfoScope->allTokens); VtDictionaryOver(site, &d, /*coerceToWeakerOpinionType*/ true); }); return d; } -std::ostream& -operator <<(std::ostream& out, const UsdMayaJobImportArgs& importArgs) +std::ostream& operator<<(std::ostream& out, const UsdMayaJobImportArgs& importArgs) { out << "shadingModes (" << importArgs.shadingModes.size() << ")" << std::endl; for (const auto& shadingMode : importArgs.shadingModes) { @@ -701,5 +625,4 @@ operator <<(std::ostream& out, const UsdMayaJobImportArgs& importArgs) return out; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/jobs/jobArgs.h b/lib/mayaUsd/fileio/jobs/jobArgs.h index a53e9db686..9dddd5364f 100644 --- a/lib/mayaUsd/fileio/jobs/jobArgs.h +++ b/lib/mayaUsd/fileio/jobs/jobArgs.h @@ -16,138 +16,92 @@ #ifndef PXRUSDMAYA_JOB_ARGS_H #define PXRUSDMAYA_JOB_ARGS_H -#include -#include -#include -#include -#include +#include +#include -#include #include #include +#include #include #include -#include -#include +#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -#define PXRUSDMAYA_TRANSLATOR_TOKENS \ - ((UsdFileExtensionDefault, "usd")) \ - ((UsdFileExtensionASCII, "usda")) \ - ((UsdFileExtensionCrate, "usdc")) \ - ((UsdFileExtensionPackage, "usdz")) \ - ((UsdReadableFileFilter, "*.usd *.usda *.usdc *.usdz")) \ - ((UsdWritableFileFilter, "*.usd *.usda *.usdc *.usdz")) +#define PXRUSDMAYA_TRANSLATOR_TOKENS \ + ((UsdFileExtensionDefault, "usd"))((UsdFileExtensionASCII, "usda"))( \ + (UsdFileExtensionCrate, "usdc"))((UsdFileExtensionPackage, "usdz"))( \ + (UsdReadableFileFilter, "*.usd *.usda *.usdc *.usdz"))( \ + (UsdWritableFileFilter, "*.usd *.usda *.usdc *.usdz")) TF_DECLARE_PUBLIC_TOKENS( UsdMayaTranslatorTokens, MAYAUSD_CORE_PUBLIC, PXRUSDMAYA_TRANSLATOR_TOKENS); -#define PXRUSDMAYA_JOB_EXPORT_ARGS_TOKENS \ - /* Dictionary keys */ \ - (chaser) \ - (chaserArgs) \ - (compatibility) \ - (defaultCameras) \ - (defaultMeshScheme) \ - (defaultUSDFormat) \ - (eulerFilter) \ - (exportCollectionBasedBindings) \ - (exportColorSets) \ - (exportDisplayColor) \ - (exportInstances) \ - (exportMaterialCollections) \ - (exportReferenceObjects) \ - (exportRefsAsInstanceable) \ - (exportSkels) \ - (exportSkin) \ - (exportUVs) \ - (exportVisibility) \ - (kind) \ - (materialCollectionsPath) \ - (materialsScopeName) \ - (melPerFrameCallback) \ - (melPostCallback) \ - (mergeTransformAndShape) \ - (normalizeNurbs) \ - (parentScope) \ - (pythonPerFrameCallback) \ - (pythonPostCallback) \ - (renderableOnly) \ - (renderLayerMode) \ - (shadingMode) \ - (convertMaterialsTo) \ - (stripNamespaces) \ - (verbose) \ - /* Special "none" token */ \ - (none) \ - /* renderLayerMode values */ \ - (defaultLayer) \ - (currentLayer) \ - (modelingVariant) \ - /* exportSkels/exportSkin values */ \ - ((auto_, "auto")) \ - ((explicit_, "explicit")) \ - /* compatibility values */ \ - (appleArKit) +#define PXRUSDMAYA_JOB_EXPORT_ARGS_TOKENS \ + /* Dictionary keys */ \ + (chaser)(chaserArgs)(compatibility)(defaultCameras)(defaultMeshScheme)(defaultUSDFormat)( \ + eulerFilter)(exportCollectionBasedBindings)(exportColorSets)(exportDisplayColor)( \ + exportInstances)(exportMaterialCollections)(exportReferenceObjects)( \ + exportRefsAsInstanceable)(exportSkels)(exportSkin)(exportUVs)(exportVisibility)(kind)( \ + materialCollectionsPath)(materialsScopeName)(melPerFrameCallback)(melPostCallback)( \ + mergeTransformAndShape)(normalizeNurbs)(parentScope)(pythonPerFrameCallback)( \ + pythonPostCallback)(renderableOnly)(renderLayerMode)(shadingMode)(convertMaterialsTo)( \ + stripNamespaces)(verbose) /* Special "none" token */ \ + (none) /* renderLayerMode values */ \ + (defaultLayer)(currentLayer)(modelingVariant) /* exportSkels/exportSkin values */ \ + ((auto_, "auto"))((explicit_, "explicit")) /* compatibility values */ \ + (appleArKit) TF_DECLARE_PUBLIC_TOKENS( UsdMayaJobExportArgsTokens, MAYAUSD_CORE_PUBLIC, PXRUSDMAYA_JOB_EXPORT_ARGS_TOKENS); -#define PXRUSDMAYA_JOB_IMPORT_ARGS_TOKENS \ - /* Dictionary keys */ \ - (apiSchema) \ - (assemblyRep) \ - (excludePrimvar) \ - (metadata) \ - (shadingMode) \ - (preferredMaterial) \ - (useAsAnimationCache) \ - (importInstances) \ - /* assemblyRep values */ \ - (Collapsed) \ - (Full) \ - (Import) \ - ((Unloaded, "")) +#define PXRUSDMAYA_JOB_IMPORT_ARGS_TOKENS \ + /* Dictionary keys */ \ + (apiSchema)(assemblyRep)(excludePrimvar)(metadata)(shadingMode)(preferredMaterial)( \ + useAsAnimationCache)(importInstances) /* assemblyRep values */ \ + (Collapsed)(Full)(Import)((Unloaded, "")) TF_DECLARE_PUBLIC_TOKENS( UsdMayaJobImportArgsTokens, MAYAUSD_CORE_PUBLIC, PXRUSDMAYA_JOB_IMPORT_ARGS_TOKENS); - struct UsdMayaJobExportArgs { const TfToken compatibility; const TfToken defaultMeshScheme; const TfToken defaultUSDFormat; - const bool eulerFilter; - const bool excludeInvisible; + const bool eulerFilter; + const bool excludeInvisible; /// If set to false, then direct per-gprim bindings are exported. /// If set to true and if \p materialCollectionsPath is non-empty, then /// material-collections are created and bindings are made to the /// collections at \p materialCollectionsPath, instead of direct /// per-gprim bindings. - const bool exportCollectionBasedBindings; - const bool exportColorSets; - const bool exportDefaultCameras; - const bool exportDisplayColor; - const bool exportInstances; - const bool exportMaterialCollections; - const bool exportMeshUVs; - const bool exportNurbsExplicitUV; - const bool exportReferenceObjects; - const bool exportRefsAsInstanceable; + const bool exportCollectionBasedBindings; + const bool exportColorSets; + const bool exportDefaultCameras; + const bool exportDisplayColor; + const bool exportInstances; + const bool exportMaterialCollections; + const bool exportMeshUVs; + const bool exportNurbsExplicitUV; + const bool exportReferenceObjects; + const bool exportRefsAsInstanceable; const TfToken exportSkels; const TfToken exportSkin; - const bool exportVisibility; + const bool exportVisibility; /// If this is not empty, then a set of collections are exported on the /// prim pointed to by the path, each representing the collection of @@ -171,11 +125,11 @@ struct UsdMayaJobExportArgs const TfToken rootKind; const TfToken shadingMode; const TfToken convertMaterialsTo; - const bool verbose; + const bool verbose; typedef std::map ChaserArgs; - const std::vector chaserNames; - const std::map< std::string, ChaserArgs > allChaserArgs; + const std::vector chaserNames; + const std::map allChaserArgs; const std::string melPerFrameCallback; const std::string melPostCallback; @@ -202,9 +156,9 @@ struct UsdMayaJobExportArgs /// types should match those declared in GetDefaultDictionary(). MAYAUSD_CORE_PUBLIC static UsdMayaJobExportArgs CreateFromDictionary( - const VtDictionary& userArgs, + const VtDictionary& userArgs, const UsdMayaUtil::MDagPathSet& dagPaths, - const std::vector& timeSamples = std::vector()); + const std::vector& timeSamples = std::vector()); /// Gets the default arguments dictionary for UsdMayaJobExportArgs. MAYAUSD_CORE_PUBLIC @@ -216,20 +170,16 @@ struct UsdMayaJobExportArgs MAYAUSD_CORE_PUBLIC void AddFilteredTypeName(const MString& typeName); - const std::set& GetFilteredTypeIds() const { - return _filteredTypeIds; - } + const std::set& GetFilteredTypeIds() const { return _filteredTypeIds; } - void ClearFilteredTypeIds() { - _filteredTypeIds.clear(); - } + void ClearFilteredTypeIds() { _filteredTypeIds.clear(); } private: MAYAUSD_CORE_PUBLIC UsdMayaJobExportArgs( - const VtDictionary& userArgs, + const VtDictionary& userArgs, const UsdMayaUtil::MDagPathSet& dagPaths, - const std::vector& timeSamples = std::vector()); + const std::vector& timeSamples = std::vector()); // Maya type ids to avoid exporting; these are // EXACT types, though the only exposed way to modify this, @@ -240,26 +190,24 @@ struct UsdMayaJobExportArgs }; MAYAUSD_CORE_PUBLIC -std::ostream& operator <<( - std::ostream& out, - const UsdMayaJobExportArgs& exportArgs); - +std::ostream& operator<<(std::ostream& out, const UsdMayaJobExportArgs& exportArgs); struct UsdMayaJobImportArgs { - const TfToken assemblyRep; + const TfToken assemblyRep; const TfToken::Set excludePrimvarNames; const TfToken::Set includeAPINames; const TfToken::Set includeMetadataKeys; - struct ShadingMode { + struct ShadingMode + { TfToken mode; TfToken materialConversion; }; using ShadingModes = std::vector; - ShadingModes shadingModes; // XXX can we make this const? + ShadingModes shadingModes; // XXX can we make this const? const TfToken preferredMaterial; - const bool importInstances; - const bool useAsAnimationCache; + const bool importInstances; + const bool useAsAnimationCache; const bool importWithProxyShapes; /// The interval over which to import animated data. @@ -284,8 +232,8 @@ struct UsdMayaJobImportArgs MAYAUSD_CORE_PUBLIC static UsdMayaJobImportArgs CreateFromDictionary( const VtDictionary& userArgs, - const bool importWithProxyShapes = false, - const GfInterval& timeInterval = GfInterval::GetFullInterval()); + const bool importWithProxyShapes = false, + const GfInterval& timeInterval = GfInterval::GetFullInterval()); /// Gets the default arguments dictionary for UsdMayaJobImportArgs. MAYAUSD_CORE_PUBLIC @@ -295,17 +243,13 @@ struct UsdMayaJobImportArgs MAYAUSD_CORE_PUBLIC UsdMayaJobImportArgs( const VtDictionary& userArgs, - const bool importWithProxyShapes, - const GfInterval& timeInterval); + const bool importWithProxyShapes, + const GfInterval& timeInterval); }; MAYAUSD_CORE_PUBLIC -std::ostream& operator <<( - std::ostream& out, - const UsdMayaJobImportArgs& importArgs); - +std::ostream& operator<<(std::ostream& out, const UsdMayaJobImportArgs& importArgs); PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/jobs/modelKindProcessor.cpp b/lib/mayaUsd/fileio/jobs/modelKindProcessor.cpp index 1b9611ba80..28fb3f292a 100644 --- a/lib/mayaUsd/fileio/jobs/modelKindProcessor.cpp +++ b/lib/mayaUsd/fileio/jobs/modelKindProcessor.cpp @@ -20,27 +20,24 @@ PXR_NAMESPACE_OPEN_SCOPE -UsdMaya_ModelKindProcessor::UsdMaya_ModelKindProcessor( - const UsdMayaJobExportArgs& args) - : _args(args), - _rootIsAssembly(KindRegistry::IsA(args.rootKind, KindTokens->assembly)) +UsdMaya_ModelKindProcessor::UsdMaya_ModelKindProcessor(const UsdMayaJobExportArgs& args) + : _args(args) + , _rootIsAssembly(KindRegistry::IsA(args.rootKind, KindTokens->assembly)) { } /// Returns the root-most ancestor of prim, which is either a component /// or a root-level prim. -static SdfPath -_FindAncestorRootPrimOrComponent(const UsdPrim& prim) +static SdfPath _FindAncestorRootPrimOrComponent(const UsdPrim& prim) { SdfPath rootPath; - for (SdfPath p = prim.GetPath(); p != SdfPath::AbsoluteRootPath(); - p = p.GetParentPath()) { + for (SdfPath p = prim.GetPath(); p != SdfPath::AbsoluteRootPath(); p = p.GetParentPath()) { UsdPrim ancestor = prim.GetStage()->GetPrimAtPath(p); if (ancestor && ancestor.IsModel()) { TfToken kind; - if (UsdModelAPI(ancestor).GetKind(&kind) && - KindRegistry::IsA(kind, KindTokens->component)) { + if (UsdModelAPI(ancestor).GetKind(&kind) + && KindRegistry::IsA(kind, KindTokens->component)) { return p; } } @@ -50,10 +47,8 @@ _FindAncestorRootPrimOrComponent(const UsdPrim& prim) return rootPath; } - -void -UsdMaya_ModelKindProcessor::OnWritePrim( - const UsdPrim& prim, +void UsdMaya_ModelKindProcessor::OnWritePrim( + const UsdPrim& prim, const UsdMayaPrimWriterSharedPtr& primWriter) { const SdfPath& path = prim.GetPath(); @@ -88,18 +83,13 @@ UsdMaya_ModelKindProcessor::OnWritePrim( } } - const SdfPathVector& modelPaths = - primWriter->GetModelPaths(); - _pathsThatMayHaveKind.insert( - _pathsThatMayHaveKind.end(), - modelPaths.begin(), - modelPaths.end()); + const SdfPathVector& modelPaths = primWriter->GetModelPaths(); + _pathsThatMayHaveKind.insert(_pathsThatMayHaveKind.end(), modelPaths.begin(), modelPaths.end()); } -bool -UsdMaya_ModelKindProcessor::MakeModelHierarchy(UsdStageRefPtr& stage) +bool UsdMaya_ModelKindProcessor::MakeModelHierarchy(UsdStageRefPtr& stage) { - // For any root-prim that doesn't already have an authored kind + // For any root-prim that doesn't already have an authored kind // (thinking ahead to being able to specify USD_kind per bug/128430), // make it a model. If there were any gprims authored directly during // export, we will make the roots be component models, and author @@ -107,7 +97,7 @@ UsdMaya_ModelKindProcessor::MakeModelHierarchy(UsdStageRefPtr& stage) // evaluate to some model-kind; we may in future make this behavior // a jobargs option. // - // If there were no gprims directly authored, we'll make it an assembly + // If there were no gprims directly authored, we'll make it an assembly // instead, and attempt to create a valid model-hierarchy if any of the // references we authored are references to models. // @@ -130,16 +120,15 @@ UsdMaya_ModelKindProcessor::MakeModelHierarchy(UsdStageRefPtr& stage) return true; } -bool -UsdMaya_ModelKindProcessor::_AuthorRootPrimKinds( +bool UsdMaya_ModelKindProcessor::_AuthorRootPrimKinds( UsdStageRefPtr& stage, - _PathBoolMap& rootPrimIsComponent) + _PathBoolMap& rootPrimIsComponent) { UsdPrimSiblingRange usdRootPrims = stage->GetPseudoRoot().GetChildren(); for (UsdPrim const& prim : usdRootPrims) { - SdfPath primPath = prim.GetPath(); + SdfPath primPath = prim.GetPath(); UsdModelAPI usdRootModel(prim); - TfToken kind; + TfToken kind; usdRootModel.GetKind(&kind); // If the rootKind job arg was set, then we need to check it against @@ -153,20 +142,19 @@ UsdMaya_ModelKindProcessor::_AuthorRootPrimKinds( // If no existing kind, author based on rootKind job arg. kind = _args.rootKind; usdRootModel.SetKind(kind); - } - else if (!KindRegistry::IsA(kind, _args.rootKind)) { + } else if (!KindRegistry::IsA(kind, _args.rootKind)) { // If existing kind is not derived from rootKind, then error. TF_RUNTIME_ERROR( - "<%s> has kind '%s' but the export root kind option " - "is set to '%s'; expected that or a derived kind", - primPath.GetText(), - kind.GetText(), - _args.rootKind.GetText()); + "<%s> has kind '%s' but the export root kind option " + "is set to '%s'; expected that or a derived kind", + primPath.GetText(), + kind.GetText(), + _args.rootKind.GetText()); return false; } } - bool hasExportedGprims = false; + bool hasExportedGprims = false; const auto pathIter = _pathsWithExportedGprims.find(primPath); if (pathIter != _pathsWithExportedGprims.end()) { hasExportedGprims = true; @@ -174,56 +162,52 @@ UsdMaya_ModelKindProcessor::_AuthorRootPrimKinds( if (kind.IsEmpty()) { // Author kind based on hasExportedGprims. - kind = hasExportedGprims ? - KindTokens->component : KindTokens->assembly; + kind = hasExportedGprims ? KindTokens->component : KindTokens->assembly; usdRootModel.SetKind(kind); } else { // Verify kind based on hasExportedGprims. - if (hasExportedGprims && - KindRegistry::IsA(kind, KindTokens->assembly)) { + if (hasExportedGprims && KindRegistry::IsA(kind, KindTokens->assembly)) { MString errorMsg = primPath.GetText(); errorMsg += " has kind '"; errorMsg += kind.GetText(); errorMsg += "' and cannot have a mesh below. Please remove:"; std::vector pathStrings; - const auto exportedGprimsIter = - _pathsToExportedGprimsMap.find(primPath); + const auto exportedGprimsIter = _pathsToExportedGprimsMap.find(primPath); if (exportedGprimsIter != _pathsToExportedGprimsMap.end()) { std::vector& paths = exportedGprimsIter->second; std::transform( - paths.begin(), paths.end(), - std::back_inserter(pathStrings), - [](const SdfPath& p) { return p.GetString(); }); + paths.begin(), + paths.end(), + std::back_inserter(pathStrings), + [](const SdfPath& p) { return p.GetString(); }); } TF_RUNTIME_ERROR( - "<%s> has kind '%s', which is derived from 'assembly'. " - "Assemblies should not directly contain meshes/gprims. " - "Please remove %zu prim%s: %s", - primPath.GetText(), - kind.GetText(), - pathStrings.size(), - pathStrings.size() == 1 ? "" : "s", - TfStringJoin(pathStrings, "; ").c_str()); + "<%s> has kind '%s', which is derived from 'assembly'. " + "Assemblies should not directly contain meshes/gprims. " + "Please remove %zu prim%s: %s", + primPath.GetText(), + kind.GetText(), + pathStrings.size(), + pathStrings.size() == 1 ? "" : "s", + TfStringJoin(pathStrings, "; ").c_str()); return false; } } - rootPrimIsComponent[primPath] = - KindRegistry::IsA(kind, KindTokens->component); + rootPrimIsComponent[primPath] = KindRegistry::IsA(kind, KindTokens->component); } return true; } -bool -UsdMaya_ModelKindProcessor::_FixUpPrimKinds( - UsdStageRefPtr& stage, +bool UsdMaya_ModelKindProcessor::_FixUpPrimKinds( + UsdStageRefPtr& stage, const _PathBoolMap& rootPrimIsComponent) { std::unordered_set pathsToBeGroup; - for (SdfPath const &path : _pathsThatMayHaveKind) { + for (SdfPath const& path : _pathsThatMayHaveKind) { // The kind of the root prim under which each reference was authored // informs how we will fix-up/fill-in kind on it and its ancestors. UsdPrim prim = stage->GetPrimAtPath(path); @@ -232,13 +216,13 @@ UsdMaya_ModelKindProcessor::_FixUpPrimKinds( } UsdModelAPI usdModel(prim); - TfToken kind; - + TfToken kind; + // Nothing to fix if there's no resolved kind. if (!usdModel.GetKind(&kind) || kind.IsEmpty()) { continue; } - + SdfPathVector ancestorPaths; path.GetParentPath().GetPrefixes(&ancestorPaths); if (ancestorPaths.empty()) { @@ -258,17 +242,16 @@ UsdMaya_ModelKindProcessor::_FixUpPrimKinds( if (!ancestorPrim) continue; UsdModelAPI ancestorModel(ancestorPrim); - TfToken kind; - - if (!ancestorModel.GetKind(&kind) || - !KindRegistry::IsA(kind, KindTokens->group)) { + TfToken kind; + + if (!ancestorModel.GetKind(&kind) || !KindRegistry::IsA(kind, KindTokens->group)) { pathsToBeGroup.insert(ancestorPaths[i]); } } } } - { + { // We drop down to Sdf to do the kind-authoring, because authoring // kind induces recomposition since we cache model-hierarchy. Using // Sdf api, we can bundle the changes into a change block, and do all @@ -276,22 +259,20 @@ UsdMaya_ModelKindProcessor::_FixUpPrimKinds( SdfLayerHandle layer = stage->GetEditTarget().GetLayer(); SdfChangeBlock block; - for (SdfPath const &path : pathsToBeGroup) { + for (SdfPath const& path : pathsToBeGroup) { SdfPrimSpecHandle primSpec = SdfCreatePrimInLayer(layer, path); if (!primSpec) { TF_RUNTIME_ERROR( - "Failed to create prim spec for setting kind at path " - "<%s>", - path.GetText()); - } - else { + "Failed to create prim spec for setting kind at path " + "<%s>", + path.GetText()); + } else { primSpec->SetKind(KindTokens->group); } - } + } } return true; } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/jobs/modelKindProcessor.h b/lib/mayaUsd/fileio/jobs/modelKindProcessor.h index d320653902..df63f3d0b7 100644 --- a/lib/mayaUsd/fileio/jobs/modelKindProcessor.h +++ b/lib/mayaUsd/fileio/jobs/modelKindProcessor.h @@ -16,16 +16,16 @@ #ifndef PXRUSDMAYA_MODEL_KIND_PROCESSOR_H #define PXRUSDMAYA_MODEL_KIND_PROCESSOR_H -#include -#include -#include +#include +#include #include #include #include -#include -#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -43,9 +43,7 @@ class UsdMaya_ModelKindProcessor /// prim writer. /// Note: this assumes DFS traversal, i.e. parent prims should be traversed /// before child prims. - void OnWritePrim( - const UsdPrim& prim, - const UsdMayaPrimWriterSharedPtr& primWriter); + void OnWritePrim(const UsdPrim& prim, const UsdMayaPrimWriterSharedPtr& primWriter); /// Writes model hierarchy for the given stage based on the information /// collected by OnWritePrim. @@ -57,10 +55,9 @@ class UsdMaya_ModelKindProcessor bool MakeModelHierarchy(UsdStageRefPtr& stage); private: - typedef std::unordered_map, SdfPath::Hash> - _PathVectorMap; - typedef std::unordered_map _PathBoolMap; - typedef std::unordered_set _PathSet; + typedef std::unordered_map, SdfPath::Hash> _PathVectorMap; + typedef std::unordered_map _PathBoolMap; + typedef std::unordered_set _PathSet; UsdMayaJobExportArgs _args; @@ -80,16 +77,11 @@ class UsdMaya_ModelKindProcessor // Set of all root paths that contain exported gprims. _PathSet _pathsWithExportedGprims; - bool _AuthorRootPrimKinds( - UsdStageRefPtr& stage, - _PathBoolMap& rootPrimIsComponent); + bool _AuthorRootPrimKinds(UsdStageRefPtr& stage, _PathBoolMap& rootPrimIsComponent); - bool _FixUpPrimKinds( - UsdStageRefPtr& stage, - const _PathBoolMap& rootPrimIsComponent); + bool _FixUpPrimKinds(UsdStageRefPtr& stage, const _PathBoolMap& rootPrimIsComponent); }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/jobs/readJob.cpp b/lib/mayaUsd/fileio/jobs/readJob.cpp index 29d8ed0dfb..e0b63baeb1 100644 --- a/lib/mayaUsd/fileio/jobs/readJob.cpp +++ b/lib/mayaUsd/fileio/jobs/readJob.cpp @@ -15,21 +15,12 @@ // #include "readJob.h" -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include #include @@ -47,33 +38,38 @@ #include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE UsdMaya_ReadJob::UsdMaya_ReadJob( - const MayaUsd::ImportData &iImportData, - const UsdMayaJobImportArgs &iArgs) : - mArgs(iArgs), - mImportData(iImportData), - mMayaRootDagPath(), - mDagModifierUndo(), - mDagModifierSeeded(false) + const MayaUsd::ImportData& iImportData, + const UsdMayaJobImportArgs& iArgs) + : mArgs(iArgs) + , mImportData(iImportData) + , mMayaRootDagPath() + , mDagModifierUndo() + , mDagModifierSeeded(false) { } -UsdMaya_ReadJob::~UsdMaya_ReadJob() -{ -} +UsdMaya_ReadJob::~UsdMaya_ReadJob() { } -bool -UsdMaya_ReadJob::Read(std::vector* addedDagPaths) +bool UsdMaya_ReadJob::Read(std::vector* addedDagPaths) { MStatus status; @@ -89,32 +85,30 @@ UsdMaya_ReadJob::Read(std::vector* addedDagPaths) TfToken modelName = UsdUtilsGetModelNameFromRootLayer(rootLayer); SdfVariantSelectionMap varSelsMap = mImportData.rootVariantSelections(); - std::vector > varSelsVec; - TF_FOR_ALL(iter, varSelsMap) { + std::vector> varSelsVec; + TF_FOR_ALL(iter, varSelsMap) + { const std::string& variantSetName = iter->first; const std::string& variantSelectionName = iter->second; - varSelsVec.push_back( - std::make_pair(variantSetName, variantSelectionName)); + varSelsVec.push_back(std::make_pair(variantSetName, variantSelectionName)); } - SdfLayerRefPtr sessionLayer = - UsdUtilsStageCache::GetSessionLayerForVariantSelections(modelName, - varSelsVec); + SdfLayerRefPtr sessionLayer + = UsdUtilsStageCache::GetSessionLayerForVariantSelections(modelName, varSelsVec); // Layer and Stage used to Read in the USD file UsdStageRefPtr stage; - if (mImportData.hasPopulationMask()) - { + if (mImportData.hasPopulationMask()) { // OpenMasked doesn't use the UsdStageCache, so don't create a UsdStageCacheContext - stage = UsdStage::OpenMasked(rootLayer, sessionLayer, - mImportData.stagePopulationMask(), - mImportData.stageInitialLoadSet()); - } - else - { - UsdStageCacheContext stageCacheContext(UsdMayaStageCache::Get(mImportData.stageInitialLoadSet() == UsdStage::InitialLoadSet::LoadAll)); - stage = UsdStage::Open(rootLayer, sessionLayer, - mImportData.stageInitialLoadSet()); + stage = UsdStage::OpenMasked( + rootLayer, + sessionLayer, + mImportData.stagePopulationMask(), + mImportData.stageInitialLoadSet()); + } else { + UsdStageCacheContext stageCacheContext(UsdMayaStageCache::Get( + mImportData.stageInitialLoadSet() == UsdStage::InitialLoadSet::LoadAll)); + stage = UsdStage::Open(rootLayer, sessionLayer, mImportData.stageInitialLoadSet()); } if (!stage) { return false; @@ -122,19 +116,18 @@ UsdMaya_ReadJob::Read(std::vector* addedDagPaths) stage->SetEditTarget(stage->GetSessionLayer()); - // XXX Currently all distance values are set directly from USD and will be + // XXX Currently all distance values are set directly from USD and will be // interpreted as centimeters (Maya's internal distance unit). Future work // could include converting distance values based on the specified meters- - // per-unit in the USD stage metadata. For now, simply warn. + // per-unit in the USD stage metadata. For now, simply warn. if (UsdGeomStageHasAuthoredMetersPerUnit(stage)) { - MDistance::Unit mdistanceUnit = - UsdMayaUtil::ConvertUsdGeomLinearUnitToMDistanceUnit( - UsdGeomGetStageMetersPerUnit(stage)); + MDistance::Unit mdistanceUnit = UsdMayaUtil::ConvertUsdGeomLinearUnitToMDistanceUnit( + UsdGeomGetStageMetersPerUnit(stage)); if (mdistanceUnit != MDistance::internalUnit()) { TF_WARN("Distance unit conversion is not yet supported. " - "All distance values will be imported in Maya's internal " - "distance unit."); + "All distance values will be imported in Maya's internal " + "distance unit."); } } @@ -148,9 +141,9 @@ UsdMaya_ReadJob::Read(std::vector* addedDagPaths) if (mArgs.timeInterval.IsFinite()) { if (mArgs.timeInterval.GetMin() > mArgs.timeInterval.GetMax()) { TF_RUNTIME_ERROR( - "Frame range start (%f) was greater than end (%f)", - mArgs.timeInterval.GetMin(), - mArgs.timeInterval.GetMax()); + "Frame range start (%f) was greater than end (%f)", + mArgs.timeInterval.GetMin(), + mArgs.timeInterval.GetMax()); return false; } stageInterval = mArgs.timeInterval; @@ -169,39 +162,34 @@ UsdMaya_ReadJob::Read(std::vector* addedDagPaths) // Use the primPath to get the root usdNode std::string primPath = mImportData.rootPrimPath(); - UsdPrim usdRootPrim = primPath.empty() ? stage->GetDefaultPrim() : - stage->GetPrimAtPath(SdfPath(primPath)); + UsdPrim usdRootPrim + = primPath.empty() ? stage->GetDefaultPrim() : stage->GetPrimAtPath(SdfPath(primPath)); if (!usdRootPrim && !(primPath.empty() || primPath == "/")) { TF_RUNTIME_ERROR( - "Unable to set root prim to <%s> when reading USD file '%s'; " - "using the pseudo-root instead", - primPath.c_str(), mImportData.filename().c_str()); + "Unable to set root prim to <%s> when reading USD file '%s'; " + "using the pseudo-root instead", + primPath.c_str(), + mImportData.filename().c_str()); usdRootPrim = stage->GetPseudoRoot(); } bool isImportingPseudoRoot = (usdRootPrim == stage->GetPseudoRoot()); if (!usdRootPrim) { - TF_RUNTIME_ERROR( - "No default prim found in USD file '%s'", - mImportData.filename().c_str()); + TF_RUNTIME_ERROR("No default prim found in USD file '%s'", mImportData.filename().c_str()); return false; } // Set the variants on the usdRootPrim for (auto& variant : mImportData.rootVariantSelections()) { - usdRootPrim - .GetVariantSet(variant.first) - .SetVariantSelection(variant.second); + usdRootPrim.GetVariantSet(variant.first).SetVariantSelection(variant.second); } // Set the variants on all the import data prims. for (auto& varPrim : mImportData.primVariantSelections()) { - for(auto& variant : varPrim.second) { + for (auto& variant : varPrim.second) { UsdPrim usdVarPrim = stage->GetPrimAtPath(varPrim.first); - usdVarPrim - .GetVariantSet(variant.first) - .SetVariantSelection(variant.second); + usdVarPrim.GetVariantSet(variant.first).SetVariantSelection(variant.second); } } @@ -232,29 +220,24 @@ UsdMaya_ReadJob::Read(std::vector* addedDagPaths) rootPathToRegister = rootPathToRegister.GetParentPath(); } - mNewNodeRegistry.insert(std::make_pair( - rootPathToRegister.GetString(), - mMayaRootDagPath.node())); + mNewNodeRegistry.insert( + std::make_pair(rootPathToRegister.GetString(), mMayaRootDagPath.node())); if (mArgs.useAsAnimationCache) { MDGModifier dgMod; - MObject usdStageNode = dgMod.createNode(UsdMayaStageNode::typeId, - &status); + MObject usdStageNode = dgMod.createNode(UsdMayaStageNode::typeId, &status); CHECK_MSTATUS_AND_RETURN(status, false); // We only ever create a single stage node per usdImport, so we can // simply register it and later look it up in the registry using its // type name. mNewNodeRegistry.insert( - std::make_pair(UsdMayaStageNodeTokens->MayaTypeName.GetString(), - usdStageNode)); + std::make_pair(UsdMayaStageNodeTokens->MayaTypeName.GetString(), usdStageNode)); MFnDependencyNode depNodeFn(usdStageNode, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug filePathPlug = depNodeFn.findPlug(UsdMayaStageNode::filePathAttr, - true, - &status); + MPlug filePathPlug = depNodeFn.findPlug(UsdMayaStageNode::filePathAttr, true, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = dgMod.newPlugValueString(filePathPlug, mImportData.filename().c_str()); @@ -269,16 +252,18 @@ UsdMaya_ReadJob::Read(std::vector* addedDagPaths) SdfPathSet topImportedPaths; if (isImportingPseudoRoot) { // get all the dag paths for the root prims - TF_FOR_ALL(childIter, stage->GetPseudoRoot().GetChildren()) { + TF_FOR_ALL(childIter, stage->GetPseudoRoot().GetChildren()) + { topImportedPaths.insert(childIter->GetPath()); } } else { topImportedPaths.insert(usdRootPrim.GetPath()); } - TF_FOR_ALL(pathsIter, topImportedPaths) { + TF_FOR_ALL(pathsIter, topImportedPaths) + { std::string key = pathsIter->GetString(); - MObject obj; + MObject obj; if (TfMapLookup(mNewNodeRegistry, key, &obj)) { if (obj.hasFn(MFn::kDagNode)) { addedDagPaths->push_back(MDagPath::getAPathTo(obj)); @@ -289,8 +274,7 @@ UsdMaya_ReadJob::Read(std::vector* addedDagPaths) return (status == MS::kSuccess); } -bool -UsdMaya_ReadJob::DoImport(UsdPrimRange& rootRange, const UsdPrim& usdRootPrim) +bool UsdMaya_ReadJob::DoImport(UsdPrimRange& rootRange, const UsdPrim& usdRootPrim) { return _DoImport(rootRange, usdRootPrim); } @@ -300,18 +284,16 @@ bool UsdMaya_ReadJob::OverridePrimReader( const UsdPrim& prim, const UsdMayaPrimReaderArgs& args, UsdMayaPrimReaderContext& readCtx, - UsdPrimRange::iterator& primIt -) + UsdPrimRange::iterator& primIt) { return false; } void UsdMaya_ReadJob::_DoImportPrimIt( - UsdPrimRange::iterator& primIt, - const UsdPrim& usdRootPrim, + UsdPrimRange::iterator& primIt, + const UsdPrim& usdRootPrim, UsdMayaPrimReaderContext& readCtx, - _PrimReaderMap& primReaderMap -) + _PrimReaderMap& primReaderMap) { const UsdPrim& prim = *primIt; // The iterator will hit each prim twice. IsPostVisit tells us if @@ -333,7 +315,7 @@ void UsdMaya_ReadJob::_DoImportPrimIt( TfToken typeName = prim.GetTypeName(); if (UsdMayaPrimReaderRegistry::ReaderFactoryFn factoryFn - = UsdMayaPrimReaderRegistry::FindOrFallback(typeName)) { + = UsdMayaPrimReaderRegistry::FindOrFallback(typeName)) { UsdMayaPrimReaderSharedPtr primReader = factoryFn(args); if (primReader) { primReader->Read(&readCtx); @@ -417,8 +399,7 @@ void UsdMaya_ReadJob::_ImportMaster( } } -bool -UsdMaya_ReadJob::_DoImport(UsdPrimRange& rootRange, const UsdPrim& usdRootPrim) +bool UsdMaya_ReadJob::_DoImport(UsdPrimRange& rootRange, const UsdPrim& usdRootPrim) { const bool buildInstances = mArgs.importInstances; @@ -429,13 +410,13 @@ UsdMaya_ReadJob::_DoImport(UsdPrimRange& rootRange, const UsdPrim& usdRootPrim) const UsdPrim& rootPrim = *rootIt; rootIt.PruneChildren(); - _PrimReaderMap primReaderMap; + _PrimReaderMap primReaderMap; const UsdPrimRange range = buildInstances ? UsdPrimRange::PreAndPostVisit(rootPrim) : UsdPrimRange::PreAndPostVisit( rootPrim, UsdTraverseInstanceProxies(UsdPrimAllPrimsPredicate)); for (auto primIt = range.begin(); primIt != range.end(); ++primIt) { - const UsdPrim& prim = *primIt; + const UsdPrim& prim = *primIt; UsdMayaPrimReaderContext readCtx(&mNewNodeRegistry); if (buildInstances && prim.IsInstance()) { @@ -469,16 +450,11 @@ UsdMaya_ReadJob::_DoImport(UsdPrimRange& rootRange, const UsdPrim& usdRootPrim) return true; } -void UsdMaya_ReadJob::PreImport(Usd_PrimFlagsPredicate& returnPredicate) -{} +void UsdMaya_ReadJob::PreImport(Usd_PrimFlagsPredicate& returnPredicate) { } -bool UsdMaya_ReadJob::SkipRootPrim(bool isImportingPseudoRoot) -{ - return isImportingPseudoRoot; -} +bool UsdMaya_ReadJob::SkipRootPrim(bool isImportingPseudoRoot) { return isImportingPseudoRoot; } -bool -UsdMaya_ReadJob::Redo() +bool UsdMaya_ReadJob::Redo() { // Undo the undo MStatus status = mDagModifierUndo.undoIt(); @@ -486,24 +462,23 @@ UsdMaya_ReadJob::Redo() return (status == MS::kSuccess); } -bool -UsdMaya_ReadJob::Undo() +bool UsdMaya_ReadJob::Undo() { if (!mDagModifierSeeded) { mDagModifierSeeded = true; MStatus dagStatus; // Construct list of top level DAG nodes to delete and any DG nodes for (auto& it : mNewNodeRegistry) { - if (it.second != mMayaRootDagPath.node() ) { // if not the parent root node + if (it.second != mMayaRootDagPath.node()) { // if not the parent root node MFnDagNode dagFn(it.second, &dagStatus); if (dagStatus == MS::kSuccess) { if (mMayaRootDagPath.node() != MObject::kNullObj) { - if (!dagFn.hasParent(mMayaRootDagPath.node() )) { // skip if a DAG Node, but not under the root + if (!dagFn.hasParent(mMayaRootDagPath.node())) { // skip if a DAG Node, but + // not under the root continue; } - } - else { - if (dagFn.parentCount() == 0) { // under scene root + } else { + if (dagFn.parentCount() == 0) { // under scene root continue; } } @@ -518,16 +493,11 @@ UsdMaya_ReadJob::Undo() return (status == MS::kSuccess); } -void -UsdMaya_ReadJob::SetMayaRootDagPath(const MDagPath &mayaRootDagPath) +void UsdMaya_ReadJob::SetMayaRootDagPath(const MDagPath& mayaRootDagPath) { mMayaRootDagPath = mayaRootDagPath; } -const MDagPath& -UsdMaya_ReadJob::GetMayaRootDagPath() const -{ - return mMayaRootDagPath; -} +const MDagPath& UsdMaya_ReadJob::GetMayaRootDagPath() const { return mMayaRootDagPath; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/jobs/readJob.h b/lib/mayaUsd/fileio/jobs/readJob.h index 408a0a79b8..effa634381 100644 --- a/lib/mayaUsd/fileio/jobs/readJob.h +++ b/lib/mayaUsd/fileio/jobs/readJob.h @@ -16,21 +16,21 @@ #ifndef PXRUSDMAYA_READ_JOB_H #define PXRUSDMAYA_READ_JOB_H -#include -#include -#include - -#include -#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include +#include +#include + +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -40,9 +40,7 @@ class UsdMaya_ReadJob { public: MAYAUSD_CORE_PUBLIC - UsdMaya_ReadJob( - const MayaUsd::ImportData& iImportData, - const UsdMayaJobImportArgs & iArgs); + UsdMaya_ReadJob(const MayaUsd::ImportData& iImportData, const UsdMayaJobImportArgs& iArgs); MAYAUSD_CORE_PUBLIC virtual ~UsdMaya_ReadJob(); @@ -63,14 +61,13 @@ class UsdMaya_ReadJob // Getters/Setters MAYAUSD_CORE_PUBLIC - void SetMayaRootDagPath(const MDagPath &mayaRootDagPath); + void SetMayaRootDagPath(const MDagPath& mayaRootDagPath); MAYAUSD_CORE_PUBLIC const MDagPath& GetMayaRootDagPath() const; protected: // Types - using _PrimReaderMap = - std::unordered_map; + using _PrimReaderMap = std::unordered_map; MAYAUSD_CORE_PUBLIC virtual bool DoImport(UsdPrimRange& range, const UsdPrim& usdRootPrim); @@ -84,8 +81,7 @@ class UsdMaya_ReadJob const UsdPrim& prim, const UsdMayaPrimReaderArgs& args, UsdMayaPrimReaderContext& readCtx, - UsdPrimRange::iterator& primIt - ); + UsdPrimRange::iterator& primIt); // Engine method for DoImport(). Covers the functionality of a regular // usdImport. @@ -103,10 +99,10 @@ class UsdMaya_ReadJob virtual bool SkipRootPrim(bool isImportingPseudoRoot); // Data - UsdMayaJobImportArgs mArgs; - const MayaUsd::ImportData& mImportData; + UsdMayaJobImportArgs mArgs; + const MayaUsd::ImportData& mImportData; UsdMayaPrimReaderContext::ObjectRegistry mNewNodeRegistry; - MDagPath mMayaRootDagPath; + MDagPath mMayaRootDagPath; private: void _DoImportPrimIt( @@ -128,11 +124,9 @@ class UsdMaya_ReadJob // Data MDagModifier mDagModifierUndo; - bool mDagModifierSeeded; + bool mDagModifierSeeded; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/jobs/writeJob.cpp b/lib/mayaUsd/fileio/jobs/writeJob.cpp index 22911e8848..e6f415aad9 100644 --- a/lib/mayaUsd/fileio/jobs/writeJob.cpp +++ b/lib/mayaUsd/fileio/jobs/writeJob.cpp @@ -15,9 +15,17 @@ // #include "writeJob.h" -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -31,32 +39,12 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include // Needed for directly removing a UsdVariant via Sdf // Remove when UsdVariantSet::RemoveVariant() is exposed // XXX [bug 75864] -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - #include #include #include @@ -68,41 +56,46 @@ #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE UsdMaya_WriteJob::UsdMaya_WriteJob(const UsdMayaJobExportArgs& iArgs) - : mJobCtx(iArgs), - _modelKindProcessor(new UsdMaya_ModelKindProcessor(iArgs)) + : mJobCtx(iArgs) + , _modelKindProcessor(new UsdMaya_ModelKindProcessor(iArgs)) { } -UsdMaya_WriteJob::~UsdMaya_WriteJob() -{ -} +UsdMaya_WriteJob::~UsdMaya_WriteJob() { } /// Generates a name for a temporary usdc file in \p dir. /// Unless you are very, very unlucky, the stage name is unique because it's /// generated from a UUID. -static -std::string -_MakeTmpStageName(const std::string& dir) +static std::string _MakeTmpStageName(const std::string& dir) { MUuid uuid; uuid.generate(); - const std::string fileName = - TfStringPrintf( - "tmp-%s.%s", - uuid.asString().asChar(), - UsdMayaTranslatorTokens->UsdFileExtensionCrate.GetText()); + const std::string fileName = TfStringPrintf( + "tmp-%s.%s", + uuid.asString().asChar(), + UsdMayaTranslatorTokens->UsdFileExtensionCrate.GetText()); return TfStringCatPaths(dir, fileName); } /// Chooses the fallback extension based on the compatibility profile, e.g. /// ARKit-compatible files should be usdz's by default. -static -TfToken -_GetFallbackExtension(const TfToken& compatibilityMode) +static TfToken _GetFallbackExtension(const TfToken& compatibilityMode) { if (compatibilityMode == UsdMayaJobExportArgsTokens->appleArKit) { return UsdMayaTranslatorTokens->UsdFileExtensionPackage; @@ -110,8 +103,7 @@ _GetFallbackExtension(const TfToken& compatibilityMode) return UsdMayaTranslatorTokens->UsdFileExtensionDefault; } -bool -UsdMaya_WriteJob::Write(const std::string& fileName, bool append) +bool UsdMaya_WriteJob::Write(const std::string& fileName, bool append) { const std::vector& timeSamples = mJobCtx.mArgs.timeSamples; @@ -119,8 +111,7 @@ UsdMaya_WriteJob::Write(const std::string& fileName, bool append) if (timeSamples.empty()) { // Non-animated export doesn't show progress. computation.beginComputation(/*showProgressBar*/ false); - } - else { + } else { // Animated export shows frame-by-frame progress. computation.beginComputation(/*showProgressBar*/ true); computation.setProgressRange(0, timeSamples.size()); @@ -172,45 +163,41 @@ UsdMaya_WriteJob::Write(const std::string& fileName, bool append) return true; } -bool -UsdMaya_WriteJob::_BeginWriting(const std::string& fileName, bool append) +bool UsdMaya_WriteJob::_BeginWriting(const std::string& fileName, bool append) { // Check for DAG nodes that are a child of an already specified DAG node to export // if that's the case, report the issue and skip the export UsdMayaUtil::MDagPathSet::const_iterator m, n; UsdMayaUtil::MDagPathSet::const_iterator endPath = mJobCtx.mArgs.dagPaths.end(); - for (m = mJobCtx.mArgs.dagPaths.begin(); m != endPath; ) { - MDagPath path1 = *m; m++; + for (m = mJobCtx.mArgs.dagPaths.begin(); m != endPath;) { + MDagPath path1 = *m; + m++; for (n = m; n != endPath; n++) { MDagPath path2 = *n; - if (UsdMayaUtil::isAncestorDescendentRelationship(path1,path2)) { + if (UsdMayaUtil::isAncestorDescendentRelationship(path1, path2)) { TF_RUNTIME_ERROR( - "%s and %s are ancestors or descendants of each other. " - "Please specify export DAG paths that don't overlap. " - "Exiting.", - path1.fullPathName().asChar(), - path2.fullPathName().asChar()); + "%s and %s are ancestors or descendants of each other. " + "Please specify export DAG paths that don't overlap. " + "Exiting.", + path1.fullPathName().asChar(), + path2.fullPathName().asChar()); return false; } - } // for n - } // for m + } // for n + } // for m // Make sure the file name is a valid one with a proper USD extension. - TfToken fileExt(TfGetExtension(fileName)); + TfToken fileExt(TfGetExtension(fileName)); std::string fileNameWithExt; - if (!(SdfLayer::IsAnonymousLayerIdentifier(fileName) || - fileExt == UsdMayaTranslatorTokens->UsdFileExtensionDefault || - fileExt == UsdMayaTranslatorTokens->UsdFileExtensionASCII || - fileExt == UsdMayaTranslatorTokens->UsdFileExtensionCrate || - fileExt == UsdMayaTranslatorTokens->UsdFileExtensionPackage)) { + if (!(SdfLayer::IsAnonymousLayerIdentifier(fileName) + || fileExt == UsdMayaTranslatorTokens->UsdFileExtensionDefault + || fileExt == UsdMayaTranslatorTokens->UsdFileExtensionASCII + || fileExt == UsdMayaTranslatorTokens->UsdFileExtensionCrate + || fileExt == UsdMayaTranslatorTokens->UsdFileExtensionPackage)) { // No extension; get fallback extension based on compatibility profile. fileExt = _GetFallbackExtension(mJobCtx.mArgs.compatibility); - fileNameWithExt = TfStringPrintf( - "%s.%s", - fileName.c_str(), - fileExt.GetText()); - } - else { + fileNameWithExt = TfStringPrintf("%s.%s", fileName.c_str(), fileExt.GetText()); + } else { // Has correct extension; use as-is. fileNameWithExt = fileName; } @@ -229,22 +216,19 @@ UsdMaya_WriteJob::_BeginWriting(const std::string& fileName, bool append) if (TfPathExists(_fileName)) { // This shouldn't happen (since we made the temp stage name from // a UUID). Don't try to recover. - TF_RUNTIME_ERROR( - "Temporary stage '%s' already exists", _fileName.c_str()); + TF_RUNTIME_ERROR("Temporary stage '%s' already exists", _fileName.c_str()); return false; } // The packaged file gets written to fileNameWithExt. _packageName = fileNameWithExt; - } - else { + } else { _fileName = fileNameWithExt; _packageName = std::string(); } TF_STATUS("Opening layer '%s' for writing", _fileName.c_str()); - if (mJobCtx.mArgs.renderLayerMode == - UsdMayaJobExportArgsTokens->modelingVariant) { + if (mJobCtx.mArgs.renderLayerMode == UsdMayaJobExportArgsTokens->modelingVariant) { // Handle usdModelRootOverridePath for USD Variants MFnRenderLayer::listAllRenderLayers(mRenderLayerObjs); if (mRenderLayerObjs.length() > 1) { @@ -279,14 +263,14 @@ UsdMaya_WriteJob::_BeginWriting(const std::string& fileName, bool append) // Switch to the default render layer unless the renderLayerMode is // 'currentLayer', or the default layer is already the current layer. - if ((mJobCtx.mArgs.renderLayerMode != - UsdMayaJobExportArgsTokens->currentLayer) && - (MFnRenderLayer::currentLayer() != - MFnRenderLayer::defaultRenderLayer())) { + if ((mJobCtx.mArgs.renderLayerMode != UsdMayaJobExportArgsTokens->currentLayer) + && (MFnRenderLayer::currentLayer() != MFnRenderLayer::defaultRenderLayer())) { // Set the RenderLayer to the default render layer MFnRenderLayer defaultLayer(MFnRenderLayer::defaultRenderLayer()); - MGlobal::executeCommand(MString("editRenderLayerGlobals -currentRenderLayer ")+ - defaultLayer.name(), false, false); + MGlobal::executeCommand( + MString("editRenderLayerGlobals -currentRenderLayer ") + defaultLayer.name(), + false, + false); } // Pre-process the argument dagPath path names into two sets. One set @@ -294,14 +278,14 @@ UsdMaya_WriteJob::_BeginWriting(const std::string& fileName, bool append) // arg dagPaths all the way up to the world root. Partial path names are // enough because Maya guarantees them to still be unique, and they require // less work to hash and compare than full path names. - TfHashSet argDagPaths; - TfHashSet argDagPathParents; + TfHashSet argDagPaths; + TfHashSet argDagPathParents; UsdMayaUtil::MDagPathSet::const_iterator end = mJobCtx.mArgs.dagPaths.end(); - for (UsdMayaUtil::MDagPathSet::const_iterator it = mJobCtx.mArgs.dagPaths.begin(); - it != end; ++it) { + for (UsdMayaUtil::MDagPathSet::const_iterator it = mJobCtx.mArgs.dagPaths.begin(); it != end; + ++it) { MDagPath curDagPath = *it; - MStatus status; - bool curDagPathIsValid = curDagPath.isValid(&status); + MStatus status; + bool curDagPathIsValid = curDagPath.isValid(&status); if (status != MS::kSuccess || !curDagPathIsValid) { continue; } @@ -362,12 +346,11 @@ UsdMaya_WriteJob::_BeginWriting(const std::string& fileName, bool append) continue; } - if (!mJobCtx._NeedToTraverse(curDagPath) && - curDagPath.length() > 0) { + if (!mJobCtx._NeedToTraverse(curDagPath) && curDagPath.length() > 0) { // This dagPath and all of its children should be pruned. itDag.prune(); } else { - const MFnDagNode dagNodeFn(curDagPath); + const MFnDagNode dagNodeFn(curDagPath); UsdMayaPrimWriterSharedPtr primWriter = mJobCtx.CreatePrimWriter(dagNodeFn); if (primWriter) { @@ -375,16 +358,14 @@ UsdMaya_WriteJob::_BeginWriting(const std::string& fileName, bool append) // Write out data (non-animated/default values). if (const auto& usdPrim = primWriter->GetUsdPrim()) { - if (!_CheckNameClashes( - usdPrim.GetPath(), primWriter->GetDagPath())) - { + if (!_CheckNameClashes(usdPrim.GetPath(), primWriter->GetDagPath())) { return false; } primWriter->Write(UsdTimeCode::Default()); - const UsdMayaUtil::MDagPathMap& mapping = - primWriter->GetDagToUsdPathMapping(); + const UsdMayaUtil::MDagPathMap& mapping + = primWriter->GetDagToUsdPathMapping(); mDagPathToUsdPathMap.insert(mapping.begin(), mapping.end()); _modelKindProcessor->OnWritePrim(usdPrim, primWriter); @@ -398,9 +379,7 @@ UsdMaya_WriteJob::_BeginWriting(const std::string& fileName, bool append) } // Writing Materials/Shading - UsdMayaTranslatorMaterial::ExportShadingEngines( - mJobCtx, - mDagPathToUsdPathMap); + UsdMayaTranslatorMaterial::ExportShadingEngines(mJobCtx, mDagPathToUsdPathMap); // Perform post-processing for instances, skel, etc. // We shouldn't be creating new instance masters after this point, and we @@ -417,11 +396,9 @@ UsdMaya_WriteJob::_BeginWriting(const std::string& fileName, bool append) mChasers.clear(); UsdMayaChaserRegistry::FactoryContext ctx(mJobCtx.mStage, mDagPathToUsdPathMap, mJobCtx.mArgs); for (const std::string& chaserName : mJobCtx.mArgs.chaserNames) { - if (UsdMayaChaserRefPtr fn = - UsdMayaChaserRegistry::GetInstance().Create(chaserName, ctx)) { + if (UsdMayaChaserRefPtr fn = UsdMayaChaserRegistry::GetInstance().Create(chaserName, ctx)) { mChasers.push_back(fn); - } - else { + } else { TF_RUNTIME_ERROR("Failed to create chaser: %s", chaserName.c_str()); } } @@ -435,13 +412,11 @@ UsdMaya_WriteJob::_BeginWriting(const std::string& fileName, bool append) return true; } -bool -UsdMaya_WriteJob::_WriteFrame(double iFrame) +bool UsdMaya_WriteJob::_WriteFrame(double iFrame) { const UsdTimeCode usdTime(iFrame); - for (const UsdMayaPrimWriterSharedPtr& primWriter : - mJobCtx.mMayaPrimWriterList) { + for (const UsdMayaPrimWriterSharedPtr& primWriter : mJobCtx.mMayaPrimWriterList) { const UsdPrim& usdPrim = primWriter->GetUsdPrim(); if (usdPrim) { primWriter->Write(usdTime); @@ -459,8 +434,7 @@ UsdMaya_WriteJob::_WriteFrame(double iFrame) return true; } -bool -UsdMaya_WriteJob::_FinishWriting() +bool UsdMaya_WriteJob::_FinishWriting() { UsdPrimSiblingRange usdRootPrims = mJobCtx.mStage->GetPseudoRoot().GetChildren(); @@ -473,24 +447,26 @@ UsdMaya_WriteJob::_FinishWriting() defaultPrim = usdRootPrim.GetName(); } - if (usdRootPrim && mRenderLayerObjs.length() > 1 && - !mJobCtx.mArgs.usdModelRootOverridePath.IsEmpty()) { - // Get RenderLayers - // mArgs.usdModelRootOverridePath: - // Require mArgs.usdModelRootOverridePath to be set so that - // the variants are put under a UsdPrim that references a BaseModel - // prim that has all of the geometry, transforms, and other details. - // This needs to be done since "local" values have stronger precedence - // than "variant" values, but "referencing" will cause the variant values - // to take precedence. + if (usdRootPrim && mRenderLayerObjs.length() > 1 + && !mJobCtx.mArgs.usdModelRootOverridePath.IsEmpty()) { + // Get RenderLayers + // mArgs.usdModelRootOverridePath: + // Require mArgs.usdModelRootOverridePath to be set so that + // the variants are put under a UsdPrim that references a BaseModel + // prim that has all of the geometry, transforms, and other details. + // This needs to be done since "local" values have stronger precedence + // than "variant" values, but "referencing" will cause the variant values + // to take precedence. defaultPrim = _WriteVariants(usdRootPrim); } // Restoring the currentRenderLayer MFnRenderLayer currentLayer(MFnRenderLayer::currentLayer()); if (currentLayer.name() != mCurrentRenderLayerName) { - MGlobal::executeCommand(MString("editRenderLayerGlobals -currentRenderLayer ")+ - mCurrentRenderLayerName, false, false); + MGlobal::executeCommand( + MString("editRenderLayerGlobals -currentRenderLayer ") + mCurrentRenderLayerName, + false, + false); } // Unfortunately, MGlobal::isZAxisUp() is merely session state that does @@ -498,33 +474,32 @@ UsdMaya_WriteJob::_FinishWriting() // properly. Since "Y" is the more common upAxis, we'll just use // isZAxisUp as an override to whatever our pipeline is configured for. TfToken upAxis = UsdGeomGetFallbackUpAxis(); - if (MGlobal::isZAxisUp()){ + if (MGlobal::isZAxisUp()) { upAxis = UsdGeomTokens->z; } UsdGeomSetStageUpAxis(mJobCtx.mStage, upAxis); // XXX Currently all distance values are written directly to USD, and will // be in centimeters (Maya's internal unit) despite what the users UIUnit - // preference is. Future work could include converting exported values to - // the UIUnit setting and writing that unit to metadata. + // preference is. Future work could include converting exported values to + // the UIUnit setting and writing that unit to metadata. MDistance::Unit mayaInternalUnit = MDistance::internalUnit(); if (mayaInternalUnit != MDistance::uiUnit()) { TF_WARN("Distance unit conversion is not yet supported. " - "All distance values will be exported in Maya's internal " - "distance unit."); + "All distance values will be exported in Maya's internal " + "distance unit."); } UsdGeomSetStageMetersPerUnit( - mJobCtx.mStage, - UsdMayaUtil::ConvertMDistanceUnitToUsdGeomLinearUnit(mayaInternalUnit)); + mJobCtx.mStage, UsdMayaUtil::ConvertMDistanceUnitToUsdGeomLinearUnit(mayaInternalUnit)); - if (usdRootPrim){ + if (usdRootPrim) { // We have already decided above that 'usdRootPrim' is the important // prim for the export... usdVariantRootPrimPath mJobCtx.mStage->GetRootLayer()->SetDefaultPrim(defaultPrim); } // Running post export function on all the prim writers. - for (auto& primWriter: mJobCtx.mMayaPrimWriterList) { + for (auto& primWriter : mJobCtx.mMayaPrimWriterList) { primWriter->PostExport(); } @@ -563,7 +538,7 @@ UsdMaya_WriteJob::_FinishWriting() return true; } -TfToken UsdMaya_WriteJob::_WriteVariants(const UsdPrim &usdRootPrim) +TfToken UsdMaya_WriteJob::_WriteVariants(const UsdPrim& usdRootPrim) { // Some notes about the expected structure that this function will create: @@ -612,12 +587,16 @@ TfToken UsdMaya_WriteJob::_WriteVariants(const UsdPrim &usdRootPrim) if (mJobCtx.mParentScopePath.IsEmpty()) { // Get the usdVariantRootPrimPath (optionally filter by renderLayer prefix) UsdMayaPrimWriterSharedPtr firstPrimWriterPtr = *mJobCtx.mMayaPrimWriterList.begin(); - std::string firstPrimWriterPathStr( firstPrimWriterPtr->GetDagPath().fullPathName().asChar() ); - std::replace( firstPrimWriterPathStr.begin(), firstPrimWriterPathStr.end(), '|', '/'); - std::replace( firstPrimWriterPathStr.begin(), firstPrimWriterPathStr.end(), ':', '_'); // replace namespace ":" with "_" + std::string firstPrimWriterPathStr( + firstPrimWriterPtr->GetDagPath().fullPathName().asChar()); + std::replace(firstPrimWriterPathStr.begin(), firstPrimWriterPathStr.end(), '|', '/'); + std::replace( + firstPrimWriterPathStr.begin(), + firstPrimWriterPathStr.end(), + ':', + '_'); // replace namespace ":" with "_" usdVariantRootPrimPath = SdfPath(firstPrimWriterPathStr).GetPrefixes()[0]; - } - else { + } else { // If they passed a parentScope, then use that for our new top-level // variant-switcher prim usdVariantRootPrimPath = mJobCtx.mParentScopePath; @@ -632,23 +611,23 @@ TfToken UsdMaya_WriteJob::_WriteVariants(const UsdPrim &usdRootPrim) usdRootPrim.SetActive(false); // Loop over all the renderLayers - for (unsigned int ir=0; ir < mRenderLayerObjs.length(); ++ir) { + for (unsigned int ir = 0; ir < mRenderLayerObjs.length(); ++ir) { SdfPathTable tableOfActivePaths; - MFnRenderLayer renderLayerFn( mRenderLayerObjs[ir] ); - MString renderLayerName = renderLayerFn.name(); - std::string variantName(renderLayerName.asChar()); + MFnRenderLayer renderLayerFn(mRenderLayerObjs[ir]); + MString renderLayerName = renderLayerFn.name(); + std::string variantName(renderLayerName.asChar()); // Determine default variant. Currently unsupported - //MPlug renderLayerDisplayOrderPlug = renderLayerFn.findPlug("displayOrder", true); - //int renderLayerDisplayOrder = renderLayerDisplayOrderPlug.asShort(); + // MPlug renderLayerDisplayOrderPlug = renderLayerFn.findPlug("displayOrder", true); + // int renderLayerDisplayOrder = renderLayerDisplayOrderPlug.asShort(); // The Maya default RenderLayer is also the default modeling variant if (mRenderLayerObjs[ir] == MFnRenderLayer::defaultRenderLayer()) { - defaultModelingVariant=variantName; + defaultModelingVariant = variantName; } // Make the renderlayer being looped the current one - MGlobal::executeCommand(MString("editRenderLayerGlobals -currentRenderLayer ")+ - renderLayerName, false, false); + MGlobal::executeCommand( + MString("editRenderLayerGlobals -currentRenderLayer ") + renderLayerName, false, false); // == ModelingVariants == // Identify prims to activate @@ -657,45 +636,49 @@ TfToken UsdMaya_WriteJob::_WriteVariants(const UsdPrim &usdRootPrim) // It has to be done this way since SetActive(false) disables access to all child prims. MObjectArray renderLayerMemberObjs; renderLayerFn.listMembers(renderLayerMemberObjs); - std::vector< SdfPath > activePaths; - for (unsigned int im=0; im < renderLayerMemberObjs.length(); ++im) { + std::vector activePaths; + for (unsigned int im = 0; im < renderLayerMemberObjs.length(); ++im) { MFnDagNode dagFn(renderLayerMemberObjs[im]); - MDagPath dagPath; + MDagPath dagPath; dagFn.getPath(dagPath); dagPath.extendToShape(); SdfPath usdPrimPath; if (!TfMapLookup(mDagPathToUsdPathMap, dagPath, &usdPrimPath)) { continue; } - usdPrimPath = usdPrimPath.ReplacePrefix(usdPrimPath.GetPrefixes()[0], usdVariantRootPrimPath); // Convert base to variant usdPrimPath + usdPrimPath = usdPrimPath.ReplacePrefix( + usdPrimPath.GetPrefixes()[0], + usdVariantRootPrimPath); // Convert base to variant usdPrimPath tableOfActivePaths[usdPrimPath] = true; activePaths.push_back(usdPrimPath); - //UsdPrim usdPrim = mStage->GetPrimAtPath(usdPrimPath); - //usdPrim.SetActive(true); + // UsdPrim usdPrim = mStage->GetPrimAtPath(usdPrimPath); + // usdPrim.SetActive(true); } if (!tableOfActivePaths.empty()) { { // == BEG: Scope for Variant EditContext // Create the variantSet and variant - UsdVariantSet modelingVariantSet = usdVariantRootPrim.GetVariantSets().AddVariantSet("modelingVariant"); + UsdVariantSet modelingVariantSet + = usdVariantRootPrim.GetVariantSets().AddVariantSet("modelingVariant"); modelingVariantSet.AddVariant(variantName); modelingVariantSet.SetVariantSelection(variantName); // Set the Edit Context - UsdEditTarget editTarget = modelingVariantSet.GetVariantEditTarget(); + UsdEditTarget editTarget = modelingVariantSet.GetVariantEditTarget(); UsdEditContext editContext(mJobCtx.mStage, editTarget); // == Activate/Deactivate UsdPrims - UsdPrimRange rng = UsdPrimRange::AllPrims(mJobCtx.mStage->GetPseudoRoot()); + UsdPrimRange rng = UsdPrimRange::AllPrims(mJobCtx.mStage->GetPseudoRoot()); std::vector primsToDeactivate; for (auto it = rng.begin(); it != rng.end(); ++it) { UsdPrim usdPrim = *it; // For all xformable usdPrims... if (usdPrim && usdPrim.IsA()) { - bool isActive=false; + bool isActive = false; for (const auto& activePath : activePaths) { - //primPathD.HasPrefix(primPathA); - if (usdPrim.GetPath().HasPrefix(activePath) || - activePath.HasPrefix(usdPrim.GetPath())) { - isActive=true; break; + // primPathD.HasPrefix(primPathA); + if (usdPrim.GetPath().HasPrefix(activePath) + || activePath.HasPrefix(usdPrim.GetPath())) { + isActive = true; + break; } } if (!isActive) { @@ -706,7 +689,7 @@ TfToken UsdMaya_WriteJob::_WriteVariants(const UsdPrim &usdRootPrim) } // Now deactivate the prims (done outside of the UsdPrimRange // so not to modify the iterator while in the loop) - for ( UsdPrim const& prim : primsToDeactivate ) { + for (UsdPrim const& prim : primsToDeactivate) { prim.SetActive(false); } } // == END: Scope for Variant EditContext @@ -721,19 +704,15 @@ TfToken UsdMaya_WriteJob::_WriteVariants(const UsdPrim &usdRootPrim) return defaultPrim; } -void -UsdMaya_WriteJob::_CreatePackage() const +void UsdMaya_WriteJob::_CreatePackage() const { // Since we're packaging a temporary stage file that has an // auto-generated name, create a nicer name for the root layer from // the package layer name specified by the user. // (Otherwise, the name inside the package will be a random string!) - const std::string firstLayerBaseName = - TfStringGetBeforeSuffix(TfGetBaseName(_packageName)); - const std::string firstLayerName = TfStringPrintf( - "%s.%s", - firstLayerBaseName.c_str(), - TfGetExtension(_fileName).c_str()); + const std::string firstLayerBaseName = TfStringGetBeforeSuffix(TfGetBaseName(_packageName)); + const std::string firstLayerName + = TfStringPrintf("%s.%s", firstLayerBaseName.c_str(), TfGetExtension(_fileName).c_str()); if (mJobCtx.mArgs.compatibility == UsdMayaJobExportArgsTokens->appleArKit) { // If exporting with compatibility=appleArKit, there are additional @@ -742,30 +721,24 @@ UsdMaya_WriteJob::_CreatePackage() const // UsdUtilsCreateNewARKitUsdzPackage will automatically flatten and // enforce that the first layer has a .usdc extension. if (!UsdUtilsCreateNewARKitUsdzPackage( - SdfAssetPath(_fileName), - _packageName, - firstLayerName)) { + SdfAssetPath(_fileName), _packageName, firstLayerName)) { TF_RUNTIME_ERROR( - "Could not create package '%s' from temporary stage '%s'", - _packageName.c_str(), - _fileName.c_str()); + "Could not create package '%s' from temporary stage '%s'", + _packageName.c_str(), + _fileName.c_str()); } - } - else { + } else { // No compatibility options (standard). - if (!UsdUtilsCreateNewUsdzPackage( - SdfAssetPath(_fileName), - _packageName, - firstLayerName)) { + if (!UsdUtilsCreateNewUsdzPackage(SdfAssetPath(_fileName), _packageName, firstLayerName)) { TF_RUNTIME_ERROR( - "Could not create package '%s' from temporary stage '%s'", - _packageName.c_str(), - _fileName.c_str()); + "Could not create package '%s' from temporary stage '%s'", + _packageName.c_str(), + _fileName.c_str()); } } } -void UsdMaya_WriteJob::_PerFrameCallback(double /*iFrame*/) +void UsdMaya_WriteJob::_PerFrameCallback(double /*iFrame*/) { // XXX Should we be passing the frame number into the callback? // Unfortunately, we need to be careful that we don't affect existing @@ -780,7 +753,6 @@ void UsdMaya_WriteJob::_PerFrameCallback(double /*iFrame*/) } } - // write the frame ranges and statistic string on the root // Also call the post callbacks void UsdMaya_WriteJob::_PostCallback() @@ -794,13 +766,13 @@ void UsdMaya_WriteJob::_PostCallback() } } -bool UsdMaya_WriteJob::_CheckNameClashes(const SdfPath &path, const MDagPath &dagPath) +bool UsdMaya_WriteJob::_CheckNameClashes(const SdfPath& path, const MDagPath& dagPath) { if (!mJobCtx.mArgs.stripNamespaces) { return true; } auto foundPair = mUsdPathToDagPathMap.find(path); - if (foundPair != mUsdPathToDagPathMap.end()){ + if (foundPair != mUsdPathToDagPathMap.end()) { if (mJobCtx.mArgs.mergeTransformAndShape) { // Shape should not conflict with xform MDagPath other = foundPair->second; @@ -826,6 +798,4 @@ bool UsdMaya_WriteJob::_CheckNameClashes(const SdfPath &path, const MDagPath &da return true; } - PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/jobs/writeJob.h b/lib/mayaUsd/fileio/jobs/writeJob.h index f05076a8c8..fc54e35d3a 100644 --- a/lib/mayaUsd/fileio/jobs/writeJob.h +++ b/lib/mayaUsd/fileio/jobs/writeJob.h @@ -16,18 +16,18 @@ #ifndef PXRUSDMAYA_WRITE_JOB_H #define PXRUSDMAYA_WRITE_JOB_H -#include - -#include - -#include -#include - #include #include #include #include +#include +#include + +#include + +#include + PXR_NAMESPACE_OPEN_SCOPE class UsdMaya_ModelKindProcessor; @@ -36,7 +36,7 @@ class UsdMaya_WriteJob { public: MAYAUSD_CORE_PUBLIC - UsdMaya_WriteJob(const UsdMayaJobExportArgs & iArgs); + UsdMaya_WriteJob(const UsdMayaJobExportArgs& iArgs); MAYAUSD_CORE_PUBLIC ~UsdMaya_WriteJob(); @@ -53,7 +53,7 @@ class UsdMaya_WriteJob /// Begins constructing the USD stage, writing out the values at the default /// time. Returns \c true if the stage can be created successfully. bool _BeginWriting(const std::string& fileName, bool append); - + /// Writes the stage values at the given frame. /// Warning: this function must be called with non-decreasing frame numbers. /// If you call WriteFrame() with a frame number lower than a previous @@ -65,7 +65,7 @@ class UsdMaya_WriteJob bool _FinishWriting(); /// Writes the root prim variants based on the Maya render layers. - TfToken _WriteVariants(const UsdPrim &usdRootPrim); + TfToken _WriteVariants(const UsdPrim& usdRootPrim); /// Creates a usdz package from the write job's current USD stage. void _CreatePackage() const; @@ -73,7 +73,7 @@ class UsdMaya_WriteJob void _PerFrameCallback(double iFrame); void _PostCallback(); - bool _CheckNameClashes(const SdfPath &path, const MDagPath &dagPath); + bool _CheckNameClashes(const SdfPath& path, const MDagPath& dagPath); // Name of the created/appended USD file std::string _fileName; @@ -83,7 +83,7 @@ class UsdMaya_WriteJob // Name of current layer since it should be restored after looping over them MString mCurrentRenderLayerName; - + // List of renderLayerObjects. Currently used for variants MObjectArray mRenderLayerObjs; @@ -99,7 +99,6 @@ class UsdMaya_WriteJob std::unique_ptr _modelKindProcessor; }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/primReader.cpp b/lib/mayaUsd/fileio/primReader.cpp index 107ae54c62..38292adbce 100644 --- a/lib/mayaUsd/fileio/primReader.cpp +++ b/lib/mayaUsd/fileio/primReader.cpp @@ -22,20 +22,10 @@ UsdMayaPrimReader::UsdMayaPrimReader(const UsdMayaPrimReaderArgs& args) { } -bool -UsdMayaPrimReader::HasPostReadSubtree() const -{ - return false; -} +bool UsdMayaPrimReader::HasPostReadSubtree() const { return false; } -void -UsdMayaPrimReader::PostReadSubtree(UsdMayaPrimReaderContext*) -{ -} +void UsdMayaPrimReader::PostReadSubtree(UsdMayaPrimReaderContext*) { } -const UsdMayaPrimReaderArgs& -UsdMayaPrimReader::_GetArgs() { - return _args; -} +const UsdMayaPrimReaderArgs& UsdMayaPrimReader::_GetArgs() { return _args; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/primReader.h b/lib/mayaUsd/fileio/primReader.h index 7f6a43e850..174473021c 100644 --- a/lib/mayaUsd/fileio/primReader.h +++ b/lib/mayaUsd/fileio/primReader.h @@ -16,12 +16,12 @@ #ifndef PXRUSDMAYA_MAYAPRIMREADER_H #define PXRUSDMAYA_MAYAPRIMREADER_H -#include - #include #include #include +#include + PXR_NAMESPACE_OPEN_SCOPE class UsdMayaPrimReader diff --git a/lib/mayaUsd/fileio/primReaderArgs.cpp b/lib/mayaUsd/fileio/primReaderArgs.cpp index d1d8fdbd22..4ee7ce8081 100644 --- a/lib/mayaUsd/fileio/primReaderArgs.cpp +++ b/lib/mayaUsd/fileio/primReaderArgs.cpp @@ -18,48 +18,31 @@ PXR_NAMESPACE_OPEN_SCOPE UsdMayaPrimReaderArgs::UsdMayaPrimReaderArgs( - const UsdPrim& prim, - const UsdMayaJobImportArgs& jobArgs) - : - _prim(prim), - _jobArgs(jobArgs) + const UsdPrim& prim, + const UsdMayaJobImportArgs& jobArgs) + : _prim(prim) + , _jobArgs(jobArgs) { } -const UsdPrim& -UsdMayaPrimReaderArgs::GetUsdPrim() const -{ - return _prim; -} +const UsdPrim& UsdMayaPrimReaderArgs::GetUsdPrim() const { return _prim; } -GfInterval -UsdMayaPrimReaderArgs::GetTimeInterval() const -{ - return _jobArgs.timeInterval; -} +GfInterval UsdMayaPrimReaderArgs::GetTimeInterval() const { return _jobArgs.timeInterval; } -const TfToken::Set& -UsdMayaPrimReaderArgs::GetIncludeMetadataKeys() const +const TfToken::Set& UsdMayaPrimReaderArgs::GetIncludeMetadataKeys() const { return _jobArgs.includeMetadataKeys; } -const TfToken::Set& -UsdMayaPrimReaderArgs::GetIncludeAPINames() const +const TfToken::Set& UsdMayaPrimReaderArgs::GetIncludeAPINames() const { return _jobArgs.includeAPINames; } -const TfToken::Set& -UsdMayaPrimReaderArgs::GetExcludePrimvarNames() const +const TfToken::Set& UsdMayaPrimReaderArgs::GetExcludePrimvarNames() const { return _jobArgs.excludePrimvarNames; } -bool -UsdMayaPrimReaderArgs::GetUseAsAnimationCache() const -{ - return _jobArgs.useAsAnimationCache; -} - +bool UsdMayaPrimReaderArgs::GetUseAsAnimationCache() const { return _jobArgs.useAsAnimationCache; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/primReaderArgs.h b/lib/mayaUsd/fileio/primReaderArgs.h index ea105b02b0..bab9a5ce65 100644 --- a/lib/mayaUsd/fileio/primReaderArgs.h +++ b/lib/mayaUsd/fileio/primReaderArgs.h @@ -16,27 +16,25 @@ #ifndef PXRUSDMAYA_PRIMREADERARGS_H #define PXRUSDMAYA_PRIMREADERARGS_H -#include -#include -#include - #include #include +#include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE /// \class UsdMayaPrimReaderArgs /// \brief This class holds read-only arguments that are passed into reader plugins for /// the usdMaya library. -/// +/// /// \sa UsdMayaPrimReaderContext class UsdMayaPrimReaderArgs { public: MAYAUSD_CORE_PUBLIC - UsdMayaPrimReaderArgs( - const UsdPrim& prim, - const UsdMayaJobImportArgs& jobArgs); + UsdMayaPrimReaderArgs(const UsdPrim& prim, const UsdMayaJobImportArgs& jobArgs); /// \brief return the usd prim that should be read. MAYAUSD_CORE_PUBLIC @@ -45,9 +43,7 @@ class UsdMayaPrimReaderArgs /// \brief return the initial job arguments, allowing a prim reader to /// execute a secondary prim reader. MAYAUSD_CORE_PUBLIC - const UsdMayaJobImportArgs& GetJobArguments() const { - return _jobArgs; - } + const UsdMayaJobImportArgs& GetJobArguments() const { return _jobArgs; } /// Returns the time interval over which to import animated data. /// An empty interval (GfInterval::IsEmpty()) means that no @@ -66,17 +62,17 @@ class UsdMayaPrimReaderArgs MAYAUSD_CORE_PUBLIC bool GetUseAsAnimationCache() const; - bool ShouldImportUnboundShaders() const { + bool ShouldImportUnboundShaders() const + { // currently this is disabled. return false; } private: - const UsdPrim& _prim; + const UsdPrim& _prim; const UsdMayaJobImportArgs& _jobArgs; }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/primReaderContext.cpp b/lib/mayaUsd/fileio/primReaderContext.cpp index 14aa0244d3..af3723eace 100644 --- a/lib/mayaUsd/fileio/primReaderContext.cpp +++ b/lib/mayaUsd/fileio/primReaderContext.cpp @@ -17,27 +17,21 @@ PXR_NAMESPACE_OPEN_SCOPE -UsdMayaPrimReaderContext::UsdMayaPrimReaderContext( - ObjectRegistry* pathNodeMap) - : - _prune(false), - _pathNodeMap(pathNodeMap) +UsdMayaPrimReaderContext::UsdMayaPrimReaderContext(ObjectRegistry* pathNodeMap) + : _prune(false) + , _pathNodeMap(pathNodeMap) { } -MObject -UsdMayaPrimReaderContext::GetMayaNode( - const SdfPath& path, - bool findAncestors) const +MObject UsdMayaPrimReaderContext::GetMayaNode(const SdfPath& path, bool findAncestors) const { // Get Node parent if (_pathNodeMap) { - for (SdfPath parentPath = path; - !parentPath.IsEmpty(); - parentPath = parentPath.GetParentPath()) { + for (SdfPath parentPath = path; !parentPath.IsEmpty(); + parentPath = parentPath.GetParentPath()) { // retrieve from a registry since nodes have not yet been put into DG ObjectRegistry::iterator it = _pathNodeMap->find(parentPath.GetString()); - if (it != _pathNodeMap->end() ) { + if (it != _pathNodeMap->end()) { return it->second; } @@ -46,37 +40,25 @@ UsdMayaPrimReaderContext::GetMayaNode( } } } - return MObject::kNullObj; // returning MObject::kNullObj indicates that the parent is the root for the scene + return MObject::kNullObj; // returning MObject::kNullObj indicates that the parent is the root + // for the scene } -void -UsdMayaPrimReaderContext::RegisterNewMayaNode( - const std::string &path, - const MObject &mayaNode) const +void UsdMayaPrimReaderContext::RegisterNewMayaNode(const std::string& path, const MObject& mayaNode) + const { if (_pathNodeMap) { _pathNodeMap->insert(std::make_pair(path, mayaNode)); } } -bool -UsdMayaPrimReaderContext::GetPruneChildren() const -{ - return _prune; -} +bool UsdMayaPrimReaderContext::GetPruneChildren() const { return _prune; } /// Sets whether traversal should automatically continue into this prim's /// children. This only has an effect if set during the /// UsdMayaPrimReader::Read() step, and not in the /// UsdMayaPrimReader::PostReadSubtree() step, since in the latter, the /// children have already been processed. -void -UsdMayaPrimReaderContext::SetPruneChildren( - bool prune) -{ - _prune = prune; -} - +void UsdMayaPrimReaderContext::SetPruneChildren(bool prune) { _prune = prune; } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/primReaderContext.h b/lib/mayaUsd/fileio/primReaderContext.h index f6f3876a90..78b5df5db0 100644 --- a/lib/mayaUsd/fileio/primReaderContext.h +++ b/lib/mayaUsd/fileio/primReaderContext.h @@ -16,19 +16,19 @@ #ifndef PXRUSDMAYA_PRIMREADERCONTEXT_H #define PXRUSDMAYA_PRIMREADERCONTEXT_H -#include +#include #include #include -#include +#include PXR_NAMESPACE_OPEN_SCOPE /// \class UsdMayaPrimReaderContext /// \brief This class provides an interface for reader plugins to communicate /// state back to the core usd maya logic as well as retrieve information set by -/// other plugins. +/// other plugins. /// /// Maya operations should be made directly with the Maya API. Any additional /// state that needs to be stored that isn't directly related to the Maya scene @@ -50,9 +50,7 @@ class UsdMayaPrimReaderContext /// /// Returns an invalid MObject if no such object exists. MAYAUSD_CORE_PUBLIC - MObject GetMayaNode( - const SdfPath& path, - bool findAncestors) const; + MObject GetMayaNode(const SdfPath& path, bool findAncestors) const; /// \brief Record \p mayaNode prim as being created \p path. /// @@ -60,10 +58,10 @@ class UsdMayaPrimReaderContext /// reasons for this may be: /// - looking up later (for shader bindings, relationship targets, etc) /// - undo/redo purposes - /// + /// /// Plugins should call this as needed. MAYAUSD_CORE_PUBLIC - void RegisterNewMayaNode(const std::string &path, const MObject &mayaNode) const; + void RegisterNewMayaNode(const std::string& path, const MObject& mayaNode) const; /// \brief returns true if prim traversal of the children of the current /// node can be pruned. @@ -71,14 +69,13 @@ class UsdMayaPrimReaderContext bool GetPruneChildren() const; /// \brief If this plugin takes care of reading all of its children, it - /// should SetPruneChildren(true). + /// should SetPruneChildren(true). MAYAUSD_CORE_PUBLIC void SetPruneChildren(bool prune); ~UsdMayaPrimReaderContext() { } private: - bool _prune; // used to keep track of prims that are created. @@ -86,7 +83,6 @@ class UsdMayaPrimReaderContext ObjectRegistry* _pathNodeMap; }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/primReaderRegistry.cpp b/lib/mayaUsd/fileio/primReaderRegistry.cpp index b35127d3a4..c84312fbd3 100644 --- a/lib/mayaUsd/fileio/primReaderRegistry.cpp +++ b/lib/mayaUsd/fileio/primReaderRegistry.cpp @@ -15,9 +15,10 @@ // #include "primReaderRegistry.h" -#include -#include -#include +#include +#include +#include +#include #include #include @@ -27,48 +28,35 @@ #include #include -#include -#include -#include -#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PRIVATE_TOKENS(_tokens, - (UsdMaya) - (PrimReader) -); +TF_DEFINE_PRIVATE_TOKENS(_tokens, (UsdMaya)(PrimReader)); typedef std::map _Registry; -static _Registry _reg; - +static _Registry _reg; /* static */ -void -UsdMayaPrimReaderRegistry::Register( - const TfType& t, - UsdMayaPrimReaderRegistry::ReaderFactoryFn fn) +void UsdMayaPrimReaderRegistry::Register( + const TfType& t, + UsdMayaPrimReaderRegistry::ReaderFactoryFn fn) { TfToken tfTypeName(t.GetTypeName()); - TF_DEBUG(PXRUSDMAYA_REGISTRY).Msg( - "Registering UsdMayaPrimReader for TfType %s.\n", tfTypeName.GetText()); - std::pair< _Registry::iterator, bool> insertStatus = - _reg.insert(std::make_pair(tfTypeName, fn)); + TF_DEBUG(PXRUSDMAYA_REGISTRY) + .Msg("Registering UsdMayaPrimReader for TfType %s.\n", tfTypeName.GetText()); + std::pair<_Registry::iterator, bool> insertStatus = _reg.insert(std::make_pair(tfTypeName, fn)); if (insertStatus.second) { - UsdMaya_RegistryHelper::AddUnloader([tfTypeName]() { - _reg.erase(tfTypeName); - }); - } - else { + UsdMaya_RegistryHelper::AddUnloader([tfTypeName]() { _reg.erase(tfTypeName); }); + } else { TF_CODING_ERROR("Multiple readers for type %s", tfTypeName.GetText()); } } /* static */ -void -UsdMayaPrimReaderRegistry::RegisterRaw( - const TfType& t, - UsdMayaPrimReaderRegistry::ReaderFn fn) +void UsdMayaPrimReaderRegistry::RegisterRaw(const TfType& t, UsdMayaPrimReaderRegistry::ReaderFn fn) { Register(t, UsdMaya_FunctorPrimReader::CreateFactory(fn)); } @@ -81,26 +69,22 @@ UsdMayaPrimReaderRegistry::Find(const TfToken& usdTypeName) // unfortunately, usdTypeName is diff from the tfTypeName which we use to // register. do the conversion here. - TfType tfType = PlugRegistry::FindDerivedTypeByName(usdTypeName); - std::string typeNameStr = tfType.GetTypeName(); - TfToken typeName(typeNameStr); + TfType tfType = PlugRegistry::FindDerivedTypeByName(usdTypeName); + std::string typeNameStr = tfType.GetTypeName(); + TfToken typeName(typeNameStr); ReaderFactoryFn ret = nullptr; if (TfMapLookup(_reg, typeName, &ret)) { return ret; } - static const TfTokenVector SCOPE = { - _tokens->UsdMaya, - _tokens->PrimReader - }; + static const TfTokenVector SCOPE = { _tokens->UsdMaya, _tokens->PrimReader }; UsdMaya_RegistryHelper::FindAndLoadMayaPlug(SCOPE, typeNameStr); // ideally something just registered itself. if not, we at least put it in // the registry in case we encounter it again. if (!TfMapLookup(_reg, typeName, &ret)) { - TF_DEBUG(PXRUSDMAYA_REGISTRY).Msg( - "No usdMaya reader plugin for TfType %s. No maya plugin.\n", - typeName.GetText()); + TF_DEBUG(PXRUSDMAYA_REGISTRY) + .Msg("No usdMaya reader plugin for TfType %s. No maya plugin.\n", typeName.GetText()); _reg[typeName] = nullptr; } return ret; @@ -117,5 +101,4 @@ UsdMayaPrimReaderRegistry::FindOrFallback(const TfToken& usdTypeName) return UsdMaya_FallbackPrimReader::CreateFactory(); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/primReaderRegistry.h b/lib/mayaUsd/fileio/primReaderRegistry.h index c35b2b2a00..49c526a8ad 100644 --- a/lib/mayaUsd/fileio/primReaderRegistry.h +++ b/lib/mayaUsd/fileio/primReaderRegistry.h @@ -16,14 +16,14 @@ #ifndef PXRUSDMAYA_PRIMREADERREGISTRY_H #define PXRUSDMAYA_PRIMREADERREGISTRY_H -#include -#include - #include #include #include #include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE /// \class UsdMayaPrimReaderRegistry @@ -31,7 +31,7 @@ PXR_NAMESPACE_OPEN_SCOPE /// plugins. /// /// Use PXRUSDMAYA_DEFINE_READER(MyUsdType, args, ctx) to register a new reader -/// for maya. +/// for maya. /// /// In order for the core system to discover the plugin, you should also /// have a plugInfo.json file that contains the type and maya plugin to load: @@ -45,21 +45,18 @@ PXR_NAMESPACE_OPEN_SCOPE /// ] /// } /// } -/// } +/// } /// \endcode struct UsdMayaPrimReaderRegistry { /// Reader factory function, i.e. a function that creates a prim reader /// for the given prim reader args. - typedef std::function< UsdMayaPrimReaderSharedPtr ( - const UsdMayaPrimReaderArgs&) > ReaderFactoryFn; + typedef std::function ReaderFactoryFn; /// Reader function, i.e. a function that reads a prim. This is the /// signature of the function declared in the PXRUSDMAYA_DEFINE_READER /// macro. - typedef std::function< bool ( - const UsdMayaPrimReaderArgs&, - UsdMayaPrimReaderContext*) > ReaderFn; + typedef std::function ReaderFn; /// \brief Register \p fn as a reader provider for \p type. MAYAUSD_CORE_PUBLIC @@ -78,15 +75,12 @@ struct UsdMayaPrimReaderRegistry /// UsdMayaPrimReaderRegistry::Register(MyReader::Create); /// } /// \endcode - template - static void Register(ReaderFactoryFn fn) + template static void Register(ReaderFactoryFn fn) { if (TfType t = TfType::Find()) { Register(t, fn); - } - else { - TF_CODING_ERROR("Cannot register unknown TfType: %s.", - ArchGetDemangled().c_str()); + } else { + TF_CODING_ERROR("Cannot register unknown TfType: %s.", ArchGetDemangled().c_str()); } } @@ -101,28 +95,24 @@ struct UsdMayaPrimReaderRegistry /// function as a reader provider for \p T. /// This is a helper method for the macro PXRUSDMAYA_DEFINE_READER; /// you probably want to use PXRUSDMAYA_DEFINE_READER directly instead. - template - static void RegisterRaw(ReaderFn fn) + template static void RegisterRaw(ReaderFn fn) { if (TfType t = TfType::Find()) { RegisterRaw(t, fn); - } - else { - TF_CODING_ERROR("Cannot register unknown TfType: %s.", - ArchGetDemangled().c_str()); + } else { + TF_CODING_ERROR("Cannot register unknown TfType: %s.", ArchGetDemangled().c_str()); } } // takes a usdType (i.e. prim.GetTypeName()) /// \brief Finds a reader factory if one exists for \p usdTypeName. /// - /// \p usdTypeName should be a usd typeName, for example, + /// \p usdTypeName should be a usd typeName, for example, /// \code /// prim.GetTypeName() /// \endcode MAYAUSD_CORE_PUBLIC - static ReaderFactoryFn Find( - const TfToken& usdTypeName); + static ReaderFactoryFn Find(const TfToken& usdTypeName); /// Similar to Find(), but returns a "fallback" prim reader factory if none /// can be found for \p usdTypeName. Thus, this always returns a valid @@ -131,14 +121,14 @@ struct UsdMayaPrimReaderRegistry static ReaderFactoryFn FindOrFallback(const TfToken& usdTypeName); }; -#define PXRUSDMAYA_DEFINE_READER(T, argsVarName, ctxVarName)\ -static bool UsdMaya_PrimReader_##T(const UsdMayaPrimReaderArgs&, UsdMayaPrimReaderContext*); \ -TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaPrimReaderRegistry, T) \ -{\ - UsdMayaPrimReaderRegistry::RegisterRaw(UsdMaya_PrimReader_##T);\ -}\ -bool UsdMaya_PrimReader_##T(const UsdMayaPrimReaderArgs& argsVarName, UsdMayaPrimReaderContext* ctxVarName) - +#define PXRUSDMAYA_DEFINE_READER(T, argsVarName, ctxVarName) \ + static bool UsdMaya_PrimReader_##T(const UsdMayaPrimReaderArgs&, UsdMayaPrimReaderContext*); \ + TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaPrimReaderRegistry, T) \ + { \ + UsdMayaPrimReaderRegistry::RegisterRaw(UsdMaya_PrimReader_##T); \ + } \ + bool UsdMaya_PrimReader_##T( \ + const UsdMayaPrimReaderArgs& argsVarName, UsdMayaPrimReaderContext* ctxVarName) PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/primUpdater.cpp b/lib/mayaUsd/fileio/primUpdater.cpp index 70960e4a9a..0d82457d3e 100644 --- a/lib/mayaUsd/fileio/primUpdater.cpp +++ b/lib/mayaUsd/fileio/primUpdater.cpp @@ -22,46 +22,24 @@ PXR_NAMESPACE_OPEN_SCOPE -UsdMayaPrimUpdater::UsdMayaPrimUpdater( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath) : - _dagPath(UsdMayaUtil::getDagPath(depNodeFn)), - _mayaObject(depNodeFn.object()), - _usdPath(usdPath), - _baseDagToUsdPaths(UsdMayaUtil::getDagPathMap(depNodeFn, usdPath)) +UsdMayaPrimUpdater::UsdMayaPrimUpdater(const MFnDependencyNode& depNodeFn, const SdfPath& usdPath) + : _dagPath(UsdMayaUtil::getDagPath(depNodeFn)) + , _mayaObject(depNodeFn.object()) + , _usdPath(usdPath) + , _baseDagToUsdPaths(UsdMayaUtil::getDagPathMap(depNodeFn, usdPath)) { } -bool UsdMayaPrimUpdater::Push(UsdMayaPrimUpdaterContext* context) -{ - return false; -} +bool UsdMayaPrimUpdater::Push(UsdMayaPrimUpdaterContext* context) { return false; } -bool UsdMayaPrimUpdater::Pull(UsdMayaPrimUpdaterContext* context) -{ - return false; -} +bool UsdMayaPrimUpdater::Pull(UsdMayaPrimUpdaterContext* context) { return false; } -void UsdMayaPrimUpdater::Clear(UsdMayaPrimUpdaterContext* context) -{ -} +void UsdMayaPrimUpdater::Clear(UsdMayaPrimUpdaterContext* context) { } -const MDagPath& -UsdMayaPrimUpdater::GetDagPath() const -{ - return _dagPath; -} +const MDagPath& UsdMayaPrimUpdater::GetDagPath() const { return _dagPath; } -const MObject& -UsdMayaPrimUpdater::GetMayaObject() const -{ - return _mayaObject; -} +const MObject& UsdMayaPrimUpdater::GetMayaObject() const { return _mayaObject; } -const SdfPath& -UsdMayaPrimUpdater::GetUsdPath() const -{ - return _usdPath; -} +const SdfPath& UsdMayaPrimUpdater::GetUsdPath() const { return _usdPath; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/primUpdater.h b/lib/mayaUsd/fileio/primUpdater.h index 5438ed5b03..1f04a0338f 100644 --- a/lib/mayaUsd/fileio/primUpdater.h +++ b/lib/mayaUsd/fileio/primUpdater.h @@ -17,16 +17,16 @@ #ifndef PXRUSDMAYA_MAYAPRIMUPDATER_H #define PXRUSDMAYA_MAYAPRIMUPDATER_H -#include -#include -#include +#include +#include +#include #include #include -#include -#include -#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -34,24 +34,24 @@ class UsdMayaPrimUpdater { public: MAYAUSD_CORE_PUBLIC - UsdMayaPrimUpdater(const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath); - + UsdMayaPrimUpdater(const MFnDependencyNode& depNodeFn, const SdfPath& usdPath); + // clang errors if you use "= default" here, due to const SdfPath member // see: http://open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#253 // ...which it seems clang only implements if using newer version + cpp std - UsdMayaPrimUpdater() {} + UsdMayaPrimUpdater() { } virtual ~UsdMayaPrimUpdater() = default; - enum class Supports { + enum class Supports + { Invalid = 0, - Push = 1 << 0, - Pull = 1 << 1, - Clear = 1 << 2, - All = Push | Pull | Clear + Push = 1 << 0, + Pull = 1 << 1, + Clear = 1 << 2, + All = Push | Pull | Clear }; - + MAYAUSD_CORE_PUBLIC virtual bool Push(UsdMayaPrimUpdaterContext* context); @@ -77,8 +77,7 @@ class UsdMayaPrimUpdater const SdfPath& GetUsdPath() const; /// The destination USD prim which we are updating. - template - UsdPrim GetUsdPrim(UsdMayaPrimUpdaterContext& context) const + template UsdPrim GetUsdPrim(UsdMayaPrimUpdaterContext& context) const { UsdPrim usdPrim; @@ -86,19 +85,18 @@ class UsdMayaPrimUpdater return usdPrim; } - T primSchema = - T::Define(context.GetUsdStage(), GetUsdPath()); + T primSchema = T::Define(context.GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( - primSchema, - "Could not define given updater type at path '%s'\n", - GetUsdPath().GetText())) { + primSchema, + "Could not define given updater type at path '%s'\n", + GetUsdPath().GetText())) { return usdPrim; } usdPrim = primSchema.GetPrim(); if (!TF_VERIFY( - usdPrim, - "Could not get UsdPrim for given updater type at path '%s'\n", - primSchema.GetPath().GetText())) { + usdPrim, + "Could not get UsdPrim for given updater type at path '%s'\n", + primSchema.GetPath().GetText())) { return usdPrim; } @@ -114,24 +112,24 @@ class UsdMayaPrimUpdater /// node prim updaters. const MObject _mayaObject; - const SdfPath _usdPath; + const SdfPath _usdPath; const UsdMayaUtil::MDagPathMap _baseDagToUsdPaths; - }; using UsdMayaPrimUpdaterSharedPtr = std::shared_ptr; -inline UsdMayaPrimUpdater::Supports operator|(UsdMayaPrimUpdater::Supports a, UsdMayaPrimUpdater::Supports b) +inline UsdMayaPrimUpdater::Supports +operator|(UsdMayaPrimUpdater::Supports a, UsdMayaPrimUpdater::Supports b) { return static_cast(static_cast(a) | static_cast(b)); } -inline UsdMayaPrimUpdater::Supports operator&(UsdMayaPrimUpdater::Supports a, UsdMayaPrimUpdater::Supports b) +inline UsdMayaPrimUpdater::Supports +operator&(UsdMayaPrimUpdater::Supports a, UsdMayaPrimUpdater::Supports b) { return static_cast(static_cast(a) & static_cast(b)); } - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/primUpdaterContext.cpp b/lib/mayaUsd/fileio/primUpdaterContext.cpp index 1e21210f33..58b7134d24 100644 --- a/lib/mayaUsd/fileio/primUpdaterContext.cpp +++ b/lib/mayaUsd/fileio/primUpdaterContext.cpp @@ -19,17 +19,13 @@ PXR_NAMESPACE_OPEN_SCOPE UsdMayaPrimUpdaterContext::UsdMayaPrimUpdaterContext( - const UsdTimeCode& timeCode, - const UsdStageRefPtr& stage) : - _timeCode(timeCode), - _stage(stage) + const UsdTimeCode& timeCode, + const UsdStageRefPtr& stage) + : _timeCode(timeCode) + , _stage(stage) { } -void -UsdMayaPrimUpdaterContext::Clear(const SdfPath&) -{ -} +void UsdMayaPrimUpdaterContext::Clear(const SdfPath&) { } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/primUpdaterContext.h b/lib/mayaUsd/fileio/primUpdaterContext.h index e682a6bb33..89286e1cda 100644 --- a/lib/mayaUsd/fileio/primUpdaterContext.h +++ b/lib/mayaUsd/fileio/primUpdaterContext.h @@ -17,12 +17,12 @@ #ifndef PXRUSDMAYA_PRIMUPDATERCONTEXT_H #define PXRUSDMAYA_PRIMUPDATERCONTEXT_H +#include + #include #include #include -#include - PXR_NAMESPACE_OPEN_SCOPE /// \class UsdMayaPrimUpdaterContext @@ -32,9 +32,7 @@ class UsdMayaPrimUpdaterContext { public: MAYAUSD_CORE_PUBLIC - UsdMayaPrimUpdaterContext( - const UsdTimeCode& timeCode, - const UsdStageRefPtr& stage); + UsdMayaPrimUpdaterContext(const UsdTimeCode& timeCode, const UsdStageRefPtr& stage); /// \brief returns the time frame where data should be edited. const UsdTimeCode& GetTimeCode() const { return _timeCode; } @@ -44,14 +42,12 @@ class UsdMayaPrimUpdaterContext MAYAUSD_CORE_PUBLIC virtual void Clear(const SdfPath&); - + private: - const UsdTimeCode& _timeCode; - UsdStageRefPtr _stage; + const UsdTimeCode& _timeCode; + UsdStageRefPtr _stage; }; - PXR_NAMESPACE_CLOSE_SCOPE #endif - diff --git a/lib/mayaUsd/fileio/primUpdaterRegistry.cpp b/lib/mayaUsd/fileio/primUpdaterRegistry.cpp index 39b9ec57f8..0d0448586e 100644 --- a/lib/mayaUsd/fileio/primUpdaterRegistry.cpp +++ b/lib/mayaUsd/fileio/primUpdaterRegistry.cpp @@ -16,11 +16,9 @@ // #include "primUpdaterRegistry.h" -#include -#include -#include +#include +#include -#include #include #include #include @@ -28,43 +26,36 @@ #include #include #include +#include #include -#include -#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PRIVATE_TOKENS(_tokens, - (UsdMaya) - (PrimUpdater) -); +TF_DEFINE_PRIVATE_TOKENS(_tokens, (UsdMaya)(PrimUpdater)); typedef std::map _Registry; -static _Registry _reg; - +static _Registry _reg; /* static */ -void -UsdMayaPrimUpdaterRegistry::Register( - const TfType& t, - UsdMayaPrimUpdater::Supports sup, - UsdMayaPrimUpdaterRegistry::UpdaterFactoryFn fn) +void UsdMayaPrimUpdaterRegistry::Register( + const TfType& t, + UsdMayaPrimUpdater::Supports sup, + UsdMayaPrimUpdaterRegistry::UpdaterFactoryFn fn) { TfToken tfTypeName(t.GetTypeName()); - TF_DEBUG(PXRUSDMAYA_REGISTRY).Msg( - "Registering UsdMayaPrimWriter for TfType type %s.\n", - tfTypeName.GetText()); + TF_DEBUG(PXRUSDMAYA_REGISTRY) + .Msg("Registering UsdMayaPrimWriter for TfType type %s.\n", tfTypeName.GetText()); - std::pair< _Registry::iterator, bool> insertStatus = - _reg.insert(std::make_pair(tfTypeName, std::make_tuple(sup,fn))); + std::pair<_Registry::iterator, bool> insertStatus + = _reg.insert(std::make_pair(tfTypeName, std::make_tuple(sup, fn))); if (insertStatus.second) { - UsdMaya_RegistryHelper::AddUnloader([tfTypeName]() { - _reg.erase(tfTypeName); - }); - } - else { + UsdMaya_RegistryHelper::AddUnloader([tfTypeName]() { _reg.erase(tfTypeName); }); + } else { TF_CODING_ERROR("Multiple updaters for TfType %s", tfTypeName.GetText()); } } @@ -77,32 +68,29 @@ UsdMayaPrimUpdaterRegistry::Find(const TfToken& usdTypeName) // unfortunately, usdTypeName is diff from the tfTypeName which we use to // register. do the conversion here. - TfType tfType = PlugRegistry::FindDerivedTypeByName(usdTypeName); + TfType tfType = PlugRegistry::FindDerivedTypeByName(usdTypeName); std::string typeNameStr = tfType.GetTypeName(); - TfToken typeName(typeNameStr); + TfToken typeName(typeNameStr); RegisterItem ret; if (TfMapLookup(_reg, typeName, &ret)) { return ret; } - static const TfTokenVector SCOPE = { - _tokens->UsdMaya, - _tokens->PrimUpdater - }; + static const TfTokenVector SCOPE = { _tokens->UsdMaya, _tokens->PrimUpdater }; UsdMaya_RegistryHelper::FindAndLoadMayaPlug(SCOPE, typeNameStr); // ideally something just registered itself. if not, we at least put it in // the registry in case we encounter it again. if (!TfMapLookup(_reg, typeName, &ret)) { - TF_DEBUG(PXRUSDMAYA_REGISTRY).Msg( - "No usdMaya updater plugin for TfType %s. No maya plugin found.\n", - typeName.GetText()); + TF_DEBUG(PXRUSDMAYA_REGISTRY) + .Msg( + "No usdMaya updater plugin for TfType %s. No maya plugin found.\n", + typeName.GetText()); _reg[typeName] = {}; } return ret; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/primUpdaterRegistry.h b/lib/mayaUsd/fileio/primUpdaterRegistry.h index ff1cb49067..49d29ad0a5 100644 --- a/lib/mayaUsd/fileio/primUpdaterRegistry.h +++ b/lib/mayaUsd/fileio/primUpdaterRegistry.h @@ -17,17 +17,17 @@ #ifndef PXRUSDMAYA_PRIM_UPDATER_REGISTRY_H #define PXRUSDMAYA_PRIM_UPDATER_REGISTRY_H -#include -#include - -#include +#include +#include +#include #include #include -#include -#include -#include +#include + +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -64,9 +64,8 @@ struct UsdMayaPrimUpdaterRegistry { /// Updater factory function, i.e. a function that creates a prim updater /// for the given Maya node/USD paths and context. - using UpdaterFactoryFn = std::function< UsdMayaPrimUpdaterSharedPtr ( - const MFnDependencyNode&, - const SdfPath&) >; + using UpdaterFactoryFn + = std::function; using RegisterItem = std::tuple; @@ -108,17 +107,15 @@ struct UsdMayaPrimUpdaterRegistry { if (TfType t = TfType::Find()) { Register(t, sup, fn); - } - else { - TF_CODING_ERROR("Cannot register unknown TfType: %s.", - ArchGetDemangled().c_str()); + } else { + TF_CODING_ERROR("Cannot register unknown TfType: %s.", ArchGetDemangled().c_str()); } } // takes a usdType (i.e. prim.GetTypeName()) /// \brief Finds a updater factory if one exists for \p usdTypeName. /// - /// \p usdTypeName should be a usd typeName, for example, + /// \p usdTypeName should be a usd typeName, for example, /// \code /// prim.GetTypeName() /// \endcode @@ -143,22 +140,15 @@ struct UsdMayaPrimUpdaterRegistry /// }; /// PXRUSDMAYA_REGISTER_UPDATER(myUsdTypeName, MyUpdater); /// \endcode -#define PXRUSDMAYA_REGISTER_UPDATER(usdTypeName, updaterClass, supports) \ -TF_REGISTRY_FUNCTION_WITH_TAG( \ - UsdMayaPrimUpdaterRegistry, \ - usdTypeName##_##updaterClass) \ -{ \ - UsdMayaPrimUpdaterRegistry::Register( \ - supports, \ - []( \ - const MFnDependencyNode& depNodeFn, \ - const SdfPath& usdPath) { \ - return std::make_shared(depNodeFn, usdPath); \ - }); \ -} - +#define PXRUSDMAYA_REGISTER_UPDATER(usdTypeName, updaterClass, supports) \ + TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaPrimUpdaterRegistry, usdTypeName##_##updaterClass) \ + { \ + UsdMayaPrimUpdaterRegistry::Register( \ + supports, [](const MFnDependencyNode& depNodeFn, const SdfPath& usdPath) { \ + return std::make_shared(depNodeFn, usdPath); \ + }); \ + } PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/primWriter.cpp b/lib/mayaUsd/fileio/primWriter.cpp index 21185b80a9..19e1ad623d 100644 --- a/lib/mayaUsd/fileio/primWriter.cpp +++ b/lib/mayaUsd/fileio/primWriter.cpp @@ -15,22 +15,18 @@ // #include "primWriter.h" -#include -#include -#include - -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include -#include #include #include #include #include +#include #include #include #include @@ -40,27 +36,27 @@ #include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -PXRUSDMAYA_REGISTER_ADAPTOR_ATTRIBUTE_ALIAS( - UsdGeomTokens->purpose, "USD_purpose"); +PXRUSDMAYA_REGISTER_ADAPTOR_ATTRIBUTE_ALIAS(UsdGeomTokens->purpose, "USD_purpose"); TF_DEFINE_PRIVATE_TOKENS( _tokens, - (USD_inheritClassNames) -); + (USD_inheritClassNames)); -static -bool -_IsAnimated(const UsdMayaJobExportArgs& args, const MObject& obj) +static bool _IsAnimated(const UsdMayaJobExportArgs& args, const MObject& obj) { if (!args.timeSamples.empty()) { return UsdMayaUtil::isAnimated(obj); @@ -70,32 +66,28 @@ _IsAnimated(const UsdMayaJobExportArgs& args, const MObject& obj) } UsdMayaPrimWriter::UsdMayaPrimWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - _writeJobCtx(jobCtx), - _dagPath(UsdMayaUtil::getDagPath(depNodeFn)), - _mayaObject(depNodeFn.object()), - _usdPath(usdPath), - _baseDagToUsdPaths(UsdMayaUtil::getDagPathMap(depNodeFn, usdPath)), - _exportVisibility(jobCtx.GetArgs().exportVisibility), - _hasAnimCurves(_IsAnimated(jobCtx.GetArgs(), depNodeFn.object())) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : _writeJobCtx(jobCtx) + , _dagPath(UsdMayaUtil::getDagPath(depNodeFn)) + , _mayaObject(depNodeFn.object()) + , _usdPath(usdPath) + , _baseDagToUsdPaths(UsdMayaUtil::getDagPathMap(depNodeFn, usdPath)) + , _exportVisibility(jobCtx.GetArgs().exportVisibility) + , _hasAnimCurves(_IsAnimated(jobCtx.GetArgs(), depNodeFn.object())) { } /* virtual */ -UsdMayaPrimWriter::~UsdMayaPrimWriter() -{ -} +UsdMayaPrimWriter::~UsdMayaPrimWriter() { } -bool -UsdMayaPrimWriter::_IsMergedTransform() const +bool UsdMayaPrimWriter::_IsMergedTransform() const { return _writeJobCtx.IsMergedTransform(GetDagPath()); } -bool -UsdMayaPrimWriter::_IsMergedShape() const +bool UsdMayaPrimWriter::_IsMergedShape() const { // For DG nodes, popping an invalid path will silently fail leaving the // path invalid, and IsMergedTransform() returns false for invalid paths. @@ -105,23 +97,16 @@ UsdMayaPrimWriter::_IsMergedShape() const } // In the future, we'd like to make this a plugin point. -static -bool -_GetClassNamesToWrite( - const MObject& mObj, - std::vector* outClassNames) +static bool _GetClassNamesToWrite(const MObject& mObj, std::vector* outClassNames) { return UsdMayaWriteUtil::ReadMayaAttribute( - MFnDependencyNode(mObj), - MString(_tokens->USD_inheritClassNames.GetText()), - outClassNames); + MFnDependencyNode(mObj), MString(_tokens->USD_inheritClassNames.GetText()), outClassNames); } /* virtual */ -void -UsdMayaPrimWriter::Write(const UsdTimeCode& usdTime) +void UsdMayaPrimWriter::Write(const UsdTimeCode& usdTime) { - MStatus status; + MStatus status; const MFnDependencyNode depNodeFn(GetMayaObject(), &status); if (status != MS::kSuccess) { return; @@ -138,11 +123,7 @@ UsdMayaPrimWriter::Write(const UsdTimeCode& usdTime) if (imageable && _exportVisibility && !_IsMergedTransform()) { bool isVisible = true; bool isVisAnimated = false; - UsdMayaUtil::getPlugValue( - depNodeFn, - "visibility", - &isVisible, - &isVisAnimated); + UsdMayaUtil::getPlugValue(depNodeFn, "visibility", &isVisible, &isVisAnimated); if (_IsMergedShape()) { MDagPath parentDagPath = GetDagPath(); @@ -152,10 +133,7 @@ UsdMayaPrimWriter::Write(const UsdTimeCode& usdTime) bool parentIsVisible = true; bool parentIsVisAnimated = false; UsdMayaUtil::getPlugValue( - parentDepNodeFn, - "visibility", - &parentIsVisible, - &parentIsVisAnimated); + parentDepNodeFn, "visibility", &parentIsVisible, &parentIsVisAnimated); // If BOTH the shape AND the transform are visible, then the // prim is visible. @@ -170,15 +148,14 @@ UsdMayaPrimWriter::Write(const UsdTimeCode& usdTime) // if it is animated or not. If we're not writing to default, we only // write visibility if it's animated. if (usdTime.IsDefault() || isVisAnimated) { - const TfToken& visibilityTok = - (isVisible ? - UsdGeomTokens->inherited : - UsdGeomTokens->invisible); - - UsdMayaWriteUtil::SetAttribute(imageable.CreateVisibilityAttr(VtValue(), true), - visibilityTok, - usdTime, - _GetSparseValueWriter()); + const TfToken& visibilityTok + = (isVisible ? UsdGeomTokens->inherited : UsdGeomTokens->invisible); + + UsdMayaWriteUtil::SetAttribute( + imageable.CreateVisibilityAttr(VtValue(), true), + visibilityTok, + usdTime, + _GetSparseValueWriter()); } } @@ -203,126 +180,66 @@ UsdMayaPrimWriter::Write(const UsdTimeCode& usdTime) // Currently only purpose, which is uniform, so only export at // default time. UsdMayaWriteUtil::WriteSchemaAttributesToPrim( - GetMayaObject(), - _usdPrim, - {UsdGeomTokens->purpose}, - usdTime, - &_valueWriter); + GetMayaObject(), _usdPrim, { UsdGeomTokens->purpose }, usdTime, &_valueWriter); } // Write API schema attributes and strongly-typed metadata. // We currently only support these at default time. UsdMayaWriteUtil::WriteMetadataToPrim(GetMayaObject(), _usdPrim); UsdMayaWriteUtil::WriteAPISchemaAttributesToPrim( - GetMayaObject(), - _usdPrim, - _GetSparseValueWriter()); + GetMayaObject(), _usdPrim, _GetSparseValueWriter()); } // Write out user-tagged attributes, which are supported at default time // and at animated time-samples. UsdMayaWriteUtil::WriteUserExportedAttributes( - GetMayaObject(), - _usdPrim, - usdTime, - _GetSparseValueWriter()); + GetMayaObject(), _usdPrim, usdTime, _GetSparseValueWriter()); } /* virtual */ -bool -UsdMayaPrimWriter::ExportsGprims() const -{ - return false; -} +bool UsdMayaPrimWriter::ExportsGprims() const { return false; } /* virtual */ -bool -UsdMayaPrimWriter::ShouldPruneChildren() const -{ - return false; -} +bool UsdMayaPrimWriter::ShouldPruneChildren() const { return false; } /* virtual */ -void -UsdMayaPrimWriter::PostExport() -{ -} +void UsdMayaPrimWriter::PostExport() { } -void -UsdMayaPrimWriter::SetExportVisibility(const bool exportVis) -{ - _exportVisibility = exportVis; -} +void UsdMayaPrimWriter::SetExportVisibility(const bool exportVis) { _exportVisibility = exportVis; } -bool -UsdMayaPrimWriter::GetExportVisibility() const -{ - return _exportVisibility; -} +bool UsdMayaPrimWriter::GetExportVisibility() const { return _exportVisibility; } /* virtual */ -const SdfPathVector& -UsdMayaPrimWriter::GetModelPaths() const +const SdfPathVector& UsdMayaPrimWriter::GetModelPaths() const { static const SdfPathVector empty; return empty; } /* virtual */ -const UsdMayaUtil::MDagPathMap& -UsdMayaPrimWriter::GetDagToUsdPathMapping() const +const UsdMayaUtil::MDagPathMap& UsdMayaPrimWriter::GetDagToUsdPathMapping() const { return _baseDagToUsdPaths; } -const MDagPath& -UsdMayaPrimWriter::GetDagPath() const -{ - return _dagPath; -} +const MDagPath& UsdMayaPrimWriter::GetDagPath() const { return _dagPath; } -const MObject& -UsdMayaPrimWriter::GetMayaObject() const -{ - return _mayaObject; -} +const MObject& UsdMayaPrimWriter::GetMayaObject() const { return _mayaObject; } -const SdfPath& -UsdMayaPrimWriter::GetUsdPath() const -{ - return _usdPath; -} +const SdfPath& UsdMayaPrimWriter::GetUsdPath() const { return _usdPath; } -const UsdPrim& -UsdMayaPrimWriter::GetUsdPrim() const -{ - return _usdPrim; -} +const UsdPrim& UsdMayaPrimWriter::GetUsdPrim() const { return _usdPrim; } -const UsdStageRefPtr& -UsdMayaPrimWriter::GetUsdStage() const -{ - return _writeJobCtx.GetUsdStage(); -} +const UsdStageRefPtr& UsdMayaPrimWriter::GetUsdStage() const { return _writeJobCtx.GetUsdStage(); } -const UsdMayaJobExportArgs& -UsdMayaPrimWriter::_GetExportArgs() const +const UsdMayaJobExportArgs& UsdMayaPrimWriter::_GetExportArgs() const { return _writeJobCtx.GetArgs(); } -UsdUtilsSparseValueWriter* -UsdMayaPrimWriter::_GetSparseValueWriter() -{ - return &_valueWriter; -} +UsdUtilsSparseValueWriter* UsdMayaPrimWriter::_GetSparseValueWriter() { return &_valueWriter; } /* virtual */ -bool -UsdMayaPrimWriter::_HasAnimCurves() const -{ - return _hasAnimCurves; -} - +bool UsdMayaPrimWriter::_HasAnimCurves() const { return _hasAnimCurves; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/primWriter.h b/lib/mayaUsd/fileio/primWriter.h index b9c76876ff..625df22f5e 100644 --- a/lib/mayaUsd/fileio/primWriter.h +++ b/lib/mayaUsd/fileio/primWriter.h @@ -16,14 +16,12 @@ #ifndef PXRUSDMAYA_PRIM_WRITER_H #define PXRUSDMAYA_PRIM_WRITER_H -#include - -#include -#include -#include +#include +#include +#include -#include #include +#include #include #include #include @@ -31,9 +29,11 @@ #include #include -#include -#include -#include +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE @@ -59,9 +59,9 @@ class UsdMayaPrimWriter /// constructed with an MDagPath. MAYAUSD_CORE_PUBLIC UsdMayaPrimWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); MAYAUSD_CORE_PUBLIC virtual ~UsdMayaPrimWriter(); @@ -135,8 +135,7 @@ class UsdMayaPrimWriter /// The base implementation for DAG prim writers simply maps GetDagPath() /// to GetUsdPath(). For DG prim writers, an empty map is returned. MAYAUSD_CORE_PUBLIC - virtual const UsdMayaUtil::MDagPathMap& - GetDagToUsdPathMapping() const; + virtual const UsdMayaUtil::MDagPathMap& GetDagToUsdPathMapping() const; /// The source Maya DAG path that we are consuming. /// @@ -177,7 +176,7 @@ class UsdMayaPrimWriter MAYAUSD_CORE_PUBLIC UsdUtilsSparseValueWriter* _GetSparseValueWriter(); - UsdPrim _usdPrim; + UsdPrim _usdPrim; UsdMayaWriteJobContext& _writeJobCtx; private: @@ -197,7 +196,7 @@ class UsdMayaPrimWriter /// node prim writers. const MObject _mayaObject; - const SdfPath _usdPath; + const SdfPath _usdPath; const UsdMayaUtil::MDagPathMap _baseDagToUsdPaths; UsdUtilsSparseValueWriter _valueWriter; @@ -208,8 +207,6 @@ class UsdMayaPrimWriter typedef std::shared_ptr UsdMayaPrimWriterSharedPtr; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/primWriterArgs.cpp b/lib/mayaUsd/fileio/primWriterArgs.cpp index 89665b47f6..94a8819baf 100644 --- a/lib/mayaUsd/fileio/primWriterArgs.cpp +++ b/lib/mayaUsd/fileio/primWriterArgs.cpp @@ -15,78 +15,51 @@ // #include "primWriterArgs.h" -#include - #include +#include + PXR_NAMESPACE_OPEN_SCOPE UsdMayaPrimWriterArgs::UsdMayaPrimWriterArgs( - const MDagPath& dagPath, - const bool exportRefsAsInstanceable) : - _dagPath(dagPath), - _exportRefsAsInstanceable(exportRefsAsInstanceable) + const MDagPath& dagPath, + const bool exportRefsAsInstanceable) + : _dagPath(dagPath) + , _exportRefsAsInstanceable(exportRefsAsInstanceable) { } -MObject -UsdMayaPrimWriterArgs::GetMObject() const -{ - return _dagPath.node(); -} +MObject UsdMayaPrimWriterArgs::GetMObject() const { return _dagPath.node(); } -const MDagPath& -UsdMayaPrimWriterArgs::GetMDagPath() const -{ - return _dagPath; -} +const MDagPath& UsdMayaPrimWriterArgs::GetMDagPath() const { return _dagPath; } -bool -UsdMayaPrimWriterArgs::GetExportRefsAsInstanceable() const +bool UsdMayaPrimWriterArgs::GetExportRefsAsInstanceable() const { return _exportRefsAsInstanceable; } -bool -UsdMayaPrimWriterArgs::ReadAttribute( - const std::string& name, - std::string* val) const +bool UsdMayaPrimWriterArgs::ReadAttribute(const std::string& name, std::string* val) const { return UsdMayaWriteUtil::ReadMayaAttribute( - MFnDependencyNode(GetMObject()), - MString(name.c_str()), val); + MFnDependencyNode(GetMObject()), MString(name.c_str()), val); } -bool -UsdMayaPrimWriterArgs::ReadAttribute( - const std::string& name, - VtIntArray* val) const +bool UsdMayaPrimWriterArgs::ReadAttribute(const std::string& name, VtIntArray* val) const { return UsdMayaWriteUtil::ReadMayaAttribute( - MFnDependencyNode(GetMObject()), - MString(name.c_str()), val); + MFnDependencyNode(GetMObject()), MString(name.c_str()), val); } -bool -UsdMayaPrimWriterArgs::ReadAttribute( - const std::string& name, - VtFloatArray* val) const +bool UsdMayaPrimWriterArgs::ReadAttribute(const std::string& name, VtFloatArray* val) const { return UsdMayaWriteUtil::ReadMayaAttribute( - MFnDependencyNode(GetMObject()), - MString(name.c_str()), val); + MFnDependencyNode(GetMObject()), MString(name.c_str()), val); } -bool -UsdMayaPrimWriterArgs::ReadAttribute( - const std::string& name, - VtVec3fArray* val) const +bool UsdMayaPrimWriterArgs::ReadAttribute(const std::string& name, VtVec3fArray* val) const { return UsdMayaWriteUtil::ReadMayaAttribute( - MFnDependencyNode(GetMObject()), - MString(name.c_str()), val); + MFnDependencyNode(GetMObject()), MString(name.c_str()), val); } - PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/primWriterArgs.h b/lib/mayaUsd/fileio/primWriterArgs.h index 603ff9cf62..8fa581a4b3 100644 --- a/lib/mayaUsd/fileio/primWriterArgs.h +++ b/lib/mayaUsd/fileio/primWriterArgs.h @@ -16,14 +16,14 @@ #ifndef PXRUSDMAYA_PRIMWRITERERARGS_H #define PXRUSDMAYA_PRIMWRITERERARGS_H -#include -#include +#include -#include -#include #include +#include +#include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -38,11 +38,9 @@ class UsdMayaPrimWriterArgs { public: MAYAUSD_CORE_PUBLIC - UsdMayaPrimWriterArgs( - const MDagPath& dagPath, - const bool exportRefsAsInstanceable); + UsdMayaPrimWriterArgs(const MDagPath& dagPath, const bool exportRefsAsInstanceable); - /// \brief returns the MObject that should be exported. + /// \brief returns the MObject that should be exported. MAYAUSD_CORE_PUBLIC MObject GetMObject() const; @@ -53,7 +51,7 @@ class UsdMayaPrimWriterArgs bool GetExportRefsAsInstanceable() const; /// helper functions to get data from attribute named \p from the current - /// MObject. + /// MObject. /// \{ MAYAUSD_CORE_PUBLIC bool ReadAttribute(const std::string& name, std::string* val) const; @@ -67,11 +65,9 @@ class UsdMayaPrimWriterArgs private: MDagPath _dagPath; - bool _exportRefsAsInstanceable; + bool _exportRefsAsInstanceable; }; - PXR_NAMESPACE_CLOSE_SCOPE #endif - diff --git a/lib/mayaUsd/fileio/primWriterContext.cpp b/lib/mayaUsd/fileio/primWriterContext.cpp index 4b71ddc0ab..f6342239e2 100644 --- a/lib/mayaUsd/fileio/primWriterContext.cpp +++ b/lib/mayaUsd/fileio/primWriterContext.cpp @@ -18,78 +18,47 @@ PXR_NAMESPACE_OPEN_SCOPE UsdMayaPrimWriterContext::UsdMayaPrimWriterContext( - const UsdTimeCode& timeCode, - const SdfPath& authorPath, - const UsdStageRefPtr& stage) : - _timeCode(timeCode), - _authorPath(authorPath), - _stage(stage), - _exportsGprims(false), - _pruneChildren(false) + const UsdTimeCode& timeCode, + const SdfPath& authorPath, + const UsdStageRefPtr& stage) + : _timeCode(timeCode) + , _authorPath(authorPath) + , _stage(stage) + , _exportsGprims(false) + , _pruneChildren(false) { } -const UsdTimeCode& -UsdMayaPrimWriterContext::GetTimeCode() const -{ - return _timeCode; -} +const UsdTimeCode& UsdMayaPrimWriterContext::GetTimeCode() const { return _timeCode; } -const SdfPath& -UsdMayaPrimWriterContext::GetAuthorPath() const -{ - return _authorPath; -} +const SdfPath& UsdMayaPrimWriterContext::GetAuthorPath() const { return _authorPath; } -UsdStageRefPtr -UsdMayaPrimWriterContext::GetUsdStage() const -{ - return _stage; -} +UsdStageRefPtr UsdMayaPrimWriterContext::GetUsdStage() const { return _stage; } -bool -UsdMayaPrimWriterContext::GetExportsGprims() const -{ - return _exportsGprims; -} +bool UsdMayaPrimWriterContext::GetExportsGprims() const { return _exportsGprims; } -void -UsdMayaPrimWriterContext::SetExportsGprims(bool exportsGprims) +void UsdMayaPrimWriterContext::SetExportsGprims(bool exportsGprims) { _exportsGprims = exportsGprims; } -void -UsdMayaPrimWriterContext::SetPruneChildren(bool pruneChildren) +void UsdMayaPrimWriterContext::SetPruneChildren(bool pruneChildren) { _pruneChildren = pruneChildren; } -bool -UsdMayaPrimWriterContext::GetPruneChildren() const -{ - return _pruneChildren; -} +bool UsdMayaPrimWriterContext::GetPruneChildren() const { return _pruneChildren; } -const SdfPathVector& -UsdMayaPrimWriterContext::GetModelPaths() const -{ - return _modelPaths; -} +const SdfPathVector& UsdMayaPrimWriterContext::GetModelPaths() const { return _modelPaths; } -void -UsdMayaPrimWriterContext::SetModelPaths( - const SdfPathVector& modelPaths) +void UsdMayaPrimWriterContext::SetModelPaths(const SdfPathVector& modelPaths) { _modelPaths = modelPaths; } -void -UsdMayaPrimWriterContext::SetModelPaths( - SdfPathVector&& modelPaths) +void UsdMayaPrimWriterContext::SetModelPaths(SdfPathVector&& modelPaths) { _modelPaths = std::move(modelPaths); } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/primWriterContext.h b/lib/mayaUsd/fileio/primWriterContext.h index d7aae50b60..8433e2d8c2 100644 --- a/lib/mayaUsd/fileio/primWriterContext.h +++ b/lib/mayaUsd/fileio/primWriterContext.h @@ -16,12 +16,12 @@ #ifndef PXRUSDMAYA_PRIMWRITERCONTEXT_H #define PXRUSDMAYA_PRIMWRITERCONTEXT_H +#include + #include #include #include -#include - PXR_NAMESPACE_OPEN_SCOPE /// \class UsdMayaPrimWriterContext @@ -30,38 +30,37 @@ PXR_NAMESPACE_OPEN_SCOPE class UsdMayaPrimWriterContext { public: - MAYAUSD_CORE_PUBLIC UsdMayaPrimWriterContext( - const UsdTimeCode& timeCode, - const SdfPath& authorPath, - const UsdStageRefPtr& stage); + const UsdTimeCode& timeCode, + const SdfPath& authorPath, + const UsdStageRefPtr& stage); /// \brief returns the time frame where data should be authored. MAYAUSD_CORE_PUBLIC const UsdTimeCode& GetTimeCode() const; - /// \brief returns the path where the writer plugin should create + /// \brief returns the path where the writer plugin should create /// a prim. MAYAUSD_CORE_PUBLIC const SdfPath& GetAuthorPath() const; /// \brief returns the usd stage that is being written to. MAYAUSD_CORE_PUBLIC - UsdStageRefPtr GetUsdStage() const; - + UsdStageRefPtr GetUsdStage() const; + /// \brief Returns the value provided by SetExportsGprims(), or \c false - /// if SetExportsGprims() is not called. + /// if SetExportsGprims() is not called. /// /// May be used by export processes to reason about what kind of asset we /// are creating. MAYAUSD_CORE_PUBLIC bool GetExportsGprims() const; - + /// Set the value that will be returned by GetExportsGprims(). /// /// A plugin should set this to \c true if it directly creates any - /// gprims, and should return the same value each time its write() + /// gprims, and should return the same value each time its write() /// function is invoked. /// /// \sa GetExportsGprims() @@ -110,15 +109,13 @@ class UsdMayaPrimWriterContext private: const UsdTimeCode& _timeCode; - const SdfPath& _authorPath; - UsdStageRefPtr _stage; - bool _exportsGprims; - bool _pruneChildren; - SdfPathVector _modelPaths; + const SdfPath& _authorPath; + UsdStageRefPtr _stage; + bool _exportsGprims; + bool _pruneChildren; + SdfPathVector _modelPaths; }; - PXR_NAMESPACE_CLOSE_SCOPE #endif - diff --git a/lib/mayaUsd/fileio/primWriterRegistry.cpp b/lib/mayaUsd/fileio/primWriterRegistry.cpp index 437fc09712..dcbe690acc 100644 --- a/lib/mayaUsd/fileio/primWriterRegistry.cpp +++ b/lib/mayaUsd/fileio/primWriterRegistry.cpp @@ -15,60 +15,50 @@ // #include "primWriterRegistry.h" -#include -#include -#include +#include +#include +#include -#include #include #include #include #include #include #include +#include -#include -#include -#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PRIVATE_TOKENS(_tokens, - (UsdMaya) - (PrimWriter) -); +TF_DEFINE_PRIVATE_TOKENS(_tokens, (UsdMaya)(PrimWriter)); typedef std::map _Registry; -static _Registry _reg; - +static _Registry _reg; /* static */ -void -UsdMayaPrimWriterRegistry::Register( - const std::string& mayaTypeName, - UsdMayaPrimWriterRegistry::WriterFactoryFn fn) +void UsdMayaPrimWriterRegistry::Register( + const std::string& mayaTypeName, + UsdMayaPrimWriterRegistry::WriterFactoryFn fn) { - TF_DEBUG(PXRUSDMAYA_REGISTRY).Msg( - "Registering UsdMayaPrimWriter for maya type %s.\n", - mayaTypeName.c_str()); + TF_DEBUG(PXRUSDMAYA_REGISTRY) + .Msg("Registering UsdMayaPrimWriter for maya type %s.\n", mayaTypeName.c_str()); - std::pair< _Registry::iterator, bool> insertStatus = - _reg.insert(std::make_pair(mayaTypeName, fn)); + std::pair<_Registry::iterator, bool> insertStatus + = _reg.insert(std::make_pair(mayaTypeName, fn)); if (insertStatus.second) { - UsdMaya_RegistryHelper::AddUnloader([mayaTypeName]() { - _reg.erase(mayaTypeName); - }); - } - else { + UsdMaya_RegistryHelper::AddUnloader([mayaTypeName]() { _reg.erase(mayaTypeName); }); + } else { TF_CODING_ERROR("Multiple writers for type %s", mayaTypeName.c_str()); } } /* static */ -void -UsdMayaPrimWriterRegistry::RegisterRaw( - const std::string& mayaTypeName, - UsdMayaPrimWriterRegistry::WriterFn fn) +void UsdMayaPrimWriterRegistry::RegisterRaw( + const std::string& mayaTypeName, + UsdMayaPrimWriterRegistry::WriterFn fn) { Register(mayaTypeName, UsdMaya_FunctorPrimWriter::CreateFactory(fn)); } @@ -86,23 +76,20 @@ UsdMayaPrimWriterRegistry::Find(const std::string& mayaTypeName) return ret; } - static const TfTokenVector SCOPE = { - _tokens->UsdMaya, - _tokens->PrimWriter - }; + static const TfTokenVector SCOPE = { _tokens->UsdMaya, _tokens->PrimWriter }; UsdMaya_RegistryHelper::FindAndLoadMayaPlug(SCOPE, mayaTypeName); // ideally something just registered itself. if not, we at least put it in // the registry in case we encounter it again. if (!TfMapLookup(_reg, mayaTypeName, &ret)) { - TF_DEBUG(PXRUSDMAYA_REGISTRY).Msg( - "No usdMaya writer plugin for maya type %s. No maya plugin found.\n", - mayaTypeName.c_str()); + TF_DEBUG(PXRUSDMAYA_REGISTRY) + .Msg( + "No usdMaya writer plugin for maya type %s. No maya plugin found.\n", + mayaTypeName.c_str()); _reg[mayaTypeName] = nullptr; } return ret; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/primWriterRegistry.h b/lib/mayaUsd/fileio/primWriterRegistry.h index ab1381bd33..0b7625385f 100644 --- a/lib/mayaUsd/fileio/primWriterRegistry.h +++ b/lib/mayaUsd/fileio/primWriterRegistry.h @@ -16,19 +16,19 @@ #ifndef PXRUSDMAYA_PRIM_WRITER_REGISTRY_H #define PXRUSDMAYA_PRIM_WRITER_REGISTRY_H -#include -#include - -#include - -#include -#include - #include #include #include #include +#include +#include + +#include + +#include +#include + PXR_NAMESPACE_OPEN_SCOPE /// \class UsdMayaPrimWriterRegistry @@ -66,17 +66,16 @@ struct UsdMayaPrimWriterRegistry { /// Writer factory function, i.e. a function that creates a prim writer /// for the given Maya node/USD paths and context. - typedef std::function< UsdMayaPrimWriterSharedPtr ( - const MFnDependencyNode&, - const SdfPath&, - UsdMayaWriteJobContext&) > WriterFactoryFn; + typedef std::function + WriterFactoryFn; /// Writer function, i.e. a function that writes a prim. This is the /// signature of the function defined by the PXRUSDMAYA_DEFINE_WRITER /// macro. - typedef std::function< bool ( - const UsdMayaPrimWriterArgs&, - UsdMayaPrimWriterContext*) > WriterFn; + typedef std::function WriterFn; /// \brief Register \p fn as a factory function providing a /// UsdMayaPrimWriter subclass that can be used to write \p mayaType. @@ -127,25 +126,18 @@ struct UsdMayaPrimWriterRegistry /// return true; /// } /// \endcode -#define PXRUSDMAYA_DEFINE_WRITER(mayaTypeName, argsVarName, ctxVarName) \ -struct UsdMayaWriterDummy_##mayaTypeName { }; \ -static \ -bool \ -UsdMaya_PrimWriter_##mayaTypeName( \ - const UsdMayaPrimWriterArgs&, \ - UsdMayaPrimWriterContext*); \ -TF_REGISTRY_FUNCTION_WITH_TAG( \ - UsdMayaPrimWriterRegistry, \ - UsdMayaWriterDummy_##mayaTypeName) \ -{ \ - UsdMayaPrimWriterRegistry::RegisterRaw( \ - #mayaTypeName, \ - UsdMaya_PrimWriter_##mayaTypeName); \ -} \ -bool \ -UsdMaya_PrimWriter_##mayaTypeName( \ - const UsdMayaPrimWriterArgs& argsVarName, \ - UsdMayaPrimWriterContext* ctxVarName) +#define PXRUSDMAYA_DEFINE_WRITER(mayaTypeName, argsVarName, ctxVarName) \ + struct UsdMayaWriterDummy_##mayaTypeName \ + { \ + }; \ + static bool UsdMaya_PrimWriter_##mayaTypeName( \ + const UsdMayaPrimWriterArgs&, UsdMayaPrimWriterContext*); \ + TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaPrimWriterRegistry, UsdMayaWriterDummy_##mayaTypeName) \ + { \ + UsdMayaPrimWriterRegistry::RegisterRaw(#mayaTypeName, UsdMaya_PrimWriter_##mayaTypeName); \ + } \ + bool UsdMaya_PrimWriter_##mayaTypeName( \ + const UsdMayaPrimWriterArgs& argsVarName, UsdMayaPrimWriterContext* ctxVarName) /// \brief Registers a pre-existing writer class for the given Maya type; /// the writer class should be a subclass of UsdMayaPrimWriter with a three-place @@ -164,23 +156,18 @@ UsdMaya_PrimWriter_##mayaTypeName( \ /// }; /// PXRUSDMAYA_REGISTER_WRITER(myCustomMayaNode, MyWriter); /// \endcode -#define PXRUSDMAYA_REGISTER_WRITER(mayaTypeName, writerClass) \ -TF_REGISTRY_FUNCTION_WITH_TAG( \ - UsdMayaPrimWriterRegistry, \ - mayaTypeName##_##writerClass) \ -{ \ - UsdMayaPrimWriterRegistry::Register( \ - #mayaTypeName, \ - []( \ - const MFnDependencyNode& depNodeFn, \ - const SdfPath& usdPath, \ - UsdMayaWriteJobContext& jobCtx) { \ - return std::make_shared(depNodeFn, usdPath, jobCtx); \ - }); \ -} - +#define PXRUSDMAYA_REGISTER_WRITER(mayaTypeName, writerClass) \ + TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaPrimWriterRegistry, mayaTypeName##_##writerClass) \ + { \ + UsdMayaPrimWriterRegistry::Register( \ + #mayaTypeName, \ + [](const MFnDependencyNode& depNodeFn, \ + const SdfPath& usdPath, \ + UsdMayaWriteJobContext& jobCtx) { \ + return std::make_shared(depNodeFn, usdPath, jobCtx); \ + }); \ + } PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/registryHelper.cpp b/lib/mayaUsd/fileio/registryHelper.cpp index e5a7a61157..00049c21f5 100644 --- a/lib/mayaUsd/fileio/registryHelper.cpp +++ b/lib/mayaUsd/fileio/registryHelper.cpp @@ -15,10 +15,7 @@ // #include "registryHelper.h" -#include -#include - -#include +#include #include #include @@ -28,20 +25,16 @@ #include #include -#include +#include + +#include +#include PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PRIVATE_TOKENS(_tokens, - (mayaPlugin) - (providesTranslator) - (UsdMaya) - (ShadingModePlugin) -); +TF_DEFINE_PRIVATE_TOKENS(_tokens, (mayaPlugin)(providesTranslator)(UsdMaya)(ShadingModePlugin)); -template -bool -_GetData(const JsValue& any, T* val) +template bool _GetData(const JsValue& any, T* val) { if (!any.Is()) { TF_CODING_ERROR("bad plugInfo.json"); @@ -52,9 +45,7 @@ _GetData(const JsValue& any, T* val) return true; } -template -bool -_GetData(const JsValue& any, std::vector* val) +template bool _GetData(const JsValue& any, std::vector* val) { if (!any.IsArrayOf()) { TF_CODING_ERROR("bad plugInfo.json"); @@ -65,16 +56,13 @@ _GetData(const JsValue& any, std::vector* val) return true; } -static bool -_ReadNestedDict( - const JsObject& data, - const std::vector& keys, - JsObject* dict) +static bool _ReadNestedDict(const JsObject& data, const std::vector& keys, JsObject* dict) { JsObject currDict = data; - TF_FOR_ALL(iter, keys) { + TF_FOR_ALL(iter, keys) + { const TfToken& currKey = *iter; - JsValue any; + JsValue any; if (!TfMapLookup(currDict, currKey, &any)) { return false; } @@ -89,12 +77,11 @@ _ReadNestedDict( return true; } -static bool -_ProvidesForType( - const PlugPluginPtr& plug, - const std::vector& scope, - const std::string& typeName, - std::string* mayaPluginName) +static bool _ProvidesForType( + const PlugPluginPtr& plug, + const std::vector& scope, + const std::string& typeName, + std::string* mayaPluginName) { JsObject metadata = plug->GetMetadata(); @@ -112,9 +99,7 @@ _ProvidesForType( return false; } - bool provides = std::find( - usdTypes.begin(), usdTypes.end(), - typeName) != usdTypes.end(); + bool provides = std::find(usdTypes.begin(), usdTypes.end(), typeName) != usdTypes.end(); if (provides) { if (TfMapLookup(mayaTranslatorMetadata, _tokens->mayaPlugin, &any)) { return _GetData(any, mayaPluginName); @@ -124,11 +109,10 @@ _ProvidesForType( return provides; } -static bool -_HasShadingModePlugin( - const PlugPluginPtr& plug, +static bool _HasShadingModePlugin( + const PlugPluginPtr& plug, const std::vector& scope, - std::string* mayaPluginName) + std::string* mayaPluginName) { JsObject metadata = plug->GetMetadata(); JsObject mayaTranslatorMetadata; @@ -145,50 +129,45 @@ _HasShadingModePlugin( } /* static */ -std::string -_PluginDictScopeToDebugString( - const std::vector& scope) +std::string _PluginDictScopeToDebugString(const std::vector& scope) { std::vector s; - TF_FOR_ALL(iter, scope) { - s.push_back(iter->GetString()); - } + TF_FOR_ALL(iter, scope) { s.push_back(iter->GetString()); } return TfStringJoin(s, "/"); } /* static */ -void -UsdMaya_RegistryHelper::FindAndLoadMayaPlug( - const std::vector& scope, - const std::string& value) +void UsdMaya_RegistryHelper::FindAndLoadMayaPlug( + const std::vector& scope, + const std::string& value) { - std::string mayaPlugin; + std::string mayaPlugin; PlugPluginPtrVector plugins = PlugRegistry::GetInstance().GetAllPlugins(); - TF_FOR_ALL(plugIter, plugins) { + TF_FOR_ALL(plugIter, plugins) + { PlugPluginPtr plug = *plugIter; if (_ProvidesForType(plug, scope, value, &mayaPlugin)) { if (!mayaPlugin.empty()) { - TF_DEBUG(PXRUSDMAYA_REGISTRY).Msg( - "Found usdMaya plugin %s: %s = %s. Loading maya plugin %s.\n", + TF_DEBUG(PXRUSDMAYA_REGISTRY) + .Msg( + "Found usdMaya plugin %s: %s = %s. Loading maya plugin %s.\n", plug->GetName().c_str(), _PluginDictScopeToDebugString(scope).c_str(), value.c_str(), mayaPlugin.c_str()); - std::string loadPluginCmd = TfStringPrintf( - "loadPlugin -quiet %s", mayaPlugin.c_str()); + std::string loadPluginCmd + = TfStringPrintf("loadPlugin -quiet %s", mayaPlugin.c_str()); if (MGlobal::executeCommand(loadPluginCmd.c_str())) { // Need to ensure Python script modules are loaded // properly for this library (Maya's loadPlugin will not // load script modules like TfDlopen would). TfScriptModuleLoader::GetInstance().LoadModules(); + } else { + TF_CODING_ERROR("Unable to load mayaplugin %s\n", mayaPlugin.c_str()); } - else { - TF_CODING_ERROR("Unable to load mayaplugin %s\n", - mayaPlugin.c_str()); - } - } - else { - TF_DEBUG(PXRUSDMAYA_REGISTRY).Msg( + } else { + TF_DEBUG(PXRUSDMAYA_REGISTRY) + .Msg( "Found %s usdMaya plugin %s: %s = %s. No maya plugin.\n", plug->IsLoaded() ? "loaded" : "unloaded", plug->GetName().c_str(), @@ -207,30 +186,31 @@ UsdMaya_RegistryHelper::FindAndLoadMayaPlug( } /* static */ -void -UsdMaya_RegistryHelper::LoadShadingModePlugins() { - static std::once_flag _shadingModesLoaded; - static std::vector scope = {_tokens->UsdMaya, _tokens->ShadingModePlugin}; - std::call_once(_shadingModesLoaded, [](){ +void UsdMaya_RegistryHelper::LoadShadingModePlugins() +{ + static std::once_flag _shadingModesLoaded; + static std::vector scope = { _tokens->UsdMaya, _tokens->ShadingModePlugin }; + std::call_once(_shadingModesLoaded, []() { PlugPluginPtrVector plugins = PlugRegistry::GetInstance().GetAllPlugins(); - std::string mayaPlugin; - TF_FOR_ALL(plugIter, plugins) { + std::string mayaPlugin; + TF_FOR_ALL(plugIter, plugins) + { PlugPluginPtr plug = *plugIter; if (_HasShadingModePlugin(plug, scope, &mayaPlugin) && !mayaPlugin.empty()) { - TF_DEBUG(PXRUSDMAYA_REGISTRY).Msg( - "Found usdMaya plugin %s: Loading maya plugin %s.\n", - plug->GetName().c_str(), - mayaPlugin.c_str()); - std::string loadPluginCmd = TfStringPrintf( - "loadPlugin -quiet %s", mayaPlugin.c_str()); + TF_DEBUG(PXRUSDMAYA_REGISTRY) + .Msg( + "Found usdMaya plugin %s: Loading maya plugin %s.\n", + plug->GetName().c_str(), + mayaPlugin.c_str()); + std::string loadPluginCmd + = TfStringPrintf("loadPlugin -quiet %s", mayaPlugin.c_str()); if (MGlobal::executeCommand(loadPluginCmd.c_str())) { // Need to ensure Python script modules are loaded // properly for this library (Maya's loadPlugin will not // load script modules like TfDlopen would). TfScriptModuleLoader::GetInstance().LoadModules(); } else { - TF_CODING_ERROR("Unable to load mayaplugin %s\n", - mayaPlugin.c_str()); + TF_CODING_ERROR("Unable to load mayaplugin %s\n", mayaPlugin.c_str()); } } } @@ -238,9 +218,7 @@ UsdMaya_RegistryHelper::LoadShadingModePlugins() { } /* static */ -VtDictionary -UsdMaya_RegistryHelper::GetComposedInfoDictionary( - const std::vector& scope) +VtDictionary UsdMaya_RegistryHelper::GetComposedInfoDictionary(const std::vector& scope) { VtDictionary result; @@ -249,34 +227,32 @@ UsdMaya_RegistryHelper::GetComposedInfoDictionary( for (const PlugPluginPtr& plugin : plugins) { JsObject curJsDict; if (_ReadNestedDict(plugin->GetMetadata(), scope, &curJsDict)) { - const VtValue curValue = - JsConvertToContainerType(curJsDict); + const VtValue curValue = JsConvertToContainerType(curJsDict); if (curValue.IsHolding()) { for (const std::pair& pair : - curValue.UncheckedGet()) { + curValue.UncheckedGet()) { result[pair.first] = pair.second; keyDefinitionSites[pair.first].push_back(plugin->GetName()); } - } - else { - TF_RUNTIME_ERROR("Unable to read scope '%s' from plugInfo for " - "plugin '%s'", - TfStringJoin(scope.begin(), scope.end(), "/").c_str(), - plugin->GetName().c_str()); + } else { + TF_RUNTIME_ERROR( + "Unable to read scope '%s' from plugInfo for " + "plugin '%s'", + TfStringJoin(scope.begin(), scope.end(), "/").c_str(), + plugin->GetName().c_str()); } } } // Validate that keys are only defined once globally. - for (const std::pair>& pair : - keyDefinitionSites) { + for (const std::pair>& pair : keyDefinitionSites) { if (pair.second.size() != 1) { TF_RUNTIME_ERROR( - "Key '%s' is defined in multiple plugins (%s). " - "Key values must be defined in only one plugin at a time. " - "Plugin values will be ignored for this key.", - pair.first.c_str(), - TfStringJoin(pair.second, ", ").c_str()); + "Key '%s' is defined in multiple plugins (%s). " + "Key values must be defined in only one plugin at a time. " + "Plugin values will be ignored for this key.", + pair.first.c_str(), + TfStringJoin(pair.second, ", ").c_str()); result.erase(pair.first); } } @@ -285,8 +261,7 @@ UsdMaya_RegistryHelper::GetComposedInfoDictionary( } /* static */ -void -UsdMaya_RegistryHelper::AddUnloader(const std::function& func) +void UsdMaya_RegistryHelper::AddUnloader(const std::function& func) { if (TfRegistryManager::GetInstance().AddFunctionForUnload(func)) { // It is likely that the registering plugin library is opened/closed @@ -294,13 +269,10 @@ UsdMaya_RegistryHelper::AddUnloader(const std::function& func) // unloaders won't be invoked unless we use RunUnloadersAtExit(), // which allows unloaders to be called from normal dlclose(). TfRegistryManager::GetInstance().RunUnloadersAtExit(); - } - else { - TF_CODING_ERROR( - "Couldn't add unload function (was this function called from " - "outside a TF_REGISTRY_FUNCTION block?)"); + } else { + TF_CODING_ERROR("Couldn't add unload function (was this function called from " + "outside a TF_REGISTRY_FUNCTION block?)"); } } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/registryHelper.h b/lib/mayaUsd/fileio/registryHelper.h index 278fe22f78..8cd2f62d01 100644 --- a/lib/mayaUsd/fileio/registryHelper.h +++ b/lib/mayaUsd/fileio/registryHelper.h @@ -16,19 +16,19 @@ #ifndef PXRUSDMAYA_REGISTRYHELPER_H #define PXRUSDMAYA_REGISTRYHELPER_H -#include - -#include #include #include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE /// private helper so that both reader/writer registries can share the same /// plugin discovery/load mechanism. -struct UsdMaya_RegistryHelper +struct UsdMaya_RegistryHelper { - /// searches plugInfo's for \p value at the specified \p scope. + /// searches plugInfo's for \p value at the specified \p scope. /// /// The scope are the nested keys to search through in the plugInfo (for /// example, ["UsdMaya", "PrimReader"]. @@ -46,13 +46,10 @@ struct UsdMaya_RegistryHelper /// "providesTranslator" and "mayaPlugin". If \p value matches the /// something in the "providesTranslator" list, it will proceed to try to /// load the "mayaPlugin". - static void - FindAndLoadMayaPlug( - const std::vector& scope, - const std::string& value); + static void FindAndLoadMayaPlug(const std::vector& scope, const std::string& value); /// Searches the plugInfos and looks for ShadingModePlugin. - /// + /// /// "UsdMaya" : { /// "ShadingModePlugin" : { /// "mayaPlugin" : "arnoldShaderExporter" @@ -61,11 +58,10 @@ struct UsdMaya_RegistryHelper /// /// At that scope, it expects a dictionary with one key: "mayaPlugin". /// usdMaya will try to load the "mayaPlugin" when shading modes are first accessed. - static void - LoadShadingModePlugins(); + static void LoadShadingModePlugins(); /// Searches the plugInfos for metadata dictionaries at the given \p scope, - /// and composes them together. + /// and composes them together. /// The scope are the nested keys to search through in the plugInfo (for /// example, ["UsdMaya", "UsdExport"]). /// The same key under the \p scope must not be defined in multiple @@ -75,8 +71,7 @@ struct UsdMaya_RegistryHelper /// XXX We might relax the restriction on multiply-defined keys later on /// if there is a need to define values at different scopes, e.g. /// site-specific, department-specific, show-specific values. - static VtDictionary GetComposedInfoDictionary( - const std::vector& scope); + static VtDictionary GetComposedInfoDictionary(const std::vector& scope); static void AddUnloader(const std::function& func); }; diff --git a/lib/mayaUsd/fileio/shaderReader.cpp b/lib/mayaUsd/fileio/shaderReader.cpp index 1090739182..42897b3467 100644 --- a/lib/mayaUsd/fileio/shaderReader.cpp +++ b/lib/mayaUsd/fileio/shaderReader.cpp @@ -47,7 +47,7 @@ MPlug UsdMayaShaderReader::GetMayaPlugForUsdAttrName( const TfToken& usdAttrName, const MObject& mayaObject) const { - MStatus status; + MStatus status; MFnDependencyNode depFn(mayaObject, &status); if (status != MS::kSuccess) { return MPlug(); diff --git a/lib/mayaUsd/fileio/shaderReader.h b/lib/mayaUsd/fileio/shaderReader.h index 725919c675..12c1ac7010 100644 --- a/lib/mayaUsd/fileio/shaderReader.h +++ b/lib/mayaUsd/fileio/shaderReader.h @@ -32,7 +32,8 @@ class TfToken; class UsdMayaPrimReaderArgs; /// Base class for USD prim readers that import USD shader prims as Maya shading nodes. -class UsdMayaShaderReader : public UsdMayaPrimReader { +class UsdMayaShaderReader : public UsdMayaPrimReader +{ public: MAYAUSD_CORE_PUBLIC UsdMayaShaderReader(const UsdMayaPrimReaderArgs&); @@ -43,7 +44,12 @@ class UsdMayaShaderReader : public UsdMayaPrimReader { /// report `Fallback`, while a specialized reader that really shines in a /// given context should report `Supported` when the context is right and /// `Unsupported` if the context is not as expected. - enum class ContextSupport { Supported, Fallback, Unsupported }; + enum class ContextSupport + { + Supported, + Fallback, + Unsupported + }; /// This static function is expected for all shader readers and allows /// declaring how well this class can support the current context: diff --git a/lib/mayaUsd/fileio/shaderReaderRegistry.cpp b/lib/mayaUsd/fileio/shaderReaderRegistry.cpp index b5d3f90bef..9cde3702a6 100644 --- a/lib/mayaUsd/fileio/shaderReaderRegistry.cpp +++ b/lib/mayaUsd/fileio/shaderReaderRegistry.cpp @@ -34,26 +34,22 @@ PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PRIVATE_TOKENS( - _tokens, - (UsdMaya) - (ShaderReader) -); +TF_DEFINE_PRIVATE_TOKENS(_tokens, (UsdMaya)(ShaderReader)); namespace { -struct _RegistryEntry { +struct _RegistryEntry +{ UsdMayaShaderReaderRegistry::ContextPredicateFn _pred; UsdMayaShaderReaderRegistry::ReaderFactoryFn _fn; int _index; }; typedef std::unordered_multimap _Registry; -static _Registry _reg; -static int _indexCounter = 0; +static _Registry _reg; +static int _indexCounter = 0; -_Registry::const_iterator _Find( - const TfToken& usdInfoId, - const UsdMayaJobImportArgs& importArgs) { +_Registry::const_iterator _Find(const TfToken& usdInfoId, const UsdMayaJobImportArgs& importArgs) +{ using ContextSupport = UsdMayaShaderReader::ContextSupport; _Registry::const_iterator ret = _reg.cend(); @@ -87,11 +83,11 @@ void UsdMayaShaderReaderRegistry::Register( usdInfoId.GetText(), index); - _reg.insert(std::make_pair(usdInfoId, _RegistryEntry{pred, fn, index})); + _reg.insert(std::make_pair(usdInfoId, _RegistryEntry { pred, fn, index })); // The unloader uses the index to know which entry to erase when there are // more than one for the same usdInfoId. - UsdMaya_RegistryHelper::AddUnloader([usdInfoId, index]() { + UsdMaya_RegistryHelper::AddUnloader([usdInfoId, index]() { _Registry::const_iterator it, itEnd; std::tie(it, itEnd) = _reg.equal_range(usdInfoId); for (; it != itEnd; ++it) { @@ -104,15 +100,14 @@ void UsdMayaShaderReaderRegistry::Register( } /* static */ -UsdMayaShaderReaderRegistry::ReaderFactoryFn UsdMayaShaderReaderRegistry::Find( - const TfToken& usdInfoId, - const UsdMayaJobImportArgs& importArgs) +UsdMayaShaderReaderRegistry::ReaderFactoryFn +UsdMayaShaderReaderRegistry::Find(const TfToken& usdInfoId, const UsdMayaJobImportArgs& importArgs) { using ContextSupport = UsdMayaShaderReader::ContextSupport; TfRegistryManager::GetInstance().SubscribeTo(); _Registry::const_iterator it = _Find(usdInfoId, importArgs); - + if (it != _reg.end()) { return it->second._fn; } diff --git a/lib/mayaUsd/fileio/shaderReaderRegistry.h b/lib/mayaUsd/fileio/shaderReaderRegistry.h index a462bb44ab..14aef4e864 100644 --- a/lib/mayaUsd/fileio/shaderReaderRegistry.h +++ b/lib/mayaUsd/fileio/shaderReaderRegistry.h @@ -57,7 +57,8 @@ PXR_NAMESPACE_OPEN_SCOPE /// and for any user-defined plugin types. If UsdMaya does not ship with a /// reader plugin for some Maya built-in type, you can register your own /// plugin for that Maya built-in type. -struct UsdMayaShaderReaderRegistry { +struct UsdMayaShaderReaderRegistry +{ /// Predicate function, i.e. a function that can tell the level of support /// the reader function will provide for a given context. using ContextPredicateFn @@ -95,9 +96,7 @@ struct UsdMayaShaderReaderRegistry { /// /// If there is no supported reader plugin for \p usdInfoId, returns nullptr. MAYAUSD_CORE_PUBLIC - static ReaderFactoryFn Find( - const TfToken& usdInfoId, - const UsdMayaJobImportArgs& importArgs); + static ReaderFactoryFn Find(const TfToken& usdInfoId, const UsdMayaJobImportArgs& importArgs); }; /// \brief Registers a pre-existing reader class for the given USD info:id; diff --git a/lib/mayaUsd/fileio/shaderWriter.cpp b/lib/mayaUsd/fileio/shaderWriter.cpp index 8b19b98d18..c54409a70e 100644 --- a/lib/mayaUsd/fileio/shaderWriter.cpp +++ b/lib/mayaUsd/fileio/shaderWriter.cpp @@ -15,7 +15,7 @@ // #include "shaderWriter.h" -#include +#include #include #include @@ -23,33 +23,28 @@ #include #include -#include +#include PXR_NAMESPACE_OPEN_SCOPE UsdMayaShaderWriter::UsdMayaShaderWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) { } /* virtual */ -TfToken -UsdMayaShaderWriter::GetShadingAttributeNameForMayaAttrName( - const TfToken& mayaAttrName) +TfToken UsdMayaShaderWriter::GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) { return TfToken(); } /* virtual */ -UsdAttribute -UsdMayaShaderWriter::GetShadingAttributeForMayaAttrName( - const TfToken& mayaAttrName) +UsdAttribute UsdMayaShaderWriter::GetShadingAttributeForMayaAttrName(const TfToken& mayaAttrName) { - const TfToken attrName = - GetShadingAttributeNameForMayaAttrName(mayaAttrName); + const TfToken attrName = GetShadingAttributeNameForMayaAttrName(mayaAttrName); if (attrName.IsEmpty()) { return UsdAttribute(); } @@ -57,5 +52,4 @@ UsdMayaShaderWriter::GetShadingAttributeForMayaAttrName( return _usdPrim.GetAttribute(attrName); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/shaderWriter.h b/lib/mayaUsd/fileio/shaderWriter.h index 3782d0725f..18726d5760 100644 --- a/lib/mayaUsd/fileio/shaderWriter.h +++ b/lib/mayaUsd/fileio/shaderWriter.h @@ -16,17 +16,17 @@ #ifndef PXRUSDMAYA_SHADER_WRITER_H #define PXRUSDMAYA_SHADER_WRITER_H -#include - -#include +#include +#include +#include -#include #include +#include #include -#include -#include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE @@ -36,63 +36,64 @@ class UsdAttribute; /// shader prims. class UsdMayaShaderWriter : public UsdMayaPrimWriter { - public: - MAYAUSD_CORE_PUBLIC - UsdMayaShaderWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); - - /// The level of support a writer can offer for a given context - /// - /// A basic writer that gives correct results across most contexts should - /// report `Fallback`, while a specialized writer that really shines in a - /// given context should report `Supported` when the context is right and - /// `Unsupported` if the context is not as expected. - enum class ContextSupport { Supported, Fallback, Unsupported }; - - /// A static function is expected for all shader writers and allows - /// declaring how well this class can support the current context. - /// - /// The prototype is: - /// - /// static ContextSupport CanExport(const UsdMayaJobExportArgs& exportArgs); - - /// Get the name of the USD shading attribute that corresponds to the - /// Maya attribute named \p mayaAttrName. - /// - /// The attribute name should be the fully namespaced name in USD (e.g. - /// "inputs:myInputAttribute" or "outputs:myOutputAttribute" for shader - /// input and output attributes, respectively). - /// - /// The default implementation always returns an empty token, which - /// effectively prevents any connections from being authored to or from - /// the exported prims in USD. Derived classes should override this and - /// return the corresponding attribute names for the Maya attributes - /// that should be considered for connections. - MAYAUSD_CORE_PUBLIC - virtual TfToken GetShadingAttributeNameForMayaAttrName( - const TfToken& mayaAttrName); - - /// Get the USD shading attribute that corresponds to the Maya attribute - /// named \p mayaAttrName. - /// - /// The default implementation calls - /// GetShadingAttributeNameForMayaAttrName() with the given - /// \p mayaAttrName and then attempts to get the USD attribute with that - /// name from the shader writer's USD prim. Note that this means this - /// method will only return valid USD attribute that the shader writer - /// has already authored on its privately held UsdPrim, so this method - /// should only be called after Write() has been called at least once. - MAYAUSD_CORE_PUBLIC - virtual UsdAttribute GetShadingAttributeForMayaAttrName( - const TfToken& mayaAttrName); +public: + MAYAUSD_CORE_PUBLIC + UsdMayaShaderWriter( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); + + /// The level of support a writer can offer for a given context + /// + /// A basic writer that gives correct results across most contexts should + /// report `Fallback`, while a specialized writer that really shines in a + /// given context should report `Supported` when the context is right and + /// `Unsupported` if the context is not as expected. + enum class ContextSupport + { + Supported, + Fallback, + Unsupported + }; + + /// A static function is expected for all shader writers and allows + /// declaring how well this class can support the current context. + /// + /// The prototype is: + /// + /// static ContextSupport CanExport(const UsdMayaJobExportArgs& exportArgs); + + /// Get the name of the USD shading attribute that corresponds to the + /// Maya attribute named \p mayaAttrName. + /// + /// The attribute name should be the fully namespaced name in USD (e.g. + /// "inputs:myInputAttribute" or "outputs:myOutputAttribute" for shader + /// input and output attributes, respectively). + /// + /// The default implementation always returns an empty token, which + /// effectively prevents any connections from being authored to or from + /// the exported prims in USD. Derived classes should override this and + /// return the corresponding attribute names for the Maya attributes + /// that should be considered for connections. + MAYAUSD_CORE_PUBLIC + virtual TfToken GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName); + + /// Get the USD shading attribute that corresponds to the Maya attribute + /// named \p mayaAttrName. + /// + /// The default implementation calls + /// GetShadingAttributeNameForMayaAttrName() with the given + /// \p mayaAttrName and then attempts to get the USD attribute with that + /// name from the shader writer's USD prim. Note that this means this + /// method will only return valid USD attribute that the shader writer + /// has already authored on its privately held UsdPrim, so this method + /// should only be called after Write() has been called at least once. + MAYAUSD_CORE_PUBLIC + virtual UsdAttribute GetShadingAttributeForMayaAttrName(const TfToken& mayaAttrName); }; typedef std::shared_ptr UsdMayaShaderWriterSharedPtr; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/shaderWriterRegistry.cpp b/lib/mayaUsd/fileio/shaderWriterRegistry.cpp index a6d7011c3d..c04f2b97ea 100644 --- a/lib/mayaUsd/fileio/shaderWriterRegistry.cpp +++ b/lib/mayaUsd/fileio/shaderWriterRegistry.cpp @@ -27,8 +27,8 @@ #include #include -#include #include +#include #include PXR_NAMESPACE_OPEN_SCOPE @@ -36,12 +36,11 @@ PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PRIVATE_TOKENS( _tokens, - (UsdMaya) - (ShaderWriter) -); + (UsdMaya)(ShaderWriter)); namespace { -struct _RegistryEntry { +struct _RegistryEntry +{ UsdMayaShaderWriterRegistry::ContextPredicateFn _pred; UsdMayaShaderWriterRegistry::WriterFactoryFn _writer; int _index; @@ -49,11 +48,10 @@ struct _RegistryEntry { using _Registry = std::unordered_multimap; static _Registry _reg; -static int _indexCounter = 0; +static int _indexCounter = 0; -_Registry::const_iterator _Find( - const TfToken& usdInfoId, - const UsdMayaJobExportArgs& exportArgs) { +_Registry::const_iterator _Find(const TfToken& usdInfoId, const UsdMayaJobExportArgs& exportArgs) +{ using ContextSupport = UsdMayaShaderWriter::ContextSupport; _Registry::const_iterator ret = _reg.cend(); @@ -104,13 +102,14 @@ void UsdMayaShaderWriterRegistry::Register( } /* static */ -UsdMayaShaderWriterRegistry::WriterFactoryFn -UsdMayaShaderWriterRegistry::Find(const TfToken& mayaTypeName, const UsdMayaJobExportArgs& exportArgs) +UsdMayaShaderWriterRegistry::WriterFactoryFn UsdMayaShaderWriterRegistry::Find( + const TfToken& mayaTypeName, + const UsdMayaJobExportArgs& exportArgs) { TfRegistryManager::GetInstance().SubscribeTo(); _Registry::const_iterator it = _Find(mayaTypeName, exportArgs); - + if (it != _reg.end()) { return it->second._writer; } diff --git a/lib/mayaUsd/fileio/shaderWriterRegistry.h b/lib/mayaUsd/fileio/shaderWriterRegistry.h index 653a268f74..0bd0a8547b 100644 --- a/lib/mayaUsd/fileio/shaderWriterRegistry.h +++ b/lib/mayaUsd/fileio/shaderWriterRegistry.h @@ -60,7 +60,8 @@ PXR_NAMESPACE_OPEN_SCOPE /// and for any user-defined plugin types. If mayaUSD does not ship with a /// writer plugin for some Maya built-in type, you can register your own /// plugin for that Maya built-in type. -struct UsdMayaShaderWriterRegistry { +struct UsdMayaShaderWriterRegistry +{ /// Writer factory function, i.e. a function that creates a shader writer /// for the given Maya node/USD paths and context. using WriterFactoryFn = std::function class HasCanExport { +template class HasCanExport +{ typedef char _One; - struct _Two { + struct _Two + { char _x[2]; }; @@ -101,7 +104,10 @@ template class HasCanExport { template static _Two _Test(...); public: - enum { value = sizeof(_Test(0)) == sizeof(char) }; + enum + { + value = sizeof(_Test(0)) == sizeof(char) + }; }; /// \brief Registers a pre-existing writer class for the given Maya type; @@ -141,7 +147,7 @@ template class HasCanExport { &writerClass::CanExport, \ [](const MFnDependencyNode& depNodeFn, \ const SdfPath& usdPath, \ - UsdMayaWriteJobContext& jobCtx) { \ + UsdMayaWriteJobContext& jobCtx) { \ return std::make_shared(depNodeFn, usdPath, jobCtx); \ }); \ } diff --git a/lib/mayaUsd/fileio/shading/rfmShaderMap.h b/lib/mayaUsd/fileio/shading/rfmShaderMap.h index 2c39468071..0e8f51d196 100644 --- a/lib/mayaUsd/fileio/shading/rfmShaderMap.h +++ b/lib/mayaUsd/fileio/shading/rfmShaderMap.h @@ -24,21 +24,21 @@ #ifndef MAYAUSD_FILEIO_SHADING_RFM_SHADER_MAP_H #define MAYAUSD_FILEIO_SHADING_RFM_SHADER_MAP_H -#include #include +#include #include #include - PXR_NAMESPACE_OPEN_SCOPE - static const std::vector> RfmNodesToShaderIds = { // These Maya nodes are provided by Maya itself, so we map a Maya node type // name to a "Pxr" prefixed RenderMan for Maya shader ID. - { TfToken("bifrostAeroMaterial", TfToken::Immortal), TfToken("PxrBifrostAero", TfToken::Immortal) }, - { TfToken("xgen_hair_physical", TfToken::Immortal), TfToken("PxrMayaXgenHairPhysical", TfToken::Immortal) }, + { TfToken("bifrostAeroMaterial", TfToken::Immortal), + TfToken("PxrBifrostAero", TfToken::Immortal) }, + { TfToken("xgen_hair_physical", TfToken::Immortal), + TfToken("PxrMayaXgenHairPhysical", TfToken::Immortal) }, { TfToken("blendColors", TfToken::Immortal), TfToken("PxrMayaBlendColors", TfToken::Immortal) }, { TfToken("blinn", TfToken::Immortal), TfToken("PxrMayaBlinn", TfToken::Immortal) }, { TfToken("bulge", TfToken::Immortal), TfToken("PxrMayaBulge", TfToken::Immortal) }, @@ -55,23 +55,29 @@ static const std::vector> RfmNodesToShaderIds = { { TfToken("file", TfToken::Immortal), TfToken("PxrMayaFile", TfToken::Immortal) }, { TfToken("fluidShape", TfToken::Immortal), TfToken("PxrMayaFluidShape", TfToken::Immortal) }, { TfToken("fractal", TfToken::Immortal), TfToken("PxrMayaFractal", TfToken::Immortal) }, - { TfToken("gammaCorrect", TfToken::Immortal), TfToken("PxrMayaGammaCorrect", TfToken::Immortal) }, + { TfToken("gammaCorrect", TfToken::Immortal), + TfToken("PxrMayaGammaCorrect", TfToken::Immortal) }, { TfToken("granite", TfToken::Immortal), TfToken("PxrMayaGranite", TfToken::Immortal) }, { TfToken("grid", TfToken::Immortal), TfToken("PxrMayaGrid", TfToken::Immortal) }, { TfToken("hairSystem", TfToken::Immortal), TfToken("PxrMayaHair", TfToken::Immortal) }, { TfToken("hsvToRgb", TfToken::Immortal), TfToken("PxrMayaHsvToRgb", TfToken::Immortal) }, { TfToken("imagePlane", TfToken::Immortal), TfToken("PxrMayaImagePlane", TfToken::Immortal) }, { TfToken("lambert", TfToken::Immortal), TfToken("PxrMayaLambert", TfToken::Immortal) }, - { TfToken("layeredTexture", TfToken::Immortal), TfToken("PxrMayaLayeredTexture", TfToken::Immortal) }, + { TfToken("layeredTexture", TfToken::Immortal), + TfToken("PxrMayaLayeredTexture", TfToken::Immortal) }, { TfToken("leather", TfToken::Immortal), TfToken("PxrMayaLeather", TfToken::Immortal) }, { TfToken("luminance", TfToken::Immortal), TfToken("PxrMayaLuminance", TfToken::Immortal) }, { TfToken("marble", TfToken::Immortal), TfToken("PxrMayaMarble", TfToken::Immortal) }, { TfToken("mountain", TfToken::Immortal), TfToken("PxrMayaMountain", TfToken::Immortal) }, - { TfToken("multiplyDivide", TfToken::Immortal), TfToken("PxrMultiplyDivide", TfToken::Immortal) }, + { TfToken("multiplyDivide", TfToken::Immortal), + TfToken("PxrMultiplyDivide", TfToken::Immortal) }, { TfToken("noise", TfToken::Immortal), TfToken("PxrMayaNoise", TfToken::Immortal) }, - { TfToken("place2dTexture", TfToken::Immortal), TfToken("PxrMayaPlacement2d", TfToken::Immortal) }, - { TfToken("place3dTexture", TfToken::Immortal), TfToken("PxrMayaPlacement3d", TfToken::Immortal) }, - { TfToken("plusMinusAverage", TfToken::Immortal), TfToken("PxrMayaPlusMinusAverage", TfToken::Immortal) }, + { TfToken("place2dTexture", TfToken::Immortal), + TfToken("PxrMayaPlacement2d", TfToken::Immortal) }, + { TfToken("place3dTexture", TfToken::Immortal), + TfToken("PxrMayaPlacement3d", TfToken::Immortal) }, + { TfToken("plusMinusAverage", TfToken::Immortal), + TfToken("PxrMayaPlusMinusAverage", TfToken::Immortal) }, { TfToken("projection", TfToken::Immortal), TfToken("PxrMayaProjection", TfToken::Immortal) }, { TfToken("ramp", TfToken::Immortal), TfToken("PxrMayaRamp", TfToken::Immortal) }, { TfToken("remapColor", TfToken::Immortal), TfToken("PxrMayaRemapColor", TfToken::Immortal) }, @@ -82,7 +88,8 @@ static const std::vector> RfmNodesToShaderIds = { { TfToken("rock", TfToken::Immortal), TfToken("PxrMayaRock", TfToken::Immortal) }, { TfToken("setRange", TfToken::Immortal), TfToken("PxrMayaSetRange", TfToken::Immortal) }, { TfToken("snow", TfToken::Immortal), TfToken("PxrMayaSnow", TfToken::Immortal) }, - { TfToken("solidFractal", TfToken::Immortal), TfToken("PxrMayaSolidFractal", TfToken::Immortal) }, + { TfToken("solidFractal", TfToken::Immortal), + TfToken("PxrMayaSolidFractal", TfToken::Immortal) }, { TfToken("stucco", TfToken::Immortal), TfToken("PxrMayaStucco", TfToken::Immortal) }, { TfToken("uvChooser", TfToken::Immortal), TfToken("PxrMayaUVChooser", TfToken::Immortal) }, { TfToken("volumeFog", TfToken::Immortal), TfToken("PxrMayaVolumeFog", TfToken::Immortal) }, @@ -96,78 +103,110 @@ static const std::vector> RfmNodesToShaderIds = { // cmds.loadPlugin('RenderMan_for_Maya') // allRfmNodes = cmds.pluginInfo('RenderMan_for_Maya', q=True, dependNode=True) // sorted([node for node in allRfmNodes if node.startswith('Pxr')]) - { TfToken("PxrAdjustNormal", TfToken::Immortal), TfToken("PxrAdjustNormal", TfToken::Immortal) }, + { TfToken("PxrAdjustNormal", TfToken::Immortal), + TfToken("PxrAdjustNormal", TfToken::Immortal) }, { TfToken("PxrAovLight", TfToken::Immortal), TfToken("PxrAovLight", TfToken::Immortal) }, { TfToken("PxrAttribute", TfToken::Immortal), TfToken("PxrAttribute", TfToken::Immortal) }, - { TfToken("PxrBackgroundDisplayFilter", TfToken::Immortal), TfToken("PxrBackgroundDisplayFilter", TfToken::Immortal) }, - { TfToken("PxrBackgroundSampleFilter", TfToken::Immortal), TfToken("PxrBackgroundSampleFilter", TfToken::Immortal) }, - { TfToken("PxrBakePointCloud", TfToken::Immortal), TfToken("PxrBakePointCloud", TfToken::Immortal) }, + { TfToken("PxrBackgroundDisplayFilter", TfToken::Immortal), + TfToken("PxrBackgroundDisplayFilter", TfToken::Immortal) }, + { TfToken("PxrBackgroundSampleFilter", TfToken::Immortal), + TfToken("PxrBackgroundSampleFilter", TfToken::Immortal) }, + { TfToken("PxrBakePointCloud", TfToken::Immortal), + TfToken("PxrBakePointCloud", TfToken::Immortal) }, { TfToken("PxrBakeTexture", TfToken::Immortal), TfToken("PxrBakeTexture", TfToken::Immortal) }, - { TfToken("PxrBarnLightFilter", TfToken::Immortal), TfToken("PxrBarnLightFilter", TfToken::Immortal) }, + { TfToken("PxrBarnLightFilter", TfToken::Immortal), + TfToken("PxrBarnLightFilter", TfToken::Immortal) }, { TfToken("PxrBlack", TfToken::Immortal), TfToken("PxrBlack", TfToken::Immortal) }, { TfToken("PxrBlackBody", TfToken::Immortal), TfToken("PxrBlackBody", TfToken::Immortal) }, { TfToken("PxrBlend", TfToken::Immortal), TfToken("PxrBlend", TfToken::Immortal) }, - { TfToken("PxrBlockerLightFilter", TfToken::Immortal), TfToken("PxrBlockerLightFilter", TfToken::Immortal) }, + { TfToken("PxrBlockerLightFilter", TfToken::Immortal), + TfToken("PxrBlockerLightFilter", TfToken::Immortal) }, { TfToken("PxrBump", TfToken::Immortal), TfToken("PxrBump", TfToken::Immortal) }, - { TfToken("PxrBumpManifold2D", TfToken::Immortal), TfToken("PxrBumpManifold2D", TfToken::Immortal) }, + { TfToken("PxrBumpManifold2D", TfToken::Immortal), + TfToken("PxrBumpManifold2D", TfToken::Immortal) }, { TfToken("PxrCamera", TfToken::Immortal), TfToken("PxrCamera", TfToken::Immortal) }, { TfToken("PxrChecker", TfToken::Immortal), TfToken("PxrChecker", TfToken::Immortal) }, { TfToken("PxrClamp", TfToken::Immortal), TfToken("PxrClamp", TfToken::Immortal) }, - { TfToken("PxrColorCorrect", TfToken::Immortal), TfToken("PxrColorCorrect", TfToken::Immortal) }, + { TfToken("PxrColorCorrect", TfToken::Immortal), + TfToken("PxrColorCorrect", TfToken::Immortal) }, { TfToken("PxrConstant", TfToken::Immortal), TfToken("PxrConstant", TfToken::Immortal) }, - { TfToken("PxrCookieLightFilter", TfToken::Immortal), TfToken("PxrCookieLightFilter", TfToken::Immortal) }, - { TfToken("PxrCopyAOVDisplayFilter", TfToken::Immortal), TfToken("PxrCopyAOVDisplayFilter", TfToken::Immortal) }, - { TfToken("PxrCopyAOVSampleFilter", TfToken::Immortal), TfToken("PxrCopyAOVSampleFilter", TfToken::Immortal) }, + { TfToken("PxrCookieLightFilter", TfToken::Immortal), + TfToken("PxrCookieLightFilter", TfToken::Immortal) }, + { TfToken("PxrCopyAOVDisplayFilter", TfToken::Immortal), + TfToken("PxrCopyAOVDisplayFilter", TfToken::Immortal) }, + { TfToken("PxrCopyAOVSampleFilter", TfToken::Immortal), + TfToken("PxrCopyAOVSampleFilter", TfToken::Immortal) }, { TfToken("PxrCross", TfToken::Immortal), TfToken("PxrCross", TfToken::Immortal) }, { TfToken("PxrCryptomatte", TfToken::Immortal), TfToken("PxrCryptomatte", TfToken::Immortal) }, { TfToken("PxrCurvature", TfToken::Immortal), TfToken("PxrCurvature", TfToken::Immortal) }, - { TfToken("PxrCylinderCamera", TfToken::Immortal), TfToken("PxrCylinderCamera", TfToken::Immortal) }, - { TfToken("PxrCylinderLight", TfToken::Immortal), TfToken("PxrCylinderLight", TfToken::Immortal) }, + { TfToken("PxrCylinderCamera", TfToken::Immortal), + TfToken("PxrCylinderCamera", TfToken::Immortal) }, + { TfToken("PxrCylinderLight", TfToken::Immortal), + TfToken("PxrCylinderLight", TfToken::Immortal) }, { TfToken("PxrDefault", TfToken::Immortal), TfToken("PxrDefault", TfToken::Immortal) }, { TfToken("PxrDiffuse", TfToken::Immortal), TfToken("PxrDiffuse", TfToken::Immortal) }, - { TfToken("PxrDirectLighting", TfToken::Immortal), TfToken("PxrDirectLighting", TfToken::Immortal) }, + { TfToken("PxrDirectLighting", TfToken::Immortal), + TfToken("PxrDirectLighting", TfToken::Immortal) }, { TfToken("PxrDirt", TfToken::Immortal), TfToken("PxrDirt", TfToken::Immortal) }, { TfToken("PxrDiskLight", TfToken::Immortal), TfToken("PxrDiskLight", TfToken::Immortal) }, { TfToken("PxrDisney", TfToken::Immortal), TfToken("PxrDisney", TfToken::Immortal) }, - { TfToken("PxrDispScalarLayer", TfToken::Immortal), TfToken("PxrDispScalarLayer", TfToken::Immortal) }, - { TfToken("PxrDispTransform", TfToken::Immortal), TfToken("PxrDispTransform", TfToken::Immortal) }, - { TfToken("PxrDispVectorLayer", TfToken::Immortal), TfToken("PxrDispVectorLayer", TfToken::Immortal) }, + { TfToken("PxrDispScalarLayer", TfToken::Immortal), + TfToken("PxrDispScalarLayer", TfToken::Immortal) }, + { TfToken("PxrDispTransform", TfToken::Immortal), + TfToken("PxrDispTransform", TfToken::Immortal) }, + { TfToken("PxrDispVectorLayer", TfToken::Immortal), + TfToken("PxrDispVectorLayer", TfToken::Immortal) }, { TfToken("PxrDisplace", TfToken::Immortal), TfToken("PxrDisplace", TfToken::Immortal) }, - { TfToken("PxrDistantLight", TfToken::Immortal), TfToken("PxrDistantLight", TfToken::Immortal) }, + { TfToken("PxrDistantLight", TfToken::Immortal), + TfToken("PxrDistantLight", TfToken::Immortal) }, { TfToken("PxrDomeLight", TfToken::Immortal), TfToken("PxrDomeLight", TfToken::Immortal) }, { TfToken("PxrDot", TfToken::Immortal), TfToken("PxrDot", TfToken::Immortal) }, { TfToken("PxrEdgeDetect", TfToken::Immortal), TfToken("PxrEdgeDetect", TfToken::Immortal) }, { TfToken("PxrEnvDayLight", TfToken::Immortal), TfToken("PxrEnvDayLight", TfToken::Immortal) }, { TfToken("PxrExposure", TfToken::Immortal), TfToken("PxrExposure", TfToken::Immortal) }, { TfToken("PxrFacingRatio", TfToken::Immortal), TfToken("PxrFacingRatio", TfToken::Immortal) }, - { TfToken("PxrFilmicTonemapperDisplayFilter", TfToken::Immortal), TfToken("PxrFilmicTonemapperDisplayFilter", TfToken::Immortal) }, - { TfToken("PxrFilmicTonemapperSampleFilter", TfToken::Immortal), TfToken("PxrFilmicTonemapperSampleFilter", TfToken::Immortal) }, + { TfToken("PxrFilmicTonemapperDisplayFilter", TfToken::Immortal), + TfToken("PxrFilmicTonemapperDisplayFilter", TfToken::Immortal) }, + { TfToken("PxrFilmicTonemapperSampleFilter", TfToken::Immortal), + TfToken("PxrFilmicTonemapperSampleFilter", TfToken::Immortal) }, { TfToken("PxrFlakes", TfToken::Immortal), TfToken("PxrFlakes", TfToken::Immortal) }, { TfToken("PxrFractal", TfToken::Immortal), TfToken("PxrFractal", TfToken::Immortal) }, { TfToken("PxrGamma", TfToken::Immortal), TfToken("PxrGamma", TfToken::Immortal) }, - { TfToken("PxrGoboLightFilter", TfToken::Immortal), TfToken("PxrGoboLightFilter", TfToken::Immortal) }, - { TfToken("PxrGradeDisplayFilter", TfToken::Immortal), TfToken("PxrGradeDisplayFilter", TfToken::Immortal) }, - { TfToken("PxrGradeSampleFilter", TfToken::Immortal), TfToken("PxrGradeSampleFilter", TfToken::Immortal) }, + { TfToken("PxrGoboLightFilter", TfToken::Immortal), + TfToken("PxrGoboLightFilter", TfToken::Immortal) }, + { TfToken("PxrGradeDisplayFilter", TfToken::Immortal), + TfToken("PxrGradeDisplayFilter", TfToken::Immortal) }, + { TfToken("PxrGradeSampleFilter", TfToken::Immortal), + TfToken("PxrGradeSampleFilter", TfToken::Immortal) }, { TfToken("PxrHSL", TfToken::Immortal), TfToken("PxrHSL", TfToken::Immortal) }, { TfToken("PxrHairColor", TfToken::Immortal), TfToken("PxrHairColor", TfToken::Immortal) }, - { TfToken("PxrHalfBufferErrorFilter", TfToken::Immortal), TfToken("PxrHalfBufferErrorFilter", TfToken::Immortal) }, - { TfToken("PxrImageDisplayFilter", TfToken::Immortal), TfToken("PxrImageDisplayFilter", TfToken::Immortal) }, - { TfToken("PxrIntMultLightFilter", TfToken::Immortal), TfToken("PxrIntMultLightFilter", TfToken::Immortal) }, + { TfToken("PxrHalfBufferErrorFilter", TfToken::Immortal), + TfToken("PxrHalfBufferErrorFilter", TfToken::Immortal) }, + { TfToken("PxrImageDisplayFilter", TfToken::Immortal), + TfToken("PxrImageDisplayFilter", TfToken::Immortal) }, + { TfToken("PxrIntMultLightFilter", TfToken::Immortal), + TfToken("PxrIntMultLightFilter", TfToken::Immortal) }, { TfToken("PxrInvert", TfToken::Immortal), TfToken("PxrInvert", TfToken::Immortal) }, { TfToken("PxrLayer", TfToken::Immortal), TfToken("PxrLayer", TfToken::Immortal) }, { TfToken("PxrLayerMixer", TfToken::Immortal), TfToken("PxrLayerMixer", TfToken::Immortal) }, - { TfToken("PxrLayerSurface", TfToken::Immortal), TfToken("PxrLayerSurface", TfToken::Immortal) }, - { TfToken("PxrLayeredBlend", TfToken::Immortal), TfToken("PxrLayeredBlend", TfToken::Immortal) }, - { TfToken("PxrLayeredTexture", TfToken::Immortal), TfToken("PxrLayeredTexture", TfToken::Immortal) }, + { TfToken("PxrLayerSurface", TfToken::Immortal), + TfToken("PxrLayerSurface", TfToken::Immortal) }, + { TfToken("PxrLayeredBlend", TfToken::Immortal), + TfToken("PxrLayeredBlend", TfToken::Immortal) }, + { TfToken("PxrLayeredTexture", TfToken::Immortal), + TfToken("PxrLayeredTexture", TfToken::Immortal) }, { TfToken("PxrLightProbe", TfToken::Immortal), TfToken("PxrLightProbe", TfToken::Immortal) }, - { TfToken("PxrLightSaturation", TfToken::Immortal), TfToken("PxrLightSaturation", TfToken::Immortal) }, + { TfToken("PxrLightSaturation", TfToken::Immortal), + TfToken("PxrLightSaturation", TfToken::Immortal) }, { TfToken("PxrManifold2D", TfToken::Immortal), TfToken("PxrManifold2D", TfToken::Immortal) }, { TfToken("PxrManifold3D", TfToken::Immortal), TfToken("PxrManifold3D", TfToken::Immortal) }, - { TfToken("PxrMarschnerHair", TfToken::Immortal), TfToken("PxrMarschnerHair", TfToken::Immortal) }, + { TfToken("PxrMarschnerHair", TfToken::Immortal), + TfToken("PxrMarschnerHair", TfToken::Immortal) }, { TfToken("PxrMatteID", TfToken::Immortal), TfToken("PxrMatteID", TfToken::Immortal) }, { TfToken("PxrMeshLight", TfToken::Immortal), TfToken("PxrMeshLight", TfToken::Immortal) }, { TfToken("PxrMix", TfToken::Immortal), TfToken("PxrMix", TfToken::Immortal) }, - { TfToken("PxrMultiTexture", TfToken::Immortal), TfToken("PxrMultiTexture", TfToken::Immortal) }, + { TfToken("PxrMultiTexture", TfToken::Immortal), + TfToken("PxrMultiTexture", TfToken::Immortal) }, { TfToken("PxrNormalMap", TfToken::Immortal), TfToken("PxrNormalMap", TfToken::Immortal) }, { TfToken("PxrOSL", TfToken::Immortal), TfToken("PxrOSL", TfToken::Immortal) }, { TfToken("PxrOcclusion", TfToken::Immortal), TfToken("PxrOcclusion", TfToken::Immortal) }, @@ -175,32 +214,43 @@ static const std::vector> RfmNodesToShaderIds = { { TfToken("PxrPathTracer", TfToken::Immortal), TfToken("PxrPathTracer", TfToken::Immortal) }, { TfToken("PxrPortalLight", TfToken::Immortal), TfToken("PxrPortalLight", TfToken::Immortal) }, { TfToken("PxrPrimvar", TfToken::Immortal), TfToken("PxrPrimvar", TfToken::Immortal) }, - { TfToken("PxrProjectionLayer", TfToken::Immortal), TfToken("PxrProjectionLayer", TfToken::Immortal) }, - { TfToken("PxrProjectionStack", TfToken::Immortal), TfToken("PxrProjectionStack", TfToken::Immortal) }, + { TfToken("PxrProjectionLayer", TfToken::Immortal), + TfToken("PxrProjectionLayer", TfToken::Immortal) }, + { TfToken("PxrProjectionStack", TfToken::Immortal), + TfToken("PxrProjectionStack", TfToken::Immortal) }, { TfToken("PxrProjector", TfToken::Immortal), TfToken("PxrProjector", TfToken::Immortal) }, { TfToken("PxrPtexture", TfToken::Immortal), TfToken("PxrPtexture", TfToken::Immortal) }, { TfToken("PxrRamp", TfToken::Immortal), TfToken("PxrRamp", TfToken::Immortal) }, - { TfToken("PxrRampLightFilter", TfToken::Immortal), TfToken("PxrRampLightFilter", TfToken::Immortal) }, - { TfToken("PxrRandomTextureManifold", TfToken::Immortal), TfToken("PxrRandomTextureManifold", TfToken::Immortal) }, + { TfToken("PxrRampLightFilter", TfToken::Immortal), + TfToken("PxrRampLightFilter", TfToken::Immortal) }, + { TfToken("PxrRandomTextureManifold", TfToken::Immortal), + TfToken("PxrRandomTextureManifold", TfToken::Immortal) }, { TfToken("PxrRectLight", TfToken::Immortal), TfToken("PxrRectLight", TfToken::Immortal) }, { TfToken("PxrRemap", TfToken::Immortal), TfToken("PxrRemap", TfToken::Immortal) }, - { TfToken("PxrRodLightFilter", TfToken::Immortal), TfToken("PxrRodLightFilter", TfToken::Immortal) }, + { TfToken("PxrRodLightFilter", TfToken::Immortal), + TfToken("PxrRodLightFilter", TfToken::Immortal) }, { TfToken("PxrRoundCube", TfToken::Immortal), TfToken("PxrRoundCube", TfToken::Immortal) }, { TfToken("PxrSeExpr", TfToken::Immortal), TfToken("PxrSeExpr", TfToken::Immortal) }, { TfToken("PxrShadedSide", TfToken::Immortal), TfToken("PxrShadedSide", TfToken::Immortal) }, - { TfToken("PxrShadowDisplayFilter", TfToken::Immortal), TfToken("PxrShadowDisplayFilter", TfToken::Immortal) }, - { TfToken("PxrShadowFilter", TfToken::Immortal), TfToken("PxrShadowFilter", TfToken::Immortal) }, - { TfToken("PxrSharedSignalLightFilter", TfToken::Immortal), TfToken("PxrSharedSignalLightFilter", TfToken::Immortal) }, - { TfToken("PxrSphereCamera", TfToken::Immortal), TfToken("PxrSphereCamera", TfToken::Immortal) }, + { TfToken("PxrShadowDisplayFilter", TfToken::Immortal), + TfToken("PxrShadowDisplayFilter", TfToken::Immortal) }, + { TfToken("PxrShadowFilter", TfToken::Immortal), + TfToken("PxrShadowFilter", TfToken::Immortal) }, + { TfToken("PxrSharedSignalLightFilter", TfToken::Immortal), + TfToken("PxrSharedSignalLightFilter", TfToken::Immortal) }, + { TfToken("PxrSphereCamera", TfToken::Immortal), + TfToken("PxrSphereCamera", TfToken::Immortal) }, { TfToken("PxrSphereLight", TfToken::Immortal), TfToken("PxrSphereLight", TfToken::Immortal) }, { TfToken("PxrSurface", TfToken::Immortal), TfToken("PxrSurface", TfToken::Immortal) }, { TfToken("PxrSwitch", TfToken::Immortal), TfToken("PxrSwitch", TfToken::Immortal) }, - { TfToken("PxrTangentField", TfToken::Immortal), TfToken("PxrTangentField", TfToken::Immortal) }, + { TfToken("PxrTangentField", TfToken::Immortal), + TfToken("PxrTangentField", TfToken::Immortal) }, { TfToken("PxrTee", TfToken::Immortal), TfToken("PxrTee", TfToken::Immortal) }, { TfToken("PxrTexture", TfToken::Immortal), TfToken("PxrTexture", TfToken::Immortal) }, { TfToken("PxrThinFilm", TfToken::Immortal), TfToken("PxrThinFilm", TfToken::Immortal) }, { TfToken("PxrThreshold", TfToken::Immortal), TfToken("PxrThreshold", TfToken::Immortal) }, - { TfToken("PxrTileManifold", TfToken::Immortal), TfToken("PxrTileManifold", TfToken::Immortal) }, + { TfToken("PxrTileManifold", TfToken::Immortal), + TfToken("PxrTileManifold", TfToken::Immortal) }, { TfToken("PxrToFloat", TfToken::Immortal), TfToken("PxrToFloat", TfToken::Immortal) }, { TfToken("PxrToFloat3", TfToken::Immortal), TfToken("PxrToFloat3", TfToken::Immortal) }, { TfToken("PxrVCM", TfToken::Immortal), TfToken("PxrVCM", TfToken::Immortal) }, @@ -209,15 +259,16 @@ static const std::vector> RfmNodesToShaderIds = { { TfToken("PxrVisualizer", TfToken::Immortal), TfToken("PxrVisualizer", TfToken::Immortal) }, { TfToken("PxrVolume", TfToken::Immortal), TfToken("PxrVolume", TfToken::Immortal) }, { TfToken("PxrVoronoise", TfToken::Immortal), TfToken("PxrVoronoise", TfToken::Immortal) }, - { TfToken("PxrWatermarkFilter", TfToken::Immortal), TfToken("PxrWatermarkFilter", TfToken::Immortal) }, - { TfToken("PxrWhitePointDisplayFilter", TfToken::Immortal), TfToken("PxrWhitePointDisplayFilter", TfToken::Immortal) }, - { TfToken("PxrWhitePointSampleFilter", TfToken::Immortal), TfToken("PxrWhitePointSampleFilter", TfToken::Immortal) }, + { TfToken("PxrWatermarkFilter", TfToken::Immortal), + TfToken("PxrWatermarkFilter", TfToken::Immortal) }, + { TfToken("PxrWhitePointDisplayFilter", TfToken::Immortal), + TfToken("PxrWhitePointDisplayFilter", TfToken::Immortal) }, + { TfToken("PxrWhitePointSampleFilter", TfToken::Immortal), + TfToken("PxrWhitePointSampleFilter", TfToken::Immortal) }, { TfToken("PxrWireframe", TfToken::Immortal), TfToken("PxrWireframe", TfToken::Immortal) }, { TfToken("PxrWorley", TfToken::Immortal), TfToken("PxrWorley", TfToken::Immortal) } }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/shading/shadingModeDisplayColor.cpp b/lib/mayaUsd/fileio/shading/shadingModeDisplayColor.cpp index 04dfb4123a..63d930e581 100644 --- a/lib/mayaUsd/fileio/shading/shadingModeDisplayColor.cpp +++ b/lib/mayaUsd/fileio/shading/shadingModeDisplayColor.cpp @@ -62,13 +62,12 @@ PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PRIVATE_TOKENS( _tokens, - (diffuseColor) - (opacity) + (diffuseColor)(opacity) - ((NiceName, "Display Colors")) - ((ImportDescription, "Imports the displayColor primvar on the USD mesh as a Maya" - " surface shader.")) -); + ((NiceName, "Display Colors"))( + (ImportDescription, + "Imports the displayColor primvar on the USD mesh as a Maya" + " surface shader."))); DEFINE_SHADING_MODE_IMPORTER_WITH_JOB_ARGUMENTS( displayColor, @@ -78,21 +77,20 @@ DEFINE_SHADING_MODE_IMPORTER_WITH_JOB_ARGUMENTS( jobArguments) { const UsdShadeMaterial& shadeMaterial = context->GetShadeMaterial(); - const UsdGeomGprim& primSchema = context->GetBoundPrim(); + const UsdGeomGprim& primSchema = context->GetBoundPrim(); MStatus status; // Get Display Color from USD (linear) and convert to Display - GfVec3f linearDisplayColor(.5,.5,.5); + GfVec3f linearDisplayColor(.5, .5, .5); GfVec3f linearTransparency(0, 0, 0); VtVec3fArray gprimDisplayColor(1); - if (primSchema && - primSchema.GetDisplayColorPrimvar().ComputeFlattened(&gprimDisplayColor)) { + if (primSchema && primSchema.GetDisplayColorPrimvar().ComputeFlattened(&gprimDisplayColor)) { linearDisplayColor = gprimDisplayColor[0]; VtFloatArray gprimDisplayOpacity(1); - if (primSchema.GetDisplayOpacityPrimvar().GetAttr().HasAuthoredValue() && - primSchema.GetDisplayOpacityPrimvar().ComputeFlattened(&gprimDisplayOpacity)) { + if (primSchema.GetDisplayOpacityPrimvar().GetAttr().HasAuthoredValue() + && primSchema.GetDisplayOpacityPrimvar().ComputeFlattened(&gprimDisplayOpacity)) { const float trans = 1.0 - gprimDisplayOpacity[0]; linearTransparency = GfVec3f(trans, trans, trans); } @@ -100,8 +98,7 @@ DEFINE_SHADING_MODE_IMPORTER_WITH_JOB_ARGUMENTS( return MObject(); } - const GfVec3f displayColor = - UsdMayaColorSpace::ConvertLinearToMaya(linearDisplayColor); + const GfVec3f displayColor = UsdMayaColorSpace::ConvertLinearToMaya(linearDisplayColor); // We default to lambert if no conversion was requested: const TfToken& preferredMaterial @@ -109,24 +106,22 @@ DEFINE_SHADING_MODE_IMPORTER_WITH_JOB_ARGUMENTS( ? jobArguments.preferredMaterial : UsdMayaPreferredMaterialTokens->lambert; std::string shaderName(preferredMaterial.GetText()); - SdfPath shaderParentPath = SdfPath::AbsoluteRootPath(); + SdfPath shaderParentPath = SdfPath::AbsoluteRootPath(); if (shadeMaterial) { const UsdPrim& shadeMaterialPrim = shadeMaterial.GetPrim(); - shaderName = - TfStringPrintf("%s_%s", - shadeMaterialPrim.GetName().GetText(), - preferredMaterial.GetText()); + shaderName = TfStringPrintf( + "%s_%s", shadeMaterialPrim.GetName().GetText(), preferredMaterial.GetText()); shaderParentPath = shadeMaterialPrim.GetPath(); } // Construct the selected shader. - MObject shadingObj; + MObject shadingObj; UsdMayaTranslatorUtil::CreateShaderNode( - MString(shaderName.c_str()), - preferredMaterial.GetText(), - UsdMayaShadingNodeType::Shader, - &status, - &shadingObj); + MString(shaderName.c_str()), + preferredMaterial.GetText(), + UsdMayaShadingNodeType::Shader, + &status, + &shadingObj); if (status != MS::kSuccess) { TF_RUNTIME_ERROR( "Could not create node of type '%s' for prim '%s'.\n", @@ -141,22 +136,21 @@ DEFINE_SHADING_MODE_IMPORTER_WITH_JOB_ARGUMENTS( MFnStandardSurfaceShader surfaceFn; surfaceFn.setObject(shadingObj); surfaceFn.setBase(1.0f); - surfaceFn.setBaseColor( - MColor(displayColor[0], displayColor[1], displayColor[2])); + surfaceFn.setBaseColor(MColor(displayColor[0], displayColor[1], displayColor[2])); surfaceFn.setTransmission(linearTransparency[0]); - const SdfPath surfacePath = - shaderParentPath.AppendChild(TfToken(surfaceFn.name().asChar())); + const SdfPath surfacePath + = shaderParentPath.AppendChild(TfToken(surfaceFn.name().asChar())); context->AddCreatedObject(surfacePath, shadingObj); // Find the outColor plug so we can connect it as the surface shader of the // shading engine. outputPlug = surfaceFn.findPlug("outColor", &status); CHECK_MSTATUS_AND_RETURN(status, MObject()); - } else + } else #endif - if (preferredMaterial == UsdMayaPreferredMaterialTokens->usdPreviewSurface) { + if (preferredMaterial == UsdMayaPreferredMaterialTokens->usdPreviewSurface) { MFnDependencyNode depNodeFn; depNodeFn.setObject(shadingObj); @@ -173,19 +167,18 @@ DEFINE_SHADING_MODE_IMPORTER_WITH_JOB_ARGUMENTS( } else { MFnLambertShader lambertFn; lambertFn.setObject(shadingObj); - lambertFn.setColor( - MColor(displayColor[0], displayColor[1], displayColor[2])); + lambertFn.setColor(MColor(displayColor[0], displayColor[1], displayColor[2])); lambertFn.setTransparency( MColor(linearTransparency[0], linearTransparency[1], linearTransparency[2])); - + // We explicitly set diffuse coefficient to 1.0 here since new lamberts // default to 0.8. This is to make sure the color value matches visually // when roundtripping since we bake the diffuseCoeff into the diffuse color // at export. lambertFn.setDiffuseCoeff(1.0); - const SdfPath lambertPath = - shaderParentPath.AppendChild(TfToken(lambertFn.name().asChar())); + const SdfPath lambertPath + = shaderParentPath.AppendChild(TfToken(lambertFn.name().asChar())); context->AddCreatedObject(lambertPath, shadingObj); outputPlug = lambertFn.findPlug("outColor", &status); @@ -203,12 +196,12 @@ DEFINE_SHADING_MODE_IMPORTER_WITH_JOB_ARGUMENTS( const TfToken surfaceShaderPlugName = context->GetSurfaceShaderPlugName(); if (!surfaceShaderPlugName.IsEmpty()) { - MPlug seSurfaceShaderPlg = - fnSet.findPlug(surfaceShaderPlugName.GetText(), &status); + MPlug seSurfaceShaderPlg = fnSet.findPlug(surfaceShaderPlugName.GetText(), &status); CHECK_MSTATUS_AND_RETURN(status, MObject()); - UsdMayaUtil::Connect(outputPlug, - seSurfaceShaderPlg, - /* clearDstPlug = */ true); + UsdMayaUtil::Connect( + outputPlug, + seSurfaceShaderPlg, + /* clearDstPlug = */ true); } return shadingEngine; diff --git a/lib/mayaUsd/fileio/shading/shadingModeExporter.cpp b/lib/mayaUsd/fileio/shading/shadingModeExporter.cpp index ea10b3f1dc..c8b9c92c12 100644 --- a/lib/mayaUsd/fileio/shading/shadingModeExporter.cpp +++ b/lib/mayaUsd/fileio/shading/shadingModeExporter.cpp @@ -15,12 +15,11 @@ // #include "shadingModeExporter.h" -#include -#include -#include - -#include -#include +#include +#include +#include +#include +#include #include #include @@ -33,48 +32,35 @@ #include #include -#include -#include -#include -#include -#include +#include +#include + +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PRIVATE_TOKENS( - _tokens, - ((materialNamespace, "material:")) -); +TF_DEFINE_PRIVATE_TOKENS(_tokens, ((materialNamespace, "material:"))); -UsdMayaShadingModeExporter::UsdMayaShadingModeExporter() -{ -} +UsdMayaShadingModeExporter::UsdMayaShadingModeExporter() { } /* virtual */ -UsdMayaShadingModeExporter::~UsdMayaShadingModeExporter() -{ -} +UsdMayaShadingModeExporter::~UsdMayaShadingModeExporter() { } -static -TfToken -_GetCollectionName(const UsdShadeMaterial& mat) +static TfToken _GetCollectionName(const UsdShadeMaterial& mat) { - return TfToken(_tokens->materialNamespace.GetString() + - mat.GetPrim().GetName().GetString()); + return TfToken(_tokens->materialNamespace.GetString() + mat.GetPrim().GetName().GetString()); } // Returns the set of root prim paths present in the given path-set. -static -SdfPathSet -_GetRootPaths(const SdfPathSet& paths) +static SdfPathSet _GetRootPaths(const SdfPathSet& paths) { SdfPathSet result; - for (const auto &p : paths) { - const std::string &pathString = p.GetString(); + for (const auto& p : paths) { + const std::string& pathString = p.GetString(); // Skip pseudo-root. - if (!TF_VERIFY(pathString.size() > 1u, - "Invalid path '%s'", - pathString.c_str())) { + if (!TF_VERIFY(pathString.size() > 1u, "Invalid path '%s'", pathString.c_str())) { continue; } @@ -85,20 +71,18 @@ _GetRootPaths(const SdfPathSet& paths) return result; } -void -UsdMayaShadingModeExporter::DoExport( - UsdMayaWriteJobContext& writeJobContext, - const UsdMayaUtil::MDagPathMap& dagPathToUsdMap) +void UsdMayaShadingModeExporter::DoExport( + UsdMayaWriteJobContext& writeJobContext, + const UsdMayaUtil::MDagPathMap& dagPathToUsdMap) { const UsdMayaJobExportArgs& exportArgs = writeJobContext.GetArgs(); - const UsdStageRefPtr& stage = writeJobContext.GetUsdStage(); + const UsdStageRefPtr& stage = writeJobContext.GetUsdStage(); MItDependencyNodes shadingEngineIter(MFn::kShadingEngine); - const SdfPath& materialCollectionsPath = - exportArgs.exportMaterialCollections ? - exportArgs.materialCollectionsPath : - SdfPath::EmptyPath(); + const SdfPath& materialCollectionsPath = exportArgs.exportMaterialCollections + ? exportArgs.materialCollectionsPath + : SdfPath::EmptyPath(); UsdPrim materialCollectionsPrim; if (!materialCollectionsPath.IsEmpty()) { @@ -112,15 +96,11 @@ UsdMayaShadingModeExporter::DoExport( } } - UsdMayaShadingModeExportContext context( - MObject(), - writeJobContext, - dagPathToUsdMap); + UsdMayaShadingModeExportContext context(MObject(), writeJobContext, dagPathToUsdMap); PreExport(&context); - using MaterialAssignments = std::vector>; + using MaterialAssignments = std::vector>; MaterialAssignments matAssignments; std::vector exportedMaterials; @@ -129,13 +109,12 @@ UsdMayaShadingModeExporter::DoExport( context.SetShadingEngine(shadingEngine); UsdShadeMaterial mat; - SdfPathSet boundPrimPaths; + SdfPathSet boundPrimPaths; Export(context, &mat, &boundPrimPaths); if (mat && !boundPrimPaths.empty()) { exportedMaterials.push_back(mat); - matAssignments.push_back(std::make_pair( - _GetCollectionName(mat), boundPrimPaths)); + matAssignments.push_back(std::make_pair(_GetCollectionName(mat), boundPrimPaths)); } } @@ -143,8 +122,7 @@ UsdMayaShadingModeExporter::DoExport( PostExport(context); if ((materialCollectionsPrim || exportArgs.exportCollectionBasedBindings) - && !matAssignments.empty()) - { + && !matAssignments.empty()) { if (!materialCollectionsPrim) { // Find a place to export the material collections. The collections // can live anywhere in the scene, but the collection-based bindings @@ -152,35 +130,36 @@ UsdMayaShadingModeExporter::DoExport( // // This computes the first root prim below which a material has // been exported. - SdfPath rootPrimPath = - exportedMaterials[0].GetPath().GetPrefixes()[0]; + SdfPath rootPrimPath = exportedMaterials[0].GetPath().GetPrefixes()[0]; materialCollectionsPrim = stage->GetPrimAtPath(rootPrimPath); - TF_VERIFY(materialCollectionsPrim, + TF_VERIFY( + materialCollectionsPrim, "Could not get prim at path <%s>. Not exporting material " - "collections / bindings.", rootPrimPath.GetText()); + "collections / bindings.", + rootPrimPath.GetText()); return; } - std::vector collections = - UsdUtilsCreateCollections(matAssignments, materialCollectionsPrim); + std::vector collections + = UsdUtilsCreateCollections(matAssignments, materialCollectionsPrim); if (exportArgs.exportCollectionBasedBindings) { for (size_t i = 0u; i < exportedMaterials.size(); ++i) { - const UsdShadeMaterial &mat = exportedMaterials[i]; - const UsdCollectionAPI &coll = collections[i]; + const UsdShadeMaterial& mat = exportedMaterials[i]; + const UsdCollectionAPI& coll = collections[i]; // If the all the paths are under the prim with the materialBind // collections, export the binding on the prim. - const SdfPathSet &paths = matAssignments[i].second; - if (std::all_of(paths.begin(), paths.end(), - [materialCollectionsPrim](const SdfPath &p) { - return p.HasPrefix(materialCollectionsPrim.GetPath()); + const SdfPathSet& paths = matAssignments[i].second; + if (std::all_of( + paths.begin(), paths.end(), [materialCollectionsPrim](const SdfPath& p) { + return p.HasPrefix(materialCollectionsPrim.GetPath()); })) { // Materials are named uniquely in maya, so we can // skip passing in the 'bindingName' param. - UsdShadeMaterialBindingAPI bindingAPI = - UsdMayaTranslatorUtil::GetAPISchemaForAuthoring< + UsdShadeMaterialBindingAPI bindingAPI + = UsdMayaTranslatorUtil::GetAPISchemaForAuthoring< UsdShadeMaterialBindingAPI>(materialCollectionsPrim); bindingAPI.Bind(coll, mat); continue; @@ -189,17 +168,16 @@ UsdMayaShadingModeExporter::DoExport( // If all the paths are not under materialCollectionsPrim, then // figure out the set of root paths at which to export the // collection-based bindings. - const SdfPathSet rootPaths = - _GetRootPaths(matAssignments[i].second); - for (auto &rootPath : rootPaths) { + const SdfPathSet rootPaths = _GetRootPaths(matAssignments[i].second); + for (auto& rootPath : rootPaths) { auto rootPrim = stage->GetPrimAtPath(rootPath); - if (!TF_VERIFY(rootPrim, "Could not get prim at path <%s>", - rootPath.GetText())) { + if (!TF_VERIFY( + rootPrim, "Could not get prim at path <%s>", rootPath.GetText())) { continue; } - UsdShadeMaterialBindingAPI bindingAPI = - UsdMayaTranslatorUtil::GetAPISchemaForAuthoring< + UsdShadeMaterialBindingAPI bindingAPI + = UsdMayaTranslatorUtil::GetAPISchemaForAuthoring< UsdShadeMaterialBindingAPI>(rootPrim); bindingAPI.Bind(coll, mat); } @@ -208,5 +186,4 @@ UsdMayaShadingModeExporter::DoExport( } } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/shading/shadingModeExporter.h b/lib/mayaUsd/fileio/shading/shadingModeExporter.h index 220ae55b94..b05fadfb0c 100644 --- a/lib/mayaUsd/fileio/shading/shadingModeExporter.h +++ b/lib/mayaUsd/fileio/shading/shadingModeExporter.h @@ -16,17 +16,17 @@ #ifndef PXRUSDMAYA_SHADING_MODE_EXPORTER_H #define PXRUSDMAYA_SHADING_MODE_EXPORTER_H -#include -#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -40,8 +40,8 @@ class UsdMayaShadingModeExporter MAYAUSD_CORE_PUBLIC void DoExport( - UsdMayaWriteJobContext& writeJobContext, - const UsdMayaUtil::MDagPathMap& dagPathToUsdMap); + UsdMayaWriteJobContext& writeJobContext, + const UsdMayaUtil::MDagPathMap& dagPathToUsdMap); /// Called once, before any exports are started. /// @@ -54,9 +54,10 @@ class UsdMayaShadingModeExporter /// Called inside of a loop, per-shading-engine MAYAUSD_CORE_PUBLIC virtual void Export( - const UsdMayaShadingModeExportContext& context, - UsdShadeMaterial* const mat, - SdfPathSet* const boundPrimPaths) = 0; + const UsdMayaShadingModeExportContext& context, + UsdShadeMaterial* const mat, + SdfPathSet* const boundPrimPaths) + = 0; /// Called once, after Export is called for all shading engines. /// @@ -68,10 +69,9 @@ class UsdMayaShadingModeExporter }; using UsdMayaShadingModeExporterPtr = std::shared_ptr; -using UsdMayaShadingModeExporterCreator = std::function()>; - +using UsdMayaShadingModeExporterCreator + = std::function()>; PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/shading/shadingModeExporterContext.cpp b/lib/mayaUsd/fileio/shading/shadingModeExporterContext.cpp index 889f6da2a8..5c7b081c28 100644 --- a/lib/mayaUsd/fileio/shading/shadingModeExporterContext.cpp +++ b/lib/mayaUsd/fileio/shading/shadingModeExporterContext.cpp @@ -15,22 +15,13 @@ // #include "shadingModeExporterContext.h" -#include -#include +#include "pxr/usd/usd/specializes.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include @@ -40,7 +31,6 @@ #include #include #include -#include "pxr/usd/usd/specializes.h" #include #include #include @@ -49,43 +39,45 @@ #include #include -#include -#include -#include -#include -#include - -PXR_NAMESPACE_OPEN_SCOPE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -TF_DEFINE_PRIVATE_TOKENS( - _tokens, - (surfaceShader) - (volumeShader) - (displacementShader) - (varname) - (map1) -); +PXR_NAMESPACE_OPEN_SCOPE +TF_DEFINE_PRIVATE_TOKENS(_tokens, (surfaceShader)(volumeShader)(displacementShader)(varname)(map1)); UsdMayaShadingModeExportContext::UsdMayaShadingModeExportContext( - const MObject& shadingEngine, - UsdMayaWriteJobContext& writeJobContext, - const UsdMayaUtil::MDagPathMap& dagPathToUsdMap) : - _shadingEngine(shadingEngine), - _stage(writeJobContext.GetUsdStage()), - _dagPathToUsdMap(dagPathToUsdMap), - _writeJobContext(writeJobContext), - _surfaceShaderPlugName(_tokens->surfaceShader), - _volumeShaderPlugName(_tokens->volumeShader), - _displacementShaderPlugName(_tokens->displacementShader) + const MObject& shadingEngine, + UsdMayaWriteJobContext& writeJobContext, + const UsdMayaUtil::MDagPathMap& dagPathToUsdMap) + : _shadingEngine(shadingEngine) + , _stage(writeJobContext.GetUsdStage()) + , _dagPathToUsdMap(dagPathToUsdMap) + , _writeJobContext(writeJobContext) + , _surfaceShaderPlugName(_tokens->surfaceShader) + , _volumeShaderPlugName(_tokens->volumeShader) + , _displacementShaderPlugName(_tokens->displacementShader) { if (GetExportArgs().dagPaths.empty()) { // if none specified, push back '/' which encompasses all _bindableRoots.insert(SdfPath::AbsoluteRootPath()); - } - else { - TF_FOR_ALL(bindableRootIter, GetExportArgs().dagPaths) { + } else { + TF_FOR_ALL(bindableRootIter, GetExportArgs().dagPaths) + { const MDagPath& bindableRootDagPath = *bindableRootIter; auto iter = _dagPathToUsdMap.find(bindableRootDagPath); @@ -100,8 +92,7 @@ UsdMayaShadingModeExportContext::UsdMayaShadingModeExportContext( // namespace with it. if (!GetExportArgs().usdModelRootOverridePath.IsEmpty()) { usdPath = usdPath.ReplacePrefix( - usdPath.GetPrefixes()[0], - GetExportArgs().usdModelRootOverridePath); + usdPath.GetPrefixes()[0], GetExportArgs().usdModelRootOverridePath); } _bindableRoots.insert(usdPath); @@ -109,32 +100,24 @@ UsdMayaShadingModeExportContext::UsdMayaShadingModeExportContext( } } -void -UsdMayaShadingModeExportContext::SetSurfaceShaderPlugName( - const TfToken& surfaceShaderPlugName) +void UsdMayaShadingModeExportContext::SetSurfaceShaderPlugName(const TfToken& surfaceShaderPlugName) { _surfaceShaderPlugName = surfaceShaderPlugName; } -void -UsdMayaShadingModeExportContext::SetVolumeShaderPlugName( - const TfToken& volumeShaderPlugName) +void UsdMayaShadingModeExportContext::SetVolumeShaderPlugName(const TfToken& volumeShaderPlugName) { _volumeShaderPlugName = volumeShaderPlugName; } -void -UsdMayaShadingModeExportContext::SetDisplacementShaderPlugName( - const TfToken& displacementShaderPlugName) +void UsdMayaShadingModeExportContext::SetDisplacementShaderPlugName( + const TfToken& displacementShaderPlugName) { _displacementShaderPlugName = displacementShaderPlugName; } -static -MPlug -_GetShaderPlugFromShadingEngine( - const MObject& shadingEngine, - const TfToken& shaderPlugName) +static MPlug +_GetShaderPlugFromShadingEngine(const MObject& shadingEngine, const TfToken& shaderPlugName) { MStatus status; @@ -143,11 +126,10 @@ _GetShaderPlugFromShadingEngine( return MPlug(); } - const MPlug shaderPlug = - seDepNodeFn.findPlug( - shaderPlugName.GetText(), - /* wantNetworkedPlug = */ true, - &status); + const MPlug shaderPlug = seDepNodeFn.findPlug( + shaderPlugName.GetText(), + /* wantNetworkedPlug = */ true, + &status); if (status != MS::kSuccess) { return MPlug(); } @@ -155,16 +137,12 @@ _GetShaderPlugFromShadingEngine( return shaderPlug; } -static -MObject -_GetShaderFromShadingEngine( - const MObject& shadingEngine, - const TfToken& shaderPlugName) +static MObject +_GetShaderFromShadingEngine(const MObject& shadingEngine, const TfToken& shaderPlugName) { MStatus status; - const MPlug shaderPlug = - _GetShaderPlugFromShadingEngine(shadingEngine, shaderPlugName); + const MPlug shaderPlug = _GetShaderPlugFromShadingEngine(shadingEngine, shaderPlugName); if (shaderPlug.isNull()) { return MObject(); } @@ -177,52 +155,34 @@ _GetShaderFromShadingEngine( return UsdMayaUtil::GetConnected(shaderPlug).node(); } -MPlug -UsdMayaShadingModeExportContext::GetSurfaceShaderPlug() const +MPlug UsdMayaShadingModeExportContext::GetSurfaceShaderPlug() const { - return _GetShaderPlugFromShadingEngine( - _shadingEngine, - _surfaceShaderPlugName); + return _GetShaderPlugFromShadingEngine(_shadingEngine, _surfaceShaderPlugName); } -MObject -UsdMayaShadingModeExportContext::GetSurfaceShader() const +MObject UsdMayaShadingModeExportContext::GetSurfaceShader() const { - return _GetShaderFromShadingEngine( - _shadingEngine, - _surfaceShaderPlugName); + return _GetShaderFromShadingEngine(_shadingEngine, _surfaceShaderPlugName); } -MPlug -UsdMayaShadingModeExportContext::GetVolumeShaderPlug() const +MPlug UsdMayaShadingModeExportContext::GetVolumeShaderPlug() const { - return _GetShaderPlugFromShadingEngine( - _shadingEngine, - _volumeShaderPlugName); + return _GetShaderPlugFromShadingEngine(_shadingEngine, _volumeShaderPlugName); } -MObject -UsdMayaShadingModeExportContext::GetVolumeShader() const +MObject UsdMayaShadingModeExportContext::GetVolumeShader() const { - return _GetShaderFromShadingEngine( - _shadingEngine, - _volumeShaderPlugName); + return _GetShaderFromShadingEngine(_shadingEngine, _volumeShaderPlugName); } -MPlug -UsdMayaShadingModeExportContext::GetDisplacementShaderPlug() const +MPlug UsdMayaShadingModeExportContext::GetDisplacementShaderPlug() const { - return _GetShaderPlugFromShadingEngine( - _shadingEngine, - _displacementShaderPlugName); + return _GetShaderPlugFromShadingEngine(_shadingEngine, _displacementShaderPlugName); } -MObject -UsdMayaShadingModeExportContext::GetDisplacementShader() const +MObject UsdMayaShadingModeExportContext::GetDisplacementShader() const { - return _GetShaderFromShadingEngine( - _shadingEngine, - _displacementShaderPlugName); + return _GetShaderFromShadingEngine(_shadingEngine, _displacementShaderPlugName); } UsdMayaShadingModeExportContext::AssignmentVector @@ -230,7 +190,7 @@ UsdMayaShadingModeExportContext::GetAssignments() const { AssignmentVector ret; - MStatus status; + MStatus status; MFnDependencyNode seDepNode(_shadingEngine, &status); if (!status) { return ret; @@ -243,9 +203,9 @@ UsdMayaShadingModeExportContext::GetAssignments() const SdfPathSet seenBoundPrimPaths; for (unsigned int i = 0; i < dsmPlug.numConnectedElements(); i++) { - MPlug dsmElemPlug(dsmPlug.connectionByPhysicalIndex(i)); + MPlug dsmElemPlug(dsmPlug.connectionByPhysicalIndex(i)); MStatus status = MS::kFailure; - MPlug connectedPlug = UsdMayaUtil::GetConnected(dsmElemPlug); + MPlug connectedPlug = UsdMayaUtil::GetConnected(dsmElemPlug); // Maya connects shader bindings for instances based on element indices // of the instObjGroups[x] or instObjGroups[x].objectGroups[y] plugs. @@ -266,11 +226,11 @@ UsdMayaShadingModeExportContext::GetAssignments() const MDagPath::getAllPathsTo(connectedPlug.node(), allDagPaths); if (instanceNumber >= allDagPaths.length()) { TF_RUNTIME_ERROR( - "Instance number is %d (from plug '%s') but node only has " - "%d paths", - instanceNumber, - connectedPlug.name().asChar(), - allDagPaths.length()); + "Instance number is %d (from plug '%s') but node only has " + "%d paths", + instanceNumber, + connectedPlug.name().asChar(), + allDagPaths.length()); continue; } @@ -292,8 +252,7 @@ UsdMayaShadingModeExportContext::GetAssignments() const // root namespace with it. if (!GetExportArgs().usdModelRootOverridePath.IsEmpty()) { usdPath = usdPath.ReplacePrefix( - usdPath.GetPrefixes()[0], - GetExportArgs().usdModelRootOverridePath); + usdPath.GetPrefixes()[0], GetExportArgs().usdModelRootOverridePath); } // If this path has already been processed, skip it. @@ -302,17 +261,12 @@ UsdMayaShadingModeExportContext::GetAssignments() const } // If the bound prim's path is not below a bindable root, skip it. - if (SdfPathFindLongestPrefix( - _bindableRoots, usdPath) == _bindableRoots.end()) { + if (SdfPathFindLongestPrefix(_bindableRoots, usdPath) == _bindableRoots.end()) { continue; } MObjectArray sgObjs, compObjs; - status = dagNode.getConnectedSetsAndMembers( - instanceNumber, - sgObjs, - compObjs, - true); + status = dagNode.getConnectedSetsAndMembers(instanceNumber, sgObjs, compObjs, true); if (status != MS::kSuccess) { continue; } @@ -337,21 +291,19 @@ UsdMayaShadingModeExportContext::GetAssignments() const return ret; } -static -UsdPrim -_GetMaterialParent( - const UsdStageRefPtr& stage, - const TfToken& materialsScopeName, - const UsdMayaShadingModeExportContext::AssignmentVector& assignments) +static UsdPrim _GetMaterialParent( + const UsdStageRefPtr& stage, + const TfToken& materialsScopeName, + const UsdMayaShadingModeExportContext::AssignmentVector& assignments) { SdfPath commonAncestor; - TF_FOR_ALL(iter, assignments) { + TF_FOR_ALL(iter, assignments) + { const SdfPath& assn = iter->boundPrimPath; if (stage->GetPrimAtPath(assn)) { if (commonAncestor.IsEmpty()) { commonAncestor = assn; - } - else { + } else { commonAncestor = commonAncestor.GetCommonPrefix(assn); } } @@ -379,9 +331,7 @@ _GetMaterialParent( /// it existed, i.e., if any of its ancestor paths are instances. /// (Note that if \p path itself is an instance, then it is _not_ an instance /// proxy path.) -static -bool -_IsInstanceProxyPath(const UsdStageRefPtr& stage, const SdfPath& path) +static bool _IsInstanceProxyPath(const UsdStageRefPtr& stage, const SdfPath& path) { for (const SdfPath& prefix : path.GetParentPath().GetPrefixes()) { if (const UsdPrim prim = stage->GetPrimAtPath(prefix)) { @@ -396,12 +346,8 @@ _IsInstanceProxyPath(const UsdStageRefPtr& stage, const SdfPath& path) /// Ensures that a prim exists at \p path on \p stage and that the prim is /// neither an instance nor an instance proxy. -static -UsdPrim -_UninstancePrim( - const UsdStageRefPtr& stage, - const SdfPath& path, - const std::string& reason) +static UsdPrim +_UninstancePrim(const UsdStageRefPtr& stage, const SdfPath& path, const std::string& reason) { bool didUninstance = false; for (const SdfPath& prefix : path.GetPrefixes()) { @@ -410,16 +356,13 @@ _UninstancePrim( prim.SetInstanceable(false); didUninstance = true; } - } - else { + } else { break; } } if (didUninstance) { - TF_WARN("Uninstanced <%s> (and ancestors) because: %s", - path.GetText(), - reason.c_str()); + TF_WARN("Uninstanced <%s> (and ancestors) because: %s", path.GetText(), reason.c_str()); } return stage->OverridePrim(path); @@ -523,13 +466,13 @@ class _UVMappingManager using MappingGroups = std::map; MappingGroups mappingGroups; for (const auto& iter : _shapeNameToUVNames) { - const TfToken& shapeName = iter.first; + const TfToken& shapeName = iter.first; const TfTokenVector& streams = iter.second; mappingGroups[streams].push_back(shapeName); } // Find out the most common one, which will take over the unspecialized material: - size_t largestSize = 0; + size_t largestSize = 0; TfTokenVector largestSet; for (const auto& iter : mappingGroups) { if (iter.second.size() > largestSize) { @@ -555,7 +498,7 @@ class _UVMappingManager const UsdShadeMaterial& getMaterial(const TfToken& shapeName) { // Look for an existing material for the requested shape: - const TfTokenVector& uvNames = _shapeNameToUVNames[shapeName]; + const TfTokenVector& uvNames = _shapeNameToUVNames[shapeName]; MaterialMappings::const_iterator iter = _uvNamesToMaterial.find(uvNames); if (iter != _uvNamesToMaterial.end()) { return iter->second; diff --git a/lib/mayaUsd/fileio/shading/shadingModeExporterContext.h b/lib/mayaUsd/fileio/shading/shadingModeExporterContext.h index 6c93a0130e..95ec3997ff 100644 --- a/lib/mayaUsd/fileio/shading/shadingModeExporterContext.h +++ b/lib/mayaUsd/fileio/shading/shadingModeExporterContext.h @@ -16,54 +16,42 @@ #ifndef PXRUSDMAYA_SHADING_MODE_EXPORTER_CONTEXT_H #define PXRUSDMAYA_SHADING_MODE_EXPORTER_CONTEXT_H -#include -#include -#include - -#include -#include +#include +#include +#include +#include -#include #include #include +#include #include #include #include -#include -#include -#include -#include +#include +#include + +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE class UsdMayaShadingModeExportContext { public: - void SetShadingEngine(const MObject& shadingEngine) { - _shadingEngine = shadingEngine; - } + void SetShadingEngine(const MObject& shadingEngine) { _shadingEngine = shadingEngine; } MObject GetShadingEngine() const { return _shadingEngine; } const UsdStageRefPtr& GetUsdStage() const { return _stage; } - UsdMayaWriteJobContext& GetWriteJobContext() const { - return _writeJobContext; - } + UsdMayaWriteJobContext& GetWriteJobContext() const { return _writeJobContext; } - const UsdMayaJobExportArgs& GetExportArgs() const { - return _writeJobContext.GetArgs(); - } + const UsdMayaJobExportArgs& GetExportArgs() const { return _writeJobContext.GetArgs(); } - bool GetMergeTransformAndShape() const { - return GetExportArgs().mergeTransformAndShape; - } - const SdfPath& GetOverrideRootPath() const { - return GetExportArgs().usdModelRootOverridePath; - } - const SdfPathSet& GetBindableRoots() const { - return _bindableRoots; - } + bool GetMergeTransformAndShape() const { return GetExportArgs().mergeTransformAndShape; } + const SdfPath& GetOverrideRootPath() const { return GetExportArgs().usdModelRootOverridePath; } + const SdfPathSet& GetBindableRoots() const { return _bindableRoots; } MAYAUSD_CORE_PUBLIC void SetSurfaceShaderPlugName(const TfToken& surfaceShaderPlugName); @@ -72,9 +60,7 @@ class UsdMayaShadingModeExportContext MAYAUSD_CORE_PUBLIC void SetDisplacementShaderPlugName(const TfToken& displacementShaderPlugName); - const UsdMayaUtil::MDagPathMap& GetDagPathToUsdMap() const { - return _dagPathToUsdMap; - } + const UsdMayaUtil::MDagPathMap& GetDagPathToUsdMap() const { return _dagPathToUsdMap; } MAYAUSD_CORE_PUBLIC MPlug GetSurfaceShaderPlug() const; @@ -123,32 +109,30 @@ class UsdMayaShadingModeExportContext /// given \p assignmentsToBind. MAYAUSD_CORE_PUBLIC void BindStandardMaterialPrim( - const UsdPrim & materialPrim, - const AssignmentVector& assignmentsToBind, - SdfPathSet* const boundPrimPaths=nullptr) const; + const UsdPrim& materialPrim, + const AssignmentVector& assignmentsToBind, + SdfPathSet* const boundPrimPaths = nullptr) const; MAYAUSD_CORE_PUBLIC UsdMayaShadingModeExportContext( - const MObject& shadingEngine, - UsdMayaWriteJobContext& writeJobContext, - const UsdMayaUtil::MDagPathMap& dagPathToUsdMap); + const MObject& shadingEngine, + UsdMayaWriteJobContext& writeJobContext, + const UsdMayaUtil::MDagPathMap& dagPathToUsdMap); private: - MObject _shadingEngine; - const UsdStageRefPtr& _stage; + MObject _shadingEngine; + const UsdStageRefPtr& _stage; const UsdMayaUtil::MDagPathMap& _dagPathToUsdMap; - UsdMayaWriteJobContext& _writeJobContext; - TfToken _surfaceShaderPlugName; - TfToken _volumeShaderPlugName; - TfToken _displacementShaderPlugName; + UsdMayaWriteJobContext& _writeJobContext; + TfToken _surfaceShaderPlugName; + TfToken _volumeShaderPlugName; + TfToken _displacementShaderPlugName; /// Shaders that are bound to prims under \p _bindableRoot paths will get /// exported. If \p bindableRoots is empty, it will export all. SdfPathSet _bindableRoots; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/shading/shadingModeImporter.cpp b/lib/mayaUsd/fileio/shading/shadingModeImporter.cpp index e1f1b71201..a3faef2b76 100644 --- a/lib/mayaUsd/fileio/shading/shadingModeImporter.cpp +++ b/lib/mayaUsd/fileio/shading/shadingModeImporter.cpp @@ -15,11 +15,6 @@ // #include "shadingModeImporter.h" -#include -#include -#include -#include - #include #include #include @@ -27,16 +22,16 @@ #include #include -PXR_NAMESPACE_OPEN_SCOPE +#include +#include +#include +#include -TF_DEFINE_PUBLIC_TOKENS(UsdMayaShadingModeImporterTokens, - PXRUSDMAYA_SHADING_MODE_IMPORTER_TOKENS); +PXR_NAMESPACE_OPEN_SCOPE +TF_DEFINE_PUBLIC_TOKENS(UsdMayaShadingModeImporterTokens, PXRUSDMAYA_SHADING_MODE_IMPORTER_TOKENS); -bool -UsdMayaShadingModeImportContext::GetCreatedObject( - const UsdPrim& prim, - MObject* obj) const +bool UsdMayaShadingModeImportContext::GetCreatedObject(const UsdPrim& prim, MObject* obj) const { if (!prim) { return false; @@ -51,10 +46,7 @@ UsdMayaShadingModeImportContext::GetCreatedObject( return false; } -MObject -UsdMayaShadingModeImportContext::AddCreatedObject( - const UsdPrim& prim, - const MObject& obj) +MObject UsdMayaShadingModeImportContext::AddCreatedObject(const UsdPrim& prim, const MObject& obj) { if (prim) { return AddCreatedObject(prim.GetPath(), obj); @@ -63,10 +55,7 @@ UsdMayaShadingModeImportContext::AddCreatedObject( return obj; } -MObject -UsdMayaShadingModeImportContext::AddCreatedObject( - const SdfPath& path, - const MObject& obj) +MObject UsdMayaShadingModeImportContext::AddCreatedObject(const SdfPath& path, const MObject& obj) { if (!path.IsEmpty()) { _context->RegisterNewMayaNode(path.GetString(), obj); @@ -75,35 +64,32 @@ UsdMayaShadingModeImportContext::AddCreatedObject( return obj; } -MObject -UsdMayaShadingModeImportContext::CreateShadingEngine() const +MObject UsdMayaShadingModeImportContext::CreateShadingEngine() const { const TfToken shadingEngineName = GetShadingEngineName(); if (shadingEngineName.IsEmpty()) { return MObject(); } - MStatus status; - MFnSet fnSet; + MStatus status; + MFnSet fnSet; MSelectionList tmpSelList; - MObject shadingEngine = - fnSet.create(tmpSelList, MFnSet::kRenderableOnly, &status); + MObject shadingEngine = fnSet.create(tmpSelList, MFnSet::kRenderableOnly, &status); if (status != MS::kSuccess) { - TF_RUNTIME_ERROR("Failed to create shadingEngine: %s", - shadingEngineName.GetText()); + TF_RUNTIME_ERROR("Failed to create shadingEngine: %s", shadingEngineName.GetText()); return MObject(); } - fnSet.setName(shadingEngineName.GetText(), - /* createNamespace = */ true, - &status); + fnSet.setName( + shadingEngineName.GetText(), + /* createNamespace = */ true, + &status); CHECK_MSTATUS_AND_RETURN(status, MObject()); return shadingEngine; } -TfToken -UsdMayaShadingModeImportContext::GetShadingEngineName() const +TfToken UsdMayaShadingModeImportContext::GetShadingEngineName() const { if (!_shadeMaterial && !_boundPrim) { return TfToken(); @@ -123,63 +109,51 @@ UsdMayaShadingModeImportContext::GetShadingEngineName() const // To make sure that the shadingEngine object names do not collide with // Maya transform or shape node names, we put the shadingEngine objects // into their own namespace. - const TfToken shadingEngineName( - TfStringPrintf( - "%s:%s", - UsdMayaShadingModeImporterTokens->MayaMaterialNamespace.GetText(), - primName.GetText())); + const TfToken shadingEngineName(TfStringPrintf( + "%s:%s", + UsdMayaShadingModeImporterTokens->MayaMaterialNamespace.GetText(), + primName.GetText())); return shadingEngineName; } -TfToken -UsdMayaShadingModeImportContext::GetSurfaceShaderPlugName() const +TfToken UsdMayaShadingModeImportContext::GetSurfaceShaderPlugName() const { return _surfaceShaderPlugName; } -TfToken -UsdMayaShadingModeImportContext::GetVolumeShaderPlugName() const +TfToken UsdMayaShadingModeImportContext::GetVolumeShaderPlugName() const { return _volumeShaderPlugName; } -TfToken -UsdMayaShadingModeImportContext::GetDisplacementShaderPlugName() const +TfToken UsdMayaShadingModeImportContext::GetDisplacementShaderPlugName() const { return _displacementShaderPlugName; } -void -UsdMayaShadingModeImportContext::SetShadingEngineName( - const TfToken& shadingEngineName) +void UsdMayaShadingModeImportContext::SetShadingEngineName(const TfToken& shadingEngineName) { _shadingEngineName = shadingEngineName; } -void -UsdMayaShadingModeImportContext::SetSurfaceShaderPlugName( - const TfToken& surfaceShaderPlugName) +void UsdMayaShadingModeImportContext::SetSurfaceShaderPlugName(const TfToken& surfaceShaderPlugName) { _surfaceShaderPlugName = surfaceShaderPlugName; } -void -UsdMayaShadingModeImportContext::SetVolumeShaderPlugName( - const TfToken& volumeShaderPlugName) +void UsdMayaShadingModeImportContext::SetVolumeShaderPlugName(const TfToken& volumeShaderPlugName) { _volumeShaderPlugName = volumeShaderPlugName; } -void -UsdMayaShadingModeImportContext::SetDisplacementShaderPlugName( - const TfToken& displacementShaderPlugName) +void UsdMayaShadingModeImportContext::SetDisplacementShaderPlugName( + const TfToken& displacementShaderPlugName) { _displacementShaderPlugName = displacementShaderPlugName; } -UsdMayaPrimReaderContext* -UsdMayaShadingModeImportContext::GetPrimReaderContext() const +UsdMayaPrimReaderContext* UsdMayaShadingModeImportContext::GetPrimReaderContext() const { return _context; } diff --git a/lib/mayaUsd/fileio/shading/shadingModeImporter.h b/lib/mayaUsd/fileio/shading/shadingModeImporter.h index 539f7ca30a..34cc58c311 100644 --- a/lib/mayaUsd/fileio/shading/shadingModeImporter.h +++ b/lib/mayaUsd/fileio/shading/shadingModeImporter.h @@ -16,49 +16,47 @@ #ifndef PXRUSDMAYA_SHADING_MODE_IMPORTER_H #define PXRUSDMAYA_SHADING_MODE_IMPORTER_H -#include - -#include +#include +#include +#include -#include #include #include +#include #include #include #include #include -#include -#include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -#define PXRUSDMAYA_SHADING_MODE_IMPORTER_TOKENS \ - ((MayaMaterialNamespace, "USD_Materials")) +#define PXRUSDMAYA_SHADING_MODE_IMPORTER_TOKENS ((MayaMaterialNamespace, "USD_Materials")) -TF_DECLARE_PUBLIC_TOKENS(UsdMayaShadingModeImporterTokens, +TF_DECLARE_PUBLIC_TOKENS( + UsdMayaShadingModeImporterTokens, MAYAUSD_CORE_PUBLIC, PXRUSDMAYA_SHADING_MODE_IMPORTER_TOKENS); - class UsdMayaShadingModeImportContext { public: - const UsdShadeMaterial& GetShadeMaterial() const { return _shadeMaterial; } - const UsdGeomGprim& GetBoundPrim() const { return _boundPrim; } + const UsdGeomGprim& GetBoundPrim() const { return _boundPrim; } UsdMayaShadingModeImportContext( - const UsdShadeMaterial& shadeMaterial, - const UsdGeomGprim& boundPrim, - UsdMayaPrimReaderContext* context) : - _shadeMaterial(shadeMaterial), - _boundPrim(boundPrim), - _context(context), - _surfaceShaderPlugName("surfaceShader"), - _volumeShaderPlugName("volumeShader"), - _displacementShaderPlugName("displacementShader") + const UsdShadeMaterial& shadeMaterial, + const UsdGeomGprim& boundPrim, + UsdMayaPrimReaderContext* context) + : _shadeMaterial(shadeMaterial) + , _boundPrim(boundPrim) + , _context(context) + , _surfaceShaderPlugName("surfaceShader") + , _volumeShaderPlugName("volumeShader") + , _displacementShaderPlugName("displacementShader") { } @@ -137,8 +135,8 @@ class UsdMayaShadingModeImportContext UsdMayaPrimReaderContext* GetPrimReaderContext() const; private: - const UsdShadeMaterial& _shadeMaterial; - const UsdGeomGprim& _boundPrim; + const UsdShadeMaterial& _shadeMaterial; + const UsdGeomGprim& _boundPrim; UsdMayaPrimReaderContext* _context; TfToken _shadingEngineName; @@ -152,5 +150,4 @@ typedef std::function #include -#include #include #include #include #include #include +#include #include #include #include @@ -63,52 +63,42 @@ PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PRIVATE_TOKENS( _tokens, - ((PxrShaderPrefix, "Pxr")) - ((DefaultShaderOutputName, "out")) - ((MayaShaderOutputName, "outColor")) + ((PxrShaderPrefix, "Pxr"))((DefaultShaderOutputName, "out"))((MayaShaderOutputName, "outColor")) - ((RmanPlugPreferenceName, "rfmShadingEngineUseRmanPlugs")) + ((RmanPlugPreferenceName, "rfmShadingEngineUseRmanPlugs")) - ((RmanVolumeShaderPlugName, "volumeShader")) -); + ((RmanVolumeShaderPlugName, "volumeShader"))); namespace { -struct _ShadingPlugs { +struct _ShadingPlugs +{ const TfToken surface; const TfToken displacement; }; -static const _ShadingPlugs _RmanPlugs { - TfToken("rman__surface"), - TfToken("rman__displacement") -}; +static const _ShadingPlugs _RmanPlugs { TfToken("rman__surface"), TfToken("rman__displacement") }; -static const _ShadingPlugs _MayaPlugs { - TfToken("surfaceShader"), - TfToken("displacementShader") -}; +static const _ShadingPlugs _MayaPlugs { TfToken("surfaceShader"), TfToken("displacementShader") }; -static -_ShadingPlugs -_GetShadingPlugs() +static _ShadingPlugs _GetShadingPlugs() { // Check for rfmShadingEngineUseRmanPlugs preference // If set to 1, use rman__surface and rman__displacement plug names // Otherwise, fallback to Maya's surfaceShader and displacementShader bool exists = false; - int useRmanPlugs = MGlobal::optionVarIntValue( - _tokens->RmanPlugPreferenceName.GetText(), &exists); + int useRmanPlugs + = MGlobal::optionVarIntValue(_tokens->RmanPlugPreferenceName.GetText(), &exists); return (exists && useRmanPlugs) ? _RmanPlugs : _MayaPlugs; } -class PxrRisShadingModeExporter : public UsdMayaShadingModeExporter { +class PxrRisShadingModeExporter : public UsdMayaShadingModeExporter +{ public: - PxrRisShadingModeExporter() {} -private: + PxrRisShadingModeExporter() { } - void - PreExport(UsdMayaShadingModeExportContext* context) override +private: + void PreExport(UsdMayaShadingModeExportContext* context) override { context->SetVolumeShaderPlugName(_tokens->RmanVolumeShaderPlugName); @@ -117,8 +107,7 @@ class PxrRisShadingModeExporter : public UsdMayaShadingModeExporter { context->SetDisplacementShaderPlugName(shadingPlugs.displacement); } - TfToken - _GetShaderTypeName(const MFnDependencyNode& depNode) + TfToken _GetShaderTypeName(const MFnDependencyNode& depNode) { const TfToken mayaTypeName(depNode.typeName().asChar()); @@ -134,12 +123,11 @@ class PxrRisShadingModeExporter : public UsdMayaShadingModeExporter { return mayaTypeName; } - UsdPrim - _ExportShadingNodeHelper( - const UsdPrim& materialPrim, - const MFnDependencyNode& depNode, - const UsdMayaShadingModeExportContext& context, - SdfPathSet* processedPaths) + UsdPrim _ExportShadingNodeHelper( + const UsdPrim& materialPrim, + const MFnDependencyNode& depNode, + const UsdMayaShadingModeExportContext& context, + SdfPathSet* processedPaths) { UsdStagePtr stage = materialPrim.GetStage(); @@ -147,8 +135,7 @@ class PxrRisShadingModeExporter : public UsdMayaShadingModeExporter { // well. currently, when we re-import, we don't get the display color so // it shows up as black. - const TfToken shaderPrimName( - UsdMayaUtil::SanitizeName(depNode.name().asChar())); + const TfToken shaderPrimName(UsdMayaUtil::SanitizeName(depNode.name().asChar())); const SdfPath shaderPath = materialPrim.GetPath().AppendChild(shaderPrimName); if (processedPaths->count(shaderPath) == 1u) { return stage->GetPrimAtPath(shaderPath); @@ -161,9 +148,9 @@ class PxrRisShadingModeExporter : public UsdMayaShadingModeExporter { if (!TfStringStartsWith(risShaderType, _tokens->PxrShaderPrefix)) { TF_RUNTIME_ERROR( - "Skipping '%s' because its type '%s' is not Pxr-prefixed.", - depNode.name().asChar(), - risShaderType.GetText()); + "Skipping '%s' because its type '%s' is not Pxr-prefixed.", + depNode.name().asChar(), + risShaderType.GetText()); return UsdPrim(); } @@ -184,7 +171,7 @@ class PxrRisShadingModeExporter : public UsdMayaShadingModeExporter { } // We can identify "output" parameters for Pxr* by checking if they - // are writable. + // are writable. if (!MFnAttribute(attrPlug.attribute()).isWritable()) { // If needed, we could author these as outputs, but // currently don't have an immediate need to bake these out. @@ -213,8 +200,7 @@ class PxrRisShadingModeExporter : public UsdMayaShadingModeExporter { attrPlug.name().asChar()); } } - } - else { + } else { inputAttrPlugs.push_back(attrPlug); } } @@ -223,49 +209,41 @@ class PxrRisShadingModeExporter : public UsdMayaShadingModeExporter { // this is writing out things that live on the MFnDependencyNode. // maybe that's OK? nothing downstream cares about it. - const TfToken attrName = TfToken( - UsdMayaShadingUtil::GetStandardAttrName(attrPlug, false)); + const TfToken attrName + = TfToken(UsdMayaShadingUtil::GetStandardAttrName(attrPlug, false)); if (attrName.IsEmpty()) { continue; } - const SdfValueTypeName attrTypeName = - Converter::getUsdTypeName(attrPlug); + const SdfValueTypeName attrTypeName = Converter::getUsdTypeName(attrPlug); if (!attrTypeName) { continue; } - UsdShadeInput input = shaderSchema.CreateInput(attrName, - attrTypeName); + UsdShadeInput input = shaderSchema.CreateInput(attrName, attrTypeName); if (!input) { continue; } if (attrPlug.isElement()) { - UsdMayaRoundTripUtil::MarkAttributeAsArray(input.GetAttr(), - 0u); + UsdMayaRoundTripUtil::MarkAttributeAsArray(input.GetAttr(), 0u); } - UsdMayaWriteUtil::SetUsdAttr(attrPlug, - input.GetAttr(), - UsdTimeCode::Default()); + UsdMayaWriteUtil::SetUsdAttr(attrPlug, input.GetAttr(), UsdTimeCode::Default()); // Now handle plug connections and recurse if necessary. if (!attrPlug.isConnected() || !attrPlug.isDestination()) { continue; } - const MPlug connectedPlug(UsdMayaUtil::GetConnected(attrPlug)); - const MFnDependencyNode connectedDepFn(connectedPlug.node(), - &status); + const MPlug connectedPlug(UsdMayaUtil::GetConnected(attrPlug)); + const MFnDependencyNode connectedDepFn(connectedPlug.node(), &status); if (status != MS::kSuccess) { continue; } - if (UsdPrim cPrim = _ExportShadingNodeHelper(materialPrim, - connectedDepFn, - context, - processedPaths)) { + if (UsdPrim cPrim + = _ExportShadingNodeHelper(materialPrim, connectedDepFn, context, processedPaths)) { UsdShadeConnectableAPI::ConnectToSource( input, UsdShadeShader(cPrim), @@ -276,27 +254,22 @@ class PxrRisShadingModeExporter : public UsdMayaShadingModeExporter { return shaderSchema.GetPrim(); } - UsdPrim - _ExportShadingNode( - const UsdPrim& materialPrim, - const MFnDependencyNode& depNode, - const UsdMayaShadingModeExportContext& context) + UsdPrim _ExportShadingNode( + const UsdPrim& materialPrim, + const MFnDependencyNode& depNode, + const UsdMayaShadingModeExportContext& context) { SdfPathSet processedNodes; - return _ExportShadingNodeHelper(materialPrim, - depNode, - context, - &processedNodes); + return _ExportShadingNodeHelper(materialPrim, depNode, context, &processedNodes); } - void - Export( - const UsdMayaShadingModeExportContext& context, - UsdShadeMaterial* const mat, - SdfPathSet* const boundPrimPaths) override + void Export( + const UsdMayaShadingModeExportContext& context, + UsdShadeMaterial* const mat, + SdfPathSet* const boundPrimPaths) override { - const UsdMayaShadingModeExportContext::AssignmentVector& assignments = - context.GetAssignments(); + const UsdMayaShadingModeExportContext::AssignmentVector& assignments + = context.GetAssignments(); if (assignments.empty()) { return; } @@ -316,93 +289,61 @@ class PxrRisShadingModeExporter : public UsdMayaShadingModeExporter { MStatus status; - const MFnDependencyNode surfaceDepNodeFn( - context.GetSurfaceShader(), - &status); + const MFnDependencyNode surfaceDepNodeFn(context.GetSurfaceShader(), &status); if (status == MS::kSuccess) { - UsdPrim surfaceShaderPrim = - _ExportShadingNode(materialPrim, - surfaceDepNodeFn, - context); + UsdPrim surfaceShaderPrim = _ExportShadingNode(materialPrim, surfaceDepNodeFn, context); UsdShadeShader surfaceShaderSchema(surfaceShaderPrim); if (surfaceShaderSchema) { - UsdShadeOutput surfaceShaderOutput = - surfaceShaderSchema.CreateOutput( - _tokens->DefaultShaderOutputName, - SdfValueTypeNames->Token); + UsdShadeOutput surfaceShaderOutput = surfaceShaderSchema.CreateOutput( + _tokens->DefaultShaderOutputName, SdfValueTypeNames->Token); - riMaterialAPI.SetSurfaceSource( - surfaceShaderOutput.GetAttr().GetPath()); + riMaterialAPI.SetSurfaceSource(surfaceShaderOutput.GetAttr().GetPath()); } } - const MFnDependencyNode volumeDepNodeFn( - context.GetVolumeShader(), - &status); + const MFnDependencyNode volumeDepNodeFn(context.GetVolumeShader(), &status); if (status == MS::kSuccess) { - UsdPrim volumeShaderPrim = - _ExportShadingNode(materialPrim, - volumeDepNodeFn, - context); + UsdPrim volumeShaderPrim = _ExportShadingNode(materialPrim, volumeDepNodeFn, context); UsdShadeShader volumeShaderSchema(volumeShaderPrim); if (volumeShaderSchema) { - UsdShadeOutput volumeShaderOutput = - volumeShaderSchema.CreateOutput( - _tokens->DefaultShaderOutputName, - SdfValueTypeNames->Token); + UsdShadeOutput volumeShaderOutput = volumeShaderSchema.CreateOutput( + _tokens->DefaultShaderOutputName, SdfValueTypeNames->Token); - riMaterialAPI.SetVolumeSource( - volumeShaderOutput.GetAttr().GetPath()); + riMaterialAPI.SetVolumeSource(volumeShaderOutput.GetAttr().GetPath()); } } - const MFnDependencyNode displacementDepNodeFn( - context.GetDisplacementShader(), - &status); + const MFnDependencyNode displacementDepNodeFn(context.GetDisplacementShader(), &status); if (status == MS::kSuccess) { - UsdPrim displacementShaderPrim = - _ExportShadingNode(materialPrim, - displacementDepNodeFn, - context); + UsdPrim displacementShaderPrim + = _ExportShadingNode(materialPrim, displacementDepNodeFn, context); UsdShadeShader displacementShaderSchema(displacementShaderPrim); if (displacementShaderSchema) { - UsdShadeOutput displacementShaderOutput = - displacementShaderSchema.CreateOutput( - _tokens->DefaultShaderOutputName, - SdfValueTypeNames->Token); + UsdShadeOutput displacementShaderOutput = displacementShaderSchema.CreateOutput( + _tokens->DefaultShaderOutputName, SdfValueTypeNames->Token); - riMaterialAPI.SetDisplacementSource( - displacementShaderOutput.GetAttr().GetPath()); + riMaterialAPI.SetDisplacementSource(displacementShaderOutput.GetAttr().GetPath()); } } } }; -} +} // namespace TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaShadingModeExportContext, pxrRis) { UsdMayaShadingModeRegistry::GetInstance().RegisterExporter( - "pxrRis", - "RfM Shaders", - "", - []() -> UsdMayaShadingModeExporterPtr { + "pxrRis", "RfM Shaders", "", []() -> UsdMayaShadingModeExporterPtr { return UsdMayaShadingModeExporterPtr( - static_cast( - new PxrRisShadingModeExporter())); - } - ); + static_cast(new PxrRisShadingModeExporter())); + }); } namespace { -static -TfToken -_GetMayaTypeNameForShaderId( - const TfToken& shaderId, - bool defaultToMayaNodes = true) +static TfToken _GetMayaTypeNameForShaderId(const TfToken& shaderId, bool defaultToMayaNodes = true) { // Remap the mayaTypeName if found in the RIS table. - for (const auto & i : RfmNodesToShaderIds) { + for (const auto& i : RfmNodesToShaderIds) { if (i.second == shaderId) { return i.first; } @@ -412,19 +353,15 @@ _GetMayaTypeNameForShaderId( return defaultToMayaNodes ? shaderId : TfToken(); } -static -MObject -_CreateAndPopulateShaderObject( - const UsdShadeShader& shaderSchema, - const UsdMayaShadingNodeType shadingNodeType, - UsdMayaShadingModeImportContext* context); - -static -MObject -_GetOrCreateShaderObject( - const UsdShadeShader& shaderSchema, - const UsdMayaShadingNodeType shadingNodeType, - UsdMayaShadingModeImportContext* context) +static MObject _CreateAndPopulateShaderObject( + const UsdShadeShader& shaderSchema, + const UsdMayaShadingNodeType shadingNodeType, + UsdMayaShadingModeImportContext* context); + +static MObject _GetOrCreateShaderObject( + const UsdShadeShader& shaderSchema, + const UsdMayaShadingNodeType shadingNodeType, + UsdMayaShadingModeImportContext* context) { MObject shaderObj; if (!shaderSchema) { @@ -449,12 +386,10 @@ _GetOrCreateShaderObject( return context->AddCreatedObject(shaderSchema.GetPrim(), shaderObj); } -static -MPlug -_ImportAttr(const UsdAttribute& usdAttr, const MFnDependencyNode& fnDep) +static MPlug _ImportAttr(const UsdAttribute& usdAttr, const MFnDependencyNode& fnDep) { const std::string mayaAttrName = usdAttr.GetBaseName().GetString(); - MStatus status; + MStatus status; MPlug mayaAttrPlug = fnDep.findPlug(mayaAttrName.c_str(), &status); if (status != MS::kSuccess) { @@ -474,11 +409,8 @@ _ImportAttr(const UsdAttribute& usdAttr, const MFnDependencyNode& fnDep) return mayaAttrPlug; } -static -UsdMayaShadingNodeType -_ComputeShadingNodeTypeForShaderId( - const TfToken& shaderId, - const UsdMayaShadingNodeType& fallback) +static UsdMayaShadingNodeType +_ComputeShadingNodeTypeForShaderId(const TfToken& shaderId, const UsdMayaShadingNodeType& fallback) { MString mayaType(_GetMayaTypeNameForShaderId(shaderId).GetText()); MStatus status; @@ -490,17 +422,17 @@ _ComputeShadingNodeTypeForShaderId( status = MGlobal::executeCommand(cmd, compoundClassifications, false, false); CHECK_MSTATUS_AND_RETURN(status, fallback); - static const std::vector > - _classificationsToTypes = { - { "texture/", UsdMayaShadingNodeType::Texture }, - { "utility/", UsdMayaShadingNodeType::Utility }, - { "shader/", UsdMayaShadingNodeType::Shader }, - }; + static const std::vector> _classificationsToTypes + = { + { "texture/", UsdMayaShadingNodeType::Texture }, + { "utility/", UsdMayaShadingNodeType::Utility }, + { "shader/", UsdMayaShadingNodeType::Shader }, + }; // The docs for getClassification are pretty confusing. You'd think that // the string array returned would give you each "classification", but // instead, it's a list of "single compound classification string by joining - // the individual classifications with ':'". + // the individual classifications with ':'". // Loop over the compoundClassifications, though I believe // compoundClassifications will always have size 0 or 1. @@ -511,11 +443,9 @@ _ComputeShadingNodeTypeForShaderId( const MString& compoundClassification = compoundClassifications[i]; #endif const std::string compoundClassificationStr(compoundClassification.asChar()); - for (const std::string& classification : - TfStringSplit(compoundClassificationStr, ":")) { + for (const std::string& classification : TfStringSplit(compoundClassificationStr, ":")) { for (const auto& classPrefixAndType : _classificationsToTypes) { - if (TfStringStartsWith( - classification, classPrefixAndType.first)) { + if (TfStringStartsWith(classification, classPrefixAndType.first)) { return classPrefixAndType.second; } } @@ -525,56 +455,51 @@ _ComputeShadingNodeTypeForShaderId( return fallback; } -static -UsdMayaShadingNodeType -_GetShadingNodeTypeForNestedNode( - const UsdShadeShader& shaderSchema) +static UsdMayaShadingNodeType _GetShadingNodeTypeForNestedNode(const UsdShadeShader& shaderSchema) { TfToken shaderId; shaderSchema.GetIdAttr().Get(&shaderId); static std::map _cache; - const auto iter = _cache.find(shaderId); + const auto iter = _cache.find(shaderId); if (iter != _cache.end()) { return iter->second; } return _cache[shaderId] = _ComputeShadingNodeTypeForShaderId( - shaderId, + shaderId, // any "nested" shader objects that we can't classify should // fallback to NonShading. UsdMayaShadingNodeType::NonShading); } - // Should only be called by _GetOrCreateShaderObject, no one else. -MObject -_CreateAndPopulateShaderObject( - const UsdShadeShader& shaderSchema, - const UsdMayaShadingNodeType shadingNodeType, - UsdMayaShadingModeImportContext* context) +MObject _CreateAndPopulateShaderObject( + const UsdShadeShader& shaderSchema, + const UsdMayaShadingNodeType shadingNodeType, + UsdMayaShadingModeImportContext* context) { TfToken shaderId; shaderSchema.GetIdAttr().Get(&shaderId); TfToken mayaTypeName = _GetMayaTypeNameForShaderId(shaderId); - MStatus status; - MObject shaderObj; + MStatus status; + MObject shaderObj; MFnDependencyNode depFn; if (!(UsdMayaTranslatorUtil::CreateShaderNode( - MString(shaderSchema.GetPrim().GetName().GetText()), - mayaTypeName.GetText(), - shadingNodeType, - &status, - &shaderObj) - && depFn.setObject(shaderObj))) { + MString(shaderSchema.GetPrim().GetName().GetText()), + mayaTypeName.GetText(), + shadingNodeType, + &status, + &shaderObj) + && depFn.setObject(shaderObj))) { // we need to make sure assumes those types are loaded.. TF_RUNTIME_ERROR( - "Could not create node of type '%s' for shader '%s'. " - "Probably missing a loadPlugin.\n", - mayaTypeName.GetText(), - shaderSchema.GetPrim().GetName().GetText()); + "Could not create node of type '%s' for shader '%s'. " + "Probably missing a loadPlugin.\n", + mayaTypeName.GetText(), + shaderSchema.GetPrim().GetName().GetText()); return MObject(); } @@ -586,14 +511,12 @@ _CreateAndPopulateShaderObject( } UsdShadeConnectableAPI source; - TfToken sourceOutputName; - UsdShadeAttributeType sourceType; + TfToken sourceOutputName; + UsdShadeAttributeType sourceType; // Follow shader connections and recurse. - if (!UsdShadeConnectableAPI::GetConnectedSource(input, - &source, - &sourceOutputName, - &sourceType)) { + if (!UsdShadeConnectableAPI::GetConnectedSource( + input, &source, &sourceOutputName, &sourceType)) { continue; } @@ -603,9 +526,7 @@ _CreateAndPopulateShaderObject( } MObject sourceObj = _GetOrCreateShaderObject( - sourceShaderSchema, - _GetShadingNodeTypeForNestedNode(sourceShaderSchema), - context); + sourceShaderSchema, _GetShadingNodeTypeForNestedNode(sourceShaderSchema), context); MFnDependencyNode sourceDepFn(sourceObj, &status); if (status != MS::kSuccess) { @@ -637,7 +558,7 @@ _CreateAndPopulateShaderObject( }; // anonymous namespace -DEFINE_SHADING_MODE_IMPORTER(pxrRis, "RfM Shaders", "",context) +DEFINE_SHADING_MODE_IMPORTER(pxrRis, "RfM Shaders", "", context) { // RenderMan for Maya wants the shader nodes to get hooked into the shading // group via its own plugs. @@ -672,16 +593,14 @@ DEFINE_SHADING_MODE_IMPORTER(pxrRis, "RfM Shaders", "",context) displacementShader = UsdRiMaterialAPI(shadeMaterial).GetDisplacement(); } - MObject surfaceShaderObj = _GetOrCreateShaderObject( - surfaceShader, UsdMayaShadingNodeType::Shader, context); - MObject volumeShaderObj = _GetOrCreateShaderObject( - volumeShader, UsdMayaShadingNodeType::Shader, context); - MObject displacementShaderObj = _GetOrCreateShaderObject( - displacementShader, UsdMayaShadingNodeType::Shader, context); + MObject surfaceShaderObj + = _GetOrCreateShaderObject(surfaceShader, UsdMayaShadingNodeType::Shader, context); + MObject volumeShaderObj + = _GetOrCreateShaderObject(volumeShader, UsdMayaShadingNodeType::Shader, context); + MObject displacementShaderObj + = _GetOrCreateShaderObject(displacementShader, UsdMayaShadingNodeType::Shader, context); - if (surfaceShaderObj.isNull() && - volumeShaderObj.isNull() && - displacementShaderObj.isNull()) { + if (surfaceShaderObj.isNull() && volumeShaderObj.isNull() && displacementShaderObj.isNull()) { return MObject(); } @@ -691,7 +610,7 @@ DEFINE_SHADING_MODE_IMPORTER(pxrRis, "RfM Shaders", "",context) return MObject(); } MStatus status; - MFnSet fnSet(shadingEngine, &status); + MFnSet fnSet(shadingEngine, &status); if (status != MS::kSuccess) { return MObject(); } @@ -703,19 +622,19 @@ DEFINE_SHADING_MODE_IMPORTER(pxrRis, "RfM Shaders", "",context) return MObject(); } - MPlug shaderOutputPlug = - depNodeFn.findPlug(_tokens->MayaShaderOutputName.GetText(), &status); + MPlug shaderOutputPlug + = depNodeFn.findPlug(_tokens->MayaShaderOutputName.GetText(), &status); if (status != MS::kSuccess || shaderOutputPlug.isNull()) { return MObject(); } - MPlug seInputPlug = - fnSet.findPlug(surfaceShaderPlugName.GetText(), &status); + MPlug seInputPlug = fnSet.findPlug(surfaceShaderPlugName.GetText(), &status); CHECK_MSTATUS_AND_RETURN(status, MObject()); - UsdMayaUtil::Connect(shaderOutputPlug, - seInputPlug, - /* clearDstPlug = */ true); + UsdMayaUtil::Connect( + shaderOutputPlug, + seInputPlug, + /* clearDstPlug = */ true); } const TfToken volumeShaderPlugName = context->GetVolumeShaderPlugName(); @@ -725,19 +644,19 @@ DEFINE_SHADING_MODE_IMPORTER(pxrRis, "RfM Shaders", "",context) return MObject(); } - MPlug shaderOutputPlug = - depNodeFn.findPlug(_tokens->MayaShaderOutputName.GetText(), &status); + MPlug shaderOutputPlug + = depNodeFn.findPlug(_tokens->MayaShaderOutputName.GetText(), &status); if (status != MS::kSuccess || shaderOutputPlug.isNull()) { return MObject(); } - MPlug seInputPlug = - fnSet.findPlug(volumeShaderPlugName.GetText(), &status); + MPlug seInputPlug = fnSet.findPlug(volumeShaderPlugName.GetText(), &status); CHECK_MSTATUS_AND_RETURN(status, MObject()); - UsdMayaUtil::Connect(shaderOutputPlug, - seInputPlug, - /* clearDstPlug = */ true); + UsdMayaUtil::Connect( + shaderOutputPlug, + seInputPlug, + /* clearDstPlug = */ true); } const TfToken displacementShaderPlugName = context->GetDisplacementShaderPlugName(); @@ -747,23 +666,22 @@ DEFINE_SHADING_MODE_IMPORTER(pxrRis, "RfM Shaders", "",context) return MObject(); } - MPlug shaderOutputPlug = - depNodeFn.findPlug(_tokens->MayaShaderOutputName.GetText(), &status); + MPlug shaderOutputPlug + = depNodeFn.findPlug(_tokens->MayaShaderOutputName.GetText(), &status); if (status != MS::kSuccess || shaderOutputPlug.isNull()) { return MObject(); } - MPlug seInputPlug = - fnSet.findPlug(displacementShaderPlugName.GetText(), &status); + MPlug seInputPlug = fnSet.findPlug(displacementShaderPlugName.GetText(), &status); CHECK_MSTATUS_AND_RETURN(status, MObject()); - UsdMayaUtil::Connect(shaderOutputPlug, - seInputPlug, - /* clearDstPlug = */ true); + UsdMayaUtil::Connect( + shaderOutputPlug, + seInputPlug, + /* clearDstPlug = */ true); } return shadingEngine; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/shading/shadingModeRegistry.cpp b/lib/mayaUsd/fileio/shading/shadingModeRegistry.cpp index 770e97eb84..2e2f9c0d34 100644 --- a/lib/mayaUsd/fileio/shading/shadingModeRegistry.cpp +++ b/lib/mayaUsd/fileio/shading/shadingModeRegistry.cpp @@ -15,67 +15,62 @@ // #include "shadingModeRegistry.h" -#include -#include -#include +#include +#include +#include +#include #include #include #include #include -#include -#include -#include -#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PUBLIC_TOKENS(UsdMayaShadingModeTokens, - PXRUSDMAYA_SHADINGMODE_TOKENS); +TF_DEFINE_PUBLIC_TOKENS(UsdMayaShadingModeTokens, PXRUSDMAYA_SHADINGMODE_TOKENS); namespace { - static const std::string _kEmptyString; +static const std::string _kEmptyString; } -struct _ExportShadingMode { - std::string _niceName; - std::string _description; +struct _ExportShadingMode +{ + std::string _niceName; + std::string _description; UsdMayaShadingModeExporterCreator _fn; }; using _ExportRegistry = std::map; static _ExportRegistry _exportReg; -TF_DEFINE_PUBLIC_TOKENS(UsdMayaPreferredMaterialTokens, - PXRUSDMAYA_SHADINGCONVERSION_TOKENS); +TF_DEFINE_PUBLIC_TOKENS(UsdMayaPreferredMaterialTokens, PXRUSDMAYA_SHADINGCONVERSION_TOKENS); -using _MaterialConversionRegistry = std:: - unordered_map; +using _MaterialConversionRegistry + = std::unordered_map; static _MaterialConversionRegistry _conversionReg; -bool -UsdMayaShadingModeRegistry::RegisterExporter( - const std::string& name, - std::string niceName, - std::string description, - UsdMayaShadingModeExporterCreator fn) +bool UsdMayaShadingModeRegistry::RegisterExporter( + const std::string& name, + std::string niceName, + std::string description, + UsdMayaShadingModeExporterCreator fn) { - const TfToken nameToken(name); + const TfToken nameToken(name); std::pair<_ExportRegistry::const_iterator, bool> insertStatus = _exportReg.insert(_ExportRegistry::value_type( nameToken, _ExportShadingMode { std::move(niceName), std::move(description), fn })); if (insertStatus.second) { - UsdMaya_RegistryHelper::AddUnloader([nameToken]() { - _exportReg.erase(nameToken); - }); + UsdMaya_RegistryHelper::AddUnloader([nameToken]() { _exportReg.erase(nameToken); }); } else { TF_CODING_ERROR("Multiple shading exporters named '%s'", name.c_str()); } return insertStatus.second; } -UsdMayaShadingModeExporterCreator -UsdMayaShadingModeRegistry::_GetExporter(const TfToken& name) +UsdMayaShadingModeExporterCreator UsdMayaShadingModeRegistry::_GetExporter(const TfToken& name) { UsdMaya_RegistryHelper::LoadShadingModePlugins(); TfRegistryManager::GetInstance().SubscribeTo(); @@ -83,54 +78,50 @@ UsdMayaShadingModeRegistry::_GetExporter(const TfToken& name) return it == _exportReg.end() ? nullptr : it->second._fn; } -const std::string& -UsdMayaShadingModeRegistry::_GetExporterNiceName(const TfToken& name) { +const std::string& UsdMayaShadingModeRegistry::_GetExporterNiceName(const TfToken& name) +{ UsdMaya_RegistryHelper::LoadShadingModePlugins(); TfRegistryManager::GetInstance().SubscribeTo(); const auto it = _exportReg.find(name); return it == _exportReg.end() ? _kEmptyString : it->second._niceName; } -const std::string& -UsdMayaShadingModeRegistry::_GetExporterDescription(const TfToken& name) { +const std::string& UsdMayaShadingModeRegistry::_GetExporterDescription(const TfToken& name) +{ UsdMaya_RegistryHelper::LoadShadingModePlugins(); TfRegistryManager::GetInstance().SubscribeTo(); const auto it = _exportReg.find(name); return it == _exportReg.end() ? _kEmptyString : it->second._description; } -struct _ImportShadingMode { - std::string _niceName; - std::string _description; +struct _ImportShadingMode +{ + std::string _niceName; + std::string _description; UsdMayaShadingModeImporter _fn; }; using _ImportRegistry = std::map; static _ImportRegistry _importReg; -bool -UsdMayaShadingModeRegistry::RegisterImporter( - const std::string& name, - std::string niceName, - std::string description, - UsdMayaShadingModeImporter fn) +bool UsdMayaShadingModeRegistry::RegisterImporter( + const std::string& name, + std::string niceName, + std::string description, + UsdMayaShadingModeImporter fn) { - const TfToken nameToken(name); + const TfToken nameToken(name); std::pair<_ImportRegistry::const_iterator, bool> insertStatus = _importReg.insert(_ImportRegistry::value_type( nameToken, _ImportShadingMode { std::move(niceName), std::move(description), fn })); if (insertStatus.second) { - UsdMaya_RegistryHelper::AddUnloader([nameToken]() { - _importReg.erase(nameToken); - }); - } - else { + UsdMaya_RegistryHelper::AddUnloader([nameToken]() { _importReg.erase(nameToken); }); + } else { TF_CODING_ERROR("Multiple shading importers named '%s'", name.c_str()); } return insertStatus.second; } -UsdMayaShadingModeImporter -UsdMayaShadingModeRegistry::_GetImporter(const TfToken& name) +UsdMayaShadingModeImporter UsdMayaShadingModeRegistry::_GetImporter(const TfToken& name) { UsdMaya_RegistryHelper::LoadShadingModePlugins(); TfRegistryManager::GetInstance().SubscribeTo(); @@ -138,16 +129,16 @@ UsdMayaShadingModeRegistry::_GetImporter(const TfToken& name) return it == _importReg.end() ? nullptr : it->second._fn; } -const std::string& -UsdMayaShadingModeRegistry::_GetImporterNiceName(const TfToken& name) { +const std::string& UsdMayaShadingModeRegistry::_GetImporterNiceName(const TfToken& name) +{ UsdMaya_RegistryHelper::LoadShadingModePlugins(); TfRegistryManager::GetInstance().SubscribeTo(); const auto it = _importReg.find(name); return it == _importReg.end() ? _kEmptyString : it->second._niceName; } -const std::string& -UsdMayaShadingModeRegistry::_GetImporterDescription(const TfToken& name) { +const std::string& UsdMayaShadingModeRegistry::_GetImporterDescription(const TfToken& name) +{ UsdMaya_RegistryHelper::LoadShadingModePlugins(); TfRegistryManager::GetInstance().SubscribeTo(); const auto it = _importReg.find(name); @@ -166,8 +157,8 @@ TfTokenVector UsdMayaShadingModeRegistry::_ListExporters() return ret; } -TfTokenVector -UsdMayaShadingModeRegistry::_ListImporters() { +TfTokenVector UsdMayaShadingModeRegistry::_ListImporters() +{ UsdMaya_RegistryHelper::LoadShadingModePlugins(); TfRegistryManager::GetInstance().SubscribeTo(); TfTokenVector ret; @@ -226,8 +217,8 @@ void UsdMayaShadingModeRegistry::RegisterImportConversion( } } -TfTokenVector -UsdMayaShadingModeRegistry::_ListMaterialConversions() { +TfTokenVector UsdMayaShadingModeRegistry::_ListMaterialConversions() +{ UsdMaya_RegistryHelper::LoadShadingModePlugins(); TfRegistryManager::GetInstance().SubscribeTo(); TfRegistryManager::GetInstance().SubscribeTo(); @@ -244,26 +235,20 @@ UsdMayaShadingModeRegistry::_GetMaterialConversionInfo(const TfToken& materialCo { UsdMaya_RegistryHelper::LoadShadingModePlugins(); TfRegistryManager::GetInstance().SubscribeTo(); - auto it = _conversionReg.find(materialConversion); + auto it = _conversionReg.find(materialConversion); static const ConversionInfo _emptyInfo; return it != _conversionReg.end() ? it->second : _emptyInfo; } TF_INSTANTIATE_SINGLETON(UsdMayaShadingModeRegistry); -UsdMayaShadingModeRegistry& -UsdMayaShadingModeRegistry::GetInstance() +UsdMayaShadingModeRegistry& UsdMayaShadingModeRegistry::GetInstance() { return TfSingleton::GetInstance(); } -UsdMayaShadingModeRegistry::UsdMayaShadingModeRegistry() -{ -} - -UsdMayaShadingModeRegistry::~UsdMayaShadingModeRegistry() -{ -} +UsdMayaShadingModeRegistry::UsdMayaShadingModeRegistry() { } +UsdMayaShadingModeRegistry::~UsdMayaShadingModeRegistry() { } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/shading/shadingModeRegistry.h b/lib/mayaUsd/fileio/shading/shadingModeRegistry.h index 35135529f0..a6b55e2fef 100644 --- a/lib/mayaUsd/fileio/shading/shadingModeRegistry.h +++ b/lib/mayaUsd/fileio/shading/shadingModeRegistry.h @@ -16,42 +16,36 @@ #ifndef PXRUSDMAYA_SHADING_MODE_REGISTRY_H #define PXRUSDMAYA_SHADING_MODE_REGISTRY_H -#include - -#include +#include +#include +#include +#include -#include #include #include #include #include #include +#include -#include -#include -#include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -#define PXRUSDMAYA_SHADINGMODE_TOKENS \ - (none) \ - (displayColor) \ - (useRegistry) +#define PXRUSDMAYA_SHADINGMODE_TOKENS (none)(displayColor)(useRegistry) -TF_DECLARE_PUBLIC_TOKENS(UsdMayaShadingModeTokens, +TF_DECLARE_PUBLIC_TOKENS( + UsdMayaShadingModeTokens, MAYAUSD_CORE_PUBLIC, PXRUSDMAYA_SHADINGMODE_TOKENS); #define PXRUSDMAYA_SHADINGCONVERSION_TOKENS \ - (none) \ - (lambert) \ - (standardSurface) \ - (usdPreviewSurface) \ - (blinn) \ - (phong) - -TF_DECLARE_PUBLIC_TOKENS(UsdMayaPreferredMaterialTokens, + (none)(lambert)(standardSurface)(usdPreviewSurface)(blinn)(phong) + +TF_DECLARE_PUBLIC_TOKENS( + UsdMayaPreferredMaterialTokens, MAYAUSD_CORE_PUBLIC, PXRUSDMAYA_SHADINGCONVERSION_TOKENS); @@ -66,19 +60,16 @@ TF_DECLARE_WEAK_PTRS(UsdMayaShadingModeRegistry); class UsdMayaShadingModeRegistry : public TfWeakBase { public: - - static UsdMayaShadingModeExporterCreator GetExporter(const TfToken& name) { + static UsdMayaShadingModeExporterCreator GetExporter(const TfToken& name) + { return GetInstance()._GetExporter(name); } - static UsdMayaShadingModeImporter GetImporter(const TfToken& name) { + static UsdMayaShadingModeImporter GetImporter(const TfToken& name) + { return GetInstance()._GetImporter(name); } - static TfTokenVector ListExporters() { - return GetInstance()._ListExporters(); - } - static TfTokenVector ListImporters() { - return GetInstance()._ListImporters(); - } + static TfTokenVector ListExporters() { return GetInstance()._ListExporters(); } + static TfTokenVector ListImporters() { return GetInstance()._ListImporters(); } /// Gets the nice name of an exporter. Used for the UI label of the export options static const std::string& GetExporterNiceName(const TfToken& name) @@ -109,17 +100,17 @@ class UsdMayaShadingModeRegistry : public TfWeakBase MAYAUSD_CORE_PUBLIC bool RegisterExporter( - const std::string& name, - std::string niceName, - std::string description, - UsdMayaShadingModeExporterCreator fn); + const std::string& name, + std::string niceName, + std::string description, + UsdMayaShadingModeExporterCreator fn); MAYAUSD_CORE_PUBLIC bool RegisterImporter( - const std::string& name, - std::string niceName, - std::string description, - UsdMayaShadingModeImporter fn); + const std::string& name, + std::string niceName, + std::string description, + UsdMayaShadingModeImporter fn); /// The useRegistry exporters and importers can be specialized to support material conversions. /// The most well known is the default conversion to UsdPreviewSurface shaders. This registry @@ -136,16 +127,20 @@ class UsdMayaShadingModeRegistry : public TfWeakBase /// REGISTER_SHADING_MODE_IMPORT_MATERIAL_CONVERSION macro for each material conversion. /// Get all registered export conversions: - static TfTokenVector ListMaterialConversions() { return GetInstance()._ListMaterialConversions(); } + static TfTokenVector ListMaterialConversions() + { + return GetInstance()._ListMaterialConversions(); + } /// All the information registered for a specific material conversion. - struct ConversionInfo { + struct ConversionInfo + { TfToken renderContext; TfToken niceName; TfToken exportDescription; TfToken importDescription; - bool hasExporter = false; - bool hasImporter = false; + bool hasExporter = false; + bool hasImporter = false; }; /// Gets the conversion information associated with \p materialConversion on export and import @@ -164,7 +159,7 @@ class UsdMayaShadingModeRegistry : public TfWeakBase /// used if the resulting UsdShade nodes are written using an API shared by multiple renderers, /// like UsdPreviewSurface or MaterialX. For UsdShade nodes targetting a specific rendering /// engine, please define a custom render context understood by the renderer. - /// + /// /// The \p niceName is the name displayed in the render options dialog. /// /// The \p description is displayed as a tooltip in the render options dialog. @@ -186,7 +181,7 @@ class UsdMayaShadingModeRegistry : public TfWeakBase /// /// The \p renderContext will be used to locate the specialized binding point in the USD data. /// See UsdShadeMaterial documentation for details. - /// + /// /// The \p niceName is the name to be displayed in the import options dialog. /// /// The \p description is displayed as a tooltip in the import options dialog. @@ -243,23 +238,22 @@ class UsdMayaShadingModeRegistry : public TfWeakBase UsdMayaShadingModeImportContext* contextName, \ const UsdMayaJobImportArgs& jobArgumentsName) -#define REGISTER_SHADING_MODE_EXPORT_MATERIAL_CONVERSION( \ - name, renderContext, niceName, description) \ - TF_REGISTRY_FUNCTION(UsdMayaShadingModeExportContext) \ - { \ - UsdMayaShadingModeRegistry::GetInstance().RegisterExportConversion( \ - name, renderContext, niceName, description); \ +#define REGISTER_SHADING_MODE_EXPORT_MATERIAL_CONVERSION( \ + name, renderContext, niceName, description) \ + TF_REGISTRY_FUNCTION(UsdMayaShadingModeExportContext) \ + { \ + UsdMayaShadingModeRegistry::GetInstance().RegisterExportConversion( \ + name, renderContext, niceName, description); \ } -#define REGISTER_SHADING_MODE_IMPORT_MATERIAL_CONVERSION( \ - name, renderContext, niceName, description) \ - TF_REGISTRY_FUNCTION(UsdMayaShadingModeImportContext) \ - { \ - UsdMayaShadingModeRegistry::GetInstance().RegisterImportConversion( \ - name, renderContext, niceName, description); \ +#define REGISTER_SHADING_MODE_IMPORT_MATERIAL_CONVERSION( \ + name, renderContext, niceName, description) \ + TF_REGISTRY_FUNCTION(UsdMayaShadingModeImportContext) \ + { \ + UsdMayaShadingModeRegistry::GetInstance().RegisterImportConversion( \ + name, renderContext, niceName, description); \ } PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/shading/shadingModeUseRegistry.cpp b/lib/mayaUsd/fileio/shading/shadingModeUseRegistry.cpp index a38b875695..dba204ceaa 100644 --- a/lib/mayaUsd/fileio/shading/shadingModeUseRegistry.cpp +++ b/lib/mayaUsd/fileio/shading/shadingModeUseRegistry.cpp @@ -58,328 +58,293 @@ namespace { TF_DEFINE_PRIVATE_TOKENS( _tokens, - ((ArgName, "useRegistry")) - ((NiceName, "Use Registry")) - ((ExportDescription, "Use a registry based mechanism, complemented with material conversions," - " to export to a UsdShade network")) - ((ImportDescription, "Use a registry based mechanism, complemented with material conversions," - " to import from a UsdShade network")) -); + ((ArgName, "useRegistry"))((NiceName, "Use Registry"))( + (ExportDescription, + "Use a registry based mechanism, complemented with material conversions," + " to export to a UsdShade network"))( + (ImportDescription, + "Use a registry based mechanism, complemented with material conversions," + " to import from a UsdShade network"))); -using _NodeHandleToShaderWriterMap = - UsdMayaUtil::MObjectHandleUnorderedMap; +using _NodeHandleToShaderWriterMap + = UsdMayaUtil::MObjectHandleUnorderedMap; class UseRegistryShadingModeExporter : public UsdMayaShadingModeExporter { - public: - - UseRegistryShadingModeExporter() {} - - private: - - /// Gets the exported ShadeNode associated with the \p depNode that was written under - /// the path \p parentPath. If no such node exists, then one is created and written. - /// - /// If no shader writer can be found for the Maya node or if the node - /// otherwise should not be authored, an empty pointer is returned. - /// - /// A cached mapping of node handles to shader writer pointers is - /// maintained in the provided \p shaderWriterMap. - UsdMayaShaderWriterSharedPtr - _GetExportedShaderForNode( - const MObject& depNode, - const SdfPath& parentPath, - const UsdMayaShadingModeExportContext& context, - _NodeHandleToShaderWriterMap& shaderWriterMap) - { - if (depNode.hasFn(MFn::kShadingEngine)) { - // depNode is the material itself, so we don't need to create a - // new shader. Connections between it and the top-level shader - // will be handled by the main Export() method. - return nullptr; - } +public: + UseRegistryShadingModeExporter() { } - if (!UsdMayaUtil::isWritable(depNode)) { - return nullptr; - } +private: + /// Gets the exported ShadeNode associated with the \p depNode that was written under + /// the path \p parentPath. If no such node exists, then one is created and written. + /// + /// If no shader writer can be found for the Maya node or if the node + /// otherwise should not be authored, an empty pointer is returned. + /// + /// A cached mapping of node handles to shader writer pointers is + /// maintained in the provided \p shaderWriterMap. + UsdMayaShaderWriterSharedPtr _GetExportedShaderForNode( + const MObject& depNode, + const SdfPath& parentPath, + const UsdMayaShadingModeExportContext& context, + _NodeHandleToShaderWriterMap& shaderWriterMap) + { + if (depNode.hasFn(MFn::kShadingEngine)) { + // depNode is the material itself, so we don't need to create a + // new shader. Connections between it and the top-level shader + // will be handled by the main Export() method. + return nullptr; + } - const MObjectHandle nodeHandle(depNode); - const auto iter = shaderWriterMap.find(nodeHandle); - if (iter != shaderWriterMap.end()) { - // We've already created a shader writer for this node, so just - // return it. - return iter->second; - } + if (!UsdMayaUtil::isWritable(depNode)) { + return nullptr; + } - // No shader writer exists for this node yet, so create one. - MStatus status; - const MFnDependencyNode depNodeFn(depNode, &status); - if (status != MS::kSuccess) { - return nullptr; - } + const MObjectHandle nodeHandle(depNode); + const auto iter = shaderWriterMap.find(nodeHandle); + if (iter != shaderWriterMap.end()) { + // We've already created a shader writer for this node, so just + // return it. + return iter->second; + } - const TfToken shaderUsdPrimName( - UsdMayaUtil::SanitizeName(depNodeFn.name().asChar())); + // No shader writer exists for this node yet, so create one. + MStatus status; + const MFnDependencyNode depNodeFn(depNode, &status); + if (status != MS::kSuccess) { + return nullptr; + } - const SdfPath shaderUsdPath = - parentPath.AppendChild(shaderUsdPrimName); + const TfToken shaderUsdPrimName(UsdMayaUtil::SanitizeName(depNodeFn.name().asChar())); - UsdMayaShaderWriterRegistry::WriterFactoryFn primWriterFactory - = UsdMayaShaderWriterRegistry::Find( - TfToken(depNodeFn.typeName().asChar()), context.GetExportArgs()); - if (!primWriterFactory) { - return nullptr; - } + const SdfPath shaderUsdPath = parentPath.AppendChild(shaderUsdPrimName); - UsdMayaPrimWriterSharedPtr primWriter - = primWriterFactory(depNodeFn, shaderUsdPath, context.GetWriteJobContext()); - if (!primWriter) { - return nullptr; - } + UsdMayaShaderWriterRegistry::WriterFactoryFn primWriterFactory + = UsdMayaShaderWriterRegistry::Find( + TfToken(depNodeFn.typeName().asChar()), context.GetExportArgs()); + if (!primWriterFactory) { + return nullptr; + } - UsdMayaShaderWriterSharedPtr shaderWriter - = std::dynamic_pointer_cast(primWriter); + UsdMayaPrimWriterSharedPtr primWriter + = primWriterFactory(depNodeFn, shaderUsdPath, context.GetWriteJobContext()); + if (!primWriter) { + return nullptr; + } - // Store the shader writer pointer whether we succeeded or not so - // that we don't repeatedly attempt and fail to create it for the - // same node. - shaderWriterMap[nodeHandle] = shaderWriter; + UsdMayaShaderWriterSharedPtr shaderWriter + = std::dynamic_pointer_cast(primWriter); + + // Store the shader writer pointer whether we succeeded or not so + // that we don't repeatedly attempt and fail to create it for the + // same node. + shaderWriterMap[nodeHandle] = shaderWriter; - shaderWriter->Write(UsdTimeCode::Default()); + shaderWriter->Write(UsdTimeCode::Default()); - return shaderWriter; + return shaderWriter; + } + + /// Export nodes in the Maya dependency graph rooted at \p rootPlug + /// under \p materialExportPath. + /// + /// The root plug should be from an attribute on the Maya shadingEngine + /// node that the material represents. + /// + /// The first shader prim authored during the traversal will be assumed + /// to be the primary shader for the connection represented by + /// \p rootPlug. That shader prim will be returned so that it can be + /// connected to the Material prim. + UsdShadeShader _ExportShadingDepGraph( + const SdfPath& materialExportPath, + const MPlug& rootPlug, + const UsdMayaShadingModeExportContext& context) + { + // Maintain a mapping of Maya shading node handles to shader + // writers so that we only author each shader once, but can still + // look them up again to create connections. + _NodeHandleToShaderWriterMap shaderWriterMap; + + // MItDependencyGraph takes a non-const MPlug as a constructor + // parameter, so we have to make a copy of rootPlug here. + MPlug rootPlugCopy(rootPlug); + + MStatus status; + MItDependencyGraph iterDepGraph( + rootPlugCopy, + MFn::kInvalid, + MItDependencyGraph::Direction::kUpstream, + MItDependencyGraph::Traversal::kDepthFirst, + MItDependencyGraph::Level::kPlugLevel, + &status); + if (status != MS::kSuccess) { + return UsdShadeShader(); } - /// Export nodes in the Maya dependency graph rooted at \p rootPlug - /// under \p materialExportPath. - /// - /// The root plug should be from an attribute on the Maya shadingEngine - /// node that the material represents. - /// - /// The first shader prim authored during the traversal will be assumed - /// to be the primary shader for the connection represented by - /// \p rootPlug. That shader prim will be returned so that it can be - /// connected to the Material prim. - UsdShadeShader - _ExportShadingDepGraph( - const SdfPath& materialExportPath, - const MPlug& rootPlug, - const UsdMayaShadingModeExportContext& context) - { - // Maintain a mapping of Maya shading node handles to shader - // writers so that we only author each shader once, but can still - // look them up again to create connections. - _NodeHandleToShaderWriterMap shaderWriterMap; - - // MItDependencyGraph takes a non-const MPlug as a constructor - // parameter, so we have to make a copy of rootPlug here. - MPlug rootPlugCopy(rootPlug); - - MStatus status; - MItDependencyGraph iterDepGraph( - rootPlugCopy, - MFn::kInvalid, - MItDependencyGraph::Direction::kUpstream, - MItDependencyGraph::Traversal::kDepthFirst, - MItDependencyGraph::Level::kPlugLevel, - &status); + // We'll consider the first shader we create to be the "top-level" + // shader, which will be the one we return so that it can be + // connected to the Material prim. + UsdShadeShader topLevelShader; + + for (; !iterDepGraph.isDone(); iterDepGraph.next()) { + const MPlug iterPlug = iterDepGraph.thisPlug(&status); if (status != MS::kSuccess) { - return UsdShadeShader(); + continue; } - // We'll consider the first shader we create to be the "top-level" - // shader, which will be the one we return so that it can be - // connected to the Material prim. - UsdShadeShader topLevelShader; + // We'll check the source and the destination(s) of the + // connection to see if we encounter new shading nodes that + // need to be exported. + MPlug srcPlug; + MPlugArray dstPlugs; - for (; !iterDepGraph.isDone(); iterDepGraph.next()) { - const MPlug iterPlug = iterDepGraph.thisPlug(&status); + const bool isDestination = iterPlug.isDestination(&status); + if (status != MS::kSuccess) { + continue; + } + const bool isSource = iterPlug.isSource(&status); + if (status != MS::kSuccess) { + continue; + } + + if (isDestination) { + srcPlug = iterPlug.source(&status); if (status != MS::kSuccess) { continue; } - // We'll check the source and the destination(s) of the - // connection to see if we encounter new shading nodes that - // need to be exported. - MPlug srcPlug; - MPlugArray dstPlugs; + dstPlugs.append(iterPlug); + } else if (isSource) { + srcPlug = iterPlug; - const bool isDestination = iterPlug.isDestination(&status); - if (status != MS::kSuccess) { - continue; - } - const bool isSource = iterPlug.isSource(&status); - if (status != MS::kSuccess) { + if (!iterPlug.destinations(dstPlugs, &status) || status != MS::kSuccess) { continue; } + } - if (isDestination) { - srcPlug = iterPlug.source(&status); - if (status != MS::kSuccess) { - continue; - } + // Since we are traversing the shading graph in the upstream + // direction, we'll be visiting shading nodes from destinations + // to sources, beginning with the shadingEngine node. This + // means that if we don't have a source shader to work with, + // there's no need to consider any of the plug's destinations. + if (srcPlug.isNull()) { + continue; + } - dstPlugs.append(iterPlug); - } else if (isSource) { - srcPlug = iterPlug; + auto srcShaderInfo = _GetExportedShaderForNode( + srcPlug.node(), materialExportPath, context, shaderWriterMap); + if (!srcShaderInfo) { + continue; + } - if (!iterPlug.destinations(dstPlugs, &status) || - status != MS::kSuccess) { - continue; - } - } + UsdPrim shaderPrim = srcShaderInfo->GetUsdPrim(); + if (shaderPrim && !topLevelShader) { + topLevelShader = UsdShadeShader(shaderPrim); + } - // Since we are traversing the shading graph in the upstream - // direction, we'll be visiting shading nodes from destinations - // to sources, beginning with the shadingEngine node. This - // means that if we don't have a source shader to work with, - // there's no need to consider any of the plug's destinations. - if (srcPlug.isNull()) { + for (unsigned int i = 0u; i < dstPlugs.length(); ++i) { + const MPlug dstPlug = dstPlugs[i]; + if (dstPlug.isNull()) { continue; } - auto srcShaderInfo = _GetExportedShaderForNode( - srcPlug.node(), materialExportPath, context, shaderWriterMap); - if (!srcShaderInfo) { + auto dstShaderInfo = _GetExportedShaderForNode( + dstPlug.node(), materialExportPath, context, shaderWriterMap); + if (!dstShaderInfo) { continue; } - UsdPrim shaderPrim = srcShaderInfo->GetUsdPrim(); + UsdPrim shaderPrim = dstShaderInfo->GetUsdPrim(); if (shaderPrim && !topLevelShader) { topLevelShader = UsdShadeShader(shaderPrim); } - for (unsigned int i = 0u; i < dstPlugs.length(); ++i) { - const MPlug dstPlug = dstPlugs[i]; - if (dstPlug.isNull()) { - continue; - } + // See if we can get the USD shading attributes that the + // Maya plugs represent so that we can author the + // connection in USD. - auto dstShaderInfo = _GetExportedShaderForNode( - dstPlug.node(), materialExportPath, context, shaderWriterMap); - if (!dstShaderInfo) { - continue; - } + const TfToken srcPlugName + = TfToken(UsdMayaShadingUtil::GetStandardAttrName(srcPlug, false)); + UsdAttribute srcAttribute + = srcShaderInfo->GetShadingAttributeForMayaAttrName(srcPlugName); - UsdPrim shaderPrim = dstShaderInfo->GetUsdPrim(); - if (shaderPrim && !topLevelShader) { - topLevelShader = UsdShadeShader(shaderPrim); - } + const TfToken dstPlugName + = TfToken(UsdMayaShadingUtil::GetStandardAttrName(dstPlug, false)); + UsdAttribute dstAttribute + = dstShaderInfo->GetShadingAttributeForMayaAttrName(dstPlugName); + + if (srcAttribute && dstAttribute) { + if (UsdShadeInput::IsInput(srcAttribute)) { + UsdShadeInput srcInput(srcAttribute); - // See if we can get the USD shading attributes that the - // Maya plugs represent so that we can author the - // connection in USD. - - const TfToken srcPlugName = TfToken( - UsdMayaShadingUtil::GetStandardAttrName(srcPlug, false)); - UsdAttribute srcAttribute = - srcShaderInfo->GetShadingAttributeForMayaAttrName( - srcPlugName); - - const TfToken dstPlugName = TfToken( - UsdMayaShadingUtil::GetStandardAttrName(dstPlug, false)); - UsdAttribute dstAttribute = - dstShaderInfo->GetShadingAttributeForMayaAttrName( - dstPlugName); - - if (srcAttribute && dstAttribute) { - if (UsdShadeInput::IsInput(srcAttribute)) { - UsdShadeInput srcInput(srcAttribute); - - UsdShadeConnectableAPI::ConnectToSource( - dstAttribute, - srcInput); - } - else if (UsdShadeOutput::IsOutput(srcAttribute)) { - UsdShadeOutput srcOutput(srcAttribute); - - UsdShadeConnectableAPI::ConnectToSource( - dstAttribute, - srcOutput); - } + UsdShadeConnectableAPI::ConnectToSource(dstAttribute, srcInput); + } else if (UsdShadeOutput::IsOutput(srcAttribute)) { + UsdShadeOutput srcOutput(srcAttribute); + + UsdShadeConnectableAPI::ConnectToSource(dstAttribute, srcOutput); } } } - - return topLevelShader; } - void - Export( - const UsdMayaShadingModeExportContext& context, - UsdShadeMaterial* const mat, - SdfPathSet* const boundPrimPaths) override - { - MStatus status; - - MObject shadingEngine = context.GetShadingEngine(); - const MFnDependencyNode shadingEngineDepNodeFn( - shadingEngine, - &status); - if (status != MS::kSuccess) { - TF_RUNTIME_ERROR( - "Cannot export invalid shading engine node '%s'\n", - UsdMayaUtil::GetMayaNodeName(shadingEngine).c_str()); - return; - } + return topLevelShader; + } - const UsdMayaShadingModeExportContext::AssignmentVector& assignments = - context.GetAssignments(); - if (assignments.empty()) { - return; - } + void Export( + const UsdMayaShadingModeExportContext& context, + UsdShadeMaterial* const mat, + SdfPathSet* const boundPrimPaths) override + { + MStatus status; - UsdPrim materialPrim = context.MakeStandardMaterialPrim(assignments, std::string()); - UsdShadeMaterial material(materialPrim); - if (!material) { - return; - } + MObject shadingEngine = context.GetShadingEngine(); + const MFnDependencyNode shadingEngineDepNodeFn(shadingEngine, &status); + if (status != MS::kSuccess) { + TF_RUNTIME_ERROR( + "Cannot export invalid shading engine node '%s'\n", + UsdMayaUtil::GetMayaNodeName(shadingEngine).c_str()); + return; + } - if (mat != nullptr) { - *mat = material; - } + const UsdMayaShadingModeExportContext::AssignmentVector& assignments + = context.GetAssignments(); + if (assignments.empty()) { + return; + } - const TfToken& convertMaterialsTo = context.GetExportArgs().convertMaterialsTo; - const TfToken& renderContext - = UsdMayaShadingModeRegistry::GetMaterialConversionInfo(convertMaterialsTo) - .renderContext; - SdfPath materialExportPath = materialPrim.GetPath(); - - UsdShadeShader surfaceShaderSchema = - _ExportShadingDepGraph( - materialExportPath, - context.GetSurfaceShaderPlug(), - context); - UsdMayaShadingUtil::CreateShaderOutputAndConnectMaterial( - surfaceShaderSchema, - material, - UsdShadeTokens->surface, - renderContext); - - UsdShadeShader volumeShaderSchema = - _ExportShadingDepGraph( - materialExportPath, - context.GetVolumeShaderPlug(), - context); - UsdMayaShadingUtil::CreateShaderOutputAndConnectMaterial( - volumeShaderSchema, - material, - UsdShadeTokens->volume, - renderContext); - - UsdShadeShader displacementShaderSchema = - _ExportShadingDepGraph( - materialExportPath, - context.GetDisplacementShaderPlug(), - context); - UsdMayaShadingUtil::CreateShaderOutputAndConnectMaterial( - displacementShaderSchema, - material, - UsdShadeTokens->displacement, - renderContext); - - context.BindStandardMaterialPrim(materialPrim, assignments, boundPrimPaths); + UsdPrim materialPrim = context.MakeStandardMaterialPrim(assignments, std::string()); + UsdShadeMaterial material(materialPrim); + if (!material) { + return; } + + if (mat != nullptr) { + *mat = material; + } + + const TfToken& convertMaterialsTo = context.GetExportArgs().convertMaterialsTo; + const TfToken& renderContext + = UsdMayaShadingModeRegistry::GetMaterialConversionInfo(convertMaterialsTo) + .renderContext; + SdfPath materialExportPath = materialPrim.GetPath(); + + UsdShadeShader surfaceShaderSchema + = _ExportShadingDepGraph(materialExportPath, context.GetSurfaceShaderPlug(), context); + UsdMayaShadingUtil::CreateShaderOutputAndConnectMaterial( + surfaceShaderSchema, material, UsdShadeTokens->surface, renderContext); + + UsdShadeShader volumeShaderSchema + = _ExportShadingDepGraph(materialExportPath, context.GetVolumeShaderPlug(), context); + UsdMayaShadingUtil::CreateShaderOutputAndConnectMaterial( + volumeShaderSchema, material, UsdShadeTokens->volume, renderContext); + + UsdShadeShader displacementShaderSchema = _ExportShadingDepGraph( + materialExportPath, context.GetDisplacementShaderPlug(), context); + UsdMayaShadingUtil::CreateShaderOutputAndConnectMaterial( + displacementShaderSchema, material, UsdShadeTokens->displacement, renderContext); + + context.BindStandardMaterialPrim(materialPrim, assignments, boundPrimPaths); + } }; } // anonymous namespace @@ -392,8 +357,7 @@ TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaShadingModeExportContext, useRegistry) _tokens->ExportDescription.GetString(), []() -> UsdMayaShadingModeExporterPtr { return UsdMayaShadingModeExporterPtr( - static_cast( - new UseRegistryShadingModeExporter())); + static_cast(new UseRegistryShadingModeExporter())); }); } @@ -402,10 +366,12 @@ namespace { /// This class implements a shading mode importer which uses a registry keyed by the info:id USD /// attribute to provide an importer class for each UsdShade node processed while traversing the /// main connections of a UsdMaterial node. -class UseRegistryShadingModeImporter { +class UseRegistryShadingModeImporter +{ public: - UseRegistryShadingModeImporter(UsdMayaShadingModeImportContext* context, - const UsdMayaJobImportArgs& jobArguments) + UseRegistryShadingModeImporter( + UsdMayaShadingModeImportContext* context, + const UsdMayaJobImportArgs& jobArguments) : _context(context) , _jobArguments(jobArguments) { @@ -423,8 +389,9 @@ class UseRegistryShadingModeImporter { return MObject(); } const TfToken& materialConversion = _jobArguments.GetMaterialConversion(); - TfToken renderContext = UsdMayaShadingModeRegistry::GetMaterialConversionInfo( - materialConversion).renderContext; + TfToken renderContext + = UsdMayaShadingModeRegistry::GetMaterialConversionInfo(materialConversion) + .renderContext; const UsdShadeMaterial& shadeMaterial = _context->GetShadeMaterial(); if (!shadeMaterial) { @@ -516,11 +483,12 @@ class UseRegistryShadingModeImporter { /// This will create the Maya dependency nodes as necessary and return an empty plug in case of /// import failure or if \p outputName could not map to a Maya plug. /// - MPlug _GetSourcePlug(const UsdShadeShader& shaderSchema, const TfToken& outputName) { - const SdfPath& shaderPath(shaderSchema.GetPath()); - const auto iter = _shaderReaderMap.find(shaderPath); + MPlug _GetSourcePlug(const UsdShadeShader& shaderSchema, const TfToken& outputName) + { + const SdfPath& shaderPath(shaderSchema.GetPath()); + const auto iter = _shaderReaderMap.find(shaderPath); UsdMayaShaderReaderSharedPtr shaderReader; - MObject sourceObj; + MObject sourceObj; if (iter != _shaderReaderMap.end()) { shaderReader = iter->second; if (!_context->GetCreatedObject(shaderSchema.GetPrim(), &sourceObj)) { @@ -534,7 +502,7 @@ class UseRegistryShadingModeImporter { if (UsdMayaShaderReaderRegistry::ReaderFactoryFn factoryFn = UsdMayaShaderReaderRegistry::Find(shaderId, _jobArguments)) { - UsdPrim shaderPrim = shaderSchema.GetPrim(); + UsdPrim shaderPrim = shaderSchema.GetPrim(); UsdMayaPrimReaderArgs args(shaderPrim, _jobArguments); shaderReader = std::dynamic_pointer_cast(factoryFn(args)); @@ -556,10 +524,9 @@ class UseRegistryShadingModeImporter { } } - TfToken sourceOutputName - = TfToken(TfStringPrintf( - "%s%s", UsdShadeTokens->outputs.GetText(), outputName.GetText()) - .c_str()); + TfToken sourceOutputName = TfToken( + TfStringPrintf("%s%s", UsdShadeTokens->outputs.GetText(), outputName.GetText()) + .c_str()); MPlug sourcePlug = shaderReader->GetMayaPlugForUsdAttrName(sourceOutputName, sourceObj); if (sourcePlug.isArray()) { const unsigned int numElements = sourcePlug.evaluateNumElements(); @@ -585,8 +552,7 @@ class UseRegistryShadingModeImporter { /// This will create the Maya dependency nodes for the \p shaderSchema UsdShade node. The /// connections will be recursively traversed to complete the network. /// - MObject - _ReadSchema(const UsdShadeShader& shaderSchema, UsdMayaShaderReader& shaderReader) + MObject _ReadSchema(const UsdShadeShader& shaderSchema, UsdMayaShaderReader& shaderReader) { // UsdMayaPrimReader::Read is a function that works by indirect effect. It will return // "true" on success, and the resulting changes will be found in the _context object. diff --git a/lib/mayaUsd/fileio/shading/symmetricShaderReader.cpp b/lib/mayaUsd/fileio/shading/symmetricShaderReader.cpp index e1b59c0233..7d0b204b71 100644 --- a/lib/mayaUsd/fileio/shading/symmetricShaderReader.cpp +++ b/lib/mayaUsd/fileio/shading/symmetricShaderReader.cpp @@ -15,11 +15,11 @@ // #include "symmetricShaderReader.h" +#include #include #include #include #include -#include #include #include #include @@ -48,46 +48,35 @@ #include #include - PXR_NAMESPACE_OPEN_SCOPE - TF_DEFINE_PRIVATE_TOKENS( _tokens, - ((MayaShaderOutputName, "outColor")) -); - + ((MayaShaderOutputName, "outColor"))); /* static */ -void -UsdMayaSymmetricShaderReader::RegisterReader( - const TfToken& usdShaderId, - const TfToken& mayaNodeTypeName, - const TfToken& materialConversion) +void UsdMayaSymmetricShaderReader::RegisterReader( + const TfToken& usdShaderId, + const TfToken& mayaNodeTypeName, + const TfToken& materialConversion) { UsdMayaShaderReaderRegistry::Register( usdShaderId, [materialConversion](const UsdMayaJobImportArgs& importArgs) { - return UsdMayaSymmetricShaderReader::CanImport( - importArgs, - materialConversion); + return UsdMayaSymmetricShaderReader::CanImport(importArgs, materialConversion); }, [mayaNodeTypeName](const UsdMayaPrimReaderArgs& readerArgs) { - return std::make_shared( - readerArgs, - mayaNodeTypeName); + return std::make_shared(readerArgs, mayaNodeTypeName); }); } /* static */ -UsdMayaShaderReader::ContextSupport -UsdMayaSymmetricShaderReader::CanImport( - const UsdMayaJobImportArgs& importArgs, - const TfToken& materialConversion) +UsdMayaShaderReader::ContextSupport UsdMayaSymmetricShaderReader::CanImport( + const UsdMayaJobImportArgs& importArgs, + const TfToken& materialConversion) { - if (materialConversion.IsEmpty() - || importArgs.GetMaterialConversion() == materialConversion) { + if (materialConversion.IsEmpty() || importArgs.GetMaterialConversion() == materialConversion) { // This shader reader advertises "Fallback" support so that any more // specialized readers for a particular shader ID can take precedence. return ContextSupport::Fallback; @@ -96,13 +85,11 @@ UsdMayaSymmetricShaderReader::CanImport( return ContextSupport::Unsupported; } -static -UsdMayaShadingNodeType +static UsdMayaShadingNodeType _ComputeShadingNodeTypeForMayaTypeName(const TfToken& mayaNodeTypeName) { // Use NonShading as a fallback. - UsdMayaShadingNodeType shadingNodeType = - UsdMayaShadingNodeType::NonShading; + UsdMayaShadingNodeType shadingNodeType = UsdMayaShadingNodeType::NonShading; MStatus status; MString cmd; @@ -113,12 +100,10 @@ _ComputeShadingNodeTypeForMayaTypeName(const TfToken& mayaNodeTypeName) status = MGlobal::executeCommand(cmd, compoundClassifications, false, false); CHECK_MSTATUS_AND_RETURN(status, shadingNodeType); - static const std::vector> - _classificationsToTypes = { - { "texture/", UsdMayaShadingNodeType::Texture }, + static const std::vector> _classificationsToTypes + = { { "texture/", UsdMayaShadingNodeType::Texture }, { "utility/", UsdMayaShadingNodeType::Utility }, - { "shader/", UsdMayaShadingNodeType::Shader } - }; + { "shader/", UsdMayaShadingNodeType::Shader } }; // The docs for getClassification() are pretty confusing. You'd think that // the string array returned would give you each "classification", but @@ -133,14 +118,10 @@ _ComputeShadingNodeTypeForMayaTypeName(const TfToken& mayaNodeTypeName) for (unsigned int i = 0u; i < compoundClassifications.length(); ++i) { const MString& compoundClassification = compoundClassifications[i]; #endif - const std::string compoundClassificationStr( - compoundClassification.asChar()); - for (const std::string& classification : - TfStringSplit(compoundClassificationStr, ":")) { + const std::string compoundClassificationStr(compoundClassification.asChar()); + for (const std::string& classification : TfStringSplit(compoundClassificationStr, ":")) { for (const auto& classPrefixAndType : _classificationsToTypes) { - if (TfStringStartsWith( - classification, - classPrefixAndType.first)) { + if (TfStringStartsWith(classification, classPrefixAndType.first)) { return classPrefixAndType.second; } } @@ -151,20 +132,18 @@ _ComputeShadingNodeTypeForMayaTypeName(const TfToken& mayaNodeTypeName) } UsdMayaSymmetricShaderReader::UsdMayaSymmetricShaderReader( - const UsdMayaPrimReaderArgs& readerArgs, - const TfToken& mayaNodeTypeName) : - UsdMayaShaderReader(readerArgs), - _mayaNodeTypeName(mayaNodeTypeName), - _mayaShadingNodeType( - _ComputeShadingNodeTypeForMayaTypeName(mayaNodeTypeName)) + const UsdMayaPrimReaderArgs& readerArgs, + const TfToken& mayaNodeTypeName) + : UsdMayaShaderReader(readerArgs) + , _mayaNodeTypeName(mayaNodeTypeName) + , _mayaShadingNodeType(_ComputeShadingNodeTypeForMayaTypeName(mayaNodeTypeName)) { } /* override */ -bool -UsdMayaSymmetricShaderReader::Read(UsdMayaPrimReaderContext* context) +bool UsdMayaSymmetricShaderReader::Read(UsdMayaPrimReaderContext* context) { - const UsdPrim& prim = _GetArgs().GetUsdPrim(); + const UsdPrim& prim = _GetArgs().GetUsdPrim(); const UsdShadeShader shaderSchema = UsdShadeShader(prim); if (!shaderSchema) { return false; @@ -175,8 +154,8 @@ UsdMayaSymmetricShaderReader::Read(UsdMayaPrimReaderContext* context) return false; } - MStatus status; - MObject mayaObject; + MStatus status; + MObject mayaObject; MFnDependencyNode depNodeFn; if (!(UsdMayaTranslatorUtil::CreateShaderNode( MString(prim.GetName().GetText()), @@ -197,7 +176,7 @@ UsdMayaSymmetricShaderReader::Read(UsdMayaPrimReaderContext* context) for (const UsdShadeInput& input : shaderSchema.GetInputs()) { const UsdAttribute& usdAttr = input.GetAttr(); - const std::string mayaAttrName = usdAttr.GetBaseName().GetString(); + const std::string mayaAttrName = usdAttr.GetBaseName().GetString(); MPlug attrPlug = depNodeFn.findPlug(mayaAttrName.c_str(), &status); if (status != MS::kSuccess) { @@ -219,23 +198,19 @@ UsdMayaSymmetricShaderReader::Read(UsdMayaPrimReaderContext* context) } /* override */ -TfToken -UsdMayaSymmetricShaderReader::GetMayaNameForUsdAttrName( - const TfToken& usdAttrName) const +TfToken UsdMayaSymmetricShaderReader::GetMayaNameForUsdAttrName(const TfToken& usdAttrName) const { - TfToken usdBaseName; + TfToken usdBaseName; UsdShadeAttributeType usdAttrType; - std::tie(usdBaseName, usdAttrType) = - UsdShadeUtils::GetBaseNameAndType(usdAttrName); + std::tie(usdBaseName, usdAttrType) = UsdShadeUtils::GetBaseNameAndType(usdAttrName); // The one edge case we're handling here is the connection to a "top-level" // shader from one of its Material prim's terminal outputs. We make an // assumption about the name of the Maya shading node's primary output // attribute. - if (usdAttrType == UsdShadeAttributeType::Output && - (usdBaseName == UsdShadeTokens->surface || - usdBaseName == UsdShadeTokens->displacement || - usdBaseName == UsdShadeTokens->volume)) { + if (usdAttrType == UsdShadeAttributeType::Output + && (usdBaseName == UsdShadeTokens->surface || usdBaseName == UsdShadeTokens->displacement + || usdBaseName == UsdShadeTokens->volume)) { return _tokens->MayaShaderOutputName; } @@ -244,5 +219,4 @@ UsdMayaSymmetricShaderReader::GetMayaNameForUsdAttrName( return usdBaseName; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/shading/symmetricShaderReader.h b/lib/mayaUsd/fileio/shading/symmetricShaderReader.h index a5c1b851e6..446653eb60 100644 --- a/lib/mayaUsd/fileio/shading/symmetricShaderReader.h +++ b/lib/mayaUsd/fileio/shading/symmetricShaderReader.h @@ -19,19 +19,17 @@ /// \file #include +#include #include #include #include -#include #include -#include #include - +#include PXR_NAMESPACE_OPEN_SCOPE - /// \class UsdMayaSymmetricShaderReader /// \brief Provides "literal" translation of USD Shader prims to Maya shading /// nodes. @@ -73,34 +71,31 @@ class UsdMayaSymmetricShaderReader : public UsdMayaShaderReader /// TF_REGISTRY_FUNCTION(UsdMayaShaderReaderRegistry) block. MAYAUSD_CORE_PUBLIC static void RegisterReader( - const TfToken& usdShaderId, - const TfToken& mayaNodeTypeName, - const TfToken& materialConversion = TfToken()); + const TfToken& usdShaderId, + const TfToken& mayaNodeTypeName, + const TfToken& materialConversion = TfToken()); MAYAUSD_CORE_PUBLIC static ContextSupport CanImport( - const UsdMayaJobImportArgs& importArgs, - const TfToken& materialConversion = TfToken()); + const UsdMayaJobImportArgs& importArgs, + const TfToken& materialConversion = TfToken()); MAYAUSD_CORE_PUBLIC UsdMayaSymmetricShaderReader( - const UsdMayaPrimReaderArgs& readerArgs, - const TfToken& mayaNodeTypeName); + const UsdMayaPrimReaderArgs& readerArgs, + const TfToken& mayaNodeTypeName); MAYAUSD_CORE_PUBLIC bool Read(UsdMayaPrimReaderContext* context) override; MAYAUSD_CORE_PUBLIC - TfToken GetMayaNameForUsdAttrName( - const TfToken& usdAttrName) const override; + TfToken GetMayaNameForUsdAttrName(const TfToken& usdAttrName) const override; private: - const TfToken _mayaNodeTypeName; + const TfToken _mayaNodeTypeName; const UsdMayaShadingNodeType _mayaShadingNodeType; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/shading/symmetricShaderWriter.cpp b/lib/mayaUsd/fileio/shading/symmetricShaderWriter.cpp index 2e13e0cb28..e6138cade5 100644 --- a/lib/mayaUsd/fileio/shading/symmetricShaderWriter.cpp +++ b/lib/mayaUsd/fileio/shading/symmetricShaderWriter.cpp @@ -25,10 +25,10 @@ #include #include -#include #include #include #include +#include #include #include #include @@ -42,44 +42,35 @@ #include - PXR_NAMESPACE_OPEN_SCOPE - /* static */ -void -UsdMayaSymmetricShaderWriter::RegisterWriter( - const TfToken& mayaNodeTypeName, - const TfToken& usdShaderId, - const TfToken& materialConversionName) +void UsdMayaSymmetricShaderWriter::RegisterWriter( + const TfToken& mayaNodeTypeName, + const TfToken& usdShaderId, + const TfToken& materialConversionName) { UsdMayaShaderWriterRegistry::Register( mayaNodeTypeName, [materialConversionName](const UsdMayaJobExportArgs& exportArgs) { - return UsdMayaSymmetricShaderWriter::CanExport( - exportArgs, - materialConversionName); + return UsdMayaSymmetricShaderWriter::CanExport(exportArgs, materialConversionName); }, [usdShaderId]( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) { + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) { return std::make_shared( - depNodeFn, - usdPath, - jobCtx, - usdShaderId); + depNodeFn, usdPath, jobCtx, usdShaderId); }); } /* static */ -UsdMayaShaderWriter::ContextSupport -UsdMayaSymmetricShaderWriter::CanExport( - const UsdMayaJobExportArgs& exportArgs, - const TfToken& materialConversionName) +UsdMayaShaderWriter::ContextSupport UsdMayaSymmetricShaderWriter::CanExport( + const UsdMayaJobExportArgs& exportArgs, + const TfToken& materialConversionName) { - if (materialConversionName.IsEmpty() || - exportArgs.convertMaterialsTo == materialConversionName) { + if (materialConversionName.IsEmpty() + || exportArgs.convertMaterialsTo == materialConversionName) { return ContextSupport::Supported; } @@ -87,14 +78,13 @@ UsdMayaSymmetricShaderWriter::CanExport( } UsdMayaSymmetricShaderWriter::UsdMayaSymmetricShaderWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx, - const TfToken& usdShaderId) : - UsdMayaShaderWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx, + const TfToken& usdShaderId) + : UsdMayaShaderWriter(depNodeFn, usdPath, jobCtx) { - UsdShadeShader shaderSchema = - UsdShadeShader::Define(GetUsdStage(), GetUsdPath()); + UsdShadeShader shaderSchema = UsdShadeShader::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( shaderSchema, "Could not define UsdShadeShader at path '%s'\n", @@ -113,8 +103,8 @@ UsdMayaSymmetricShaderWriter::UsdMayaSymmetricShaderWriter( shaderSchema.CreateIdAttr(VtValue(usdShaderId)); for (unsigned int i = 0u; i < depNodeFn.attributeCount(); ++i) { - const MObject attrObj = depNodeFn.reorderedAttribute(i); - MPlug attrPlug = depNodeFn.findPlug(attrObj, true); + const MObject attrObj = depNodeFn.reorderedAttribute(i); + MPlug attrPlug = depNodeFn.findPlug(attrObj, true); const MFnAttribute attrFn(attrObj); if (attrPlug.isProcedural() || attrFn.isHidden()) { @@ -153,14 +143,13 @@ UsdMayaSymmetricShaderWriter::UsdMayaSymmetricShaderWriter( continue; } - const TfToken usdAttrName = TfToken( - UsdMayaShadingUtil::GetStandardAttrName(attrPlug, false)); + const TfToken usdAttrName + = TfToken(UsdMayaShadingUtil::GetStandardAttrName(attrPlug, false)); if (usdAttrName.IsEmpty()) { continue; } - const SdfValueTypeName valueTypeName = - MayaUsd::Converter::getUsdTypeName(attrPlug); + const SdfValueTypeName valueTypeName = MayaUsd::Converter::getUsdTypeName(attrPlug); if (!valueTypeName) { // Unsupported Maya attribute type (e.g. "message" attributes). continue; @@ -169,8 +158,7 @@ UsdMayaSymmetricShaderWriter::UsdMayaSymmetricShaderWriter( // If the Maya attribute is writable, we assume it must be an input. // Inputs can still be connected as sources to inputs on other shaders. if (attrFn.isWritable()) { - UsdShadeInput input = - shaderSchema.CreateInput(usdAttrName, valueTypeName); + UsdShadeInput input = shaderSchema.CreateInput(usdAttrName, valueTypeName); if (!input) { continue; } @@ -191,8 +179,7 @@ UsdMayaSymmetricShaderWriter::UsdMayaSymmetricShaderWriter( } /* override */ -void -UsdMayaSymmetricShaderWriter::Write(const UsdTimeCode& usdTime) +void UsdMayaSymmetricShaderWriter::Write(const UsdTimeCode& usdTime) { UsdMayaShaderWriter::Write(usdTime); @@ -206,25 +193,20 @@ UsdMayaSymmetricShaderWriter::Write(const UsdTimeCode& usdTime) for (const auto& inputAttrPair : _inputNameAttrMap) { const TfToken& inputName = inputAttrPair.first; - const MPlug& attrPlug = inputAttrPair.second; + const MPlug& attrPlug = inputAttrPair.second; UsdShadeInput input = shaderSchema.GetInput(inputName); if (!input) { continue; } - UsdMayaWriteUtil::SetUsdAttr( - attrPlug, - input.GetAttr(), - usdTime, - _GetSparseValueWriter()); + UsdMayaWriteUtil::SetUsdAttr(attrPlug, input.GetAttr(), usdTime, _GetSparseValueWriter()); } } /* override */ TfToken -UsdMayaSymmetricShaderWriter::GetShadingAttributeNameForMayaAttrName( - const TfToken& mayaAttrName) +UsdMayaSymmetricShaderWriter::GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) { UsdShadeShader shaderSchema(_usdPrim); if (!shaderSchema) { @@ -247,5 +229,4 @@ UsdMayaSymmetricShaderWriter::GetShadingAttributeNameForMayaAttrName( return TfToken(); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/shading/symmetricShaderWriter.h b/lib/mayaUsd/fileio/shading/symmetricShaderWriter.h index 32fb2e704c..0cb1e4b3bc 100644 --- a/lib/mayaUsd/fileio/shading/symmetricShaderWriter.h +++ b/lib/mayaUsd/fileio/shading/symmetricShaderWriter.h @@ -19,12 +19,12 @@ /// \file #include +#include #include #include -#include -#include #include +#include #include #include @@ -33,10 +33,8 @@ #include - PXR_NAMESPACE_OPEN_SCOPE - /// \class UsdMayaSymmetricShaderWriter /// \brief Provides "literal" translation of Maya shading nodes to USD Shader /// prims. @@ -78,35 +76,32 @@ class UsdMayaSymmetricShaderWriter : public UsdMayaShaderWriter /// TF_REGISTRY_FUNCTION(UsdMayaShaderWriterRegistry) block. MAYAUSD_CORE_PUBLIC static void RegisterWriter( - const TfToken& mayaNodeTypeName, - const TfToken& usdShaderId, - const TfToken& materialConversionName = TfToken()); + const TfToken& mayaNodeTypeName, + const TfToken& usdShaderId, + const TfToken& materialConversionName = TfToken()); MAYAUSD_CORE_PUBLIC static ContextSupport CanExport( - const UsdMayaJobExportArgs& exportArgs, - const TfToken& materialConversionName = TfToken()); + const UsdMayaJobExportArgs& exportArgs, + const TfToken& materialConversionName = TfToken()); MAYAUSD_CORE_PUBLIC UsdMayaSymmetricShaderWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx, - const TfToken& usdShaderId); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx, + const TfToken& usdShaderId); MAYAUSD_CORE_PUBLIC void Write(const UsdTimeCode& usdTime) override; MAYAUSD_CORE_PUBLIC - TfToken GetShadingAttributeNameForMayaAttrName( - const TfToken& mayaAttrName) override; + TfToken GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) override; private: std::unordered_map _inputNameAttrMap; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/transformWriter.cpp b/lib/mayaUsd/fileio/transformWriter.cpp index 741ae82271..1eedf6e4d3 100644 --- a/lib/mayaUsd/fileio/transformWriter.cpp +++ b/lib/mayaUsd/fileio/transformWriter.cpp @@ -15,32 +15,32 @@ // #include "transformWriter.h" -#include - -#include -#include -#include -#include +#include +#include +#include +#include +#include -#include #include #include #include #include #include #include +#include #include #include -#include #include #include +#include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE @@ -48,13 +48,11 @@ PXRUSDMAYA_REGISTER_WRITER(transform, UsdMayaTransformWriter); PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(transform, UsdGeomXform); // Given an Op, value and time, set the Op value based on op type and precision -static -void -setXformOp( - const UsdGeomXformOp& op, - const GfVec3d& value, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter* valueWriter) +static void setXformOp( + const UsdGeomXformOp& op, + const GfVec3d& value, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) { if (!op) { TF_CODING_ERROR("Xform op is not valid"); @@ -63,32 +61,30 @@ setXformOp( if (op.GetOpType() == UsdGeomXformOp::TypeTransform) { GfMatrix4d shearXForm(1.0); - shearXForm[1][0] = value[0]; //xyVal - shearXForm[2][0] = value[1]; //xzVal - shearXForm[2][1] = value[2]; //yzVal + shearXForm[1][0] = value[0]; // xyVal + shearXForm[2][0] = value[1]; // xzVal + shearXForm[2][1] = value[2]; // yzVal valueWriter->SetAttribute(op.GetAttr(), shearXForm, usdTime); return; } VtValue vtValue; if (UsdGeomXformOp::GetPrecisionFromValueTypeName(op.GetAttr().GetTypeName()) - == UsdGeomXformOp::PrecisionDouble) { + == UsdGeomXformOp::PrecisionDouble) { vtValue = VtValue(value); - } - else { // float precision + } else { // float precision vtValue = VtValue(GfVec3f(value)); } valueWriter->SetAttribute(op.GetAttr(), vtValue, usdTime); } /* static */ -void -UsdMayaTransformWriter::_ComputeXformOps( - const std::vector<_AnimChannel>& animChanList, - const UsdTimeCode& usdTime, - const bool eulerFilter, - UsdMayaTransformWriter::_TokenRotationMap* previousRotates, - UsdUtilsSparseValueWriter* valueWriter) +void UsdMayaTransformWriter::_ComputeXformOps( + const std::vector<_AnimChannel>& animChanList, + const UsdTimeCode& usdTime, + const bool eulerFilter, + UsdMayaTransformWriter::_TokenRotationMap* previousRotates, + UsdUtilsSparseValueWriter* valueWriter) { if (!TF_VERIFY(previousRotates)) { return; @@ -103,14 +99,13 @@ UsdMayaTransformWriter::_ComputeXformOps( } GfVec3d value = animChannel.defValue; - bool hasAnimated = false; - bool hasStatic = false; + bool hasAnimated = false; + bool hasStatic = false; for (unsigned int i = 0u; i < 3u; ++i) { if (animChannel.sampleType[i] == _SampleType::Animated) { value[i] = animChannel.plug[i].asDouble(); hasAnimated = true; - } - else if (animChannel.sampleType[i] == _SampleType::Static) { + } else if (animChannel.sampleType[i] == _SampleType::Static) { hasStatic = true; } } @@ -123,38 +118,35 @@ UsdMayaTransformWriter::_ComputeXformOps( // // This to make sure static channels are setting their default while // animating ones are actually animating - if ((usdTime == UsdTimeCode::Default() && hasStatic && !hasAnimated) || - (usdTime != UsdTimeCode::Default() && hasAnimated)) { + if ((usdTime == UsdTimeCode::Default() && hasStatic && !hasAnimated) + || (usdTime != UsdTimeCode::Default() && hasAnimated)) { if (animChannel.opType == _XformType::Rotate) { if (hasAnimated && eulerFilter) { - const TfToken& lookupName = animChannel.opName.IsEmpty() ? - UsdGeomXformOp::GetOpTypeToken(animChannel.usdOpType) : - animChannel.opName; + const TfToken& lookupName = animChannel.opName.IsEmpty() + ? UsdGeomXformOp::GetOpTypeToken(animChannel.usdOpType) + : animChannel.opName; auto findResult = previousRotates->find(lookupName); if (findResult == previousRotates->end()) { - MEulerRotation::RotationOrder rotOrder = - UsdMayaXformStack::RotateOrderFromOpType( - animChannel.usdOpType, - MEulerRotation::kXYZ); + MEulerRotation::RotationOrder rotOrder + = UsdMayaXformStack::RotateOrderFromOpType( + animChannel.usdOpType, MEulerRotation::kXYZ); MEulerRotation currentRotate(value[0], value[1], value[2], rotOrder); (*previousRotates)[lookupName] = currentRotate; - } - else { - MEulerRotation& previousRotate = findResult->second; - MEulerRotation::RotationOrder rotOrder = - UsdMayaXformStack::RotateOrderFromOpType( - animChannel.usdOpType, - previousRotate.order); + } else { + MEulerRotation& previousRotate = findResult->second; + MEulerRotation::RotationOrder rotOrder + = UsdMayaXformStack::RotateOrderFromOpType( + animChannel.usdOpType, previousRotate.order); MEulerRotation currentRotate(value[0], value[1], value[2], rotOrder); currentRotate.setToClosestSolution(previousRotate); - for (unsigned int i = 0; i<3; i++) { + for (unsigned int i = 0; i < 3; i++) { value[i] = currentRotate[i]; } (*previousRotates)[lookupName] = currentRotate; } } - for (unsigned int i = 0; i<3; i++) { + for (unsigned int i = 0; i < 3; i++) { value[i] = GfRadiansToDegrees(value[i]); } } @@ -165,15 +157,16 @@ UsdMayaTransformWriter::_ComputeXformOps( } /* static */ -bool -UsdMayaTransformWriter::_GatherAnimChannel( - const _XformType opType, - const MFnTransform& iTrans, - const TfToken& parentName, - const MString& xName, const MString& yName, const MString& zName, - std::vector<_AnimChannel>* oAnimChanList, - const bool isWritingAnimation, - const bool setOpName) +bool UsdMayaTransformWriter::_GatherAnimChannel( + const _XformType opType, + const MFnTransform& iTrans, + const TfToken& parentName, + const MString& xName, + const MString& yName, + const MString& zName, + std::vector<_AnimChannel>* oAnimChanList, + const bool isWritingAnimation, + const bool setOpName) { _AnimChannel chan; chan.opType = opType; @@ -192,17 +185,17 @@ UsdMayaTransformWriter::_GatherAnimChannel( // this is to handle the case where there is a connection to the parent // plug but not to the child plugs, if the connection is there and you are // not forcing static, then all of the children are considered animated - int parentSample = UsdMayaUtil::getSampledType(iTrans.findPlug(parentNameMStr),false); + int parentSample = UsdMayaUtil::getSampledType(iTrans.findPlug(parentNameMStr), false); // Determine what plug are needed based on default value & being // connected/animated MStringArray channels; - channels.append(parentNameMStr+xName); - channels.append(parentNameMStr+yName); - channels.append(parentNameMStr+zName); + channels.append(parentNameMStr + xName); + channels.append(parentNameMStr + yName); + channels.append(parentNameMStr + zName); GfVec3d nullValue(opType == _XformType::Scale ? 1.0 : 0.0); - for (unsigned int i = 0; i<3; i++) { + for (unsigned int i = 0; i < 3; i++) { // Find the plug and retrieve the data as the channel default value. It // won't be updated if the channel is NOT ANIMATED chan.plug[i] = iTrans.findPlug(channels[i]); @@ -212,12 +205,11 @@ UsdMayaTransformWriter::_GatherAnimChannel( // If we allow animation and either the parent sample or local sample is // not 0 then we have an Animated sample else we have a scale and the // value is NOT 1 or if the value is NOT 0 then we have a static xform - if ((parentSample != 0 || UsdMayaUtil::getSampledType(chan.plug[i], true) != 0) && - isWritingAnimation) { + if ((parentSample != 0 || UsdMayaUtil::getSampledType(chan.plug[i], true) != 0) + && isWritingAnimation) { chan.sampleType[i] = _SampleType::Animated; hasValidComponents = true; - } - else if (!GfIsClose(chan.defValue[i], nullValue[i], 1e-7)) { + } else if (!GfIsClose(chan.defValue[i], nullValue[i], 1e-7)) { chan.sampleType[i] = _SampleType::Static; hasValidComponents = true; } @@ -238,31 +230,28 @@ UsdMayaTransformWriter::_GatherAnimChannel( // Rotation Order ONLY applies to the "rotate" attribute if (parentName == UsdMayaXformStackTokens->rotate) { switch (iTrans.rotationOrder()) { - case MTransformationMatrix::kYZX: - chan.usdOpType = UsdGeomXformOp::TypeRotateYZX; - break; - case MTransformationMatrix::kZXY: - chan.usdOpType = UsdGeomXformOp::TypeRotateZXY; - break; - case MTransformationMatrix::kXZY: - chan.usdOpType = UsdGeomXformOp::TypeRotateXZY; - break; - case MTransformationMatrix::kYXZ: - chan.usdOpType = UsdGeomXformOp::TypeRotateYXZ; - break; - case MTransformationMatrix::kZYX: - chan.usdOpType = UsdGeomXformOp::TypeRotateZYX; - break; - default: - break; + case MTransformationMatrix::kYZX: + chan.usdOpType = UsdGeomXformOp::TypeRotateYZX; + break; + case MTransformationMatrix::kZXY: + chan.usdOpType = UsdGeomXformOp::TypeRotateZXY; + break; + case MTransformationMatrix::kXZY: + chan.usdOpType = UsdGeomXformOp::TypeRotateXZY; + break; + case MTransformationMatrix::kYXZ: + chan.usdOpType = UsdGeomXformOp::TypeRotateYXZ; + break; + case MTransformationMatrix::kZYX: + chan.usdOpType = UsdGeomXformOp::TypeRotateZYX; + break; + default: break; } } - } - else if (opType == _XformType::Shear) { + } else if (opType == _XformType::Shear) { chan.usdOpType = UsdGeomXformOp::TypeTransform; chan.precision = UsdGeomXformOp::PrecisionDouble; - } - else { + } else { return false; } oAnimChanList->push_back(chan); @@ -271,11 +260,10 @@ UsdMayaTransformWriter::_GatherAnimChannel( return false; } -void -UsdMayaTransformWriter::_PushTransformStack( - const MFnTransform& iTrans, - const UsdGeomXformable& usdXformable, - const bool writeAnim) +void UsdMayaTransformWriter::_PushTransformStack( + const MFnTransform& iTrans, + const UsdGeomXformable& usdXformable, + const bool writeAnim) { // NOTE: I think this logic and the logic in MayaTransformReader // should be merged so the concept of "CommonAPI" stays centralized. @@ -299,24 +287,69 @@ UsdMayaTransformWriter::_PushTransformStack( } // inspect the translate, no suffix to be closer compatibility with common API - _GatherAnimChannel(_XformType::Translate, iTrans, UsdMayaXformStackTokens->translate, "X", "Y", "Z", &_animChannels, writeAnim, false); + _GatherAnimChannel( + _XformType::Translate, + iTrans, + UsdMayaXformStackTokens->translate, + "X", + "Y", + "Z", + &_animChannels, + writeAnim, + false); // inspect the rotate pivot translate - if (_GatherAnimChannel(_XformType::Translate, iTrans, UsdMayaXformStackTokens->rotatePivotTranslate, "X", "Y", "Z", &_animChannels, writeAnim, true)) { + if (_GatherAnimChannel( + _XformType::Translate, + iTrans, + UsdMayaXformStackTokens->rotatePivotTranslate, + "X", + "Y", + "Z", + &_animChannels, + writeAnim, + true)) { conformsToCommonAPI = false; } // inspect the rotate pivot - bool hasRotatePivot = _GatherAnimChannel(_XformType::Translate, iTrans, UsdMayaXformStackTokens->rotatePivot, "X", "Y", "Z", &_animChannels, writeAnim, true); + bool hasRotatePivot = _GatherAnimChannel( + _XformType::Translate, + iTrans, + UsdMayaXformStackTokens->rotatePivot, + "X", + "Y", + "Z", + &_animChannels, + writeAnim, + true); if (hasRotatePivot) { - rotPivotIdx = _animChannels.size()-1; + rotPivotIdx = _animChannels.size() - 1; } // inspect the rotate, no suffix to be closer compatibility with common API - _GatherAnimChannel(_XformType::Rotate, iTrans, UsdMayaXformStackTokens->rotate, "X", "Y", "Z", &_animChannels, writeAnim, false); + _GatherAnimChannel( + _XformType::Rotate, + iTrans, + UsdMayaXformStackTokens->rotate, + "X", + "Y", + "Z", + &_animChannels, + writeAnim, + false); // inspect the rotateAxis/orientation - if (_GatherAnimChannel(_XformType::Rotate, iTrans, UsdMayaXformStackTokens->rotateAxis, "X", "Y", "Z", &_animChannels, writeAnim, true)) { + if (_GatherAnimChannel( + _XformType::Rotate, + iTrans, + UsdMayaXformStackTokens->rotateAxis, + "X", + "Y", + "Z", + &_animChannels, + writeAnim, + true)) { conformsToCommonAPI = false; } @@ -328,27 +361,64 @@ UsdMayaTransformWriter::_PushTransformStack( chan.opName = UsdMayaXformStackTokens->rotatePivot; chan.isInverse = true; _animChannels.push_back(chan); - rotPivotINVIdx = _animChannels.size()-1; + rotPivotINVIdx = _animChannels.size() - 1; } // inspect the scale pivot translation - if (_GatherAnimChannel(_XformType::Translate, iTrans, UsdMayaXformStackTokens->scalePivotTranslate, "X", "Y", "Z", &_animChannels, writeAnim, true)) { + if (_GatherAnimChannel( + _XformType::Translate, + iTrans, + UsdMayaXformStackTokens->scalePivotTranslate, + "X", + "Y", + "Z", + &_animChannels, + writeAnim, + true)) { conformsToCommonAPI = false; } // inspect the scale pivot point - bool hasScalePivot = _GatherAnimChannel(_XformType::Translate, iTrans, UsdMayaXformStackTokens->scalePivot, "X", "Y", "Z", &_animChannels, writeAnim, true); + bool hasScalePivot = _GatherAnimChannel( + _XformType::Translate, + iTrans, + UsdMayaXformStackTokens->scalePivot, + "X", + "Y", + "Z", + &_animChannels, + writeAnim, + true); if (hasScalePivot) { - scalePivotIdx = _animChannels.size()-1; + scalePivotIdx = _animChannels.size() - 1; } - // inspect the shear. Even if we have one xform on the xform list, it represents a share so we should name it - if (_GatherAnimChannel(_XformType::Shear, iTrans, UsdMayaXformStackTokens->shear, "XY", "XZ", "YZ", &_animChannels, writeAnim, true)) { + // inspect the shear. Even if we have one xform on the xform list, it represents a share so we + // should name it + if (_GatherAnimChannel( + _XformType::Shear, + iTrans, + UsdMayaXformStackTokens->shear, + "XY", + "XZ", + "YZ", + &_animChannels, + writeAnim, + true)) { conformsToCommonAPI = false; } // add the scale. no suffix to be closer compatibility with common API - _GatherAnimChannel(_XformType::Scale, iTrans, UsdMayaXformStackTokens->scale, "X", "Y", "Z", &_animChannels, writeAnim, false); + _GatherAnimChannel( + _XformType::Scale, + iTrans, + UsdMayaXformStackTokens->scale, + "X", + "Y", + "Z", + &_animChannels, + writeAnim, + false); // inverse the scale pivot point if (hasScalePivot) { @@ -358,7 +428,7 @@ UsdMayaTransformWriter::_PushTransformStack( chan.opName = UsdMayaXformStackTokens->scalePivot; chan.isInverse = true; _animChannels.push_back(chan); - scalePivotINVIdx = _animChannels.size()-1; + scalePivotINVIdx = _animChannels.size() - 1; } // If still potential common API, check if the pivots are the same and NOT animated/connected @@ -372,9 +442,9 @@ UsdMayaTransformWriter::_PushTransformStack( scalePivChan = _animChannels[scalePivotIdx]; // If they have different sampleType or are animated, then this does not // conformsToCommonAPI anymore - for (unsigned int i = 0;i<3;i++) { - if (rotPivChan.sampleType[i] != scalePivChan.sampleType[i] || - rotPivChan.sampleType[i] == _SampleType::Animated) { + for (unsigned int i = 0; i < 3; i++) { + if (rotPivChan.sampleType[i] != scalePivChan.sampleType[i] + || rotPivChan.sampleType[i] == _SampleType::Animated) { conformsToCommonAPI = false; } } @@ -385,9 +455,9 @@ UsdMayaTransformWriter::_PushTransformStack( } // If opType, usdType or precision are not the same, does not conformsToCommonAPI anymore - if (rotPivChan.opType != scalePivChan.opType || - rotPivChan.usdOpType != scalePivChan.usdOpType || - rotPivChan.precision != scalePivChan.precision) { + if (rotPivChan.opType != scalePivChan.opType + || rotPivChan.usdOpType != scalePivChan.usdOpType + || rotPivChan.precision != scalePivChan.precision) { conformsToCommonAPI = false; } @@ -402,19 +472,18 @@ UsdMayaTransformWriter::_PushTransformStack( // NOTE: scalePivotIdx > rotPivotINVIdx _animChannels[rotPivotIdx].opName = UsdMayaXformStackTokens->pivot; _animChannels[scalePivotINVIdx].opName = UsdMayaXformStackTokens->pivot; - _animChannels.erase(_animChannels.begin()+scalePivotIdx); - _animChannels.erase(_animChannels.begin()+rotPivotINVIdx); + _animChannels.erase(_animChannels.begin() + scalePivotIdx); + _animChannels.erase(_animChannels.begin() + rotPivotINVIdx); } } // Loop over anim channel vector and create corresponding XFormOps // including the inverse ones if needed - TF_FOR_ALL(iter, _animChannels) { + TF_FOR_ALL(iter, _animChannels) + { _AnimChannel& animChan = *iter; animChan.op = usdXformable.AddXformOp( - animChan.usdOpType, animChan.precision, - animChan.opName, - animChan.isInverse); + animChan.usdOpType, animChan.precision, animChan.opName, animChan.isInverse); if (!animChan.op) { TF_CODING_ERROR("Could not add xform op"); animChan.op = UsdGeomXformOp(); @@ -423,10 +492,10 @@ UsdMayaTransformWriter::_PushTransformStack( } UsdMayaTransformWriter::UsdMayaTransformWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) { // Even though we define an Xform here, it's OK for subclassers to // re-define the prim as another type. @@ -441,16 +510,12 @@ UsdMayaTransformWriter::UsdMayaTransformWriter( const MFnTransform transFn(GetDagPath()); // Create a vector of _AnimChannels based on the Maya transformation // ordering - _PushTransformStack( - transFn, - primSchema, - !_GetExportArgs().timeSamples.empty()); + _PushTransformStack(transFn, primSchema, !_GetExportArgs().timeSamples.empty()); } } /* virtual */ -void -UsdMayaTransformWriter::Write(const UsdTimeCode& usdTime) +void UsdMayaTransformWriter::Write(const UsdTimeCode& usdTime) { UsdMayaPrimWriter::Write(usdTime); @@ -471,5 +536,4 @@ UsdMayaTransformWriter::Write(const UsdTimeCode& usdTime) } } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/transformWriter.h b/lib/mayaUsd/fileio/transformWriter.h index cff77c79b6..6eaa95971c 100644 --- a/lib/mayaUsd/fileio/transformWriter.h +++ b/lib/mayaUsd/fileio/transformWriter.h @@ -16,27 +16,27 @@ #ifndef PXRUSDMAYA_TRANSFORM_WRITER_H #define PXRUSDMAYA_TRANSFORM_WRITER_H -#include -#include - -#include -#include -#include -#include -#include +#include +#include +#include -#include #include #include +#include #include #include -#include #include +#include #include -#include -#include -#include +#include +#include +#include +#include +#include + +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -47,9 +47,9 @@ class UsdMayaTransformWriter : public UsdMayaPrimWriter public: MAYAUSD_CORE_PUBLIC UsdMayaTransformWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); /// Main export function that runs when the traversal hits the node. /// This extends UsdMayaPrimWriter::Write() by exporting xform ops for @@ -58,67 +58,78 @@ class UsdMayaTransformWriter : public UsdMayaPrimWriter void Write(const UsdTimeCode& usdTime) override; private: - using _TokenRotationMap = std::unordered_map< - const TfToken, MEulerRotation, TfToken::HashFunctor>; + using _TokenRotationMap + = std::unordered_map; - enum class _XformType { Translate, Rotate, Scale, Shear }; - enum class _SampleType { None, Static, Animated }; + enum class _XformType + { + Translate, + Rotate, + Scale, + Shear + }; + enum class _SampleType + { + None, + Static, + Animated + }; // This may not be the best name here as it isn't necessarily animated. struct _AnimChannel { - MPlug plug[3]; + MPlug plug[3]; _SampleType sampleType[3]; // defValue should always be in "maya" space. that is, if it's a // rotation it should be radians, not degrees. (This is done so we only // need to do conversion in one place, and so that, if we need to do // euler filtering, we don't do conversions, and then undo them to use // MEulerRotation). - GfVec3d defValue; - _XformType opType; - UsdGeomXformOp::Type usdOpType; + GfVec3d defValue; + _XformType opType; + UsdGeomXformOp::Type usdOpType; UsdGeomXformOp::Precision precision; - TfToken opName; - bool isInverse; - UsdGeomXformOp op; + TfToken opName; + bool isInverse; + UsdGeomXformOp op; }; // For a given array of _AnimChannels and time, compute the xformOp data if // needed and set the xformOps' values. static void _ComputeXformOps( - const std::vector<_AnimChannel>& animChanList, - const UsdTimeCode& usdTime, - const bool eulerFilter, - UsdMayaTransformWriter::_TokenRotationMap* previousRotates, - UsdUtilsSparseValueWriter* valueWriter); + const std::vector<_AnimChannel>& animChanList, + const UsdTimeCode& usdTime, + const bool eulerFilter, + UsdMayaTransformWriter::_TokenRotationMap* previousRotates, + UsdUtilsSparseValueWriter* valueWriter); // Creates an _AnimChannel from a Maya compound attribute if there is // meaningful data. This means we found data that is non-identity. // Returns true if we extracted an _AnimChannel and false otherwise (e.g. // the data was identity). static bool _GatherAnimChannel( - const _XformType opType, - const MFnTransform& iTrans, - const TfToken& parentName, - const MString& xName, const MString& yName, const MString& zName, - std::vector<_AnimChannel>* oAnimChanList, - const bool isWritingAnimation, - const bool setOpName); + const _XformType opType, + const MFnTransform& iTrans, + const TfToken& parentName, + const MString& xName, + const MString& yName, + const MString& zName, + std::vector<_AnimChannel>* oAnimChanList, + const bool isWritingAnimation, + const bool setOpName); /// Populates the AnimChannel vector with various ops based on /// the Maya transformation logic. If scale and/or rotate pivot are /// declared, creates inverse ops in the appropriate order. void _PushTransformStack( - const MFnTransform& iTrans, - const UsdGeomXformable& usdXForm, - const bool writeAnim); + const MFnTransform& iTrans, + const UsdGeomXformable& usdXForm, + const bool writeAnim); std::vector<_AnimChannel> _animChannels; - _TokenRotationMap _previousRotates; + _TokenRotationMap _previousRotates; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/translators/skelBindingsProcessor.cpp b/lib/mayaUsd/fileio/translators/skelBindingsProcessor.cpp index 8f855670fa..62c935bce6 100644 --- a/lib/mayaUsd/fileio/translators/skelBindingsProcessor.cpp +++ b/lib/mayaUsd/fileio/translators/skelBindingsProcessor.cpp @@ -15,23 +15,20 @@ // #include "skelBindingsProcessor.h" +#include + #include #include #include #include -#include - PXR_NAMESPACE_OPEN_SCOPE -UsdMaya_SkelBindingsProcessor::UsdMaya_SkelBindingsProcessor() -{ -} +UsdMaya_SkelBindingsProcessor::UsdMaya_SkelBindingsProcessor() { } /// Finds the rootmost ancestor of the prim at \p path that is an Xform /// or SkelRoot type prim. The result may be the prim itself. -static UsdPrim -_FindRootmostXformOrSkelRoot(const UsdStagePtr& stage, const SdfPath& path) +static UsdPrim _FindRootmostXformOrSkelRoot(const UsdStagePtr& stage, const SdfPath& path) { UsdPrim currentPrim = stage->GetPrimAtPath(path); UsdPrim rootmost; @@ -47,7 +44,6 @@ _FindRootmostXformOrSkelRoot(const UsdStagePtr& stage, const SdfPath& path) return rootmost; } - /// Finds the existing SkelRoot which is shared by all \p paths. /// If no SkelRoot is found, and \p config is "auto", then attempts to /// find a common ancestor of \p paths which can be converted to SkelRoot. @@ -57,12 +53,10 @@ _FindRootmostXformOrSkelRoot(const UsdStagePtr& stage, const SdfPath& path) /// If an existing, common SkelRoot cannot be found for all paths, and if /// it's not possible to create one, returns an empty SdfPath. static SdfPath -_VerifyOrMakeSkelRoot(const UsdStagePtr& stage, - const SdfPath& path, - const TfToken& config) +_VerifyOrMakeSkelRoot(const UsdStagePtr& stage, const SdfPath& path, const TfToken& config) { - if (config != UsdMayaJobExportArgsTokens->auto_ && - config != UsdMayaJobExportArgsTokens->explicit_) { + if (config != UsdMayaJobExportArgsTokens->auto_ + && config != UsdMayaJobExportArgsTokens->explicit_) { return SdfPath(); } @@ -76,15 +70,16 @@ _VerifyOrMakeSkelRoot(const UsdStagePtr& stage, // This is necessary because UsdSkel doesn't handle nested skel roots // very well currently; this restriction may be loosened in the future. if (UsdSkelRoot root2 = UsdSkelRoot::Find(root.GetPrim().GetParent())) { - TF_RUNTIME_ERROR("The SkelRoot <%s> is nested inside another " - "SkelRoot <%s>. This might cause unexpected behavior.", - root.GetPath().GetText(), root2.GetPath().GetText()); + TF_RUNTIME_ERROR( + "The SkelRoot <%s> is nested inside another " + "SkelRoot <%s>. This might cause unexpected behavior.", + root.GetPath().GetText(), + root2.GetPath().GetText()); return SdfPath(); - } - else { + } else { return root.GetPath(); } - } else if(config == UsdMayaJobExportArgsTokens->auto_) { + } else if (config == UsdMayaJobExportArgsTokens->auto_) { // If auto-generating the SkelRoot, find the rootmost // UsdGeomXform and turn it into a SkelRoot. // XXX: It might be good to also consider model hierarchy here, and not @@ -96,27 +91,27 @@ _VerifyOrMakeSkelRoot(const UsdStagePtr& stage, if (UsdPrim root = _FindRootmostXformOrSkelRoot(stage, path)) { UsdSkelRoot::Define(stage, root.GetPath()); return root.GetPath(); - } - else { + } else { if (path.IsRootPrimPath()) { // This is the most common problem when we can't obtain a // SkelRoot. // Show a nice error with useful information about root prims. - TF_RUNTIME_ERROR("The prim <%s> is a root prim, so it has no " - "ancestors that can be converted to a SkelRoot. (USD " - "requires that skinned meshes and skeletons be " - "encapsulated under a SkelRoot.) Try grouping this " - "prim under a parent group.", - path.GetText()); - } - else { + TF_RUNTIME_ERROR( + "The prim <%s> is a root prim, so it has no " + "ancestors that can be converted to a SkelRoot. (USD " + "requires that skinned meshes and skeletons be " + "encapsulated under a SkelRoot.) Try grouping this " + "prim under a parent group.", + path.GetText()); + } else { // Show generic error as a last resort if we don't know exactly // what went wrong. - TF_RUNTIME_ERROR("Could not find an ancestor of the prim <%s> " - "that can be converted to a SkelRoot. (USD requires " - "that skinned meshes and skeletons be encapsulated " - "under a SkelRoot.)", - path.GetText()); + TF_RUNTIME_ERROR( + "Could not find an ancestor of the prim <%s> " + "that can be converted to a SkelRoot. (USD requires " + "that skinned meshes and skeletons be encapsulated " + "under a SkelRoot.)", + path.GetText()); } return SdfPath(); } @@ -124,10 +119,7 @@ _VerifyOrMakeSkelRoot(const UsdStagePtr& stage, return SdfPath(); } - - -void -UsdMaya_SkelBindingsProcessor::MarkBindings( +void UsdMaya_SkelBindingsProcessor::MarkBindings( const SdfPath& path, const SdfPath& skelPath, const TfToken& config) @@ -135,25 +127,18 @@ UsdMaya_SkelBindingsProcessor::MarkBindings( _bindingToSkelMap[path] = _Entry(skelPath, config); } - -bool -UsdMaya_SkelBindingsProcessor::_VerifyOrMakeSkelRoots( - const UsdStagePtr& stage) const +bool UsdMaya_SkelBindingsProcessor::_VerifyOrMakeSkelRoots(const UsdStagePtr& stage) const { bool success = true; for (const auto& pair : _bindingToSkelMap) { const _Entry& entry = pair.second; - SdfPath skelRootPath = - _VerifyOrMakeSkelRoot(stage, pair.first, entry.second); + SdfPath skelRootPath = _VerifyOrMakeSkelRoot(stage, pair.first, entry.second); success = success && !skelRootPath.IsEmpty(); } return success; } - -bool -UsdMaya_SkelBindingsProcessor::PostProcessSkelBindings( - const UsdStagePtr& stage) const +bool UsdMaya_SkelBindingsProcessor::PostProcessSkelBindings(const UsdStagePtr& stage) const { bool success = _VerifyOrMakeSkelRoots(stage); @@ -163,5 +148,4 @@ UsdMaya_SkelBindingsProcessor::PostProcessSkelBindings( return success; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/translators/skelBindingsProcessor.h b/lib/mayaUsd/fileio/translators/skelBindingsProcessor.h index 135493514c..699662ef71 100644 --- a/lib/mayaUsd/fileio/translators/skelBindingsProcessor.h +++ b/lib/mayaUsd/fileio/translators/skelBindingsProcessor.h @@ -16,17 +16,17 @@ #ifndef PXRUSDMAYA_SKEL_BINDINGS_PROCESSOR_H #define PXRUSDMAYA_SKEL_BINDINGS_PROCESSOR_H -#include -#include - -#include +#include +#include #include #include #include -#include -#include +#include + +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -45,23 +45,19 @@ class UsdMaya_SkelBindingsProcessor /// - UsdMayaJobExportArgsTokens->auto_: create a SkelRoot if needed /// UsdMayaJobExportArgsTokens->none is not valid for \p config; it will /// mark an invalid binding. - void MarkBindings(const SdfPath& path, - const SdfPath& skelPath, - const TfToken& config); + void MarkBindings(const SdfPath& path, const SdfPath& skelPath, const TfToken& config); /// Performs final processing for skel bindings. bool PostProcessSkelBindings(const UsdStagePtr& stage) const; private: - bool _VerifyOrMakeSkelRoots(const UsdStagePtr& stage) const; - using _Entry = std::pair; + using _Entry = std::pair; std::unordered_map _bindingToSkelMap; }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/translators/translatorCamera.cpp b/lib/mayaUsd/fileio/translators/translatorCamera.cpp index 9d3d0a0348..adda3273ff 100644 --- a/lib/mayaUsd/fileio/translators/translatorCamera.cpp +++ b/lib/mayaUsd/fileio/translators/translatorCamera.cpp @@ -15,14 +15,12 @@ // #include "translatorCamera.h" -#include -#include - -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include #include @@ -35,53 +33,52 @@ #include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include + +#include +#include PXR_NAMESPACE_OPEN_SCOPE static bool _ReadToCamera( - const UsdGeomCamera& usdCamera, - MFnCamera& cameraObject, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context); - -TF_DEFINE_PRIVATE_TOKENS(_tokens, - ((MayaCameraTypeName, "camera")) - ((MayaCameraShapeNameSuffix, "Shape")) - - ((MayaCameraAttrNameHorizontalAperture, "horizontalFilmAperture")) - ((MayaCameraAttrNameVerticalAperture, "verticalFilmAperture")) - ((MayaCameraAttrNameHorizontalApertureOffset, "horizontalFilmOffset")) - ((MayaCameraAttrNameVerticalApertureOffset, "verticalFilmOffset")) - ((MayaCameraAttrNameOrthographicWidth, "orthographicWidth")) - ((MayaCameraAttrNameFocalLength, "focalLength")) - ((MayaCameraAttrNameFocusDistance, "focusDistance")) - ((MayaCameraAttrNameFStop, "fStop")) - ((MayaCameraAttrNameNearClippingPlane, "nearClipPlane")) - ((MayaCameraAttrNameFarClippingPlane, "farClipPlane")) -); - - -static -bool -_CheckUsdTypeAndResizeArrays( - const UsdAttribute& usdAttr, - const TfType& expectedType, - const GfInterval& timeInterval, - std::vector* timeSamples, - MTimeArray* timeArray, - MDoubleArray* valueArray) + const UsdGeomCamera& usdCamera, + MFnCamera& cameraObject, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context); + +TF_DEFINE_PRIVATE_TOKENS( + _tokens, + ((MayaCameraTypeName, "camera"))((MayaCameraShapeNameSuffix, "Shape")) + + ((MayaCameraAttrNameHorizontalAperture, + "horizontalFilmAperture"))((MayaCameraAttrNameVerticalAperture, "verticalFilmAperture"))( + (MayaCameraAttrNameHorizontalApertureOffset, "horizontalFilmOffset"))( + (MayaCameraAttrNameVerticalApertureOffset, + "verticalFilmOffset"))((MayaCameraAttrNameOrthographicWidth, "orthographicWidth"))( + (MayaCameraAttrNameFocalLength, "focalLength"))( + (MayaCameraAttrNameFocusDistance, "focusDistance"))((MayaCameraAttrNameFStop, "fStop"))( + (MayaCameraAttrNameNearClippingPlane, + "nearClipPlane"))((MayaCameraAttrNameFarClippingPlane, "farClipPlane"))); + +static bool _CheckUsdTypeAndResizeArrays( + const UsdAttribute& usdAttr, + const TfType& expectedType, + const GfInterval& timeInterval, + std::vector* timeSamples, + MTimeArray* timeArray, + MDoubleArray* valueArray) { // Validate that the attribute holds values of the expected type. const TfType type = usdAttr.GetTypeName().GetType(); if (type != expectedType) { - TF_CODING_ERROR("Unsupported type name for USD attribute '%s': %s", - usdAttr.GetName().GetText(), type.GetTypeName().c_str()); + TF_CODING_ERROR( + "Unsupported type name for USD attribute '%s': %s", + usdAttr.GetName().GetText(), + type.GetTypeName().c_str()); return false; } @@ -100,24 +97,18 @@ _CheckUsdTypeAndResizeArrays( return true; } -static -bool -_GetTimeAndValueArrayForUsdAttribute( - const UsdAttribute& usdAttr, - const GfInterval& timeInterval, - MTimeArray* timeArray, - MDoubleArray* valueArray, - const MDistance::Unit convertToUnit = MDistance::kMillimeters) +static bool _GetTimeAndValueArrayForUsdAttribute( + const UsdAttribute& usdAttr, + const GfInterval& timeInterval, + MTimeArray* timeArray, + MDoubleArray* valueArray, + const MDistance::Unit convertToUnit = MDistance::kMillimeters) { static const TfType& floatType = TfType::Find(); - std::vector timeSamples; - - if (!_CheckUsdTypeAndResizeArrays(usdAttr, - floatType, - timeInterval, - &timeSamples, - timeArray, - valueArray)) { + std::vector timeSamples; + + if (!_CheckUsdTypeAndResizeArrays( + usdAttr, floatType, timeInterval, &timeSamples, timeArray, valueArray)) { return false; } @@ -125,21 +116,17 @@ _GetTimeAndValueArrayForUsdAttribute( for (size_t i = 0; i < numTimeSamples; ++i) { const double timeSample = timeSamples[i]; - float attrValue; + float attrValue; if (!usdAttr.Get(&attrValue, timeSample)) { return false; } switch (convertToUnit) { - case MDistance::kInches: - attrValue = UsdMayaUtil::ConvertMMToInches(attrValue); - break; - case MDistance::kCentimeters: - attrValue = UsdMayaUtil::ConvertMMToCM(attrValue); - break; - default: - // The input is expected to be in millimeters. - break; + case MDistance::kInches: attrValue = UsdMayaUtil::ConvertMMToInches(attrValue); break; + case MDistance::kCentimeters: attrValue = UsdMayaUtil::ConvertMMToCM(attrValue); break; + default: + // The input is expected to be in millimeters. + break; } timeArray->set(MTime(timeSample), i); @@ -152,24 +139,18 @@ _GetTimeAndValueArrayForUsdAttribute( // This is primarily intended for use in translating the clippingRange // USD attribute which is stored in USD as a single GfVec2f value but // in Maya as separate nearClipPlane and farClipPlane attributes. -static -bool -_GetTimeAndValueArraysForUsdAttribute( - const UsdAttribute& usdAttr, - const GfInterval& timeInterval, - MTimeArray* timeArray, - MDoubleArray* valueArray1, - MDoubleArray* valueArray2) +static bool _GetTimeAndValueArraysForUsdAttribute( + const UsdAttribute& usdAttr, + const GfInterval& timeInterval, + MTimeArray* timeArray, + MDoubleArray* valueArray1, + MDoubleArray* valueArray2) { static const TfType& vec2fType = TfType::Find(); - std::vector timeSamples; - - if (!_CheckUsdTypeAndResizeArrays(usdAttr, - vec2fType, - timeInterval, - &timeSamples, - timeArray, - valueArray1)) { + std::vector timeSamples; + + if (!_CheckUsdTypeAndResizeArrays( + usdAttr, vec2fType, timeInterval, &timeSamples, timeArray, valueArray1)) { return false; } @@ -178,7 +159,7 @@ _GetTimeAndValueArraysForUsdAttribute( for (size_t i = 0; i < numTimeSamples; ++i) { const double timeSample = timeSamples[i]; - GfVec2f attrValue; + GfVec2f attrValue; if (!usdAttr.Get(&attrValue, timeSample)) { return false; } @@ -190,17 +171,15 @@ _GetTimeAndValueArraysForUsdAttribute( return true; } -static -bool -_CreateAnimCurveForPlug( - MPlug& plug, - MTimeArray& timeArray, - MDoubleArray& valueArray, - UsdMayaPrimReaderContext* context) +static bool _CreateAnimCurveForPlug( + MPlug& plug, + MTimeArray& timeArray, + MDoubleArray& valueArray, + UsdMayaPrimReaderContext* context) { MFnAnimCurve animFn; - MStatus status; - MObject animObj = animFn.create(plug, nullptr, &status); + MStatus status; + MObject animObj = animFn.create(plug, nullptr, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = animFn.addKeys(&timeArray, &valueArray); @@ -214,26 +193,21 @@ _CreateAnimCurveForPlug( return true; } -static -bool -_TranslateAnimatedUsdAttributeToPlug( - const UsdAttribute& usdAttr, - MPlug& plug, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context, - const MDistance::Unit convertToUnit = MDistance::kMillimeters) +static bool _TranslateAnimatedUsdAttributeToPlug( + const UsdAttribute& usdAttr, + MPlug& plug, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context, + const MDistance::Unit convertToUnit = MDistance::kMillimeters) { if (args.GetTimeInterval().IsEmpty()) { return false; } - MTimeArray timeArray; + MTimeArray timeArray; MDoubleArray valueArray; - if (!_GetTimeAndValueArrayForUsdAttribute(usdAttr, - args.GetTimeInterval(), - &timeArray, - &valueArray, - convertToUnit)) { + if (!_GetTimeAndValueArrayForUsdAttribute( + usdAttr, args.GetTimeInterval(), &timeArray, &valueArray, convertToUnit)) { return false; } @@ -244,27 +218,22 @@ _TranslateAnimatedUsdAttributeToPlug( return true; } -static -bool -_TranslateAnimatedUsdAttributeToPlugs( - const UsdAttribute& usdAttr, - MPlug& plug1, - MPlug& plug2, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context) +static bool _TranslateAnimatedUsdAttributeToPlugs( + const UsdAttribute& usdAttr, + MPlug& plug1, + MPlug& plug2, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context) { if (args.GetTimeInterval().IsEmpty()) { return false; } - MTimeArray timeArray; + MTimeArray timeArray; MDoubleArray valueArray1; MDoubleArray valueArray2; - if (!_GetTimeAndValueArraysForUsdAttribute(usdAttr, - args.GetTimeInterval(), - &timeArray, - &valueArray1, - &valueArray2)) { + if (!_GetTimeAndValueArraysForUsdAttribute( + usdAttr, args.GetTimeInterval(), &timeArray, &valueArray1, &valueArray2)) { return false; } @@ -279,15 +248,13 @@ _TranslateAnimatedUsdAttributeToPlugs( return true; } -static -bool -_TranslateUsdAttributeToPlug( - const UsdAttribute& usdAttr, - const MFnCamera& cameraFn, - const TfToken& plugName, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context, - const MDistance::Unit convertToUnit = MDistance::kMillimeters) +static bool _TranslateUsdAttributeToPlug( + const UsdAttribute& usdAttr, + const MFnCamera& cameraFn, + const TfToken& plugName, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context, + const MDistance::Unit convertToUnit = MDistance::kMillimeters) { MStatus status; @@ -295,26 +262,18 @@ _TranslateUsdAttributeToPlug( CHECK_MSTATUS_AND_RETURN(status, false); // First check for and translate animation if there is any. - if (!_TranslateAnimatedUsdAttributeToPlug(usdAttr, - plug, - args, - context, - convertToUnit)) { + if (!_TranslateAnimatedUsdAttributeToPlug(usdAttr, plug, args, context, convertToUnit)) { // If that fails, then try just setting a static value. UsdTimeCode timeCode = UsdTimeCode::EarliestTime(); - float attrValue; + float attrValue; usdAttr.Get(&attrValue, timeCode); switch (convertToUnit) { - case MDistance::kInches: - attrValue = UsdMayaUtil::ConvertMMToInches(attrValue); - break; - case MDistance::kCentimeters: - attrValue = UsdMayaUtil::ConvertMMToCM(attrValue); - break; - default: - // The input is expected to be in millimeters. - break; + case MDistance::kInches: attrValue = UsdMayaUtil::ConvertMMToInches(attrValue); break; + case MDistance::kCentimeters: attrValue = UsdMayaUtil::ConvertMMToCM(attrValue); break; + default: + // The input is expected to be in millimeters. + break; } status = plug.setFloat(attrValue); @@ -325,38 +284,32 @@ _TranslateUsdAttributeToPlug( } /* static */ -bool -UsdMayaTranslatorCamera::Read( - const UsdGeomCamera& usdCamera, - MObject parentNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context) +bool UsdMayaTranslatorCamera::Read( + const UsdGeomCamera& usdCamera, + MObject parentNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context) { if (!usdCamera) { return false; } const UsdPrim& prim = usdCamera.GetPrim(); - const SdfPath primPath = prim.GetPath(); + const SdfPath primPath = prim.GetPath(); MStatus status; // Create the transform node for the camera. MObject transformObj; - if (!UsdMayaTranslatorUtil::CreateTransformNode(prim, - parentNode, - args, - context, - &status, - &transformObj)) { + if (!UsdMayaTranslatorUtil::CreateTransformNode( + prim, parentNode, args, context, &status, &transformObj)) { return false; } // Create the camera shape node. MDagModifier dagMod; - MObject cameraObj = dagMod.createNode(_tokens->MayaCameraTypeName.GetText(), - transformObj, - &status); + MObject cameraObj + = dagMod.createNode(_tokens->MayaCameraTypeName.GetText(), transformObj, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = dagMod.doIt(); CHECK_MSTATUS_AND_RETURN(status, false); @@ -364,8 +317,8 @@ UsdMayaTranslatorCamera::Read( MFnCamera cameraFn(cameraObj, &status); CHECK_MSTATUS_AND_RETURN(status, false); - const std::string cameraShapeName = prim.GetName().GetString() + - _tokens->MayaCameraShapeNameSuffix.GetString(); + const std::string cameraShapeName + = prim.GetName().GetString() + _tokens->MayaCameraShapeNameSuffix.GetString(); cameraFn.setName(cameraShapeName.c_str(), &status); CHECK_MSTATUS_AND_RETURN(status, false); if (context) { @@ -377,40 +330,33 @@ UsdMayaTranslatorCamera::Read( } /* static */ -bool -UsdMayaTranslatorCamera::ReadToCamera( - const UsdGeomCamera& usdCamera, - MFnCamera& cameraObject) +bool UsdMayaTranslatorCamera::ReadToCamera(const UsdGeomCamera& usdCamera, MFnCamera& cameraObject) { VtDictionary userArgsDict; // Disable shading import since we're only interested in the camera. - userArgsDict[UsdMayaJobImportArgsTokens->shadingMode] = - std::vector { VtValue( - std::vector { - VtValue(UsdMayaShadingModeTokens->none.GetString()), - VtValue(std::string("default")) }) }; - - UsdMayaJobImportArgs importArgs = - UsdMayaJobImportArgs::CreateFromDictionary(userArgsDict); + userArgsDict[UsdMayaJobImportArgsTokens->shadingMode] = std::vector { VtValue( + std::vector { VtValue(UsdMayaShadingModeTokens->none.GetString()), + VtValue(std::string("default")) }) }; + + UsdMayaJobImportArgs importArgs = UsdMayaJobImportArgs::CreateFromDictionary(userArgsDict); UsdMayaPrimReaderArgs args(usdCamera.GetPrim(), importArgs); return _ReadToCamera(usdCamera, cameraObject, args, nullptr); } -bool -_ReadToCamera( - const UsdGeomCamera& usdCamera, - MFnCamera& cameraFn, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context) +bool _ReadToCamera( + const UsdGeomCamera& usdCamera, + MFnCamera& cameraFn, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context) { MStatus status; // Now translate all of the USD camera attributes over to plugs on the // Maya cameraFn. - UsdTimeCode timeCode = UsdTimeCode::EarliestTime(); + UsdTimeCode timeCode = UsdTimeCode::EarliestTime(); UsdAttribute usdAttr; - TfToken plugName; + TfToken plugName; // Set the type of projection. This is NOT keyable in Maya. TfToken projection; @@ -422,9 +368,13 @@ _ReadToCamera( // Setup the aperture. usdAttr = usdCamera.GetHorizontalApertureAttr(); plugName = _tokens->MayaCameraAttrNameHorizontalAperture; - if (!_TranslateUsdAttributeToPlug(usdAttr, cameraFn, plugName, - args, context, - /* convertToUnit = */ MDistance::kInches)) { + if (!_TranslateUsdAttributeToPlug( + usdAttr, + cameraFn, + plugName, + args, + context, + /* convertToUnit = */ MDistance::kInches)) { return false; } @@ -435,18 +385,26 @@ _ReadToCamera( // but we author them anyway so that the data is preserved. Note also // that Maya stores the orthographicWidth as centimeters. plugName = _tokens->MayaCameraAttrNameOrthographicWidth; - if (!_TranslateUsdAttributeToPlug(usdAttr, cameraFn, plugName, - args, context, - /* convertToUnit = */ MDistance::kCentimeters)) { + if (!_TranslateUsdAttributeToPlug( + usdAttr, + cameraFn, + plugName, + args, + context, + /* convertToUnit = */ MDistance::kCentimeters)) { return false; } } usdAttr = usdCamera.GetVerticalApertureAttr(); plugName = _tokens->MayaCameraAttrNameVerticalAperture; - if (!_TranslateUsdAttributeToPlug(usdAttr, cameraFn, plugName, - args, context, - /* convertToUnit = */ MDistance::kInches)) { + if (!_TranslateUsdAttributeToPlug( + usdAttr, + cameraFn, + plugName, + args, + context, + /* convertToUnit = */ MDistance::kInches)) { return false; } @@ -457,39 +415,44 @@ _ReadToCamera( usdAttr = usdCamera.GetHorizontalApertureOffsetAttr(); plugName = _tokens->MayaCameraAttrNameHorizontalApertureOffset; - if (!_TranslateUsdAttributeToPlug(usdAttr, cameraFn, plugName, - args, context, - /* convertToUnit = */ MDistance::kInches)) { + if (!_TranslateUsdAttributeToPlug( + usdAttr, + cameraFn, + plugName, + args, + context, + /* convertToUnit = */ MDistance::kInches)) { return false; } usdAttr = usdCamera.GetVerticalApertureOffsetAttr(); plugName = _tokens->MayaCameraAttrNameVerticalApertureOffset; - if (!_TranslateUsdAttributeToPlug(usdAttr, cameraFn, plugName, - args, context, - /* convertToUnit = */ MDistance::kInches)) { + if (!_TranslateUsdAttributeToPlug( + usdAttr, + cameraFn, + plugName, + args, + context, + /* convertToUnit = */ MDistance::kInches)) { return false; } // Set the lens parameters. usdAttr = usdCamera.GetFocalLengthAttr(); plugName = _tokens->MayaCameraAttrNameFocalLength; - if (!_TranslateUsdAttributeToPlug(usdAttr, cameraFn, plugName, - args, context)) { + if (!_TranslateUsdAttributeToPlug(usdAttr, cameraFn, plugName, args, context)) { return false; } usdAttr = usdCamera.GetFocusDistanceAttr(); plugName = _tokens->MayaCameraAttrNameFocusDistance; - if (!_TranslateUsdAttributeToPlug(usdAttr, cameraFn, plugName, - args, context)) { + if (!_TranslateUsdAttributeToPlug(usdAttr, cameraFn, plugName, args, context)) { return false; } usdAttr = usdCamera.GetFStopAttr(); plugName = _tokens->MayaCameraAttrNameFStop; - if (!_TranslateUsdAttributeToPlug(usdAttr, cameraFn, plugName, - args, context)) { + if (!_TranslateUsdAttributeToPlug(usdAttr, cameraFn, plugName, args, context)) { return false; } @@ -497,17 +460,13 @@ _ReadToCamera( // because it is stored in USD as a single GfVec2f value but in Maya as // separate nearClipPlane and farClipPlane attributes. usdAttr = usdCamera.GetClippingRangeAttr(); - MPlug nearClipPlug = cameraFn.findPlug( - _tokens->MayaCameraAttrNameNearClippingPlane.GetText(), true, &status); + MPlug nearClipPlug + = cameraFn.findPlug(_tokens->MayaCameraAttrNameNearClippingPlane.GetText(), true, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug farClipPlug = cameraFn.findPlug( - _tokens->MayaCameraAttrNameFarClippingPlane.GetText(), true, &status); + MPlug farClipPlug + = cameraFn.findPlug(_tokens->MayaCameraAttrNameFarClippingPlane.GetText(), true, &status); CHECK_MSTATUS_AND_RETURN(status, false); - if (!_TranslateAnimatedUsdAttributeToPlugs(usdAttr, - nearClipPlug, - farClipPlug, - args, - context)) { + if (!_TranslateAnimatedUsdAttributeToPlugs(usdAttr, nearClipPlug, farClipPlug, args, context)) { GfVec2f clippingRange; usdCamera.GetClippingRangeAttr().Get(&clippingRange, timeCode); status = cameraFn.setNearClippingPlane(clippingRange[0]); @@ -519,5 +478,4 @@ _ReadToCamera( return true; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/translators/translatorCamera.h b/lib/mayaUsd/fileio/translators/translatorCamera.h index 2abe378560..8d464a36c2 100644 --- a/lib/mayaUsd/fileio/translators/translatorCamera.h +++ b/lib/mayaUsd/fileio/translators/translatorCamera.h @@ -16,15 +16,15 @@ #ifndef PXRUSDMAYA_TRANSLATOR_CAMERA_H #define PXRUSDMAYA_TRANSLATOR_CAMERA_H -#include -#include +#include +#include +#include #include #include -#include -#include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -35,22 +35,17 @@ struct UsdMayaTranslatorCamera /// MFnCamera under \p parentNode. MAYAUSD_CORE_PUBLIC static bool Read( - const UsdGeomCamera& usdCamera, - MObject parentNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context); + const UsdGeomCamera& usdCamera, + MObject parentNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context); /// Helper function to access just the logic that writes from a non-animated /// camera into an existing maya camera. MAYAUSD_CORE_PUBLIC - static bool ReadToCamera( - const UsdGeomCamera& usdCamera, - MFnCamera& cameraObject); - + static bool ReadToCamera(const UsdGeomCamera& usdCamera, MFnCamera& cameraObject); }; - - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/translators/translatorCurves.cpp b/lib/mayaUsd/fileio/translators/translatorCurves.cpp index 1b48fabca6..3bc0772f55 100644 --- a/lib/mayaUsd/fileio/translators/translatorCurves.cpp +++ b/lib/mayaUsd/fileio/translators/translatorCurves.cpp @@ -15,6 +15,11 @@ // #include "translatorCurves.h" +#include + +#include +#include + #include #include #include @@ -26,20 +31,14 @@ #include #include -#include -#include - -#include - PXR_NAMESPACE_OPEN_SCOPE /* static */ -bool -UsdMayaTranslatorCurves::Create( - const UsdGeomCurves& curves, - MObject parentNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context) +bool UsdMayaTranslatorCurves::Create( + const UsdGeomCurves& curves, + MObject parentNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context) { if (!curves) { return false; @@ -51,12 +50,8 @@ UsdMayaTranslatorCurves::Create( // Create node (transform) MObject mayaNodeTransformObj; - if (!UsdMayaTranslatorUtil::CreateTransformNode(prim, - parentNode, - args, - context, - &status, - &mayaNodeTransformObj)) { + if (!UsdMayaTranslatorUtil::CreateTransformNode( + prim, parentNode, args, context, &status, &mayaNodeTransformObj)) { return false; } @@ -79,12 +74,11 @@ UsdMayaTranslatorCurves::Create( // Sanity Checks if (curveVertexCounts.empty()) { TF_RUNTIME_ERROR( - "vertexCount array is empty on NurbsCurves <%s>. Skipping...", - prim.GetPath().GetText()); + "vertexCount array is empty on NurbsCurves <%s>. Skipping...", + prim.GetPath().GetText()); return false; // No verts for the curve, so exit } else if (curveVertexCounts.size() > 1) { - TF_WARN("Multiple curves in <%s>. Only reading the first one...", - prim.GetPath().GetText()); + TF_WARN("Multiple curves in <%s>. Only reading the first one...", prim.GetPath().GetText()); } int curveIndex = 0; @@ -92,23 +86,21 @@ UsdMayaTranslatorCurves::Create( // Gather points. If timeInterval is non-empty, pick the first available // sample in the timeInterval or default. - UsdTimeCode pointsTimeSample=UsdTimeCode::EarliestTime(); + UsdTimeCode pointsTimeSample = UsdTimeCode::EarliestTime(); std::vector pointsTimeSamples; - size_t numTimeSamples = 0; + size_t numTimeSamples = 0; if (!args.GetTimeInterval().IsEmpty()) { - curves.GetPointsAttr().GetTimeSamplesInInterval( - args.GetTimeInterval(), &pointsTimeSamples); + curves.GetPointsAttr().GetTimeSamplesInInterval(args.GetTimeInterval(), &pointsTimeSamples); numTimeSamples = pointsTimeSamples.size(); - if (numTimeSamples>0) { + if (numTimeSamples > 0) { pointsTimeSample = pointsTimeSamples[0]; } } curves.GetPointsAttr().Get(&points, pointsTimeSample); - + if (points.empty()) { TF_RUNTIME_ERROR( - "points array is empty on NurbsCurves <%s>. Skipping...", - prim.GetPath().GetText()); + "points array is empty on NurbsCurves <%s>. Skipping...", prim.GetPath().GetText()); return false; // invalid nurbscurves, so exit } @@ -122,12 +114,12 @@ UsdMayaTranslatorCurves::Create( curveOrder.resize(1); UsdGeomBasisCurves basisSchema = UsdGeomBasisCurves(prim); - TfToken typeToken; + TfToken typeToken; basisSchema.GetTypeAttr().Get(&typeToken); if (typeToken == UsdGeomTokens->linear) { curveOrder[0] = 2; curveKnots.resize(points.size()); - for (size_t i=0; i < curveKnots.size(); ++i) { + for (size_t i = 0; i < curveKnots.size(); ++i) { curveKnots[i] = i; } } else { @@ -141,9 +133,9 @@ UsdMayaTranslatorCurves::Create( // Cubic curves in Maya have numSpans + 2*3 - 1, and for geometry // that came in as basis curves, we have numCV's - 3 spans. See the // MFnNurbsCurve documentation for more details. - curveKnots.resize(points.size() -3 + 5); + curveKnots.resize(points.size() - 3 + 5); int knotIdx = 0; - for (size_t i=0; i < curveKnots.size(); ++i) { + for (size_t i = 0; i < curveKnots.size(); ++i) { if (i < 3) { curveKnots[i] = 0.0; } else { @@ -151,50 +143,50 @@ UsdMayaTranslatorCurves::Create( ++knotIdx; } curveKnots[i] = double(knotIdx); - } + } } } } // == Convert data - size_t mayaNumVertices = points.size(); + size_t mayaNumVertices = points.size(); MPointArray mayaPoints(mayaNumVertices); - for (size_t i=0; i < mayaNumVertices; i++) { - mayaPoints.set( i, points[i][0], points[i][1], points[i][2] ); + for (size_t i = 0; i < mayaNumVertices; i++) { + mayaPoints.set(i, points[i][0], points[i][1], points[i][2]); } - double *knots=curveKnots.data(); - MDoubleArray mayaKnots( knots, curveKnots.size()); + double* knots = curveKnots.data(); + MDoubleArray mayaKnots(knots, curveKnots.size()); int mayaDegree = curveOrder[curveIndex] - 1; MFnNurbsCurve::Form mayaCurveForm = MFnNurbsCurve::kOpen; // HARDCODED - bool mayaCurveCreate2D = false; - bool mayaCurveCreateRational = true; + bool mayaCurveCreate2D = false; + bool mayaCurveCreateRational = true; // == Create NurbsCurve Shape Node MFnNurbsCurve curveFn; - MObject curveObj = curveFn.create(mayaPoints, - mayaKnots, - mayaDegree, - mayaCurveForm, - mayaCurveCreate2D, - mayaCurveCreateRational, - mayaNodeTransformObj, - &status - ); - if (status != MS::kSuccess) { - return false; - } - MString nodeName( prim.GetName().GetText() ); + MObject curveObj = curveFn.create( + mayaPoints, + mayaKnots, + mayaDegree, + mayaCurveForm, + mayaCurveCreate2D, + mayaCurveCreateRational, + mayaNodeTransformObj, + &status); + if (status != MS::kSuccess) { + return false; + } + MString nodeName(prim.GetName().GetText()); nodeName += "Shape"; curveFn.setName(nodeName, false, &status); - std::string nodePath( prim.GetPath().GetText() ); + std::string nodePath(prim.GetPath().GetText()); nodePath += "/"; nodePath += nodeName.asChar(); if (context) { - context->RegisterNewMayaNode( nodePath, curveObj ); // used for undo/redo + context->RegisterNewMayaNode(nodePath, curveObj); // used for undo/redo } // == Animate points == @@ -203,38 +195,37 @@ UsdMayaTranslatorCurves::Create( // if (numTimeSamples > 0) { MPointArray mayaPoints(mayaNumVertices); - MObject curveAnimObj; + MObject curveAnimObj; MFnBlendShapeDeformer blendFn; - MObject blendObj = blendFn.create(curveObj); + MObject blendObj = blendFn.create(curveObj); if (context) { - context->RegisterNewMayaNode(blendFn.name().asChar(), blendObj ); // used for undo/redo + context->RegisterNewMayaNode(blendFn.name().asChar(), blendObj); // used for undo/redo } - - for (unsigned int ti=0; ti < numTimeSamples; ++ti) { - curves.GetPointsAttr().Get(&points, pointsTimeSamples[ti]); - for (unsigned int i=0; i < mayaNumVertices; i++) { - mayaPoints.set( i, points[i][0], points[i][1], points[i][2] ); + for (unsigned int ti = 0; ti < numTimeSamples; ++ti) { + curves.GetPointsAttr().Get(&points, pointsTimeSamples[ti]); + + for (unsigned int i = 0; i < mayaNumVertices; i++) { + mayaPoints.set(i, points[i][0], points[i][1], points[i][2]); } // == Create NurbsCurve Shape Node MFnNurbsCurve curveFn; - if ( curveAnimObj.isNull() ) { - curveAnimObj = curveFn.create(mayaPoints, - mayaKnots, - mayaDegree, - mayaCurveForm, - mayaCurveCreate2D, - mayaCurveCreateRational, - mayaNodeTransformObj, - &status - ); + if (curveAnimObj.isNull()) { + curveAnimObj = curveFn.create( + mayaPoints, + mayaKnots, + mayaDegree, + mayaCurveForm, + mayaCurveCreate2D, + mayaCurveCreateRational, + mayaNodeTransformObj, + &status); if (status != MS::kSuccess) { continue; } - } - else { + } else { // Reuse the already created curve by copying it and then setting the points curveAnimObj = curveFn.copy(curveAnimObj, mayaNodeTransformObj, &status); curveFn.setCVs(mayaPoints); @@ -242,7 +233,8 @@ UsdMayaTranslatorCurves::Create( blendFn.addTarget(curveObj, ti, curveAnimObj, 1.0); curveFn.setIntermediateObject(true); if (context) { - context->RegisterNewMayaNode( curveFn.fullPathName().asChar(), curveAnimObj ); // used for undo/redo + context->RegisterNewMayaNode( + curveFn.fullPathName().asChar(), curveAnimObj); // used for undo/redo } } @@ -252,21 +244,22 @@ UsdMayaTranslatorCurves::Create( // Construct the time array to be used for all the keys MTimeArray timeArray; timeArray.setLength(numTimeSamples); - for (unsigned int ti=0; ti < numTimeSamples; ++ti) { - timeArray.set( MTime(pointsTimeSamples[ti]), ti); + for (unsigned int ti = 0; ti < numTimeSamples; ++ti) { + timeArray.set(MTime(pointsTimeSamples[ti]), ti); } // Key/Animate the weights - MPlug plgAry = blendFn.findPlug( "weight" ); - if ( !plgAry.isNull() && plgAry.isArray() ) { - for (unsigned int ti=0; ti < numTimeSamples; ++ti) { - MPlug plg = plgAry.elementByLogicalIndex(ti, &status); + MPlug plgAry = blendFn.findPlug("weight"); + if (!plgAry.isNull() && plgAry.isArray()) { + for (unsigned int ti = 0; ti < numTimeSamples; ++ti) { + MPlug plg = plgAry.elementByLogicalIndex(ti, &status); MDoubleArray valueArray(numTimeSamples, 0.0); valueArray[ti] = 1.0; // Set the time value where this curve's weight should be 1.0 MObject animObj = animFn.create(plg, nullptr, &status); animFn.addKeys(&timeArray, &valueArray); if (context) { - context->RegisterNewMayaNode(animFn.name().asChar(), animObj ); // used for undo/redo + context->RegisterNewMayaNode( + animFn.name().asChar(), animObj); // used for undo/redo } } } @@ -276,4 +269,3 @@ UsdMayaTranslatorCurves::Create( } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/translators/translatorCurves.h b/lib/mayaUsd/fileio/translators/translatorCurves.h index ea4dedbda6..8ca1a6e8f5 100644 --- a/lib/mayaUsd/fileio/translators/translatorCurves.h +++ b/lib/mayaUsd/fileio/translators/translatorCurves.h @@ -16,14 +16,14 @@ #ifndef PXRUSDMAYA_TRANSLATOR_CURVES_H #define PXRUSDMAYA_TRANSLATOR_CURVES_H -#include +#include +#include +#include #include #include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -33,10 +33,10 @@ struct UsdMayaTranslatorCurves /// \brief Creates a NurbsCurve under \p parentNode. MAYAUSD_CORE_PUBLIC static bool Create( - const UsdGeomCurves& curves, - MObject parentNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context); + const UsdGeomCurves& curves, + MObject parentNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context); }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/translators/translatorGprim.cpp b/lib/mayaUsd/fileio/translators/translatorGprim.cpp index b5b3bc0472..fd48f6b468 100644 --- a/lib/mayaUsd/fileio/translators/translatorGprim.cpp +++ b/lib/mayaUsd/fileio/translators/translatorGprim.cpp @@ -15,56 +15,50 @@ // #include "translatorGprim.h" -#include - #include +#include + PXR_NAMESPACE_OPEN_SCOPE -void -UsdMayaTranslatorGprim::Read( - const UsdGeomGprim& gprim, - MObject mayaNode, - UsdMayaPrimReaderContext* ) +void UsdMayaTranslatorGprim::Read( + const UsdGeomGprim& gprim, + MObject mayaNode, + UsdMayaPrimReaderContext*) { MFnDagNode fnGprim(mayaNode); TfToken orientation; - if (gprim.GetOrientationAttr().Get(&orientation)){ - UsdMayaUtil::setPlugValue(fnGprim, "opposite", (orientation == - UsdGeomTokens->leftHanded)); + if (gprim.GetOrientationAttr().Get(&orientation)) { + UsdMayaUtil::setPlugValue(fnGprim, "opposite", (orientation == UsdGeomTokens->leftHanded)); } bool doubleSided; - if (gprim.GetDoubleSidedAttr().Get(&doubleSided)){ + if (gprim.GetDoubleSidedAttr().Get(&doubleSided)) { UsdMayaUtil::setPlugValue(fnGprim, "doubleSided", doubleSided); } } -void -UsdMayaTranslatorGprim::Write( - const MObject& mayaNode, - const UsdGeomGprim& gprim, - UsdMayaPrimWriterContext*) +void UsdMayaTranslatorGprim::Write( + const MObject& mayaNode, + const UsdGeomGprim& gprim, + UsdMayaPrimWriterContext*) { MFnDependencyNode depFn(mayaNode); bool doubleSided = false; - if (UsdMayaUtil::getPlugValue(depFn, "doubleSided", &doubleSided)){ + if (UsdMayaUtil::getPlugValue(depFn, "doubleSided", &doubleSided)) { gprim.CreateDoubleSidedAttr(VtValue(doubleSided), true); } bool opposite = false; // Gprim properties always authored on the shape - if (UsdMayaUtil::getPlugValue(depFn, "opposite", &opposite)){ + if (UsdMayaUtil::getPlugValue(depFn, "opposite", &opposite)) { // If mesh is double sided in maya, opposite is disregarded - TfToken orientation = (opposite && !doubleSided ? UsdGeomTokens->leftHanded : - UsdGeomTokens->rightHanded); + TfToken orientation + = (opposite && !doubleSided ? UsdGeomTokens->leftHanded : UsdGeomTokens->rightHanded); gprim.CreateOrientationAttr(VtValue(orientation), true); } - } - PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/translators/translatorGprim.h b/lib/mayaUsd/fileio/translators/translatorGprim.h index a111e8ecde..3b3918148b 100644 --- a/lib/mayaUsd/fileio/translators/translatorGprim.h +++ b/lib/mayaUsd/fileio/translators/translatorGprim.h @@ -16,14 +16,14 @@ #ifndef PXRUSDMAYA_TRANSLATOR_GPRIM_H #define PXRUSDMAYA_TRANSLATOR_GPRIM_H -#include +#include +#include +#include #include #include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -31,20 +31,14 @@ PXR_NAMESPACE_OPEN_SCOPE struct UsdMayaTranslatorGprim { MAYAUSD_CORE_PUBLIC - static void Read( - const UsdGeomGprim& gprim, - MObject mayaNode, - UsdMayaPrimReaderContext* context); + static void + Read(const UsdGeomGprim& gprim, MObject mayaNode, UsdMayaPrimReaderContext* context); MAYAUSD_CORE_PUBLIC - static void Write( - const MObject& mayaNode, - const UsdGeomGprim& gprim, - UsdMayaPrimWriterContext* context); + static void + Write(const MObject& mayaNode, const UsdGeomGprim& gprim, UsdMayaPrimWriterContext* context); }; - PXR_NAMESPACE_CLOSE_SCOPE #endif - diff --git a/lib/mayaUsd/fileio/translators/translatorMaterial.cpp b/lib/mayaUsd/fileio/translators/translatorMaterial.cpp index fa76cb67cb..c185c82611 100644 --- a/lib/mayaUsd/fileio/translators/translatorMaterial.cpp +++ b/lib/mayaUsd/fileio/translators/translatorMaterial.cpp @@ -15,18 +15,12 @@ // #include "translatorMaterial.h" -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include #include @@ -42,12 +36,18 @@ #include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -89,28 +89,24 @@ MObject UsdMayaTranslatorMaterial::Read( return shadingEngine; } -static -bool -_AssignMaterialFaceSet( - const MObject& shadingEngine, - const MDagPath& shapeDagPath, - const VtIntArray& faceIndices) +static bool _AssignMaterialFaceSet( + const MObject& shadingEngine, + const MDagPath& shapeDagPath, + const VtIntArray& faceIndices) { MStatus status; // Create component object using single indexed // components, i.e. face indices. MFnSingleIndexedComponent compFn; - MObject faceComp = compFn.create(MFn::kMeshPolygonComponent, &status); + MObject faceComp = compFn.create(MFn::kMeshPolygonComponent, &status); if (!status) { TF_RUNTIME_ERROR("Failed to create face component."); return false; } MIntArray mFaces; - TF_FOR_ALL(fIdxIt, faceIndices) { - mFaces.append(*fIdxIt); - } + TF_FOR_ALL(fIdxIt, faceIndices) { mFaces.append(*fIdxIt); } compFn.addElements(mFaces); MFnSet seFnSet(shadingEngine, &status); @@ -118,8 +114,7 @@ _AssignMaterialFaceSet( status = seFnSet.addMember(shapeDagPath, faceComp); if (!status) { TF_RUNTIME_ERROR( - "Could not add component to shadingEngine %s.", - seFnSet.name().asChar()); + "Could not add component to shadingEngine %s.", seFnSet.name().asChar()); return false; } } @@ -127,17 +122,16 @@ _AssignMaterialFaceSet( return true; } -bool -UsdMayaTranslatorMaterial::AssignMaterial( - const UsdMayaJobImportArgs& jobArguments, - const UsdGeomGprim& primSchema, - MObject shapeObj, - UsdMayaPrimReaderContext* context) +bool UsdMayaTranslatorMaterial::AssignMaterial( + const UsdMayaJobImportArgs& jobArguments, + const UsdGeomGprim& primSchema, + MObject shapeObj, + UsdMayaPrimReaderContext* context) { // if we don't have a valid context, we make one temporarily. This is to // make sure we don't duplicate shading nodes within a material. UsdMayaPrimReaderContext::ObjectRegistry tmpRegistry; - UsdMayaPrimReaderContext tmpContext(&tmpRegistry); + UsdMayaPrimReaderContext tmpContext(&tmpRegistry); if (!context) { context = &tmpContext; } @@ -145,17 +139,13 @@ UsdMayaTranslatorMaterial::AssignMaterial( MDagPath shapeDagPath; MFnDagNode(shapeObj).getPath(shapeDagPath); - MStatus status; + MStatus status; const UsdShadeMaterialBindingAPI bindingAPI(primSchema.GetPrim()); - MObject shadingEngine = - UsdMayaTranslatorMaterial::Read(jobArguments, - bindingAPI.ComputeBoundMaterial(), - primSchema, - context); + MObject shadingEngine = UsdMayaTranslatorMaterial::Read( + jobArguments, bindingAPI.ComputeBoundMaterial(), primSchema, context); if (shadingEngine.isNull()) { - status = UsdMayaUtil::GetMObjectByName("initialShadingGroup", - shadingEngine); + status = UsdMayaUtil::GetMObjectByName("initialShadingGroup", shadingEngine); if (status != MS::kSuccess) { return false; } @@ -163,9 +153,8 @@ UsdMayaTranslatorMaterial::AssignMaterial( // If the gprim does not have a material faceSet which represents per-face // shader assignments, assign the shading engine to the entire gprim. - const std::vector faceSubsets = - UsdShadeMaterialBindingAPI( - primSchema.GetPrim()).GetMaterialBindSubsets(); + const std::vector faceSubsets + = UsdShadeMaterialBindingAPI(primSchema.GetPrim()).GetMaterialBindSubsets(); if (faceSubsets.empty()) { MFnSet seFnSet(shadingEngine, &status); @@ -173,8 +162,7 @@ UsdMayaTranslatorMaterial::AssignMaterial( status = seFnSet.addMember(shapeObj); if (!status) { TF_RUNTIME_ERROR( - "Could not add shadingEngine for '%s'.", - shapeDagPath.fullPathName().asChar()); + "Could not add shadingEngine for '%s'.", shapeDagPath.fullPathName().asChar()); } } @@ -183,7 +171,7 @@ UsdMayaTranslatorMaterial::AssignMaterial( if (!faceSubsets.empty()) { - int faceCount = 0; + int faceCount = 0; const UsdGeomMesh mesh(primSchema); if (mesh) { VtIntArray faceVertexCounts; @@ -193,49 +181,36 @@ UsdMayaTranslatorMaterial::AssignMaterial( if (faceCount == 0) { TF_RUNTIME_ERROR( - "Unable to get face count for gprim at path <%s>.", - primSchema.GetPath().GetText()); + "Unable to get face count for gprim at path <%s>.", primSchema.GetPath().GetText()); return false; } std::string reasonWhyNotPartition; - const bool validPartition = - UsdGeomSubset::ValidateSubsets( - faceSubsets, - faceCount, - UsdGeomTokens->partition, - &reasonWhyNotPartition); + const bool validPartition = UsdGeomSubset::ValidateSubsets( + faceSubsets, faceCount, UsdGeomTokens->partition, &reasonWhyNotPartition); if (!validPartition) { - TF_WARN("Face-subsets on <%s> don't form a valid partition: %s", - primSchema.GetPath().GetText(), - reasonWhyNotPartition.c_str()); - - VtIntArray unassignedIndices = - UsdGeomSubset::GetUnassignedIndices(faceSubsets, faceCount); - if (!_AssignMaterialFaceSet(shadingEngine, - shapeDagPath, - unassignedIndices)) { + TF_WARN( + "Face-subsets on <%s> don't form a valid partition: %s", + primSchema.GetPath().GetText(), + reasonWhyNotPartition.c_str()); + + VtIntArray unassignedIndices + = UsdGeomSubset::GetUnassignedIndices(faceSubsets, faceCount); + if (!_AssignMaterialFaceSet(shadingEngine, shapeDagPath, unassignedIndices)) { return false; } } for (const auto& subset : faceSubsets) { const UsdShadeMaterialBindingAPI subsetBindingAPI(subset.GetPrim()); - const UsdShadeMaterial boundMaterial = - subsetBindingAPI.ComputeBoundMaterial(); + const UsdShadeMaterial boundMaterial = subsetBindingAPI.ComputeBoundMaterial(); if (boundMaterial) { - MObject faceSubsetShadingEngine = - UsdMayaTranslatorMaterial::Read( - jobArguments, - boundMaterial, - UsdGeomGprim(), - context); + MObject faceSubsetShadingEngine = UsdMayaTranslatorMaterial::Read( + jobArguments, boundMaterial, UsdGeomGprim(), context); if (faceSubsetShadingEngine.isNull()) { - status = - UsdMayaUtil::GetMObjectByName( - "initialShadingGroup", - faceSubsetShadingEngine); + status = UsdMayaUtil::GetMObjectByName( + "initialShadingGroup", faceSubsetShadingEngine); if (status != MS::kSuccess) { return false; } @@ -244,12 +219,9 @@ UsdMayaTranslatorMaterial::AssignMaterial( // Only transfer the first timeSample or default indices, if // there are no time-samples. VtIntArray indices; - subset.GetIndicesAttr().Get(&indices, - UsdTimeCode::EarliestTime()); + subset.GetIndicesAttr().Get(&indices, UsdTimeCode::EarliestTime()); - if (!_AssignMaterialFaceSet(faceSubsetShadingEngine, - shapeDagPath, - indices)) { + if (!_AssignMaterialFaceSet(faceSubsetShadingEngine, shapeDagPath, indices)) { return false; } } @@ -260,26 +232,22 @@ UsdMayaTranslatorMaterial::AssignMaterial( } /* static */ -void -UsdMayaTranslatorMaterial::ExportShadingEngines( - UsdMayaWriteJobContext& writeJobContext, - const UsdMayaUtil::MDagPathMap& dagPathToUsdMap) +void UsdMayaTranslatorMaterial::ExportShadingEngines( + UsdMayaWriteJobContext& writeJobContext, + const UsdMayaUtil::MDagPathMap& dagPathToUsdMap) { const TfToken& shadingMode = writeJobContext.GetArgs().shadingMode; if (shadingMode == UsdMayaShadingModeTokens->none) { return; } - if (auto exporterCreator = - UsdMayaShadingModeRegistry::GetExporter(shadingMode)) { + if (auto exporterCreator = UsdMayaShadingModeRegistry::GetExporter(shadingMode)) { if (auto exporter = exporterCreator()) { exporter->DoExport(writeJobContext, dagPathToUsdMap); } - } - else { + } else { TF_RUNTIME_ERROR("No shadingMode '%s' found.", shadingMode.GetText()); } } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/translators/translatorMaterial.h b/lib/mayaUsd/fileio/translators/translatorMaterial.h index e107c1fa14..025f6ba099 100644 --- a/lib/mayaUsd/fileio/translators/translatorMaterial.h +++ b/lib/mayaUsd/fileio/translators/translatorMaterial.h @@ -16,18 +16,18 @@ #ifndef PXRUSDMAYA_TRANSLATOR_MATERIAL_H #define PXRUSDMAYA_TRANSLATOR_MATERIAL_H -#include +#include +#include +#include +#include -#include #include +#include #include #include #include -#include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -39,10 +39,10 @@ struct UsdMayaTranslatorMaterial /// that corresponds to \p material. MAYAUSD_CORE_PUBLIC static MObject Read( - const UsdMayaJobImportArgs& jobArguments, - const UsdShadeMaterial& material, - const UsdGeomGprim& boundPrim, - UsdMayaPrimReaderContext* context); + const UsdMayaJobImportArgs& jobArguments, + const UsdShadeMaterial& material, + const UsdGeomGprim& boundPrim, + UsdMayaPrimReaderContext* context); /// Given a \p prim, assigns a material to it according to the shading mode found in /// \p jobArguments. This will see which UsdShadeMaterial is bound to \p prim. If the material @@ -50,21 +50,19 @@ struct UsdMayaTranslatorMaterial /// assigned to \p shapeObj. MAYAUSD_CORE_PUBLIC static bool AssignMaterial( - const UsdMayaJobImportArgs& jobArguments, - const UsdGeomGprim& prim, - MObject shapeObj, - UsdMayaPrimReaderContext* context); + const UsdMayaJobImportArgs& jobArguments, + const UsdGeomGprim& prim, + MObject shapeObj, + UsdMayaPrimReaderContext* context); /// Finds shadingEngines in the Maya scene and exports them to the USD /// stage contained in \p writeJobContext. MAYAUSD_CORE_PUBLIC static void ExportShadingEngines( - UsdMayaWriteJobContext& writeJobContext, - const UsdMayaUtil::MDagPathMap& dagPathToUsdMap); + UsdMayaWriteJobContext& writeJobContext, + const UsdMayaUtil::MDagPathMap& dagPathToUsdMap); }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/translators/translatorMayaReference.cpp b/lib/mayaUsd/fileio/translators/translatorMayaReference.cpp index b099346a07..061265f118 100644 --- a/lib/mayaUsd/fileio/translators/translatorMayaReference.cpp +++ b/lib/mayaUsd/fileio/translators/translatorMayaReference.cpp @@ -31,13 +31,15 @@ // #include "translatorMayaReference.h" +#include +#include + #include #include #include #include #include #include -#include #include #include #include @@ -45,170 +47,166 @@ #include #include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE namespace { - // If the given source and destArrayPlug are already connected, returns the index they are - // connected at; otherwise, returns the lowest index in the destArray that does not already - // have a connection - MStatus connectedOrFirstAvailableIndex( - MPlug srcPlug, - MPlug destArrayPlug, - unsigned int& foundIndex, - bool& wasConnected) - { - // Want to find the lowest unconnected (as dest) open logical index... so we add to - // a list, then sort - MStatus status; - foundIndex = 0; - wasConnected = false; - unsigned int numConnected = destArrayPlug.numConnectedElements(&status); - CHECK_MSTATUS_AND_RETURN_IT(status); - if (numConnected > 0) - { - std::vector usedLogicalIndices; - usedLogicalIndices.reserve(numConnected); - MPlug elemPlug; - MPlug elemSrcPlug; - for (unsigned int connectedI = 0; connectedI < numConnected; ++connectedI) - { - elemPlug = destArrayPlug.connectionByPhysicalIndex(connectedI, &status); - CHECK_MSTATUS_AND_RETURN_IT(status); - elemSrcPlug = elemPlug.source(&status); - CHECK_MSTATUS_AND_RETURN_IT(status); - if (!elemSrcPlug.isNull()) - { - if (elemSrcPlug == srcPlug) - { - foundIndex = elemPlug.logicalIndex(); - wasConnected = true; - return status; - } - usedLogicalIndices.push_back(elemPlug.logicalIndex()); +// If the given source and destArrayPlug are already connected, returns the index they are +// connected at; otherwise, returns the lowest index in the destArray that does not already +// have a connection +MStatus connectedOrFirstAvailableIndex( + MPlug srcPlug, + MPlug destArrayPlug, + unsigned int& foundIndex, + bool& wasConnected) +{ + // Want to find the lowest unconnected (as dest) open logical index... so we add to + // a list, then sort + MStatus status; + foundIndex = 0; + wasConnected = false; + unsigned int numConnected = destArrayPlug.numConnectedElements(&status); + CHECK_MSTATUS_AND_RETURN_IT(status); + if (numConnected > 0) { + std::vector usedLogicalIndices; + usedLogicalIndices.reserve(numConnected); + MPlug elemPlug; + MPlug elemSrcPlug; + for (unsigned int connectedI = 0; connectedI < numConnected; ++connectedI) { + elemPlug = destArrayPlug.connectionByPhysicalIndex(connectedI, &status); + CHECK_MSTATUS_AND_RETURN_IT(status); + elemSrcPlug = elemPlug.source(&status); + CHECK_MSTATUS_AND_RETURN_IT(status); + if (!elemSrcPlug.isNull()) { + if (elemSrcPlug == srcPlug) { + foundIndex = elemPlug.logicalIndex(); + wasConnected = true; + return status; } + usedLogicalIndices.push_back(elemPlug.logicalIndex()); } - if (!usedLogicalIndices.empty()) - { - std::sort(usedLogicalIndices.begin(), usedLogicalIndices.end()); - // after sorting, since we assume no repeated indices, if the number of - // elements = value of last element + 1, then we know it's tightly packed... - if (usedLogicalIndices.size() - 1 == usedLogicalIndices.back()) - { - foundIndex = usedLogicalIndices.size(); - } - else - { - // If it's not tightly packed, just iterate through from start until we - // find an element whose index != it's value - for (foundIndex = 0; - foundIndex < usedLogicalIndices.size(); - ++foundIndex) - { - if (usedLogicalIndices[foundIndex] != foundIndex) break; - } + } + if (!usedLogicalIndices.empty()) { + std::sort(usedLogicalIndices.begin(), usedLogicalIndices.end()); + // after sorting, since we assume no repeated indices, if the number of + // elements = value of last element + 1, then we know it's tightly packed... + if (usedLogicalIndices.size() - 1 == usedLogicalIndices.back()) { + foundIndex = usedLogicalIndices.size(); + } else { + // If it's not tightly packed, just iterate through from start until we + // find an element whose index != it's value + for (foundIndex = 0; foundIndex < usedLogicalIndices.size(); ++foundIndex) { + if (usedLogicalIndices[foundIndex] != foundIndex) + break; } } } - return status; } + return status; +} - // Given a function set attached to a DAG node, create a string from the - // node's full path by replacing all the path dividers (|) by underscores - // and stripping off the first character so the name doesn't start with an - // underscore. (We use this for creating unique names for Maya reference - // nodes created from ALUSD proxy nodes.) - // - MString refNameFromPath(const MFnDagNode &nodeFn) - { +// Given a function set attached to a DAG node, create a string from the +// node's full path by replacing all the path dividers (|) by underscores +// and stripping off the first character so the name doesn't start with an +// underscore. (We use this for creating unique names for Maya reference +// nodes created from ALUSD proxy nodes.) +// +MString refNameFromPath(const MFnDagNode& nodeFn) +{ MString name = nodeFn.fullPathName(); name.substitute("|", "_"); name = MString(name.asChar() + 1); return name; - } +} - // Cache "associatedNode" attribute to avoid look-up cost. Since UsdMayaTranslatorMayaReference doesn't have initialization method - // we use method with static variable to defere the search when everything is initialized. - const MObject getAssociatedNodeAttr() - { +// Cache "associatedNode" attribute to avoid look-up cost. Since UsdMayaTranslatorMayaReference +// doesn't have initialization method we use method with static variable to defere the search when +// everything is initialized. +const MObject getAssociatedNodeAttr() +{ static MObject associatedNodeAttr = MNodeClass("reference").attribute("associatedNode"); return associatedNodeAttr; - } +} - // Cache "message" attribute to avoid look-up cost. Since UsdMayaTranslatorMayaReference doesn't have initialization method - // we use method with static variable to defere the search when everything is initialized. - const MObject getMessageAttr() - { +// Cache "message" attribute to avoid look-up cost. Since UsdMayaTranslatorMayaReference doesn't +// have initialization method we use method with static variable to defere the search when +// everything is initialized. +const MObject getMessageAttr() +{ static MObject messageAttr = MNodeClass("dagNode").attribute("message"); return messageAttr; - } } +} // namespace const TfToken UsdMayaTranslatorMayaReference::m_namespaceName = TfToken("mayaNamespace"); const TfToken UsdMayaTranslatorMayaReference::m_referenceName = TfToken("mayaReference"); -MStatus -UsdMayaTranslatorMayaReference::LoadMayaReference(const UsdPrim& prim, MObject& parent, MString& mayaReferencePath, MString& rigNamespaceM) +MStatus UsdMayaTranslatorMayaReference::LoadMayaReference( + const UsdPrim& prim, + MObject& parent, + MString& mayaReferencePath, + MString& rigNamespaceM) { - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::LoadMayaReference prim=%s\n", prim.GetPath().GetText()); + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg("MayaReferenceLogic::LoadMayaReference prim=%s\n", prim.GetPath().GetText()); const TfToken maya_associatedReferenceNode("maya_associatedReferenceNode"); - MStatus status; + MStatus status; MFnDagNode parentDag(parent, &status); CHECK_MSTATUS_AND_RETURN_IT(status); - // Need to create new reference (initially unloaded). - // - // When we create reference nodes, we want a separate reference node to be - // created for each proxy, even proxies that are duplicates of each other. - // This is to ensure that edits to each copy of an asset are preserved - // separately. To this end, we must create a unique name for each proxy's - // reference node. Simply including namespace information (if any) from the - // proxy node is not enough to guarantee uniqueness, since duplicates of a - // proxy node will all have the same namespace. So we also include a string - // created from the full path to the proxy in the name of the reference - // node. The resulting name may be long, but it will be unique and the user - // shouldn't be interacting directly with these nodes anyway. - // - // Note that the 'file' command will name the new reference node after the - // given namespace. However, the command doesn't seem to provide a reference - // node name override option, so we will rename the node later. - // - // (Also note that a new namespace is currently created whenever there is - // already a reference node that uses the same one. If, in the future, we - // find that reference-related workflows result in an overly large number - // of namespaces being created and/or we run into problems where Maya doesn't - // handle this number of workspaces efficiently, we might consider setting - // -mergeNamespacesOnClash to true.) - // + // Need to create new reference (initially unloaded). + // + // When we create reference nodes, we want a separate reference node to be + // created for each proxy, even proxies that are duplicates of each other. + // This is to ensure that edits to each copy of an asset are preserved + // separately. To this end, we must create a unique name for each proxy's + // reference node. Simply including namespace information (if any) from the + // proxy node is not enough to guarantee uniqueness, since duplicates of a + // proxy node will all have the same namespace. So we also include a string + // created from the full path to the proxy in the name of the reference + // node. The resulting name may be long, but it will be unique and the user + // shouldn't be interacting directly with these nodes anyway. + // + // Note that the 'file' command will name the new reference node after the + // given namespace. However, the command doesn't seem to provide a reference + // node name override option, so we will rename the node later. + // + // (Also note that a new namespace is currently created whenever there is + // already a reference node that uses the same one. If, in the future, we + // find that reference-related workflows result in an overly large number + // of namespaces being created and/or we run into problems where Maya doesn't + // handle this number of workspaces efficiently, we might consider setting + // -mergeNamespacesOnClash to true.) + // MStringArray createdNodes; - MString referenceCommand = MString("file" - " -reference" - " -returnNewNodes" - " -deferReference true" - " -mergeNamespacesOnClash false" - " -ignoreVersion" - " -options \"v=0;\"" - " -namespace \"") + rigNamespaceM + - "\" \"" + mayaReferencePath + "\""; - - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::LoadMayaReference prim=%s execute \"%s\"\n", - prim.GetPath().GetText(), - referenceCommand.asChar()); + MString referenceCommand = MString("file" + " -reference" + " -returnNewNodes" + " -deferReference true" + " -mergeNamespacesOnClash false" + " -ignoreVersion" + " -options \"v=0;\"" + " -namespace \"") + + rigNamespaceM + "\" \"" + mayaReferencePath + "\""; + + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg( + "MayaReferenceLogic::LoadMayaReference prim=%s execute \"%s\"\n", + prim.GetPath().GetText(), + referenceCommand.asChar()); status = MGlobal::executeCommand(referenceCommand, createdNodes); CHECK_MSTATUS_AND_RETURN_IT(status); - if (createdNodes.length() != 1) - { - MGlobal::displayError(MString("Expected to exactly 1 node result from reference command: ") + referenceCommand); + if (createdNodes.length() != 1) { + MGlobal::displayError( + MString("Expected to exactly 1 node result from reference command: ") + + referenceCommand); return MS::kFailure; } // Retrieve created reference node - MObject referenceObject; - MString refNode = createdNodes[0]; + MObject referenceObject; + MString refNode = createdNodes[0]; MSelectionList selectionList; selectionList.add(refNode); selectionList.getDependNode(0, referenceObject); @@ -218,21 +216,21 @@ UsdMayaTranslatorMayaReference::LoadMayaReference(const UsdPrim& prim, MObject& MFnReference refDependNode(referenceObject); connectReferenceAssociatedNode(parentDag, refDependNode); - // Rename the reference node. We want a unique name so that multiple copies - // of a given prim can each have their own reference edits. We make a name - // from the full path to the prim for which the reference is being created - // (and append "_RN" to the end, to indicate it's a reference node, just - // because). - // - MString uniqueRefNodeName = refNameFromPath(parentDag) + "_RN"; - refDependNode.setName(uniqueRefNodeName); + // Rename the reference node. We want a unique name so that multiple copies + // of a given prim can each have their own reference edits. We make a name + // from the full path to the prim for which the reference is being created + // (and append "_RN" to the end, to indicate it's a reference node, just + // because). + // + MString uniqueRefNodeName = refNameFromPath(parentDag) + "_RN"; + refDependNode.setName(uniqueRefNodeName); // Now load the reference to properly trigger the kAfterReferenceLoad callback MFileIO::loadReferenceByNode(referenceObject, &status); CHECK_MSTATUS_AND_RETURN_IT(status); { - // To avoid the error that USD complains about editing to same layer simultaneously from different threads, - // we record it as custom data instead of creating an attribute. + // To avoid the error that USD complains about editing to same layer simultaneously from + // different threads, we record it as custom data instead of creating an attribute. MString refDependNodeName = refDependNode.name(); VtValue value(std::string(refDependNodeName.asChar(), refDependNodeName.length())); prim.SetCustomDataByKey(maya_associatedReferenceNode, value); @@ -241,26 +239,22 @@ UsdMayaTranslatorMayaReference::LoadMayaReference(const UsdPrim& prim, MObject& return MS::kSuccess; } -MStatus -UsdMayaTranslatorMayaReference::UnloadMayaReference(const MObject& parent){ +MStatus UsdMayaTranslatorMayaReference::UnloadMayaReference(const MObject& parent) +{ TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::UnloadMayaReference\n"); - MStatus status; + MStatus status; MFnDependencyNode fnParent(parent, &status); - if (status) - { + if (status) { MPlug messagePlug(fnParent.object(), getMessageAttr()); - if (status) - { + if (status) { MPlugArray referencePlugs; messagePlug.connectedTo(referencePlugs, false, true); // Unload the connected references. auto referencePlugsLength = referencePlugs.length(); - for (uint32_t i = 0; i < referencePlugsLength; ++i) - { + for (uint32_t i = 0; i < referencePlugsLength; ++i) { MObject temp = referencePlugs[i].node(); - if (temp.hasFn(MFn::kReference)) - { + if (temp.hasFn(MFn::kReference)) { MFileIO::unloadReferenceByNode(temp, &status); CHECK_MSTATUS_AND_RETURN_IT(status); } @@ -270,8 +264,9 @@ UsdMayaTranslatorMayaReference::UnloadMayaReference(const MObject& parent){ return status; } -MStatus -UsdMayaTranslatorMayaReference::connectReferenceAssociatedNode(MFnDagNode& dagNode, MFnReference& refNode) +MStatus UsdMayaTranslatorMayaReference::connectReferenceAssociatedNode( + MFnDagNode& dagNode, + MFnReference& refNode) { MPlug srcPlug(dagNode.object(), getMessageAttr()); /* @@ -282,22 +277,20 @@ UsdMayaTranslatorMayaReference::connectReferenceAssociatedNode(MFnDagNode& dagNo > lifespan as the reference, and will be deleted along with the reference > if it is removed. */ - MStatus result; - MPlug destArrayPlug(refNode.object(), getAssociatedNodeAttr()); - bool wasConnected = false; + MStatus result; + MPlug destArrayPlug(refNode.object(), getAssociatedNodeAttr()); + bool wasConnected = false; unsigned int destIndex = 0; result = connectedOrFirstAvailableIndex(srcPlug, destArrayPlug, destIndex, wasConnected); CHECK_MSTATUS_AND_RETURN_IT(result); - if (wasConnected) - { + if (wasConnected) { // If it's already connected, abort, we're done return result; } MPlug destPlug = destArrayPlug.elementByLogicalIndex(destIndex); result = MS::kFailure; - if (!srcPlug.isNull() && !destPlug.isNull()) - { + if (!srcPlug.isNull() && !destPlug.isNull()) { MDGModifier dgMod; result = dgMod.connect(srcPlug, destPlug); CHECK_MSTATUS_AND_RETURN_IT(result); @@ -306,10 +299,9 @@ UsdMayaTranslatorMayaReference::connectReferenceAssociatedNode(MFnDagNode& dagNo return result; } -MStatus -UsdMayaTranslatorMayaReference::update(const UsdPrim& prim, MObject parent) +MStatus UsdMayaTranslatorMayaReference::update(const UsdPrim& prim, MObject parent) { - MStatus status; + MStatus status; SdfAssetPath mayaReferenceAssetPath; // Check to see if we have a valid Maya reference attribute UsdAttribute mayaReferenceAttribute = prim.GetAttribute(m_referenceName); @@ -317,179 +309,191 @@ UsdMayaTranslatorMayaReference::update(const UsdPrim& prim, MObject parent) MString mayaReferencePath(mayaReferenceAssetPath.GetResolvedPath().c_str()); // The resolved path is empty if the maya reference is a full path. - if (!mayaReferencePath.length()) - { + if (!mayaReferencePath.length()) { mayaReferencePath = mayaReferenceAssetPath.GetAssetPath().c_str(); } // If the path is still empty return, there is no reference to import - if (!mayaReferencePath.length()) - { + if (!mayaReferencePath.length()) { return MS::kFailure; } - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::update Looking for attribute on \"%s\".\"%s\"\n", prim.GetTypeName().GetText(), m_namespaceName.GetText()); + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg( + "MayaReferenceLogic::update Looking for attribute on \"%s\".\"%s\"\n", + prim.GetTypeName().GetText(), + m_namespaceName.GetText()); // Get required namespace attribute from prim std::string rigNamespace; - if (UsdAttribute rigNamespaceAttribute = prim.GetAttribute(m_namespaceName)) - { - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::update Checking namespace on prim \"%s\".\n", prim.GetPath().GetText()); - - if (!rigNamespaceAttribute.Get(&rigNamespace)) - { - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::update Missing namespace on prim \"%s\". Will create one from prim path.\n", prim.GetPath().GetText()); + if (UsdAttribute rigNamespaceAttribute = prim.GetAttribute(m_namespaceName)) { + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg( + "MayaReferenceLogic::update Checking namespace on prim \"%s\".\n", + prim.GetPath().GetText()); + + if (!rigNamespaceAttribute.Get(&rigNamespace)) { + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg( + "MayaReferenceLogic::update Missing namespace on prim \"%s\". Will create one " + "from prim path.\n", + prim.GetPath().GetText()); // Creating default namespace from prim path. Converts /a/b/c to a_b_c. rigNamespace = prim.GetPath().GetString(); std::replace(rigNamespace.begin() + 1, rigNamespace.end(), '/', '_'); } } - MFnDagNode parentDag(parent, &status); + MFnDagNode parentDag(parent, &status); CHECK_MSTATUS_AND_RETURN_IT(status); - MString rigNamespaceM(rigNamespace.c_str(), rigNamespace.size()); - - MObject refNode; - - // First, see if a reference is already attached - MFnDependencyNode fnParent(parent, &status); - if(status) - { - MPlug messagePlug(fnParent.object(), getMessageAttr()); - MPlugArray referencePlugs; - messagePlug.connectedTo(referencePlugs, false, true); - for (uint32_t i = 0, n = referencePlugs.length(); i < n; ++i) { - MObject temp = referencePlugs[i].node(); - if (temp.hasFn(MFn::kReference)) { - refNode = temp; - } + MString rigNamespaceM(rigNamespace.c_str(), rigNamespace.size()); + + MObject refNode; + + // First, see if a reference is already attached + MFnDependencyNode fnParent(parent, &status); + if (status) { + MPlug messagePlug(fnParent.object(), getMessageAttr()); + MPlugArray referencePlugs; + messagePlug.connectedTo(referencePlugs, false, true); + for (uint32_t i = 0, n = referencePlugs.length(); i < n; ++i) { + MObject temp = referencePlugs[i].node(); + if (temp.hasFn(MFn::kReference)) { + refNode = temp; + } + } } - } - - // Check to see whether we have previously created a reference node for this - // prim. If so, we can just reuse it. - // - // The check is based on comparing the prim's full path and the name of the - // reference node, which we had originally created from the prim's full - // path. (Because of this, if the name or parentage of the prim has changed - // since we created the reference, we won't find the old reference node. - // The old one will be left orphaned, a new one will be created, and we will - // lose any reference edits we had made. Ideally, this won't happen often. - // To prevent the problem, we could store the name of the reference node in - // an attribute on the prim node. The reference node would never be renamed - // by the user, since it's locked. If the user were to rename the prim - // node, we could update the reference node's name too, for consistency, - // when the two nodes got reattached. Not doing this currently, but can - // revisit if renaming/reparenting of prims with reference nodes turns out - // to be a common thing in the workflow.) - // - if(refNode.isNull()) - { - for (MItDependencyNodes refIter(MFn::kReference); !refIter.isDone(); refIter.next()) { - MObject tempRefNode = refIter.item(); - MFnReference tempRefFn(tempRefNode); - if (!tempRefFn.isFromReferencedFile()) { - - // Get the name of the reference node so we can check if this node - // matches the prim we are processing. Strip off the "_RN" suffix. - // - MString refNodeName = tempRefFn.name(); - MString refName(refNodeName.asChar(), refNodeName.numChars()-3); - - // What reference node name is the prim expecting? - MString expectedRefName = refNameFromPath(parentDag); - - // If found a match, reconnect the reference node's `associatedNode` - // attr before loading it, since the previous connection may be gone. - // - if (refName == expectedRefName) { - // Reconnect the reference node's `associatedNode` attr before - // loading it, since the previous connection may be gone. - connectReferenceAssociatedNode(parentDag, tempRefFn); - refNode = tempRefNode; - break; + + // Check to see whether we have previously created a reference node for this + // prim. If so, we can just reuse it. + // + // The check is based on comparing the prim's full path and the name of the + // reference node, which we had originally created from the prim's full + // path. (Because of this, if the name or parentage of the prim has changed + // since we created the reference, we won't find the old reference node. + // The old one will be left orphaned, a new one will be created, and we will + // lose any reference edits we had made. Ideally, this won't happen often. + // To prevent the problem, we could store the name of the reference node in + // an attribute on the prim node. The reference node would never be renamed + // by the user, since it's locked. If the user were to rename the prim + // node, we could update the reference node's name too, for consistency, + // when the two nodes got reattached. Not doing this currently, but can + // revisit if renaming/reparenting of prims with reference nodes turns out + // to be a common thing in the workflow.) + // + if (refNode.isNull()) { + for (MItDependencyNodes refIter(MFn::kReference); !refIter.isDone(); refIter.next()) { + MObject tempRefNode = refIter.item(); + MFnReference tempRefFn(tempRefNode); + if (!tempRefFn.isFromReferencedFile()) { + + // Get the name of the reference node so we can check if this node + // matches the prim we are processing. Strip off the "_RN" suffix. + // + MString refNodeName = tempRefFn.name(); + MString refName(refNodeName.asChar(), refNodeName.numChars() - 3); + + // What reference node name is the prim expecting? + MString expectedRefName = refNameFromPath(parentDag); + + // If found a match, reconnect the reference node's `associatedNode` + // attr before loading it, since the previous connection may be gone. + // + if (refName == expectedRefName) { + // Reconnect the reference node's `associatedNode` attr before + // loading it, since the previous connection may be gone. + connectReferenceAssociatedNode(parentDag, tempRefFn); + refNode = tempRefNode; + break; + } + } } - } } - } // If no reference found, we'll need to create it. This may be the first time we are // bring in the reference or it may have been imported or removed directly in maya. - if (refNode.isNull()) - { + if (refNode.isNull()) { return LoadMayaReference(prim, parent, mayaReferencePath, rigNamespaceM); } - if (status) - { - MString command, filepath; + if (status) { + MString command, filepath; MFnReference fnReference(refNode); command = MString("referenceQuery -f -withoutCopyNumber \"") + fnReference.name() + "\""; MGlobal::executeCommand(command, filepath); - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::update referenceNode=%s prim=%s execute \"%s\"=%s\n", - fnReference.absoluteName().asChar(), - prim.GetPath().GetText(), - command.asChar(), - filepath.asChar()); - - if (prim.IsActive()) - { - if (mayaReferencePath.length() != 0 && filepath != mayaReferencePath) - { + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg( + "MayaReferenceLogic::update referenceNode=%s prim=%s execute \"%s\"=%s\n", + fnReference.absoluteName().asChar(), + prim.GetPath().GetText(), + command.asChar(), + filepath.asChar()); + + if (prim.IsActive()) { + if (mayaReferencePath.length() != 0 && filepath != mayaReferencePath) { command = "file -loadReference \""; command += fnReference.name(); command += "\" \""; command += mayaReferencePath; command += "\""; - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::update prim=%s execute %s\n", - prim.GetPath().GetText(), - command.asChar()); + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg( + "MayaReferenceLogic::update prim=%s execute %s\n", + prim.GetPath().GetText(), + command.asChar()); status = MGlobal::executeCommand(command); CHECK_MSTATUS_AND_RETURN_IT(status); - } - else - { + } else { // Check to see if reference is already loaded - if so, don't need to do anything! - if (fnReference.isLoaded()) - { - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::update prim=%s already loaded with correct path\n", prim.GetPath().GetText()); - } - else - { - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::update prim=%s loadReferenceByNode\n", prim.GetPath().GetText()); + if (fnReference.isLoaded()) { + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg( + "MayaReferenceLogic::update prim=%s already loaded with correct path\n", + prim.GetPath().GetText()); + } else { + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg( + "MayaReferenceLogic::update prim=%s loadReferenceByNode\n", + prim.GetPath().GetText()); MString s = MFileIO::loadReferenceByNode(refNode, &status); } - if (!rigNamespace.empty()) - { + if (!rigNamespace.empty()) { // check to see if the namespace has changed MString refNamespace = fnReference.associatedNamespace(true); - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::update prim=%s, namespace was: %s\n", - prim.GetPath().GetText(), - refNamespace.asChar()); - if (refNamespace != rigNamespace.c_str()) - { + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg( + "MayaReferenceLogic::update prim=%s, namespace was: %s\n", + prim.GetPath().GetText(), + refNamespace.asChar()); + if (refNamespace != rigNamespace.c_str()) { command = "file -e -ns \""; command += rigNamespace.c_str(); command += "\" \""; command += filepath; command += "\""; - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::update prim=%s execute %s\n", - prim.GetPath().GetText(), - command.asChar()); - if (!MGlobal::executeCommand(command)) - { - MGlobal::displayError(MString("Failed to update reference with new namespace. refNS:" + refNamespace + "rigNs: " + rigNamespace.c_str() + ": ") + mayaReferencePath); + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg( + "MayaReferenceLogic::update prim=%s execute %s\n", + prim.GetPath().GetText(), + command.asChar()); + if (!MGlobal::executeCommand(command)) { + MGlobal::displayError( + MString( + "Failed to update reference with new namespace. refNS:" + + refNamespace + "rigNs: " + rigNamespace.c_str() + ": ") + + mayaReferencePath); } } } } - } - else - { + } else { // Can unconditionally unload, as unloading an already unloaded reference // won't do anything, and won't error - TF_DEBUG(PXRUSDMAYA_TRANSLATORS).Msg("MayaReferenceLogic::update prim=%s unloadReferenceByNode\n", prim.GetPath().GetText()); + TF_DEBUG(PXRUSDMAYA_TRANSLATORS) + .Msg( + "MayaReferenceLogic::update prim=%s unloadReferenceByNode\n", + prim.GetPath().GetText()); MString s = MFileIO::unloadReferenceByNode(refNode, &status); } } @@ -497,4 +501,3 @@ UsdMayaTranslatorMayaReference::update(const UsdPrim& prim, MObject parent) } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/translators/translatorMayaReference.h b/lib/mayaUsd/fileio/translators/translatorMayaReference.h index 5de0e7d0ec..a1427a9735 100644 --- a/lib/mayaUsd/fileio/translators/translatorMayaReference.h +++ b/lib/mayaUsd/fileio/translators/translatorMayaReference.h @@ -32,15 +32,15 @@ #ifndef PXRUSDMAYA_TRANSLATOR_GPRIM_H #define PXRUSDMAYA_TRANSLATOR_GPRIM_H -#include -#include +#include +#include +#include #include #include -#include -#include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -48,11 +48,15 @@ PXR_NAMESPACE_OPEN_SCOPE struct UsdMayaTranslatorMayaReference { MAYAUSD_CORE_PUBLIC - static MStatus LoadMayaReference(const UsdPrim& prim, MObject& parent, MString& mayaReferencePath, MString& rigNamespaceM); - + static MStatus LoadMayaReference( + const UsdPrim& prim, + MObject& parent, + MString& mayaReferencePath, + MString& rigNamespaceM); + MAYAUSD_CORE_PUBLIC static MStatus UnloadMayaReference(const MObject& parent); - + MAYAUSD_CORE_PUBLIC static MStatus update(const UsdPrim& prim, MObject parent); @@ -66,4 +70,3 @@ struct UsdMayaTranslatorMayaReference PXR_NAMESPACE_CLOSE_SCOPE #endif - diff --git a/lib/mayaUsd/fileio/translators/translatorMesh.cpp b/lib/mayaUsd/fileio/translators/translatorMesh.cpp index 38dd266ffb..f7a380043e 100644 --- a/lib/mayaUsd/fileio/translators/translatorMesh.cpp +++ b/lib/mayaUsd/fileio/translators/translatorMesh.cpp @@ -15,8 +15,12 @@ // #include "translatorMesh.h" -#include -#include +#include +#include +#include +#include +#include +#include #include #include @@ -38,26 +42,23 @@ #include #include -#include -#include -#include -#include -#include -#include +#include +#include namespace MAYAUSD_NS_DEF { -TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, - const UsdPrim& prim, - const MObject& transformObj, - const MObject& stageNode, - const GfInterval& frameRange, - bool wantCacheAnimation, - MStatus * status) +TranslatorMeshRead::TranslatorMeshRead( + const UsdGeomMesh& mesh, + const UsdPrim& prim, + const MObject& transformObj, + const MObject& stageNode, + const GfInterval& frameRange, + bool wantCacheAnimation, + MStatus* status) : m_wantCacheAnimation(wantCacheAnimation) , m_pointsNumTimeSamples(0u) { - MStatus stat{MS::kSuccess}; + MStatus stat { MS::kSuccess }; // ============================================== // construct a Maya mesh @@ -66,27 +67,27 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, VtIntArray faceVertexIndices; const UsdAttribute fvc = mesh.GetFaceVertexCountsAttr(); - if (fvc.ValueMightBeTimeVarying()){ + if (fvc.ValueMightBeTimeVarying()) { // at some point, it would be great, instead of failing, to create a usd/hydra proxy node // for the mesh, perhaps? For now, better to give a more specific error TF_RUNTIME_ERROR( - "<%s> is a topologically varying Mesh (has animated " - "faceVertexCounts), which isn't currently supported. " - "Skipping...", - prim.GetPath().GetText()); + "<%s> is a topologically varying Mesh (has animated " + "faceVertexCounts), which isn't currently supported. " + "Skipping...", + prim.GetPath().GetText()); } else { fvc.Get(&faceVertexCounts, UsdTimeCode::EarliestTime()); } const UsdAttribute fvi = mesh.GetFaceVertexIndicesAttr(); - if (fvi.ValueMightBeTimeVarying()){ + if (fvi.ValueMightBeTimeVarying()) { // at some point, it would be great, instead of failing, to create a usd/hydra proxy node // for the mesh, perhaps? For now, better to give a more specific error TF_RUNTIME_ERROR( - "<%s> is a topologically varying Mesh (has animated " - "faceVertexIndices), which isn't currently supported. " - "Skipping...", - prim.GetPath().GetText()); + "<%s> is a topologically varying Mesh (has animated " + "faceVertexIndices), which isn't currently supported. " + "Skipping...", + prim.GetPath().GetText()); } else { fvi.Get(&faceVertexIndices, UsdTimeCode::EarliestTime()); } @@ -94,32 +95,31 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, // Sanity Checks. If the vertex arrays are empty, skip this mesh if (faceVertexCounts.empty() || faceVertexIndices.empty()) { TF_RUNTIME_ERROR( - "faceVertexCounts or faceVertexIndices array is empty " - "[count: %zu, indices:%zu] on Mesh <%s>. Skipping...", - faceVertexCounts.size(), faceVertexIndices.size(), - prim.GetPath().GetText()); + "faceVertexCounts or faceVertexIndices array is empty " + "[count: %zu, indices:%zu] on Mesh <%s>. Skipping...", + faceVertexCounts.size(), + faceVertexIndices.size(), + prim.GetPath().GetText()); } // Gather points and normals // If timeInterval is non-empty, pick the first available sample in the // timeInterval or default. - VtVec3fArray points; - VtVec3fArray normals; - UsdTimeCode pointsTimeSample = UsdTimeCode::EarliestTime(); - UsdTimeCode normalsTimeSample = UsdTimeCode::EarliestTime(); + VtVec3fArray points; + VtVec3fArray normals; + UsdTimeCode pointsTimeSample = UsdTimeCode::EarliestTime(); + UsdTimeCode normalsTimeSample = UsdTimeCode::EarliestTime(); std::vector pointsTimeSamples; if (!frameRange.IsEmpty()) { - mesh.GetPointsAttr().GetTimeSamplesInInterval(frameRange, - &pointsTimeSamples); + mesh.GetPointsAttr().GetTimeSamplesInInterval(frameRange, &pointsTimeSamples); if (!pointsTimeSamples.empty()) { m_pointsNumTimeSamples = pointsTimeSamples.size(); pointsTimeSample = pointsTimeSamples.front(); } std::vector normalsTimeSamples; - mesh.GetNormalsAttr().GetTimeSamplesInInterval(frameRange, - &normalsTimeSamples); + mesh.GetNormalsAttr().GetTimeSamplesInInterval(frameRange, &normalsTimeSamples); if (!normalsTimeSamples.empty()) { normalsTimeSample = normalsTimeSamples.front(); } @@ -129,24 +129,24 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, mesh.GetNormalsAttr().Get(&normals, normalsTimeSample); if (points.empty()) { - TF_RUNTIME_ERROR("points array is empty on Mesh <%s>. Skipping...", - prim.GetPath().GetText()); + TF_RUNTIME_ERROR( + "points array is empty on Mesh <%s>. Skipping...", prim.GetPath().GetText()); } std::string reason; - if (!UsdGeomMesh::ValidateTopology(faceVertexIndices, - faceVertexCounts, - points.size(), - &reason)) { - TF_RUNTIME_ERROR("Skipping Mesh <%s> with invalid topology: %s", - prim.GetPath().GetText(), reason.c_str()); + if (!UsdGeomMesh::ValidateTopology( + faceVertexIndices, faceVertexCounts, points.size(), &reason)) { + TF_RUNTIME_ERROR( + "Skipping Mesh <%s> with invalid topology: %s", + prim.GetPath().GetText(), + reason.c_str()); *status = MS::kFailure; return; } // == Convert data to Maya ( vertices, faces, indices ) const size_t mayaNumVertices = points.size(); - MPointArray mayaPoints(mayaNumVertices); + MPointArray mayaPoints(mayaNumVertices); for (size_t i = 0u; i < mayaNumVertices; ++i) { mayaPoints.set(i, points[i][0], points[i][1], points[i][2]); } @@ -156,13 +156,14 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, // == Create Mesh Shape Node MFnMesh meshFn; - m_meshObj = meshFn.create( mayaPoints.length(), - polygonCounts.length(), - mayaPoints, - polygonCounts, - polygonConnects, - transformObj, - &stat); + m_meshObj = meshFn.create( + mayaPoints.length(), + polygonCounts.length(), + mayaPoints, + polygonCounts, + polygonConnects, + transformObj, + &stat); if (!stat) { *status = stat; @@ -171,12 +172,12 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, // set mesh name const auto& primName = prim.GetName().GetString(); - const auto shapeName = TfStringPrintf("%sShape", primName.c_str()); + const auto shapeName = TfStringPrintf("%sShape", primName.c_str()); meshFn.setName(MString(shapeName.c_str()), false, &stat); if (!stat) { - *status = stat; - return; + *status = stat; + return; } // store the path @@ -194,28 +195,23 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, if (normalsFaceIds.length() == static_cast(meshFn.numFaceVertices())) { MVectorArray mayaNormals(normals.size()); for (size_t i = 0u; i < normals.size(); ++i) { - mayaNormals.set(MVector(normals[i][0u], - normals[i][1u], - normals[i][2u]),i); + mayaNormals.set(MVector(normals[i][0u], normals[i][1u], normals[i][2u]), i); } - meshFn.setFaceVertexNormals(mayaNormals, - normalsFaceIds, - polygonConnects); + meshFn.setFaceVertexNormals(mayaNormals, normalsFaceIds, polygonConnects); } - } + } // If we are dealing with polys, check if there are normals and set the // internal emit-normals tag so that the normals will round-trip. // If we are dealing with a subdiv, read additional subdiv tags. TfToken subdScheme; if (mesh.GetSubdivisionSchemeAttr().Get(&subdScheme) && subdScheme == UsdGeomTokens->none) { - if (normals.size() == static_cast(meshFn.numFaceVertices()) && - mesh.GetNormalsInterpolation() == UsdGeomTokens->faceVarying) { - UsdMayaMeshReadUtils::setEmitNormalsTag(meshFn, true); - } - } - else { + if (normals.size() == static_cast(meshFn.numFaceVertices()) + && mesh.GetNormalsInterpolation() == UsdGeomTokens->faceVarying) { + UsdMayaMeshReadUtils::setEmitNormalsTag(meshFn, true); + } + } else { stat = UsdMayaMeshReadUtils::assignSubDivTagsToMesh(mesh, m_meshObj, meshFn); } @@ -223,11 +219,9 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, UsdMayaReadUtil::ReadSchemaAttributesFromPrim( prim, meshFn.object(), - { - UsdGeomTokens->subdivisionScheme, - UsdGeomTokens->interpolateBoundary, - UsdGeomTokens->faceVaryingLinearInterpolation - }); + { UsdGeomTokens->subdivisionScheme, + UsdGeomTokens->interpolateBoundary, + UsdGeomTokens->faceVaryingLinearInterpolation }); // ================================================== // construct blendshape object, PointBasedDeformer @@ -245,7 +239,7 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, // Use blendShapeDeformer so that all the points for a frame are contained in a single node. MPointArray mayaAnimPoints(mayaNumVertices); - MObject meshAnimObj; + MObject meshAnimObj; MFnBlendShapeDeformer blendFn; m_meshBlendObj = blendFn.create(m_meshObj); @@ -260,19 +254,19 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, // == Create Mesh Shape Node MFnMesh meshFn; if (meshAnimObj.isNull()) { - meshAnimObj = meshFn.create(mayaAnimPoints.length(), - polygonCounts.length(), - mayaAnimPoints, - polygonCounts, - polygonConnects, - transformObj, - &stat); + meshAnimObj = meshFn.create( + mayaAnimPoints.length(), + polygonCounts.length(), + mayaAnimPoints, + polygonCounts, + polygonConnects, + transformObj, + &stat); if (!stat) { continue; } - } - else { + } else { // Reuse the already created mesh by copying it and then setting the points meshAnimObj = meshFn.copy(meshAnimObj, transformObj, &stat); meshFn.setPoints(mayaAnimPoints); @@ -280,21 +274,18 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, // Set normals if supplied // - // NOTE: This normal information is not propagated through the blendShapes, only the controlPoints. + // NOTE: This normal information is not propagated through the blendShapes, only the + // controlPoints. // mesh.GetNormalsAttr().Get(&normals, pointsTimeSamples[ti]); - if (normals.size() == static_cast(meshFn.numFaceVertices()) && - normalsFaceIds.length() == static_cast(meshFn.numFaceVertices())) { + if (normals.size() == static_cast(meshFn.numFaceVertices()) + && normalsFaceIds.length() == static_cast(meshFn.numFaceVertices())) { MVectorArray mayaNormals(normals.size()); for (size_t i = 0; i < normals.size(); ++i) { - mayaNormals.set(MVector(normals[i][0u], - normals[i][1u], - normals[i][2u]),i); + mayaNormals.set(MVector(normals[i][0u], normals[i][1u], normals[i][2u]), i); } - meshFn.setFaceVertexNormals(mayaNormals, - normalsFaceIds, - polygonConnects); + meshFn.setFaceVertexNormals(mayaNormals, normalsFaceIds, polygonConnects); } // Add as target and set as an intermediate object. We do *not* @@ -318,7 +309,7 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, MPlug plgAry = blendFn.findPlug("weight"); if (!plgAry.isNull() && plgAry.isArray()) { for (unsigned int ti = 0u; ti < m_pointsNumTimeSamples; ++ti) { - MPlug plg = plgAry.elementByLogicalIndex(ti, &stat); + MPlug plg = plgAry.elementByLogicalIndex(ti, &stat); MDoubleArray valueArray(m_pointsNumTimeSamples, 0.0); valueArray[ti] = 1.0; // Set the time value where this mesh's weight should be 1.0 MObject animObj = animFn.create(plg, nullptr, &stat); @@ -332,10 +323,12 @@ TranslatorMeshRead::TranslatorMeshRead(const UsdGeomMesh& mesh, *status = stat; } -MStatus -TranslatorMeshRead::setPointBasedDeformerForMayaNode(const MObject& mayaObj, const MObject& stageNode, const UsdPrim& prim) +MStatus TranslatorMeshRead::setPointBasedDeformerForMayaNode( + const MObject& mayaObj, + const MObject& stageNode, + const UsdPrim& prim) { - MStatus status{MS::kSuccess}; + MStatus status { MS::kSuccess }; // Get the output time plug and node for Maya's global time object. MPlug timePlug = UsdMayaUtil::GetMayaTimePlug(); @@ -352,23 +345,21 @@ TranslatorMeshRead::setPointBasedDeformerForMayaNode(const MObject& mayaObj, con CHECK_MSTATUS(status); // Create the point based deformer node for this prim. - const std::string pointBasedDeformerNodeName = - TfStringPrintf("usdPointBasedDeformerNode%s", - TfStringReplace(prim.GetPath().GetString(), - SdfPathTokens->childDelimiter.GetString(), - "_").c_str()); + const std::string pointBasedDeformerNodeName = TfStringPrintf( + "usdPointBasedDeformerNode%s", + TfStringReplace(prim.GetPath().GetString(), SdfPathTokens->childDelimiter.GetString(), "_") + .c_str()); const std::string deformerCmd = TfStringPrintf( "from maya import cmds; cmds.deformer(name=\'%s\', type=\'%s\')[0]", pointBasedDeformerNodeName.c_str(), UsdMayaPointBasedDeformerNodeTokens->MayaTypeName.GetText()); - status = MGlobal::executePythonCommand(deformerCmd.c_str(), - m_newPointBasedDeformerName); + status = MGlobal::executePythonCommand(deformerCmd.c_str(), m_newPointBasedDeformerName); CHECK_MSTATUS(status); // Get the newly created point based deformer node. - status = UsdMayaUtil::GetMObjectByName(m_newPointBasedDeformerName.asChar(), - m_pointBasedDeformerNode); + status = UsdMayaUtil::GetMObjectByName( + m_newPointBasedDeformerName.asChar(), m_pointBasedDeformerNode); CHECK_MSTATUS(status); MFnDependencyNode depNodeFn(m_pointBasedDeformerNode, &status); @@ -377,27 +368,27 @@ TranslatorMeshRead::setPointBasedDeformerForMayaNode(const MObject& mayaObj, con MDGModifier dgMod; // Set the prim path on the deformer node. - MPlug primPathPlug = - depNodeFn.findPlug(UsdMayaPointBasedDeformerNode::primPathAttr, - true, - &status); + MPlug primPathPlug + = depNodeFn.findPlug(UsdMayaPointBasedDeformerNode::primPathAttr, true, &status); CHECK_MSTATUS(status); status = dgMod.newPlugValueString(primPathPlug, prim.GetPath().GetText()); CHECK_MSTATUS(status); // Connect the stage node's stage output to the deformer node. - status = dgMod.connect(stageNode, - UsdMayaStageNode::outUsdStageAttr, - m_pointBasedDeformerNode, - UsdMayaPointBasedDeformerNode::inUsdStageAttr); + status = dgMod.connect( + stageNode, + UsdMayaStageNode::outUsdStageAttr, + m_pointBasedDeformerNode, + UsdMayaPointBasedDeformerNode::inUsdStageAttr); CHECK_MSTATUS(status); // Connect the global Maya time to the deformer node. - status = dgMod.connect(timeNode, - timePlug.attribute(), - m_pointBasedDeformerNode, - UsdMayaPointBasedDeformerNode::timeAttr); + status = dgMod.connect( + timeNode, + timePlug.attribute(), + m_pointBasedDeformerNode, + UsdMayaPointBasedDeformerNode::timeAttr); CHECK_MSTATUS(status); status = dgMod.doIt(); @@ -430,12 +421,12 @@ TranslatorMeshRead::setPointBasedDeformerForMayaNode(const MObject& mayaObj, con // XXX: This seems to be the "most sane" way of finding the tweak deformer // node's name... const std::string findTweakCmd = TfStringPrintf( - "from maya import cmds; [x for x in cmds.listHistory(\'%s\') if cmds.nodeType(x) == \'tweak\'][0]", + "from maya import cmds; [x for x in cmds.listHistory(\'%s\') if cmds.nodeType(x) == " + "\'tweak\'][0]", dagNodeFn.fullPathName().asChar()); MString tweakDeformerNodeName; - status = MGlobal::executePythonCommand(findTweakCmd.c_str(), - tweakDeformerNodeName); + status = MGlobal::executePythonCommand(findTweakCmd.c_str(), tweakDeformerNodeName); CHECK_MSTATUS(status); // Do the reordering. @@ -450,46 +441,23 @@ TranslatorMeshRead::setPointBasedDeformerForMayaNode(const MObject& mayaObj, con return status; } -MObject -TranslatorMeshRead::meshObject() const -{ - return m_meshObj; -} +MObject TranslatorMeshRead::meshObject() const { return m_meshObj; } -MObject -TranslatorMeshRead::blendObject() const -{ - return m_meshBlendObj; -} +MObject TranslatorMeshRead::blendObject() const { return m_meshBlendObj; } -MObject -TranslatorMeshRead::pointBasedDeformerNode() const -{ - return m_pointBasedDeformerNode; -} +MObject TranslatorMeshRead::pointBasedDeformerNode() const { return m_pointBasedDeformerNode; } -MString -TranslatorMeshRead::pointBasedDeformerName() const -{ - return m_newPointBasedDeformerName; -} +MString TranslatorMeshRead::pointBasedDeformerName() const { return m_newPointBasedDeformerName; } -size_t -TranslatorMeshRead::pointsNumTimeSamples() const -{ - return m_pointsNumTimeSamples; -} +size_t TranslatorMeshRead::pointsNumTimeSamples() const { return m_pointsNumTimeSamples; } -SdfPath -TranslatorMeshRead::shapePath() const -{ - return m_shapePath; -} +SdfPath TranslatorMeshRead::shapePath() const { return m_shapePath; } -TranslatorMeshWrite::TranslatorMeshWrite(const MFnDependencyNode& depNodeFn, - const UsdStageRefPtr& stage, - const SdfPath& usdPath, - const MDagPath& dagPath) +TranslatorMeshWrite::TranslatorMeshWrite( + const MFnDependencyNode& depNodeFn, + const UsdStageRefPtr& stage, + const SdfPath& usdPath, + const MDagPath& dagPath) { if (!TF_VERIFY(dagPath.isValid())) { return; @@ -500,20 +468,11 @@ TranslatorMeshWrite::TranslatorMeshWrite(const MFnDependencyNode& depNodeFn, } m_usdMesh = UsdGeomMesh::Define(stage, usdPath); - if (!TF_VERIFY( - m_usdMesh, - "Could not define UsdGeomMesh at path '%s'\n", - usdPath.GetText())) { + if (!TF_VERIFY(m_usdMesh, "Could not define UsdGeomMesh at path '%s'\n", usdPath.GetText())) { return; } } -UsdGeomMesh -TranslatorMeshWrite::usdMesh() const -{ - return m_usdMesh; -} - -} // namespace MayaUsd - +UsdGeomMesh TranslatorMeshWrite::usdMesh() const { return m_usdMesh; } +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/fileio/translators/translatorMesh.h b/lib/mayaUsd/fileio/translators/translatorMesh.h index fae25f8b02..e2dc6aa847 100644 --- a/lib/mayaUsd/fileio/translators/translatorMesh.h +++ b/lib/mayaUsd/fileio/translators/translatorMesh.h @@ -20,12 +20,12 @@ #include -#include -#include - #include #include +#include +#include + PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { @@ -35,13 +35,14 @@ namespace MAYAUSD_NS_DEF { class MAYAUSD_CORE_PUBLIC TranslatorMeshRead { public: - TranslatorMeshRead(const UsdGeomMesh& mesh, - const UsdPrim& prim, - const MObject& transformObj, - const MObject& stageNode, - const GfInterval& frameRange, - bool wantCacheAnimation, - MStatus * status = nullptr); + TranslatorMeshRead( + const UsdGeomMesh& mesh, + const UsdPrim& prim, + const MObject& transformObj, + const MObject& stageNode, + const GfInterval& frameRange, + bool wantCacheAnimation, + MStatus* status = nullptr); ~TranslatorMeshRead() = default; @@ -55,21 +56,20 @@ class MAYAUSD_CORE_PUBLIC TranslatorMeshRead MObject blendObject() const; MObject pointBasedDeformerNode() const; MString pointBasedDeformerName() const; - size_t pointsNumTimeSamples() const; + size_t pointsNumTimeSamples() const; SdfPath shapePath() const; private: - MStatus setPointBasedDeformerForMayaNode(const MObject&, - const MObject&, - const UsdPrim&); + MStatus setPointBasedDeformerForMayaNode(const MObject&, const MObject&, const UsdPrim&); + private: MObject m_meshObj; MObject m_meshBlendObj; MObject m_pointBasedDeformerNode; MString m_newPointBasedDeformerName; - bool m_wantCacheAnimation; - size_t m_pointsNumTimeSamples; + bool m_wantCacheAnimation; + size_t m_pointsNumTimeSamples; SdfPath m_shapePath; }; @@ -77,10 +77,11 @@ class MAYAUSD_CORE_PUBLIC TranslatorMeshRead class MAYAUSD_CORE_PUBLIC TranslatorMeshWrite { public: - TranslatorMeshWrite(const MFnDependencyNode&, - const UsdStageRefPtr&, - const SdfPath&, - const MDagPath&); + TranslatorMeshWrite( + const MFnDependencyNode&, + const UsdStageRefPtr&, + const SdfPath&, + const MDagPath&); ~TranslatorMeshWrite() = default; @@ -95,4 +96,4 @@ class MAYAUSD_CORE_PUBLIC TranslatorMeshWrite UsdGeomMesh m_usdMesh; }; -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/fileio/translators/translatorNurbsPatch.cpp b/lib/mayaUsd/fileio/translators/translatorNurbsPatch.cpp index 63606f500d..f4d11e8896 100644 --- a/lib/mayaUsd/fileio/translators/translatorNurbsPatch.cpp +++ b/lib/mayaUsd/fileio/translators/translatorNurbsPatch.cpp @@ -15,6 +15,14 @@ // #include "translatorNurbsPatch.h" +#include +#include +#include +#include +#include + +#include + #include #include #include @@ -30,23 +38,14 @@ #include #include -#include - -#include -#include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE /* static */ -bool -UsdMayaTranslatorNurbsPatch::Read( - const UsdGeomNurbsPatch& usdNurbsPatch, - MObject parentNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context) +bool UsdMayaTranslatorNurbsPatch::Read( + const UsdGeomNurbsPatch& usdNurbsPatch, + MObject parentNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context) { if (!usdNurbsPatch) { return false; @@ -58,31 +57,28 @@ UsdMayaTranslatorNurbsPatch::Read( // Create the transform node for the patch. MObject mayaNode; - if (!UsdMayaTranslatorUtil::CreateTransformNode(prim, - parentNode, - args, - context, - &status, - &mayaNode)) { + if (!UsdMayaTranslatorUtil::CreateTransformNode( + prim, parentNode, args, context, &status, &mayaNode)) { return false; } // Since we are "decollapsing", we will create a xform and a shape node for each USD prim std::string usdPrimName(prim.GetName().GetText()); - std::string shapeName(usdPrimName); shapeName += "Shape"; + std::string shapeName(usdPrimName); + shapeName += "Shape"; std::string usdPrimPath(prim.GetPath().GetText()); std::string shapePath(usdPrimPath); shapePath += "/"; shapePath += shapeName; - int numCVsInU, numCVsInV; - int orderInU, orderInV; - VtArray knotsInU; - VtArray knotsInV; - GfVec2d rangeInU, rangeInV; + int numCVsInU, numCVsInV; + int orderInU, orderInV; + VtArray knotsInU; + VtArray knotsInV; + GfVec2d rangeInU, rangeInV; VtArray points; - VtArray weights; - + VtArray weights; + // NurbsPatch usdNurbsPatch.GetUVertexCountAttr().Get(&numCVsInU); usdNurbsPatch.GetVVertexCountAttr().Get(&numCVsInV); @@ -97,110 +93,113 @@ UsdMayaTranslatorNurbsPatch::Read( // Gather points. // If timeInterval is non-empty, pick the first available sample in the // timeInterval or default. - UsdTimeCode pointsTimeSample=UsdTimeCode::EarliestTime(); + UsdTimeCode pointsTimeSample = UsdTimeCode::EarliestTime(); std::vector pointsTimeSamples; - size_t numTimeSamples = 0; + size_t numTimeSamples = 0; if (!args.GetTimeInterval().IsEmpty()) { usdNurbsPatch.GetPointsAttr().GetTimeSamplesInInterval( - args.GetTimeInterval(), &pointsTimeSamples); + args.GetTimeInterval(), &pointsTimeSamples); numTimeSamples = pointsTimeSamples.size(); - if (numTimeSamples>0) { + if (numTimeSamples > 0) { pointsTimeSample = pointsTimeSamples[0]; } } usdNurbsPatch.GetPointsAttr().Get(&points, pointsTimeSample); - + if (points.empty()) { TF_RUNTIME_ERROR( - "points array is empty on NurbsPatch <%s>. Skipping...", - usdPrimPath.c_str()); + "points array is empty on NurbsPatch <%s>. Skipping...", usdPrimPath.c_str()); return false; // invalid nurbs, so exit } - + if (points.size() != static_cast((numCVsInU * numCVsInV))) { TF_RUNTIME_ERROR( - "points array size != uVertexCount * vVertexCount on " - "NurbsPatch <%s>. Skipping...", - usdPrimPath.c_str()); + "points array size != uVertexCount * vVertexCount on " + "NurbsPatch <%s>. Skipping...", + usdPrimPath.c_str()); return false; // Bad CV data, so exit } // Maya stores the data where v varies the fastest (v,u order) // so we need to unpack the data differently u,v order // WE DIFFER FROM ALEMBIC READER, WE DON'T FLIP V - + bool rationalSurface = false, hasWeights = false; - if (points.size()==weights.size()) hasWeights=true; - int cvIndex=0; + if (points.size() == weights.size()) + hasWeights = true; + int cvIndex = 0; MPointArray mayaPoints; - mayaPoints.setLength(numCVsInV*numCVsInU); - for (int v = 0; v < numCVsInV; v++) - { - for (int u = 0; u < numCVsInU; u++) - { + mayaPoints.setLength(numCVsInV * numCVsInU); + for (int v = 0; v < numCVsInV; v++) { + for (int u = 0; u < numCVsInU; u++) { int index = u * numCVsInV + v; if (hasWeights && !GfIsClose(weights[cvIndex], 1.0, 1e-9)) { - rationalSurface=true; - mayaPoints.set( index, points[cvIndex][0], points[cvIndex][1], points[cvIndex][2], weights[cvIndex] ); + rationalSurface = true; + mayaPoints.set( + index, + points[cvIndex][0], + points[cvIndex][1], + points[cvIndex][2], + weights[cvIndex]); } else { - mayaPoints.set( index, points[cvIndex][0], points[cvIndex][1], points[cvIndex][2] ); + mayaPoints.set(index, points[cvIndex][0], points[cvIndex][1], points[cvIndex][2]); } cvIndex++; } } - double *knotsU=knotsInU.data(); - MDoubleArray mayaKnotsInU( &knotsU[1], knotsInU.size()-2); - double *knotsV=knotsInV.data(); - MDoubleArray mayaKnotsInV( &knotsV[1], knotsInV.size()-2); + double* knotsU = knotsInU.data(); + MDoubleArray mayaKnotsInU(&knotsU[1], knotsInU.size() - 2); + double* knotsV = knotsInV.data(); + MDoubleArray mayaKnotsInV(&knotsV[1], knotsInV.size() - 2); MFnNurbsSurface::Form formInU = MFnNurbsSurface::kOpen; MFnNurbsSurface::Form formInV = MFnNurbsSurface::kOpen; - TfToken form; + TfToken form; usdNurbsPatch.GetUFormAttr().Get(&form); - if (form == UsdGeomTokens->closed ) formInU = MFnNurbsSurface::kClosed; - else if (form == UsdGeomTokens->periodic ) formInU = MFnNurbsSurface::kPeriodic; - + if (form == UsdGeomTokens->closed) + formInU = MFnNurbsSurface::kClosed; + else if (form == UsdGeomTokens->periodic) + formInU = MFnNurbsSurface::kPeriodic; + usdNurbsPatch.GetVFormAttr().Get(&form); - if (form == UsdGeomTokens->closed ) formInV = MFnNurbsSurface::kClosed; - else if (form == UsdGeomTokens->periodic ) formInV = MFnNurbsSurface::kPeriodic; + if (form == UsdGeomTokens->closed) + formInV = MFnNurbsSurface::kClosed; + else if (form == UsdGeomTokens->periodic) + formInV = MFnNurbsSurface::kPeriodic; // NOTE: In certain cases (i.e. linear cyilnder) Maya can't set the form // back to Closed when importing back an exported model. Seems a Maya bug - + // == Create NurbsSurface Shape Node MFnNurbsSurface surfaceFn; - - MObject surfaceObj = surfaceFn.create(mayaPoints, - mayaKnotsInU, - mayaKnotsInV, - orderInU-1, - orderInV-1, - formInU, - formInV, - rationalSurface, - mayaNode, - &status); + + MObject surfaceObj = surfaceFn.create( + mayaPoints, + mayaKnotsInU, + mayaKnotsInV, + orderInU - 1, + orderInV - 1, + formInU, + formInV, + rationalSurface, + mayaNode, + &status); if (status != MS::kSuccess) { TF_RUNTIME_ERROR( - "Unable to create Maya Nurbs for USD NurbsPatch <%s>", - usdPrimPath.c_str()); + "Unable to create Maya Nurbs for USD NurbsPatch <%s>", usdPrimPath.c_str()); return false; } - + surfaceFn.setName(MString(shapeName.c_str()), false, &status); if (context) { - context->RegisterNewMayaNode( shapePath, surfaceObj ); // used for undo/redo + context->RegisterNewMayaNode(shapePath, surfaceObj); // used for undo/redo } // If a material is bound, create (or reuse if already present) and assign it // If no binding is present, assign the nurbs surface to the default shader - const UsdMayaJobImportArgs& jobArguments = args.GetJobArguments(); - UsdMayaTranslatorMaterial::AssignMaterial( - jobArguments, - usdNurbsPatch, - surfaceObj, - context); + const UsdMayaJobImportArgs& jobArguments = args.GetJobArguments(); + UsdMayaTranslatorMaterial::AssignMaterial(jobArguments, usdNurbsPatch, surfaceObj, context); // NurbsSurface is a shape, so read Gprim properties UsdMayaTranslatorGprim::Read(usdNurbsPatch, surfaceObj, context); @@ -213,41 +212,42 @@ UsdMayaTranslatorNurbsPatch::Read( MObject surfaceAnimObj; MFnBlendShapeDeformer blendFn; - MObject blendObj = blendFn.create(surfaceObj); + MObject blendObj = blendFn.create(surfaceObj); if (context) { - context->RegisterNewMayaNode(blendFn.name().asChar(), blendObj ); // used for undo/redo + context->RegisterNewMayaNode(blendFn.name().asChar(), blendObj); // used for undo/redo } - - for (unsigned int ti=0; ti < numTimeSamples; ++ti) { + + for (unsigned int ti = 0; ti < numTimeSamples; ++ti) { usdNurbsPatch.GetPointsAttr().Get(&points, pointsTimeSamples[ti]); - cvIndex=0; + cvIndex = 0; for (int v = 0; v < numCVsInV; v++) { for (int u = 0; u < numCVsInU; u++) { int index = u * numCVsInV + v; - mayaPoints.set( index, points[cvIndex][0], points[cvIndex][1], points[cvIndex][2] ); + mayaPoints.set( + index, points[cvIndex][0], points[cvIndex][1], points[cvIndex][2]); cvIndex++; } } // == Create NurbsSurface Shape Node MFnNurbsSurface surfaceFn; - if ( surfaceAnimObj.isNull() ) { - surfaceAnimObj = surfaceFn.create(mayaPoints, - mayaKnotsInU, - mayaKnotsInV, - orderInU-1, - orderInV-1, - formInU, - formInV, - rationalSurface, - mayaNode, - &status); + if (surfaceAnimObj.isNull()) { + surfaceAnimObj = surfaceFn.create( + mayaPoints, + mayaKnotsInU, + mayaKnotsInV, + orderInU - 1, + orderInV - 1, + formInU, + formInV, + rationalSurface, + mayaNode, + &status); if (status != MS::kSuccess) { continue; } - } - else { + } else { // Reuse the already created surface by copying it and then setting the points surfaceAnimObj = surfaceFn.copy(surfaceAnimObj, mayaNode, &status); surfaceFn.setCVs(mayaPoints); @@ -255,7 +255,8 @@ UsdMayaTranslatorNurbsPatch::Read( blendFn.addTarget(surfaceObj, ti, surfaceAnimObj, 1.0); surfaceFn.setIntermediateObject(true); if (context) { - context->RegisterNewMayaNode( surfaceFn.fullPathName().asChar(), surfaceAnimObj ); // used for undo/redo + context->RegisterNewMayaNode( + surfaceFn.fullPathName().asChar(), surfaceAnimObj); // used for undo/redo } } @@ -265,47 +266,48 @@ UsdMayaTranslatorNurbsPatch::Read( // Construct the time array to be used for all the keys MTimeArray timeArray; timeArray.setLength(numTimeSamples); - for (unsigned int ti=0; ti < numTimeSamples; ++ti) { - timeArray.set( MTime(pointsTimeSamples[ti]), ti); + for (unsigned int ti = 0; ti < numTimeSamples; ++ti) { + timeArray.set(MTime(pointsTimeSamples[ti]), ti); } // Key/Animate the weights - MPlug plgAry = blendFn.findPlug( "weight" ); - if ( !plgAry.isNull() && plgAry.isArray() ) { - for (unsigned int ti=0; ti < numTimeSamples; ++ti) { - MPlug plg = plgAry.elementByLogicalIndex(ti, &status); + MPlug plgAry = blendFn.findPlug("weight"); + if (!plgAry.isNull() && plgAry.isArray()) { + for (unsigned int ti = 0; ti < numTimeSamples; ++ti) { + MPlug plg = plgAry.elementByLogicalIndex(ti, &status); MDoubleArray valueArray(numTimeSamples, 0.0); valueArray[ti] = 1.0; // Set the time value where this curve's weight should be 1.0 MObject animObj = animFn.create(plg, nullptr, &status); animFn.addKeys(&timeArray, &valueArray); if (context) { - context->RegisterNewMayaNode(animFn.name().asChar(), animObj ); // used for undo/redo + context->RegisterNewMayaNode( + animFn.name().asChar(), animObj); // used for undo/redo } } } } // Look for trim curves - - VtArray trimNumCurves; - VtArray trimNumPos; - VtArray trimOrder; - VtArray trimKnot; + + VtArray trimNumCurves; + VtArray trimNumPos; + VtArray trimOrder; + VtArray trimKnot; VtArray trimRange; VtArray trimPoint; - usdNurbsPatch.GetTrimCurveCountsAttr().Get(&trimNumCurves); - usdNurbsPatch.GetTrimCurveOrdersAttr().Get(&trimOrder); - usdNurbsPatch.GetTrimCurveVertexCountsAttr().Get(&trimNumPos); - usdNurbsPatch.GetTrimCurveKnotsAttr().Get(&trimKnot); - usdNurbsPatch.GetTrimCurveRangesAttr().Get(&trimRange); - usdNurbsPatch.GetTrimCurvePointsAttr().Get(&trimPoint); - - int numLoops=trimNumCurves.size(); + usdNurbsPatch.GetTrimCurveCountsAttr().Get(&trimNumCurves); + usdNurbsPatch.GetTrimCurveOrdersAttr().Get(&trimOrder); + usdNurbsPatch.GetTrimCurveVertexCountsAttr().Get(&trimNumPos); + usdNurbsPatch.GetTrimCurveKnotsAttr().Get(&trimKnot); + usdNurbsPatch.GetTrimCurveRangesAttr().Get(&trimRange); + usdNurbsPatch.GetTrimCurvePointsAttr().Get(&trimPoint); + + int numLoops = trimNumCurves.size(); if (numLoops == 0) return true; MTrimBoundaryArray trimBoundaryArray; - MObjectArray deleteAfterTrim; + MObjectArray deleteAfterTrim; int curCurve = 0; int curPos = 0; @@ -317,13 +319,13 @@ UsdMayaTranslatorNurbsPatch::Read( int numCurves = trimNumCurves[i]; for (int j = 0; j < numCurves; ++j, ++curCurve) { unsigned int degree = trimOrder[curCurve] - 1; - int numVerts = trimNumPos[curCurve]; - int numKnots = numVerts + degree + 1; + int numVerts = trimNumPos[curCurve]; + int numKnots = numVerts + degree + 1; MPointArray cvs; cvs.setLength(numVerts); // WE DIFFER FROM ALEMBIC READER, WE DON'T FLIP V - for (int k=0 ; k(rightMostIndex) == curvePoints.length() - 1) ? 0 : rightMostIndex + 1; + int afterIndex = (static_cast(rightMostIndex) == curvePoints.length() - 1) + ? 0 + : rightMostIndex + 1; for (unsigned int j = 0; j < curvePoints.length(); j++) { if (fabs(curvePoints[beforeIndex].x - curvePoints[rightMostIndex].x) < 1e-5) { @@ -410,25 +416,29 @@ UsdMayaTranslatorNurbsPatch::Read( } for (unsigned int j = 0; j < curvePoints.length(); j++) { - if (fabs(curvePoints[afterIndex].x - curvePoints[rightMostIndex].x) < 1e-5) { - afterIndex = (afterIndex == (int)(curvePoints.length()) - 1) ? 0 : afterIndex + 1; - } + if (fabs(curvePoints[afterIndex].x - curvePoints[rightMostIndex].x) < 1e-5) { + afterIndex = (afterIndex == (int)(curvePoints.length()) - 1) ? 0 : afterIndex + 1; + } } // failed. not a closed curve. - if (fabs(curvePoints[afterIndex].x - curvePoints[rightMostIndex].x) < 1e-5 && - fabs(curvePoints[beforeIndex].x - curvePoints[rightMostIndex].x) < 1e-5) { + if (fabs(curvePoints[afterIndex].x - curvePoints[rightMostIndex].x) < 1e-5 + && fabs(curvePoints[beforeIndex].x - curvePoints[rightMostIndex].x) < 1e-5) { continue; } - if (beforeIndex < 0) beforeIndex += curvePoints.length(); - if (beforeIndex >= (int)(curvePoints.length())) beforeIndex = beforeIndex & curvePoints.length(); - if (afterIndex < 0) afterIndex += curvePoints.length(); - if (afterIndex >= (int)(curvePoints.length())) afterIndex = afterIndex & curvePoints.length(); + if (beforeIndex < 0) + beforeIndex += curvePoints.length(); + if (beforeIndex >= (int)(curvePoints.length())) + beforeIndex = beforeIndex & curvePoints.length(); + if (afterIndex < 0) + afterIndex += curvePoints.length(); + if (afterIndex >= (int)(curvePoints.length())) + afterIndex = afterIndex & curvePoints.length(); // Compute the cross product MVector vector1 = curvePoints[beforeIndex] - curvePoints[rightMostIndex]; - MVector vector2 = curvePoints[afterIndex] - curvePoints[rightMostIndex]; + MVector vector2 = curvePoints[afterIndex] - curvePoints[rightMostIndex]; if ((vector1 ^ vector2).z < 0) { isOuterBoundary = true; } @@ -437,31 +447,26 @@ UsdMayaTranslatorNurbsPatch::Read( if (isOuterBoundary) { status = surfaceFn.trimWithBoundaries(oneRegion, false, 1e-3, 1e-5, true); if (status != MS::kSuccess) { - TF_RUNTIME_ERROR( - "Trimming failed on NURBS for <%s>", - usdPrimPath.c_str()); + TF_RUNTIME_ERROR("Trimming failed on NURBS for <%s>", usdPrimPath.c_str()); } oneRegion.clear(); } oneRegion.append(trimBoundaryArray[i]); } - if (oneRegion.length()>0) { + if (oneRegion.length() > 0) { status = surfaceFn.trimWithBoundaries(oneRegion, false, 1e-3, 1e-5, true); } if (status != MS::kSuccess) { - TF_RUNTIME_ERROR( - "Trimming failed on NURBS for <%s>", - usdPrimPath.c_str()); + TF_RUNTIME_ERROR("Trimming failed on NURBS for <%s>", usdPrimPath.c_str()); } // Deleted collected curves since they are not needed anymore unsigned int length = deleteAfterTrim.length(); - for (unsigned int l=0; l +#include +#include +#include #include #include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -31,14 +31,12 @@ struct UsdMayaTranslatorNurbsPatch { MAYAUSD_CORE_PUBLIC static bool Read( - const UsdGeomNurbsPatch& usdNurbsPatch, - MObject parentNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context); + const UsdGeomNurbsPatch& usdNurbsPatch, + MObject parentNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context); }; - - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/translators/translatorPrim.cpp b/lib/mayaUsd/fileio/translators/translatorPrim.cpp index 8a4f4b8739..8bfd481b27 100644 --- a/lib/mayaUsd/fileio/translators/translatorPrim.cpp +++ b/lib/mayaUsd/fileio/translators/translatorPrim.cpp @@ -15,103 +15,95 @@ // #include "translatorPrim.h" -#include -#include - -#include - #include #include #include +#include + +#include +#include + PXR_NAMESPACE_OPEN_SCOPE -void -UsdMayaTranslatorPrim::Read( - const UsdPrim& prim, - MObject mayaNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context) +void UsdMayaTranslatorPrim::Read( + const UsdPrim& prim, + MObject mayaNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context) { UsdGeomImageable primSchema(prim); if (!primSchema) { - TF_CODING_ERROR("Prim %s is not UsdGeomImageable.", - prim.GetPath().GetText()); + TF_CODING_ERROR("Prim %s is not UsdGeomImageable.", prim.GetPath().GetText()); return; } // Gather visibility // If timeInterval is non-empty, pick the first available sample in the // timeInterval or default. - UsdTimeCode visTimeSample=UsdTimeCode::EarliestTime(); + UsdTimeCode visTimeSample = UsdTimeCode::EarliestTime(); std::vector visTimeSamples; - size_t visNumTimeSamples = 0; + size_t visNumTimeSamples = 0; if (!args.GetTimeInterval().IsEmpty()) { primSchema.GetVisibilityAttr().GetTimeSamplesInInterval( - args.GetTimeInterval(), &visTimeSamples); + args.GetTimeInterval(), &visTimeSamples); visNumTimeSamples = visTimeSamples.size(); - if (visNumTimeSamples>0) { + if (visNumTimeSamples > 0) { visTimeSample = visTimeSamples[0]; } } - MStatus status; + MStatus status; MFnDependencyNode depFn(mayaNode); - TfToken visibilityTok; + TfToken visibilityTok; - if (primSchema.GetVisibilityAttr().Get(&visibilityTok, visTimeSample)){ - UsdMayaUtil::setPlugValue(depFn, "visibility", - visibilityTok != UsdGeomTokens->invisible); + if (primSchema.GetVisibilityAttr().Get(&visibilityTok, visTimeSample)) { + UsdMayaUtil::setPlugValue(depFn, "visibility", visibilityTok != UsdGeomTokens->invisible); } // == Animation == if (visNumTimeSamples > 0) { - size_t numTimeSamples = visNumTimeSamples; + size_t numTimeSamples = visNumTimeSamples; MDoubleArray valueArray(numTimeSamples); // Populate the channel arrays - for (unsigned int ti=0; ti < visNumTimeSamples; ++ti) { + for (unsigned int ti = 0; ti < visNumTimeSamples; ++ti) { primSchema.GetVisibilityAttr().Get(&visibilityTok, visTimeSamples[ti]); - valueArray[ti] = - static_cast(visibilityTok != UsdGeomTokens->invisible); + valueArray[ti] = static_cast(visibilityTok != UsdGeomTokens->invisible); } // == Write to maya node == - MFnDagNode depFn(mayaNode); - MPlug plg; + MFnDagNode depFn(mayaNode); + MPlug plg; MFnAnimCurve animFn; // Construct the time array to be used for all the keys MTimeArray timeArray; timeArray.setLength(numTimeSamples); - for (unsigned int ti=0; ti < numTimeSamples; ++ti) { - timeArray.set( MTime(visTimeSamples[ti]), ti); + for (unsigned int ti = 0; ti < numTimeSamples; ++ti) { + timeArray.set(MTime(visTimeSamples[ti]), ti); } // Add the keys - plg = depFn.findPlug( "visibility" ); - if ( !plg.isNull() ) { + plg = depFn.findPlug("visibility"); + if (!plg.isNull()) { MObject animObj = animFn.create(plg, nullptr, &status); animFn.addKeys(&timeArray, &valueArray); if (context) { - context->RegisterNewMayaNode( - animFn.name().asChar(), animObj ); // used for undo/redo + context->RegisterNewMayaNode(animFn.name().asChar(), animObj); // used for undo/redo } } } // Process UsdGeomImageable typed schema (note that purpose is uniform). UsdMayaReadUtil::ReadSchemaAttributesFromPrim( - prim, mayaNode, {UsdGeomTokens->purpose}); + prim, mayaNode, { UsdGeomTokens->purpose }); // Process API schema attributes and strongly-typed metadata. - UsdMayaReadUtil::ReadMetadataFromPrim( - args.GetIncludeMetadataKeys(), prim, mayaNode); - UsdMayaReadUtil::ReadAPISchemaAttributesFromPrim( - args.GetIncludeAPINames(), prim, mayaNode); + UsdMayaReadUtil::ReadMetadataFromPrim(args.GetIncludeMetadataKeys(), prim, mayaNode); + UsdMayaReadUtil::ReadAPISchemaAttributesFromPrim(args.GetIncludeAPINames(), prim, mayaNode); // XXX What about all the "user attributes" that PrimWriter exports??? } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/translators/translatorPrim.h b/lib/mayaUsd/fileio/translators/translatorPrim.h index cbe24f6e15..f2bdf8f996 100644 --- a/lib/mayaUsd/fileio/translators/translatorPrim.h +++ b/lib/mayaUsd/fileio/translators/translatorPrim.h @@ -16,14 +16,14 @@ #ifndef PXRUSDMAYA_TRANSLATOR_PRIM_H #define PXRUSDMAYA_TRANSLATOR_PRIM_H -#include +#include +#include +#include #include #include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -33,13 +33,12 @@ struct UsdMayaTranslatorPrim { MAYAUSD_CORE_PUBLIC static void Read( - const UsdPrim& prim, - MObject mayaNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context); + const UsdPrim& prim, + MObject mayaNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context); }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/translators/translatorRfMLight.cpp b/lib/mayaUsd/fileio/translators/translatorRfMLight.cpp index f0691e030d..a8fb2518b9 100644 --- a/lib/mayaUsd/fileio/translators/translatorRfMLight.cpp +++ b/lib/mayaUsd/fileio/translators/translatorRfMLight.cpp @@ -15,14 +15,15 @@ // #include "translatorRfMLight.h" -#include - -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -46,15 +47,14 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE @@ -62,94 +62,59 @@ TF_DEFINE_PRIVATE_TOKENS( _tokens, // RenderMan for Maya light types. - ((AovLightMayaTypeName, "PxrAovLight")) - ((CylinderLightMayaTypeName, "PxrCylinderLight")) - ((DiskLightMayaTypeName, "PxrDiskLight")) - ((DistantLightMayaTypeName, "PxrDistantLight")) - ((DomeLightMayaTypeName, "PxrDomeLight")) - ((EnvDayLightMayaTypeName, "PxrEnvDayLight")) - ((GeometryLightMayaTypeName, "PxrMeshLight")) - ((RectLightMayaTypeName, "PxrRectLight")) - ((SphereLightMayaTypeName, "PxrSphereLight")) + ((AovLightMayaTypeName, "PxrAovLight"))((CylinderLightMayaTypeName, "PxrCylinderLight"))( + (DiskLightMayaTypeName, "PxrDiskLight"))((DistantLightMayaTypeName, "PxrDistantLight"))( + (DomeLightMayaTypeName, "PxrDomeLight"))((EnvDayLightMayaTypeName, "PxrEnvDayLight"))( + (GeometryLightMayaTypeName, "PxrMeshLight"))((RectLightMayaTypeName, "PxrRectLight"))( + (SphereLightMayaTypeName, "PxrSphereLight")) // Light plug names. - ((IntensityPlugName, "intensity")) - ((ExposurePlugName, "exposure")) - ((DiffuseAmountPlugName, "diffuse")) - ((SpecularAmountPlugName, "specular")) - ((NormalizePowerPlugName, "areaNormalize")) - ((ColorPlugName, "lightColor")) - ((EnableTemperaturePlugName, "enableTemperature")) - ((TemperaturePlugName, "temperature")) + ((IntensityPlugName, "intensity"))((ExposurePlugName, "exposure"))( + (DiffuseAmountPlugName, "diffuse"))((SpecularAmountPlugName, "specular"))( + (NormalizePowerPlugName, "areaNormalize"))((ColorPlugName, "lightColor"))( + (EnableTemperaturePlugName, "enableTemperature"))((TemperaturePlugName, "temperature")) // Type-specific Light plug names. - ((DistantLightAnglePlugName, "angleExtent")) - ((TextureFilePlugName, "lightColorMap")) + ((DistantLightAnglePlugName, "angleExtent"))((TextureFilePlugName, "lightColorMap")) // PxrAovLight plug names. - ((AovNamePlugName, "aovName")) - ((InPrimaryHitPlugName, "inPrimaryHit")) - ((InReflectionPlugName, "inReflection")) - ((InRefractionPlugName, "inRefraction")) - ((InvertPlugName, "invert")) - ((OnVolumeBoundariesPlugName, "onVolumeBoundaries")) - ((UseColorPlugName, "useColor")) - ((UseThroughputPlugName, "useThroughput")) + ((AovNamePlugName, "aovName"))((InPrimaryHitPlugName, "inPrimaryHit"))( + (InReflectionPlugName, "inReflection"))((InRefractionPlugName, "inRefraction"))( + (InvertPlugName, "invert"))((OnVolumeBoundariesPlugName, "onVolumeBoundaries"))( + (UseColorPlugName, "useColor"))((UseThroughputPlugName, "useThroughput")) // PxrEnvDayLight plug names. - ((DayPlugName, "day")) - ((HazinessPlugName, "haziness")) - ((HourPlugName, "hour")) - ((LatitudePlugName, "latitude")) - ((LongitudePlugName, "longitude")) - ((MonthPlugName, "month")) - ((SkyTintPlugName, "skyTint")) - ((SunDirectionPlugName, "sunDirection")) - ((SunSizePlugName, "sunSize")) - ((SunTintPlugName, "sunTint")) - ((YearPlugName, "year")) - ((ZonePlugName, "zone")) + ((DayPlugName, "day"))((HazinessPlugName, "haziness"))((HourPlugName, "hour"))( + (LatitudePlugName, "latitude"))((LongitudePlugName, "longitude"))((MonthPlugName, "month"))( + (SkyTintPlugName, + "skyTint"))((SunDirectionPlugName, "sunDirection"))((SunSizePlugName, "sunSize"))( + (SunTintPlugName, "sunTint"))((YearPlugName, "year"))((ZonePlugName, "zone")) // ShapingAPI plug names. - ((FocusPlugName, "emissionFocus")) - ((FocusTintPlugName, "emissionFocusTint")) - ((ConeAnglePlugName, "coneAngle")) - ((ConeSoftnessPlugName, "coneSoftness")) - ((ProfileFilePlugName, "iesProfile")) - ((ProfileScalePlugName, "iesProfileScale")) + ((FocusPlugName, "emissionFocus"))((FocusTintPlugName, "emissionFocusTint"))( + (ConeAnglePlugName, "coneAngle"))((ConeSoftnessPlugName, "coneSoftness"))( + (ProfileFilePlugName, "iesProfile"))((ProfileScalePlugName, "iesProfileScale")) // ShadowAPI plug names. - ((EnableShadowsPlugName, "enableShadows")) - ((ShadowColorPlugName, "shadowColor")) - ((ShadowDistancePlugName, "shadowDistance")) - ((ShadowFalloffPlugName, "shadowFalloff")) - ((ShadowFalloffGammaPlugName, "shadowFalloffGamma")) -); - + ((EnableShadowsPlugName, "enableShadows"))((ShadowColorPlugName, "shadowColor"))( + (ShadowDistancePlugName, "shadowDistance"))((ShadowFalloffPlugName, "shadowFalloff"))( + (ShadowFalloffGammaPlugName, "shadowFalloffGamma"))); -static -bool -_ReportError(const std::string& msg, const SdfPath& primPath=SdfPath()) +static bool _ReportError(const std::string& msg, const SdfPath& primPath = SdfPath()) { TF_RUNTIME_ERROR( - "%s%s", - msg.c_str(), - primPath.IsPrimPath() - ? TfStringPrintf(" for Light <%s>", primPath.GetText()).c_str() - : ""); + "%s%s", + msg.c_str(), + primPath.IsPrimPath() ? TfStringPrintf(" for Light <%s>", primPath.GetText()).c_str() : ""); return false; } - // INTENSITY -static -bool -_WriteLightIntensity(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) +static bool _WriteLightIntensity(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { - MStatus status; - const MPlug lightIntensityPlug = - depFn.findPlug(_tokens->IntensityPlugName.GetText(), &status); + MStatus status; + const MPlug lightIntensityPlug = depFn.findPlug(_tokens->IntensityPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -165,13 +130,10 @@ _WriteLightIntensity(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return true; } -static -bool -_ReadLightIntensity(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadLightIntensity(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { MStatus status; - MPlug lightIntensityPlug = - depFn.findPlug(_tokens->IntensityPlugName.GetText(), &status); + MPlug lightIntensityPlug = depFn.findPlug(_tokens->IntensityPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -184,16 +146,12 @@ _ReadLightIntensity(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return (status == MS::kSuccess); } - // EXPOSURE -static -bool -_WriteLightExposure(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) +static bool _WriteLightExposure(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { - MStatus status; - const MPlug lightExposurePlug = - depFn.findPlug(_tokens->ExposurePlugName.GetText(), &status); + MStatus status; + const MPlug lightExposurePlug = depFn.findPlug(_tokens->ExposurePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -209,13 +167,10 @@ _WriteLightExposure(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return true; } -static -bool -_ReadLightExposure(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadLightExposure(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { MStatus status; - MPlug lightExposurePlug = - depFn.findPlug(_tokens->ExposurePlugName.GetText(), &status); + MPlug lightExposurePlug = depFn.findPlug(_tokens->ExposurePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -228,16 +183,13 @@ _ReadLightExposure(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return (status == MS::kSuccess); } - // DIFFUSE -static -bool -_WriteLightDiffuse(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) +static bool _WriteLightDiffuse(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { - MStatus status; - const MPlug lightDiffusePlug = - depFn.findPlug(_tokens->DiffuseAmountPlugName.GetText(), &status); + MStatus status; + const MPlug lightDiffusePlug + = depFn.findPlug(_tokens->DiffuseAmountPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -253,13 +205,10 @@ _WriteLightDiffuse(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return true; } -static -bool -_ReadLightDiffuse(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadLightDiffuse(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { MStatus status; - MPlug lightDiffusePlug = - depFn.findPlug(_tokens->DiffuseAmountPlugName.GetText(), &status); + MPlug lightDiffusePlug = depFn.findPlug(_tokens->DiffuseAmountPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -272,16 +221,13 @@ _ReadLightDiffuse(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return (status == MS::kSuccess); } - // SPECULAR -static -bool -_WriteLightSpecular(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) +static bool _WriteLightSpecular(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { - MStatus status; - const MPlug lightSpecularPlug = - depFn.findPlug(_tokens->SpecularAmountPlugName.GetText(), &status); + MStatus status; + const MPlug lightSpecularPlug + = depFn.findPlug(_tokens->SpecularAmountPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -297,13 +243,10 @@ _WriteLightSpecular(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return true; } -static -bool -_ReadLightSpecular(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadLightSpecular(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { MStatus status; - MPlug lightSpecularPlug = - depFn.findPlug(_tokens->SpecularAmountPlugName.GetText(), &status); + MPlug lightSpecularPlug = depFn.findPlug(_tokens->SpecularAmountPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -316,18 +259,13 @@ _ReadLightSpecular(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return (status == MS::kSuccess); } - // NORMALIZE POWER -static -bool -_WriteLightNormalizePower( - const MFnDependencyNode& depFn, - UsdLuxLight& lightSchema) +static bool _WriteLightNormalizePower(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { - MStatus status; - const MPlug lightNormalizePowerPlug = - depFn.findPlug(_tokens->NormalizePowerPlugName.GetText(), &status); + MStatus status; + const MPlug lightNormalizePowerPlug + = depFn.findPlug(_tokens->NormalizePowerPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -343,15 +281,11 @@ _WriteLightNormalizePower( return true; } -static -bool -_ReadLightNormalizePower( - const UsdLuxLight& lightSchema, - MFnDependencyNode& depFn) +static bool _ReadLightNormalizePower(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { MStatus status; - MPlug lightNormalizePowerPlug = - depFn.findPlug(_tokens->NormalizePowerPlugName.GetText(), &status); + MPlug lightNormalizePowerPlug + = depFn.findPlug(_tokens->NormalizePowerPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -364,35 +298,29 @@ _ReadLightNormalizePower( return (status == MS::kSuccess); } - // COLOR -static -bool -_WriteLightColor(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) +static bool _WriteLightColor(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { - MStatus status; - const MPlug lightColorPlug = - depFn.findPlug(_tokens->ColorPlugName.GetText(), &status); + MStatus status; + const MPlug lightColorPlug = depFn.findPlug(_tokens->ColorPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } - const GfVec3f lightColor(lightColorPlug.child(0).asFloat(), - lightColorPlug.child(1).asFloat(), - lightColorPlug.child(2).asFloat()); + const GfVec3f lightColor( + lightColorPlug.child(0).asFloat(), + lightColorPlug.child(1).asFloat(), + lightColorPlug.child(2).asFloat()); lightSchema.CreateColorAttr(VtValue(lightColor), true); return true; } -static -bool -_ReadLightColor(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadLightColor(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { MStatus status; - MPlug lightColorPlug = - depFn.findPlug(_tokens->ColorPlugName.GetText(), &status); + MPlug lightColorPlug = depFn.findPlug(_tokens->ColorPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -407,16 +335,13 @@ _ReadLightColor(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return (status == MS::kSuccess); } - // TEMPERATURE -static -bool -_WriteLightTemperature(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) +static bool _WriteLightTemperature(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { - MStatus status; - const MPlug lightEnableTemperaturePlug = - depFn.findPlug(_tokens->EnableTemperaturePlugName.GetText(), &status); + MStatus status; + const MPlug lightEnableTemperaturePlug + = depFn.findPlug(_tokens->EnableTemperaturePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -427,8 +352,8 @@ _WriteLightTemperature(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return false; } - const MPlug lightTemperaturePlug = - depFn.findPlug(_tokens->TemperaturePlugName.GetText(), &status); + const MPlug lightTemperaturePlug + = depFn.findPlug(_tokens->TemperaturePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -439,26 +364,22 @@ _WriteLightTemperature(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return false; } - lightSchema.CreateEnableColorTemperatureAttr( - VtValue(mayaLightEnableTemperature), true); + lightSchema.CreateEnableColorTemperatureAttr(VtValue(mayaLightEnableTemperature), true); lightSchema.CreateColorTemperatureAttr(VtValue(mayaLightTemperature), true); return true; } -static -bool -_ReadLightTemperature(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadLightTemperature(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { MStatus status; - MPlug lightEnableTemperaturePlug = - depFn.findPlug(_tokens->EnableTemperaturePlugName.GetText(), &status); + MPlug lightEnableTemperaturePlug + = depFn.findPlug(_tokens->EnableTemperaturePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } - MPlug lightTemperaturePlug = - depFn.findPlug(_tokens->TemperaturePlugName.GetText(), &status); + MPlug lightTemperaturePlug = depFn.findPlug(_tokens->TemperaturePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -482,23 +403,18 @@ _ReadLightTemperature(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return true; } - // DISTANT LIGHT ANGLE -static -bool -_WriteDistantLightAngle( - const MFnDependencyNode& depFn, - UsdLuxLight& lightSchema) +static bool _WriteDistantLightAngle(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { UsdLuxDistantLight distantLightSchema(lightSchema); if (!distantLightSchema) { return false; } - MStatus status; - const MPlug lightAnglePlug = - depFn.findPlug(_tokens->DistantLightAnglePlugName.GetText(), &status); + MStatus status; + const MPlug lightAnglePlug + = depFn.findPlug(_tokens->DistantLightAnglePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -514,9 +430,7 @@ _WriteDistantLightAngle( return true; } -static -bool -_ReadDistantLightAngle(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadDistantLightAngle(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { const UsdLuxDistantLight distantLightSchema(lightSchema); if (!distantLightSchema) { @@ -524,8 +438,7 @@ _ReadDistantLightAngle(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } MStatus status; - MPlug lightAnglePlug = - depFn.findPlug(_tokens->DistantLightAnglePlugName.GetText(), &status); + MPlug lightAnglePlug = depFn.findPlug(_tokens->DistantLightAnglePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -538,12 +451,9 @@ _ReadDistantLightAngle(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return (status == MS::kSuccess); } - // LIGHT TEXTURE FILE -static -bool -_WriteLightTextureFile(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) +static bool _WriteLightTextureFile(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { UsdLuxRectLight rectLightSchema(lightSchema); UsdLuxDomeLight domeLightSchema(lightSchema); @@ -551,10 +461,9 @@ _WriteLightTextureFile(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return false; } - MStatus status; - const MPlug lightTextureFilePlug = - depFn.findPlug(_tokens->TextureFilePlugName.GetText(), - &status); + MStatus status; + const MPlug lightTextureFilePlug + = depFn.findPlug(_tokens->TextureFilePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -571,19 +480,15 @@ _WriteLightTextureFile(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) const SdfAssetPath lightTextureAssetPath(mayaLightTextureFile.asChar()); if (rectLightSchema) { - rectLightSchema.CreateTextureFileAttr(VtValue(lightTextureAssetPath), - true); + rectLightSchema.CreateTextureFileAttr(VtValue(lightTextureAssetPath), true); } else if (domeLightSchema) { - domeLightSchema.CreateTextureFileAttr(VtValue(lightTextureAssetPath), - true); + domeLightSchema.CreateTextureFileAttr(VtValue(lightTextureAssetPath), true); } return true; } -static -bool -_ReadLightTextureFile(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadLightTextureFile(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { const UsdLuxRectLight rectLightSchema(lightSchema); const UsdLuxDomeLight domeLightSchema(lightSchema); @@ -592,9 +497,7 @@ _ReadLightTextureFile(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } MStatus status; - MPlug lightTextureFilePlug = - depFn.findPlug(_tokens->TextureFilePlugName.GetText(), - &status); + MPlug lightTextureFilePlug = depFn.findPlug(_tokens->TextureFilePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -612,11 +515,8 @@ _ReadLightTextureFile(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return (status == MS::kSuccess); } - // AOV LIGHT -static -bool -_WriteAovLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) +static bool _WriteAovLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { UsdRiPxrAovLight aovLightSchema(lightSchema); if (!aovLightSchema) { @@ -626,8 +526,7 @@ _WriteAovLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) MStatus status; // AOV Name. - MPlug aovNamePlug = - depFn.findPlug(_tokens->AovNamePlugName.GetText(), &status); + MPlug aovNamePlug = depFn.findPlug(_tokens->AovNamePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -643,8 +542,7 @@ _WriteAovLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // In Primary Hit. - MPlug inPrimaryHitPlug = - depFn.findPlug(_tokens->InPrimaryHitPlugName.GetText(), &status); + MPlug inPrimaryHitPlug = depFn.findPlug(_tokens->InPrimaryHitPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -660,8 +558,7 @@ _WriteAovLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // In Reflection. - MPlug inReflectionPlug = - depFn.findPlug(_tokens->InReflectionPlugName.GetText(), &status); + MPlug inReflectionPlug = depFn.findPlug(_tokens->InReflectionPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -677,8 +574,7 @@ _WriteAovLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // In Refraction. - MPlug inRefractionPlug = - depFn.findPlug(_tokens->InRefractionPlugName.GetText(), &status); + MPlug inRefractionPlug = depFn.findPlug(_tokens->InRefractionPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -694,8 +590,7 @@ _WriteAovLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // Invert. - MPlug invertPlug = - depFn.findPlug(_tokens->InvertPlugName.GetText(), &status); + MPlug invertPlug = depFn.findPlug(_tokens->InvertPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -711,8 +606,8 @@ _WriteAovLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // On Volume Boundaries. - MPlug onVolumeBoundariesPlug = - depFn.findPlug(_tokens->OnVolumeBoundariesPlugName.GetText(), &status); + MPlug onVolumeBoundariesPlug + = depFn.findPlug(_tokens->OnVolumeBoundariesPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -724,14 +619,11 @@ _WriteAovLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return false; } - aovLightSchema.CreateOnVolumeBoundariesAttr( - VtValue(mayaOnVolumeBoundaries), - true); + aovLightSchema.CreateOnVolumeBoundariesAttr(VtValue(mayaOnVolumeBoundaries), true); } // Use Color. - MPlug useColorPlug = - depFn.findPlug(_tokens->UseColorPlugName.GetText(), &status); + MPlug useColorPlug = depFn.findPlug(_tokens->UseColorPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -747,8 +639,7 @@ _WriteAovLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // Use Throughput. - MPlug useThroughputPlug = - depFn.findPlug(_tokens->UseThroughputPlugName.GetText(), &status); + MPlug useThroughputPlug = depFn.findPlug(_tokens->UseThroughputPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -760,16 +651,13 @@ _WriteAovLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return false; } - aovLightSchema.CreateUseThroughputAttr(VtValue(mayaUseThroughput), - true); + aovLightSchema.CreateUseThroughputAttr(VtValue(mayaUseThroughput), true); } return true; } -static -bool -_ReadAovLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadAovLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { const UsdRiPxrAovLight aovLightSchema(lightSchema); if (!aovLightSchema) { @@ -779,8 +667,7 @@ _ReadAovLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) MStatus status; // AOV Name. - MPlug lightAovNamePlug = - depFn.findPlug(_tokens->AovNamePlugName.GetText(), &status); + MPlug lightAovNamePlug = depFn.findPlug(_tokens->AovNamePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -794,8 +681,7 @@ _ReadAovLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // In Primary Hit. - MPlug lightInPrimaryHitPlug = - depFn.findPlug(_tokens->InPrimaryHitPlugName.GetText(), &status); + MPlug lightInPrimaryHitPlug = depFn.findPlug(_tokens->InPrimaryHitPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -809,8 +695,7 @@ _ReadAovLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // In Reflection. - MPlug lightInReflectionPlug = - depFn.findPlug(_tokens->InReflectionPlugName.GetText(), &status); + MPlug lightInReflectionPlug = depFn.findPlug(_tokens->InReflectionPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -824,8 +709,7 @@ _ReadAovLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // In Refraction. - MPlug lightInRefractionPlug = - depFn.findPlug(_tokens->InRefractionPlugName.GetText(), &status); + MPlug lightInRefractionPlug = depFn.findPlug(_tokens->InRefractionPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -839,8 +723,7 @@ _ReadAovLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Invert. - MPlug lightInvertPlug = - depFn.findPlug(_tokens->InvertPlugName.GetText(), &status); + MPlug lightInvertPlug = depFn.findPlug(_tokens->InvertPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -854,8 +737,8 @@ _ReadAovLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // On Volume Boundaries. - MPlug lightOnVolumeBoundariesPlug = - depFn.findPlug(_tokens->OnVolumeBoundariesPlugName.GetText(), &status); + MPlug lightOnVolumeBoundariesPlug + = depFn.findPlug(_tokens->OnVolumeBoundariesPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -869,8 +752,7 @@ _ReadAovLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Use Color. - MPlug lightUseColorPlug = - depFn.findPlug(_tokens->UseColorPlugName.GetText(), &status); + MPlug lightUseColorPlug = depFn.findPlug(_tokens->UseColorPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -884,8 +766,8 @@ _ReadAovLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Use Throughput. - MPlug lightUseThroughputPlug = - depFn.findPlug(_tokens->UseThroughputPlugName.GetText(), &status); + MPlug lightUseThroughputPlug + = depFn.findPlug(_tokens->UseThroughputPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -897,11 +779,8 @@ _ReadAovLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return status == MS::kSuccess; } - // ENVDAY LIGHT -static -bool -_WriteEnvDayLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) +static bool _WriteEnvDayLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { UsdRiPxrEnvDayLight envDayLightSchema(lightSchema); if (!envDayLightSchema) { @@ -927,8 +806,7 @@ _WriteEnvDayLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // Haziness. - MPlug hazinessPlug = - depFn.findPlug(_tokens->HazinessPlugName.GetText(), &status); + MPlug hazinessPlug = depFn.findPlug(_tokens->HazinessPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -960,8 +838,7 @@ _WriteEnvDayLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // Latitude. - MPlug latitudePlug = - depFn.findPlug(_tokens->LatitudePlugName.GetText(), &status); + MPlug latitudePlug = depFn.findPlug(_tokens->LatitudePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -977,8 +854,7 @@ _WriteEnvDayLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // Longitude. - MPlug longitudePlug = - depFn.findPlug(_tokens->LongitudePlugName.GetText(), &status); + MPlug longitudePlug = depFn.findPlug(_tokens->LongitudePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -994,8 +870,7 @@ _WriteEnvDayLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // Month. - MPlug monthPlug = - depFn.findPlug(_tokens->MonthPlugName.GetText(), &status); + MPlug monthPlug = depFn.findPlug(_tokens->MonthPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1011,38 +886,37 @@ _WriteEnvDayLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // Sky tint. - MPlug skyTintPlug = - depFn.findPlug(_tokens->SkyTintPlugName.GetText(), &status); + MPlug skyTintPlug = depFn.findPlug(_tokens->SkyTintPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } if (UsdMayaUtil::IsAuthored(skyTintPlug)) { - const GfVec3f mayaSkyTint(skyTintPlug.child(0).asFloat(), - skyTintPlug.child(1).asFloat(), - skyTintPlug.child(2).asFloat()); + const GfVec3f mayaSkyTint( + skyTintPlug.child(0).asFloat(), + skyTintPlug.child(1).asFloat(), + skyTintPlug.child(2).asFloat()); envDayLightSchema.CreateSkyTintAttr(VtValue(mayaSkyTint), true); } // Sun direction. - MPlug sunDirectionPlug = - depFn.findPlug(_tokens->SunDirectionPlugName.GetText(), &status); + MPlug sunDirectionPlug = depFn.findPlug(_tokens->SunDirectionPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } if (UsdMayaUtil::IsAuthored(sunDirectionPlug)) { - const GfVec3f mayaSunDirection(sunDirectionPlug.child(0).asFloat(), - sunDirectionPlug.child(1).asFloat(), - sunDirectionPlug.child(2).asFloat()); + const GfVec3f mayaSunDirection( + sunDirectionPlug.child(0).asFloat(), + sunDirectionPlug.child(1).asFloat(), + sunDirectionPlug.child(2).asFloat()); envDayLightSchema.CreateSunDirectionAttr(VtValue(mayaSunDirection), true); } // Sun size. - MPlug sunSizePlug = - depFn.findPlug(_tokens->SunSizePlugName.GetText(), &status); + MPlug sunSizePlug = depFn.findPlug(_tokens->SunSizePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1058,16 +932,16 @@ _WriteEnvDayLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // Sun tint. - MPlug sunTintPlug = - depFn.findPlug(_tokens->SunTintPlugName.GetText(), &status); + MPlug sunTintPlug = depFn.findPlug(_tokens->SunTintPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } if (UsdMayaUtil::IsAuthored(sunTintPlug)) { - const GfVec3f mayaSunTint(sunTintPlug.child(0).asFloat(), - sunTintPlug.child(1).asFloat(), - sunTintPlug.child(2).asFloat()); + const GfVec3f mayaSunTint( + sunTintPlug.child(0).asFloat(), + sunTintPlug.child(1).asFloat(), + sunTintPlug.child(2).asFloat()); envDayLightSchema.CreateSunTintAttr(VtValue(mayaSunTint), true); } @@ -1107,9 +981,7 @@ _WriteEnvDayLight(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return true; } -static -bool -_ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { const UsdRiPxrEnvDayLight envDayLightSchema(lightSchema); if (!envDayLightSchema) { @@ -1119,8 +991,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) MStatus status; // Day. - MPlug lightDayPlug = - depFn.findPlug(_tokens->DayPlugName.GetText(), &status); + MPlug lightDayPlug = depFn.findPlug(_tokens->DayPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1134,8 +1005,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Haziness. - MPlug lightHazinessPlug = - depFn.findPlug(_tokens->HazinessPlugName.GetText(), &status); + MPlug lightHazinessPlug = depFn.findPlug(_tokens->HazinessPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1149,8 +1019,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Hour. - MPlug lightHourPlug = - depFn.findPlug(_tokens->HourPlugName.GetText(), &status); + MPlug lightHourPlug = depFn.findPlug(_tokens->HourPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1164,8 +1033,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Latitude. - MPlug lightLatitudePlug = - depFn.findPlug(_tokens->LatitudePlugName.GetText(), &status); + MPlug lightLatitudePlug = depFn.findPlug(_tokens->LatitudePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1179,8 +1047,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Longitude. - MPlug lightLongitudePlug = - depFn.findPlug(_tokens->LongitudePlugName.GetText(), &status); + MPlug lightLongitudePlug = depFn.findPlug(_tokens->LongitudePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1194,8 +1061,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Month. - MPlug lightMonthPlug = - depFn.findPlug(_tokens->MonthPlugName.GetText(), &status); + MPlug lightMonthPlug = depFn.findPlug(_tokens->MonthPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1209,8 +1075,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Sky tint. - MPlug lightSkyTintPlug = - depFn.findPlug(_tokens->SkyTintPlugName.GetText(), &status); + MPlug lightSkyTintPlug = depFn.findPlug(_tokens->SkyTintPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1226,8 +1091,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Sun direction. - MPlug lightSunDirectionPlug = - depFn.findPlug(_tokens->SunDirectionPlugName.GetText(), &status); + MPlug lightSunDirectionPlug = depFn.findPlug(_tokens->SunDirectionPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1243,8 +1107,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Sun size. - MPlug lightSunSizePlug = - depFn.findPlug(_tokens->SunSizePlugName.GetText(), &status); + MPlug lightSunSizePlug = depFn.findPlug(_tokens->SunSizePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1258,8 +1121,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Sun tint. - MPlug lightSunTintPlug = - depFn.findPlug(_tokens->SunTintPlugName.GetText(), &status); + MPlug lightSunTintPlug = depFn.findPlug(_tokens->SunTintPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1275,8 +1137,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Year. - MPlug lightYearPlug = - depFn.findPlug(_tokens->YearPlugName.GetText(), &status); + MPlug lightYearPlug = depFn.findPlug(_tokens->YearPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1290,8 +1151,7 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Zone. - MPlug lightZonePlug = - depFn.findPlug(_tokens->ZonePlugName.GetText(), &status); + MPlug lightZonePlug = depFn.findPlug(_tokens->ZonePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1303,16 +1163,12 @@ _ReadEnvDayLight(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return status == MS::kSuccess; } - // SHAPING API -static -bool -_WriteLightShapingAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) +static bool _WriteLightShapingAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { - UsdLuxShapingAPI shapingAPI = - UsdMayaTranslatorUtil::GetAPISchemaForAuthoring( - lightSchema.GetPrim()); + UsdLuxShapingAPI shapingAPI + = UsdMayaTranslatorUtil::GetAPISchemaForAuthoring(lightSchema.GetPrim()); if (!shapingAPI) { return false; } @@ -1320,8 +1176,7 @@ _WriteLightShapingAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) MStatus status; // Focus. - MPlug lightFocusPlug = - depFn.findPlug(_tokens->FocusPlugName.GetText(), &status); + MPlug lightFocusPlug = depFn.findPlug(_tokens->FocusPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1337,23 +1192,22 @@ _WriteLightShapingAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } // Focus Tint. - MPlug lightFocusTintPlug = - depFn.findPlug(_tokens->FocusTintPlugName.GetText(), &status); + MPlug lightFocusTintPlug = depFn.findPlug(_tokens->FocusTintPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } if (UsdMayaUtil::IsAuthored(lightFocusTintPlug)) { - const GfVec3f lightFocusTint(lightFocusTintPlug.child(0).asFloat(), - lightFocusTintPlug.child(1).asFloat(), - lightFocusTintPlug.child(2).asFloat()); + const GfVec3f lightFocusTint( + lightFocusTintPlug.child(0).asFloat(), + lightFocusTintPlug.child(1).asFloat(), + lightFocusTintPlug.child(2).asFloat()); shapingAPI.CreateShapingFocusTintAttr(VtValue(lightFocusTint), true); } // Cone Angle. - MPlug lightConeAnglePlug = - depFn.findPlug(_tokens->ConeAnglePlugName.GetText(), &status); + MPlug lightConeAnglePlug = depFn.findPlug(_tokens->ConeAnglePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1365,13 +1219,11 @@ _WriteLightShapingAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return false; } - shapingAPI.CreateShapingConeAngleAttr(VtValue(mayaLightConeAngle), - true); + shapingAPI.CreateShapingConeAngleAttr(VtValue(mayaLightConeAngle), true); } // Cone Softness. - MPlug lightConeSoftnessPlug = - depFn.findPlug(_tokens->ConeSoftnessPlugName.GetText(), &status); + MPlug lightConeSoftnessPlug = depFn.findPlug(_tokens->ConeSoftnessPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1383,13 +1235,11 @@ _WriteLightShapingAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return false; } - shapingAPI.CreateShapingConeSoftnessAttr(VtValue(mayaLightConeSoftness), - true); + shapingAPI.CreateShapingConeSoftnessAttr(VtValue(mayaLightConeSoftness), true); } // Profile File. - MPlug lightProfileFilePlug = - depFn.findPlug(_tokens->ProfileFilePlugName.GetText(), &status); + MPlug lightProfileFilePlug = depFn.findPlug(_tokens->ProfileFilePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1402,16 +1252,13 @@ _WriteLightShapingAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) } if (mayaLightProfileFile.numChars() > 0u) { - const SdfAssetPath lightProfileAssetPath( - mayaLightProfileFile.asChar()); - shapingAPI.CreateShapingIesFileAttr(VtValue(lightProfileAssetPath), - true); + const SdfAssetPath lightProfileAssetPath(mayaLightProfileFile.asChar()); + shapingAPI.CreateShapingIesFileAttr(VtValue(lightProfileAssetPath), true); } } // Profile Scale. - MPlug lightProfileScalePlug = - depFn.findPlug(_tokens->ProfileScalePlugName.GetText(), &status); + MPlug lightProfileScalePlug = depFn.findPlug(_tokens->ProfileScalePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1423,16 +1270,13 @@ _WriteLightShapingAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return false; } - shapingAPI.CreateShapingIesAngleScaleAttr(VtValue(mayaLightProfileScale), - true); + shapingAPI.CreateShapingIesAngleScaleAttr(VtValue(mayaLightProfileScale), true); } return true; } -static -bool -_ReadLightShapingAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadLightShapingAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { const UsdLuxShapingAPI shapingAPI(lightSchema); if (!shapingAPI) { @@ -1442,8 +1286,7 @@ _ReadLightShapingAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) MStatus status; // Focus. - MPlug lightFocusPlug = - depFn.findPlug(_tokens->FocusPlugName.GetText(), &status); + MPlug lightFocusPlug = depFn.findPlug(_tokens->FocusPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1457,8 +1300,7 @@ _ReadLightShapingAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Focus Tint. - MPlug lightFocusTintPlug = - depFn.findPlug(_tokens->FocusTintPlugName.GetText(), &status); + MPlug lightFocusTintPlug = depFn.findPlug(_tokens->FocusTintPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1474,8 +1316,7 @@ _ReadLightShapingAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Cone Angle. - MPlug lightConeAnglePlug = - depFn.findPlug(_tokens->ConeAnglePlugName.GetText(), &status); + MPlug lightConeAnglePlug = depFn.findPlug(_tokens->ConeAnglePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1489,8 +1330,7 @@ _ReadLightShapingAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Cone Softness. - MPlug lightConeSoftnessPlug = - depFn.findPlug(_tokens->ConeSoftnessPlugName.GetText(), &status); + MPlug lightConeSoftnessPlug = depFn.findPlug(_tokens->ConeSoftnessPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1504,8 +1344,7 @@ _ReadLightShapingAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Profile File. - MPlug lightProfileFilePlug = - depFn.findPlug(_tokens->ProfileFilePlugName.GetText(), &status); + MPlug lightProfileFilePlug = depFn.findPlug(_tokens->ProfileFilePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1520,8 +1359,7 @@ _ReadLightShapingAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Profile Scale. - MPlug lightProfileScalePlug = - depFn.findPlug(_tokens->ProfileScalePlugName.GetText(), &status); + MPlug lightProfileScalePlug = depFn.findPlug(_tokens->ProfileScalePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1533,16 +1371,12 @@ _ReadLightShapingAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return status == MS::kSuccess; } - // SHADOW API -static -bool -_WriteLightShadowAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) +static bool _WriteLightShadowAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) { - UsdLuxShadowAPI shadowAPI = - UsdMayaTranslatorUtil::GetAPISchemaForAuthoring( - lightSchema.GetPrim()); + UsdLuxShadowAPI shadowAPI + = UsdMayaTranslatorUtil::GetAPISchemaForAuthoring(lightSchema.GetPrim()); if (!shadowAPI) { return false; } @@ -1550,8 +1384,8 @@ _WriteLightShadowAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) MStatus status; // Enable Shadows. - MPlug lightEnableShadowsPlug = - depFn.findPlug(_tokens->EnableShadowsPlugName.GetText(), &status); + MPlug lightEnableShadowsPlug + = depFn.findPlug(_tokens->EnableShadowsPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1573,23 +1407,23 @@ _WriteLightShadowAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) // XXX: Not yet implemented. // Shadow Color. - MPlug lightShadowColorPlug = - depFn.findPlug(_tokens->ShadowColorPlugName.GetText(), &status); + MPlug lightShadowColorPlug = depFn.findPlug(_tokens->ShadowColorPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } if (UsdMayaUtil::IsAuthored(lightShadowColorPlug)) { - const GfVec3f lightShadowColor(lightShadowColorPlug.child(0).asFloat(), - lightShadowColorPlug.child(1).asFloat(), - lightShadowColorPlug.child(2).asFloat()); + const GfVec3f lightShadowColor( + lightShadowColorPlug.child(0).asFloat(), + lightShadowColorPlug.child(1).asFloat(), + lightShadowColorPlug.child(2).asFloat()); shadowAPI.CreateShadowColorAttr(VtValue(lightShadowColor), true); } // Shadow Distance. - MPlug lightShadowDistancePlug = - depFn.findPlug(_tokens->ShadowDistancePlugName.GetText(), &status); + MPlug lightShadowDistancePlug + = depFn.findPlug(_tokens->ShadowDistancePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1601,13 +1435,12 @@ _WriteLightShadowAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return false; } - shadowAPI.CreateShadowDistanceAttr(VtValue(mayaLightShadowDistance), - true); + shadowAPI.CreateShadowDistanceAttr(VtValue(mayaLightShadowDistance), true); } // Shadow Falloff. - MPlug lightShadowFalloffPlug = - depFn.findPlug(_tokens->ShadowFalloffPlugName.GetText(), &status); + MPlug lightShadowFalloffPlug + = depFn.findPlug(_tokens->ShadowFalloffPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1619,36 +1452,30 @@ _WriteLightShadowAPI(const MFnDependencyNode& depFn, UsdLuxLight& lightSchema) return false; } - shadowAPI.CreateShadowFalloffAttr(VtValue(mayaLightShadowFalloff), - true); + shadowAPI.CreateShadowFalloffAttr(VtValue(mayaLightShadowFalloff), true); } // Shadow Falloff Gamma. - MPlug lightShadowFalloffGammaPlug = - depFn.findPlug(_tokens->ShadowFalloffGammaPlugName.GetText(), &status); + MPlug lightShadowFalloffGammaPlug + = depFn.findPlug(_tokens->ShadowFalloffGammaPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } if (UsdMayaUtil::IsAuthored(lightShadowFalloffGammaPlug)) { float mayaLightShadowFalloffGamma = 1.0f; - status = - lightShadowFalloffGammaPlug.getValue(mayaLightShadowFalloffGamma); + status = lightShadowFalloffGammaPlug.getValue(mayaLightShadowFalloffGamma); if (status != MS::kSuccess) { return false; } - shadowAPI.CreateShadowFalloffGammaAttr( - VtValue(mayaLightShadowFalloffGamma), - true); + shadowAPI.CreateShadowFalloffGammaAttr(VtValue(mayaLightShadowFalloffGamma), true); } return true; } -static -bool -_ReadLightShadowAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) +static bool _ReadLightShadowAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) { const UsdLuxShadowAPI shadowAPI(lightSchema); if (!shadowAPI) { @@ -1658,8 +1485,8 @@ _ReadLightShadowAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) MStatus status; // Enable Shadows. - MPlug lightEnableShadowsPlug = - depFn.findPlug(_tokens->EnableShadowsPlugName.GetText(), &status); + MPlug lightEnableShadowsPlug + = depFn.findPlug(_tokens->EnableShadowsPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1679,8 +1506,7 @@ _ReadLightShadowAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) // XXX: Not yet implemented. // Shadow Color. - MPlug lightShadowColorPlug = - depFn.findPlug(_tokens->ShadowColorPlugName.GetText(), &status); + MPlug lightShadowColorPlug = depFn.findPlug(_tokens->ShadowColorPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1696,8 +1522,8 @@ _ReadLightShadowAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Shadow Distance. - MPlug lightShadowDistancePlug = - depFn.findPlug(_tokens->ShadowDistancePlugName.GetText(), &status); + MPlug lightShadowDistancePlug + = depFn.findPlug(_tokens->ShadowDistancePlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1711,8 +1537,8 @@ _ReadLightShadowAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Shadow Falloff. - MPlug lightShadowFalloffPlug = - depFn.findPlug(_tokens->ShadowFalloffPlugName.GetText(), &status); + MPlug lightShadowFalloffPlug + = depFn.findPlug(_tokens->ShadowFalloffPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1726,8 +1552,8 @@ _ReadLightShadowAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) } // Shadow Falloff Gamma. - MPlug lightShadowFalloffGammaPlug = - depFn.findPlug(_tokens->ShadowFalloffGammaPlugName.GetText(), &status); + MPlug lightShadowFalloffGammaPlug + = depFn.findPlug(_tokens->ShadowFalloffGammaPlugName.GetText(), &status); if (status != MS::kSuccess) { return false; } @@ -1739,19 +1565,15 @@ _ReadLightShadowAPI(const UsdLuxLight& lightSchema, MFnDependencyNode& depFn) return status == MS::kSuccess; } - -static -UsdLuxLight -_DefineUsdLuxLightForMayaLight( - const MFnDependencyNode& depFn, - UsdMayaPrimWriterContext* context) +static UsdLuxLight +_DefineUsdLuxLightForMayaLight(const MFnDependencyNode& depFn, UsdMayaPrimWriterContext* context) { UsdLuxLight lightSchema; UsdStageRefPtr stage = context->GetUsdStage(); const SdfPath& authorPath = context->GetAuthorPath(); - MStatus status; + MStatus status; const MString mayaLightTypeName = depFn.typeName(&status); if (status != MS::kSuccess) { _ReportError("Failed to get Maya light type name", authorPath); @@ -1779,23 +1601,21 @@ _DefineUsdLuxLightForMayaLight( } else if (mayaLightTypeToken == _tokens->SphereLightMayaTypeName) { lightSchema = UsdLuxSphereLight::Define(stage, authorPath); } else { - _ReportError("Could not determine UsdLux schema for Maya light", - authorPath); + _ReportError("Could not determine UsdLux schema for Maya light", authorPath); } return lightSchema; } /* static */ -bool -UsdMayaTranslatorRfMLight::Write( - const UsdMayaPrimWriterArgs& args, - UsdMayaPrimWriterContext* context) +bool UsdMayaTranslatorRfMLight::Write( + const UsdMayaPrimWriterArgs& args, + UsdMayaPrimWriterContext* context) { const SdfPath& authorPath = context->GetAuthorPath(); - MStatus status; - const MObject& lightObj = args.GetMObject(); + MStatus status; + const MObject& lightObj = args.GetMObject(); const MFnDependencyNode depFn(lightObj, &status); if (status != MS::kSuccess) { return _ReportError("Failed to get Maya light", authorPath); @@ -1833,10 +1653,7 @@ UsdMayaTranslatorRfMLight::Write( return true; } - -static -TfToken -_GetMayaTypeTokenForUsdLuxLight(const UsdLuxLight& lightSchema) +static TfToken _GetMayaTypeTokenForUsdLuxLight(const UsdLuxLight& lightSchema) { const UsdPrim& lightPrim = lightSchema.GetPrim(); @@ -1864,10 +1681,9 @@ _GetMayaTypeTokenForUsdLuxLight(const UsdLuxLight& lightSchema) } /* static */ -bool -UsdMayaTranslatorRfMLight::Read( - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context) +bool UsdMayaTranslatorRfMLight::Read( + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context) { const UsdPrim& usdPrim = args.GetUsdPrim(); if (!usdPrim) { @@ -1876,36 +1692,25 @@ UsdMayaTranslatorRfMLight::Read( const UsdLuxLight lightSchema(usdPrim); if (!lightSchema) { - return _ReportError("Failed to read UsdLuxLight prim", - usdPrim.GetPath()); + return _ReportError("Failed to read UsdLuxLight prim", usdPrim.GetPath()); } - const TfToken mayaLightTypeToken = - _GetMayaTypeTokenForUsdLuxLight(lightSchema); + const TfToken mayaLightTypeToken = _GetMayaTypeTokenForUsdLuxLight(lightSchema); if (mayaLightTypeToken.IsEmpty()) { return _ReportError( - "Could not determine Maya light type for UsdLuxLight prim", - lightSchema.GetPath()); + "Could not determine Maya light type for UsdLuxLight prim", lightSchema.GetPath()); } - MObject parentNode = - context->GetMayaNode(lightSchema.GetPath().GetParentPath(), false); + MObject parentNode = context->GetMayaNode(lightSchema.GetPath().GetParentPath(), false); MStatus status; MObject mayaNodeTransformObj; if (!UsdMayaTranslatorUtil::CreateTransformNode( - usdPrim, - parentNode, - args, - context, - &status, - &mayaNodeTransformObj)) { - return _ReportError("Failed to create transform node", - lightSchema.GetPath()); + usdPrim, parentNode, args, context, &status, &mayaNodeTransformObj)) { + return _ReportError("Failed to create transform node", lightSchema.GetPath()); } - const MString nodeName = - TfStringPrintf("%sShape", usdPrim.GetName().GetText()).c_str(); + const MString nodeName = TfStringPrintf("%sShape", usdPrim.GetName().GetText()).c_str(); MObject lightObj; if (!UsdMayaTranslatorUtil::CreateShaderNode( @@ -1915,13 +1720,13 @@ UsdMayaTranslatorRfMLight::Read( &status, &lightObj, mayaNodeTransformObj)) { - return _ReportError(TfStringPrintf("Failed to create %s node", - mayaLightTypeToken.GetText()), - lightSchema.GetPath()); + return _ReportError( + TfStringPrintf("Failed to create %s node", mayaLightTypeToken.GetText()), + lightSchema.GetPath()); } - const std::string nodePath = lightSchema.GetPath().AppendChild( - TfToken(nodeName.asChar())).GetString(); + const std::string nodePath + = lightSchema.GetPath().AppendChild(TfToken(nodeName.asChar())).GetString(); context->RegisterNewMayaNode(nodePath, lightObj); MFnDependencyNode depFn(lightObj, &status); @@ -1956,5 +1761,4 @@ UsdMayaTranslatorRfMLight::Read( return true; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/translators/translatorRfMLight.h b/lib/mayaUsd/fileio/translators/translatorRfMLight.h index fc0e8f0601..41a1eccc61 100644 --- a/lib/mayaUsd/fileio/translators/translatorRfMLight.h +++ b/lib/mayaUsd/fileio/translators/translatorRfMLight.h @@ -16,14 +16,14 @@ #ifndef PXRUSDMAYA_TRANSLATOR_RFM_LIGHT_H #define PXRUSDMAYA_TRANSLATOR_RFM_LIGHT_H -#include - #include #include #include #include #include +#include + PXR_NAMESPACE_OPEN_SCOPE struct UsdMayaTranslatorRfMLight @@ -33,21 +33,15 @@ struct UsdMayaTranslatorRfMLight /// /// Returns true if this succeeds in creating a UsdLux schema prim. MAYAUSD_CORE_PUBLIC - static bool Write( - const UsdMayaPrimWriterArgs& args, - UsdMayaPrimWriterContext* context); + static bool Write(const UsdMayaPrimWriterArgs& args, UsdMayaPrimWriterContext* context); /// Imports a UsdLux schema prim as a RenderMan for Maya light. /// /// Returns true if this succeeds in creating a RenderMan for Maya light. MAYAUSD_CORE_PUBLIC - static bool Read( - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context); + static bool Read(const UsdMayaPrimReaderArgs& args, UsdMayaPrimReaderContext* context); }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/translators/translatorSkel.cpp b/lib/mayaUsd/fileio/translators/translatorSkel.cpp index fb7d27123f..0ef91b6d10 100644 --- a/lib/mayaUsd/fileio/translators/translatorSkel.cpp +++ b/lib/mayaUsd/fileio/translators/translatorSkel.cpp @@ -15,6 +15,10 @@ // #include "translatorSkel.h" +#include +#include +#include + #include #include #include @@ -22,9 +26,9 @@ #include #include -#include -#include #include +#include +#include #include #include #include @@ -39,10 +43,6 @@ #include #include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE // There are a lot of nodes and connections that go into a basic skinning rig. @@ -105,81 +105,70 @@ PXR_NAMESPACE_OPEN_SCOPE // set skinCluster.bindPreMatrix[i] to the inverse of the skel-space // transform of joint i - namespace { +TF_DEFINE_PRIVATE_TOKENS(_tokens, (Animation)(bindPose)(Maya)(generated)(Skeleton)); -TF_DEFINE_PRIVATE_TOKENS( - _tokens, - (Animation) - (bindPose) - (Maya) - (generated) - (Skeleton) -); - - -struct _MayaTokensData { +struct _MayaTokensData +{ // Types - const MString dagPoseType{"dagPose"}; - const MString groupIdType{"groupId"}; - const MString groupPartsType{"groupParts"}; - const MString jointType{"joint"}; - const MString meshType{"mesh"}; - const MString skinClusterType{"skinCluster"}; + const MString dagPoseType { "dagPose" }; + const MString groupIdType { "groupId" }; + const MString groupPartsType { "groupParts" }; + const MString jointType { "joint" }; + const MString meshType { "mesh" }; + const MString skinClusterType { "skinCluster" }; // Plugs, etc. - const MString bindPose{"bindPose"}; - const MString bindPreMatrix{"bindPreMatrix"}; - const MString drawStyle{"drawStyle"}; - const MString geomMatrix{"geomMatrix"}; - const MString groupId{"groupId"}; - const MString inheritsTransform{"inheritsTransform"}; - const MString inputComponents{"inputComponents"}; - const MString input{"input"}; - const MString inputGeometry{"inputGeometry"}; - const MString inMesh{"inMesh"}; - const MString intermediateObject{"intermediateObject"}; - const MString instObjGroups{"instObjGroups"}; - const MString USD_isUsdSkeleton{"USD_isUsdSkeleton"}; - const MString matrix{"matrix"}; - const MString members{"members"}; - const MString message{"message"}; - const MString none{"none"}; - const MString normalizeWeights{"normalizeWeights"}; - const MString objectGroups{"objectGroups"}; - const MString objectGroupId{"objectGroupId"}; - const MString outputGeometry{"outputGeometry"}; - const MString outMesh{"outMesh"}; - const MString parents{"parents"}; - const MString radius{"radius"}; - const MString segmentScaleCompensate{"segmentScaleCompensate"}; - const MString skinClusterGroupId{"skinClusterGroupId"}; - const MString skinClusterGroupParts{"skinClusterGroupParts"}; - const MString Skeleton{"Skeleton"}; - const MString weightList{"weightList"}; - const MString world{"world"}; - const MString worldMatrix{"worldMatrix"}; - const MString xformMatrix{"xformMatrix"}; + const MString bindPose { "bindPose" }; + const MString bindPreMatrix { "bindPreMatrix" }; + const MString drawStyle { "drawStyle" }; + const MString geomMatrix { "geomMatrix" }; + const MString groupId { "groupId" }; + const MString inheritsTransform { "inheritsTransform" }; + const MString inputComponents { "inputComponents" }; + const MString input { "input" }; + const MString inputGeometry { "inputGeometry" }; + const MString inMesh { "inMesh" }; + const MString intermediateObject { "intermediateObject" }; + const MString instObjGroups { "instObjGroups" }; + const MString USD_isUsdSkeleton { "USD_isUsdSkeleton" }; + const MString matrix { "matrix" }; + const MString members { "members" }; + const MString message { "message" }; + const MString none { "none" }; + const MString normalizeWeights { "normalizeWeights" }; + const MString objectGroups { "objectGroups" }; + const MString objectGroupId { "objectGroupId" }; + const MString outputGeometry { "outputGeometry" }; + const MString outMesh { "outMesh" }; + const MString parents { "parents" }; + const MString radius { "radius" }; + const MString segmentScaleCompensate { "segmentScaleCompensate" }; + const MString skinClusterGroupId { "skinClusterGroupId" }; + const MString skinClusterGroupParts { "skinClusterGroupParts" }; + const MString Skeleton { "Skeleton" }; + const MString weightList { "weightList" }; + const MString world { "world" }; + const MString worldMatrix { "worldMatrix" }; + const MString xformMatrix { "xformMatrix" }; // Translate/rotate/scale - const MString translates[3] {"translateX","translateY","translateZ"}; - const MString rotates[3] {"rotateX","rotateY","rotateZ"}; - const MString scales[3] {"scaleX","scaleY","scaleZ"}; + const MString translates[3] { "translateX", "translateY", "translateZ" }; + const MString rotates[3] { "rotateX", "rotateY", "rotateZ" }; + const MString scales[3] { "scaleX", "scaleY", "scaleZ" }; }; - TfStaticData<_MayaTokensData> _MayaTokens; - /// Set keyframes on \p depNode using \p values keyed at \p times. -bool -_SetAnimPlugData(MFnDependencyNode& depNode, - const MString& attr, - MDoubleArray& values, - MTimeArray& times, - const UsdMayaPrimReaderContext* context) +bool _SetAnimPlugData( + MFnDependencyNode& depNode, + const MString& attr, + MDoubleArray& values, + MTimeArray& times, + const UsdMayaPrimReaderContext* context) { MStatus status; @@ -192,13 +181,13 @@ _SetAnimPlugData(MFnDependencyNode& depNode, } MFnAnimCurve animFn; - MObject animObj = animFn.create(plug, nullptr, &status); + MObject animObj = animFn.create(plug, nullptr, &status); CHECK_MSTATUS_AND_RETURN(status, false); // XXX: Why do the input arrays need to be mutable here? status = animFn.addKeys(×, &values); CHECK_MSTATUS_AND_RETURN(status, false); - + if (context) { // Register node for undo/redo context->RegisterNewMayaNode(animFn.name().asChar(), animObj); @@ -206,19 +195,17 @@ _SetAnimPlugData(MFnDependencyNode& depNode, return true; } - /// Set animation on \p transformNode. /// The \p xforms holds transforms at each time, while the \p times /// array holds the corresponding times. -bool -_SetTransformAnim(MFnDependencyNode& transformNode, - const std::vector& xforms, - MTimeArray& times, - const UsdMayaPrimReaderContext* context) +bool _SetTransformAnim( + MFnDependencyNode& transformNode, + const std::vector& xforms, + MTimeArray& times, + const UsdMayaPrimReaderContext* context) { if (xforms.size() != times.length()) { - TF_WARN("xforms size [%zu] != times size [%du].", - xforms.size(), times.length()); + TF_WARN("xforms size [%zu] != times size [%du].", xforms.size(), times.length()); return false; } if (xforms.empty()) @@ -229,29 +216,20 @@ _SetTransformAnim(MFnDependencyNode& transformNode, const unsigned int numSamples = times.length(); if (numSamples > 1) { - MDoubleArray translates[3] = { - MDoubleArray(numSamples), - MDoubleArray(numSamples), - MDoubleArray(numSamples) - }; - MDoubleArray rotates[3] = { - MDoubleArray(numSamples), - MDoubleArray(numSamples), - MDoubleArray(numSamples) - }; - MDoubleArray scales[3] = { - MDoubleArray(numSamples, 1), - MDoubleArray(numSamples, 1), - MDoubleArray(numSamples, 1) - }; + MDoubleArray translates[3] + = { MDoubleArray(numSamples), MDoubleArray(numSamples), MDoubleArray(numSamples) }; + MDoubleArray rotates[3] + = { MDoubleArray(numSamples), MDoubleArray(numSamples), MDoubleArray(numSamples) }; + MDoubleArray scales[3] = { MDoubleArray(numSamples, 1), + MDoubleArray(numSamples, 1), + MDoubleArray(numSamples, 1) }; // Decompose all transforms. for (unsigned int i = 0; i < numSamples; ++i) { const auto& xform = xforms[i]; - GfVec3d t, r, s; - if (UsdMayaTranslatorXformable::ConvertUsdMatrixToComponents( - xform, &t, &r, &s)) { - for (int c = 0 ; c < 3; ++c) { + GfVec3d t, r, s; + if (UsdMayaTranslatorXformable::ConvertUsdMatrixToComponents(xform, &t, &r, &s)) { + for (int c = 0; c < 3; ++c) { translates[c][i] = t[c]; rotates[c][i] = r[c]; scales[c][i] = s[c]; @@ -260,27 +238,23 @@ _SetTransformAnim(MFnDependencyNode& transformNode, } for (int c = 0; c < 3; ++c) { - if (!_SetAnimPlugData(transformNode, _MayaTokens->translates[c], - translates[c], times, context) || - !_SetAnimPlugData(transformNode, _MayaTokens->rotates[c], - rotates[c], times, context) || - !_SetAnimPlugData(transformNode, _MayaTokens->scales[c], - scales[c], times, context)) { + if (!_SetAnimPlugData( + transformNode, _MayaTokens->translates[c], translates[c], times, context) + || !_SetAnimPlugData( + transformNode, _MayaTokens->rotates[c], rotates[c], times, context) + || !_SetAnimPlugData( + transformNode, _MayaTokens->scales[c], scales[c], times, context)) { return false; } } } else { const auto& xform = xforms.front(); - GfVec3d t, r, s; - if (UsdMayaTranslatorXformable::ConvertUsdMatrixToComponents( - xform, &t, &r, &s)) { + GfVec3d t, r, s; + if (UsdMayaTranslatorXformable::ConvertUsdMatrixToComponents(xform, &t, &r, &s)) { for (int c = 0; c < 3; ++c) { - if (!UsdMayaUtil::setPlugValue( - transformNode, _MayaTokens->translates[c], t[c]) || - !UsdMayaUtil::setPlugValue( - transformNode, _MayaTokens->rotates[c], r[c]) || - !UsdMayaUtil::setPlugValue( - transformNode, _MayaTokens->scales[c], s[c])) { + if (!UsdMayaUtil::setPlugValue(transformNode, _MayaTokens->translates[c], t[c]) + || !UsdMayaUtil::setPlugValue(transformNode, _MayaTokens->rotates[c], r[c]) + || !UsdMayaUtil::setPlugValue(transformNode, _MayaTokens->scales[c], s[c])) { return false; } } @@ -289,11 +263,10 @@ _SetTransformAnim(MFnDependencyNode& transformNode, return true; } - -void -_GetJointAnimTimeSamples(const UsdSkelSkeletonQuery& skelQuery, - const UsdMayaPrimReaderArgs& args, - std::vector* times) +void _GetJointAnimTimeSamples( + const UsdSkelSkeletonQuery& skelQuery, + const UsdMayaPrimReaderArgs& args, + std::vector* times) { if (!args.GetTimeInterval().IsEmpty()) { if (UsdSkelAnimQuery animQuery = skelQuery.GetAnimQuery()) { @@ -302,8 +275,7 @@ _GetJointAnimTimeSamples(const UsdSkelSkeletonQuery& skelQuery, // correct to use 'GetBracketingTimeSamples'. But UsdSkel is // waiting on alternate time-querying API before providing // such queries. - animQuery.GetJointTransformTimeSamplesInInterval( - args.GetTimeInterval(), times); + animQuery.GetJointTransformTimeSamplesInInterval(args.GetTimeInterval(), times); } } if (times->empty()) { @@ -313,10 +285,8 @@ _GetJointAnimTimeSamples(const UsdSkelSkeletonQuery& skelQuery, } } - /// Get the absolute path to \p joint, within \p containerPath. -SdfPath -_GetJointPath(const SdfPath& containerPath, const TfToken& joint) +SdfPath _GetJointPath(const SdfPath& containerPath, const TfToken& joint) { SdfPath jointPath(joint); if (jointPath.IsAbsolutePath()) { @@ -328,80 +298,79 @@ _GetJointPath(const SdfPath& containerPath, const TfToken& joint) return SdfPath(); } - /// Create joint nodes for each joint in the joint order of \p skelQuery. /// If successful, \p jointNodes holds the ordered set of joint nodes. -bool -_CreateJointNodes(const UsdSkelSkeletonQuery& skelQuery, - const SdfPath& containerPath, - UsdMayaPrimReaderContext* context, - VtArray* jointNodes) +bool _CreateJointNodes( + const UsdSkelSkeletonQuery& skelQuery, + const SdfPath& containerPath, + UsdMayaPrimReaderContext* context, + VtArray* jointNodes) { MStatus status; - + VtTokenArray jointNames = skelQuery.GetJointOrder(); const size_t numJoints = jointNames.size(); jointNodes->resize(numJoints); - + // Joints are ordered so that ancestors precede descendants. // So we can iterate over joints in order and be assured that parent // joints will be created before their children. for (size_t i = 0; i < numJoints; ++i) { - + const SdfPath jointPath = _GetJointPath(containerPath, jointNames[i]); if (!jointPath.IsPrimPath()) continue; - MObject parentJoint = - context->GetMayaNode(jointPath.GetParentPath(), true); + MObject parentJoint = context->GetMayaNode(jointPath.GetParentPath(), true); if (parentJoint.isNull()) { - TF_WARN("Could not find parent node for joint <%s>.", - jointPath.GetText()); + TF_WARN("Could not find parent node for joint <%s>.", jointPath.GetText()); return false; } - if (!UsdMayaTranslatorUtil::CreateNode(jointPath, - _MayaTokens->jointType, - parentJoint, context, - &status, &(*jointNodes)[i])) { + if (!UsdMayaTranslatorUtil::CreateNode( + jointPath, + _MayaTokens->jointType, + parentJoint, + context, + &status, + &(*jointNodes)[i])) { return false; } } return true; } - /// Set the radius of joint nodes in proportion to the average length of /// each child bone. This uses the same scaling factor as UsdSkelImaging, /// with the intent of trying to maintain some consistenty in the skel /// display. But note that, whereas UsdSkelImaging produces a /// bone per (parent,child) pair, a Maya joint has its own, distinct spherical /// representation, so the imaging representations cannot be identical. -bool -_SetJointRadii(const UsdSkelSkeletonQuery& skelQuery, - const VtArray& jointNodes, - const VtMatrix4dArray& restXforms) +bool _SetJointRadii( + const UsdSkelSkeletonQuery& skelQuery, + const VtArray& jointNodes, + const VtMatrix4dArray& restXforms) { - MStatus status; + MStatus status; MFnDependencyNode jointDep; const size_t numJoints = jointNodes.size(); std::vector radii(numJoints, 1); - std::vector childCounts(numJoints, 0); + std::vector childCounts(numJoints, 0); for (size_t i = 0; i < numJoints; ++i) { const GfVec3d pivot = restXforms[i].ExtractTranslation(); int parent = skelQuery.GetTopology().GetParent(i); if (parent >= 0 && static_cast(parent) < numJoints) { GfVec3d parentPivot = restXforms[parent].ExtractTranslation(); - double length = (pivot - parentPivot).GetLength(); + double length = (pivot - parentPivot).GetLength(); // TODO: Scaling factor matches UsdSkelImaging, but should // have a common, static variable to reference. - double radius = length*0.1; + double radius = length * 0.1; radii[parent] = radius; ++childCounts[parent]; } @@ -410,10 +379,10 @@ _SetJointRadii(const UsdSkelSkeletonQuery& skelQuery, // Compute average radii for parent joints, and set resolved values. for (size_t i = 0; i < numJoints; ++i) { if (jointDep.setObject(jointNodes[i])) { - int count = childCounts[i]; + int count = childCounts[i]; double radius = 1.0; if (count > 0) { - radius = radii[i]/count; + radius = radii[i] / count; } else { int parent = skelQuery.GetTopology().GetParent(i); // Leaf joint. Use the same size as the parent joint. @@ -423,48 +392,44 @@ _SetJointRadii(const UsdSkelSkeletonQuery& skelQuery, } radii[i] = radius; - if (!UsdMayaUtil::setPlugValue( - jointDep, _MayaTokens->radius, radius)) { + if (!UsdMayaUtil::setPlugValue(jointDep, _MayaTokens->radius, radius)) { return false; } } } return true; -} - +} /// Set various rest state properties for \p jointNodes based on the /// state of the equivalent joints as defined in \p skelQuery. -bool -_CopyJointRestStatesFromSkel(const UsdSkelSkeletonQuery& skelQuery, - const VtArray& jointNodes) +bool _CopyJointRestStatesFromSkel( + const UsdSkelSkeletonQuery& skelQuery, + const VtArray& jointNodes) { const size_t numJoints = jointNodes.size(); // Compute skel-space rest xforms to store as the bindPose of each joint. VtMatrix4dArray restXforms; if (!skelQuery.ComputeJointSkelTransforms( - &restXforms, UsdTimeCode::Default(), /*atRest*/ true)) { + &restXforms, UsdTimeCode::Default(), /*atRest*/ true)) { return false; } if (!TF_VERIFY(restXforms.size() == numJoints)) return false; - MStatus status; + MStatus status; MFnDependencyNode jointDep; for (size_t i = 0; i < numJoints; ++i) { - + if (jointDep.setObject(jointNodes[i])) { - if (!UsdMayaUtil::setPlugMatrix(jointDep, _MayaTokens->bindPose, - restXforms[i])) { + if (!UsdMayaUtil::setPlugMatrix(jointDep, _MayaTokens->bindPose, restXforms[i])) { return false; } // Scale does not inherit as expected without disabling // segmentScaleCompensate - if (!UsdMayaUtil::setPlugValue( - jointDep, _MayaTokens->segmentScaleCompensate, false)) { + if (!UsdMayaUtil::setPlugValue(jointDep, _MayaTokens->segmentScaleCompensate, false)) { return false; } } @@ -474,29 +439,28 @@ _CopyJointRestStatesFromSkel(const UsdSkelSkeletonQuery& skelQuery, // objectColor,useObjectColor -- for debugging // lockInfluenceWeights // There may be other attrs required to allow joints to be repainted. - // Will revisit this as-needed. + // Will revisit this as-needed. } if (!_SetJointRadii(skelQuery, jointNodes, restXforms)) return false; - + return true; } - /// Apply joint animation, as computed from from \p skelQuery, /// onto \p jointNodes. /// If \p jointContainerIsSkeleton is true, the \p jointContainer node /// represents the Skeleton itself, and should hold the local transform /// anim of the Skeleton. Otherwise, the local transform of the Skeleton /// is concatenated onto the root joints. -bool -_CopyAnimFromSkel(const UsdSkelSkeletonQuery& skelQuery, - const MObject& jointContainer, - const VtArray& jointNodes, - bool jointContainerIsSkeleton, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context) +bool _CopyAnimFromSkel( + const UsdSkelSkeletonQuery& skelQuery, + const MObject& jointContainer, + const VtArray& jointNodes, + bool jointContainerIsSkeleton, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context) { std::vector usdTimes; _GetJointAnimTimeSamples(skelQuery, args, &usdTimes); @@ -509,7 +473,7 @@ _CopyAnimFromSkel(const UsdSkelSkeletonQuery& skelQuery, MStatus status; // Pre-sample the Skeleton's local transforms. - std::vector skelLocalXforms(usdTimes.size()); + std::vector skelLocalXforms(usdTimes.size()); UsdGeomXformable::XformQuery xfQuery(skelQuery.GetSkeleton()); for (size_t i = 0; i < usdTimes.size(); ++i) { if (!xfQuery.GetLocalTransformation(&skelLocalXforms[i], usdTimes[i])) { @@ -524,8 +488,7 @@ _CopyAnimFromSkel(const UsdSkelSkeletonQuery& skelQuery, MFnDependencyNode skelXformDep(jointContainer, &status); CHECK_MSTATUS_AND_RETURN(status, false); - if (!_SetTransformAnim(skelXformDep, skelLocalXforms, - mayaTimes, context)) { + if (!_SetTransformAnim(skelXformDep, skelLocalXforms, mayaTimes, context)) { return false; } } @@ -540,7 +503,7 @@ _CopyAnimFromSkel(const UsdSkelSkeletonQuery& skelQuery, // We do not have a node to receive the local transforms of the // Skeleton, so any local transforms on the Skeleton must be // concatened onto the root joints instead. - for (size_t j = 0; j < skelQuery.GetTopology().GetNumJoints(); ++j){ + for (size_t j = 0; j < skelQuery.GetTopology().GetNumJoints(); ++j) { if (skelQuery.GetTopology().GetParent(j) < 0) { // This is a root joint. Concat by the local skel xform. samples[i][j] *= skelLocalXforms[i]; @@ -569,41 +532,34 @@ _CopyAnimFromSkel(const UsdSkelSkeletonQuery& skelQuery, return true; } - } // namespace - /* static */ -bool -UsdMayaTranslatorSkel::IsUsdSkeleton(const MDagPath& joint) +bool UsdMayaTranslatorSkel::IsUsdSkeleton(const MDagPath& joint) { MFnDependencyNode jointDep(joint.node()); - MPlug plug = jointDep.findPlug(_MayaTokens->USD_isUsdSkeleton); + MPlug plug = jointDep.findPlug(_MayaTokens->USD_isUsdSkeleton); if (!plug.isNull()) { return plug.asBool(); } return false; } - /* static */ -bool -UsdMayaTranslatorSkel::IsSkelMayaGenerated(const UsdSkelSkeleton& skel) +bool UsdMayaTranslatorSkel::IsSkelMayaGenerated(const UsdSkelSkeleton& skel) { VtValue mayaData = skel.GetPrim().GetCustomDataByKey(_tokens->Maya); if (mayaData.IsHolding()) { const VtDictionary& mayaDict = mayaData.UncheckedGet(); - const VtValue* val = mayaDict.GetValueAtPath(_tokens->generated); + const VtValue* val = mayaDict.GetValueAtPath(_tokens->generated); if (val && val->IsHolding()) return val->UncheckedGet(); } return false; } - /* static */ -void -UsdMayaTranslatorSkel::MarkSkelAsMayaGenerated(const UsdSkelSkeleton& skel) +void UsdMayaTranslatorSkel::MarkSkelAsMayaGenerated(const UsdSkelSkeleton& skel) { VtValue mayaData = skel.GetPrim().GetCustomDataByKey(_tokens->Maya); @@ -614,21 +570,19 @@ UsdMayaTranslatorSkel::MarkSkelAsMayaGenerated(const UsdSkelSkeleton& skel) skel.GetPrim().SetCustomDataByKey(_tokens->Maya, VtValue(newDict)); } - /* static */ -bool -UsdMayaTranslatorSkel::CreateJointHierarchy( - const UsdSkelSkeletonQuery& skelQuery, - MObject& parentNode, +bool UsdMayaTranslatorSkel::CreateJointHierarchy( + const UsdSkelSkeletonQuery& skelQuery, + MObject& parentNode, const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context, - VtArray* joints) + UsdMayaPrimReaderContext* context, + VtArray* joints) { - if (!skelQuery) { + if (!skelQuery) { TF_CODING_ERROR("'skelQuery' is invalid"); return false; } - if (!joints) { + if (!joints) { TF_CODING_ERROR("'joints' is null"); return false; } @@ -636,7 +590,7 @@ UsdMayaTranslatorSkel::CreateJointHierarchy( MStatus status; SdfPath jointContainerPath; - bool jointContainerIsSkeleton = false; + bool jointContainerIsSkeleton = false; MObject jointContainer; if (IsSkelMayaGenerated(skelQuery.GetSkeleton())) { // If a joint hierarchy was originally exported from Maya, then @@ -660,8 +614,12 @@ UsdMayaTranslatorSkel::CreateJointHierarchy( // Create a joint to represent thte Skeleton. if (!UsdMayaTranslatorUtil::CreateNode( - jointContainerPath, _MayaTokens->jointType, parentNode, - context, &status, &jointContainer)) { + jointContainerPath, + _MayaTokens->jointType, + parentNode, + context, + &status, + &jointContainer)) { return false; } @@ -671,35 +629,32 @@ UsdMayaTranslatorSkel::CreateJointHierarchy( // Create an attribute to indicate to export that this joint // represents UsdSkelSkeleton's transform. MObject attrObj = MFnNumericAttribute().create( - _MayaTokens->USD_isUsdSkeleton, - _MayaTokens->USD_isUsdSkeleton, - MFnNumericData::kBoolean, - true, - &status); + _MayaTokens->USD_isUsdSkeleton, + _MayaTokens->USD_isUsdSkeleton, + MFnNumericData::kBoolean, + true, + &status); CHECK_MSTATUS_AND_RETURN(status, false); status = skelXformJointDep.addAttribute(attrObj); CHECK_MSTATUS_AND_RETURN(status, false); - UsdMayaUtil::setPlugValue( - skelXformJointDep, _MayaTokens->USD_isUsdSkeleton, true); + UsdMayaUtil::setPlugValue(skelXformJointDep, _MayaTokens->USD_isUsdSkeleton, true); // Change the draw style of the extra joints so that it is not drawn. - UsdMayaUtil::setPlugValue(skelXformJointDep, - _MayaTokens->drawStyle, 2 /*None*/); + UsdMayaUtil::setPlugValue(skelXformJointDep, _MayaTokens->drawStyle, 2 /*None*/); } - return _CreateJointNodes(skelQuery, jointContainerPath, context, joints) && - _CopyJointRestStatesFromSkel(skelQuery, *joints) && - _CopyAnimFromSkel(skelQuery, jointContainer, *joints, - jointContainerIsSkeleton, args, context); + return _CreateJointNodes(skelQuery, jointContainerPath, context, joints) + && _CopyJointRestStatesFromSkel(skelQuery, *joints) + && _CopyAnimFromSkel( + skelQuery, jointContainer, *joints, jointContainerIsSkeleton, args, context); } - -bool -UsdMayaTranslatorSkel::GetJoints(const UsdSkelSkeletonQuery& skelQuery, - UsdMayaPrimReaderContext* context, - VtArray* joints) +bool UsdMayaTranslatorSkel::GetJoints( + const UsdSkelSkeletonQuery& skelQuery, + UsdMayaPrimReaderContext* context, + VtArray* joints) { if (!skelQuery) { TF_CODING_ERROR("'skelQuery is invalid."); @@ -719,8 +674,7 @@ UsdMayaTranslatorSkel::GetJoints(const UsdSkelSkeletonQuery& skelQuery, // explanation of why there is a difference. SdfPath jointContainerPath; if (IsSkelMayaGenerated(skelQuery.GetSkeleton())) { - jointContainerPath = - skelQuery.GetSkeleton().GetPrim().GetPath().GetParentPath(); + jointContainerPath = skelQuery.GetSkeleton().GetPrim().GetPath().GetParentPath(); } else { jointContainerPath = skelQuery.GetSkeleton().GetPrim().GetPath(); } @@ -737,31 +691,27 @@ UsdMayaTranslatorSkel::GetJoints(const UsdSkelSkeletonQuery& skelQuery, return true; } - namespace { - -SdfPath -_GetBindPosePrimPath(const SdfPath& skelPath) +SdfPath _GetBindPosePrimPath(const SdfPath& skelPath) { return skelPath.AppendChild(TfToken(skelPath.GetName() + "_bindPose")); } - /// Create a dagPose node for the objects in \p members, whose transforms /// are given by \p localXforms and \p worldXforms. /// The \p parentIndices array gives the index of the parent of each member, /// or -1 if a member has no parent. -bool -_CreateDagPose(const SdfPath& path, - const VtArray& members, - const VtIntArray& parentIndices, - const VtMatrix4dArray& localXforms, - const VtMatrix4dArray& worldXforms, - UsdMayaPrimReaderContext* context, - MObject* dagPoseNode) +bool _CreateDagPose( + const SdfPath& path, + const VtArray& members, + const VtIntArray& parentIndices, + const VtMatrix4dArray& localXforms, + const VtMatrix4dArray& worldXforms, + UsdMayaPrimReaderContext* context, + MObject* dagPoseNode) { - MStatus status; + MStatus status; MDGModifier dgMod; *dagPoseNode = dgMod.createNode(_MayaTokens->dagPoseType, &status); @@ -784,14 +734,12 @@ _CreateDagPose(const SdfPath& path, MPlug worldPlug = dagPoseDep.findPlug(_MayaTokens->world, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug worldMatrixPlug = - dagPoseDep.findPlug(_MayaTokens->worldMatrix, &status); + MPlug worldMatrixPlug = dagPoseDep.findPlug(_MayaTokens->worldMatrix, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = worldMatrixPlug.setNumElements(numMembers); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug xformMatrixPlug = - dagPoseDep.findPlug(_MayaTokens->xformMatrix, &status); + MPlug xformMatrixPlug = dagPoseDep.findPlug(_MayaTokens->xformMatrix, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = xformMatrixPlug.setNumElements(numMembers); CHECK_MSTATUS_AND_RETURN(status, false); @@ -809,12 +757,10 @@ _CreateDagPose(const SdfPath& path, CHECK_MSTATUS_AND_RETURN(status, false); // Connect members[i].message -> dagPose.members[i] - MPlug memberMessagePlug = - memberDep.findPlug(_MayaTokens->message, &status); + MPlug memberMessagePlug = memberDep.findPlug(_MayaTokens->message, &status); CHECK_MSTATUS_AND_RETURN(status, false); - status = dgMod.connect(memberMessagePlug, - membersPlug.elementByLogicalIndex(i)); + status = dgMod.connect(memberMessagePlug, membersPlug.elementByLogicalIndex(i)); CHECK_MSTATUS_AND_RETURN(status, false); int parentIdx = parentIndices[i]; @@ -823,8 +769,7 @@ _CreateDagPose(const SdfPath& path, if (parentIdx >= 0 && static_cast(parentIdx) < numMembers) { // Connect dagPose.members[parent] -> dagPose.parents[child] - MPlug parentMemberPlug = - membersPlug.elementByLogicalIndex(parentIdx); + MPlug parentMemberPlug = membersPlug.elementByLogicalIndex(parentIdx); status = dgMod.connect(parentMemberPlug, parentsI); CHECK_MSTATUS_AND_RETURN(status, false); @@ -850,20 +795,16 @@ _CreateDagPose(const SdfPath& path, status = dgMod.doIt(); CHECK_MSTATUS_AND_RETURN(status, false); - return UsdMayaUtil::setPlugValue( - dagPoseDep, _MayaTokens->bindPose, true); + return UsdMayaUtil::setPlugValue(dagPoseDep, _MayaTokens->bindPose, true); } - } // namespace - -bool -UsdMayaTranslatorSkel::CreateBindPose( +bool UsdMayaTranslatorSkel::CreateBindPose( const UsdSkelSkeletonQuery& skelQuery, - const VtArray& joints, - UsdMayaPrimReaderContext* context, - MObject* bindPoseNode) + const VtArray& joints, + UsdMayaPrimReaderContext* context, + MObject* bindPoseNode) { if (!skelQuery) { TF_CODING_ERROR("'skelQuery' is invalid."); @@ -877,46 +818,49 @@ UsdMayaTranslatorSkel::CreateBindPose( VtMatrix4dArray localXforms, worldXforms; if (!skelQuery.ComputeJointLocalTransforms( &localXforms, UsdTimeCode::Default(), /*atRest*/ true)) { - TF_WARN("%s -- Failed reading rest transforms. No dagPose " - "will be created for the Skeleton.", - skelQuery.GetPrim().GetPath().GetText()); + TF_WARN( + "%s -- Failed reading rest transforms. No dagPose " + "will be created for the Skeleton.", + skelQuery.GetPrim().GetPath().GetText()); return false; } if (!skelQuery.GetJointWorldBindTransforms(&worldXforms)) { - TF_WARN("%s -- Failed reading bind transforms. No dagPose " - "will be created for the Skeleton.", - skelQuery.GetPrim().GetPath().GetText()); + TF_WARN( + "%s -- Failed reading bind transforms. No dagPose " + "will be created for the Skeleton.", + skelQuery.GetPrim().GetPath().GetText()); return false; } SdfPath path = _GetBindPosePrimPath(skelQuery.GetPrim().GetPath()); - return _CreateDagPose(path, joints, - skelQuery.GetTopology().GetParentIndices(), - localXforms, worldXforms, context, bindPoseNode); + return _CreateDagPose( + path, + joints, + skelQuery.GetTopology().GetParentIndices(), + localXforms, + worldXforms, + context, + bindPoseNode); } - -MObject -UsdMayaTranslatorSkel::GetBindPose(const UsdSkelSkeletonQuery& skelQuery, - UsdMayaPrimReaderContext* context) +MObject UsdMayaTranslatorSkel::GetBindPose( + const UsdSkelSkeletonQuery& skelQuery, + UsdMayaPrimReaderContext* context) { - return context->GetMayaNode( - _GetBindPosePrimPath(skelQuery.GetPrim().GetPath()), false); + return context->GetMayaNode(_GetBindPosePrimPath(skelQuery.GetPrim().GetPath()), false); } - namespace { - -bool -_SetVaryingJointInfluences(const MFnMesh& meshFn, - const MObject& skinCluster, - const VtArray& joints, - const VtIntArray& indices, - const VtFloatArray& weights, - int numInfluencesPerPoint, - unsigned int numPoints) +bool _SetVaryingJointInfluences( + const MFnMesh& meshFn, + const MObject& skinCluster, + const VtArray& joints, + const VtIntArray& indices, + const VtFloatArray& weights, + int numInfluencesPerPoint, + unsigned int numPoints) { if (joints.empty()) return true; @@ -934,18 +878,17 @@ _SetVaryingJointInfluences(const MFnMesh& meshFn, // Compute a vertex-ordered weight arrays. Weights are stored as: // vert_0_joint_0 ... vert_0_joint_n ... vert_n_joint_0 ... vert_n_joint_n - MDoubleArray vertOrderedWeights(numPoints*numJoints, 0.0f); + MDoubleArray vertOrderedWeights(numPoints * numJoints, 0.0f); for (unsigned int pt = 0; pt < numPoints; ++pt) { for (int c = 0; c < numInfluencesPerPoint; ++c) { - int jointIdx = indices[pt*numInfluencesPerPoint+c]; - if (jointIdx >= 0 - && static_cast(jointIdx) < numJoints) { - float w = weights[pt*numInfluencesPerPoint+c]; + int jointIdx = indices[pt * numInfluencesPerPoint + c]; + if (jointIdx >= 0 && static_cast(jointIdx) < numJoints) { + float w = weights[pt * numInfluencesPerPoint + c]; // There may be multiple influences referencing the same joint // for this point. eg., 'unweighted' points are assigned // index 0 and weight 0. Sum the weight contributions to ensure // that we properly account for this. - vertOrderedWeights[pt*numJoints + jointIdx] += w; + vertOrderedWeights[pt * numJoints + jointIdx] += w; } } } @@ -955,7 +898,7 @@ _SetVaryingJointInfluences(const MFnMesh& meshFn, influenceIndices[i] = i; } - // Set all weights in one batch + // Set all weights in one batch MFnSingleIndexedComponent components; components.create(MFn::kMeshVertComponent); components.setCompleteData(numPoints); @@ -964,18 +907,17 @@ _SetVaryingJointInfluences(const MFnMesh& meshFn, // In order to faithfully transfer our source data, we do not perform // any normalization on import. Maya's weight normalization also seems // finicky w.r.t. precision, and tends to throw warnings even when the - // weights have been properly normalized, so this also saves us from + // weights have been properly normalized, so this also saves us from // unnecessary warning spam. - + // If the 'normalizeWeights' attribute of the skinCluster is set to // 'interactive' -- and by default, it is -- then weights are still // normalized even if we set normalize=false on // MFnSkinCluster::normalize(). This fact is unfortunately not made - // clear in the MFnSkinCluster documentation... + // clear in the MFnSkinCluster documentation... // Temporarily set the attr to 'none' - MPlug normalizeWeights = - skinClusterFn.findPlug(_MayaTokens->normalizeWeights, &status); + MPlug normalizeWeights = skinClusterFn.findPlug(_MayaTokens->normalizeWeights, &status); MString initialNormalizeWeights; if (!normalizeWeights.isNull()) { initialNormalizeWeights = normalizeWeights.asString(); @@ -988,27 +930,27 @@ _SetVaryingJointInfluences(const MFnMesh& meshFn, // Apply the weights. Note that this fails with kInvalidParameter // if the influenceIndices are invalid. Validity is based on the // set of joints wired up to the skinCluster. - status = skinClusterFn.setWeights(dagPath, components.object(), - influenceIndices, vertOrderedWeights, - /*normalize*/ false); + status = skinClusterFn.setWeights( + dagPath, + components.object(), + influenceIndices, + vertOrderedWeights, + /*normalize*/ false); CHECK_MSTATUS_AND_RETURN(status, false); - // Reset the normalization flag to its previous value. if (!normalizeWeights.isNull()) { normalizeWeights.setString(initialNormalizeWeights); } - return true; } - -bool -_ComputeAndSetJointInfluences(const UsdSkelSkinningQuery& skinningQuery, - const VtArray& joints, - const MObject& skinCluster, - const MObject& shapeToSkin) +bool _ComputeAndSetJointInfluences( + const UsdSkelSkinningQuery& skinningQuery, + const VtArray& joints, + const MObject& skinCluster, + const MObject& shapeToSkin) { MStatus status; @@ -1018,55 +960,52 @@ _ComputeAndSetJointInfluences(const UsdSkelSkinningQuery& skinningQuery, unsigned int numPoints = meshFn.numVertices(&status); CHECK_MSTATUS_AND_RETURN(status, false); - VtIntArray indices; + VtIntArray indices; VtFloatArray weights; - if (skinningQuery.ComputeVaryingJointInfluences( - numPoints, &indices, &weights)) { + if (skinningQuery.ComputeVaryingJointInfluences(numPoints, &indices, &weights)) { return _SetVaryingJointInfluences( - meshFn, skinCluster, joints, indices, weights, - skinningQuery.GetNumInfluencesPerComponent(), numPoints); + meshFn, + skinCluster, + joints, + indices, + weights, + skinningQuery.GetNumInfluencesPerComponent(), + numPoints); } return false; } - /// Create a copy of mesh \p inputMesh beneath \p parent, /// for use as an input mesh for deformers. -bool -_CreateRestMesh(const MObject& inputMesh, - const MObject& parent, - MObject* restMesh) +bool _CreateRestMesh(const MObject& inputMesh, const MObject& parent, MObject* restMesh) { MStatus status; MFnMesh meshFn(inputMesh, &status); CHECK_MSTATUS_AND_RETURN(status, false); - + *restMesh = meshFn.copy(inputMesh, parent, &status); CHECK_MSTATUS_AND_RETURN(status, false); // Determine a new name for the rest mesh, and rename the copy. static const MString restSuffix("_rest"); - MString restMeshName = meshFn.name() + restSuffix; - MDGModifier dgMod; + MString restMeshName = meshFn.name() + restSuffix; + MDGModifier dgMod; status = dgMod.renameNode(*restMesh, restMeshName); CHECK_MSTATUS_AND_RETURN(status, false); status = dgMod.doIt(); CHECK_MSTATUS_AND_RETURN(status, false); - return UsdMayaUtil::setPlugValue( - *restMesh, _MayaTokens->intermediateObject, true); + return UsdMayaUtil::setPlugValue(*restMesh, _MayaTokens->intermediateObject, true); } - /// Clear any incoming connections on \p plug. -bool -_ClearIncomingConnections(MPlug& plug) +bool _ClearIncomingConnections(MPlug& plug) { MPlugArray connections; if (plug.connectedTo(connections, /*asDst*/ true, /*asSrc*/ false)) { - MStatus status; + MStatus status; MDGModifier dgMod; for (unsigned int i = 0; i < connections.length(); ++i) { status = dgMod.disconnect(plug, connections[i]); @@ -1078,32 +1017,30 @@ _ClearIncomingConnections(MPlug& plug) return true; } - /// Configure the transform node of a skinned object. -bool -_ConfigureSkinnedObjectTransform(const UsdSkelSkinningQuery& skinningQuery, - const MObject& transform) +bool _ConfigureSkinnedObjectTransform( + const UsdSkelSkinningQuery& skinningQuery, + const MObject& transform) { - MStatus status; + MStatus status; MFnDependencyNode transformDep(transform, &status); CHECK_MSTATUS_AND_RETURN(status, false); // Make sure transforms are not ineherited. // Otherwise we get a double transform when a transform ancestor // affects both this object and the joints that drive the skinned object. - if (!UsdMayaUtil::setPlugValue( - transformDep, _MayaTokens->inheritsTransform, false)) { + if (!UsdMayaUtil::setPlugValue(transformDep, _MayaTokens->inheritsTransform, false)) { return false; } // The transform needs to be set to the geomBindTransform. GfVec3d t, r, s; if (UsdMayaTranslatorXformable::ConvertUsdMatrixToComponents( - skinningQuery.GetGeomBindTransform(), &t, &r, &s)) { + skinningQuery.GetGeomBindTransform(), &t, &r, &s)) { - for (const auto& pair : {std::make_pair(t, _MayaTokens->translates), - std::make_pair(r, _MayaTokens->rotates), - std::make_pair(s, _MayaTokens->scales)}) { + for (const auto& pair : { std::make_pair(t, _MayaTokens->translates), + std::make_pair(r, _MayaTokens->rotates), + std::make_pair(s, _MayaTokens->scales) }) { for (int c = 0; c < 3; ++c) { MPlug plug = transformDep.findPlug(pair.second[c], &status); @@ -1120,24 +1057,21 @@ _ConfigureSkinnedObjectTransform(const UsdSkelSkinningQuery& skinningQuery, } } } - + return true; } - } // namespace - /* static */ -bool -UsdMayaTranslatorSkel::CreateSkinCluster( - const UsdSkelSkeletonQuery& skelQuery, - const UsdSkelSkinningQuery& skinningQuery, - const VtArray& joints, - const UsdPrim& primToSkin, +bool UsdMayaTranslatorSkel::CreateSkinCluster( + const UsdSkelSkeletonQuery& skelQuery, + const UsdSkelSkinningQuery& skinningQuery, + const VtArray& joints, + const UsdPrim& primToSkin, const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context, - const MObject& bindPose) + UsdMayaPrimReaderContext* context, + const MObject& bindPose) { MStatus status; @@ -1149,7 +1083,7 @@ UsdMayaTranslatorSkel::CreateSkinCluster( TF_CODING_ERROR("'skinningQuery is invalid"); } if (!primToSkin) { - TF_CODING_ERROR("'primToSkin 'is invalid"); + TF_CODING_ERROR("'primToSkin 'is invalid"); return false; } @@ -1168,7 +1102,7 @@ UsdMayaTranslatorSkel::CreateSkinCluster( MObject shapeToSkin = shapeDagPath.node(&status); CHECK_MSTATUS_AND_RETURN(status, false); - + if (shapeToSkin.apiType() != MFn::kMesh) { // USD considers this prim skinnable, but in Maya, we currently only // know how to skin meshes. Skip it. @@ -1183,19 +1117,17 @@ UsdMayaTranslatorSkel::CreateSkinCluster( return false; } - if (!_ConfigureSkinnedObjectTransform(skinningQuery, parentTransform)){ + if (!_ConfigureSkinnedObjectTransform(skinningQuery, parentTransform)) { return false; } MDGModifier dgMod; - MObject skinCluster = - dgMod.createNode(_MayaTokens->skinClusterType, &status); + MObject skinCluster = dgMod.createNode(_MayaTokens->skinClusterType, &status); CHECK_MSTATUS_AND_RETURN(status, false); - std::string skinClusterName = - TfStringPrintf("skinCluster_%s", primToSkin.GetName().GetText()); + std::string skinClusterName = TfStringPrintf("skinCluster_%s", primToSkin.GetName().GetText()); status = dgMod.renameNode(skinCluster, MString(skinClusterName.c_str())); - + CHECK_MSTATUS_AND_RETURN(status, false); MObject groupId = dgMod.createNode(_MayaTokens->groupIdType, &status); @@ -1232,42 +1164,38 @@ UsdMayaTranslatorSkel::CreateSkinCluster( // set groupParts.inputComponents = vtx[*] { MFnSingleIndexedComponent componentsFn; - MObject vertComponents = componentsFn.create(MFn::kMeshVertComponent); + MObject vertComponents = componentsFn.create(MFn::kMeshVertComponent); componentsFn.setComplete(true); MFnComponentListData componentListFn; - MObject componentList = componentListFn.create(); + MObject componentList = componentListFn.create(); status = componentListFn.add(vertComponents); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug inputComponentsPlug = - groupPartsDep.findPlug(_MayaTokens->inputComponents, &status); + MPlug inputComponentsPlug = groupPartsDep.findPlug(_MayaTokens->inputComponents, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = inputComponentsPlug.setValue(componentList); CHECK_MSTATUS_AND_RETURN(status, false); } - + // Connect restMesh.outMesh -> groupParts->inputGeometry { - MPlug restMeshOutMesh = - restMeshDep.findPlug(_MayaTokens->outMesh, &status); + MPlug restMeshOutMesh = restMeshDep.findPlug(_MayaTokens->outMesh, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug groupPartsInputGeometry = - groupPartsDep.findPlug(_MayaTokens->inputGeometry, &status); + MPlug groupPartsInputGeometry = groupPartsDep.findPlug(_MayaTokens->inputGeometry, &status); CHECK_MSTATUS_AND_RETURN(status, false); - + status = dgMod.connect(restMeshOutMesh, groupPartsInputGeometry); CHECK_MSTATUS_AND_RETURN(status, false); } - + MPlug groupIdGroupId = groupIdDep.findPlug(_MayaTokens->groupId, &status); CHECK_MSTATUS_AND_RETURN(status, false); // Connect groupId.groupId -> groupParts.groupId { - MPlug groupPartsGroupId = - groupPartsDep.findPlug(_MayaTokens->groupId, &status); + MPlug groupPartsGroupId = groupPartsDep.findPlug(_MayaTokens->groupId, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = dgMod.connect(groupIdGroupId, groupPartsGroupId); @@ -1277,60 +1205,50 @@ UsdMayaTranslatorSkel::CreateSkinCluster( // connect groupId.groupId -> // shapeToSkin.instObjGroups[0].objectGroups[0].objectGroupId { - MPlug instObjGroups = - shapeToSkinDep.findPlug(_MayaTokens->instObjGroups, &status); + MPlug instObjGroups = shapeToSkinDep.findPlug(_MayaTokens->instObjGroups, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug instObjGroups0 = - instObjGroups.elementByLogicalIndex(0, &status); + MPlug instObjGroups0 = instObjGroups.elementByLogicalIndex(0, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug objectGroups = - UsdMayaUtil::FindChildPlugByName(instObjGroups0, - _MayaTokens->objectGroups); - //number of objectGroups + MPlug objectGroups + = UsdMayaUtil::FindChildPlugByName(instObjGroups0, _MayaTokens->objectGroups); + // number of objectGroups unsigned int count = objectGroups.numElements(); - MPlug objectGroups0 = - objectGroups.elementByLogicalIndex(count, &status); + MPlug objectGroups0 = objectGroups.elementByLogicalIndex(count, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug objectGroupId = - UsdMayaUtil::FindChildPlugByName(objectGroups0, - _MayaTokens->objectGroupId); - + MPlug objectGroupId + = UsdMayaUtil::FindChildPlugByName(objectGroups0, _MayaTokens->objectGroupId); + status = dgMod.connect(groupIdGroupId, objectGroupId); } - MPlug skinClusterInput = - skinClusterDep.findPlug(_MayaTokens->input, &status); + MPlug skinClusterInput = skinClusterDep.findPlug(_MayaTokens->input, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = skinClusterInput.setNumElements(1); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug skinClusterInput0 = - skinClusterInput.elementByLogicalIndex(0, &status); + MPlug skinClusterInput0 = skinClusterInput.elementByLogicalIndex(0, &status); CHECK_MSTATUS_AND_RETURN(status, false); // groupParts.outputGeometry -> skinCluster.input[0].inputGeometry { - MPlug skinClusterInputGeometry = - UsdMayaUtil::FindChildPlugByName(skinClusterInput0, - _MayaTokens->inputGeometry); + MPlug skinClusterInputGeometry + = UsdMayaUtil::FindChildPlugByName(skinClusterInput0, _MayaTokens->inputGeometry); - MPlug groupPartsOutputGeometry = - groupPartsDep.findPlug(_MayaTokens->outputGeometry, &status); + MPlug groupPartsOutputGeometry + = groupPartsDep.findPlug(_MayaTokens->outputGeometry, &status); CHECK_MSTATUS_AND_RETURN(status, false); - status = dgMod.connect(groupPartsOutputGeometry, - skinClusterInputGeometry); + status = dgMod.connect(groupPartsOutputGeometry, skinClusterInputGeometry); CHECK_MSTATUS_AND_RETURN(status, false); } // Connect groupId.groupId -> skinCluster.input[0].groupId { - MPlug skinClusterGroupId = - UsdMayaUtil::FindChildPlugByName(skinClusterInput0, - _MayaTokens->groupId); + MPlug skinClusterGroupId + = UsdMayaUtil::FindChildPlugByName(skinClusterInput0, _MayaTokens->groupId); status = dgMod.connect(groupIdGroupId, skinClusterGroupId); CHECK_MSTATUS_AND_RETURN(status, false); @@ -1338,22 +1256,21 @@ UsdMayaTranslatorSkel::CreateSkinCluster( // Connect skinCluster.outputGeometry[0] -> shapeToSkin.inMesh { - MPlug skinClusterOutputGeometry = - skinClusterDep.findPlug(_MayaTokens->outputGeometry, &status); + MPlug skinClusterOutputGeometry + = skinClusterDep.findPlug(_MayaTokens->outputGeometry, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug skinClusterOutputGeometry0 = - skinClusterOutputGeometry.elementByLogicalIndex(0, &status); + MPlug skinClusterOutputGeometry0 + = skinClusterOutputGeometry.elementByLogicalIndex(0, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug shapeToSkinInMesh = - shapeToSkinDep.findPlug(_MayaTokens->inMesh, &status); + MPlug shapeToSkinInMesh = shapeToSkinDep.findPlug(_MayaTokens->inMesh, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = dgMod.connect(skinClusterOutputGeometry0, shapeToSkinInMesh); CHECK_MSTATUS_AND_RETURN(status, false); } - + // Connect joints[i].worldMatrix[0] -> skinCluster.matrix[i] // Set skinCluster.bindPreMatrix[i] = inv(jointWorldBindXforms[i]) { @@ -1362,35 +1279,36 @@ UsdMayaTranslatorSkel::CreateSkinCluster( return false; } VtMatrix4dArray remappedBindXforms; - const auto& mapper = skinningQuery.GetMapper(); + const auto& mapper = skinningQuery.GetMapper(); if (mapper && !mapper->IsNull()) { if (mapper->IsSparse()) { - TF_WARN("Error - not all joints for the skinned object %s could " - "be found in the skeleton %s", - primToSkin.GetPath().GetText(), - skelQuery.GetPrim().GetPath().GetText()); + TF_WARN( + "Error - not all joints for the skinned object %s could " + "be found in the skeleton %s", + primToSkin.GetPath().GetText(), + skelQuery.GetPrim().GetPath().GetText()); return false; } mapper->RemapTransforms(bindXforms, &remappedBindXforms); } if (joints.size() > bindXforms.size()) { - TF_WARN("Error - skinned object (%s) had more joints (%lu) " - "than the skeleton (%s) had bind xforms (%lu)", - primToSkin.GetPath().GetText(), joints.size(), - skelQuery.GetPrim().GetPath().GetText(), - bindXforms.size()); + TF_WARN( + "Error - skinned object (%s) had more joints (%lu) " + "than the skeleton (%s) had bind xforms (%lu)", + primToSkin.GetPath().GetText(), + joints.size(), + skelQuery.GetPrim().GetPath().GetText(), + bindXforms.size()); return false; } - MPlug skinClusterMatrix = - skinClusterDep.findPlug(_MayaTokens->matrix, &status); + MPlug skinClusterMatrix = skinClusterDep.findPlug(_MayaTokens->matrix, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = skinClusterMatrix.setNumElements(joints.size()); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug bindPreMatrix = - skinClusterDep.findPlug(_MayaTokens->bindPreMatrix, &status); + MPlug bindPreMatrix = skinClusterDep.findPlug(_MayaTokens->bindPreMatrix, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = bindPreMatrix.setNumElements(joints.size()); CHECK_MSTATUS_AND_RETURN(status, false); @@ -1400,28 +1318,23 @@ UsdMayaTranslatorSkel::CreateSkinCluster( status = jointDep.setObject(joints[i]); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug jointWorldMatrix = - jointDep.findPlug(_MayaTokens->worldMatrix); + MPlug jointWorldMatrix = jointDep.findPlug(_MayaTokens->worldMatrix); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug jointWorldMatrix0 = - jointWorldMatrix.elementByLogicalIndex(0, &status); + MPlug jointWorldMatrix0 = jointWorldMatrix.elementByLogicalIndex(0, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug skinClusterMatrixI = - skinClusterMatrix.elementByLogicalIndex(i, &status); + MPlug skinClusterMatrixI = skinClusterMatrix.elementByLogicalIndex(i, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = dgMod.connect(jointWorldMatrix0, skinClusterMatrixI); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug bindPreMatrixI = - bindPreMatrix.elementByLogicalIndex(i, &status); + MPlug bindPreMatrixI = bindPreMatrix.elementByLogicalIndex(i, &status); CHECK_MSTATUS_AND_RETURN(status, false); - const auto& bindXform = remappedBindXforms.size() > 0 ? - remappedBindXforms[i] : bindXforms[i]; - if (!UsdMayaUtil::setPlugMatrix( - bindXform.GetInverse(), bindPreMatrixI)) { + const auto& bindXform + = remappedBindXforms.size() > 0 ? remappedBindXforms[i] : bindXforms[i]; + if (!UsdMayaUtil::setPlugMatrix(bindXform.GetInverse(), bindPreMatrixI)) { return false; } } @@ -1431,11 +1344,9 @@ UsdMayaTranslatorSkel::CreateSkinCluster( if (!bindPose.isNull()) { MFnDependencyNode bindPoseDep(bindPose, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug bindPoseMessage = - bindPoseDep.findPlug(_MayaTokens->message, &status); + MPlug bindPoseMessage = bindPoseDep.findPlug(_MayaTokens->message, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MPlug skinClusterBindPose = - skinClusterDep.findPlug(_MayaTokens->bindPose, &status); + MPlug skinClusterBindPose = skinClusterDep.findPlug(_MayaTokens->bindPose, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = dgMod.connect(bindPoseMessage, skinClusterBindPose); @@ -1445,14 +1356,12 @@ UsdMayaTranslatorSkel::CreateSkinCluster( status = dgMod.doIt(); CHECK_MSTATUS_AND_RETURN(status, false); - if (!UsdMayaUtil::setPlugMatrix(skinClusterDep, _MayaTokens->geomMatrix, - skinningQuery.GetGeomBindTransform())) { + if (!UsdMayaUtil::setPlugMatrix( + skinClusterDep, _MayaTokens->geomMatrix, skinningQuery.GetGeomBindTransform())) { return false; } - return _ComputeAndSetJointInfluences(skinningQuery, joints, - skinCluster, shapeToSkin); + return _ComputeAndSetJointInfluences(skinningQuery, joints, skinCluster, shapeToSkin); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/translators/translatorSkel.h b/lib/mayaUsd/fileio/translators/translatorSkel.h index 8b29b6348b..71e182f73f 100644 --- a/lib/mayaUsd/fileio/translators/translatorSkel.h +++ b/lib/mayaUsd/fileio/translators/translatorSkel.h @@ -17,12 +17,11 @@ #define PXRUSDMAYA_TRANSLATOR_SKEL_H #include - #include #include -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -52,45 +51,48 @@ struct UsdMayaTranslatorSkel /// Create joint nodes for each joint in \p skelQuery. /// Animation is applied to the joints if \p args enable it. MAYAUSD_CORE_PUBLIC - static bool CreateJointHierarchy(const UsdSkelSkeletonQuery& skelQuery, - MObject& parentNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context, - VtArray* joints); + static bool CreateJointHierarchy( + const UsdSkelSkeletonQuery& skelQuery, + MObject& parentNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context, + VtArray* joints); /// Find the set of MObjects joint objects for a skeleton. MAYAUSD_CORE_PUBLIC - static bool GetJoints(const UsdSkelSkeletonQuery& skelQuery, - UsdMayaPrimReaderContext* context, - VtArray* joints); + static bool GetJoints( + const UsdSkelSkeletonQuery& skelQuery, + UsdMayaPrimReaderContext* context, + VtArray* joints); /// Create a dagPose node holding a bind pose for skel \p skelQuery. MAYAUSD_CORE_PUBLIC - static bool CreateBindPose(const UsdSkelSkeletonQuery& skelQuery, - const VtArray& joints, - UsdMayaPrimReaderContext* context, - MObject* bindPoseNode); + static bool CreateBindPose( + const UsdSkelSkeletonQuery& skelQuery, + const VtArray& joints, + UsdMayaPrimReaderContext* context, + MObject* bindPoseNode); /// Find the bind pose for a Skeleton. MAYAUSD_CORE_PUBLIC - static MObject GetBindPose(const UsdSkelSkeletonQuery& skelQuery, - UsdMayaPrimReaderContext* context); + static MObject + GetBindPose(const UsdSkelSkeletonQuery& skelQuery, UsdMayaPrimReaderContext* context); /// Create a skin cluster for skinning \p primToSkin. /// The skinning cluster is wired up to be driven by the joints /// created by CreateJoints(). /// This currently only supports mesh objects. MAYAUSD_CORE_PUBLIC - static bool CreateSkinCluster(const UsdSkelSkeletonQuery& skelQuery, - const UsdSkelSkinningQuery& skinningQuery, - const VtArray& joints, - const UsdPrim& primToSkin, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context, - const MObject& bindPose=MObject()); + static bool CreateSkinCluster( + const UsdSkelSkeletonQuery& skelQuery, + const UsdSkelSkinningQuery& skinningQuery, + const VtArray& joints, + const UsdPrim& primToSkin, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context, + const MObject& bindPose = MObject()); }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/translators/translatorUtil.cpp b/lib/mayaUsd/fileio/translators/translatorUtil.cpp index 79cf566130..58165cc018 100644 --- a/lib/mayaUsd/fileio/translators/translatorUtil.cpp +++ b/lib/mayaUsd/fileio/translators/translatorUtil.cpp @@ -15,6 +15,18 @@ // #include "translatorUtil.h" +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + #include #include #include @@ -25,42 +37,24 @@ #include #include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE const MString _DEFAULT_TRANSFORM_TYPE("transform"); /* static */ -bool -UsdMayaTranslatorUtil::CreateTransformNode( - const UsdPrim& usdPrim, - MObject& parentNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context, - MStatus* status, - MObject* mayaNodeObj) +bool UsdMayaTranslatorUtil::CreateTransformNode( + const UsdPrim& usdPrim, + MObject& parentNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context, + MStatus* status, + MObject* mayaNodeObj) { if (!usdPrim || !usdPrim.IsA()) { return false; } - if (!CreateNode(usdPrim, - _DEFAULT_TRANSFORM_TYPE, - parentNode, - context, - status, - mayaNodeObj)) { + if (!CreateNode(usdPrim, _DEFAULT_TRANSFORM_TYPE, parentNode, context, status, mayaNodeObj)) { return false; } @@ -72,26 +66,20 @@ UsdMayaTranslatorUtil::CreateTransformNode( } /* static */ -bool -UsdMayaTranslatorUtil::CreateDummyTransformNode( - const UsdPrim& usdPrim, - MObject& parentNode, - bool importTypeName, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context, - MStatus* status, - MObject* mayaNodeObj) +bool UsdMayaTranslatorUtil::CreateDummyTransformNode( + const UsdPrim& usdPrim, + MObject& parentNode, + bool importTypeName, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context, + MStatus* status, + MObject* mayaNodeObj) { if (!usdPrim) { return false; } - if (!CreateNode(usdPrim, - _DEFAULT_TRANSFORM_TYPE, - parentNode, - context, - status, - mayaNodeObj)) { + if (!CreateNode(usdPrim, _DEFAULT_TRANSFORM_TYPE, parentNode, context, status, mayaNodeObj)) { return false; } @@ -103,30 +91,27 @@ UsdMayaTranslatorUtil::CreateDummyTransformNode( if (!usdPrim.HasAuthoredTypeName()) { // A regular typeless def. typeName = TfToken(); - } - else if (importTypeName) { + } else if (importTypeName) { // Preserve type info for round-tripping. typeName = usdPrim.GetTypeName(); - } - else { + } else { // Unknown type name; treat this as though it were a typeless def. typeName = TfToken(); // If there is a typename that we're ignoring, leave a note so that // we know where it came from. const std::string notes = TfStringPrintf( - "Imported from @%s@<%s> with type '%s'", - usdPrim.GetStage()->GetRootLayer()->GetIdentifier().c_str(), - usdPrim.GetPath().GetText(), - usdPrim.GetTypeName().GetText()); + "Imported from @%s@<%s> with type '%s'", + usdPrim.GetStage()->GetRootLayer()->GetIdentifier().c_str(), + usdPrim.GetPath().GetText(), + usdPrim.GetTypeName().GetText()); UsdMayaUtil::SetNotes(dagNode, notes); } adaptor.SetMetadata(SdfFieldKeys->TypeName, typeName); } // Lock all the transform attributes. - for (const UsdMayaXformOpClassification& opClass : - UsdMayaXformStack::MayaStack().GetOps()) { + for (const UsdMayaXformOpClassification& opClass : UsdMayaXformStack::MayaStack().GetOps()) { if (!opClass.IsInvertedTwin()) { MPlug plug = dagNode.findPlug(opClass.GetName().GetText(), true); if (!plug.isNull()) { @@ -137,8 +122,7 @@ UsdMayaTranslatorUtil::CreateDummyTransformNode( child.setLocked(true); child.setChannelBox(false); } - } - else { + } else { plug.setKeyable(false); plug.setLocked(true); plug.setChannelBox(false); @@ -151,34 +135,32 @@ UsdMayaTranslatorUtil::CreateDummyTransformNode( } /* static */ -bool -UsdMayaTranslatorUtil::CreateNode( - const UsdPrim& usdPrim, - const MString& nodeTypeName, - MObject& parentNode, - UsdMayaPrimReaderContext* context, - MStatus* status, - MObject* mayaNodeObj) +bool UsdMayaTranslatorUtil::CreateNode( + const UsdPrim& usdPrim, + const MString& nodeTypeName, + MObject& parentNode, + UsdMayaPrimReaderContext* context, + MStatus* status, + MObject* mayaNodeObj) { - return CreateNode(usdPrim.GetPath(), nodeTypeName, parentNode, - context, status, mayaNodeObj); + return CreateNode(usdPrim.GetPath(), nodeTypeName, parentNode, context, status, mayaNodeObj); } /* static */ -bool -UsdMayaTranslatorUtil::CreateNode( - const SdfPath& path, - const MString& nodeTypeName, - MObject& parentNode, - UsdMayaPrimReaderContext* context, - MStatus* status, - MObject* mayaNodeObj) +bool UsdMayaTranslatorUtil::CreateNode( + const SdfPath& path, + const MString& nodeTypeName, + MObject& parentNode, + UsdMayaPrimReaderContext* context, + MStatus* status, + MObject* mayaNodeObj) { - if (!CreateNode(MString(path.GetName().c_str(), path.GetName().size()), - nodeTypeName, - parentNode, - status, - mayaNodeObj)) { + if (!CreateNode( + MString(path.GetName().c_str(), path.GetName().size()), + nodeTypeName, + parentNode, + status, + mayaNodeObj)) { return false; } @@ -190,13 +172,12 @@ UsdMayaTranslatorUtil::CreateNode( } /* static */ -bool -UsdMayaTranslatorUtil::CreateNode( - const MString& nodeName, - const MString& nodeTypeName, - MObject& parentNode, - MStatus* status, - MObject* mayaNodeObj) +bool UsdMayaTranslatorUtil::CreateNode( + const MString& nodeName, + const MString& nodeTypeName, + MObject& parentNode, + MStatus* status, + MObject* mayaNodeObj) { // XXX: // Using MFnDagNode::create() results in nodes that are not properly @@ -217,43 +198,42 @@ UsdMayaTranslatorUtil::CreateNode( } /* static */ -bool -UsdMayaTranslatorUtil::CreateShaderNode( - const MString& nodeName, - const MString& nodeTypeName, - const UsdMayaShadingNodeType shadingNodeType, - MStatus* status, - MObject* shaderObj, - const MObject parentNode) +bool UsdMayaTranslatorUtil::CreateShaderNode( + const MString& nodeName, + const MString& nodeTypeName, + const UsdMayaShadingNodeType shadingNodeType, + MStatus* status, + MObject* shaderObj, + const MObject parentNode) { MString typeFlag; switch (shadingNodeType) { - case UsdMayaShadingNodeType::Light: - typeFlag = "-al"; // -asLight - break; - case UsdMayaShadingNodeType::PostProcess: - typeFlag = "-app"; // -asPostProcess - break; - case UsdMayaShadingNodeType::Rendering: - typeFlag = "-ar"; // -asRendering - break; - case UsdMayaShadingNodeType::Shader: - typeFlag = "-as"; // -asShader - break; - case UsdMayaShadingNodeType::Texture: - typeFlag = "-icm -at"; // -isColorManaged -asTexture - break; - case UsdMayaShadingNodeType::Utility: - typeFlag = "-au"; // -asUtility - break; - default: { - MFnDependencyNode depNodeFn; - depNodeFn.create(nodeTypeName, nodeName, status); - CHECK_MSTATUS_AND_RETURN(*status, false); - *shaderObj = depNodeFn.object(status); - CHECK_MSTATUS_AND_RETURN(*status, false); - return true; - } + case UsdMayaShadingNodeType::Light: + typeFlag = "-al"; // -asLight + break; + case UsdMayaShadingNodeType::PostProcess: + typeFlag = "-app"; // -asPostProcess + break; + case UsdMayaShadingNodeType::Rendering: + typeFlag = "-ar"; // -asRendering + break; + case UsdMayaShadingNodeType::Shader: + typeFlag = "-as"; // -asShader + break; + case UsdMayaShadingNodeType::Texture: + typeFlag = "-icm -at"; // -isColorManaged -asTexture + break; + case UsdMayaShadingNodeType::Utility: + typeFlag = "-au"; // -asUtility + break; + default: { + MFnDependencyNode depNodeFn; + depNodeFn.create(nodeTypeName, nodeName, status); + CHECK_MSTATUS_AND_RETURN(*status, false); + *shaderObj = depNodeFn.object(status); + CHECK_MSTATUS_AND_RETURN(*status, false); + return true; + } } MString parentFlag; @@ -266,12 +246,11 @@ UsdMayaTranslatorUtil::CreateShaderNode( MString cmd; // ss = skipSelect - *status = cmd.format("shadingNode ^1s^2s -ss -n \"^3s\" \"^4s\"", - typeFlag, parentFlag, nodeName, nodeTypeName); + *status = cmd.format( + "shadingNode ^1s^2s -ss -n \"^3s\" \"^4s\"", typeFlag, parentFlag, nodeName, nodeTypeName); CHECK_MSTATUS_AND_RETURN(*status, false); - const MString createdNode = - MGlobal::executeCommandStringResult(cmd, false, false, status); + const MString createdNode = MGlobal::executeCommandStringResult(cmd, false, false, status); CHECK_MSTATUS_AND_RETURN(*status, false); *status = UsdMayaUtil::GetMObjectByName(createdNode.asChar(), *shaderObj); @@ -302,5 +281,4 @@ UsdMayaTranslatorUtil::CreateShaderNode( return true; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/translators/translatorUtil.h b/lib/mayaUsd/fileio/translators/translatorUtil.h index 88bfc2a902..af42c4732d 100644 --- a/lib/mayaUsd/fileio/translators/translatorUtil.h +++ b/lib/mayaUsd/fileio/translators/translatorUtil.h @@ -17,19 +17,19 @@ #define PXRUSDMAYA_TRANSLATOR_UTIL_H #include - -#include #include - -#include -#include +#include #include #include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE -enum class UsdMayaShadingNodeType { +enum class UsdMayaShadingNodeType +{ NonShading, Light, PostProcess, @@ -49,14 +49,13 @@ struct UsdMayaTranslatorUtil /// non-NULL, the new Maya node will be registered to the path of /// \p usdPrim. MAYAUSD_CORE_PUBLIC - static bool - CreateTransformNode( - const UsdPrim& usdPrim, - MObject& parentNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context, - MStatus* status, - MObject* mayaNodeObj); + static bool CreateTransformNode( + const UsdPrim& usdPrim, + MObject& parentNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context, + MStatus* status, + MObject* mayaNodeObj); /// \brief Creates a "dummy" transform node for the given prim, where the /// dummy transform has all transform properties locked. @@ -66,54 +65,50 @@ struct UsdMayaTranslatorUtil /// be applied on export. Otherwise, this attribute will be set to the /// empty string, so a typeless def will be generated on export. MAYAUSD_CORE_PUBLIC - static bool - CreateDummyTransformNode( - const UsdPrim& usdPrim, - MObject& parentNode, - bool importTypeName, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context, - MStatus* status, - MObject* mayaNodeObj); + static bool CreateDummyTransformNode( + const UsdPrim& usdPrim, + MObject& parentNode, + bool importTypeName, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context, + MStatus* status, + MObject* mayaNodeObj); /// \brief Helper to create a node for \p usdPrim of type \p /// nodeTypeName under \p parentNode. If \p context is non-NULL, /// the new Maya node will be registered to the path of \p usdPrim. MAYAUSD_CORE_PUBLIC - static bool - CreateNode( - const UsdPrim& usdPrim, - const MString& nodeTypeName, - MObject& parentNode, - UsdMayaPrimReaderContext* context, - MStatus* status, - MObject* mayaNodeObj); + static bool CreateNode( + const UsdPrim& usdPrim, + const MString& nodeTypeName, + MObject& parentNode, + UsdMayaPrimReaderContext* context, + MStatus* status, + MObject* mayaNodeObj); /// \brief Helper to create a node for \p usdPath of type \p /// nodeTypeName under \p parentNode. If \p context is non-NULL, /// the new Maya node will be registered to the path of \p usdPrim. MAYAUSD_CORE_PUBLIC - static bool - CreateNode( - const SdfPath& usdPath, - const MString& nodeTypeName, - MObject& parentNode, - UsdMayaPrimReaderContext* context, - MStatus* status, - MObject* mayaNodeObj); + static bool CreateNode( + const SdfPath& usdPath, + const MString& nodeTypeName, + MObject& parentNode, + UsdMayaPrimReaderContext* context, + MStatus* status, + MObject* mayaNodeObj); /// \brief Helper to create a node named \p nodeName of type \p /// nodeTypeName under \p parentNode. Note that this version does /// NOT take a context and cannot register the newly created Maya node /// since it does not know the SdfPath to an originating object. MAYAUSD_CORE_PUBLIC - static bool - CreateNode( - const MString& nodeName, - const MString& nodeTypeName, - MObject& parentNode, - MStatus* status, - MObject* mayaNodeObj); + static bool CreateNode( + const MString& nodeName, + const MString& nodeTypeName, + MObject& parentNode, + MStatus* status, + MObject* mayaNodeObj); /// \brief Helper to create shadingNodes. Wrapper around mel "shadingNode". /// @@ -128,14 +123,13 @@ struct UsdMayaTranslatorUtil /// determine the type of node automatically using it's classification /// string MAYAUSD_CORE_PUBLIC - static bool - CreateShaderNode( - const MString& nodeName, - const MString& nodeTypeName, - const UsdMayaShadingNodeType shadingNodeType, - MStatus* status, - MObject* shaderObj, - const MObject parentNode=MObject::kNullObj); + static bool CreateShaderNode( + const MString& nodeName, + const MString& nodeTypeName, + const UsdMayaShadingNodeType shadingNodeType, + MStatus* status, + MObject* shaderObj, + const MObject parentNode = MObject::kNullObj); /// Gets an API schema of the requested type for the given \p usdPrim. /// @@ -150,11 +144,8 @@ struct UsdMayaTranslatorUtil return APISchemaType(usdPrim); } - }; - - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/translators/translatorXformable.cpp b/lib/mayaUsd/fileio/translators/translatorXformable.cpp index 6d35135c03..144557d9a9 100644 --- a/lib/mayaUsd/fileio/translators/translatorXformable.cpp +++ b/lib/mayaUsd/fileio/translators/translatorXformable.cpp @@ -15,9 +15,20 @@ // #include "translatorXformable.h" -#include -#include -#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -32,29 +43,16 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE // This function retrieves a value for a given xformOp and given time sample. It // knows how to deal with different type of ops and angle conversion -static bool _getXformOpAsVec3d( - const UsdGeomXformOp &xformOp, - GfVec3d &value, - const UsdTimeCode &usdTime) +static bool +_getXformOpAsVec3d(const UsdGeomXformOp& xformOp, GfVec3d& value, const UsdTimeCode& usdTime) { bool retValue = false; @@ -67,40 +65,33 @@ static bool _getXformOpAsVec3d( } // Check whether the XformOp is a type of rotation. - int rotAxis = -1; + int rotAxis = -1; double angleMult = GfDegreesToRadians(1.0); - switch(opType) { - case UsdGeomXformOp::TypeRotateX: - rotAxis = 0; - break; - case UsdGeomXformOp::TypeRotateY: - rotAxis = 1; - break; - case UsdGeomXformOp::TypeRotateZ: - rotAxis = 2; - break; - case UsdGeomXformOp::TypeRotateXYZ: - case UsdGeomXformOp::TypeRotateXZY: - case UsdGeomXformOp::TypeRotateYXZ: - case UsdGeomXformOp::TypeRotateYZX: - case UsdGeomXformOp::TypeRotateZXY: - case UsdGeomXformOp::TypeRotateZYX: - break; - default: - // This XformOp is not a rotation, so we're not converting an - // angular value from degrees to radians. - angleMult = 1.0; - break; + switch (opType) { + case UsdGeomXformOp::TypeRotateX: rotAxis = 0; break; + case UsdGeomXformOp::TypeRotateY: rotAxis = 1; break; + case UsdGeomXformOp::TypeRotateZ: rotAxis = 2; break; + case UsdGeomXformOp::TypeRotateXYZ: + case UsdGeomXformOp::TypeRotateXZY: + case UsdGeomXformOp::TypeRotateYXZ: + case UsdGeomXformOp::TypeRotateYZX: + case UsdGeomXformOp::TypeRotateZXY: + case UsdGeomXformOp::TypeRotateZYX: break; + default: + // This XformOp is not a rotation, so we're not converting an + // angular value from degrees to radians. + angleMult = 1.0; + break; } // If we encounter a transform op, we treat it as a shear operation. if (opType == UsdGeomXformOp::TypeTransform) { // GetOpTransform() handles the inverse op case for us. GfMatrix4d xform = xformOp.GetOpTransform(usdTime); - value[0] = xform[1][0]; //xyVal - value[1] = xform[2][0]; //xzVal - value[2] = xform[2][1]; //yzVal + value[0] = xform[1][0]; // xyVal + value[1] = xform[2][0]; // xzVal + value[2] = xform[2][1]; // yzVal retValue = true; } else if (rotAxis != -1) { // Single Axis rotation @@ -129,36 +120,41 @@ static bool _getXformOpAsVec3d( } // Sets the animation curve (a knot per frame) for a given plug/attribute -static void _setAnimPlugData(MPlug plg, std::vector &value, MTimeArray &timeArray, - const UsdMayaPrimReaderContext* context) +static void _setAnimPlugData( + MPlug plg, + std::vector& value, + MTimeArray& timeArray, + const UsdMayaPrimReaderContext* context) { - MStatus status; + MStatus status; MFnAnimCurve animFn; // Make the plug keyable before attaching an anim curve if (!plg.isKeyable()) { plg.setKeyable(true); } MObject animObj = animFn.create(plg, nullptr, &status); - if (status == MS::kSuccess ) { - MDoubleArray valueArray( &value[0], value.size()); + if (status == MS::kSuccess) { + MDoubleArray valueArray(&value[0], value.size()); animFn.addKeys(&timeArray, &valueArray); if (context) { - context->RegisterNewMayaNode(animFn.name().asChar(), animObj ); + context->RegisterNewMayaNode(animFn.name().asChar(), animObj); } } else { MString mayaPlgName = plg.partialName(true, true, true, false, true, true, &status); TF_RUNTIME_ERROR( - "Failed to create animation object for attribute: %s", - mayaPlgName.asChar()); + "Failed to create animation object for attribute: %s", mayaPlgName.asChar()); } } // Returns true if the array is not constant -static bool _isArrayVarying(std::vector &value) +static bool _isArrayVarying(std::vector& value) { - bool isVarying=false; - for (unsigned int i=1;i &value) // double arrays and then if the array is varying defines an anym curve for the // attribute static void _setMayaAttribute( - MFnDagNode &depFn, - std::vector &xVal, std::vector &yVal, std::vector &zVal, - MTimeArray &timeArray, - const MString& opName, - const MString& x, const MString& y, const MString& z, - const UsdMayaPrimReaderContext* context) + MFnDagNode& depFn, + std::vector& xVal, + std::vector& yVal, + std::vector& zVal, + MTimeArray& timeArray, + const MString& opName, + const MString& x, + const MString& y, + const MString& z, + const UsdMayaPrimReaderContext* context) { MPlug plg; - if (x!="" && !xVal.empty()) { - plg = depFn.findPlug(opName+x); - if ( !plg.isNull() ) { + if (x != "" && !xVal.empty()) { + plg = depFn.findPlug(opName + x); + if (!plg.isNull()) { plg.setDouble(xVal[0]); - if (xVal.size()>1 && _isArrayVarying(xVal)) _setAnimPlugData(plg, xVal, timeArray, context); + if (xVal.size() > 1 && _isArrayVarying(xVal)) + _setAnimPlugData(plg, xVal, timeArray, context); } } - if (y!="" && !yVal.empty()) { - plg = depFn.findPlug(opName+y); - if ( !plg.isNull() ) { + if (y != "" && !yVal.empty()) { + plg = depFn.findPlug(opName + y); + if (!plg.isNull()) { plg.setDouble(yVal[0]); - if (yVal.size()>1 && _isArrayVarying(yVal)) _setAnimPlugData(plg, yVal, timeArray, context); + if (yVal.size() > 1 && _isArrayVarying(yVal)) + _setAnimPlugData(plg, yVal, timeArray, context); } } - if (z!="" && !zVal.empty()) { - plg = depFn.findPlug(opName+z); - if ( !plg.isNull() ) { + if (z != "" && !zVal.empty()) { + plg = depFn.findPlug(opName + z); + if (!plg.isNull()) { plg.setDouble(zVal[0]); - if (zVal.size()>1 && _isArrayVarying(zVal)) _setAnimPlugData(plg, zVal, timeArray, context); + if (zVal.size() > 1 && _isArrayVarying(zVal)) + _setAnimPlugData(plg, zVal, timeArray, context); } } } @@ -201,16 +204,16 @@ static void _setMayaAttribute( // For each xformop, we gather it's data either time sampled or not and we push // it to the corresponding Maya xform static bool _pushUSDXformOpToMayaXform( - const UsdGeomXformOp& xformop, - const TfToken& opName, - MFnDagNode &MdagNode, - const UsdMayaPrimReaderArgs& args, - const UsdMayaPrimReaderContext* context) + const UsdGeomXformOp& xformop, + const TfToken& opName, + MFnDagNode& MdagNode, + const UsdMayaPrimReaderArgs& args, + const UsdMayaPrimReaderContext* context) { std::vector xValue; std::vector yValue; std::vector zValue; - GfVec3d value; + GfVec3d value; std::vector timeSamples; if (!args.GetTimeInterval().IsEmpty()) { xformop.GetTimeSamplesInInterval(args.GetTimeInterval(), &timeSamples); @@ -221,76 +224,113 @@ static bool _pushUSDXformOpToMayaXform( xValue.resize(timeSamples.size()); yValue.resize(timeSamples.size()); zValue.resize(timeSamples.size()); - for (unsigned int ti=0; ti < timeSamples.size(); ++ti) { + for (unsigned int ti = 0; ti < timeSamples.size(); ++ti) { UsdTimeCode time(timeSamples[ti]); if (_getXformOpAsVec3d(xformop, value, time)) { - xValue[ti]=value[0]; yValue[ti]=value[1]; zValue[ti]=value[2]; + xValue[ti] = value[0]; + yValue[ti] = value[1]; + zValue[ti] = value[2]; timeArray.set(MTime(timeSamples[ti]), ti); - } - else { + } else { TF_RUNTIME_ERROR( - "Missing sampled data on xformOp: %s", - xformop.GetName().GetText()); + "Missing sampled data on xformOp: %s", xformop.GetName().GetText()); } } - } - else { + } else { // pick the first available sample or default - UsdTimeCode time=UsdTimeCode::EarliestTime(); + UsdTimeCode time = UsdTimeCode::EarliestTime(); if (_getXformOpAsVec3d(xformop, value, time)) { xValue.resize(1); yValue.resize(1); zValue.resize(1); - xValue[0]=value[0]; yValue[0]=value[1]; zValue[0]=value[2]; - } - else { - TF_RUNTIME_ERROR( - "Missing default data on xformOp: %s", - xformop.GetName().GetText()); + xValue[0] = value[0]; + yValue[0] = value[1]; + zValue[0] = value[2]; + } else { + TF_RUNTIME_ERROR("Missing default data on xformOp: %s", xformop.GetName().GetText()); } } if (!xValue.empty()) { - if (opName==UsdMayaXformStackTokens->shear) { - _setMayaAttribute(MdagNode, xValue, yValue, zValue, timeArray, MString(opName.GetText()), "XY", "XZ", "YZ", context); - } - else if (opName==UsdMayaXformStackTokens->pivot) { - _setMayaAttribute(MdagNode, xValue, yValue, zValue, timeArray, MString("rotatePivot"), "X", "Y", "Z", context); - _setMayaAttribute(MdagNode, xValue, yValue, zValue, timeArray, MString("scalePivot"), "X", "Y", "Z", context); - } - else if (opName==UsdMayaXformStackTokens->pivotTranslate) { - _setMayaAttribute(MdagNode, xValue, yValue, zValue, timeArray, MString("rotatePivotTranslate"), "X", "Y", "Z", context); - _setMayaAttribute(MdagNode, xValue, yValue, zValue, timeArray, MString("scalePivotTranslate"), "X", "Y", "Z", context); - } - else { - if (opName==UsdMayaXformStackTokens->rotate) { + if (opName == UsdMayaXformStackTokens->shear) { + _setMayaAttribute( + MdagNode, + xValue, + yValue, + zValue, + timeArray, + MString(opName.GetText()), + "XY", + "XZ", + "YZ", + context); + } else if (opName == UsdMayaXformStackTokens->pivot) { + _setMayaAttribute( + MdagNode, + xValue, + yValue, + zValue, + timeArray, + MString("rotatePivot"), + "X", + "Y", + "Z", + context); + _setMayaAttribute( + MdagNode, + xValue, + yValue, + zValue, + timeArray, + MString("scalePivot"), + "X", + "Y", + "Z", + context); + } else if (opName == UsdMayaXformStackTokens->pivotTranslate) { + _setMayaAttribute( + MdagNode, + xValue, + yValue, + zValue, + timeArray, + MString("rotatePivotTranslate"), + "X", + "Y", + "Z", + context); + _setMayaAttribute( + MdagNode, + xValue, + yValue, + zValue, + timeArray, + MString("scalePivotTranslate"), + "X", + "Y", + "Z", + context); + } else { + if (opName == UsdMayaXformStackTokens->rotate) { MFnTransform trans; - if(trans.setObject(MdagNode.object())) - { - auto MrotOrder = - UsdMayaXformStack::RotateOrderFromOpType( - xformop.GetOpType()); + if (trans.setObject(MdagNode.object())) { + auto MrotOrder = UsdMayaXformStack::RotateOrderFromOpType< + MTransformationMatrix::RotationOrder>(xformop.GetOpType()); MPlug plg = MdagNode.findPlug("rotateOrder"); - if ( !plg.isNull() ) { + if (!plg.isNull()) { trans.setRotationOrder(MrotOrder, /*no need to reorder*/ false); } } - } - else if(opName==UsdMayaXformStackTokens->rotateAxis) - { + } else if (opName == UsdMayaXformStackTokens->rotateAxis) { // Rotate axis only accepts input in XYZ form // (though it's actually stored as a quaternion), // so we need to convert other rotation orders to XYZ const auto opType = xformop.GetOpType(); - if (opType != UsdGeomXformOp::TypeRotateXYZ - && opType != UsdGeomXformOp::TypeRotateX - && opType != UsdGeomXformOp::TypeRotateY - && opType != UsdGeomXformOp::TypeRotateZ) - { - for (size_t i = 0u; i < xValue.size(); ++i) - { - auto MrotOrder = - UsdMayaXformStack::RotateOrderFromOpType( - xformop.GetOpType()); + if (opType != UsdGeomXformOp::TypeRotateXYZ && opType != UsdGeomXformOp::TypeRotateX + && opType != UsdGeomXformOp::TypeRotateY + && opType != UsdGeomXformOp::TypeRotateZ) { + for (size_t i = 0u; i < xValue.size(); ++i) { + auto MrotOrder = UsdMayaXformStack::RotateOrderFromOpType< + MEulerRotation::RotationOrder>(xformop.GetOpType()); MEulerRotation eulerRot(xValue[i], yValue[i], zValue[i], MrotOrder); eulerRot.reorderIt(MEulerRotation::kXYZ); xValue[i] = eulerRot.x; @@ -299,7 +339,17 @@ static bool _pushUSDXformOpToMayaXform( } } } - _setMayaAttribute(MdagNode, xValue, yValue, zValue, timeArray, MString(opName.GetText()), "X", "Y", "Z", context); + _setMayaAttribute( + MdagNode, + xValue, + yValue, + zValue, + timeArray, + MString(opName.GetText()), + "X", + "Y", + "Z", + context); } return true; } @@ -309,9 +359,7 @@ static bool _pushUSDXformOpToMayaXform( // Simple function that determines if the matrix is identity // XXX Maybe there is something already in Gf but couldn't see it -static -bool -_isIdentityMatrix(const GfMatrix4d& m) +static bool _isIdentityMatrix(const GfMatrix4d& m) { static const GfMatrix4d identityMatrix(1.0); static constexpr double tolerance = 1e-9; @@ -319,18 +367,19 @@ _isIdentityMatrix(const GfMatrix4d& m) return GfIsClose(m, identityMatrix, tolerance); } -// For each xformop, we gather it's data either time sampled or not and we push it to the corresponding Maya xform +// For each xformop, we gather it's data either time sampled or not and we push it to the +// corresponding Maya xform static bool _pushUSDXformToMayaXform( - const UsdGeomXformable &xformSchema, - MFnDagNode &MdagNode, - const UsdMayaPrimReaderArgs& args, - const UsdMayaPrimReaderContext* context) + const UsdGeomXformable& xformSchema, + MFnDagNode& MdagNode, + const UsdMayaPrimReaderArgs& args, + const UsdMayaPrimReaderContext* context) { std::vector timeSamples; xformSchema.GetTimeSamplesInInterval(args.GetTimeInterval(), &timeSamples); std::vector timeCodes; - MTimeArray timeArray; + MTimeArray timeArray; if (!timeSamples.empty()) { // Convert all the time samples to UsdTimeCodes. @@ -338,10 +387,7 @@ static bool _pushUSDXformToMayaXform( timeSamples.cbegin(), timeSamples.cend(), std::back_inserter(timeCodes), - [](const double timeSample) { - return UsdTimeCode(timeSample); - } - ); + [](const double timeSample) { return UsdTimeCode(timeSample); }); timeArray.setLength(timeCodes.size()); } else { @@ -370,7 +416,7 @@ static bool _pushUSDXformToMayaXform( const UsdTimeCode& timeCode = timeCodes[ti]; GfMatrix4d usdLocalTransform(1.0); - bool resetsXformStack; + bool resetsXformStack; if (!xformSchema.GetLocalTransformation(&usdLocalTransform, &resetsXformStack, timeCode) && !xformSchema.GetPrim().IsInstance()) { if (timeCode.IsDefault()) { @@ -395,37 +441,25 @@ static bool _pushUSDXformToMayaXform( if (!_isIdentityMatrix(usdLocalTransform)) { double usdLocalTransformData[4u][4u]; usdLocalTransform.Get(usdLocalTransformData); - const MMatrix localMatrix(usdLocalTransformData); + const MMatrix localMatrix(usdLocalTransformData); const MTransformationMatrix localTransformationMatrix(localMatrix); - double tempVec[3u]; + double tempVec[3u]; MStatus status; - translation = - localTransformationMatrix.getTranslation( - MSpace::kTransform, - &status); + translation = localTransformationMatrix.getTranslation(MSpace::kTransform, &status); CHECK_MSTATUS(status); - status = - localTransformationMatrix.getScale( - tempVec, - MSpace::kTransform); + status = localTransformationMatrix.getScale(tempVec, MSpace::kTransform); CHECK_MSTATUS(status); scale = MVector(tempVec); MTransformationMatrix::RotationOrder rotateOrder; - status = - localTransformationMatrix.getRotation( - tempVec, - rotateOrder); + status = localTransformationMatrix.getRotation(tempVec, rotateOrder); CHECK_MSTATUS(status); rotation = MVector(tempVec); - status = - localTransformationMatrix.getShear( - tempVec, - MSpace::kTransform); + status = localTransformationMatrix.getShear(tempVec, MSpace::kTransform); CHECK_MSTATUS(status); shear = MVector(tempVec); } @@ -453,10 +487,23 @@ static bool _pushUSDXformToMayaXform( // All of these vectors should have the same size and greater than 0 to set their values if (TxVal.size() == TyVal.size() && TxVal.size() == TzVal.size() && !TxVal.empty()) { - _setMayaAttribute(MdagNode, TxVal, TyVal, TzVal, timeArray, MString("translate"), "X", "Y", "Z", context); - _setMayaAttribute(MdagNode, RxVal, RyVal, RzVal, timeArray, MString("rotate"), "X", "Y", "Z", context); - _setMayaAttribute(MdagNode, SxVal, SyVal, SzVal, timeArray, MString("scale"), "X", "Y", "Z", context); - _setMayaAttribute(MdagNode, ShearXYVal, ShearXZVal, ShearYZVal, timeArray, MString("shear"), "XY", "XZ", "YZ", context); + _setMayaAttribute( + MdagNode, TxVal, TyVal, TzVal, timeArray, MString("translate"), "X", "Y", "Z", context); + _setMayaAttribute( + MdagNode, RxVal, RyVal, RzVal, timeArray, MString("rotate"), "X", "Y", "Z", context); + _setMayaAttribute( + MdagNode, SxVal, SyVal, SzVal, timeArray, MString("scale"), "X", "Y", "Z", context); + _setMayaAttribute( + MdagNode, + ShearXYVal, + ShearXZVal, + ShearYZVal, + timeArray, + MString("shear"), + "XY", + "XZ", + "YZ", + context); return true; } @@ -464,12 +511,11 @@ static bool _pushUSDXformToMayaXform( return false; } -void -UsdMayaTranslatorXformable::Read( - const UsdGeomXformable& xformSchema, - MObject mayaNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context) +void UsdMayaTranslatorXformable::Read( + const UsdGeomXformable& xformSchema, + MObject mayaNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context) { MStatus status; @@ -482,32 +528,27 @@ UsdMayaTranslatorXformable::Read( // // If fail to retrieve proper ops with proper name and order, will try to // decompose the xform matrix - bool resetsXformStack= false; - std::vector xformops = xformSchema.GetOrderedXformOps( - &resetsXformStack); + bool resetsXformStack = false; + std::vector xformops = xformSchema.GetOrderedXformOps(&resetsXformStack); // When we find ops, we match the ops by suffix ("" will define the basic // translate, rotate, scale) and by order. If we find an op with a // different name or out of order that will miss the match, we will rely on // matrix decomposition - UsdMayaXformStack::OpClassList stackOps = \ - UsdMayaXformStack::FirstMatchingSubstack( - { - &UsdMayaXformStack::MayaStack(), - &UsdMayaXformStack::CommonStack() - }, - xformops); + UsdMayaXformStack::OpClassList stackOps = UsdMayaXformStack::FirstMatchingSubstack( + { &UsdMayaXformStack::MayaStack(), &UsdMayaXformStack::CommonStack() }, xformops); MFnDagNode MdagNode(mayaNode); if (!stackOps.empty()) { // make sure stackIndices.size() == xformops.size() - for (unsigned int i=0; i < stackOps.size(); i++) { - const UsdGeomXformOp& xformop(xformops[i]); + for (unsigned int i = 0; i < stackOps.size(); i++) { + const UsdGeomXformOp& xformop(xformops[i]); const UsdMayaXformOpClassification& opDef(stackOps[i]); // If we got a valid stack, we have both the members of the inverted twins.. // ...so we can go ahead and skip the inverted twin - if (opDef.IsInvertedTwin()) continue; + if (opDef.IsInvertedTwin()) + continue; const TfToken& opName(opDef.GetName()); @@ -516,16 +557,16 @@ UsdMayaTranslatorXformable::Read( } else { if (!_pushUSDXformToMayaXform(xformSchema, MdagNode, args, context)) { TF_RUNTIME_ERROR( - "Unable to successfully decompose matrix at USD prim <%s>", - xformSchema.GetPath().GetText()); + "Unable to successfully decompose matrix at USD prim <%s>", + xformSchema.GetPath().GetText()); } } if (resetsXformStack) { MPlug plg = MdagNode.findPlug("inheritsTransform"); - if (!plg.isNull()) plg.setBool(false); + if (!plg.isNull()) + plg.setBool(false); } } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/translators/translatorXformable.h b/lib/mayaUsd/fileio/translators/translatorXformable.h index 37d41c4ee6..d38e046005 100644 --- a/lib/mayaUsd/fileio/translators/translatorXformable.h +++ b/lib/mayaUsd/fileio/translators/translatorXformable.h @@ -17,41 +17,39 @@ #define PXRUSDMAYA_TRANSLATOR_XFORMABLE_H #include +#include +#include -#include - -#include #include #include +#include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE -/// \brief Provides helper functions for reading UsdGeomXformable. +/// \brief Provides helper functions for reading UsdGeomXformable. struct UsdMayaTranslatorXformable { /// \brief reads xform attributes from \p xformable and converts them into /// maya transform values. MAYAUSD_CORE_PUBLIC static void Read( - const UsdGeomXformable& xformable, - MObject mayaNode, - const UsdMayaPrimReaderArgs& args, - UsdMayaPrimReaderContext* context); + const UsdGeomXformable& xformable, + MObject mayaNode, + const UsdMayaPrimReaderArgs& args, + UsdMayaPrimReaderContext* context); /// \brief Convenince function for decomposing \p usdMatrix. MAYAUSD_CORE_PUBLIC static bool ConvertUsdMatrixToComponents( - const GfMatrix4d &usdMatrix, - GfVec3d *trans, - GfVec3d *rot, - GfVec3d *scale); + const GfMatrix4d& usdMatrix, + GfVec3d* trans, + GfVec3d* rot, + GfVec3d* scale); }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/translators/translatorXformable_decompose.cpp b/lib/mayaUsd/fileio/translators/translatorXformable_decompose.cpp index eb35999e5f..c897739b21 100644 --- a/lib/mayaUsd/fileio/translators/translatorXformable_decompose.cpp +++ b/lib/mayaUsd/fileio/translators/translatorXformable_decompose.cpp @@ -13,14 +13,14 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include -#include #include #include #include +#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -29,87 +29,79 @@ PXR_NAMESPACE_OPEN_SCOPE // MatrixToVectorsWithPivotInvariant; needs to be generalized for arbitrary // rotationOrder (which means lofting that concept to Gf), orthonormalization, // etc. - -static GfMatrix3d -_EulerXYZToMatrix3d(GfVec3d eulerXYZ) + +static GfMatrix3d _EulerXYZToMatrix3d(GfVec3d eulerXYZ) { - GfMatrix3d result(GfRotation(GfVec3d::XAxis(),eulerXYZ[0]) * - GfRotation(GfVec3d::YAxis(),eulerXYZ[1]) * - GfRotation(GfVec3d::ZAxis(),eulerXYZ[2])); + GfMatrix3d result( + GfRotation(GfVec3d::XAxis(), eulerXYZ[0]) * GfRotation(GfVec3d::YAxis(), eulerXYZ[1]) + * GfRotation(GfVec3d::ZAxis(), eulerXYZ[2])); return result; } // Assumes rotationOrder is XYZ. -static void -_RotMatToRotTriplet( - const GfMatrix4d &rotMat, - GfVec3d *rotTriplet) +static void _RotMatToRotTriplet(const GfMatrix4d& rotMat, GfVec3d* rotTriplet) { GfRotation rot = rotMat.ExtractRotation(); - GfVec3d angles = rot.Decompose(GfVec3d::ZAxis(), - GfVec3d::YAxis(), - GfVec3d::XAxis()); + GfVec3d angles = rot.Decompose(GfVec3d::ZAxis(), GfVec3d::YAxis(), GfVec3d::XAxis()); (*rotTriplet)[0] = angles[2]; (*rotTriplet)[1] = angles[1]; (*rotTriplet)[2] = angles[0]; } -static void -_MatrixToVectorsWithPivotInvariant( - const GfMatrix4d &m, - const GfVec3d& pivotPosition, - const GfVec3d& pivotOrientation, - GfVec3d *translation, - GfVec3d *rotation, - GfVec3d *scale, - GfVec3d *scaleOrientation) +static void _MatrixToVectorsWithPivotInvariant( + const GfMatrix4d& m, + const GfVec3d& pivotPosition, + const GfVec3d& pivotOrientation, + GfVec3d* translation, + GfVec3d* rotation, + GfVec3d* scale, + GfVec3d* scaleOrientation) { GfMatrix3d pivotOrientMat = _EulerXYZToMatrix3d(pivotOrientation); - GfMatrix4d pp = GfMatrix4d(1.0).SetTranslate( pivotPosition); + GfMatrix4d pp = GfMatrix4d(1.0).SetTranslate(pivotPosition); GfMatrix4d ppInv = GfMatrix4d(1.0).SetTranslate(-pivotPosition); - GfMatrix4d po = GfMatrix4d(1.0).SetRotate(pivotOrientMat); + GfMatrix4d po = GfMatrix4d(1.0).SetRotate(pivotOrientMat); GfMatrix4d poInv = GfMatrix4d(1.0).SetRotate(pivotOrientMat.GetInverse()); GfMatrix4d factorMe = po * pp * m * ppInv; GfMatrix4d scaleOrientMat, factoredRotMat, perspMat; - factorMe.Factor(&scaleOrientMat, scale, &factoredRotMat, - translation, &perspMat); + factorMe.Factor(&scaleOrientMat, scale, &factoredRotMat, translation, &perspMat); GfMatrix4d rotMat = factoredRotMat * poInv; - if(!rotMat.Orthonormalize(/* issueWarning */ false)) + if (!rotMat.Orthonormalize(/* issueWarning */ false)) TF_WARN("Failed to orthonormalize rotMat."); _RotMatToRotTriplet(rotMat, rotation); - if(!scaleOrientMat.Orthonormalize(/* issueWarning */ false)) + if (!scaleOrientMat.Orthonormalize(/* issueWarning */ false)) TF_WARN("Failed to orthonormalize scaleOrientMat."); _RotMatToRotTriplet(scaleOrientMat, scaleOrientation); } bool UsdMayaTranslatorXformable::ConvertUsdMatrixToComponents( - const GfMatrix4d &usdMatrix, - GfVec3d *trans, - GfVec3d *rot, - GfVec3d *scale) + const GfMatrix4d& usdMatrix, + GfVec3d* trans, + GfVec3d* rot, + GfVec3d* scale) { GfVec3d rotation, scaleVec, scaleOrientation; _MatrixToVectorsWithPivotInvariant( usdMatrix, - //const TransformRotationOrder rotationOrder, XYZ - GfVec3d(0,0,0), // const GfVec3d pivotPosition - GfVec3d(0,0,0), // const GfVec3d pivotOrientation - trans, - &rotation, - &scaleVec, + // const TransformRotationOrder rotationOrder, XYZ + GfVec3d(0, 0, 0), // const GfVec3d pivotPosition + GfVec3d(0, 0, 0), // const GfVec3d pivotOrientation + trans, + &rotation, + &scaleVec, &scaleOrientation); - for (int i=0; i<3; ++i) { + for (int i = 0; i < 3; ++i) { // Note that setting rotation via Maya API takes radians, even though // the MEL attribute itself is encoded in degrees. #wtf (*rot)[i] = GfDegreesToRadians(rotation[i]); @@ -120,6 +112,4 @@ bool UsdMayaTranslatorXformable::ConvertUsdMatrixToComponents( return true; } - PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/fileio/utils/adaptor.cpp b/lib/mayaUsd/fileio/utils/adaptor.cpp index 6a2429937a..43c416cf9b 100644 --- a/lib/mayaUsd/fileio/utils/adaptor.cpp +++ b/lib/mayaUsd/fileio/utils/adaptor.cpp @@ -15,52 +15,45 @@ // #include "adaptor.h" -#include -#include -#include +#include +#include +#include +#include +#include #include #include #include #include -#include -#include -#include -#include -#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -static std::string -_GetMayaAttrNameForMetadataKey(const TfToken& key) +static std::string _GetMayaAttrNameForMetadataKey(const TfToken& key) { - return TfStringPrintf("USD_%s", - TfMakeValidIdentifier(key.GetString()).c_str()); + return TfStringPrintf("USD_%s", TfMakeValidIdentifier(key.GetString()).c_str()); } -static std::string -_GetMayaAttrNameForAttrName(const TfToken& attrName) +static std::string _GetMayaAttrNameForAttrName(const TfToken& attrName) { - return TfStringPrintf("USD_ATTR_%s", - TfMakeValidIdentifier(attrName.GetString()).c_str()); + return TfStringPrintf("USD_ATTR_%s", TfMakeValidIdentifier(attrName.GetString()).c_str()); } -static VtValue -_GetListOpForTokenVector(const TfTokenVector& vector) +static VtValue _GetListOpForTokenVector(const TfTokenVector& vector) { SdfTokenListOp op; op.SetPrependedItems(vector); return VtValue(op); } +std::map UsdMayaAdaptor::_schemaLookup; +std::map> UsdMayaAdaptor::_attributeAliases; - -std::map UsdMayaAdaptor::_schemaLookup; -std::map> - UsdMayaAdaptor::_attributeAliases; - -UsdMayaAdaptor::UsdMayaAdaptor(const MObject& obj) : _handle(obj) +UsdMayaAdaptor::UsdMayaAdaptor(const MObject& obj) + : _handle(obj) { } @@ -70,13 +63,12 @@ UsdMayaAdaptor::operator bool() const return false; } - MStatus status; + MStatus status; MFnDependencyNode node(_handle.object(), &status); return status; } -std::string -UsdMayaAdaptor::GetMayaNodeName() const +std::string UsdMayaAdaptor::GetMayaNodeName() const { if (!*this) { return std::string(); @@ -85,15 +77,13 @@ UsdMayaAdaptor::GetMayaNodeName() const if (_handle.object().hasFn(MFn::kDagNode)) { MFnDagNode dagNode(_handle.object()); return dagNode.fullPathName().asChar(); - } - else { + } else { MFnDependencyNode depNode(_handle.object()); return depNode.name().asChar(); } } -TfToken -UsdMayaAdaptor::GetUsdTypeName() const +TfToken UsdMayaAdaptor::GetUsdTypeName() const { if (!*this) { return TfToken(); @@ -103,8 +93,7 @@ UsdMayaAdaptor::GetUsdTypeName() const #if USD_VERSION_NUM > 2002 return UsdSchemaRegistry::GetInstance().GetSchemaTypeName(ty); #else - const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance() - .GetPrimDefinition(ty); + const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance().GetPrimDefinition(ty); if (!primDef) { return TfToken(); } @@ -113,14 +102,13 @@ UsdMayaAdaptor::GetUsdTypeName() const #endif } -TfType -UsdMayaAdaptor::GetUsdType() const +TfType UsdMayaAdaptor::GetUsdType() const { if (!*this) { return TfType(); } - MObject object = _handle.object(); + MObject object = _handle.object(); MFnDependencyNode depNode(object); // The adaptor type mapping might be registered externally in a prim writer @@ -132,14 +120,12 @@ UsdMayaAdaptor::GetUsdType() const const auto iter = _schemaLookup.find(depNode.typeName().asChar()); if (iter != _schemaLookup.end()) { return iter->second; - } - else { + } else { return TfType(); } } -TfTokenVector -UsdMayaAdaptor::GetAppliedSchemas() const +TfTokenVector UsdMayaAdaptor::GetAppliedSchemas() const { if (!*this) { return TfTokenVector(); @@ -155,18 +141,13 @@ UsdMayaAdaptor::GetAppliedSchemas() const return TfTokenVector(); } -UsdMayaAdaptor::SchemaAdaptor -UsdMayaAdaptor::GetSchema(const TfType& ty) const +UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::GetSchema(const TfType& ty) const { #if USD_VERSION_NUM > 2002 - const TfToken usdTypeName = - UsdSchemaRegistry::GetInstance().GetSchemaTypeName(ty); + const TfToken usdTypeName = UsdSchemaRegistry::GetInstance().GetSchemaTypeName(ty); #else - const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance() - .GetPrimDefinition(ty); - const TfToken usdTypeName = bool(primDef) ? - primDef->GetNameToken() : - TfToken(); + const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance().GetPrimDefinition(ty); + const TfToken usdTypeName = bool(primDef) ? primDef->GetNameToken() : TfToken(); #endif if (usdTypeName.IsEmpty()) { @@ -176,8 +157,7 @@ UsdMayaAdaptor::GetSchema(const TfType& ty) const return GetSchemaByName(usdTypeName); } -UsdMayaAdaptor::SchemaAdaptor -UsdMayaAdaptor::GetSchemaByName(const TfToken& schemaName) const +UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::GetSchemaByName(const TfToken& schemaName) const { if (!*this) { return SchemaAdaptor(); @@ -185,19 +165,17 @@ UsdMayaAdaptor::GetSchemaByName(const TfToken& schemaName) const #if USD_VERSION_NUM > 2002 // Is this an API schema? - const UsdSchemaRegistry &schemaReg = UsdSchemaRegistry::GetInstance(); - if (const UsdPrimDefinition *primDef = - schemaReg.FindAppliedAPIPrimDefinition(schemaName)) { + const UsdSchemaRegistry& schemaReg = UsdSchemaRegistry::GetInstance(); + if (const UsdPrimDefinition* primDef = schemaReg.FindAppliedAPIPrimDefinition(schemaName)) { return SchemaAdaptor(_handle.object(), schemaName, primDef); } // Is this a typed schema? - else if (const UsdPrimDefinition *primDef = - schemaReg.FindConcretePrimDefinition(schemaName)) { + else if (const UsdPrimDefinition* primDef = schemaReg.FindConcretePrimDefinition(schemaName)) { // XXX // We currently require an exact type match instead of the polymorphic // behavior that actual USD schema classes implement. This is because // we can't currently get the prim definition from the schema registry - // for non-concrete schemas like Imageable (see bug 160436). Ideally, + // for non-concrete schemas like Imageable (see bug 160436). Ideally, // once that's resolved, we would cache a mapping of Maya types to all // compatible USD type names based on schema inheritance. // (In that future world, we'll also want to special case some schemas @@ -206,8 +184,7 @@ UsdMayaAdaptor::GetSchemaByName(const TfToken& schemaName) const if (schemaName == objectTypeName) { // There's an exact MFn::Type match? Easy-peasy. return SchemaAdaptor(_handle.object(), schemaName, primDef); - } - else { + } else { // If no match, do not allow usage of the typed-schema adaptor // mechanism. The importer/exporter have not declared that they // will use the adaptor mechanism to handle this type. @@ -219,13 +196,11 @@ UsdMayaAdaptor::GetSchemaByName(const TfToken& schemaName) const SdfPrimSpecHandle primSpec; // Get the schema's TfType; its name should be registered as an alias. - const TfType schemaType = - TfType::Find().FindDerivedByName(schemaName); + const TfType schemaType = TfType::Find().FindDerivedByName(schemaName); // Is this an API schema? if (schemaType.IsA()) { - primSpec = - UsdSchemaRegistry::GetInstance().GetPrimDefinition(schemaName); + primSpec = UsdSchemaRegistry::GetInstance().GetPrimDefinition(schemaName); } // Is this a typed schema? else if (schemaType.IsA()) { @@ -241,10 +216,8 @@ UsdMayaAdaptor::GetSchemaByName(const TfToken& schemaName) const const TfToken objectTypeName = GetUsdTypeName(); if (schemaName == objectTypeName) { // There's an exact MFn::Type match? Easy-peasy. - primSpec = - UsdSchemaRegistry::GetInstance().GetPrimDefinition(schemaName); - } - else { + primSpec = UsdSchemaRegistry::GetInstance().GetPrimDefinition(schemaName); + } else { // If no match, do not allow usage of the typed-schema adaptor // mechanism. The importer/exporter have not declared that they // will use the adaptor mechanism to handle this type. @@ -258,13 +231,11 @@ UsdMayaAdaptor::GetSchemaByName(const TfToken& schemaName) const #endif // We shouldn't be able to reach this (everything is either typed or API). - TF_CODING_ERROR("'%s' isn't a known API or typed schema", - schemaName.GetText()); + TF_CODING_ERROR("'%s' isn't a known API or typed schema", schemaName.GetText()); return SchemaAdaptor(); } -UsdMayaAdaptor::SchemaAdaptor -UsdMayaAdaptor::GetSchemaOrInheritedSchema(const TfType& ty) const +UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::GetSchemaOrInheritedSchema(const TfType& ty) const { if (!*this) { return SchemaAdaptor(); @@ -273,8 +244,7 @@ UsdMayaAdaptor::GetSchemaOrInheritedSchema(const TfType& ty) const if (ty.IsA()) { // No "promotion" for API schemas. return GetSchema(ty); - } - else if (ty.IsA()) { + } else if (ty.IsA()) { // Can "promote" typed schemas based on inheritance. const TfType objectType = GetUsdType(); if (objectType.IsA(ty)) { @@ -285,47 +255,37 @@ UsdMayaAdaptor::GetSchemaOrInheritedSchema(const TfType& ty) const return SchemaAdaptor(); } -UsdMayaAdaptor::SchemaAdaptor -UsdMayaAdaptor::ApplySchema(const TfType& ty) +UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::ApplySchema(const TfType& ty) { MDGModifier modifier; return ApplySchema(ty, modifier); } -UsdMayaAdaptor::SchemaAdaptor -UsdMayaAdaptor::ApplySchema(const TfType& ty, MDGModifier& modifier) +UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::ApplySchema(const TfType& ty, MDGModifier& modifier) { #if USD_VERSION_NUM > 2002 - const TfToken usdTypeName = - UsdSchemaRegistry::GetInstance().GetSchemaTypeName(ty); + const TfToken usdTypeName = UsdSchemaRegistry::GetInstance().GetSchemaTypeName(ty); #else - const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance() - .GetPrimDefinition(ty); - const TfToken usdTypeName = bool(primDef) ? - primDef->GetNameToken() : - TfToken(); + const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance().GetPrimDefinition(ty); + const TfToken usdTypeName = bool(primDef) ? primDef->GetNameToken() : TfToken(); #endif if (usdTypeName.IsEmpty()) { - TF_CODING_ERROR("Can't find schema definition for type '%s'", - ty.GetTypeName().c_str()); + TF_CODING_ERROR("Can't find schema definition for type '%s'", ty.GetTypeName().c_str()); return SchemaAdaptor(); } return ApplySchemaByName(usdTypeName, modifier); } -UsdMayaAdaptor::SchemaAdaptor -UsdMayaAdaptor::ApplySchemaByName(const TfToken& schemaName) +UsdMayaAdaptor::SchemaAdaptor UsdMayaAdaptor::ApplySchemaByName(const TfToken& schemaName) { MDGModifier modifier; return ApplySchemaByName(schemaName, modifier); } UsdMayaAdaptor::SchemaAdaptor -UsdMayaAdaptor::ApplySchemaByName( - const TfToken& schemaName, - MDGModifier& modifier) +UsdMayaAdaptor::ApplySchemaByName(const TfToken& schemaName, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Adaptor is not valid"); @@ -333,113 +293,90 @@ UsdMayaAdaptor::ApplySchemaByName( } #if USD_VERSION_NUM > 2002 - // Get the "apply" schema definition. If it's registered, there should be a + // Get the "apply" schema definition. If it's registered, there should be a // def. - const UsdPrimDefinition *primDef = - UsdSchemaRegistry::GetInstance().FindAppliedAPIPrimDefinition(schemaName); + const UsdPrimDefinition* primDef + = UsdSchemaRegistry::GetInstance().FindAppliedAPIPrimDefinition(schemaName); if (!primDef) { - TF_CODING_ERROR("'%s' is not an applied API schema", - schemaName.GetText()); + TF_CODING_ERROR("'%s' is not an applied API schema", schemaName.GetText()); return SchemaAdaptor(); } // Add to schema list (if not yet present). TfTokenVector currentSchemas = GetAppliedSchemas(); - if (std::find(currentSchemas.begin(), currentSchemas.end(), schemaName) == - currentSchemas.end()) { + if (std::find(currentSchemas.begin(), currentSchemas.end(), schemaName) + == currentSchemas.end()) { currentSchemas.push_back(schemaName); - SetMetadata( - UsdTokens->apiSchemas, - _GetListOpForTokenVector(currentSchemas), - modifier); + SetMetadata(UsdTokens->apiSchemas, _GetListOpForTokenVector(currentSchemas), modifier); } return SchemaAdaptor(_handle.object(), schemaName, primDef); -#else +#else // Get the schema's TfType; its name should be registered as an alias. - const TfType schemaType = - TfType::Find().FindDerivedByName(schemaName); + const TfType schemaType = TfType::Find().FindDerivedByName(schemaName); // Make sure that this is an API schema. Only API schemas can be applied. if (!schemaType.IsA()) { - TF_CODING_ERROR("'%s' is not a registered API schema", - schemaName.GetText()); + TF_CODING_ERROR("'%s' is not a registered API schema", schemaName.GetText()); return SchemaAdaptor(); } // Make sure that this is an "apply" schema. if (!UsdSchemaRegistry::GetInstance().IsAppliedAPISchema(schemaType)) { - TF_CODING_ERROR("'%s' is not an applied API schema", - schemaName.GetText()); + TF_CODING_ERROR("'%s' is not an applied API schema", schemaName.GetText()); return SchemaAdaptor(); } // Get the schema definition. If it's registered, there should be a def. - SdfPrimSpecHandle primSpec = - UsdSchemaRegistry::GetInstance().GetPrimDefinition(schemaName); + SdfPrimSpecHandle primSpec = UsdSchemaRegistry::GetInstance().GetPrimDefinition(schemaName); if (!primSpec) { - TF_CODING_ERROR("Can't find schema definition for name '%s'", - schemaName.GetText()); + TF_CODING_ERROR("Can't find schema definition for name '%s'", schemaName.GetText()); return SchemaAdaptor(); } // Add to schema list (if not yet present). TfTokenVector currentSchemas = GetAppliedSchemas(); - if (std::find(currentSchemas.begin(), currentSchemas.end(), schemaName) == - currentSchemas.end()) { + if (std::find(currentSchemas.begin(), currentSchemas.end(), schemaName) + == currentSchemas.end()) { currentSchemas.push_back(schemaName); - SetMetadata( - UsdTokens->apiSchemas, - _GetListOpForTokenVector(currentSchemas), - modifier); + SetMetadata(UsdTokens->apiSchemas, _GetListOpForTokenVector(currentSchemas), modifier); } return SchemaAdaptor(_handle.object(), primSpec); #endif } -void -UsdMayaAdaptor::UnapplySchema(const TfType& ty) +void UsdMayaAdaptor::UnapplySchema(const TfType& ty) { MDGModifier modifier; UnapplySchema(ty, modifier); } -void -UsdMayaAdaptor::UnapplySchema(const TfType& ty, MDGModifier& modifier) +void UsdMayaAdaptor::UnapplySchema(const TfType& ty, MDGModifier& modifier) { #if USD_VERSION_NUM > 2002 - const TfToken usdTypeName = - UsdSchemaRegistry::GetInstance().GetSchemaTypeName(ty); + const TfToken usdTypeName = UsdSchemaRegistry::GetInstance().GetSchemaTypeName(ty); #else - const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance() - .GetPrimDefinition(ty); - const TfToken usdTypeName = bool(primDef) ? - primDef->GetNameToken() : - TfToken(); + const SdfPrimSpecHandle primDef = UsdSchemaRegistry::GetInstance().GetPrimDefinition(ty); + const TfToken usdTypeName = bool(primDef) ? primDef->GetNameToken() : TfToken(); #endif if (usdTypeName.IsEmpty()) { - TF_CODING_ERROR("Can't find schema definition for type '%s'", - ty.GetTypeName().c_str()); + TF_CODING_ERROR("Can't find schema definition for type '%s'", ty.GetTypeName().c_str()); return; } UnapplySchemaByName(usdTypeName, modifier); } -void -UsdMayaAdaptor::UnapplySchemaByName(const TfToken& schemaName) +void UsdMayaAdaptor::UnapplySchemaByName(const TfToken& schemaName) { MDGModifier modifier; UnapplySchemaByName(schemaName, modifier); } -void -UsdMayaAdaptor::UnapplySchemaByName( - const TfToken& schemaName, - MDGModifier& modifier) +void UsdMayaAdaptor::UnapplySchemaByName(const TfToken& schemaName, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Adaptor is not valid"); @@ -449,25 +386,16 @@ UsdMayaAdaptor::UnapplySchemaByName( // Remove from schema list. TfTokenVector currentSchemas = GetAppliedSchemas(); currentSchemas.erase( - std::remove( - currentSchemas.begin(), currentSchemas.end(), schemaName), - currentSchemas.end()); + std::remove(currentSchemas.begin(), currentSchemas.end(), schemaName), + currentSchemas.end()); if (currentSchemas.empty()) { ClearMetadata(UsdTokens->apiSchemas, modifier); - } - else { - SetMetadata( - UsdTokens->apiSchemas, - _GetListOpForTokenVector(currentSchemas), - modifier); + } else { + SetMetadata(UsdTokens->apiSchemas, _GetListOpForTokenVector(currentSchemas), modifier); } } -static bool -_GetMetadataUnchecked( - const MFnDependencyNode& node, - const TfToken& key, - VtValue* value) +static bool _GetMetadataUnchecked(const MFnDependencyNode& node, const TfToken& key, VtValue* value) { VtValue fallback = SdfSchema::GetInstance().GetFallback(key); if (fallback.IsEmpty()) { @@ -475,19 +403,19 @@ _GetMetadataUnchecked( } std::string mayaAttrName = _GetMayaAttrNameForMetadataKey(key); - MPlug plug = node.findPlug(mayaAttrName.c_str()); + MPlug plug = node.findPlug(mayaAttrName.c_str()); if (plug.isNull()) { return false; } - TfType ty = fallback.GetType(); + TfType ty = fallback.GetType(); VtValue result = UsdMayaWriteUtil::GetVtValue(plug, ty, TfToken()); if (result.IsEmpty()) { TF_RUNTIME_ERROR( - "Cannot convert plug '%s' into metadata '%s' (%s)", - plug.name().asChar(), - key.GetText(), - ty.GetTypeName().c_str()); + "Cannot convert plug '%s' into metadata '%s' (%s)", + plug.name().asChar(), + key.GetText(), + ty.GetTypeName().c_str()); return false; } @@ -495,14 +423,13 @@ _GetMetadataUnchecked( return true; } -UsdMetadataValueMap -UsdMayaAdaptor::GetAllAuthoredMetadata() const +UsdMetadataValueMap UsdMayaAdaptor::GetAllAuthoredMetadata() const { if (!*this) { return UsdMetadataValueMap(); } - MFnDependencyNode node(_handle.object()); + MFnDependencyNode node(_handle.object()); UsdMetadataValueMap metaMap; for (const TfToken& key : GetPrimMetadataFields()) { VtValue value; @@ -514,8 +441,7 @@ UsdMayaAdaptor::GetAllAuthoredMetadata() const return metaMap; } -bool -UsdMayaAdaptor::GetMetadata(const TfToken& key, VtValue* value) const +bool UsdMayaAdaptor::GetMetadata(const TfToken& key, VtValue* value) const { if (!*this) { return false; @@ -530,18 +456,13 @@ UsdMayaAdaptor::GetMetadata(const TfToken& key, VtValue* value) const return _GetMetadataUnchecked(node, key, value); } -bool -UsdMayaAdaptor::SetMetadata(const TfToken& key, const VtValue& value) +bool UsdMayaAdaptor::SetMetadata(const TfToken& key, const VtValue& value) { MDGModifier modifier; return SetMetadata(key, value, modifier); } -bool -UsdMayaAdaptor::SetMetadata( - const TfToken& key, - const VtValue& value, - MDGModifier& modifier) +bool UsdMayaAdaptor::SetMetadata(const TfToken& key, const VtValue& value, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Adaptor is not valid"); @@ -560,18 +481,16 @@ UsdMayaAdaptor::SetMetadata( VtValue castValue = VtValue::CastToTypeOf(value, fallback); if (castValue.IsEmpty()) { - TF_CODING_ERROR("Can't cast value to type '%s'", - fallback.GetTypeName().c_str()); + TF_CODING_ERROR("Can't cast value to type '%s'", fallback.GetTypeName().c_str()); return false; } - std::string mayaAttrName = _GetMayaAttrNameForMetadataKey(key); - std::string mayaNiceAttrName = key.GetText(); + std::string mayaAttrName = _GetMayaAttrNameForMetadataKey(key); + std::string mayaNiceAttrName = key.GetText(); MFnDependencyNode node(_handle.object()); - TfType ty = fallback.GetType(); - MObject attrObj = UsdMayaReadUtil::FindOrCreateMayaAttr( - ty, TfToken(), SdfVariabilityUniform, - node, mayaAttrName, mayaNiceAttrName, modifier); + TfType ty = fallback.GetType(); + MObject attrObj = UsdMayaReadUtil::FindOrCreateMayaAttr( + ty, TfToken(), SdfVariabilityUniform, node, mayaAttrName, mayaNiceAttrName, modifier); if (attrObj.isNull()) { return false; } @@ -584,15 +503,13 @@ UsdMayaAdaptor::SetMetadata( return true; } -void -UsdMayaAdaptor::ClearMetadata(const TfToken& key) +void UsdMayaAdaptor::ClearMetadata(const TfToken& key) { MDGModifier modifier; ClearMetadata(key, modifier); } -void -UsdMayaAdaptor::ClearMetadata(const TfToken& key, MDGModifier& modifier) +void UsdMayaAdaptor::ClearMetadata(const TfToken& key, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Adaptor is not valid"); @@ -600,7 +517,7 @@ UsdMayaAdaptor::ClearMetadata(const TfToken& key, MDGModifier& modifier) } MFnDependencyNode node(_handle.object()); - std::string mayaAttrName = _GetMayaAttrNameForMetadataKey(key); + std::string mayaAttrName = _GetMayaAttrNameForMetadataKey(key); if (node.hasAttribute(mayaAttrName.c_str())) { MObject attr = node.attribute(mayaAttrName.c_str()); modifier.removeAttribute(_handle.object(), attr); @@ -609,28 +526,24 @@ UsdMayaAdaptor::ClearMetadata(const TfToken& key, MDGModifier& modifier) } /* static */ -TfTokenVector -UsdMayaAdaptor::GetPrimMetadataFields() +TfTokenVector UsdMayaAdaptor::GetPrimMetadataFields() { return SdfSchema::GetInstance().GetMetadataFields(SdfSpecTypePrim); } -template -static TfToken::Set _GetRegisteredSchemas() +template static TfToken::Set _GetRegisteredSchemas() { - TfToken::Set schemas; + TfToken::Set schemas; std::set derivedTypes; TfType::Find().GetAllDerivedTypes(&derivedTypes); - const UsdSchemaRegistry ®istry = UsdSchemaRegistry::GetInstance(); + const UsdSchemaRegistry& registry = UsdSchemaRegistry::GetInstance(); for (const TfType& ty : derivedTypes) { #if USD_VERSION_NUM > 2002 const TfToken usdTypeName = registry.GetSchemaTypeName(ty); #else const SdfPrimSpecHandle primDef = registry.GetPrimDefinition(ty); - const TfToken usdTypeName = bool(primDef) ? - primDef->GetNameToken() : - TfToken(); + const TfToken usdTypeName = bool(primDef) ? primDef->GetNameToken() : TfToken(); #endif if (usdTypeName.IsEmpty()) { @@ -644,64 +557,54 @@ static TfToken::Set _GetRegisteredSchemas() } /* static */ -TfToken::Set -UsdMayaAdaptor::GetRegisteredAPISchemas() +TfToken::Set UsdMayaAdaptor::GetRegisteredAPISchemas() { return _GetRegisteredSchemas(); } /* static */ -TfToken::Set -UsdMayaAdaptor::GetRegisteredTypedSchemas() +TfToken::Set UsdMayaAdaptor::GetRegisteredTypedSchemas() { return _GetRegisteredSchemas(); } /* static */ -void -UsdMayaAdaptor::RegisterTypedSchemaConversion( +void UsdMayaAdaptor::RegisterTypedSchemaConversion( const std::string& nodeTypeName, - const TfType& usdType) + const TfType& usdType) { - const auto iterAndInserted = _schemaLookup.insert( - std::make_pair(nodeTypeName, usdType)); + const auto iterAndInserted = _schemaLookup.insert(std::make_pair(nodeTypeName, usdType)); if (iterAndInserted.second) { - UsdMaya_RegistryHelper::AddUnloader([nodeTypeName]() { - _schemaLookup.erase(nodeTypeName); - }); - } - else { - TF_CODING_ERROR("Typed schema conversion already registered for Maya " - "type %s", nodeTypeName.c_str()); + UsdMaya_RegistryHelper::AddUnloader( + [nodeTypeName]() { _schemaLookup.erase(nodeTypeName); }); + } else { + TF_CODING_ERROR( + "Typed schema conversion already registered for Maya " + "type %s", + nodeTypeName.c_str()); } } /* static */ -void -UsdMayaAdaptor::RegisterAttributeAlias( - const TfToken& attributeName, - const std::string& alias) +void UsdMayaAdaptor::RegisterAttributeAlias(const TfToken& attributeName, const std::string& alias) { std::vector& aliases = _attributeAliases[attributeName]; if (std::find(aliases.begin(), aliases.end(), alias) == aliases.end()) { aliases.push_back(alias); UsdMaya_RegistryHelper::AddUnloader([attributeName, alias]() { - std::vector& aliases = - _attributeAliases[attributeName]; - aliases.erase( - std::remove(aliases.begin(), aliases.end(), alias), - aliases.end()); + std::vector& aliases = _attributeAliases[attributeName]; + aliases.erase(std::remove(aliases.begin(), aliases.end(), alias), aliases.end()); }); - } - else { - TF_CODING_ERROR("Attribute alias '%s' (='%s') already registered", - alias.c_str(), attributeName.GetText()); + } else { + TF_CODING_ERROR( + "Attribute alias '%s' (='%s') already registered", + alias.c_str(), + attributeName.GetText()); } } /* static */ -std::vector -UsdMayaAdaptor::GetAttributeAliases(const TfToken& attributeName) +std::vector UsdMayaAdaptor::GetAttributeAliases(const TfToken& attributeName) { TfRegistryManager::GetInstance().SubscribeTo(); @@ -717,24 +620,26 @@ UsdMayaAdaptor::GetAttributeAliases(const TfToken& attributeName) return result; } - - UsdMayaAdaptor::SchemaAdaptor::SchemaAdaptor() - : _handle(), _schemaDef(nullptr) + : _handle() + , _schemaDef(nullptr) { } #if USD_VERSION_NUM > 2002 UsdMayaAdaptor::SchemaAdaptor::SchemaAdaptor( - const MObjectHandle& handle, - const TfToken &schemaName, - const UsdPrimDefinition *schemaDef) - : _handle(handle), _schemaDef(schemaDef), _schemaName(schemaName) + const MObjectHandle& handle, + const TfToken& schemaName, + const UsdPrimDefinition* schemaDef) + : _handle(handle) + , _schemaDef(schemaDef) + , _schemaName(schemaName) { } #else UsdMayaAdaptor::SchemaAdaptor::SchemaAdaptor( - const MObjectHandle& handle, SdfPrimSpecHandle schemaDef) + const MObjectHandle& handle, + SdfPrimSpecHandle schemaDef) : _handle(handle) , _schemaDef(schemaDef) , _schemaName(schemaDef->GetNameToken()) @@ -748,14 +653,12 @@ UsdMayaAdaptor::SchemaAdaptor::operator bool() const return false; } - MStatus status; + MStatus status; MFnDependencyNode node(_handle.object(), &status); return status; } -std::string -UsdMayaAdaptor::SchemaAdaptor::_GetMayaAttrNameOrAlias( - const TfToken& name) const +std::string UsdMayaAdaptor::SchemaAdaptor::_GetMayaAttrNameOrAlias(const TfToken& name) const { if (!*this) { TF_CODING_ERROR("Schema adaptor is not valid"); @@ -764,7 +667,7 @@ UsdMayaAdaptor::SchemaAdaptor::_GetMayaAttrNameOrAlias( TfRegistryManager::GetInstance().SubscribeTo(); - const MObject thisObject = _handle.object(); + const MObject thisObject = _handle.object(); MFnDependencyNode depNode(thisObject); // If the generated name exists, it is the most preferred name, @@ -789,8 +692,7 @@ UsdMayaAdaptor::SchemaAdaptor::_GetMayaAttrNameOrAlias( return genName; } -UsdMayaAdaptor -UsdMayaAdaptor::SchemaAdaptor::GetNodeAdaptor() const +UsdMayaAdaptor UsdMayaAdaptor::SchemaAdaptor::GetNodeAdaptor() const { if (!*this) { return UsdMayaAdaptor(MObject::kNullObj); @@ -799,8 +701,7 @@ UsdMayaAdaptor::SchemaAdaptor::GetNodeAdaptor() const return UsdMayaAdaptor(_handle.object()); } -TfToken -UsdMayaAdaptor::SchemaAdaptor::GetName() const +TfToken UsdMayaAdaptor::SchemaAdaptor::GetName() const { if (!*this) { return TfToken(); @@ -810,16 +711,14 @@ UsdMayaAdaptor::SchemaAdaptor::GetName() const } #if USD_VERSION_NUM > 2002 -static -SdfAttributeSpecHandle -_GetAttributeSpec(const UsdPrimDefinition *primDef, const TfToken &attrName) +static SdfAttributeSpecHandle +_GetAttributeSpec(const UsdPrimDefinition* primDef, const TfToken& attrName) { return primDef->GetSchemaAttributeSpec(attrName); } #else -static -SdfAttributeSpecHandle -_GetAttributeSpec(const SdfPrimSpecHandle &primSpec, const TfToken &attrName) +static SdfAttributeSpecHandle +_GetAttributeSpec(const SdfPrimSpecHandle& primSpec, const TfToken& attrName) { return primSpec->GetAttributes()[attrName]; } @@ -834,14 +733,16 @@ UsdMayaAdaptor::SchemaAdaptor::GetAttribute(const TfToken& attrName) const SdfAttributeSpecHandle attrDef = _GetAttributeSpec(_schemaDef, attrName); if (!attrDef) { - TF_CODING_ERROR("Attribute '%s' doesn't exist on schema '%s'", - attrName.GetText(), _schemaName.GetText()); + TF_CODING_ERROR( + "Attribute '%s' doesn't exist on schema '%s'", + attrName.GetText(), + _schemaName.GetText()); return AttributeAdaptor(); } - std::string mayaAttrName = _GetMayaAttrNameOrAlias(attrName); + std::string mayaAttrName = _GetMayaAttrNameOrAlias(attrName); MFnDependencyNode node(_handle.object()); - MPlug plug = node.findPlug(mayaAttrName.c_str()); + MPlug plug = node.findPlug(mayaAttrName.c_str()); if (plug.isNull()) { return AttributeAdaptor(); } @@ -857,8 +758,7 @@ UsdMayaAdaptor::SchemaAdaptor::CreateAttribute(const TfToken& attrName) } UsdMayaAdaptor::AttributeAdaptor -UsdMayaAdaptor::SchemaAdaptor::CreateAttribute( - const TfToken& attrName, MDGModifier& modifier) +UsdMayaAdaptor::SchemaAdaptor::CreateAttribute(const TfToken& attrName, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Schema adaptor is not valid"); @@ -867,19 +767,25 @@ UsdMayaAdaptor::SchemaAdaptor::CreateAttribute( SdfAttributeSpecHandle attrDef = _GetAttributeSpec(_schemaDef, attrName); if (!attrDef) { - TF_CODING_ERROR("Attribute '%s' doesn't exist on schema '%s'", - attrName.GetText(), _schemaName.GetText()); + TF_CODING_ERROR( + "Attribute '%s' doesn't exist on schema '%s'", + attrName.GetText(), + _schemaName.GetText()); return AttributeAdaptor(); } - std::string mayaAttrName = _GetMayaAttrNameOrAlias(attrName); - std::string mayaNiceAttrName = attrDef->GetName(); + std::string mayaAttrName = _GetMayaAttrNameOrAlias(attrName); + std::string mayaNiceAttrName = attrDef->GetName(); MFnDependencyNode node(_handle.object()); - bool newAttr = !node.hasAttribute(mayaAttrName.c_str()); + bool newAttr = !node.hasAttribute(mayaAttrName.c_str()); MObject attrObj = UsdMayaReadUtil::FindOrCreateMayaAttr( - attrDef->GetTypeName(), attrDef->GetVariability(), - node, mayaAttrName, mayaNiceAttrName, modifier); + attrDef->GetTypeName(), + attrDef->GetVariability(), + node, + mayaAttrName, + mayaNiceAttrName, + modifier); if (attrObj.isNull()) { return AttributeAdaptor(); } @@ -889,23 +795,19 @@ UsdMayaAdaptor::SchemaAdaptor::CreateAttribute( // Set the fallback value as the initial value of the attribute, if // it exists. (There's not much point in setting the "default" value in // Maya, because it won't behave like the fallback value in USD.) - UsdMayaReadUtil::SetMayaAttr( - plug, attrDef->GetDefaultValue(), modifier); + UsdMayaReadUtil::SetMayaAttr(plug, attrDef->GetDefaultValue(), modifier); } return AttributeAdaptor(plug, attrDef); } -void -UsdMayaAdaptor::SchemaAdaptor::RemoveAttribute(const TfToken& attrName) +void UsdMayaAdaptor::SchemaAdaptor::RemoveAttribute(const TfToken& attrName) { MDGModifier modifier; RemoveAttribute(attrName, modifier); } -void -UsdMayaAdaptor::SchemaAdaptor::RemoveAttribute( - const TfToken& attrName, MDGModifier& modifier) +void UsdMayaAdaptor::SchemaAdaptor::RemoveAttribute(const TfToken& attrName, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Schema adaptor is not valid"); @@ -914,12 +816,14 @@ UsdMayaAdaptor::SchemaAdaptor::RemoveAttribute( SdfAttributeSpecHandle attrDef = _GetAttributeSpec(_schemaDef, attrName); if (!attrDef) { - TF_CODING_ERROR("Attribute '%s' doesn't exist on schema '%s'", - attrName.GetText(), _schemaName.GetText()); + TF_CODING_ERROR( + "Attribute '%s' doesn't exist on schema '%s'", + attrName.GetText(), + _schemaName.GetText()); return; } - std::string mayaAttrName = _GetMayaAttrNameOrAlias(attrName); + std::string mayaAttrName = _GetMayaAttrNameOrAlias(attrName); MFnDependencyNode node(_handle.object()); if (node.hasAttribute(mayaAttrName.c_str())) { MObject attr = node.attribute(mayaAttrName.c_str()); @@ -928,15 +832,14 @@ UsdMayaAdaptor::SchemaAdaptor::RemoveAttribute( } } -TfTokenVector -UsdMayaAdaptor::SchemaAdaptor::GetAuthoredAttributeNames() const +TfTokenVector UsdMayaAdaptor::SchemaAdaptor::GetAuthoredAttributeNames() const { if (!*this) { return TfTokenVector(); } MFnDependencyNode node(_handle.object()); - TfTokenVector result; + TfTokenVector result; #if USD_VERSION_NUM > 2002 for (const TfToken& propName : _schemaDef->GetPropertyNames()) { if (_schemaDef->GetSpecType(propName) == SdfSpecTypeAttribute) { @@ -958,8 +861,7 @@ UsdMayaAdaptor::SchemaAdaptor::GetAuthoredAttributeNames() const return result; } -TfTokenVector -UsdMayaAdaptor::SchemaAdaptor::GetAttributeNames() const +TfTokenVector UsdMayaAdaptor::SchemaAdaptor::GetAttributeNames() const { if (!*this) { return TfTokenVector(); @@ -982,28 +884,32 @@ UsdMayaAdaptor::SchemaAdaptor::GetAttributeNames() const } #if USD_VERSION_NUM > 2002 -const UsdPrimDefinition * -UsdMayaAdaptor::SchemaAdaptor::GetSchemaDefinition() const +const UsdPrimDefinition* UsdMayaAdaptor::SchemaAdaptor::GetSchemaDefinition() const { return _schemaDef; } #else -const SdfPrimSpecHandle -UsdMayaAdaptor::SchemaAdaptor::GetSchemaDefinition() const +const SdfPrimSpecHandle UsdMayaAdaptor::SchemaAdaptor::GetSchemaDefinition() const { return _schemaDef; } #endif UsdMayaAdaptor::AttributeAdaptor::AttributeAdaptor() - : _plug(), _node(), _attr(), _attrDef(nullptr) + : _plug() + , _node() + , _attr() + , _attrDef(nullptr) { } UsdMayaAdaptor::AttributeAdaptor::AttributeAdaptor( - const MPlug& plug, SdfAttributeSpecHandle attrDef) - : _plug(plug), _node(plug.node()), _attr(plug.attribute()), - _attrDef(attrDef) + const MPlug& plug, + SdfAttributeSpecHandle attrDef) + : _plug(plug) + , _node(plug.node()) + , _attr(plug.attribute()) + , _attrDef(attrDef) { } @@ -1013,7 +919,7 @@ UsdMayaAdaptor::AttributeAdaptor::operator bool() const return false; } - MStatus status; + MStatus status; MFnDependencyNode depNode(_node.object(), &status); if (!status) { return false; @@ -1027,8 +933,7 @@ UsdMayaAdaptor::AttributeAdaptor::operator bool() const return depNode.hasAttribute(attr.name()); } -UsdMayaAdaptor -UsdMayaAdaptor::AttributeAdaptor::GetNodeAdaptor() const +UsdMayaAdaptor UsdMayaAdaptor::AttributeAdaptor::GetNodeAdaptor() const { if (!*this) { return UsdMayaAdaptor(MObject::kNullObj); @@ -1037,8 +942,7 @@ UsdMayaAdaptor::AttributeAdaptor::GetNodeAdaptor() const return UsdMayaAdaptor(_plug.node()); } -TfToken -UsdMayaAdaptor::AttributeAdaptor::GetName() const +TfToken UsdMayaAdaptor::AttributeAdaptor::GetName() const { if (!*this) { return TfToken(); @@ -1047,15 +951,13 @@ UsdMayaAdaptor::AttributeAdaptor::GetName() const return _attrDef->GetNameToken(); } -bool -UsdMayaAdaptor::AttributeAdaptor::Get(VtValue* value) const +bool UsdMayaAdaptor::AttributeAdaptor::Get(VtValue* value) const { if (!*this) { return false; } - VtValue result = UsdMayaWriteUtil::GetVtValue(_plug, - _attrDef->GetTypeName()); + VtValue result = UsdMayaWriteUtil::GetVtValue(_plug, _attrDef->GetTypeName()); if (result.IsEmpty()) { return false; } @@ -1064,17 +966,13 @@ UsdMayaAdaptor::AttributeAdaptor::Get(VtValue* value) const return true; } -bool -UsdMayaAdaptor::AttributeAdaptor::Set(const VtValue& newValue) +bool UsdMayaAdaptor::AttributeAdaptor::Set(const VtValue& newValue) { MDGModifier modifier; return Set(newValue, modifier); } -bool -UsdMayaAdaptor::AttributeAdaptor::Set( - const VtValue& newValue, - MDGModifier& modifier) +bool UsdMayaAdaptor::AttributeAdaptor::Set(const VtValue& newValue, MDGModifier& modifier) { if (!*this) { TF_CODING_ERROR("Attribute adaptor is not valid"); @@ -1084,8 +982,7 @@ UsdMayaAdaptor::AttributeAdaptor::Set( return UsdMayaReadUtil::SetMayaAttr(_plug, newValue, modifier); } -const SdfAttributeSpecHandle -UsdMayaAdaptor::AttributeAdaptor::GetAttributeDefinition() const +const SdfAttributeSpecHandle UsdMayaAdaptor::AttributeAdaptor::GetAttributeDefinition() const { return _attrDef; } diff --git a/lib/mayaUsd/fileio/utils/adaptor.h b/lib/mayaUsd/fileio/utils/adaptor.h index ca4e9a056a..b53669db17 100644 --- a/lib/mayaUsd/fileio/utils/adaptor.h +++ b/lib/mayaUsd/fileio/utils/adaptor.h @@ -16,19 +16,19 @@ #ifndef PXRUSDMAYA_ADAPTOR_H #define PXRUSDMAYA_ADAPTOR_H -#include -#include -#include +#include -#include #include #include +#include #include #include #include #include -#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -121,7 +121,8 @@ PXR_NAMESPACE_OPEN_SCOPE /// schema.CreateAttribute('fakeAttributeName') /// # Error: ErrorException /// \endcode -class UsdMayaAdaptor { +class UsdMayaAdaptor +{ public: /// The AttributeAdaptor stores a mapping between a USD schema attribute and /// a Maya plug, enabling conversions between the two. @@ -137,10 +138,11 @@ class UsdMayaAdaptor { /// attribute, and Maya attributes always have values, it's not possible to /// Clear() the authored value. You can, however, completely remove the /// attribute by using UsdMayaAdaptor::SchemaAdaptor::RemoveAttribute(). - class AttributeAdaptor { - MPlug _plug; - MObjectHandle _node; - MObjectHandle _attr; + class AttributeAdaptor + { + MPlug _plug; + MObjectHandle _node; + MObjectHandle _attr; SdfAttributeSpecHandle _attrDef; public: @@ -169,8 +171,8 @@ class UsdMayaAdaptor { /// the requested type, or if this attribute adaptor is invalid. /// \warning Unlike UsdAttribute::Get(), this function never performs /// fallback value resolution, since Maya attributes always have values. - template - bool Get(T* value) const { + template bool Get(T* value) const + { VtValue v; if (Get(&v) && v.IsHolding()) { *value = v.Get(); @@ -215,10 +217,11 @@ class UsdMayaAdaptor { /// stored on the Maya object, which include attributes previously set /// using an adaptor and attributes automatically adapted from USD during /// import. - class SchemaAdaptor { + class SchemaAdaptor + { MObjectHandle _handle; #if USD_VERSION_NUM > 2002 - const UsdPrimDefinition *_schemaDef; + const UsdPrimDefinition* _schemaDef; #else SdfPrimSpecHandle _schemaDef; #endif @@ -230,9 +233,10 @@ class UsdMayaAdaptor { #if USD_VERSION_NUM > 2002 MAYAUSD_CORE_PUBLIC - SchemaAdaptor(const MObjectHandle& object, - const TfToken &schemaName, - const UsdPrimDefinition *schemaPrimDef); + SchemaAdaptor( + const MObjectHandle& object, + const TfToken& schemaName, + const UsdPrimDefinition* schemaPrimDef); #else MAYAUSD_CORE_PUBLIC SchemaAdaptor(const MObjectHandle& object, SdfPrimSpecHandle schemaDef); @@ -284,9 +288,7 @@ class UsdMayaAdaptor { /// \note This overload will call doIt() on the MDGModifier; thus /// any actions will have been committed when the function returns. MAYAUSD_CORE_PUBLIC - AttributeAdaptor CreateAttribute( - const TfToken& attrName, - MDGModifier& modifier); + AttributeAdaptor CreateAttribute(const TfToken& attrName, MDGModifier& modifier); /// Removes the named attribute adaptor from this Maya object. Raises a /// coding error if \p attrName does not exist on the schema, or if @@ -318,8 +320,8 @@ class UsdMayaAdaptor { /// Gets the prim definition for this schema from the schema registry. /// Returns a null pointer if this schema adaptor is invalid. MAYAUSD_CORE_PUBLIC - const UsdPrimDefinition *GetSchemaDefinition() const; -#else + const UsdPrimDefinition* GetSchemaDefinition() const; +#else /// Gets the prim spec for this schema from the schema registry. /// Returns a null handle if this schema adaptor is invalid. MAYAUSD_CORE_PUBLIC @@ -392,8 +394,8 @@ class UsdMayaAdaptor { MAYAUSD_CORE_PUBLIC SchemaAdaptor GetSchemaByName(const TfToken& schemaName) const; - template - SchemaAdaptor GetSchemaOrInheritedSchema() const { + template SchemaAdaptor GetSchemaOrInheritedSchema() const + { return GetSchemaOrInheritedSchema(TfType::Find()); } @@ -459,9 +461,7 @@ class UsdMayaAdaptor { /// \note This overload will call doIt() on the MDGModifier; thus any /// actions will have been committed when the function returns. MAYAUSD_CORE_PUBLIC - SchemaAdaptor ApplySchemaByName( - const TfToken& schemaName, - MDGModifier& modifier); + SchemaAdaptor ApplySchemaByName(const TfToken& schemaName, MDGModifier& modifier); /// Removes the given API schema from the adaptor's apiSchemas metadata. /// Raises a coding error if the adaptor is invalid. @@ -518,10 +518,7 @@ class UsdMayaAdaptor { /// \note This overload will call doIt() on the MDGModifier; thus any /// actions will have been committed when the function returns. MAYAUSD_CORE_PUBLIC - bool SetMetadata( - const TfToken& key, - const VtValue& value, - MDGModifier& modifier); + bool SetMetadata(const TfToken& key, const VtValue& value, MDGModifier& modifier); /// Clears the authored \p key's value on this Maya object. /// Raises a coding error if the adaptor is invalid. @@ -552,8 +549,8 @@ class UsdMayaAdaptor { /// the same Maya type again will overwrite the previous registration. /// However, multiple Maya types may map to the same TfType. MAYAUSD_CORE_PUBLIC - static void RegisterTypedSchemaConversion( - const std::string& nodeTypeName, const TfType& usdType); + static void + RegisterTypedSchemaConversion(const std::string& nodeTypeName, const TfType& usdType); /// For backwards compatibility only: when upgrading any pre-existing code /// to use the adaptor mechanism, you can instruct the adaptor to recognize @@ -570,16 +567,14 @@ class UsdMayaAdaptor { /// it always uses the generated name. /// \sa UsdMayaAdaptor::SchemaAdaptor::CreateAttribute() MAYAUSD_CORE_PUBLIC - static void RegisterAttributeAlias( - const TfToken& attributeName, const std::string& alias); + static void RegisterAttributeAlias(const TfToken& attributeName, const std::string& alias); /// Gets the name of all possible Maya attribute names for the given USD /// schema \p attributeName, in the order in which the aliases were /// registered. The default generated name is always the zeroth item in the /// returned vector. MAYAUSD_CORE_PUBLIC - static std::vector GetAttributeAliases( - const TfToken& attributeName); + static std::vector GetAttributeAliases(const TfToken& attributeName); private: MObjectHandle _handle; @@ -608,12 +603,11 @@ class UsdMayaAdaptor { /// \endcode /// /// \sa UsdMayaAdaptor::RegisterTypedSchemaConversion() -#define PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(mayaTypeName, schemaType)\ -TF_REGISTRY_FUNCTION(UsdMayaAdaptor)\ -{\ - UsdMayaAdaptor::RegisterTypedSchemaConversion(\ - #mayaTypeName, TfType::Find());\ -} +#define PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(mayaTypeName, schemaType) \ + TF_REGISTRY_FUNCTION(UsdMayaAdaptor) \ + { \ + UsdMayaAdaptor::RegisterTypedSchemaConversion(#mayaTypeName, TfType::Find()); \ + } /// Registers an \p alias string for the given \p attrName token or string. /// @@ -622,11 +616,11 @@ TF_REGISTRY_FUNCTION(UsdMayaAdaptor)\ /// that all the aliases are registered at the correct time. /// /// \sa UsdMayaAdaptor::RegisterAttributeAlias() -#define PXRUSDMAYA_REGISTER_ADAPTOR_ATTRIBUTE_ALIAS(attrName, alias)\ -TF_REGISTRY_FUNCTION(UsdMayaAdaptor)\ -{\ - UsdMayaAdaptor::RegisterAttributeAlias(TfToken(attrName), alias);\ -} +#define PXRUSDMAYA_REGISTER_ADAPTOR_ATTRIBUTE_ALIAS(attrName, alias) \ + TF_REGISTRY_FUNCTION(UsdMayaAdaptor) \ + { \ + UsdMayaAdaptor::RegisterAttributeAlias(TfToken(attrName), alias); \ + } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/utils/jointWriteUtils.cpp b/lib/mayaUsd/fileio/utils/jointWriteUtils.cpp index 9bbf930222..43bc015238 100644 --- a/lib/mayaUsd/fileio/utils/jointWriteUtils.cpp +++ b/lib/mayaUsd/fileio/utils/jointWriteUtils.cpp @@ -17,6 +17,27 @@ // #include "jointWriteUtils.h" +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + #include #include #include @@ -34,48 +55,22 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PRIVATE_TOKENS( - _tokens, - (Animation) - (Skeleton) -); +TF_DEFINE_PRIVATE_TOKENS(_tokens, (Animation)(Skeleton)); -SdfPath -UsdMayaJointUtil::getAnimationPath(const SdfPath& skelPath) +SdfPath UsdMayaJointUtil::getAnimationPath(const SdfPath& skelPath) { return skelPath.AppendChild(_tokens->Animation); } -void -UsdMayaJointUtil::getJointHierarchyComponents(const MDagPath& dagPath, - MDagPath* skelXformPath, - MDagPath* jointHierarchyRootPath, - std::vector* joints) +void UsdMayaJointUtil::getJointHierarchyComponents( + const MDagPath& dagPath, + MDagPath* skelXformPath, + MDagPath* jointHierarchyRootPath, + std::vector* joints) { - if(joints) + if (joints) joints->clear(); *skelXformPath = MDagPath(); @@ -102,7 +97,7 @@ UsdMayaJointUtil::getJointHierarchyComponents(const MDagPath& dagPath, } } - if(skelXformPath->isValid()) { + if (skelXformPath->isValid()) { *jointHierarchyRootPath = *skelXformPath; } else { *jointHierarchyRootPath = dagPath; @@ -110,10 +105,10 @@ UsdMayaJointUtil::getJointHierarchyComponents(const MDagPath& dagPath, } } -VtTokenArray -UsdMayaJointUtil::getJointNames(const std::vector& joints, - const MDagPath& rootDagPath, - bool stripNamespaces) +VtTokenArray UsdMayaJointUtil::getJointNames( + const std::vector& joints, + const MDagPath& rootDagPath, + bool stripNamespaces) { MDagPath skelXformPath, jointHierarchyRootPath; getJointHierarchyComponents(rootDagPath, &skelXformPath, &jointHierarchyRootPath); @@ -130,20 +125,19 @@ UsdMayaJointUtil::getJointNames(const std::vector& joints, // only error inside the UsdMaya_SkelBindingsProcessor so that we // consolidate the SkelRoot-related errors in one place. rootPath = SdfPath::AbsoluteRootPath(); - } - else { + } else { // Joint name relative to joint root. rootPath = UsdMayaUtil::MDagPathToUsdPath( - jointHierarchyRootPath, - /*mergeTransformAndShape*/ false, - stripNamespaces); + jointHierarchyRootPath, + /*mergeTransformAndShape*/ false, + stripNamespaces); } VtTokenArray result; for (const MDagPath& joint : joints) { SdfPath path = UsdMayaUtil::MDagPathToUsdPath( - joint, /*mergeTransformAndShape*/ false, stripNamespaces); + joint, /*mergeTransformAndShape*/ false, stripNamespaces); result.push_back(path.MakeRelativePath(rootPath).GetToken()); } return result; @@ -152,20 +146,18 @@ UsdMayaJointUtil::getJointNames(const std::vector& joints, /// Gets the expected path where a skeleton will be exported for /// the given root joint. The skeleton both binds a skeleton and /// holds root transformations of the joint hierarchy. -SdfPath -UsdMayaJointUtil::getSkeletonPath(const MDagPath& rootJoint, bool stripNamespaces) +SdfPath UsdMayaJointUtil::getSkeletonPath(const MDagPath& rootJoint, bool stripNamespaces) { return UsdMayaUtil::MDagPathToUsdPath( rootJoint, /*mergeTransformAndShape*/ false, stripNamespaces); } -MObject -UsdMayaJointUtil::getSkinCluster(const MDagPath& dagPath) +MObject UsdMayaJointUtil::getSkinCluster(const MDagPath& dagPath) { MObject currentDagObject = dagPath.node(); - MItDependencyGraph itDG(currentDagObject, MFn::kSkinClusterFilter, - MItDependencyGraph::kUpstream); + MItDependencyGraph itDG( + currentDagObject, MFn::kSkinClusterFilter, MItDependencyGraph::kUpstream); if (itDG.isDone()) { // No skin clusters. return MObject::kNullObj; @@ -184,11 +176,10 @@ UsdMayaJointUtil::getSkinCluster(const MDagPath& dagPath) return skinClusterObj; } -MObject -UsdMayaJointUtil::getInputMesh(const MFnSkinCluster& skinCluster) +MObject UsdMayaJointUtil::getInputMesh(const MFnSkinCluster& skinCluster) { MStatus status; - MPlug inputPlug = skinCluster.findPlug("input", true, &status); + MPlug inputPlug = skinCluster.findPlug("input", true, &status); CHECK_MSTATUS_AND_RETURN(status, MObject()); MPlug inputPlug0 = inputPlug.elementByLogicalIndex(0, &status); @@ -197,48 +188,47 @@ UsdMayaJointUtil::getInputMesh(const MFnSkinCluster& skinCluster) MPlug inputGeometry = inputPlug0.child(0, &status); CHECK_MSTATUS_AND_RETURN(status, MObject()); - MObject inputGeometryObj = - inputGeometry.asMObject(MDGContext::fsNormal, &status); + MObject inputGeometryObj = inputGeometry.asMObject(MDGContext::fsNormal, &status); CHECK_MSTATUS_AND_RETURN(status, MObject()); if (!inputGeometryObj.hasFn(MFn::kMesh)) { TF_WARN( - "%s is not a mesh; unable to obtain input mesh for %s", - inputGeometry.name().asChar(), skinCluster.name().asChar()); + "%s is not a mesh; unable to obtain input mesh for %s", + inputGeometry.name().asChar(), + skinCluster.name().asChar()); return MObject(); } return inputGeometryObj; } -int -UsdMayaJointUtil::getCompressedSkinWeights( const MFnMesh& mesh, - const MFnSkinCluster& skinCluster, - VtIntArray* usdJointIndices, - VtFloatArray* usdJointWeights) +int UsdMayaJointUtil::getCompressedSkinWeights( + const MFnMesh& mesh, + const MFnSkinCluster& skinCluster, + VtIntArray* usdJointIndices, + VtFloatArray* usdJointWeights) { // Get the single output dag path from the skin cluster. // Note that we can't get the dag path from the mesh because it's the input // mesh (and also may not have a dag path). MDagPath outputDagPath; - MStatus status = skinCluster.getPathAtIndex(0, outputDagPath); + MStatus status = skinCluster.getPathAtIndex(0, outputDagPath); if (!status) { TF_CODING_ERROR( - "Calling code should have guaranteed that skinCluster " - "'%s' has at least one output", - skinCluster.name().asChar()); + "Calling code should have guaranteed that skinCluster " + "'%s' has at least one output", + skinCluster.name().asChar()); return 0; } // Get all of the weights from the skinCluster in one batch. - unsigned int numVertices = mesh.numVertices(); + unsigned int numVertices = mesh.numVertices(); MFnSingleIndexedComponent components; components.create(MFn::kMeshVertComponent); components.setCompleteData(numVertices); MDoubleArray weights; unsigned int numInfluences; - skinCluster.getWeights( - outputDagPath, components.object(), weights, numInfluences); + skinCluster.getWeights(outputDagPath, components.object(), weights, numInfluences); // Determine how many influence/weight "slots" we actually need per point. // For example, if there are the joints /a, /a/b, and /a/c, but each point @@ -248,7 +238,7 @@ UsdMayaJointUtil::getCompressedSkinWeights( const MFnMesh& mesh, for (unsigned int vert = 0; vert < numVertices; ++vert) { // Looping through each vertex. const unsigned int offset = vert * numInfluences; - int influenceCount = 0; + int influenceCount = 0; for (unsigned int i = 0; i < numInfluences; ++i) { // Looping through each weight for vertex. if (weights[offset + i] != 0.0) { @@ -263,7 +253,7 @@ UsdMayaJointUtil::getCompressedSkinWeights( const MFnMesh& mesh, for (unsigned int vert = 0; vert < numVertices; ++vert) { // Looping through each vertex. const unsigned int inputOffset = vert * numInfluences; - int outputOffset = vert * maxInfluenceCount; + int outputOffset = vert * maxInfluenceCount; for (unsigned int i = 0; i < numInfluences; ++i) { // Looping through each weight for vertex. float weight = weights[inputOffset + i]; @@ -277,10 +267,10 @@ UsdMayaJointUtil::getCompressedSkinWeights( const MFnMesh& mesh, return maxInfluenceCount; } -void -UsdMayaJointUtil::warnForPostDeformationTransform(const SdfPath& path, - const MDagPath& deformedMeshDag, - const MFnSkinCluster& skinCluster) +void UsdMayaJointUtil::warnForPostDeformationTransform( + const SdfPath& path, + const MDagPath& deformedMeshDag, + const MFnSkinCluster& skinCluster) { MStatus status; @@ -289,31 +279,29 @@ UsdMayaJointUtil::warnForPostDeformationTransform(const SdfPath& path, return; MMatrix bindPreMatrix; - if (UsdMayaUtil::getPlugMatrix( - skinCluster, "bindPreMatrix", &bindPreMatrix)) { - - if (!GfIsClose(GfMatrix4d(deformedMeshWorldXf.matrix), - GfMatrix4d(bindPreMatrix.matrix), 1e-5)) { - TF_WARN("Mesh <%s> appears to have a non-identity post-deformation " - "transform (the 'bindPreMatrix' property of the skinCluster " - "does not match the inclusive matrix of the deformed mesh). " - "The resulting skinning in USD may be incorrect.", - path.GetText()); + if (UsdMayaUtil::getPlugMatrix(skinCluster, "bindPreMatrix", &bindPreMatrix)) { + + if (!GfIsClose( + GfMatrix4d(deformedMeshWorldXf.matrix), GfMatrix4d(bindPreMatrix.matrix), 1e-5)) { + TF_WARN( + "Mesh <%s> appears to have a non-identity post-deformation " + "transform (the 'bindPreMatrix' property of the skinCluster " + "does not match the inclusive matrix of the deformed mesh). " + "The resulting skinning in USD may be incorrect.", + path.GetText()); } } } -bool -UsdMayaJointUtil::getGeomBindTransform(const MFnSkinCluster& skinCluster, - GfMatrix4d* geomBindXf) +bool UsdMayaJointUtil::getGeomBindTransform( + const MFnSkinCluster& skinCluster, + GfMatrix4d* geomBindXf) { MMatrix geomWorldRestXf; - if (!UsdMayaUtil::getPlugMatrix( - skinCluster, "geomMatrix", &geomWorldRestXf)) { + if (!UsdMayaUtil::getPlugMatrix(skinCluster, "geomMatrix", &geomWorldRestXf)) { // All skinClusters should have geomMatrix, but if not... TF_RUNTIME_ERROR( - "Couldn't read geomMatrix from skinCluster '%s'", - skinCluster.name().asChar()); + "Couldn't read geomMatrix from skinCluster '%s'", skinCluster.name().asChar()); return false; } @@ -321,54 +309,49 @@ UsdMayaJointUtil::getGeomBindTransform(const MFnSkinCluster& skinCluster, return true; } - -bool -UsdMayaJointUtil::writeJointInfluences(const MFnSkinCluster& skinCluster, - const MFnMesh& inMesh, - const UsdSkelBindingAPI& binding) +bool UsdMayaJointUtil::writeJointInfluences( + const MFnSkinCluster& skinCluster, + const MFnMesh& inMesh, + const UsdSkelBindingAPI& binding) { // The data in the skinCluster is essentially already in the same format // as UsdSkel expects, but we're going to compress it by only outputting // the nonzero weights. - VtIntArray jointIndices; + VtIntArray jointIndices; VtFloatArray jointWeights; - int maxInfluenceCount = getCompressedSkinWeights( - inMesh, skinCluster, &jointIndices, &jointWeights); + int maxInfluenceCount + = getCompressedSkinWeights(inMesh, skinCluster, &jointIndices, &jointWeights); if (maxInfluenceCount <= 0) return false; UsdSkelSortInfluences(&jointIndices, &jointWeights, maxInfluenceCount); - UsdGeomPrimvar indicesPrimvar = - binding.CreateJointIndicesPrimvar(false, maxInfluenceCount); + UsdGeomPrimvar indicesPrimvar = binding.CreateJointIndicesPrimvar(false, maxInfluenceCount); indicesPrimvar.Set(jointIndices); - UsdGeomPrimvar weightsPrimvar = - binding.CreateJointWeightsPrimvar(false, maxInfluenceCount); + UsdGeomPrimvar weightsPrimvar = binding.CreateJointWeightsPrimvar(false, maxInfluenceCount); weightsPrimvar.Set(jointWeights); return true; } -bool -UsdMayaJointUtil::writeJointOrder(const MDagPath& rootJoint, - const std::vector& jointDagPaths, - const UsdSkelBindingAPI& binding, - const bool stripNamespaces) +bool UsdMayaJointUtil::writeJointOrder( + const MDagPath& rootJoint, + const std::vector& jointDagPaths, + const UsdSkelBindingAPI& binding, + const bool stripNamespaces) { // Get joint name tokens how PxrUsdTranslators_JointWriter would generate // them. We don't need to check that they actually exist. - VtTokenArray jointNames = UsdMayaJointUtil::getJointNames( jointDagPaths, - rootJoint, - stripNamespaces); + VtTokenArray jointNames + = UsdMayaJointUtil::getJointNames(jointDagPaths, rootJoint, stripNamespaces); binding.CreateJointsAttr().Set(jointNames); return true; } -MDagPath -UsdMayaJointUtil::getRootJoint(const std::vector& jointDagPaths) +MDagPath UsdMayaJointUtil::getRootJoint(const std::vector& jointDagPaths) { MDagPath uniqueRoot; @@ -389,8 +372,7 @@ UsdMayaJointUtil::getRootJoint(const std::vector& jointDagPaths) if (!(uniqueRoot == rootmostJoint)) { return MDagPath(); } - } - else { + } else { uniqueRoot = rootmostJoint; } } @@ -398,13 +380,13 @@ UsdMayaJointUtil::getRootJoint(const std::vector& jointDagPaths) return uniqueRoot; } -MObject -UsdMayaJointUtil::writeSkinningData(UsdGeomMesh& primSchema, - const SdfPath& usdPath, - const MDagPath& dagPath, - SdfPath& skelPath, - const bool stripNamespaces, - UsdUtilsSparseValueWriter* valueWriter) +MObject UsdMayaJointUtil::writeSkinningData( + UsdGeomMesh& primSchema, + const SdfPath& usdPath, + const MDagPath& dagPath, + SdfPath& skelPath, + const bool stripNamespaces, + UsdUtilsSparseValueWriter* valueWriter) { // Figure out if we even have a skin cluster in the first place. MObject skinClusterObj = UsdMayaJointUtil::getSkinCluster(dagPath); @@ -447,20 +429,20 @@ UsdMayaJointUtil::writeSkinningData(UsdGeomMesh& primSchema, } // Write everything to USD once we know that we have OK data. - const UsdSkelBindingAPI bindingAPI = - UsdMayaTranslatorUtil::GetAPISchemaForAuthoring(primSchema.GetPrim()); - - if (UsdMayaJointUtil::writeJointInfluences(skinCluster, inMesh, bindingAPI)){ - UsdMayaJointUtil::writeJointOrder(rootJoint, - jointDagPaths, - bindingAPI, - stripNamespaces); + const UsdSkelBindingAPI bindingAPI + = UsdMayaTranslatorUtil::GetAPISchemaForAuthoring(primSchema.GetPrim()); + + if (UsdMayaJointUtil::writeJointInfluences(skinCluster, inMesh, bindingAPI)) { + UsdMayaJointUtil::writeJointOrder(rootJoint, jointDagPaths, bindingAPI, stripNamespaces); } GfMatrix4d geomBindTransform; - if (UsdMayaJointUtil::getGeomBindTransform(skinCluster,&geomBindTransform)) { - UsdMayaWriteUtil::SetAttribute(bindingAPI.CreateGeomBindTransformAttr(), - &geomBindTransform, UsdTimeCode::Default(), valueWriter); + if (UsdMayaJointUtil::getGeomBindTransform(skinCluster, &geomBindTransform)) { + UsdMayaWriteUtil::SetAttribute( + bindingAPI.CreateGeomBindTransformAttr(), + &geomBindTransform, + UsdTimeCode::Default(), + valueWriter); } UsdMayaJointUtil::warnForPostDeformationTransform(usdPath, dagPath, skinCluster); @@ -469,10 +451,9 @@ UsdMayaJointUtil::writeSkinningData(UsdGeomMesh& primSchema, // Export will create a Skeleton at the location corresponding to // the root joint. Configure this mesh to be bound to the same skel. - bindingAPI.CreateSkeletonRel().SetTargets({skelPath}); + bindingAPI.CreateSkeletonRel().SetTargets({ skelPath }); return inMeshObj; } - PXR_NAMESPACE_CLOSE_SCOPE \ No newline at end of file diff --git a/lib/mayaUsd/fileio/utils/jointWriteUtils.h b/lib/mayaUsd/fileio/utils/jointWriteUtils.h index 246c4a0267..dcbb589fea 100644 --- a/lib/mayaUsd/fileio/utils/jointWriteUtils.h +++ b/lib/mayaUsd/fileio/utils/jointWriteUtils.h @@ -21,156 +21,158 @@ #include -#include -#include -#include -#include - -#include #include #include #include #include +#include #include #include -#include #include #include -#include #include +#include +#include + +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE // Utilities for dealing with writing out joint and skin data. -namespace UsdMayaJointUtil -{ - /// Gets all of the components of the joint hierarchy rooted at \p dagPath. - /// The \p skelXformPath will hold the path to a joint that defines - /// the transform of a UsdSkelSkeleton. It may be invalid if no - /// joint explicitly defines that transform. - /// The \p joints array, if provided, will be filled with the ordered set of - /// joint paths, excluding the set of joints described above. - /// The \p jointHierarchyRootPath will hold the common parent path of - /// all of the returned joints. - MAYAUSD_CORE_PUBLIC - void getJointHierarchyComponents(const MDagPath& dagPath, - MDagPath* skelXformPath, - MDagPath* jointHierarchyRootPath, - std::vector* joints=nullptr); - - MAYAUSD_CORE_PUBLIC - SdfPath getAnimationPath(const SdfPath& skelPath); - - /// Gets the joint name tokens for the given dag paths, assuming a joint - /// hierarchy with the given root joint. - MAYAUSD_CORE_PUBLIC - VtTokenArray getJointNames(const std::vector& joints, - const MDagPath& rootJoint, - bool stripNamespaces); - - /// Gets the expected path where a skeleton will be exported for - /// the given root joint. The skeleton both binds a skeleton and - /// holds root transformations of the joint hierarchy. - MAYAUSD_CORE_PUBLIC - SdfPath getSkeletonPath(const MDagPath& rootJoint, bool stripNamespaces); - - /// Gets the closest upstream skin cluster for the mesh at the given dag path. - /// Warns if there is more than one skin cluster. - MAYAUSD_CORE_PUBLIC - MObject getSkinCluster(const MDagPath& dagPath); - - /// Finds the input (pre-skin) mesh for the given skin cluster. - /// Warning, do not use MFnSkinCluster::getInputGeometry; it will give you - /// the wrong results (or rather, not the ones we want here). - /// Given the following (simplified) DG: - /// pCubeShape1Orig.worldMesh[0] -> tweak1.inputGeometry - /// tweak1.outputGeometry[0] -> skinCluster1.input[0].inputGeometry - /// skinCluster1.outputGeometry[0] -> pCubeShape1.inMesh - /// Requesting the input geometry for skinCluster1 will give you the mesh - /// pCubeShape1Orig - /// and not - /// tweak1.outputGeometry - /// as desired for this use case. - /// For best results, read skinCluster1.input[0].inputGeometry directly. - /// Note that the Maya documentation states "a skinCluster node can deform - /// only a single geometry" [1] so we are free to ignore any input geometries - /// after the first one. - /// [1]: http://help.autodesk.com/view/MAYAUL/2018/ENU/?guid=__cpp_ref_class_m_fn_skin_cluster_html - MAYAUSD_CORE_PUBLIC - MObject getInputMesh(const MFnSkinCluster& skinCluster); - - /// Gets skin weights, and compresses them into the form expected by - /// UsdSkelBindingAPI, which allows us to omit zero-weight influences from the - /// joint weights list. - MAYAUSD_CORE_PUBLIC - int getCompressedSkinWeights(const MFnMesh& mesh, - const MFnSkinCluster& skinCluster, - VtIntArray* usdJointIndices, - VtFloatArray* usdJointWeights); - - /// Check if a skinned primitive has an unsupported post-deformation - /// transformation. These transformations aren't represented in UsdSkel. - /// - /// When a SkinCluster deforms meshes, the results are transformed back into the - /// space of the mesh. The output is then plugged up to the final mesh, which - /// has its own transform. Usually this change in transformation -- from putting - /// the deformation results back into the space of the source mesh, and then - /// transforming the result by the output mesh -- share the same transformation, - /// such that there's no overall change in transformation. This is not always - /// the case. In particular, 'broken' rigs may have the transformations out of - /// sync (the result of which being that the deformed meshes drift away from the - /// skeleton that drives them). - /// - /// We have no nice way of encoding a mesh-specific post-deformation transform - /// in UsdSkel, and so can only try and warn the user. - MAYAUSD_CORE_PUBLIC - void warnForPostDeformationTransform(const SdfPath& path, - const MDagPath& deformedMeshDag, - const MFnSkinCluster& skinCluster); - - /// Compute the geomBindTransform for a mesh using \p skinCluster. - MAYAUSD_CORE_PUBLIC - bool getGeomBindTransform(const MFnSkinCluster& skinCluster, GfMatrix4d* geomBindXf); - - /// Gets the unique root joint of the given joint dag paths, or an invalid - /// MDagPath if there is no such unique joint (i.e. the joints form two - /// separate joint hierarchies). Currently, we don't support skin bound to - /// multiple joint hierarchies. - MAYAUSD_CORE_PUBLIC - MDagPath getRootJoint(const std::vector& jointDagPaths); - - /// Compute and write joint influences. - MAYAUSD_CORE_PUBLIC - bool writeJointInfluences(const MFnSkinCluster& skinCluster, - const MFnMesh& inMesh, - const UsdSkelBindingAPI& binding); - - MAYAUSD_CORE_PUBLIC - bool writeJointOrder(const MDagPath& rootJoint, - const std::vector& jointDagPaths, - const UsdSkelBindingAPI& binding, - const bool stripNamespaces); - - - /// Writes skeleton skinning data for the mesh if it has skin clusters. - /// This method will internally determine, based on the job export args, - /// whether the prim has skinning data and whether it is eligible for - /// skinning data export. - /// If skinning data is successfully exported, then returns the pre-skin - /// mesh object. Otherwise, if no skeleton data was exported (whether there - /// was an error, or this mesh had no skinning, or this mesh was skipped), - /// returns a null MObject. - /// This should only be called once at the default time. - MAYAUSD_CORE_PUBLIC - MObject writeSkinningData(UsdGeomMesh& primSchema, - const SdfPath& usdPath, - const MDagPath& dagPath, - SdfPath& skelPath, - const bool stripNamespaces, - UsdUtilsSparseValueWriter* valueWriter); +namespace UsdMayaJointUtil { +/// Gets all of the components of the joint hierarchy rooted at \p dagPath. +/// The \p skelXformPath will hold the path to a joint that defines +/// the transform of a UsdSkelSkeleton. It may be invalid if no +/// joint explicitly defines that transform. +/// The \p joints array, if provided, will be filled with the ordered set of +/// joint paths, excluding the set of joints described above. +/// The \p jointHierarchyRootPath will hold the common parent path of +/// all of the returned joints. +MAYAUSD_CORE_PUBLIC +void getJointHierarchyComponents( + const MDagPath& dagPath, + MDagPath* skelXformPath, + MDagPath* jointHierarchyRootPath, + std::vector* joints = nullptr); + +MAYAUSD_CORE_PUBLIC +SdfPath getAnimationPath(const SdfPath& skelPath); + +/// Gets the joint name tokens for the given dag paths, assuming a joint +/// hierarchy with the given root joint. +MAYAUSD_CORE_PUBLIC +VtTokenArray +getJointNames(const std::vector& joints, const MDagPath& rootJoint, bool stripNamespaces); + +/// Gets the expected path where a skeleton will be exported for +/// the given root joint. The skeleton both binds a skeleton and +/// holds root transformations of the joint hierarchy. +MAYAUSD_CORE_PUBLIC +SdfPath getSkeletonPath(const MDagPath& rootJoint, bool stripNamespaces); + +/// Gets the closest upstream skin cluster for the mesh at the given dag path. +/// Warns if there is more than one skin cluster. +MAYAUSD_CORE_PUBLIC +MObject getSkinCluster(const MDagPath& dagPath); + +/// Finds the input (pre-skin) mesh for the given skin cluster. +/// Warning, do not use MFnSkinCluster::getInputGeometry; it will give you +/// the wrong results (or rather, not the ones we want here). +/// Given the following (simplified) DG: +/// pCubeShape1Orig.worldMesh[0] -> tweak1.inputGeometry +/// tweak1.outputGeometry[0] -> skinCluster1.input[0].inputGeometry +/// skinCluster1.outputGeometry[0] -> pCubeShape1.inMesh +/// Requesting the input geometry for skinCluster1 will give you the mesh +/// pCubeShape1Orig +/// and not +/// tweak1.outputGeometry +/// as desired for this use case. +/// For best results, read skinCluster1.input[0].inputGeometry directly. +/// Note that the Maya documentation states "a skinCluster node can deform +/// only a single geometry" [1] so we are free to ignore any input geometries +/// after the first one. +/// [1]: http://help.autodesk.com/view/MAYAUL/2018/ENU/?guid=__cpp_ref_class_m_fn_skin_cluster_html +MAYAUSD_CORE_PUBLIC +MObject getInputMesh(const MFnSkinCluster& skinCluster); + +/// Gets skin weights, and compresses them into the form expected by +/// UsdSkelBindingAPI, which allows us to omit zero-weight influences from the +/// joint weights list. +MAYAUSD_CORE_PUBLIC +int getCompressedSkinWeights( + const MFnMesh& mesh, + const MFnSkinCluster& skinCluster, + VtIntArray* usdJointIndices, + VtFloatArray* usdJointWeights); + +/// Check if a skinned primitive has an unsupported post-deformation +/// transformation. These transformations aren't represented in UsdSkel. +/// +/// When a SkinCluster deforms meshes, the results are transformed back into the +/// space of the mesh. The output is then plugged up to the final mesh, which +/// has its own transform. Usually this change in transformation -- from putting +/// the deformation results back into the space of the source mesh, and then +/// transforming the result by the output mesh -- share the same transformation, +/// such that there's no overall change in transformation. This is not always +/// the case. In particular, 'broken' rigs may have the transformations out of +/// sync (the result of which being that the deformed meshes drift away from the +/// skeleton that drives them). +/// +/// We have no nice way of encoding a mesh-specific post-deformation transform +/// in UsdSkel, and so can only try and warn the user. +MAYAUSD_CORE_PUBLIC +void warnForPostDeformationTransform( + const SdfPath& path, + const MDagPath& deformedMeshDag, + const MFnSkinCluster& skinCluster); + +/// Compute the geomBindTransform for a mesh using \p skinCluster. +MAYAUSD_CORE_PUBLIC +bool getGeomBindTransform(const MFnSkinCluster& skinCluster, GfMatrix4d* geomBindXf); + +/// Gets the unique root joint of the given joint dag paths, or an invalid +/// MDagPath if there is no such unique joint (i.e. the joints form two +/// separate joint hierarchies). Currently, we don't support skin bound to +/// multiple joint hierarchies. +MAYAUSD_CORE_PUBLIC +MDagPath getRootJoint(const std::vector& jointDagPaths); + +/// Compute and write joint influences. +MAYAUSD_CORE_PUBLIC +bool writeJointInfluences( + const MFnSkinCluster& skinCluster, + const MFnMesh& inMesh, + const UsdSkelBindingAPI& binding); + +MAYAUSD_CORE_PUBLIC +bool writeJointOrder( + const MDagPath& rootJoint, + const std::vector& jointDagPaths, + const UsdSkelBindingAPI& binding, + const bool stripNamespaces); + +/// Writes skeleton skinning data for the mesh if it has skin clusters. +/// This method will internally determine, based on the job export args, +/// whether the prim has skinning data and whether it is eligible for +/// skinning data export. +/// If skinning data is successfully exported, then returns the pre-skin +/// mesh object. Otherwise, if no skeleton data was exported (whether there +/// was an error, or this mesh had no skinning, or this mesh was skipped), +/// returns a null MObject. +/// This should only be called once at the default time. +MAYAUSD_CORE_PUBLIC +MObject writeSkinningData( + UsdGeomMesh& primSchema, + const SdfPath& usdPath, + const MDagPath& dagPath, + SdfPath& skelPath, + const bool stripNamespaces, + UsdUtilsSparseValueWriter* valueWriter); } // namespace UsdMayaJointUtil - PXR_NAMESPACE_CLOSE_SCOPE #endif \ No newline at end of file diff --git a/lib/mayaUsd/fileio/utils/meshReadUtils.cpp b/lib/mayaUsd/fileio/utils/meshReadUtils.cpp index 23e31ff1ba..b341b1745e 100644 --- a/lib/mayaUsd/fileio/utils/meshReadUtils.cpp +++ b/lib/mayaUsd/fileio/utils/meshReadUtils.cpp @@ -17,6 +17,21 @@ // #include "meshReadUtils.h" +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + #include #include #include @@ -34,25 +49,9 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PUBLIC_TOKENS(UsdMayaMeshPrimvarTokens, - PXRUSDMAYA_MESH_PRIMVAR_TOKENS); +TF_DEFINE_PUBLIC_TOKENS(UsdMayaMeshPrimvarTokens, PXRUSDMAYA_MESH_PRIMVAR_TOKENS); // These tokens are supported Maya attributes used for Mesh surfaces TF_DEFINE_PRIVATE_TOKENS( @@ -68,517 +67,512 @@ TF_DEFINE_PRIVATE_TOKENS( // This token is deprecated as it is from OpenSubdiv 2 and the USD // schema now conforms to OpenSubdiv 3, but we continue to look for it // and translate to the equivalent new value for backwards compatibility. - (USD_faceVaryingInterpolateBoundary) -); + (USD_faceVaryingInterpolateBoundary)); PXRUSDMAYA_REGISTER_ADAPTOR_ATTRIBUTE_ALIAS( - UsdGeomTokens->subdivisionScheme, - "USD_subdivisionScheme"); + UsdGeomTokens->subdivisionScheme, + "USD_subdivisionScheme"); PXRUSDMAYA_REGISTER_ADAPTOR_ATTRIBUTE_ALIAS( - UsdGeomTokens->interpolateBoundary, - "USD_interpolateBoundary"); + UsdGeomTokens->interpolateBoundary, + "USD_interpolateBoundary"); PXRUSDMAYA_REGISTER_ADAPTOR_ATTRIBUTE_ALIAS( - UsdGeomTokens->faceVaryingLinearInterpolation, - "USD_faceVaryingLinearInterpolation"); - -namespace + UsdGeomTokens->faceVaryingLinearInterpolation, + "USD_faceVaryingLinearInterpolation"); + +namespace { +bool addCreaseSet( + const std::string& rootName, + double creaseLevel, + MSelectionList& componentList, + MStatus* statusOK) { - bool addCreaseSet( const std::string &rootName, - double creaseLevel, - MSelectionList &componentList, - MStatus *statusOK ) - { - // Crease Set functionality is native to Maya, but undocumented and not - // directly supported in the API. The below implementation is derived from - // the editor code in the maya distro at: - // - // .../lib/python2.7/site-packages/maya/app/general/creaseSetEditor.py - - MObject creasePartitionObj; - *statusOK = UsdMayaUtil::GetMObjectByName(":creasePartition", - creasePartitionObj); - - if (creasePartitionObj.isNull()) { - statusOK->clear(); - - // There is no documented way to create a shared node through the C++ API - const std::string partitionName = MGlobal::executeCommandStringResult( - "createNode \"partition\" -shared -name \":creasePartition\"").asChar(); - - *statusOK = UsdMayaUtil::GetMObjectByName(partitionName, - creasePartitionObj); - if (!*statusOK) { - return false; - } - } + // Crease Set functionality is native to Maya, but undocumented and not + // directly supported in the API. The below implementation is derived from + // the editor code in the maya distro at: + // + // .../lib/python2.7/site-packages/maya/app/general/creaseSetEditor.py - MFnPartition creasePartition( creasePartitionObj, statusOK ); - if (!*statusOK) return false; + MObject creasePartitionObj; + *statusOK = UsdMayaUtil::GetMObjectByName(":creasePartition", creasePartitionObj); - std::string creaseSetname = - TfStringPrintf("%s_creaseSet#",rootName.c_str()); + if (creasePartitionObj.isNull()) { + statusOK->clear(); - MFnDependencyNode creaseSetFn; - MObject creaseSetObj = - creaseSetFn.create("creaseSet", creaseSetname.c_str(), statusOK ); - if (!*statusOK) return false; + // There is no documented way to create a shared node through the C++ API + const std::string partitionName + = MGlobal::executeCommandStringResult( + "createNode \"partition\" -shared -name \":creasePartition\"") + .asChar(); - MPlug levelPlug = creaseSetFn.findPlug("creaseLevel",false, statusOK); - if (!*statusOK) return false; + *statusOK = UsdMayaUtil::GetMObjectByName(partitionName, creasePartitionObj); + if (!*statusOK) { + return false; + } + } - *statusOK = levelPlug.setValue(creaseLevel); - if (!*statusOK) return false; + MFnPartition creasePartition(creasePartitionObj, statusOK); + if (!*statusOK) + return false; - *statusOK = creasePartition.addMember(creaseSetObj); - if (!*statusOK) return false; + std::string creaseSetname = TfStringPrintf("%s_creaseSet#", rootName.c_str()); - MFnSet creaseSet( creaseSetObj, statusOK ); - if (!*statusOK) return false; + MFnDependencyNode creaseSetFn; + MObject creaseSetObj = creaseSetFn.create("creaseSet", creaseSetname.c_str(), statusOK); + if (!*statusOK) + return false; - *statusOK = creaseSet.addMembers( componentList ); - if (!*statusOK) return false; + MPlug levelPlug = creaseSetFn.findPlug("creaseLevel", false, statusOK); + if (!*statusOK) + return false; - return true; - } + *statusOK = levelPlug.setValue(creaseLevel); + if (!*statusOK) + return false; - MIntArray - getMayaFaceVertexAssignmentIds( const MFnMesh& meshFn, - const TfToken& interpolation, - const VtIntArray& assignmentIndices, - const int unauthoredValuesIndex) - { - MIntArray valueIds(meshFn.numFaceVertices(), -1); - - MItMeshFaceVertex itFV(meshFn.object()); - unsigned int fvi = 0; - for (itFV.reset(); !itFV.isDone(); itFV.next(), ++fvi) { - int valueId = 0; - if (interpolation == UsdGeomTokens->constant) { - valueId = 0; - } else if (interpolation == UsdGeomTokens->uniform) { - valueId = itFV.faceId(); - } else if (interpolation == UsdGeomTokens->vertex) { - valueId = itFV.vertId(); - } else if (interpolation == UsdGeomTokens->faceVarying) { - valueId = fvi; - } + *statusOK = creasePartition.addMember(creaseSetObj); + if (!*statusOK) + return false; - if (static_cast(valueId) < assignmentIndices.size()) { - // The data is indexed, so consult the indices array for the - // correct index into the data. - valueId = assignmentIndices[valueId]; + MFnSet creaseSet(creaseSetObj, statusOK); + if (!*statusOK) + return false; - if (valueId == unauthoredValuesIndex) { - // This component had no authored value, so leave it unassigned. - continue; - } - } + *statusOK = creaseSet.addMembers(componentList); + if (!*statusOK) + return false; - valueIds[fvi] = valueId; + return true; +} + +MIntArray getMayaFaceVertexAssignmentIds( + const MFnMesh& meshFn, + const TfToken& interpolation, + const VtIntArray& assignmentIndices, + const int unauthoredValuesIndex) +{ + MIntArray valueIds(meshFn.numFaceVertices(), -1); + + MItMeshFaceVertex itFV(meshFn.object()); + unsigned int fvi = 0; + for (itFV.reset(); !itFV.isDone(); itFV.next(), ++fvi) { + int valueId = 0; + if (interpolation == UsdGeomTokens->constant) { + valueId = 0; + } else if (interpolation == UsdGeomTokens->uniform) { + valueId = itFV.faceId(); + } else if (interpolation == UsdGeomTokens->vertex) { + valueId = itFV.vertId(); + } else if (interpolation == UsdGeomTokens->faceVarying) { + valueId = fvi; + } + + if (static_cast(valueId) < assignmentIndices.size()) { + // The data is indexed, so consult the indices array for the + // correct index into the data. + valueId = assignmentIndices[valueId]; + + if (valueId == unauthoredValuesIndex) { + // This component had no authored value, so leave it unassigned. + continue; + } } - return valueIds; + valueIds[fvi] = valueId; } - bool - assignUVSetPrimvarToMesh(const UsdGeomPrimvar& primvar, MFnMesh& meshFn, bool hasDefaultUVSet) - { - const TfToken& primvarName = primvar.GetPrimvarName(); + return valueIds; +} - // Get the raw data before applying any indexing. - VtVec2fArray uvValues; - if (!primvar.Get(&uvValues) || uvValues.empty()) { - TF_WARN("Could not read UV values from primvar '%s' on mesh: %s", - primvarName.GetText(), - primvar.GetAttr().GetPrimPath().GetText()); - return false; - } +bool assignUVSetPrimvarToMesh(const UsdGeomPrimvar& primvar, MFnMesh& meshFn, bool hasDefaultUVSet) +{ + const TfToken& primvarName = primvar.GetPrimvarName(); + + // Get the raw data before applying any indexing. + VtVec2fArray uvValues; + if (!primvar.Get(&uvValues) || uvValues.empty()) { + TF_WARN( + "Could not read UV values from primvar '%s' on mesh: %s", + primvarName.GetText(), + primvar.GetAttr().GetPrimPath().GetText()); + return false; + } - // This is the number of UV values assuming the primvar is NOT indexed. - VtIntArray assignmentIndices; - if (primvar.GetIndices(&assignmentIndices)) { - // The primvar IS indexed, so the indices array is what determines the - // number of UV values. - int unauthoredValuesIndex = primvar.GetUnauthoredValuesIndex(); - - // Replace any index equal to unauthoredValuesIndex with -1. - if (unauthoredValuesIndex != -1) { - for (int& index : assignmentIndices) { - if (index == unauthoredValuesIndex) { - index = -1; - } + // This is the number of UV values assuming the primvar is NOT indexed. + VtIntArray assignmentIndices; + if (primvar.GetIndices(&assignmentIndices)) { + // The primvar IS indexed, so the indices array is what determines the + // number of UV values. + int unauthoredValuesIndex = primvar.GetUnauthoredValuesIndex(); + + // Replace any index equal to unauthoredValuesIndex with -1. + if (unauthoredValuesIndex != -1) { + for (int& index : assignmentIndices) { + if (index == unauthoredValuesIndex) { + index = -1; } } + } - // Furthermore, if unauthoredValuesIndex is valid for uvValues, then - // remove it from uvValues and shift the indices (we don't want to - // import the unauthored value into Maya, where it has no meaning). - if (unauthoredValuesIndex >= 0 && - static_cast(unauthoredValuesIndex) < uvValues.size()) { - // This moves [unauthoredValuesIndex + 1, end) to - // [unauthoredValuesIndex, end - 1), erasing the - // unauthoredValuesIndex. - std::move( - uvValues.begin() + unauthoredValuesIndex + 1, - uvValues.end(), - uvValues.begin() + unauthoredValuesIndex); - uvValues.pop_back(); - - for (int& index : assignmentIndices) { - if (index > unauthoredValuesIndex) { - index = index - 1; - } + // Furthermore, if unauthoredValuesIndex is valid for uvValues, then + // remove it from uvValues and shift the indices (we don't want to + // import the unauthored value into Maya, where it has no meaning). + if (unauthoredValuesIndex >= 0 + && static_cast(unauthoredValuesIndex) < uvValues.size()) { + // This moves [unauthoredValuesIndex + 1, end) to + // [unauthoredValuesIndex, end - 1), erasing the + // unauthoredValuesIndex. + std::move( + uvValues.begin() + unauthoredValuesIndex + 1, + uvValues.end(), + uvValues.begin() + unauthoredValuesIndex); + uvValues.pop_back(); + + for (int& index : assignmentIndices) { + if (index > unauthoredValuesIndex) { + index = index - 1; } } } + } - // Go through the UV data and add the U and V values to separate - // MFloatArrays. - MFloatArray uCoords; - MFloatArray vCoords; - for (const GfVec2f& v : uvValues) { - uCoords.append(v[0]); - vCoords.append(v[1]); - } - - MStatus status{MS::kSuccess}; - MString uvSetName(primvarName.GetText()); - bool createUVSet = true; + // Go through the UV data and add the U and V values to separate + // MFloatArrays. + MFloatArray uCoords; + MFloatArray vCoords; + for (const GfVec2f& v : uvValues) { + uCoords.append(v[0]); + vCoords.append(v[1]); + } - if (primvarName == UsdUtilsGetPrimaryUVSetName() && UsdMayaReadUtil::ReadSTAsMap1()) { - // We assume that the primary USD UV set maps to Maya's default 'map1' - // set which always exists, so we shouldn't try to create it. - uvSetName = UsdMayaMeshPrimvarTokens->DefaultMayaTexcoordName.GetText(); + MStatus status { MS::kSuccess }; + MString uvSetName(primvarName.GetText()); + bool createUVSet = true; + + if (primvarName == UsdUtilsGetPrimaryUVSetName() && UsdMayaReadUtil::ReadSTAsMap1()) { + // We assume that the primary USD UV set maps to Maya's default 'map1' + // set which always exists, so we shouldn't try to create it. + uvSetName = UsdMayaMeshPrimvarTokens->DefaultMayaTexcoordName.GetText(); + createUVSet = false; + } else if (!hasDefaultUVSet) { // If map1 still exists, we rename and re-use it: + MStringArray uvSetNames; + meshFn.getUVSetNames(uvSetNames); + if (uvSetNames[0] == UsdMayaMeshPrimvarTokens->DefaultMayaTexcoordName.GetText()) { + meshFn.renameUVSet( + UsdMayaMeshPrimvarTokens->DefaultMayaTexcoordName.GetText(), uvSetName); createUVSet = false; - } else if (!hasDefaultUVSet) { // If map1 still exists, we rename and re-use it: - MStringArray uvSetNames; - meshFn.getUVSetNames(uvSetNames); - if (uvSetNames[0] == UsdMayaMeshPrimvarTokens->DefaultMayaTexcoordName.GetText()) { - meshFn.renameUVSet( - UsdMayaMeshPrimvarTokens->DefaultMayaTexcoordName.GetText(), uvSetName); - createUVSet = false; - } } + } - if (createUVSet) { - status = meshFn.createUVSet(uvSetName); - if (status != MS::kSuccess) { - TF_WARN("Unable to create UV set '%s' for mesh: %s", - uvSetName.asChar(), - meshFn.fullPathName().asChar()); - return false; - } - } - - // The following two lines should have no effect on user-visible state but - // prevent a Maya crash in MFnMesh.setUVs after creating a crease set. - // XXX this workaround is needed pending a fix by Autodesk. - MString currentSet = meshFn.currentUVSetName(); - meshFn.setCurrentUVSetName(currentSet); - - // Create UVs on the mesh from the values we collected out of the primvar. - // We'll assign mesh components to these values below. - status = meshFn.setUVs(uCoords, vCoords, &uvSetName); + if (createUVSet) { + status = meshFn.createUVSet(uvSetName); if (status != MS::kSuccess) { - TF_WARN("Unable to set UV data on UV set '%s' for mesh: %s", - uvSetName.asChar(), - meshFn.fullPathName().asChar()); + TF_WARN( + "Unable to create UV set '%s' for mesh: %s", + uvSetName.asChar(), + meshFn.fullPathName().asChar()); return false; } + } - const TfToken& interpolation = primvar.GetInterpolation(); + // The following two lines should have no effect on user-visible state but + // prevent a Maya crash in MFnMesh.setUVs after creating a crease set. + // XXX this workaround is needed pending a fix by Autodesk. + MString currentSet = meshFn.currentUVSetName(); + meshFn.setCurrentUVSetName(currentSet); + + // Create UVs on the mesh from the values we collected out of the primvar. + // We'll assign mesh components to these values below. + status = meshFn.setUVs(uCoords, vCoords, &uvSetName); + if (status != MS::kSuccess) { + TF_WARN( + "Unable to set UV data on UV set '%s' for mesh: %s", + uvSetName.asChar(), + meshFn.fullPathName().asChar()); + return false; + } - // Build an array of value assignments for each face vertex in the mesh. - // Any assignments left as -1 will not be assigned a value. - MIntArray uvIds = getMayaFaceVertexAssignmentIds(meshFn, - interpolation, - assignmentIndices, - -1); + const TfToken& interpolation = primvar.GetInterpolation(); + + // Build an array of value assignments for each face vertex in the mesh. + // Any assignments left as -1 will not be assigned a value. + MIntArray uvIds = getMayaFaceVertexAssignmentIds(meshFn, interpolation, assignmentIndices, -1); + + MIntArray vertexCounts; + MIntArray vertexList; + status = meshFn.getVertices(vertexCounts, vertexList); + if (status != MS::kSuccess) { + TF_WARN( + "Could not get vertex counts for UV set '%s' on mesh: %s", + uvSetName.asChar(), + meshFn.fullPathName().asChar()); + return false; + } - MIntArray vertexCounts; - MIntArray vertexList; - status = meshFn.getVertices(vertexCounts, vertexList); - if (status != MS::kSuccess) { - TF_WARN("Could not get vertex counts for UV set '%s' on mesh: %s", - uvSetName.asChar(), - meshFn.fullPathName().asChar()); - return false; - } + status = meshFn.assignUVs(vertexCounts, uvIds, &uvSetName); + if (status != MS::kSuccess) { + TF_WARN( + "Could not assign UV values to UV set '%s' on mesh: %s", + uvSetName.asChar(), + meshFn.fullPathName().asChar()); + return false; + } - status = meshFn.assignUVs(vertexCounts, uvIds, &uvSetName); - if (status != MS::kSuccess) { - TF_WARN("Could not assign UV values to UV set '%s' on mesh: %s", - uvSetName.asChar(), - meshFn.fullPathName().asChar()); - return false; - } + return true; +} - return true; - } +bool assignColorSetPrimvarToMesh( + const UsdGeomMesh& mesh, + const UsdGeomPrimvar& primvar, + MFnMesh& meshFn) +{ - bool - assignColorSetPrimvarToMesh(const UsdGeomMesh& mesh, - const UsdGeomPrimvar& primvar, - MFnMesh& meshFn) - { - - const TfToken& primvarName = primvar.GetPrimvarName(); - const SdfValueTypeName& typeName = primvar.GetTypeName(); - - MString colorSetName(primvarName.GetText()); - - // If the primvar is displayOpacity and it is a FloatArray, check if - // displayColor is authored. If not, we'll import this 'displayOpacity' - // primvar as a 'displayColor' color set. This supports cases where the - // user created a single channel value for displayColor. - // Note that if BOTH displayColor and displayOpacity are authored, they will - // be imported as separate color sets. We do not attempt to combine them - // into a single color set. - if (primvarName == UsdMayaMeshPrimvarTokens->DisplayOpacityColorSetName && - typeName == SdfValueTypeNames->FloatArray) { - if (!UsdMayaRoundTripUtil::IsAttributeUserAuthored(mesh.GetDisplayColorPrimvar())) { - colorSetName = UsdMayaMeshPrimvarTokens->DisplayColorColorSetName.GetText(); - } + const TfToken& primvarName = primvar.GetPrimvarName(); + const SdfValueTypeName& typeName = primvar.GetTypeName(); + + MString colorSetName(primvarName.GetText()); + + // If the primvar is displayOpacity and it is a FloatArray, check if + // displayColor is authored. If not, we'll import this 'displayOpacity' + // primvar as a 'displayColor' color set. This supports cases where the + // user created a single channel value for displayColor. + // Note that if BOTH displayColor and displayOpacity are authored, they will + // be imported as separate color sets. We do not attempt to combine them + // into a single color set. + if (primvarName == UsdMayaMeshPrimvarTokens->DisplayOpacityColorSetName + && typeName == SdfValueTypeNames->FloatArray) { + if (!UsdMayaRoundTripUtil::IsAttributeUserAuthored(mesh.GetDisplayColorPrimvar())) { + colorSetName = UsdMayaMeshPrimvarTokens->DisplayColorColorSetName.GetText(); } + } - // We'll need to convert colors from linear to display if this color set is - // for display colors. - const bool isDisplayColor = - (colorSetName == UsdMayaMeshPrimvarTokens->DisplayColorColorSetName.GetText()); - - // Get the raw data before applying any indexing. We'll only populate one - // of these arrays based on the primvar's typeName, and we'll also set the - // color representation so we know which array to use later. - VtFloatArray alphaArray; - VtVec3fArray rgbArray; - VtVec4fArray rgbaArray; - MFnMesh::MColorRepresentation colorRep; - size_t numValues = 0; - - MStatus status = MS::kSuccess; - - if (typeName == SdfValueTypeNames->FloatArray) { - colorRep = MFnMesh::kAlpha; - if (!primvar.Get(&alphaArray) || alphaArray.empty()) { - status = MS::kFailure; - } else { - numValues = alphaArray.size(); - } - } else if (typeName == SdfValueTypeNames->Float3Array || - typeName == SdfValueTypeNames->Color3fArray) { - colorRep = MFnMesh::kRGB; - if (!primvar.Get(&rgbArray) || rgbArray.empty()) { - status = MS::kFailure; - } else { - numValues = rgbArray.size(); - } - } else if (typeName == SdfValueTypeNames->Float4Array || - typeName == SdfValueTypeNames->Color4fArray) { - colorRep = MFnMesh::kRGBA; - if (!primvar.Get(&rgbaArray) || rgbaArray.empty()) { - status = MS::kFailure; - } else { - numValues = rgbaArray.size(); - } + // We'll need to convert colors from linear to display if this color set is + // for display colors. + const bool isDisplayColor + = (colorSetName == UsdMayaMeshPrimvarTokens->DisplayColorColorSetName.GetText()); + + // Get the raw data before applying any indexing. We'll only populate one + // of these arrays based on the primvar's typeName, and we'll also set the + // color representation so we know which array to use later. + VtFloatArray alphaArray; + VtVec3fArray rgbArray; + VtVec4fArray rgbaArray; + MFnMesh::MColorRepresentation colorRep; + size_t numValues = 0; + + MStatus status = MS::kSuccess; + + if (typeName == SdfValueTypeNames->FloatArray) { + colorRep = MFnMesh::kAlpha; + if (!primvar.Get(&alphaArray) || alphaArray.empty()) { + status = MS::kFailure; } else { - TF_WARN("Unsupported color set primvar type '%s' for primvar '%s' on " - "mesh: %s", - typeName.GetAsToken().GetText(), - primvarName.GetText(), - primvar.GetAttr().GetPrimPath().GetText()); - return false; + numValues = alphaArray.size(); } - - if (status != MS::kSuccess || numValues == 0) { - TF_WARN("Could not read color set values from primvar '%s' on mesh: %s", - primvarName.GetText(), - primvar.GetAttr().GetPrimPath().GetText()); - return false; + } else if ( + typeName == SdfValueTypeNames->Float3Array || typeName == SdfValueTypeNames->Color3fArray) { + colorRep = MFnMesh::kRGB; + if (!primvar.Get(&rgbArray) || rgbArray.empty()) { + status = MS::kFailure; + } else { + numValues = rgbArray.size(); } + } else if ( + typeName == SdfValueTypeNames->Float4Array || typeName == SdfValueTypeNames->Color4fArray) { + colorRep = MFnMesh::kRGBA; + if (!primvar.Get(&rgbaArray) || rgbaArray.empty()) { + status = MS::kFailure; + } else { + numValues = rgbaArray.size(); + } + } else { + TF_WARN( + "Unsupported color set primvar type '%s' for primvar '%s' on " + "mesh: %s", + typeName.GetAsToken().GetText(), + primvarName.GetText(), + primvar.GetAttr().GetPrimPath().GetText()); + return false; + } - VtIntArray assignmentIndices; - int unauthoredValuesIndex = -1; - if (primvar.GetIndices(&assignmentIndices)) { - // The primvar IS indexed, so the indices array is what determines the - // number of color values. - numValues = assignmentIndices.size(); - unauthoredValuesIndex = primvar.GetUnauthoredValuesIndex(); - } + if (status != MS::kSuccess || numValues == 0) { + TF_WARN( + "Could not read color set values from primvar '%s' on mesh: %s", + primvarName.GetText(), + primvar.GetAttr().GetPrimPath().GetText()); + return false; + } - // Go through the color data and translate the values into MColors in the - // colorArray, taking into consideration that indexed data may have been - // authored sparsely. If the assignmentIndices array is empty then the data - // is NOT indexed. - // Note that with indexed data, the data is added to the arrays in ascending - // component ID order according to the primvar's interpolation (ascending - // face ID for uniform interpolation, ascending vertex ID for vertex - // interpolation, etc.). This ordering may be different from the way the - // values are ordered in the primvar. Because of this, we recycle the - // assignmentIndices array as we go to store the new mapping from component - // index to color index. - MColorArray colorArray; - for (size_t i = 0; i < numValues; ++i) { - int valueIndex = i; - - if (i < assignmentIndices.size()) { - // The data is indexed, so consult the indices array for the - // correct index into the data. - valueIndex = assignmentIndices[i]; - - if (valueIndex == unauthoredValuesIndex) { - // This component is unauthored, so just update the - // mapping in assignmentIndices and then skip the value. - // We don't actually use the value at the unassigned index. - assignmentIndices[i] = -1; - continue; - } + VtIntArray assignmentIndices; + int unauthoredValuesIndex = -1; + if (primvar.GetIndices(&assignmentIndices)) { + // The primvar IS indexed, so the indices array is what determines the + // number of color values. + numValues = assignmentIndices.size(); + unauthoredValuesIndex = primvar.GetUnauthoredValuesIndex(); + } - // We'll be appending a new value, so the current length of the - // array gives us the new value's index. - assignmentIndices[i] = colorArray.length(); + // Go through the color data and translate the values into MColors in the + // colorArray, taking into consideration that indexed data may have been + // authored sparsely. If the assignmentIndices array is empty then the data + // is NOT indexed. + // Note that with indexed data, the data is added to the arrays in ascending + // component ID order according to the primvar's interpolation (ascending + // face ID for uniform interpolation, ascending vertex ID for vertex + // interpolation, etc.). This ordering may be different from the way the + // values are ordered in the primvar. Because of this, we recycle the + // assignmentIndices array as we go to store the new mapping from component + // index to color index. + MColorArray colorArray; + for (size_t i = 0; i < numValues; ++i) { + int valueIndex = i; + + if (i < assignmentIndices.size()) { + // The data is indexed, so consult the indices array for the + // correct index into the data. + valueIndex = assignmentIndices[i]; + + if (valueIndex == unauthoredValuesIndex) { + // This component is unauthored, so just update the + // mapping in assignmentIndices and then skip the value. + // We don't actually use the value at the unassigned index. + assignmentIndices[i] = -1; + continue; } - GfVec4f colorValue(1.0); - - switch(colorRep) { - case MFnMesh::kAlpha: - colorValue[3] = alphaArray[valueIndex]; - break; - case MFnMesh::kRGB: - colorValue[0] = rgbArray[valueIndex][0]; - colorValue[1] = rgbArray[valueIndex][1]; - colorValue[2] = rgbArray[valueIndex][2]; - break; - case MFnMesh::kRGBA: - colorValue[0] = rgbaArray[valueIndex][0]; - colorValue[1] = rgbaArray[valueIndex][1]; - colorValue[2] = rgbaArray[valueIndex][2]; - colorValue[3] = rgbaArray[valueIndex][3]; - break; - default: - break; - } + // We'll be appending a new value, so the current length of the + // array gives us the new value's index. + assignmentIndices[i] = colorArray.length(); + } - if (isDisplayColor) { - colorValue = UsdMayaColorSpace::ConvertLinearToMaya(colorValue); - } + GfVec4f colorValue(1.0); - MColor mColor(colorValue[0], colorValue[1], colorValue[2], colorValue[3]); - colorArray.append(mColor); + switch (colorRep) { + case MFnMesh::kAlpha: colorValue[3] = alphaArray[valueIndex]; break; + case MFnMesh::kRGB: + colorValue[0] = rgbArray[valueIndex][0]; + colorValue[1] = rgbArray[valueIndex][1]; + colorValue[2] = rgbArray[valueIndex][2]; + break; + case MFnMesh::kRGBA: + colorValue[0] = rgbaArray[valueIndex][0]; + colorValue[1] = rgbaArray[valueIndex][1]; + colorValue[2] = rgbaArray[valueIndex][2]; + colorValue[3] = rgbaArray[valueIndex][3]; + break; + default: break; } - // colorArray now stores all of the values and any unassigned components - // have had their indices set to -1, so update the unauthored values index. - unauthoredValuesIndex = -1; + if (isDisplayColor) { + colorValue = UsdMayaColorSpace::ConvertLinearToMaya(colorValue); + } - const bool clamped = UsdMayaRoundTripUtil::IsPrimvarClamped(primvar); + MColor mColor(colorValue[0], colorValue[1], colorValue[2], colorValue[3]); + colorArray.append(mColor); + } - status = meshFn.createColorSet(colorSetName, nullptr, clamped, colorRep); - if (status != MS::kSuccess) { - TF_WARN("Unable to create color set '%s' for mesh: %s", - colorSetName.asChar(), - meshFn.fullPathName().asChar()); - return false; - } + // colorArray now stores all of the values and any unassigned components + // have had their indices set to -1, so update the unauthored values index. + unauthoredValuesIndex = -1; - // Create colors on the mesh from the values we collected out of the - // primvar. We'll assign mesh components to these values below. - status = meshFn.setColors(colorArray, &colorSetName, colorRep); - if (status != MS::kSuccess) { - TF_WARN("Unable to set color data on color set '%s' for mesh: %s", - colorSetName.asChar(), - meshFn.fullPathName().asChar()); - return false; - } + const bool clamped = UsdMayaRoundTripUtil::IsPrimvarClamped(primvar); + + status = meshFn.createColorSet(colorSetName, nullptr, clamped, colorRep); + if (status != MS::kSuccess) { + TF_WARN( + "Unable to create color set '%s' for mesh: %s", + colorSetName.asChar(), + meshFn.fullPathName().asChar()); + return false; + } - const TfToken& interpolation = primvar.GetInterpolation(); + // Create colors on the mesh from the values we collected out of the + // primvar. We'll assign mesh components to these values below. + status = meshFn.setColors(colorArray, &colorSetName, colorRep); + if (status != MS::kSuccess) { + TF_WARN( + "Unable to set color data on color set '%s' for mesh: %s", + colorSetName.asChar(), + meshFn.fullPathName().asChar()); + return false; + } - // Build an array of value assignments for each face vertex in the mesh. - // Any assignments left as -1 will not be assigned a value. - MIntArray colorIds = getMayaFaceVertexAssignmentIds(meshFn, - interpolation, - assignmentIndices, - unauthoredValuesIndex); + const TfToken& interpolation = primvar.GetInterpolation(); - status = meshFn.assignColors(colorIds, &colorSetName); - if (status != MS::kSuccess) { - TF_WARN("Could not assign color values to color set '%s' on mesh: %s", - colorSetName.asChar(), - meshFn.fullPathName().asChar()); - return false; - } + // Build an array of value assignments for each face vertex in the mesh. + // Any assignments left as -1 will not be assigned a value. + MIntArray colorIds = getMayaFaceVertexAssignmentIds( + meshFn, interpolation, assignmentIndices, unauthoredValuesIndex); - // we only visualize the colorset by default if it is "displayColor". - // this is a limitation and affects user experience. This needs further review. HS, 1-Nov-2019 - MStringArray colorSetNames; - if (meshFn.getColorSetNames(colorSetNames) == MS::kSuccess) - { - for (unsigned int i = 0u; i < colorSetNames.length(); ++i) - { - const MString colorSetName = colorSetNames[i]; - - if (std::string(colorSetName.asChar()) - == UsdMayaMeshPrimvarTokens->DisplayColorColorSetName.GetString()) - { - const auto csRep = meshFn.getColorRepresentation(colorSetName); - - if (csRep == MFnMesh::kRGB || csRep == MFnMesh::kRGBA) - { - meshFn.setCurrentColorSetName(colorSetName); - MPlug plg = meshFn.findPlug("displayColors"); - if (!plg.isNull()) { - plg.setBool(true); - } + status = meshFn.assignColors(colorIds, &colorSetName); + if (status != MS::kSuccess) { + TF_WARN( + "Could not assign color values to color set '%s' on mesh: %s", + colorSetName.asChar(), + meshFn.fullPathName().asChar()); + return false; + } + + // we only visualize the colorset by default if it is "displayColor". + // this is a limitation and affects user experience. This needs further review. HS, 1-Nov-2019 + MStringArray colorSetNames; + if (meshFn.getColorSetNames(colorSetNames) == MS::kSuccess) { + for (unsigned int i = 0u; i < colorSetNames.length(); ++i) { + const MString colorSetName = colorSetNames[i]; + + if (std::string(colorSetName.asChar()) + == UsdMayaMeshPrimvarTokens->DisplayColorColorSetName.GetString()) { + const auto csRep = meshFn.getColorRepresentation(colorSetName); + + if (csRep == MFnMesh::kRGB || csRep == MFnMesh::kRGBA) { + meshFn.setCurrentColorSetName(colorSetName); + MPlug plg = meshFn.findPlug("displayColors"); + if (!plg.isNull()) { + plg.setBool(true); } - break; } + break; } } - - return true; } - bool - assignConstantPrimvarToMesh(const UsdGeomPrimvar& primvar, MFnMesh& meshFn) - { - const TfToken& interpolation = primvar.GetInterpolation(); - if (interpolation != UsdGeomTokens->constant) { - return false; - } + return true; +} - const TfToken& name = primvar.GetBaseName(); - const SdfValueTypeName& typeName = primvar.GetTypeName(); - const SdfVariability& variability = SdfVariabilityUniform; - - MObject attrObj = - UsdMayaReadUtil::FindOrCreateMayaAttr( - typeName, - variability, - meshFn, - name.GetText()); - if (attrObj.isNull()) { - return false; - } +bool assignConstantPrimvarToMesh(const UsdGeomPrimvar& primvar, MFnMesh& meshFn) +{ + const TfToken& interpolation = primvar.GetInterpolation(); + if (interpolation != UsdGeomTokens->constant) { + return false; + } - VtValue primvarData; - primvar.Get(&primvarData); + const TfToken& name = primvar.GetBaseName(); + const SdfValueTypeName& typeName = primvar.GetTypeName(); + const SdfVariability& variability = SdfVariabilityUniform; - MStatus status{MS::kSuccess}; - MPlug plug = meshFn.findPlug( - name.GetText(), - /* wantNetworkedPlug = */ true, - &status); - if (!status || plug.isNull()) { - return false; - } + MObject attrObj + = UsdMayaReadUtil::FindOrCreateMayaAttr(typeName, variability, meshFn, name.GetText()); + if (attrObj.isNull()) { + return false; + } + + VtValue primvarData; + primvar.Get(&primvarData); - return UsdMayaReadUtil::SetMayaAttr(plug, primvarData); + MStatus status { MS::kSuccess }; + MPlug plug = meshFn.findPlug( + name.GetText(), + /* wantNetworkedPlug = */ true, + &status); + if (!status || plug.isNull()) { + return false; } + + return UsdMayaReadUtil::SetMayaAttr(plug, primvarData); } +} // namespace // This can be customized for specific pipelines. -bool -UsdMayaMeshReadUtils::getEmitNormalsTag(const MFnMesh& mesh, bool* value) +bool UsdMayaMeshReadUtils::getEmitNormalsTag(const MFnMesh& mesh, bool* value) { MPlug plug = mesh.findPlug(MString(_meshTokens->USD_EmitNormals.GetText())); if (!plug.isNull()) { @@ -589,15 +583,12 @@ UsdMayaMeshReadUtils::getEmitNormalsTag(const MFnMesh& mesh, bool* value) return false; } -void -UsdMayaMeshReadUtils::setEmitNormalsTag( - MFnMesh& meshFn, - const bool emitNormals) +void UsdMayaMeshReadUtils::setEmitNormalsTag(MFnMesh& meshFn, const bool emitNormals) { - MStatus status{MS::kSuccess}; + MStatus status { MS::kSuccess }; MFnNumericAttribute nAttr; - MObject attr = nAttr.create(_meshTokens->USD_EmitNormals.GetText(), - "", MFnNumericData::kBoolean, 0, &status); + MObject attr = nAttr.create( + _meshTokens->USD_EmitNormals.GetText(), "", MFnNumericData::kBoolean, 0, &status); if (status == MS::kSuccess) { meshFn.addAttribute(attr); MPlug plug = meshFn.findPlug(attr); @@ -607,12 +598,12 @@ UsdMayaMeshReadUtils::setEmitNormalsTag( } } -void -UsdMayaMeshReadUtils::assignPrimvarsToMesh(const UsdGeomMesh& mesh, - const MObject& meshObj, - const TfToken::Set& excludePrimvarSet) +void UsdMayaMeshReadUtils::assignPrimvarsToMesh( + const UsdGeomMesh& mesh, + const MObject& meshObj, + const TfToken::Set& excludePrimvarSet) { - if(meshObj.apiType() != MFn::kMesh){ + if (meshObj.apiType() != MFn::kMesh) { return; } @@ -625,8 +616,7 @@ UsdMayaMeshReadUtils::assignPrimvarsToMesh(const UsdGeomMesh& mesh, // will use that slot. If not, the first texcoord stream to load will replace the default map1 // stream. bool hasDefaultUVSet = false; - for (const UsdGeomPrimvar& primvar: primvars) - { + for (const UsdGeomPrimvar& primvar : primvars) { const SdfValueTypeName typeName = primvar.GetTypeName(); if (typeName == SdfValueTypeNames->TexCoord2fArray || (UsdMayaReadUtil::ReadFloat2AsUV() && typeName == SdfValueTypeNames->Float2Array)) { @@ -638,12 +628,11 @@ UsdMayaMeshReadUtils::assignPrimvarsToMesh(const UsdGeomMesh& mesh, } } - for (const UsdGeomPrimvar& primvar: primvars) - { - const TfToken name = primvar.GetBaseName(); - const TfToken fullName = primvar.GetPrimvarName(); + for (const UsdGeomPrimvar& primvar : primvars) { + const TfToken name = primvar.GetBaseName(); + const TfToken fullName = primvar.GetPrimvarName(); const SdfValueTypeName typeName = primvar.GetTypeName(); - const TfToken& interpolation = primvar.GetInterpolation(); + const TfToken& interpolation = primvar.GetInterpolation(); // Exclude primvars using the full primvar name without "primvars:". // This applies to all primvars; we don't care if it's a color set, a @@ -657,57 +646,58 @@ UsdMayaMeshReadUtils::assignPrimvarsToMesh(const UsdGeomMesh& mesh, // authored by the user, for example if it was generated by shader // values and not an authored colorset/entity. // If it was not really authored, we skip the primvar. - if (name == UsdMayaMeshPrimvarTokens->DisplayColorColorSetName || - name == UsdMayaMeshPrimvarTokens->DisplayOpacityColorSetName) { - if (!UsdMayaRoundTripUtil::IsAttributeUserAuthored(primvar)) { - continue; - } + if (name == UsdMayaMeshPrimvarTokens->DisplayColorColorSetName + || name == UsdMayaMeshPrimvarTokens->DisplayOpacityColorSetName) { + if (!UsdMayaRoundTripUtil::IsAttributeUserAuthored(primvar)) { + continue; + } } // XXX: Maya stores UVs in MFloatArrays and color set data in MColors // which store floats, so we currently only import primvars holding // float-typed arrays. Should we still consider other precisions // (double, half, ...) and/or numeric types (int)? - if (typeName == SdfValueTypeNames->TexCoord2fArray || - (UsdMayaReadUtil::ReadFloat2AsUV() && - typeName == SdfValueTypeNames->Float2Array)) { - // Looks for TexCoord2fArray types for UV sets first - // Otherwise, if env variable for reading Float2 - // as uv sets is turned on, we assume that Float2Array primvars - // are UV sets. - if (!assignUVSetPrimvarToMesh(primvar, meshFn, hasDefaultUVSet)) { - TF_WARN("Unable to retrieve and assign data for UV set <%s> on " - "mesh <%s>", - name.GetText(), - mesh.GetPrim().GetPath().GetText()); - } - } else if (typeName == SdfValueTypeNames->FloatArray || - typeName == SdfValueTypeNames->Float3Array || - typeName == SdfValueTypeNames->Color3fArray || - typeName == SdfValueTypeNames->Float4Array || - typeName == SdfValueTypeNames->Color4fArray) { - if (!assignColorSetPrimvarToMesh(mesh, primvar, meshFn)) { - TF_WARN("Unable to retrieve and assign data for color set <%s> " - "on mesh <%s>", - name.GetText(), - mesh.GetPrim().GetPath().GetText()); - } + if (typeName == SdfValueTypeNames->TexCoord2fArray + || (UsdMayaReadUtil::ReadFloat2AsUV() && typeName == SdfValueTypeNames->Float2Array)) { + // Looks for TexCoord2fArray types for UV sets first + // Otherwise, if env variable for reading Float2 + // as uv sets is turned on, we assume that Float2Array primvars + // are UV sets. + if (!assignUVSetPrimvarToMesh(primvar, meshFn, hasDefaultUVSet)) { + TF_WARN( + "Unable to retrieve and assign data for UV set <%s> on " + "mesh <%s>", + name.GetText(), + mesh.GetPrim().GetPath().GetText()); + } + } else if ( + typeName == SdfValueTypeNames->FloatArray || typeName == SdfValueTypeNames->Float3Array + || typeName == SdfValueTypeNames->Color3fArray + || typeName == SdfValueTypeNames->Float4Array + || typeName == SdfValueTypeNames->Color4fArray) { + if (!assignColorSetPrimvarToMesh(mesh, primvar, meshFn)) { + TF_WARN( + "Unable to retrieve and assign data for color set <%s> " + "on mesh <%s>", + name.GetText(), + mesh.GetPrim().GetPath().GetText()); + } } else if (interpolation == UsdGeomTokens->constant) { - // Constant primvars get added as attributes on the mesh. - if (!assignConstantPrimvarToMesh(primvar, meshFn)) { - TF_WARN("Unable to assign constant primvar <%s> as attribute " - "on mesh <%s>", - name.GetText(), - mesh.GetPrim().GetPath().GetText()); - } + // Constant primvars get added as attributes on the mesh. + if (!assignConstantPrimvarToMesh(primvar, meshFn)) { + TF_WARN( + "Unable to assign constant primvar <%s> as attribute " + "on mesh <%s>", + name.GetText(), + mesh.GetPrim().GetPath().GetText()); + } } } } -void -UsdMayaMeshReadUtils::assignInvisibleFaces(const UsdGeomMesh& mesh, const MObject& meshObj) +void UsdMayaMeshReadUtils::assignInvisibleFaces(const UsdGeomMesh& mesh, const MObject& meshObj) { - if(meshObj.apiType() != MFn::kMesh){ + if (meshObj.apiType() != MFn::kMesh) { return; } @@ -724,63 +714,62 @@ UsdMayaMeshReadUtils::assignInvisibleFaces(const UsdGeomMesh& mesh, const MObjec } if (meshFn.setInvisibleFaces(mayaHoleIndices) != MS::kSuccess) { - TF_RUNTIME_ERROR("Unable to set Invisible Faces on <%s>", - meshFn.fullPathName().asChar()); + TF_RUNTIME_ERROR( + "Unable to set Invisible Faces on <%s>", meshFn.fullPathName().asChar()); } } } -MStatus -UsdMayaMeshReadUtils::assignSubDivTagsToMesh( const UsdGeomMesh& mesh, - MObject& meshObj, - MFnMesh& meshFn ) +MStatus UsdMayaMeshReadUtils::assignSubDivTagsToMesh( + const UsdGeomMesh& mesh, + MObject& meshObj, + MFnMesh& meshFn) { // We may want to provide the option in the future, but for now, we // default to using crease sets when setting crease data. // const bool USE_CREASE_SETS = true; - MStatus statusOK{MS::kSuccess}; + MStatus statusOK { MS::kSuccess }; MDagPath meshPath; - statusOK = MDagPath::getAPathTo(meshObj,meshPath); + statusOK = MDagPath::getAPathTo(meshObj, meshPath); - if (!statusOK){ + if (!statusOK) { return MS::kFailure; } // USD does not support grouped verts and edges, so combine all components // with the same weight into one set to reduce the overall crease set // count. The user can always split the sets up later if desired. - // + // // This structure is unused if crease sets aren't being created. - std::unordered_map elemsPerWeight; + std::unordered_map elemsPerWeight; // Vert Creasing VtIntArray subdCornerIndices; VtFloatArray subdCornerSharpnesses; - mesh.GetCornerIndicesAttr().Get(&subdCornerIndices); // not animatable + mesh.GetCornerIndicesAttr().Get(&subdCornerIndices); // not animatable mesh.GetCornerSharpnessesAttr().Get(&subdCornerSharpnesses); // not animatable if (!subdCornerIndices.empty()) { - if (subdCornerIndices.size() == subdCornerSharpnesses.size() ) { + if (subdCornerIndices.size() == subdCornerSharpnesses.size()) { statusOK.clear(); if (USE_CREASE_SETS) { MItMeshVertex vertIt(meshObj); - for (unsigned int i=0; i < subdCornerIndices.size(); i++) { + for (unsigned int i = 0; i < subdCornerIndices.size(); i++) { // Ignore zero-sharpness corners - if (subdCornerSharpnesses[i]==0) + if (subdCornerSharpnesses[i] == 0) continue; - MSelectionList &elemList = - elemsPerWeight[ subdCornerSharpnesses[i] ]; + MSelectionList& elemList = elemsPerWeight[subdCornerSharpnesses[i]]; int prevIndexDummy; // dummy param statusOK = vertIt.setIndex(subdCornerIndices[i], prevIndexDummy); if (!statusOK) break; - statusOK = elemList.add(meshPath,vertIt.currentItem()); + statusOK = elemList.add(meshPath, vertIt.currentItem()); if (!statusOK) break; } @@ -788,12 +777,12 @@ UsdMayaMeshReadUtils::assignSubDivTagsToMesh( const UsdGeomMesh& mesh, } else { MUintArray mayaCreaseVertIds; MDoubleArray mayaCreaseVertValues; - mayaCreaseVertIds.setLength( subdCornerIndices.size() ); - mayaCreaseVertValues.setLength( subdCornerIndices.size() ); - for (unsigned int i=0; i < subdCornerIndices.size(); i++) { + mayaCreaseVertIds.setLength(subdCornerIndices.size()); + mayaCreaseVertValues.setLength(subdCornerIndices.size()); + for (unsigned int i = 0; i < subdCornerIndices.size(); i++) { // Ignore zero-sharpness corners - if (subdCornerSharpnesses[i]==0) + if (subdCornerSharpnesses[i] == 0) continue; mayaCreaseVertIds[i] = subdCornerIndices[i]; @@ -803,16 +792,17 @@ UsdMayaMeshReadUtils::assignSubDivTagsToMesh( const UsdGeomMesh& mesh, } if (!statusOK) { - TF_RUNTIME_ERROR("Unable to set Crease Vertices on <%s>: %s", - meshFn.fullPathName().asChar(), - statusOK.errorString().asChar()); + TF_RUNTIME_ERROR( + "Unable to set Crease Vertices on <%s>: %s", + meshFn.fullPathName().asChar(), + statusOK.errorString().asChar()); return MS::kFailure; } } else { TF_RUNTIME_ERROR( - "Mismatch between Corner Indices & Sharpness on <%s>", - mesh.GetPrim().GetPath().GetText()); + "Mismatch between Corner Indices & Sharpness on <%s>", + mesh.GetPrim().GetPath().GetText()); return MS::kFailure; } } @@ -825,29 +815,29 @@ UsdMayaMeshReadUtils::assignSubDivTagsToMesh( const UsdGeomMesh& mesh, mesh.GetCreaseIndicesAttr().Get(&subdCreaseIndices); mesh.GetCreaseSharpnessesAttr().Get(&subdCreaseSharpnesses); if (!subdCreaseLengths.empty()) { - if (subdCreaseLengths.size() == subdCreaseSharpnesses.size() ) { + if (subdCreaseLengths.size() == subdCreaseSharpnesses.size()) { MUintArray mayaCreaseEdgeIds; MDoubleArray mayaCreaseEdgeValues; - MIntArray connectedEdges; + MIntArray connectedEdges; unsigned int creaseIndexBase = 0; statusOK.clear(); - for (unsigned int creaseGroup=0; - statusOK && creaseGroup: %s", - meshFn.fullPathName().asChar(), - statusOK.errorString().asChar()); + TF_RUNTIME_ERROR( + "Unable to set Crease Edges on <%s>: %s", + meshFn.fullPathName().asChar(), + statusOK.errorString().asChar()); return MS::kFailure; } } else { TF_RUNTIME_ERROR( - "Mismatch between Crease Lengths & Sharpness on <%s>", - mesh.GetPrim().GetPath().GetText()); + "Mismatch between Crease Lengths & Sharpness on <%s>", + mesh.GetPrim().GetPath().GetText()); return MS::kFailure; } } if (USE_CREASE_SETS) { - TF_FOR_ALL(weightList, elemsPerWeight) { - double creaseLevel = weightList->first; - MSelectionList &elemList = weightList->second; - - if (!addCreaseSet( meshFn.name().asChar(), - creaseLevel, elemList, &statusOK )){ - TF_RUNTIME_ERROR("Unable to set crease sets on <%s>: %s", - meshFn.fullPathName().asChar(), - statusOK.errorString().asChar()); + TF_FOR_ALL(weightList, elemsPerWeight) + { + double creaseLevel = weightList->first; + MSelectionList& elemList = weightList->second; + + if (!addCreaseSet(meshFn.name().asChar(), creaseLevel, elemList, &statusOK)) { + TF_RUNTIME_ERROR( + "Unable to set crease sets on <%s>: %s", + meshFn.fullPathName().asChar(), + statusOK.errorString().asChar()); return MS::kFailure; } } diff --git a/lib/mayaUsd/fileio/utils/meshReadUtils.h b/lib/mayaUsd/fileio/utils/meshReadUtils.h index fea81feb82..b77701e354 100644 --- a/lib/mayaUsd/fileio/utils/meshReadUtils.h +++ b/lib/mayaUsd/fileio/utils/meshReadUtils.h @@ -18,63 +18,61 @@ #ifndef PXRUSDMAYA_MESH_READ_UTILS_H #define PXRUSDMAYA_MESH_READ_UTILS_H -#include -#include -#include -#include +#include -#include #include #include #include #include +#include #include #include -#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE class UsdGeomMesh; -#define PXRUSDMAYA_MESH_PRIMVAR_TOKENS \ - ((DisplayColorColorSetName, "displayColor")) \ - ((DisplayOpacityColorSetName, "displayOpacity")) \ - ((DefaultMayaTexcoordName, "map1")) - +#define PXRUSDMAYA_MESH_PRIMVAR_TOKENS \ + ((DisplayColorColorSetName, "displayColor"))((DisplayOpacityColorSetName, "displayOpacity"))( \ + (DefaultMayaTexcoordName, "map1")) -TF_DECLARE_PUBLIC_TOKENS(UsdMayaMeshPrimvarTokens, +TF_DECLARE_PUBLIC_TOKENS( + UsdMayaMeshPrimvarTokens, MAYAUSD_CORE_PUBLIC, PXRUSDMAYA_MESH_PRIMVAR_TOKENS); /// Utilities for dealing with USD and RenderMan for Maya mesh/subdiv tags. -namespace UsdMayaMeshReadUtils -{ - /// Gets the internal emit-normals tag on the Maya \p mesh, placing it in - /// \p value. Returns true if the tag exists on the mesh, and false if not. - MAYAUSD_CORE_PUBLIC - bool getEmitNormalsTag(const MFnMesh &mesh, bool* value); - - /// Sets the internal emit-normals tag on the Maya \p mesh. - /// This value indicates to the exporter whether it should write out the - /// normals for the mesh to USD. - MAYAUSD_CORE_PUBLIC - void setEmitNormalsTag(MFnMesh &meshFn, const bool emitNormals); - - MAYAUSD_CORE_PUBLIC - void assignPrimvarsToMesh(const UsdGeomMesh& mesh, - const MObject& meshObj, - const TfToken::Set& excludePrimvarSet); - - MAYAUSD_CORE_PUBLIC - void assignInvisibleFaces(const UsdGeomMesh& mesh, const MObject& meshObj); - - MAYAUSD_CORE_PUBLIC - MStatus assignSubDivTagsToMesh(const UsdGeomMesh&, MObject&, MFnMesh&); +namespace UsdMayaMeshReadUtils { +/// Gets the internal emit-normals tag on the Maya \p mesh, placing it in +/// \p value. Returns true if the tag exists on the mesh, and false if not. +MAYAUSD_CORE_PUBLIC +bool getEmitNormalsTag(const MFnMesh& mesh, bool* value); + +/// Sets the internal emit-normals tag on the Maya \p mesh. +/// This value indicates to the exporter whether it should write out the +/// normals for the mesh to USD. +MAYAUSD_CORE_PUBLIC +void setEmitNormalsTag(MFnMesh& meshFn, const bool emitNormals); + +MAYAUSD_CORE_PUBLIC +void assignPrimvarsToMesh( + const UsdGeomMesh& mesh, + const MObject& meshObj, + const TfToken::Set& excludePrimvarSet); + +MAYAUSD_CORE_PUBLIC +void assignInvisibleFaces(const UsdGeomMesh& mesh, const MObject& meshObj); + +MAYAUSD_CORE_PUBLIC +MStatus assignSubDivTagsToMesh(const UsdGeomMesh&, MObject&, MFnMesh&); } // namespace UsdMayaMeshReadUtils - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/utils/meshWriteUtils.cpp b/lib/mayaUsd/fileio/utils/meshWriteUtils.cpp index b3685db317..a323deca79 100644 --- a/lib/mayaUsd/fileio/utils/meshWriteUtils.cpp +++ b/lib/mayaUsd/fileio/utils/meshWriteUtils.cpp @@ -17,19 +17,13 @@ // #include "meshWriteUtils.h" +#include #include #include #include #include - -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include #include #include @@ -42,9 +36,14 @@ #include #include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -62,292 +61,284 @@ TF_DEFINE_PRIVATE_TOKENS( // This token is deprecated as it is from OpenSubdiv 2 and the USD // schema now conforms to OpenSubdiv 3, but we continue to look for it // and translate to the equivalent new value for backwards compatibility. - (USD_faceVaryingInterpolateBoundary) -); - -namespace + (USD_faceVaryingInterpolateBoundary)); + +namespace { +/// Default value to use when collecting UVs from a UV set and a component +/// has no authored value. +const GfVec2f UnauthoredUV = GfVec2f(0.f); + +/// Default values to use when collecting colors based on shader values +/// and an object or component has no assigned shader. +const GfVec3f UnauthoredShaderRGB = GfVec3f(0.5f); +const float UnauthoredShaderAlpha = 0.0f; + +/// Default values to use when collecting colors from a color set and a +/// component has no authored value. +const GfVec3f UnauthoredColorSetRGB = GfVec3f(1.0f); +const float UnauthoredColorAlpha = 1.0f; +const GfVec4f UnauthoredColorSetRGBA = GfVec4f( + UnauthoredColorSetRGB[0], + UnauthoredColorSetRGB[1], + UnauthoredColorSetRGB[2], + UnauthoredColorAlpha); + +// XXX: Note that this function is not exposed publicly since the USD schema +// has been updated to conform to OpenSubdiv 3. We still look for this attribute +// on Maya nodes specifying this value from OpenSubdiv 2, but we translate the +// value to OpenSubdiv 3. This is to support legacy assets authored against +// OpenSubdiv 2. +static TfToken getOsd2FVInterpBoundary(const MFnMesh& mesh) { - /// Default value to use when collecting UVs from a UV set and a component - /// has no authored value. - const GfVec2f UnauthoredUV = GfVec2f(0.f); - - /// Default values to use when collecting colors based on shader values - /// and an object or component has no assigned shader. - const GfVec3f UnauthoredShaderRGB = GfVec3f(0.5f); - const float UnauthoredShaderAlpha = 0.0f; - - /// Default values to use when collecting colors from a color set and a - /// component has no authored value. - const GfVec3f UnauthoredColorSetRGB = GfVec3f(1.0f); - const float UnauthoredColorAlpha = 1.0f; - const GfVec4f UnauthoredColorSetRGBA = GfVec4f(UnauthoredColorSetRGB[0], - UnauthoredColorSetRGB[1], - UnauthoredColorSetRGB[2], - UnauthoredColorAlpha); - - // XXX: Note that this function is not exposed publicly since the USD schema - // has been updated to conform to OpenSubdiv 3. We still look for this attribute - // on Maya nodes specifying this value from OpenSubdiv 2, but we translate the - // value to OpenSubdiv 3. This is to support legacy assets authored against - // OpenSubdiv 2. - static - TfToken - getOsd2FVInterpBoundary(const MFnMesh& mesh) - { - TfToken sdFVInterpBound; - - MPlug plug = mesh.findPlug(MString( - _meshTokens->USD_faceVaryingInterpolateBoundary.GetText())); + TfToken sdFVInterpBound; + + MPlug plug = mesh.findPlug(MString(_meshTokens->USD_faceVaryingInterpolateBoundary.GetText())); + if (!plug.isNull()) { + sdFVInterpBound = TfToken(plug.asString().asChar()); + + // Translate OSD2 values to OSD3. + if (sdFVInterpBound == UsdGeomTokens->bilinear) { + sdFVInterpBound = UsdGeomTokens->all; + } else if (sdFVInterpBound == UsdGeomTokens->edgeAndCorner) { + sdFVInterpBound = UsdGeomTokens->cornersPlus1; + } else if (sdFVInterpBound == _meshTokens->alwaysSharp) { + sdFVInterpBound = UsdGeomTokens->boundaries; + } else if (sdFVInterpBound == UsdGeomTokens->edgeOnly) { + sdFVInterpBound = UsdGeomTokens->none; + } + } else { + plug = mesh.findPlug(MString("rman__torattr___subdivFacevaryingInterp")); if (!plug.isNull()) { - sdFVInterpBound = TfToken(plug.asString().asChar()); - - // Translate OSD2 values to OSD3. - if (sdFVInterpBound == UsdGeomTokens->bilinear) { - sdFVInterpBound = UsdGeomTokens->all; - } else if (sdFVInterpBound == UsdGeomTokens->edgeAndCorner) { - sdFVInterpBound = UsdGeomTokens->cornersPlus1; - } else if (sdFVInterpBound == _meshTokens->alwaysSharp) { - sdFVInterpBound = UsdGeomTokens->boundaries; - } else if (sdFVInterpBound == UsdGeomTokens->edgeOnly) { - sdFVInterpBound = UsdGeomTokens->none; - } - } else { - plug = mesh.findPlug(MString("rman__torattr___subdivFacevaryingInterp")); - if (!plug.isNull()) { - switch(plug.asInt()) { - case 0: - sdFVInterpBound = UsdGeomTokens->all; - break; - case 1: - sdFVInterpBound = UsdGeomTokens->cornersPlus1; - break; - case 2: - sdFVInterpBound = UsdGeomTokens->none; - break; - case 3: - sdFVInterpBound = UsdGeomTokens->boundaries; - break; - default: - break; - } + switch (plug.asInt()) { + case 0: sdFVInterpBound = UsdGeomTokens->all; break; + case 1: sdFVInterpBound = UsdGeomTokens->cornersPlus1; break; + case 2: sdFVInterpBound = UsdGeomTokens->none; break; + case 3: sdFVInterpBound = UsdGeomTokens->boundaries; break; + default: break; } } - - return sdFVInterpBound; } - void - compressCreases( const std::vector& inCreaseIndices, - const std::vector& inCreaseSharpnesses, - std::vector* creaseLengths, - std::vector* creaseIndices, - std::vector* creaseSharpnesses) - { - // Process vertex pairs. - for (size_t i = 0; i < inCreaseSharpnesses.size(); i++) { - const float sharpness = inCreaseSharpnesses[i]; - const int v0 = inCreaseIndices[i*2+0]; - const int v1 = inCreaseIndices[i*2+1]; - // Check if this edge represents a continuation of the last crease. - if (!creaseIndices->empty() && v0 == creaseIndices->back() - && sharpness == creaseSharpnesses->back()) { - // Extend the last crease. - creaseIndices->push_back(v1); - creaseLengths->back()++; - } else { - // Start a new crease. - creaseIndices->push_back(v0); - creaseIndices->push_back(v1); - creaseLengths->push_back(2); - creaseSharpnesses->push_back(sharpness); - } + return sdFVInterpBound; +} + +void compressCreases( + const std::vector& inCreaseIndices, + const std::vector& inCreaseSharpnesses, + std::vector* creaseLengths, + std::vector* creaseIndices, + std::vector* creaseSharpnesses) +{ + // Process vertex pairs. + for (size_t i = 0; i < inCreaseSharpnesses.size(); i++) { + const float sharpness = inCreaseSharpnesses[i]; + const int v0 = inCreaseIndices[i * 2 + 0]; + const int v1 = inCreaseIndices[i * 2 + 1]; + // Check if this edge represents a continuation of the last crease. + if (!creaseIndices->empty() && v0 == creaseIndices->back() + && sharpness == creaseSharpnesses->back()) { + // Extend the last crease. + creaseIndices->push_back(v1); + creaseLengths->back()++; + } else { + // Start a new crease. + creaseIndices->push_back(v0); + creaseIndices->push_back(v1); + creaseLengths->push_back(2); + creaseSharpnesses->push_back(sharpness); } } +} - /// Sets the primvar \p primvar at time \p usdTime using the given - /// \p indices (can be empty) and \p values. - /// The \p defaultValue is used to pad the \p values array in case - /// \p indices contains unassigned indices (i.e. indices < 0) that need a - /// corresponding value in the array. - /// - /// When authoring values at a non-default time, setPrimvar() might - /// unnecessarily pad \p values with \p defaultValue in order to guarantee - /// that the primvar remains valid during the export process. In that case, - /// the expected value of UsdGeomPrimvar::ComputeFlattened() is still - /// correct (there is just some memory wasted). - /// In order to cleanup any extra values and reclaim the wasted memory, call - /// cleanupPrimvars() at the end of the export process. - void - setPrimvar( const UsdGeomPrimvar& primvar, - const VtIntArray& indices, - const VtValue& values, - const VtValue& defaultValue, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter* valueWriter) - { - // Simple case of non-indexed primvars. - if (indices.empty()) { - UsdMayaWriteUtil::SetAttribute(primvar.GetAttr(), values, usdTime, valueWriter); - return; - } +/// Sets the primvar \p primvar at time \p usdTime using the given +/// \p indices (can be empty) and \p values. +/// The \p defaultValue is used to pad the \p values array in case +/// \p indices contains unassigned indices (i.e. indices < 0) that need a +/// corresponding value in the array. +/// +/// When authoring values at a non-default time, setPrimvar() might +/// unnecessarily pad \p values with \p defaultValue in order to guarantee +/// that the primvar remains valid during the export process. In that case, +/// the expected value of UsdGeomPrimvar::ComputeFlattened() is still +/// correct (there is just some memory wasted). +/// In order to cleanup any extra values and reclaim the wasted memory, call +/// cleanupPrimvars() at the end of the export process. +void setPrimvar( + const UsdGeomPrimvar& primvar, + const VtIntArray& indices, + const VtValue& values, + const VtValue& defaultValue, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) +{ + // Simple case of non-indexed primvars. + if (indices.empty()) { + UsdMayaWriteUtil::SetAttribute(primvar.GetAttr(), values, usdTime, valueWriter); + return; + } - // The mesh writer writes primvars only at default time or at time samples, - // but never both. We depend on that fact here to do different things - // depending on whether you ever export the default-time data or not. - if (usdTime.IsDefault()) { - // If we are only exporting the default values, then we know - // definitively whether we need to pad the values array with the - // unassigned value or not. - if (UsdMayaUtil::containsUnauthoredValues(indices)) { - primvar.SetUnauthoredValuesIndex(0); - - const VtValue paddedValues = UsdMayaUtil::pushFirstValue(values, defaultValue); - if (!paddedValues.IsEmpty()) { - UsdMayaWriteUtil::SetAttribute(primvar.GetAttr(), paddedValues, usdTime, valueWriter); - UsdMayaWriteUtil::SetAttribute(primvar.CreateIndicesAttr(), UsdMayaUtil::shiftIndices(indices, 1), usdTime, valueWriter); - } - else { - TF_CODING_ERROR("Unable to pad values array for <%s>", - primvar.GetAttr().GetPath().GetText()); - } - } - else { - UsdMayaWriteUtil::SetAttribute(primvar.GetAttr(), values, usdTime, valueWriter); - UsdMayaWriteUtil::SetAttribute(primvar.CreateIndicesAttr(), indices, usdTime, valueWriter); - } - } - else { - // If we are exporting animation, then we don't know definitively - // whether we need to set the unauthoredValuesIndex. - // In order to keep the primvar valid throughout the entire export - // process, _always_ pad the values array with the unassigned value, - // then go back and clean it up during the post-export. - if (primvar.GetUnauthoredValuesIndex() != 0 && UsdMayaUtil::containsUnauthoredValues(indices)) { - primvar.SetUnauthoredValuesIndex(0); - } + // The mesh writer writes primvars only at default time or at time samples, + // but never both. We depend on that fact here to do different things + // depending on whether you ever export the default-time data or not. + if (usdTime.IsDefault()) { + // If we are only exporting the default values, then we know + // definitively whether we need to pad the values array with the + // unassigned value or not. + if (UsdMayaUtil::containsUnauthoredValues(indices)) { + primvar.SetUnauthoredValuesIndex(0); const VtValue paddedValues = UsdMayaUtil::pushFirstValue(values, defaultValue); if (!paddedValues.IsEmpty()) { - UsdMayaWriteUtil::SetAttribute(primvar.GetAttr(), paddedValues, usdTime, valueWriter); - UsdMayaWriteUtil::SetAttribute(primvar.CreateIndicesAttr(), UsdMayaUtil::shiftIndices(indices, 1), usdTime, valueWriter); - } - else { - TF_CODING_ERROR("Unable to pad values array for <%s>", - primvar.GetAttr().GetPath().GetText()); + UsdMayaWriteUtil::SetAttribute( + primvar.GetAttr(), paddedValues, usdTime, valueWriter); + UsdMayaWriteUtil::SetAttribute( + primvar.CreateIndicesAttr(), + UsdMayaUtil::shiftIndices(indices, 1), + usdTime, + valueWriter); + } else { + TF_CODING_ERROR( + "Unable to pad values array for <%s>", primvar.GetAttr().GetPath().GetText()); } + } else { + UsdMayaWriteUtil::SetAttribute(primvar.GetAttr(), values, usdTime, valueWriter); + UsdMayaWriteUtil::SetAttribute( + primvar.CreateIndicesAttr(), indices, usdTime, valueWriter); } - } - - void - createUVPrimVar( UsdGeomGprim &primSchema, - const TfToken& name, - const UsdTimeCode& usdTime, - const VtArray& data, - const TfToken& interpolation, - const VtIntArray& assignmentIndices, - UsdUtilsSparseValueWriter* valueWriter) - { - const unsigned int numValues = data.size(); - if (numValues == 0) { - return; + } else { + // If we are exporting animation, then we don't know definitively + // whether we need to set the unauthoredValuesIndex. + // In order to keep the primvar valid throughout the entire export + // process, _always_ pad the values array with the unassigned value, + // then go back and clean it up during the post-export. + if (primvar.GetUnauthoredValuesIndex() != 0 + && UsdMayaUtil::containsUnauthoredValues(indices)) { + primvar.SetUnauthoredValuesIndex(0); } - TfToken interp = interpolation; - if (numValues == 1 && interp == UsdGeomTokens->constant) { - interp = TfToken(); + const VtValue paddedValues = UsdMayaUtil::pushFirstValue(values, defaultValue); + if (!paddedValues.IsEmpty()) { + UsdMayaWriteUtil::SetAttribute(primvar.GetAttr(), paddedValues, usdTime, valueWriter); + UsdMayaWriteUtil::SetAttribute( + primvar.CreateIndicesAttr(), + UsdMayaUtil::shiftIndices(indices, 1), + usdTime, + valueWriter); + } else { + TF_CODING_ERROR( + "Unable to pad values array for <%s>", primvar.GetAttr().GetPath().GetText()); } + } +} - SdfValueTypeName uvValueType = (UsdMayaWriteUtil::WriteUVAsFloat2())? - (SdfValueTypeNames->Float2Array) : (SdfValueTypeNames->TexCoord2fArray); - - UsdGeomPrimvar primVar = primSchema.CreatePrimvar(name, uvValueType, interp); +void createUVPrimVar( + UsdGeomGprim& primSchema, + const TfToken& name, + const UsdTimeCode& usdTime, + const VtArray& data, + const TfToken& interpolation, + const VtIntArray& assignmentIndices, + UsdUtilsSparseValueWriter* valueWriter) +{ + const unsigned int numValues = data.size(); + if (numValues == 0) { + return; + } - setPrimvar(primVar, - assignmentIndices, - VtValue(data), - VtValue(UnauthoredUV), - usdTime, - valueWriter); + TfToken interp = interpolation; + if (numValues == 1 && interp == UsdGeomTokens->constant) { + interp = TfToken(); } - // This function condenses distinct indices that point to the same color values - // (the combination of RGB AND Alpha) to all point to the same index for that - // value. This will potentially shrink the data arrays. - void - MergeEquivalentColorSetValues(VtVec3fArray* colorSetRGBData, - VtFloatArray* colorSetAlphaData, - VtIntArray* colorSetAssignmentIndices) - { - if (!colorSetRGBData || !colorSetAlphaData || !colorSetAssignmentIndices) { - return; - } + SdfValueTypeName uvValueType = (UsdMayaWriteUtil::WriteUVAsFloat2()) + ? (SdfValueTypeNames->Float2Array) + : (SdfValueTypeNames->TexCoord2fArray); - const size_t numValues = colorSetRGBData->size(); - if (numValues == 0) { - return; - } + UsdGeomPrimvar primVar = primSchema.CreatePrimvar(name, uvValueType, interp); - if (colorSetAlphaData->size() != numValues) { - TF_CODING_ERROR("Unequal sizes for color (%zu) and alpha (%zu)", - colorSetRGBData->size(), colorSetAlphaData->size()); - } + setPrimvar( + primVar, assignmentIndices, VtValue(data), VtValue(UnauthoredUV), usdTime, valueWriter); +} - // We first combine the separate color and alpha arrays into one GfVec4f - // array. - VtArray colorsWithAlphasData(numValues); - for (size_t i = 0; i < numValues; ++i) { - const GfVec3f color = (*colorSetRGBData)[i]; - const float alpha = (*colorSetAlphaData)[i]; - - colorsWithAlphasData[i][0] = color[0]; - colorsWithAlphasData[i][1] = color[1]; - colorsWithAlphasData[i][2] = color[2]; - colorsWithAlphasData[i][3] = alpha; - } +// This function condenses distinct indices that point to the same color values +// (the combination of RGB AND Alpha) to all point to the same index for that +// value. This will potentially shrink the data arrays. +void MergeEquivalentColorSetValues( + VtVec3fArray* colorSetRGBData, + VtFloatArray* colorSetAlphaData, + VtIntArray* colorSetAssignmentIndices) +{ + if (!colorSetRGBData || !colorSetAlphaData || !colorSetAssignmentIndices) { + return; + } + + const size_t numValues = colorSetRGBData->size(); + if (numValues == 0) { + return; + } + + if (colorSetAlphaData->size() != numValues) { + TF_CODING_ERROR( + "Unequal sizes for color (%zu) and alpha (%zu)", + colorSetRGBData->size(), + colorSetAlphaData->size()); + } - VtIntArray mergedIndices(*colorSetAssignmentIndices); - UsdMayaUtil::MergeEquivalentIndexedValues(&colorsWithAlphasData, &mergedIndices); + // We first combine the separate color and alpha arrays into one GfVec4f + // array. + VtArray colorsWithAlphasData(numValues); + for (size_t i = 0; i < numValues; ++i) { + const GfVec3f color = (*colorSetRGBData)[i]; + const float alpha = (*colorSetAlphaData)[i]; + + colorsWithAlphasData[i][0] = color[0]; + colorsWithAlphasData[i][1] = color[1]; + colorsWithAlphasData[i][2] = color[2]; + colorsWithAlphasData[i][3] = alpha; + } - // If we reduced the number of values by merging, copy the results back, - // separating the values back out into colors and alphas. - const size_t newSize = colorsWithAlphasData.size(); - if (newSize < numValues) { - colorSetRGBData->resize(newSize); - colorSetAlphaData->resize(newSize); + VtIntArray mergedIndices(*colorSetAssignmentIndices); + UsdMayaUtil::MergeEquivalentIndexedValues(&colorsWithAlphasData, &mergedIndices); - for (size_t i = 0; i < newSize; ++i) { - const GfVec4f colorWithAlpha = colorsWithAlphasData[i]; + // If we reduced the number of values by merging, copy the results back, + // separating the values back out into colors and alphas. + const size_t newSize = colorsWithAlphasData.size(); + if (newSize < numValues) { + colorSetRGBData->resize(newSize); + colorSetAlphaData->resize(newSize); - (*colorSetRGBData)[i][0] = colorWithAlpha[0]; - (*colorSetRGBData)[i][1] = colorWithAlpha[1]; - (*colorSetRGBData)[i][2] = colorWithAlpha[2]; - (*colorSetAlphaData)[i] = colorWithAlpha[3]; - } - (*colorSetAssignmentIndices) = mergedIndices; + for (size_t i = 0; i < newSize; ++i) { + const GfVec4f colorWithAlpha = colorsWithAlphasData[i]; + + (*colorSetRGBData)[i][0] = colorWithAlpha[0]; + (*colorSetRGBData)[i][1] = colorWithAlpha[1]; + (*colorSetRGBData)[i][2] = colorWithAlpha[2]; + (*colorSetAlphaData)[i] = colorWithAlpha[3]; } + (*colorSetAssignmentIndices) = mergedIndices; } +} - GfVec3f - LinearColorFromColorSet(const MColor& mayaColor, bool shouldConvertToLinear) - { - // we assume all color sets except displayColor are in linear space. - // if we got a color from colorSetData and we're a displayColor, we - // need to convert it to linear. - GfVec3f c(mayaColor[0], mayaColor[1], mayaColor[2]); - if (shouldConvertToLinear) { - return UsdMayaColorSpace::ConvertMayaToLinear(c); - } - return c; +GfVec3f LinearColorFromColorSet(const MColor& mayaColor, bool shouldConvertToLinear) +{ + // we assume all color sets except displayColor are in linear space. + // if we got a color from colorSetData and we're a displayColor, we + // need to convert it to linear. + GfVec3f c(mayaColor[0], mayaColor[1], mayaColor[2]); + if (shouldConvertToLinear) { + return UsdMayaColorSpace::ConvertMayaToLinear(c); } + return c; +} } // anonymous namespace -bool -UsdMayaMeshWriteUtils::getMeshNormals(const MFnMesh& mesh, - VtVec3fArray* normalsArray, - TfToken* interpolation) +bool UsdMayaMeshWriteUtils::getMeshNormals( + const MFnMesh& mesh, + VtVec3fArray* normalsArray, + TfToken* interpolation) { - MStatus status{MS::kSuccess}; + MStatus status { MS::kSuccess }; // Sanity check first to make sure we can get this mesh's normals. const int numNormals = mesh.numNormals(&status); @@ -390,42 +381,36 @@ UsdMayaMeshWriteUtils::getMeshNormals(const MFnMesh& mesh, // We first look for the USD string attribute, and if not present we look for // the RenderMan for Maya int attribute. // XXX Maybe we should come up with a OSD centric nomenclature ?? -TfToken -UsdMayaMeshWriteUtils::getSubdivScheme(const MFnMesh& mesh) +TfToken UsdMayaMeshWriteUtils::getSubdivScheme(const MFnMesh& mesh) { // Try grabbing the value via the adaptor first. TfToken schemeToken; UsdMayaAdaptor(mesh.object()) - .GetSchemaOrInheritedSchema() - .GetAttribute(UsdGeomTokens->subdivisionScheme) - .Get(&schemeToken); + .GetSchemaOrInheritedSchema() + .GetAttribute(UsdGeomTokens->subdivisionScheme) + .Get(&schemeToken); // Fall back to the RenderMan for Maya attribute. if (schemeToken.IsEmpty()) { MPlug plug = mesh.findPlug(MString("rman__torattr___subdivScheme")); if (!plug.isNull()) { switch (plug.asInt()) { - case 0: - schemeToken = UsdGeomTokens->catmullClark; - break; - case 1: - schemeToken = UsdGeomTokens->loop; - break; - default: - break; + case 0: schemeToken = UsdGeomTokens->catmullClark; break; + case 1: schemeToken = UsdGeomTokens->loop; break; + default: break; } } } if (schemeToken.IsEmpty()) { return TfToken(); - } else if (schemeToken != UsdGeomTokens->none && - schemeToken != UsdGeomTokens->catmullClark && - schemeToken != UsdGeomTokens->loop && - schemeToken != UsdGeomTokens->bilinear) { + } else if ( + schemeToken != UsdGeomTokens->none && schemeToken != UsdGeomTokens->catmullClark + && schemeToken != UsdGeomTokens->loop && schemeToken != UsdGeomTokens->bilinear) { TF_RUNTIME_ERROR( - "Unsupported subdivision scheme: %s on mesh: %s", - schemeToken.GetText(), mesh.fullPathName().asChar()); + "Unsupported subdivision scheme: %s on mesh: %s", + schemeToken.GetText(), + mesh.fullPathName().asChar()); return TfToken(); } @@ -441,38 +426,33 @@ TfToken UsdMayaMeshWriteUtils::getSubdivInterpBoundary(const MFnMesh& mesh) // Try grabbing the value via the adaptor first. TfToken interpBoundaryToken; UsdMayaAdaptor(mesh.object()) - .GetSchemaOrInheritedSchema() - .GetAttribute(UsdGeomTokens->interpolateBoundary) - .Get(&interpBoundaryToken); + .GetSchemaOrInheritedSchema() + .GetAttribute(UsdGeomTokens->interpolateBoundary) + .Get(&interpBoundaryToken); // Fall back to the RenderMan for Maya attr. if (interpBoundaryToken.IsEmpty()) { MPlug plug = mesh.findPlug(MString("rman__torattr___subdivInterp")); if (!plug.isNull()) { switch (plug.asInt()) { - case 0: - interpBoundaryToken = UsdGeomTokens->none; - break; - case 1: - interpBoundaryToken = UsdGeomTokens->edgeAndCorner; - break; - case 2: - interpBoundaryToken = UsdGeomTokens->edgeOnly; - break; - default: - break; + case 0: interpBoundaryToken = UsdGeomTokens->none; break; + case 1: interpBoundaryToken = UsdGeomTokens->edgeAndCorner; break; + case 2: interpBoundaryToken = UsdGeomTokens->edgeOnly; break; + default: break; } } } if (interpBoundaryToken.IsEmpty()) { return TfToken(); - } else if (interpBoundaryToken != UsdGeomTokens->none && - interpBoundaryToken != UsdGeomTokens->edgeAndCorner && - interpBoundaryToken != UsdGeomTokens->edgeOnly) { + } else if ( + interpBoundaryToken != UsdGeomTokens->none + && interpBoundaryToken != UsdGeomTokens->edgeAndCorner + && interpBoundaryToken != UsdGeomTokens->edgeOnly) { TF_RUNTIME_ERROR( - "Unsupported interpolate boundary setting: %s on mesh: %s", - interpBoundaryToken.GetText(), mesh.fullPathName().asChar()); + "Unsupported interpolate boundary setting: %s on mesh: %s", + interpBoundaryToken.GetText(), + mesh.fullPathName().asChar()); return TfToken(); } @@ -484,9 +464,9 @@ TfToken UsdMayaMeshWriteUtils::getSubdivFVLinearInterpolation(const MFnMesh& mes // Try grabbing the value via the adaptor first. TfToken sdFVLinearInterpolation; UsdMayaAdaptor(mesh.object()) - .GetSchemaOrInheritedSchema() - .GetAttribute(UsdGeomTokens->faceVaryingLinearInterpolation) - .Get(&sdFVLinearInterpolation); + .GetSchemaOrInheritedSchema() + .GetAttribute(UsdGeomTokens->faceVaryingLinearInterpolation) + .Get(&sdFVLinearInterpolation); // If the OpenSubdiv 3-style face varying linear interpolation value // wasn't specified, fall back to the old OpenSubdiv 2-style face @@ -495,59 +475,54 @@ TfToken UsdMayaMeshWriteUtils::getSubdivFVLinearInterpolation(const MFnMesh& mes sdFVLinearInterpolation = getOsd2FVInterpBoundary(mesh); } - if (!sdFVLinearInterpolation.IsEmpty() && - sdFVLinearInterpolation != UsdGeomTokens->all && - sdFVLinearInterpolation != UsdGeomTokens->none && - sdFVLinearInterpolation != UsdGeomTokens->boundaries && - sdFVLinearInterpolation != UsdGeomTokens->cornersOnly && - sdFVLinearInterpolation != UsdGeomTokens->cornersPlus1 && - sdFVLinearInterpolation != UsdGeomTokens->cornersPlus2) { + if (!sdFVLinearInterpolation.IsEmpty() && sdFVLinearInterpolation != UsdGeomTokens->all + && sdFVLinearInterpolation != UsdGeomTokens->none + && sdFVLinearInterpolation != UsdGeomTokens->boundaries + && sdFVLinearInterpolation != UsdGeomTokens->cornersOnly + && sdFVLinearInterpolation != UsdGeomTokens->cornersPlus1 + && sdFVLinearInterpolation != UsdGeomTokens->cornersPlus2) { TF_RUNTIME_ERROR( - "Unsupported face-varying linear interpolation: %s " - "on mesh: %s", - sdFVLinearInterpolation.GetText(), - mesh.fullPathName().asChar()); + "Unsupported face-varying linear interpolation: %s " + "on mesh: %s", + sdFVLinearInterpolation.GetText(), + mesh.fullPathName().asChar()); return TfToken(); } return sdFVLinearInterpolation; } -bool -UsdMayaMeshWriteUtils::isMeshValid(const MDagPath& dagPath) +bool UsdMayaMeshWriteUtils::isMeshValid(const MDagPath& dagPath) { - MStatus status{MS::kSuccess}; + MStatus status { MS::kSuccess }; // sanity checks MFnMesh lMesh(dagPath, &status); if (!status) { TF_RUNTIME_ERROR( - "MFnMesh() failed for mesh at DAG path: %s", - dagPath.fullPathName().asChar()); + "MFnMesh() failed for mesh at DAG path: %s", dagPath.fullPathName().asChar()); return false; } const auto numVertices = lMesh.numVertices(); const auto numPolygons = lMesh.numPolygons(); - if (numVertices < 3 && numVertices > 0) - { + if (numVertices < 3 && numVertices > 0) { TF_RUNTIME_ERROR( - "%s is not a valid mesh, because it only has %u points,", - lMesh.fullPathName().asChar(), numVertices); + "%s is not a valid mesh, because it only has %u points,", + lMesh.fullPathName().asChar(), + numVertices); } - if (numPolygons == 0) - { + if (numPolygons == 0) { TF_WARN("%s has no polygons.", lMesh.fullPathName().asChar()); } return true; } -void -UsdMayaMeshWriteUtils::exportReferenceMesh(UsdGeomMesh& primSchema, MObject obj) +void UsdMayaMeshWriteUtils::exportReferenceMesh(UsdGeomMesh& primSchema, MObject obj) { - MStatus status{MS::kSuccess}; + MStatus status { MS::kSuccess }; MFnDependencyNode dNode(obj, &status); if (!status) { @@ -575,15 +550,13 @@ UsdMayaMeshWriteUtils::exportReferenceMesh(UsdGeomMesh& primSchema, MObject obj) return; } - const float* mayaRawPoints = referenceMesh.getRawPoints(&status); + const float* mayaRawPoints = referenceMesh.getRawPoints(&status); const GfVec3f* mayaRawVec3 = reinterpret_cast(mayaRawPoints); - const int numVertices = referenceMesh.numVertices(); - VtVec3fArray points(mayaRawVec3, mayaRawVec3 + numVertices); + const int numVertices = referenceMesh.numVertices(); + VtVec3fArray points(mayaRawVec3, mayaRawVec3 + numVertices); UsdGeomPrimvar primVar = primSchema.CreatePrimvar( - UsdUtilsGetPrefName(), - SdfValueTypeNames->Point3fArray, - UsdGeomTokens->varying); + UsdUtilsGetPrefName(), SdfValueTypeNames->Point3fArray, UsdGeomTokens->varying); if (!primVar) { return; @@ -592,20 +565,20 @@ UsdMayaMeshWriteUtils::exportReferenceMesh(UsdGeomMesh& primSchema, MObject obj) primVar.GetAttr().Set(VtValue(points)); } -void -UsdMayaMeshWriteUtils::assignSubDivTagsToUSDPrim(MFnMesh& meshFn, - UsdGeomMesh& primSchema, - UsdUtilsSparseValueWriter* valueWriter) +void UsdMayaMeshWriteUtils::assignSubDivTagsToUSDPrim( + MFnMesh& meshFn, + UsdGeomMesh& primSchema, + UsdUtilsSparseValueWriter* valueWriter) { // Vert Creasing - MUintArray mayaCreaseVertIds; + MUintArray mayaCreaseVertIds; MDoubleArray mayaCreaseVertValues; meshFn.getCreaseVertices(mayaCreaseVertIds, mayaCreaseVertValues); if (!TF_VERIFY(mayaCreaseVertIds.length() == mayaCreaseVertValues.length())) { return; } if (mayaCreaseVertIds.length() > 0u) { - VtIntArray subdCornerIndices(mayaCreaseVertIds.length()); + VtIntArray subdCornerIndices(mayaCreaseVertIds.length()); VtFloatArray subdCornerSharpnesses(mayaCreaseVertIds.length()); for (unsigned int i = 0u; i < mayaCreaseVertIds.length(); ++i) { subdCornerIndices[i] = mayaCreaseVertIds[i]; @@ -613,17 +586,23 @@ UsdMayaMeshWriteUtils::assignSubDivTagsToUSDPrim(MFnMesh& meshFn, } // not animatable - UsdMayaWriteUtil::SetAttribute(primSchema.GetCornerIndicesAttr(), - &subdCornerIndices, UsdTimeCode::Default(), valueWriter); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetCornerIndicesAttr(), + &subdCornerIndices, + UsdTimeCode::Default(), + valueWriter); // not animatable - UsdMayaWriteUtil::SetAttribute(primSchema.GetCornerSharpnessesAttr(), - &subdCornerSharpnesses, UsdTimeCode::Default(), valueWriter); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetCornerSharpnessesAttr(), + &subdCornerSharpnesses, + UsdTimeCode::Default(), + valueWriter); } // Edge Creasing - int edgeVerts[2]; - MUintArray mayaCreaseEdgeIds; + int edgeVerts[2]; + MUintArray mayaCreaseEdgeIds; MDoubleArray mayaCreaseEdgeValues; meshFn.getCreaseEdges(mayaCreaseEdgeIds, mayaCreaseEdgeValues); if (!TF_VERIFY(mayaCreaseEdgeIds.length() == mayaCreaseEdgeValues.length())) { @@ -633,59 +612,71 @@ UsdMayaMeshWriteUtils::assignSubDivTagsToUSDPrim(MFnMesh& meshFn, std::vector subdCreaseIndices(mayaCreaseEdgeIds.length() * 2); // just construct directly from the array data // by moving this out of the loop, you'll leverage SIMD ops here. - std::vector subdCreaseSharpnesses(&mayaCreaseEdgeValues[0], &mayaCreaseEdgeValues[0] + mayaCreaseEdgeValues.length()); - // avoid dso call by taking a copy of length. + std::vector subdCreaseSharpnesses( + &mayaCreaseEdgeValues[0], &mayaCreaseEdgeValues[0] + mayaCreaseEdgeValues.length()); + // avoid dso call by taking a copy of length. for (unsigned int i = 0u, n = mayaCreaseEdgeIds.length(); i < n; ++i) { meshFn.getEdgeVertices(mayaCreaseEdgeIds[i], edgeVerts); subdCreaseIndices[i * 2] = edgeVerts[0]; subdCreaseIndices[i * 2 + 1] = edgeVerts[1]; } - std::vector numCreases; - std::vector creases; + std::vector numCreases; + std::vector creases; std::vector creaseSharpnesses; - compressCreases(subdCreaseIndices, subdCreaseSharpnesses, - &numCreases, &creases, &creaseSharpnesses); + compressCreases( + subdCreaseIndices, subdCreaseSharpnesses, &numCreases, &creases, &creaseSharpnesses); if (!creases.empty()) { VtIntArray creaseIndicesVt(creases.size()); std::copy(creases.begin(), creases.end(), creaseIndicesVt.begin()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetCreaseIndicesAttr(), &creaseIndicesVt, UsdTimeCode::Default(), valueWriter); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetCreaseIndicesAttr(), + &creaseIndicesVt, + UsdTimeCode::Default(), + valueWriter); } if (!numCreases.empty()) { VtIntArray creaseLengthsVt(numCreases.size()); std::copy(numCreases.begin(), numCreases.end(), creaseLengthsVt.begin()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetCreaseLengthsAttr(), &creaseLengthsVt, UsdTimeCode::Default(), valueWriter); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetCreaseLengthsAttr(), + &creaseLengthsVt, + UsdTimeCode::Default(), + valueWriter); } if (!creaseSharpnesses.empty()) { VtFloatArray creaseSharpnessesVt(creaseSharpnesses.size()); std::copy( - creaseSharpnesses.begin(), - creaseSharpnesses.end(), - creaseSharpnessesVt.begin()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetCreaseSharpnessesAttr(), &creaseSharpnessesVt, UsdTimeCode::Default(), valueWriter); + creaseSharpnesses.begin(), creaseSharpnesses.end(), creaseSharpnessesVt.begin()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetCreaseSharpnessesAttr(), + &creaseSharpnessesVt, + UsdTimeCode::Default(), + valueWriter); } } } -void -UsdMayaMeshWriteUtils::writePointsData(const MFnMesh& meshFn, - UsdGeomMesh& primSchema, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter* valueWriter) +void UsdMayaMeshWriteUtils::writePointsData( + const MFnMesh& meshFn, + UsdGeomMesh& primSchema, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) { - MStatus status{MS::kSuccess}; + MStatus status { MS::kSuccess }; const uint32_t numVertices = meshFn.numVertices(); - const float* pointsData = meshFn.getRawPoints(&status); - if(!status) { - MGlobal::displayError(MString("Unable to access mesh vertices on mesh: ") + meshFn.fullPathName()); + const float* pointsData = meshFn.getRawPoints(&status); + if (!status) { + MGlobal::displayError( + MString("Unable to access mesh vertices on mesh: ") + meshFn.fullPathName()); return; } const GfVec3f* vecData = reinterpret_cast(pointsData); - VtVec3fArray points(vecData, vecData + numVertices); - VtVec3fArray extent(2); + VtVec3fArray points(vecData, vecData + numVertices); + VtVec3fArray extent(2); // Compute the extent using the raw points UsdGeomPointBased::ComputeExtent(points, &extent); @@ -693,57 +684,59 @@ UsdMayaMeshWriteUtils::writePointsData(const MFnMesh& meshFn, UsdMayaWriteUtil::SetAttribute(primSchema.CreateExtentAttr(), &extent, usdTime, valueWriter); } -void -UsdMayaMeshWriteUtils::writeFaceVertexIndicesData(const MFnMesh& meshFn, - UsdGeomMesh& primSchema, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter* valueWriter) +void UsdMayaMeshWriteUtils::writeFaceVertexIndicesData( + const MFnMesh& meshFn, + UsdGeomMesh& primSchema, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) { const int numFaceVertices = meshFn.numFaceVertices(); const int numPolygons = meshFn.numPolygons(); - VtIntArray faceVertexCounts(numPolygons); - VtIntArray faceVertexIndices(numFaceVertices); - MIntArray mayaFaceVertexIndices; // used in loop below + VtIntArray faceVertexCounts(numPolygons); + VtIntArray faceVertexIndices(numFaceVertices); + MIntArray mayaFaceVertexIndices; // used in loop below unsigned int curFaceVertexIndex = 0; for (int i = 0; i < numPolygons; i++) { meshFn.getPolygonVertices(i, mayaFaceVertexIndices); faceVertexCounts[i] = mayaFaceVertexIndices.length(); - for (unsigned int j=0; j < mayaFaceVertexIndices.length(); j++) { - faceVertexIndices[ curFaceVertexIndex ] = mayaFaceVertexIndices[j]; // push_back + for (unsigned int j = 0; j < mayaFaceVertexIndices.length(); j++) { + faceVertexIndices[curFaceVertexIndex] = mayaFaceVertexIndices[j]; // push_back curFaceVertexIndex++; } } - UsdMayaWriteUtil::SetAttribute(primSchema.GetFaceVertexCountsAttr(), &faceVertexCounts, usdTime, valueWriter); - UsdMayaWriteUtil::SetAttribute(primSchema.GetFaceVertexIndicesAttr(), &faceVertexIndices, usdTime, valueWriter); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetFaceVertexCountsAttr(), &faceVertexCounts, usdTime, valueWriter); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetFaceVertexIndicesAttr(), &faceVertexIndices, usdTime, valueWriter); } -void -UsdMayaMeshWriteUtils::writeInvisibleFacesData(const MFnMesh& meshFn, - UsdGeomMesh& primSchema, - UsdUtilsSparseValueWriter* valueWriter) +void UsdMayaMeshWriteUtils::writeInvisibleFacesData( + const MFnMesh& meshFn, + UsdGeomMesh& primSchema, + UsdUtilsSparseValueWriter* valueWriter) { - MUintArray mayaHoles = meshFn.getInvisibleFaces(); + MUintArray mayaHoles = meshFn.getInvisibleFaces(); const uint32_t count = mayaHoles.length(); - if (count) - { + if (count) { VtIntArray subdHoles(count); - uint32_t* ptr = &mayaHoles[0]; + uint32_t* ptr = &mayaHoles[0]; // use memcpy() to copy the data. HS April 20, 2019 memcpy((int32_t*)subdHoles.data(), ptr, count * sizeof(uint32_t)); // not animatable in Maya, so we'll set default only - UsdMayaWriteUtil::SetAttribute(primSchema.GetHoleIndicesAttr(), &subdHoles, UsdTimeCode::Default(), valueWriter); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetHoleIndicesAttr(), &subdHoles, UsdTimeCode::Default(), valueWriter); } } -bool -UsdMayaMeshWriteUtils::getMeshUVSetData(const MFnMesh& mesh, - const MString& uvSetName, - VtVec2fArray* uvArray, - TfToken* interpolation, - VtIntArray* assignmentIndices) +bool UsdMayaMeshWriteUtils::getMeshUVSetData( + const MFnMesh& mesh, + const MString& uvSetName, + VtVec2fArray* uvArray, + TfToken* interpolation, + VtIntArray* assignmentIndices) { - MStatus status{MS::kSuccess}; + MStatus status { MS::kSuccess }; // Sanity check first to make sure this UV set even has assigned values // before we attempt to do anything with the data. @@ -775,7 +768,7 @@ UsdMayaMeshWriteUtils::getMeshUVSetData(const MFnMesh& mesh, *interpolation = UsdGeomTokens->faceVarying; MItMeshFaceVertex itFV(mesh.object()); - unsigned int fvi = 0; + unsigned int fvi = 0; for (itFV.reset(); !itFV.isDone(); itFV.next(), ++fvi) { if (!itFV.hasUVs(uvSetName)) { // No UVs for this faceVertex, so leave it unassigned. @@ -799,32 +792,29 @@ UsdMayaMeshWriteUtils::getMeshUVSetData(const MFnMesh& mesh, return true; } -bool -UsdMayaMeshWriteUtils::writeUVSetsAsVec2fPrimvars(const MFnMesh& meshFn, - UsdGeomMesh& primSchema, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter* valueWriter) +bool UsdMayaMeshWriteUtils::writeUVSetsAsVec2fPrimvars( + const MFnMesh& meshFn, + UsdGeomMesh& primSchema, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) { - MStatus status{MS::kSuccess}; + MStatus status { MS::kSuccess }; MStringArray uvSetNames; status = meshFn.getUVSetNames(uvSetNames); - if(!status) { + if (!status) { return false; } for (unsigned int i = 0; i < uvSetNames.length(); ++i) { VtVec2fArray uvValues; - TfToken interpolation; - VtIntArray assignmentIndices; - - if (!UsdMayaMeshWriteUtils::getMeshUVSetData( meshFn, - uvSetNames[i], - &uvValues, - &interpolation, - &assignmentIndices)) { + TfToken interpolation; + VtIntArray assignmentIndices; + + if (!UsdMayaMeshWriteUtils::getMeshUVSetData( + meshFn, uvSetNames[i], &uvValues, &interpolation, &assignmentIndices)) { continue; } @@ -836,70 +826,72 @@ UsdMayaMeshWriteUtils::writeUVSetsAsVec2fPrimvars(const MFnMesh& meshFn, } // create UV PrimVar - createUVPrimVar(primSchema, - setName, - usdTime, - uvValues, - interpolation, - assignmentIndices, - valueWriter); + createUVPrimVar( + primSchema, setName, usdTime, uvValues, interpolation, assignmentIndices, valueWriter); } return true; } -void -UsdMayaMeshWriteUtils::writeSubdivInterpBound(MFnMesh& meshFn, - UsdGeomMesh& primSchema, - UsdUtilsSparseValueWriter* valueWriter) +void UsdMayaMeshWriteUtils::writeSubdivInterpBound( + MFnMesh& meshFn, + UsdGeomMesh& primSchema, + UsdUtilsSparseValueWriter* valueWriter) { TfToken sdInterpBound = UsdMayaMeshWriteUtils::getSubdivInterpBoundary(meshFn); if (!sdInterpBound.IsEmpty()) { - UsdMayaWriteUtil::SetAttribute(primSchema.CreateInterpolateBoundaryAttr(), - sdInterpBound, UsdTimeCode::Default(), valueWriter); + UsdMayaWriteUtil::SetAttribute( + primSchema.CreateInterpolateBoundaryAttr(), + sdInterpBound, + UsdTimeCode::Default(), + valueWriter); } } -void -UsdMayaMeshWriteUtils::writeSubdivFVLinearInterpolation(MFnMesh& meshFn, - UsdGeomMesh& primSchema, - UsdUtilsSparseValueWriter* valueWriter) +void UsdMayaMeshWriteUtils::writeSubdivFVLinearInterpolation( + MFnMesh& meshFn, + UsdGeomMesh& primSchema, + UsdUtilsSparseValueWriter* valueWriter) { TfToken sdFVLinearInterpolation = UsdMayaMeshWriteUtils::getSubdivFVLinearInterpolation(meshFn); if (!sdFVLinearInterpolation.IsEmpty()) { - UsdMayaWriteUtil::SetAttribute(primSchema.CreateFaceVaryingLinearInterpolationAttr(), - sdFVLinearInterpolation, UsdTimeCode::Default(), valueWriter); + UsdMayaWriteUtil::SetAttribute( + primSchema.CreateFaceVaryingLinearInterpolationAttr(), + sdFVLinearInterpolation, + UsdTimeCode::Default(), + valueWriter); } } -void -UsdMayaMeshWriteUtils::writeNormalsData(const MFnMesh& meshFn, - UsdGeomMesh& primSchema, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter* valueWriter) +void UsdMayaMeshWriteUtils::writeNormalsData( + const MFnMesh& meshFn, + UsdGeomMesh& primSchema, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) { VtVec3fArray meshNormals; - TfToken normalInterp; + TfToken normalInterp; - if (UsdMayaMeshWriteUtils::getMeshNormals(meshFn, &meshNormals,&normalInterp)) { + if (UsdMayaMeshWriteUtils::getMeshNormals(meshFn, &meshNormals, &normalInterp)) { - UsdMayaWriteUtil::SetAttribute(primSchema.GetNormalsAttr(), &meshNormals, usdTime, valueWriter); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetNormalsAttr(), &meshNormals, usdTime, valueWriter); primSchema.SetNormalsInterpolation(normalInterp); } } -bool -UsdMayaMeshWriteUtils::addDisplayPrimvars(UsdGeomGprim &primSchema, - const UsdTimeCode& usdTime, - const MFnMesh::MColorRepresentation colorRep, - const VtVec3fArray& RGBData, - const VtFloatArray& AlphaData, - const TfToken& interpolation, - const VtIntArray& assignmentIndices, - const bool clamped, - const bool authored, - UsdUtilsSparseValueWriter* valueWriter) +bool UsdMayaMeshWriteUtils::addDisplayPrimvars( + UsdGeomGprim& primSchema, + const UsdTimeCode& usdTime, + const MFnMesh::MColorRepresentation colorRep, + const VtVec3fArray& RGBData, + const VtFloatArray& AlphaData, + const TfToken& interpolation, + const VtIntArray& assignmentIndices, + const bool clamped, + const bool authored, + UsdUtilsSparseValueWriter* valueWriter) { // We are appending the default value to the primvar in the post export function // so if the dataset is empty and the assignment indices are not, we still @@ -912,12 +904,13 @@ UsdMayaMeshWriteUtils::addDisplayPrimvars(UsdGeomGprim &primSchema, displayColor.SetInterpolation(interpolation); } - setPrimvar(displayColor, - assignmentIndices, - VtValue(RGBData), - VtValue(UnauthoredShaderRGB), - usdTime, - valueWriter); + setPrimvar( + displayColor, + assignmentIndices, + VtValue(RGBData), + VtValue(UnauthoredShaderRGB), + usdTime, + valueWriter); bool authRGB = authored; if (colorRep == MFnMesh::kAlpha) { @@ -927,8 +920,7 @@ UsdMayaMeshWriteUtils::addDisplayPrimvars(UsdGeomGprim &primSchema, if (clamped) { UsdMayaRoundTripUtil::MarkPrimvarAsClamped(displayColor); } - } - else { + } else { UsdMayaRoundTripUtil::MarkAttributeAsMayaGenerated(colorAttr); } } @@ -944,12 +936,13 @@ UsdMayaMeshWriteUtils::addDisplayPrimvars(UsdGeomGprim &primSchema, displayOpacity.SetInterpolation(interpolation); } - setPrimvar(displayOpacity, - assignmentIndices, - VtValue(AlphaData), - VtValue(UnauthoredShaderAlpha), - usdTime, - valueWriter); + setPrimvar( + displayOpacity, + assignmentIndices, + VtValue(AlphaData), + VtValue(UnauthoredShaderAlpha), + usdTime, + valueWriter); bool authAlpha = authored; if (colorRep == MFnMesh::kRGB) { @@ -959,8 +952,7 @@ UsdMayaMeshWriteUtils::addDisplayPrimvars(UsdGeomGprim &primSchema, if (clamped) { UsdMayaRoundTripUtil::MarkPrimvarAsClamped(displayOpacity); } - } - else { + } else { UsdMayaRoundTripUtil::MarkAttributeAsMayaGenerated(alphaAttr); } } @@ -969,15 +961,15 @@ UsdMayaMeshWriteUtils::addDisplayPrimvars(UsdGeomGprim &primSchema, return true; } -bool -UsdMayaMeshWriteUtils::createRGBPrimVar(UsdGeomGprim &primSchema, - const TfToken& name, - const UsdTimeCode& usdTime, - const VtVec3fArray& data, - const TfToken& interpolation, - const VtIntArray& assignmentIndices, - bool clamped, - UsdUtilsSparseValueWriter* valueWriter) +bool UsdMayaMeshWriteUtils::createRGBPrimVar( + UsdGeomGprim& primSchema, + const TfToken& name, + const UsdTimeCode& usdTime, + const VtVec3fArray& data, + const TfToken& interpolation, + const VtIntArray& assignmentIndices, + bool clamped, + UsdUtilsSparseValueWriter* valueWriter) { const unsigned int numValues = data.size(); if (numValues == 0) { @@ -989,15 +981,16 @@ UsdMayaMeshWriteUtils::createRGBPrimVar(UsdGeomGprim &primSchema, interp = TfToken(); } - UsdGeomPrimvar primVar = primSchema.CreatePrimvar(name, - SdfValueTypeNames->Color3fArray, - interp); + UsdGeomPrimvar primVar + = primSchema.CreatePrimvar(name, SdfValueTypeNames->Color3fArray, interp); - setPrimvar(primVar, - assignmentIndices, - VtValue(data), - VtValue(UnauthoredColorSetRGB), - usdTime, valueWriter); + setPrimvar( + primVar, + assignmentIndices, + VtValue(data), + VtValue(UnauthoredColorSetRGB), + usdTime, + valueWriter); if (clamped) { UsdMayaRoundTripUtil::MarkPrimvarAsClamped(primVar); @@ -1006,16 +999,16 @@ UsdMayaMeshWriteUtils::createRGBPrimVar(UsdGeomGprim &primSchema, return true; } -bool -UsdMayaMeshWriteUtils::createRGBAPrimVar(UsdGeomGprim &primSchema, - const TfToken& name, - const UsdTimeCode& usdTime, - const VtVec3fArray& rgbData, - const VtFloatArray& alphaData, - const TfToken& interpolation, - const VtIntArray& assignmentIndices, - bool clamped, - UsdUtilsSparseValueWriter* valueWriter) +bool UsdMayaMeshWriteUtils::createRGBAPrimVar( + UsdGeomGprim& primSchema, + const TfToken& name, + const UsdTimeCode& usdTime, + const VtVec3fArray& rgbData, + const VtFloatArray& alphaData, + const TfToken& interpolation, + const VtIntArray& assignmentIndices, + bool clamped, + UsdUtilsSparseValueWriter* valueWriter) { const unsigned int numValues = rgbData.size(); if (numValues == 0 || numValues != alphaData.size()) { @@ -1027,23 +1020,21 @@ UsdMayaMeshWriteUtils::createRGBAPrimVar(UsdGeomGprim &primSchema, interp = TfToken(); } - UsdGeomPrimvar primVar = - primSchema.CreatePrimvar(name, - SdfValueTypeNames->Color4fArray, - interp); + UsdGeomPrimvar primVar + = primSchema.CreatePrimvar(name, SdfValueTypeNames->Color4fArray, interp); VtArray rgbaData(numValues); for (size_t i = 0; i < rgbaData.size(); ++i) { - rgbaData[i] = GfVec4f(rgbData[i][0], rgbData[i][1], rgbData[i][2], - alphaData[i]); + rgbaData[i] = GfVec4f(rgbData[i][0], rgbData[i][1], rgbData[i][2], alphaData[i]); } - setPrimvar(primVar, - assignmentIndices, - VtValue(rgbaData), - VtValue(UnauthoredColorSetRGBA), - usdTime, - valueWriter); + setPrimvar( + primVar, + assignmentIndices, + VtValue(rgbaData), + VtValue(UnauthoredColorSetRGBA), + usdTime, + valueWriter); if (clamped) { UsdMayaRoundTripUtil::MarkPrimvarAsClamped(primVar); @@ -1052,15 +1043,15 @@ UsdMayaMeshWriteUtils::createRGBAPrimVar(UsdGeomGprim &primSchema, return true; } -bool -UsdMayaMeshWriteUtils::createAlphaPrimVar(UsdGeomGprim &primSchema, - const TfToken& name, - const UsdTimeCode& usdTime, - const VtFloatArray& data, - const TfToken& interpolation, - const VtIntArray& assignmentIndices, - bool clamped, - UsdUtilsSparseValueWriter* valueWriter) +bool UsdMayaMeshWriteUtils::createAlphaPrimVar( + UsdGeomGprim& primSchema, + const TfToken& name, + const UsdTimeCode& usdTime, + const VtFloatArray& data, + const TfToken& interpolation, + const VtIntArray& assignmentIndices, + bool clamped, + UsdUtilsSparseValueWriter* valueWriter) { const unsigned int numValues = data.size(); if (numValues == 0) { @@ -1072,16 +1063,14 @@ UsdMayaMeshWriteUtils::createAlphaPrimVar(UsdGeomGprim &primSchema, interp = TfToken(); } - UsdGeomPrimvar primVar = - primSchema.CreatePrimvar(name, - SdfValueTypeNames->FloatArray, - interp); - setPrimvar(primVar, - assignmentIndices, - VtValue(data), - VtValue(UnauthoredColorAlpha), - usdTime, - valueWriter); + UsdGeomPrimvar primVar = primSchema.CreatePrimvar(name, SdfValueTypeNames->FloatArray, interp); + setPrimvar( + primVar, + assignmentIndices, + VtValue(data), + VtValue(UnauthoredColorAlpha), + usdTime, + valueWriter); if (clamped) { UsdMayaRoundTripUtil::MarkPrimvarAsClamped(primVar); @@ -1090,29 +1079,28 @@ UsdMayaMeshWriteUtils::createAlphaPrimVar(UsdGeomGprim &primSchema, return true; } -bool -UsdMayaMeshWriteUtils::getMeshColorSetData(MFnMesh& mesh, - const MString& colorSet, - bool isDisplayColor, - const VtVec3fArray& shadersRGBData, - const VtFloatArray& shadersAlphaData, - const VtIntArray& shadersAssignmentIndices, - VtVec3fArray* colorSetRGBData, - VtFloatArray* colorSetAlphaData, - TfToken* interpolation, - VtIntArray* colorSetAssignmentIndices, - MFnMesh::MColorRepresentation* colorSetRep, - bool* clamped) +bool UsdMayaMeshWriteUtils::getMeshColorSetData( + MFnMesh& mesh, + const MString& colorSet, + bool isDisplayColor, + const VtVec3fArray& shadersRGBData, + const VtFloatArray& shadersAlphaData, + const VtIntArray& shadersAssignmentIndices, + VtVec3fArray* colorSetRGBData, + VtFloatArray* colorSetAlphaData, + TfToken* interpolation, + VtIntArray* colorSetAssignmentIndices, + MFnMesh::MColorRepresentation* colorSetRep, + bool* clamped) { // If there are no colors, return immediately as failure. if (mesh.numColors(colorSet) == 0) { return false; } - MColorArray colorSetData; + MColorArray colorSetData; const MColor unsetColor(-FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX); - if (mesh.getFaceVertexColors(colorSetData, &colorSet, &unsetColor) - == MS::kFailure) { + if (mesh.getFaceVertexColors(colorSetData, &colorSet, &unsetColor) == MS::kFailure) { return false; } @@ -1134,7 +1122,7 @@ UsdMayaMeshWriteUtils::getMeshColorSetData(MFnMesh& mesh, // Loop over every face vertex to populate the value arrays. MItMeshFaceVertex itFV(mesh.object()); - unsigned int fvi = 0; + unsigned int fvi = 0; for (itFV.reset(); !itFV.isDone(); itFV.next(), ++fvi) { // If this is a displayColor color set, we may need to fallback on the // bound shader colors/alphas for this face in some cases. In @@ -1177,12 +1165,12 @@ UsdMayaMeshWriteUtils::getMeshColorSetData(MFnMesh& mesh, if (shadersRGBData.size() == 1) { valueIndex = 0; } - } else if (faceIndex >= 0 && - static_cast(faceIndex) < shadersAssignmentIndices.size()) { + } else if ( + faceIndex >= 0 + && static_cast(faceIndex) < shadersAssignmentIndices.size()) { int tmpIndex = shadersAssignmentIndices[faceIndex]; - if (tmpIndex >= 0 && - static_cast(tmpIndex) < shadersRGBData.size()) { + if (tmpIndex >= 0 && static_cast(tmpIndex) < shadersRGBData.size()) { valueIndex = tmpIndex; } } @@ -1203,11 +1191,11 @@ UsdMayaMeshWriteUtils::getMeshColorSetData(MFnMesh& mesh, if (shadersAlphaData.size() == 1) { valueIndex = 0; } - } else if (faceIndex >= 0 && - static_cast(faceIndex) < shadersAssignmentIndices.size()) { + } else if ( + faceIndex >= 0 + && static_cast(faceIndex) < shadersAssignmentIndices.size()) { int tmpIndex = shadersAssignmentIndices[faceIndex]; - if (tmpIndex >= 0 && - static_cast(tmpIndex) < shadersAlphaData.size()) { + if (tmpIndex >= 0 && static_cast(tmpIndex) < shadersAlphaData.size()) { valueIndex = tmpIndex; } } @@ -1222,17 +1210,14 @@ UsdMayaMeshWriteUtils::getMeshColorSetData(MFnMesh& mesh, // If we have a color/alpha value, add it to the data to be returned. if (colorSetData[fvi] != unsetColor) { GfVec3f rgbValue = UnauthoredColorSetRGB; - float alphaValue = UnauthoredColorAlpha; + float alphaValue = UnauthoredColorAlpha; - if (useShaderColorFallback || - (*colorSetRep == MFnMesh::kRGB) || - (*colorSetRep == MFnMesh::kRGBA)) { - rgbValue = LinearColorFromColorSet(colorSetData[fvi], - convertDisplayColorToLinear); + if (useShaderColorFallback || (*colorSetRep == MFnMesh::kRGB) + || (*colorSetRep == MFnMesh::kRGBA)) { + rgbValue = LinearColorFromColorSet(colorSetData[fvi], convertDisplayColorToLinear); } - if (useShaderAlphaFallback || - (*colorSetRep == MFnMesh::kAlpha) || - (*colorSetRep == MFnMesh::kRGBA)) { + if (useShaderAlphaFallback || (*colorSetRep == MFnMesh::kAlpha) + || (*colorSetRep == MFnMesh::kRGBA)) { alphaValue = colorSetData[fvi][3]; } @@ -1242,13 +1227,9 @@ UsdMayaMeshWriteUtils::getMeshColorSetData(MFnMesh& mesh, } } - MergeEquivalentColorSetValues(colorSetRGBData, - colorSetAlphaData, - colorSetAssignmentIndices); + MergeEquivalentColorSetValues(colorSetRGBData, colorSetAlphaData, colorSetAssignmentIndices); - UsdMayaUtil::CompressFaceVaryingPrimvarIndices(mesh, - interpolation, - colorSetAssignmentIndices); + UsdMayaUtil::CompressFaceVaryingPrimvarIndices(mesh, interpolation, colorSetAssignmentIndices); return true; } diff --git a/lib/mayaUsd/fileio/utils/meshWriteUtils.h b/lib/mayaUsd/fileio/utils/meshWriteUtils.h index 5257ef4395..2b9dd6e313 100644 --- a/lib/mayaUsd/fileio/utils/meshWriteUtils.h +++ b/lib/mayaUsd/fileio/utils/meshWriteUtils.h @@ -20,176 +20,188 @@ #include -#include -#include -#include -#include - -#include #include #include #include #include +#include #include #include #include +#include +#include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE class UsdGeomMesh; // Utilities for dealing with writing USD from Maya mesh/subdiv tags. -namespace UsdMayaMeshWriteUtils -{ - /// Helper method for getting Maya mesh normals as a VtVec3fArray. - MAYAUSD_CORE_PUBLIC - bool getMeshNormals(const MFnMesh& mesh, - VtVec3fArray* normalsArray, - TfToken* interpolation); - - /// Gets the subdivision scheme tagged for the Maya mesh by consulting the - /// adaptor for \c UsdGeomMesh.subdivisionSurface, and then falling back to - /// the RenderMan for Maya attribute. - MAYAUSD_CORE_PUBLIC - TfToken getSubdivScheme(const MFnMesh &mesh); - - /// Gets the subdivision interpolate boundary tagged for the Maya mesh by - /// consulting the adaptor for \c UsdGeomMesh.interpolateBoundary, and then - /// falling back to the RenderMan for Maya attribute. - MAYAUSD_CORE_PUBLIC - TfToken getSubdivInterpBoundary(const MFnMesh &mesh); - - /// Gets the subdivision face-varying linear interpolation tagged for the - /// Maya mesh by consulting the adaptor for - /// \c UsdGeomMesh.faceVaryingLinearInterpolation, and then falling back to - /// the OpenSubdiv2-style tagging. - MAYAUSD_CORE_PUBLIC - TfToken getSubdivFVLinearInterpolation(const MFnMesh& mesh); - - MAYAUSD_CORE_PUBLIC - bool isMeshValid(const MDagPath& dagPath); - - MAYAUSD_CORE_PUBLIC - void exportReferenceMesh(UsdGeomMesh& primSchema, MObject obj); - - MAYAUSD_CORE_PUBLIC - void assignSubDivTagsToUSDPrim(MFnMesh& meshFn, - UsdGeomMesh& primSchema, - UsdUtilsSparseValueWriter* valueWriter); - - void assignSubDivTagsToUSDPrim(MFnMesh& meshFn, - UsdGeomMesh& primSchema, - UsdUtilsSparseValueWriter* valueWriter); - - MAYAUSD_CORE_PUBLIC - void writePointsData(const MFnMesh& meshFn, - UsdGeomMesh& primSchema, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter* valueWriter); - - MAYAUSD_CORE_PUBLIC - void writeFaceVertexIndicesData(const MFnMesh& meshFn, - UsdGeomMesh& primSchema, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter* valueWriter); - - MAYAUSD_CORE_PUBLIC - void writeInvisibleFacesData(const MFnMesh& meshFn, - UsdGeomMesh& primSchema, - UsdUtilsSparseValueWriter* valueWriter); - - MAYAUSD_CORE_PUBLIC - bool getMeshUVSetData(const MFnMesh& mesh, - const MString& uvSetName, - VtVec2fArray* uvArray, - TfToken* interpolation, - VtIntArray* assignmentIndices); - - MAYAUSD_CORE_PUBLIC - bool writeUVSetsAsVec2fPrimvars(const MFnMesh& meshFn, - UsdGeomMesh& primSchema, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter* valueWriter); - - MAYAUSD_CORE_PUBLIC - void writeSubdivInterpBound(MFnMesh& mesh, - UsdGeomMesh& primSchema, - UsdUtilsSparseValueWriter* valueWriter); - - MAYAUSD_CORE_PUBLIC - void writeSubdivFVLinearInterpolation(MFnMesh& meshFn, - UsdGeomMesh& primSchema, - UsdUtilsSparseValueWriter* valueWriter); - - MAYAUSD_CORE_PUBLIC - void writeNormalsData(const MFnMesh& meshFn, - UsdGeomMesh& primSchema, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter* valueWriter); - - MAYAUSD_CORE_PUBLIC - bool addDisplayPrimvars(UsdGeomGprim& primSchema, - const UsdTimeCode& usdTime, - const MFnMesh::MColorRepresentation colorRep, - const VtVec3fArray& RGBData, - const VtFloatArray& AlphaData, - const TfToken& interpolation, - const VtIntArray& assignmentIndices, - const bool clamped, - const bool authored, - UsdUtilsSparseValueWriter* valueWriter); - - MAYAUSD_CORE_PUBLIC - bool createRGBPrimVar(UsdGeomGprim& primSchema, - const TfToken& name, - const UsdTimeCode& usdTime, - const VtVec3fArray& data, - const TfToken& interpolation, - const VtIntArray& assignmentIndices, - bool clamped, - UsdUtilsSparseValueWriter* valueWriter); - - MAYAUSD_CORE_PUBLIC - bool createRGBAPrimVar(UsdGeomGprim& primSchema, - const TfToken& name, - const UsdTimeCode& usdTime, - const VtVec3fArray& rgbData, - const VtFloatArray& alphaData, - const TfToken& interpolation, - const VtIntArray& assignmentIndices, - bool clamped, - UsdUtilsSparseValueWriter* valueWriter); - - MAYAUSD_CORE_PUBLIC - bool createAlphaPrimVar(UsdGeomGprim& primSchema, - const TfToken& name, - const UsdTimeCode& usdTime, - const VtFloatArray& data, - const TfToken& interpolation, - const VtIntArray& assignmentIndices, - bool clamped, - UsdUtilsSparseValueWriter* valueWriter); - - /// Collect values from the color set named \p colorSet. - /// If \p isDisplayColor is true and this color set represents displayColor, - /// the unauthored/unpainted values in the color set will be filled in using - /// the shader values in \p shadersRGBData and \p shadersAlphaData if available. - /// Values are gathered per face vertex, but then the data is compressed to - /// vertex, uniform, or constant interpolation if possible. - /// Unauthored/unpainted values will be given the index -1. - MAYAUSD_CORE_PUBLIC - bool getMeshColorSetData( MFnMesh& mesh, - const MString& colorSet, - bool isDisplayColor, - const VtVec3fArray& shadersRGBData, - const VtFloatArray& shadersAlphaData, - const VtIntArray& shadersAssignmentIndices, - VtVec3fArray* colorSetRGBData, - VtFloatArray* colorSetAlphaData, - TfToken* interpolation, - VtIntArray* colorSetAssignmentIndices, - MFnMesh::MColorRepresentation* colorSetRep, - bool* clamped); +namespace UsdMayaMeshWriteUtils { +/// Helper method for getting Maya mesh normals as a VtVec3fArray. +MAYAUSD_CORE_PUBLIC +bool getMeshNormals(const MFnMesh& mesh, VtVec3fArray* normalsArray, TfToken* interpolation); + +/// Gets the subdivision scheme tagged for the Maya mesh by consulting the +/// adaptor for \c UsdGeomMesh.subdivisionSurface, and then falling back to +/// the RenderMan for Maya attribute. +MAYAUSD_CORE_PUBLIC +TfToken getSubdivScheme(const MFnMesh& mesh); + +/// Gets the subdivision interpolate boundary tagged for the Maya mesh by +/// consulting the adaptor for \c UsdGeomMesh.interpolateBoundary, and then +/// falling back to the RenderMan for Maya attribute. +MAYAUSD_CORE_PUBLIC +TfToken getSubdivInterpBoundary(const MFnMesh& mesh); + +/// Gets the subdivision face-varying linear interpolation tagged for the +/// Maya mesh by consulting the adaptor for +/// \c UsdGeomMesh.faceVaryingLinearInterpolation, and then falling back to +/// the OpenSubdiv2-style tagging. +MAYAUSD_CORE_PUBLIC +TfToken getSubdivFVLinearInterpolation(const MFnMesh& mesh); + +MAYAUSD_CORE_PUBLIC +bool isMeshValid(const MDagPath& dagPath); + +MAYAUSD_CORE_PUBLIC +void exportReferenceMesh(UsdGeomMesh& primSchema, MObject obj); + +MAYAUSD_CORE_PUBLIC +void assignSubDivTagsToUSDPrim( + MFnMesh& meshFn, + UsdGeomMesh& primSchema, + UsdUtilsSparseValueWriter* valueWriter); + +void assignSubDivTagsToUSDPrim( + MFnMesh& meshFn, + UsdGeomMesh& primSchema, + UsdUtilsSparseValueWriter* valueWriter); + +MAYAUSD_CORE_PUBLIC +void writePointsData( + const MFnMesh& meshFn, + UsdGeomMesh& primSchema, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter); + +MAYAUSD_CORE_PUBLIC +void writeFaceVertexIndicesData( + const MFnMesh& meshFn, + UsdGeomMesh& primSchema, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter); + +MAYAUSD_CORE_PUBLIC +void writeInvisibleFacesData( + const MFnMesh& meshFn, + UsdGeomMesh& primSchema, + UsdUtilsSparseValueWriter* valueWriter); + +MAYAUSD_CORE_PUBLIC +bool getMeshUVSetData( + const MFnMesh& mesh, + const MString& uvSetName, + VtVec2fArray* uvArray, + TfToken* interpolation, + VtIntArray* assignmentIndices); + +MAYAUSD_CORE_PUBLIC +bool writeUVSetsAsVec2fPrimvars( + const MFnMesh& meshFn, + UsdGeomMesh& primSchema, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter); + +MAYAUSD_CORE_PUBLIC +void writeSubdivInterpBound( + MFnMesh& mesh, + UsdGeomMesh& primSchema, + UsdUtilsSparseValueWriter* valueWriter); + +MAYAUSD_CORE_PUBLIC +void writeSubdivFVLinearInterpolation( + MFnMesh& meshFn, + UsdGeomMesh& primSchema, + UsdUtilsSparseValueWriter* valueWriter); + +MAYAUSD_CORE_PUBLIC +void writeNormalsData( + const MFnMesh& meshFn, + UsdGeomMesh& primSchema, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter); + +MAYAUSD_CORE_PUBLIC +bool addDisplayPrimvars( + UsdGeomGprim& primSchema, + const UsdTimeCode& usdTime, + const MFnMesh::MColorRepresentation colorRep, + const VtVec3fArray& RGBData, + const VtFloatArray& AlphaData, + const TfToken& interpolation, + const VtIntArray& assignmentIndices, + const bool clamped, + const bool authored, + UsdUtilsSparseValueWriter* valueWriter); + +MAYAUSD_CORE_PUBLIC +bool createRGBPrimVar( + UsdGeomGprim& primSchema, + const TfToken& name, + const UsdTimeCode& usdTime, + const VtVec3fArray& data, + const TfToken& interpolation, + const VtIntArray& assignmentIndices, + bool clamped, + UsdUtilsSparseValueWriter* valueWriter); + +MAYAUSD_CORE_PUBLIC +bool createRGBAPrimVar( + UsdGeomGprim& primSchema, + const TfToken& name, + const UsdTimeCode& usdTime, + const VtVec3fArray& rgbData, + const VtFloatArray& alphaData, + const TfToken& interpolation, + const VtIntArray& assignmentIndices, + bool clamped, + UsdUtilsSparseValueWriter* valueWriter); + +MAYAUSD_CORE_PUBLIC +bool createAlphaPrimVar( + UsdGeomGprim& primSchema, + const TfToken& name, + const UsdTimeCode& usdTime, + const VtFloatArray& data, + const TfToken& interpolation, + const VtIntArray& assignmentIndices, + bool clamped, + UsdUtilsSparseValueWriter* valueWriter); + +/// Collect values from the color set named \p colorSet. +/// If \p isDisplayColor is true and this color set represents displayColor, +/// the unauthored/unpainted values in the color set will be filled in using +/// the shader values in \p shadersRGBData and \p shadersAlphaData if available. +/// Values are gathered per face vertex, but then the data is compressed to +/// vertex, uniform, or constant interpolation if possible. +/// Unauthored/unpainted values will be given the index -1. +MAYAUSD_CORE_PUBLIC +bool getMeshColorSetData( + MFnMesh& mesh, + const MString& colorSet, + bool isDisplayColor, + const VtVec3fArray& shadersRGBData, + const VtFloatArray& shadersAlphaData, + const VtIntArray& shadersAssignmentIndices, + VtVec3fArray* colorSetRGBData, + VtFloatArray* colorSetAlphaData, + TfToken* interpolation, + VtIntArray* colorSetAssignmentIndices, + MFnMesh::MColorRepresentation* colorSetRep, + bool* clamped); } // namespace UsdMayaMeshWriteUtils diff --git a/lib/mayaUsd/fileio/utils/readUtil.cpp b/lib/mayaUsd/fileio/utils/readUtil.cpp index 934fa1ba2a..0bae5cfedb 100644 --- a/lib/mayaUsd/fileio/utils/readUtil.cpp +++ b/lib/mayaUsd/fileio/utils/readUtil.cpp @@ -15,6 +15,19 @@ // #include "readUtil.h" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + #include #include #include @@ -36,32 +49,18 @@ #include #include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - using namespace MAYAUSD_NS_DEF; PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_ENV_SETTING( - PIXMAYA_READ_FLOAT2_AS_UV, true, - "Set to false to disable ability to read Float2 type as a UV set"); + PIXMAYA_READ_FLOAT2_AS_UV, + true, + "Set to false to disable ability to read Float2 type as a UV set"); -bool -UsdMayaReadUtil::ReadFloat2AsUV() +bool UsdMayaReadUtil::ReadFloat2AsUV() { - static const bool readFloat2AsUV = - TfGetEnvSetting(PIXMAYA_READ_FLOAT2_AS_UV); + static const bool readFloat2AsUV = TfGetEnvSetting(PIXMAYA_READ_FLOAT2_AS_UV); return readFloat2AsUV; } @@ -71,47 +70,41 @@ TF_DEFINE_ENV_SETTING( "Translates the primary UV set in USD to the map1 UV set in Maya. " "When disabled, UV set names are translated directly (st in USD becomes st in Maya)."); -bool -UsdMayaReadUtil::ReadSTAsMap1() +bool UsdMayaReadUtil::ReadSTAsMap1() { - static const bool readSTAsMap1 = - TfGetEnvSetting(MAYAUSD_IMPORT_PRIMARY_UV_SET_AS_MAP1); + static const bool readSTAsMap1 = TfGetEnvSetting(MAYAUSD_IMPORT_PRIMARY_UV_SET_AS_MAP1); return readSTAsMap1; } -MObject -UsdMayaReadUtil::FindOrCreateMayaAttr( - const SdfValueTypeName& typeName, - const SdfVariability variability, - MFnDependencyNode& depNode, - const std::string& attrName, - const std::string& attrNiceName) +MObject UsdMayaReadUtil::FindOrCreateMayaAttr( + const SdfValueTypeName& typeName, + const SdfVariability variability, + MFnDependencyNode& depNode, + const std::string& attrName, + const std::string& attrNiceName) { MDGModifier modifier; - return FindOrCreateMayaAttr(typeName, variability, depNode, attrName, - attrNiceName, modifier); + return FindOrCreateMayaAttr(typeName, variability, depNode, attrName, attrNiceName, modifier); } -static MObject -_FindOrCreateMayaTypedAttr( - const std::string& attrName, - const std::string& attrNiceName, +static MObject _FindOrCreateMayaTypedAttr( + const std::string& attrName, + const std::string& attrNiceName, const MFnData::Type type, - const bool keyable, - const bool usedAsColor, - const bool usedAsFilename, - MFnDependencyNode& depNode, - MDGModifier& modifier) + const bool keyable, + const bool usedAsColor, + const bool usedAsFilename, + MFnDependencyNode& depNode, + MDGModifier& modifier) { MString mayaName = attrName.c_str(); - MString niceName = attrNiceName.empty() ? - attrName.c_str() : attrNiceName.c_str(); + MString niceName = attrNiceName.empty() ? attrName.c_str() : attrNiceName.c_str(); MPlug plug = depNode.findPlug(mayaName, true); if (plug.isNull()) { // Create. MFnTypedAttribute attr; - MObject attrObj = attr.create(mayaName, mayaName, type); + MObject attrObj = attr.create(mayaName, mayaName, type); attr.setNiceNameOverride(niceName); attr.setKeyable(keyable); @@ -125,39 +118,34 @@ _FindOrCreateMayaTypedAttr( modifier.addAttribute(depNode.object(), attrObj); modifier.doIt(); return attrObj; - } - else { + } else { // Found -- verify. if (Converter::hasAttrType(plug, type)) { return plug.attribute(); - } - else { - TF_RUNTIME_ERROR("Plug %s has unexpected type", - plug.name().asChar()); + } else { + TF_RUNTIME_ERROR("Plug %s has unexpected type", plug.name().asChar()); return MObject(); } } } -static MObject -_FindOrCreateMayaNumericAttr( - const std::string& attrName, - const std::string& attrNiceName, +static MObject _FindOrCreateMayaNumericAttr( + const std::string& attrName, + const std::string& attrNiceName, const MFnNumericData::Type type, - const bool keyable, - const bool usedAsColor, - MFnDependencyNode& depNode, - MDGModifier& modifier) + const bool keyable, + const bool usedAsColor, + MFnDependencyNode& depNode, + MDGModifier& modifier) { MString mayaName = attrName.c_str(); - MString niceName = attrNiceName.empty() ? - attrName.c_str() : attrNiceName.c_str(); + MString niceName = attrNiceName.empty() ? attrName.c_str() : attrNiceName.c_str(); MPlug plug = depNode.findPlug(mayaName, true); if (plug.isNull()) { // Create. MFnNumericAttribute attr; - MObject attrObj = attr.create(mayaName, mayaName, type); + MObject attrObj = attr.create(mayaName, mayaName, type); attr.setNiceNameOverride(niceName); attr.setKeyable(keyable); @@ -166,66 +154,59 @@ _FindOrCreateMayaNumericAttr( } const unsigned int numChildren = MFnCompoundAttribute(attrObj).numChildren(); - if(numChildren < 5u) { - static MString suffix[4] = {" X", " Y", " Z", " W"}; - for(unsigned int i = 0; i < numChildren; i++) { - MFnAttribute(attr.child(i)).setNiceNameOverride(niceName+suffix[i]); + if (numChildren < 5u) { + static MString suffix[4] = { " X", " Y", " Z", " W" }; + for (unsigned int i = 0; i < numChildren; i++) { + MFnAttribute(attr.child(i)).setNiceNameOverride(niceName + suffix[i]); } } else { TF_CODING_ERROR("Unexpected number of children on numeric attribute"); } - + modifier.addAttribute(depNode.object(), attrObj); modifier.doIt(); return attrObj; - } - else { + } else { // Found -- verify. if (Converter::hasNumericType(plug, type) - || (type == MFnNumericData::kInt && Converter::hasEnumType(plug))) - { + || (type == MFnNumericData::kInt && Converter::hasEnumType(plug))) { return plug.attribute(); - } - else { - TF_RUNTIME_ERROR("Plug %s has unexpected type", - plug.name().asChar()); + } else { + TF_RUNTIME_ERROR("Plug %s has unexpected type", plug.name().asChar()); return MObject(); } } } -MObject -UsdMayaReadUtil::FindOrCreateMayaAttr( - const SdfValueTypeName& typeName, - const SdfVariability variability, - MFnDependencyNode& depNode, - const std::string& attrName, - const std::string& attrNiceName, - MDGModifier& modifier) +MObject UsdMayaReadUtil::FindOrCreateMayaAttr( + const SdfValueTypeName& typeName, + const SdfVariability variability, + MFnDependencyNode& depNode, + const std::string& attrName, + const std::string& attrNiceName, + MDGModifier& modifier) { return FindOrCreateMayaAttr( - typeName.GetType(), - typeName.GetRole(), - variability, - depNode, - attrName, - attrNiceName, - modifier); + typeName.GetType(), + typeName.GetRole(), + variability, + depNode, + attrName, + attrNiceName, + modifier); } -MObject -UsdMayaReadUtil::FindOrCreateMayaAttr( - const TfType& type, - const TfToken& role, - const SdfVariability variability, - MFnDependencyNode& depNode, - const std::string& attrName, - const std::string& attrNiceName, - MDGModifier& modifier) +MObject UsdMayaReadUtil::FindOrCreateMayaAttr( + const TfType& type, + const TfToken& role, + const SdfVariability variability, + MFnDependencyNode& depNode, + const std::string& attrName, + const std::string& attrNiceName, + MDGModifier& modifier) { MString mayaName = attrName.c_str(); - MString niceName = attrNiceName.empty() ? - attrName.c_str() : attrNiceName.c_str(); + MString niceName = attrNiceName.empty() ? attrName.c_str() : attrNiceName.c_str(); // For the majority of things, we don't care about the role, just about // the type, e.g. we export point3f/vector3f/float3 the same. @@ -235,141 +216,240 @@ UsdMayaReadUtil::FindOrCreateMayaAttr( MObject attrObj; if (type.IsA()) { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kString, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kString, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else if (type.IsA()) { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kString, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kString, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else if (type.IsA()) { // XXX We're not setting usedAsFilename right now because we can't // figure out how to opt-out of Maya's internal path resolution. // This is still OK when we round-trip because we'll still generate // SdfAssetPaths when we check the schema attribute's value type name. - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kString, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kMatrix, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kStringArray, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kStringArray, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kStringArray, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kStringArray, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kDoubleArray, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kFloatArray, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kIntArray, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else if (type.IsA() || - type.IsA()) { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kString, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kMatrix, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kStringArray, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kStringArray, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kStringArray, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kStringArray, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kDoubleArray, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kFloatArray, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kIntArray, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else if (type.IsA() || type.IsA()) { if (role == SdfValueRoleNames->Point) { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kPointArray, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - else { - return _FindOrCreateMayaTypedAttr(attrName, attrNiceName, - MFnData::kVectorArray, keyable, usedAsColor, - /*usedAsFilename*/ false, depNode, modifier); - } - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::kBoolean, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::kInt, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::k2Int, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::k3Int, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::kFloat, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::k2Float, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::k3Float, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::kDouble, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::k2Double, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::k3Double, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::k4Double, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::k4Double, keyable, usedAsColor, - depNode, modifier); - } - else if (type.IsA()) { - return _FindOrCreateMayaNumericAttr(attrName, attrNiceName, - MFnNumericData::k4Double, keyable, usedAsColor, - depNode, modifier); + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kPointArray, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } else { + return _FindOrCreateMayaTypedAttr( + attrName, + attrNiceName, + MFnData::kVectorArray, + keyable, + usedAsColor, + /*usedAsFilename*/ false, + depNode, + modifier); + } + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, + attrNiceName, + MFnNumericData::kBoolean, + keyable, + usedAsColor, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, attrNiceName, MFnNumericData::kInt, keyable, usedAsColor, depNode, modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, attrNiceName, MFnNumericData::k2Int, keyable, usedAsColor, depNode, modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, attrNiceName, MFnNumericData::k3Int, keyable, usedAsColor, depNode, modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, + attrNiceName, + MFnNumericData::kFloat, + keyable, + usedAsColor, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, + attrNiceName, + MFnNumericData::k2Float, + keyable, + usedAsColor, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, + attrNiceName, + MFnNumericData::k3Float, + keyable, + usedAsColor, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, + attrNiceName, + MFnNumericData::kDouble, + keyable, + usedAsColor, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, + attrNiceName, + MFnNumericData::k2Double, + keyable, + usedAsColor, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, + attrNiceName, + MFnNumericData::k3Double, + keyable, + usedAsColor, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, + attrNiceName, + MFnNumericData::k4Double, + keyable, + usedAsColor, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, + attrNiceName, + MFnNumericData::k4Double, + keyable, + usedAsColor, + depNode, + modifier); + } else if (type.IsA()) { + return _FindOrCreateMayaNumericAttr( + attrName, + attrNiceName, + MFnNumericData::k4Double, + keyable, + usedAsColor, + depNode, + modifier); } TF_RUNTIME_ERROR("Type '%s' isn't supported", type.GetTypeName().c_str()); @@ -377,23 +457,19 @@ UsdMayaReadUtil::FindOrCreateMayaAttr( } /// Converts a vec from linear to display color if its attribute is a color. -template -T -_ConvertVec( - const MPlug& plug, - const T& val) { +template T _ConvertVec(const MPlug& plug, const T& val) +{ if (MFnAttribute(plug.attribute()).isUsedAsColor()) { return UsdMayaColorSpace::ConvertLinearToMaya(val); - } - else { + } else { return val; } } bool UsdMayaReadUtil::SetMayaAttr( - MPlug& attrPlug, - const UsdAttribute& usdAttr, - const bool unlinearizeColors) + MPlug& attrPlug, + const UsdAttribute& usdAttr, + const bool unlinearizeColors) { VtValue val; if (usdAttr.Get(&val)) { @@ -407,19 +483,19 @@ bool UsdMayaReadUtil::SetMayaAttr( } bool UsdMayaReadUtil::SetMayaAttr( - MPlug& attrPlug, - const VtValue& newValue, - const bool unlinearizeColors) + MPlug& attrPlug, + const VtValue& newValue, + const bool unlinearizeColors) { MDGModifier modifier; return SetMayaAttr(attrPlug, newValue, modifier, unlinearizeColors); } bool UsdMayaReadUtil::SetMayaAttr( - MPlug& attrPlug, - const VtValue& newValue, - MDGModifier& modifier, - const bool unlinearizeColors) + MPlug& attrPlug, + const VtValue& newValue, + MDGModifier& modifier, + const bool unlinearizeColors) { bool ok = false; if (newValue.IsHolding()) { @@ -428,39 +504,34 @@ bool UsdMayaReadUtil::SetMayaAttr( modifier.newPlugValueString(attrPlug, token.GetText()); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kString)) { std::string str = newValue.Get(); modifier.newPlugValueString(attrPlug, str.c_str()); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kString)) { SdfAssetPath assetPath = newValue.Get(); - modifier.newPlugValueString(attrPlug, - assetPath.GetAssetPath().c_str()); + modifier.newPlugValueString(attrPlug, assetPath.GetAssetPath().c_str()); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kMatrix)) { GfMatrix4d mat = newValue.Get(); - MMatrix mayaMat; + MMatrix mayaMat; for (size_t i = 0; i < 4; ++i) { for (size_t j = 0; j < 4; ++j) { mayaMat[i][j] = mat[i][j]; } } MFnMatrixData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaMat); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kStringArray)) { TfTokenVector result; newValue.Get().ApplyOperations(&result); @@ -469,13 +540,12 @@ bool UsdMayaReadUtil::SetMayaAttr( mayaArr.append(tok.GetText()); } MFnStringArrayData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaArr); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kStringArray)) { std::vector result; newValue.Get().ApplyOperations(&result); @@ -484,13 +554,12 @@ bool UsdMayaReadUtil::SetMayaAttr( mayaArr.append(str.c_str()); } MFnStringArrayData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaArr); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kStringArray)) { VtTokenArray arr = newValue.Get(); MStringArray mayaArr; @@ -498,60 +567,55 @@ bool UsdMayaReadUtil::SetMayaAttr( mayaArr.append(tok.GetText()); } MFnStringArrayData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaArr); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kStringArray)) { VtStringArray arr = newValue.Get(); - MStringArray mayaArr; + MStringArray mayaArr; for (const std::string& str : arr) { mayaArr.append(str.c_str()); } MFnStringArrayData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaArr); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kDoubleArray)) { - VtDoubleArray arr = newValue.Get(); - MDoubleArray mayaArr(arr.data(), arr.size()); + VtDoubleArray arr = newValue.Get(); + MDoubleArray mayaArr(arr.data(), arr.size()); MFnDoubleArrayData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaArr); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kFloatArray)) { - VtFloatArray arr = newValue.Get(); - MFloatArray mayaArr(arr.data(), arr.size()); + VtFloatArray arr = newValue.Get(); + MFloatArray mayaArr(arr.data(), arr.size()); MFnFloatArrayData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaArr); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kIntArray)) { - VtIntArray arr = newValue.Get(); - MIntArray mayaArr(arr.data(), arr.size()); + VtIntArray arr = newValue.Get(); + MIntArray mayaArr(arr.data(), arr.size()); MFnIntArrayData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaArr); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kVectorArray)) { VtVec3dArray arr = newValue.Get(); MVectorArray mayaArr; @@ -559,25 +623,23 @@ bool UsdMayaReadUtil::SetMayaAttr( mayaArr.append(MVector(v[0], v[1], v[2])); } MFnVectorArrayData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaArr); modifier.newPlugValue(attrPlug, dataObj); ok = true; - } - else if (Converter::hasAttrType(attrPlug, MFnData::kPointArray)) { + } else if (Converter::hasAttrType(attrPlug, MFnData::kPointArray)) { VtVec3dArray arr = newValue.Get(); - MPointArray mayaArr; + MPointArray mayaArr; for (const GfVec3d& v : arr) { mayaArr.append(MPoint(v[0], v[1], v[2])); } MFnPointArrayData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaArr); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasAttrType(attrPlug, MFnData::kVectorArray)) { VtVec3fArray arr = newValue.Get(); MVectorArray mayaArr; @@ -585,45 +647,39 @@ bool UsdMayaReadUtil::SetMayaAttr( mayaArr.append(MVector(v[0], v[1], v[2])); } MFnVectorArrayData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaArr); modifier.newPlugValue(attrPlug, dataObj); ok = true; - } - else if (Converter::hasAttrType(attrPlug, MFnData::kPointArray)) { + } else if (Converter::hasAttrType(attrPlug, MFnData::kPointArray)) { VtVec3fArray arr = newValue.Get(); - MPointArray mayaArr; + MPointArray mayaArr; for (const GfVec3d& v : arr) { mayaArr.append(MPoint(v[0], v[1], v[2])); } MFnPointArrayData data; - MObject dataObj = data.create(); + MObject dataObj = data.create(); data.set(mayaArr); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasNumericType(attrPlug, MFnNumericData::kBoolean)) { bool b = newValue.Get(); modifier.newPlugValueBool(attrPlug, b); ok = true; } - } - else if (newValue.IsHolding() || - newValue.IsHolding() || - newValue.IsHolding()) { + } else if ( + newValue.IsHolding() || newValue.IsHolding() || newValue.IsHolding()) { if (Converter::hasNumericType(attrPlug, MFnNumericData::kInt)) { int i = VtValue::Cast(newValue).Get(); modifier.newPlugValueInt(attrPlug, i); ok = true; - } - else if (Converter::hasNumericType(attrPlug, MFnNumericData::kFloat)) { + } else if (Converter::hasNumericType(attrPlug, MFnNumericData::kFloat)) { float f = VtValue::Cast(newValue).Get(); modifier.newPlugValueFloat(attrPlug, f); ok = true; - } - else if (Converter::hasNumericType(attrPlug, MFnNumericData::kDouble)) { + } else if (Converter::hasNumericType(attrPlug, MFnNumericData::kDouble)) { double d = VtValue::Cast(newValue).Get(); modifier.newPlugValueDouble(attrPlug, d); ok = true; @@ -632,103 +688,94 @@ bool UsdMayaReadUtil::SetMayaAttr( modifier.newPlugValueInt(attrPlug, i); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasNumericType(attrPlug, MFnNumericData::k2Int)) { - GfVec2i v = newValue.Get(); + GfVec2i v = newValue.Get(); MFnNumericData data; - MObject dataObj = data.create(MFnNumericData::k2Int); + MObject dataObj = data.create(MFnNumericData::k2Int); data.setData2Int(v[0], v[1]); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasNumericType(attrPlug, MFnNumericData::k3Int)) { - GfVec3i v = newValue.Get(); + GfVec3i v = newValue.Get(); MFnNumericData data; - MObject dataObj = data.create(MFnNumericData::k3Int); + MObject dataObj = data.create(MFnNumericData::k3Int); data.setData3Int(v[0], v[1], v[2]); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasNumericType(attrPlug, MFnNumericData::k2Float)) { - GfVec2f v = newValue.Get(); + GfVec2f v = newValue.Get(); MFnNumericData data; - MObject dataObj = data.create(MFnNumericData::k2Float); + MObject dataObj = data.create(MFnNumericData::k2Float); data.setData2Float(v[0], v[1]); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasNumericType(attrPlug, MFnNumericData::k3Float)) { GfVec3f v = newValue.Get(); if (unlinearizeColors) { v = _ConvertVec(attrPlug, v); } MFnNumericData data; - MObject dataObj = data.create(MFnNumericData::k3Float); + MObject dataObj = data.create(MFnNumericData::k3Float); data.setData3Float(v[0], v[1], v[2]); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasNumericType(attrPlug, MFnNumericData::k2Double)) { - GfVec2d v = newValue.Get(); + GfVec2d v = newValue.Get(); MFnNumericData data; - MObject dataObj = data.create(MFnNumericData::k2Double); + MObject dataObj = data.create(MFnNumericData::k2Double); data.setData2Double(v[0], v[1]); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasNumericType(attrPlug, MFnNumericData::k3Double)) { GfVec3d v = newValue.Get(); if (unlinearizeColors) { v = _ConvertVec(attrPlug, v); } MFnNumericData data; - MObject dataObj = data.create(MFnNumericData::k3Double); + MObject dataObj = data.create(MFnNumericData::k3Double); data.setData3Double(v[0], v[1], v[2]); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasNumericType(attrPlug, MFnNumericData::k4Double)) { GfVec4d v = newValue.Get(); if (unlinearizeColors) { v = _ConvertVec(attrPlug, v); } MFnNumericData data; - MObject dataObj = data.create(MFnNumericData::k4Double); + MObject dataObj = data.create(MFnNumericData::k4Double); data.setData4Double(v[0], v[1], v[2], v[3]); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasNumericType(attrPlug, MFnNumericData::k4Double)) { - GfQuatf q = newValue.Get(); - GfVec3f im = q.GetImaginary(); + GfQuatf q = newValue.Get(); + GfVec3f im = q.GetImaginary(); MFnNumericData data; - MObject dataObj = data.create(MFnNumericData::k4Double); + MObject dataObj = data.create(MFnNumericData::k4Double); data.setData4Double(q.GetReal(), im[0], im[1], im[2]); modifier.newPlugValue(attrPlug, dataObj); ok = true; } - } - else if (newValue.IsHolding()) { + } else if (newValue.IsHolding()) { if (Converter::hasNumericType(attrPlug, MFnNumericData::k4Double)) { - GfQuatd q = newValue.Get(); - GfVec3d im = q.GetImaginary(); + GfQuatd q = newValue.Get(); + GfVec3d im = q.GetImaginary(); MFnNumericData data; - MObject dataObj = data.create(MFnNumericData::k4Double); + MObject dataObj = data.create(MFnNumericData::k4Double); data.setData4Double(q.GetReal(), im[0], im[1], im[2]); modifier.newPlugValue(attrPlug, dataObj); ok = true; @@ -739,39 +786,36 @@ bool UsdMayaReadUtil::SetMayaAttr( modifier.doIt(); } else { TF_RUNTIME_ERROR( - "Cannot set value of type '%s' on plug '%s'", - newValue.GetTypeName().c_str(), - attrPlug.name().asChar()); + "Cannot set value of type '%s' on plug '%s'", + newValue.GetTypeName().c_str(), + attrPlug.name().asChar()); } return ok; } -void -UsdMayaReadUtil::SetMayaAttrKeyableState( - MPlug& attrPlug, - const SdfVariability variability) +void UsdMayaReadUtil::SetMayaAttrKeyableState(MPlug& attrPlug, const SdfVariability variability) { MDGModifier modifier; SetMayaAttrKeyableState(attrPlug, variability, modifier); } -void -UsdMayaReadUtil::SetMayaAttrKeyableState( - MPlug& attrPlug, - const SdfVariability variability, - MDGModifier& modifier) +void UsdMayaReadUtil::SetMayaAttrKeyableState( + MPlug& attrPlug, + const SdfVariability variability, + MDGModifier& modifier) { - modifier.commandToExecute(TfStringPrintf("setAttr -keyable %d %s", - variability == SdfVariabilityVarying ? 1 : 0, - attrPlug.name().asChar()).c_str()); + modifier.commandToExecute(TfStringPrintf( + "setAttr -keyable %d %s", + variability == SdfVariabilityVarying ? 1 : 0, + attrPlug.name().asChar()) + .c_str()); modifier.doIt(); } -bool -UsdMayaReadUtil::ReadMetadataFromPrim( +bool UsdMayaReadUtil::ReadMetadataFromPrim( const TfToken::Set& includeMetadataKeys, - const UsdPrim& prim, - const MObject& mayaObject) + const UsdPrim& prim, + const MObject& mayaObject) { UsdMayaAdaptor adaptor(mayaObject); if (!adaptor) { @@ -795,11 +839,10 @@ UsdMayaReadUtil::ReadMetadataFromPrim( return true; } -bool -UsdMayaReadUtil::ReadAPISchemaAttributesFromPrim( +bool UsdMayaReadUtil::ReadAPISchemaAttributesFromPrim( const TfToken::Set& includeAPINames, - const UsdPrim& prim, - const MObject& mayaObject) + const UsdPrim& prim, + const MObject& mayaObject) { UsdMayaAdaptor adaptor(mayaObject); if (!adaptor) { @@ -810,11 +853,10 @@ UsdMayaReadUtil::ReadAPISchemaAttributesFromPrim( if (includeAPINames.count(schemaName) == 0) { continue; } - if (UsdMayaAdaptor::SchemaAdaptor schemaAdaptor = - adaptor.ApplySchemaByName(schemaName)) { + if (UsdMayaAdaptor::SchemaAdaptor schemaAdaptor = adaptor.ApplySchemaByName(schemaName)) { for (const TfToken& attrName : schemaAdaptor.GetAttributeNames()) { if (UsdAttribute attr = prim.GetAttribute(attrName)) { - VtValue value; + VtValue value; constexpr UsdTimeCode t = UsdTimeCode::EarliestTime(); if (attr.HasAuthoredValue() && attr.Get(&value, t)) { schemaAdaptor.CreateAttribute(attrName).Set(value); @@ -827,13 +869,12 @@ UsdMayaReadUtil::ReadAPISchemaAttributesFromPrim( } /* static */ -size_t -UsdMayaReadUtil::ReadSchemaAttributesFromPrim( - const UsdPrim& prim, - const MObject& mayaObject, - const TfType& schemaType, +size_t UsdMayaReadUtil::ReadSchemaAttributesFromPrim( + const UsdPrim& prim, + const MObject& mayaObject, + const TfType& schemaType, const std::vector& attributeNames, - const UsdTimeCode& usdTime) + const UsdTimeCode& usdTime) { UsdMayaAdaptor adaptor(mayaObject); if (!adaptor) { @@ -841,8 +882,8 @@ UsdMayaReadUtil::ReadSchemaAttributesFromPrim( } size_t count = 0; - if (UsdMayaAdaptor::SchemaAdaptor schemaAdaptor = - adaptor.GetSchemaOrInheritedSchema(schemaType)) { + if (UsdMayaAdaptor::SchemaAdaptor schemaAdaptor + = adaptor.GetSchemaOrInheritedSchema(schemaType)) { for (const TfToken& attrName : attributeNames) { if (UsdAttribute attr = prim.GetAttribute(attrName)) { VtValue value; diff --git a/lib/mayaUsd/fileio/utils/readUtil.h b/lib/mayaUsd/fileio/utils/readUtil.h index a494e649e8..46bae9c217 100644 --- a/lib/mayaUsd/fileio/utils/readUtil.h +++ b/lib/mayaUsd/fileio/utils/readUtil.h @@ -16,18 +16,18 @@ #ifndef PXRUSDMAYA_READUTIL_H #define PXRUSDMAYA_READUTIL_H -#include +#include + +#include +#include +#include #include #include #include #include -#include -#include -#include - -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -37,7 +37,7 @@ struct UsdMayaReadUtil /// \name Helpers for reading USD /// \{ - /// Returns whether the environment setting for reading Float2 types as UV + /// Returns whether the environment setting for reading Float2 types as UV /// sets is set to true MAYAUSD_CORE_PUBLIC static bool ReadFloat2AsUV(); @@ -58,33 +58,33 @@ struct UsdMayaReadUtil /// attribute object. MAYAUSD_CORE_PUBLIC static MObject FindOrCreateMayaAttr( - const SdfValueTypeName& typeName, - const SdfVariability variability, - MFnDependencyNode& depNode, - const std::string& attrName, - const std::string& attrNiceName = std::string()); + const SdfValueTypeName& typeName, + const SdfVariability variability, + MFnDependencyNode& depNode, + const std::string& attrName, + const std::string& attrNiceName = std::string()); /// An overload of FindOrCreateMayaAttr that takes an MDGModifier. /// \note This function will call doIt() on the MDGModifier; thus the /// actions will have been committed when the function returns. MAYAUSD_CORE_PUBLIC static MObject FindOrCreateMayaAttr( - const SdfValueTypeName& typeName, - const SdfVariability variability, - MFnDependencyNode& depNode, - const std::string& attrName, - const std::string& attrNiceName, - MDGModifier& modifier); + const SdfValueTypeName& typeName, + const SdfVariability variability, + MFnDependencyNode& depNode, + const std::string& attrName, + const std::string& attrNiceName, + MDGModifier& modifier); MAYAUSD_CORE_PUBLIC static MObject FindOrCreateMayaAttr( - const TfType& type, - const TfToken& role, - const SdfVariability variability, - MFnDependencyNode& depNode, - const std::string& attrName, - const std::string& attrNiceName, - MDGModifier& modifier); + const TfType& type, + const TfToken& role, + const SdfVariability variability, + MFnDependencyNode& depNode, + const std::string& attrName, + const std::string& attrNiceName, + MDGModifier& modifier); /// Sets a Maya plug using the value on a USD attribute at default time. /// If the variability of the USD attribute doesn't match the keyable state @@ -94,10 +94,8 @@ struct UsdMayaReadUtil /// For plugs with color roles, the value will be converted from a linear /// color value before being set if \p unlinearizeColors is true. MAYAUSD_CORE_PUBLIC - static bool SetMayaAttr( - MPlug& attrPlug, - const UsdAttribute& usdAttr, - const bool unlinearizeColors = true); + static bool + SetMayaAttr(MPlug& attrPlug, const UsdAttribute& usdAttr, const bool unlinearizeColors = true); /// Sets a Maya plug using the given VtValue. The plug keyable state won't /// be affected. @@ -106,10 +104,8 @@ struct UsdMayaReadUtil /// For plugs with color roles, the value will be converted from a linear /// color value before being set if \p unlinearizeColors is true. MAYAUSD_CORE_PUBLIC - static bool SetMayaAttr( - MPlug& attrPlug, - const VtValue& newValue, - const bool unlinearizeColors = true); + static bool + SetMayaAttr(MPlug& attrPlug, const VtValue& newValue, const bool unlinearizeColors = true); /// An overload of SetMayaAttr that takes an MDGModifier. /// \note This function will call doIt() on the MDGModifier; thus the @@ -119,26 +115,24 @@ struct UsdMayaReadUtil /// color value before being set if \p unlinearizeColors is true. MAYAUSD_CORE_PUBLIC static bool SetMayaAttr( - MPlug& attrPlug, - const VtValue& newValue, - MDGModifier& modifier, - const bool unlinearizeColors = true); + MPlug& attrPlug, + const VtValue& newValue, + MDGModifier& modifier, + const bool unlinearizeColors = true); /// Sets the plug's keyable state based on whether the variability is /// varying or uniform. MAYAUSD_CORE_PUBLIC - static void SetMayaAttrKeyableState( - MPlug& attrPlug, - const SdfVariability variability); + static void SetMayaAttrKeyableState(MPlug& attrPlug, const SdfVariability variability); /// An overload of SetMayaAttrKeyableState that takes an MDGModifier. /// \note This function will call doIt() on the MDGModifier; thus the /// actions will have been committed when the function returns. MAYAUSD_CORE_PUBLIC static void SetMayaAttrKeyableState( - MPlug& attrPlug, - const SdfVariability variability, - MDGModifier& modifier); + MPlug& attrPlug, + const SdfVariability variability, + MDGModifier& modifier); /// \} @@ -150,9 +144,9 @@ struct UsdMayaReadUtil /// Returns true if successful (even if there was nothing to import). MAYAUSD_CORE_PUBLIC static bool ReadMetadataFromPrim( - const TfToken::Set& includeMetadataKeys, - const UsdPrim& prim, - const MObject& mayaObject); + const TfToken::Set& includeMetadataKeys, + const UsdPrim& prim, + const MObject& mayaObject); /// Reads the attributes from the non-excluded schemas applied to \p prim, /// and uses adaptors to write them onto attributes of \p mayaObject. @@ -161,9 +155,9 @@ struct UsdMayaReadUtil /// function, then this function won't recognize it. MAYAUSD_CORE_PUBLIC static bool ReadAPISchemaAttributesFromPrim( - const TfToken::Set& includeAPINames, - const UsdPrim& prim, - const MObject& mayaObject); + const TfToken::Set& includeAPINames, + const UsdPrim& prim, + const MObject& mayaObject); /// \} @@ -172,17 +166,13 @@ struct UsdMayaReadUtil template static size_t ReadSchemaAttributesFromPrim( - const UsdPrim& prim, - const MObject& mayaObject, - const std::vector& attributeNames, - const UsdTimeCode& usdTime = UsdTimeCode::Default()) + const UsdPrim& prim, + const MObject& mayaObject, + const std::vector& attributeNames, + const UsdTimeCode& usdTime = UsdTimeCode::Default()) { return ReadSchemaAttributesFromPrim( - prim, - mayaObject, - TfType::Find(), - attributeNames, - usdTime); + prim, mayaObject, TfType::Find(), attributeNames, usdTime); } /// Reads schema attributes specified by \attributeNames for the schema @@ -194,11 +184,11 @@ struct UsdMayaReadUtil /// provided, it will be used to write the values. /// Returns the number of attributes that were read into Maya. static size_t ReadSchemaAttributesFromPrim( - const UsdPrim& prim, - const MObject& mayaObject, - const TfType& schemaType, - const std::vector& attributeNames, - const UsdTimeCode& usdTime = UsdTimeCode::Default()); + const UsdPrim& prim, + const MObject& mayaObject, + const TfType& schemaType, + const std::vector& attributeNames, + const UsdTimeCode& usdTime = UsdTimeCode::Default()); /// \} }; diff --git a/lib/mayaUsd/fileio/utils/roundTripUtil.cpp b/lib/mayaUsd/fileio/utils/roundTripUtil.cpp index 0d358e7fcf..9cfdb469ed 100644 --- a/lib/mayaUsd/fileio/utils/roundTripUtil.cpp +++ b/lib/mayaUsd/fileio/utils/roundTripUtil.cpp @@ -32,23 +32,19 @@ TF_DEFINE_PRIVATE_TOKENS( // We just store everything in a top level dictionary named "Maya". (Maya) - // This annotates data that was exported to maya but should not be - // re-imported into Maya when trying to "roundtrip" data. - (generated) + // This annotates data that was exported to maya but should not be + // re-imported into Maya when trying to "roundtrip" data. + (generated) (clamped) - // This annotates if the attribute used to be a maya array. The index - // of the array is likely encoded in the attribute name though we could - // extend this to store the name and index. - (arrayIndex) -); - + // This annotates if the attribute used to be a maya array. The index + // of the array is likely encoded in the attribute name though we could + // extend this to store the name and index. + (arrayIndex)); template -static -bool -_GetMayaDictValue(const UsdAttribute& attr, const TfToken& key, T* outVal) +static bool _GetMayaDictValue(const UsdAttribute& attr, const TfToken& key, T* outVal) { VtValue data = attr.GetCustomDataByKey(_tokens->Maya); if (data.IsEmpty()) { @@ -56,9 +52,10 @@ _GetMayaDictValue(const UsdAttribute& attr, const TfToken& key, T* outVal) } if (!data.IsHolding()) { - TF_WARN("Expected %s on <%s> to be a dictionary.", - _tokens->Maya.GetText(), - attr.GetPath().GetText()); + TF_WARN( + "Expected %s on <%s> to be a dictionary.", + _tokens->Maya.GetText(), + attr.GetPath().GetText()); return false; } @@ -67,12 +64,12 @@ _GetMayaDictValue(const UsdAttribute& attr, const TfToken& key, T* outVal) if (val.IsHolding()) { *outVal = val.UncheckedGet(); return true; - } - else { - TF_WARN("Unexpected type for %s[%s] on <%s>.", - _tokens->Maya.GetText(), - key.GetText(), - attr.GetPath().GetText()); + } else { + TF_WARN( + "Unexpected type for %s[%s] on <%s>.", + _tokens->Maya.GetText(), + key.GetText(), + attr.GetPath().GetText()); } } @@ -80,12 +77,7 @@ _GetMayaDictValue(const UsdAttribute& attr, const TfToken& key, T* outVal) } template -static -void -_SetMayaDictValue( - const UsdAttribute& attr, - const TfToken& flagName, - const T& val) +static void _SetMayaDictValue(const UsdAttribute& attr, const TfToken& flagName, const T& val) { VtValue data = attr.GetCustomDataByKey(_tokens->Maya); @@ -93,11 +85,11 @@ _SetMayaDictValue( if (!data.IsEmpty()) { if (data.IsHolding()) { newDict = data.UncheckedGet(); - } - else { - TF_WARN("Expected to get %s on <%s> to be a dictionary.", - _tokens->Maya.GetText(), - attr.GetPath().GetText()); + } else { + TF_WARN( + "Expected to get %s on <%s> to be a dictionary.", + _tokens->Maya.GetText(), + attr.GetPath().GetText()); return; } } @@ -107,59 +99,47 @@ _SetMayaDictValue( } /* static */ -bool -UsdMayaRoundTripUtil::IsAttributeUserAuthored(const UsdAttribute& attr) +bool UsdMayaRoundTripUtil::IsAttributeUserAuthored(const UsdAttribute& attr) { return attr.HasAuthoredValue() && !IsAttributeMayaGenerated(attr); } /* static */ -bool -UsdMayaRoundTripUtil::IsAttributeMayaGenerated(const UsdAttribute& attr) +bool UsdMayaRoundTripUtil::IsAttributeMayaGenerated(const UsdAttribute& attr) { bool ret = false; return _GetMayaDictValue(attr, _tokens->generated, &ret) && ret; } /* static */ -void -UsdMayaRoundTripUtil::MarkAttributeAsMayaGenerated(const UsdAttribute& attr) +void UsdMayaRoundTripUtil::MarkAttributeAsMayaGenerated(const UsdAttribute& attr) { _SetMayaDictValue(attr, _tokens->generated, true); } /* static */ -bool -UsdMayaRoundTripUtil::IsPrimvarClamped(const UsdGeomPrimvar& primvar) +bool UsdMayaRoundTripUtil::IsPrimvarClamped(const UsdGeomPrimvar& primvar) { bool ret = false; return _GetMayaDictValue(primvar.GetAttr(), _tokens->clamped, &ret) && ret; } /* static */ -void -UsdMayaRoundTripUtil::MarkPrimvarAsClamped(const UsdGeomPrimvar& primvar) +void UsdMayaRoundTripUtil::MarkPrimvarAsClamped(const UsdGeomPrimvar& primvar) { _SetMayaDictValue(primvar.GetAttr(), _tokens->clamped, true); } /* static */ -bool -UsdMayaRoundTripUtil::GetAttributeArray( - const UsdAttribute& attr, - unsigned int* index) +bool UsdMayaRoundTripUtil::GetAttributeArray(const UsdAttribute& attr, unsigned int* index) { return _GetMayaDictValue(attr, _tokens->arrayIndex, index); } /* static */ -void -UsdMayaRoundTripUtil::MarkAttributeAsArray( - const UsdAttribute& attr, - const unsigned int index) +void UsdMayaRoundTripUtil::MarkAttributeAsArray(const UsdAttribute& attr, const unsigned int index) { _SetMayaDictValue(attr, _tokens->arrayIndex, index); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/utils/roundTripUtil.h b/lib/mayaUsd/fileio/utils/roundTripUtil.h index 4aff8cf931..3ae7e012c8 100644 --- a/lib/mayaUsd/fileio/utils/roundTripUtil.h +++ b/lib/mayaUsd/fileio/utils/roundTripUtil.h @@ -16,12 +16,12 @@ #ifndef PXRUSDMAYA_ROUND_TRIP_UTIL_H #define PXRUSDMAYA_ROUND_TRIP_UTIL_H +#include + #include #include #include -#include - PXR_NAMESPACE_OPEN_SCOPE /// This holds some utility functions for dealing with data from Maya to Usd @@ -57,18 +57,12 @@ struct UsdMayaRoundTripUtil /// attributes inside the array. Returns true if this was marked as an /// array attribute and will set \p index. Returns false otherwise. MAYAUSD_CORE_PUBLIC - static bool GetAttributeArray( - const UsdAttribute& attr, - unsigned int* index); + static bool GetAttributeArray(const UsdAttribute& attr, unsigned int* index); MAYAUSD_CORE_PUBLIC - static void MarkAttributeAsArray( - const UsdAttribute& attr, - const unsigned int index); + static void MarkAttributeAsArray(const UsdAttribute& attr, const unsigned int index); }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/utils/shadingUtil.cpp b/lib/mayaUsd/fileio/utils/shadingUtil.cpp index 92f52b7150..0c5ce34094 100644 --- a/lib/mayaUsd/fileio/utils/shadingUtil.cpp +++ b/lib/mayaUsd/fileio/utils/shadingUtil.cpp @@ -15,9 +15,9 @@ // #include "shadingUtil.h" -#include #include #include +#include #include #include #include @@ -29,23 +29,18 @@ #include - PXR_NAMESPACE_USING_DIRECTIVE - std::string -UsdMayaShadingUtil::GetStandardAttrName( - const MPlug& attrPlug, - bool allowMultiElementArrays) +UsdMayaShadingUtil::GetStandardAttrName(const MPlug& attrPlug, bool allowMultiElementArrays) { if (!attrPlug.isElement()) { - const MString mayaPlugName = - attrPlug.partialName(false, false, false, false, false, true); + const MString mayaPlugName = attrPlug.partialName(false, false, false, false, false, true); return mayaPlugName.asChar(); } - const MString mayaPlugName = - attrPlug.array().partialName(false, false, false, false, false, true); + const MString mayaPlugName + = attrPlug.array().partialName(false, false, false, false, false, true); const unsigned int logicalIndex = attrPlug.logicalIndex(); if (allowMultiElementArrays) { @@ -57,35 +52,31 @@ UsdMayaShadingUtil::GetStandardAttrName( return std::string(); } -UsdShadeInput -UsdMayaShadingUtil::CreateMaterialInputAndConnectShader( - UsdShadeMaterial& material, - const TfToken& materialInputName, - const SdfValueTypeName& inputTypeName, - UsdShadeShader& shader, - const TfToken& shaderInputName) +UsdShadeInput UsdMayaShadingUtil::CreateMaterialInputAndConnectShader( + UsdShadeMaterial& material, + const TfToken& materialInputName, + const SdfValueTypeName& inputTypeName, + UsdShadeShader& shader, + const TfToken& shaderInputName) { if (!material || !shader) { return UsdShadeInput(); } - UsdShadeInput materialInput = - material.CreateInput(materialInputName, inputTypeName); + UsdShadeInput materialInput = material.CreateInput(materialInputName, inputTypeName); - UsdShadeInput shaderInput = - shader.CreateInput(shaderInputName, inputTypeName); + UsdShadeInput shaderInput = shader.CreateInput(shaderInputName, inputTypeName); shaderInput.ConnectToSource(materialInput); return materialInput; } -UsdShadeOutput -UsdMayaShadingUtil::CreateShaderOutputAndConnectMaterial( - UsdShadeShader& shader, - UsdShadeMaterial& material, - const TfToken& terminalName, - const TfToken& renderContext) +UsdShadeOutput UsdMayaShadingUtil::CreateShaderOutputAndConnectMaterial( + UsdShadeShader& shader, + UsdShadeMaterial& material, + const TfToken& terminalName, + const TfToken& renderContext) { if (!shader || !material) { return UsdShadeOutput(); @@ -102,8 +93,7 @@ UsdMayaShadingUtil::CreateShaderOutputAndConnectMaterial( return UsdShadeOutput(); } - UsdShadeOutput shaderOutput = - shader.CreateOutput(terminalName, materialOutput.GetTypeName()); + UsdShadeOutput shaderOutput = shader.CreateOutput(terminalName, materialOutput.GetTypeName()); materialOutput.ConnectToSource(shaderOutput); diff --git a/lib/mayaUsd/fileio/utils/shadingUtil.h b/lib/mayaUsd/fileio/utils/shadingUtil.h index ffe78d5789..fde787c743 100644 --- a/lib/mayaUsd/fileio/utils/shadingUtil.h +++ b/lib/mayaUsd/fileio/utils/shadingUtil.h @@ -20,8 +20,8 @@ #include -#include #include +#include #include #include #include @@ -32,12 +32,9 @@ #include - PXR_NAMESPACE_OPEN_SCOPE - -namespace UsdMayaShadingUtil -{ +namespace UsdMayaShadingUtil { /// Get a "standard" USD attribute name for \p attrPlug. /// /// If \p attrPlug is not an element in a Maya array attribute, then its name @@ -48,9 +45,7 @@ namespace UsdMayaShadingUtil /// \p allowMultiElementArrays is false, this will return if it's /// the 0-th logical element. Otherwise it will return an empty string. MAYAUSD_CORE_PUBLIC -std::string GetStandardAttrName( - const MPlug& attrPlug, - bool allowMultiElementArrays); +std::string GetStandardAttrName(const MPlug& attrPlug, bool allowMultiElementArrays); /// Create an input on the given material and shader and create a connection /// between them. @@ -65,11 +60,11 @@ std::string GetStandardAttrName( /// otherwise. MAYAUSD_CORE_PUBLIC UsdShadeInput CreateMaterialInputAndConnectShader( - UsdShadeMaterial& material, - const TfToken& materialInputName, - const SdfValueTypeName& inputTypeName, - UsdShadeShader& shader, - const TfToken& shaderInputName); + UsdShadeMaterial& material, + const TfToken& materialInputName, + const SdfValueTypeName& inputTypeName, + UsdShadeShader& shader, + const TfToken& shaderInputName); /// Create an output on the given shader and material and create a connection /// between them. @@ -83,16 +78,13 @@ UsdShadeInput CreateMaterialInputAndConnectShader( /// otherwise. MAYAUSD_CORE_PUBLIC UsdShadeOutput CreateShaderOutputAndConnectMaterial( - UsdShadeShader& shader, - UsdShadeMaterial& material, - const TfToken& terminalName, - const TfToken& renderContext); - + UsdShadeShader& shader, + UsdShadeMaterial& material, + const TfToken& terminalName, + const TfToken& renderContext); } // namespace UsdMayaShadingUtil - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/utils/userTaggedAttribute.cpp b/lib/mayaUsd/fileio/utils/userTaggedAttribute.cpp index 07ff6f62a5..0a95bf68f2 100644 --- a/lib/mayaUsd/fileio/utils/userTaggedAttribute.cpp +++ b/lib/mayaUsd/fileio/utils/userTaggedAttribute.cpp @@ -15,100 +15,71 @@ // #include "userTaggedAttribute.h" -#include -#include -#include - -#include -#include -#include -#include -#include +#include -#include #include #include #include #include +#include #include -#include +#include +#include +#include +#include +#include + +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PUBLIC_TOKENS( - UsdMayaUserTaggedAttributeTokens, - PXRUSDMAYA_ATTR_TOKENS); +TF_DEFINE_PUBLIC_TOKENS(UsdMayaUserTaggedAttributeTokens, PXRUSDMAYA_ATTR_TOKENS); TF_DEFINE_PRIVATE_TOKENS( _tokens, - (USD_UserExportedAttributesJson) - (usdAttrName) - (usdAttrType) - (translateMayaDoubleToUsdSinglePrecision) - ((UserPropertiesNamespace, "userProperties:")) -); - + (USD_UserExportedAttributesJson)(usdAttrName)(usdAttrType)( + translateMayaDoubleToUsdSinglePrecision)((UserPropertiesNamespace, "userProperties:"))); UsdMayaUserTaggedAttribute::UsdMayaUserTaggedAttribute( - const MPlug& plug, - const std::string& name, - const TfToken& type, - const TfToken& interpolation, - const bool translateMayaDoubleToUsdSinglePrecision) - : _plug(plug), - _name(name), - _type(type), - _interpolation(interpolation), - _translateMayaDoubleToUsdSinglePrecision( - translateMayaDoubleToUsdSinglePrecision) + const MPlug& plug, + const std::string& name, + const TfToken& type, + const TfToken& interpolation, + const bool translateMayaDoubleToUsdSinglePrecision) + : _plug(plug) + , _name(name) + , _type(type) + , _interpolation(interpolation) + , _translateMayaDoubleToUsdSinglePrecision(translateMayaDoubleToUsdSinglePrecision) { } -MPlug -UsdMayaUserTaggedAttribute::GetMayaPlug() const -{ - return _plug; -} +MPlug UsdMayaUserTaggedAttribute::GetMayaPlug() const { return _plug; } -std::string -UsdMayaUserTaggedAttribute::GetMayaName() const +std::string UsdMayaUserTaggedAttribute::GetMayaName() const { MString name = _plug.partialName(); return std::string(name.asChar()); } -std::string -UsdMayaUserTaggedAttribute::GetUsdName() const -{ - return _name; -} +std::string UsdMayaUserTaggedAttribute::GetUsdName() const { return _name; } -TfToken -UsdMayaUserTaggedAttribute::GetUsdType() const -{ - return _type; -} +TfToken UsdMayaUserTaggedAttribute::GetUsdType() const { return _type; } -TfToken -UsdMayaUserTaggedAttribute::GetUsdInterpolation() const -{ - return _interpolation; -} +TfToken UsdMayaUserTaggedAttribute::GetUsdInterpolation() const { return _interpolation; } -bool -UsdMayaUserTaggedAttribute::GetTranslateMayaDoubleToUsdSinglePrecision() const +bool UsdMayaUserTaggedAttribute::GetTranslateMayaDoubleToUsdSinglePrecision() const { return _translateMayaDoubleToUsdSinglePrecision; } -static -std::string -_GetExportAttributeMetadata( - const JsObject& attrMetadata, - const TfToken& keyToken) +static std::string +_GetExportAttributeMetadata(const JsObject& attrMetadata, const TfToken& keyToken) { - std::string value; + std::string value; JsObject::const_iterator attrMetadataIter = attrMetadata.find(keyToken); if (attrMetadataIter != attrMetadata.end()) { value = attrMetadataIter->second.GetString(); @@ -117,14 +88,12 @@ _GetExportAttributeMetadata( return value; } -static -bool -_GetExportAttributeMetadata( - const JsObject& attrMetadata, - const TfToken& keyToken, - const bool defaultValue) +static bool _GetExportAttributeMetadata( + const JsObject& attrMetadata, + const TfToken& keyToken, + const bool defaultValue) { - bool value = defaultValue; + bool value = defaultValue; JsObject::const_iterator attrMetadataIter = attrMetadata.find(keyToken); if (attrMetadataIter != attrMetadata.end()) { value = attrMetadataIter->second.GetBool(); @@ -135,41 +104,38 @@ _GetExportAttributeMetadata( /* static */ std::vector -UsdMayaUserTaggedAttribute::GetUserTaggedAttributesForNode( - const MObject& mayaNode) +UsdMayaUserTaggedAttribute::GetUserTaggedAttributesForNode(const MObject& mayaNode) { std::vector result; - MStatus status; + MStatus status; const MFnDependencyNode depNodeFn(mayaNode, &status); if (status != MS::kSuccess) { return result; } - const MPlug exportedAttrsJsonPlug = - depNodeFn.findPlug( - _tokens->USD_UserExportedAttributesJson.GetText(), - true, - &status); + const MPlug exportedAttrsJsonPlug + = depNodeFn.findPlug(_tokens->USD_UserExportedAttributesJson.GetText(), true, &status); if (status != MS::kSuccess || exportedAttrsJsonPlug.isNull()) { // No attributes specified for export on this node. return result; } - const std::string exportedAttrsJsonString( - exportedAttrsJsonPlug.asString().asChar()); + const std::string exportedAttrsJsonString(exportedAttrsJsonPlug.asString().asChar()); if (exportedAttrsJsonString.empty()) { return result; } - JsParseError jsError; + JsParseError jsError; const JsValue jsValue = JsParseString(exportedAttrsJsonString, &jsError); if (!jsValue) { TF_RUNTIME_ERROR( "Failed to parse USD exported attributes JSON on node '%s' " "at line %d, column %d: %s", UsdMayaUtil::GetMayaNodeName(mayaNode).c_str(), - jsError.line, jsError.column, jsError.reason.c_str()); + jsError.line, + jsError.column, + jsError.reason.c_str()); return result; } @@ -177,12 +143,11 @@ UsdMayaUserTaggedAttribute::GetUserTaggedAttributesForNode( // and issue warnings for the subsequent definitions. JsObject is really // just a std::map, so we'll be considering attributes in sorted order. std::set processedAttributeNames; - const JsObject& exportedAttrs = jsValue.GetJsObject(); + const JsObject& exportedAttrs = jsValue.GetJsObject(); for (const auto& exportedAttr : exportedAttrs) { const std::string mayaAttrName = exportedAttr.first; - const MPlug attrPlug = - depNodeFn.findPlug(mayaAttrName.c_str(), true, &status); + const MPlug attrPlug = depNodeFn.findPlug(mayaAttrName.c_str(), true, &status); if (status != MS::kSuccess || attrPlug.isNull()) { TF_RUNTIME_ERROR( "Could not find attribute '%s' for USD export on node '%s'", @@ -196,32 +161,28 @@ UsdMayaUserTaggedAttribute::GetUserTaggedAttributesForNode( // Check if this is a particular type of attribute (e.g. primvar or // usdRi attribute). If we don't recognize the type specified, we'll // fall back to a regular USD attribute. - const TfToken usdAttrType( - _GetExportAttributeMetadata(attrMetadata, _tokens->usdAttrType)); + const TfToken usdAttrType(_GetExportAttributeMetadata(attrMetadata, _tokens->usdAttrType)); // Check whether an interpolation type was specified. This is only // relevant for primvars. const TfToken interpolation( - _GetExportAttributeMetadata(attrMetadata, - UsdGeomTokens->interpolation)); + _GetExportAttributeMetadata(attrMetadata, UsdGeomTokens->interpolation)); // Check whether it was specified that the double precision Maya // attribute type should be mapped to a single precision USD type. // If it wasn't specified, use the fallback value. - const bool translateMayaDoubleToUsdSinglePrecision( - _GetExportAttributeMetadata( - attrMetadata, - _tokens->translateMayaDoubleToUsdSinglePrecision, - GetFallbackTranslateMayaDoubleToUsdSinglePrecision())); + const bool translateMayaDoubleToUsdSinglePrecision(_GetExportAttributeMetadata( + attrMetadata, + _tokens->translateMayaDoubleToUsdSinglePrecision, + GetFallbackTranslateMayaDoubleToUsdSinglePrecision())); // Check whether the USD attribute name should be different than the // Maya attribute name. - std::string usdAttrName = - _GetExportAttributeMetadata(attrMetadata, _tokens->usdAttrName); + std::string usdAttrName = _GetExportAttributeMetadata(attrMetadata, _tokens->usdAttrName); if (usdAttrName.empty()) { const auto& tokens = UsdMayaUserTaggedAttributeTokens; - if (usdAttrType == tokens->USDAttrTypePrimvar || - usdAttrType == tokens->USDAttrTypeUsdRi) { + if (usdAttrType == tokens->USDAttrTypePrimvar + || usdAttrType == tokens->USDAttrTypeUsdRi) { // Primvars and UsdRi attributes will be given a type-specific // namespace, so just use the Maya attribute name. usdAttrName = mayaAttrName; @@ -229,8 +190,7 @@ UsdMayaUserTaggedAttribute::GetUserTaggedAttributesForNode( // For regular USD attributes, when no name was specified we // prepend the userProperties namespace to the Maya attribute // name to get the USD attribute name. - usdAttrName = _tokens->UserPropertiesNamespace.GetString() + - mayaAttrName; + usdAttrName = _tokens->UserPropertiesNamespace.GetString() + mayaAttrName; } } @@ -244,15 +204,15 @@ UsdMayaUserTaggedAttribute::GetUserTaggedAttributesForNode( continue; } - result.emplace_back(attrPlug, - usdAttrName, - usdAttrType, - interpolation, - translateMayaDoubleToUsdSinglePrecision); + result.emplace_back( + attrPlug, + usdAttrName, + usdAttrType, + interpolation, + translateMayaDoubleToUsdSinglePrecision); } return result; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/utils/userTaggedAttribute.h b/lib/mayaUsd/fileio/utils/userTaggedAttribute.h index e6c8f2fbd7..2dd7773858 100644 --- a/lib/mayaUsd/fileio/utils/userTaggedAttribute.h +++ b/lib/mayaUsd/fileio/utils/userTaggedAttribute.h @@ -16,42 +16,39 @@ #ifndef PXRUSDMAYA_USER_TAGGED_ATTRIBUTE_H #define PXRUSDMAYA_USER_TAGGED_ATTRIBUTE_H -#include -#include -#include - -#include -#include +#include -#include #include #include #include +#include -#include +#include +#include + +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -#define PXRUSDMAYA_ATTR_TOKENS \ - ((USDAttrTypePrimvar, "primvar")) \ - ((USDAttrTypeUsdRi, "usdRi")) +#define PXRUSDMAYA_ATTR_TOKENS ((USDAttrTypePrimvar, "primvar"))((USDAttrTypeUsdRi, "usdRi")) TF_DECLARE_PUBLIC_TOKENS( UsdMayaUserTaggedAttributeTokens, MAYAUSD_CORE_PUBLIC, PXRUSDMAYA_ATTR_TOKENS); - /// \brief Represents a single attribute tagged for translation between Maya /// and USD, and describes how it will be exported from/imported into Maya. class UsdMayaUserTaggedAttribute { private: - MPlug _plug; + MPlug _plug; const std::string _name; - const TfToken _type; - const TfToken _interpolation; - const bool _translateMayaDoubleToUsdSinglePrecision; + const TfToken _type; + const TfToken _interpolation; + const bool _translateMayaDoubleToUsdSinglePrecision; public: /// \brief Gets the fallback value for whether attribute types should be @@ -60,23 +57,21 @@ class UsdMayaUserTaggedAttribute /// By default, the fallback value for this property is false so that /// double precision data is preserved in the translation back and forth /// between Maya and USD. - static bool GetFallbackTranslateMayaDoubleToUsdSinglePrecision() { - return false; - }; + static bool GetFallbackTranslateMayaDoubleToUsdSinglePrecision() { return false; }; MAYAUSD_CORE_PUBLIC UsdMayaUserTaggedAttribute( - const MPlug& plug, - const std::string& name, - const TfToken& type, - const TfToken& interpolation, - const bool translateMayaDoubleToUsdSinglePrecision = - GetFallbackTranslateMayaDoubleToUsdSinglePrecision()); + const MPlug& plug, + const std::string& name, + const TfToken& type, + const TfToken& interpolation, + const bool translateMayaDoubleToUsdSinglePrecision + = GetFallbackTranslateMayaDoubleToUsdSinglePrecision()); /// \brief Gets all of the exported attributes for the given node. MAYAUSD_CORE_PUBLIC static std::vector - GetUserTaggedAttributesForNode(const MObject& mayaNode); + GetUserTaggedAttributesForNode(const MObject& mayaNode); /// \brief Gets the plug for the Maya attribute to be exported. MAYAUSD_CORE_PUBLIC @@ -119,8 +114,6 @@ class UsdMayaUserTaggedAttribute bool GetTranslateMayaDoubleToUsdSinglePrecision() const; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/fileio/utils/writeUtil.cpp b/lib/mayaUsd/fileio/utils/writeUtil.cpp index 71ebc9bdc9..88169c2bbe 100644 --- a/lib/mayaUsd/fileio/utils/writeUtil.cpp +++ b/lib/mayaUsd/fileio/utils/writeUtil.cpp @@ -15,8 +15,31 @@ // #include "writeUtil.h" -#include -#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -43,31 +66,8 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include +#include +#include using namespace MAYAUSD_NS_DEF; @@ -87,13 +87,11 @@ TF_DEFINE_ENV_SETTING( "Translates the map1 UV set in Maya to the primary UV set in USD. " "When disabled, UV set names are translated directly (map1 in Maya becomes map1 in USD)."); -static -bool -_GetMayaAttributeNumericTypedAndUnitDataTypes( - const MPlug& attrPlug, - MFnNumericData::Type& numericDataType, - MFnData::Type& typedDataType, - MFnUnitAttribute::Type& unitDataType) +static bool _GetMayaAttributeNumericTypedAndUnitDataTypes( + const MPlug& attrPlug, + MFnNumericData::Type& numericDataType, + MFnData::Type& typedDataType, + MFnUnitAttribute::Type& unitDataType) { numericDataType = MFnNumericData::kInvalid; typedDataType = MFnData::kInvalid; @@ -127,30 +125,25 @@ _GetMayaAttributeNumericTypedAndUnitDataTypes( return true; } -bool -UsdMayaWriteUtil::WriteUVAsFloat2() +bool UsdMayaWriteUtil::WriteUVAsFloat2() { - static const bool writeUVAsFloat2 = - TfGetEnvSetting(PIXMAYA_WRITE_UV_AS_FLOAT2); + static const bool writeUVAsFloat2 = TfGetEnvSetting(PIXMAYA_WRITE_UV_AS_FLOAT2); return writeUVAsFloat2; } -bool -UsdMayaWriteUtil::WriteMap1AsST() +bool UsdMayaWriteUtil::WriteMap1AsST() { - static const bool writeMap1AsST = - TfGetEnvSetting(MAYAUSD_EXPORT_MAP1_AS_PRIMARY_UV_SET); + static const bool writeMap1AsST = TfGetEnvSetting(MAYAUSD_EXPORT_MAP1_AS_PRIMARY_UV_SET); return writeMap1AsST; } /* static */ -UsdAttribute -UsdMayaWriteUtil::GetOrCreateUsdAttr( - const MPlug& attrPlug, - const UsdPrim& usdPrim, - const std::string& attrName, - const bool custom, - const bool translateMayaDoubleToUsdSinglePrecision) +UsdAttribute UsdMayaWriteUtil::GetOrCreateUsdAttr( + const MPlug& attrPlug, + const UsdPrim& usdPrim, + const std::string& attrName, + const bool custom, + const bool translateMayaDoubleToUsdSinglePrecision) { UsdAttribute usdAttr; @@ -163,9 +156,9 @@ UsdMayaWriteUtil::GetOrCreateUsdAttr( TfToken usdAttrNameToken(attrName); if (usdAttrNameToken.IsEmpty()) { TF_RUNTIME_ERROR( - "Invalid USD attribute name '%s' for Maya plug '%s'", - attrName.c_str(), - attrPlug.name().asChar()); + "Invalid USD attribute name '%s' for Maya plug '%s'", + attrName.c_str(), + attrPlug.name().asChar()); return usdAttr; } @@ -175,8 +168,8 @@ UsdMayaWriteUtil::GetOrCreateUsdAttr( return usdAttr; } - const SdfValueTypeName& typeName = - Converter::getUsdTypeName(attrPlug, translateMayaDoubleToUsdSinglePrecision); + const SdfValueTypeName& typeName + = Converter::getUsdTypeName(attrPlug, translateMayaDoubleToUsdSinglePrecision); if (typeName) { usdAttr = usdPrim.CreateAttribute(usdAttrNameToken, typeName, custom); } @@ -186,12 +179,12 @@ UsdMayaWriteUtil::GetOrCreateUsdAttr( /* static */ UsdGeomPrimvar UsdMayaWriteUtil::GetOrCreatePrimvar( - const MPlug& attrPlug, - UsdGeomImageable& imageable, - const std::string& primvarName, - const TfToken& interpolation, - const int elementSize, - const bool translateMayaDoubleToUsdSinglePrecision) + const MPlug& attrPlug, + UsdGeomImageable& imageable, + const std::string& primvarName, + const TfToken& interpolation, + const int elementSize, + const bool translateMayaDoubleToUsdSinglePrecision) { UsdGeomPrimvar primvar; @@ -204,9 +197,9 @@ UsdGeomPrimvar UsdMayaWriteUtil::GetOrCreatePrimvar( TfToken primvarNameToken(primvarName); if (primvarNameToken.IsEmpty()) { TF_RUNTIME_ERROR( - "Invalid primvar name '%s' for Maya plug '%s'", - primvarName.c_str(), - attrPlug.name().asChar()); + "Invalid primvar name '%s' for Maya plug '%s'", + primvarName.c_str(), + attrPlug.name().asChar()); return primvar; } @@ -216,13 +209,10 @@ UsdGeomPrimvar UsdMayaWriteUtil::GetOrCreatePrimvar( return primvar; } - const SdfValueTypeName& typeName = - Converter::getUsdTypeName(attrPlug, translateMayaDoubleToUsdSinglePrecision); + const SdfValueTypeName& typeName + = Converter::getUsdTypeName(attrPlug, translateMayaDoubleToUsdSinglePrecision); if (typeName) { - primvar = imageable.CreatePrimvar(primvarNameToken, - typeName, - interpolation, - elementSize); + primvar = imageable.CreatePrimvar(primvarNameToken, typeName, interpolation, elementSize); } return primvar; @@ -230,11 +220,11 @@ UsdGeomPrimvar UsdMayaWriteUtil::GetOrCreatePrimvar( /* static */ UsdAttribute UsdMayaWriteUtil::GetOrCreateUsdRiAttribute( - const MPlug& attrPlug, - const UsdPrim& usdPrim, - const std::string& attrName, - const std::string& nameSpace, - const bool translateMayaDoubleToUsdSinglePrecision) + const MPlug& attrPlug, + const UsdPrim& usdPrim, + const std::string& attrName, + const std::string& nameSpace, + const bool translateMayaDoubleToUsdSinglePrecision) { UsdAttribute usdAttr; @@ -247,9 +237,9 @@ UsdAttribute UsdMayaWriteUtil::GetOrCreateUsdRiAttribute( TfToken riAttrNameToken(attrName); if (riAttrNameToken.IsEmpty()) { TF_RUNTIME_ERROR( - "Invalid UsdRi attribute name '%s' for Maya plug '%s'", - attrName.c_str(), - attrPlug.name().asChar()); + "Invalid UsdRi attribute name '%s' for Maya plug '%s'", + attrName.c_str(), + attrPlug.name().asChar()); return usdAttr; } @@ -259,7 +249,8 @@ UsdAttribute UsdMayaWriteUtil::GetOrCreateUsdRiAttribute( // XXX: There isn't currently API for looking for a specific UsdRi attribute // by name, so we have to get them all and then see if one matches. const std::vector& riAttrs = riStatements.GetRiAttributes(nameSpace); - TF_FOR_ALL(iter, riAttrs) { + TF_FOR_ALL(iter, riAttrs) + { if (iter->GetBaseName() == riAttrNameToken) { // Re-get the attribute from the prim so we can return it as a // UsdAttribute rather than a UsdProperty. @@ -267,14 +258,11 @@ UsdAttribute UsdMayaWriteUtil::GetOrCreateUsdRiAttribute( } } - const SdfValueTypeName& typeName = - Converter::getUsdTypeName(attrPlug, translateMayaDoubleToUsdSinglePrecision); + const SdfValueTypeName& typeName + = Converter::getUsdTypeName(attrPlug, translateMayaDoubleToUsdSinglePrecision); if (typeName) { - riStatements = UsdMayaTranslatorUtil::GetAPISchemaForAuthoring< - UsdRiStatementsAPI>(usdPrim); - usdAttr = riStatements.CreateRiAttribute(riAttrNameToken, - typeName.GetType(), - nameSpace); + riStatements = UsdMayaTranslatorUtil::GetAPISchemaForAuthoring(usdPrim); + usdAttr = riStatements.CreateRiAttribute(riAttrNameToken, typeName.GetType(), nameSpace); } return usdAttr; @@ -282,34 +270,29 @@ UsdAttribute UsdMayaWriteUtil::GetOrCreateUsdRiAttribute( /// Converts a vec from display to linear color if its role is color. template -static -VtValue -_ConvertVec( - const T& val, - const TfToken& role, - const bool linearizeColors) { +static VtValue _ConvertVec(const T& val, const TfToken& role, const bool linearizeColors) +{ return VtValue( - ((role == SdfValueRoleNames->Color) && linearizeColors) ? - UsdMayaColorSpace::ConvertMayaToLinear(val) : - val); + ((role == SdfValueRoleNames->Color) && linearizeColors) + ? UsdMayaColorSpace::ConvertMayaToLinear(val) + : val); } -VtValue -UsdMayaWriteUtil::GetVtValue( - const MPlug& attrPlug, - const SdfValueTypeName& typeName, - const bool linearizeColors) +VtValue UsdMayaWriteUtil::GetVtValue( + const MPlug& attrPlug, + const SdfValueTypeName& typeName, + const bool linearizeColors) { - const TfType type = typeName.GetType(); - const TfToken role = typeName.GetRole();; + const TfType type = typeName.GetType(); + const TfToken role = typeName.GetRole(); + ; return GetVtValue(attrPlug, type, role, linearizeColors); } -VtValue -UsdMayaWriteUtil::GetVtValue( - const MPlug& attrPlug, - const TfType& type, - const TfToken& role, - const bool linearizeColors) +VtValue UsdMayaWriteUtil::GetVtValue( + const MPlug& attrPlug, + const TfType& type, + const TfToken& role, + const bool linearizeColors) { // We perform a similar set of type-infererence acrobatics here as we do // in Converter::getUsdTypeName(). See the comments there for more detail on a @@ -321,14 +304,12 @@ UsdMayaWriteUtil::GetVtValue( return VtValue(attrPlug.asInt()); } - MFnNumericData::Type numericDataType; - MFnData::Type typedDataType; + MFnNumericData::Type numericDataType; + MFnData::Type typedDataType; MFnUnitAttribute::Type unitDataType; - _GetMayaAttributeNumericTypedAndUnitDataTypes(attrPlug, - numericDataType, - typedDataType, - unitDataType); + _GetMayaAttributeNumericTypedAndUnitDataTypes( + attrPlug, numericDataType, typedDataType, unitDataType); if (attrObj.hasFn(MFn::kMatrixAttribute)) { typedDataType = MFnData::kMatrix; @@ -339,346 +320,318 @@ UsdMayaWriteUtil::GetVtValue( // We do care about colors and points because those can be specially-marked // in Maya. switch (typedDataType) { - case MFnData::kString: { - MFnStringData stringDataFn(attrPlug.asMObject()); - const std::string usdVal(stringDataFn.string().asChar()); - if (type.IsA()) { - return VtValue(SdfAssetPath(usdVal)); - } - else if (type.IsA()) { - return VtValue(usdVal); - } - else if (type.IsA()) { - return VtValue(TfToken(usdVal)); - } - break; + case MFnData::kString: { + MFnStringData stringDataFn(attrPlug.asMObject()); + const std::string usdVal(stringDataFn.string().asChar()); + if (type.IsA()) { + return VtValue(SdfAssetPath(usdVal)); + } else if (type.IsA()) { + return VtValue(usdVal); + } else if (type.IsA()) { + return VtValue(TfToken(usdVal)); } - case MFnData::kMatrix: { - if (type.IsA()) { - MFnMatrixData matrixDataFn(attrPlug.asMObject()); - const GfMatrix4d usdVal(matrixDataFn.matrix().matrix); - return VtValue(usdVal); - } - break; + break; + } + case MFnData::kMatrix: { + if (type.IsA()) { + MFnMatrixData matrixDataFn(attrPlug.asMObject()); + const GfMatrix4d usdVal(matrixDataFn.matrix().matrix); + return VtValue(usdVal); } - case MFnData::kStringArray: { - if (type.IsA()) { - MFnStringArrayData stringArrayDataFn(attrPlug.asMObject()); - VtStringArray usdVal(stringArrayDataFn.length()); - for (unsigned int i = 0; i < stringArrayDataFn.length(); ++i) { - usdVal[i] = std::string(stringArrayDataFn[i].asChar()); - } - return VtValue(usdVal); + break; + } + case MFnData::kStringArray: { + if (type.IsA()) { + MFnStringArrayData stringArrayDataFn(attrPlug.asMObject()); + VtStringArray usdVal(stringArrayDataFn.length()); + for (unsigned int i = 0; i < stringArrayDataFn.length(); ++i) { + usdVal[i] = std::string(stringArrayDataFn[i].asChar()); } - else if (type.IsA()) { - MFnStringArrayData stringArrayDataFn(attrPlug.asMObject()); - VtTokenArray usdVal(stringArrayDataFn.length()); - for (unsigned int i = 0; i < stringArrayDataFn.length(); ++i) { - usdVal[i] = TfToken(stringArrayDataFn[i].asChar()); - } - return VtValue(usdVal); + return VtValue(usdVal); + } else if (type.IsA()) { + MFnStringArrayData stringArrayDataFn(attrPlug.asMObject()); + VtTokenArray usdVal(stringArrayDataFn.length()); + for (unsigned int i = 0; i < stringArrayDataFn.length(); ++i) { + usdVal[i] = TfToken(stringArrayDataFn[i].asChar()); } - else if (type.IsA()) { - MFnStringArrayData stringArrayDataFn(attrPlug.asMObject()); - std::vector prepended(stringArrayDataFn.length()); - for (unsigned int i = 0; i < stringArrayDataFn.length(); ++i) { - prepended[i] = std::string(stringArrayDataFn[i].asChar()); - } - SdfStringListOp listOp; - listOp.SetPrependedItems(prepended); - return VtValue(listOp); + return VtValue(usdVal); + } else if (type.IsA()) { + MFnStringArrayData stringArrayDataFn(attrPlug.asMObject()); + std::vector prepended(stringArrayDataFn.length()); + for (unsigned int i = 0; i < stringArrayDataFn.length(); ++i) { + prepended[i] = std::string(stringArrayDataFn[i].asChar()); } - else if (type.IsA()) { - MFnStringArrayData stringArrayDataFn(attrPlug.asMObject()); - TfTokenVector prepended(stringArrayDataFn.length()); - for (unsigned int i = 0; i < stringArrayDataFn.length(); ++i) { - prepended[i] = TfToken(stringArrayDataFn[i].asChar()); - } - SdfTokenListOp listOp; - listOp.SetPrependedItems(prepended); - return VtValue(listOp); + SdfStringListOp listOp; + listOp.SetPrependedItems(prepended); + return VtValue(listOp); + } else if (type.IsA()) { + MFnStringArrayData stringArrayDataFn(attrPlug.asMObject()); + TfTokenVector prepended(stringArrayDataFn.length()); + for (unsigned int i = 0; i < stringArrayDataFn.length(); ++i) { + prepended[i] = TfToken(stringArrayDataFn[i].asChar()); } - break; + SdfTokenListOp listOp; + listOp.SetPrependedItems(prepended); + return VtValue(listOp); } - case MFnData::kDoubleArray: { - MFnDoubleArrayData doubleArrayDataFn(attrPlug.asMObject()); - if (type.IsA()) { - VtFloatArray usdVal(doubleArrayDataFn.length()); - for (unsigned int i = 0; i < doubleArrayDataFn.length(); ++i) { - usdVal[i] = (float)doubleArrayDataFn[i]; - } - return VtValue(usdVal); - } else if (type.IsA()) { - VtDoubleArray usdVal(doubleArrayDataFn.length()); - for (unsigned int i = 0; i < doubleArrayDataFn.length(); ++i) { - usdVal[i] = doubleArrayDataFn[i]; - } - return VtValue(usdVal); + break; + } + case MFnData::kDoubleArray: { + MFnDoubleArrayData doubleArrayDataFn(attrPlug.asMObject()); + if (type.IsA()) { + VtFloatArray usdVal(doubleArrayDataFn.length()); + for (unsigned int i = 0; i < doubleArrayDataFn.length(); ++i) { + usdVal[i] = (float)doubleArrayDataFn[i]; } - break; - } - case MFnData::kFloatArray: { - if (type.IsA()) { - MFnFloatArrayData floatArrayDataFn(attrPlug.asMObject()); - VtFloatArray usdVal(floatArrayDataFn.length()); - for (unsigned int i = 0; i < floatArrayDataFn.length(); ++i) { - usdVal[i] = floatArrayDataFn[i]; - } - return VtValue(usdVal); + return VtValue(usdVal); + } else if (type.IsA()) { + VtDoubleArray usdVal(doubleArrayDataFn.length()); + for (unsigned int i = 0; i < doubleArrayDataFn.length(); ++i) { + usdVal[i] = doubleArrayDataFn[i]; } - break; + return VtValue(usdVal); } - case MFnData::kIntArray: { - if (type.IsA()) { - MFnIntArrayData intArrayDataFn(attrPlug.asMObject()); - VtIntArray usdVal(intArrayDataFn.length()); - for (unsigned int i = 0; i < intArrayDataFn.length(); ++i) { - usdVal[i] = intArrayDataFn[i]; - } - return VtValue(usdVal); + break; + } + case MFnData::kFloatArray: { + if (type.IsA()) { + MFnFloatArrayData floatArrayDataFn(attrPlug.asMObject()); + VtFloatArray usdVal(floatArrayDataFn.length()); + for (unsigned int i = 0; i < floatArrayDataFn.length(); ++i) { + usdVal[i] = floatArrayDataFn[i]; } - break; + return VtValue(usdVal); } - case MFnData::kPointArray: { - MFnPointArrayData pointArrayDataFn(attrPlug.asMObject()); - if (type.IsA()) { - VtVec3fArray usdVal(pointArrayDataFn.length()); - for (unsigned int i = 0; i < pointArrayDataFn.length(); ++i) { - MPoint tmpMayaVal = pointArrayDataFn[i]; - if (tmpMayaVal.w != 0) { - tmpMayaVal.cartesianize(); - } - usdVal[i] = GfVec3f((float)tmpMayaVal[0], - (float)tmpMayaVal[1], - (float)tmpMayaVal[2]); - } - return VtValue(usdVal); - } else if (type.IsA()) { - VtVec3dArray usdVal(pointArrayDataFn.length()); - for (unsigned int i = 0; i < pointArrayDataFn.length(); ++i) { - MPoint tmpMayaVal = pointArrayDataFn[i]; - if (tmpMayaVal.w != 0) { - tmpMayaVal.cartesianize(); - } - usdVal[i] = GfVec3d(tmpMayaVal[0], - tmpMayaVal[1], - tmpMayaVal[2]); - } - return VtValue(usdVal); + break; + } + case MFnData::kIntArray: { + if (type.IsA()) { + MFnIntArrayData intArrayDataFn(attrPlug.asMObject()); + VtIntArray usdVal(intArrayDataFn.length()); + for (unsigned int i = 0; i < intArrayDataFn.length(); ++i) { + usdVal[i] = intArrayDataFn[i]; } - break; + return VtValue(usdVal); } - case MFnData::kVectorArray: { - MFnVectorArrayData vectorArrayDataFn(attrPlug.asMObject()); - if (type.IsA()) { - VtVec3fArray usdVal(vectorArrayDataFn.length()); - for (unsigned int i = 0; i < vectorArrayDataFn.length(); ++i) { - MVector tmpMayaVal = vectorArrayDataFn[i]; - usdVal[i] = GfVec3f((float)tmpMayaVal[0], - (float)tmpMayaVal[1], - (float)tmpMayaVal[2]); + break; + } + case MFnData::kPointArray: { + MFnPointArrayData pointArrayDataFn(attrPlug.asMObject()); + if (type.IsA()) { + VtVec3fArray usdVal(pointArrayDataFn.length()); + for (unsigned int i = 0; i < pointArrayDataFn.length(); ++i) { + MPoint tmpMayaVal = pointArrayDataFn[i]; + if (tmpMayaVal.w != 0) { + tmpMayaVal.cartesianize(); } - return VtValue(usdVal); - } else if (type.IsA()) { - VtVec3dArray usdVal(vectorArrayDataFn.length()); - for (unsigned int i = 0; i < vectorArrayDataFn.length(); ++i) { - MVector tmpMayaVal = vectorArrayDataFn[i]; - usdVal[i] = GfVec3d(tmpMayaVal[0], - tmpMayaVal[1], - tmpMayaVal[2]); + usdVal[i] + = GfVec3f((float)tmpMayaVal[0], (float)tmpMayaVal[1], (float)tmpMayaVal[2]); + } + return VtValue(usdVal); + } else if (type.IsA()) { + VtVec3dArray usdVal(pointArrayDataFn.length()); + for (unsigned int i = 0; i < pointArrayDataFn.length(); ++i) { + MPoint tmpMayaVal = pointArrayDataFn[i]; + if (tmpMayaVal.w != 0) { + tmpMayaVal.cartesianize(); } - return VtValue(usdVal); + usdVal[i] = GfVec3d(tmpMayaVal[0], tmpMayaVal[1], tmpMayaVal[2]); } - break; + return VtValue(usdVal); } - default: - break; + break; } - - switch (numericDataType) { - case MFnNumericData::kBoolean: { - if (type.IsA()) { - const bool usdVal(attrPlug.asBool()); - return VtValue(usdVal); + case MFnData::kVectorArray: { + MFnVectorArrayData vectorArrayDataFn(attrPlug.asMObject()); + if (type.IsA()) { + VtVec3fArray usdVal(vectorArrayDataFn.length()); + for (unsigned int i = 0; i < vectorArrayDataFn.length(); ++i) { + MVector tmpMayaVal = vectorArrayDataFn[i]; + usdVal[i] + = GfVec3f((float)tmpMayaVal[0], (float)tmpMayaVal[1], (float)tmpMayaVal[2]); } - break; - } - case MFnNumericData::kByte: - case MFnNumericData::kChar: { - if (type.IsA()) { - const int usdVal(attrPlug.asChar()); - return VtValue(usdVal); - } - break; - } - case MFnNumericData::kShort: { - if (type.IsA()) { - const int usdVal(attrPlug.asShort()); - return VtValue(usdVal); + return VtValue(usdVal); + } else if (type.IsA()) { + VtVec3dArray usdVal(vectorArrayDataFn.length()); + for (unsigned int i = 0; i < vectorArrayDataFn.length(); ++i) { + MVector tmpMayaVal = vectorArrayDataFn[i]; + usdVal[i] = GfVec3d(tmpMayaVal[0], tmpMayaVal[1], tmpMayaVal[2]); } - break; + return VtValue(usdVal); } - case MFnNumericData::kInt: { - if (type.IsA()) { - const int usdVal(attrPlug.asInt()); - return VtValue(usdVal); - } - break; + break; + } + default: break; + } + + switch (numericDataType) { + case MFnNumericData::kBoolean: { + if (type.IsA()) { + const bool usdVal(attrPlug.asBool()); + return VtValue(usdVal); } - case MFnNumericData::k2Short: { - if (type.IsA()) { - short tmp1, tmp2; - MFnNumericData numericDataFn(attrPlug.asMObject()); - numericDataFn.getData(tmp1, tmp2); - return VtValue(GfVec2i(tmp1, tmp2)); - } - break; + break; + } + case MFnNumericData::kByte: + case MFnNumericData::kChar: { + if (type.IsA()) { + const int usdVal(attrPlug.asChar()); + return VtValue(usdVal); } - case MFnNumericData::k2Int: { - if (type.IsA()) { - int tmp1, tmp2; - MFnNumericData numericDataFn(attrPlug.asMObject()); - numericDataFn.getData(tmp1, tmp2); - return VtValue(GfVec2i(tmp1, tmp2)); - } - break; + break; + } + case MFnNumericData::kShort: { + if (type.IsA()) { + const int usdVal(attrPlug.asShort()); + return VtValue(usdVal); } - case MFnNumericData::k3Short: { - if (type.IsA()) { - short tmp1, tmp2, tmp3; - MFnNumericData numericDataFn(attrPlug.asMObject()); - numericDataFn.getData(tmp1, tmp2, tmp3); - return VtValue(GfVec3i(tmp1, tmp2, tmp3)); - } - break; + break; + } + case MFnNumericData::kInt: { + if (type.IsA()) { + const int usdVal(attrPlug.asInt()); + return VtValue(usdVal); } - case MFnNumericData::k3Int: { - if (type.IsA()) { - int tmp1, tmp2, tmp3; - MFnNumericData numericDataFn(attrPlug.asMObject()); - numericDataFn.getData(tmp1, tmp2, tmp3); - return VtValue(GfVec3i(tmp1, tmp2, tmp3)); - } - break; + break; + } + case MFnNumericData::k2Short: { + if (type.IsA()) { + short tmp1, tmp2; + MFnNumericData numericDataFn(attrPlug.asMObject()); + numericDataFn.getData(tmp1, tmp2); + return VtValue(GfVec2i(tmp1, tmp2)); } - case MFnNumericData::kFloat: { - if (type.IsA()) { - const float usdVal(attrPlug.asFloat()); - return VtValue(usdVal); - } - break; + break; + } + case MFnNumericData::k2Int: { + if (type.IsA()) { + int tmp1, tmp2; + MFnNumericData numericDataFn(attrPlug.asMObject()); + numericDataFn.getData(tmp1, tmp2); + return VtValue(GfVec2i(tmp1, tmp2)); } - case MFnNumericData::k2Float: { - if (type.IsA()) { - float tmp1, tmp2; - MFnNumericData numericDataFn(attrPlug.asMObject()); - numericDataFn.getData(tmp1, tmp2); - return VtValue(GfVec2f(tmp1, tmp2)); - } - break; + break; + } + case MFnNumericData::k3Short: { + if (type.IsA()) { + short tmp1, tmp2, tmp3; + MFnNumericData numericDataFn(attrPlug.asMObject()); + numericDataFn.getData(tmp1, tmp2, tmp3); + return VtValue(GfVec3i(tmp1, tmp2, tmp3)); } - case MFnNumericData::k3Float: { - if (type.IsA()) { - float tmp1, tmp2, tmp3; - MFnNumericData numericDataFn(attrPlug.asMObject()); - numericDataFn.getData(tmp1, tmp2, tmp3); - return _ConvertVec( - GfVec3f(tmp1, tmp2, tmp3), - role, - linearizeColors); - } - break; + break; + } + case MFnNumericData::k3Int: { + if (type.IsA()) { + int tmp1, tmp2, tmp3; + MFnNumericData numericDataFn(attrPlug.asMObject()); + numericDataFn.getData(tmp1, tmp2, tmp3); + return VtValue(GfVec3i(tmp1, tmp2, tmp3)); } - case MFnNumericData::kDouble: { - const double usdVal(attrPlug.asDouble()); - if (type.IsA()) { - return VtValue((float)usdVal); - } else if (type.IsA()) { - return VtValue(usdVal); - } - break; + break; + } + case MFnNumericData::kFloat: { + if (type.IsA()) { + const float usdVal(attrPlug.asFloat()); + return VtValue(usdVal); } - case MFnNumericData::k2Double: { - double tmp1, tmp2; + break; + } + case MFnNumericData::k2Float: { + if (type.IsA()) { + float tmp1, tmp2; MFnNumericData numericDataFn(attrPlug.asMObject()); numericDataFn.getData(tmp1, tmp2); - if (type.IsA()) { - return VtValue(GfVec2f((float)tmp1, (float)tmp2)); - } else if (type.IsA()) { - return VtValue(GfVec2d(tmp1, tmp2)); - } - break; + return VtValue(GfVec2f(tmp1, tmp2)); } - case MFnNumericData::k3Double: { - double tmp1, tmp2, tmp3; + break; + } + case MFnNumericData::k3Float: { + if (type.IsA()) { + float tmp1, tmp2, tmp3; MFnNumericData numericDataFn(attrPlug.asMObject()); numericDataFn.getData(tmp1, tmp2, tmp3); - if (type.IsA()) { - return _ConvertVec( - GfVec3f((float)tmp1, (float)tmp2, (float)tmp3), - role, - linearizeColors); - } else if (type.IsA()) { - return _ConvertVec( - GfVec3d(tmp1, tmp2, tmp3), - role, - linearizeColors); - } - break; + return _ConvertVec(GfVec3f(tmp1, tmp2, tmp3), role, linearizeColors); } - case MFnNumericData::k4Double: { - double tmp1, tmp2, tmp3, tmp4; - MFnNumericData numericDataFn(attrPlug.asMObject()); - numericDataFn.getData(tmp1, tmp2, tmp3, tmp4); - if (type.IsA()) { - return _ConvertVec( - GfVec4f((float)tmp1, (float)tmp2, (float)tmp3, (float)tmp4), - role, - linearizeColors); - } else if (type.IsA()) { - return _ConvertVec( - GfVec4d(tmp1, tmp2, tmp3, tmp4), - role, - linearizeColors); - } else if (type.IsA()) { - float re = tmp1; - GfVec3f im(tmp2, tmp3, tmp4); - return VtValue(GfQuatf(re, im)); - } else if (type.IsA()) { - double re = tmp1; - GfVec3d im(tmp2, tmp3, tmp4); - return VtValue(GfQuatd(re, im)); - } - break; + break; + } + case MFnNumericData::kDouble: { + const double usdVal(attrPlug.asDouble()); + if (type.IsA()) { + return VtValue((float)usdVal); + } else if (type.IsA()) { + return VtValue(usdVal); + } + break; + } + case MFnNumericData::k2Double: { + double tmp1, tmp2; + MFnNumericData numericDataFn(attrPlug.asMObject()); + numericDataFn.getData(tmp1, tmp2); + if (type.IsA()) { + return VtValue(GfVec2f((float)tmp1, (float)tmp2)); + } else if (type.IsA()) { + return VtValue(GfVec2d(tmp1, tmp2)); + } + break; + } + case MFnNumericData::k3Double: { + double tmp1, tmp2, tmp3; + MFnNumericData numericDataFn(attrPlug.asMObject()); + numericDataFn.getData(tmp1, tmp2, tmp3); + if (type.IsA()) { + return _ConvertVec( + GfVec3f((float)tmp1, (float)tmp2, (float)tmp3), role, linearizeColors); + } else if (type.IsA()) { + return _ConvertVec(GfVec3d(tmp1, tmp2, tmp3), role, linearizeColors); } - default: - break; + break; + } + case MFnNumericData::k4Double: { + double tmp1, tmp2, tmp3, tmp4; + MFnNumericData numericDataFn(attrPlug.asMObject()); + numericDataFn.getData(tmp1, tmp2, tmp3, tmp4); + if (type.IsA()) { + return _ConvertVec( + GfVec4f((float)tmp1, (float)tmp2, (float)tmp3, (float)tmp4), role, linearizeColors); + } else if (type.IsA()) { + return _ConvertVec(GfVec4d(tmp1, tmp2, tmp3, tmp4), role, linearizeColors); + } else if (type.IsA()) { + float re = tmp1; + GfVec3f im(tmp2, tmp3, tmp4); + return VtValue(GfQuatf(re, im)); + } else if (type.IsA()) { + double re = tmp1; + GfVec3d im(tmp2, tmp3, tmp4); + return VtValue(GfQuatd(re, im)); + } + break; + } + default: break; } switch (unitDataType) { - case MFnUnitAttribute::kAngle: - case MFnUnitAttribute::kDistance: - if (type.IsA()) { - const float usdVal(attrPlug.asFloat()); - return VtValue(usdVal); - } else if (type.IsA()) { - const double usdVal(attrPlug.asDouble()); - return VtValue(usdVal); - } - break; - default: - break; + case MFnUnitAttribute::kAngle: + case MFnUnitAttribute::kDistance: + if (type.IsA()) { + const float usdVal(attrPlug.asFloat()); + return VtValue(usdVal); + } else if (type.IsA()) { + const double usdVal(attrPlug.asDouble()); + return VtValue(usdVal); + } + break; + default: break; } return VtValue(); } -bool -UsdMayaWriteUtil::SetUsdAttr( - const MPlug& attrPlug, - const UsdAttribute& usdAttr, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter *valueWriter) +bool UsdMayaWriteUtil::SetUsdAttr( + const MPlug& attrPlug, + const UsdAttribute& usdAttr, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) { if (!usdAttr || attrPlug.isNull()) { return false; @@ -689,9 +642,7 @@ UsdMayaWriteUtil::SetUsdAttr( return true; } - VtValue val = GetVtValue( - attrPlug, - usdAttr.GetTypeName()); + VtValue val = GetVtValue(attrPlug, usdAttr.GetTypeName()); if (val.IsEmpty()) { return false; } @@ -735,75 +686,61 @@ UsdMayaWriteUtil::SetUsdAttr( // USD attribute name collisions will be resolved by using the first attribute // visited and warning about subsequent attribute tags. // -bool -UsdMayaWriteUtil::WriteUserExportedAttributes( - const MObject& mayaNode, - const UsdPrim& usdPrim, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter *valueWriter) +bool UsdMayaWriteUtil::WriteUserExportedAttributes( + const MObject& mayaNode, + const UsdPrim& usdPrim, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) { - std::vector exportedAttributes = - UsdMayaUserTaggedAttribute::GetUserTaggedAttributesForNode(mayaNode); + std::vector exportedAttributes + = UsdMayaUserTaggedAttribute::GetUserTaggedAttributesForNode(mayaNode); for (const UsdMayaUserTaggedAttribute& attr : exportedAttributes) { const std::string& usdAttrName = attr.GetUsdName(); - const TfToken& usdAttrType = attr.GetUsdType(); - const TfToken& interpolation = attr.GetUsdInterpolation(); - const bool translateMayaDoubleToUsdSinglePrecision = - attr.GetTranslateMayaDoubleToUsdSinglePrecision(); + const TfToken& usdAttrType = attr.GetUsdType(); + const TfToken& interpolation = attr.GetUsdInterpolation(); + const bool translateMayaDoubleToUsdSinglePrecision + = attr.GetTranslateMayaDoubleToUsdSinglePrecision(); const MPlug& attrPlug = attr.GetMayaPlug(); UsdAttribute usdAttr; - if (usdAttrType == - UsdMayaUserTaggedAttributeTokens->USDAttrTypePrimvar) { + if (usdAttrType == UsdMayaUserTaggedAttributeTokens->USDAttrTypePrimvar) { UsdGeomImageable imageable(usdPrim); if (!imageable) { TF_RUNTIME_ERROR( - "Cannot create primvar for non-UsdGeomImageable USD " - "prim <%s>", - usdPrim.GetPath().GetText()); + "Cannot create primvar for non-UsdGeomImageable USD " + "prim <%s>", + usdPrim.GetPath().GetText()); continue; } - UsdGeomPrimvar primvar = - UsdMayaWriteUtil::GetOrCreatePrimvar(attrPlug, - imageable, - usdAttrName, - interpolation, - -1, - translateMayaDoubleToUsdSinglePrecision); + UsdGeomPrimvar primvar = UsdMayaWriteUtil::GetOrCreatePrimvar( + attrPlug, + imageable, + usdAttrName, + interpolation, + -1, + translateMayaDoubleToUsdSinglePrecision); if (primvar) { usdAttr = primvar.GetAttr(); } - } else if (usdAttrType == - UsdMayaUserTaggedAttributeTokens->USDAttrTypeUsdRi) { - usdAttr = - UsdMayaWriteUtil::GetOrCreateUsdRiAttribute(attrPlug, - usdPrim, - usdAttrName, - "user", - translateMayaDoubleToUsdSinglePrecision); + } else if (usdAttrType == UsdMayaUserTaggedAttributeTokens->USDAttrTypeUsdRi) { + usdAttr = UsdMayaWriteUtil::GetOrCreateUsdRiAttribute( + attrPlug, usdPrim, usdAttrName, "user", translateMayaDoubleToUsdSinglePrecision); } else { - usdAttr = UsdMayaWriteUtil::GetOrCreateUsdAttr(attrPlug, - usdPrim, - usdAttrName, - true, - translateMayaDoubleToUsdSinglePrecision); + usdAttr = UsdMayaWriteUtil::GetOrCreateUsdAttr( + attrPlug, usdPrim, usdAttrName, true, translateMayaDoubleToUsdSinglePrecision); } if (usdAttr) { - if (!UsdMayaWriteUtil::SetUsdAttr(attrPlug, - usdAttr, - usdTime, - valueWriter)) { + if (!UsdMayaWriteUtil::SetUsdAttr(attrPlug, usdAttr, usdTime, valueWriter)) { TF_RUNTIME_ERROR( - "Could not set value for attribute <%s>", - usdAttr.GetPath().GetText()); + "Could not set value for attribute <%s>", usdAttr.GetPath().GetText()); continue; } } else { TF_RUNTIME_ERROR( - "Could not create attribute '%s' for USD prim <%s>", - usdAttrName.c_str(), - usdPrim.GetPath().GetText()); + "Could not create attribute '%s' for USD prim <%s>", + usdAttrName.c_str(), + usdPrim.GetPath().GetText()); continue; } } @@ -812,10 +749,7 @@ UsdMayaWriteUtil::WriteUserExportedAttributes( } /* static */ -bool -UsdMayaWriteUtil::WriteMetadataToPrim( - const MObject& mayaObject, - const UsdPrim& prim) +bool UsdMayaWriteUtil::WriteMetadataToPrim(const MObject& mayaObject, const UsdPrim& prim) { UsdMayaAdaptor adaptor(mayaObject); if (!adaptor) { @@ -829,11 +763,10 @@ UsdMayaWriteUtil::WriteMetadataToPrim( } /* static */ -bool -UsdMayaWriteUtil::WriteAPISchemaAttributesToPrim( - const MObject& mayaObject, - const UsdPrim& prim, - UsdUtilsSparseValueWriter *valueWriter) +bool UsdMayaWriteUtil::WriteAPISchemaAttributesToPrim( + const MObject& mayaObject, + const UsdPrim& prim, + UsdUtilsSparseValueWriter* valueWriter) { UsdMayaAdaptor adaptor(mayaObject); if (!adaptor) { @@ -841,21 +774,19 @@ UsdMayaWriteUtil::WriteAPISchemaAttributesToPrim( } for (const TfToken& schemaName : adaptor.GetAppliedSchemas()) { - if (const UsdMayaAdaptor::SchemaAdaptor schemaAdaptor = - adaptor.GetSchemaByName(schemaName)) { - for (const TfToken& attrName : - schemaAdaptor.GetAuthoredAttributeNames()) { - if (const UsdMayaAdaptor::AttributeAdaptor attrAdaptor = - schemaAdaptor.GetAttribute(attrName)) { + if (const UsdMayaAdaptor::SchemaAdaptor schemaAdaptor + = adaptor.GetSchemaByName(schemaName)) { + for (const TfToken& attrName : schemaAdaptor.GetAuthoredAttributeNames()) { + if (const UsdMayaAdaptor::AttributeAdaptor attrAdaptor + = schemaAdaptor.GetAttribute(attrName)) { VtValue value; if (attrAdaptor.Get(&value)) { - const SdfAttributeSpecHandle attrDef = - attrAdaptor.GetAttributeDefinition(); - UsdAttribute attr = prim.CreateAttribute( - attrDef->GetNameToken(), - attrDef->GetTypeName(), - /*custom*/ false, - attrDef->GetVariability()); + const SdfAttributeSpecHandle attrDef = attrAdaptor.GetAttributeDefinition(); + UsdAttribute attr = prim.CreateAttribute( + attrDef->GetNameToken(), + attrDef->GetTypeName(), + /*custom*/ false, + attrDef->GetVariability()); const UsdTimeCode usdTime = UsdTimeCode::Default(); SetAttribute(attr, value, usdTime, valueWriter); } @@ -867,14 +798,13 @@ UsdMayaWriteUtil::WriteAPISchemaAttributesToPrim( } /* static */ -size_t -UsdMayaWriteUtil::WriteSchemaAttributesToPrim( - const MObject& object, - const UsdPrim& prim, - const TfType& schemaType, +size_t UsdMayaWriteUtil::WriteSchemaAttributesToPrim( + const MObject& object, + const UsdPrim& prim, + const TfType& schemaType, const std::vector& attributeNames, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter *valueWriter) + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) { UsdMayaAdaptor::SchemaAdaptor schema; if (UsdMayaAdaptor adaptor = UsdMayaAdaptor(object)) { @@ -886,20 +816,19 @@ UsdMayaWriteUtil::WriteSchemaAttributesToPrim( size_t count = 0; for (const TfToken& attrName : attributeNames) { - VtValue value; + VtValue value; SdfAttributeSpecHandle attrDef; - if (UsdMayaAdaptor::AttributeAdaptor attr = - schema.GetAttribute(attrName)) { + if (UsdMayaAdaptor::AttributeAdaptor attr = schema.GetAttribute(attrName)) { attr.Get(&value); attrDef = attr.GetAttributeDefinition(); } if (!value.IsEmpty() && attrDef) { UsdAttribute attr = prim.CreateAttribute( - attrDef->GetNameToken(), - attrDef->GetTypeName(), - /*custom*/ false, - attrDef->GetVariability()); + attrDef->GetNameToken(), + attrDef->GetTypeName(), + /*custom*/ false, + attrDef->GetVariability()); if (SetAttribute(attr, value, usdTime, valueWriter)) { count++; } @@ -910,16 +839,15 @@ UsdMayaWriteUtil::WriteSchemaAttributesToPrim( } // static -bool -UsdMayaWriteUtil::WriteClassInherits( - const UsdPrim& prim, - const std::vector& classNamesToInherit) +bool UsdMayaWriteUtil::WriteClassInherits( + const UsdPrim& prim, + const std::vector& classNamesToInherit) { if (classNamesToInherit.empty()) { return true; } - for (const auto& className: classNamesToInherit) { + for (const auto& className : classNamesToInherit) { if (!TfIsValidIdentifier(className)) { return false; } @@ -928,10 +856,9 @@ UsdMayaWriteUtil::WriteClassInherits( UsdStagePtr stage = prim.GetStage(); auto inherits = prim.GetInherits(); - for (const auto& className: classNamesToInherit) { - const SdfPath inheritPath = SdfPath::AbsoluteRootPath().AppendChild( - TfToken(className)); - UsdPrim classPrim = stage->CreateClassPrim(inheritPath); + for (const auto& className : classNamesToInherit) { + const SdfPath inheritPath = SdfPath::AbsoluteRootPath().AppendChild(TfToken(className)); + UsdPrim classPrim = stage->CreateClassPrim(inheritPath); inherits.AddInherit(classPrim.GetPath()); } return true; @@ -939,9 +866,7 @@ UsdMayaWriteUtil::WriteClassInherits( template static VtArray -_MapMayaToVtArray( - const MArrayType& mayaArray, - const std::function mapper) +_MapMayaToVtArray(const MArrayType& mayaArray, const std::function mapper) { VtArray vtArray(mayaArray.length()); for (unsigned int i = 0; i < mayaArray.length(); ++i) { @@ -951,13 +876,12 @@ _MapMayaToVtArray( } // static -bool -UsdMayaWriteUtil::WriteArrayAttrsToInstancer( - MFnArrayAttrsData& inputPointsData, +bool UsdMayaWriteUtil::WriteArrayAttrsToInstancer( + MFnArrayAttrsData& inputPointsData, const UsdGeomPointInstancer& instancer, - const size_t numPrototypes, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter *valueWriter) + const size_t numPrototypes, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) { MStatus status; @@ -965,29 +889,29 @@ UsdMayaWriteUtil::WriteArrayAttrsToInstancer( // sparse (contain less values than there are instances), so just loop // through all the arrays and assume that there are as many instances as the // size of the largest array. - unsigned int numInstances = 0; + unsigned int numInstances = 0; const MStringArray channels = inputPointsData.list(); for (unsigned int i = 0; i < channels.length(); ++i) { MFnArrayAttrsData::Type type; if (inputPointsData.checkArrayExist(channels[i], type)) { switch (type) { - case MFnArrayAttrsData::kVectorArray: { - MVectorArray arr = inputPointsData.vectorArray(channels[i]); - numInstances = std::max(numInstances, arr.length()); - } break; - case MFnArrayAttrsData::kDoubleArray: { - MDoubleArray arr = inputPointsData.doubleArray(channels[i]); - numInstances = std::max(numInstances, arr.length()); - } break; - case MFnArrayAttrsData::kIntArray: { - MIntArray arr = inputPointsData.intArray(channels[i]); - numInstances = std::max(numInstances, arr.length()); - } break; - case MFnArrayAttrsData::kStringArray: { - MStringArray arr = inputPointsData.stringArray(channels[i]); - numInstances = std::max(numInstances, arr.length()); - } break; - default: break; + case MFnArrayAttrsData::kVectorArray: { + MVectorArray arr = inputPointsData.vectorArray(channels[i]); + numInstances = std::max(numInstances, arr.length()); + } break; + case MFnArrayAttrsData::kDoubleArray: { + MDoubleArray arr = inputPointsData.doubleArray(channels[i]); + numInstances = std::max(numInstances, arr.length()); + } break; + case MFnArrayAttrsData::kIntArray: { + MIntArray arr = inputPointsData.intArray(channels[i]); + numInstances = std::max(numInstances, arr.length()); + } break; + case MFnArrayAttrsData::kStringArray: { + MStringArray arr = inputPointsData.stringArray(channels[i]); + numInstances = std::max(numInstances, arr.length()); + } break; + default: break; } } } @@ -998,22 +922,16 @@ UsdMayaWriteUtil::WriteArrayAttrsToInstancer( // Note that we need to populate indicesOrIds in either case; the schema // interprets some attributes (e.g. visibility) as referring to id's if // present or indices otherwise. - VtInt64Array indicesOrIds; + VtInt64Array indicesOrIds; MFnArrayAttrsData::Type type; - if (inputPointsData.checkArrayExist("id", type) && - type == MFnArrayAttrsData::kDoubleArray) { + if (inputPointsData.checkArrayExist("id", type) && type == MFnArrayAttrsData::kDoubleArray) { const MDoubleArray id = inputPointsData.doubleArray("id", &status); CHECK_MSTATUS_AND_RETURN(status, false); - indicesOrIds = _MapMayaToVtArray< - MDoubleArray, double, int64_t>( - id, - [](double x) { - return (int64_t) x; - }); + indicesOrIds = _MapMayaToVtArray( + id, [](double x) { return (int64_t)x; }); SetAttribute(instancer.CreateIdsAttr(), indicesOrIds, usdTime, valueWriter); - } - else { + } else { // Skip writing the id's, but still generate the indicesOrIds array. for (size_t i = 0; i < numInstances; ++i) { indicesOrIds.push_back(i); @@ -1023,90 +941,67 @@ UsdMayaWriteUtil::WriteArrayAttrsToInstancer( // Export the rest of the per-instance array attrs. // Some attributes might be missing elements; pad the array according to // Maya's fallback behavior up to the numInstances. - if (inputPointsData.checkArrayExist("objectIndex", type) && - type == MFnArrayAttrsData::kDoubleArray) { - const MDoubleArray objectIndex = inputPointsData.doubleArray( - "objectIndex", &status); + if (inputPointsData.checkArrayExist("objectIndex", type) + && type == MFnArrayAttrsData::kDoubleArray) { + const MDoubleArray objectIndex = inputPointsData.doubleArray("objectIndex", &status); CHECK_MSTATUS_AND_RETURN(status, false); - VtIntArray vtArray = _MapMayaToVtArray( - objectIndex, - [numPrototypes](double x) { - if (x < numPrototypes) { - return (int) x; - } - else { - // Return the *last* prototype if out of bounds. - return (int) numPrototypes - 1; - } - }); + VtIntArray vtArray + = _MapMayaToVtArray(objectIndex, [numPrototypes](double x) { + if (x < numPrototypes) { + return (int)x; + } else { + // Return the *last* prototype if out of bounds. + return (int)numPrototypes - 1; + } + }); SetAttribute(instancer.CreateProtoIndicesAttr(), vtArray, usdTime, valueWriter); - } - else { + } else { VtIntArray vtArray; vtArray.assign(numInstances, 0); - SetAttribute(instancer.CreateProtoIndicesAttr(), - vtArray, usdTime, valueWriter); + SetAttribute(instancer.CreateProtoIndicesAttr(), vtArray, usdTime, valueWriter); } - if (inputPointsData.checkArrayExist("position", type) && - type == MFnArrayAttrsData::kVectorArray) { - const MVectorArray position = inputPointsData.vectorArray("position", - &status); + if (inputPointsData.checkArrayExist("position", type) + && type == MFnArrayAttrsData::kVectorArray) { + const MVectorArray position = inputPointsData.vectorArray("position", &status); CHECK_MSTATUS_AND_RETURN(status, false); - VtVec3fArray vtArray = _MapMayaToVtArray< - MVectorArray, const MVector&, GfVec3f>( - position, - [](const MVector& v) { - return GfVec3f(v.x, v.y, v.z); - }); + VtVec3fArray vtArray = _MapMayaToVtArray( + position, [](const MVector& v) { return GfVec3f(v.x, v.y, v.z); }); SetAttribute(instancer.CreatePositionsAttr(), vtArray, usdTime, valueWriter); - } - else { + } else { VtVec3fArray vtArray; vtArray.assign(numInstances, GfVec3f(0.0f)); SetAttribute(instancer.CreatePositionsAttr(), vtArray, usdTime, valueWriter); } - if (inputPointsData.checkArrayExist("rotation", type) && - type == MFnArrayAttrsData::kVectorArray) { - const MVectorArray rotation = inputPointsData.vectorArray("rotation", - &status); + if (inputPointsData.checkArrayExist("rotation", type) + && type == MFnArrayAttrsData::kVectorArray) { + const MVectorArray rotation = inputPointsData.vectorArray("rotation", &status); CHECK_MSTATUS_AND_RETURN(status, false); - VtQuathArray vtArray = _MapMayaToVtArray< - MVectorArray, const MVector&, GfQuath>( - rotation, - [](const MVector& v) { + VtQuathArray vtArray = _MapMayaToVtArray( + rotation, [](const MVector& v) { GfRotation rot = GfRotation(GfVec3d::XAxis(), v.x) - * GfRotation(GfVec3d::YAxis(), v.y) - * GfRotation(GfVec3d::ZAxis(), v.z); + * GfRotation(GfVec3d::YAxis(), v.y) * GfRotation(GfVec3d::ZAxis(), v.z); return GfQuath(rot.GetQuat()); }); SetAttribute(instancer.CreateOrientationsAttr(), vtArray, usdTime, valueWriter); - } - else { + } else { VtQuathArray vtArray; vtArray.assign(numInstances, GfQuath(0.0f)); SetAttribute(instancer.CreateOrientationsAttr(), vtArray, usdTime, valueWriter); } - if (inputPointsData.checkArrayExist("scale", type) && - type == MFnArrayAttrsData::kVectorArray) { - const MVectorArray scale = inputPointsData.vectorArray("scale", - &status); + if (inputPointsData.checkArrayExist("scale", type) && type == MFnArrayAttrsData::kVectorArray) { + const MVectorArray scale = inputPointsData.vectorArray("scale", &status); CHECK_MSTATUS_AND_RETURN(status, false); - VtVec3fArray vtArray = _MapMayaToVtArray< - MVectorArray, const MVector&, GfVec3f>( - scale, - [](const MVector& v) { - return GfVec3f(v.x, v.y, v.z); - }); + VtVec3fArray vtArray = _MapMayaToVtArray( + scale, [](const MVector& v) { return GfVec3f(v.x, v.y, v.z); }); SetAttribute(instancer.CreateScalesAttr(), vtArray, usdTime, valueWriter); - } - else { + } else { VtVec3fArray vtArray; vtArray.assign(numInstances, GfVec3f(1.0)); SetAttribute(instancer.CreateScalesAttr(), vtArray, usdTime, valueWriter); @@ -1116,10 +1011,9 @@ UsdMayaWriteUtil::WriteArrayAttrsToInstancer( // to each instance. USD stores visibility as a sparse array of only the // particular id's (or indices) to be invis'ed. // Visibility isn't required, so skip authoring if it doesn't exist. - if (inputPointsData.checkArrayExist("visibility", type) && - type == MFnArrayAttrsData::kDoubleArray) { - const MDoubleArray visibility = inputPointsData.doubleArray( - "visibility", &status); + if (inputPointsData.checkArrayExist("visibility", type) + && type == MFnArrayAttrsData::kDoubleArray) { + const MDoubleArray visibility = inputPointsData.doubleArray("visibility", &status); CHECK_MSTATUS_AND_RETURN(status, false); VtInt64Array invisibleIds; @@ -1136,21 +1030,19 @@ UsdMayaWriteUtil::WriteArrayAttrsToInstancer( return true; } -bool -UsdMayaWriteUtil::ReadMayaAttribute( - const MFnDependencyNode& depNode, - const MString& name, - std::string* val) +bool UsdMayaWriteUtil::ReadMayaAttribute( + const MFnDependencyNode& depNode, + const MString& name, + std::string* val) { MStatus status; depNode.attribute(name, &status); if (status == MS::kSuccess) { - MPlug plug = depNode.findPlug(name); + MPlug plug = depNode.findPlug(name); MObject dataObj; - if ( (plug.getValue(dataObj) == MS::kSuccess) && - (dataObj.hasFn(MFn::kStringData)) ) { + if ((plug.getValue(dataObj) == MS::kSuccess) && (dataObj.hasFn(MFn::kStringData))) { (*val) = std::string(plug.asString().asChar()); return true; @@ -1160,26 +1052,24 @@ UsdMayaWriteUtil::ReadMayaAttribute( return false; } -bool -UsdMayaWriteUtil::ReadMayaAttribute( - const MFnDependencyNode& depNode, - const MString& name, - std::vector* val) +bool UsdMayaWriteUtil::ReadMayaAttribute( + const MFnDependencyNode& depNode, + const MString& name, + std::vector* val) { MStatus status; depNode.attribute(name, &status); if (status == MS::kSuccess) { - MPlug plug = depNode.findPlug(name); + MPlug plug = depNode.findPlug(name); MObject dataObj; - if ( (plug.getValue(dataObj) == MS::kSuccess) && - (dataObj.hasFn(MFn::kStringArrayData)) ) { + if ((plug.getValue(dataObj) == MS::kSuccess) && (dataObj.hasFn(MFn::kStringArrayData))) { MFnStringArrayData dData(dataObj, &status); if (status == MS::kSuccess) { MStringArray arrayValues = dData.array(); - size_t numValues = arrayValues.length(); + size_t numValues = arrayValues.length(); val->resize(numValues); for (size_t i = 0; i < numValues; ++i) { (*val)[i] = std::string(arrayValues[i].asChar()); @@ -1192,26 +1082,24 @@ UsdMayaWriteUtil::ReadMayaAttribute( return false; } -bool -UsdMayaWriteUtil::ReadMayaAttribute( - const MFnDependencyNode& depNode, - const MString& name, - VtIntArray* val) +bool UsdMayaWriteUtil::ReadMayaAttribute( + const MFnDependencyNode& depNode, + const MString& name, + VtIntArray* val) { MStatus status; depNode.attribute(name, &status); if (status == MS::kSuccess) { - MPlug plug = depNode.findPlug(name); + MPlug plug = depNode.findPlug(name); MObject dataObj; - if ( (plug.getValue(dataObj) == MS::kSuccess) && - (dataObj.hasFn(MFn::kIntArrayData)) ) { + if ((plug.getValue(dataObj) == MS::kSuccess) && (dataObj.hasFn(MFn::kIntArrayData))) { MFnIntArrayData dData(dataObj, &status); if (status == MS::kSuccess) { MIntArray arrayValues = dData.array(); - size_t numValues = arrayValues.length(); + size_t numValues = arrayValues.length(); val->resize(numValues); for (size_t i = 0; i < numValues; ++i) { (*val)[i] = arrayValues[i]; @@ -1224,26 +1112,24 @@ UsdMayaWriteUtil::ReadMayaAttribute( return false; } -bool -UsdMayaWriteUtil::ReadMayaAttribute( - const MFnDependencyNode& depNode, - const MString& name, - VtFloatArray* val) +bool UsdMayaWriteUtil::ReadMayaAttribute( + const MFnDependencyNode& depNode, + const MString& name, + VtFloatArray* val) { MStatus status; depNode.attribute(name, &status); if (status == MS::kSuccess) { - MPlug plug = depNode.findPlug(name); + MPlug plug = depNode.findPlug(name); MObject dataObj; - if ( (plug.getValue(dataObj) == MS::kSuccess) && - (dataObj.hasFn(MFn::kDoubleArrayData)) ) { + if ((plug.getValue(dataObj) == MS::kSuccess) && (dataObj.hasFn(MFn::kDoubleArrayData))) { MFnDoubleArrayData dData(dataObj, &status); if (status == MS::kSuccess) { MDoubleArray arrayValues = dData.array(); - size_t numValues = arrayValues.length(); + size_t numValues = arrayValues.length(); val->resize(numValues); for (size_t i = 0; i < numValues; ++i) { (*val)[i] = arrayValues[i]; @@ -1256,32 +1142,27 @@ UsdMayaWriteUtil::ReadMayaAttribute( return false; } -bool -UsdMayaWriteUtil::ReadMayaAttribute( - const MFnDependencyNode& depNode, - const MString& name, - VtVec3fArray* val) +bool UsdMayaWriteUtil::ReadMayaAttribute( + const MFnDependencyNode& depNode, + const MString& name, + VtVec3fArray* val) { MStatus status; depNode.attribute(name, &status); if (status == MS::kSuccess) { - MPlug plug = depNode.findPlug(name); + MPlug plug = depNode.findPlug(name); MObject dataObj; - if ( (plug.getValue(dataObj) == MS::kSuccess) && - (dataObj.hasFn(MFn::kVectorArrayData)) ) { + if ((plug.getValue(dataObj) == MS::kSuccess) && (dataObj.hasFn(MFn::kVectorArrayData))) { MFnVectorArrayData dData(dataObj, &status); if (status == MS::kSuccess) { MVectorArray arrayValues = dData.array(); - size_t numValues = arrayValues.length(); + size_t numValues = arrayValues.length(); val->resize(numValues); for (size_t i = 0; i < numValues; ++i) { - (*val)[i].Set( - arrayValues[i][0], - arrayValues[i][1], - arrayValues[i][2]); + (*val)[i].Set(arrayValues[i][0], arrayValues[i][1], arrayValues[i][2]); } return true; } @@ -1291,11 +1172,10 @@ UsdMayaWriteUtil::ReadMayaAttribute( return false; } -std::vector -UsdMayaWriteUtil::GetTimeSamples( - const GfInterval& frameRange, - const std::set& subframeOffsets, - const double stride) +std::vector UsdMayaWriteUtil::GetTimeSamples( + const GfInterval& frameRange, + const std::set& subframeOffsets, + const double stride) { std::vector samples; @@ -1310,8 +1190,7 @@ UsdMayaWriteUtil::GetTimeSamples( for (const double t : subframeOffsets) { if (t <= -stride) { TF_WARN("subframe offset (%f) <= -stride (-%f)", t, stride); - } - else if (t >= stride) { + } else if (t >= stride) { TF_WARN("subframe offset (%f) >= stride (%f)", t, stride); } } @@ -1322,10 +1201,9 @@ UsdMayaWriteUtil::GetTimeSamples( } // Iterate over all possible times and sample offsets. - static const std::set zeroOffset = {0.0}; - const std::set& actualOffsets = subframeOffsets.empty() ? - zeroOffset : subframeOffsets; - double currentTime = frameRange.GetMin(); + static const std::set zeroOffset = { 0.0 }; + const std::set& actualOffsets = subframeOffsets.empty() ? zeroOffset : subframeOffsets; + double currentTime = frameRange.GetMin(); while (frameRange.Contains(currentTime)) { for (const double offset : actualOffsets) { samples.push_back(currentTime + offset); @@ -1340,5 +1218,4 @@ UsdMayaWriteUtil::GetTimeSamples( return samples; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/utils/writeUtil.h b/lib/mayaUsd/fileio/utils/writeUtil.h index 81b9fc5686..cc12812fba 100644 --- a/lib/mayaUsd/fileio/utils/writeUtil.h +++ b/lib/mayaUsd/fileio/utils/writeUtil.h @@ -16,17 +16,12 @@ #ifndef PXRUSDMAYA_WRITEUTIL_H #define PXRUSDMAYA_WRITEUTIL_H -#include - -#include -#include -#include -#include -#include +#include +#include -#include #include #include +#include #include #include #include @@ -36,8 +31,13 @@ #include #include -#include -#include +#include +#include +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE @@ -70,12 +70,12 @@ struct UsdMayaWriteUtil /// float-based type. Otherwise, their type will be double-based. MAYAUSD_CORE_PUBLIC static UsdAttribute GetOrCreateUsdAttr( - const MPlug& attrPlug, - const UsdPrim& usdPrim, - const std::string& attrName, - const bool custom = false, - const bool translateMayaDoubleToUsdSinglePrecision = - UsdMayaUserTaggedAttribute::GetFallbackTranslateMayaDoubleToUsdSinglePrecision()); + const MPlug& attrPlug, + const UsdPrim& usdPrim, + const std::string& attrName, + const bool custom = false, + const bool translateMayaDoubleToUsdSinglePrecision + = UsdMayaUserTaggedAttribute::GetFallbackTranslateMayaDoubleToUsdSinglePrecision()); /// Given an \p attrPlug, try to create a primvar on \p imageable with /// the name \p primvarName. Note, it's value will not be set. @@ -85,13 +85,13 @@ struct UsdMayaWriteUtil /// float-based type. Otherwise, their type will be double-based. MAYAUSD_CORE_PUBLIC static UsdGeomPrimvar GetOrCreatePrimvar( - const MPlug& attrPlug, - UsdGeomImageable& imageable, - const std::string& primvarName, - const TfToken& interpolation = TfToken(), - const int elementSize = -1, - const bool translateMayaDoubleToUsdSinglePrecision = - UsdMayaUserTaggedAttribute::GetFallbackTranslateMayaDoubleToUsdSinglePrecision()); + const MPlug& attrPlug, + UsdGeomImageable& imageable, + const std::string& primvarName, + const TfToken& interpolation = TfToken(), + const int elementSize = -1, + const bool translateMayaDoubleToUsdSinglePrecision + = UsdMayaUserTaggedAttribute::GetFallbackTranslateMayaDoubleToUsdSinglePrecision()); /// Given an \p attrPlug, try to create a UsdRi attribute on \p usdPrim with /// the name \p attrName. Note, it's value will not be set. @@ -101,12 +101,12 @@ struct UsdMayaWriteUtil /// float-based type. Otherwise, their type will be double-based. MAYAUSD_CORE_PUBLIC static UsdAttribute GetOrCreateUsdRiAttribute( - const MPlug& attrPlug, - const UsdPrim& usdPrim, - const std::string& attrName, - const std::string& nameSpace = "user", - const bool translateMayaDoubleToUsdSinglePrecision = - UsdMayaUserTaggedAttribute::GetFallbackTranslateMayaDoubleToUsdSinglePrecision()); + const MPlug& attrPlug, + const UsdPrim& usdPrim, + const std::string& attrName, + const std::string& nameSpace = "user", + const bool translateMayaDoubleToUsdSinglePrecision + = UsdMayaUserTaggedAttribute::GetFallbackTranslateMayaDoubleToUsdSinglePrecision()); /// Given an \p attrPlug, reads its value and returns it as a wrapped /// VtValue. The type of the value is determined by consulting the given @@ -117,9 +117,9 @@ struct UsdMayaWriteUtil /// converted to a linear color value if \p linearizeColors is true. MAYAUSD_CORE_PUBLIC static VtValue GetVtValue( - const MPlug& attrPlug, - const SdfValueTypeName& typeName, - const bool linearizeColors = true); + const MPlug& attrPlug, + const SdfValueTypeName& typeName, + const bool linearizeColors = true); /// Given an \p attrPlug, reads its value and returns it as a wrapped /// VtValue. The type of the value is determined by consulting the given @@ -130,10 +130,10 @@ struct UsdMayaWriteUtil /// to a linear color value if \p linearizeColors is true. MAYAUSD_CORE_PUBLIC static VtValue GetVtValue( - const MPlug& attrPlug, - const TfType& type, - const TfToken& role, - const bool linearizeColors = true); + const MPlug& attrPlug, + const TfType& type, + const TfToken& role, + const bool linearizeColors = true); /// Given an \p attrPlug, determine it's value and set it on \p usdAttr at /// \p usdTime. @@ -143,27 +143,25 @@ struct UsdMayaWriteUtil /// name of the USD attribute. MAYAUSD_CORE_PUBLIC static bool SetUsdAttr( - const MPlug& attrPlug, - const UsdAttribute& usdAttr, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter *valueWriter=nullptr); + const MPlug& attrPlug, + const UsdAttribute& usdAttr, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter = nullptr); /// Given a Maya node \p mayaNode, inspect it for attributes tagged by /// the user for export to USD and write them onto \p usdPrim at time /// \p usdTime. MAYAUSD_CORE_PUBLIC static bool WriteUserExportedAttributes( - const MObject& mayaNode, - const UsdPrim& usdPrim, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter *valueWriter=nullptr); + const MObject& mayaNode, + const UsdPrim& usdPrim, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter = nullptr); /// Writes all of the adaptor metadata from \p mayaObject onto the \p prim. /// Returns true if successful (even if there was nothing to export). MAYAUSD_CORE_PUBLIC - static bool WriteMetadataToPrim( - const MObject& mayaObject, - const UsdPrim& prim); + static bool WriteMetadataToPrim(const MObject& mayaObject, const UsdPrim& prim); /// Writes all of the adaptor API schema attributes from \p mayaObject onto /// the \p prim. Only attributes on applied schemas will be written to @@ -172,25 +170,20 @@ struct UsdMayaWriteUtil /// \sa UsdMayaAdaptor::GetAppliedSchemas MAYAUSD_CORE_PUBLIC static bool WriteAPISchemaAttributesToPrim( - const MObject& mayaObject, - const UsdPrim& prim, - UsdUtilsSparseValueWriter *valueWriter=nullptr); + const MObject& mayaObject, + const UsdPrim& prim, + UsdUtilsSparseValueWriter* valueWriter = nullptr); template static size_t WriteSchemaAttributesToPrim( - const MObject& object, - const UsdPrim& prim, - const std::vector& attributeNames, - const UsdTimeCode& usdTime = UsdTimeCode::Default(), - UsdUtilsSparseValueWriter *valueWriter=nullptr) + const MObject& object, + const UsdPrim& prim, + const std::vector& attributeNames, + const UsdTimeCode& usdTime = UsdTimeCode::Default(), + UsdUtilsSparseValueWriter* valueWriter = nullptr) { return WriteSchemaAttributesToPrim( - object, - prim, - TfType::Find(), - attributeNames, - usdTime, - valueWriter); + object, prim, TfType::Find(), attributeNames, usdTime, valueWriter); } /// Writes schema attributes specified by \attributeNames for the schema @@ -200,20 +193,19 @@ struct UsdMayaWriteUtil /// it will be used to write the values. /// Returns the number of attributes actually written to the USD stage. static size_t WriteSchemaAttributesToPrim( - const MObject& object, - const UsdPrim& prim, - const TfType& schemaType, - const std::vector& attributeNames, - const UsdTimeCode& usdTime = UsdTimeCode::Default(), - UsdUtilsSparseValueWriter *valueWriter=nullptr); + const MObject& object, + const UsdPrim& prim, + const TfType& schemaType, + const std::vector& attributeNames, + const UsdTimeCode& usdTime = UsdTimeCode::Default(), + UsdUtilsSparseValueWriter* valueWriter = nullptr); /// Authors class inherits on \p usdPrim. \p inheritClassNames are /// specified as names (not paths). For example, they should be /// ["_class_Special", ...]. MAYAUSD_CORE_PUBLIC - static bool WriteClassInherits( - const UsdPrim& usdPrim, - const std::vector& inheritClassNames); + static bool + WriteClassInherits(const UsdPrim& usdPrim, const std::vector& inheritClassNames); /// Given \p inputPointsData (native Maya particle data), writes the /// arrays as point-instancer attributes on the given \p instancer @@ -221,11 +213,11 @@ struct UsdMayaWriteUtil /// Returns true if successful. MAYAUSD_CORE_PUBLIC static bool WriteArrayAttrsToInstancer( - MFnArrayAttrsData& inputPointsData, - const UsdGeomPointInstancer& instancer, - const size_t numPrototypes, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter *valueWriter=nullptr); + MFnArrayAttrsData& inputPointsData, + const UsdGeomPointInstancer& instancer, + const size_t numPrototypes, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter = nullptr); /// \} @@ -234,37 +226,29 @@ struct UsdMayaWriteUtil /// \brief Reads attribute \p name on \p depNode into \p val. MAYAUSD_CORE_PUBLIC - static bool ReadMayaAttribute( - const MFnDependencyNode& depNode, - const MString& name, - std::string* val); + static bool + ReadMayaAttribute(const MFnDependencyNode& depNode, const MString& name, std::string* val); MAYAUSD_CORE_PUBLIC static bool ReadMayaAttribute( - const MFnDependencyNode& depNode, - const MString& name, - std::vector* val); + const MFnDependencyNode& depNode, + const MString& name, + std::vector* val); /// \brief Reads attribute \p name on \p depNode into \p val. MAYAUSD_CORE_PUBLIC - static bool ReadMayaAttribute( - const MFnDependencyNode& depNode, - const MString& name, - VtIntArray* val); + static bool + ReadMayaAttribute(const MFnDependencyNode& depNode, const MString& name, VtIntArray* val); /// \brief Reads attribute \p name on \p depNode into \p val. MAYAUSD_CORE_PUBLIC - static bool ReadMayaAttribute( - const MFnDependencyNode& depNode, - const MString& name, - VtFloatArray* val); + static bool + ReadMayaAttribute(const MFnDependencyNode& depNode, const MString& name, VtFloatArray* val); /// \brief Reads attribute \p name on \p depNode into \p val. MAYAUSD_CORE_PUBLIC - static bool ReadMayaAttribute( - const MFnDependencyNode& depNode, - const MString& name, - VtVec3fArray* val); + static bool + ReadMayaAttribute(const MFnDependencyNode& depNode, const MString& name, VtVec3fArray* val); /// \} /// \name Frame/time utilities { @@ -291,9 +275,9 @@ struct UsdMayaWriteUtil /// _outside_ the specified \p frameRange. MAYAUSD_CORE_PUBLIC static std::vector GetTimeSamples( - const GfInterval& frameRange, - const std::set& subframeOffsets, - const double stride = 1.0); + const GfInterval& frameRange, + const std::set& subframeOffsets, + const double stride = 1.0); /// \} @@ -306,14 +290,13 @@ struct UsdMayaWriteUtil /// if provided. template static bool SetAttribute( - const UsdAttribute& attr, - const T& value, - const UsdTimeCode time = UsdTimeCode::Default(), - UsdUtilsSparseValueWriter* valueWriter = nullptr) + const UsdAttribute& attr, + const T& value, + const UsdTimeCode time = UsdTimeCode::Default(), + UsdUtilsSparseValueWriter* valueWriter = nullptr) { - return valueWriter ? - valueWriter->SetAttribute(attr, VtValue(value), time) : - attr.Set(value, time); + return valueWriter ? valueWriter->SetAttribute(attr, VtValue(value), time) + : attr.Set(value, time); } /// \overload @@ -323,18 +306,16 @@ struct UsdMayaWriteUtil /// leaving it in default-constructed state (value-initialized). template static bool SetAttribute( - const UsdAttribute& attr, - T* value, - const UsdTimeCode time = UsdTimeCode::Default(), - UsdUtilsSparseValueWriter* valueWriter = nullptr) + const UsdAttribute& attr, + T* value, + const UsdTimeCode time = UsdTimeCode::Default(), + UsdUtilsSparseValueWriter* valueWriter = nullptr) { - return valueWriter ? - valueWriter->SetAttribute(attr, VtValue::Take(*value), time) : - attr.Set(*value, time); + return valueWriter ? valueWriter->SetAttribute(attr, VtValue::Take(*value), time) + : attr.Set(*value, time); } }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/fileio/utils/xformStack.cpp b/lib/mayaUsd/fileio/utils/xformStack.cpp index 9fd636dd4a..885b9c5a47 100644 --- a/lib/mayaUsd/fileio/utils/xformStack.cpp +++ b/lib/mayaUsd/fileio/utils/xformStack.cpp @@ -14,365 +14,312 @@ // #include "xformStack.h" -#include - #include #include +#include + PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PUBLIC_TOKENS(UsdMayaXformStackTokens, - PXRUSDMAYA_XFORM_STACK_TOKENS); +TF_DEFINE_PUBLIC_TOKENS(UsdMayaXformStackTokens, PXRUSDMAYA_XFORM_STACK_TOKENS); namespace { - const UsdGeomXformOp::Type RotateOpTypes[] = { - UsdGeomXformOp::TypeRotateX, - UsdGeomXformOp::TypeRotateY, - UsdGeomXformOp::TypeRotateZ, - UsdGeomXformOp::TypeRotateXYZ, - UsdGeomXformOp::TypeRotateXZY, - UsdGeomXformOp::TypeRotateYXZ, - UsdGeomXformOp::TypeRotateYZX, - UsdGeomXformOp::TypeRotateZXY, - UsdGeomXformOp::TypeRotateZYX - }; - - bool _isThreeAxisRotate(UsdGeomXformOp::Type opType) - { - return (opType == UsdGeomXformOp::TypeRotateXYZ - || opType == UsdGeomXformOp::TypeRotateXZY - || opType == UsdGeomXformOp::TypeRotateYXZ - || opType == UsdGeomXformOp::TypeRotateYZX - || opType == UsdGeomXformOp::TypeRotateZXY - || opType == UsdGeomXformOp::TypeRotateZYX); - } +const UsdGeomXformOp::Type RotateOpTypes[] = { + UsdGeomXformOp::TypeRotateX, UsdGeomXformOp::TypeRotateY, UsdGeomXformOp::TypeRotateZ, + UsdGeomXformOp::TypeRotateXYZ, UsdGeomXformOp::TypeRotateXZY, UsdGeomXformOp::TypeRotateYXZ, + UsdGeomXformOp::TypeRotateYZX, UsdGeomXformOp::TypeRotateZXY, UsdGeomXformOp::TypeRotateZYX +}; - bool _isOneOrThreeAxisRotate(UsdGeomXformOp::Type opType) - { - return (opType == UsdGeomXformOp::TypeRotateXYZ - || opType == UsdGeomXformOp::TypeRotateXZY - || opType == UsdGeomXformOp::TypeRotateYXZ - || opType == UsdGeomXformOp::TypeRotateYZX - || opType == UsdGeomXformOp::TypeRotateZXY - || opType == UsdGeomXformOp::TypeRotateZYX - || opType == UsdGeomXformOp::TypeRotateX - || opType == UsdGeomXformOp::TypeRotateY - || opType == UsdGeomXformOp::TypeRotateZ); - } +bool _isThreeAxisRotate(UsdGeomXformOp::Type opType) +{ + return ( + opType == UsdGeomXformOp::TypeRotateXYZ || opType == UsdGeomXformOp::TypeRotateXZY + || opType == UsdGeomXformOp::TypeRotateYXZ || opType == UsdGeomXformOp::TypeRotateYZX + || opType == UsdGeomXformOp::TypeRotateZXY || opType == UsdGeomXformOp::TypeRotateZYX); +} - UsdMayaXformStack::IndexMap - _buildInversionMap( - const std::vector& inversionTwins) - { - UsdMayaXformStack::IndexMap result; - for (const auto& twinPair : inversionTwins) - { - result[twinPair.first] = twinPair.second; - result[twinPair.second] = twinPair.first; - } - return result; - } +bool _isOneOrThreeAxisRotate(UsdGeomXformOp::Type opType) +{ + return ( + opType == UsdGeomXformOp::TypeRotateXYZ || opType == UsdGeomXformOp::TypeRotateXZY + || opType == UsdGeomXformOp::TypeRotateYXZ || opType == UsdGeomXformOp::TypeRotateYZX + || opType == UsdGeomXformOp::TypeRotateZXY || opType == UsdGeomXformOp::TypeRotateZYX + || opType == UsdGeomXformOp::TypeRotateX || opType == UsdGeomXformOp::TypeRotateY + || opType == UsdGeomXformOp::TypeRotateZ); +} - // Given a single index into ops, return the pair of - // indices, which is: - // { opIndex, NO_INDEX } if opIndex has no inversion twin - // { opIndex, opIndexTwin } if opIndex has an inversion twin, and opIndex < opIndexTwin - // { opIndexTwin, opIndex } if opIndex has an inversion twin, and opIndex > opIndexTwin - UsdMayaXformStack::IndexPair - _makeInversionIndexPair( - size_t opIndex, - const UsdMayaXformStack::IndexMap& inversionMap) - { - auto foundTwin = inversionMap.find(opIndex); - if (foundTwin == inversionMap.end()) - { - return std::make_pair(opIndex, UsdMayaXformStack::NO_INDEX); - } - else - { - const size_t twinOpIndex = foundTwin->second; - if (twinOpIndex >= opIndex) - { - return std::make_pair(opIndex, twinOpIndex); - } - else - { - return std::make_pair(twinOpIndex, opIndex); - } - } +UsdMayaXformStack::IndexMap +_buildInversionMap(const std::vector& inversionTwins) +{ + UsdMayaXformStack::IndexMap result; + for (const auto& twinPair : inversionTwins) { + result[twinPair.first] = twinPair.second; + result[twinPair.second] = twinPair.first; } + return result; +} - UsdMayaXformStack::TokenIndexPairMap - _buildAttrNamesToIdxs( - const UsdMayaXformStack::OpClassList& ops, - const UsdMayaXformStack::IndexMap& inversionMap) - { - UsdMayaXformStack::TokenIndexPairMap result; - for (size_t i = 0; i < ops.size(); ++i) - { - const UsdMayaXformOpClassification& op = ops[i]; - // Inverted twin pairs will always have same name, so can skip one - if (op.IsInvertedTwin()) continue; - - for (auto attrName : op.CompatibleAttrNames()) - { - UsdMayaXformStack::IndexPair indexPair = - _makeInversionIndexPair(i, inversionMap); - // Insert, and check if it already existed - TF_VERIFY(result.insert({attrName, indexPair}).second, - "AttrName %s already found in attrName lookup map", - attrName.GetText()); - } +// Given a single index into ops, return the pair of +// indices, which is: +// { opIndex, NO_INDEX } if opIndex has no inversion twin +// { opIndex, opIndexTwin } if opIndex has an inversion twin, and opIndex < opIndexTwin +// { opIndexTwin, opIndex } if opIndex has an inversion twin, and opIndex > opIndexTwin +UsdMayaXformStack::IndexPair +_makeInversionIndexPair(size_t opIndex, const UsdMayaXformStack::IndexMap& inversionMap) +{ + auto foundTwin = inversionMap.find(opIndex); + if (foundTwin == inversionMap.end()) { + return std::make_pair(opIndex, UsdMayaXformStack::NO_INDEX); + } else { + const size_t twinOpIndex = foundTwin->second; + if (twinOpIndex >= opIndex) { + return std::make_pair(opIndex, twinOpIndex); + } else { + return std::make_pair(twinOpIndex, opIndex); } - return result; } +} - UsdMayaXformStack::TokenIndexPairMap _buildOpNamesToIdxs( - const UsdMayaXformStack::OpClassList& ops, - const UsdMayaXformStack::IndexMap& inversionMap) - { - UsdMayaXformStack::TokenIndexPairMap result; - for (size_t i = 0; i < ops.size(); ++i) - { - const UsdMayaXformOpClassification& op = ops[i]; - // Inverted twin pairs will always have same name, so can skip one - if (op.IsInvertedTwin()) continue; - - UsdMayaXformStack::IndexPair indexPair = - _makeInversionIndexPair(i, inversionMap); +UsdMayaXformStack::TokenIndexPairMap _buildAttrNamesToIdxs( + const UsdMayaXformStack::OpClassList& ops, + const UsdMayaXformStack::IndexMap& inversionMap) +{ + UsdMayaXformStack::TokenIndexPairMap result; + for (size_t i = 0; i < ops.size(); ++i) { + const UsdMayaXformOpClassification& op = ops[i]; + // Inverted twin pairs will always have same name, so can skip one + if (op.IsInvertedTwin()) + continue; + + for (auto attrName : op.CompatibleAttrNames()) { + UsdMayaXformStack::IndexPair indexPair = _makeInversionIndexPair(i, inversionMap); // Insert, and check if it already existed - TF_VERIFY(result.insert({op.GetName(), indexPair}).second, - "Op classification name %s already found in op lookup map", - op.GetName().GetText()); + TF_VERIFY( + result.insert({ attrName, indexPair }).second, + "AttrName %s already found in attrName lookup map", + attrName.GetText()); } - return result; } + return result; +} +UsdMayaXformStack::TokenIndexPairMap _buildOpNamesToIdxs( + const UsdMayaXformStack::OpClassList& ops, + const UsdMayaXformStack::IndexMap& inversionMap) +{ + UsdMayaXformStack::TokenIndexPairMap result; + for (size_t i = 0; i < ops.size(); ++i) { + const UsdMayaXformOpClassification& op = ops[i]; + // Inverted twin pairs will always have same name, so can skip one + if (op.IsInvertedTwin()) + continue; + + UsdMayaXformStack::IndexPair indexPair = _makeInversionIndexPair(i, inversionMap); + // Insert, and check if it already existed + TF_VERIFY( + result.insert({ op.GetName(), indexPair }).second, + "Op classification name %s already found in op lookup map", + op.GetName().GetText()); + } + return result; } +} // namespace + class UsdMayaXformOpClassification::_Data : public TfRefBase { public: - _DataRefPtr static Create(const TfToken &name, - UsdGeomXformOp::Type opType, - bool isInvertedTwin) + _DataRefPtr static Create(const TfToken& name, UsdGeomXformOp::Type opType, bool isInvertedTwin) { return _DataRefPtr(new _Data(name, opType, isInvertedTwin)); } - bool operator ==(const _Data& other) const + bool operator==(const _Data& other) const { - return (m_name == other.m_name - && m_opType == other.m_opType - && m_isInvertedTwin == other.m_isInvertedTwin); + return ( + m_name == other.m_name && m_opType == other.m_opType + && m_isInvertedTwin == other.m_isInvertedTwin); } - const TfToken m_name; + const TfToken m_name; const UsdGeomXformOp::Type m_opType; - const bool m_isInvertedTwin; + const bool m_isInvertedTwin; private: - _Data(const TfToken &name, UsdGeomXformOp::Type opType, bool isInvertedTwin) - : m_name(name), - m_opType(opType), - m_isInvertedTwin(isInvertedTwin) + _Data(const TfToken& name, UsdGeomXformOp::Type opType, bool isInvertedTwin) + : m_name(name) + , m_opType(opType) + , m_isInvertedTwin(isInvertedTwin) { } }; -UsdMayaXformOpClassification::UsdMayaXformOpClassification() : - _sharedData(nullptr) +UsdMayaXformOpClassification::UsdMayaXformOpClassification() + : _sharedData(nullptr) { } UsdMayaXformOpClassification::UsdMayaXformOpClassification( - const TfToken &name, - UsdGeomXformOp::Type opType, - bool isInvertedTwin) : - _sharedData(_Data::Create(name, opType, isInvertedTwin)) + const TfToken& name, + UsdGeomXformOp::Type opType, + bool isInvertedTwin) + : _sharedData(_Data::Create(name, opType, isInvertedTwin)) { } -UsdMayaXformOpClassification const & -UsdMayaXformOpClassification::NullInstance() +UsdMayaXformOpClassification const& UsdMayaXformOpClassification::NullInstance() { static UsdMayaXformOpClassification theNull; return theNull; } -bool -UsdMayaXformOpClassification::IsNull() const -{ - return !_sharedData; -} +bool UsdMayaXformOpClassification::IsNull() const { return !_sharedData; } -TfToken const & -UsdMayaXformOpClassification::GetName() const -{ - return _sharedData->m_name; -} +TfToken const& UsdMayaXformOpClassification::GetName() const { return _sharedData->m_name; } -UsdGeomXformOp::Type -UsdMayaXformOpClassification::GetOpType() const +UsdGeomXformOp::Type UsdMayaXformOpClassification::GetOpType() const { return _sharedData->m_opType; } -bool -UsdMayaXformOpClassification::IsInvertedTwin() const -{ - return _sharedData->m_isInvertedTwin; -} +bool UsdMayaXformOpClassification::IsInvertedTwin() const { return _sharedData->m_isInvertedTwin; } -std::vector -UsdMayaXformOpClassification::CompatibleAttrNames() const +std::vector UsdMayaXformOpClassification::CompatibleAttrNames() const { // Note that we make tokens immortal because UsdMayaXformOpClassification // is currently not publically creatable, and is only used to make // some global constants (ie, MayaStack and CommonStack) std::vector result; - std::string attrName; - if (_isThreeAxisRotate(GetOpType())) - { + std::string attrName; + if (_isThreeAxisRotate(GetOpType())) { // Special handling for rotates, to deal with rotateX/rotateZXY/etc - if (GetName() == UsdMayaXformStackTokens->rotate) - { + if (GetName() == UsdMayaXformStackTokens->rotate) { result.reserve(std::extent::value * 3); // Special handling for rotate, to deal with rotateX/rotateZXY/etc - for (UsdGeomXformOp::Type rotateType : RotateOpTypes) - { + for (UsdGeomXformOp::Type rotateType : RotateOpTypes) { // Add, ie, xformOp::rotateX - result.emplace_back(TfToken( - UsdGeomXformOp::GetOpName(rotateType).GetString(), - TfToken::Immortal)); + result.emplace_back( + TfToken(UsdGeomXformOp::GetOpName(rotateType).GetString(), TfToken::Immortal)); // Add, ie, xformOp::rotateX::rotate result.emplace_back(TfToken( - UsdGeomXformOp::GetOpName(rotateType, - UsdMayaXformStackTokens->rotate).GetString(), - TfToken::Immortal)); + UsdGeomXformOp::GetOpName(rotateType, UsdMayaXformStackTokens->rotate) + .GetString(), + TfToken::Immortal)); // Add, ie, xformOp::rotateX::rotateX result.emplace_back(TfToken( - UsdGeomXformOp::GetOpName(rotateType, - UsdGeomXformOp::GetOpTypeToken(rotateType)).GetString(), - TfToken::Immortal)); + UsdGeomXformOp::GetOpName( + rotateType, UsdGeomXformOp::GetOpTypeToken(rotateType)) + .GetString(), + TfToken::Immortal)); } - } - else - { + } else { result.reserve(std::extent::value); - for (UsdGeomXformOp::Type rotateType : RotateOpTypes) - { + for (UsdGeomXformOp::Type rotateType : RotateOpTypes) { // Add, ie, xformOp::rotateX::rotateAxis result.emplace_back(TfToken( - UsdGeomXformOp::GetOpName(rotateType, - GetName()).GetString(), - TfToken::Immortal)); + UsdGeomXformOp::GetOpName(rotateType, GetName()).GetString(), + TfToken::Immortal)); } } - } - else - { + } else { // Add, ie, xformOp::translate::someName result.emplace_back(TfToken( - UsdGeomXformOp::GetOpName(GetOpType(), GetName()).GetString(), - TfToken::Immortal)); - if (GetName() == UsdGeomXformOp::GetOpTypeToken(GetOpType())) - { + UsdGeomXformOp::GetOpName(GetOpType(), GetName()).GetString(), TfToken::Immortal)); + if (GetName() == UsdGeomXformOp::GetOpTypeToken(GetOpType())) { // Add, ie, xformOp::translate - result.emplace_back(TfToken( - UsdGeomXformOp::GetOpName(GetOpType()).GetString(), - TfToken::Immortal)); + result.emplace_back( + TfToken(UsdGeomXformOp::GetOpName(GetOpType()).GetString(), TfToken::Immortal)); } } return result; } -bool -UsdMayaXformOpClassification::IsCompatibleType(UsdGeomXformOp::Type otherType) const +bool UsdMayaXformOpClassification::IsCompatibleType(UsdGeomXformOp::Type otherType) const { - if (GetOpType() == otherType) return true; - if (_isThreeAxisRotate(GetOpType() )) - { + if (GetOpType() == otherType) + return true; + if (_isThreeAxisRotate(GetOpType())) { return _isOneOrThreeAxisRotate(otherType); } return false; } -bool UsdMayaXformOpClassification::operator ==(const UsdMayaXformOpClassification& other) const +bool UsdMayaXformOpClassification::operator==(const UsdMayaXformOpClassification& other) const { return *_sharedData == *other._sharedData; } // Lame that we need this... I had thought that constexpr would essentially be treated like -// a compile-time #define, with better type safety! Instead, it seems it still creates a full-fledged -// linker symbol... +// a compile-time #define, with better type safety! Instead, it seems it still creates a +// full-fledged linker symbol... constexpr size_t UsdMayaXformStack::NO_INDEX; class UsdMayaXformStack::_Data : public TfRefBase { public: _DataRefPtr static Create( - const UsdMayaXformStack::OpClassList& ops, - const std::vector& inversionTwins, - bool nameMatters) + const UsdMayaXformStack::OpClassList& ops, + const std::vector& inversionTwins, + bool nameMatters) { return _DataRefPtr(new _Data(ops, inversionTwins, nameMatters)); } _Data( - const UsdMayaXformStack::OpClassList& ops, - const std::vector& inversionTwins, - bool nameMatters) : - m_ops(ops), - m_inversionTwins(inversionTwins), - m_inversionMap(_buildInversionMap(inversionTwins)), - m_attrNamesToIdxs( - _buildAttrNamesToIdxs(m_ops, m_inversionMap)), - m_opNamesToIdxs( - _buildOpNamesToIdxs(m_ops, m_inversionMap)), - m_nameMatters(nameMatters) + const UsdMayaXformStack::OpClassList& ops, + const std::vector& inversionTwins, + bool nameMatters) + : m_ops(ops) + , m_inversionTwins(inversionTwins) + , m_inversionMap(_buildInversionMap(inversionTwins)) + , m_attrNamesToIdxs(_buildAttrNamesToIdxs(m_ops, m_inversionMap)) + , m_opNamesToIdxs(_buildOpNamesToIdxs(m_ops, m_inversionMap)) + , m_nameMatters(nameMatters) { // Verify that all inversion twins are of same type, and exactly one is marked // as the inverted twin - for (auto& pair : m_inversionTwins) - { + for (auto& pair : m_inversionTwins) { const UsdMayaXformOpClassification& first = m_ops[pair.first]; const UsdMayaXformOpClassification& second = m_ops[pair.second]; - TF_VERIFY(first.GetName() == second.GetName(), - "Inversion twins %lu (%s) and %lu (%s) did not have same name", - pair.first, first.GetName().GetText(), - pair.second, second.GetName().GetText()); - TF_VERIFY(first.GetOpType() == second.GetOpType(), - "Inversion twins %lu and %lu (%s) were not same op type", - pair.first, pair.second, first.GetName().GetText()); - TF_VERIFY(first.IsInvertedTwin() != second.IsInvertedTwin(), - "Inversion twins %lu and %lu (%s) were both marked as %s inverted twin", - pair.first, pair.second, first.GetName().GetText(), - first.IsInvertedTwin() ? "the" : "not the"); + TF_VERIFY( + first.GetName() == second.GetName(), + "Inversion twins %lu (%s) and %lu (%s) did not have same name", + pair.first, + first.GetName().GetText(), + pair.second, + second.GetName().GetText()); + TF_VERIFY( + first.GetOpType() == second.GetOpType(), + "Inversion twins %lu and %lu (%s) were not same op type", + pair.first, + pair.second, + first.GetName().GetText()); + TF_VERIFY( + first.IsInvertedTwin() != second.IsInvertedTwin(), + "Inversion twins %lu and %lu (%s) were both marked as %s inverted twin", + pair.first, + pair.second, + first.GetName().GetText(), + first.IsInvertedTwin() ? "the" : "not the"); } } - inline const UsdMayaXformStack::OpClass& - GetOpClassFromIndex( - const size_t i) const + inline const UsdMayaXformStack::OpClass& GetOpClassFromIndex(const size_t i) const { - return i == UsdMayaXformStack::NO_INDEX - ? UsdMayaXformStack::OpClass::NullInstance() - : m_ops[i]; + return i == UsdMayaXformStack::NO_INDEX ? UsdMayaXformStack::OpClass::NullInstance() + : m_ops[i]; } inline UsdMayaXformStack::OpClassPair - MakeOpClassPairFromIndexPair( - const UsdMayaXformStack::IndexPair& indexPair) const + MakeOpClassPairFromIndexPair(const UsdMayaXformStack::IndexPair& indexPair) const { return std::make_pair( - GetOpClassFromIndex(indexPair.first), - GetOpClassFromIndex(indexPair.second)); + GetOpClassFromIndex(indexPair.first), GetOpClassFromIndex(indexPair.second)); } - const UsdMayaXformStack::OpClassList m_ops; + const UsdMayaXformStack::OpClassList m_ops; std::vector m_inversionTwins; - UsdMayaXformStack::IndexMap m_inversionMap; + UsdMayaXformStack::IndexMap m_inversionMap; // We store lookups from raw attribute name - use full attribute // name because it's the only "piece" we know we have a pre-generated @@ -395,58 +342,52 @@ class UsdMayaXformStack::_Data : public TfRefBase }; UsdMayaXformStack::UsdMayaXformStack( - const UsdMayaXformStack::OpClassList& ops, - const std::vector& inversionTwins, - bool nameMatters) : - _sharedData(_Data::Create(ops, inversionTwins, nameMatters)) + const UsdMayaXformStack::OpClassList& ops, + const std::vector& inversionTwins, + bool nameMatters) + : _sharedData(_Data::Create(ops, inversionTwins, nameMatters)) { } -UsdMayaXformStack::OpClassList const & -UsdMayaXformStack::GetOps() const { +UsdMayaXformStack::OpClassList const& UsdMayaXformStack::GetOps() const +{ return _sharedData->m_ops; } -std::vector const & -UsdMayaXformStack::GetInversionTwins() const { +std::vector const& UsdMayaXformStack::GetInversionTwins() const +{ return _sharedData->m_inversionTwins; } -bool -UsdMayaXformStack::GetNameMatters() const { - return _sharedData->m_nameMatters; -} +bool UsdMayaXformStack::GetNameMatters() const { return _sharedData->m_nameMatters; } -UsdMayaXformOpClassification const & -UsdMayaXformStack::operator[] (const size_t index) const { +UsdMayaXformOpClassification const& UsdMayaXformStack::operator[](const size_t index) const +{ return _sharedData->m_ops[index]; } -size_t -UsdMayaXformStack::GetSize() const { - return _sharedData->m_ops.size(); -} +size_t UsdMayaXformStack::GetSize() const { return _sharedData->m_ops.size(); } -size_t -UsdMayaXformStack::FindOpIndex(const TfToken& opName, bool isInvertedTwin) const +size_t UsdMayaXformStack::FindOpIndex(const TfToken& opName, bool isInvertedTwin) const { - const UsdMayaXformStack::IndexPair& foundIdxPair = - FindOpIndexPair(opName); + const UsdMayaXformStack::IndexPair& foundIdxPair = FindOpIndexPair(opName); - if(foundIdxPair.first == NO_INDEX) return NO_INDEX; + if (foundIdxPair.first == NO_INDEX) + return NO_INDEX; // we (potentially) found a pair of opPtrs... use the one that // matches isInvertedTwin const UsdMayaXformOpClassification& firstOp = GetOps()[foundIdxPair.first]; - if (firstOp.IsInvertedTwin()) - { - if (isInvertedTwin) return foundIdxPair.first; - else return foundIdxPair.second; - } - else - { - if (isInvertedTwin) return foundIdxPair.second; - else return foundIdxPair.first; + if (firstOp.IsInvertedTwin()) { + if (isInvertedTwin) + return foundIdxPair.first; + else + return foundIdxPair.second; + } else { + if (isInvertedTwin) + return foundIdxPair.second; + else + return foundIdxPair.first; } } @@ -456,34 +397,30 @@ UsdMayaXformStack::FindOp(const TfToken& opName, bool isInvertedTwin) const return _sharedData->GetOpClassFromIndex(FindOpIndex(opName, isInvertedTwin)); } -const UsdMayaXformStack::IndexPair& -UsdMayaXformStack::FindOpIndexPair(const TfToken& opName) const +const UsdMayaXformStack::IndexPair& UsdMayaXformStack::FindOpIndexPair(const TfToken& opName) const { - static UsdMayaXformStack::IndexPair _NO_MATCH = - std::make_pair(NO_INDEX, NO_INDEX); - UsdMayaXformStack::TokenIndexPairMap::const_iterator foundTokenIdxPair = - _sharedData->m_opNamesToIdxs.find(opName); - if (foundTokenIdxPair == _sharedData->m_opNamesToIdxs.end()) - { + static UsdMayaXformStack::IndexPair _NO_MATCH = std::make_pair(NO_INDEX, NO_INDEX); + UsdMayaXformStack::TokenIndexPairMap::const_iterator foundTokenIdxPair + = _sharedData->m_opNamesToIdxs.find(opName); + if (foundTokenIdxPair == _sharedData->m_opNamesToIdxs.end()) { // Couldn't find the xformop in our stack, abort return _NO_MATCH; } return foundTokenIdxPair->second; } -const UsdMayaXformStack::OpClassPair -UsdMayaXformStack::FindOpPair(const TfToken& opName) const +const UsdMayaXformStack::OpClassPair UsdMayaXformStack::FindOpPair(const TfToken& opName) const { return _sharedData->MakeOpClassPairFromIndexPair(FindOpIndexPair(opName)); } UsdMayaXformStack::OpClassList -UsdMayaXformStack::MatchingSubstack( - const std::vector& xformops) const +UsdMayaXformStack::MatchingSubstack(const std::vector& xformops) const { static const UsdMayaXformStack::OpClassList _NO_MATCH; - if (xformops.empty()) return _NO_MATCH; + if (xformops.empty()) + return _NO_MATCH; UsdMayaXformStack::OpClassList ret; @@ -493,35 +430,29 @@ UsdMayaXformStack::MatchingSubstack( std::vector opNamesFound(GetOps().size(), false); - TF_FOR_ALL(iter, xformops) { + TF_FOR_ALL(iter, xformops) + { const UsdGeomXformOp& xformOp = *iter; - size_t foundOpIdx = NO_INDEX; + size_t foundOpIdx = NO_INDEX; - if(GetNameMatters()) { + if (GetNameMatters()) { // First try the fast attrName lookup... - const auto foundTokenIdxPairIter = - _sharedData->m_attrNamesToIdxs.find(xformOp.GetName()); - if (foundTokenIdxPairIter == _sharedData->m_attrNamesToIdxs.end()) - { + const auto foundTokenIdxPairIter + = _sharedData->m_attrNamesToIdxs.find(xformOp.GetName()); + if (foundTokenIdxPairIter == _sharedData->m_attrNamesToIdxs.end()) { // Couldn't find the xformop in our stack, abort return _NO_MATCH; } // we found a pair of opPtrs... make sure one is // not less than nextOp... - const UsdMayaXformStack::IndexPair& foundIdxPair = - foundTokenIdxPairIter->second; + const UsdMayaXformStack::IndexPair& foundIdxPair = foundTokenIdxPairIter->second; - if (foundIdxPair.first >= nextOpIndex) - { + if (foundIdxPair.first >= nextOpIndex) { foundOpIdx = foundIdxPair.first; - } - else if (foundIdxPair.second >= nextOpIndex && foundIdxPair.second != NO_INDEX) - { + } else if (foundIdxPair.second >= nextOpIndex && foundIdxPair.second != NO_INDEX) { foundOpIdx = foundIdxPair.second; - } - else - { + } else { // The result we found is before an earlier-found op, // so it doesn't match our stack... abort. return _NO_MATCH; @@ -530,26 +461,22 @@ UsdMayaXformStack::MatchingSubstack( assert(foundOpIdx != NO_INDEX); // Now check that the op type matches... - if (!GetOps()[foundOpIdx].IsCompatibleType(xformOp.GetOpType())) - { + if (!GetOps()[foundOpIdx].IsCompatibleType(xformOp.GetOpType())) { return _NO_MATCH; } - } - else { + } else { // If name does not matter, we just iterate through the remaining ops, until // we find one with a matching type... - for(size_t i = nextOpIndex; i < GetSize(); ++i) - { - if (GetOps()[i].IsCompatibleType(xformOp.GetOpType())) - { + for (size_t i = nextOpIndex; i < GetSize(); ++i) { + if (GetOps()[i].IsCompatibleType(xformOp.GetOpType())) { foundOpIdx = i; break; } } - if (foundOpIdx == NO_INDEX) return _NO_MATCH; + if (foundOpIdx == NO_INDEX) + return _NO_MATCH; } - // Ok, we found a match... const UsdMayaXformOpClassification& foundOp = GetOps()[foundOpIdx]; @@ -560,7 +487,8 @@ UsdMayaXformStack::MatchingSubstack( } // check pivot pairs - TF_FOR_ALL(pairIter, GetInversionTwins()) { + TF_FOR_ALL(pairIter, GetInversionTwins()) + { if (opNamesFound[pairIter->first] != opNamesFound[pairIter->second]) { return _NO_MATCH; } @@ -569,21 +497,17 @@ UsdMayaXformStack::MatchingSubstack( return ret; } -UsdMayaXformStack::OpClassList -UsdMayaXformStack::FirstMatchingSubstack( - const std::vector& stacks, - const std::vector& xformops) +UsdMayaXformStack::OpClassList UsdMayaXformStack::FirstMatchingSubstack( + const std::vector& stacks, + const std::vector& xformops) { if (xformops.empty() || stacks.empty()) { return UsdMayaXformStack::OpClassList(); } - for (auto& stackPtr : stacks) - { - std::vector stackOps = \ - stackPtr->MatchingSubstack(xformops); - if (!stackOps.empty()) - { + for (auto& stackPtr : stacks) { + std::vector stackOps = stackPtr->MatchingSubstack(xformops); + if (!stackOps.empty()) { return stackOps; } } @@ -591,108 +515,81 @@ UsdMayaXformStack::FirstMatchingSubstack( return UsdMayaXformStack::OpClassList(); } -const UsdMayaXformStack& -UsdMayaXformStack::MayaStack() +const UsdMayaXformStack& UsdMayaXformStack::MayaStack() { static UsdMayaXformStack mayaStack( - // ops - { - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->translate, - UsdGeomXformOp::TypeTranslate), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->rotatePivotTranslate, - UsdGeomXformOp::TypeTranslate), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->rotatePivot, - UsdGeomXformOp::TypeTranslate), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->rotate, - UsdGeomXformOp::TypeRotateXYZ), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->rotateAxis, - UsdGeomXformOp::TypeRotateXYZ), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->rotatePivot, - UsdGeomXformOp::TypeTranslate, - true /* isInvertedTwin */), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->scalePivotTranslate, - UsdGeomXformOp::TypeTranslate), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->scalePivot, - UsdGeomXformOp::TypeTranslate), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->shear, - UsdGeomXformOp::TypeTransform), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->scale, - UsdGeomXformOp::TypeScale), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->scalePivot, - UsdGeomXformOp::TypeTranslate, - true /* isInvertedTwin */) - }, - - // inversionTwins - { - {2, 5}, - {7, 10}, - }); + // ops + { UsdMayaXformOpClassification( + UsdMayaXformStackTokens->translate, UsdGeomXformOp::TypeTranslate), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->rotatePivotTranslate, UsdGeomXformOp::TypeTranslate), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->rotatePivot, UsdGeomXformOp::TypeTranslate), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->rotate, UsdGeomXformOp::TypeRotateXYZ), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->rotateAxis, UsdGeomXformOp::TypeRotateXYZ), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->rotatePivot, + UsdGeomXformOp::TypeTranslate, + true /* isInvertedTwin */), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->scalePivotTranslate, UsdGeomXformOp::TypeTranslate), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->scalePivot, UsdGeomXformOp::TypeTranslate), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->shear, UsdGeomXformOp::TypeTransform), + UsdMayaXformOpClassification(UsdMayaXformStackTokens->scale, UsdGeomXformOp::TypeScale), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->scalePivot, + UsdGeomXformOp::TypeTranslate, + true /* isInvertedTwin */) }, + + // inversionTwins + { + { 2, 5 }, + { 7, 10 }, + }); return mayaStack; } -const UsdMayaXformStack& -UsdMayaXformStack::CommonStack() +const UsdMayaXformStack& UsdMayaXformStack::CommonStack() { static UsdMayaXformStack commonStack( - // ops - { - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->translate, - UsdGeomXformOp::TypeTranslate), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->pivot, - UsdGeomXformOp::TypeTranslate), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->rotate, - UsdGeomXformOp::TypeRotateXYZ), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->scale, - UsdGeomXformOp::TypeScale), - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->pivot, - UsdGeomXformOp::TypeTranslate, - true /* isInvertedTwin */) - }, - - // inversionTwins - { - {1, 4}, - }); + // ops + { UsdMayaXformOpClassification( + UsdMayaXformStackTokens->translate, UsdGeomXformOp::TypeTranslate), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->pivot, UsdGeomXformOp::TypeTranslate), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->rotate, UsdGeomXformOp::TypeRotateXYZ), + UsdMayaXformOpClassification(UsdMayaXformStackTokens->scale, UsdGeomXformOp::TypeScale), + UsdMayaXformOpClassification( + UsdMayaXformStackTokens->pivot, + UsdGeomXformOp::TypeTranslate, + true /* isInvertedTwin */) }, + + // inversionTwins + { + { 1, 4 }, + }); return commonStack; } -const UsdMayaXformStack& -UsdMayaXformStack::MatrixStack() +const UsdMayaXformStack& UsdMayaXformStack::MatrixStack() { static UsdMayaXformStack matrixStack( - // ops - { - UsdMayaXformOpClassification( - UsdMayaXformStackTokens->transform, - UsdGeomXformOp::TypeTransform) - }, - - // inversionTwins - { - }, - - // nameMatters - false - ); + // ops + { UsdMayaXformOpClassification( + UsdMayaXformStackTokens->transform, UsdGeomXformOp::TypeTransform) }, + + // inversionTwins + {}, + + // nameMatters + false); return matrixStack; } diff --git a/lib/mayaUsd/fileio/utils/xformStack.h b/lib/mayaUsd/fileio/utils/xformStack.h index d9e6586f1a..a9fab73e81 100644 --- a/lib/mayaUsd/fileio/utils/xformStack.h +++ b/lib/mayaUsd/fileio/utils/xformStack.h @@ -15,18 +15,18 @@ #ifndef PXRUSDMAYA_XFORM_STACK_H #define PXRUSDMAYA_XFORM_STACK_H -#include -#include -#include - -#include +#include -#include #include #include +#include #include -#include +#include + +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -36,23 +36,14 @@ PXR_NAMESPACE_OPEN_SCOPE // why it's here /// \hideinitializer -#define PXRUSDMAYA_XFORM_STACK_TOKENS \ - (translate) \ - (rotatePivotTranslate) \ - (rotatePivot) \ - (rotate) \ - (rotateAxis) \ - (scalePivotTranslate) \ - (scalePivot) \ - (shear) \ - (scale) \ - (pivot) \ - (pivotTranslate) \ - (transform) - -TF_DECLARE_PUBLIC_TOKENS(UsdMayaXformStackTokens, - MAYAUSD_CORE_PUBLIC, - PXRUSDMAYA_XFORM_STACK_TOKENS); +#define PXRUSDMAYA_XFORM_STACK_TOKENS \ + (translate)(rotatePivotTranslate)(rotatePivot)(rotate)(rotateAxis)(scalePivotTranslate)( \ + scalePivot)(shear)(scale)(pivot)(pivotTranslate)(transform) + +TF_DECLARE_PUBLIC_TOKENS( + UsdMayaXformStackTokens, + MAYAUSD_CORE_PUBLIC, + PXRUSDMAYA_XFORM_STACK_TOKENS); /// \class UsdMayaXformOpClassification /// \brief Defines a named "class" of xform operation @@ -63,22 +54,24 @@ TF_DECLARE_PUBLIC_TOKENS(UsdMayaXformStackTokens, class UsdMayaXformOpClassification { public: - UsdMayaXformOpClassification(const TfToken &name, - UsdGeomXformOp::Type opType, - bool isInvertedTwin=false); + UsdMayaXformOpClassification( + const TfToken& name, + UsdGeomXformOp::Type opType, + bool isInvertedTwin = false); UsdMayaXformOpClassification(); - static UsdMayaXformOpClassification const & NullInstance(); + static UsdMayaXformOpClassification const& NullInstance(); MAYAUSD_CORE_PUBLIC - TfToken const &GetName() const; + TfToken const& GetName() const; MAYAUSD_CORE_PUBLIC UsdGeomXformOp::Type GetOpType() const; MAYAUSD_CORE_PUBLIC - bool IsInvertedTwin() const;; + bool IsInvertedTwin() const; + ; /// Return True if the given op type is compatible with this /// OpClassification (ie, is the same, or is, say rotateX, when @@ -87,7 +80,7 @@ class UsdMayaXformOpClassification bool IsCompatibleType(UsdGeomXformOp::Type otherType) const; MAYAUSD_CORE_PUBLIC - bool operator ==(const UsdMayaXformOpClassification& other) const; + bool operator==(const UsdMayaXformOpClassification& other) const; MAYAUSD_CORE_PUBLIC bool IsNull() const; @@ -103,7 +96,7 @@ class UsdMayaXformOpClassification // a RefPtr, while having easy-python-wrapping (without overhead // of WeakPtr) typedef TfRefPtr<_Data> _DataRefPtr; - _DataRefPtr _sharedData; + _DataRefPtr _sharedData; }; /// \class UsdMayaXformStack @@ -114,55 +107,39 @@ class UsdMayaXformOpClassification class UsdMayaXformStack { public: - typedef UsdMayaXformOpClassification OpClass; - typedef std::vector OpClassList; + typedef UsdMayaXformOpClassification OpClass; + typedef std::vector OpClassList; typedef std::pair OpClassPair; // Internally, we use indices, because position sometimes matters... // should be safe, since _ops is const. - static constexpr size_t NO_INDEX = std::numeric_limits::max(); + static constexpr size_t NO_INDEX = std::numeric_limits::max(); typedef std::pair IndexPair; - typedef std::unordered_map - TokenIndexPairMap; - typedef std::unordered_map IndexMap; - + typedef std::unordered_map TokenIndexPairMap; + typedef std::unordered_map IndexMap; // Templated because we want it to work with both MEulerRotation::RotationOrder // and MTransformationMatrix::RotationOrder - template + template static RotationOrder RotateOrderFromOpType( - UsdGeomXformOp::Type opType, - RotationOrder defaultRotOrder=RotationOrder::kXYZ) + UsdGeomXformOp::Type opType, + RotationOrder defaultRotOrder = RotationOrder::kXYZ) { - switch(opType) { - case UsdGeomXformOp::TypeRotateXYZ: - return RotationOrder::kXYZ; - break; - case UsdGeomXformOp::TypeRotateXZY: - return RotationOrder::kXZY; - break; - case UsdGeomXformOp::TypeRotateYXZ: - return RotationOrder::kYXZ; - break; - case UsdGeomXformOp::TypeRotateYZX: - return RotationOrder::kYZX; - break; - case UsdGeomXformOp::TypeRotateZXY: - return RotationOrder::kZXY; - break; - case UsdGeomXformOp::TypeRotateZYX: - return RotationOrder::kZYX; - break; - default: - return defaultRotOrder; - break; + switch (opType) { + case UsdGeomXformOp::TypeRotateXYZ: return RotationOrder::kXYZ; break; + case UsdGeomXformOp::TypeRotateXZY: return RotationOrder::kXZY; break; + case UsdGeomXformOp::TypeRotateYXZ: return RotationOrder::kYXZ; break; + case UsdGeomXformOp::TypeRotateYZX: return RotationOrder::kYZX; break; + case UsdGeomXformOp::TypeRotateZXY: return RotationOrder::kZXY; break; + case UsdGeomXformOp::TypeRotateZYX: return RotationOrder::kZYX; break; + default: return defaultRotOrder; break; } } UsdMayaXformStack( - const OpClassList& ops, - const std::vector& inversionTwins, - bool nameMatters=true); + const OpClassList& ops, + const std::vector& inversionTwins, + bool nameMatters = true); // Don't want to accidentally make a copy, since the only instances are supposed // to be static! @@ -170,7 +147,7 @@ class UsdMayaXformStack explicit UsdMayaXformStack(UsdMayaXformStack&& other) = default; MAYAUSD_CORE_PUBLIC - OpClassList const & GetOps() const; + OpClassList const& GetOps() const; MAYAUSD_CORE_PUBLIC const std::vector& GetInversionTwins() const; @@ -179,12 +156,11 @@ class UsdMayaXformStack bool GetNameMatters() const; MAYAUSD_CORE_PUBLIC - UsdMayaXformOpClassification const & operator[] (const size_t index) const; + UsdMayaXformOpClassification const& operator[](const size_t index) const; MAYAUSD_CORE_PUBLIC size_t GetSize() const; - /// \brief Finds the index of the Op Classification with the given name in this stack /// \param opName the name of the operator classification we wish to find /// \param isInvertedTwin the returned op classification object must match @@ -193,7 +169,7 @@ class UsdMayaXformStack /// return Index to the op classification object with the given name (and /// inverted twin state); will be NO_INDEX if no match could be found. MAYAUSD_CORE_PUBLIC - size_t FindOpIndex(const TfToken& opName, bool isInvertedTwin=false) const; + size_t FindOpIndex(const TfToken& opName, bool isInvertedTwin = false) const; /// \brief Finds the Op Classification with the given name in this stack /// \param opName the name of the operator classification we wish to find @@ -205,7 +181,7 @@ class UsdMayaXformStack /// inverted twin state); will be a reference to OpClass::NullInstance /// if no match could be found. MAYAUSD_CORE_PUBLIC - const OpClass& FindOp(const TfToken& opName, bool isInvertedTwin=false) const; + const OpClass& FindOp(const TfToken& opName, bool isInvertedTwin = false) const; /// \brief Finds the indices of Op Classification(s) with the given name in this stack /// \param opName the name of the operator classification we wish to find @@ -241,9 +217,7 @@ class UsdMayaXformStack /// size of this vector will be 0 if no complete match is found, or xformops.size() /// if a complete match is found. MAYAUSD_CORE_PUBLIC - OpClassList - MatchingSubstack( - const std::vector& xformops) const; + OpClassList MatchingSubstack(const std::vector& xformops) const; /// \brief The standard Maya xform stack /// @@ -262,7 +236,6 @@ class UsdMayaXformStack MAYAUSD_CORE_PUBLIC static const UsdMayaXformStack& MayaStack(); - /// \brief The Common API xform stack /// /// Consists of these xform operators: @@ -288,10 +261,9 @@ class UsdMayaXformStack /// Returns the first non-empty result it finds; if all stacks /// return an empty vector, an empty vector is returned. MAYAUSD_CORE_PUBLIC - static OpClassList - FirstMatchingSubstack( - const std::vector& stacks, - const std::vector& xformops); + static OpClassList FirstMatchingSubstack( + const std::vector& stacks, + const std::vector& xformops); private: class _Data; @@ -301,7 +273,7 @@ class UsdMayaXformStack // a RefPtr, while having easy-python-wrapping (without overhead // of WeakPtr) typedef TfRefPtr<_Data> _DataRefPtr; - _DataRefPtr _sharedData; + _DataRefPtr _sharedData; }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/writeJobContext.cpp b/lib/mayaUsd/fileio/writeJobContext.cpp index 8bd7711246..31ff9efa34 100644 --- a/lib/mayaUsd/fileio/writeJobContext.cpp +++ b/lib/mayaUsd/fileio/writeJobContext.cpp @@ -15,28 +15,19 @@ // #include "writeJobContext.h" -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include -#include #include #include #include +#include #include #include #include @@ -44,31 +35,36 @@ #include #include #include +#include #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE namespace { -inline -SdfPath -_GetRootOverridePath(const UsdMayaJobExportArgs& args, const SdfPath& path) +inline SdfPath _GetRootOverridePath(const UsdMayaJobExportArgs& args, const SdfPath& path) { if (!args.usdModelRootOverridePath.IsEmpty() && !path.IsEmpty()) { - return path.ReplacePrefix( - path.GetPrefixes()[0], - args.usdModelRootOverridePath); + return path.ReplacePrefix(path.GetPrefixes()[0], args.usdModelRootOverridePath); } return path; @@ -78,23 +74,21 @@ const SdfPath INSTANCES_SCOPE_PATH("/MayaExportedInstanceSources"); } // anonymous namespace - UsdMayaWriteJobContext::UsdMayaWriteJobContext(const UsdMayaJobExportArgs& args) - : mArgs(args), - _skelBindingsProcessor(new UsdMaya_SkelBindingsProcessor()) + : mArgs(args) + , _skelBindingsProcessor(new UsdMaya_SkelBindingsProcessor()) { } UsdMayaWriteJobContext::~UsdMayaWriteJobContext() = default; -bool -UsdMayaWriteJobContext::IsMergedTransform(const MDagPath& path) const +bool UsdMayaWriteJobContext::IsMergedTransform(const MDagPath& path) const { if (!mArgs.mergeTransformAndShape) { return false; } - MStatus status; + MStatus status; const bool isDagPathValid = path.isValid(&status); if (status != MS::kSuccess || !isDagPathValid) { return false; @@ -134,7 +128,7 @@ UsdMayaWriteJobContext::IsMergedTransform(const MDagPath& path) const // exportable. const unsigned int childCount = path.childCount(); if (childCount != 1) { - MDagPath childDag(path); + MDagPath childDag(path); unsigned int numExportableChildren = 0u; for (unsigned int i = 0u; i < childCount; ++i) { childDag.push(path.child(i)); @@ -151,11 +145,9 @@ UsdMayaWriteJobContext::IsMergedTransform(const MDagPath& path) const return true; } -SdfPath -UsdMayaWriteJobContext::ConvertDagToUsdPath(const MDagPath& dagPath) const +SdfPath UsdMayaWriteJobContext::ConvertDagToUsdPath(const MDagPath& dagPath) const { - SdfPath path = UsdMayaUtil::MDagPathToUsdPath( - dagPath, false, mArgs.stripNamespaces); + SdfPath path = UsdMayaUtil::MDagPathToUsdPath(dagPath, false, mArgs.stripNamespaces); // If we're merging transforms and shapes and this is a shape node, then // write to the parent (transform) path instead. @@ -168,9 +160,7 @@ UsdMayaWriteJobContext::ConvertDagToUsdPath(const MDagPath& dagPath) const if (!mParentScopePath.IsEmpty()) { // Since path is from MDagPathToUsdPath, it will always be // an absolute path... - path = path.ReplacePrefix( - SdfPath::AbsoluteRootPath(), - mParentScopePath); + path = path.ReplacePrefix(SdfPath::AbsoluteRootPath(), mParentScopePath); } return _GetRootOverridePath(mArgs, path); @@ -184,7 +174,7 @@ UsdMayaWriteJobContext::_GetInstanceMasterPaths(const MDagPath& instancePath) co } std::string fullName = instancePath.fullPathName().asChar(); - if (mArgs.stripNamespaces){ + if (mArgs.stripNamespaces) { fullName = UsdMayaUtil::stripNamespaces(fullName); } @@ -196,8 +186,8 @@ UsdMayaWriteJobContext::_GetInstanceMasterPaths(const MDagPath& instancePath) co // This should make a valid path component. fullName = TfMakeValidIdentifier(fullName); - const SdfPath path = _GetRootOverridePath( - mArgs, mInstancesPrim.GetPath().AppendChild(TfToken(fullName))); + const SdfPath path + = _GetRootOverridePath(mArgs, mInstancesPrim.GetPath().AppendChild(TfToken(fullName))); // In Maya, you can directly instance gprims or transforms, but // UsdImaging really wants you to instance at the transform level. @@ -209,8 +199,7 @@ UsdMayaWriteJobContext::_GetInstanceMasterPaths(const MDagPath& instancePath) co if (instancePath.hasFn(MFn::kTransform)) { // Can directly instance transforms. return std::make_pair(path, path); - } - else { + } else { // Cannot directly instance gprims, so this must be exported underneath // a fake scope using the gprim name. MFnDagNode primNode(instancePath.node()); @@ -222,26 +211,24 @@ UsdMayaWriteJobContext::_ExportAndRefPaths UsdMayaWriteJobContext::_FindOrCreateInstanceMaster(const MDagPath& instancePath) { const MObjectHandle handle(instancePath.node()); - const auto it = _objectsToMasterPaths.find(handle); + const auto it = _objectsToMasterPaths.find(handle); if (it != _objectsToMasterPaths.end()) { return it->second; - } - else { + } else { MDagPathArray allInstances; - if (!MDagPath::getAllPathsTo(instancePath.node(), allInstances) || - (allInstances.length() == 0)) { - TF_RUNTIME_ERROR("Could not find any instances for '%s'", - instancePath.fullPathName().asChar()); + if (!MDagPath::getAllPathsTo(instancePath.node(), allInstances) + || (allInstances.length() == 0)) { + TF_RUNTIME_ERROR( + "Could not find any instances for '%s'", instancePath.fullPathName().asChar()); _objectsToMasterPaths[handle] = _ExportAndRefPaths(); return _ExportAndRefPaths(); } // We use the DAG path of the first instance to construct the name of // the master. - const _ExportAndRefPaths masterPaths = - _GetInstanceMasterPaths(allInstances[0]); - const SdfPath& exportPath = masterPaths.first; - const SdfPath& referencePath = masterPaths.second; + const _ExportAndRefPaths masterPaths = _GetInstanceMasterPaths(allInstances[0]); + const SdfPath& exportPath = masterPaths.first; + const SdfPath& referencePath = masterPaths.second; if (exportPath.IsEmpty()) { _objectsToMasterPaths[handle] = _ExportAndRefPaths(); @@ -254,11 +241,11 @@ UsdMayaWriteJobContext::_FindOrCreateInstanceMaster(const MDagPath& instancePath // once). std::vector primWriters; CreatePrimWriterHierarchy( - allInstances[0], - exportPath, - /*forceUninstance*/ true, - /*exportRootVisibility*/ true, - &primWriters); + allInstances[0], + exportPath, + /*forceUninstance*/ true, + /*exportRootVisibility*/ true, + &primWriters); if (primWriters.empty()) { _objectsToMasterPaths[handle] = _ExportAndRefPaths(); @@ -273,8 +260,8 @@ UsdMayaWriteJobContext::_FindOrCreateInstanceMaster(const MDagPath& instancePath // referencePath down to exportPath have empty type names by converting // prims to Xforms if necessary. for (UsdPrim prim = mStage->GetPrimAtPath(exportPath); - prim && prim.GetPath().HasPrefix(referencePath); - prim = prim.GetParent()) { + prim && prim.GetPath().HasPrefix(referencePath); + prim = prim.GetParent()) { if (prim.GetTypeName().IsEmpty()) { UsdGeomXform::Define(mStage, prim.GetPath()); } @@ -282,29 +269,25 @@ UsdMayaWriteJobContext::_FindOrCreateInstanceMaster(const MDagPath& instancePath _objectsToMasterPaths[handle] = masterPaths; _objectsToMasterWriters[handle] = std::make_pair( - mMayaPrimWriterList.size(), - mMayaPrimWriterList.size() + primWriters.size()); + mMayaPrimWriterList.size(), mMayaPrimWriterList.size() + primWriters.size()); mMayaPrimWriterList.insert( - mMayaPrimWriterList.end(), - primWriters.begin(), - primWriters.end()); + mMayaPrimWriterList.end(), primWriters.begin(), primWriters.end()); return masterPaths; } } -bool -UsdMayaWriteJobContext::_GetInstanceMasterPrimWriters( - const MDagPath& instancePath, +bool UsdMayaWriteJobContext::_GetInstanceMasterPrimWriters( + const MDagPath& instancePath, std::vector::const_iterator* begin, std::vector::const_iterator* end) const { const MObjectHandle handle(instancePath.node()); - const auto it = _objectsToMasterWriters.find(handle); + const auto it = _objectsToMasterWriters.find(handle); if (it != _objectsToMasterWriters.end()) { std::pair range = it->second; - if (range.first < mMayaPrimWriterList.size() && - range.second <= mMayaPrimWriterList.size()) { + if (range.first < mMayaPrimWriterList.size() + && range.second <= mMayaPrimWriterList.size()) { *begin = mMayaPrimWriterList.cbegin() + range.first; *end = mMayaPrimWriterList.cbegin() + range.second; return true; @@ -314,8 +297,7 @@ UsdMayaWriteJobContext::_GetInstanceMasterPrimWriters( return false; } -bool -UsdMayaWriteJobContext::_NeedToTraverse(const MDagPath& curDag) const +bool UsdMayaWriteJobContext::_NeedToTraverse(const MDagPath& curDag) const { MObject ob = curDag.node(); // NOTE: Already skipping all intermediate objects @@ -337,10 +319,8 @@ UsdMayaWriteJobContext::_NeedToTraverse(const MDagPath& curDag) const if (!mArgs.exportDefaultCameras && ob.hasFn(MFn::kTransform) && curDag.length() == 1) { // Ignore transforms of default cameras MString fullPathName = curDag.fullPathName(); - if (fullPathName == "|persp" || - fullPathName == "|top" || - fullPathName == "|front" || - fullPathName == "|side") { + if (fullPathName == "|persp" || fullPathName == "|top" || fullPathName == "|front" + || fullPathName == "|side") { return false; } } @@ -348,7 +328,7 @@ UsdMayaWriteJobContext::_NeedToTraverse(const MDagPath& curDag) const if (!mArgs.GetFilteredTypeIds().empty()) { MFnDependencyNode mfnNode(ob); if (mArgs.GetFilteredTypeIds().find(mfnNode.typeId().id()) - != mArgs.GetFilteredTypeIds().end()) { + != mArgs.GetFilteredTypeIds().end()) { return false; } } @@ -356,16 +336,14 @@ UsdMayaWriteJobContext::_NeedToTraverse(const MDagPath& curDag) const return true; } -bool -UsdMayaWriteJobContext::_OpenFile(const std::string& filename, bool append) +bool UsdMayaWriteJobContext::_OpenFile(const std::string& filename, bool append) { - SdfLayerRefPtr layer; + SdfLayerRefPtr layer; ArResolverContext resolverCtx = ArGetResolver().GetCurrentContext(); if (append) { layer = SdfLayer::FindOrOpen(filename); if (!layer) { - TF_RUNTIME_ERROR( - "Failed to open layer '%s' for append", filename.c_str()); + TF_RUNTIME_ERROR("Failed to open layer '%s' for append", filename.c_str()); return false; } } else { @@ -378,12 +356,10 @@ UsdMayaWriteJobContext::_OpenFile(const std::string& filename, bool append) UsdMayaStageCache::EraseAllStagesWithRootLayerPath(filename); if (SdfLayerRefPtr existingLayer = SdfLayer::Find(filename)) { - TF_STATUS( - "Writing to already-open layer '%s'", filename.c_str()); + TF_STATUS("Writing to already-open layer '%s'", filename.c_str()); existingLayer->Clear(); layer = existingLayer; - } - else { + } else { SdfLayer::FileFormatArguments args; args[UsdUsdFileFormatTokens->FormatArg] = mArgs.defaultUSDFormat.GetString(); #if USD_VERSION_NUM > 2008 @@ -393,8 +369,7 @@ UsdMayaWriteJobContext::_OpenFile(const std::string& filename, bool append) #endif } if (!layer) { - TF_RUNTIME_ERROR( - "Failed to create layer '%s'", filename.c_str()); + TF_RUNTIME_ERROR("Failed to create layer '%s'", filename.c_str()); return false; } } @@ -412,8 +387,8 @@ UsdMayaWriteJobContext::_OpenFile(const std::string& filename, bool append) // usdModelRootOverridePath, then IT will take the name of our parent // scope, and will be created when we writ out the model variants if (mArgs.usdModelRootOverridePath.IsEmpty()) { - mParentScopePath = UsdGeomScope::Define(mStage, - mParentScopePath).GetPrim().GetPrimPath(); + mParentScopePath + = UsdGeomScope::Define(mStage, mParentScopePath).GetPrim().GetPrimPath(); } } @@ -424,8 +399,7 @@ UsdMayaWriteJobContext::_OpenFile(const std::string& filename, bool append) return true; } -bool -UsdMayaWriteJobContext::_PostProcess() +bool UsdMayaWriteJobContext::_PostProcess() { if (mArgs.exportInstances) { if (_objectsToMasterWriters.empty()) { @@ -438,26 +412,24 @@ UsdMayaWriteJobContext::_PostProcess() // We need to drop down to the Sdf level to reorder root prims. // (Note that we want to change the actual order in the layer, and // not just author a reorder statement.) - const SdfPath instancesPrimPath = mInstancesPrim.GetPrimPath(); + const SdfPath instancesPrimPath = mInstancesPrim.GetPrimPath(); SdfPrimSpecHandleVector newRootPrims; - SdfPrimSpecHandle instancesPrimSpec; - for (const SdfPrimSpecHandle& rootPrimSpec : - mStage->GetRootLayer()->GetRootPrims()) { + SdfPrimSpecHandle instancesPrimSpec; + for (const SdfPrimSpecHandle& rootPrimSpec : mStage->GetRootLayer()->GetRootPrims()) { if (rootPrimSpec->GetPath() == instancesPrimPath) { instancesPrimSpec = rootPrimSpec; - } - else { + } else { newRootPrims.push_back(rootPrimSpec); } } if (instancesPrimSpec) { newRootPrims.push_back(instancesPrimSpec); mStage->GetRootLayer()->SetRootPrims(newRootPrims); - } - else { - TF_CODING_ERROR("Expected to find <%s> in the root prims; " - "was it moved or removed?", - instancesPrimPath.GetText()); + } else { + TF_CODING_ERROR( + "Expected to find <%s> in the root prims; " + "was it moved or removed?", + instancesPrimPath.GetText()); } } } @@ -469,16 +441,14 @@ UsdMayaWriteJobContext::_PostProcess() return true; } -UsdMayaPrimWriterSharedPtr -UsdMayaWriteJobContext::CreatePrimWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - const bool forceUninstance) +UsdMayaPrimWriterSharedPtr UsdMayaWriteJobContext::CreatePrimWriter( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + const bool forceUninstance) { SdfPath writePath = usdPath; - const MDagPath dagPath = - UsdMayaUtil::getDagPath(depNodeFn, /* reportError = */ false); + const MDagPath dagPath = UsdMayaUtil::getDagPath(depNodeFn, /* reportError = */ false); if (!dagPath.isValid()) { // This must be a DG node. usdPath must be supplied for DG nodes. if (writePath.IsEmpty()) { @@ -498,13 +468,10 @@ UsdMayaWriteJobContext::CreatePrimWriter( } const MFnDagNode dagNodeFn(dagPath); - const bool instanced = dagNodeFn.isInstanced(/* indirect = */ false); + const bool instanced = dagNodeFn.isInstanced(/* indirect = */ false); if (mArgs.exportInstances && instanced && !forceUninstance) { // Deal with instances -- we use a special internal writer for them. - return std::make_shared( - dagNodeFn, - writePath, - *this); + return std::make_shared(dagNodeFn, writePath, *this); } } @@ -512,12 +479,8 @@ UsdMayaWriteJobContext::CreatePrimWriter( // a writer plugin. We search through the node's type ancestors, working // backwards until we find a prim writer plugin. const std::string mayaTypeName(depNodeFn.typeName().asChar()); - if (UsdMayaPrimWriterRegistry::WriterFactoryFn primWriterFactory = - _FindWriter(mayaTypeName)) { - if (UsdMayaPrimWriterSharedPtr primPtr = primWriterFactory( - depNodeFn, - writePath, - *this)) { + if (UsdMayaPrimWriterRegistry::WriterFactoryFn primWriterFactory = _FindWriter(mayaTypeName)) { + if (UsdMayaPrimWriterSharedPtr primPtr = primWriterFactory(depNodeFn, writePath, *this)) { // We found a registered user prim writer that handles this node // type, so return now. return primPtr; @@ -538,11 +501,11 @@ UsdMayaWriteJobContext::_FindWriter(const std::string& mayaNodeType) } // Search up the ancestor hierarchy for a writer plugin. - const std::vector ancestorTypes = - UsdMayaUtil::GetAllAncestorMayaNodeTypes(mayaNodeType); + const std::vector ancestorTypes + = UsdMayaUtil::GetAllAncestorMayaNodeTypes(mayaNodeType); for (auto i = ancestorTypes.rbegin(); i != ancestorTypes.rend(); ++i) { - if (UsdMayaPrimWriterRegistry::WriterFactoryFn primWriterFactory = - UsdMayaPrimWriterRegistry::Find(*i)) { + if (UsdMayaPrimWriterRegistry::WriterFactoryFn primWriterFactory + = UsdMayaPrimWriterRegistry::Find(*i)) { mWriterFactoryCache[mayaNodeType] = primWriterFactory; return primWriterFactory; } @@ -553,13 +516,12 @@ UsdMayaWriteJobContext::_FindWriter(const std::string& mayaNodeType) return nullptr; } -void -UsdMayaWriteJobContext::CreatePrimWriterHierarchy( - const MDagPath& rootDag, - const SdfPath& rootUsdPath, - const bool forceUninstance, - const bool exportRootVisibility, - std::vector* primWritersOut) +void UsdMayaWriteJobContext::CreatePrimWriterHierarchy( + const MDagPath& rootDag, + const SdfPath& rootUsdPath, + const bool forceUninstance, + const bool exportRootVisibility, + std::vector* primWritersOut) { if (!primWritersOut) { TF_CODING_ERROR("primWritersOut is null"); @@ -583,20 +545,17 @@ UsdMayaWriteJobContext::CreatePrimWriterHierarchy( // The USD path of this prototype descendant prim if it were exported // at its current Maya location. - const SdfPath curComputedUsdPath = - this->ConvertDagToUsdPath(curDagPath); + const SdfPath curComputedUsdPath = this->ConvertDagToUsdPath(curDagPath); SdfPath curActualUsdPath; if (rootUsdPath.IsEmpty()) { // Just use the actual computed current path. curActualUsdPath = curComputedUsdPath; - } - else { + } else { // Compute the current prim's relative path w/r/t the prototype // root, and use this to re-anchor it under the USD stage location // where we want to write out the prototype. - const SdfPath curRelPath = curComputedUsdPath.MakeRelativePath( - rootComputedUsdPath); + const SdfPath curRelPath = curComputedUsdPath.MakeRelativePath(rootComputedUsdPath); curActualUsdPath = rootUsdPath.AppendPath(curRelPath); } @@ -606,9 +565,7 @@ UsdMayaWriteJobContext::CreatePrimWriterHierarchy( // to descendant nodes (i.e. nested instancing will always occur). // Its purpose is to allow us to do the actual write of the master. UsdMayaPrimWriterSharedPtr writer = this->CreatePrimWriter( - dagNodeFn, - curActualUsdPath, - curDagPath == rootDag ? forceUninstance : false); + dagNodeFn, curActualUsdPath, curDagPath == rootDag ? forceUninstance : false); if (!writer) { continue; } @@ -625,8 +582,7 @@ UsdMayaWriteJobContext::CreatePrimWriterHierarchy( } } -void -UsdMayaWriteJobContext::MarkSkelBindings( +void UsdMayaWriteJobContext::MarkSkelBindings( const SdfPath& path, const SdfPath& skelPath, const TfToken& config) @@ -634,5 +590,4 @@ UsdMayaWriteJobContext::MarkSkelBindings( _skelBindingsProcessor->MarkBindings(path, skelPath, config); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/fileio/writeJobContext.h b/lib/mayaUsd/fileio/writeJobContext.h index 77dfd9ee46..f04c9659eb 100644 --- a/lib/mayaUsd/fileio/writeJobContext.h +++ b/lib/mayaUsd/fileio/writeJobContext.h @@ -16,19 +16,19 @@ #ifndef PXRUSDMAYA_WRITE_JOB_CONTEXT_H #define PXRUSDMAYA_WRITE_JOB_CONTEXT_H -#include +#include +#include +#include +#include + +#include +#include #include #include #include -#include -#include - -#include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -53,15 +53,9 @@ class UsdMayaWriteJobContext ~UsdMayaWriteJobContext(); public: - const UsdMayaJobExportArgs& GetArgs() const - { - return mArgs; - } + const UsdMayaJobExportArgs& GetArgs() const { return mArgs; } - const UsdStageRefPtr& GetUsdStage() const - { - return mStage; - } + const UsdStageRefPtr& GetUsdStage() const { return mStage; } /// Whether we will merge the transform at \p path with its single /// exportable child shape, given its hierarchy and the current path @@ -95,9 +89,9 @@ class UsdMayaWriteJobContext /// writer in order to author its USD attributes. MAYAUSD_CORE_PUBLIC UsdMayaPrimWriterSharedPtr CreatePrimWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath = SdfPath(), - const bool forceUninstance = false); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath = SdfPath(), + const bool forceUninstance = false); /// Creates all prim writers necessary for writing the Maya node hierarchy /// rooted at \p rootDag to the USD namespace hierarchy rooted at @@ -116,10 +110,10 @@ class UsdMayaWriteJobContext /// writers in order to author their USD attributes. MAYAUSD_CORE_PUBLIC void CreatePrimWriterHierarchy( - const MDagPath& rootDag, - const SdfPath& rootUsdPath, - const bool forceUninstance, - const bool exportRootVisibility, + const MDagPath& rootDag, + const SdfPath& rootUsdPath, + const bool forceUninstance, + const bool exportRootVisibility, std::vector* primWritersOut); /// Mark \p path as containing bindings utilizing the skeleton @@ -131,10 +125,7 @@ class UsdMayaWriteJobContext /// UsdMayaJobExportArgsTokens->none is not valid for \p config; it will /// mark an invalid binding. MAYAUSD_CORE_PUBLIC - void MarkSkelBindings( - const SdfPath& path, - const SdfPath& skelPath, - const TfToken& config); + void MarkSkelBindings(const SdfPath& path, const SdfPath& skelPath, const TfToken& config); protected: /// Opens the stage with the given \p filename for writing. @@ -169,14 +160,12 @@ class UsdMayaWriteJobContext /// In most cases, the two paths are the same, but is \p instancePath /// represents a directly-instanced gprim, the two paths may be different. /// The reference path is _always_ a prefix of the export path. - _ExportAndRefPaths _GetInstanceMasterPaths( - const MDagPath& instancePath) const; + _ExportAndRefPaths _GetInstanceMasterPaths(const MDagPath& instancePath) const; /// If the instance master for \p instancePath already exists, returns its /// USD path pair. Otherwise, creates the instance master (including its /// descendants) and returns the new USD path pair. - _ExportAndRefPaths _FindOrCreateInstanceMaster( - const MDagPath& instancePath); + _ExportAndRefPaths _FindOrCreateInstanceMaster(const MDagPath& instancePath); /// Gets the existing prim writers for the instance master of /// \p instancePath if that instance master has already been created. @@ -184,16 +173,17 @@ class UsdMayaWriteJobContext /// requested prim writers are in the range [\p begin, \p end). /// Otherwise, returns \c false and does nothing with the iterators. bool _GetInstanceMasterPrimWriters( - const MDagPath& instancePath, - std::vector::const_iterator* begin, - std::vector::const_iterator* end) const; + const MDagPath& instancePath, + std::vector::const_iterator* begin, + std::vector::const_iterator* end) const; /// Prim writer search with ancestor type resolution behavior. - UsdMayaPrimWriterRegistry::WriterFactoryFn _FindWriter( - const std::string& mayaNodeType); + UsdMayaPrimWriterRegistry::WriterFactoryFn _FindWriter(const std::string& mayaNodeType); - struct MObjectHandleComp { - bool operator()(const MObjectHandle& rhs, const MObjectHandle& lhs) const { + struct MObjectHandleComp + { + bool operator()(const MObjectHandle& rhs, const MObjectHandle& lhs) const + { return rhs.hashCode() < lhs.hashCode(); } }; @@ -201,16 +191,14 @@ class UsdMayaWriteJobContext /// Mapping of Maya object handles to the corresponding instance master's /// USD export path and reference path. A pair of empty USD paths means that /// we previously tried, but failed, to create the instance master. - std::map - _objectsToMasterPaths; + std::map _objectsToMasterPaths; // Mapping of Maya object handles to the indices of the instance master's // prim writers in mMayaPrimWriterList. An instance master has a prim writer // for each node in its hierarchy; thus, the value represents an interval // of indices [first, last) in mMayaPrimWriterList. This avoids having to // manage two containers of shared pointers. - std::map, MObjectHandleComp> - _objectsToMasterWriters; + std::map, MObjectHandleComp> _objectsToMasterWriters; UsdPrim mInstancesPrim; SdfPath mParentScopePath; @@ -221,16 +209,13 @@ class UsdMayaWriteJobContext // taking into account Maya's type hierarchy (note that this means that // some types not resolved by the UsdMayaPrimWriterRegistry will get // resolved in this map). - std::map - mWriterFactoryCache; + std::map mWriterFactoryCache; // UsdMaya_InstancedNodeWriter is in a separate file, but functions as // an internal helper for UsdMayaWriteJobContext. friend class UsdMaya_InstancedNodeWriter; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/listeners/notice.cpp b/lib/mayaUsd/listeners/notice.cpp index 6f7d433113..0f0709e07a 100644 --- a/lib/mayaUsd/listeners/notice.cpp +++ b/lib/mayaUsd/listeners/notice.cpp @@ -13,12 +13,12 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include +#include #include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -29,9 +29,7 @@ namespace { // to be removed. static int _newOrOpenRegistrationCount = 0; -static -void -_OnMayaNewOrOpenSceneCallback(void* /*clientData*/) +static void _OnMayaNewOrOpenSceneCallback(void* /*clientData*/) { // kBeforeFileRead messages are emitted when importing/referencing files, // which we don't consider a "scene reset". @@ -44,19 +42,15 @@ _OnMayaNewOrOpenSceneCallback(void* /*clientData*/) } // anonymous namespace -TF_INSTANTIATE_TYPE(UsdMayaSceneResetNotice, - TfType::CONCRETE, TF_1_PARENT(TfNotice)); +TF_INSTANTIATE_TYPE(UsdMayaSceneResetNotice, TfType::CONCRETE, TF_1_PARENT(TfNotice)); MCallbackId UsdMayaSceneResetNotice::_afterNewCallbackId = 0; MCallbackId UsdMayaSceneResetNotice::_beforeFileReadCallbackId = 0; -UsdMayaSceneResetNotice::UsdMayaSceneResetNotice() -{ -} +UsdMayaSceneResetNotice::UsdMayaSceneResetNotice() { } /* static */ -void -UsdMayaSceneResetNotice::InstallListener() +void UsdMayaSceneResetNotice::InstallListener() { if (_newOrOpenRegistrationCount++ > 0) { return; @@ -72,26 +66,23 @@ UsdMayaSceneResetNotice::InstallListener() // file is imported or referenced, so we check for that and do *not* send // a scene reset notice. if (_afterNewCallbackId == 0) { - _afterNewCallbackId = - MSceneMessage::addCallback(MSceneMessage::kAfterNew, - _OnMayaNewOrOpenSceneCallback); + _afterNewCallbackId + = MSceneMessage::addCallback(MSceneMessage::kAfterNew, _OnMayaNewOrOpenSceneCallback); } if (_beforeFileReadCallbackId == 0) { - _beforeFileReadCallbackId = - MSceneMessage::addCallback(MSceneMessage::kBeforeFileRead, - _OnMayaNewOrOpenSceneCallback); + _beforeFileReadCallbackId = MSceneMessage::addCallback( + MSceneMessage::kBeforeFileRead, _OnMayaNewOrOpenSceneCallback); } } /* static */ -void -UsdMayaSceneResetNotice::RemoveListener() +void UsdMayaSceneResetNotice::RemoveListener() { if (_newOrOpenRegistrationCount-- > 1) { return; } - + if (_afterNewCallbackId != 0) { MMessage::removeCallback(_afterNewCallbackId); } @@ -101,47 +92,40 @@ UsdMayaSceneResetNotice::RemoveListener() } } - UsdMaya_AssemblyInstancerNoticeBase::UsdMaya_AssemblyInstancerNoticeBase( - const MObject& assembly, - const MObject& instancer) - : _assembly(assembly), _instancer(instancer) -{ -} - -MObject -UsdMaya_AssemblyInstancerNoticeBase::GetAssembly() const + const MObject& assembly, + const MObject& instancer) + : _assembly(assembly) + , _instancer(instancer) { - return _assembly; } -MObject -UsdMaya_AssemblyInstancerNoticeBase::GetInstancer() const -{ - return _instancer; -} +MObject UsdMaya_AssemblyInstancerNoticeBase::GetAssembly() const { return _assembly; } +MObject UsdMaya_AssemblyInstancerNoticeBase::GetInstancer() const { return _instancer; } -TF_INSTANTIATE_TYPE(UsdMayaAssemblyConnectedToInstancerNotice, - TfType::CONCRETE, TF_1_PARENT(TfNotice)); +TF_INSTANTIATE_TYPE( + UsdMayaAssemblyConnectedToInstancerNotice, + TfType::CONCRETE, + TF_1_PARENT(TfNotice)); UsdMayaAssemblyConnectedToInstancerNotice::UsdMayaAssemblyConnectedToInstancerNotice( - const MObject& assembly, - const MObject& instancer) - : UsdMaya_AssemblyInstancerNoticeBase(assembly, instancer) + const MObject& assembly, + const MObject& instancer) + : UsdMaya_AssemblyInstancerNoticeBase(assembly, instancer) { } - -TF_INSTANTIATE_TYPE(UsdMayaAssemblyDisconnectedFromInstancerNotice, - TfType::CONCRETE, TF_1_PARENT(TfNotice)); +TF_INSTANTIATE_TYPE( + UsdMayaAssemblyDisconnectedFromInstancerNotice, + TfType::CONCRETE, + TF_1_PARENT(TfNotice)); UsdMayaAssemblyDisconnectedFromInstancerNotice::UsdMayaAssemblyDisconnectedFromInstancerNotice( - const MObject& assembly, - const MObject& instancer) - : UsdMaya_AssemblyInstancerNoticeBase(assembly, instancer) + const MObject& assembly, + const MObject& instancer) + : UsdMaya_AssemblyInstancerNoticeBase(assembly, instancer) { } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/listeners/notice.h b/lib/mayaUsd/listeners/notice.h index 1c02980878..d788ccbd5e 100644 --- a/lib/mayaUsd/listeners/notice.h +++ b/lib/mayaUsd/listeners/notice.h @@ -16,12 +16,12 @@ #ifndef USDMAYA_NOTICE_H #define USDMAYA_NOTICE_H -#include -#include +#include #include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -62,9 +62,7 @@ class UsdMaya_AssemblyInstancerNoticeBase : public TfNotice protected: MAYAUSD_CORE_PUBLIC - UsdMaya_AssemblyInstancerNoticeBase( - const MObject& assembly, - const MObject& instancer); + UsdMaya_AssemblyInstancerNoticeBase(const MObject& assembly, const MObject& instancer); private: MObject _assembly; @@ -73,26 +71,22 @@ class UsdMaya_AssemblyInstancerNoticeBase : public TfNotice /// Notice sent when any reference assembly is connected as a prototype of a /// native Maya instancer. -class UsdMayaAssemblyConnectedToInstancerNotice - : public UsdMaya_AssemblyInstancerNoticeBase +class UsdMayaAssemblyConnectedToInstancerNotice : public UsdMaya_AssemblyInstancerNoticeBase { public: MAYAUSD_CORE_PUBLIC - UsdMayaAssemblyConnectedToInstancerNotice( - const MObject& assembly, - const MObject& instancer); + UsdMayaAssemblyConnectedToInstancerNotice(const MObject& assembly, const MObject& instancer); }; /// Notice sent when any reference assembly was previously a prototype of a /// native Maya instancer but has now been disconnected from it. -class UsdMayaAssemblyDisconnectedFromInstancerNotice - : public UsdMaya_AssemblyInstancerNoticeBase +class UsdMayaAssemblyDisconnectedFromInstancerNotice : public UsdMaya_AssemblyInstancerNoticeBase { public: MAYAUSD_CORE_PUBLIC UsdMayaAssemblyDisconnectedFromInstancerNotice( - const MObject& assembly, - const MObject& instancer); + const MObject& assembly, + const MObject& instancer); }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/listeners/proxyShapeNotice.h b/lib/mayaUsd/listeners/proxyShapeNotice.h index f36dea5859..bc233aec84 100644 --- a/lib/mayaUsd/listeners/proxyShapeNotice.h +++ b/lib/mayaUsd/listeners/proxyShapeNotice.h @@ -16,14 +16,14 @@ #ifndef MAYAUSD_PROXYSTAGE_NOTICE_H #define MAYAUSD_PROXYSTAGE_NOTICE_H -#include - -#include +#include #include #include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE diff --git a/lib/mayaUsd/listeners/stageNoticeListener.cpp b/lib/mayaUsd/listeners/stageNoticeListener.cpp index 6bad1fbf7c..9dd595c8e3 100644 --- a/lib/mayaUsd/listeners/stageNoticeListener.cpp +++ b/lib/mayaUsd/listeners/stageNoticeListener.cpp @@ -33,25 +33,22 @@ UsdMayaStageNoticeListener::~UsdMayaStageNoticeListener() } } -void -UsdMayaStageNoticeListener::SetStage(const UsdStageWeakPtr& stage) +void UsdMayaStageNoticeListener::SetStage(const UsdStageWeakPtr& stage) { _stage = stage; _UpdateStageContentsChangedRegistration(); } -void -UsdMayaStageNoticeListener::SetStageContentsChangedCallback( - const StageContentsChangedCallback& callback) +void UsdMayaStageNoticeListener::SetStageContentsChangedCallback( + const StageContentsChangedCallback& callback) { _stageContentsChangedCallback = callback; _UpdateStageContentsChangedRegistration(); } -void -UsdMayaStageNoticeListener::SetStageObjectsChangedCallback( +void UsdMayaStageNoticeListener::SetStageObjectsChangedCallback( const StageObjectsChangedCallback& callback) { _stageObjectsChangedCallback = callback; @@ -59,16 +56,13 @@ UsdMayaStageNoticeListener::SetStageObjectsChangedCallback( _UpdateStageContentsChangedRegistration(); } -void -UsdMayaStageNoticeListener::_UpdateStageContentsChangedRegistration() +void UsdMayaStageNoticeListener::_UpdateStageContentsChangedRegistration() { if (_stage && _stageContentsChangedCallback) { // Register for notices if we're not already listening. if (!_stageContentsChangedKey.IsValid()) { - _stageContentsChangedKey = - TfNotice::Register( - TfCreateWeakPtr(this), - &UsdMayaStageNoticeListener::_OnStageContentsChanged); + _stageContentsChangedKey = TfNotice::Register( + TfCreateWeakPtr(this), &UsdMayaStageNoticeListener::_OnStageContentsChanged); } } else { // Either the stage or the callback is invalid, so stop listening for @@ -81,14 +75,10 @@ UsdMayaStageNoticeListener::_UpdateStageContentsChangedRegistration() if (_stage && _stageObjectsChangedCallback) { // Register for notices if we're not already listening. if (!_stageObjectsChangedKey.IsValid()) { - _stageObjectsChangedKey = - TfNotice::Register( - TfCreateWeakPtr(this), - &UsdMayaStageNoticeListener::_OnStageObjectsChanged, - _stage); + _stageObjectsChangedKey = TfNotice::Register( + TfCreateWeakPtr(this), &UsdMayaStageNoticeListener::_OnStageObjectsChanged, _stage); } - } - else { + } else { // Either the stage or the callback is invalid, so stop listening for // notices. if (_stageObjectsChangedKey.IsValid()) { @@ -97,18 +87,17 @@ UsdMayaStageNoticeListener::_UpdateStageContentsChangedRegistration() } } -void -UsdMayaStageNoticeListener::_OnStageContentsChanged( - const UsdNotice::StageContentsChanged& notice) const +void UsdMayaStageNoticeListener::_OnStageContentsChanged( + const UsdNotice::StageContentsChanged& notice) const { if (notice.GetStage() == _stage && _stageContentsChangedCallback) { _stageContentsChangedCallback(notice); } } -void -UsdMayaStageNoticeListener::_OnStageObjectsChanged( - const UsdNotice::ObjectsChanged& notice, const UsdStageWeakPtr& sender) const +void UsdMayaStageNoticeListener::_OnStageObjectsChanged( + const UsdNotice::ObjectsChanged& notice, + const UsdStageWeakPtr& sender) const { if (notice.GetStage() == _stage && _stageObjectsChangedCallback) { _stageObjectsChangedCallback(notice); diff --git a/lib/mayaUsd/listeners/stageNoticeListener.h b/lib/mayaUsd/listeners/stageNoticeListener.h index 574cc5c502..73d88bc968 100644 --- a/lib/mayaUsd/listeners/stageNoticeListener.h +++ b/lib/mayaUsd/listeners/stageNoticeListener.h @@ -16,15 +16,15 @@ #ifndef PXRUSDMAYA_STAGE_NOTICE_LISTENER_H #define PXRUSDMAYA_STAGE_NOTICE_LISTENER_H -#include +#include -#include #include #include +#include #include #include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -36,55 +36,53 @@ PXR_NAMESPACE_OPEN_SCOPE /// stage. class UsdMayaStageNoticeListener : public TfWeakBase { - public: - MAYAUSD_CORE_PUBLIC - UsdMayaStageNoticeListener() = default; - - MAYAUSD_CORE_PUBLIC - virtual ~UsdMayaStageNoticeListener(); - - /// Set the USD stage for which this instance will listen for notices. - MAYAUSD_CORE_PUBLIC - void SetStage(const UsdStageWeakPtr& stage); - - /// Callback type for stage notices. - using StageContentsChangedCallback = std::function; - using StageObjectsChangedCallback = std::function; - - /// Sets the callback to be invoked when the listener receives a - /// StageContentsChanged notice. - MAYAUSD_CORE_PUBLIC - void SetStageContentsChangedCallback( - const StageContentsChangedCallback& callback); - - /// Sets the callback to be invoked when the listener receives a - /// ObjectsChanged notice. - MAYAUSD_CORE_PUBLIC - void SetStageObjectsChangedCallback( - const StageObjectsChangedCallback& callback); - - private: - UsdMayaStageNoticeListener(const UsdMayaStageNoticeListener&) = delete; - UsdMayaStageNoticeListener& operator=(const UsdMayaStageNoticeListener&) = delete; - - UsdStageWeakPtr _stage; - - /// Handling for UsdNotices - TfNotice::Key _stageContentsChangedKey{}; - StageContentsChangedCallback _stageContentsChangedCallback{}; - - TfNotice::Key _stageObjectsChangedKey{}; - StageObjectsChangedCallback _stageObjectsChangedCallback{}; - - void _UpdateStageContentsChangedRegistration(); - void _OnStageContentsChanged( - const UsdNotice::StageContentsChanged& notice) const; - void _OnStageObjectsChanged( - const UsdNotice::ObjectsChanged& notice, const UsdStageWeakPtr& sender) const; +public: + MAYAUSD_CORE_PUBLIC + UsdMayaStageNoticeListener() = default; + + MAYAUSD_CORE_PUBLIC + virtual ~UsdMayaStageNoticeListener(); + + /// Set the USD stage for which this instance will listen for notices. + MAYAUSD_CORE_PUBLIC + void SetStage(const UsdStageWeakPtr& stage); + + /// Callback type for stage notices. + using StageContentsChangedCallback + = std::function; + using StageObjectsChangedCallback + = std::function; + + /// Sets the callback to be invoked when the listener receives a + /// StageContentsChanged notice. + MAYAUSD_CORE_PUBLIC + void SetStageContentsChangedCallback(const StageContentsChangedCallback& callback); + + /// Sets the callback to be invoked when the listener receives a + /// ObjectsChanged notice. + MAYAUSD_CORE_PUBLIC + void SetStageObjectsChangedCallback(const StageObjectsChangedCallback& callback); + +private: + UsdMayaStageNoticeListener(const UsdMayaStageNoticeListener&) = delete; + UsdMayaStageNoticeListener& operator=(const UsdMayaStageNoticeListener&) = delete; + + UsdStageWeakPtr _stage; + + /// Handling for UsdNotices + TfNotice::Key _stageContentsChangedKey {}; + StageContentsChangedCallback _stageContentsChangedCallback {}; + + TfNotice::Key _stageObjectsChangedKey {}; + StageObjectsChangedCallback _stageObjectsChangedCallback {}; + + void _UpdateStageContentsChangedRegistration(); + void _OnStageContentsChanged(const UsdNotice::StageContentsChanged& notice) const; + void _OnStageObjectsChanged( + const UsdNotice::ObjectsChanged& notice, + const UsdStageWeakPtr& sender) const; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/nodes/hdImagingShape.cpp b/lib/mayaUsd/nodes/hdImagingShape.cpp index ab36e6251c..c2fea657ef 100644 --- a/lib/mayaUsd/nodes/hdImagingShape.cpp +++ b/lib/mayaUsd/nodes/hdImagingShape.cpp @@ -15,12 +15,20 @@ // #include "hdImagingShape.h" -#include +#include +#include +#include + +#include +#include +#include +#include +#include #include +#include #include #include -#include #include #include #include @@ -39,15 +47,7 @@ #include #include -#include -#include -#include -#include -#include - -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -70,13 +70,10 @@ TF_DEFINE_ENV_SETTING( false, "Enables area selection of objects occluded in depth"); - -TF_DEFINE_PUBLIC_TOKENS(PxrMayaHdImagingShapeTokens, - PXRUSDMAYA_HD_IMAGING_SHAPE_TOKENS); +TF_DEFINE_PUBLIC_TOKENS(PxrMayaHdImagingShapeTokens, PXRUSDMAYA_HD_IMAGING_SHAPE_TOKENS); const MTypeId PxrMayaHdImagingShape::typeId(0x00126402); -const MString PxrMayaHdImagingShape::typeName( - PxrMayaHdImagingShapeTokens->MayaTypeName.GetText()); +const MString PxrMayaHdImagingShape::typeName(PxrMayaHdImagingShapeTokens->MayaTypeName.GetText()); // Attributes MObject PxrMayaHdImagingShape::selectionResolutionAttr; @@ -88,9 +85,7 @@ namespace { // any other node in Maya. These are consistent over a Maya session, so that // we can find the nodes again, but they are re-generated between different // Maya runs since we don't write the imaging shape to disk. -static -MUuid -_GenerateUuid() +static MUuid _GenerateUuid() { MUuid uuid; uuid.generate(); @@ -98,38 +93,28 @@ _GenerateUuid() } static const std::string _HdImagingTransformName("HdImaging"); -static const std::string _HdImagingShapeName = - TfStringPrintf("%sShape", _HdImagingTransformName.c_str()); +static const std::string _HdImagingShapeName + = TfStringPrintf("%sShape", _HdImagingTransformName.c_str()); static const MUuid _HdImagingTransformUuid = _GenerateUuid(); static const MUuid _HdImagingShapeUuid = _GenerateUuid(); } // anonymous namespace /* static */ -void* -PxrMayaHdImagingShape::creator() -{ - return new PxrMayaHdImagingShape(); -} +void* PxrMayaHdImagingShape::creator() { return new PxrMayaHdImagingShape(); } /* static */ -MStatus -PxrMayaHdImagingShape::initialize() +MStatus PxrMayaHdImagingShape::initialize() { MStatus status; - MFnEnumAttribute enumAttrFn; + MFnEnumAttribute enumAttrFn; MFnNumericAttribute numericAttrFn; - const int defaultSelectionResolution = - TfGetEnvSetting(PXRMAYAHD_DEFAULT_SELECTION_RESOLUTION); + const int defaultSelectionResolution = TfGetEnvSetting(PXRMAYAHD_DEFAULT_SELECTION_RESOLUTION); - selectionResolutionAttr = - enumAttrFn.create( - "selectionResolution", - "sr", - defaultSelectionResolution, - &status); + selectionResolutionAttr + = enumAttrFn.create("selectionResolution", "sr", defaultSelectionResolution, &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = enumAttrFn.addField("256x256", 256); CHECK_MSTATUS_AND_RETURN_IT(status); @@ -150,15 +135,10 @@ PxrMayaHdImagingShape::initialize() status = addAttribute(selectionResolutionAttr); CHECK_MSTATUS_AND_RETURN_IT(status); - const bool enableDepthSelection = - TfGetEnvSetting(PXRMAYAHD_ENABLE_DEPTH_SELECTION); + const bool enableDepthSelection = TfGetEnvSetting(PXRMAYAHD_ENABLE_DEPTH_SELECTION); enableDepthSelectionAttr = numericAttrFn.create( - "enableDepthSelection", - "eds", - MFnNumericData::kBoolean, - 0.0, - &status); + "enableDepthSelection", "eds", MFnNumericData::kBoolean, 0.0, &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = numericAttrFn.setDefault(enableDepthSelection); CHECK_MSTATUS_AND_RETURN_IT(status); @@ -175,8 +155,7 @@ PxrMayaHdImagingShape::initialize() } /* static */ -PxrMayaHdImagingShape* -PxrMayaHdImagingShape::GetShapeAtDagPath(const MDagPath& dagPath) +PxrMayaHdImagingShape* PxrMayaHdImagingShape::GetShapeAtDagPath(const MDagPath& dagPath) { const MObject mObj = dagPath.node(); if (mObj.apiType() != MFn::kPluginShape) { @@ -189,8 +168,7 @@ PxrMayaHdImagingShape::GetShapeAtDagPath(const MDagPath& dagPath) } const MFnDependencyNode depNodeFn(mObj); - PxrMayaHdImagingShape* imagingShape = - static_cast(depNodeFn.userNode()); + PxrMayaHdImagingShape* imagingShape = static_cast(depNodeFn.userNode()); if (!imagingShape) { TF_CODING_ERROR( "Could not get PxrMayaHdImagingShape for node at DAG path: %s", @@ -202,8 +180,7 @@ PxrMayaHdImagingShape::GetShapeAtDagPath(const MDagPath& dagPath) } /* static */ -MObject -PxrMayaHdImagingShape::GetOrCreateInstance() +MObject PxrMayaHdImagingShape::GetOrCreateInstance() { MStatus status; @@ -240,9 +217,10 @@ PxrMayaHdImagingShape::GetOrCreateInstance() MObject::kNullObj, &status, &hdImagingTransformObj)) { - TF_RUNTIME_ERROR("Failed to create transform node %s for %s", - _HdImagingTransformName.c_str(), - _HdImagingShapeName.c_str()); + TF_RUNTIME_ERROR( + "Failed to create transform node %s for %s", + _HdImagingTransformName.c_str(), + _HdImagingShapeName.c_str()); MNamespace::setCurrentNamespace(currNamespace); @@ -266,7 +244,7 @@ PxrMayaHdImagingShape::GetOrCreateInstance() for (unsigned int i = 0u; i < depNodeFn.attributeCount(); ++i) { const MObject attribute = depNodeFn.attribute(i); - MPlug plug = depNodeFn.findPlug(attribute, true); + MPlug plug = depNodeFn.findPlug(attribute, true); plug.setLocked(true); } @@ -299,22 +277,13 @@ PxrMayaHdImagingShape::GetOrCreateInstance() } /* virtual */ -bool -PxrMayaHdImagingShape::isBounded() const -{ - return false; -} +bool PxrMayaHdImagingShape::isBounded() const { return false; } /* virtual */ -MBoundingBox -PxrMayaHdImagingShape::boundingBox() const -{ - return MBoundingBox(); -} +MBoundingBox PxrMayaHdImagingShape::boundingBox() const { return MBoundingBox(); } /* virtual */ -void -PxrMayaHdImagingShape::postConstructor() +void PxrMayaHdImagingShape::postConstructor() { MStatus status = setDoNotWrite(true); CHECK_MSTATUS(status); @@ -327,13 +296,9 @@ PxrMayaHdImagingShape::postConstructor() } /* virtual */ -bool -PxrMayaHdImagingShape::getInternalValue( - const MPlug& plug, - MDataHandle& dataHandle) +bool PxrMayaHdImagingShape::getInternalValue(const MPlug& plug, MDataHandle& dataHandle) { - if (plug == selectionResolutionAttr || - plug == enableDepthSelectionAttr) { + if (plug == selectionResolutionAttr || plug == enableDepthSelectionAttr) { // We just want notification of attribute gets and sets. We return // false here to tell Maya that it should still manage storage of the // value in the data block. @@ -344,13 +309,9 @@ PxrMayaHdImagingShape::getInternalValue( } /* virtual */ -bool -PxrMayaHdImagingShape::setInternalValue( - const MPlug& plug, - const MDataHandle& dataHandle) +bool PxrMayaHdImagingShape::setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) { - if (plug == selectionResolutionAttr || - plug == enableDepthSelectionAttr) { + if (plug == selectionResolutionAttr || plug == enableDepthSelectionAttr) { // If these attributes are changed, we mark the HdImagingShape as // needing to be redrawn, which is when we'll pull the new values from // the shape and pass them to the batch renderer. @@ -366,11 +327,10 @@ PxrMayaHdImagingShape::setInternalValue( } /* static */ -void -PxrMayaHdImagingShape::_OnObjectSetAdded(MObject& node, void* clientData) +void PxrMayaHdImagingShape::_OnObjectSetAdded(MObject& node, void* clientData) { MStatus status; - MFnSet objectSet(node, &status); + MFnSet objectSet(node, &status); if (!status) { return; } @@ -388,15 +348,13 @@ PxrMayaHdImagingShape::_OnObjectSetAdded(MObject& node, void* clientData) // re-add ourselves if the user changes the set of nodes to isolate without // exiting isolate selection mode. If the node is already being tracked, // then skip it. - PxrMayaHdImagingShape* me = - static_cast(clientData); - MObjectHandle handle(node); + PxrMayaHdImagingShape* me = static_cast(clientData); + MObjectHandle handle(node); if (me->_objectSetAttrChangedCallbackIds.count(handle) != 0) { return; } - me->_objectSetAttrChangedCallbackIds[handle] = - MNodeMessage::addAttributeChangedCallback( - node, _OnObjectSetAttrChanged, me); + me->_objectSetAttrChangedCallbackIds[handle] + = MNodeMessage::addAttributeChangedCallback(node, _OnObjectSetAttrChanged, me); // In rare cases, the user may have manually added the pxrHdImagingShape // into the isolate selection list. However, we won't know about it until @@ -406,21 +364,19 @@ PxrMayaHdImagingShape::_OnObjectSetAdded(MObject& node, void* clientData) } /* static */ -void -PxrMayaHdImagingShape::_OnObjectSetRemoved(MObject& node, void* clientData) +void PxrMayaHdImagingShape::_OnObjectSetRemoved(MObject& node, void* clientData) { MStatus status; - MFnSet objectSet(node, &status); + MFnSet objectSet(node, &status); if (!status) { return; } // Just to be safe, always check the removed set to see if we've been // tracking it, regardless of the set's name. - PxrMayaHdImagingShape* me = - static_cast(clientData); - MObjectHandle handle(node); - auto iter = me->_objectSetAttrChangedCallbackIds.find(handle); + PxrMayaHdImagingShape* me = static_cast(clientData); + MObjectHandle handle(node); + auto iter = me->_objectSetAttrChangedCallbackIds.find(handle); if (iter == me->_objectSetAttrChangedCallbackIds.end()) { return; } @@ -433,12 +389,11 @@ PxrMayaHdImagingShape::_OnObjectSetRemoved(MObject& node, void* clientData) } /* static */ -void -PxrMayaHdImagingShape::_OnObjectSetAttrChanged( - MNodeMessage::AttributeMessage msg, - MPlug& plug, - MPlug& otherPlug, - void *clientData) +void PxrMayaHdImagingShape::_OnObjectSetAttrChanged( + MNodeMessage::AttributeMessage msg, + MPlug& plug, + MPlug& otherPlug, + void* clientData) { // We only care about the case where the user has loaded a different set of // nodes into the isolate selection set, and when that happens, new @@ -451,8 +406,7 @@ PxrMayaHdImagingShape::_OnObjectSetAttrChanged( // If the connection-made message indicates that _this node_ is the node // connecting to the set, then there is no more work for us to do, so // simply return. - PxrMayaHdImagingShape* me = - static_cast(clientData); + PxrMayaHdImagingShape* me = static_cast(clientData); if (otherPlug.node() == me->thisMObject()) { return; } @@ -461,7 +415,8 @@ PxrMayaHdImagingShape::_OnObjectSetAttrChanged( objectSet.addMember(me->thisMObject()); } -PxrMayaHdImagingShape::PxrMayaHdImagingShape() : MPxSurfaceShape() +PxrMayaHdImagingShape::PxrMayaHdImagingShape() + : MPxSurfaceShape() { // If a shape is isolated but depends on Hydra batched drawing for imaging, // it won't image in the viewport unless the pxrHdImagingShape is also @@ -470,10 +425,10 @@ PxrMayaHdImagingShape::PxrMayaHdImagingShape() : MPxSurfaceShape() // actual drawing for the original shape. Thus, we listen for the // addition/removal of objectSets so that we can insert ourselves into any // objectSets used for viewport isolate selection. - _objectSetAddedCallbackId = MDGMessage::addNodeAddedCallback( - _OnObjectSetAdded, "objectSet", this); - _objectSetRemovedCallbackId = MDGMessage::addNodeRemovedCallback( - _OnObjectSetRemoved, "objectSet", this); + _objectSetAddedCallbackId + = MDGMessage::addNodeAddedCallback(_OnObjectSetAdded, "objectSet", this); + _objectSetRemovedCallbackId + = MDGMessage::addNodeRemovedCallback(_OnObjectSetRemoved, "objectSet", this); } /* virtual */ @@ -486,5 +441,4 @@ PxrMayaHdImagingShape::~PxrMayaHdImagingShape() } } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/nodes/hdImagingShape.h b/lib/mayaUsd/nodes/hdImagingShape.h index 9384259cb2..f932f4918a 100644 --- a/lib/mayaUsd/nodes/hdImagingShape.h +++ b/lib/mayaUsd/nodes/hdImagingShape.h @@ -16,11 +16,17 @@ #ifndef PXRUSDMAYA_HD_IMAGING_SHAPE_H #define PXRUSDMAYA_HD_IMAGING_SHAPE_H +#include +#include + +#include +#include + #include #include #include -#include #include +#include #include #include #include @@ -28,21 +34,14 @@ #include #include -#include -#include - -#include -#include - PXR_NAMESPACE_OPEN_SCOPE -#define PXRUSDMAYA_HD_IMAGING_SHAPE_TOKENS \ - ((MayaTypeName, "pxrHdImagingShape")) - -TF_DECLARE_PUBLIC_TOKENS(PxrMayaHdImagingShapeTokens, - MAYAUSD_CORE_PUBLIC, - PXRUSDMAYA_HD_IMAGING_SHAPE_TOKENS); +#define PXRUSDMAYA_HD_IMAGING_SHAPE_TOKENS ((MayaTypeName, "pxrHdImagingShape")) +TF_DECLARE_PUBLIC_TOKENS( + PxrMayaHdImagingShapeTokens, + MAYAUSD_CORE_PUBLIC, + PXRUSDMAYA_HD_IMAGING_SHAPE_TOKENS); /// Simple Maya shape providing batched drawing of other shapes imaged by Hydra. /// @@ -53,94 +52,83 @@ TF_DECLARE_PUBLIC_TOKENS(PxrMayaHdImagingShapeTokens, /// invoked when this shape is drawn. class PxrMayaHdImagingShape : public MPxSurfaceShape { - public: - - MAYAUSD_CORE_PUBLIC - static const MTypeId typeId; - MAYAUSD_CORE_PUBLIC - static const MString typeName; - - // Attributes - MAYAUSD_CORE_PUBLIC - static MObject selectionResolutionAttr; - MAYAUSD_CORE_PUBLIC - static MObject enableDepthSelectionAttr; - - MAYAUSD_CORE_PUBLIC - static void* creator(); - - MAYAUSD_CORE_PUBLIC - static MStatus initialize(); - - MAYAUSD_CORE_PUBLIC - static PxrMayaHdImagingShape* GetShapeAtDagPath( - const MDagPath& dagPath); - - /// Gets the "singleton" instance of the shape if it exists, or creates - /// it if it doesn't. - /// - /// There is typically only one instance of this node in a Maya scene - /// that takes care of all Hydra imaging for the scene. This method can - /// be used to ensure that that instance exists, and to get the MObject - /// for it. - /// Note that since this node is a shape, it is required to have a - /// transform node as a parent. This method will create that node as - /// well and set it up such that it will *not* save into the Maya scene - /// file. The nodes are also locked to prevent accidental deletion, - /// re-naming, or re-parenting. - MAYAUSD_CORE_PUBLIC - static MObject GetOrCreateInstance(); - - - // MPxSurfaceShape Overrides - - MAYAUSD_CORE_PUBLIC - bool isBounded() const override; - - MAYAUSD_CORE_PUBLIC - MBoundingBox boundingBox() const override; - - - // MPxNode Overrides - - MAYAUSD_CORE_PUBLIC - void postConstructor() override; - - MAYAUSD_CORE_PUBLIC - bool getInternalValue( - const MPlug& plug, - MDataHandle& dataHandle) override; - - MAYAUSD_CORE_PUBLIC - bool setInternalValue( - const MPlug& plug, - const MDataHandle& dataHandle) override; - - private: - // The callback IDs and functions below are used to ensure that this - // shape is always inserted into any viewport isolate selection set. - MCallbackId _objectSetAddedCallbackId; - MCallbackId _objectSetRemovedCallbackId; - UsdMayaUtil::MObjectHandleUnorderedMap - _objectSetAttrChangedCallbackIds; - - static void _OnObjectSetAdded(MObject& node, void* clientData); - static void _OnObjectSetRemoved(MObject& node, void* clientData); - static void _OnObjectSetAttrChanged( - MNodeMessage::AttributeMessage msg, - MPlug& plug, - MPlug& otherPlug, - void *clientData); - - PxrMayaHdImagingShape(); - ~PxrMayaHdImagingShape() override; - - PxrMayaHdImagingShape(const PxrMayaHdImagingShape&) = delete; - PxrMayaHdImagingShape& operator=(const PxrMayaHdImagingShape&) = delete; +public: + MAYAUSD_CORE_PUBLIC + static const MTypeId typeId; + MAYAUSD_CORE_PUBLIC + static const MString typeName; + + // Attributes + MAYAUSD_CORE_PUBLIC + static MObject selectionResolutionAttr; + MAYAUSD_CORE_PUBLIC + static MObject enableDepthSelectionAttr; + + MAYAUSD_CORE_PUBLIC + static void* creator(); + + MAYAUSD_CORE_PUBLIC + static MStatus initialize(); + + MAYAUSD_CORE_PUBLIC + static PxrMayaHdImagingShape* GetShapeAtDagPath(const MDagPath& dagPath); + + /// Gets the "singleton" instance of the shape if it exists, or creates + /// it if it doesn't. + /// + /// There is typically only one instance of this node in a Maya scene + /// that takes care of all Hydra imaging for the scene. This method can + /// be used to ensure that that instance exists, and to get the MObject + /// for it. + /// Note that since this node is a shape, it is required to have a + /// transform node as a parent. This method will create that node as + /// well and set it up such that it will *not* save into the Maya scene + /// file. The nodes are also locked to prevent accidental deletion, + /// re-naming, or re-parenting. + MAYAUSD_CORE_PUBLIC + static MObject GetOrCreateInstance(); + + // MPxSurfaceShape Overrides + + MAYAUSD_CORE_PUBLIC + bool isBounded() const override; + + MAYAUSD_CORE_PUBLIC + MBoundingBox boundingBox() const override; + + // MPxNode Overrides + + MAYAUSD_CORE_PUBLIC + void postConstructor() override; + + MAYAUSD_CORE_PUBLIC + bool getInternalValue(const MPlug& plug, MDataHandle& dataHandle) override; + + MAYAUSD_CORE_PUBLIC + bool setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) override; + +private: + // The callback IDs and functions below are used to ensure that this + // shape is always inserted into any viewport isolate selection set. + MCallbackId _objectSetAddedCallbackId; + MCallbackId _objectSetRemovedCallbackId; + UsdMayaUtil::MObjectHandleUnorderedMap _objectSetAttrChangedCallbackIds; + + static void _OnObjectSetAdded(MObject& node, void* clientData); + static void _OnObjectSetRemoved(MObject& node, void* clientData); + static void _OnObjectSetAttrChanged( + MNodeMessage::AttributeMessage msg, + MPlug& plug, + MPlug& otherPlug, + void* clientData); + + PxrMayaHdImagingShape(); + ~PxrMayaHdImagingShape() override; + + PxrMayaHdImagingShape(const PxrMayaHdImagingShape&) = delete; + PxrMayaHdImagingShape& operator=(const PxrMayaHdImagingShape&) = delete; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/nodes/pointBasedDeformerNode.cpp b/lib/mayaUsd/nodes/pointBasedDeformerNode.cpp index e0909b7c6b..7db2d8ad61 100644 --- a/lib/mayaUsd/nodes/pointBasedDeformerNode.cpp +++ b/lib/mayaUsd/nodes/pointBasedDeformerNode.cpp @@ -15,7 +15,21 @@ // #include "pointBasedDeformerNode.h" -#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -35,28 +49,13 @@ #include #include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include +#include PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PUBLIC_TOKENS(UsdMayaPointBasedDeformerNodeTokens, - PXRUSDMAYA_POINT_BASED_DEFORMER_NODE_TOKENS); - +TF_DEFINE_PUBLIC_TOKENS( + UsdMayaPointBasedDeformerNodeTokens, + PXRUSDMAYA_POINT_BASED_DEFORMER_NODE_TOKENS); const MTypeId UsdMayaPointBasedDeformerNode::typeId(0x00126401); const MString UsdMayaPointBasedDeformerNode::typeName( @@ -67,28 +66,19 @@ MObject UsdMayaPointBasedDeformerNode::inUsdStageAttr; MObject UsdMayaPointBasedDeformerNode::primPathAttr; MObject UsdMayaPointBasedDeformerNode::timeAttr; - /* static */ -void* -UsdMayaPointBasedDeformerNode::creator() -{ - return new UsdMayaPointBasedDeformerNode(); -} +void* UsdMayaPointBasedDeformerNode::creator() { return new UsdMayaPointBasedDeformerNode(); } /* static */ -MStatus -UsdMayaPointBasedDeformerNode::initialize() +MStatus UsdMayaPointBasedDeformerNode::initialize() { MStatus status; MFnTypedAttribute typedAttrFn; - MFnUnitAttribute unitAttrFn; + MFnUnitAttribute unitAttrFn; - inUsdStageAttr = typedAttrFn.create("inUsdStage", - "is", - MayaUsdStageData::mayaTypeId, - MObject::kNullObj, - &status); + inUsdStageAttr = typedAttrFn.create( + "inUsdStage", "is", MayaUsdStageData::mayaTypeId, MObject::kNullObj, &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = typedAttrFn.setReadable(false); CHECK_MSTATUS_AND_RETURN_IT(status); @@ -104,20 +94,13 @@ UsdMayaPointBasedDeformerNode::initialize() MFnStringData stringDataFn; const MObject defaultStringDataObj = stringDataFn.create(""); - primPathAttr = typedAttrFn.create("primPath", - "pp", - MFnData::kString, - defaultStringDataObj, - &status); + primPathAttr + = typedAttrFn.create("primPath", "pp", MFnData::kString, defaultStringDataObj, &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = addAttribute(primPathAttr); CHECK_MSTATUS_AND_RETURN_IT(status); - timeAttr = unitAttrFn.create("time", - "tm", - MFnUnitAttribute::kTime, - 0.0, - &status); + timeAttr = unitAttrFn.create("time", "tm", MFnUnitAttribute::kTime, 0.0, &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = addAttribute(timeAttr); CHECK_MSTATUS_AND_RETURN_IT(status); @@ -133,22 +116,19 @@ UsdMayaPointBasedDeformerNode::initialize() } /* virtual */ -MStatus -UsdMayaPointBasedDeformerNode::deform( - MDataBlock& block, - MItGeometry& iter, - const MMatrix& /* mat */, - unsigned int multiIndex) +MStatus UsdMayaPointBasedDeformerNode::deform( + MDataBlock& block, + MItGeometry& iter, + const MMatrix& /* mat */, + unsigned int multiIndex) { MStatus status; // Get the USD stage. - const MDataHandle inUsdStageHandle = - block.inputValue(inUsdStageAttr, &status); + const MDataHandle inUsdStageHandle = block.inputValue(inUsdStageAttr, &status); CHECK_MSTATUS_AND_RETURN_IT(status); - MayaUsdStageData* stageData = - dynamic_cast(inUsdStageHandle.asPluginData()); + MayaUsdStageData* stageData = dynamic_cast(inUsdStageHandle.asPluginData()); if (!stageData || !stageData->stage) { return MS::kFailure; } @@ -159,8 +139,7 @@ UsdMayaPointBasedDeformerNode::deform( const MDataHandle primPathHandle = block.inputValue(primPathAttr, &status); CHECK_MSTATUS_AND_RETURN_IT(status); - const std::string primPathString = - TfStringTrim(primPathHandle.asString().asChar()); + const std::string primPathString = TfStringTrim(primPathHandle.asString().asChar()); if (primPathString.empty()) { return MS::kFailure; @@ -168,7 +147,7 @@ UsdMayaPointBasedDeformerNode::deform( const SdfPath primPath(primPathString); - const UsdPrim& usdPrim = usdStage->GetPrimAtPath(primPath); + const UsdPrim& usdPrim = usdStage->GetPrimAtPath(primPath); const UsdGeomPointBased usdPointBased(usdPrim); if (!usdPointBased) { return MS::kFailure; @@ -183,43 +162,36 @@ UsdMayaPointBasedDeformerNode::deform( const float envelope = envelopeHandle.asFloat(); VtVec3fArray usdPoints; - if (!usdPointBased.GetPointsAttr().Get(&usdPoints, usdTime) || - usdPoints.empty()) { + if (!usdPointBased.GetPointsAttr().Get(&usdPoints, usdTime) || usdPoints.empty()) { return MS::kFailure; } - for ( ; !iter.isDone(); iter.next()) { + for (; !iter.isDone(); iter.next()) { const int index = iter.index(); if (index < 0 || static_cast(index) >= usdPoints.size()) { continue; } const MPoint mayaPoint = iter.position(); - const float weight = weightValue(block, multiIndex, index); + const float weight = weightValue(block, multiIndex, index); const GfVec3f& usdPoint = usdPoints[static_cast(index)]; - const GfVec3f deformedPoint = - GfLerp(weight * envelope, - GfVec3f(mayaPoint[0], mayaPoint[1], mayaPoint[2]), - usdPoint); + const GfVec3f deformedPoint = GfLerp( + weight * envelope, GfVec3f(mayaPoint[0], mayaPoint[1], mayaPoint[2]), usdPoint); - iter.setPosition( - MPoint(deformedPoint[0], deformedPoint[1], deformedPoint[2])); + iter.setPosition(MPoint(deformedPoint[0], deformedPoint[1], deformedPoint[2])); } return status; } -UsdMayaPointBasedDeformerNode::UsdMayaPointBasedDeformerNode() : - MPxDeformerNode() +UsdMayaPointBasedDeformerNode::UsdMayaPointBasedDeformerNode() + : MPxDeformerNode() { } /* virtual */ -UsdMayaPointBasedDeformerNode::~UsdMayaPointBasedDeformerNode() -{ -} - +UsdMayaPointBasedDeformerNode::~UsdMayaPointBasedDeformerNode() { } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/nodes/pointBasedDeformerNode.h b/lib/mayaUsd/nodes/pointBasedDeformerNode.h index fe3f7ee157..8af04eea75 100644 --- a/lib/mayaUsd/nodes/pointBasedDeformerNode.h +++ b/lib/mayaUsd/nodes/pointBasedDeformerNode.h @@ -16,6 +16,11 @@ #ifndef PXRUSDMAYA_POINT_BASED_DEFORMER_NODE_H #define PXRUSDMAYA_POINT_BASED_DEFORMER_NODE_H +#include + +#include +#include + #include #include #include @@ -25,20 +30,14 @@ #include #include -#include -#include - -#include - PXR_NAMESPACE_OPEN_SCOPE -#define PXRUSDMAYA_POINT_BASED_DEFORMER_NODE_TOKENS \ - ((MayaTypeName, "pxrUsdPointBasedDeformerNode")) - -TF_DECLARE_PUBLIC_TOKENS(UsdMayaPointBasedDeformerNodeTokens, - MAYAUSD_CORE_PUBLIC, - PXRUSDMAYA_POINT_BASED_DEFORMER_NODE_TOKENS); +#define PXRUSDMAYA_POINT_BASED_DEFORMER_NODE_TOKENS ((MayaTypeName, "pxrUsdPointBasedDeformerNode")) +TF_DECLARE_PUBLIC_TOKENS( + UsdMayaPointBasedDeformerNodeTokens, + MAYAUSD_CORE_PUBLIC, + PXRUSDMAYA_POINT_BASED_DEFORMER_NODE_TOKENS); /// Maya deformer that uses the points of a UsdGeomPointBased prim to deform /// the geometry. @@ -52,45 +51,40 @@ TF_DECLARE_PUBLIC_TOKENS(UsdMayaPointBasedDeformerNodeTokens, /// being deformed. class UsdMayaPointBasedDeformerNode : public MPxDeformerNode { - public: - MAYAUSD_CORE_PUBLIC - static const MTypeId typeId; - MAYAUSD_CORE_PUBLIC - static const MString typeName; - - // Attributes - MAYAUSD_CORE_PUBLIC - static MObject inUsdStageAttr; - MAYAUSD_CORE_PUBLIC - static MObject primPathAttr; - MAYAUSD_CORE_PUBLIC - static MObject timeAttr; - - MAYAUSD_CORE_PUBLIC - static void* creator(); - - MAYAUSD_CORE_PUBLIC - static MStatus initialize(); - - // MPxGeometryFilter overrides - MAYAUSD_CORE_PUBLIC - MStatus deform( - MDataBlock& block, - MItGeometry& iter, - const MMatrix& mat, - unsigned int multiIndex) override; - - private: - UsdMayaPointBasedDeformerNode(); - ~UsdMayaPointBasedDeformerNode() override; - - UsdMayaPointBasedDeformerNode(const UsdMayaPointBasedDeformerNode&); - UsdMayaPointBasedDeformerNode& operator=( - const UsdMayaPointBasedDeformerNode&); +public: + MAYAUSD_CORE_PUBLIC + static const MTypeId typeId; + MAYAUSD_CORE_PUBLIC + static const MString typeName; + + // Attributes + MAYAUSD_CORE_PUBLIC + static MObject inUsdStageAttr; + MAYAUSD_CORE_PUBLIC + static MObject primPathAttr; + MAYAUSD_CORE_PUBLIC + static MObject timeAttr; + + MAYAUSD_CORE_PUBLIC + static void* creator(); + + MAYAUSD_CORE_PUBLIC + static MStatus initialize(); + + // MPxGeometryFilter overrides + MAYAUSD_CORE_PUBLIC + MStatus + deform(MDataBlock& block, MItGeometry& iter, const MMatrix& mat, unsigned int multiIndex) + override; + +private: + UsdMayaPointBasedDeformerNode(); + ~UsdMayaPointBasedDeformerNode() override; + + UsdMayaPointBasedDeformerNode(const UsdMayaPointBasedDeformerNode&); + UsdMayaPointBasedDeformerNode& operator=(const UsdMayaPointBasedDeformerNode&); }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/nodes/proxyAccessor.cpp b/lib/mayaUsd/nodes/proxyAccessor.cpp index b1b66612a2..ee49112980 100644 --- a/lib/mayaUsd/nodes/proxyAccessor.cpp +++ b/lib/mayaUsd/nodes/proxyAccessor.cpp @@ -48,551 +48,535 @@ #include #include -namespace MAYAUSD_NS_DEF -{ +namespace MAYAUSD_NS_DEF { - namespace { - //! Profiler category for proxy accessor events - const int _accessorProfilerCategory = MProfiler::addCategory( +namespace { +//! Profiler category for proxy accessor events +const int _accessorProfilerCategory = MProfiler::addCategory( #if MAYA_API_VERSION >= 20190000 - "ProxyAccessor", - "ProxyAccessor" + "ProxyAccessor", + "ProxyAccessor" #else - "ProxyAccessor" + "ProxyAccessor" #endif - ); +); - //! \brief Test if given plug name is matching the convention used by accessor plugs - bool isAccessorPlugName(const char* plugName) - { - return (strncmp(plugName, "AP_", 3) == 0); - } +//! \brief Test if given plug name is matching the convention used by accessor plugs +bool isAccessorPlugName(const char* plugName) { return (strncmp(plugName, "AP_", 3) == 0); } - //! \brief Returns True is given plug is categorized as input plug, or False if output plug - bool isAccessorInputPlug(const MPlug& plug) - { - if (plug.isDestination()) +//! \brief Returns True is given plug is categorized as input plug, or False if output plug +bool isAccessorInputPlug(const MPlug& plug) +{ + if (plug.isDestination()) + return true; + + if (!plug.isCompound()) + return false; + + auto childCount = plug.numChildren(); + for (unsigned int i = 0; i < childCount; ++i) { + MPlug child = plug.child(i); + if (child.isDestination()) return true; + } - if (!plug.isCompound()) - return false; + return false; +} - auto childCount = plug.numChildren(); - for (unsigned int i = 0; i < childCount; ++i) { - MPlug child = plug.child(i); - if (child.isDestination()) - return true; +//! \brief Retrieve SdfPath from give plug +SdfPath getAccessorSdfPath(const MPlug& plug) +{ + MString niceNameCmd; + niceNameCmd.format("attributeName -nice ^1s", plug.name().asChar()); + + MString niceNameCmdResult; + if (MGlobal::executeCommand(niceNameCmd, niceNameCmdResult)) { + // Something we shouldn't have to deal with when things will get exposed + // to C++. For array we will receive sdfpath with element index. + // Example: "/path/to/prim[0]" + int arrayIndex = plug.isArray() ? niceNameCmdResult.rindexW('[') : -1; + if (arrayIndex >= 1) { + niceNameCmdResult = niceNameCmdResult.substringW(0, arrayIndex - 1); } - return false; + if (SdfPath::IsValidPathString(niceNameCmdResult.asChar())) + return SdfPath(niceNameCmdResult.asChar()); } - //! \brief Retrieve SdfPath from give plug - SdfPath getAccessorSdfPath(const MPlug& plug) - { - MString niceNameCmd; - niceNameCmd.format("attributeName -nice ^1s", plug.name().asChar()); - - MString niceNameCmdResult; - if (MGlobal::executeCommand(niceNameCmd, niceNameCmdResult)) { - // Something we shouldn't have to deal with when things will get exposed - // to C++. For array we will receive sdfpath with element index. - // Example: "/path/to/prim[0]" - int arrayIndex = plug.isArray() ? niceNameCmdResult.rindexW('[') : -1; - if (arrayIndex >= 1) { - niceNameCmdResult = niceNameCmdResult.substringW(0, arrayIndex - 1); + return SdfPath(); +} +} // namespace + +MStatus ProxyAccessor::addCallbacks(MObject object) +{ + _callbackIds.append(MNodeMessage::addAttributeAddedOrRemovedCallback( + object, + [](MNodeMessage::AttributeMessage msg, MPlug& plug, void* clientData) { + if (clientData) { + if (isAccessorPlugName(plug.partialName().asChar())) { + static_cast(clientData)->invalidateAccessorItems(); + } } + }, + (void*)(this))); - if (SdfPath::IsValidPathString(niceNameCmdResult.asChar())) - return SdfPath(niceNameCmdResult.asChar()); - } + _callbackIds.append(MNodeMessage::addAttributeChangedCallback( + object, + [](MNodeMessage::AttributeMessage msg, MPlug& plug, MPlug& otherPlug, void* clientData) { + if (!clientData + || (msg & (MNodeMessage::kConnectionMade | MNodeMessage::kConnectionBroken)) == 0) + return; - return SdfPath(); - } - } // namespace - - MStatus ProxyAccessor::addCallbacks(MObject object) - { - _callbackIds.append(MNodeMessage::addAttributeAddedOrRemovedCallback( - object, - [](MNodeMessage::AttributeMessage msg, MPlug& plug, void* clientData) { - if (clientData) { - if (isAccessorPlugName(plug.partialName().asChar())) { - static_cast(clientData)->invalidateAccessorItems(); - } - } - }, - (void*)(this))); - - _callbackIds.append(MNodeMessage::addAttributeChangedCallback( - object, - [](MNodeMessage::AttributeMessage msg, - MPlug& plug, - MPlug& otherPlug, - void* clientData) { - if (!clientData - || (msg & (MNodeMessage::kConnectionMade | MNodeMessage::kConnectionBroken)) - == 0) + if (isAccessorPlugName(plug.partialName().asChar())) { + auto* accessor = static_cast(clientData); + accessor->invalidateAccessorItems(); + + if ((msg & MNodeMessage::kConnectionBroken) == 0) return; - if (isAccessorPlugName(plug.partialName().asChar())) { - auto* accessor = static_cast(clientData); - accessor->invalidateAccessorItems(); - - if ((msg & MNodeMessage::kConnectionBroken) == 0) - return; - - auto stage = accessor->getUsdStage(); - if (!stage) - return; - - MFnAttribute attr(plug.attribute()); - MObject parentAttr = attr.parent(); - - SdfPath path; - if (parentAttr.isNull()) - path = getAccessorSdfPath(plug); - else { - MPlug parentPlug(plug.node(), parentAttr); - path = getAccessorSdfPath(parentPlug); - } - - if (path.IsEmpty() || !path.IsPrimPropertyPath()) - return; - - // Compute dependencies is considered as temporary data - UsdEditContext editContext(stage, stage->GetSessionLayer()); - - SdfPath primPath = path.GetPrimPath(); - UsdPrim prim = stage->GetPrimAtPath(primPath); - - if (!prim.RemoveProperty(path.GetNameToken())) { - TF_DEBUG(USDMAYA_PROXYACCESSOR) - .Msg( - "Failed to clear target layer on disconnect of '%s'\n", - path.GetText()); - } + auto stage = accessor->getUsdStage(); + if (!stage) + return; + + MFnAttribute attr(plug.attribute()); + MObject parentAttr = attr.parent(); + + SdfPath path; + if (parentAttr.isNull()) + path = getAccessorSdfPath(plug); + else { + MPlug parentPlug(plug.node(), parentAttr); + path = getAccessorSdfPath(parentPlug); } - }, - (void*)(this))); - return MS::kSuccess; - } + if (path.IsEmpty() || !path.IsPrimPropertyPath()) + return; - MStatus ProxyAccessor::removeCallbacks() - { - MMessage::removeCallbacks(_callbackIds); - _callbackIds.clear(); - return MS::kSuccess; - } + // Compute dependencies is considered as temporary data + UsdEditContext editContext(stage, stage->GetSessionLayer()); - void ProxyAccessor::collectAccessorItems(MObject node) - { - if (_validAccessorItems) - return; + SdfPath primPath = path.GetPrimPath(); + UsdPrim prim = stage->GetPrimAtPath(primPath); - MProfilingScope profilingScope( - _accessorProfilerCategory, MProfiler::kColorB_L1, "Generate acceleration structure"); + if (!prim.RemoveProperty(path.GetNameToken())) { + TF_DEBUG(USDMAYA_PROXYACCESSOR) + .Msg( + "Failed to clear target layer on disconnect of '%s'\n", path.GetText()); + } + } + }, + (void*)(this))); - _accessorInputItems.clear(); - _accessorOutputItems.clear(); + return MS::kSuccess; +} - _validAccessorItems = true; +MStatus ProxyAccessor::removeCallbacks() +{ + MMessage::removeCallbacks(_callbackIds); + _callbackIds.clear(); + return MS::kSuccess; +} - auto stage = getUsdStage(); - if (!stage) - return; +void ProxyAccessor::collectAccessorItems(MObject node) +{ + if (_validAccessorItems) + return; - ArResolverScopedCache resolverCache; + MProfilingScope profilingScope( + _accessorProfilerCategory, MProfiler::kColorB_L1, "Generate acceleration structure"); - MFnDependencyNode fnDep(node); - unsigned attrCount = fnDep.attributeCount(); - for (unsigned i = 0; i < attrCount; ++i) { - MFnAttribute attr(fnDep.attribute(i)); + _accessorInputItems.clear(); + _accessorOutputItems.clear(); - MStatus parentStatus = MS::kSuccess; - attr.parent(&parentStatus); + _validAccessorItems = true; - // Filter out child attributes - if (parentStatus == MS::kSuccess) - continue; + auto stage = getUsdStage(); + if (!stage) + return; - MString name = attr.name(); - if (!isAccessorPlugName(name.asChar())) - continue; + ArResolverScopedCache resolverCache; - MPlug valuePlug(node, attr.object()); - SdfPath path = getAccessorSdfPath(valuePlug); + MFnDependencyNode fnDep(node); + unsigned attrCount = fnDep.attributeCount(); + for (unsigned i = 0; i < attrCount; ++i) { + MFnAttribute attr(fnDep.attribute(i)); - if (path.IsEmpty()) { - TF_DEBUG(USDMAYA_PROXYACCESSOR) - .Msg( - "Plug found '%s', but it's not pointing at a valid SdfPath; ignoring\n", - valuePlug.name().asChar()); - continue; - } + MStatus parentStatus = MS::kSuccess; + attr.parent(&parentStatus); - SdfPath primPath = path.GetPrimPath(); - const UsdPrim& prim = stage->GetPrimAtPath(primPath); + // Filter out child attributes + if (parentStatus == MS::kSuccess) + continue; - const Converter* converter = nullptr; - if (!path.IsPrimPropertyPath()) { - SdfValueTypeName typeName = Converter::getUsdTypeName(valuePlug, false); - if (typeName != SdfValueTypeNames->Matrix4d) { - TF_DEBUG(USDMAYA_PROXYACCESSOR) - .Msg( - "Prim path found, but value plug is not a supported data type '%s' " - "(%s); ignoring\n", - path.GetText(), - valuePlug.attribute().apiTypeStr()); - continue; - } + MString name = attr.name(); + if (!isAccessorPlugName(name.asChar())) + continue; - converter = Converter::find(typeName, false); - } else { - const TfToken& propertyToken = path.GetNameToken(); - UsdAttribute attribute = prim.GetAttribute(propertyToken); + MPlug valuePlug(node, attr.object()); + SdfPath path = getAccessorSdfPath(valuePlug); - if (!attribute.IsDefined()) { - TF_DEBUG(USDMAYA_PROXYACCESSOR) - .Msg("Attribute is not defined '%s'; ignoring\n", path.GetText()); - continue; - } + if (path.IsEmpty()) { + TF_DEBUG(USDMAYA_PROXYACCESSOR) + .Msg( + "Plug found '%s', but it's not pointing at a valid SdfPath; ignoring\n", + valuePlug.name().asChar()); + continue; + } - converter = Converter::find(valuePlug, attribute); - } + SdfPath primPath = path.GetPrimPath(); + const UsdPrim& prim = stage->GetPrimAtPath(primPath); - if (!converter) { + const Converter* converter = nullptr; + if (!path.IsPrimPropertyPath()) { + SdfValueTypeName typeName = Converter::getUsdTypeName(valuePlug, false); + if (typeName != SdfValueTypeNames->Matrix4d) { TF_DEBUG(USDMAYA_PROXYACCESSOR) - .Msg("Skipped attribute, no valid converter found for '%s'\n", path.GetText()); + .Msg( + "Prim path found, but value plug is not a supported data type '%s' " + "(%s); ignoring\n", + path.GetText(), + valuePlug.attribute().apiTypeStr()); continue; } - if (isAccessorInputPlug(valuePlug)) { - TF_DEBUG(USDMAYA_PROXYACCESSOR).Msg("Added INPUT '%s'\n", path.GetText()); - _accessorInputItems.emplace_back(valuePlug, path, converter); - } else { - TF_DEBUG(USDMAYA_PROXYACCESSOR).Msg("Added OUTPUT '%s'\n", path.GetText()); - _accessorOutputItems.emplace_back(valuePlug, path, converter); + converter = Converter::find(typeName, false); + } else { + const TfToken& propertyToken = path.GetNameToken(); + UsdAttribute attribute = prim.GetAttribute(propertyToken); + + if (!attribute.IsDefined()) { + TF_DEBUG(USDMAYA_PROXYACCESSOR) + .Msg("Attribute is not defined '%s'; ignoring\n", path.GetText()); + continue; } + + converter = Converter::find(valuePlug, attribute); } - return; + if (!converter) { + TF_DEBUG(USDMAYA_PROXYACCESSOR) + .Msg("Skipped attribute, no valid converter found for '%s'\n", path.GetText()); + continue; + } + + if (isAccessorInputPlug(valuePlug)) { + TF_DEBUG(USDMAYA_PROXYACCESSOR).Msg("Added INPUT '%s'\n", path.GetText()); + _accessorInputItems.emplace_back(valuePlug, path, converter); + } else { + TF_DEBUG(USDMAYA_PROXYACCESSOR).Msg("Added OUTPUT '%s'\n", path.GetText()); + _accessorOutputItems.emplace_back(valuePlug, path, converter); + } } - MStatus ProxyAccessor::addDependentsDirty(const MPlug& plug, MPlugArray& plugArray) - { - if (inCompute()) - return MS::kUnknownParameter; + return; +} - MProfilingScope profilingScope( - _accessorProfilerCategory, MProfiler::kColorB_L1, "Dirty accessor plugs"); +MStatus ProxyAccessor::addDependentsDirty(const MPlug& plug, MPlugArray& plugArray) +{ + if (inCompute()) + return MS::kUnknownParameter; - collectAccessorItems(plug.node()); + MProfilingScope profilingScope( + _accessorProfilerCategory, MProfiler::kColorB_L1, "Dirty accessor plugs"); - if (_accessorInputItems.size() == 0 && _accessorOutputItems.size() == 0) - return MS::kUnknownParameter; + collectAccessorItems(plug.node()); - const bool accessorPlug = isAccessorPlugName(plug.partialName().asChar()); - const bool isInputPlug = accessorPlug && isAccessorInputPlug(plug); + if (_accessorInputItems.size() == 0 && _accessorOutputItems.size() == 0) + return MS::kUnknownParameter; - if (isInputPlug || !plug.isDynamic() || plug == _forceCompute) { - TF_DEBUG(USDMAYA_PROXYACCESSOR) - .Msg("Dirty all outputs from '%s'\n", plug.name().asChar()); + const bool accessorPlug = isAccessorPlugName(plug.partialName().asChar()); + const bool isInputPlug = accessorPlug && isAccessorInputPlug(plug); - for (const auto& item : _accessorOutputItems) { - const MPlug& itemPlug = std::get<0>(item); - if (!itemPlug.isArray()) - plugArray.append(itemPlug); - else { - const unsigned int numElements = itemPlug.numElements(); - for (unsigned int i = 0; i < numElements; i++) { - plugArray.append(itemPlug[i]); - } + if (isInputPlug || !plug.isDynamic() || plug == _forceCompute) { + TF_DEBUG(USDMAYA_PROXYACCESSOR).Msg("Dirty all outputs from '%s'\n", plug.name().asChar()); + + for (const auto& item : _accessorOutputItems) { + const MPlug& itemPlug = std::get<0>(item); + if (!itemPlug.isArray()) + plugArray.append(itemPlug); + else { + const unsigned int numElements = itemPlug.numElements(); + for (unsigned int i = 0; i < numElements; i++) { + plugArray.append(itemPlug[i]); } } } - return MS::kSuccess; } + return MS::kSuccess; +} + +MStatus ProxyAccessor::compute(const MPlug& plug, MDataBlock& dataBlock) +{ + if (inCompute()) + return MS::kSuccess; - MStatus ProxyAccessor::compute(const MPlug& plug, MDataBlock& dataBlock) - { - if (inCompute()) - return MS::kSuccess; + MProfilingScope profilingScope( + _accessorProfilerCategory, MProfiler::kColorB_L1, "Compute USD accessor"); - MProfilingScope profilingScope( - _accessorProfilerCategory, MProfiler::kColorB_L1, "Compute USD accessor"); + TF_DEBUG(USDMAYA_PROXYACCESSOR) + .Msg("Compute USD accessor triggered by '%s'\n", plug.name().asChar()); - TF_DEBUG(USDMAYA_PROXYACCESSOR) - .Msg("Compute USD accessor triggered by '%s'\n", plug.name().asChar()); + Scoped_InCompute inComputeNow(*this); - Scoped_InCompute inComputeNow(*this); + collectAccessorItems(plug.node()); - collectAccessorItems(plug.node()); + // Early exit to avoid virtual function calls when no compute will happen + if (_accessorInputItems.size() == 0 && _accessorOutputItems.size() == 0) + return MS::kSuccess; - // Early exit to avoid virtual function calls when no compute will happen - if (_accessorInputItems.size() == 0 && _accessorOutputItems.size() == 0) - return MS::kSuccess; + const UsdStageRefPtr stage = getUsdStage(); - const UsdStageRefPtr stage = getUsdStage(); + ArResolverScopedCache resolverCache; - ArResolverScopedCache resolverCache; + ConverterArgs args; + args._timeCode = getTime(); - ConverterArgs args; - args._timeCode = getTime(); + // Compute dependencies is considered as temporary data + UsdEditContext editContext(stage, stage->GetSessionLayer()); - // Compute dependencies is considered as temporary data - UsdEditContext editContext(stage, stage->GetSessionLayer()); + computeInputs(stage, dataBlock, args); + computeOutputs(plug.node(), stage, dataBlock, args); - computeInputs(stage, dataBlock, args); - computeOutputs(plug.node(), stage, dataBlock, args); + return MS::kSuccess; +} - return MS::kSuccess; - } +MStatus ProxyAccessor::computeInputs( + const UsdStageRefPtr stage, + MDataBlock& dataBlock, + const ConverterArgs& args) +{ + MStatus retValue = MS::kSuccess; + for (const auto& item : _accessorInputItems) { + const MPlug& itemPlug = std::get<0>(item); + const SdfPath& itemPath = std::get<1>(item); + const Converter* itemConverter = std::get<2>(item); + // We should cache UsdAttribute in here too and avoid expensive + // searches (i.e. getting the prim, getting attribute, checking if defined) - MStatus ProxyAccessor::computeInputs( - const UsdStageRefPtr stage, MDataBlock& dataBlock, const ConverterArgs& args) - { - MStatus retValue = MS::kSuccess; - for (const auto& item : _accessorInputItems) { - const MPlug& itemPlug = std::get<0>(item); - const SdfPath& itemPath = std::get<1>(item); - const Converter* itemConverter = std::get<2>(item); - // We should cache UsdAttribute in here too and avoid expensive - // searches (i.e. getting the prim, getting attribute, checking if defined) - - MProfilingScope profilingScope( - _accessorProfilerCategory, - MProfiler::kColorB_L1, - "Write input", - itemPath.GetText()); - - SdfPath itemPrimPath = itemPath.GetPrimPath(); - const UsdPrim& itemPrim = stage->GetPrimAtPath(itemPrimPath); - - if (!itemPath.IsPrimPropertyPath() || !itemConverter) - continue; + MProfilingScope profilingScope( + _accessorProfilerCategory, MProfiler::kColorB_L1, "Write input", itemPath.GetText()); - const TfToken& itemPropertyToken = itemPath.GetNameToken(); - UsdAttribute itemAttribute = itemPrim.GetAttribute(itemPropertyToken); + SdfPath itemPrimPath = itemPath.GetPrimPath(); + const UsdPrim& itemPrim = stage->GetPrimAtPath(itemPrimPath); - if (!itemAttribute.IsDefined()) { - TF_CODING_ERROR("Undefined/invalid attribute '%s'", itemPath.GetText()); - continue; - } + if (!itemPath.IsPrimPropertyPath() || !itemConverter) + continue; - MDataHandle itemDataHandle = dataBlock.inputValue(itemPlug, &retValue); - if (MFAIL(retValue)) { - continue; - } + const TfToken& itemPropertyToken = itemPath.GetNameToken(); + UsdAttribute itemAttribute = itemPrim.GetAttribute(itemPropertyToken); - VtValue convertedValue; - itemConverter->convert(itemDataHandle, convertedValue, args); + if (!itemAttribute.IsDefined()) { + TF_CODING_ERROR("Undefined/invalid attribute '%s'", itemPath.GetText()); + continue; + } - // Don't set the value if it didn't change. This will save us expensive invalidation + - // compute - VtValue currentValue; - if (itemAttribute.Get(¤tValue, args._timeCode) - && convertedValue != currentValue) { - itemAttribute.Set(convertedValue, args._timeCode); - } + MDataHandle itemDataHandle = dataBlock.inputValue(itemPlug, &retValue); + if (MFAIL(retValue)) { + continue; } - return retValue; + VtValue convertedValue; + itemConverter->convert(itemDataHandle, convertedValue, args); + + // Don't set the value if it didn't change. This will save us expensive invalidation + + // compute + VtValue currentValue; + if (itemAttribute.Get(¤tValue, args._timeCode) && convertedValue != currentValue) { + itemAttribute.Set(convertedValue, args._timeCode); + } } - MStatus ProxyAccessor::computeOutputs( - const MObject& ownerNode, - const UsdStageRefPtr stage, - MDataBlock& dataBlock, - const ConverterArgs& args) - { - MStatus retValue = MS::kSuccess; + return retValue; +} - UsdGeomXformCache xformCache(args._timeCode); +MStatus ProxyAccessor::computeOutputs( + const MObject& ownerNode, + const UsdStageRefPtr stage, + MDataBlock& dataBlock, + const ConverterArgs& args) +{ + MStatus retValue = MS::kSuccess; - MDagPath proxyDagPath; - MDagPath::getAPathTo(ownerNode, proxyDagPath); - const MMatrix proxyInclusiveMatrix = proxyDagPath.inclusiveMatrix(); + UsdGeomXformCache xformCache(args._timeCode); - for (const auto& item : _accessorOutputItems) { - const MPlug& itemPlug = std::get<0>(item); - const SdfPath& itemPath = std::get<1>(item); - const Converter* itemConverter = std::get<2>(item); - // We should cache UsdAttribute in here too and avoid expensive - // searches (i.e. getting the prim, getting attribute, checking if defined) - - MProfilingScope profilingScope( - _accessorProfilerCategory, - MProfiler::kColorB_L1, - "Write output", - itemPath.GetText()); - - SdfPath itemPrimPath = itemPath.GetPrimPath(); - const UsdPrim& itemPrim = stage->GetPrimAtPath(itemPrimPath); - - MDataHandle itemDataHandle = dataBlock.outputValue(itemPlug, &retValue); - if (MFAIL(retValue)) { - continue; - } + MDagPath proxyDagPath; + MDagPath::getAPathTo(ownerNode, proxyDagPath); + const MMatrix proxyInclusiveMatrix = proxyDagPath.inclusiveMatrix(); - // If it's not a property path, then we will be writing out world matrix data - if (!itemPath.IsPrimPropertyPath()) { - GfMatrix4d mat = xformCache.GetLocalToWorldTransform(itemPrim); - MMatrix mayaMat; - TypedConverter::convert(mat, mayaMat); + for (const auto& item : _accessorOutputItems) { + const MPlug& itemPlug = std::get<0>(item); + const SdfPath& itemPath = std::get<1>(item); + const Converter* itemConverter = std::get<2>(item); + // We should cache UsdAttribute in here too and avoid expensive + // searches (i.e. getting the prim, getting attribute, checking if defined) - mayaMat *= proxyInclusiveMatrix; + MProfilingScope profilingScope( + _accessorProfilerCategory, MProfiler::kColorB_L1, "Write output", itemPath.GetText()); - MFnMatrixData data; - MObject dataMatrix = data.create(); - data.set(mayaMat); + SdfPath itemPrimPath = itemPath.GetPrimPath(); + const UsdPrim& itemPrim = stage->GetPrimAtPath(itemPrimPath); - MArrayDataHandle dstArray(itemDataHandle); - MArrayDataBuilder dstArrayBuilder(&dataBlock, itemPlug.attribute(), 1); + MDataHandle itemDataHandle = dataBlock.outputValue(itemPlug, &retValue); + if (MFAIL(retValue)) { + continue; + } - MDataHandle dstElement = dstArrayBuilder.addElement(0); - dstElement.set(dataMatrix); + // If it's not a property path, then we will be writing out world matrix data + if (!itemPath.IsPrimPropertyPath()) { + GfMatrix4d mat = xformCache.GetLocalToWorldTransform(itemPrim); + MMatrix mayaMat; + TypedConverter::convert(mat, mayaMat); - dstArray.set(dstArrayBuilder); - dstArray.setAllClean(); - } else if (itemConverter) { - const TfToken& itemPropertyToken = itemPath.GetNameToken(); - UsdAttribute itemAttribute = itemPrim.GetAttribute(itemPropertyToken); + mayaMat *= proxyInclusiveMatrix; - // cache this! expensive call - if (!itemAttribute.IsDefined()) { - TF_CODING_ERROR("Undefined/invalid attribute '%s'", itemPath.GetText()); + MFnMatrixData data; + MObject dataMatrix = data.create(); + data.set(mayaMat); - dataBlock.setClean(itemPlug); - continue; - } + MArrayDataHandle dstArray(itemDataHandle); + MArrayDataBuilder dstArrayBuilder(&dataBlock, itemPlug.attribute(), 1); + + MDataHandle dstElement = dstArrayBuilder.addElement(0); + dstElement.set(dataMatrix); - itemConverter->convert(itemAttribute, itemDataHandle, args); + dstArray.set(dstArrayBuilder); + dstArray.setAllClean(); + } else if (itemConverter) { + const TfToken& itemPropertyToken = itemPath.GetNameToken(); + UsdAttribute itemAttribute = itemPrim.GetAttribute(itemPropertyToken); + + // cache this! expensive call + if (!itemAttribute.IsDefined()) { + TF_CODING_ERROR("Undefined/invalid attribute '%s'", itemPath.GetText()); + + dataBlock.setClean(itemPlug); + continue; } - // Even if we have no data to write, we set the data in data block as clean - // This will prevent entering compute loop again and in case of changes to USD - // which result in particular path being invalid, we will preserve the value - // from last time it was available - itemDataHandle.setClean(); - dataBlock.setClean(itemPlug.attribute()); + itemConverter->convert(itemAttribute, itemDataHandle, args); } - return retValue; + // Even if we have no data to write, we set the data in data block as clean + // This will prevent entering compute loop again and in case of changes to USD + // which result in particular path being invalid, we will preserve the value + // from last time it was available + itemDataHandle.setClean(); + dataBlock.setClean(itemPlug.attribute()); } - MStatus ProxyAccessor::syncCache(const MObject& node, MDataBlock& dataBlock) - { - if (inCompute()) - return MS::kSuccess; + return retValue; +} - MProfilingScope profilingScope( - _accessorProfilerCategory, MProfiler::kColorB_L1, "Update USD cache"); +MStatus ProxyAccessor::syncCache(const MObject& node, MDataBlock& dataBlock) +{ + if (inCompute()) + return MS::kSuccess; - TF_DEBUG(USDMAYA_PROXYACCESSOR).Msg("Update USD cache\n"); + MProfilingScope profilingScope( + _accessorProfilerCategory, MProfiler::kColorB_L1, "Update USD cache"); - Scoped_InCompute inComputeNow(*this); + TF_DEBUG(USDMAYA_PROXYACCESSOR).Msg("Update USD cache\n"); - collectAccessorItems(node); + Scoped_InCompute inComputeNow(*this); - // Early exit to avoid virtual function calls when no compute will happen - if (_accessorInputItems.size() == 0) - return MS::kSuccess; + collectAccessorItems(node); - const UsdStageRefPtr stage = getUsdStage(); + // Early exit to avoid virtual function calls when no compute will happen + if (_accessorInputItems.size() == 0) + return MS::kSuccess; - ArResolverScopedCache resolverCache; + const UsdStageRefPtr stage = getUsdStage(); - ConverterArgs args; - args._timeCode = getTime(); + ArResolverScopedCache resolverCache; - // Compute dependencies is considered as temporary data - UsdEditContext editContext(stage, stage->GetSessionLayer()); + ConverterArgs args; + args._timeCode = getTime(); - return computeInputs(stage, dataBlock, args); - } + // Compute dependencies is considered as temporary data + UsdEditContext editContext(stage, stage->GetSessionLayer()); - MStatus ProxyAccessor::stageChanged( - const MObject& node, const UsdNotice::ObjectsChanged& notice) - { - const auto& stage = notice.GetStage(); - if (stage != getUsdStage()) { - TF_CODING_ERROR("We shouldn't be receiving notification for other stages than one " - "returned by stage provider"); - return MS::kUnknownParameter; - } + return computeInputs(stage, dataBlock, args); +} - bool needsForceCompute = true; +MStatus ProxyAccessor::stageChanged(const MObject& node, const UsdNotice::ObjectsChanged& notice) +{ + const auto& stage = notice.GetStage(); + if (stage != getUsdStage()) { + TF_CODING_ERROR("We shouldn't be receiving notification for other stages than one " + "returned by stage provider"); + return MS::kUnknownParameter; + } - if (_accessorInputItems.size() > 0) { - auto findInputItemFn = [this](const SdfPath& changedPath) -> Item* { - for (auto& item : _accessorInputItems) { - if (std::get<1>(item) == changedPath) { - return &item; - } + bool needsForceCompute = true; + + if (_accessorInputItems.size() > 0) { + auto findInputItemFn = [this](const SdfPath& changedPath) -> Item* { + for (auto& item : _accessorInputItems) { + if (std::get<1>(item) == changedPath) { + return &item; } - return nullptr; - }; - - // UFE currently doesn't write time sampled data. - ConverterArgs args; - args._timeCode = UsdTimeCode::Default(); // getTime(); - - // Compute dependencies is considered as temporary data - UsdEditContext editContext(stage, stage->GetSessionLayer()); - - for (const auto& changedPath : notice.GetChangedInfoOnlyPaths()) { - if (changedPath.IsPrimPropertyPath()) { - auto* changedInput = findInputItemFn(changedPath); - if (!changedInput) { - TF_DEBUG(USDMAYA_PROXYACCESSOR) - .Msg( - "Input has changed but not found in input list '%s'\n", - changedPath.GetText()); - continue; - } + } + return nullptr; + }; + + // UFE currently doesn't write time sampled data. + ConverterArgs args; + args._timeCode = UsdTimeCode::Default(); // getTime(); + // Compute dependencies is considered as temporary data + UsdEditContext editContext(stage, stage->GetSessionLayer()); + + for (const auto& changedPath : notice.GetChangedInfoOnlyPaths()) { + if (changedPath.IsPrimPropertyPath()) { + auto* changedInput = findInputItemFn(changedPath); + if (!changedInput) { TF_DEBUG(USDMAYA_PROXYACCESSOR) - .Msg("Input PrimPropertyPath has changed '%s'\n", changedPath.GetText()); + .Msg( + "Input has changed but not found in input list '%s'\n", + changedPath.GetText()); + continue; + } - MPlug& changedPlug = std::get<0>(*changedInput); - const Converter* converter = std::get<2>(*changedInput); + TF_DEBUG(USDMAYA_PROXYACCESSOR) + .Msg("Input PrimPropertyPath has changed '%s'\n", changedPath.GetText()); - SdfPath changedPrimPath = changedPath.GetPrimPath(); - const UsdPrim& changedPrim = stage->GetPrimAtPath(changedPrimPath); + MPlug& changedPlug = std::get<0>(*changedInput); + const Converter* converter = std::get<2>(*changedInput); - const TfToken& changedPropertyToken = changedPath.GetNameToken(); - UsdAttribute changedAttribute = changedPrim.GetAttribute(changedPropertyToken); + SdfPath changedPrimPath = changedPath.GetPrimPath(); + const UsdPrim& changedPrim = stage->GetPrimAtPath(changedPrimPath); - converter->convert(changedAttribute, changedPlug, args); + const TfToken& changedPropertyToken = changedPath.GetNameToken(); + UsdAttribute changedAttribute = changedPrim.GetAttribute(changedPropertyToken); - // When input plug is set, this value may be a new constant or - // just temporary value overriding what comes from animation curve. - // Input value change will properly cause outputs to compute so - // forcing compute is not necessary (and it destructive for temporary values) - needsForceCompute = false; - } - } - } + converter->convert(changedAttribute, changedPlug, args); - if (needsForceCompute && _accessorOutputItems.size() > 0) { - forceCompute(node); + // When input plug is set, this value may be a new constant or + // just temporary value overriding what comes from animation curve. + // Input value change will properly cause outputs to compute so + // forcing compute is not necessary (and it destructive for temporary values) + needsForceCompute = false; + } } + } - return MStatus::kSuccess; + if (needsForceCompute && _accessorOutputItems.size() > 0) { + forceCompute(node); } - MStatus ProxyAccessor::forceCompute(const MObject& node) - { - // don't force compute when already doing one - if (!inCompute()) { - MPlug forceCompute(node, _forceCompute); - forceCompute.setBool(!forceCompute.asBool()); - return MStatus::kSuccess; - } + return MStatus::kSuccess; +} - return MStatus::kFailure; +MStatus ProxyAccessor::forceCompute(const MObject& node) +{ + // don't force compute when already doing one + if (!inCompute()) { + MPlug forceCompute(node, _forceCompute); + forceCompute.setBool(!forceCompute.asBool()); + return MStatus::kSuccess; } -} // namespace MayaUsd + return MStatus::kFailure; +} + +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/nodes/proxyAccessor.h b/lib/mayaUsd/nodes/proxyAccessor.h index ed67463764..9518eefc75 100644 --- a/lib/mayaUsd/nodes/proxyAccessor.h +++ b/lib/mayaUsd/nodes/proxyAccessor.h @@ -41,222 +41,226 @@ PXR_NAMESPACE_USING_DIRECTIVE -namespace MAYAUSD_NS_DEF -{ - struct ConverterArgs; - class Converter; +namespace MAYAUSD_NS_DEF { +struct ConverterArgs; +class Converter; - /*! \brief Proxy accessor class enables an MPxNode node with ProxyStageProvider interface to - write and read data from the USD stage. +/*! \brief Proxy accessor class enables an MPxNode node with ProxyStageProvider interface to + write and read data from the USD stage. - Proxy accessor will discover accessor dynamic attributes on MPxNode and categorize them as - inputs or outputs. + Proxy accessor will discover accessor dynamic attributes on MPxNode and categorize them as + inputs or outputs. - During compute, proxy accessor will read all inputs, i.e. accessor attributes which have source - connection and write them to the stage and time provided by the ProxyStageProvider interface of - the owning node. Output attributes are then read from the stage and written to the data block. + During compute, proxy accessor will read all inputs, i.e. accessor attributes which have source + connection and write them to the stage and time provided by the ProxyStageProvider interface of + the owning node. Output attributes are then read from the stage and written to the data block. - Accessor attributes are dynamic attributes created on owning MPxNode and having the following - characteristics: - - attribute name is created using following formula - "AccessValue_" + hash(SdfPath) - - attribute nice name is used to store SdfPath to prim or prim property - - when no property is provided in the SdfPath, we assume the world matrix is requested. This - makes only sense for output plugs. + Accessor attributes are dynamic attributes created on owning MPxNode and having the following + characteristics: + - attribute name is created using following formula - "AccessValue_" + hash(SdfPath) + - attribute nice name is used to store SdfPath to prim or prim property + - when no property is provided in the SdfPath, we assume the world matrix is requested. This + makes only sense for output plugs. - A proxy accessor is owned by MPxNode and extends base class methods. For more information read - the documentation for the public interface of this class. + A proxy accessor is owned by MPxNode and extends base class methods. For more information read + the documentation for the public interface of this class. - \note Currently the only class leveraging proxy accessor is the proxy shape. - */ - class ProxyAccessor { - public: - using Owner = std::unique_ptr; - - /*! \brief Construct ProxyAccessor for a given MPxNode with ProxyStageProvider interface - \note Call from MPxNode::postConstructor() - */ - template < - typename ProxyClass, - typename std::enable_if< - (std::is_base_of::value - && std::is_base_of::value), - int>::type - = 0> - static Owner createAndRegister(ProxyClass& proxyNode) + \note Currently the only class leveraging proxy accessor is the proxy shape. +*/ +class ProxyAccessor +{ +public: + using Owner = std::unique_ptr; + + /*! \brief Construct ProxyAccessor for a given MPxNode with ProxyStageProvider interface + \note Call from MPxNode::postConstructor() + */ + template < + typename ProxyClass, + typename std::enable_if< + (std::is_base_of::value + && std::is_base_of::value), + int>::type + = 0> + static Owner createAndRegister(ProxyClass& proxyNode) + { + MPxNode& node = static_cast(proxyNode); + ProxyStageProvider& stageProvider = static_cast(proxyNode); + + auto accessor = Owner(new ProxyAccessor(stageProvider)); + + // add hidden attribute to force compute when USD changes + MFnDependencyNode fnDep(node.thisMObject()); { - MPxNode& node = static_cast(proxyNode); - ProxyStageProvider& stageProvider = static_cast(proxyNode); + MFnNumericAttribute attr; - auto accessor = Owner(new ProxyAccessor(stageProvider)); + accessor->_forceCompute + = attr.create("forceCompute", "forceCompute", MFnNumericData::kBoolean); - // add hidden attribute to force compute when USD changes - MFnDependencyNode fnDep(node.thisMObject()); - { - MFnNumericAttribute attr; + attr.setReadable(false); + attr.setWritable(true); + attr.setKeyable(false); + attr.setHidden(true); + attr.setConnectable(false); - accessor->_forceCompute - = attr.create("forceCompute", "forceCompute", MFnNumericData::kBoolean); + fnDep.addAttribute(accessor->_forceCompute); + } - attr.setReadable(false); - attr.setWritable(true); - attr.setKeyable(false); - attr.setHidden(true); - attr.setConnectable(false); + accessor->addCallbacks(node.thisMObject()); + + return accessor; + } + + /*! \brief Insert extra plug level dependencies for accessor plugs + \note Call from MPxNode::setDependentsDirty() + */ + static MStatus + addDependentsDirty(const Owner& accessor, const MPlug& plug, MPlugArray& plugArray) + { + if (accessor) + return accessor->addDependentsDirty(plug, plugArray); + else + return MStatus::kFailure; + } + + /*! \brief Compute will write input accessor plugs and write converted data to the stage. + Once completed, all output accessor plugs will be provided with data. \note Call from + MPxNode::compute() + */ + static MStatus compute(const Owner& accessor, const MPlug& plug, MDataBlock& dataBlock) + { + if (accessor) + return accessor->compute(plug, dataBlock); + else + return MStatus::kFailure; + } + + /*! \brief Proxy accessor is creating acceleration structure to avoid the discovery of + accessor plugs at each compute. This accelleration structure has to be invalidate when + stage changes. + */ + static MStatus stageChanged( + const Owner& accessor, + const MObject& node, + const UsdNotice::ObjectsChanged& notice) + { + if (accessor && !accessor->inCompute()) + return accessor->stageChanged(node, notice); + else + return MStatus::kFailure; + } + + /*! \brief Update USD state to match what is stored in evaluation cache (when cached + playback is on) \note Call from MPxNode::postEvaluation() + */ + static MStatus syncCache(const Owner& accessor, const MObject& node, MDataBlock& dataBlock) + { + if (accessor && !accessor->inCompute()) + return accessor->syncCache(node, dataBlock); + else + return MStatus::kFailure; + } + + //! \brief Clear all callback when destroying this object + virtual ~ProxyAccessor() { removeCallbacks(); } + +private: + /*! \brief Single item in acceleration structure holding. + To avoid expensive searches during compute, we cache MPlug, SdfPath and converter needed + to translate values between data models. + */ + using Item = std::tuple; + using Container = std::vector; + + ProxyAccessor(ProxyStageProvider& provider) + : _stageProvider(provider) + { + } + ProxyAccessor() = delete; + ProxyAccessor(const ProxyAccessor&) = delete; + ProxyAccessor& operator=(const ProxyAccessor&) = delete; + + //! \brief Makes access to current stage time easier + UsdTimeCode getTime() const { return _stageProvider.getTime(); } + //! \brief Makes access to the stage easier + UsdStageRefPtr getUsdStage() const { return _stageProvider.getUsdStage(); } + + //! \brief Register necessary callbacks + MStatus addCallbacks(MObject object); + //! \brief Remove all registered callbacks + MStatus removeCallbacks(); + + //! \brief Populate acceleration structure + void collectAccessorItems(MObject node); + //! \brief Invalidate acceleration structure + void invalidateAccessorItems() { _validAccessorItems = false; } + + //! \brief Notification from MPxNode to insert accessor plugs dependencies + MStatus addDependentsDirty(const MPlug& plug, MPlugArray& plugArray); + //! \brief Notification from MPxNode to compute accessor plugs. + MStatus compute(const MPlug& plug, MDataBlock& dataBlock); + //! \brief Using acceleration structure, do computation of accessor input plugs. + MStatus + computeInputs(const UsdStageRefPtr stage, MDataBlock& dataBlock, const ConverterArgs& args); + //! \brief Using acceleration structure, do computation of accessor output plugs. + MStatus computeOutputs( + const MObject& ownerNode, + const UsdStageRefPtr stage, + MDataBlock& dataBlock, + const ConverterArgs& args); + /*! \brief Notification from MPxNode to synchronize evaluation cache with USD stage + Each manipulation can mutate the state of USD, but not every manipulation will + invalidate the cache. In order to keep USD state in sync with what was stored in + evaluation cache, we leverage postEvaluation notification. + */ + MStatus syncCache(const MObject& node, MDataBlock& dataBlock); - fnDep.addAttribute(accessor->_forceCompute); - } + //! \brief Something in USD changed and we may have to set it on plugs. + MStatus stageChanged(const MObject& node, const UsdNotice::ObjectsChanged& notice); + //! \brief Trigger computation of accessor plugs + MStatus forceCompute(const MObject& node); - accessor->addCallbacks(node.thisMObject()); + //! \brief Is accessor compute started + bool inCompute() const { return _inCompute; } - return accessor; - } + ProxyStageProvider& _stageProvider; //!< Accessor holds reference to stage provider in order + //!< to query the stage and time - /*! \brief Insert extra plug level dependencies for accessor plugs - \note Call from MPxNode::setDependentsDirty() - */ - static MStatus addDependentsDirty(const Owner& accessor, const MPlug& plug, MPlugArray& plugArray) - { - if (accessor) - return accessor->addDependentsDirty(plug, plugArray); - else - return MStatus::kFailure; - } + MObject _forceCompute; //!< Special attribute used to force computation of accessor plugs. + //!< Needed when USD changes directly. - /*! \brief Compute will write input accessor plugs and write converted data to the stage. - Once completed, all output accessor plugs will be provided with data. \note Call from - MPxNode::compute() - */ - static MStatus compute(const Owner& accessor, const MPlug& plug, MDataBlock& dataBlock) - { - if (accessor) - return accessor->compute(plug, dataBlock); - else - return MStatus::kFailure; - } + MCallbackIdArray _callbackIds; //!< List of registered callbacks - /*! \brief Proxy accessor is creating acceleration structure to avoid the discovery of - accessor plugs at each compute. This accelleration structure has to be invalidate when - stage changes. - */ - static MStatus - stageChanged(const Owner& accessor, const MObject& node, const UsdNotice::ObjectsChanged& notice) - { - if (accessor && !accessor->inCompute()) - return accessor->stageChanged(node, notice); - else - return MStatus::kFailure; - } + //! \brief Acceleration structure holding all input accessor plugs + Container _accessorInputItems; + //! \brief Acceleration structure holding all output accessor plugs + Container _accessorOutputItems; + //! \brief Flag to indicate if acceleration structure is valid or needs to be recreated + bool _validAccessorItems { false }; + bool _inCompute { false }; //!< Prevent nested compute - /*! \brief Update USD state to match what is stored in evaluation cache (when cached - playback is on) \note Call from MPxNode::postEvaluation() - */ - static MStatus syncCache(const Owner& accessor, const MObject& node, MDataBlock& dataBlock) + //! \brief Helper scoped object to prevent nested compute + class Scoped_InCompute + { + public: + Scoped_InCompute(ProxyAccessor& accessor) + : _accessor(accessor) + , _restoreState(accessor._inCompute) { - if (accessor && !accessor->inCompute()) - return accessor->syncCache(node, dataBlock); - else - return MStatus::kFailure; + _accessor._inCompute = true; } - //! \brief Clear all callback when destroying this object - virtual ~ProxyAccessor() { removeCallbacks(); } + ~Scoped_InCompute() { _accessor._inCompute = _restoreState; } + + Scoped_InCompute(const Scoped_InCompute&) = delete; + Scoped_InCompute& operator=(const Scoped_InCompute&) = delete; private: - /*! \brief Single item in acceleration structure holding. - To avoid expensive searches during compute, we cache MPlug, SdfPath and converter needed - to translate values between data models. - */ - using Item = std::tuple; - using Container = std::vector; - - ProxyAccessor(ProxyStageProvider& provider) - : _stageProvider(provider) - { - } - ProxyAccessor() = delete; - ProxyAccessor(const ProxyAccessor&) = delete; - ProxyAccessor& operator=(const ProxyAccessor&) = delete; - - //! \brief Makes access to current stage time easier - UsdTimeCode getTime() const { return _stageProvider.getTime(); } - //! \brief Makes access to the stage easier - UsdStageRefPtr getUsdStage() const { return _stageProvider.getUsdStage(); } - - //! \brief Register necessary callbacks - MStatus addCallbacks(MObject object); - //! \brief Remove all registered callbacks - MStatus removeCallbacks(); - - //! \brief Populate acceleration structure - void collectAccessorItems(MObject node); - //! \brief Invalidate acceleration structure - void invalidateAccessorItems() { _validAccessorItems = false; } - - //! \brief Notification from MPxNode to insert accessor plugs dependencies - MStatus addDependentsDirty(const MPlug& plug, MPlugArray& plugArray); - //! \brief Notification from MPxNode to compute accessor plugs. - MStatus compute(const MPlug& plug, MDataBlock& dataBlock); - //! \brief Using acceleration structure, do computation of accessor input plugs. - MStatus - computeInputs(const UsdStageRefPtr stage, MDataBlock& dataBlock, const ConverterArgs& args); - //! \brief Using acceleration structure, do computation of accessor output plugs. - MStatus computeOutputs( - const MObject& ownerNode, - const UsdStageRefPtr stage, - MDataBlock& dataBlock, - const ConverterArgs& args); - /*! \brief Notification from MPxNode to synchronize evaluation cache with USD stage - Each manipulation can mutate the state of USD, but not every manipulation will - invalidate the cache. In order to keep USD state in sync with what was stored in - evaluation cache, we leverage postEvaluation notification. - */ - MStatus syncCache(const MObject& node, MDataBlock& dataBlock); - - //! \brief Something in USD changed and we may have to set it on plugs. - MStatus stageChanged(const MObject& node, const UsdNotice::ObjectsChanged& notice); - //! \brief Trigger computation of accessor plugs - MStatus forceCompute(const MObject& node); - - //! \brief Is accessor compute started - bool inCompute() const { return _inCompute; } - - ProxyStageProvider& _stageProvider; //!< Accessor holds reference to stage provider in order - //!< to query the stage and time - - MObject _forceCompute; //!< Special attribute used to force computation of accessor plugs. - //!< Needed when USD changes directly. - - MCallbackIdArray _callbackIds; //!< List of registered callbacks - - //! \brief Acceleration structure holding all input accessor plugs - Container _accessorInputItems; - //! \brief Acceleration structure holding all output accessor plugs - Container _accessorOutputItems; - //! \brief Flag to indicate if acceleration structure is valid or needs to be recreated - bool _validAccessorItems { false }; - bool _inCompute { false }; //!< Prevent nested compute - - //! \brief Helper scoped object to prevent nested compute - class Scoped_InCompute { - public: - Scoped_InCompute(ProxyAccessor& accessor) - : _accessor(accessor) - , _restoreState(accessor._inCompute) - { - _accessor._inCompute = true; - } - - ~Scoped_InCompute() { _accessor._inCompute = _restoreState; } - - Scoped_InCompute(const Scoped_InCompute&) = delete; - Scoped_InCompute& operator=(const Scoped_InCompute&) = delete; - - private: - ProxyAccessor& _accessor; - bool _restoreState { false }; - }; + ProxyAccessor& _accessor; + bool _restoreState { false }; }; +}; -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/mayaUsd/nodes/proxyShapeBase.cpp b/lib/mayaUsd/nodes/proxyShapeBase.cpp index f3dcca7d90..68ff65d681 100644 --- a/lib/mayaUsd/nodes/proxyShapeBase.cpp +++ b/lib/mayaUsd/nodes/proxyShapeBase.cpp @@ -15,18 +15,45 @@ // #include "proxyShapeBase.h" -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include -#include +#include +#include #include #include #include -#include -#include +#include #include #include #include @@ -51,42 +78,14 @@ #include #include #include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include + #if defined(WANT_UFE_BUILD) #include #endif @@ -95,24 +94,21 @@ using namespace MAYAUSD_NS_DEF; PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PUBLIC_TOKENS(MayaUsdProxyShapeBaseTokens, - MAYAUSD_PROXY_SHAPE_BASE_TOKENS); +TF_DEFINE_PUBLIC_TOKENS(MayaUsdProxyShapeBaseTokens, MAYAUSD_PROXY_SHAPE_BASE_TOKENS); -MayaUsdProxyShapeBase::ClosestPointDelegate -MayaUsdProxyShapeBase::_sharedClosestPointDelegate = nullptr; +MayaUsdProxyShapeBase::ClosestPointDelegate MayaUsdProxyShapeBase::_sharedClosestPointDelegate + = nullptr; -const std::string kAnonymousLayerName{"anonymousLayer1"}; +const std::string kAnonymousLayerName { "anonymousLayer1" }; // ======================================================== // TypeID from the MayaUsd type ID range. const MTypeId MayaUsdProxyShapeBase::typeId(0x58000094); -const MString MayaUsdProxyShapeBase::typeName( - MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText()); +const MString MayaUsdProxyShapeBase::typeName(MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText()); const MString MayaUsdProxyShapeBase::displayFilterName( - TfStringPrintf("%sDisplayFilter", - MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText()).c_str()); + TfStringPrintf("%sDisplayFilter", MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText()).c_str()); const MString MayaUsdProxyShapeBase::displayFilterLabel("USD Proxies"); // Attributes @@ -134,43 +130,30 @@ MObject MayaUsdProxyShapeBase::outStageDataAttr; MObject MayaUsdProxyShapeBase::outStageCacheIdAttr; /* static */ -void* -MayaUsdProxyShapeBase::creator() -{ - return new MayaUsdProxyShapeBase(); -} +void* MayaUsdProxyShapeBase::creator() { return new MayaUsdProxyShapeBase(); } /* static */ -MStatus -MayaUsdProxyShapeBase::initialize() +MStatus MayaUsdProxyShapeBase::initialize() { MStatus retValue = MS::kSuccess; // // create attr factories // - MFnNumericAttribute numericAttrFn; - MFnTypedAttribute typedAttrFn; - MFnUnitAttribute unitAttrFn; - - filePathAttr = typedAttrFn.create( - "filePath", - "fp", - MFnData::kString, - MObject::kNullObj, - &retValue); + MFnNumericAttribute numericAttrFn; + MFnTypedAttribute typedAttrFn; + MFnUnitAttribute unitAttrFn; + + filePathAttr + = typedAttrFn.create("filePath", "fp", MFnData::kString, MObject::kNullObj, &retValue); typedAttrFn.setInternal(true); typedAttrFn.setAffectsAppearance(true); CHECK_MSTATUS_AND_RETURN_IT(retValue); retValue = addAttribute(filePathAttr); CHECK_MSTATUS_AND_RETURN_IT(retValue); - primPathAttr = typedAttrFn.create( - "primPath", - "pp", - MFnData::kString, - MObject::kNullObj, - &retValue); + primPathAttr + = typedAttrFn.create("primPath", "pp", MFnData::kString, MObject::kNullObj, &retValue); typedAttrFn.setInternal(true); typedAttrFn.setAffectsAppearance(true); CHECK_MSTATUS_AND_RETURN_IT(retValue); @@ -178,23 +161,15 @@ MayaUsdProxyShapeBase::initialize() CHECK_MSTATUS_AND_RETURN_IT(retValue); excludePrimPathsAttr = typedAttrFn.create( - "excludePrimPaths", - "epp", - MFnData::kString, - MObject::kNullObj, - &retValue); + "excludePrimPaths", "epp", MFnData::kString, MObject::kNullObj, &retValue); typedAttrFn.setInternal(true); typedAttrFn.setAffectsAppearance(true); CHECK_MSTATUS_AND_RETURN_IT(retValue); retValue = addAttribute(excludePrimPathsAttr); CHECK_MSTATUS_AND_RETURN_IT(retValue); - loadPayloadsAttr = numericAttrFn.create( - "loadPayloads", - "lpl", - MFnNumericData::kBoolean, - 1.0, - &retValue); + loadPayloadsAttr + = numericAttrFn.create("loadPayloads", "lpl", MFnNumericData::kBoolean, 1.0, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); numericAttrFn.setKeyable(true); numericAttrFn.setReadable(false); @@ -202,23 +177,13 @@ MayaUsdProxyShapeBase::initialize() retValue = addAttribute(loadPayloadsAttr); CHECK_MSTATUS_AND_RETURN_IT(retValue); - timeAttr = unitAttrFn.create( - "time", - "tm", - MFnUnitAttribute::kTime, - 0.0, - &retValue); + timeAttr = unitAttrFn.create("time", "tm", MFnUnitAttribute::kTime, 0.0, &retValue); unitAttrFn.setAffectsAppearance(true); CHECK_MSTATUS_AND_RETURN_IT(retValue); retValue = addAttribute(timeAttr); CHECK_MSTATUS_AND_RETURN_IT(retValue); - complexityAttr = numericAttrFn.create( - "complexity", - "cplx", - MFnNumericData::kInt, - 0, - &retValue); + complexityAttr = numericAttrFn.create("complexity", "cplx", MFnNumericData::kInt, 0, &retValue); numericAttrFn.setMin(0); numericAttrFn.setSoftMax(4); numericAttrFn.setMax(8); @@ -230,11 +195,7 @@ MayaUsdProxyShapeBase::initialize() CHECK_MSTATUS_AND_RETURN_IT(retValue); inStageDataAttr = typedAttrFn.create( - "inStageData", - "id", - MayaUsdStageData::mayaTypeId, - MObject::kNullObj, - &retValue); + "inStageData", "id", MayaUsdStageData::mayaTypeId, MObject::kNullObj, &retValue); typedAttrFn.setReadable(false); typedAttrFn.setStorable(false); typedAttrFn.setDisconnectBehavior(MFnNumericAttribute::kReset); // on disconnect, reset to Null @@ -245,11 +206,7 @@ MayaUsdProxyShapeBase::initialize() // inStageData or filepath-> inStageDataCached -> outStageData inStageDataCachedAttr = typedAttrFn.create( - "inStageDataCached", - "idc", - MayaUsdStageData::mayaTypeId, - MObject::kNullObj, - &retValue); + "inStageDataCached", "idc", MayaUsdStageData::mayaTypeId, MObject::kNullObj, &retValue); typedAttrFn.setStorable(false); typedAttrFn.setWritable(false); typedAttrFn.setAffectsAppearance(true); @@ -257,14 +214,11 @@ MayaUsdProxyShapeBase::initialize() retValue = addAttribute(inStageDataCachedAttr); CHECK_MSTATUS_AND_RETURN_IT(retValue); - stageCacheIdAttr = numericAttrFn.create( - "stageCacheId", - "stcid", - MFnNumericData::kInt, - -1, - &retValue); + stageCacheIdAttr + = numericAttrFn.create("stageCacheId", "stcid", MFnNumericData::kInt, -1, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); - numericAttrFn.setDisconnectBehavior(MFnNumericAttribute::kReset); // on disconnect, reset to default + numericAttrFn.setDisconnectBehavior( + MFnNumericAttribute::kReset); // on disconnect, reset to default numericAttrFn.setStorable(false); numericAttrFn.setCached(true); numericAttrFn.setConnectable(true); @@ -275,11 +229,7 @@ MayaUsdProxyShapeBase::initialize() CHECK_MSTATUS_AND_RETURN_IT(retValue); drawRenderPurposeAttr = numericAttrFn.create( - "drawRenderPurpose", - "drp", - MFnNumericData::kBoolean, - 0.0, - &retValue); + "drawRenderPurpose", "drp", MFnNumericData::kBoolean, 0.0, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); numericAttrFn.setKeyable(true); numericAttrFn.setReadable(false); @@ -287,12 +237,8 @@ MayaUsdProxyShapeBase::initialize() retValue = addAttribute(drawRenderPurposeAttr); CHECK_MSTATUS_AND_RETURN_IT(retValue); - drawProxyPurposeAttr = numericAttrFn.create( - "drawProxyPurpose", - "dpp", - MFnNumericData::kBoolean, - 1.0, - &retValue); + drawProxyPurposeAttr + = numericAttrFn.create("drawProxyPurpose", "dpp", MFnNumericData::kBoolean, 1.0, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); numericAttrFn.setKeyable(true); numericAttrFn.setReadable(false); @@ -300,12 +246,8 @@ MayaUsdProxyShapeBase::initialize() retValue = addAttribute(drawProxyPurposeAttr); CHECK_MSTATUS_AND_RETURN_IT(retValue); - drawGuidePurposeAttr = numericAttrFn.create( - "drawGuidePurpose", - "dgp", - MFnNumericData::kBoolean, - 0.0, - &retValue); + drawGuidePurposeAttr + = numericAttrFn.create("drawGuidePurpose", "dgp", MFnNumericData::kBoolean, 0.0, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); numericAttrFn.setKeyable(true); numericAttrFn.setReadable(false); @@ -314,12 +256,7 @@ MayaUsdProxyShapeBase::initialize() CHECK_MSTATUS_AND_RETURN_IT(retValue); // outputs - outTimeAttr = unitAttrFn.create( - "outTime", - "otm", - MFnUnitAttribute::kTime, - 0.0, - &retValue); + outTimeAttr = unitAttrFn.create("outTime", "otm", MFnUnitAttribute::kTime, 0.0, &retValue); unitAttrFn.setCached(false); unitAttrFn.setConnectable(true); unitAttrFn.setReadable(true); @@ -331,30 +268,21 @@ MayaUsdProxyShapeBase::initialize() CHECK_MSTATUS_AND_RETURN_IT(retValue); outStageDataAttr = typedAttrFn.create( - "outStageData", - "od", - MayaUsdStageData::mayaTypeId, - MObject::kNullObj, - &retValue); + "outStageData", "od", MayaUsdStageData::mayaTypeId, MObject::kNullObj, &retValue); typedAttrFn.setStorable(false); typedAttrFn.setWritable(false); CHECK_MSTATUS_AND_RETURN_IT(retValue); retValue = addAttribute(outStageDataAttr); CHECK_MSTATUS_AND_RETURN_IT(retValue); - outStageCacheIdAttr = numericAttrFn.create( - "outStageCacheId", - "ostcid", - MFnNumericData::kInt, - -1, - &retValue); + outStageCacheIdAttr + = numericAttrFn.create("outStageCacheId", "ostcid", MFnNumericData::kInt, -1, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); typedAttrFn.setStorable(false); typedAttrFn.setWritable(false); retValue = addAttribute(outStageCacheIdAttr); CHECK_MSTATUS_AND_RETURN_IT(retValue); - // // add attribute dependencies // @@ -405,26 +333,24 @@ MayaUsdProxyShapeBase::initialize() } /* static */ -MayaUsdProxyShapeBase* -MayaUsdProxyShapeBase::GetShapeAtDagPath(const MDagPath& dagPath) +MayaUsdProxyShapeBase* MayaUsdProxyShapeBase::GetShapeAtDagPath(const MDagPath& dagPath) { MObject mObj = dagPath.node(); if (mObj.apiType() != MFn::kPluginShape) { TF_CODING_ERROR( - "Could not get MayaUsdProxyShapeBase for non-plugin shape node " - "at DAG path: %s (apiTypeStr = %s)", - dagPath.fullPathName().asChar(), - mObj.apiTypeStr()); + "Could not get MayaUsdProxyShapeBase for non-plugin shape node " + "at DAG path: %s (apiTypeStr = %s)", + dagPath.fullPathName().asChar(), + mObj.apiTypeStr()); return nullptr; } const MFnDependencyNode depNodeFn(mObj); - MayaUsdProxyShapeBase* pShape = - static_cast(depNodeFn.userNode()); + MayaUsdProxyShapeBase* pShape = static_cast(depNodeFn.userNode()); if (!pShape) { TF_CODING_ERROR( - "Could not get MayaUsdProxyShapeBase for node at DAG path: %s", - dagPath.fullPathName().asChar()); + "Could not get MayaUsdProxyShapeBase for node at DAG path: %s", + dagPath.fullPathName().asChar()); return nullptr; } @@ -432,28 +358,21 @@ MayaUsdProxyShapeBase::GetShapeAtDagPath(const MDagPath& dagPath) } /* static */ -void -MayaUsdProxyShapeBase::SetClosestPointDelegate(ClosestPointDelegate delegate) +void MayaUsdProxyShapeBase::SetClosestPointDelegate(ClosestPointDelegate delegate) { _sharedClosestPointDelegate = delegate; } /* virtual */ -bool -MayaUsdProxyShapeBase::GetObjectSoftSelectEnabled() const -{ - return false; -} +bool MayaUsdProxyShapeBase::GetObjectSoftSelectEnabled() const { return false; } -void -MayaUsdProxyShapeBase::enableProxyAccessor() +void MayaUsdProxyShapeBase::enableProxyAccessor() { _usdAccessor = ProxyAccessor::createAndRegister(*this); } /* virtual */ -void -MayaUsdProxyShapeBase::postConstructor() +void MayaUsdProxyShapeBase::postConstructor() { setRenderable(true); @@ -461,18 +380,14 @@ MayaUsdProxyShapeBase::postConstructor() } /* virtual */ -MStatus -MayaUsdProxyShapeBase::compute(const MPlug& plug, MDataBlock& dataBlock) +MStatus MayaUsdProxyShapeBase::compute(const MPlug& plug, MDataBlock& dataBlock) { - if(plug == outTimeAttr || plug.isDynamic()) + if (plug == outTimeAttr || plug.isDynamic()) ProxyAccessor::compute(_usdAccessor, plug, dataBlock); - if (plug == excludePrimPathsAttr || - plug == timeAttr || - plug == complexityAttr || - plug == drawRenderPurposeAttr || - plug == drawProxyPurposeAttr || - plug == drawGuidePurposeAttr) { + if (plug == excludePrimPathsAttr || plug == timeAttr || plug == complexityAttr + || plug == drawRenderPurposeAttr || plug == drawProxyPurposeAttr + || plug == drawGuidePurposeAttr) { // If the attribute that needs to be computed is one of these, then it // does not affect the ouput stage data, but it *does* affect imaging // the shape. In that case, we notify Maya that the shape needs to be @@ -483,17 +398,13 @@ MayaUsdProxyShapeBase::compute(const MPlug& plug, MDataBlock& dataBlock) // setDependentsDirty() might not get called and only compute() might. MHWRender::MRenderer::setGeometryDrawDirty(thisMObject()); return MS::kUnknownParameter; - } - else if (plug == inStageDataCachedAttr) { + } else if (plug == inStageDataCachedAttr) { return computeInStageDataCached(dataBlock); - } - else if (plug == outTimeAttr) { + } else if (plug == outTimeAttr) { return computeOutputTime(dataBlock); - } - else if (plug == outStageDataAttr) { + } else if (plug == outStageDataAttr) { return computeOutStageData(dataBlock); - } - else if (plug == outStageCacheIdAttr) { + } else if (plug == outStageCacheIdAttr) { return computeOutStageCacheId(dataBlock); } @@ -501,14 +412,9 @@ MayaUsdProxyShapeBase::compute(const MPlug& plug, MDataBlock& dataBlock) } /* virtual */ -SdfLayerRefPtr -MayaUsdProxyShapeBase::computeSessionLayer(MDataBlock&) -{ - return nullptr; -} +SdfLayerRefPtr MayaUsdProxyShapeBase::computeSessionLayer(MDataBlock&) { return nullptr; } -MStatus -MayaUsdProxyShapeBase::computeInStageDataCached(MDataBlock& dataBlock) +MStatus MayaUsdProxyShapeBase::computeInStageDataCached(MDataBlock& dataBlock) { MStatus retValue = MS::kSuccess; @@ -516,7 +422,7 @@ MayaUsdProxyShapeBase::computeInStageDataCached(MDataBlock& dataBlock) CHECK_MSTATUS_AND_RETURN_IT(retValue); // If inData has an incoming connection, then use it. Otherwise generate stage from the filepath - if (!inDataHandle.data().isNull() ) { + if (!inDataHandle.data().isNull()) { // // Propagate inData -> inDataCached // @@ -527,17 +433,14 @@ MayaUsdProxyShapeBase::computeInStageDataCached(MDataBlock& dataBlock) inDataCachedHandle.setClean(); return MS::kSuccess; - } - else if(!dataBlock.context().isNormal()) - { + } else if (!dataBlock.context().isNormal()) { // Create the output outData ======== MFnPluginData pluginDataFn; - MObject stageDataObj = - pluginDataFn.create(MayaUsdStageData::mayaTypeId, &retValue); + MObject stageDataObj = pluginDataFn.create(MayaUsdStageData::mayaTypeId, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); - MayaUsdStageData* outData = - reinterpret_cast(pluginDataFn.data(&retValue)); + MayaUsdStageData* outData + = reinterpret_cast(pluginDataFn.data(&retValue)); CHECK_MSTATUS_AND_RETURN_IT(retValue); // When evaluating in background we should point to the same stage as in normal context @@ -546,14 +449,14 @@ MayaUsdProxyShapeBase::computeInStageDataCached(MDataBlock& dataBlock) MDGContext normalContext; { MDGContextGuard contextGuard(normalContext); - MDataBlock dataBlockForNormalContext = forceCache(); + MDataBlock dataBlockForNormalContext = forceCache(); - MDataHandle inDataCachedHandleForNormalContext = - dataBlockForNormalContext.inputValue(inStageDataCachedAttr, &retValue); + MDataHandle inDataCachedHandleForNormalContext + = dataBlockForNormalContext.inputValue(inStageDataCachedAttr, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); - MayaUsdStageData* inData = - dynamic_cast(inDataCachedHandleForNormalContext.asPluginData()); + MayaUsdStageData* inData = dynamic_cast( + inDataCachedHandleForNormalContext.asPluginData()); // Set the outUsdStageData outData->stage = inData->stage; @@ -561,15 +464,13 @@ MayaUsdProxyShapeBase::computeInStageDataCached(MDataBlock& dataBlock) } // Retrieve data handle for stage data cache - MDataHandle outDataCachedHandle = - dataBlock.outputValue(inStageDataCachedAttr, &retValue); + MDataHandle outDataCachedHandle = dataBlock.outputValue(inStageDataCachedAttr, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); outDataCachedHandle.set(outData); outDataCachedHandle.setClean(); return MS::kSuccess; - } - else { + } else { // Check if we have a Stage from the Cache Id const auto cacheIdNum = dataBlock.inputValue(stageCacheIdAttr, &retValue).asInt(); CHECK_MSTATUS_AND_RETURN_IT(retValue); @@ -578,8 +479,7 @@ MayaUsdProxyShapeBase::computeInStageDataCached(MDataBlock& dataBlock) const auto stageCached = cacheId.IsValid() && UsdUtilsStageCache::Get().Contains(cacheId); if (stageCached) { usdStage = UsdUtilsStageCache::Get().Find(cacheId); - } - else { + } else { // // Calculate from USD filepath and primPath and variantKey // @@ -593,30 +493,37 @@ MayaUsdProxyShapeBase::computeInStageDataCached(MDataBlock& dataBlock) // std::string fileString = TfStringTrimRight(file.asChar()); - TF_DEBUG(USDMAYA_PROXYSHAPEBASE).Msg("ProxyShapeBase::reloadStage original USD file path is %s\n", fileString.c_str()); + TF_DEBUG(USDMAYA_PROXYSHAPEBASE) + .Msg( + "ProxyShapeBase::reloadStage original USD file path is %s\n", + fileString.c_str()); boost::filesystem::path filestringPath(fileString); - if(filestringPath.is_absolute()) - { + if (filestringPath.is_absolute()) { fileString = UsdMayaUtilFileSystem::resolvePath(fileString); - TF_DEBUG(USDMAYA_PROXYSHAPEBASE).Msg("ProxyShapeBase::reloadStage resolved the USD file path to %s\n", fileString.c_str()); - } - else - { - fileString = UsdMayaUtilFileSystem::resolveRelativePathWithinMayaContext(thisMObject(), fileString); - TF_DEBUG(USDMAYA_PROXYSHAPEBASE).Msg("ProxyShapeBase::reloadStage resolved the relative USD file path to %s\n", fileString.c_str()); + TF_DEBUG(USDMAYA_PROXYSHAPEBASE) + .Msg( + "ProxyShapeBase::reloadStage resolved the USD file path to %s\n", + fileString.c_str()); + } else { + fileString = UsdMayaUtilFileSystem::resolveRelativePathWithinMayaContext( + thisMObject(), fileString); + TF_DEBUG(USDMAYA_PROXYSHAPEBASE) + .Msg( + "ProxyShapeBase::reloadStage resolved the relative USD file path to %s\n", + fileString.c_str()); } // Fall back on providing the path "as is" to USD - if (fileString.empty()) - { + if (fileString.empty()) { fileString.assign(file.asChar(), file.length()); } - TF_DEBUG(USDMAYA_PROXYSHAPEBASE).Msg("ProxyShapeBase::loadStage called for the usd file: %s\n", fileString.c_str()); + TF_DEBUG(USDMAYA_PROXYSHAPEBASE) + .Msg("ProxyShapeBase::loadStage called for the usd file: %s\n", fileString.c_str()); // == Load the Stage - auto loadSet = UsdStage::InitialLoadSet::LoadAll; + auto loadSet = UsdStage::InitialLoadSet::LoadAll; MDataHandle loadPayloadsHandle = dataBlock.inputValue(loadPayloadsAttr, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); @@ -629,42 +536,38 @@ MayaUsdProxyShapeBase::computeInStageDataCached(MDataBlock& dataBlock) // The stage cache is the only one who holds a strong reference to the // UsdStage. See https://github.com/Autodesk/maya-usd/issues/528 for // more information. - UsdStageCacheContext ctx(UsdMayaStageCache::Get(loadSet == UsdStage::InitialLoadSet::LoadAll)); + UsdStageCacheContext ctx( + UsdMayaStageCache::Get(loadSet == UsdStage::InitialLoadSet::LoadAll)); if (SdfLayerRefPtr rootLayer = SdfLayer::FindOrOpen(fileString)) { SdfLayerRefPtr sessionLayer = computeSessionLayer(dataBlock); if (sessionLayer) { - usdStage = UsdStage::Open(rootLayer, - sessionLayer, - ArGetResolver().GetCurrentContext(), - loadSet); + usdStage = UsdStage::Open( + rootLayer, sessionLayer, ArGetResolver().GetCurrentContext(), loadSet); } else { - usdStage = UsdStage::Open(rootLayer, - ArGetResolver().GetCurrentContext(), - loadSet); + usdStage = UsdStage::Open( + rootLayer, ArGetResolver().GetCurrentContext(), loadSet); } usdStage->SetEditTarget(usdStage->GetRootLayer()); - } - else { + } else { // Create a new stage in memory with an anonymous root layer. usdStage = UsdStage::CreateInMemory(kAnonymousLayerName, loadSet); } } - } - SdfPath primPath; + } + SdfPath primPath; if (usdStage) { primPath = usdStage->GetPseudoRoot().GetPath(); } // Create the output outData ======== MFnPluginData pluginDataFn; - MObject stageDataObj = - pluginDataFn.create(MayaUsdStageData::mayaTypeId, &retValue); + MObject stageDataObj = pluginDataFn.create(MayaUsdStageData::mayaTypeId, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); - MayaUsdStageData* stageData = - reinterpret_cast(pluginDataFn.data(&retValue)); + MayaUsdStageData* stageData + = reinterpret_cast(pluginDataFn.data(&retValue)); CHECK_MSTATUS_AND_RETURN_IT(retValue); // Set the outUsdStageData @@ -674,8 +577,7 @@ MayaUsdProxyShapeBase::computeInStageDataCached(MDataBlock& dataBlock) // // set the data on the output plug // - MDataHandle inDataCachedHandle = - dataBlock.outputValue(inStageDataCachedAttr, &retValue); + MDataHandle inDataCachedHandle = dataBlock.outputValue(inStageDataCachedAttr, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); inDataCachedHandle.set(stageData); @@ -684,14 +586,12 @@ MayaUsdProxyShapeBase::computeInStageDataCached(MDataBlock& dataBlock) } } -MStatus -MayaUsdProxyShapeBase::computeOutStageData(MDataBlock& dataBlock) +MStatus MayaUsdProxyShapeBase::computeOutStageData(MDataBlock& dataBlock) { MStatus retValue = MS::kSuccess; const bool isNormalContext = dataBlock.context().isNormal(); - if(isNormalContext) - { + if (isNormalContext) { TfReset(_boundingBoxCache); // Reset the stage listener until we determine that everything is valid. @@ -700,16 +600,13 @@ MayaUsdProxyShapeBase::computeOutStageData(MDataBlock& dataBlock) _stageNoticeListener.SetStageObjectsChangedCallback(nullptr); } - MDataHandle inDataCachedHandle = - dataBlock.inputValue(inStageDataCachedAttr, &retValue); + MDataHandle inDataCachedHandle = dataBlock.inputValue(inStageDataCachedAttr, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); UsdStageRefPtr usdStage; - MayaUsdStageData* inData = - dynamic_cast(inDataCachedHandle.asPluginData()); - if(inData) - { + MayaUsdStageData* inData = dynamic_cast(inDataCachedHandle.asPluginData()); + if (inData) { usdStage = inData->stage; } @@ -729,22 +626,22 @@ MayaUsdProxyShapeBase::computeOutStageData(MDataBlock& dataBlock) // Get the prim // If no primPath string specified, then use the pseudo-root. - UsdPrim usdPrim; + UsdPrim usdPrim; std::string primPathStr(primPath.asChar(), primPath.length()); - if ( !primPathStr.empty() ) { + if (!primPathStr.empty()) { SdfPath primPath(primPathStr); // Validate assumption: primPath is descendent of passed-in stage primPath // Make sure that the primPath is a child of the passed in stage's primpath - if ( primPath.HasPrefix(inData->primPath) ) { - usdPrim = usdStage->GetPrimAtPath( primPath ); - } - else { - TF_WARN("%s: Shape primPath <%s> is not a descendant of input " - "stage primPath <%s>", - MPxSurfaceShape::name().asChar(), - primPath.GetText(), - inData->primPath.GetText()); + if (primPath.HasPrefix(inData->primPath)) { + usdPrim = usdStage->GetPrimAtPath(primPath); + } else { + TF_WARN( + "%s: Shape primPath <%s> is not a descendant of input " + "stage primPath <%s>", + MPxSurfaceShape::name().asChar(), + primPath.GetText(), + inData->primPath.GetText()); } } else { usdPrim = usdStage->GetPseudoRoot(); @@ -752,40 +649,37 @@ MayaUsdProxyShapeBase::computeOutStageData(MDataBlock& dataBlock) // Create the output outData MFnPluginData pluginDataFn; - MObject stageDataObj = - pluginDataFn.create(MayaUsdStageData::mayaTypeId, &retValue); + MObject stageDataObj = pluginDataFn.create(MayaUsdStageData::mayaTypeId, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); - MayaUsdStageData* stageData = - reinterpret_cast(pluginDataFn.data(&retValue)); + MayaUsdStageData* stageData = reinterpret_cast(pluginDataFn.data(&retValue)); CHECK_MSTATUS_AND_RETURN_IT(retValue); // Set the outUsdStageData stageData->stage = usdStage; - stageData->primPath = usdPrim ? usdPrim.GetPath() : - usdStage->GetPseudoRoot().GetPath(); + stageData->primPath = usdPrim ? usdPrim.GetPath() : usdStage->GetPseudoRoot().GetPath(); // // set the data on the output plug // - MDataHandle outDataHandle = - dataBlock.outputValue(outStageDataAttr, &retValue); + MDataHandle outDataHandle = dataBlock.outputValue(outStageDataAttr, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); outDataHandle.set(stageData); outDataHandle.setClean(); - if(isNormalContext) - { + if (isNormalContext) { // Start listening for notices for the USD stage. _stageNoticeListener.SetStage(usdStage); - _stageNoticeListener.SetStageContentsChangedCallback([this](const UsdNotice::StageContentsChanged& notice) { - return _OnStageContentsChanged(notice); - }); + _stageNoticeListener.SetStageContentsChangedCallback( + [this](const UsdNotice::StageContentsChanged& notice) { + return _OnStageContentsChanged(notice); + }); - _stageNoticeListener.SetStageObjectsChangedCallback([this](const UsdNotice::ObjectsChanged& notice) { - return _OnStageObjectsChanged(notice); - }); + _stageNoticeListener.SetStageObjectsChangedCallback( + [this](const UsdNotice::ObjectsChanged& notice) { + return _OnStageObjectsChanged(notice); + }); MayaUsdProxyStageSetNotice(*this).Send(); } @@ -793,10 +687,9 @@ MayaUsdProxyShapeBase::computeOutStageData(MDataBlock& dataBlock) return MS::kSuccess; } -MStatus -MayaUsdProxyShapeBase::computeOutputTime(MDataBlock& dataBlock) +MStatus MayaUsdProxyShapeBase::computeOutputTime(MDataBlock& dataBlock) { - MStatus retValue = MS::kSuccess; + MStatus retValue = MS::kSuccess; MDataHandle inDataHandle = dataBlock.inputValue(timeAttr, &retValue); CHECK_MSTATUS_AND_RETURN_IT(retValue); @@ -810,8 +703,7 @@ MayaUsdProxyShapeBase::computeOutputTime(MDataBlock& dataBlock) return retValue; } -MStatus -MayaUsdProxyShapeBase::computeOutStageCacheId(MDataBlock& dataBlock) +MStatus MayaUsdProxyShapeBase::computeOutStageCacheId(MDataBlock& dataBlock) { MStatus retValue = MS::kSuccess; @@ -829,8 +721,8 @@ MayaUsdProxyShapeBase::computeOutStageCacheId(MDataBlock& dataBlock) return MS::kFailure; } - int cacheId = -1; - auto id = UsdUtilsStageCache::Get().Insert(usdStage); + int cacheId = -1; + auto id = UsdUtilsStageCache::Get().Insert(usdStage); if (id) cacheId = id.ToLongInt(); @@ -844,27 +736,19 @@ MayaUsdProxyShapeBase::computeOutStageCacheId(MDataBlock& dataBlock) } /* virtual */ -bool -MayaUsdProxyShapeBase::isBounded() const -{ - return isStageValid(); -} +bool MayaUsdProxyShapeBase::isBounded() const { return isStageValid(); } /* virtual */ -void -MayaUsdProxyShapeBase::CacheEmptyBoundingBox(MBoundingBox&) -{} +void MayaUsdProxyShapeBase::CacheEmptyBoundingBox(MBoundingBox&) { } /* virtual */ -UsdTimeCode -MayaUsdProxyShapeBase::GetOutputTime(MDataBlock dataBlock) const +UsdTimeCode MayaUsdProxyShapeBase::GetOutputTime(MDataBlock dataBlock) const { return _GetTime(dataBlock); } /* virtual */ -MBoundingBox -MayaUsdProxyShapeBase::boundingBox() const +MBoundingBox MayaUsdProxyShapeBase::boundingBox() const { TRACE_FUNCTION(); @@ -872,7 +756,7 @@ MayaUsdProxyShapeBase::boundingBox() const // Make sure outStage is up to date MayaUsdProxyShapeBase* nonConstThis = const_cast(this); - MDataBlock dataBlock = nonConstThis->forceCache(); + MDataBlock dataBlock = nonConstThis->forceCache(); dataBlock.inputValue(outStageDataAttr, &status); CHECK_MSTATUS_AND_RETURN(status, MBoundingBox()); @@ -882,8 +766,8 @@ MayaUsdProxyShapeBase::boundingBox() const // memory overhead of a cache entry per frame UsdTimeCode currTime = GetOutputTime(dataBlock); - std::map::const_iterator cacheLookup = - _boundingBoxCache.find(currTime); + std::map::const_iterator cacheLookup + = _boundingBoxCache.find(currTime); if (cacheLookup != _boundingBoxCache.end()) { return cacheLookup->second; @@ -899,117 +783,103 @@ MayaUsdProxyShapeBase::boundingBox() const bool drawRenderPurpose = false; bool drawProxyPurpose = true; bool drawGuidePurpose = false; - _GetDrawPurposeToggles( - dataBlock, - &drawRenderPurpose, - &drawProxyPurpose, - &drawGuidePurpose); + _GetDrawPurposeToggles(dataBlock, &drawRenderPurpose, &drawProxyPurpose, &drawGuidePurpose); const TfToken purpose1 = UsdGeomTokens->default_; - const TfToken purpose2 = - drawRenderPurpose ? UsdGeomTokens->render : TfToken(); - const TfToken purpose3 = - drawProxyPurpose ? UsdGeomTokens->proxy : TfToken(); - const TfToken purpose4 = - drawGuidePurpose ? UsdGeomTokens->guide : TfToken(); - - const GfBBox3d allBox = imageablePrim.ComputeUntransformedBound( - currTime, - purpose1, - purpose2, - purpose3, - purpose4); - - MBoundingBox &retval = nonConstThis->_boundingBoxCache[currTime]; + const TfToken purpose2 = drawRenderPurpose ? UsdGeomTokens->render : TfToken(); + const TfToken purpose3 = drawProxyPurpose ? UsdGeomTokens->proxy : TfToken(); + const TfToken purpose4 = drawGuidePurpose ? UsdGeomTokens->guide : TfToken(); + + const GfBBox3d allBox + = imageablePrim.ComputeUntransformedBound(currTime, purpose1, purpose2, purpose3, purpose4); + + MBoundingBox& retval = nonConstThis->_boundingBoxCache[currTime]; const GfRange3d boxRange = allBox.ComputeAlignedBox(); // Convert to GfRange3d to MBoundingBox - if ( !boxRange.IsEmpty() ) { + if (!boxRange.IsEmpty()) { const GfVec3d boxMin = boxRange.GetMin(); const GfVec3d boxMax = boxRange.GetMax(); retval = MBoundingBox( - MPoint(boxMin[0], boxMin[1], boxMin[2]), - MPoint(boxMax[0], boxMax[1], boxMax[2])); - } - else { + MPoint(boxMin[0], boxMin[1], boxMin[2]), MPoint(boxMax[0], boxMax[1], boxMax[2])); + } else { nonConstThis->CacheEmptyBoundingBox(retval); } return retval; } -void -MayaUsdProxyShapeBase::clearBoundingBoxCache() -{ - _boundingBoxCache.clear(); -} +void MayaUsdProxyShapeBase::clearBoundingBoxCache() { _boundingBoxCache.clear(); } -bool -MayaUsdProxyShapeBase::isStageValid() const +bool MayaUsdProxyShapeBase::isStageValid() const { - MStatus localStatus; + MStatus localStatus; MayaUsdProxyShapeBase* nonConstThis = const_cast(this); - MDataBlock dataBlock = nonConstThis->forceCache(); + MDataBlock dataBlock = nonConstThis->forceCache(); MDataHandle outDataHandle = dataBlock.inputValue(outStageDataAttr, &localStatus); CHECK_MSTATUS_AND_RETURN(localStatus, false); - MayaUsdStageData* outData = - dynamic_cast(outDataHandle.asPluginData()); - if(!outData || !outData->stage) { + MayaUsdStageData* outData = dynamic_cast(outDataHandle.asPluginData()); + if (!outData || !outData->stage) { return false; } return true; } -MStatus -MayaUsdProxyShapeBase::preEvaluation(const MDGContext& context, const MEvaluationNode& evaluationNode) +MStatus MayaUsdProxyShapeBase::preEvaluation( + const MDGContext& context, + const MEvaluationNode& evaluationNode) { - // Any logic here should have an equivalent implementation in MayaUsdProxyShapeBase::setDependentsDirty(). - if (context.isNormal()) - { + // Any logic here should have an equivalent implementation in + // MayaUsdProxyShapeBase::setDependentsDirty(). + if (context.isNormal()) { if (evaluationNode.dirtyPlugExists(excludePrimPathsAttr)) { _IncreaseExcludePrimPathsVersion(); - } - else if (evaluationNode.dirtyPlugExists(outStageDataAttr) || + } else if ( + evaluationNode.dirtyPlugExists(outStageDataAttr) || // All the plugs that affect outStageDataAttr - evaluationNode.dirtyPlugExists(filePathAttr) || - evaluationNode.dirtyPlugExists(primPathAttr) || - evaluationNode.dirtyPlugExists(loadPayloadsAttr) || - evaluationNode.dirtyPlugExists(inStageDataAttr) || - evaluationNode.dirtyPlugExists(stageCacheIdAttr)) { + evaluationNode.dirtyPlugExists(filePathAttr) + || evaluationNode.dirtyPlugExists(primPathAttr) + || evaluationNode.dirtyPlugExists(loadPayloadsAttr) + || evaluationNode.dirtyPlugExists(inStageDataAttr) + || evaluationNode.dirtyPlugExists(stageCacheIdAttr)) { _IncreaseUsdStageVersion(); MayaUsdProxyStageInvalidateNotice(*this).Send(); } } - return MPxSurfaceShape::preEvaluation(context,evaluationNode); + return MPxSurfaceShape::preEvaluation(context, evaluationNode); } -MStatus -MayaUsdProxyShapeBase::postEvaluation(const MDGContext& context, const MEvaluationNode& evaluationNode, PostEvaluationType evalType) +MStatus MayaUsdProxyShapeBase::postEvaluation( + const MDGContext& context, + const MEvaluationNode& evaluationNode, + PostEvaluationType evalType) { - // When a node is evaluated by evaluation manager setDependentsDirty is not called. The functionality in setDependentsDirty needs - // to be duplicated in preEvaluation or postEvaluation. I don't think we need the call to setGeometryDrawDirty() in - // setDependentsDirty, but there may be a workflow I'm not seeing that does require it. I'm leaving this here commented out as a - // reminder that we should either have both calls to setGeometryDrawDirty, or no calls to setGeometryDrawDirty. + // When a node is evaluated by evaluation manager setDependentsDirty is not called. The + // functionality in setDependentsDirty needs to be duplicated in preEvaluation or + // postEvaluation. I don't think we need the call to setGeometryDrawDirty() in + // setDependentsDirty, but there may be a workflow I'm not seeing that does require it. I'm + // leaving this here commented out as a reminder that we should either have both calls to + // setGeometryDrawDirty, or no calls to setGeometryDrawDirty. // MHWRender::MRenderer::setGeometryDrawDirty(thisMObject()); - if(context.isNormal() && evalType == PostEvaluationEnum::kEvaluatedDirectly) { + if (context.isNormal() && evalType == PostEvaluationEnum::kEvaluatedDirectly) { MDataBlock dataBlock = forceCache(); ProxyAccessor::syncCache(_usdAccessor, thisMObject(), dataBlock); } - return MPxSurfaceShape::postEvaluation(context,evaluationNode,evalType); + return MPxSurfaceShape::postEvaluation(context, evaluationNode, evalType); } /* virtual */ -MStatus -MayaUsdProxyShapeBase::setDependentsDirty(const MPlug& plug, MPlugArray& plugArray) +MStatus MayaUsdProxyShapeBase::setDependentsDirty(const MPlug& plug, MPlugArray& plugArray) { - // Any logic here should have an equivalent implementation in MayaUsdProxyShapeBase::preEvaluation() or postEvaluation(). + // Any logic here should have an equivalent implementation in + // MayaUsdProxyShapeBase::preEvaluation() or postEvaluation(). MStatus retValue; @@ -1021,14 +891,11 @@ MayaUsdProxyShapeBase::setDependentsDirty(const MPlug& plug, MPlugArray& plugArr if (plug == excludePrimPathsAttr) { _IncreaseExcludePrimPathsVersion(); - } - else if (plug == outStageDataAttr || + } else if ( + plug == outStageDataAttr || // All the plugs that affect outStageDataAttr - plug == filePathAttr || - plug == primPathAttr || - plug == loadPayloadsAttr || - plug == inStageDataAttr || - plug == stageCacheIdAttr) { + plug == filePathAttr || plug == primPathAttr || plug == loadPayloadsAttr + || plug == inStageDataAttr || plug == stageCacheIdAttr) { _IncreaseUsdStageVersion(); MayaUsdProxyStageInvalidateNotice(*this).Send(); } @@ -1039,10 +906,8 @@ MayaUsdProxyShapeBase::setDependentsDirty(const MPlug& plug, MPlugArray& plugArr // If accessor returns success when adding dirty plugs we have to get renderer to // trigger compute. We achieve it by adding timeAttr to dirty plugArray. This will guarantee // we don't render something that requires inputs evaluted by DG. - if(plug == timeAttr || plug.isDynamic()) - { - if (ProxyAccessor::addDependentsDirty(_usdAccessor, plug, plugArray) == MS::kSuccess) - { + if (plug == timeAttr || plug.isDynamic()) { + if (ProxyAccessor::addDependentsDirty(_usdAccessor, plug, plugArray) == MS::kSuccess) { MPlug outTimePlug(thisMObject(), outTimeAttr); plugArray.append(outTimePlug); } @@ -1053,8 +918,11 @@ MayaUsdProxyShapeBase::setDependentsDirty(const MPlug& plug, MPlugArray& plugArr #if MAYA_API_VERSION >= 20210000 /* virtual */ -void -MayaUsdProxyShapeBase::getCacheSetup(const MEvaluationNode& evalNode, MNodeCacheDisablingInfo& disablingInfo, MNodeCacheSetupInfo& cacheSetupInfo, MObjectArray& monitoredAttributes) const +void MayaUsdProxyShapeBase::getCacheSetup( + const MEvaluationNode& evalNode, + MNodeCacheDisablingInfo& disablingInfo, + MNodeCacheSetupInfo& cacheSetupInfo, + MObjectArray& monitoredAttributes) const { MPxSurfaceShape::getCacheSetup(evalNode, disablingInfo, cacheSetupInfo, monitoredAttributes); // We want this node to be cached by default (unless cache rules have been configured @@ -1063,52 +931,46 @@ MayaUsdProxyShapeBase::getCacheSetup(const MEvaluationNode& evalNode, MNodeCache } /* virtual */ -void -MayaUsdProxyShapeBase::configCache(const MEvaluationNode& evalNode, MCacheSchema& schema) const +void MayaUsdProxyShapeBase::configCache(const MEvaluationNode& evalNode, MCacheSchema& schema) const { - MPxSurfaceShape::configCache(evalNode,schema); + MPxSurfaceShape::configCache(evalNode, schema); // Out time is not always a dirty plug, but time can be animated. This is why we will // store input time and enable quick compute within proxy shape for out time schema.add(timeAttr); } #endif -UsdPrim -MayaUsdProxyShapeBase::_GetUsdPrim(MDataBlock dataBlock) const +UsdPrim MayaUsdProxyShapeBase::_GetUsdPrim(MDataBlock dataBlock) const { MStatus localStatus; UsdPrim usdPrim; - MDataHandle outDataHandle = - dataBlock.inputValue(outStageDataAttr, &localStatus); + MDataHandle outDataHandle = dataBlock.inputValue(outStageDataAttr, &localStatus); CHECK_MSTATUS_AND_RETURN(localStatus, usdPrim); MayaUsdStageData* outData = dynamic_cast(outDataHandle.asPluginData()); - if(!outData) { + if (!outData) { return usdPrim; // empty UsdPrim } - if(!outData->stage) { + if (!outData->stage) { return usdPrim; // empty UsdPrim } - usdPrim = (outData->primPath.IsEmpty()) ? - outData->stage->GetPseudoRoot() : - outData->stage->GetPrimAtPath(outData->primPath); + usdPrim = (outData->primPath.IsEmpty()) ? outData->stage->GetPseudoRoot() + : outData->stage->GetPrimAtPath(outData->primPath); return usdPrim; } -int -MayaUsdProxyShapeBase::getComplexity() const +int MayaUsdProxyShapeBase::getComplexity() const { - return _GetComplexity( const_cast(this)->forceCache() ); + return _GetComplexity(const_cast(this)->forceCache()); } -int -MayaUsdProxyShapeBase::_GetComplexity(MDataBlock dataBlock) const +int MayaUsdProxyShapeBase::_GetComplexity(MDataBlock dataBlock) const { - int complexity = 0; + int complexity = 0; MStatus status; complexity = dataBlock.inputValue(complexityAttr, &status).asInt(); @@ -1116,45 +978,36 @@ MayaUsdProxyShapeBase::_GetComplexity(MDataBlock dataBlock) const return complexity; } -UsdTimeCode -MayaUsdProxyShapeBase::getTime() const +UsdTimeCode MayaUsdProxyShapeBase::getTime() const { - return _GetTime( const_cast(this)->forceCache() ); + return _GetTime(const_cast(this)->forceCache()); } -UsdTimeCode -MayaUsdProxyShapeBase::_GetTime(MDataBlock dataBlock) const +UsdTimeCode MayaUsdProxyShapeBase::_GetTime(MDataBlock dataBlock) const { MStatus status; return UsdTimeCode(dataBlock.inputValue(outTimeAttr, &status).asTime().value()); } -UsdStageRefPtr -MayaUsdProxyShapeBase::getUsdStage() const +UsdStageRefPtr MayaUsdProxyShapeBase::getUsdStage() const { - MStatus localStatus; + MStatus localStatus; MayaUsdProxyShapeBase* nonConstThis = const_cast(this); - MDataBlock dataBlock = nonConstThis->forceCache(); + MDataBlock dataBlock = nonConstThis->forceCache(); MDataHandle outDataHandle = dataBlock.inputValue(outStageDataAttr, &localStatus); CHECK_MSTATUS_AND_RETURN(localStatus, UsdStageRefPtr()); - MayaUsdStageData* outData = - dynamic_cast(outDataHandle.asPluginData()); + MayaUsdStageData* outData = dynamic_cast(outDataHandle.asPluginData()); if (outData && outData->stage) return outData->stage; else return {}; - -} - -size_t -MayaUsdProxyShapeBase::getUsdStageVersion() const { - return _UsdStageVersion; } +size_t MayaUsdProxyShapeBase::getUsdStageVersion() const { return _UsdStageVersion; } void MayaUsdProxyShapeBase::getDrawPurposeToggles( bool* drawRenderPurpose, @@ -1165,26 +1018,22 @@ void MayaUsdProxyShapeBase::getDrawPurposeToggles( _GetDrawPurposeToggles(dataBlock, drawRenderPurpose, drawProxyPurpose, drawGuidePurpose); } -SdfPathVector -MayaUsdProxyShapeBase::getExcludePrimPaths() const +SdfPathVector MayaUsdProxyShapeBase::getExcludePrimPaths() const { - return _GetExcludePrimPaths( const_cast(this)->forceCache() ); + return _GetExcludePrimPaths(const_cast(this)->forceCache()); } -size_t -MayaUsdProxyShapeBase::getExcludePrimPathsVersion() const { +size_t MayaUsdProxyShapeBase::getExcludePrimPathsVersion() const +{ return _excludePrimPathsVersion; } -SdfPathVector -MayaUsdProxyShapeBase::_GetExcludePrimPaths(MDataBlock dataBlock) const +SdfPathVector MayaUsdProxyShapeBase::_GetExcludePrimPaths(MDataBlock dataBlock) const { SdfPathVector ret; - const MString excludePrimPathsStr = - dataBlock.inputValue(excludePrimPathsAttr).asString(); - std::vector excludePrimPaths = - TfStringTokenize(excludePrimPathsStr.asChar(), ","); + const MString excludePrimPathsStr = dataBlock.inputValue(excludePrimPathsAttr).asString(); + std::vector excludePrimPaths = TfStringTokenize(excludePrimPathsStr.asChar(), ","); ret.resize(excludePrimPaths.size()); for (size_t i = 0; i < excludePrimPaths.size(); ++i) { ret[i] = SdfPath(TfStringTrim(excludePrimPaths[i])); @@ -1193,25 +1042,21 @@ MayaUsdProxyShapeBase::_GetExcludePrimPaths(MDataBlock dataBlock) const return ret; } -bool -MayaUsdProxyShapeBase::_GetDrawPurposeToggles( - MDataBlock dataBlock, - bool* drawRenderPurpose, - bool* drawProxyPurpose, - bool* drawGuidePurpose) const +bool MayaUsdProxyShapeBase::_GetDrawPurposeToggles( + MDataBlock dataBlock, + bool* drawRenderPurpose, + bool* drawProxyPurpose, + bool* drawGuidePurpose) const { MStatus status; - MDataHandle drawRenderPurposeHandle = - dataBlock.inputValue(drawRenderPurposeAttr, &status); + MDataHandle drawRenderPurposeHandle = dataBlock.inputValue(drawRenderPurposeAttr, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MDataHandle drawProxyPurposeHandle = - dataBlock.inputValue(drawProxyPurposeAttr, &status); + MDataHandle drawProxyPurposeHandle = dataBlock.inputValue(drawProxyPurposeAttr, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MDataHandle drawGuidePurposeHandle = - dataBlock.inputValue(drawGuidePurposeAttr, &status); + MDataHandle drawGuidePurposeHandle = dataBlock.inputValue(drawGuidePurposeAttr, &status); CHECK_MSTATUS_AND_RETURN(status, false); if (drawRenderPurpose) { @@ -1227,15 +1072,14 @@ MayaUsdProxyShapeBase::_GetDrawPurposeToggles( return true; } -bool -MayaUsdProxyShapeBase::GetAllRenderAttributes( - UsdPrim* usdPrimOut, - SdfPathVector* excludePrimPathsOut, - int* complexityOut, - UsdTimeCode* timeOut, - bool* drawRenderPurpose, - bool* drawProxyPurpose, - bool* drawGuidePurpose) +bool MayaUsdProxyShapeBase::GetAllRenderAttributes( + UsdPrim* usdPrimOut, + SdfPathVector* excludePrimPathsOut, + int* complexityOut, + UsdTimeCode* timeOut, + bool* drawRenderPurpose, + bool* drawProxyPurpose, + bool* drawGuidePurpose) { MDataBlock dataBlock = forceCache(); @@ -1248,35 +1092,29 @@ MayaUsdProxyShapeBase::GetAllRenderAttributes( *complexityOut = _GetComplexity(dataBlock); *timeOut = _GetTime(dataBlock); - _GetDrawPurposeToggles( - dataBlock, - drawRenderPurpose, - drawProxyPurpose, - drawGuidePurpose); + _GetDrawPurposeToggles(dataBlock, drawRenderPurpose, drawProxyPurpose, drawGuidePurpose); return true; } /* virtual */ -UsdPrim -MayaUsdProxyShapeBase::usdPrim() const +UsdPrim MayaUsdProxyShapeBase::usdPrim() const { - return _GetUsdPrim( const_cast(this)->forceCache() ); + return _GetUsdPrim(const_cast(this)->forceCache()); } -MDagPath -MayaUsdProxyShapeBase::parentTransform() +MDagPath MayaUsdProxyShapeBase::parentTransform() { MFnDagNode fn(thisMObject()); - MDagPath proxyTransformPath; + MDagPath proxyTransformPath; fn.getPath(proxyTransformPath); proxyTransformPath.pop(); return proxyTransformPath; } -MayaUsdProxyShapeBase::MayaUsdProxyShapeBase(const bool enableUfeSelection) : - MPxSurfaceShape(), - _isUfeSelectionEnabled(enableUfeSelection) +MayaUsdProxyShapeBase::MayaUsdProxyShapeBase(const bool enableUfeSelection) + : MPxSurfaceShape() + , _isUfeSelectionEnabled(enableUfeSelection) { TfRegistryManager::GetInstance().SubscribeTo(); } @@ -1289,8 +1127,7 @@ MayaUsdProxyShapeBase::~MayaUsdProxyShapeBase() // } -MSelectionMask -MayaUsdProxyShapeBase::getShapeSelectionMask() const +MSelectionMask MayaUsdProxyShapeBase::getShapeSelectionMask() const { // The intent of this function is to control whether this object is // selectable at all in VP2 @@ -1317,35 +1154,27 @@ MayaUsdProxyShapeBase::getShapeSelectionMask() const return normalMask; } -bool -MayaUsdProxyShapeBase::canBeSoftSelected() const -{ - return false; -} +bool MayaUsdProxyShapeBase::canBeSoftSelected() const { return false; } -void -MayaUsdProxyShapeBase::_OnStageContentsChanged( - const UsdNotice::StageContentsChanged& notice) +void MayaUsdProxyShapeBase::_OnStageContentsChanged(const UsdNotice::StageContentsChanged& notice) { // If the USD stage this proxy represents changes without Maya's knowledge, // we need to inform Maya that the shape is dirty and needs to be redrawn. MHWRender::MRenderer::setGeometryDrawDirty(thisMObject()); } -void -MayaUsdProxyShapeBase::_OnStageObjectsChanged(const UsdNotice::ObjectsChanged& notice) +void MayaUsdProxyShapeBase::_OnStageObjectsChanged(const UsdNotice::ObjectsChanged& notice) { ProxyAccessor::stageChanged(_usdAccessor, thisMObject(), notice); } -bool -MayaUsdProxyShapeBase::closestPoint( - const MPoint& raySource, +bool MayaUsdProxyShapeBase::closestPoint( + const MPoint& raySource, const MVector& rayDirection, - MPoint& theClosestPoint, - MVector& theClosestNormal, - bool /*findClosestOnMiss*/, - double /*tolerance*/) + MPoint& theClosestPoint, + MVector& theClosestNormal, + bool /*findClosestOnMiss*/, + double /*tolerance*/) { if (_sharedClosestPointDelegate) { GfRay ray( @@ -1363,9 +1192,7 @@ MayaUsdProxyShapeBase::closestPoint( return false; } -bool MayaUsdProxyShapeBase::canMakeLive() const { - return (bool) _sharedClosestPointDelegate; -} +bool MayaUsdProxyShapeBase::canMakeLive() const { return (bool)_sharedClosestPointDelegate; } #if defined(WANT_UFE_BUILD) Ufe::Path MayaUsdProxyShapeBase::ufePath() const diff --git a/lib/mayaUsd/nodes/proxyShapeBase.h b/lib/mayaUsd/nodes/proxyShapeBase.h index 5c2bd08ec6..8c8d2fd76f 100644 --- a/lib/mayaUsd/nodes/proxyShapeBase.h +++ b/lib/mayaUsd/nodes/proxyShapeBase.h @@ -16,13 +16,20 @@ #ifndef PXRUSDMAYA_PROXY_SHAPE_BASE_H #define PXRUSDMAYA_PROXY_SHAPE_BASE_H -#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include #include #include #include -#include #include #include #include @@ -32,25 +39,16 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include +#include #if defined(WANT_UFE_BUILD) #include -UFE_NS_DEF { - class Path; -} +UFE_NS_DEF { class Path; } -constexpr int MAYA_UFE_RUNTIME_ID = 1; +constexpr int MAYA_UFE_RUNTIME_ID = 1; constexpr char MAYA_UFE_SEPARATOR = '|'; -constexpr int USD_UFE_RUNTIME_ID = 2; +constexpr int USD_UFE_RUNTIME_ID = 2; constexpr char USD_UFE_SEPARATOR = '/'; #endif @@ -62,296 +60,291 @@ constexpr char USD_UFE_SEPARATOR = '/'; PXR_NAMESPACE_OPEN_SCOPE -#define MAYAUSD_PROXY_SHAPE_BASE_TOKENS \ - ((MayaTypeName, "mayaUsdProxyShapeBase")) +#define MAYAUSD_PROXY_SHAPE_BASE_TOKENS ((MayaTypeName, "mayaUsdProxyShapeBase")) -TF_DECLARE_PUBLIC_TOKENS(MayaUsdProxyShapeBaseTokens, - MAYAUSD_CORE_PUBLIC, - MAYAUSD_PROXY_SHAPE_BASE_TOKENS); +TF_DECLARE_PUBLIC_TOKENS( + MayaUsdProxyShapeBaseTokens, + MAYAUSD_CORE_PUBLIC, + MAYAUSD_PROXY_SHAPE_BASE_TOKENS); -class MayaUsdProxyShapeBase : public MPxSurfaceShape, - public ProxyStageProvider, - public UsdMayaUsdPrimProvider +class MayaUsdProxyShapeBase + : public MPxSurfaceShape + , public ProxyStageProvider + , public UsdMayaUsdPrimProvider { - public: - typedef MayaUsdProxyShapeBase ThisClass; - - MAYAUSD_CORE_PUBLIC - static const MTypeId typeId; - MAYAUSD_CORE_PUBLIC - static const MString typeName; - - MAYAUSD_CORE_PUBLIC - static const MString displayFilterName; - MAYAUSD_CORE_PUBLIC - static const MString displayFilterLabel; - - // Attributes - MAYAUSD_CORE_PUBLIC - static MObject filePathAttr; - MAYAUSD_CORE_PUBLIC - static MObject primPathAttr; - MAYAUSD_CORE_PUBLIC - static MObject excludePrimPathsAttr; - MAYAUSD_CORE_PUBLIC - static MObject loadPayloadsAttr; - MAYAUSD_CORE_PUBLIC - static MObject timeAttr; - MAYAUSD_CORE_PUBLIC - static MObject complexityAttr; - MAYAUSD_CORE_PUBLIC - static MObject inStageDataAttr; - MAYAUSD_CORE_PUBLIC - static MObject inStageDataCachedAttr; - MAYAUSD_CORE_PUBLIC - static MObject stageCacheIdAttr; - MAYAUSD_CORE_PUBLIC - static MObject drawRenderPurposeAttr; - MAYAUSD_CORE_PUBLIC - static MObject drawProxyPurposeAttr; - MAYAUSD_CORE_PUBLIC - static MObject drawGuidePurposeAttr; - - // Output attributes - MAYAUSD_CORE_PUBLIC - static MObject outTimeAttr; - MAYAUSD_CORE_PUBLIC - static MObject outStageDataAttr; - MAYAUSD_CORE_PUBLIC - static MObject outStageCacheIdAttr; - - /// Delegate function for computing the closest point and surface normal - /// on the proxy shape to a given ray. - /// The input ray, output point, and output normal should be in the - /// proxy shape's local space. - /// Should return true if a point was found, and false otherwise. - /// (You could just treat this as a ray intersection and return true - /// if intersected, false if missed.) - typedef std::function ClosestPointDelegate; - - MAYAUSD_CORE_PUBLIC - static void* creator(); - - MAYAUSD_CORE_PUBLIC - static MStatus initialize(); - - MAYAUSD_CORE_PUBLIC - static MayaUsdProxyShapeBase* GetShapeAtDagPath(const MDagPath& dagPath); - - MAYAUSD_CORE_PUBLIC - static void SetClosestPointDelegate(ClosestPointDelegate delegate); - - // UsdMayaUsdPrimProvider overrides: - /** - * accessor to get the usdprim - * - * This method pulls the usdstage data from outData, and will evaluate - * the dependencies necessary to do so. It should be called instead of - * pulling on the data directly. - */ - MAYAUSD_CORE_PUBLIC - UsdPrim usdPrim() const override; - - // Virtual function overrides - - MAYAUSD_CORE_PUBLIC - void postConstructor() override; - MAYAUSD_CORE_PUBLIC - MStatus compute( - const MPlug& plug, - MDataBlock& dataBlock) override; - MAYAUSD_CORE_PUBLIC - bool isBounded() const override; - MAYAUSD_CORE_PUBLIC - MBoundingBox boundingBox() const override; - MAYAUSD_CORE_PUBLIC - MSelectionMask getShapeSelectionMask() const override; - - MAYAUSD_CORE_PUBLIC - bool closestPoint( - const MPoint& raySource, - const MVector& rayDirection, - MPoint& theClosestPoint, - MVector& theClosestNormal, - bool findClosestOnMiss, - double tolerance) override; - - MAYAUSD_CORE_PUBLIC - bool canMakeLive() const override; - - // Public functions - MAYAUSD_CORE_PUBLIC - virtual SdfPathVector getExcludePrimPaths() const; - MAYAUSD_CORE_PUBLIC - size_t getExcludePrimPathsVersion() const; - - MAYAUSD_CORE_PUBLIC - int getComplexity() const; - - MAYAUSD_CORE_PUBLIC - UsdTimeCode getTime() const override; - MAYAUSD_CORE_PUBLIC - UsdStageRefPtr getUsdStage() const override; - MAYAUSD_CORE_PUBLIC - size_t getUsdStageVersion() const; - MAYAUSD_CORE_PUBLIC - void getDrawPurposeToggles( - bool* drawRenderPurpose, - bool* drawProxyPurpose, - bool* drawGuidePurpose) const; - - MAYAUSD_CORE_PUBLIC - bool GetAllRenderAttributes( - UsdPrim* usdPrimOut, - SdfPathVector* excludePrimPathsOut, - int* complexityOut, - UsdTimeCode* timeOut, - bool* drawRenderPurpose, - bool* drawProxyPurpose, - bool* drawGuidePurpose); - - MAYAUSD_CORE_PUBLIC - MStatus preEvaluation( - const MDGContext& context, - const MEvaluationNode& evaluationNode) override; - - MAYAUSD_CORE_PUBLIC - MStatus postEvaluation( - const MDGContext& context, - const MEvaluationNode& evaluationNode, - PostEvaluationType evalType) override; +public: + typedef MayaUsdProxyShapeBase ThisClass; + + MAYAUSD_CORE_PUBLIC + static const MTypeId typeId; + MAYAUSD_CORE_PUBLIC + static const MString typeName; + + MAYAUSD_CORE_PUBLIC + static const MString displayFilterName; + MAYAUSD_CORE_PUBLIC + static const MString displayFilterLabel; + + // Attributes + MAYAUSD_CORE_PUBLIC + static MObject filePathAttr; + MAYAUSD_CORE_PUBLIC + static MObject primPathAttr; + MAYAUSD_CORE_PUBLIC + static MObject excludePrimPathsAttr; + MAYAUSD_CORE_PUBLIC + static MObject loadPayloadsAttr; + MAYAUSD_CORE_PUBLIC + static MObject timeAttr; + MAYAUSD_CORE_PUBLIC + static MObject complexityAttr; + MAYAUSD_CORE_PUBLIC + static MObject inStageDataAttr; + MAYAUSD_CORE_PUBLIC + static MObject inStageDataCachedAttr; + MAYAUSD_CORE_PUBLIC + static MObject stageCacheIdAttr; + MAYAUSD_CORE_PUBLIC + static MObject drawRenderPurposeAttr; + MAYAUSD_CORE_PUBLIC + static MObject drawProxyPurposeAttr; + MAYAUSD_CORE_PUBLIC + static MObject drawGuidePurposeAttr; + + // Output attributes + MAYAUSD_CORE_PUBLIC + static MObject outTimeAttr; + MAYAUSD_CORE_PUBLIC + static MObject outStageDataAttr; + MAYAUSD_CORE_PUBLIC + static MObject outStageCacheIdAttr; + + /// Delegate function for computing the closest point and surface normal + /// on the proxy shape to a given ray. + /// The input ray, output point, and output normal should be in the + /// proxy shape's local space. + /// Should return true if a point was found, and false otherwise. + /// (You could just treat this as a ray intersection and return true + /// if intersected, false if missed.) + typedef std::function + ClosestPointDelegate; + + MAYAUSD_CORE_PUBLIC + static void* creator(); + + MAYAUSD_CORE_PUBLIC + static MStatus initialize(); + + MAYAUSD_CORE_PUBLIC + static MayaUsdProxyShapeBase* GetShapeAtDagPath(const MDagPath& dagPath); + + MAYAUSD_CORE_PUBLIC + static void SetClosestPointDelegate(ClosestPointDelegate delegate); + + // UsdMayaUsdPrimProvider overrides: + /** + * accessor to get the usdprim + * + * This method pulls the usdstage data from outData, and will evaluate + * the dependencies necessary to do so. It should be called instead of + * pulling on the data directly. + */ + MAYAUSD_CORE_PUBLIC + UsdPrim usdPrim() const override; + + // Virtual function overrides + + MAYAUSD_CORE_PUBLIC + void postConstructor() override; + MAYAUSD_CORE_PUBLIC + MStatus compute(const MPlug& plug, MDataBlock& dataBlock) override; + MAYAUSD_CORE_PUBLIC + bool isBounded() const override; + MAYAUSD_CORE_PUBLIC + MBoundingBox boundingBox() const override; + MAYAUSD_CORE_PUBLIC + MSelectionMask getShapeSelectionMask() const override; + + MAYAUSD_CORE_PUBLIC + bool closestPoint( + const MPoint& raySource, + const MVector& rayDirection, + MPoint& theClosestPoint, + MVector& theClosestNormal, + bool findClosestOnMiss, + double tolerance) override; + + MAYAUSD_CORE_PUBLIC + bool canMakeLive() const override; + + // Public functions + MAYAUSD_CORE_PUBLIC + virtual SdfPathVector getExcludePrimPaths() const; + MAYAUSD_CORE_PUBLIC + size_t getExcludePrimPathsVersion() const; + + MAYAUSD_CORE_PUBLIC + int getComplexity() const; + + MAYAUSD_CORE_PUBLIC + UsdTimeCode getTime() const override; + MAYAUSD_CORE_PUBLIC + UsdStageRefPtr getUsdStage() const override; + MAYAUSD_CORE_PUBLIC + size_t getUsdStageVersion() const; + MAYAUSD_CORE_PUBLIC + void getDrawPurposeToggles( + bool* drawRenderPurpose, + bool* drawProxyPurpose, + bool* drawGuidePurpose) const; + + MAYAUSD_CORE_PUBLIC + bool GetAllRenderAttributes( + UsdPrim* usdPrimOut, + SdfPathVector* excludePrimPathsOut, + int* complexityOut, + UsdTimeCode* timeOut, + bool* drawRenderPurpose, + bool* drawProxyPurpose, + bool* drawGuidePurpose); + + MAYAUSD_CORE_PUBLIC + MStatus + preEvaluation(const MDGContext& context, const MEvaluationNode& evaluationNode) override; + + MAYAUSD_CORE_PUBLIC + MStatus postEvaluation( + const MDGContext& context, + const MEvaluationNode& evaluationNode, + PostEvaluationType evalType) override; #if MAYA_API_VERSION >= 20210000 - MAYAUSD_CORE_PUBLIC - void getCacheSetup(const MEvaluationNode& evalNode, MNodeCacheDisablingInfo& disablingInfo, MNodeCacheSetupInfo& cacheSetupInfo, MObjectArray& monitoredAttributes) const override; - - MAYAUSD_CORE_PUBLIC - void configCache(const MEvaluationNode& evalNode, MCacheSchema& schema) const override; + MAYAUSD_CORE_PUBLIC + void getCacheSetup( + const MEvaluationNode& evalNode, + MNodeCacheDisablingInfo& disablingInfo, + MNodeCacheSetupInfo& cacheSetupInfo, + MObjectArray& monitoredAttributes) const override; + + MAYAUSD_CORE_PUBLIC + void configCache(const MEvaluationNode& evalNode, MCacheSchema& schema) const override; #endif - - MAYAUSD_CORE_PUBLIC - MStatus setDependentsDirty( - const MPlug& plug, - MPlugArray& plugArray) override; - /// \brief Clears the bounding box cache of the shape - MAYAUSD_CORE_PUBLIC - void clearBoundingBoxCache(); + MAYAUSD_CORE_PUBLIC + MStatus setDependentsDirty(const MPlug& plug, MPlugArray& plugArray) override; + + /// \brief Clears the bounding box cache of the shape + MAYAUSD_CORE_PUBLIC + void clearBoundingBoxCache(); - // returns the shape's parent transform - MAYAUSD_CORE_PUBLIC - MDagPath parentTransform(); + // returns the shape's parent transform + MAYAUSD_CORE_PUBLIC + MDagPath parentTransform(); - // Is this required if there is parentTransform? + // Is this required if there is parentTransform? #if defined(WANT_UFE_BUILD) - MAYAUSD_CORE_PUBLIC - Ufe::Path ufePath() const; + MAYAUSD_CORE_PUBLIC + Ufe::Path ufePath() const; #endif - /// Returns whether the proxy shape allows subpaths within its - /// hierarchy to be selected independently when using the Viewport 2.0 - /// render delegate. - /// - /// UFE/subpath selection must be enabled or disabled when constructing - /// the proxy shape. This is primarily intended as a mechanism for - /// UsdMayaProxyShape to disable UFE/subpath selection. Most of the - /// usage of pxrUsdProxyShape nodes is when they are brought in by - /// activating the "Collapsed" representation of - /// pxrUsdReferenceAssembly nodes. In that case, they are intended to - /// be read-only proxies, and any edits to prims within the hierarchy - /// should be represented as assembly edits. - bool isUfeSelectionEnabled() const { - return _isUfeSelectionEnabled; - } - - protected: - MAYAUSD_CORE_PUBLIC - MayaUsdProxyShapeBase(const bool enableUfeSelection = true); - - MAYAUSD_CORE_PUBLIC - ~MayaUsdProxyShapeBase() override; - - MAYAUSD_CORE_PUBLIC - bool isStageValid() const; - - //! \brief Create and register proxy accessor on this proxy. Should be called from postConstructor. - MAYAUSD_CORE_PUBLIC - void enableProxyAccessor(); - - // Hook method for derived classes. This class returns a nullptr. - MAYAUSD_CORE_PUBLIC - virtual SdfLayerRefPtr computeSessionLayer(MDataBlock&); - - // Hook method for derived classes: can this object be soft selected? - // This class returns false. - MAYAUSD_CORE_PUBLIC - virtual bool canBeSoftSelected() const; - - // Hook method for derived classes: is soft select enabled? This - // class returns false. - MAYAUSD_CORE_PUBLIC - virtual bool GetObjectSoftSelectEnabled() const; - - MAYAUSD_CORE_PUBLIC - UsdPrim _GetUsdPrim(MDataBlock dataBlock) const; - - // Hook method for derived classes: cache an empty computed bounding - // box. This class does nothing. - MAYAUSD_CORE_PUBLIC - virtual void CacheEmptyBoundingBox(MBoundingBox&); - - // Return the output time. This class returns the value of the - // input time attribute. - MAYAUSD_CORE_PUBLIC - virtual UsdTimeCode GetOutputTime(MDataBlock) const; - - MAYAUSD_CORE_PUBLIC - void _IncreaseExcludePrimPathsVersion() { _excludePrimPathsVersion++; } - - MAYAUSD_CORE_PUBLIC - void _IncreaseUsdStageVersion() { _UsdStageVersion++; } - - private: - MayaUsdProxyShapeBase(const MayaUsdProxyShapeBase&); - MayaUsdProxyShapeBase& operator=(const MayaUsdProxyShapeBase&); - - MStatus computeOutputTime(MDataBlock& dataBlock); - MStatus computeInStageDataCached(MDataBlock& dataBlock); - MStatus computeOutStageData(MDataBlock& dataBlock); - MStatus computeOutStageCacheId(MDataBlock& dataBlock); - - SdfPathVector _GetExcludePrimPaths(MDataBlock dataBlock) const; - int _GetComplexity(MDataBlock dataBlock) const; - UsdTimeCode _GetTime(MDataBlock dataBlock) const; - - bool _GetDrawPurposeToggles( - MDataBlock dataBlock, - bool* drawRenderPurpose, - bool* drawProxyPurpose, - bool* drawGuidePurpose) const; - - void _OnStageContentsChanged( - const UsdNotice::StageContentsChanged& notice); - void _OnStageObjectsChanged( - const UsdNotice::ObjectsChanged& notice); - - UsdMayaStageNoticeListener _stageNoticeListener; - - std::map _boundingBoxCache; - size_t _excludePrimPathsVersion{ 1 }; - size_t _UsdStageVersion{ 1 }; - - MayaUsd::ProxyAccessor::Owner _usdAccessor; - - static ClosestPointDelegate _sharedClosestPointDelegate; - - // Whether or not the proxy shape has enabled UFE/subpath selection - const bool _isUfeSelectionEnabled; + /// Returns whether the proxy shape allows subpaths within its + /// hierarchy to be selected independently when using the Viewport 2.0 + /// render delegate. + /// + /// UFE/subpath selection must be enabled or disabled when constructing + /// the proxy shape. This is primarily intended as a mechanism for + /// UsdMayaProxyShape to disable UFE/subpath selection. Most of the + /// usage of pxrUsdProxyShape nodes is when they are brought in by + /// activating the "Collapsed" representation of + /// pxrUsdReferenceAssembly nodes. In that case, they are intended to + /// be read-only proxies, and any edits to prims within the hierarchy + /// should be represented as assembly edits. + bool isUfeSelectionEnabled() const { return _isUfeSelectionEnabled; } + +protected: + MAYAUSD_CORE_PUBLIC + MayaUsdProxyShapeBase(const bool enableUfeSelection = true); + + MAYAUSD_CORE_PUBLIC + ~MayaUsdProxyShapeBase() override; + + MAYAUSD_CORE_PUBLIC + bool isStageValid() const; + + //! \brief Create and register proxy accessor on this proxy. Should be called from + //! postConstructor. + MAYAUSD_CORE_PUBLIC + void enableProxyAccessor(); + + // Hook method for derived classes. This class returns a nullptr. + MAYAUSD_CORE_PUBLIC + virtual SdfLayerRefPtr computeSessionLayer(MDataBlock&); + + // Hook method for derived classes: can this object be soft selected? + // This class returns false. + MAYAUSD_CORE_PUBLIC + virtual bool canBeSoftSelected() const; + + // Hook method for derived classes: is soft select enabled? This + // class returns false. + MAYAUSD_CORE_PUBLIC + virtual bool GetObjectSoftSelectEnabled() const; + + MAYAUSD_CORE_PUBLIC + UsdPrim _GetUsdPrim(MDataBlock dataBlock) const; + + // Hook method for derived classes: cache an empty computed bounding + // box. This class does nothing. + MAYAUSD_CORE_PUBLIC + virtual void CacheEmptyBoundingBox(MBoundingBox&); + + // Return the output time. This class returns the value of the + // input time attribute. + MAYAUSD_CORE_PUBLIC + virtual UsdTimeCode GetOutputTime(MDataBlock) const; + + MAYAUSD_CORE_PUBLIC + void _IncreaseExcludePrimPathsVersion() { _excludePrimPathsVersion++; } + + MAYAUSD_CORE_PUBLIC + void _IncreaseUsdStageVersion() { _UsdStageVersion++; } + +private: + MayaUsdProxyShapeBase(const MayaUsdProxyShapeBase&); + MayaUsdProxyShapeBase& operator=(const MayaUsdProxyShapeBase&); + + MStatus computeOutputTime(MDataBlock& dataBlock); + MStatus computeInStageDataCached(MDataBlock& dataBlock); + MStatus computeOutStageData(MDataBlock& dataBlock); + MStatus computeOutStageCacheId(MDataBlock& dataBlock); + + SdfPathVector _GetExcludePrimPaths(MDataBlock dataBlock) const; + int _GetComplexity(MDataBlock dataBlock) const; + UsdTimeCode _GetTime(MDataBlock dataBlock) const; + + bool _GetDrawPurposeToggles( + MDataBlock dataBlock, + bool* drawRenderPurpose, + bool* drawProxyPurpose, + bool* drawGuidePurpose) const; + + void _OnStageContentsChanged(const UsdNotice::StageContentsChanged& notice); + void _OnStageObjectsChanged(const UsdNotice::ObjectsChanged& notice); + + UsdMayaStageNoticeListener _stageNoticeListener; + + std::map _boundingBoxCache; + size_t _excludePrimPathsVersion { 1 }; + size_t _UsdStageVersion { 1 }; + + MayaUsd::ProxyAccessor::Owner _usdAccessor; + + static ClosestPointDelegate _sharedClosestPointDelegate; + + // Whether or not the proxy shape has enabled UFE/subpath selection + const bool _isUfeSelectionEnabled; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/nodes/proxyShapePlugin.cpp b/lib/mayaUsd/nodes/proxyShapePlugin.cpp index 1d757d77f3..1492241d23 100644 --- a/lib/mayaUsd/nodes/proxyShapePlugin.cpp +++ b/lib/mayaUsd/nodes/proxyShapePlugin.cpp @@ -15,48 +15,48 @@ // #include "proxyShapePlugin.h" +#include +#include +#include +#include +#include #include #include #include #include #include #include - -#include -#include -#include -#include -#include +#include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE namespace { const MString _RegistrantId("mayaUsd"); -int _registrationCount = 0; +int _registrationCount = 0; // Name of the plugin registering the proxy shape base class. MString _registrantPluginName; bool _useVP2RenderDelegate = false; -TF_DEFINE_ENV_SETTING(VP2_RENDER_DELEGATE_PROXY, false, +TF_DEFINE_ENV_SETTING( + VP2_RENDER_DELEGATE_PROXY, + false, "Switch proxy shape rendering to VP2 render delegate."); -} +} // namespace PXR_NAMESPACE_OPEN_SCOPE /* static */ -MStatus -MayaUsdProxyShapePlugin::initialize(MFnPlugin& plugin) +MStatus MayaUsdProxyShapePlugin::initialize(MFnPlugin& plugin) { // If we're already registered, do nothing. if (_registrationCount++ > 0) { @@ -65,7 +65,7 @@ MayaUsdProxyShapePlugin::initialize(MFnPlugin& plugin) // Call one time registration of plugins compiled for same USD version as MayaUSD plugin. MayaUsd::registerVersionedPlugins(); - + _registrantPluginName = plugin.name(); _useVP2RenderDelegate = TfGetEnvSetting(VP2_RENDER_DELEGATE_PROXY); @@ -74,9 +74,7 @@ MayaUsdProxyShapePlugin::initialize(MFnPlugin& plugin) // Proxy shape initialization. status = plugin.registerData( - MayaUsdStageData::typeName, - MayaUsdStageData::mayaTypeId, - MayaUsdStageData::creator); + MayaUsdStageData::typeName, MayaUsdStageData::mayaTypeId, MayaUsdStageData::creator); CHECK_MSTATUS(status); status = plugin.registerShape( @@ -110,9 +108,7 @@ MayaUsdProxyShapePlugin::initialize(MFnPlugin& plugin) // so register it here. Native USD VP2 rendering uses a sub-scene override. if (_useVP2RenderDelegate) { status = MHWRender::MDrawRegistry::registerSubSceneOverrideCreator( - ProxyRenderDelegate::drawDbClassification, - _RegistrantId, - ProxyRenderDelegate::Creator); + ProxyRenderDelegate::drawDbClassification, _RegistrantId, ProxyRenderDelegate::Creator); CHECK_MSTATUS(status); } else { status = MHWRender::MDrawRegistry::registerDrawOverrideCreator( @@ -153,8 +149,7 @@ MayaUsdProxyShapePlugin::initialize(MFnPlugin& plugin) } /* static */ -MStatus -MayaUsdProxyShapePlugin::finalize(MFnPlugin& plugin) +MStatus MayaUsdProxyShapePlugin::finalize(MFnPlugin& plugin) { // If more than one plugin still has us registered, do nothing. if (_registrationCount == 0 || _registrationCount-- > 1) { @@ -175,8 +170,7 @@ MayaUsdProxyShapePlugin::finalize(MFnPlugin& plugin) CHECK_MSTATUS(status); status = MHWRender::MDrawRegistry::deregisterDrawOverrideCreator( - PxrMayaHdImagingShapeDrawOverride::drawDbClassification, - _RegistrantId); + PxrMayaHdImagingShapeDrawOverride::drawDbClassification, _RegistrantId); CHECK_MSTATUS(status); status = plugin.deregisterNode(PxrMayaHdImagingShape::typeId); @@ -184,19 +178,14 @@ MayaUsdProxyShapePlugin::finalize(MFnPlugin& plugin) if (_useVP2RenderDelegate) { status = MHWRender::MDrawRegistry::deregisterSubSceneOverrideCreator( - ProxyRenderDelegate::drawDbClassification, - _RegistrantId); + ProxyRenderDelegate::drawDbClassification, _RegistrantId); CHECK_MSTATUS(status); - } - else - { - status = plugin.deregisterDisplayFilter( - MayaUsdProxyShapeBase::displayFilterName); + } else { + status = plugin.deregisterDisplayFilter(MayaUsdProxyShapeBase::displayFilterName); CHECK_MSTATUS(status); status = MHWRender::MDrawRegistry::deregisterDrawOverrideCreator( - UsdMayaProxyDrawOverride::drawDbClassification, - _RegistrantId); + UsdMayaProxyDrawOverride::drawDbClassification, _RegistrantId); CHECK_MSTATUS(status); } @@ -208,7 +197,7 @@ MayaUsdProxyShapePlugin::finalize(MFnPlugin& plugin) status = plugin.deregisterNode(MayaUsdProxyShapeBase::typeId); CHECK_MSTATUS(status); - + status = plugin.deregisterData(MayaUsdStageData::mayaTypeId); CHECK_MSTATUS(status); @@ -217,13 +206,10 @@ MayaUsdProxyShapePlugin::finalize(MFnPlugin& plugin) const MString* MayaUsdProxyShapePlugin::getProxyShapeClassification() { - return _useVP2RenderDelegate ? &ProxyRenderDelegate::drawDbClassification : - &UsdMayaProxyDrawOverride::drawDbClassification; + return _useVP2RenderDelegate ? &ProxyRenderDelegate::drawDbClassification + : &UsdMayaProxyDrawOverride::drawDbClassification; } -bool MayaUsdProxyShapePlugin::useVP2_NativeUSD_Rendering() -{ - return _useVP2RenderDelegate; -} +bool MayaUsdProxyShapePlugin::useVP2_NativeUSD_Rendering() { return _useVP2RenderDelegate; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/nodes/proxyShapePlugin.h b/lib/mayaUsd/nodes/proxyShapePlugin.h index 60b30e841e..8dea04a6e0 100644 --- a/lib/mayaUsd/nodes/proxyShapePlugin.h +++ b/lib/mayaUsd/nodes/proxyShapePlugin.h @@ -16,11 +16,11 @@ #ifndef PXRUSDMAYA_PROXY_SHAPE_PLUGIN_H #define PXRUSDMAYA_PROXY_SHAPE_PLUGIN_H -#include +#include #include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -37,18 +37,18 @@ PXR_NAMESPACE_OPEN_SCOPE class MayaUsdProxyShapePlugin { - public: - MAYAUSD_CORE_PUBLIC - static MStatus initialize(MFnPlugin&); +public: + MAYAUSD_CORE_PUBLIC + static MStatus initialize(MFnPlugin&); - MAYAUSD_CORE_PUBLIC - static MStatus finalize(MFnPlugin&); + MAYAUSD_CORE_PUBLIC + static MStatus finalize(MFnPlugin&); - MAYAUSD_CORE_PUBLIC - static const MString* getProxyShapeClassification(); + MAYAUSD_CORE_PUBLIC + static const MString* getProxyShapeClassification(); - MAYAUSD_CORE_PUBLIC - static bool useVP2_NativeUSD_Rendering(); + MAYAUSD_CORE_PUBLIC + static bool useVP2_NativeUSD_Rendering(); }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/nodes/proxyStageProvider.h b/lib/mayaUsd/nodes/proxyStageProvider.h index 67bd5aa840..865fe84cb6 100644 --- a/lib/mayaUsd/nodes/proxyStageProvider.h +++ b/lib/mayaUsd/nodes/proxyStageProvider.h @@ -17,29 +17,25 @@ #define MAYAUSD_PROXY_STAGE_PROVIDER_H #include "../base/api.h" - #include "pxr/pxr.h" - #include "pxr/usd/usd/stage.h" #include "pxr/usd/usd/timeCode.h" PXR_NAMESPACE_OPEN_SCOPE - -// Interface class +// Interface class class ProxyStageProvider { public: MAYAUSD_CORE_PUBLIC - virtual UsdTimeCode getTime() const = 0; + virtual UsdTimeCode getTime() const = 0; MAYAUSD_CORE_PUBLIC - virtual UsdStageRefPtr getUsdStage() const = 0; + virtual UsdStageRefPtr getUsdStage() const = 0; MAYAUSD_CORE_PUBLIC virtual ~ProxyStageProvider() = default; }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/nodes/stageData.cpp b/lib/mayaUsd/nodes/stageData.cpp index 135a0e0242..0b246d6147 100644 --- a/lib/mayaUsd/nodes/stageData.cpp +++ b/lib/mayaUsd/nodes/stageData.cpp @@ -15,56 +15,45 @@ // #include "stageData.h" -#include -#include -#include -#include - #include #include #include #include -PXR_NAMESPACE_OPEN_SCOPE +#include +#include +#include +#include -TF_DEFINE_PUBLIC_TOKENS(MayaUsdStageDataTokens, - PXRMAYAUSD_STAGE_DATA_TOKENS); +PXR_NAMESPACE_OPEN_SCOPE +TF_DEFINE_PUBLIC_TOKENS(MayaUsdStageDataTokens, PXRMAYAUSD_STAGE_DATA_TOKENS); const MTypeId MayaUsdStageData::mayaTypeId(0x0010A257); -const MString MayaUsdStageData::typeName( - MayaUsdStageDataTokens->MayaTypeName.GetText()); - +const MString MayaUsdStageData::typeName(MayaUsdStageDataTokens->MayaTypeName.GetText()); /* This exists solely to make sure that the usdStage instance * gets discarded when Maya exits, so that any temporary files * that might have been created are unlinked. */ namespace { -void -_cleanUp(void *gdPtr) +void _cleanUp(void* gdPtr) { - MayaUsdStageData *gd = (MayaUsdStageData *)gdPtr; + MayaUsdStageData* gd = (MayaUsdStageData*)gdPtr; gd->unregisterExitCallback(); gd->stage = UsdStageRefPtr(); } -} +} // namespace /* static */ -void* -MayaUsdStageData::creator() -{ - return new MayaUsdStageData(); -} +void* MayaUsdStageData::creator() { return new MayaUsdStageData(); } /* virtual */ -void -MayaUsdStageData::copy(const MPxData& src) +void MayaUsdStageData::copy(const MPxData& src) { - const MayaUsdStageData* stageData = - dynamic_cast(&src); + const MayaUsdStageData* stageData = dynamic_cast(&src); if (stageData) { stage = stageData->stage; @@ -73,43 +62,25 @@ MayaUsdStageData::copy(const MPxData& src) } /* virtual */ -MTypeId -MayaUsdStageData::typeId() const -{ - return mayaTypeId; -} +MTypeId MayaUsdStageData::typeId() const { return mayaTypeId; } /* virtual */ -MString -MayaUsdStageData::name() const -{ - return typeName; -} +MString MayaUsdStageData::name() const { return typeName; } -MayaUsdStageData::MayaUsdStageData() : MPxGeometryData() +MayaUsdStageData::MayaUsdStageData() + : MPxGeometryData() { registerExitCallback(); } -void -MayaUsdStageData::registerExitCallback() +void MayaUsdStageData::registerExitCallback() { - _exitCallbackId = MSceneMessage::addCallback(MSceneMessage::kMayaExiting, - _cleanUp, - this); + _exitCallbackId = MSceneMessage::addCallback(MSceneMessage::kMayaExiting, _cleanUp, this); } -void -MayaUsdStageData::unregisterExitCallback() -{ - MSceneMessage::removeCallback(_exitCallbackId); -} +void MayaUsdStageData::unregisterExitCallback() { MSceneMessage::removeCallback(_exitCallbackId); } /* virtual */ -MayaUsdStageData::~MayaUsdStageData() { - - unregisterExitCallback(); -} - +MayaUsdStageData::~MayaUsdStageData() { unregisterExitCallback(); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/nodes/stageData.h b/lib/mayaUsd/nodes/stageData.h index da7f4edebe..9414fe2181 100644 --- a/lib/mayaUsd/nodes/stageData.h +++ b/lib/mayaUsd/nodes/stageData.h @@ -16,119 +16,113 @@ #ifndef PXRUSDMAYA_STAGE_DATA_H #define PXRUSDMAYA_STAGE_DATA_H -#include -#include -#include -#include -#include +#include #include #include #include #include -#include +#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -#define PXRMAYAUSD_STAGE_DATA_TOKENS \ - ((MayaTypeName, "pxrUsdStageData")) - -TF_DECLARE_PUBLIC_TOKENS(MayaUsdStageDataTokens, - MAYAUSD_CORE_PUBLIC, - PXRMAYAUSD_STAGE_DATA_TOKENS); +#define PXRMAYAUSD_STAGE_DATA_TOKENS ((MayaTypeName, "pxrUsdStageData")) +TF_DECLARE_PUBLIC_TOKENS(MayaUsdStageDataTokens, MAYAUSD_CORE_PUBLIC, PXRMAYAUSD_STAGE_DATA_TOKENS); class MayaUsdStageData : public MPxGeometryData { - public: - /// Unlike other Maya node types, MPxData/MPxGeometryData declare - /// typeId() as a pure virtual method that must be overridden in - /// derived classes, so we have to call this static member "mayaTypeId" - /// instead of just "typeId" as we usually would. - MAYAUSD_CORE_PUBLIC - static const MTypeId mayaTypeId; - MAYAUSD_CORE_PUBLIC - static const MString typeName; - - MAYAUSD_CORE_PUBLIC - static void* creator(); - - /** - * \name MPxGeometryData overrides - */ - //@{ - - MAYAUSD_CORE_PUBLIC - void copy(const MPxData& src) override; - - MAYAUSD_CORE_PUBLIC - MTypeId typeId() const override; - - MAYAUSD_CORE_PUBLIC - MString name() const override; - //@} - - void unregisterExitCallback(); - - /** - * \name data - */ - //@{ - - // The original Pixar code was the following: - // - // UsdStageRefPtr stage; - // - // Now using a weak pointer instead of a referencing pointer. The AL - // plugin originally used a referencing pointer, but ran into problems. - // From a Rob Bateman @ AL e-mail, 7-Apr-2019: - // - // "The reason for the weak pointer was that we found that Maya seemed - // to have a memory leak (as in, the MPxData derived objects were being - // created, but never deleted when we expected them to be - possibly by - // design?). We had originally used a direct mirror of the Pixar data - // object, but because the data objects were never freed (even after - // file new), the original stage would be retained. This meant the - // internal SdfLayerCache in USD would keep hold of the previously - // loaded layers. So we found we had this problem: - // - // 1. Import some.usda file into a proxy shape. - // 2. Make some modifications - // 3. File New - // 4. Import the same "some.usda" file into a proxy shape. - // - // At this point, USD would essentially hand you back the stage - // composed of the modified layers, rather than a clean stage composed - // from the files on disk. Switching the type from a shared_ptr to a - // weak_ptr worked around this issue. Basically if we use a shared - // pointer here, the only way to reload a scene, would be to restart - // Maya." - // - // Logged as https://github.com/Autodesk/maya-usd/issues/528 - - UsdStageWeakPtr stage; - SdfPath primPath; - - //@} - - protected: - MAYAUSD_CORE_PUBLIC - MayaUsdStageData(); - MAYAUSD_CORE_PUBLIC - ~MayaUsdStageData() override; - - private: - MayaUsdStageData(const MayaUsdStageData&); - MayaUsdStageData& operator=(const MayaUsdStageData&); - - void registerExitCallback(); - - MCallbackId _exitCallbackId; +public: + /// Unlike other Maya node types, MPxData/MPxGeometryData declare + /// typeId() as a pure virtual method that must be overridden in + /// derived classes, so we have to call this static member "mayaTypeId" + /// instead of just "typeId" as we usually would. + MAYAUSD_CORE_PUBLIC + static const MTypeId mayaTypeId; + MAYAUSD_CORE_PUBLIC + static const MString typeName; + + MAYAUSD_CORE_PUBLIC + static void* creator(); + + /** + * \name MPxGeometryData overrides + */ + //@{ + + MAYAUSD_CORE_PUBLIC + void copy(const MPxData& src) override; + + MAYAUSD_CORE_PUBLIC + MTypeId typeId() const override; + + MAYAUSD_CORE_PUBLIC + MString name() const override; + //@} + + void unregisterExitCallback(); + + /** + * \name data + */ + //@{ + + // The original Pixar code was the following: + // + // UsdStageRefPtr stage; + // + // Now using a weak pointer instead of a referencing pointer. The AL + // plugin originally used a referencing pointer, but ran into problems. + // From a Rob Bateman @ AL e-mail, 7-Apr-2019: + // + // "The reason for the weak pointer was that we found that Maya seemed + // to have a memory leak (as in, the MPxData derived objects were being + // created, but never deleted when we expected them to be - possibly by + // design?). We had originally used a direct mirror of the Pixar data + // object, but because the data objects were never freed (even after + // file new), the original stage would be retained. This meant the + // internal SdfLayerCache in USD would keep hold of the previously + // loaded layers. So we found we had this problem: + // + // 1. Import some.usda file into a proxy shape. + // 2. Make some modifications + // 3. File New + // 4. Import the same "some.usda" file into a proxy shape. + // + // At this point, USD would essentially hand you back the stage + // composed of the modified layers, rather than a clean stage composed + // from the files on disk. Switching the type from a shared_ptr to a + // weak_ptr worked around this issue. Basically if we use a shared + // pointer here, the only way to reload a scene, would be to restart + // Maya." + // + // Logged as https://github.com/Autodesk/maya-usd/issues/528 + + UsdStageWeakPtr stage; + SdfPath primPath; + + //@} + +protected: + MAYAUSD_CORE_PUBLIC + MayaUsdStageData(); + MAYAUSD_CORE_PUBLIC + ~MayaUsdStageData() override; + +private: + MayaUsdStageData(const MayaUsdStageData&); + MayaUsdStageData& operator=(const MayaUsdStageData&); + + void registerExitCallback(); + + MCallbackId _exitCallbackId; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/nodes/stageNode.cpp b/lib/mayaUsd/nodes/stageNode.cpp index 09d8fd75c6..86bcf2bb1e 100644 --- a/lib/mayaUsd/nodes/stageNode.cpp +++ b/lib/mayaUsd/nodes/stageNode.cpp @@ -15,7 +15,18 @@ // #include "stageNode.h" -#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -30,44 +41,24 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PUBLIC_TOKENS(UsdMayaStageNodeTokens, - PXRUSDMAYA_STAGE_NODE_TOKENS); - +TF_DEFINE_PUBLIC_TOKENS(UsdMayaStageNodeTokens, PXRUSDMAYA_STAGE_NODE_TOKENS); const MTypeId UsdMayaStageNode::typeId(0x00126400); -const MString UsdMayaStageNode::typeName( - UsdMayaStageNodeTokens->MayaTypeName.GetText()); +const MString UsdMayaStageNode::typeName(UsdMayaStageNodeTokens->MayaTypeName.GetText()); // Attributes MObject UsdMayaStageNode::filePathAttr; MObject UsdMayaStageNode::outUsdStageAttr; - /* static */ -void* -UsdMayaStageNode::creator() -{ - return new UsdMayaStageNode(); -} +void* UsdMayaStageNode::creator() { return new UsdMayaStageNode(); } /* static */ -MStatus -UsdMayaStageNode::initialize() +MStatus UsdMayaStageNode::initialize() { MStatus status; @@ -76,22 +67,16 @@ UsdMayaStageNode::initialize() MFnStringData stringDataFn; const MObject defaultStringDataObj = stringDataFn.create(""); - filePathAttr = typedAttrFn.create("filePath", - "fp", - MFnData::kString, - defaultStringDataObj, - &status); + filePathAttr + = typedAttrFn.create("filePath", "fp", MFnData::kString, defaultStringDataObj, &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = typedAttrFn.setUsedAsFilename(true); CHECK_MSTATUS_AND_RETURN_IT(status); status = addAttribute(filePathAttr); CHECK_MSTATUS_AND_RETURN_IT(status); - outUsdStageAttr = typedAttrFn.create("outUsdStage", - "os", - MayaUsdStageData::mayaTypeId, - MObject::kNullObj, - &status); + outUsdStageAttr = typedAttrFn.create( + "outUsdStage", "os", MayaUsdStageData::mayaTypeId, MObject::kNullObj, &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = typedAttrFn.setWritable(false); CHECK_MSTATUS_AND_RETURN_IT(status); @@ -107,26 +92,22 @@ UsdMayaStageNode::initialize() } /* virtual */ -MStatus -UsdMayaStageNode::compute(const MPlug& plug, MDataBlock& dataBlock) +MStatus UsdMayaStageNode::compute(const MPlug& plug, MDataBlock& dataBlock) { MStatus status = MS::kUnknownParameter; if (plug == outUsdStageAttr) { - const MDataHandle filePathHandle = dataBlock.inputValue(filePathAttr, - &status); + const MDataHandle filePathHandle = dataBlock.inputValue(filePathAttr, &status); CHECK_MSTATUS_AND_RETURN_IT(status); - const std::string usdFile = - TfStringTrim(filePathHandle.asString().asChar()); + const std::string usdFile = TfStringTrim(filePathHandle.asString().asChar()); UsdStageRefPtr usdStage; if (SdfLayerRefPtr rootLayer = SdfLayer::FindOrOpen(usdFile)) { - const bool loadAll = true; + const bool loadAll = true; UsdStageCacheContext ctx(UsdMayaStageCache::Get(loadAll)); - usdStage = UsdStage::Open(rootLayer, - ArGetResolver().GetCurrentContext()); + usdStage = UsdStage::Open(rootLayer, ArGetResolver().GetCurrentContext()); usdStage->SetEditTarget(usdStage->GetRootLayer()); } @@ -138,19 +119,17 @@ UsdMayaStageNode::compute(const MPlug& plug, MDataBlock& dataBlock) // Create the output stage data object. MFnPluginData pluginDataFn; - MObject stageDataObj = - pluginDataFn.create(MayaUsdStageData::mayaTypeId, &status); + MObject stageDataObj = pluginDataFn.create(MayaUsdStageData::mayaTypeId, &status); CHECK_MSTATUS_AND_RETURN_IT(status); - MayaUsdStageData* stageData = - reinterpret_cast(pluginDataFn.data(&status)); + MayaUsdStageData* stageData + = reinterpret_cast(pluginDataFn.data(&status)); CHECK_MSTATUS_AND_RETURN_IT(status); stageData->stage = usdStage; stageData->primPath = primPath; - MDataHandle outUsdStageHandle = dataBlock.outputValue(outUsdStageAttr, - &status); + MDataHandle outUsdStageHandle = dataBlock.outputValue(outUsdStageAttr, &status); CHECK_MSTATUS_AND_RETURN_IT(status); outUsdStageHandle.set(stageData); @@ -162,14 +141,12 @@ UsdMayaStageNode::compute(const MPlug& plug, MDataBlock& dataBlock) return status; } -UsdMayaStageNode::UsdMayaStageNode() : MPxNode() +UsdMayaStageNode::UsdMayaStageNode() + : MPxNode() { } /* virtual */ -UsdMayaStageNode::~UsdMayaStageNode() -{ -} - +UsdMayaStageNode::~UsdMayaStageNode() { } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/nodes/stageNode.h b/lib/mayaUsd/nodes/stageNode.h index c705feac48..4ce6a7a466 100644 --- a/lib/mayaUsd/nodes/stageNode.h +++ b/lib/mayaUsd/nodes/stageNode.h @@ -16,6 +16,11 @@ #ifndef PXRUSDMAYA_STAGE_NODE_H #define PXRUSDMAYA_STAGE_NODE_H +#include + +#include +#include + #include #include #include @@ -24,20 +29,11 @@ #include #include -#include -#include - -#include - PXR_NAMESPACE_OPEN_SCOPE -#define PXRUSDMAYA_STAGE_NODE_TOKENS \ - ((MayaTypeName, "pxrUsdStageNode")) - -TF_DECLARE_PUBLIC_TOKENS(UsdMayaStageNodeTokens, - MAYAUSD_CORE_PUBLIC, - PXRUSDMAYA_STAGE_NODE_TOKENS); +#define PXRUSDMAYA_STAGE_NODE_TOKENS ((MayaTypeName, "pxrUsdStageNode")) +TF_DECLARE_PUBLIC_TOKENS(UsdMayaStageNodeTokens, MAYAUSD_CORE_PUBLIC, PXRUSDMAYA_STAGE_NODE_TOKENS); /// Maya dependency node that reads and outputs a USD stage. /// @@ -51,38 +47,36 @@ TF_DECLARE_PUBLIC_TOKENS(UsdMayaStageNodeTokens, /// stage and its contents. class UsdMayaStageNode : public MPxNode { - public: - MAYAUSD_CORE_PUBLIC - static const MTypeId typeId; - MAYAUSD_CORE_PUBLIC - static const MString typeName; - - // Attributes - MAYAUSD_CORE_PUBLIC - static MObject filePathAttr; - MAYAUSD_CORE_PUBLIC - static MObject outUsdStageAttr; - - MAYAUSD_CORE_PUBLIC - static void* creator(); - - MAYAUSD_CORE_PUBLIC - static MStatus initialize(); - - // MPxNode overrides - MAYAUSD_CORE_PUBLIC - MStatus compute(const MPlug& plug, MDataBlock& dataBlock) override; - - private: - UsdMayaStageNode(); - ~UsdMayaStageNode() override; - - UsdMayaStageNode(const UsdMayaStageNode&); - UsdMayaStageNode& operator=(const UsdMayaStageNode&); +public: + MAYAUSD_CORE_PUBLIC + static const MTypeId typeId; + MAYAUSD_CORE_PUBLIC + static const MString typeName; + + // Attributes + MAYAUSD_CORE_PUBLIC + static MObject filePathAttr; + MAYAUSD_CORE_PUBLIC + static MObject outUsdStageAttr; + + MAYAUSD_CORE_PUBLIC + static void* creator(); + + MAYAUSD_CORE_PUBLIC + static MStatus initialize(); + + // MPxNode overrides + MAYAUSD_CORE_PUBLIC + MStatus compute(const MPlug& plug, MDataBlock& dataBlock) override; + +private: + UsdMayaStageNode(); + ~UsdMayaStageNode() override; + + UsdMayaStageNode(const UsdMayaStageNode&); + UsdMayaStageNode& operator=(const UsdMayaStageNode&); }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/nodes/usdPrimProvider.cpp b/lib/mayaUsd/nodes/usdPrimProvider.cpp index 463bc044a1..85ceeedeb5 100644 --- a/lib/mayaUsd/nodes/usdPrimProvider.cpp +++ b/lib/mayaUsd/nodes/usdPrimProvider.cpp @@ -19,10 +19,6 @@ PXR_NAMESPACE_OPEN_SCOPE - -UsdMayaUsdPrimProvider::~UsdMayaUsdPrimProvider() -{ -} +UsdMayaUsdPrimProvider::~UsdMayaUsdPrimProvider() { } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/nodes/usdPrimProvider.h b/lib/mayaUsd/nodes/usdPrimProvider.h index b9e5bb490b..48653fffee 100644 --- a/lib/mayaUsd/nodes/usdPrimProvider.h +++ b/lib/mayaUsd/nodes/usdPrimProvider.h @@ -16,14 +16,14 @@ #ifndef PXRUSDMAYA_USD_PRIM_PROVIDER_H #define PXRUSDMAYA_USD_PRIM_PROVIDER_H +#include + #include #include -#include - PXR_NAMESPACE_OPEN_SCOPE -// interface class +// interface class class UsdMayaUsdPrimProvider { public: @@ -34,7 +34,6 @@ class UsdMayaUsdPrimProvider virtual ~UsdMayaUsdPrimProvider(); }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/python/module.cpp b/lib/mayaUsd/python/module.cpp index ae0b70e517..82940a72f8 100644 --- a/lib/mayaUsd/python/module.cpp +++ b/lib/mayaUsd/python/module.cpp @@ -13,13 +13,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - #include +#include PXR_NAMESPACE_USING_DIRECTIVE -TF_WRAP_MODULE { +TF_WRAP_MODULE +{ TF_WRAP(Adaptor); TF_WRAP(BlockSceneModificationContext); TF_WRAP(ColorSpace); diff --git a/lib/mayaUsd/python/moduleDeps.cpp b/lib/mayaUsd/python/moduleDeps.cpp index d4bc421308..83f60b8a63 100644 --- a/lib/mayaUsd/python/moduleDeps.cpp +++ b/lib/mayaUsd/python/moduleDeps.cpp @@ -13,40 +13,26 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include #include #include #include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -TF_REGISTRY_FUNCTION(TfScriptModuleLoader) { +TF_REGISTRY_FUNCTION(TfScriptModuleLoader) +{ // List of direct dependencies for this library. - const std::vector reqs = { - TfToken("ar"), - TfToken("gf"), - TfToken("hd"), - TfToken("hdx"), - TfToken("js"), - TfToken("kind"), - TfToken("plug"), - TfToken("sdf"), - TfToken("tf"), - TfToken("usd"), - TfToken("usdGeom"), - TfToken("usdImaging"), - TfToken("usdImagingGL"), - TfToken("usdLux"), - TfToken("usdRi"), - TfToken("usdShade"), - TfToken("usdSkel"), - TfToken("usdUtils"), - TfToken("vt") - }; - TfScriptModuleLoader::GetInstance(). - RegisterLibrary(TfToken("mayaUsd"), TfToken("mayaUsd.lib"), reqs); + const std::vector reqs + = { TfToken("ar"), TfToken("gf"), TfToken("hd"), TfToken("hdx"), + TfToken("js"), TfToken("kind"), TfToken("plug"), TfToken("sdf"), + TfToken("tf"), TfToken("usd"), TfToken("usdGeom"), TfToken("usdImaging"), + TfToken("usdImagingGL"), TfToken("usdLux"), TfToken("usdRi"), TfToken("usdShade"), + TfToken("usdSkel"), TfToken("usdUtils"), TfToken("vt") }; + TfScriptModuleLoader::GetInstance().RegisterLibrary( + TfToken("mayaUsd"), TfToken("mayaUsd.lib"), reqs); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/python/wrapAdaptor.cpp b/lib/mayaUsd/python/wrapAdaptor.cpp index ca82e640e1..09b53054f0 100644 --- a/lib/mayaUsd/python/wrapAdaptor.cpp +++ b/lib/mayaUsd/python/wrapAdaptor.cpp @@ -13,26 +13,25 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include +#include +#include +#include -#include #include -#include +#include #include #include +#include -#include -#include -#include +#include + +#include using namespace boost::python; PXR_NAMESPACE_USING_DIRECTIVE; -static UsdMayaAdaptor* -_Adaptor__init__(const std::string& dagPath) +static UsdMayaAdaptor* _Adaptor__init__(const std::string& dagPath) { MObject object; MStatus status = UsdMayaUtil::GetMObjectByName(dagPath, object); @@ -43,8 +42,7 @@ _Adaptor__init__(const std::string& dagPath) return new UsdMayaAdaptor(object); } -static boost::python::object -_Adaptor_GetMetadata(const UsdMayaAdaptor& self, const TfToken& key) +static boost::python::object _Adaptor_GetMetadata(const UsdMayaAdaptor& self, const TfToken& key) { VtValue value; if (self.GetMetadata(key, &value)) { @@ -53,126 +51,91 @@ _Adaptor_GetMetadata(const UsdMayaAdaptor& self, const TfToken& key) return boost::python::object(); } -static bool -_Adaptor_SetMetadata( - UsdMayaAdaptor& self, - const TfToken& key, - const VtValue& value) +static bool _Adaptor_SetMetadata(UsdMayaAdaptor& self, const TfToken& key, const VtValue& value) { return UsdMayaUndoHelperCommand::ExecuteWithUndo( - [&self, &key, &value](MDGModifier& modifier) { - return self.SetMetadata(key, value, modifier); - }); + [&self, &key, &value](MDGModifier& modifier) { + return self.SetMetadata(key, value, modifier); + }); } -static void -_Adaptor_ClearMetadata( - UsdMayaAdaptor& self, - const TfToken& key) +static void _Adaptor_ClearMetadata(UsdMayaAdaptor& self, const TfToken& key) { UsdMayaUndoHelperCommand::ExecuteWithUndo( - [&self, &key](MDGModifier& modifier) { - self.ClearMetadata(key, modifier); - }); + [&self, &key](MDGModifier& modifier) { self.ClearMetadata(key, modifier); }); } -static UsdMayaAdaptor::SchemaAdaptor -_Adaptor_ApplySchema( - UsdMayaAdaptor& self, - const TfType& ty) +static UsdMayaAdaptor::SchemaAdaptor _Adaptor_ApplySchema(UsdMayaAdaptor& self, const TfType& ty) { typedef UsdMayaAdaptor::SchemaAdaptor Result; return UsdMayaUndoHelperCommand::ExecuteWithUndo( - [&self, &ty](MDGModifier& modifier) { - return self.ApplySchema(ty, modifier); - }); + [&self, &ty](MDGModifier& modifier) { return self.ApplySchema(ty, modifier); }); } static UsdMayaAdaptor::SchemaAdaptor -_Adaptor_ApplySchemaByName( - UsdMayaAdaptor& self, - const TfToken& schemaName) +_Adaptor_ApplySchemaByName(UsdMayaAdaptor& self, const TfToken& schemaName) { typedef UsdMayaAdaptor::SchemaAdaptor Result; return UsdMayaUndoHelperCommand::ExecuteWithUndo( - [&self, &schemaName](MDGModifier& modifier) { - return self.ApplySchemaByName(schemaName, modifier); - }); + [&self, &schemaName](MDGModifier& modifier) { + return self.ApplySchemaByName(schemaName, modifier); + }); } -static void -_Adaptor_UnapplySchema( - UsdMayaAdaptor& self, - const TfType& ty) +static void _Adaptor_UnapplySchema(UsdMayaAdaptor& self, const TfType& ty) { UsdMayaUndoHelperCommand::ExecuteWithUndo( - [&self, &ty](MDGModifier& modifier) { - self.UnapplySchema(ty, modifier); - }); + [&self, &ty](MDGModifier& modifier) { self.UnapplySchema(ty, modifier); }); } -static void -_Adaptor_UnapplySchemaByName( - UsdMayaAdaptor& self, - const TfToken& schemaName) +static void _Adaptor_UnapplySchemaByName(UsdMayaAdaptor& self, const TfToken& schemaName) { - UsdMayaUndoHelperCommand::ExecuteWithUndo( - [&self, &schemaName](MDGModifier& modifier) { - self.UnapplySchemaByName(schemaName, modifier); - }); + UsdMayaUndoHelperCommand::ExecuteWithUndo([&self, &schemaName](MDGModifier& modifier) { + self.UnapplySchemaByName(schemaName, modifier); + }); } -static std::string -_Adaptor__repr__(const UsdMayaAdaptor& self) +static std::string _Adaptor__repr__(const UsdMayaAdaptor& self) { if (self) { - return TfStringPrintf("%sAdaptor('%s')", - TF_PY_REPR_PREFIX.c_str(), - self.GetMayaNodeName().c_str()); - } - else { + return TfStringPrintf( + "%sAdaptor('%s')", TF_PY_REPR_PREFIX.c_str(), self.GetMayaNodeName().c_str()); + } else { return "invalid adaptor"; } } static UsdMayaAdaptor::AttributeAdaptor -_SchemaAdaptor_CreateAttribute( - UsdMayaAdaptor::SchemaAdaptor& self, - const TfToken& attrName) +_SchemaAdaptor_CreateAttribute(UsdMayaAdaptor::SchemaAdaptor& self, const TfToken& attrName) { typedef UsdMayaAdaptor::AttributeAdaptor Result; return UsdMayaUndoHelperCommand::ExecuteWithUndo( - [&self, &attrName](MDGModifier& modifier) { - return self.CreateAttribute(attrName, modifier); - }); + [&self, &attrName](MDGModifier& modifier) { + return self.CreateAttribute(attrName, modifier); + }); } static void -_SchemaAdaptor_RemoveAttribute( - UsdMayaAdaptor::SchemaAdaptor& self, - const TfToken& attrName) +_SchemaAdaptor_RemoveAttribute(UsdMayaAdaptor::SchemaAdaptor& self, const TfToken& attrName) { - UsdMayaUndoHelperCommand::ExecuteWithUndo( - [&self, &attrName](MDGModifier& modifier) { - return self.RemoveAttribute(attrName, modifier); - }); + UsdMayaUndoHelperCommand::ExecuteWithUndo([&self, &attrName](MDGModifier& modifier) { + return self.RemoveAttribute(attrName, modifier); + }); } -static std::string -_SchemaAdaptor__repr__(const UsdMayaAdaptor::SchemaAdaptor& self) +static std::string _SchemaAdaptor__repr__(const UsdMayaAdaptor::SchemaAdaptor& self) { if (self) { - return TfStringPrintf("%s.GetSchemaByName('%s')", - TfPyRepr(self.GetNodeAdaptor()).c_str(), - self.GetName().GetText()); - } - else { + return TfStringPrintf( + "%s.GetSchemaByName('%s')", + TfPyRepr(self.GetNodeAdaptor()).c_str(), + self.GetName().GetText()); + } else { return "invalid schema adaptor"; } } -static boost::python::object -_AttributeAdaptor_Get(const UsdMayaAdaptor::AttributeAdaptor& self) +static boost::python::object _AttributeAdaptor_Get(const UsdMayaAdaptor::AttributeAdaptor& self) { VtValue value; if (self.Get(&value)) { @@ -181,37 +144,31 @@ _AttributeAdaptor_Get(const UsdMayaAdaptor::AttributeAdaptor& self) return boost::python::object(); } -static bool -_AttributeAdaptor_Set( - UsdMayaAdaptor::AttributeAdaptor& self, - const VtValue& value) +static bool _AttributeAdaptor_Set(UsdMayaAdaptor::AttributeAdaptor& self, const VtValue& value) { return UsdMayaUndoHelperCommand::ExecuteWithUndo( - [&self, &value](MDGModifier& modifier) { - return self.Set(value, modifier); - }); + [&self, &value](MDGModifier& modifier) { return self.Set(value, modifier); }); } -static std::string -_AttributeAdaptor__repr__(const UsdMayaAdaptor::AttributeAdaptor& self) +static std::string _AttributeAdaptor__repr__(const UsdMayaAdaptor::AttributeAdaptor& self) { - std::string schemaName; + std::string schemaName; const SdfAttributeSpecHandle attrDef = self.GetAttributeDefinition(); if (TF_VERIFY(attrDef)) { - const SdfPrimSpecHandle schemaDef = - TfDynamic_cast(attrDef->GetOwner()); + const SdfPrimSpecHandle schemaDef + = TfDynamic_cast(attrDef->GetOwner()); if (TF_VERIFY(schemaDef)) { schemaName = schemaDef->GetName(); } } if (self) { - return TfStringPrintf("%s.GetSchemaByName('%s').GetAttribute('%s')", - TfPyRepr(self.GetNodeAdaptor()).c_str(), - schemaName.c_str(), - self.GetName().GetText()); - } - else { + return TfStringPrintf( + "%s.GetSchemaByName('%s').GetAttribute('%s')", + TfPyRepr(self.GetNodeAdaptor()).c_str(), + schemaName.c_str(), + self.GetName().GetText()); + } else { return "invalid attribute adaptor"; } } @@ -219,43 +176,50 @@ _AttributeAdaptor__repr__(const UsdMayaAdaptor::AttributeAdaptor& self) void wrapAdaptor() { typedef UsdMayaAdaptor This; - scope Adaptor = class_("Adaptor", no_init) - .def(!self) - .def("__init__", make_constructor(_Adaptor__init__)) - .def("__repr__", _Adaptor__repr__) - .def("GetMayaNodeName", &This::GetMayaNodeName) - .def("GetUsdTypeName", &This::GetUsdTypeName) - .def("GetUsdType", &This::GetUsdType) - .def("GetAppliedSchemas", &This::GetAppliedSchemas) - .def("GetSchema", &This::GetSchema) - .def("GetSchemaByName", - (This::SchemaAdaptor (This::*)(const TfToken&) const) - &This::GetSchemaByName) - .def("GetSchemaOrInheritedSchema", - (This::SchemaAdaptor (This::*)(const TfType&) const) - &This::GetSchemaOrInheritedSchema) - .def("ApplySchema", _Adaptor_ApplySchema) - .def("ApplySchemaByName", _Adaptor_ApplySchemaByName) - .def("UnapplySchema", _Adaptor_UnapplySchema) - .def("UnapplySchemaByName", _Adaptor_UnapplySchemaByName) - .def("GetAllAuthoredMetadata", &This::GetAllAuthoredMetadata, - return_value_policy()) - .def("GetMetadata", _Adaptor_GetMetadata) - .def("SetMetadata", _Adaptor_SetMetadata) - .def("ClearMetadata", _Adaptor_ClearMetadata) - .def("GetPrimMetadataFields", &This::GetPrimMetadataFields) - .staticmethod("GetPrimMetadataFields") - .def("GetRegisteredAPISchemas", &This::GetRegisteredAPISchemas, - return_value_policy()) - .staticmethod("GetRegisteredAPISchemas") - .def("GetRegisteredTypedSchemas", &This::GetRegisteredTypedSchemas, - return_value_policy()) - .staticmethod("GetRegisteredTypedSchemas") - .def("RegisterAttributeAlias", &This::RegisterAttributeAlias) - .staticmethod("RegisterAttributeAlias") - .def("GetAttributeAliases", &This::GetAttributeAliases) - .staticmethod("GetAttributeAliases") - ; + scope Adaptor + = class_("Adaptor", no_init) + .def(!self) + .def("__init__", make_constructor(_Adaptor__init__)) + .def("__repr__", _Adaptor__repr__) + .def("GetMayaNodeName", &This::GetMayaNodeName) + .def("GetUsdTypeName", &This::GetUsdTypeName) + .def("GetUsdType", &This::GetUsdType) + .def("GetAppliedSchemas", &This::GetAppliedSchemas) + .def("GetSchema", &This::GetSchema) + .def( + "GetSchemaByName", + (This::SchemaAdaptor(This::*)(const TfToken&) const) & This::GetSchemaByName) + .def( + "GetSchemaOrInheritedSchema", + (This::SchemaAdaptor(This::*)(const TfType&) const) + & This::GetSchemaOrInheritedSchema) + .def("ApplySchema", _Adaptor_ApplySchema) + .def("ApplySchemaByName", _Adaptor_ApplySchemaByName) + .def("UnapplySchema", _Adaptor_UnapplySchema) + .def("UnapplySchemaByName", _Adaptor_UnapplySchemaByName) + .def( + "GetAllAuthoredMetadata", + &This::GetAllAuthoredMetadata, + return_value_policy()) + .def("GetMetadata", _Adaptor_GetMetadata) + .def("SetMetadata", _Adaptor_SetMetadata) + .def("ClearMetadata", _Adaptor_ClearMetadata) + .def("GetPrimMetadataFields", &This::GetPrimMetadataFields) + .staticmethod("GetPrimMetadataFields") + .def( + "GetRegisteredAPISchemas", + &This::GetRegisteredAPISchemas, + return_value_policy()) + .staticmethod("GetRegisteredAPISchemas") + .def( + "GetRegisteredTypedSchemas", + &This::GetRegisteredTypedSchemas, + return_value_policy()) + .staticmethod("GetRegisteredTypedSchemas") + .def("RegisterAttributeAlias", &This::RegisterAttributeAlias) + .staticmethod("RegisterAttributeAlias") + .def("GetAttributeAliases", &This::GetAttributeAliases) + .staticmethod("GetAttributeAliases"); class_("SchemaAdaptor") .def(!self) @@ -265,10 +229,8 @@ void wrapAdaptor() .def("GetAttribute", &This::SchemaAdaptor::GetAttribute) .def("CreateAttribute", _SchemaAdaptor_CreateAttribute) .def("RemoveAttribute", _SchemaAdaptor_RemoveAttribute) - .def("GetAuthoredAttributeNames", - &This::SchemaAdaptor::GetAuthoredAttributeNames) - .def("GetAttributeNames", &This::SchemaAdaptor::GetAttributeNames) - ; + .def("GetAuthoredAttributeNames", &This::SchemaAdaptor::GetAuthoredAttributeNames) + .def("GetAttributeNames", &This::SchemaAdaptor::GetAttributeNames); class_("AttributeAdaptor") .def(!self) @@ -277,7 +239,5 @@ void wrapAdaptor() .def("GetName", &This::AttributeAdaptor::GetName) .def("Get", _AttributeAdaptor_Get) .def("Set", _AttributeAdaptor_Set) - .def("GetAttributeDefinition", - &This::AttributeAdaptor::GetAttributeDefinition) - ; + .def("GetAttributeDefinition", &This::AttributeAdaptor::GetAttributeDefinition); } diff --git a/lib/mayaUsd/python/wrapBlockSceneModificationContext.cpp b/lib/mayaUsd/python/wrapBlockSceneModificationContext.cpp index ae6c60a0a1..3da1c90cbc 100644 --- a/lib/mayaUsd/python/wrapBlockSceneModificationContext.cpp +++ b/lib/mayaUsd/python/wrapBlockSceneModificationContext.cpp @@ -13,13 +13,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include +#include #include -#include +#include + +#include using namespace boost::python; @@ -31,30 +31,23 @@ namespace { // manager" object that can be used with the "with" statement. class _PyBlockSceneModificationContext { - public: - void __enter__() { - _context.reset(new UsdMayaBlockSceneModificationContext()); - } +public: + void __enter__() { _context.reset(new UsdMayaBlockSceneModificationContext()); } - void __exit__(object, object, object) { - _context.reset(); - } + void __exit__(object, object, object) { _context.reset(); } - private: - std::shared_ptr _context; +private: + std::shared_ptr _context; }; } // anonymous namespace - -void -wrapBlockSceneModificationContext() +void wrapBlockSceneModificationContext() { typedef _PyBlockSceneModificationContext Context; class_( - "BlockSceneModificationContext", - "Context manager for blocking scene modification status changes") + "BlockSceneModificationContext", + "Context manager for blocking scene modification status changes") .def("__enter__", &Context::__enter__, return_self<>()) - .def("__exit__", &Context::__exit__) - ; + .def("__exit__", &Context::__exit__); } diff --git a/lib/mayaUsd/python/wrapColorSpace.cpp b/lib/mayaUsd/python/wrapColorSpace.cpp index 97b02de4e3..d028c6a2a8 100644 --- a/lib/mayaUsd/python/wrapColorSpace.cpp +++ b/lib/mayaUsd/python/wrapColorSpace.cpp @@ -13,17 +13,17 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include +#include -#include #include #include #include #include #include +#include -#include +#include +#include using namespace std; using namespace boost::python; diff --git a/lib/mayaUsd/python/wrapDiagnosticDelegate.cpp b/lib/mayaUsd/python/wrapDiagnosticDelegate.cpp index 0f5e9750ba..971dda6160 100644 --- a/lib/mayaUsd/python/wrapDiagnosticDelegate.cpp +++ b/lib/mayaUsd/python/wrapDiagnosticDelegate.cpp @@ -13,12 +13,12 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include +#include #include -#include +#include +#include using namespace boost::python; @@ -28,14 +28,11 @@ namespace { // This exposes UsdMayaDiagnosticBatchContext as a Python "context manager" // object that can be used with the "with"-statement. -class _PyDiagnosticBatchContext { +class _PyDiagnosticBatchContext +{ public: - void __enter__() { - _context.reset(new UsdMayaDiagnosticBatchContext()); - } - void __exit__(object, object, object) { - _context.reset(); - } + void __enter__() { _context.reset(new UsdMayaDiagnosticBatchContext()); } + void __exit__(object, object, object) { _context.reset(); } private: std::unique_ptr _context; @@ -48,12 +45,10 @@ void wrapDiagnosticDelegate() typedef UsdMayaDiagnosticDelegate This; class_("DiagnosticDelegate", no_init) .def("GetBatchCount", &This::GetBatchCount) - .staticmethod("GetBatchCount") - ; + .staticmethod("GetBatchCount"); typedef _PyDiagnosticBatchContext Context; class_("DiagnosticBatchContext") .def("__enter__", &Context::__enter__, return_self<>()) - .def("__exit__", &Context::__exit__) - ; + .def("__exit__", &Context::__exit__); } diff --git a/lib/mayaUsd/python/wrapMeshWriteUtils.cpp b/lib/mayaUsd/python/wrapMeshWriteUtils.cpp index ceb20b5c60..65a33e9454 100644 --- a/lib/mayaUsd/python/wrapMeshWriteUtils.cpp +++ b/lib/mayaUsd/python/wrapMeshWriteUtils.cpp @@ -13,23 +13,23 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include +#include -#include -#include +#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include -#include +#include +#include -#include -#include +#include using namespace boost::python; @@ -37,25 +37,21 @@ PXR_NAMESPACE_USING_DIRECTIVE namespace { -static -tuple -_GetMeshNormals(const std::string& meshDagPath) +static tuple _GetMeshNormals(const std::string& meshDagPath) { VtArray normalsArray; - TfToken interpolation; + TfToken interpolation; MObject meshObj; MStatus status = UsdMayaUtil::GetMObjectByName(meshDagPath, meshObj); if (status != MS::kSuccess) { - TF_CODING_ERROR("Could not get MObject for dagPath: %s", - meshDagPath.c_str()); + TF_CODING_ERROR("Could not get MObject for dagPath: %s", meshDagPath.c_str()); return make_tuple(normalsArray, interpolation); } MFnMesh meshFn(meshObj, &status); if (!meshObj.hasFn(MFn::kMesh)) { - TF_CODING_ERROR("MFnMesh() failed for object at dagPath: %s", - meshDagPath.c_str()); + TF_CODING_ERROR("MFnMesh() failed for object at dagPath: %s", meshDagPath.c_str()); return make_tuple(normalsArray, interpolation); } @@ -66,17 +62,18 @@ _GetMeshNormals(const std::string& meshDagPath) // Dummy class for putting UsdMayaMeshWriteUtils namespace functions in a Python // MeshWriteUtils namespace. -class DummyScopeClass{}; - -} // anonymous namespace +class DummyScopeClass +{ +}; +} // anonymous namespace void wrapMeshWriteUtils() { scope s = class_("MeshWriteUtils", no_init) - .def("GetMeshNormals", &_GetMeshNormals) - .staticmethod("GetMeshNormals") + .def("GetMeshNormals", &_GetMeshNormals) + .staticmethod("GetMeshNormals") ; } diff --git a/lib/mayaUsd/python/wrapQuery.cpp b/lib/mayaUsd/python/wrapQuery.cpp index 5ef7df9515..1784b56b5d 100644 --- a/lib/mayaUsd/python/wrapQuery.cpp +++ b/lib/mayaUsd/python/wrapQuery.cpp @@ -13,13 +13,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include +#include -#include #include +#include -#include +#include +#include using namespace std; using namespace boost::python; diff --git a/lib/mayaUsd/python/wrapReadUtil.cpp b/lib/mayaUsd/python/wrapReadUtil.cpp index 01949a268a..445a8cdc50 100644 --- a/lib/mayaUsd/python/wrapReadUtil.cpp +++ b/lib/mayaUsd/python/wrapReadUtil.cpp @@ -13,29 +13,28 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include +#include +#include -#include #include +#include #include #include -#include -#include +#include + +#include using namespace boost::python; PXR_NAMESPACE_USING_DIRECTIVE; -static -std::string _FindOrCreateMayaAttr( +static std::string _FindOrCreateMayaAttr( const SdfValueTypeName& typeName, - const SdfVariability variability, - const std::string& nodeName, - const std::string& attrName, - const std::string& attrNiceName = std::string()) + const SdfVariability variability, + const std::string& nodeName, + const std::string& attrName, + const std::string& attrNiceName = std::string()) { std::string attrPath; @@ -47,7 +46,7 @@ std::string _FindOrCreateMayaAttr( CHECK_MSTATUS_AND_RETURN(status, attrPath); MObject attrObj = UsdMayaReadUtil::FindOrCreateMayaAttr( - typeName, variability, depNode, attrName, attrNiceName); + typeName, variability, depNode, attrName, attrNiceName); if (attrObj.isNull()) { return attrPath; } @@ -56,12 +55,9 @@ std::string _FindOrCreateMayaAttr( return attrPath; } -static -bool _SetMayaAttr( - const std::string& attrPath, - const VtValue& newValue) +static bool _SetMayaAttr(const std::string& attrPath, const VtValue& newValue) { - MPlug plug; + MPlug plug; MStatus status = UsdMayaUtil::GetPlugByName(attrPath, plug); if (!status) { TF_RUNTIME_ERROR("Couldn't find plug '%s'", attrPath.c_str()); @@ -71,12 +67,9 @@ bool _SetMayaAttr( return UsdMayaReadUtil::SetMayaAttr(plug, newValue); } -static -void _SetMayaAttrKeyableState( - const std::string& attrPath, - const SdfVariability variability) +static void _SetMayaAttrKeyableState(const std::string& attrPath, const SdfVariability variability) { - MPlug plug; + MPlug plug; MStatus status = UsdMayaUtil::GetPlugByName(attrPath, plug); if (!status) { TF_RUNTIME_ERROR("Couldn't find plug '%s'", attrPath.c_str()); @@ -94,13 +87,17 @@ void wrapReadUtil() .staticmethod("ReadFloat2AsUV") .def("ReadSTAsMap1", This::ReadSTAsMap1) .staticmethod("ReadSTAsMap1") - .def("FindOrCreateMayaAttr", _FindOrCreateMayaAttr, - (arg("typeName"), arg("variability"), arg("nodeName"), - arg("attrName"), arg("attrNiceName")=std::string())) + .def( + "FindOrCreateMayaAttr", + _FindOrCreateMayaAttr, + (arg("typeName"), + arg("variability"), + arg("nodeName"), + arg("attrName"), + arg("attrNiceName") = std::string())) .staticmethod("FindOrCreateMayaAttr") .def("SetMayaAttr", _SetMayaAttr) .staticmethod("SetMayaAttr") .def("SetMayaAttrKeyableState", _SetMayaAttrKeyableState) - .staticmethod("SetMayaAttrKeyableState") - ; + .staticmethod("SetMayaAttrKeyableState"); } diff --git a/lib/mayaUsd/python/wrapRoundTripUtil.cpp b/lib/mayaUsd/python/wrapRoundTripUtil.cpp index 8c790ecdc0..db2761ae29 100644 --- a/lib/mayaUsd/python/wrapRoundTripUtil.cpp +++ b/lib/mayaUsd/python/wrapRoundTripUtil.cpp @@ -13,14 +13,14 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include #include -#include #include #include +#include -#include +#include using namespace std; using namespace boost::python; @@ -31,20 +31,19 @@ PXR_NAMESPACE_USING_DIRECTIVE; void wrapRoundTripUtil() { typedef UsdMayaRoundTripUtil This; - scope RoundTripUtil = class_("RoundTripUtil", no_init) - .def("IsAttributeUserAuthored", This::IsAttributeUserAuthored) - .staticmethod("IsAttributeUserAuthored") - - .def("IsAttributeMayaGenerated", This::IsAttributeMayaGenerated) - .staticmethod("IsAttributeMayaGenerated") - .def("MarkAttributeAsMayaGenerated", This::MarkAttributeAsMayaGenerated) - .staticmethod("MarkAttributeAsMayaGenerated") - - .def("IsPrimvarClamped", This::IsPrimvarClamped) - .staticmethod("IsPrimvarClamped") - - .def("MarkPrimvarAsClamped", This::MarkPrimvarAsClamped) - .staticmethod("MarkPrimvarAsClamped") - ; - + scope RoundTripUtil + = class_("RoundTripUtil", no_init) + .def("IsAttributeUserAuthored", This::IsAttributeUserAuthored) + .staticmethod("IsAttributeUserAuthored") + + .def("IsAttributeMayaGenerated", This::IsAttributeMayaGenerated) + .staticmethod("IsAttributeMayaGenerated") + .def("MarkAttributeAsMayaGenerated", This::MarkAttributeAsMayaGenerated) + .staticmethod("MarkAttributeAsMayaGenerated") + + .def("IsPrimvarClamped", This::IsPrimvarClamped) + .staticmethod("IsPrimvarClamped") + + .def("MarkPrimvarAsClamped", This::MarkPrimvarAsClamped) + .staticmethod("MarkPrimvarAsClamped"); } diff --git a/lib/mayaUsd/python/wrapStageCache.cpp b/lib/mayaUsd/python/wrapStageCache.cpp index e2fc4132bd..0906525c87 100644 --- a/lib/mayaUsd/python/wrapStageCache.cpp +++ b/lib/mayaUsd/python/wrapStageCache.cpp @@ -13,14 +13,14 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include -#include +#include -#include #include +#include -#include +#include +#include +#include using namespace std; using namespace boost::python; @@ -32,11 +32,12 @@ void wrapStageCache() { class_("StageCache") - .def("Get", &UsdMayaStageCache::Get, - args("loadAll"), - return_value_policy()) + .def( + "Get", + &UsdMayaStageCache::Get, + args("loadAll"), + return_value_policy()) .staticmethod("Get") .def("Clear", &UsdMayaStageCache::Clear) - .staticmethod("Clear") - ; + .staticmethod("Clear"); } diff --git a/lib/mayaUsd/python/wrapUserTaggedAttribute.cpp b/lib/mayaUsd/python/wrapUserTaggedAttribute.cpp index 50d1958bef..93a7095bd2 100644 --- a/lib/mayaUsd/python/wrapUserTaggedAttribute.cpp +++ b/lib/mayaUsd/python/wrapUserTaggedAttribute.cpp @@ -13,74 +13,68 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include +#include +#include -#include -#include +#include +#include +#include +#include +#include #include #include #include #include -#include -#include -#include -#include -#include +#include +#include -#include -#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE namespace { -static -std::vector +static std::vector _GetUserTaggedAttributesForNode(const std::string& nodeName) { MObject mayaNode; MStatus status = UsdMayaUtil::GetMObjectByName(nodeName, mayaNode); - CHECK_MSTATUS_AND_RETURN( - status, - std::vector()); + CHECK_MSTATUS_AND_RETURN(status, std::vector()); return UsdMayaUserTaggedAttribute::GetUserTaggedAttributesForNode(mayaNode); } } // anonymous namespace - void wrapUserTaggedAttribute() { using namespace boost::python; - TF_PY_WRAP_PUBLIC_TOKENS("UserTaggedAttributeTokens", - UsdMayaUserTaggedAttributeTokens, - PXRUSDMAYA_ATTR_TOKENS); + TF_PY_WRAP_PUBLIC_TOKENS( + "UserTaggedAttributeTokens", UsdMayaUserTaggedAttributeTokens, PXRUSDMAYA_ATTR_TOKENS); - TfPyContainerConversions::from_python_sequence< - std::set, - TfPyContainerConversions::set_policy >(); + TfPyContainerConversions:: + from_python_sequence, TfPyContainerConversions::set_policy>(); - class_("UserTaggedAttribute", - "Attribute tagged for USD export", - no_init) - .def("GetMayaName", &UsdMayaUserTaggedAttribute::GetMayaName) - .def("GetUsdName", &UsdMayaUserTaggedAttribute::GetUsdName) - .def("GetUsdType", &UsdMayaUserTaggedAttribute::GetUsdType) - .def("GetUsdInterpolation", - &UsdMayaUserTaggedAttribute::GetUsdInterpolation) - .def("GetTranslateMayaDoubleToUsdSinglePrecision", - &UsdMayaUserTaggedAttribute::GetTranslateMayaDoubleToUsdSinglePrecision) - .def("GetFallbackTranslateMayaDoubleToUsdSinglePrecision", - &UsdMayaUserTaggedAttribute::GetFallbackTranslateMayaDoubleToUsdSinglePrecision) - .staticmethod("GetFallbackTranslateMayaDoubleToUsdSinglePrecision") - .def("GetUserTaggedAttributesForNode", - _GetUserTaggedAttributesForNode, - return_value_policy()) - .staticmethod("GetUserTaggedAttributesForNode") - ; + class_( + "UserTaggedAttribute", "Attribute tagged for USD export", no_init) + .def("GetMayaName", &UsdMayaUserTaggedAttribute::GetMayaName) + .def("GetUsdName", &UsdMayaUserTaggedAttribute::GetUsdName) + .def("GetUsdType", &UsdMayaUserTaggedAttribute::GetUsdType) + .def("GetUsdInterpolation", &UsdMayaUserTaggedAttribute::GetUsdInterpolation) + .def( + "GetTranslateMayaDoubleToUsdSinglePrecision", + &UsdMayaUserTaggedAttribute::GetTranslateMayaDoubleToUsdSinglePrecision) + .def( + "GetFallbackTranslateMayaDoubleToUsdSinglePrecision", + &UsdMayaUserTaggedAttribute::GetFallbackTranslateMayaDoubleToUsdSinglePrecision) + .staticmethod("GetFallbackTranslateMayaDoubleToUsdSinglePrecision") + .def( + "GetUserTaggedAttributesForNode", + _GetUserTaggedAttributesForNode, + return_value_policy()) + .staticmethod("GetUserTaggedAttributesForNode"); } diff --git a/lib/mayaUsd/python/wrapWriteUtil.cpp b/lib/mayaUsd/python/wrapWriteUtil.cpp index ef7ebce959..50b594d83c 100644 --- a/lib/mayaUsd/python/wrapWriteUtil.cpp +++ b/lib/mayaUsd/python/wrapWriteUtil.cpp @@ -13,30 +13,27 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include +#include +#include -#include #include +#include #include #include -#include -#include +#include + +#include using namespace boost::python; PXR_NAMESPACE_USING_DIRECTIVE; -static -VtValue _GetVtValue( - const std::string& attrPath, - const SdfValueTypeName& typeName) +static VtValue _GetVtValue(const std::string& attrPath, const SdfValueTypeName& typeName) { VtValue val; - MPlug plug; + MPlug plug; MStatus status = UsdMayaUtil::GetPlugByName(attrPath, plug); CHECK_MSTATUS_AND_RETURN(status, val); @@ -53,6 +50,5 @@ void wrapWriteUtil() .def("WriteMap1AsST", This::WriteMap1AsST) .staticmethod("WriteMap1AsST") .def("GetVtValue", _GetVtValue) - .staticmethod("GetVtValue") - ; + .staticmethod("GetVtValue"); } diff --git a/lib/mayaUsd/python/wrapXformStack.cpp b/lib/mayaUsd/python/wrapXformStack.cpp index e79ca3442d..10c0f57c93 100644 --- a/lib/mayaUsd/python/wrapXformStack.cpp +++ b/lib/mayaUsd/python/wrapXformStack.cpp @@ -13,244 +13,205 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include -#include -#include - -#include -#include +#include -#include #include #include #include #include +#include -#include +#include +#include + +#include +#include +#include +#include using namespace std; -using boost::python::object; using boost::python::class_; -using boost::python::no_init; -using boost::python::self; -using boost::python::extract; -using boost::python::return_value_policy; -using boost::python::return_by_value; using boost::python::copy_const_reference; +using boost::python::extract; +using boost::python::no_init; +using boost::python::object; using boost::python::reference_existing_object; +using boost::python::return_by_value; +using boost::python::return_value_policy; +using boost::python::self; PXR_NAMESPACE_USING_DIRECTIVE namespace { - // We wrap this class, instead of UsdMayaXformOpClassification directly, mostly - // just so we can handle the .IsNull() -> None conversion - class _PyXformOpClassification { - public: - _PyXformOpClassification(const UsdMayaXformOpClassification& opClass) - : _opClass(opClass) - { - } - - bool operator == (const _PyXformOpClassification& other) - { - return _opClass == other._opClass; - } - - TfToken const &GetName() const - { - return _opClass.GetName(); - } - - // In order to return wrapped UsdGeomXformOp::Type objects, we need to import - // the UsdGeom module - static void - ImportUsdGeomOnce() - { - static std::once_flag once; - std::call_once(once, [](){ - boost::python::import("pxr.UsdGeom"); - }); - } - - UsdGeomXformOp::Type GetOpType() const - { - ImportUsdGeomOnce(); - return _opClass.GetOpType(); - } +// We wrap this class, instead of UsdMayaXformOpClassification directly, mostly +// just so we can handle the .IsNull() -> None conversion +class _PyXformOpClassification +{ +public: + _PyXformOpClassification(const UsdMayaXformOpClassification& opClass) + : _opClass(opClass) + { + } - bool IsInvertedTwin() const - { - return _opClass.IsInvertedTwin(); - } + bool operator==(const _PyXformOpClassification& other) { return _opClass == other._opClass; } - bool IsCompatibleType(UsdGeomXformOp::Type otherType) const - { - return _opClass.IsCompatibleType(otherType); - } + TfToken const& GetName() const { return _opClass.GetName(); } - std::vector CompatibleAttrNames() const - { - return _opClass.CompatibleAttrNames(); - } + // In order to return wrapped UsdGeomXformOp::Type objects, we need to import + // the UsdGeom module + static void ImportUsdGeomOnce() + { + static std::once_flag once; + std::call_once(once, []() { boost::python::import("pxr.UsdGeom"); }); + } - // to-python conversion of const UsdMayaXformOpClassification. - static PyObject* - convert(const UsdMayaXformOpClassification& opClass) { - TfPyLock lock; - if (opClass.IsNull()) - { - return boost::python::incref(Py_None); - } - else - { - object obj((_PyXformOpClassification(opClass))); - // Incref because ~object does a decref - return boost::python::incref(obj.ptr()); - } - } + UsdGeomXformOp::Type GetOpType() const + { + ImportUsdGeomOnce(); + return _opClass.GetOpType(); + } - private: - UsdMayaXformOpClassification _opClass; - }; + bool IsInvertedTwin() const { return _opClass.IsInvertedTwin(); } - class _PyXformStack + bool IsCompatibleType(UsdGeomXformOp::Type otherType) const { - public: - static inline object - convert_index(size_t index) - { - if (index == UsdMayaXformStack::NO_INDEX) - { - return object(); // return None (handles the incref) - } - return object(index); - } + return _opClass.IsCompatibleType(otherType); + } - // Don't want to make this into a generic conversion rule, via - // to_python_converter(), - // because that would make this apply to ANY pair of unsigned ints, which - // could be dangerous - static object - convert_index_pair(const UsdMayaXformStack::IndexPair& indexPair) - { - return boost::python::make_tuple( - convert_index(indexPair.first), - convert_index(indexPair.second)); - } + std::vector CompatibleAttrNames() const { return _opClass.CompatibleAttrNames(); } - static PyObject* - convert(const UsdMayaXformStack::OpClassPair& opPair) - { - boost::python::tuple result = boost::python::make_tuple( - opPair.first, opPair.second); + // to-python conversion of const UsdMayaXformOpClassification. + static PyObject* convert(const UsdMayaXformOpClassification& opClass) + { + TfPyLock lock; + if (opClass.IsNull()) { + return boost::python::incref(Py_None); + } else { + object obj((_PyXformOpClassification(opClass))); // Incref because ~object does a decref - return boost::python::incref(result.ptr()); + return boost::python::incref(obj.ptr()); } + } - static const UsdMayaXformOpClassification& - getitem(const UsdMayaXformStack& stack, long index) - { - auto raise_index_error = [] () { - PyErr_SetString(PyExc_IndexError, "index out of range"); - boost::python::throw_error_already_set(); - }; +private: + UsdMayaXformOpClassification _opClass; +}; - if (index < 0) - { - if (static_cast(-index) > stack.GetSize()) raise_index_error(); - return stack[stack.GetSize() + index]; - } - else - { - if (static_cast(index) >= stack.GetSize()) raise_index_error(); - return stack[index]; - } +class _PyXformStack +{ +public: + static inline object convert_index(size_t index) + { + if (index == UsdMayaXformStack::NO_INDEX) { + return object(); // return None (handles the incref) } + return object(index); + } - static object - GetInversionTwins(const UsdMayaXformStack& stack) - { - boost::python::list result; - for(const auto& idxPair : stack.GetInversionTwins()) - { - result.append(convert_index_pair(idxPair)); - } - return move(result); - } + // Don't want to make this into a generic conversion rule, via + // to_python_converter(), + // because that would make this apply to ANY pair of unsigned ints, which + // could be dangerous + static object convert_index_pair(const UsdMayaXformStack::IndexPair& indexPair) + { + return boost::python::make_tuple( + convert_index(indexPair.first), convert_index(indexPair.second)); + } - static object - FindOpIndex( - const UsdMayaXformStack& stack, - const TfToken& opName, - bool isInvertedTwin=false) - { - return convert_index(stack.FindOpIndex(opName, isInvertedTwin)); - } + static PyObject* convert(const UsdMayaXformStack::OpClassPair& opPair) + { + boost::python::tuple result = boost::python::make_tuple(opPair.first, opPair.second); + // Incref because ~object does a decref + return boost::python::incref(result.ptr()); + } - static object - FindOpIndexPair( - const UsdMayaXformStack& stack, - const TfToken& opName) - { - return convert_index_pair(stack.FindOpIndexPair(opName)); + static const UsdMayaXformOpClassification& getitem(const UsdMayaXformStack& stack, long index) + { + auto raise_index_error = []() { + PyErr_SetString(PyExc_IndexError, "index out of range"); + boost::python::throw_error_already_set(); + }; + + if (index < 0) { + if (static_cast(-index) > stack.GetSize()) + raise_index_error(); + return stack[stack.GetSize() + index]; + } else { + if (static_cast(index) >= stack.GetSize()) + raise_index_error(); + return stack[index]; + } + } + + static object GetInversionTwins(const UsdMayaXformStack& stack) + { + boost::python::list result; + for (const auto& idxPair : stack.GetInversionTwins()) { + result.append(convert_index_pair(idxPair)); } - }; -} + return move(result); + } + static object + FindOpIndex(const UsdMayaXformStack& stack, const TfToken& opName, bool isInvertedTwin = false) + { + return convert_index(stack.FindOpIndex(opName, isInvertedTwin)); + } + static object FindOpIndexPair(const UsdMayaXformStack& stack, const TfToken& opName) + { + return convert_index_pair(stack.FindOpIndexPair(opName)); + } +}; +} // namespace void wrapXformStack() { class_<_PyXformOpClassification>("XformOpClassification", no_init) .def(self == self) - .def("GetName", &_PyXformOpClassification::GetName, - return_value_policy()) + .def("GetName", &_PyXformOpClassification::GetName, return_value_policy()) .def("GetOpType", &_PyXformOpClassification::GetOpType) .def("IsInvertedTwin", &_PyXformOpClassification::IsInvertedTwin) .def("IsCompatibleType", &_PyXformOpClassification::IsCompatibleType) - .def("CompatibleAttrNames", &_PyXformOpClassification::CompatibleAttrNames) - ; + .def("CompatibleAttrNames", &_PyXformOpClassification::CompatibleAttrNames); - boost::python::to_python_converter(); + boost::python::to_python_converter(); class_("XformStack", no_init) - .def("GetOps", &UsdMayaXformStack::GetOps, - return_value_policy()) + .def("GetOps", &UsdMayaXformStack::GetOps, return_value_policy()) .def("GetInversionTwins", &_PyXformStack::GetInversionTwins) .def("GetNameMatters", &UsdMayaXformStack::GetNameMatters) - .def("__getitem__", &_PyXformStack::getitem, - return_value_policy()) + .def("__getitem__", &_PyXformStack::getitem, return_value_policy()) .def("__len__", &UsdMayaXformStack::GetSize) .def("GetSize", &UsdMayaXformStack::GetSize) - .def("FindOpIndex", &_PyXformStack::FindOpIndex, - (boost::python::arg("opName"), boost::python::arg("isInvertedTwin")=false)) - .def("FindOp", &UsdMayaXformStack::FindOp, - (boost::python::arg("opName"), boost::python::arg("isInvertedTwin")=false), - return_value_policy()) + .def( + "FindOpIndex", + &_PyXformStack::FindOpIndex, + (boost::python::arg("opName"), boost::python::arg("isInvertedTwin") = false)) + .def( + "FindOp", + &UsdMayaXformStack::FindOp, + (boost::python::arg("opName"), boost::python::arg("isInvertedTwin") = false), + return_value_policy()) .def("FindOpIndexPair", &_PyXformStack::FindOpIndexPair) .def("FindOpPair", &UsdMayaXformStack::FindOpPair) .def("MatchingSubstack", &UsdMayaXformStack::MatchingSubstack) - .def("MayaStack", &UsdMayaXformStack::MayaStack, - return_value_policy()) + .def("MayaStack", &UsdMayaXformStack::MayaStack, return_value_policy()) .staticmethod("MayaStack") - .def("CommonStack", &UsdMayaXformStack::CommonStack, - return_value_policy()) + .def("CommonStack", &UsdMayaXformStack::CommonStack, return_value_policy()) .staticmethod("CommonStack") - .def("MatrixStack", &UsdMayaXformStack::MatrixStack, - return_value_policy()) + .def("MatrixStack", &UsdMayaXformStack::MatrixStack, return_value_policy()) .staticmethod("MatrixStack") .def("FirstMatchingSubstack", &UsdMayaXformStack::FirstMatchingSubstack) - .staticmethod("FirstMatchingSubstack") - ; + .staticmethod("FirstMatchingSubstack"); - boost::python::to_python_converter(); + boost::python::to_python_converter(); - boost::python::to_python_converter, - TfPySequenceToPython > >(); + boost::python::to_python_converter< + std::vector, + TfPySequenceToPython>>(); - TfPyContainerConversions::from_python_sequence, - TfPyContainerConversions::variable_capacity_policy >(); + TfPyContainerConversions::from_python_sequence< + std::vector, + TfPyContainerConversions::variable_capacity_policy>(); } diff --git a/lib/mayaUsd/render/mayaToHydra/defaultLightDelegate.cpp b/lib/mayaUsd/render/mayaToHydra/defaultLightDelegate.cpp index 3cdb9d0352..a78ec0e5fb 100644 --- a/lib/mayaUsd/render/mayaToHydra/defaultLightDelegate.cpp +++ b/lib/mayaUsd/render/mayaToHydra/defaultLightDelegate.cpp @@ -15,14 +15,14 @@ // #include "defaultLightDelegate.h" +#include + #include #include #include #include #include -#include - PXR_NAMESPACE_OPEN_SCOPE // clang-format off @@ -34,40 +34,44 @@ TF_DEFINE_PRIVATE_TOKENS( // clang-format on MtohDefaultLightDelegate::MtohDefaultLightDelegate(const InitData& initData) - : HdSceneDelegate(initData.renderIndex, initData.delegateID), - HdMayaDelegate(initData), - _lightPath(initData.delegateID.AppendChild(_tokens->DefaultMayaLight)) -{} + : HdSceneDelegate(initData.renderIndex, initData.delegateID) + , HdMayaDelegate(initData) + , _lightPath(initData.delegateID.AppendChild(_tokens->DefaultMayaLight)) +{ +} -MtohDefaultLightDelegate::~MtohDefaultLightDelegate() { - if (ARCH_UNLIKELY(!_isSupported)) { return; } +MtohDefaultLightDelegate::~MtohDefaultLightDelegate() +{ + if (ARCH_UNLIKELY(!_isSupported)) { + return; + } if (IsHdSt()) { GetRenderIndex().RemoveSprim(HdPrimTypeTokens->simpleLight, _lightPath); } else { - GetRenderIndex().RemoveSprim( - HdPrimTypeTokens->distantLight, _lightPath); + GetRenderIndex().RemoveSprim(HdPrimTypeTokens->distantLight, _lightPath); } } -void MtohDefaultLightDelegate::Populate() { - _isSupported = IsHdSt() ? GetRenderIndex().IsSprimTypeSupported( - HdPrimTypeTokens->simpleLight) - : GetRenderIndex().IsSprimTypeSupported( - HdPrimTypeTokens->distantLight); - if (ARCH_UNLIKELY(!_isSupported)) { return; } +void MtohDefaultLightDelegate::Populate() +{ + _isSupported = IsHdSt() ? GetRenderIndex().IsSprimTypeSupported(HdPrimTypeTokens->simpleLight) + : GetRenderIndex().IsSprimTypeSupported(HdPrimTypeTokens->distantLight); + if (ARCH_UNLIKELY(!_isSupported)) { + return; + } if (IsHdSt()) { - GetRenderIndex().InsertSprim( - HdPrimTypeTokens->simpleLight, this, _lightPath); + GetRenderIndex().InsertSprim(HdPrimTypeTokens->simpleLight, this, _lightPath); } else { - GetRenderIndex().InsertSprim( - HdPrimTypeTokens->distantLight, this, _lightPath); + GetRenderIndex().InsertSprim(HdPrimTypeTokens->distantLight, this, _lightPath); } - GetRenderIndex().GetChangeTracker().SprimInserted( - _lightPath, HdLight::AllDirty); + GetRenderIndex().GetChangeTracker().SprimInserted(_lightPath, HdLight::AllDirty); } -void MtohDefaultLightDelegate::SetDefaultLight(const GlfSimpleLight& light) { - if (ARCH_UNLIKELY(!_isSupported)) { return; } +void MtohDefaultLightDelegate::SetDefaultLight(const GlfSimpleLight& light) +{ + if (ARCH_UNLIKELY(!_isSupported)) { + return; + } if (_light != light) { _light = light; GetRenderIndex().GetChangeTracker().MarkSprimDirty( @@ -75,7 +79,8 @@ void MtohDefaultLightDelegate::SetDefaultLight(const GlfSimpleLight& light) { } } -GfMatrix4d MtohDefaultLightDelegate::GetTransform(const SdfPath& id) { +GfMatrix4d MtohDefaultLightDelegate::GetTransform(const SdfPath& id) +{ TF_UNUSED(id); TF_DEBUG(HDMAYA_DELEGATE_GET_TRANSFORM) @@ -85,23 +90,21 @@ GfMatrix4d MtohDefaultLightDelegate::GetTransform(const SdfPath& id) { // stored in it's position. Otherwise, the matrix needs to be an identity // matrix. if (!IsHdSt()) { - const auto position = _light.GetPosition(); + const auto position = _light.GetPosition(); GfTransform transform; - transform.SetRotation(GfRotation( - GfVec3d(0.0, 0.0, -1.0), - GfVec3d(-position[0], -position[1], -position[2]))); + transform.SetRotation( + GfRotation(GfVec3d(0.0, 0.0, -1.0), GfVec3d(-position[0], -position[1], -position[2]))); return transform.GetMatrix(); } return GfMatrix4d(1.0); } -VtValue MtohDefaultLightDelegate::Get(const SdfPath& id, const TfToken& key) { +VtValue MtohDefaultLightDelegate::Get(const SdfPath& id, const TfToken& key) +{ TF_UNUSED(id); TF_DEBUG(HDMAYA_DELEGATE_GET) - .Msg( - "MtohDefaultLightDelegate::Get(%s, %s)\n", id.GetText(), - key.GetText()); + .Msg("MtohDefaultLightDelegate::Get(%s, %s)\n", id.GetText(), key.GetText()); if (key == HdLightTokens->params) { return VtValue(_light); @@ -110,8 +113,7 @@ VtValue MtohDefaultLightDelegate::Get(const SdfPath& id, const TfToken& key) { return VtValue(GfMatrix4d(1.0)); // Hydra might crash when this is an empty VtValue. } else if (key == HdLightTokens->shadowCollection) { - HdRprimCollection coll( - HdTokens->geometry, HdReprSelector(HdReprTokens->refined)); + HdRprimCollection coll(HdTokens->geometry, HdReprSelector(HdReprTokens->refined)); return VtValue(coll); } else if (key == HdLightTokens->shadowParams) { HdxShadowParams shadowParams; @@ -121,17 +123,17 @@ VtValue MtohDefaultLightDelegate::Get(const SdfPath& id, const TfToken& key) { return {}; } -VtValue MtohDefaultLightDelegate::GetLightParamValue( - const SdfPath& id, const TfToken& paramName) { +VtValue MtohDefaultLightDelegate::GetLightParamValue(const SdfPath& id, const TfToken& paramName) +{ TF_UNUSED(id); TF_DEBUG(HDMAYA_DELEGATE_GET_LIGHT_PARAM_VALUE) .Msg( "MtohDefaultLightDelegate::GetLightParamValue(%s, %s)\n", - id.GetText(), paramName.GetText()); + id.GetText(), + paramName.GetText()); - if (paramName == HdLightTokens->color || - paramName == HdTokens->displayColor) { + if (paramName == HdLightTokens->color || paramName == HdTokens->displayColor) { const auto diffuse = _light.GetDiffuse(); return VtValue(GfVec3f(diffuse[0], diffuse[1], diffuse[2])); } else if (paramName == HdLightTokens->intensity) { @@ -156,7 +158,8 @@ VtValue MtohDefaultLightDelegate::GetLightParamValue( return {}; } -bool MtohDefaultLightDelegate::GetVisible(const SdfPath& id) { +bool MtohDefaultLightDelegate::GetVisible(const SdfPath& id) +{ TF_UNUSED(id); TF_DEBUG(HDMAYA_DELEGATE_GET_VISIBLE) .Msg("MtohDefaultLightDelegate::GetVisible(%s)\n", id.GetText()); diff --git a/lib/mayaUsd/render/mayaToHydra/defaultLightDelegate.h b/lib/mayaUsd/render/mayaToHydra/defaultLightDelegate.h index 6a5c389e52..c9cb4fb3de 100644 --- a/lib/mayaUsd/render/mayaToHydra/defaultLightDelegate.h +++ b/lib/mayaUsd/render/mayaToHydra/defaultLightDelegate.h @@ -16,18 +16,21 @@ #ifndef MTOH_DEFAULT_LIGHT_DELEGATE_H #define MTOH_DEFAULT_LIGHT_DELEGATE_H -#include +#include + #include #include +#include #include #include #include -#include - PXR_NAMESPACE_OPEN_SCOPE -class MtohDefaultLightDelegate : public HdSceneDelegate, public HdMayaDelegate { +class MtohDefaultLightDelegate + : public HdSceneDelegate + , public HdMayaDelegate +{ public: MtohDefaultLightDelegate(const InitData& initData); @@ -38,15 +41,14 @@ class MtohDefaultLightDelegate : public HdSceneDelegate, public HdMayaDelegate { protected: GfMatrix4d GetTransform(const SdfPath& id) override; - VtValue Get(const SdfPath& id, const TfToken& key) override; - VtValue GetLightParamValue( - const SdfPath& id, const TfToken& paramName) override; - bool GetVisible(const SdfPath& id) override; + VtValue Get(const SdfPath& id, const TfToken& key) override; + VtValue GetLightParamValue(const SdfPath& id, const TfToken& paramName) override; + bool GetVisible(const SdfPath& id) override; private: GlfSimpleLight _light; - SdfPath _lightPath; - bool _isSupported = false; + SdfPath _lightPath; + bool _isSupported = false; }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/mayaToHydra/plugin.cpp b/lib/mayaUsd/render/mayaToHydra/plugin.cpp index 767d4d2b48..618c4a3061 100644 --- a/lib/mayaUsd/render/mayaToHydra/plugin.cpp +++ b/lib/mayaUsd/render/mayaToHydra/plugin.cpp @@ -13,47 +13,49 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include +#include "renderGlobals.h" +#include "renderOverride.h" +#include "viewCommand.h" -#include -#include +#include +#include #include #include #include -#include - -#include +#include +#include -#include "renderGlobals.h" -#include "renderOverride.h" -#include "viewCommand.h" +#include +#include #if defined(MAYAUSD_VERSION) #define STRINGIFY(x) #x -#define TOSTRING(x) STRINGIFY(x) +#define TOSTRING(x) STRINGIFY(x) #else #error "MAYAUSD_VERSION is not defined" #endif PXR_NAMESPACE_USING_DIRECTIVE -PLUGIN_EXPORT MStatus initializePlugin(MObject obj) { +PLUGIN_EXPORT MStatus initializePlugin(MObject obj) +{ MStatus ret = MS::kSuccess; // Call one time registration of plugins compiled for same USD version as MayaUSD plugin. MayaUsd::registerVersionedPlugins(); - + ret = HdMayaAdapter::Initialize(); - if (!ret) { return ret; } + if (!ret) { + return ret; + } // For now this is required for the HdSt backed to use lights. // putenv requires char* and I'm not willing to use const cast! constexpr const char* envVarSet = "USDIMAGING_ENABLE_SCENE_LIGHTS=1"; - const auto envVarSize = strlen(envVarSet) + 1; - std::vector envVarData; + const auto envVarSize = strlen(envVarSet) + 1; + std::vector envVarData; envVarData.resize(envVarSize); snprintf(envVarData.data(), envVarSize, "%s", envVarSet); putenv(envVarData.data()); @@ -61,8 +63,7 @@ PLUGIN_EXPORT MStatus initializePlugin(MObject obj) { MFnPlugin plugin(obj, "Autodesk", TOSTRING(MAYAUSD_VERSION), "Any"); if (!plugin.registerCommand( - MtohViewCmd::name, MtohViewCmd::creator, - MtohViewCmd::createSyntax)) { + MtohViewCmd::name, MtohViewCmd::creator, MtohViewCmd::createSyntax)) { ret = MS::kFailure; ret.perror("Error registering mtoh command!"); return ret; @@ -80,15 +81,15 @@ PLUGIN_EXPORT MStatus initializePlugin(MObject obj) { return ret; } -PLUGIN_EXPORT MStatus uninitializePlugin(MObject obj) { +PLUGIN_EXPORT MStatus uninitializePlugin(MObject obj) +{ MFnPlugin plugin(obj, "Autodesk", TOSTRING(MAYAUSD_VERSION), "Any"); - MStatus ret = MS::kSuccess; + MStatus ret = MS::kSuccess; auto* renderer = MHWRender::MRenderer::theRenderer(); if (renderer) { for (const auto& desc : MtohGetRendererDescriptions()) { - const auto* override = - renderer->findRenderOverride(desc.overrideName.GetText()); + const auto* override = renderer->findRenderOverride(desc.overrideName.GetText()); if (override) { renderer->deregisterOverride(override); delete override; diff --git a/lib/mayaUsd/render/mayaToHydra/pluginDebugCodes.cpp b/lib/mayaUsd/render/mayaToHydra/pluginDebugCodes.cpp index be56e0d132..59f66640ec 100644 --- a/lib/mayaUsd/render/mayaToHydra/pluginDebugCodes.cpp +++ b/lib/mayaUsd/render/mayaToHydra/pluginDebugCodes.cpp @@ -19,7 +19,8 @@ PXR_NAMESPACE_OPEN_SCOPE -TF_REGISTRY_FUNCTION(TfDebug) { +TF_REGISTRY_FUNCTION(TfDebug) +{ TF_DEBUG_ENVIRONMENT_SYMBOL( HDMAYA_RENDEROVERRIDE_DEFAULT_LIGHTING, "Print information detection of default lighting for the Maya VP2 " diff --git a/lib/mayaUsd/render/mayaToHydra/pluginDebugCodes.h b/lib/mayaUsd/render/mayaToHydra/pluginDebugCodes.h index 39ea56e005..b9ed9755c0 100644 --- a/lib/mayaUsd/render/mayaToHydra/pluginDebugCodes.h +++ b/lib/mayaUsd/render/mayaToHydra/pluginDebugCodes.h @@ -16,8 +16,8 @@ #ifndef HDMAYA_PLUGIN_DEBUG_CODES_H #define HDMAYA_PLUGIN_DEBUG_CODES_H -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE diff --git a/lib/mayaUsd/render/mayaToHydra/renderGlobals.cpp b/lib/mayaUsd/render/mayaToHydra/renderGlobals.cpp index 474229caa0..3324ab949d 100644 --- a/lib/mayaUsd/render/mayaToHydra/renderGlobals.cpp +++ b/lib/mayaUsd/render/mayaToHydra/renderGlobals.cpp @@ -14,26 +14,26 @@ // limitations under the License. // #include "renderGlobals.h" + #include "renderOverride.h" +#include "utils.h" -#include -#include +#include +#include +#include #include #include #include #include #include +#include #include #include #include -#include - -#include -#include -#include -#include "utils.h" +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -78,17 +78,17 @@ global proc mtohRenderOverride_AddMTOHAttributes(int $fromAE) { mtohRenderOverride_AddAttribute("mtoh", "Highlight Color for Selected Objects", "mtohColorSelectionHighlightColor", $fromAE); )mel" #if USD_VERSION_NUM >= 2005 -R"mel( + R"mel( mtohRenderOverride_AddAttribute("mtoh", "Highlight outline (in pixels, 0 to disable)", "mtohSelectionOutline", $fromAE); )mel" #endif #if USD_VERSION_NUM > 1911 && USD_VERSION_NUM <= 2005 -R"mel( + R"mel( mtohRenderOverride_AddAttribute("mtoh", "Enable color quantization", "mtohColorQuantization", $fromAE); )mel" #endif -R"mel( + R"mel( } global proc mtohRenderOverride_AEAttributesCallback(string $nodeName) { @@ -144,12 +144,12 @@ global proc {{override}}OptionBox() { } )mel"; - static constexpr const char* kMtohNSToken = "_mtohns_"; -static const std::string kMtohRendererPostFix("__"); +static const std::string kMtohRendererPostFix("__"); -static MString _MangleColorAttribute(const MString& attrName, unsigned i) { - static const MString kMtohCmptToken("_mtohc_"); +static MString _MangleColorAttribute(const MString& attrName, unsigned i) +{ + static const MString kMtohCmptToken("_mtohc_"); static const std::array kColorComponents = { "R", "G", "B", "A" }; if (i < kColorComponents.size()) { return attrName + kMtohCmptToken + kColorComponents[i]; @@ -159,14 +159,18 @@ static MString _MangleColorAttribute(const MString& attrName, unsigned i) { return attrName + kMtohCmptToken + MString("INVALID"); } -static MString _AlphaAttribute(const MString& attrName) { +static MString _AlphaAttribute(const MString& attrName) +{ return _MangleColorAttribute(attrName, 3); } template -bool _RestoreValue(MFnDependencyNode& node, const MString& attrName, - PrefType (*getter)(const MString&, bool* valid)) { - bool valid = false; +bool _RestoreValue( + MFnDependencyNode& node, + const MString& attrName, + PrefType (*getter)(const MString&, bool* valid)) +{ + bool valid = false; PrefType mayaPref = getter(attrName, &valid); if (valid) { auto plug = node.findPlug(attrName); @@ -176,19 +180,26 @@ bool _RestoreValue(MFnDependencyNode& node, const MString& attrName, } void _CreateEnumAttribute( - MFnDependencyNode& node, const MString& attrName, - const TfTokenVector& values, const TfToken& defValue, - bool useUserOptions) { + MFnDependencyNode& node, + const MString& attrName, + const TfTokenVector& values, + const TfToken& defValue, + bool useUserOptions) +{ const auto attr = node.attribute(attrName); const bool existed = !attr.isNull(); if (existed) { const auto sameOrder = [&attr, &values]() -> bool { - MStatus status; + MStatus status; MFnEnumAttribute eAttr(attr, &status); - if (!status) { return false; } + if (!status) { + return false; + } short id = 0; for (const auto& v : values) { - if (eAttr.fieldName(id++) != v.GetText()) { return false; } + if (eAttr.fieldName(id++) != v.GetText()) { + return false; + } } return true; }; @@ -200,8 +211,8 @@ void _CreateEnumAttribute( } MFnEnumAttribute eAttr; - auto o = eAttr.create(attrName, attrName); - short id = 0; + auto o = eAttr.create(attrName, attrName); + short id = 0; for (const auto& v : values) { eAttr.addField(v.GetText(), id++); } @@ -215,7 +226,7 @@ void _CreateEnumAttribute( // Enums stored as string to allow re-ordering // Why MPlug::setValue doesn't handle this ? // - bool valid = false; + bool valid = false; TfToken mayaPref(MGlobal::optionVarStringValue(attrName, &valid).asChar()); if (!valid) { return; @@ -231,31 +242,41 @@ void _CreateEnumAttribute( TF_WARN("[mtoh] Cannot restore enum '%s'", mayaPref.GetText()); } -void _CreateEnumAttribute(MFnDependencyNode& node, const MString& attrName, - const TfEnum& defValue, bool useUserOptions) { +void _CreateEnumAttribute( + MFnDependencyNode& node, + const MString& attrName, + const TfEnum& defValue, + bool useUserOptions) +{ std::vector names = TfEnum::GetAllNames(defValue); - TfTokenVector tokens(names.begin(), names.end()); - return _CreateEnumAttribute(node, attrName, tokens, - TfToken(TfEnum::GetDisplayName(defValue)), useUserOptions); + TfTokenVector tokens(names.begin(), names.end()); + return _CreateEnumAttribute( + node, attrName, tokens, TfToken(TfEnum::GetDisplayName(defValue)), useUserOptions); } -void _CreateStringAttribute(MFnDependencyNode& node, const MString& attrName, - const std::string& defValue, bool useUserOptions) { +void _CreateStringAttribute( + MFnDependencyNode& node, + const MString& attrName, + const std::string& defValue, + bool useUserOptions) +{ const auto attr = node.attribute(attrName); const bool existed = !attr.isNull(); if (existed) { - MStatus status; + MStatus status; MFnTypedAttribute tAttr(attr, &status); - if (status && tAttr.attrType() == MFnData::kString) { return; } + if (status && tAttr.attrType() == MFnData::kString) { + return; + } node.removeAttribute(attr); } MFnTypedAttribute tAttr; - const auto obj = tAttr.create(attrName, attrName, MFnData::kString); + const auto obj = tAttr.create(attrName, attrName, MFnData::kString); if (!defValue.empty()) { MFnStringData strData; - MObject defObj = strData.create(defValue.c_str()); + MObject defObj = strData.create(defValue.c_str()); tAttr.setDefault(defObj); } node.addAttribute(obj); @@ -267,22 +288,28 @@ void _CreateStringAttribute(MFnDependencyNode& node, const MString& attrName, template void _CreateNumericAttribute( - MFnDependencyNode& node, const MString& attrName, MFnNumericData::Type type, - typename std::enable_if::value, T>::type defValue, bool useUserOptions, + MFnDependencyNode& node, + const MString& attrName, + MFnNumericData::Type type, + typename std::enable_if::value, T>::type defValue, + bool useUserOptions, MayaType (*getter)(const MString&, bool* valid), - std::function postCreate = {}) { + std::function postCreate = {}) +{ const auto attr = node.attribute(attrName); const bool existed = !attr.isNull(); if (existed) { - MStatus status; + MStatus status; MFnNumericAttribute nAttr(attr, &status); - if (status && nAttr.unitType() == type) { return; } + if (status && nAttr.unitType() == type) { + return; + } node.removeAttribute(attr); } MFnNumericAttribute nAttr; - const auto obj = nAttr.create(attrName, attrName, type); + const auto obj = nAttr.create(attrName, attrName, type); nAttr.setDefault(defValue); if (postCreate) { postCreate(nAttr); @@ -296,11 +323,15 @@ void _CreateNumericAttribute( template void _CreateColorAttribute( - MFnDependencyNode& node, const MString& attrName, T defValue, bool useUserOptions, - std::function alphaOp = {}) { + MFnDependencyNode& node, + const MString& attrName, + T defValue, + bool useUserOptions, + std::function alphaOp = {}) +{ const auto attr = node.attribute(attrName); if (!attr.isNull()) { - MStatus status; + MStatus status; MFnNumericAttribute nAttr(attr, &status); if (status && nAttr.isUsedAsColor() && (!alphaOp || alphaOp(nAttr, false))) { return; @@ -308,7 +339,7 @@ void _CreateColorAttribute( node.removeAttribute(attr); } MFnNumericAttribute nAttr; - const auto o = nAttr.createColor(attrName, attrName); + const auto o = nAttr.createColor(attrName, attrName); nAttr.setDefault(defValue[0], defValue[1], defValue[2]); node.addAttribute(o); @@ -318,25 +349,32 @@ void _CreateColorAttribute( if (useUserOptions) { for (unsigned i = 0; i < T::dimension; ++i) { - _RestoreValue(node, _MangleColorAttribute(attrName, i), - MGlobal::optionVarDoubleValue); + _RestoreValue( + node, _MangleColorAttribute(attrName, i), MGlobal::optionVarDoubleValue); } } } void _CreateColorAttribute( - MFnDependencyNode& node, const MString& attrName, GfVec4f defVec4, bool useUserOptions) { - _CreateColorAttribute(node, attrName, GfVec3f(defVec4.data()), useUserOptions, - [&](MFnNumericAttribute& nAttr, bool doCreate) -> bool - { + MFnDependencyNode& node, + const MString& attrName, + GfVec4f defVec4, + bool useUserOptions) +{ + _CreateColorAttribute( + node, + attrName, + GfVec3f(defVec4.data()), + useUserOptions, + [&](MFnNumericAttribute& nAttr, bool doCreate) -> bool { const MString attrAName = _AlphaAttribute(attrName); - const auto attrA = node.attribute(attrAName); + const auto attrA = node.attribute(attrAName); // If we previously found the color attribute, make sure the Alpha attribute // is also a match (MFnNumericData::kFloat), otherwise delete it and signal to re-create // the color too. if (!doCreate) { if (!attrA.isNull()) { - MStatus status; + MStatus status; MFnNumericAttribute nAttr(attrA, &status); if (status && nAttr.unitType() == MFnNumericData::kFloat) { return true; @@ -350,100 +388,124 @@ void _CreateColorAttribute( nAttr.setDefault(defVec4[3]); node.addAttribute(o); return true; - } - ); + }); } -void _CreateBoolAttribute(MFnDependencyNode& node, const MString& attrName, - bool defValue, bool useUserOptions) { - _CreateNumericAttribute(node, attrName, MFnNumericData::kBoolean, - defValue, useUserOptions, MGlobal::optionVarIntValue); +void _CreateBoolAttribute( + MFnDependencyNode& node, + const MString& attrName, + bool defValue, + bool useUserOptions) +{ + _CreateNumericAttribute( + node, + attrName, + MFnNumericData::kBoolean, + defValue, + useUserOptions, + MGlobal::optionVarIntValue); } -void _CreateIntAttribute(MFnDependencyNode& node, const MString& attrName, - int defValue, bool useUserOptions, - std::function postCreate = {}) { - _CreateNumericAttribute(node, attrName, MFnNumericData::kInt, - defValue, useUserOptions, MGlobal::optionVarIntValue, std::move(postCreate)); +void _CreateIntAttribute( + MFnDependencyNode& node, + const MString& attrName, + int defValue, + bool useUserOptions, + std::function postCreate = {}) +{ + _CreateNumericAttribute( + node, + attrName, + MFnNumericData::kInt, + defValue, + useUserOptions, + MGlobal::optionVarIntValue, + std::move(postCreate)); } -void _CreateFloatAttribute(MFnDependencyNode& node, const MString& attrName, - float defValue, bool useUserOptions) { - _CreateNumericAttribute(node, attrName, MFnNumericData::kFloat, - defValue, useUserOptions, MGlobal::optionVarDoubleValue); +void _CreateFloatAttribute( + MFnDependencyNode& node, + const MString& attrName, + float defValue, + bool useUserOptions) +{ + _CreateNumericAttribute( + node, + attrName, + MFnNumericData::kFloat, + defValue, + useUserOptions, + MGlobal::optionVarDoubleValue); } -template -void _GetFromPlug(const MPlug& plug, T& out) { - assert(false); -} +template void _GetFromPlug(const MPlug& plug, T& out) { assert(false); } -template <> -void _GetFromPlug(const MPlug& plug, bool& out) { - out = plug.asBool(); -} +template <> void _GetFromPlug(const MPlug& plug, bool& out) { out = plug.asBool(); } -template <> -void _GetFromPlug(const MPlug& plug, int& out) { - out = plug.asInt(); -} +template <> void _GetFromPlug(const MPlug& plug, int& out) { out = plug.asInt(); } -template <> -void _GetFromPlug(const MPlug& plug, float& out) { - out = plug.asFloat(); -} +template <> void _GetFromPlug(const MPlug& plug, float& out) { out = plug.asFloat(); } -template <> -void _GetFromPlug(const MPlug& plug, std::string& out) { +template <> void _GetFromPlug(const MPlug& plug, std::string& out) +{ out = plug.asString().asChar(); } -template <> -void _GetFromPlug(const MPlug& plug, TfEnum& out) { +template <> void _GetFromPlug(const MPlug& plug, TfEnum& out) +{ out = TfEnum(out.GetType(), plug.asInt()); } -template -bool _SetOptionVar(const MString& attrName, const T& value) { +template bool _SetOptionVar(const MString& attrName, const T& value) +{ return MGlobal::setOptionVarValue(attrName, value); } -bool _SetOptionVar(const MString& attrName, const bool& value) { +bool _SetOptionVar(const MString& attrName, const bool& value) +{ return _SetOptionVar(attrName, int(value)); } -bool _SetOptionVar(const MString& attrName, const float& value) { +bool _SetOptionVar(const MString& attrName, const float& value) +{ return _SetOptionVar(attrName, double(value)); } -bool _SetOptionVar(const MString& attrName, const TfToken& value) { +bool _SetOptionVar(const MString& attrName, const TfToken& value) +{ return _SetOptionVar(attrName, MString(value.GetText())); } -bool _SetOptionVar(const MString& attrName, const std::string& value) { +bool _SetOptionVar(const MString& attrName, const std::string& value) +{ return _SetOptionVar(attrName, MString(value.c_str())); } -bool _SetOptionVar(const MString& attrName, const TfEnum& value) { +bool _SetOptionVar(const MString& attrName, const TfEnum& value) +{ return _SetOptionVar(attrName, TfEnum::GetDisplayName(value)); } -template -bool _SetColorOptionVar(const MString& attrName, const T& values) { +template bool _SetColorOptionVar(const MString& attrName, const T& values) +{ bool rval = true; for (size_t i = 0; i < T::dimension; ++i) { - rval = _SetOptionVar(_MangleColorAttribute(attrName, i), - values[i]) && rval; + rval = _SetOptionVar(_MangleColorAttribute(attrName, i), values[i]) && rval; } return rval; } template bool _GetAttribute( - const MFnDependencyNode& node, const MString& attrName, T& out, - bool storeUserSetting) { + const MFnDependencyNode& node, + const MString& attrName, + T& out, + bool storeUserSetting) +{ const auto plug = node.findPlug(attrName, true); - if (plug.isNull()) { return false; } + if (plug.isNull()) { + return false; + } _GetFromPlug(plug, out); if (storeUserSetting) { _SetOptionVar(attrName, out); @@ -452,8 +514,12 @@ bool _GetAttribute( } void _GetColorAttribute( - const MFnDependencyNode& node, const MString& attrName, GfVec3f& out, - bool storeUserSetting, std::function alphaOp = {}) { + const MFnDependencyNode& node, + const MString& attrName, + GfVec3f& out, + bool storeUserSetting, + std::function alphaOp = {}) +{ const auto plug = node.findPlug(attrName, true); if (plug.isNull()) { return; @@ -471,78 +537,89 @@ void _GetColorAttribute( } void _GetColorAttribute( - const MFnDependencyNode& node, const MString& attrName, GfVec4f& out, - bool storeUserSetting) { + const MFnDependencyNode& node, + const MString& attrName, + GfVec4f& out, + bool storeUserSetting) +{ GfVec3f color3; - _GetColorAttribute(node, attrName, color3, storeUserSetting, - [&](GfVec3f& color3, bool storeUserSetting) { - const auto plugA = node.findPlug(_AlphaAttribute(attrName), true); - if (plugA.isNull()) { - TF_WARN("[mtoh] No Alpha plug for GfVec4f"); - return; - } - out[0] = color3[0]; - out[1] = color3[1]; - out[2] = color3[2]; - out[3] = plugA.asFloat(); - if (storeUserSetting) { - _SetColorOptionVar(attrName, out); - } - }); + _GetColorAttribute( + node, attrName, color3, storeUserSetting, [&](GfVec3f& color3, bool storeUserSetting) { + const auto plugA = node.findPlug(_AlphaAttribute(attrName), true); + if (plugA.isNull()) { + TF_WARN("[mtoh] No Alpha plug for GfVec4f"); + return; + } + out[0] = color3[0]; + out[1] = color3[1]; + out[2] = color3[2]; + out[3] = plugA.asFloat(); + if (storeUserSetting) { + _SetColorOptionVar(attrName, out); + } + }); } -bool _IsSupportedAttribute(const VtValue& v) { - return v.IsHolding() || v.IsHolding() || v.IsHolding() || - v.IsHolding() || v.IsHolding() || - v.IsHolding() || v.IsHolding() || - v.IsHolding(); +bool _IsSupportedAttribute(const VtValue& v) +{ + return v.IsHolding() || v.IsHolding() || v.IsHolding() + || v.IsHolding() || v.IsHolding() || v.IsHolding() + || v.IsHolding() || v.IsHolding(); } -TfToken -_MangleString(const std::string& settingKey, const std::string& token, - const std::string& replacement, std::string str = {}) { +TfToken _MangleString( + const std::string& settingKey, + const std::string& token, + const std::string& replacement, + std::string str = {}) +{ std::size_t pos = 0; - auto delim = settingKey.find(token); + auto delim = settingKey.find(token); while (delim != std::string::npos) { - str += settingKey.substr(pos, delim-pos).c_str(); + str += settingKey.substr(pos, delim - pos).c_str(); str += replacement; pos = delim + token.size(); delim = settingKey.find(token, pos); } - str += settingKey.substr(pos, settingKey.size()-pos).c_str(); + str += settingKey.substr(pos, settingKey.size() - pos).c_str(); return TfToken(str, TfToken::Immortal); } -std::string -_MangleRenderer(const TfToken& rendererName) { +std::string _MangleRenderer(const TfToken& rendererName) +{ return rendererName.IsEmpty() ? "" : (rendererName.GetString() + kMtohRendererPostFix); } -TfToken -_MangleString(const TfToken& settingKey, const TfToken& rendererName) { +TfToken _MangleString(const TfToken& settingKey, const TfToken& rendererName) +{ return _MangleString(settingKey.GetString(), ":", kMtohNSToken, _MangleRenderer(rendererName)); } -TfToken -_DeMangleString(const TfToken& settingKey, const TfToken& rendererName) { +TfToken _DeMangleString(const TfToken& settingKey, const TfToken& rendererName) +{ assert(!rendererName.IsEmpty() && "No condition for this"); - return _MangleString(settingKey.GetString().substr(rendererName.size()+kMtohRendererPostFix.size()), - kMtohNSToken, ":"); + return _MangleString( + settingKey.GetString().substr(rendererName.size() + kMtohRendererPostFix.size()), + kMtohNSToken, + ":"); } -TfToken _MangleName(const TfToken& settingKey, const TfToken& rendererName = {}) { - assert(rendererName.GetString().find(':') == std::string::npos && "Unexpected : token in plug-in name"); +TfToken _MangleName(const TfToken& settingKey, const TfToken& rendererName = {}) +{ + assert( + rendererName.GetString().find(':') == std::string::npos + && "Unexpected : token in plug-in name"); return _MangleString(settingKey, rendererName); } - } // namespace -MtohRenderGlobals::MtohRenderGlobals() {} +MtohRenderGlobals::MtohRenderGlobals() { } // Does the attribute in 'attrName' apply to the renderer // XXX: Not the greatest check in the world, but currently no overlap in renderer-names -bool MtohRenderGlobals::AffectsRenderer(const TfToken& mangledAttr, const TfToken& rendererName) { +bool MtohRenderGlobals::AffectsRenderer(const TfToken& mangledAttr, const TfToken& rendererName) +{ // If no explicit renderer, the setting affects them all if (rendererName.IsEmpty()) { return true; @@ -550,8 +627,11 @@ bool MtohRenderGlobals::AffectsRenderer(const TfToken& mangledAttr, const TfToke return mangledAttr.GetString().find(_MangleRenderer(rendererName)) == 0; } -bool MtohRenderGlobals::ApplySettings(HdRenderDelegate* delegate, - const TfToken& rendererName, const TfTokenVector& attrNames) const { +bool MtohRenderGlobals::ApplySettings( + HdRenderDelegate* delegate, + const TfToken& rendererName, + const TfTokenVector& attrNames) const +{ const auto* settings = TfMapLookupPtr(_rendererSettings, rendererName); if (!settings) { return false; @@ -561,15 +641,14 @@ bool MtohRenderGlobals::ApplySettings(HdRenderDelegate* delegate, if (!attrNames.empty()) { for (auto& mangledAttr : attrNames) { if (const auto* setting = TfMapLookupPtr(*settings, mangledAttr)) { - delegate->SetRenderSetting(_DeMangleString(mangledAttr, rendererName), - *setting); + delegate->SetRenderSetting(_DeMangleString(mangledAttr, rendererName), *setting); appliedAny = true; } } } else { for (auto&& setting : *settings) { - delegate->SetRenderSetting(_DeMangleString(setting.first, rendererName), - setting.second); + delegate->SetRenderSetting( + _DeMangleString(setting.first, rendererName), setting.second); } appliedAny = true; } @@ -577,7 +656,8 @@ bool MtohRenderGlobals::ApplySettings(HdRenderDelegate* delegate, return appliedAny; } -void MtohRenderGlobals::OptionsPreamble() { +void MtohRenderGlobals::OptionsPreamble() +{ MStatus status = MGlobal::executeCommand(_renderOverride_PreAmble); if (status) { return; @@ -585,27 +665,29 @@ void MtohRenderGlobals::OptionsPreamble() { TF_WARN("[mtoh] Error executing preamble:\n%s", _renderOverride_PreAmble); } -void MtohRenderGlobals::BuildOptionsMenu(const MtohRendererDescription& rendererDesc, +void MtohRenderGlobals::BuildOptionsMenu( + const MtohRendererDescription& rendererDesc, const HdRenderSettingDescriptorList& rendererSettingDescriptors) { // FIXME: Horribly in-effecient, 3 parse/replace calls // auto optionBoxCommand = TfStringReplace( - _renderOverrideOptionBoxTemplate, "{{override}}", - rendererDesc.overrideName.GetText()); - optionBoxCommand = TfStringReplace(optionBoxCommand, "{{hydraplugin}}", - rendererDesc.rendererName); - optionBoxCommand = TfStringReplace(optionBoxCommand, "{{hydraDisplayName}}", - rendererDesc.displayName); + _renderOverrideOptionBoxTemplate, "{{override}}", rendererDesc.overrideName.GetText()); + optionBoxCommand + = TfStringReplace(optionBoxCommand, "{{hydraplugin}}", rendererDesc.rendererName); + optionBoxCommand + = TfStringReplace(optionBoxCommand, "{{hydraDisplayName}}", rendererDesc.displayName); auto status = MGlobal::executeCommand(optionBoxCommand.c_str()); if (!status) { - TF_WARN("[mtoh] Error in render override option box command function: \n%s", + TF_WARN( + "[mtoh] Error in render override option box command function: \n%s", status.errorString().asChar()); } auto quote = [&](std::string str, const char* strb = nullptr) -> std::string { - if (strb) str += strb; + if (strb) + str += strb; return "\"" + str + "\""; }; @@ -616,17 +698,15 @@ void MtohRenderGlobals::BuildOptionsMenu(const MtohRendererDescription& renderer continue; } - ss << "\tmtohRenderOverride_AddAttribute(" - << quote(rendererDesc.rendererName.GetString()) - << ',' << quote(desc.name) - << ',' << quote(_MangleName(desc.key, rendererDesc.rendererName).GetString()) + ss << "\tmtohRenderOverride_AddAttribute(" << quote(rendererDesc.rendererName.GetString()) + << ',' << quote(desc.name) << ',' + << quote(_MangleName(desc.key, rendererDesc.rendererName).GetString()) << ", $fromAE);\n"; } if (rendererDesc.rendererName == MtohTokens->HdStormRendererPlugin) { - ss << "\tmtohRenderOverride_AddAttribute(" - << quote(rendererDesc.rendererName.GetString()) - << ',' << quote("Maximum shadow map size") - << ',' << quote(_MangleName(MtohTokens->mtohMaximumShadowMapResolution).GetString()) + ss << "\tmtohRenderOverride_AddAttribute(" << quote(rendererDesc.rendererName.GetString()) + << ',' << quote("Maximum shadow map size") << ',' + << quote(_MangleName(MtohTokens->mtohMaximumShadowMapResolution).GetString()) << ", $fromAE);\n"; } ss << "}\n"; @@ -634,23 +714,29 @@ void MtohRenderGlobals::BuildOptionsMenu(const MtohRendererDescription& renderer const auto optionsCommand = ss.str(); status = MGlobal::executeCommand(optionsCommand.c_str()); if (!status) { - TF_WARN("[mtoh] Error in render delegate options function: \n%s", + TF_WARN( + "[mtoh] Error in render delegate options function: \n%s", status.errorString().asChar()); } } -class MtohRenderGlobals::MtohSettingFilter { - TfToken _attrName; - MString _mayaString; - const TfToken _inFilter; - bool _isAttributeFilt; +class MtohRenderGlobals::MtohSettingFilter +{ + TfToken _attrName; + MString _mayaString; + const TfToken _inFilter; + bool _isAttributeFilt; + public: MtohSettingFilter(const GlobalParams& params) : _inFilter(params.filter) - , _isAttributeFilt(!(params.filterIsRenderer || _inFilter.IsEmpty())) {} + , _isAttributeFilt(!(params.filterIsRenderer || _inFilter.IsEmpty())) + { + } // Create the mangled key, and convert it to a Maya string if needed - bool operator() (const TfToken& attr, const TfToken& renderer = {}) { + bool operator()(const TfToken& attr, const TfToken& renderer = {}) + { _attrName = _MangleName(attr, renderer); if (attributeFilter()) { if (_inFilter != _attrName) { @@ -664,35 +750,29 @@ class MtohRenderGlobals::MtohSettingFilter { } _mayaString = MString(_attrName.GetText()); return true; - - } - bool attributeFilter() const { - return _isAttributeFilt; - } - bool renderFilter() const { - return !_isAttributeFilt && !_inFilter.IsEmpty(); } - bool affectsRenderer(const TfToken& renderer) { + bool attributeFilter() const { return _isAttributeFilt; } + bool renderFilter() const { return !_isAttributeFilt && !_inFilter.IsEmpty(); } + bool affectsRenderer(const TfToken& renderer) + { // If there's no filter, then the filter DOES affect this renderer if (_inFilter.IsEmpty()) { return true; } - // If it's an attribute-filter, test with mangling, otherwise the renderer-names should match + // If it's an attribute-filter, test with mangling, otherwise the renderer-names should + // match return _isAttributeFilt ? AffectsRenderer(_inFilter, renderer) : renderer == _inFilter; } - const TfToken& attrName() const { - return _attrName; - } - const MString& mayaString() const { - return _mayaString; - } + const TfToken& attrName() const { return _attrName; } + const MString& mayaString() const { return _mayaString; } }; // TODO : MtohRenderGlobals::CreateNode && MtohRenderGlobals::GetInstance // are extrmely redundant in logic, with most divergance occurring // at the leaf operation (_CreatXXXAttr vs. _GetAttribute) // -MObject MtohRenderGlobals::CreateAttributes(const GlobalParams& params) { +MObject MtohRenderGlobals::CreateAttributes(const GlobalParams& params) +{ MSelectionList slist; slist.add(_tokens->defaultRenderGlobals.GetText()); @@ -701,7 +781,7 @@ MObject MtohRenderGlobals::CreateAttributes(const GlobalParams& params) { return mayaObject; } - MStatus status; + MStatus status; MFnDependencyNode node(mayaObject, &status); if (!status) { return MObject(); @@ -712,17 +792,19 @@ MObject MtohRenderGlobals::CreateAttributes(const GlobalParams& params) { static const MtohRenderGlobals defGlobals; MtohSettingFilter filter(params); - const bool userDefaults = params.fallbackToUserDefaults; + const bool userDefaults = params.fallbackToUserDefaults; if (filter(_tokens->mtohEnableMotionSamples)) { - _CreateBoolAttribute(node, filter.mayaString(), - defGlobals.delegateParams.enableMotionSamples, userDefaults); + _CreateBoolAttribute( + node, filter.mayaString(), defGlobals.delegateParams.enableMotionSamples, userDefaults); if (filter.attributeFilter()) { return mayaObject; } } if (filter(_tokens->mtohTextureMemoryPerTexture)) { - _CreateIntAttribute(node, filter.mayaString(), + _CreateIntAttribute( + node, + filter.mayaString(), defGlobals.delegateParams.textureMemoryPerTexture / 1024, userDefaults, [](MFnNumericAttribute& nAttr) { @@ -736,7 +818,9 @@ MObject MtohRenderGlobals::CreateAttributes(const GlobalParams& params) { } } if (filter(MtohTokens->mtohMaximumShadowMapResolution)) { - _CreateIntAttribute(node, filter.mayaString(), + _CreateIntAttribute( + node, + filter.mayaString(), defGlobals.delegateParams.maximumShadowMapResolution, userDefaults, [](MFnNumericAttribute& nAttr) { @@ -748,36 +832,36 @@ MObject MtohRenderGlobals::CreateAttributes(const GlobalParams& params) { } } if (filter(_tokens->mtohWireframeSelectionHighlight)) { - _CreateBoolAttribute(node, filter.mayaString(), - defGlobals.wireframeSelectionHighlight, userDefaults); + _CreateBoolAttribute( + node, filter.mayaString(), defGlobals.wireframeSelectionHighlight, userDefaults); if (filter.attributeFilter()) { return mayaObject; } } if (filter(_tokens->mtohColorSelectionHighlight)) { - _CreateBoolAttribute(node, filter.mayaString(), - defGlobals.colorSelectionHighlight, userDefaults); + _CreateBoolAttribute( + node, filter.mayaString(), defGlobals.colorSelectionHighlight, userDefaults); if (filter.attributeFilter()) { return mayaObject; } } if (filter(_tokens->mtohColorSelectionHighlightColor)) { - _CreateColorAttribute(node, filter.mayaString(), - defGlobals.colorSelectionHighlightColor, userDefaults); + _CreateColorAttribute( + node, filter.mayaString(), defGlobals.colorSelectionHighlightColor, userDefaults); if (filter.attributeFilter()) { return mayaObject; } } #if USD_VERSION_NUM >= 2005 if (filter(_tokens->mtohSelectionOutline)) { - _CreateFloatAttribute(node, filter.mayaString(), - defGlobals.outlineSelectionWidth, userDefaults); + _CreateFloatAttribute( + node, filter.mayaString(), defGlobals.outlineSelectionWidth, userDefaults); } #endif #if USD_VERSION_NUM > 1911 && USD_VERSION_NUM <= 2005 if (filter(_tokens->mtohColorQuantization)) { - _CreateBoolAttribute(node, filter.mayaString(), - defGlobals.enableColorQuantization, userDefaults); + _CreateBoolAttribute( + node, filter.mayaString(), defGlobals.enableColorQuantization, userDefaults); if (filter.attributeFilter()) { return mayaObject; } @@ -798,41 +882,58 @@ MObject MtohRenderGlobals::CreateAttributes(const GlobalParams& params) { } if (attr.defaultValue.IsHolding()) { - _CreateBoolAttribute(node, filter.mayaString(), + _CreateBoolAttribute( + node, + filter.mayaString(), attr.defaultValue.UncheckedGet(), userDefaults); } else if (attr.defaultValue.IsHolding()) { - _CreateIntAttribute(node, filter.mayaString(), - attr.defaultValue.UncheckedGet(), - userDefaults); + _CreateIntAttribute( + node, filter.mayaString(), attr.defaultValue.UncheckedGet(), userDefaults); } else if (attr.defaultValue.IsHolding()) { - _CreateFloatAttribute(node, filter.mayaString(), + _CreateFloatAttribute( + node, + filter.mayaString(), attr.defaultValue.UncheckedGet(), userDefaults); } else if (attr.defaultValue.IsHolding()) { - _CreateColorAttribute(node, filter.mayaString(), + _CreateColorAttribute( + node, + filter.mayaString(), attr.defaultValue.UncheckedGet(), userDefaults); } else if (attr.defaultValue.IsHolding()) { - _CreateColorAttribute(node, filter.mayaString(), + _CreateColorAttribute( + node, + filter.mayaString(), attr.defaultValue.UncheckedGet(), userDefaults); } else if (attr.defaultValue.IsHolding()) { - _CreateStringAttribute(node, filter.mayaString(), + _CreateStringAttribute( + node, + filter.mayaString(), attr.defaultValue.UncheckedGet().GetString(), userDefaults); } else if (attr.defaultValue.IsHolding()) { - _CreateStringAttribute(node, filter.mayaString(), + _CreateStringAttribute( + node, + filter.mayaString(), attr.defaultValue.UncheckedGet(), userDefaults); } else if (attr.defaultValue.IsHolding()) { - _CreateEnumAttribute(node, filter.mayaString(), + _CreateEnumAttribute( + node, + filter.mayaString(), attr.defaultValue.UncheckedGet(), userDefaults); } else { - assert(!_IsSupportedAttribute(attr.defaultValue) && "_IsSupportedAttribute out of synch"); + assert( + !_IsSupportedAttribute(attr.defaultValue) + && "_IsSupportedAttribute out of synch"); - TF_WARN("[mtoh] Ignoring setting: '%s' for %s", attr.key.GetText(), + TF_WARN( + "[mtoh] Ignoring setting: '%s' for %s", + attr.key.GetText(), rendererName.GetText()); } if (filter.attributeFilter()) { @@ -843,15 +944,16 @@ MObject MtohRenderGlobals::CreateAttributes(const GlobalParams& params) { return mayaObject; } -const MtohRenderGlobals& MtohRenderGlobals::GetInstance(const GlobalParams& params, - bool storeUserSetting) { +const MtohRenderGlobals& +MtohRenderGlobals::GetInstance(const GlobalParams& params, bool storeUserSetting) +{ static MtohRenderGlobals globals; - const auto obj = CreateAttributes(params); + const auto obj = CreateAttributes(params); if (obj.isNull()) { return globals; } - MStatus status; + MStatus status; MFnDependencyNode node(obj, &status); if (!status) { return globals; @@ -859,53 +961,60 @@ const MtohRenderGlobals& MtohRenderGlobals::GetInstance(const GlobalParams& para MtohSettingFilter filter(params); - if (filter(_tokens->mtohTextureMemoryPerTexture) && - _GetAttribute(node, filter.mayaString(), - globals.delegateParams.textureMemoryPerTexture, storeUserSetting)) { + if (filter(_tokens->mtohTextureMemoryPerTexture) + && _GetAttribute( + node, + filter.mayaString(), + globals.delegateParams.textureMemoryPerTexture, + storeUserSetting)) { globals.delegateParams.textureMemoryPerTexture *= 1024; if (filter.attributeFilter()) { return globals; } } if (filter(_tokens->mtohEnableMotionSamples)) { - _GetAttribute(node, filter.mayaString(), - globals.delegateParams.enableMotionSamples, storeUserSetting); + _GetAttribute( + node, + filter.mayaString(), + globals.delegateParams.enableMotionSamples, + storeUserSetting); if (filter.attributeFilter()) { return globals; } } if (filter(MtohTokens->mtohMaximumShadowMapResolution)) { - _GetAttribute(node, filter.mayaString(), - globals.delegateParams.maximumShadowMapResolution, storeUserSetting); + _GetAttribute( + node, + filter.mayaString(), + globals.delegateParams.maximumShadowMapResolution, + storeUserSetting); if (filter.attributeFilter()) { return globals; } } if (filter(_tokens->mtohWireframeSelectionHighlight)) { - _GetAttribute(node, filter.mayaString(), - globals.wireframeSelectionHighlight, storeUserSetting); + _GetAttribute( + node, filter.mayaString(), globals.wireframeSelectionHighlight, storeUserSetting); if (filter.attributeFilter()) { return globals; } } if (filter(_tokens->mtohColorSelectionHighlight)) { - _GetAttribute(node, filter.mayaString(), - globals.colorSelectionHighlight, storeUserSetting); + _GetAttribute(node, filter.mayaString(), globals.colorSelectionHighlight, storeUserSetting); if (filter.attributeFilter()) { return globals; } } if (filter(_tokens->mtohColorSelectionHighlightColor)) { - _GetColorAttribute(node, filter.mayaString(), - globals.colorSelectionHighlightColor, storeUserSetting); + _GetColorAttribute( + node, filter.mayaString(), globals.colorSelectionHighlightColor, storeUserSetting); if (filter.attributeFilter()) { return globals; } } #if USD_VERSION_NUM >= 2005 if (filter(_tokens->mtohSelectionOutline)) { - _GetAttribute(node, filter.mayaString(), - globals.outlineSelectionWidth, storeUserSetting); + _GetAttribute(node, filter.mayaString(), globals.outlineSelectionWidth, storeUserSetting); if (filter.attributeFilter()) { return globals; } @@ -913,8 +1022,7 @@ const MtohRenderGlobals& MtohRenderGlobals::GetInstance(const GlobalParams& para #endif #if USD_VERSION_NUM > 1911 && USD_VERSION_NUM <= 2005 if (filter(_tokens->mtohColorQuantization)) { - _GetAttribute(node, filter.mayaString(), - globals.enableColorQuantization, storeUserSetting); + _GetAttribute(node, filter.mayaString(), globals.enableColorQuantization, storeUserSetting); if (filter.attributeFilter()) { return globals; } @@ -970,9 +1078,13 @@ const MtohRenderGlobals& MtohRenderGlobals::GetInstance(const GlobalParams& para _GetAttribute(node, filter.mayaString(), v, storeUserSetting); settings[filter.attrName()] = v; } else { - assert(!_IsSupportedAttribute(attr.defaultValue) && "_IsSupportedAttribute out of synch"); + assert( + !_IsSupportedAttribute(attr.defaultValue) + && "_IsSupportedAttribute out of synch"); - TF_WARN("[mtoh] Can't get setting: '%s' for %s", attr.key.GetText(), + TF_WARN( + "[mtoh] Can't get setting: '%s' for %s", + attr.key.GetText(), rendererName.GetText()); } if (filter.attributeFilter()) { @@ -983,12 +1095,14 @@ const MtohRenderGlobals& MtohRenderGlobals::GetInstance(const GlobalParams& para return globals; } -const MtohRenderGlobals& MtohRenderGlobals::GetInstance(bool storeUserSetting) { +const MtohRenderGlobals& MtohRenderGlobals::GetInstance(bool storeUserSetting) +{ return GetInstance(GlobalParams(), storeUserSetting); } -const MtohRenderGlobals& MtohRenderGlobals::GlobalChanged(const GlobalParams& params, - bool storeUserSetting) { +const MtohRenderGlobals& +MtohRenderGlobals::GlobalChanged(const GlobalParams& params, bool storeUserSetting) +{ return GetInstance(params, storeUserSetting); } diff --git a/lib/mayaUsd/render/mayaToHydra/renderGlobals.h b/lib/mayaUsd/render/mayaToHydra/renderGlobals.h index a26b12abb5..97ca4c37d1 100644 --- a/lib/mayaUsd/render/mayaToHydra/renderGlobals.h +++ b/lib/mayaUsd/render/mayaToHydra/renderGlobals.h @@ -16,29 +16,31 @@ #ifndef MTOH_RENDER_GLOBALS_H #define MTOH_RENDER_GLOBALS_H -#include -#include +#include "tokens.h" +#include "utils.h" -#include +#include -#include #include #include #include +#include -#include +#include -#include "tokens.h" -#include "utils.h" +#include +#include PXR_NAMESPACE_OPEN_SCOPE -class MtohRenderGlobals { +class MtohRenderGlobals +{ public: MtohRenderGlobals(); ~MtohRenderGlobals() = default; - struct GlobalParams { + struct GlobalParams + { const TfToken filter = {}; // Is the filter above only a renderer, or a renderer.attribute const bool filterIsRenderer = false; @@ -54,8 +56,8 @@ class MtohRenderGlobals { static const MtohRenderGlobals& GetInstance(bool storeUserSettings = false); // Inform mtoh one of the settings stored on "defaultRenderGlobals" has changed - static const MtohRenderGlobals& GlobalChanged(const GlobalParams&, - bool storeUserSetting = false); + static const MtohRenderGlobals& + GlobalChanged(const GlobalParams&, bool storeUserSetting = false); // Check that the attribute given affects the renderer given. static bool AffectsRenderer(const TfToken& mangledAttr, const TfToken& rendererName); @@ -64,27 +66,29 @@ class MtohRenderGlobals { static void OptionsPreamble(); // Build a UI options menu for the renderer and it's settings list - static void BuildOptionsMenu(const MtohRendererDescription& rendererDesc, + static void BuildOptionsMenu( + const MtohRendererDescription& rendererDesc, const HdRenderSettingDescriptorList& rendererSettingDescriptors); - // Apply the given setting (or all of a delegate's settings when attrNames is empty) to the given renderDelegate - bool ApplySettings(HdRenderDelegate* delegate, const TfToken& rendererName, + // Apply the given setting (or all of a delegate's settings when attrNames is empty) to the + // given renderDelegate + bool ApplySettings( + HdRenderDelegate* delegate, + const TfToken& rendererName, const TfTokenVector& attrNames = {}) const; private: - static const MtohRenderGlobals& GetInstance(const GlobalParams&, - bool storeUserSetting); + static const MtohRenderGlobals& GetInstance(const GlobalParams&, bool storeUserSetting); class MtohSettingFilter; using RendererSettings = std::unordered_map; - std::unordered_map - _rendererSettings; + std::unordered_map _rendererSettings; public: HdMayaParams delegateParams; - GfVec4f colorSelectionHighlightColor = GfVec4f(1.0f, 1.0f, 0.0f, 0.5f); - bool colorSelectionHighlight = true; - bool wireframeSelectionHighlight = true; + GfVec4f colorSelectionHighlightColor = GfVec4f(1.0f, 1.0f, 0.0f, 0.5f); + bool colorSelectionHighlight = true; + bool wireframeSelectionHighlight = true; #if USD_VERSION_NUM >= 2005 float outlineSelectionWidth = 4.f; #endif @@ -93,7 +97,6 @@ class MtohRenderGlobals { #endif }; - PXR_NAMESPACE_CLOSE_SCOPE #endif // MTOH_RENDER_GLOBALS_H diff --git a/lib/mayaUsd/render/mayaToHydra/renderOverride.cpp b/lib/mayaUsd/render/mayaToHydra/renderOverride.cpp index 9ca4a37370..5d74f890ff 100644 --- a/lib/mayaUsd/render/mayaToHydra/renderOverride.cpp +++ b/lib/mayaUsd/render/mayaToHydra/renderOverride.cpp @@ -15,11 +15,28 @@ // #include "renderOverride.h" -#include -#include -#include +#include "pluginDebugCodes.h" +#include "renderOverrideUtils.h" +#include "tokens.h" +#include "utils.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include #include +#include #include #include #include @@ -28,31 +45,12 @@ #include #include #include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "pluginDebugCodes.h" -#include "renderOverrideUtils.h" -#include "tokens.h" -#include "utils.h" - -#include -#include -#include #include +#include +#include +#include #include #if USD_VERSION_NUM > 2002 @@ -74,33 +72,40 @@ namespace { // Not sure if we actually need a mutex guarding _allInstances, but // everywhere that uses it isn't a "frequent" operation, so the // extra speed loss should be fine, and I'd rather be safe. -std::mutex _allInstancesMutex; +std::mutex _allInstancesMutex; std::vector _allInstances; #if WANT_UFE_BUILD // Observe UFE scene items for transformation changed only when they are // selected. -class UfeSelectionObserver : public UFE_NS::Observer { +class UfeSelectionObserver : public UFE_NS::Observer +{ public: UfeSelectionObserver(MtohRenderOverride& mtohRenderOverride) - : UFE_NS::Observer(), _mtohRenderOverride(mtohRenderOverride) {} + : UFE_NS::Observer() + , _mtohRenderOverride(mtohRenderOverride) + { + } //~UfeSelectionObserver() override {} - void operator()(const UFE_NS::Notification& notification) override { + void operator()(const UFE_NS::Notification& notification) override + { // During Maya file read, each node will be selected in turn, so we get // notified for each node in the scene. Prune this out. - if (MFileIO::isOpeningFile()) { return; } + if (MFileIO::isOpeningFile()) { + return; + } - auto selectionChanged = - dynamic_cast(¬ification); - if (selectionChanged == nullptr) { return; } + auto selectionChanged = dynamic_cast(¬ification); + if (selectionChanged == nullptr) { + return; + } TF_DEBUG(HDMAYA_RENDEROVERRIDE_SELECTION) - .Msg( - "UfeSelectionObserver triggered (ufe selection change " - "triggered)\n"); + .Msg("UfeSelectionObserver triggered (ufe selection change " + "triggered)\n"); _mtohRenderOverride.SelectionChanged(); } @@ -187,51 +192,59 @@ void ResolveUniqueHits_Workaround(const HdxPickHitVector& inHits, HdxPickHitVect } // namespace MtohRenderOverride::MtohRenderOverride(const MtohRendererDescription& desc) - : MHWRender::MRenderOverride(desc.overrideName.GetText()), - _rendererDesc(desc), - _globals(MtohRenderGlobals::GetInstance()), + : MHWRender::MRenderOverride(desc.overrideName.GetText()) + , _rendererDesc(desc) + , _globals(MtohRenderGlobals::GetInstance()) + , #if USD_VERSION_NUM > 2002 #if USD_VERSION_NUM > 2005 - _hgi(Hgi::CreatePlatformDefaultHgi()), + _hgi(Hgi::CreatePlatformDefaultHgi()) + , #else - _hgi(Hgi::GetPlatformDefaultHgi()), + _hgi(Hgi::GetPlatformDefaultHgi()) + , #endif - _hgiDriver{HgiTokens->renderDriver, VtValue(_hgi.get())}, + _hgiDriver { HgiTokens->renderDriver, VtValue(_hgi.get()) } + , #endif - _selectionTracker(new HdxSelectionTracker), - _isUsingHdSt(desc.rendererName == MtohTokens->HdStormRendererPlugin) { + _selectionTracker(new HdxSelectionTracker) + , _isUsingHdSt(desc.rendererName == MtohTokens->HdStormRendererPlugin) +{ TF_DEBUG(HDMAYA_RENDEROVERRIDE_RESOURCES) .Msg( "MtohRenderOverride created (%s - %s - %s)\n", _rendererDesc.rendererName.GetText(), _rendererDesc.overrideName.GetText(), _rendererDesc.displayName.GetText()); - HdMayaDelegateRegistry::InstallDelegatesChangedSignal( - [this]() { _needsClear.store(true); }); + HdMayaDelegateRegistry::InstallDelegatesChangedSignal([this]() { _needsClear.store(true); }); _ID = SdfPath("/HdMayaViewportRenderer") - .AppendChild(TfToken(TfStringPrintf( - "_HdMaya_%s_%p", desc.rendererName.GetText(), this))); + .AppendChild( + TfToken(TfStringPrintf("_HdMaya_%s_%p", desc.rendererName.GetText(), this))); MStatus status; - auto id = MSceneMessage::addCallback( - MSceneMessage::kBeforeNew, _ClearHydraCallback, this, &status); - if (status) { _callbacks.push_back(id); } - id = MSceneMessage::addCallback( - MSceneMessage::kBeforeOpen, _ClearHydraCallback, this, &status); - if (status) { _callbacks.push_back(id); } + auto id + = MSceneMessage::addCallback(MSceneMessage::kBeforeNew, _ClearHydraCallback, this, &status); + if (status) { + _callbacks.push_back(id); + } + id = MSceneMessage::addCallback(MSceneMessage::kBeforeOpen, _ClearHydraCallback, this, &status); + if (status) { + _callbacks.push_back(id); + } id = MEventMessage::addEventCallback( MString("SelectionChanged"), _SelectionChangedCallback, this, &status); - if (status) { _callbacks.push_back(id); } + if (status) { + _callbacks.push_back(id); + } // Setup the playblast watch. // _playBlasting is forced to true here so we can just use _PlayblastingChanged below // _playBlasting = true; - MConditionMessage::addConditionCallback("playblasting", - &MtohRenderOverride::_PlayblastingChanged, this, &status); + MConditionMessage::addConditionCallback( + "playblasting", &MtohRenderOverride::_PlayblastingChanged, this, &status); MtohRenderOverride::_PlayblastingChanged(false, this); - _defaultLight.SetSpecular(GfVec4f(0.0f)); _defaultLight.SetAmbient(GfVec4f(0.0f)); @@ -241,8 +254,7 @@ MtohRenderOverride::MtohRenderOverride(const MtohRendererDescription& desc) } #if WANT_UFE_BUILD - const UFE_NS::GlobalSelection::Ptr& ufeSelection = - UFE_NS::GlobalSelection::get(); + const UFE_NS::GlobalSelection::Ptr& ufeSelection = UFE_NS::GlobalSelection::get(); if (ufeSelection) { _ufeSelectionObserver = std::make_shared(*this); ufeSelection->addObserver(_ufeSelectionObserver); @@ -250,7 +262,8 @@ MtohRenderOverride::MtohRenderOverride(const MtohRendererDescription& desc) #endif // WANT_UFE_BUILD } -MtohRenderOverride::~MtohRenderOverride() { +MtohRenderOverride::~MtohRenderOverride() +{ TF_DEBUG(HDMAYA_RENDEROVERRIDE_RESOURCES) .Msg( "MtohRenderOverride destroyed (%s - %s - %s)\n", @@ -263,9 +276,13 @@ MtohRenderOverride::~MtohRenderOverride() { ClearHydraResources(); - for (auto operation : _operations) { delete operation; } + for (auto operation : _operations) { + delete operation; + } - for (auto callback : _callbacks) { MMessage::removeCallback(callback); } + for (auto callback : _callbacks) { + MMessage::removeCallback(callback); + } for (auto& panelAndCallbacks : _renderPanelCallbacks) { MMessage::removeCallbacks(panelAndCallbacks.second); } @@ -273,16 +290,19 @@ MtohRenderOverride::~MtohRenderOverride() { { std::lock_guard lock(_allInstancesMutex); _allInstances.erase( - std::remove(_allInstances.begin(), _allInstances.end(), this), - _allInstances.end()); + std::remove(_allInstances.begin(), _allInstances.end(), this), _allInstances.end()); } } -HdRenderDelegate* MtohRenderOverride::_GetRenderDelegate() { +HdRenderDelegate* MtohRenderOverride::_GetRenderDelegate() +{ return _renderIndex ? _renderIndex->GetRenderDelegate() : nullptr; } -void MtohRenderOverride::UpdateRenderGlobals(const MtohRenderGlobals& globals, const TfToken& attrName) { +void MtohRenderOverride::UpdateRenderGlobals( + const MtohRenderGlobals& globals, + const TfToken& attrName) +{ // If no attribute or attribute starts with 'mtoh', these setting wil be applied on the next // call to MtohRenderOverride::Render, so just force an invalidation // XXX: This will need to change if mtoh settings should ever make it to the delegate itself. @@ -299,8 +319,10 @@ void MtohRenderOverride::UpdateRenderGlobals(const MtohRenderGlobals& globals, c // Will be applied in _InitHydraResources later anyway if (auto* renderDelegate = instance->_GetRenderDelegate()) { - instance->_globals.ApplySettings(renderDelegate, - instance->_rendererDesc.rendererName, TfTokenVector(attrFilter, attrName)); + instance->_globals.ApplySettings( + renderDelegate, + instance->_rendererDesc.rendererName, + TfTokenVector(attrFilter, attrName)); if (attrFilter) { break; } @@ -312,7 +334,8 @@ void MtohRenderOverride::UpdateRenderGlobals(const MtohRenderGlobals& globals, c MGlobal::executeCommandOnIdle("refresh -f"); } -std::vector MtohRenderOverride::AllActiveRendererNames() { +std::vector MtohRenderOverride::AllActiveRendererNames() +{ std::vector renderers; std::lock_guard lock(_allInstancesMutex); @@ -324,21 +347,27 @@ std::vector MtohRenderOverride::AllActiveRendererNames() { return renderers; } -SdfPathVector MtohRenderOverride::RendererRprims( - TfToken rendererName, bool visibleOnly) { +SdfPathVector MtohRenderOverride::RendererRprims(TfToken rendererName, bool visibleOnly) +{ MtohRenderOverride* instance = _GetByName(rendererName); - if (!instance) { return SdfPathVector(); } + if (!instance) { + return SdfPathVector(); + } auto* renderIndex = instance->_renderIndex; - if (!renderIndex) { return SdfPathVector(); } + if (!renderIndex) { + return SdfPathVector(); + } auto primIds = renderIndex->GetRprimIds(); if (visibleOnly) { primIds.erase( std::remove_if( - primIds.begin(), primIds.end(), + primIds.begin(), + primIds.end(), [renderIndex](const SdfPath& primId) { auto* rprim = renderIndex->GetRprim(primId); - if (!rprim) return true; + if (!rprim) + return true; return !rprim->IsVisible(); }), primIds.end()); @@ -346,10 +375,12 @@ SdfPathVector MtohRenderOverride::RendererRprims( return primIds; } -SdfPath MtohRenderOverride::RendererSceneDelegateId( - TfToken rendererName, TfToken sceneDelegateName) { +SdfPath MtohRenderOverride::RendererSceneDelegateId(TfToken rendererName, TfToken sceneDelegateName) +{ MtohRenderOverride* instance = _GetByName(rendererName); - if (!instance) { return SdfPath(); } + if (!instance) { + return SdfPath(); + } for (auto& delegate : instance->_delegates) { if (delegate->GetName() == sceneDelegateName) { @@ -359,38 +390,39 @@ SdfPath MtohRenderOverride::RendererSceneDelegateId( return SdfPath(); } -void MtohRenderOverride::_DetectMayaDefaultLighting( - const MHWRender::MDrawContext& drawContext) { - constexpr auto considerAllSceneLights = - MHWRender::MDrawContext::kFilteredIgnoreLightLimit; +void MtohRenderOverride::_DetectMayaDefaultLighting(const MHWRender::MDrawContext& drawContext) +{ + constexpr auto considerAllSceneLights = MHWRender::MDrawContext::kFilteredIgnoreLightLimit; - const auto numLights = - drawContext.numberOfActiveLights(considerAllSceneLights); - auto foundMayaDefaultLight = false; + const auto numLights = drawContext.numberOfActiveLights(considerAllSceneLights); + auto foundMayaDefaultLight = false; if (numLights == 1) { - auto* lightParam = - drawContext.getLightParameterInformation(0, considerAllSceneLights); + auto* lightParam = drawContext.getLightParameterInformation(0, considerAllSceneLights); if (lightParam != nullptr && !lightParam->lightPath().isValid()) { // This light does not exist so it must be the // default maya light MFloatPointArray positions; - MFloatVector direction; - auto intensity = 0.0f; - MColor color; - auto hasDirection = false; - auto hasPosition = false; + MFloatVector direction; + auto intensity = 0.0f; + MColor color; + auto hasDirection = false; + auto hasPosition = false; // Maya default light has no position, only direction drawContext.getLightInformation( - 0, positions, direction, intensity, color, hasDirection, - hasPosition, considerAllSceneLights); + 0, + positions, + direction, + intensity, + color, + hasDirection, + hasPosition, + considerAllSceneLights); if (hasDirection && !hasPosition) { - _defaultLight.SetPosition( - {-direction.x, -direction.y, -direction.z, 0.0f}); - _defaultLight.SetDiffuse({intensity * color.r, - intensity * color.g, - intensity * color.b, 1.0f}); + _defaultLight.SetPosition({ -direction.x, -direction.y, -direction.z, 0.0f }); + _defaultLight.SetDiffuse( + { intensity * color.r, intensity * color.g, intensity * color.b, 1.0f }); foundMayaDefaultLight = true; } } @@ -415,7 +447,8 @@ void MtohRenderOverride::_DetectMayaDefaultLighting( } } -MStatus MtohRenderOverride::Render(const MHWRender::MDrawContext& drawContext) { +MStatus MtohRenderOverride::Render(const MHWRender::MDrawContext& drawContext) +{ // It would be good to clear the resources of the overrides that are // not in active use, but I'm not sure if we have a better way than // the idle time we use currently. The approach below would break if @@ -425,13 +458,12 @@ MStatus MtohRenderOverride::Render(const MHWRender::MDrawContext& drawContext) { // override->ClearHydraResources(); // } // } - TF_DEBUG(HDMAYA_RENDEROVERRIDE_RENDER) - .Msg("MtohRenderOverride::Render()\n"); + TF_DEBUG(HDMAYA_RENDEROVERRIDE_RENDER).Msg("MtohRenderOverride::Render()\n"); auto renderFrame = [&](bool markTime = false) { const auto originX = 0; const auto originY = 0; - int width = 0; - int height = 0; + int width = 0; + int height = 0; drawContext.getRenderTargetSize(width, height); GfVec4d viewport(originX, originY, width, height); @@ -440,10 +472,8 @@ MStatus MtohRenderOverride::Render(const MHWRender::MDrawContext& drawContext) { #else _taskController->SetCameraMatrices( #endif // USD_VERSION_NUM >= 1910 - GetGfMatrixFromMaya( - drawContext.getMatrix(MHWRender::MFrameContext::kViewMtx)), - GetGfMatrixFromMaya(drawContext.getMatrix( - MHWRender::MFrameContext::kProjectionMtx))); + GetGfMatrixFromMaya(drawContext.getMatrix(MHWRender::MFrameContext::kViewMtx)), + GetGfMatrixFromMaya(drawContext.getMatrix(MHWRender::MFrameContext::kProjectionMtx))); #if USD_VERSION_NUM >= 1910 _taskController->SetRenderViewport(viewport); #else @@ -465,9 +495,11 @@ MStatus MtohRenderOverride::Render(const MHWRender::MDrawContext& drawContext) { // XXX: Is this better as user-configurable ? constexpr auto msWait = std::chrono::duration(100); #if USD_VERSION_NUM >= 2005 - std::shared_ptr renderTask = std::dynamic_pointer_cast(tasks.front()); + std::shared_ptr renderTask + = std::dynamic_pointer_cast(tasks.front()); #else - boost::shared_ptr renderTask = boost::dynamic_pointer_cast(tasks.front()); + boost::shared_ptr renderTask + = boost::dynamic_pointer_cast(tasks.front()); #endif if (renderTask) { HdTaskSharedPtrVector renderOnly = { renderTask }; @@ -495,7 +527,9 @@ MStatus MtohRenderOverride::Render(const MHWRender::MDrawContext& drawContext) { }; _DetectMayaDefaultLighting(drawContext); - if (_needsClear.exchange(false)) { ClearHydraResources(); } + if (_needsClear.exchange(false)) { + ClearHydraResources(); + } if (!_initializedViewport) { _InitHydraResources(); @@ -505,7 +539,7 @@ MStatus MtohRenderOverride::Render(const MHWRender::MDrawContext& drawContext) { _SelectionChanged(); - const auto displayStyle = drawContext.getDisplayStyle(); + const auto displayStyle = drawContext.getDisplayStyle(); HdMayaParams delegateParams = _globals.delegateParams; delegateParams.displaySmoothMeshes = !(displayStyle & MHWRender::MFrameContext::kFlatShaded); @@ -519,7 +553,8 @@ MStatus MtohRenderOverride::Render(const MHWRender::MDrawContext& drawContext) { HdxRenderTaskParams params; params.enableLighting = true; - params.enableSceneMaterials = !(drawContext.getDisplayStyle() & MHWRender::MFrameContext::kDefaultMaterial); + params.enableSceneMaterials + = !(drawContext.getDisplayStyle() & MHWRender::MFrameContext::kDefaultMaterial); /* TODO: Find replacement * if (displayStyle & MHWRender::MFrameContext::kBoundingBox) { @@ -560,22 +595,22 @@ MStatus MtohRenderOverride::Render(const MHWRender::MDrawContext& drawContext) { _taskController->SetCollection(_renderCollection); if (_isUsingHdSt) { // TODO: Is there a way to improve this? Quite silly. - auto enableShadows = true; + auto enableShadows = true; auto* lightParam = drawContext.getLightParameterInformation( 0, MHWRender::MDrawContext::kFilteredIgnoreLightLimit); if (lightParam != nullptr) { MIntArray intVals; if (lightParam->getParameter( - MHWRender::MLightParameterInformation::kGlobalShadowOn, - intVals) && - intVals.length() > 0) { + MHWRender::MLightParameterInformation::kGlobalShadowOn, intVals) + && intVals.length() > 0) { enableShadows = intVals[0] != 0; } } HdxShadowTaskParams shadowParams; shadowParams.cullStyle = HdCullStyleNothing; - // The light & shadow parameters currently (19.11-20.08) are only used for tasks specific to Storm + // The light & shadow parameters currently (19.11-20.08) are only used for tasks specific to + // Storm _taskController->SetEnableShadows(enableShadows); _taskController->SetShadowParams(shadowParams); @@ -592,19 +627,23 @@ MStatus MtohRenderOverride::Render(const MHWRender::MDrawContext& drawContext) { if (_globals.wireframeSelectionHighlight && !_selectionCollection.GetRootPaths().empty()) { _taskController->SetCollection(_selectionCollection); renderFrame(); - // XXX: This call isn't 'free' and will be done again on the next MtohRenderOverride::Render call anyway + // XXX: This call isn't 'free' and will be done again on the next + // MtohRenderOverride::Render call anyway _taskController->SetCollection(_renderCollection); } } else { renderFrame(true); } - for (auto& it : _delegates) { it->PostFrame(); } + for (auto& it : _delegates) { + it->PostFrame(); + } return MStatus::kSuccess; } -MtohRenderOverride* MtohRenderOverride::_GetByName(TfToken rendererName) { +MtohRenderOverride* MtohRenderOverride::_GetByName(TfToken rendererName) +{ std::lock_guard lock(_allInstancesMutex); for (auto* instance : _allInstances) { if (instance->_rendererDesc.rendererName == rendererName) { @@ -614,19 +653,17 @@ MtohRenderOverride* MtohRenderOverride::_GetByName(TfToken rendererName) { return nullptr; } -void MtohRenderOverride::_InitHydraResources() { +void MtohRenderOverride::_InitHydraResources() +{ TF_DEBUG(HDMAYA_RENDEROVERRIDE_RESOURCES) - .Msg( - "MtohRenderOverride::_InitHydraResources(%s)\n", - _rendererDesc.rendererName.GetText()); + .Msg("MtohRenderOverride::_InitHydraResources(%s)\n", _rendererDesc.rendererName.GetText()); GlfGlewInit(); GlfContextCaps::InitInstance(); - _rendererPlugin = - HdRendererPluginRegistry::GetInstance().GetRendererPlugin( - _rendererDesc.rendererName); + _rendererPlugin + = HdRendererPluginRegistry::GetInstance().GetRendererPlugin(_rendererDesc.rendererName); auto* renderDelegate = _rendererPlugin->CreateRenderDelegate(); #if USD_VERSION_NUM > 2002 - _renderIndex = HdRenderIndex::New(renderDelegate, {&_hgiDriver}); + _renderIndex = HdRenderIndex::New(renderDelegate, { &_hgiDriver }); #else _renderIndex = HdRenderIndex::New(renderDelegate); #endif @@ -640,18 +677,25 @@ void MtohRenderOverride::_InitHydraResources() { _taskController->SetEnableShadows(true); HdMayaDelegate::InitData delegateInitData( - TfToken(), _engine, _renderIndex, _rendererPlugin, _taskController, - SdfPath(), _isUsingHdSt); + TfToken(), + _engine, + _renderIndex, + _rendererPlugin, + _taskController, + SdfPath(), + _isUsingHdSt); auto delegateNames = HdMayaDelegateRegistry::GetDelegateNames(); auto creators = HdMayaDelegateRegistry::GetDelegateCreators(); TF_VERIFY(delegateNames.size() == creators.size()); for (size_t i = 0, n = creators.size(); i < n; ++i) { const auto& creator = creators[i]; - if (creator == nullptr) { continue; } + if (creator == nullptr) { + continue; + } delegateInitData.name = delegateNames[i]; - delegateInitData.delegateID = _ID.AppendChild(TfToken(TfStringPrintf( - "_Delegate_%s_%lu_%p", delegateNames[i].GetText(), i, this))); + delegateInitData.delegateID = _ID.AppendChild( + TfToken(TfStringPrintf("_Delegate_%s_%lu_%p", delegateNames[i].GetText(), i, this))); auto newDelegate = creator(delegateInitData); if (newDelegate) { // Call SetLightsEnabled before the delegate is populated @@ -660,19 +704,20 @@ void MtohRenderOverride::_InitHydraResources() { } } if (_hasDefaultLighting) { - delegateInitData.delegateID = _ID.AppendChild( - TfToken(TfStringPrintf("_DefaultLightDelegate_%p", this))); - _defaultLightDelegate.reset( - new MtohDefaultLightDelegate(delegateInitData)); + delegateInitData.delegateID + = _ID.AppendChild(TfToken(TfStringPrintf("_DefaultLightDelegate_%p", this))); + _defaultLightDelegate.reset(new MtohDefaultLightDelegate(delegateInitData)); } VtValue selectionTrackerValue(_selectionTracker); - _engine.SetTaskContextData( - HdxTokens->selectionState, selectionTrackerValue); - for (auto& it : _delegates) { it->Populate(); } - if (_defaultLightDelegate) { _defaultLightDelegate->Populate(); } + _engine.SetTaskContextData(HdxTokens->selectionState, selectionTrackerValue); + for (auto& it : _delegates) { + it->Populate(); + } + if (_defaultLightDelegate) { + _defaultLightDelegate->Populate(); + } - _renderIndex->GetChangeTracker().AddCollection( - _selectionCollection.GetName()); + _renderIndex->GetChangeTracker().AddCollection(_selectionCollection.GetName()); _SelectionChanged(); _initializedViewport = true; @@ -682,18 +727,20 @@ void MtohRenderOverride::_InitHydraResources() { // but if not, fallback to user-defaults (current state) . const bool filterRenderer = true; const bool fallbackToUserDefaults = true; - _globals.GlobalChanged({_rendererDesc.rendererName, filterRenderer, fallbackToUserDefaults}); + _globals.GlobalChanged( + { _rendererDesc.rendererName, filterRenderer, fallbackToUserDefaults }); _globals.ApplySettings(renderDelegate, _rendererDesc.rendererName); } } -void MtohRenderOverride::ClearHydraResources() { - if (!_initializedViewport) { return; } +void MtohRenderOverride::ClearHydraResources() +{ + if (!_initializedViewport) { + return; + } TF_DEBUG(HDMAYA_RENDEROVERRIDE_RESOURCES) - .Msg( - "MtohRenderOverride::ClearHydraResources(%s)\n", - _rendererDesc.rendererName.GetText()); + .Msg("MtohRenderOverride::ClearHydraResources(%s)\n", _rendererDesc.rendererName.GetText()); _delegates.clear(); _defaultLightDelegate.reset(); @@ -722,7 +769,8 @@ void MtohRenderOverride::ClearHydraResources() { SelectionChanged(); } -void MtohRenderOverride::_RemovePanel(MString panelName) { +void MtohRenderOverride::_RemovePanel(MString panelName) +{ auto foundPanelCallbacks = _FindPanelCallbacks(panelName); if (foundPanelCallbacks != _renderPanelCallbacks.end()) { MMessage::removeCallbacks(foundPanelCallbacks->second); @@ -736,11 +784,16 @@ void MtohRenderOverride::_RemovePanel(MString panelName) { void MtohRenderOverride::SelectionChanged() { _selectionChanged = true; } -void MtohRenderOverride::_SelectionChanged() { - if (!_selectionChanged) { return; } +void MtohRenderOverride::_SelectionChanged() +{ + if (!_selectionChanged) { + return; + } _selectionChanged = false; MSelectionList sel; - if (!TF_VERIFY(MGlobal::getActiveSelectionList(sel))) { return; } + if (!TF_VERIFY(MGlobal::getActiveSelectionList(sel))) { + return; + } SdfPathVector selectedPaths; #if USD_VERSION_NUM > 2002 auto selection = std::make_shared(); @@ -749,16 +802,14 @@ void MtohRenderOverride::_SelectionChanged() { #endif // USD_VERSION_NUM > 2002 #if WANT_UFE_BUILD - const UFE_NS::GlobalSelection::Ptr& ufeSelection = - UFE_NS::GlobalSelection::get(); + const UFE_NS::GlobalSelection::Ptr& ufeSelection = UFE_NS::GlobalSelection::get(); #endif // WANT_UFE_BUILD for (auto& it : _delegates) { #if WANT_UFE_BUILD if (it->SupportsUfeSelection()) { if (ufeSelection) { - it->PopulateSelectedPaths( - *ufeSelection, selectedPaths, selection); + it->PopulateSelectedPaths(*ufeSelection, selectedPaths, selection); } // skip non-ufe PopulateSelectedPaths call continue; @@ -769,16 +820,16 @@ void MtohRenderOverride::_SelectionChanged() { _selectionCollection.SetRootPaths(selectedPaths); _selectionTracker->SetSelection(HdSelectionSharedPtr(selection)); TF_DEBUG(HDMAYA_RENDEROVERRIDE_SELECTION) - .Msg( - "MtohRenderOverride::_SelectionChanged - num selected: %lu\n", - selectedPaths.size()); + .Msg("MtohRenderOverride::_SelectionChanged - num selected: %lu\n", selectedPaths.size()); } -MHWRender::DrawAPI MtohRenderOverride::supportedDrawAPIs() const { +MHWRender::DrawAPI MtohRenderOverride::supportedDrawAPIs() const +{ return MHWRender::kOpenGLCoreProfile | MHWRender::kOpenGL; } -MStatus MtohRenderOverride::setup(const MString& destination) { +MStatus MtohRenderOverride::setup(const MString& destination) +{ MStatus status; auto panelNameAndCallbacks = _FindPanelCallbacks(destination); @@ -788,79 +839,85 @@ MStatus MtohRenderOverride::setup(const MString& destination) { auto id = MUiMessage::add3dViewDestroyMsgCallback( destination, _PanelDeletedCallback, this, &status); - if (status) { newCallbacks.append(id); } + if (status) { + newCallbacks.append(id); + } id = MUiMessage::add3dViewRendererChangedCallback( destination, _RendererChangedCallback, this, &status); - if (status) { newCallbacks.append(id); } + if (status) { + newCallbacks.append(id); + } id = MUiMessage::add3dViewRenderOverrideChangedCallback( destination, _RenderOverrideChangedCallback, this, &status); - if (status) { newCallbacks.append(id); } + if (status) { + newCallbacks.append(id); + } _renderPanelCallbacks.emplace_back(destination, newCallbacks); } auto* renderer = MHWRender::MRenderer::theRenderer(); - if (renderer == nullptr) { return MStatus::kFailure; } + if (renderer == nullptr) { + return MStatus::kFailure; + } if (_operations.empty()) { // Clear and draw the grid - _operations.push_back( - new HdMayaPreRender("HydraRenderOverride_PreScene")); + _operations.push_back(new HdMayaPreRender("HydraRenderOverride_PreScene")); // The main hydra render - _operations.push_back( - new HdMayaRender("HydraRenderOverride_Hydra", this)); + _operations.push_back(new HdMayaRender("HydraRenderOverride_Hydra", this)); // Draw scene elements (cameras, CVs, grid, shapes not pushed into hydra) - _operations.push_back( - new HdMayaPostRender("HydraRenderOverride_PostScene")); + _operations.push_back(new HdMayaPostRender("HydraRenderOverride_PostScene")); // Draw HUD elements _operations.push_back(new MHWRender::MHUDRender()); // Set final buffer options - auto* presentTarget = - new MHWRender::MPresentTarget("HydraRenderOverride_Present"); + auto* presentTarget = new MHWRender::MPresentTarget("HydraRenderOverride_Present"); presentTarget->setPresentDepth(true); - presentTarget->setTargetBackBuffer( - MHWRender::MPresentTarget::kCenterBuffer); + presentTarget->setTargetBackBuffer(MHWRender::MPresentTarget::kCenterBuffer); _operations.push_back(presentTarget); } return MS::kSuccess; } -MStatus MtohRenderOverride::cleanup() { +MStatus MtohRenderOverride::cleanup() +{ _currentOperation = -1; return MS::kSuccess; } -bool MtohRenderOverride::startOperationIterator() { +bool MtohRenderOverride::startOperationIterator() +{ _currentOperation = 0; return true; } -MHWRender::MRenderOperation* MtohRenderOverride::renderOperation() { - if (_currentOperation >= 0 && - _currentOperation < static_cast(_operations.size())) { +MHWRender::MRenderOperation* MtohRenderOverride::renderOperation() +{ + if (_currentOperation >= 0 && _currentOperation < static_cast(_operations.size())) { return _operations[_currentOperation]; } return nullptr; } -bool MtohRenderOverride::nextRenderOperation() { +bool MtohRenderOverride::nextRenderOperation() +{ return ++_currentOperation < static_cast(_operations.size()); } #if MAYA_API_VERSION >= 20210000 bool MtohRenderOverride::select( - const MHWRender::MFrameContext& frameContext, + const MHWRender::MFrameContext& frameContext, const MHWRender::MSelectionInfo& selectInfo, bool /*useDepth*/, MSelectionList& selectionList, - MPointArray& worldSpaceHitPts) + MPointArray& worldSpaceHitPts) { MStatus status = MStatus::kFailure; @@ -958,13 +1015,17 @@ bool MtohRenderOverride::select( } #endif -void MtohRenderOverride::_ClearHydraCallback(void* data) { +void MtohRenderOverride::_ClearHydraCallback(void* data) +{ auto* instance = reinterpret_cast(data); - if (!TF_VERIFY(instance)) { return; } + if (!TF_VERIFY(instance)) { + return; + } instance->ClearHydraResources(); } -void MtohRenderOverride::_PlayblastingChanged(bool playBlasting, void* userData) { +void MtohRenderOverride::_PlayblastingChanged(bool playBlasting, void* userData) +{ auto* instance = reinterpret_cast(userData); if (std::atomic_exchange(&instance->_playBlasting, playBlasting) == playBlasting) return; @@ -972,62 +1033,79 @@ void MtohRenderOverride::_PlayblastingChanged(bool playBlasting, void* userData) MStatus status; if (!playBlasting) { assert(instance->_timerCallback == 0 && "Callback exists"); - instance->_timerCallback = MTimerMessage::addTimerCallback(1.0f / 10.0f, - _TimerCallback, instance, &status); - } - else { + instance->_timerCallback + = MTimerMessage::addTimerCallback(1.0f / 10.0f, _TimerCallback, instance, &status); + } else { status = MMessage::removeCallback(instance->_timerCallback); - instance->_timerCallback= 0; + instance->_timerCallback = 0; } CHECK_MSTATUS(status); } -void MtohRenderOverride::_TimerCallback(float, float, void* data) { +void MtohRenderOverride::_TimerCallback(float, float, void* data) +{ auto* instance = reinterpret_cast(data); if (instance->_playBlasting || instance->_isConverged) { return; } std::lock_guard lock(instance->_lastRenderTimeMutex); - if ((std::chrono::system_clock::now() - instance->_lastRenderTime) < - std::chrono::seconds(5)) { + if ((std::chrono::system_clock::now() - instance->_lastRenderTime) < std::chrono::seconds(5)) { MGlobal::executeCommandOnIdle("refresh -f"); } } -void MtohRenderOverride::_PanelDeletedCallback( - const MString& panelName, void* data) { +void MtohRenderOverride::_PanelDeletedCallback(const MString& panelName, void* data) +{ auto* instance = reinterpret_cast(data); - if (!TF_VERIFY(instance)) { return; } + if (!TF_VERIFY(instance)) { + return; + } instance->_RemovePanel(panelName); } void MtohRenderOverride::_RendererChangedCallback( - const MString& panelName, const MString& oldRenderer, - const MString& newRenderer, void* data) { + const MString& panelName, + const MString& oldRenderer, + const MString& newRenderer, + void* data) +{ auto* instance = reinterpret_cast(data); - if (!TF_VERIFY(instance)) { return; } + if (!TF_VERIFY(instance)) { + return; + } - if (newRenderer != oldRenderer) { instance->_RemovePanel(panelName); } + if (newRenderer != oldRenderer) { + instance->_RemovePanel(panelName); + } } void MtohRenderOverride::_RenderOverrideChangedCallback( - const MString& panelName, const MString& oldOverride, - const MString& newOverride, void* data) { + const MString& panelName, + const MString& oldOverride, + const MString& newOverride, + void* data) +{ auto* instance = reinterpret_cast(data); - if (!TF_VERIFY(instance)) { return; } + if (!TF_VERIFY(instance)) { + return; + } - if (newOverride != instance->name()) { instance->_RemovePanel(panelName); } + if (newOverride != instance->name()) { + instance->_RemovePanel(panelName); + } } -void MtohRenderOverride::_SelectionChangedCallback(void* data) { +void MtohRenderOverride::_SelectionChangedCallback(void* data) +{ TF_DEBUG(HDMAYA_RENDEROVERRIDE_SELECTION) - .Msg( - "MtohRenderOverride::_SelectionChangedCallback() (normal maya " - "selection triggered)\n"); + .Msg("MtohRenderOverride::_SelectionChangedCallback() (normal maya " + "selection triggered)\n"); auto* instance = reinterpret_cast(data); - if (!TF_VERIFY(instance)) { return; } + if (!TF_VERIFY(instance)) { + return; + } instance->SelectionChanged(); } diff --git a/lib/mayaUsd/render/mayaToHydra/renderOverride.h b/lib/mayaUsd/render/mayaToHydra/renderOverride.h index 89915e45c8..f0826f8310 100644 --- a/lib/mayaUsd/render/mayaToHydra/renderOverride.h +++ b/lib/mayaUsd/render/mayaToHydra/renderOverride.h @@ -16,54 +16,54 @@ #ifndef MTOH_VIEW_OVERRIDE_H #define MTOH_VIEW_OVERRIDE_H -#include -#include -#include -#include +#include + +#include +#include #include #include #include #include -#include -#include -#include +#include +#include +#include +#include #if USD_VERSION_NUM > 2002 #include #endif #include #include +#include #include #include - -#include #include #if WANT_UFE_BUILD #include #endif // WANT_UFE_BUILD -#include -#include - #include "defaultLightDelegate.h" #include "renderGlobals.h" #include "utils.h" +#include +#include + PXR_NAMESPACE_OPEN_SCOPE using HgiUniquePtr = std::unique_ptr; -class MtohRenderOverride : public MHWRender::MRenderOverride { +class MtohRenderOverride : public MHWRender::MRenderOverride +{ public: MtohRenderOverride(const MtohRendererDescription& desc); ~MtohRenderOverride() override; /// Mark a setting (or all settings when attrName is '') as out of date - static void UpdateRenderGlobals(const MtohRenderGlobals& globals, - const TfToken& attrName = {}); + static void UpdateRenderGlobals(const MtohRenderGlobals& globals, const TfToken& attrName = {}); /// The names of all render delegates that are being used by at least /// one modelEditor panel. @@ -73,64 +73,60 @@ class MtohRenderOverride : public MHWRender::MRenderOverride { /// delegate. /// /// Intended mostly for use in debugging and testing. - static SdfPathVector RendererRprims( - TfToken rendererName, bool visibleOnly = false); + static SdfPathVector RendererRprims(TfToken rendererName, bool visibleOnly = false); /// Returns the scene delegate id for the given render delegate and /// scene delegate names. /// /// Intended mostly for use in debugging and testing. - static SdfPath RendererSceneDelegateId( - TfToken rendererName, TfToken sceneDelegateName); + static SdfPath RendererSceneDelegateId(TfToken rendererName, TfToken sceneDelegateName); MStatus Render(const MHWRender::MDrawContext& drawContext); void ClearHydraResources(); void SelectionChanged(); - MString uiName() const override { - return MString(_rendererDesc.displayName.GetText()); - } + MString uiName() const override { return MString(_rendererDesc.displayName.GetText()); } MHWRender::DrawAPI supportedDrawAPIs() const override; MStatus setup(const MString& destination) override; MStatus cleanup() override; - bool startOperationIterator() override; + bool startOperationIterator() override; MHWRender::MRenderOperation* renderOperation() override; - bool nextRenderOperation() override; + bool nextRenderOperation() override; #if MAYA_API_VERSION >= 20210000 bool select( - const MHWRender::MFrameContext& frameContext, + const MHWRender::MFrameContext& frameContext, const MHWRender::MSelectionInfo& selectInfo, - bool useDepth, - MSelectionList& selectionList, - MPointArray& worldSpaceHitPts) override; + bool useDepth, + MSelectionList& selectionList, + MPointArray& worldSpaceHitPts) override; #endif private: typedef std::pair PanelCallbacks; - typedef std::vector PanelCallbacksList; + typedef std::vector PanelCallbacksList; static MtohRenderOverride* _GetByName(TfToken rendererName); - void _InitHydraResources(); - void _RemovePanel(MString panelName); - void _SelectionChanged(); - void _DetectMayaDefaultLighting(const MHWRender::MDrawContext& drawContext); + void _InitHydraResources(); + void _RemovePanel(MString panelName); + void _SelectionChanged(); + void _DetectMayaDefaultLighting(const MHWRender::MDrawContext& drawContext); HdRenderDelegate* _GetRenderDelegate(); - inline PanelCallbacksList::iterator _FindPanelCallbacks(MString panelName) { + inline PanelCallbacksList::iterator _FindPanelCallbacks(MString panelName) + { // There should never be that many render panels, so linear iteration // should be fine return std::find_if( - _renderPanelCallbacks.begin(), _renderPanelCallbacks.end(), - [&panelName](const PanelCallbacks& item) { - return item.first == panelName; - }); + _renderPanelCallbacks.begin(), + _renderPanelCallbacks.end(), + [&panelName](const PanelCallbacks& item) { return item.first == panelName; }); } // Callbacks @@ -140,54 +136,59 @@ class MtohRenderOverride : public MHWRender::MRenderOverride { static void _SelectionChangedCallback(void* data); static void _PanelDeletedCallback(const MString& panelName, void* data); static void _RendererChangedCallback( - const MString& panelName, const MString& oldRenderer, - const MString& newRenderer, void* data); + const MString& panelName, + const MString& oldRenderer, + const MString& newRenderer, + void* data); static void _RenderOverrideChangedCallback( - const MString& panelName, const MString& oldOverride, - const MString& newOverride, void* data); + const MString& panelName, + const MString& oldOverride, + const MString& newOverride, + void* data); MtohRendererDescription _rendererDesc; std::vector _operations; - std::vector _callbacks; - MCallbackId _timerCallback = 0; - PanelCallbacksList _renderPanelCallbacks; - const MtohRenderGlobals& _globals; + std::vector _callbacks; + MCallbackId _timerCallback = 0; + PanelCallbacksList _renderPanelCallbacks; + const MtohRenderGlobals& _globals; - std::mutex _lastRenderTimeMutex; + std::mutex _lastRenderTimeMutex; std::chrono::system_clock::time_point _lastRenderTime; - std::atomic _playBlasting = {false}; - std::atomic _isConverged = {false}; - std::atomic _needsClear = {false}; + std::atomic _playBlasting = { false }; + std::atomic _isConverged = { false }; + std::atomic _needsClear = { false }; #if USD_VERSION_NUM > 2002 /// Hgi and HdDriver should be constructed before HdEngine to ensure they /// are destructed last. Hgi may be used during engine/delegate destruction. HgiUniquePtr _hgi; - HdDriver _hgiDriver; + HdDriver _hgiDriver; #endif - HdEngine _engine; - HdRendererPlugin* _rendererPlugin = nullptr; - HdxTaskController* _taskController = nullptr; - HdRenderIndex* _renderIndex = nullptr; + HdEngine _engine; + HdRendererPlugin* _rendererPlugin = nullptr; + HdxTaskController* _taskController = nullptr; + HdRenderIndex* _renderIndex = nullptr; std::unique_ptr _defaultLightDelegate = nullptr; - HdxSelectionTrackerSharedPtr _selectionTracker; - HdRprimCollection _renderCollection{ + HdxSelectionTrackerSharedPtr _selectionTracker; + HdRprimCollection _renderCollection + { HdTokens->geometry, - HdReprSelector( + HdReprSelector( #if MAYA_APP_VERSION >= 2019 - HdReprTokens->refined + HdReprTokens->refined #else - HdReprTokens->smoothHull + HdReprTokens->smoothHull #endif - ), - SdfPath::AbsoluteRootPath()}; - HdRprimCollection _selectionCollection{ - HdReprTokens->wire, HdReprSelector(HdReprTokens->wire) + ), + SdfPath::AbsoluteRootPath() }; + HdRprimCollection _selectionCollection { HdReprTokens->wire, + HdReprSelector(HdReprTokens->wire) }; #if MAYA_API_VERSION >= 20210000 - HdRprimCollection _pointSnappingCollection{ + HdRprimCollection _pointSnappingCollection { HdTokens->geometry, HdReprSelector(HdReprTokens->refined, TfToken(), HdReprTokens->points), SdfPath::AbsoluteRootPath() @@ -203,9 +204,9 @@ class MtohRenderOverride : public MHWRender::MRenderOverride { int _currentOperation = -1; const bool _isUsingHdSt = false; - bool _initializedViewport = false; - bool _hasDefaultLighting = false; - bool _selectionChanged = true; + bool _initializedViewport = false; + bool _hasDefaultLighting = false; + bool _selectionChanged = true; #if WANT_UFE_BUILD UFE_NS::Observer::Ptr _ufeSelectionObserver; diff --git a/lib/mayaUsd/render/mayaToHydra/renderOverrideUtils.h b/lib/mayaUsd/render/mayaToHydra/renderOverrideUtils.h index d606a40766..ae216be727 100644 --- a/lib/mayaUsd/render/mayaToHydra/renderOverrideUtils.h +++ b/lib/mayaUsd/render/mayaToHydra/renderOverrideUtils.h @@ -17,44 +17,46 @@ #define MTOH_VIEW_OVERRIDE_UTILS_H #include + #include PXR_NAMESPACE_OPEN_SCOPE -class HdMayaPreRender : public MHWRender::MSceneRender { +class HdMayaPreRender : public MHWRender::MSceneRender +{ public: explicit HdMayaPreRender(const MString& name) - : MHWRender::MSceneRender(name) { - auto* renderer = MHWRender::MRenderer::theRenderer(); + : MHWRender::MSceneRender(name) + { + auto* renderer = MHWRender::MRenderer::theRenderer(); const auto gradient = renderer->useGradient(); const auto color1 = renderer->clearColor(); const auto color2 = renderer->clearColor2(); - float c1[4] = {color1[0], color1[1], color1[2], 1.0f}; - float c2[4] = {color2[0], color2[1], color2[2], 1.0f}; + float c1[4] = { color1[0], color1[1], color1[2], 1.0f }; + float c2[4] = { color2[0], color2[1], color2[2], 1.0f }; mClearOperation.setClearColor(c1); mClearOperation.setClearColor2(c2); mClearOperation.setClearGradient(gradient); } - MSceneFilterOption renderFilterOverride() override { - return kRenderPreSceneUIItems; - } + MSceneFilterOption renderFilterOverride() override { return kRenderPreSceneUIItems; } - MHWRender::MClearOperation& clearOperation() override { - return mClearOperation; - } + MHWRender::MClearOperation& clearOperation() override { return mClearOperation; } }; -class HdMayaPostRender : public MHWRender::MSceneRender { +class HdMayaPostRender : public MHWRender::MSceneRender +{ public: explicit HdMayaPostRender(const MString& name) - : MHWRender::MSceneRender(name) { + : MHWRender::MSceneRender(name) + { mClearOperation.setMask(MHWRender::MClearOperation::kClearNone); } - MUint64 getObjectTypeExclusions() override { + MUint64 getObjectTypeExclusions() override + { // FIXME: // 1. kExcludePluginShapes is here so as to not re-draw UsdProxy shapes // ...but that means no plugin shapes would be drawn. @@ -63,21 +65,25 @@ class HdMayaPostRender : public MHWRender::MSceneRender { return MFrameContext::kExcludeMeshes | MFrameContext::kExcludePluginShapes; } - MSceneFilterOption renderFilterOverride() override { + MSceneFilterOption renderFilterOverride() override + { return MSceneFilterOption(kRenderShadedItems | kRenderPostSceneUIItems); } - MHWRender::MClearOperation& clearOperation() override { - return mClearOperation; - } + MHWRender::MClearOperation& clearOperation() override { return mClearOperation; } }; -class HdMayaRender : public MHWRender::MUserRenderOperation { +class HdMayaRender : public MHWRender::MUserRenderOperation +{ public: HdMayaRender(const MString& name, MtohRenderOverride* override) - : MHWRender::MUserRenderOperation(name), _override(override) {} + : MHWRender::MUserRenderOperation(name) + , _override(override) + { + } - MStatus execute(const MHWRender::MDrawContext& drawContext) override { + MStatus execute(const MHWRender::MDrawContext& drawContext) override + { return _override->Render(drawContext); } @@ -85,9 +91,11 @@ class HdMayaRender : public MHWRender::MUserRenderOperation { MtohRenderOverride* _override; }; -class HdMayaSetRenderGLState { +class HdMayaSetRenderGLState +{ public: - HdMayaSetRenderGLState() { + HdMayaSetRenderGLState() + { glGetIntegerv(GL_BLEND_SRC_ALPHA, &_oldBlendFunc); glGetIntegerv(GL_BLEND_EQUATION_RGB, &_oldBlendEquation); glGetBooleanv(GL_BLEND, &_oldBlend); @@ -101,13 +109,20 @@ class HdMayaSetRenderGLState { glBlendEquation(BLEND_EQUATION); } - if (_oldBlend != BLEND) { glEnable(GL_BLEND); } + if (_oldBlend != BLEND) { + glEnable(GL_BLEND); + } - if (_oldCullFace != CULL_FACE) { glDisable(GL_CULL_FACE); } + if (_oldCullFace != CULL_FACE) { + glDisable(GL_CULL_FACE); + } } - ~HdMayaSetRenderGLState() { - if (_oldBlend != BLEND) { glDisable(GL_BLEND); } + ~HdMayaSetRenderGLState() + { + if (_oldBlend != BLEND) { + glDisable(GL_BLEND); + } if (_oldBlendFunc != BLEND_FUNC) { glBlendFunc(GL_SRC_ALPHA, _oldBlendFunc); @@ -117,18 +132,20 @@ class HdMayaSetRenderGLState { glBlendEquation(_oldBlendEquation); } - if (_oldCullFace != CULL_FACE) { glEnable(GL_CULL_FACE); } + if (_oldCullFace != CULL_FACE) { + glEnable(GL_CULL_FACE); + } } private: // non-odr - constexpr static int BLEND_FUNC = GL_ONE_MINUS_SRC_ALPHA; - constexpr static int BLEND_EQUATION = GL_FUNC_ADD; + constexpr static int BLEND_FUNC = GL_ONE_MINUS_SRC_ALPHA; + constexpr static int BLEND_EQUATION = GL_FUNC_ADD; constexpr static GLboolean BLEND = GL_TRUE; constexpr static GLboolean CULL_FACE = GL_FALSE; - int _oldBlendFunc = BLEND_FUNC; - int _oldBlendEquation = BLEND_EQUATION; + int _oldBlendFunc = BLEND_FUNC; + int _oldBlendEquation = BLEND_EQUATION; GLboolean _oldBlend = BLEND; GLboolean _oldCullFace = CULL_FACE; }; diff --git a/lib/mayaUsd/render/mayaToHydra/shadingModeExporter.cpp b/lib/mayaUsd/render/mayaToHydra/shadingModeExporter.cpp index 6c0f142e3b..5838a033ff 100644 --- a/lib/mayaUsd/render/mayaToHydra/shadingModeExporter.cpp +++ b/lib/mayaUsd/render/mayaToHydra/shadingModeExporter.cpp @@ -13,15 +13,14 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include -#include -#include - +#include #include #include -#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE diff --git a/lib/mayaUsd/render/mayaToHydra/utils.cpp b/lib/mayaUsd/render/mayaToHydra/utils.cpp index 773da2786a..e0712e2138 100644 --- a/lib/mayaUsd/render/mayaToHydra/utils.cpp +++ b/lib/mayaUsd/render/mayaToHydra/utils.cpp @@ -15,27 +15,27 @@ // #include "utils.h" -#include - -#include - -#include "tokens.h" #include "renderGlobals.h" +#include "tokens.h" +#include #include #include +#include + PXR_NAMESPACE_OPEN_SCOPE namespace { std::pair -MtohInitializeRenderPlugins() { +MtohInitializeRenderPlugins() +{ using Storage = std::pair; static const Storage ret = []() -> Storage { HdRendererPluginRegistry& pluginRegistry = HdRendererPluginRegistry::GetInstance(); - HfPluginDescVector pluginDescs; + HfPluginDescVector pluginDescs; pluginRegistry.GetPluginDescs(&pluginDescs); Storage store; @@ -44,7 +44,7 @@ MtohInitializeRenderPlugins() { MtohRenderGlobals::OptionsPreamble(); for (const auto& pluginDesc : pluginDescs) { - const TfToken renderer = pluginDesc.id; + const TfToken renderer = pluginDesc.id; HdRendererPlugin* plugin = pluginRegistry.GetRendererPlugin(renderer); if (!plugin) { continue; @@ -54,16 +54,17 @@ MtohInitializeRenderPlugins() { if (pluginDesc.id == MtohTokens->HdStormRendererPlugin) GlfContextCaps::InitInstance(); - HdRenderDelegate* delegate = plugin->IsSupported() ? - plugin->CreateRenderDelegate() : nullptr; + HdRenderDelegate* delegate + = plugin->IsSupported() ? plugin->CreateRenderDelegate() : nullptr; // No 'delete plugin', should plugin be cached as well? if (!delegate) { continue; } - auto& rendererSettingDescriptors = store.second.emplace(renderer, - delegate->GetRenderSettingDescriptors()).first->second; + auto& rendererSettingDescriptors + = store.second.emplace(renderer, delegate->GetRenderSettingDescriptors()) + .first->second; // We only needed the delegate for the settings, so release plugin->DeleteRenderDelegate(delegate); @@ -72,13 +73,8 @@ MtohInitializeRenderPlugins() { store.first.emplace_back( renderer, - TfToken( - TfStringPrintf("mtohRenderOverride_%s", renderer.GetText()) - ), - TfToken( - TfStringPrintf("%s (Hydra)", pluginDesc.displayName.c_str()) - ) - ); + TfToken(TfStringPrintf("mtohRenderOverride_%s", renderer.GetText())), + TfToken(TfStringPrintf("%s (Hydra)", pluginDesc.displayName.c_str()))); MtohRenderGlobals::BuildOptionsMenu(store.first.back(), rendererSettingDescriptors); } @@ -90,25 +86,26 @@ MtohInitializeRenderPlugins() { return ret; } -} +} // namespace -std::string MtohGetRendererPluginDisplayName(const TfToken& id) { +std::string MtohGetRendererPluginDisplayName(const TfToken& id) +{ HfPluginDesc pluginDesc; - if (!TF_VERIFY(HdRendererPluginRegistry::GetInstance().GetPluginDesc( - id, &pluginDesc))) { + if (!TF_VERIFY(HdRendererPluginRegistry::GetInstance().GetPluginDesc(id, &pluginDesc))) { return {}; } return pluginDesc.displayName; } -const MtohRendererDescriptionVector& MtohGetRendererDescriptions() { +const MtohRendererDescriptionVector& MtohGetRendererDescriptions() +{ return MtohInitializeRenderPlugins().first; } -const MtohRendererSettings& MtohGetRendererSettings() { +const MtohRendererSettings& MtohGetRendererSettings() +{ return MtohInitializeRenderPlugins().second; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/mayaToHydra/utils.h b/lib/mayaUsd/render/mayaToHydra/utils.h index 469477a786..7f58cfe5e9 100644 --- a/lib/mayaUsd/render/mayaToHydra/utils.h +++ b/lib/mayaUsd/render/mayaToHydra/utils.h @@ -16,19 +16,23 @@ #ifndef MTOH_UTILS_H #define MTOH_UTILS_H -#include -#include - -#include #include #include +#include + +#include +#include PXR_NAMESPACE_OPEN_SCOPE -struct MtohRendererDescription { - MtohRendererDescription( - const TfToken& rn, const TfToken& on, const TfToken& dn) - : rendererName(rn), overrideName(on), displayName(dn) {} +struct MtohRendererDescription +{ + MtohRendererDescription(const TfToken& rn, const TfToken& on, const TfToken& dn) + : rendererName(rn) + , overrideName(on) + , displayName(dn) + { + } TfToken rendererName; TfToken overrideName; @@ -38,14 +42,12 @@ struct MtohRendererDescription { using MtohRendererDescriptionVector = std::vector; // Map from MtohRendererDescription::rendererName to it's a HdRenderSettingDescriptorList -using MtohRendererSettings = - std::unordered_map; +using MtohRendererSettings + = std::unordered_map; -std::string MtohGetRendererPluginDisplayName(const TfToken& id); +std::string MtohGetRendererPluginDisplayName(const TfToken& id); const MtohRendererDescriptionVector& MtohGetRendererDescriptions(); -const MtohRendererSettings& MtohGetRendererSettings(); - +const MtohRendererSettings& MtohGetRendererSettings(); PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/mayaToHydra/viewCommand.cpp b/lib/mayaUsd/render/mayaToHydra/viewCommand.cpp index 257a67ad05..0ee7584151 100644 --- a/lib/mayaUsd/render/mayaToHydra/viewCommand.cpp +++ b/lib/mayaUsd/render/mayaToHydra/viewCommand.cpp @@ -15,17 +15,16 @@ // #include "viewCommand.h" -#include -#include -#include - -#include - #include "renderGlobals.h" #include "renderOverride.h" -#include "renderOverride.h" #include "utils.h" +#include + +#include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE const MString MtohViewCmd::name("mtoh"); @@ -109,7 +108,8 @@ Debug flags: } // namespace -MSyntax MtohViewCmd::createSyntax() { +MSyntax MtohViewCmd::createSyntax() +{ MSyntax syntax; syntax.addFlag(_listRenderers, _listRenderersLong); @@ -138,17 +138,19 @@ MSyntax MtohViewCmd::createSyntax() { syntax.addFlag(_visibleOnly, _visibleOnlyLong); - syntax.addFlag(_sceneDelegateId, _sceneDelegateIdLong, MSyntax::kString, - MSyntax::kString); + syntax.addFlag(_sceneDelegateId, _sceneDelegateIdLong, MSyntax::kString, MSyntax::kString); return syntax; } -MStatus MtohViewCmd::doIt(const MArgList& args) { +MStatus MtohViewCmd::doIt(const MArgList& args) +{ MStatus status; MArgDatabase db(syntax(), args, &status); - if (!status) { return status; } + if (!status) { + return status; + } TfToken renderDelegateName; if (db.isFlagSet(_rendererId)) { @@ -166,14 +168,17 @@ MStatus MtohViewCmd::doIt(const MArgList& args) { appendToResult(plugin.rendererName.GetText()); // Want to return an empty list, not None - if (!isCurrentResultArray()) { setResult(MStringArray()); } + if (!isCurrentResultArray()) { + setResult(MStringArray()); + } } else if (db.isFlagSet(_listActiveRenderers)) { - for (const auto& renderer : - MtohRenderOverride::AllActiveRendererNames()) { + for (const auto& renderer : MtohRenderOverride::AllActiveRendererNames()) { appendToResult(renderer); } // Want to return an empty list, not None - if (!isCurrentResultArray()) { setResult(MStringArray()); } + if (!isCurrentResultArray()) { + setResult(MStringArray()); + } } else if (db.isFlagSet(_getRendererDisplayName)) { if (renderDelegateName.IsEmpty()) { return MS::kInvalidParameter; @@ -182,12 +187,13 @@ MStatus MtohViewCmd::doIt(const MArgList& args) { const auto dn = MtohGetRendererPluginDisplayName(renderDelegateName); setResult(MString(dn.c_str())); } else if (db.isFlagSet(_listDelegates)) { - for (const auto& delegate : - HdMayaDelegateRegistry::GetDelegateNames()) { + for (const auto& delegate : HdMayaDelegateRegistry::GetDelegateNames()) { appendToResult(delegate.GetText()); } // Want to return an empty list, not None - if (!isCurrentResultArray()) { setResult(MStringArray()); } + if (!isCurrentResultArray()) { + setResult(MStringArray()); + } } else if (db.isFlagSet(_help)) { MString helpText = _helpText; if (db.isFlagSet(_verbose)) { @@ -198,39 +204,41 @@ MStatus MtohViewCmd::doIt(const MArgList& args) { MGlobal::displayInfo(helpText); } else if (db.isFlagSet(_createRenderGlobals)) { bool userDefaults = db.isFlagSet(_userDefaultsId); - MtohRenderGlobals::CreateAttributes({renderDelegateName, true, userDefaults}); + MtohRenderGlobals::CreateAttributes({ renderDelegateName, true, userDefaults }); } else if (db.isFlagSet(_updateRenderGlobals)) { - MString attrFlag; + MString attrFlag; const bool storeUserSettings = true; if (db.getFlagArgument(_updateRenderGlobals, 0, attrFlag) == MS::kSuccess) { - bool userDefaults = db.isFlagSet(_userDefaultsId); + bool userDefaults = db.isFlagSet(_userDefaultsId); const TfToken attrName(attrFlag.asChar()); - auto& inst = MtohRenderGlobals::GlobalChanged({attrName, false, userDefaults}, storeUserSettings); + auto& inst = MtohRenderGlobals::GlobalChanged( + { attrName, false, userDefaults }, storeUserSettings); MtohRenderOverride::UpdateRenderGlobals(inst, attrName); return MS::kSuccess; } - MtohRenderOverride::UpdateRenderGlobals(MtohRenderGlobals::GetInstance(storeUserSettings), - renderDelegateName); + MtohRenderOverride::UpdateRenderGlobals( + MtohRenderGlobals::GetInstance(storeUserSettings), renderDelegateName); } else if (db.isFlagSet(_listRenderIndex)) { if (renderDelegateName.IsEmpty()) { return MS::kInvalidParameter; } - auto rprimPaths = MtohRenderOverride::RendererRprims( - renderDelegateName, db.isFlagSet(_visibleOnly)); + auto rprimPaths + = MtohRenderOverride::RendererRprims(renderDelegateName, db.isFlagSet(_visibleOnly)); for (auto& rprimPath : rprimPaths) { appendToResult(rprimPath.GetText()); } // Want to return an empty list, not None - if (!isCurrentResultArray()) { setResult(MStringArray()); } + if (!isCurrentResultArray()) { + setResult(MStringArray()); + } } else if (db.isFlagSet(_sceneDelegateId)) { if (renderDelegateName.IsEmpty()) { return MS::kInvalidParameter; } MString sceneDelegateName; - CHECK_MSTATUS_AND_RETURN_IT( - db.getFlagArgument(_sceneDelegateId, 0, sceneDelegateName)); + CHECK_MSTATUS_AND_RETURN_IT(db.getFlagArgument(_sceneDelegateId, 0, sceneDelegateName)); SdfPath delegateId = MtohRenderOverride::RendererSceneDelegateId( renderDelegateName, TfToken(sceneDelegateName.asChar())); diff --git a/lib/mayaUsd/render/mayaToHydra/viewCommand.h b/lib/mayaUsd/render/mayaToHydra/viewCommand.h index b6bf58fcfb..bd212277ac 100644 --- a/lib/mayaUsd/render/mayaToHydra/viewCommand.h +++ b/lib/mayaUsd/render/mayaToHydra/viewCommand.h @@ -16,15 +16,16 @@ #ifndef MTOH_CMD_H #define MTOH_CMD_H -#include - #include +#include + PXR_NAMESPACE_OPEN_SCOPE -class MtohViewCmd : public MPxCommand { +class MtohViewCmd : public MPxCommand +{ public: - static void* creator() { return new MtohViewCmd(); } + static void* creator() { return new MtohViewCmd(); } static MSyntax createSyntax(); static const MString name; diff --git a/lib/mayaUsd/render/px_vp20/glslProgram.cpp b/lib/mayaUsd/render/px_vp20/glslProgram.cpp index 7ee285f6e2..ac885d894f 100644 --- a/lib/mayaUsd/render/px_vp20/glslProgram.cpp +++ b/lib/mayaUsd/render/px_vp20/glslProgram.cpp @@ -19,15 +19,16 @@ #include "glslProgram.h" -#include - -#include #include #include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -PxrMayaGLSLProgram::PxrMayaGLSLProgram() : mProgramId(0) +PxrMayaGLSLProgram::PxrMayaGLSLProgram() + : mProgramId(0) { } @@ -43,10 +44,7 @@ PxrMayaGLSLProgram::~PxrMayaGLSLProgram() } } -bool -PxrMayaGLSLProgram::CompileShader( - const GLenum type, - const std::string& shaderSource) +bool PxrMayaGLSLProgram::CompileShader(const GLenum type, const std::string& shaderSource) { if (!glCreateProgram) { return false; @@ -58,27 +56,13 @@ PxrMayaGLSLProgram::CompileShader( const char* shaderType = NULL; switch (type) { - case GL_COMPUTE_SHADER: - shaderType = "GL_COMPUTE_SHADER"; - break; - case GL_VERTEX_SHADER: - shaderType = "GL_VERTEX_SHADER"; - break; - case GL_TESS_CONTROL_SHADER: - shaderType = "GL_TESS_CONTROL_SHADER"; - break; - case GL_TESS_EVALUATION_SHADER: - shaderType = "GL_TESS_EVALUATION_SHADER"; - break; - case GL_GEOMETRY_SHADER: - shaderType = "GL_GEOMETRY_SHADER"; - break; - case GL_FRAGMENT_SHADER: - shaderType = "GL_FRAGMENT_SHADER"; - break; - default: - TF_CODING_ERROR("Unsupported shader type %d\n", type); - return false; + case GL_COMPUTE_SHADER: shaderType = "GL_COMPUTE_SHADER"; break; + case GL_VERTEX_SHADER: shaderType = "GL_VERTEX_SHADER"; break; + case GL_TESS_CONTROL_SHADER: shaderType = "GL_TESS_CONTROL_SHADER"; break; + case GL_TESS_EVALUATION_SHADER: shaderType = "GL_TESS_EVALUATION_SHADER"; break; + case GL_GEOMETRY_SHADER: shaderType = "GL_GEOMETRY_SHADER"; break; + case GL_FRAGMENT_SHADER: shaderType = "GL_FRAGMENT_SHADER"; break; + default: TF_CODING_ERROR("Unsupported shader type %d\n", type); return false; } // Create a program if one does not already exist. @@ -90,10 +74,7 @@ PxrMayaGLSLProgram::CompileShader( const GLchar* shaderSources[1]; shaderSources[0] = shaderSource.c_str(); GLuint shader = glCreateShader(type); - glShaderSource(shader, - sizeof(shaderSources) / sizeof(const GLchar*), - shaderSources, - NULL); + glShaderSource(shader, sizeof(shaderSources) / sizeof(const GLchar*), shaderSources, NULL); glCompileShader(shader); // Verify that the shader compiled successfully. @@ -101,7 +82,7 @@ PxrMayaGLSLProgram::CompileShader( glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { std::string compileInfo; - GLint infoLogLength = 0; + GLint infoLogLength = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { char* infoLog = new char[infoLogLength]; @@ -110,9 +91,7 @@ PxrMayaGLSLProgram::CompileShader( delete[] infoLog; } - TF_WARN("Failed to compile shader type %s: %s", - shaderType, - compileInfo.c_str()); + TF_WARN("Failed to compile shader type %s: %s", shaderType, compileInfo.c_str()); return false; } @@ -125,8 +104,7 @@ PxrMayaGLSLProgram::CompileShader( return true; } -bool -PxrMayaGLSLProgram::Link() +bool PxrMayaGLSLProgram::Link() { if (!glLinkProgram) { return false; @@ -144,7 +122,7 @@ PxrMayaGLSLProgram::Link() glGetProgramiv(mProgramId, GL_LINK_STATUS, &success); if (!success) { std::string linkInfo; - GLint infoLogLength = 0; + GLint infoLogLength = 0; glGetProgramiv(mProgramId, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { char* infoLog = new char[infoLogLength]; @@ -160,8 +138,7 @@ PxrMayaGLSLProgram::Link() return true; } -bool -PxrMayaGLSLProgram::Validate() const +bool PxrMayaGLSLProgram::Validate() const { if (!glValidateProgram) { return false; @@ -177,7 +154,7 @@ PxrMayaGLSLProgram::Validate() const glGetProgramiv(mProgramId, GL_VALIDATE_STATUS, &success); if (!success) { std::string validateInfo; - GLint infoLogLength = 0; + GLint infoLogLength = 0; glGetProgramiv(mProgramId, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { char* infoLog = new char[infoLogLength]; @@ -186,13 +163,11 @@ PxrMayaGLSLProgram::Validate() const delete[] infoLog; } - TF_WARN("Validation failed for shader program: %s", - validateInfo.c_str()); + TF_WARN("Validation failed for shader program: %s", validateInfo.c_str()); return false; } return true; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/px_vp20/glslProgram.h b/lib/mayaUsd/render/px_vp20/glslProgram.h index 9b8b867799..b2c35ee159 100644 --- a/lib/mayaUsd/render/px_vp20/glslProgram.h +++ b/lib/mayaUsd/render/px_vp20/glslProgram.h @@ -19,12 +19,12 @@ #ifndef __PX_VP20_GLSL_PROGRAM_H__ #define __PX_VP20_GLSL_PROGRAM_H__ -#include +#include -#include #include +#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -35,35 +35,31 @@ PXR_NAMESPACE_OPEN_SCOPE /// class PxrMayaGLSLProgram { - public: - MAYAUSD_CORE_PUBLIC - PxrMayaGLSLProgram(); - MAYAUSD_CORE_PUBLIC - virtual ~PxrMayaGLSLProgram(); +public: + MAYAUSD_CORE_PUBLIC + PxrMayaGLSLProgram(); + MAYAUSD_CORE_PUBLIC + virtual ~PxrMayaGLSLProgram(); - /// Compile a shader of type \p type with the given \p source. - MAYAUSD_CORE_PUBLIC - bool CompileShader(const GLenum type, const std::string& source); + /// Compile a shader of type \p type with the given \p source. + MAYAUSD_CORE_PUBLIC + bool CompileShader(const GLenum type, const std::string& source); - /// Link the compiled shaders together. - MAYAUSD_CORE_PUBLIC - bool Link(); + /// Link the compiled shaders together. + MAYAUSD_CORE_PUBLIC + bool Link(); - /// Validate whether this program is valid in the current context. - MAYAUSD_CORE_PUBLIC - bool Validate() const; + /// Validate whether this program is valid in the current context. + MAYAUSD_CORE_PUBLIC + bool Validate() const; - /// Get the ID of the OpenGL program object. - GLuint GetProgramId() const { - return mProgramId; - }; + /// Get the ID of the OpenGL program object. + GLuint GetProgramId() const { return mProgramId; }; - private: - GLuint mProgramId; +private: + GLuint mProgramId; }; - PXR_NAMESPACE_CLOSE_SCOPE - -#endif // __PX_VP20_GLSL_PROGRAM_H__ +#endif // __PX_VP20_GLSL_PROGRAM_H__ diff --git a/lib/mayaUsd/render/px_vp20/utils.cpp b/lib/mayaUsd/render/px_vp20/utils.cpp index c90136da97..74ead8e1da 100644 --- a/lib/mayaUsd/render/px_vp20/utils.cpp +++ b/lib/mayaUsd/render/px_vp20/utils.cpp @@ -19,10 +19,20 @@ #include "utils.h" -#include -#include -#include -#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -43,33 +53,21 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE /* static */ -bool -px_vp20Utils::setupLightingGL(const MHWRender::MDrawContext& context) +bool px_vp20Utils::setupLightingGL(const MHWRender::MDrawContext& context) { MStatus status; // Take into account only the 8 lights supported by the basic // OpenGL profile. - const unsigned int nbLights = - std::min(context.numberOfActiveLights(&status), 8u); + const unsigned int nbLights = std::min(context.numberOfActiveLights(&status), 8u); if (status != MStatus::kSuccess) { return false; } @@ -80,8 +78,7 @@ px_vp20Utils::setupLightingGL(const MHWRender::MDrawContext& context) // Lights are specified in world space and needs to be // converted to view space. - const MMatrix worldToView = - context.getMatrix(MHWRender::MFrameContext::kViewMtx, &status); + const MMatrix worldToView = context.getMatrix(MHWRender::MFrameContext::kViewMtx, &status); if (status != MStatus::kSuccess) { return false; } @@ -97,10 +94,10 @@ px_vp20Utils::setupLightingGL(const MHWRender::MDrawContext& context) glEnable(GL_NORMALIZE); { - const GLfloat ambient[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; + const GLfloat ambient[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; const GLfloat specular[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient); + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient); @@ -109,20 +106,14 @@ px_vp20Utils::setupLightingGL(const MHWRender::MDrawContext& context) for (unsigned int i = 0u; i < nbLights; ++i) { MFloatVector direction; - float intensity; - MColor color; - bool hasDirection; - bool hasPosition; + float intensity; + MColor color; + bool hasDirection; + bool hasPosition; MFloatPointArray positions; status = context.getLightInformation( - i, - positions, - direction, - intensity, - color, - hasDirection, - hasPosition); + i, positions, direction, intensity, color, hasDirection, hasPosition); if (status != MStatus::kSuccess) { return false; } @@ -133,20 +124,10 @@ px_vp20Utils::setupLightingGL(const MHWRender::MDrawContext& context) if (hasPosition) { // Assumes a Maya Spot Light! const GLfloat ambient[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; - const GLfloat diffuse[4] = { - intensity * color[0], - intensity * color[1], - intensity * color[2], - 1.0f }; - const GLfloat pos[4] = { - position[0], - position[1], - position[2], - 1.0f }; - const GLfloat dir[3] = { - direction[0], - direction[1], - direction[2] }; + const GLfloat diffuse[4] + = { intensity * color[0], intensity * color[1], intensity * color[2], 1.0f }; + const GLfloat pos[4] = { position[0], position[1], position[2], 1.0f }; + const GLfloat dir[3] = { direction[0], direction[1], direction[2] }; glLightfv(GL_LIGHT0 + i, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0 + i, GL_DIFFUSE, diffuse); @@ -156,53 +137,33 @@ px_vp20Utils::setupLightingGL(const MHWRender::MDrawContext& context) // Maya's default values for spot lights. glLightf(GL_LIGHT0 + i, GL_SPOT_EXPONENT, 0.0); glLightf(GL_LIGHT0 + i, GL_SPOT_CUTOFF, 20.0); - } - else { + } else { // Assumes a Maya Directional Light! const GLfloat ambient[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; - const GLfloat diffuse[4] = { - intensity * color[0], - intensity * color[1], - intensity * color[2], - 1.0f }; - const GLfloat pos[4] = { - -direction[0], - -direction[1], - -direction[2], - 0.0f }; + const GLfloat diffuse[4] + = { intensity * color[0], intensity * color[1], intensity * color[2], 1.0f }; + const GLfloat pos[4] = { -direction[0], -direction[1], -direction[2], 0.0f }; glLightfv(GL_LIGHT0 + i, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0 + i, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT0 + i, GL_POSITION, pos); glLightf(GL_LIGHT0 + i, GL_SPOT_CUTOFF, 180.0f); } - } - else if (hasPosition) { + } else if (hasPosition) { // Assumes a Maya Point Light! const GLfloat ambient[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; - const GLfloat diffuse[4] = { - intensity * color[0], - intensity * color[1], - intensity * color[2], - 1.0f }; - const GLfloat pos[4] = { - position[0], - position[1], - position[2], - 1.0f }; + const GLfloat diffuse[4] + = { intensity * color[0], intensity * color[1], intensity * color[2], 1.0f }; + const GLfloat pos[4] = { position[0], position[1], position[2], 1.0f }; glLightfv(GL_LIGHT0 + i, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0 + i, GL_DIFFUSE, diffuse); glLightfv(GL_LIGHT0 + i, GL_POSITION, pos); glLightf(GL_LIGHT0 + i, GL_SPOT_CUTOFF, 180.0f); - } - else { + } else { // Assumes a Maya Ambient Light! - const GLfloat ambient[4] = { - intensity * color[0], - intensity * color[1], - intensity * color[2], - 1.0f }; + const GLfloat ambient[4] + = { intensity * color[0], intensity * color[1], intensity * color[2], 1.0f }; const GLfloat diffuse[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; const GLfloat pos[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; @@ -223,15 +184,13 @@ px_vp20Utils::setupLightingGL(const MHWRender::MDrawContext& context) } /* static */ -void -px_vp20Utils::unsetLightingGL(const MHWRender::MDrawContext& context) +void px_vp20Utils::unsetLightingGL(const MHWRender::MDrawContext& context) { MStatus status; // Take into account only the 8 lights supported by the basic // OpenGL profile. - const unsigned int nbLights = - std::min(context.numberOfActiveLights(&status), 8u); + const unsigned int nbLights = std::min(context.numberOfActiveLights(&status), 8u); if (status != MStatus::kSuccess || nbLights == 0u) { return; } @@ -250,8 +209,7 @@ px_vp20Utils::unsetLightingGL(const MHWRender::MDrawContext& context) const GLfloat spec[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; glLightfv(GL_LIGHT0 + i, GL_SPECULAR, spec); - } - else { + } else { const GLfloat diffuse[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; glLightfv(GL_LIGHT0 + i, GL_DIFFUSE, diffuse); @@ -283,12 +241,8 @@ px_vp20Utils::unsetLightingGL(const MHWRender::MDrawContext& context) glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0); } -static -bool -_GetLightingParam( - const MIntArray& intValues, - const MFloatArray& floatValues, - bool& paramValue) +static bool +_GetLightingParam(const MIntArray& intValues, const MFloatArray& floatValues, bool& paramValue) { bool gotParamValue = false; @@ -303,12 +257,8 @@ _GetLightingParam( return gotParamValue; } -static -bool -_GetLightingParam( - const MIntArray& intValues, - const MFloatArray& floatValues, - int& paramValue) +static bool +_GetLightingParam(const MIntArray& intValues, const MFloatArray& floatValues, int& paramValue) { bool gotParamValue = false; @@ -320,12 +270,8 @@ _GetLightingParam( return gotParamValue; } -static -bool -_GetLightingParam( - const MIntArray& intValues, - const MFloatArray& floatValues, - float& paramValue) +static bool +_GetLightingParam(const MIntArray& intValues, const MFloatArray& floatValues, float& paramValue) { bool gotParamValue = false; @@ -337,12 +283,8 @@ _GetLightingParam( return gotParamValue; } -static -bool -_GetLightingParam( - const MIntArray& intValues, - const MFloatArray& floatValues, - GfVec2f& paramValue) +static bool +_GetLightingParam(const MIntArray& intValues, const MFloatArray& floatValues, GfVec2f& paramValue) { bool gotParamValue = false; @@ -359,12 +301,8 @@ _GetLightingParam( return gotParamValue; } -static -bool -_GetLightingParam( - const MIntArray& intValues, - const MFloatArray& floatValues, - GfVec3f& paramValue) +static bool +_GetLightingParam(const MIntArray& intValues, const MFloatArray& floatValues, GfVec3f& paramValue) { bool gotParamValue = false; @@ -383,12 +321,8 @@ _GetLightingParam( return gotParamValue; } -static -bool -_GetLightingParam( - const MIntArray& intValues, - const MFloatArray& floatValues, - GfVec4f& paramValue) +static bool +_GetLightingParam(const MIntArray& intValues, const MFloatArray& floatValues, GfVec4f& paramValue) { bool gotParamValue = false; @@ -415,21 +349,17 @@ _GetLightingParam( /* static */ GlfSimpleLightingContextRefPtr -px_vp20Utils::GetLightingContextFromDrawContext( - const MHWRender::MDrawContext& context) +px_vp20Utils::GetLightingContextFromDrawContext(const MHWRender::MDrawContext& context) { const GfVec4f blackColor(0.0f, 0.0f, 0.0f, 1.0f); const GfVec4f whiteColor(1.0f, 1.0f, 1.0f, 1.0f); - GlfSimpleLightingContextRefPtr lightingContext = - GlfSimpleLightingContext::New(); + GlfSimpleLightingContextRefPtr lightingContext = GlfSimpleLightingContext::New(); MStatus status; - const unsigned int numMayaLights = - context.numberOfActiveLights( - MHWRender::MDrawContext::kFilteredToLightLimit, - &status); + const unsigned int numMayaLights + = context.numberOfActiveLights(MHWRender::MDrawContext::kFilteredToLightLimit, &status); if (status != MS::kSuccess || numMayaLights < 1u) { return lightingContext; } @@ -441,22 +371,20 @@ px_vp20Utils::GetLightingContextFromDrawContext( viewDirectionAlongNegZ = true; } - const MMatrix worldToViewMat = - context.getMatrix(MHWRender::MFrameContext::kViewMtx, &status); + const MMatrix worldToViewMat = context.getMatrix(MHWRender::MFrameContext::kViewMtx, &status); CHECK_MSTATUS_AND_RETURN(status, lightingContext); - const MMatrix projectionMat = - context.getMatrix(MHWRender::MFrameContext::kProjectionMtx, &status); + const MMatrix projectionMat + = context.getMatrix(MHWRender::MFrameContext::kProjectionMtx, &status); CHECK_MSTATUS_AND_RETURN(status, lightingContext); - lightingContext->SetCamera(GfMatrix4d(worldToViewMat.matrix), - GfMatrix4d(projectionMat.matrix)); + lightingContext->SetCamera(GfMatrix4d(worldToViewMat.matrix), GfMatrix4d(projectionMat.matrix)); GlfSimpleLightVector lights; for (unsigned int i = 0u; i < numMayaLights; ++i) { - MHWRender::MLightParameterInformation* mayaLightParamInfo = - context.getLightParameterInformation(i); + MHWRender::MLightParameterInformation* mayaLightParamInfo + = context.getLightParameterInformation(i); if (!mayaLightParamInfo) { continue; } @@ -477,12 +405,12 @@ px_vp20Utils::GetLightingContextFromDrawContext( lightDirection[2] = 1.0f; } - float lightIntensity = 1.0f; - GfVec4f lightColor = blackColor; - bool lightEmitsDiffuse = true; - bool lightEmitsSpecular = false; - float lightDecayRate = 0.0f; - float lightDropoff = 0.0f; + float lightIntensity = 1.0f; + GfVec4f lightColor = blackColor; + bool lightEmitsDiffuse = true; + bool lightEmitsSpecular = false; + float lightDecayRate = 0.0f; + float lightDropoff = 0.0f; // The cone angle is 180 degrees by default. GfVec2f lightCosineConeAngle(-1.0f); GfMatrix4d lightShadowMatrix(1.0); @@ -503,105 +431,105 @@ px_vp20Utils::GetLightingContextFromDrawContext( for (unsigned int paramIndex = 0u; paramIndex < paramNames.length(); ++paramIndex) { const MString paramName = paramNames[paramIndex]; - const MHWRender::MLightParameterInformation::ParameterType paramType = - mayaLightParamInfo->parameterType(paramName); - const MHWRender::MLightParameterInformation::StockParameterSemantic paramSemantic = - mayaLightParamInfo->parameterSemantic(paramName); + const MHWRender::MLightParameterInformation::ParameterType paramType + = mayaLightParamInfo->parameterType(paramName); + const MHWRender::MLightParameterInformation::StockParameterSemantic paramSemantic + = mayaLightParamInfo->parameterSemantic(paramName); - MIntArray intValues; + MIntArray intValues; MFloatArray floatValues; - MMatrix matrixValue; + MMatrix matrixValue; switch (paramType) { - case MHWRender::MLightParameterInformation::kBoolean: - case MHWRender::MLightParameterInformation::kInteger: - mayaLightParamInfo->getParameter(paramName, intValues); - break; - case MHWRender::MLightParameterInformation::kFloat: - case MHWRender::MLightParameterInformation::kFloat2: - case MHWRender::MLightParameterInformation::kFloat3: - case MHWRender::MLightParameterInformation::kFloat4: - mayaLightParamInfo->getParameter(paramName, floatValues); - break; - case MHWRender::MLightParameterInformation::kFloat4x4Row: - mayaLightParamInfo->getParameter(paramName, matrixValue); - break; - case MHWRender::MLightParameterInformation::kFloat4x4Col: - mayaLightParamInfo->getParameter(paramName, matrixValue); - // Gf matrices are row-major. - matrixValue = matrixValue.transpose(); - break; - default: - // Unsupported paramType. - continue; - break; + case MHWRender::MLightParameterInformation::kBoolean: + case MHWRender::MLightParameterInformation::kInteger: + mayaLightParamInfo->getParameter(paramName, intValues); + break; + case MHWRender::MLightParameterInformation::kFloat: + case MHWRender::MLightParameterInformation::kFloat2: + case MHWRender::MLightParameterInformation::kFloat3: + case MHWRender::MLightParameterInformation::kFloat4: + mayaLightParamInfo->getParameter(paramName, floatValues); + break; + case MHWRender::MLightParameterInformation::kFloat4x4Row: + mayaLightParamInfo->getParameter(paramName, matrixValue); + break; + case MHWRender::MLightParameterInformation::kFloat4x4Col: + mayaLightParamInfo->getParameter(paramName, matrixValue); + // Gf matrices are row-major. + matrixValue = matrixValue.transpose(); + break; + default: + // Unsupported paramType. + continue; + break; } switch (paramSemantic) { - case MHWRender::MLightParameterInformation::kLightEnabled: - _GetLightingParam(intValues, floatValues, lightEnabled); - break; - case MHWRender::MLightParameterInformation::kWorldPosition: { - GfVec4f tempPosition(0.0f, 0.0f, 0.0f, 1.0f); - if (_GetLightingParam(intValues, floatValues, tempPosition)) { - lightPosition += tempPosition; - ++lightNumPositions; - } - break; + case MHWRender::MLightParameterInformation::kLightEnabled: + _GetLightingParam(intValues, floatValues, lightEnabled); + break; + case MHWRender::MLightParameterInformation::kWorldPosition: { + GfVec4f tempPosition(0.0f, 0.0f, 0.0f, 1.0f); + if (_GetLightingParam(intValues, floatValues, tempPosition)) { + lightPosition += tempPosition; + ++lightNumPositions; + } + break; + } + case MHWRender::MLightParameterInformation::kWorldDirection: + if (_GetLightingParam(intValues, floatValues, lightDirection)) { + lightHasDirection = true; } - case MHWRender::MLightParameterInformation::kWorldDirection: - if (_GetLightingParam(intValues, floatValues, lightDirection)) { - lightHasDirection = true; - } - break; - case MHWRender::MLightParameterInformation::kIntensity: - _GetLightingParam(intValues, floatValues, lightIntensity); - break; - case MHWRender::MLightParameterInformation::kColor: - _GetLightingParam(intValues, floatValues, lightColor); - break; - case MHWRender::MLightParameterInformation::kEmitsDiffuse: - _GetLightingParam(intValues, floatValues, lightEmitsDiffuse); - break; - case MHWRender::MLightParameterInformation::kEmitsSpecular: - _GetLightingParam(intValues, floatValues, lightEmitsSpecular); - break; - case MHWRender::MLightParameterInformation::kDecayRate: - _GetLightingParam(intValues, floatValues, lightDecayRate); - break; - case MHWRender::MLightParameterInformation::kDropoff: - _GetLightingParam(intValues, floatValues, lightDropoff); - break; - case MHWRender::MLightParameterInformation::kCosConeAngle: - _GetLightingParam(intValues, floatValues, lightCosineConeAngle); - break; - case MHWRender::MLightParameterInformation::kShadowBias: - _GetLightingParam(intValues, floatValues, lightShadowBias); - // XXX: Remap the kShadowBias value back into the light's - // bias attribute value so it can be used by Hydra. - // Maya's default value for the "Bias" attribute on lights - // is 0.001, but that value gets reported here as 0.0022. - // When the attribute is set to -1.0, 0.0, or 1.0, it is - // reported back to us by the MLightParameterInformation as - // -0.198, 0.002, and 0.202, respectively. - lightShadowBias = (lightShadowBias - 0.002f) / 0.2f; - break; - case MHWRender::MLightParameterInformation::kShadowMapSize: - _GetLightingParam(intValues, floatValues, lightShadowResolution); - break; - case MHWRender::MLightParameterInformation::kShadowViewProj: - lightShadowMatrix.Set(matrixValue.matrix); - break; - case MHWRender::MLightParameterInformation::kGlobalShadowOn: - _GetLightingParam(intValues, floatValues, globalShadowOn); - break; - case MHWRender::MLightParameterInformation::kShadowOn: - _GetLightingParam(intValues, floatValues, lightShadowOn); - break; - default: - // Unsupported paramSemantic. - continue; - break; + break; + case MHWRender::MLightParameterInformation::kIntensity: + _GetLightingParam(intValues, floatValues, lightIntensity); + break; + case MHWRender::MLightParameterInformation::kColor: + _GetLightingParam(intValues, floatValues, lightColor); + break; + case MHWRender::MLightParameterInformation::kEmitsDiffuse: + _GetLightingParam(intValues, floatValues, lightEmitsDiffuse); + break; + case MHWRender::MLightParameterInformation::kEmitsSpecular: + _GetLightingParam(intValues, floatValues, lightEmitsSpecular); + break; + case MHWRender::MLightParameterInformation::kDecayRate: + _GetLightingParam(intValues, floatValues, lightDecayRate); + break; + case MHWRender::MLightParameterInformation::kDropoff: + _GetLightingParam(intValues, floatValues, lightDropoff); + break; + case MHWRender::MLightParameterInformation::kCosConeAngle: + _GetLightingParam(intValues, floatValues, lightCosineConeAngle); + break; + case MHWRender::MLightParameterInformation::kShadowBias: + _GetLightingParam(intValues, floatValues, lightShadowBias); + // XXX: Remap the kShadowBias value back into the light's + // bias attribute value so it can be used by Hydra. + // Maya's default value for the "Bias" attribute on lights + // is 0.001, but that value gets reported here as 0.0022. + // When the attribute is set to -1.0, 0.0, or 1.0, it is + // reported back to us by the MLightParameterInformation as + // -0.198, 0.002, and 0.202, respectively. + lightShadowBias = (lightShadowBias - 0.002f) / 0.2f; + break; + case MHWRender::MLightParameterInformation::kShadowMapSize: + _GetLightingParam(intValues, floatValues, lightShadowResolution); + break; + case MHWRender::MLightParameterInformation::kShadowViewProj: + lightShadowMatrix.Set(matrixValue.matrix); + break; + case MHWRender::MLightParameterInformation::kGlobalShadowOn: + _GetLightingParam(intValues, floatValues, globalShadowOn); + break; + case MHWRender::MLightParameterInformation::kShadowOn: + _GetLightingParam(intValues, floatValues, lightShadowOn); + break; + default: + // Unsupported paramSemantic. + continue; + break; } if (!lightEnabled) { @@ -700,7 +628,7 @@ px_vp20Utils::GetLightingContextFromDrawContext( light.SetSpotFalloff(lightFalloff); light.SetAttenuation(lightAttenuation); #if HDX_API_VERSION >= 6 - light.SetShadowMatrices(std::vector(1,lightShadowMatrix)); + light.SetShadowMatrices(std::vector(1, lightShadowMatrix)); #else light.SetShadowMatrix(lightShadowMatrix); #endif @@ -731,14 +659,10 @@ px_vp20Utils::GetLightingContextFromDrawContext( } /* static */ -bool -px_vp20Utils::GetViewFromDrawContext( - const MHWRender::MDrawContext& context, - M3dView& view) +bool px_vp20Utils::GetViewFromDrawContext(const MHWRender::MDrawContext& context, M3dView& view) { MString modelPanel; - if (context.renderingDestination(modelPanel) == - MHWRender::MFrameContext::k3dViewport) { + if (context.renderingDestination(modelPanel) == MHWRender::MFrameContext::k3dViewport) { if (M3dView::getM3dViewFromModelPanel(modelPanel, view)) { return true; } @@ -748,12 +672,11 @@ px_vp20Utils::GetViewFromDrawContext( } /* static */ -bool -px_vp20Utils::RenderBoundingBox( - const MBoundingBox& bounds, - const GfVec4f& color, - const MMatrix& worldViewMat, - const MMatrix& projectionMat) +bool px_vp20Utils::RenderBoundingBox( + const MBoundingBox& bounds, + const GfVec4f& color, + const MMatrix& worldViewMat, + const MMatrix& projectionMat) { // Create a transformation matrix from the bounding box's center and // dimensions. @@ -762,19 +685,18 @@ px_vp20Utils::RenderBoundingBox( const double scales[3] = { bounds.width(), bounds.height(), bounds.depth() }; bboxTransformMatrix.setScale(scales, MSpace::kTransform); return RenderWireCubes( - { GfMatrix4f(bboxTransformMatrix.asMatrix().matrix) }, - color, - GfMatrix4d(worldViewMat.matrix), - GfMatrix4d(projectionMat.matrix)); + { GfMatrix4f(bboxTransformMatrix.asMatrix().matrix) }, + color, + GfMatrix4d(worldViewMat.matrix), + GfMatrix4d(projectionMat.matrix)); } /* static */ -bool -px_vp20Utils::RenderWireCubes( - const std::vector& cubeXforms, - const GfVec4f& color, - const GfMatrix4d& worldViewMat, - const GfMatrix4d& projectionMat) +bool px_vp20Utils::RenderWireCubes( + const std::vector& cubeXforms, + const GfVec4f& color, + const GfMatrix4d& worldViewMat, + const GfMatrix4d& projectionMat) { if (cubeXforms.empty()) { return true; @@ -842,14 +764,12 @@ void main() PxrMayaGLSLProgram renderBoundsProgram; - if (!renderBoundsProgram.CompileShader(GL_VERTEX_SHADER, - vertexShaderSource)) { + if (!renderBoundsProgram.CompileShader(GL_VERTEX_SHADER, vertexShaderSource)) { MGlobal::displayError("Failed to compile bounding box vertex shader"); return false; } - if (!renderBoundsProgram.CompileShader(GL_FRAGMENT_SHADER, - fragmentShaderSource)) { + if (!renderBoundsProgram.CompileShader(GL_FRAGMENT_SHADER, fragmentShaderSource)) { MGlobal::displayError("Failed to compile bounding box fragment shader"); return false; } @@ -874,10 +794,12 @@ void main() // Populate the shader variables. GfMatrix4f vpMatrix(worldViewMat * projectionMat); - GLuint vpMatrixLoc = glGetUniformLocation(renderBoundsProgramId, "vpMatrix"); - glUniformMatrix4fv(vpMatrixLoc, 1, - GL_TRUE, // transpose - vpMatrix.data()); + GLuint vpMatrixLoc = glGetUniformLocation(renderBoundsProgramId, "vpMatrix"); + glUniformMatrix4fv( + vpMatrixLoc, + 1, + GL_TRUE, // transpose + vpMatrix.data()); // Populate the color GLuint colorLocation = glGetUniformLocation(renderBoundsProgramId, "color"); @@ -891,13 +813,13 @@ void main() // since we're copying these directly from GfMatrix4f, we need to // transpose() them in the shader. const GLuint cubeXformLoc = glGetAttribLocation(renderBoundsProgramId, "cubeXformT"); - glBufferData(GL_ARRAY_BUFFER, - sizeof(GfMatrix4f) * numCubes, cubeXforms.data(), GL_DYNAMIC_DRAW); + glBufferData( + GL_ARRAY_BUFFER, sizeof(GfMatrix4f) * numCubes, cubeXforms.data(), GL_DYNAMIC_DRAW); for (size_t r = 0; r < 4; r++) { GLuint loc = cubeXformLoc + r; glEnableVertexAttribArray(loc); - glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, sizeof(GfMatrix4f), - (char*)(sizeof(float)*4*r)); + glVertexAttribPointer( + loc, 4, GL_FLOAT, GL_FALSE, sizeof(GfMatrix4f), (char*)(sizeof(float) * 4 * r)); glVertexAttribDivisor(loc, 1); } @@ -905,10 +827,7 @@ void main() GLuint cubeLinesVBO; glGenBuffers(1, &cubeLinesVBO); glBindBuffer(GL_ARRAY_BUFFER, cubeLinesVBO); - glBufferData(GL_ARRAY_BUFFER, - sizeof(cubeLineVertices), - cubeLineVertices, - GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(cubeLineVertices), cubeLineVertices, GL_STATIC_DRAW); const GLuint positionLocation = glGetAttribLocation(renderBoundsProgramId, "position"); glEnableVertexAttribArray(positionLocation); glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); @@ -933,52 +852,42 @@ void main() } /* static */ -bool -px_vp20Utils::GetSelectionMatrices( - const MHWRender::MSelectionInfo& selectionInfo, - const MHWRender::MDrawContext& context, - GfMatrix4d& viewMatrix, - GfMatrix4d& projectionMatrix) +bool px_vp20Utils::GetSelectionMatrices( + const MHWRender::MSelectionInfo& selectionInfo, + const MHWRender::MDrawContext& context, + GfMatrix4d& viewMatrix, + GfMatrix4d& projectionMatrix) { MStatus status; - const MMatrix viewMat = - context.getMatrix(MHWRender::MFrameContext::kViewMtx, &status); + const MMatrix viewMat = context.getMatrix(MHWRender::MFrameContext::kViewMtx, &status); CHECK_MSTATUS_AND_RETURN(status, false); - MMatrix projectionMat = - context.getMatrix(MHWRender::MFrameContext::kProjectionMtx, &status); + MMatrix projectionMat = context.getMatrix(MHWRender::MFrameContext::kProjectionMtx, &status); CHECK_MSTATUS_AND_RETURN(status, false); int viewportOriginX; int viewportOriginY; int viewportWidth; int viewportHeight; - status = context.getViewportDimensions(viewportOriginX, - viewportOriginY, - viewportWidth, - viewportHeight); + status = context.getViewportDimensions( + viewportOriginX, viewportOriginY, viewportWidth, viewportHeight); CHECK_MSTATUS_AND_RETURN(status, false); unsigned int selectRectX; unsigned int selectRectY; unsigned int selectRectWidth; unsigned int selectRectHeight; - status = selectionInfo.selectRect(selectRectX, - selectRectY, - selectRectWidth, - selectRectHeight); + status = selectionInfo.selectRect(selectRectX, selectRectY, selectRectWidth, selectRectHeight); CHECK_MSTATUS_AND_RETURN(status, false); MMatrix selectionMatrix; selectionMatrix[0][0] = (double)viewportWidth / (double)selectRectWidth; selectionMatrix[1][1] = (double)viewportHeight / (double)selectRectHeight; - selectionMatrix[3][0] = - ((double)viewportWidth - (double)(selectRectX * 2 + selectRectWidth)) / - (double)selectRectWidth; - selectionMatrix[3][1] = - ((double)viewportHeight - (double)(selectRectY * 2 + selectRectHeight)) / - (double)selectRectHeight; + selectionMatrix[3][0] = ((double)viewportWidth - (double)(selectRectX * 2 + selectRectWidth)) + / (double)selectRectWidth; + selectionMatrix[3][1] = ((double)viewportHeight - (double)(selectRectY * 2 + selectRectHeight)) + / (double)selectRectHeight; projectionMat *= selectionMatrix; @@ -989,10 +898,7 @@ px_vp20Utils::GetSelectionMatrices( } /* static */ -void -px_vp20Utils::OutputDisplayStyleToStream( - const unsigned int displayStyle, - std::ostream& stream) +void px_vp20Utils::OutputDisplayStyleToStream(const unsigned int displayStyle, std::ostream& stream) { std::vector styleComponents; @@ -1040,71 +946,39 @@ px_vp20Utils::OutputDisplayStyleToStream( } /* static */ -void -px_vp20Utils::OutputDisplayStatusToStream( - const MHWRender::DisplayStatus displayStatus, - std::ostream& stream) +void px_vp20Utils::OutputDisplayStatusToStream( + const MHWRender::DisplayStatus displayStatus, + std::ostream& stream) { switch (displayStatus) { - case MHWRender::kActive: - stream << "kActive"; - break; - case MHWRender::kLive: - stream << "kLive"; - break; - case MHWRender::kDormant: - stream << "kDormant"; - break; - case MHWRender::kInvisible: - stream << "kInvisible"; - break; - case MHWRender::kHilite: - stream << "kHilite"; - break; - case MHWRender::kTemplate: - stream << "kTemplate"; - break; - case MHWRender::kActiveTemplate: - stream << "kActiveTemplate"; - break; - case MHWRender::kActiveComponent: - stream << "kActiveComponent"; - break; - case MHWRender::kLead: - stream << "kLead"; - break; - case MHWRender::kIntermediateObject: - stream << "kIntermediateObject"; - break; - case MHWRender::kActiveAffected: - stream << "kActiveAffected"; - break; - case MHWRender::kNoStatus: - stream << "kNoStatus"; - break; + case MHWRender::kActive: stream << "kActive"; break; + case MHWRender::kLive: stream << "kLive"; break; + case MHWRender::kDormant: stream << "kDormant"; break; + case MHWRender::kInvisible: stream << "kInvisible"; break; + case MHWRender::kHilite: stream << "kHilite"; break; + case MHWRender::kTemplate: stream << "kTemplate"; break; + case MHWRender::kActiveTemplate: stream << "kActiveTemplate"; break; + case MHWRender::kActiveComponent: stream << "kActiveComponent"; break; + case MHWRender::kLead: stream << "kLead"; break; + case MHWRender::kIntermediateObject: stream << "kIntermediateObject"; break; + case MHWRender::kActiveAffected: stream << "kActiveAffected"; break; + case MHWRender::kNoStatus: stream << "kNoStatus"; break; } } - GLUniformBufferBindingsSaver::GLUniformBufferBindingsSaver() { for (size_t i = 0u; i < _uniformBufferBindings.size(); ++i) { glGetIntegeri_v( - GL_UNIFORM_BUFFER_BINDING, - static_cast(i), - &_uniformBufferBindings[i]); + GL_UNIFORM_BUFFER_BINDING, static_cast(i), &_uniformBufferBindings[i]); } } GLUniformBufferBindingsSaver::~GLUniformBufferBindingsSaver() { for (size_t i = 0u; i < _uniformBufferBindings.size(); ++i) { - glBindBufferBase( - GL_UNIFORM_BUFFER, - static_cast(i), - _uniformBufferBindings[i]); + glBindBufferBase(GL_UNIFORM_BUFFER, static_cast(i), _uniformBufferBindings[i]); } } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/px_vp20/utils.h b/lib/mayaUsd/render/px_vp20/utils.h index 8204c583eb..7a2d3a43ca 100644 --- a/lib/mayaUsd/render/px_vp20/utils.h +++ b/lib/mayaUsd/render/px_vp20/utils.h @@ -18,112 +18,107 @@ /// \file px_vp20/utils.h -#include -#include +#include + +#include +#include +#include +#include +#include +#include #include #include #include -#include #include +#include #include #include -#include -#include -#include -#include -#include -#include - -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE class px_vp20Utils { - public: - /// Take VP2.0 lighting information and import it into opengl lights - MAYAUSD_CORE_PUBLIC - static bool setupLightingGL(const MHWRender::MDrawContext& context); - MAYAUSD_CORE_PUBLIC - static void unsetLightingGL(const MHWRender::MDrawContext& context); - - /// Translate a Maya MDrawContext into a GlfSimpleLightingContext. - MAYAUSD_CORE_PUBLIC - static GlfSimpleLightingContextRefPtr GetLightingContextFromDrawContext( - const MHWRender::MDrawContext& context); - - /// Tries to get the viewport for the given draw context. - /// - /// Returns true if the viewport was found, in which case it is - /// returned in the \p view parameter. - /// Returns false if there's not a 3D viewport (e.g. we're drawing into - /// a render view). - MAYAUSD_CORE_PUBLIC - static bool GetViewFromDrawContext( - const MHWRender::MDrawContext& context, - M3dView& view); - - /// Returns true if the given Maya display style indicates that a - /// bounding box should be rendered. - static bool ShouldRenderBoundingBox(unsigned int displayStyle) { - const bool boundingBoxStyle = - displayStyle & MHWRender::MFrameContext::DisplayStyle::kBoundingBox; - return boundingBoxStyle; - } - - /// Renders the given bounding box in the given \p color via OpenGL. - MAYAUSD_CORE_PUBLIC - static bool RenderBoundingBox( - const MBoundingBox& bounds, - const GfVec4f& color, - const MMatrix& worldViewMat, - const MMatrix& projectionMat); - - /// Helper to draw multiple wireframe boxes, where \p cubeXforms is a - /// list of transforms to apply to the unit cube centered around the - /// origin. Those transforms will all be concatenated with the - /// \p worldViewMat and \p projectionMat. - MAYAUSD_CORE_PUBLIC - static bool RenderWireCubes( - const std::vector& cubeXforms, - const GfVec4f& color, - const GfMatrix4d& worldViewMat, - const GfMatrix4d& projectionMat); - - /// Gets the view and projection matrices based on a particular - /// selection in the given draw context. - MAYAUSD_CORE_PUBLIC - static bool GetSelectionMatrices( - const MHWRender::MSelectionInfo& selectionInfo, - const MHWRender::MDrawContext& context, - GfMatrix4d& viewMatrix, - GfMatrix4d& projectionMatrix); - - /// Outputs a human-readable form of the given \p displayStyle to - /// \p stream for debugging. - /// - /// \p displayStyle should be a bitwise combination of - /// MHWRender::MFrameContext::DisplayStyle values. - MAYAUSD_CORE_PUBLIC - static void OutputDisplayStyleToStream( - const unsigned int displayStyle, - std::ostream& stream); - - /// Outputs a human-readable form of the given \p displayStatus to - /// \p stream for debugging. - MAYAUSD_CORE_PUBLIC - static void OutputDisplayStatusToStream( - const MHWRender::DisplayStatus displayStatus, - std::ostream& stream); - - private: - px_vp20Utils() = delete; - ~px_vp20Utils() = delete; +public: + /// Take VP2.0 lighting information and import it into opengl lights + MAYAUSD_CORE_PUBLIC + static bool setupLightingGL(const MHWRender::MDrawContext& context); + MAYAUSD_CORE_PUBLIC + static void unsetLightingGL(const MHWRender::MDrawContext& context); + + /// Translate a Maya MDrawContext into a GlfSimpleLightingContext. + MAYAUSD_CORE_PUBLIC + static GlfSimpleLightingContextRefPtr + GetLightingContextFromDrawContext(const MHWRender::MDrawContext& context); + + /// Tries to get the viewport for the given draw context. + /// + /// Returns true if the viewport was found, in which case it is + /// returned in the \p view parameter. + /// Returns false if there's not a 3D viewport (e.g. we're drawing into + /// a render view). + MAYAUSD_CORE_PUBLIC + static bool GetViewFromDrawContext(const MHWRender::MDrawContext& context, M3dView& view); + + /// Returns true if the given Maya display style indicates that a + /// bounding box should be rendered. + static bool ShouldRenderBoundingBox(unsigned int displayStyle) + { + const bool boundingBoxStyle + = displayStyle & MHWRender::MFrameContext::DisplayStyle::kBoundingBox; + return boundingBoxStyle; + } + + /// Renders the given bounding box in the given \p color via OpenGL. + MAYAUSD_CORE_PUBLIC + static bool RenderBoundingBox( + const MBoundingBox& bounds, + const GfVec4f& color, + const MMatrix& worldViewMat, + const MMatrix& projectionMat); + + /// Helper to draw multiple wireframe boxes, where \p cubeXforms is a + /// list of transforms to apply to the unit cube centered around the + /// origin. Those transforms will all be concatenated with the + /// \p worldViewMat and \p projectionMat. + MAYAUSD_CORE_PUBLIC + static bool RenderWireCubes( + const std::vector& cubeXforms, + const GfVec4f& color, + const GfMatrix4d& worldViewMat, + const GfMatrix4d& projectionMat); + + /// Gets the view and projection matrices based on a particular + /// selection in the given draw context. + MAYAUSD_CORE_PUBLIC + static bool GetSelectionMatrices( + const MHWRender::MSelectionInfo& selectionInfo, + const MHWRender::MDrawContext& context, + GfMatrix4d& viewMatrix, + GfMatrix4d& projectionMatrix); + + /// Outputs a human-readable form of the given \p displayStyle to + /// \p stream for debugging. + /// + /// \p displayStyle should be a bitwise combination of + /// MHWRender::MFrameContext::DisplayStyle values. + MAYAUSD_CORE_PUBLIC + static void OutputDisplayStyleToStream(const unsigned int displayStyle, std::ostream& stream); + + /// Outputs a human-readable form of the given \p displayStatus to + /// \p stream for debugging. + MAYAUSD_CORE_PUBLIC + static void + OutputDisplayStatusToStream(const MHWRender::DisplayStatus displayStatus, std::ostream& stream); + +private: + px_vp20Utils() = delete; + ~px_vp20Utils() = delete; }; - /// Simple RAII class to save uniform buffer bindings, to deal with a Maya /// issue. /// @@ -144,21 +139,19 @@ class px_vp20Utils /// index 4. class GLUniformBufferBindingsSaver { - public: - MAYAUSD_CORE_PUBLIC - GLUniformBufferBindingsSaver(); +public: + MAYAUSD_CORE_PUBLIC + GLUniformBufferBindingsSaver(); - MAYAUSD_CORE_PUBLIC - ~GLUniformBufferBindingsSaver(); + MAYAUSD_CORE_PUBLIC + ~GLUniformBufferBindingsSaver(); - private: - static constexpr size_t UNIFORM_BINDINGS_TO_SAVE = 5u; +private: + static constexpr size_t UNIFORM_BINDINGS_TO_SAVE = 5u; - std::array _uniformBufferBindings; + std::array _uniformBufferBindings; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/render/px_vp20/utils_legacy.cpp b/lib/mayaUsd/render/px_vp20/utils_legacy.cpp index 8d3370a9fb..dd940db9aa 100644 --- a/lib/mayaUsd/render/px_vp20/utils_legacy.cpp +++ b/lib/mayaUsd/render/px_vp20/utils_legacy.cpp @@ -15,23 +15,22 @@ // #include "utils_legacy.h" +#include +#include + #include #include #include #include #include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE /* static */ -bool -px_LegacyViewportUtils::GetSelectionMatrices( - MSelectInfo& selectInfo, - GfMatrix4d& viewMatrix, - GfMatrix4d& projectionMatrix) +bool px_LegacyViewportUtils::GetSelectionMatrices( + MSelectInfo& selectInfo, + GfMatrix4d& viewMatrix, + GfMatrix4d& projectionMatrix) { MStatus status; @@ -52,32 +51,22 @@ px_LegacyViewportUtils::GetSelectionMatrices( unsigned int viewportOriginY; unsigned int viewportWidth; unsigned int viewportHeight; - status = view.viewport( - viewportOriginX, - viewportOriginY, - viewportWidth, - viewportHeight); + status = view.viewport(viewportOriginX, viewportOriginY, viewportWidth, viewportHeight); CHECK_MSTATUS_AND_RETURN(status, false); unsigned int selectRectX; unsigned int selectRectY; unsigned int selectRectWidth; unsigned int selectRectHeight; - selectInfo.selectRect( - selectRectX, - selectRectY, - selectRectWidth, - selectRectHeight); + selectInfo.selectRect(selectRectX, selectRectY, selectRectWidth, selectRectHeight); MMatrix selectionMatrix; selectionMatrix[0][0] = (double)viewportWidth / (double)selectRectWidth; selectionMatrix[1][1] = (double)viewportHeight / (double)selectRectHeight; - selectionMatrix[3][0] = - ((double)viewportWidth - (double)(selectRectX * 2 + selectRectWidth)) / - (double)selectRectWidth; - selectionMatrix[3][1] = - ((double)viewportHeight - (double)(selectRectY * 2 + selectRectHeight)) / - (double)selectRectHeight; + selectionMatrix[3][0] = ((double)viewportWidth - (double)(selectRectX * 2 + selectRectWidth)) + / (double)selectRectWidth; + selectionMatrix[3][1] = ((double)viewportHeight - (double)(selectRectY * 2 + selectRectHeight)) + / (double)selectRectHeight; projectionMat *= selectionMatrix; @@ -87,5 +76,4 @@ px_LegacyViewportUtils::GetSelectionMatrices( return true; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/px_vp20/utils_legacy.h b/lib/mayaUsd/render/px_vp20/utils_legacy.h index 1abeb8b392..ed48aca9d3 100644 --- a/lib/mayaUsd/render/px_vp20/utils_legacy.h +++ b/lib/mayaUsd/render/px_vp20/utils_legacy.h @@ -29,81 +29,77 @@ // // The X11 include appears to have been removed in Maya 2020+, so this should // no longer be an issue with later versions. -#include +#include -#include #include +#include +#include #include #include #include -#include - PXR_NAMESPACE_OPEN_SCOPE /// This class contains helper methods and utilities to help with the /// transition from the Maya legacy viewport to Viewport 2.0. class px_LegacyViewportUtils { - public: - /// Get the view and projection matrices used for selection from the - /// given selection context in MSelectInfo \p selectInfo. - MAYAUSD_CORE_PUBLIC - static bool GetSelectionMatrices( - MSelectInfo& selectInfo, - GfMatrix4d& viewMatrix, - GfMatrix4d& projectionMatrix); - - /// Helper function that converts M3dView::DisplayStyle from the legacy - /// viewport into MHWRender::MFrameContext::DisplayStyle for Viewport - /// 2.0. - /// - /// In the legacy viewport, the M3dView can be in exactly one - /// displayStyle whereas Viewport 2.0's displayStyle is a bitmask of - /// potentially multiple styles. To translate from the legacy viewport - /// to Viewport 2.0, we simply bitwise-OR the single legacy viewport - /// displayStyle into an empty mask. - static unsigned int GetMFrameContextDisplayStyle( - M3dView::DisplayStyle legacyDisplayStyle) { - unsigned int displayStyle = 0u; - - switch (legacyDisplayStyle) { - case M3dView::kBoundingBox: - displayStyle |= MHWRender::MFrameContext::DisplayStyle::kBoundingBox; - break; - case M3dView::kFlatShaded: - displayStyle |= MHWRender::MFrameContext::DisplayStyle::kFlatShaded; - break; - case M3dView::kGouraudShaded: - displayStyle |= MHWRender::MFrameContext::DisplayStyle::kGouraudShaded; - break; - case M3dView::kWireFrame: - displayStyle |= MHWRender::MFrameContext::DisplayStyle::kWireFrame; - break; - case M3dView::kPoints: - // Not supported. - break; - } - - return displayStyle; +public: + /// Get the view and projection matrices used for selection from the + /// given selection context in MSelectInfo \p selectInfo. + MAYAUSD_CORE_PUBLIC + static bool GetSelectionMatrices( + MSelectInfo& selectInfo, + GfMatrix4d& viewMatrix, + GfMatrix4d& projectionMatrix); + + /// Helper function that converts M3dView::DisplayStyle from the legacy + /// viewport into MHWRender::MFrameContext::DisplayStyle for Viewport + /// 2.0. + /// + /// In the legacy viewport, the M3dView can be in exactly one + /// displayStyle whereas Viewport 2.0's displayStyle is a bitmask of + /// potentially multiple styles. To translate from the legacy viewport + /// to Viewport 2.0, we simply bitwise-OR the single legacy viewport + /// displayStyle into an empty mask. + static unsigned int GetMFrameContextDisplayStyle(M3dView::DisplayStyle legacyDisplayStyle) + { + unsigned int displayStyle = 0u; + + switch (legacyDisplayStyle) { + case M3dView::kBoundingBox: + displayStyle |= MHWRender::MFrameContext::DisplayStyle::kBoundingBox; + break; + case M3dView::kFlatShaded: + displayStyle |= MHWRender::MFrameContext::DisplayStyle::kFlatShaded; + break; + case M3dView::kGouraudShaded: + displayStyle |= MHWRender::MFrameContext::DisplayStyle::kGouraudShaded; + break; + case M3dView::kWireFrame: + displayStyle |= MHWRender::MFrameContext::DisplayStyle::kWireFrame; + break; + case M3dView::kPoints: + // Not supported. + break; } - /// Returns true if the given Maya display style indicates that a - /// bounding box should be rendered. - static bool ShouldRenderBoundingBox( - M3dView::DisplayStyle legacyDisplayStyle) { - return (legacyDisplayStyle == M3dView::kBoundingBox); - } - - private: - px_LegacyViewportUtils() = delete; - ~px_LegacyViewportUtils() = delete; -}; + return displayStyle; + } + /// Returns true if the given Maya display style indicates that a + /// bounding box should be rendered. + static bool ShouldRenderBoundingBox(M3dView::DisplayStyle legacyDisplayStyle) + { + return (legacyDisplayStyle == M3dView::kBoundingBox); + } +private: + px_LegacyViewportUtils() = delete; + ~px_LegacyViewportUtils() = delete; +}; PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/batchRenderer.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/batchRenderer.cpp index 1ef095d5b8..30605a83e9 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/batchRenderer.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/batchRenderer.cpp @@ -19,32 +19,11 @@ #include "batchRenderer.h" -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include -#include #include #include #include @@ -69,12 +48,33 @@ #include #include #include +#include #include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include #if USD_VERSION_NUM > 2002 #include @@ -86,26 +86,22 @@ PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PRIVATE_TOKENS( _tokens, - ((BatchRendererRootName, "MayaHdBatchRenderer")) - ((LegacyViewport, "LegacyViewport")) - ((Viewport2, "Viewport2")) - ((MayaEndRenderNotificationName, "UsdMayaEndRenderNotification")) -); - + ((BatchRendererRootName, "MayaHdBatchRenderer"))((LegacyViewport, "LegacyViewport"))( + (Viewport2, "Viewport2"))((MayaEndRenderNotificationName, "UsdMayaEndRenderNotification"))); TF_INSTANTIATE_SINGLETON(UsdMayaGLBatchRenderer); const int UsdMayaGLBatchRenderer::ProfilerCategory = MProfiler::addCategory( #if MAYA_API_VERSION >= 20190000 - "UsdMayaGLBatchRenderer", "UsdMayaGLBatchRenderer" + "UsdMayaGLBatchRenderer", + "UsdMayaGLBatchRenderer" #else "UsdMayaGLBatchRenderer" #endif ); /* static */ -void -UsdMayaGLBatchRenderer::Init() +void UsdMayaGLBatchRenderer::Init() { GlfGlewInit(); GlfContextCaps::InitInstance(); @@ -114,20 +110,14 @@ UsdMayaGLBatchRenderer::Init() } /* static */ -UsdMayaGLBatchRenderer& -UsdMayaGLBatchRenderer::GetInstance() +UsdMayaGLBatchRenderer& UsdMayaGLBatchRenderer::GetInstance() { return TfSingleton::GetInstance(); } -HdRenderIndex* -UsdMayaGLBatchRenderer::GetRenderIndex() const -{ - return _renderIndex.get(); -} +HdRenderIndex* UsdMayaGLBatchRenderer::GetRenderIndex() const { return _renderIndex.get(); } -SdfPath -UsdMayaGLBatchRenderer::GetDelegatePrefix(const bool isViewport2) const +SdfPath UsdMayaGLBatchRenderer::GetDelegatePrefix(const bool isViewport2) const { if (isViewport2) { return _viewport2Prefix; @@ -136,15 +126,12 @@ UsdMayaGLBatchRenderer::GetDelegatePrefix(const bool isViewport2) const return _legacyViewportPrefix; } -bool -UsdMayaGLBatchRenderer::AddShapeAdapter(PxrMayaHdShapeAdapter* shapeAdapter) +bool UsdMayaGLBatchRenderer::AddShapeAdapter(PxrMayaHdShapeAdapter* shapeAdapter) { TRACE_FUNCTION(); MProfilingScope profilingScope( - ProfilerCategory, - MProfiler::kColorE_L3, - "Batch Renderer Adding Shape Adapter"); + ProfilerCategory, MProfiler::kColorE_L3, "Batch Renderer Adding Shape Adapter"); if (!TF_VERIFY(shapeAdapter, "Cannot add invalid shape adapter")) { return false; @@ -153,18 +140,18 @@ UsdMayaGLBatchRenderer::AddShapeAdapter(PxrMayaHdShapeAdapter* shapeAdapter) const bool isViewport2 = shapeAdapter->IsViewport2(); // Add the shape adapter to the correct bucket based on its renderParams. - _ShapeAdapterBucketsMap& bucketsMap = isViewport2 ? - _shapeAdapterBuckets : - _legacyShapeAdapterBuckets; + _ShapeAdapterBucketsMap& bucketsMap + = isViewport2 ? _shapeAdapterBuckets : _legacyShapeAdapterBuckets; const PxrMayaHdRenderParams& renderParams = shapeAdapter->GetRenderParams(); - const size_t renderParamsHash = renderParams.Hash(); + const size_t renderParamsHash = renderParams.Hash(); - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - "Adding shape adapter: %p, isViewport2: %s, renderParamsHash: %zu\n", - shapeAdapter, - isViewport2 ? "true" : "false", - renderParamsHash); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) + .Msg( + "Adding shape adapter: %p, isViewport2: %s, renderParamsHash: %zu\n", + shapeAdapter, + isViewport2 ? "true" : "false", + renderParamsHash); auto iter = bucketsMap.find(renderParamsHash); if (iter == bucketsMap.end()) { @@ -173,20 +160,19 @@ UsdMayaGLBatchRenderer::AddShapeAdapter(PxrMayaHdShapeAdapter* shapeAdapter) // shape adapter isn't in any other bucket. RemoveShapeAdapter(shapeAdapter); - bucketsMap[renderParamsHash] = - _ShapeAdapterBucket(renderParams, _ShapeAdapterSet({shapeAdapter})); + bucketsMap[renderParamsHash] + = _ShapeAdapterBucket(renderParams, _ShapeAdapterSet({ shapeAdapter })); - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - " Added to newly created bucket\n"); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg(" Added to newly created bucket\n"); } else { // Check whether this shape adapter is already in this bucket. _ShapeAdapterSet& shapeAdapters = iter->second.second; - auto setIter = shapeAdapters.find(shapeAdapter); + auto setIter = shapeAdapters.find(shapeAdapter); if (setIter != shapeAdapters.end()) { // If it's already in this bucket, then we're done, and we didn't // have to add it. - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - " Not adding, already in correct bucket\n"); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) + .Msg(" Not adding, already in correct bucket\n"); return false; } @@ -197,67 +183,62 @@ UsdMayaGLBatchRenderer::AddShapeAdapter(PxrMayaHdShapeAdapter* shapeAdapter) shapeAdapters.insert(shapeAdapter); - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - " Added to existing bucket\n"); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg(" Added to existing bucket\n"); } // Debug dumping of current bucket state. if (TfDebug::IsEnabled(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING)) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - " _shapeAdapterBuckets (Viewport 2.0) contents:\n"); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) + .Msg(" _shapeAdapterBuckets (Viewport 2.0) contents:\n"); for (const auto& iter : _shapeAdapterBuckets) { - const size_t bucketHash = iter.first; + const size_t bucketHash = iter.first; const _ShapeAdapterSet& shapeAdapters = iter.second.second; - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - " renderParamsHash: %zu, bucket size: %zu\n", - bucketHash, - shapeAdapters.size()); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) + .Msg( + " renderParamsHash: %zu, bucket size: %zu\n", + bucketHash, + shapeAdapters.size()); for (const auto shapeAdapter : shapeAdapters) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - " shape adapter: %p\n", - shapeAdapter); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) + .Msg(" shape adapter: %p\n", shapeAdapter); } } - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - " _legacyShapeAdapterBuckets (Legacy viewport) contents:\n"); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) + .Msg(" _legacyShapeAdapterBuckets (Legacy viewport) contents:\n"); for (auto& iter : _legacyShapeAdapterBuckets) { - const size_t bucketHash = iter.first; + const size_t bucketHash = iter.first; const _ShapeAdapterSet& shapeAdapters = iter.second.second; - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - " renderParamsHash: %zu, bucket size: %zu\n", - bucketHash, - shapeAdapters.size()); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) + .Msg( + " renderParamsHash: %zu, bucket size: %zu\n", + bucketHash, + shapeAdapters.size()); for (const auto shapeAdapter : shapeAdapters) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - " shape adapter: %p\n", - shapeAdapter); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) + .Msg(" shape adapter: %p\n", shapeAdapter); } } } // Add the shape adapter to the secondary object handle map. - _ShapeAdapterHandleMap& handleMap = isViewport2 ? - _shapeAdapterHandleMap : - _legacyShapeAdapterHandleMap; + _ShapeAdapterHandleMap& handleMap + = isViewport2 ? _shapeAdapterHandleMap : _legacyShapeAdapterHandleMap; handleMap[MObjectHandle(shapeAdapter->GetDagPath().node())] = shapeAdapter; return true; } -bool -UsdMayaGLBatchRenderer::RemoveShapeAdapter(PxrMayaHdShapeAdapter* shapeAdapter) +bool UsdMayaGLBatchRenderer::RemoveShapeAdapter(PxrMayaHdShapeAdapter* shapeAdapter) { TRACE_FUNCTION(); MProfilingScope profilingScope( - ProfilerCategory, - MProfiler::kColorE_L3, - "Batch Renderer Removing Shape Adapter"); + ProfilerCategory, MProfiler::kColorE_L3, "Batch Renderer Removing Shape Adapter"); if (!TF_VERIFY(shapeAdapter, "Cannot remove invalid shape adapter")) { return false; @@ -265,32 +246,30 @@ UsdMayaGLBatchRenderer::RemoveShapeAdapter(PxrMayaHdShapeAdapter* shapeAdapter) const bool isViewport2 = shapeAdapter->IsViewport2(); - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - "Removing shape adapter: %p, isViewport2: %s\n", - shapeAdapter, - isViewport2 ? "true" : "false"); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) + .Msg( + "Removing shape adapter: %p, isViewport2: %s\n", + shapeAdapter, + isViewport2 ? "true" : "false"); // Remove shape adapter from its bucket in the bucket map. - _ShapeAdapterBucketsMap& bucketsMap = isViewport2 ? - _shapeAdapterBuckets : - _legacyShapeAdapterBuckets; + _ShapeAdapterBucketsMap& bucketsMap + = isViewport2 ? _shapeAdapterBuckets : _legacyShapeAdapterBuckets; size_t numErased = 0u; std::vector emptyBucketHashes; for (auto& iter : bucketsMap) { - const size_t renderParamsHash = iter.first; + const size_t renderParamsHash = iter.first; _ShapeAdapterSet& shapeAdapters = iter.second.second; const size_t numBefore = numErased; numErased += shapeAdapters.erase(shapeAdapter); - if (TfDebug::IsEnabled(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) && - numErased > numBefore) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - " Removed from bucket with render params hash: %zu\n", - renderParamsHash); + if (TfDebug::IsEnabled(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) && numErased > numBefore) { + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) + .Msg(" Removed from bucket with render params hash: %zu\n", renderParamsHash); } if (shapeAdapters.empty()) { @@ -303,26 +282,22 @@ UsdMayaGLBatchRenderer::RemoveShapeAdapter(PxrMayaHdShapeAdapter* shapeAdapter) for (const size_t renderParamsHash : emptyBucketHashes) { const size_t numErasedBuckets = bucketsMap.erase(renderParamsHash); - if (TfDebug::IsEnabled(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) && - numErasedBuckets > 0u) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING).Msg( - " Removed empty bucket with render params hash: %zu\n", - renderParamsHash); + if (TfDebug::IsEnabled(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) && numErasedBuckets > 0u) { + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING) + .Msg(" Removed empty bucket with render params hash: %zu\n", renderParamsHash); } } // Remove shape adapter from the secondary DAG path map. - _ShapeAdapterHandleMap& handleMap = isViewport2 ? - _shapeAdapterHandleMap : - _legacyShapeAdapterHandleMap; + _ShapeAdapterHandleMap& handleMap + = isViewport2 ? _shapeAdapterHandleMap : _legacyShapeAdapterHandleMap; handleMap.erase(MObjectHandle(shapeAdapter->GetDagPath().node())); return (numErased > 0u); } /* static */ -void -UsdMayaGLBatchRenderer::Reset() +void UsdMayaGLBatchRenderer::Reset() { if (UsdMayaGLBatchRenderer::CurrentlyExists()) { TF_STATUS("Resetting USD Batch Renderer"); @@ -332,16 +307,15 @@ UsdMayaGLBatchRenderer::Reset() UsdMayaGLBatchRenderer::GetInstance(); } -bool -UsdMayaGLBatchRenderer::PopulateCustomPrimFilter( - const MDagPath& dagPath, - PxrMayaHdPrimFilter& primFilter) +bool UsdMayaGLBatchRenderer::PopulateCustomPrimFilter( + const MDagPath& dagPath, + PxrMayaHdPrimFilter& primFilter) { // We're drawing "out-of-band", so it doesn't matter if we grab the VP2 // or the Legacy shape adapter. Prefer VP2, but fall back to Legacy if // we can't find the VP2 adapter. MObjectHandle objHandle(dagPath.node()); - auto iter = _shapeAdapterHandleMap.find(objHandle); + auto iter = _shapeAdapterHandleMap.find(objHandle); if (iter == _shapeAdapterHandleMap.end()) { iter = _legacyShapeAdapterHandleMap.find(objHandle); if (iter == _legacyShapeAdapterHandleMap.end()) { @@ -349,7 +323,7 @@ UsdMayaGLBatchRenderer::PopulateCustomPrimFilter( } } - HdRprimCollection &collection = primFilter.collection; + HdRprimCollection& collection = primFilter.collection; // Doesn't really hurt to always add, and ensures that the collection is // tracked properly. @@ -359,8 +333,8 @@ UsdMayaGLBatchRenderer::PopulateCustomPrimFilter( // Only update the collection and mark it dirty if the root paths have // actually changed. This greatly affects performance. PxrMayaHdShapeAdapter* adapter = iter->second; - const HdReprSelector repr = collection.GetReprSelector(); - const SdfPathVector& roots = adapter->GetRprimCollection(repr).GetRootPaths(); + const HdReprSelector repr = collection.GetReprSelector(); + const SdfPathVector& roots = adapter->GetRprimCollection(repr).GetRootPaths(); if (collection.GetRootPaths() != roots) { collection.SetRootPaths(roots); changeTracker.MarkCollectionDirty(collection.GetName()); @@ -374,9 +348,7 @@ UsdMayaGLBatchRenderer::PopulateCustomPrimFilter( // Since we're using a static singleton UsdMayaGLBatchRenderer object, we need // to make sure that we reset its state when switching to a new Maya scene or // when opening a different scene. -void -UsdMayaGLBatchRenderer::_OnMayaSceneReset( - const UsdMayaSceneResetNotice& notice) +void UsdMayaGLBatchRenderer::_OnMayaSceneReset(const UsdMayaSceneResetNotice& notice) { UsdMayaGLBatchRenderer::Reset(); } @@ -384,10 +356,9 @@ UsdMayaGLBatchRenderer::_OnMayaSceneReset( // For Viewport 2.0, we listen for a notification from Maya's rendering // pipeline that all render passes have completed and then we do some cleanup. /* static */ -void -UsdMayaGLBatchRenderer::_OnMayaEndRenderCallback( - MHWRender::MDrawContext& context, - void* clientData) +void UsdMayaGLBatchRenderer::_OnMayaEndRenderCallback( + MHWRender::MDrawContext& context, + void* clientData) { if (UsdMayaGLBatchRenderer::CurrentlyExists()) { UsdMayaGLBatchRenderer::GetInstance()._MayaRenderDidEnd(&context); @@ -395,11 +366,10 @@ UsdMayaGLBatchRenderer::_OnMayaEndRenderCallback( } /* static */ -void -UsdMayaGLBatchRenderer::_OnSoftSelectOptionsChangedCallback(void* clientData) +void UsdMayaGLBatchRenderer::_OnSoftSelectOptionsChangedCallback(void* clientData) { auto batchRenderer = static_cast(clientData); - int commandResult; + int commandResult; // -sse == -softSelectEnabled MGlobal::executeCommand("softSelect -q -sse", commandResult); if (!commandResult) { @@ -412,29 +382,32 @@ UsdMayaGLBatchRenderer::_OnSoftSelectOptionsChangedCallback(void* clientData) batchRenderer->_objectSoftSelectEnabled = (commandResult == 3); } -UsdMayaGLBatchRenderer::UsdMayaGLBatchRenderer() : - _isSelectionPending(false), - _objectSoftSelectEnabled(false), - _softSelectOptionsCallbackId(0), - _selectResultsKey(GfMatrix4d(0.0), GfMatrix4d(0.0), false), +UsdMayaGLBatchRenderer::UsdMayaGLBatchRenderer() + : _isSelectionPending(false) + , _objectSoftSelectEnabled(false) + , _softSelectOptionsCallbackId(0) + , _selectResultsKey(GfMatrix4d(0.0), GfMatrix4d(0.0), false) + , #if USD_VERSION_NUM > 2002 #if USD_VERSION_NUM > 2005 - _hgi(Hgi::CreatePlatformDefaultHgi()), + _hgi(Hgi::CreatePlatformDefaultHgi()) + , #else - _hgi(Hgi::GetPlatformDefaultHgi()), + _hgi(Hgi::GetPlatformDefaultHgi()) + , #endif - _hgiDriver{HgiTokens->renderDriver, VtValue(_hgi.get())}, + _hgiDriver { HgiTokens->renderDriver, VtValue(_hgi.get()) } + , #endif - _selectionResolution(256), - _enableDepthSelection(false) + _selectionResolution(256) + , _enableDepthSelection(false) { - _rootId = SdfPath::AbsoluteRootPath().AppendChild( - _tokens->BatchRendererRootName); + _rootId = SdfPath::AbsoluteRootPath().AppendChild(_tokens->BatchRendererRootName); _legacyViewportPrefix = _rootId.AppendChild(_tokens->LegacyViewport); _viewport2Prefix = _rootId.AppendChild(_tokens->Viewport2); #if USD_VERSION_NUM > 2002 - _renderIndex.reset(HdRenderIndex::New(&_renderDelegate, {&_hgiDriver})); + _renderIndex.reset(HdRenderIndex::New(&_renderDelegate, { &_hgiDriver })); #else _renderIndex.reset(HdRenderIndex::New(&_renderDelegate)); #endif @@ -442,28 +415,19 @@ UsdMayaGLBatchRenderer::UsdMayaGLBatchRenderer() : return; } - _taskDelegate.reset( - new PxrMayaHdSceneDelegate(_renderIndex.get(), _rootId)); + _taskDelegate.reset(new PxrMayaHdSceneDelegate(_renderIndex.get(), _rootId)); - _legacyViewportRprimCollection.SetName(TfToken( - TfStringPrintf("%s_%s", - _tokens->BatchRendererRootName.GetText(), - _tokens->LegacyViewport.GetText()))); - _legacyViewportRprimCollection.SetReprSelector( - HdReprSelector(HdReprTokens->refined)); + _legacyViewportRprimCollection.SetName(TfToken(TfStringPrintf( + "%s_%s", _tokens->BatchRendererRootName.GetText(), _tokens->LegacyViewport.GetText()))); + _legacyViewportRprimCollection.SetReprSelector(HdReprSelector(HdReprTokens->refined)); _legacyViewportRprimCollection.SetRootPath(_legacyViewportPrefix); - _renderIndex->GetChangeTracker().AddCollection( - _legacyViewportRprimCollection.GetName()); - - _viewport2RprimCollection.SetName(TfToken( - TfStringPrintf("%s_%s", - _tokens->BatchRendererRootName.GetText(), - _tokens->Viewport2.GetText()))); - _viewport2RprimCollection.SetReprSelector( - HdReprSelector(HdReprTokens->refined)); + _renderIndex->GetChangeTracker().AddCollection(_legacyViewportRprimCollection.GetName()); + + _viewport2RprimCollection.SetName(TfToken(TfStringPrintf( + "%s_%s", _tokens->BatchRendererRootName.GetText(), _tokens->Viewport2.GetText()))); + _viewport2RprimCollection.SetReprSelector(HdReprSelector(HdReprTokens->refined)); _viewport2RprimCollection.SetRootPath(_viewport2Prefix); - _renderIndex->GetChangeTracker().AddCollection( - _viewport2RprimCollection.GetName()); + _renderIndex->GetChangeTracker().AddCollection(_viewport2RprimCollection.GetName()); _selectionTracker.reset(new HdxSelectionTracker()); @@ -490,11 +454,8 @@ UsdMayaGLBatchRenderer::UsdMayaGLBatchRenderer() : // use CurrentlyExists()/GetInstance(), but instead pass this as clientData; // this also means we should clean up the callback in the destructor. _OnSoftSelectOptionsChangedCallback(this); - _softSelectOptionsCallbackId = - MEventMessage::addEventCallback( - "softSelectOptionsChanged", - _OnSoftSelectOptionsChangedCallback, - this); + _softSelectOptionsCallbackId = MEventMessage::addEventCallback( + "softSelectOptionsChanged", _OnSoftSelectOptionsChangedCallback, this); } /* virtual */ @@ -510,16 +471,13 @@ UsdMayaGLBatchRenderer::~UsdMayaGLBatchRenderer() MMessage::removeCallback(_softSelectOptionsCallbackId); } -const UsdMayaGLSoftSelectHelper& -UsdMayaGLBatchRenderer::GetSoftSelectHelper() +const UsdMayaGLSoftSelectHelper& UsdMayaGLBatchRenderer::GetSoftSelectHelper() { _softSelectHelper.Populate(); return _softSelectHelper; } -static -void -_GetWorldToViewMatrix(M3dView& view, GfMatrix4d* worldToViewMatrix) +static void _GetWorldToViewMatrix(M3dView& view, GfMatrix4d* worldToViewMatrix) { // Legacy viewport implementation. @@ -541,9 +499,7 @@ _GetWorldToViewMatrix(M3dView& view, GfMatrix4d* worldToViewMatrix) *worldToViewMatrix = cameraMatrix.GetInverse(); } -static -void -_GetViewport(M3dView& view, GfVec4d* viewport) +static void _GetViewport(M3dView& view, GfVec4d* viewport) { // Legacy viewport implementation. @@ -556,11 +512,8 @@ _GetViewport(M3dView& view, GfVec4d* viewport) *viewport = GfVec4d(viewX, viewY, viewWidth, viewHeight); } -static -void -_GetWorldToViewMatrix( - const MHWRender::MDrawContext& context, - GfMatrix4d* worldToViewMatrix) +static void +_GetWorldToViewMatrix(const MHWRender::MDrawContext& context, GfMatrix4d* worldToViewMatrix) { // Viewport 2.0 implementation. @@ -568,15 +521,12 @@ _GetWorldToViewMatrix( return; } - MStatus status; - const MMatrix viewMat = - context.getMatrix(MHWRender::MFrameContext::kViewMtx, &status); + MStatus status; + const MMatrix viewMat = context.getMatrix(MHWRender::MFrameContext::kViewMtx, &status); *worldToViewMatrix = GfMatrix4d(viewMat.matrix); } -static -void -_GetViewport(const MHWRender::MDrawContext& context, GfVec4d* viewport) +static void _GetViewport(const MHWRender::MDrawContext& context, GfVec4d* viewport) { // Viewport 2.0 implementation. @@ -589,22 +539,19 @@ _GetViewport(const MHWRender::MDrawContext& context, GfVec4d* viewport) *viewport = GfVec4d(viewX, viewY, viewWidth, viewHeight); } -void -UsdMayaGLBatchRenderer::Draw(const MDrawRequest& request, M3dView& view) +void UsdMayaGLBatchRenderer::Draw(const MDrawRequest& request, M3dView& view) { // Legacy viewport implementation. TRACE_FUNCTION(); MProfilingScope profilingScope( - ProfilerCategory, - MProfiler::kColorC_L2, - "Batch Renderer Draw() (Legacy Viewport)"); + ProfilerCategory, MProfiler::kColorC_L2, "Batch Renderer Draw() (Legacy Viewport)"); MDrawData drawData = request.drawData(); - const PxrMayaHdUserData* hdUserData = - static_cast(drawData.geometry()); + const PxrMayaHdUserData* hdUserData + = static_cast(drawData.geometry()); if (!hdUserData) { return; } @@ -620,38 +567,27 @@ UsdMayaGLBatchRenderer::Draw(const MDrawRequest& request, M3dView& view) _GetViewport(view, &viewport); _RenderBatches( - /* vp2Context */ nullptr, - &view, - worldToViewMatrix, - projectionMatrix, - viewport); + /* vp2Context */ nullptr, &view, worldToViewMatrix, projectionMatrix, viewport); // Clean up the user data. delete hdUserData; } -void -UsdMayaGLBatchRenderer::Draw( - const MHWRender::MDrawContext& context, - const MUserData* userData) +void UsdMayaGLBatchRenderer::Draw(const MHWRender::MDrawContext& context, const MUserData* userData) { // Viewport 2.0 implementation. TRACE_FUNCTION(); MProfilingScope profilingScope( - ProfilerCategory, - MProfiler::kColorC_L2, - "Batch Renderer Draw() (Viewport 2.0)"); + ProfilerCategory, MProfiler::kColorC_L2, "Batch Renderer Draw() (Viewport 2.0)"); - const PxrMayaHdUserData* hdUserData = - dynamic_cast(userData); + const PxrMayaHdUserData* hdUserData = dynamic_cast(userData); if (!hdUserData) { return; } - const MHWRender::MRenderer* theRenderer = - MHWRender::MRenderer::theRenderer(); + const MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer(); if (!theRenderer || !theRenderer->drawAPIIsOpenGL()) { return; } @@ -666,7 +602,7 @@ UsdMayaGLBatchRenderer::Draw( // wantUserSelection()). The draw override for pxrHdImagingShape will // likely be the only one of these where that is the case. const MHWRender::MPassContext& passContext = context.getPassContext(); - const MStringArray& passSemantics = passContext.passSemantics(); + const MStringArray& passSemantics = passContext.passSemantics(); for (unsigned int i = 0u; i < passSemantics.length(); ++i) { if (passSemantics[i] == MHWRender::MPassContext::kSelectionPassSemantic) { @@ -680,29 +616,21 @@ UsdMayaGLBatchRenderer::Draw( MStatus status; - const MMatrix projectionMat = - context.getMatrix(MHWRender::MFrameContext::kProjectionMtx, &status); + const MMatrix projectionMat + = context.getMatrix(MHWRender::MFrameContext::kProjectionMtx, &status); const GfMatrix4d projectionMatrix(projectionMat.matrix); GfVec4d viewport; _GetViewport(context, &viewport); - M3dView view; - const bool hasView = - px_vp20Utils::GetViewFromDrawContext(context, view); + M3dView view; + const bool hasView = px_vp20Utils::GetViewFromDrawContext(context, view); _RenderBatches( - &context, - hasView ? &view : nullptr, - worldToViewMatrix, - projectionMatrix, - viewport); + &context, hasView ? &view : nullptr, worldToViewMatrix, projectionMatrix, viewport); } -void -UsdMayaGLBatchRenderer::DrawBoundingBox( - const MDrawRequest& request, - M3dView& view) +void UsdMayaGLBatchRenderer::DrawBoundingBox(const MDrawRequest& request, M3dView& view) { // Legacy viewport implementation. @@ -715,8 +643,8 @@ UsdMayaGLBatchRenderer::DrawBoundingBox( MDrawData drawData = request.drawData(); - const PxrMayaHdUserData* hdUserData = - static_cast(drawData.geometry()); + const PxrMayaHdUserData* hdUserData + = static_cast(drawData.geometry()); if (!hdUserData || !hdUserData->boundingBox) { return; } @@ -733,10 +661,7 @@ UsdMayaGLBatchRenderer::DrawBoundingBox( glEnable(GL_FRAMEBUFFER_SRGB_EXT); px_vp20Utils::RenderBoundingBox( - *(hdUserData->boundingBox), - *(hdUserData->wireframeColor), - modelViewMat, - projectionMat); + *(hdUserData->boundingBox), *(hdUserData->wireframeColor), modelViewMat, projectionMat); glDisable(GL_FRAMEBUFFER_SRGB_EXT); @@ -744,76 +669,57 @@ UsdMayaGLBatchRenderer::DrawBoundingBox( delete hdUserData; } -void -UsdMayaGLBatchRenderer::DrawBoundingBox( - const MHWRender::MDrawContext& context, - const MUserData* userData) +void UsdMayaGLBatchRenderer::DrawBoundingBox( + const MHWRender::MDrawContext& context, + const MUserData* userData) { // Viewport 2.0 implementation. TRACE_FUNCTION(); MProfilingScope profilingScope( - ProfilerCategory, - MProfiler::kColorC_L2, - "Batch Renderer DrawBoundingBox() (Viewport 2.0)"); + ProfilerCategory, MProfiler::kColorC_L2, "Batch Renderer DrawBoundingBox() (Viewport 2.0)"); - const PxrMayaHdUserData* hdUserData = - dynamic_cast(userData); + const PxrMayaHdUserData* hdUserData = dynamic_cast(userData); if (!hdUserData || !hdUserData->boundingBox) { return; } - const MHWRender::MRenderer* theRenderer = - MHWRender::MRenderer::theRenderer(); + const MHWRender::MRenderer* theRenderer = MHWRender::MRenderer::theRenderer(); if (!theRenderer || !theRenderer->drawAPIIsOpenGL()) { return; } MStatus status; - const MMatrix worldViewMat = - context.getMatrix(MHWRender::MFrameContext::kWorldViewMtx, &status); + const MMatrix worldViewMat + = context.getMatrix(MHWRender::MFrameContext::kWorldViewMtx, &status); - const MMatrix projectionMat = - context.getMatrix(MHWRender::MFrameContext::kProjectionMtx, &status); + const MMatrix projectionMat + = context.getMatrix(MHWRender::MFrameContext::kProjectionMtx, &status); const GfMatrix4d projectionMatrix(projectionMat.matrix); px_vp20Utils::RenderBoundingBox( - *(hdUserData->boundingBox), - *(hdUserData->wireframeColor), - worldViewMat, - projectionMat); + *(hdUserData->boundingBox), *(hdUserData->wireframeColor), worldViewMat, projectionMat); } -GfVec2i -UsdMayaGLBatchRenderer::GetSelectionResolution() const -{ - return _selectionResolution; -} +GfVec2i UsdMayaGLBatchRenderer::GetSelectionResolution() const { return _selectionResolution; } -void -UsdMayaGLBatchRenderer::SetSelectionResolution(const GfVec2i& widthHeight) +void UsdMayaGLBatchRenderer::SetSelectionResolution(const GfVec2i& widthHeight) { _selectionResolution = widthHeight; } -bool -UsdMayaGLBatchRenderer::IsDepthSelectionEnabled() const -{ - return _enableDepthSelection; -} +bool UsdMayaGLBatchRenderer::IsDepthSelectionEnabled() const { return _enableDepthSelection; } -void -UsdMayaGLBatchRenderer::SetDepthSelectionEnabled(const bool enabled) +void UsdMayaGLBatchRenderer::SetDepthSelectionEnabled(const bool enabled) { _enableDepthSelection = enabled; } -const HdxPickHitVector* -UsdMayaGLBatchRenderer::TestIntersection( - const PxrMayaHdShapeAdapter* shapeAdapter, - MSelectInfo& selectInfo) +const HdxPickHitVector* UsdMayaGLBatchRenderer::TestIntersection( + const PxrMayaHdShapeAdapter* shapeAdapter, + MSelectInfo& selectInfo) { // Legacy viewport implementation. @@ -835,26 +741,24 @@ UsdMayaGLBatchRenderer::TestIntersection( if (_UpdateIsSelectionPending(false)) { if (TfDebug::IsEnabled(PXRUSDMAYAGL_BATCHED_SELECTION)) { - TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg( - "Computing batched selection for legacy viewport\n"); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION) + .Msg("Computing batched selection for legacy viewport\n"); } GfMatrix4d viewMatrix; GfMatrix4d projectionMatrix; - px_LegacyViewportUtils::GetSelectionMatrices( - selectInfo, - viewMatrix, - projectionMatrix); + px_LegacyViewportUtils::GetSelectionMatrices(selectInfo, viewMatrix, projectionMatrix); - _ComputeSelection(_legacyShapeAdapterBuckets, - &view, - viewMatrix, - projectionMatrix, - selectInfo.singleSelection()); + _ComputeSelection( + _legacyShapeAdapterBuckets, + &view, + viewMatrix, + projectionMatrix, + selectInfo.singleSelection()); } - const HdxPickHitVector* const hitSet = - TfMapLookupPtr(_selectResults, shapeAdapter->GetDelegateID()); + const HdxPickHitVector* const hitSet + = TfMapLookupPtr(_selectResults, shapeAdapter->GetDelegateID()); if (!hitSet || hitSet->empty()) { if (_selectResults.empty()) { // If nothing was selected previously AND nothing is selected now, @@ -872,27 +776,27 @@ UsdMayaGLBatchRenderer::TestIntersection( return nullptr; } - TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg( - " FOUND %zu HIT(s)\n", hitSet->size()); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg(" FOUND %zu HIT(s)\n", hitSet->size()); if (TfDebug::IsEnabled(PXRUSDMAYAGL_BATCHED_SELECTION)) { for (const HdxPickHit& hit : *hitSet) { - TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg( + TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION) + .Msg( #if USD_VERSION_NUM > 1911 - " HIT:\n" - " delegateId : %s\n" - " objectId : %s\n" - " normalizedDepth : %f\n", - hit.delegateId.GetText(), - hit.objectId.GetText(), - hit.normalizedDepth); + " HIT:\n" + " delegateId : %s\n" + " objectId : %s\n" + " normalizedDepth : %f\n", + hit.delegateId.GetText(), + hit.objectId.GetText(), + hit.normalizedDepth); #else - " HIT:\n" - " delegateId: %s\n" - " objectId : %s\n" - " ndcDepth : %f\n", - hit.delegateId.GetText(), - hit.objectId.GetText(), - hit.ndcDepth); + " HIT:\n" + " delegateId: %s\n" + " objectId : %s\n" + " ndcDepth : %f\n", + hit.delegateId.GetText(), + hit.objectId.GetText(), + hit.ndcDepth); #endif } } @@ -900,11 +804,10 @@ UsdMayaGLBatchRenderer::TestIntersection( return hitSet; } -const HdxPickHitVector* -UsdMayaGLBatchRenderer::TestIntersection( - const PxrMayaHdShapeAdapter* shapeAdapter, - const MHWRender::MSelectionInfo& selectionInfo, - const MHWRender::MDrawContext& context) +const HdxPickHitVector* UsdMayaGLBatchRenderer::TestIntersection( + const PxrMayaHdShapeAdapter* shapeAdapter, + const MHWRender::MSelectionInfo& selectionInfo, + const MHWRender::MDrawContext& context) { // Viewport 2.0 implementation. @@ -924,10 +827,7 @@ UsdMayaGLBatchRenderer::TestIntersection( GfMatrix4d viewMatrix; GfMatrix4d projectionMatrix; - if (!px_vp20Utils::GetSelectionMatrices(selectionInfo, - context, - viewMatrix, - projectionMatrix)) { + if (!px_vp20Utils::GetSelectionMatrices(selectionInfo, context, viewMatrix, projectionMatrix)) { return nullptr; } @@ -942,67 +842,67 @@ UsdMayaGLBatchRenderer::TestIntersection( // // In these cases, we look at the projectionMatrix for the selection as well // to see if the selection needs to be re-computed. - const _SelectResultsKey key = std::make_tuple( - viewMatrix, projectionMatrix, singleSelection); - const bool newSelKey = key != _selectResultsKey; + const _SelectResultsKey key = std::make_tuple(viewMatrix, projectionMatrix, singleSelection); + const bool newSelKey = key != _selectResultsKey; const bool needToRecomputeSelection = wasSelectionPending || newSelKey; if (needToRecomputeSelection) { if (TfDebug::IsEnabled(PXRUSDMAYAGL_BATCHED_SELECTION)) { - TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg( - "Computing batched selection for Viewport 2.0\n"); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION) + .Msg("Computing batched selection for Viewport 2.0\n"); - const MUint64 frameStamp = context.getFrameStamp(); + const MUint64 frameStamp = context.getFrameStamp(); const MHWRender::MPassContext& passContext = context.getPassContext(); - const MString& passId = passContext.passIdentifier(); - const MStringArray& passSemantics = passContext.passSemantics(); - - TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg( - " frameStamp: %s, passIdentifier: %s, passSemantics: %s\n", - TfStringify(frameStamp).c_str(), - passId.asChar(), - TfStringify(passSemantics).c_str()); + const MString& passId = passContext.passIdentifier(); + const MStringArray& passSemantics = passContext.passSemantics(); + + TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION) + .Msg( + " frameStamp: %s, passIdentifier: %s, passSemantics: %s\n", + TfStringify(frameStamp).c_str(), + passId.asChar(), + TfStringify(passSemantics).c_str()); } - M3dView view; - const bool hasView = px_vp20Utils::GetViewFromDrawContext(context, - view); + M3dView view; + const bool hasView = px_vp20Utils::GetViewFromDrawContext(context, view); - _ComputeSelection(_shapeAdapterBuckets, - hasView ? &view : nullptr, - viewMatrix, - projectionMatrix, - singleSelection); + _ComputeSelection( + _shapeAdapterBuckets, + hasView ? &view : nullptr, + viewMatrix, + projectionMatrix, + singleSelection); _selectResultsKey = key; } - const HdxPickHitVector* const hitSet = - TfMapLookupPtr(_selectResults, shapeAdapter->GetDelegateID()); + const HdxPickHitVector* const hitSet + = TfMapLookupPtr(_selectResults, shapeAdapter->GetDelegateID()); if (!hitSet || hitSet->empty()) { return nullptr; } - TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg( - " FOUND %zu HIT(s)\n", hitSet->size()); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg(" FOUND %zu HIT(s)\n", hitSet->size()); if (TfDebug::IsEnabled(PXRUSDMAYAGL_BATCHED_SELECTION)) { for (const HdxPickHit& hit : *hitSet) { - TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg( + TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION) + .Msg( #if USD_VERSION_NUM > 1911 - " HIT:\n" - " delegateId : %s\n" - " objectId : %s\n" - " normalizedDepth : %f\n", - hit.delegateId.GetText(), - hit.objectId.GetText(), - hit.normalizedDepth); + " HIT:\n" + " delegateId : %s\n" + " objectId : %s\n" + " normalizedDepth : %f\n", + hit.delegateId.GetText(), + hit.objectId.GetText(), + hit.normalizedDepth); #else - " HIT:\n" - " delegateId: %s\n" - " objectId : %s\n" - " ndcDepth : %f\n", - hit.delegateId.GetText(), - hit.objectId.GetText(), - hit.ndcDepth); + " HIT:\n" + " delegateId: %s\n" + " objectId : %s\n" + " ndcDepth : %f\n", + hit.delegateId.GetText(), + hit.objectId.GetText(), + hit.ndcDepth); #endif } } @@ -1010,12 +910,11 @@ UsdMayaGLBatchRenderer::TestIntersection( return hitSet; } -bool -UsdMayaGLBatchRenderer::TestIntersectionCustomPrimFilter( - const PxrMayaHdPrimFilter& primFilter, - const GfMatrix4d& viewMatrix, - const GfMatrix4d& projectionMatrix, - HdxPickHitVector* outResult) +bool UsdMayaGLBatchRenderer::TestIntersectionCustomPrimFilter( + const PxrMayaHdPrimFilter& primFilter, + const GfMatrix4d& viewMatrix, + const GfMatrix4d& projectionMatrix, + HdxPickHitVector* outResult) { // Custom collection implementation. // Differs from viewport implementations in that it doesn't rely on @@ -1023,16 +922,17 @@ UsdMayaGLBatchRenderer::TestIntersectionCustomPrimFilter( GLUniformBufferBindingsSaver bindingsSaver; - return _TestIntersection(primFilter.collection, - primFilter.renderTags, - viewMatrix, projectionMatrix, - true, outResult); + return _TestIntersection( + primFilter.collection, + primFilter.renderTags, + viewMatrix, + projectionMatrix, + true, + outResult); } /* static */ -const HdxPickHit* -UsdMayaGLBatchRenderer::GetNearestHit( - const HdxPickHitVector* const hitSet) +const HdxPickHit* UsdMayaGLBatchRenderer::GetNearestHit(const HdxPickHitVector* const hitSet) { if (!hitSet || hitSet->empty()) { return nullptr; @@ -1049,11 +949,10 @@ UsdMayaGLBatchRenderer::GetNearestHit( return minHit; } -PxrMayaHdPrimFilterVector -UsdMayaGLBatchRenderer::_GetIntersectionPrimFilters( - _ShapeAdapterBucketsMap& bucketsMap, - const M3dView* view, - const bool useDepthSelection) const +PxrMayaHdPrimFilterVector UsdMayaGLBatchRenderer::_GetIntersectionPrimFilters( + _ShapeAdapterBucketsMap& bucketsMap, + const M3dView* view, + const bool useDepthSelection) const { PxrMayaHdPrimFilterVector primFilters; @@ -1086,67 +985,49 @@ UsdMayaGLBatchRenderer::_GetIntersectionPrimFilters( // depth selection. Ideally though, this would be whatever repr was // most recently drawn for the viewport in which the selection is // taking place. - const HdReprSelector repr(HdReprTokens->refined); - const HdRprimCollection &rprimCollection = - shapeAdapter->GetRprimCollection(repr); + const HdReprSelector repr(HdReprTokens->refined); + const HdRprimCollection& rprimCollection = shapeAdapter->GetRprimCollection(repr); - const TfTokenVector &renderTags = shapeAdapter->GetRenderTags(); + const TfTokenVector& renderTags = shapeAdapter->GetRenderTags(); primFilters.push_back( - PxrMayaHdPrimFilter { - shapeAdapter, - rprimCollection, - renderTags - }); + PxrMayaHdPrimFilter { shapeAdapter, rprimCollection, renderTags }); } } if (!useDepthSelection) { - const HdRprimCollection &collection = - isViewport2 ? _viewport2RprimCollection : - _legacyViewportRprimCollection; - - - primFilters.push_back( - PxrMayaHdPrimFilter { - nullptr, - collection, - TfTokenVector{ - HdRenderTagTokens->geometry, - HdRenderTagTokens->proxy} - }); + const HdRprimCollection& collection + = isViewport2 ? _viewport2RprimCollection : _legacyViewportRprimCollection; + + primFilters.push_back(PxrMayaHdPrimFilter { + nullptr, + collection, + TfTokenVector { HdRenderTagTokens->geometry, HdRenderTagTokens->proxy } }); } return primFilters; } -bool -UsdMayaGLBatchRenderer::_TestIntersection( - const HdRprimCollection& rprimCollection, - const TfTokenVector& renderTags, - const GfMatrix4d& viewMatrix, - const GfMatrix4d& projectionMatrix, - const bool singleSelection, - HdxPickHitVector* result) +bool UsdMayaGLBatchRenderer::_TestIntersection( + const HdRprimCollection& rprimCollection, + const TfTokenVector& renderTags, + const GfMatrix4d& viewMatrix, + const GfMatrix4d& projectionMatrix, + const bool singleSelection, + HdxPickHitVector* result) { TRACE_FUNCTION(); MProfilingScope profilingScope( - ProfilerCategory, - MProfiler::kColorE_L3, - "Batch Renderer Testing Intersection"); + ProfilerCategory, MProfiler::kColorE_L3, "Batch Renderer Testing Intersection"); if (!result) { return false; } - glPushAttrib(GL_VIEWPORT_BIT | - GL_ENABLE_BIT | - GL_COLOR_BUFFER_BIT | - GL_DEPTH_BUFFER_BIT | - GL_STENCIL_BUFFER_BIT | - GL_TEXTURE_BIT | - GL_POLYGON_BIT); + glPushAttrib( + GL_VIEWPORT_BIT | GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT + | GL_STENCIL_BUFFER_BIT | GL_TEXTURE_BIT | GL_POLYGON_BIT); // hydra orients all geometry during topological processing so that // front faces have ccw winding. We disable culling because culling @@ -1166,9 +1047,8 @@ UsdMayaGLBatchRenderer::_TestIntersection( HdxPickTaskContextParams pickParams; pickParams.resolution = _selectionResolution; - pickParams.resolveMode = singleSelection ? - HdxPickTokens->resolveNearestToCenter : - HdxPickTokens->resolveUnique; + pickParams.resolveMode + = singleSelection ? HdxPickTokens->resolveNearestToCenter : HdxPickTokens->resolveUnique; pickParams.viewMatrix = viewMatrix; pickParams.projectionMatrix = projectionMatrix; pickParams.collection = rprimCollection; @@ -1183,20 +1063,17 @@ UsdMayaGLBatchRenderer::_TestIntersection( return (result->size() > 0); } -void -UsdMayaGLBatchRenderer::_ComputeSelection( - _ShapeAdapterBucketsMap& bucketsMap, - const M3dView* view3d, - const GfMatrix4d& viewMatrix, - const GfMatrix4d& projectionMatrix, - const bool singleSelection) +void UsdMayaGLBatchRenderer::_ComputeSelection( + _ShapeAdapterBucketsMap& bucketsMap, + const M3dView* view3d, + const GfMatrix4d& viewMatrix, + const GfMatrix4d& projectionMatrix, + const bool singleSelection) { TRACE_FUNCTION(); MProfilingScope profilingScope( - ProfilerCategory, - MProfiler::kColorE_L3, - "Batch Renderer Computing Selection"); + ProfilerCategory, MProfiler::kColorE_L3, "Batch Renderer Computing Selection"); // If depth selection has not been turned on, then we can optimize // area/marquee selections by handling collections similarly to a single @@ -1204,36 +1081,40 @@ UsdMayaGLBatchRenderer::_ComputeSelection( // renderer-based collection. const bool useDepthSelection = (!singleSelection && _enableDepthSelection); - const PxrMayaHdPrimFilterVector primFilters = - _GetIntersectionPrimFilters(bucketsMap, view3d, useDepthSelection); + const PxrMayaHdPrimFilterVector primFilters + = _GetIntersectionPrimFilters(bucketsMap, view3d, useDepthSelection); - TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg( - " ____________ SELECTION STAGE START ______________ " - "(singleSelection = %s, %zu prim filter(s))\n", - singleSelection ? "true" : "false", - primFilters.size()); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION) + .Msg( + " ____________ SELECTION STAGE START ______________ " + "(singleSelection = %s, %zu prim filter(s))\n", + singleSelection ? "true" : "false", + primFilters.size()); _selectResults.clear(); GLUniformBufferBindingsSaver bindingsSaver; for (const PxrMayaHdPrimFilter& primFilter : primFilters) { - TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg( - " --- Intersection Testing with collection: %s\n", - primFilter.collection.GetName().GetText()); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION) + .Msg( + " --- Intersection Testing with collection: %s\n", + primFilter.collection.GetName().GetText()); HdxPickHitVector hits; - if (!_TestIntersection(primFilter.collection, primFilter.renderTags, - viewMatrix, projectionMatrix, - singleSelection, &hits)) { + if (!_TestIntersection( + primFilter.collection, + primFilter.renderTags, + viewMatrix, + projectionMatrix, + singleSelection, + &hits)) { continue; } for (const HdxPickHit& hit : hits) { - const auto itIfExists = - _selectResults.emplace( - std::make_pair(hit.delegateId, - HdxPickHitVector({hit}))); + const auto itIfExists + = _selectResults.emplace(std::make_pair(hit.delegateId, HdxPickHitVector({ hit }))); const bool& inserted = itIfExists.second; if (!inserted) { @@ -1245,34 +1126,34 @@ UsdMayaGLBatchRenderer::_ComputeSelection( // Populate the Hydra selection from the selection results. HdSelectionSharedPtr selection(new HdSelection); - const HdSelection::HighlightMode selectionMode = - HdSelection::HighlightModeSelect; + const HdSelection::HighlightMode selectionMode = HdSelection::HighlightModeSelect; for (const auto& delegateHits : _selectResults) { const HdxPickHitVector& hitSet = delegateHits.second; for (const HdxPickHit& hit : hitSet) { - TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg( + TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION) + .Msg( #if USD_VERSION_NUM > 1911 - " NEW HIT\n" - " delegateId : %s\n" - " objectId : %s\n" - " instanceIndex : %d\n" - " normalizedDepth : %f\n", - hit.delegateId.GetText(), - hit.objectId.GetText(), - hit.instanceIndex, - hit.normalizedDepth); + " NEW HIT\n" + " delegateId : %s\n" + " objectId : %s\n" + " instanceIndex : %d\n" + " normalizedDepth : %f\n", + hit.delegateId.GetText(), + hit.objectId.GetText(), + hit.instanceIndex, + hit.normalizedDepth); #else - " NEW HIT\n" - " delegateId : %s\n" - " objectId : %s\n" - " instanceIndex: %d\n" - " ndcDepth : %f\n", - hit.delegateId.GetText(), - hit.objectId.GetText(), - hit.instanceIndex, - hit.ndcDepth); + " NEW HIT\n" + " delegateId : %s\n" + " objectId : %s\n" + " instanceIndex: %d\n" + " ndcDepth : %f\n", + hit.delegateId.GetText(), + hit.objectId.GetText(), + hit.instanceIndex, + hit.ndcDepth); #endif if (!hit.instancerId.IsEmpty()) { @@ -1286,35 +1167,27 @@ UsdMayaGLBatchRenderer::_ComputeSelection( _selectionTracker->SetSelection(selection); - TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION).Msg( - " ^^^^^^^^^^^^ SELECTION STAGE FINISH ^^^^^^^^^^^^^\n"); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_SELECTION) + .Msg(" ^^^^^^^^^^^^ SELECTION STAGE FINISH ^^^^^^^^^^^^^\n"); } -void -UsdMayaGLBatchRenderer::_Render( - const GfMatrix4d& worldToViewMatrix, - const GfMatrix4d& projectionMatrix, - const GfVec4d& viewport, - unsigned int displayStyle, - const std::vector<_RenderItem>& items) +void UsdMayaGLBatchRenderer::_Render( + const GfMatrix4d& worldToViewMatrix, + const GfMatrix4d& projectionMatrix, + const GfVec4d& viewport, + unsigned int displayStyle, + const std::vector<_RenderItem>& items) { TRACE_FUNCTION(); MProfilingScope profilingScope( - ProfilerCategory, - MProfiler::kColorC_L2, - "Batch Renderer Rendering Batch"); + ProfilerCategory, MProfiler::kColorC_L2, "Batch Renderer Rendering Batch"); - _taskDelegate->SetCameraState(worldToViewMatrix, - projectionMatrix, - viewport); + _taskDelegate->SetCameraState(worldToViewMatrix, projectionMatrix, viewport); // save the current GL states which hydra may reset to default - glPushAttrib(GL_LIGHTING_BIT | - GL_ENABLE_BIT | - GL_POLYGON_BIT | - GL_DEPTH_BUFFER_BIT | - GL_VIEWPORT_BIT); + glPushAttrib( + GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_POLYGON_BIT | GL_DEPTH_BUFFER_BIT | GL_VIEWPORT_BIT); GLUniformBufferBindingsSaver bindingsSaver; @@ -1345,35 +1218,29 @@ UsdMayaGLBatchRenderer::_Render( for (const auto& iter : items) { const PxrMayaHdRenderParams& params = iter.first; - const size_t paramsHash = params.Hash(); + const size_t paramsHash = params.Hash(); const PxrMayaHdPrimFilterVector& primFilters = iter.second; - TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg( - " *** renderBucket, parameters hash: %zu, bucket size %zu\n", - paramsHash, - primFilters.size()); - - HdTaskSharedPtrVector renderTasks = - _taskDelegate->GetRenderTasks( + TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING) + .Msg( + " *** renderBucket, parameters hash: %zu, bucket size %zu\n", paramsHash, - params, - displayStyle, - primFilters); + primFilters.size()); + + HdTaskSharedPtrVector renderTasks + = _taskDelegate->GetRenderTasks(paramsHash, params, displayStyle, primFilters); tasks.insert(tasks.end(), renderTasks.begin(), renderTasks.end()); } VtValue selectionTrackerValue(_selectionTracker); - _hdEngine.SetTaskContextData(HdxTokens->selectionState, - selectionTrackerValue); + _hdEngine.SetTaskContextData(HdxTokens->selectionState, selectionTrackerValue); { TRACE_SCOPE("Executing Hydra Tasks"); MProfilingScope hydraProfilingScope( - ProfilerCategory, - MProfiler::kColorC_L3, - "Batch Renderer Executing Hydra Tasks"); + ProfilerCategory, MProfiler::kColorC_L3, "Batch Renderer Executing Hydra Tasks"); _hdEngine.Execute(_renderIndex.get(), &tasks); } @@ -1384,51 +1251,48 @@ UsdMayaGLBatchRenderer::_Render( // GL_DEPTH_BUFFER_BIT | GL_VIEWPORT_BIT } -void -UsdMayaGLBatchRenderer::_RenderBatches( - const MHWRender::MDrawContext* vp2Context, - const M3dView* view3d, - const GfMatrix4d& worldToViewMatrix, - const GfMatrix4d& projectionMatrix, - const GfVec4d& viewport) +void UsdMayaGLBatchRenderer::_RenderBatches( + const MHWRender::MDrawContext* vp2Context, + const M3dView* view3d, + const GfMatrix4d& worldToViewMatrix, + const GfMatrix4d& projectionMatrix, + const GfVec4d& viewport) { TRACE_FUNCTION(); MProfilingScope profilingScope( - ProfilerCategory, - MProfiler::kColorC_L2, - "Batch Renderer Rendering Batches"); + ProfilerCategory, MProfiler::kColorC_L2, "Batch Renderer Rendering Batches"); - _ShapeAdapterBucketsMap& bucketsMap = bool(vp2Context) ? - _shapeAdapterBuckets : - _legacyShapeAdapterBuckets; + _ShapeAdapterBucketsMap& bucketsMap + = bool(vp2Context) ? _shapeAdapterBuckets : _legacyShapeAdapterBuckets; if (bucketsMap.empty()) { return; } if (TfDebug::IsEnabled(PXRUSDMAYAGL_BATCHED_DRAWING)) { - TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg( - "Drawing batches for %s\n", - bool(vp2Context) ? "Viewport 2.0" : "legacy viewport"); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING) + .Msg("Drawing batches for %s\n", bool(vp2Context) ? "Viewport 2.0" : "legacy viewport"); if (vp2Context) { - const MUint64 frameStamp = vp2Context->getFrameStamp(); + const MUint64 frameStamp = vp2Context->getFrameStamp(); const MHWRender::MPassContext& passContext = vp2Context->getPassContext(); - const MString& passId = passContext.passIdentifier(); - const MStringArray& passSemantics = passContext.passSemantics(); - - TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg( - " frameStamp: %s, passIdentifier: %s, passSemantics: %s\n", - TfStringify(frameStamp).c_str(), - passId.asChar(), - TfStringify(passSemantics).c_str()); + const MString& passId = passContext.passIdentifier(); + const MStringArray& passSemantics = passContext.passSemantics(); + + TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING) + .Msg( + " frameStamp: %s, passIdentifier: %s, passSemantics: %s\n", + TfStringify(frameStamp).c_str(), + passId.asChar(), + TfStringify(passSemantics).c_str()); } } - TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg( - " ____________ RENDER STAGE START ______________ (%zu buckets)\n", - bucketsMap.size()); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING) + .Msg( + " ____________ RENDER STAGE START ______________ (%zu buckets)\n", + bucketsMap.size()); // A new display refresh signifies that the cached selection data is no // longer valid. @@ -1442,50 +1306,43 @@ UsdMayaGLBatchRenderer::_RenderBatches( // Assume shaded displayStyle, but we *should* be able to pull it from // either the vp2Context for Viewport 2.0 or the M3dView for the legacy // viewport. - unsigned int displayStyle = - MHWRender::MFrameContext::DisplayStyle::kGouraudShaded; + unsigned int displayStyle = MHWRender::MFrameContext::DisplayStyle::kGouraudShaded; if (vp2Context) { displayStyle = vp2Context->getDisplayStyle(); } else if (view3d) { - const M3dView::DisplayStyle legacyDisplayStyle = - view3d->displayStyle(); - displayStyle = - px_LegacyViewportUtils::GetMFrameContextDisplayStyle( - legacyDisplayStyle); + const M3dView::DisplayStyle legacyDisplayStyle = view3d->displayStyle(); + displayStyle = px_LegacyViewportUtils::GetMFrameContextDisplayStyle(legacyDisplayStyle); } // Since we'll be populating the prim filters with shape adapters, we don't // need to specify collections or render tags on them, so just use empty // ones. static const HdRprimCollection emptyCollection; - static const TfTokenVector emptyRenderTags; + static const TfTokenVector emptyRenderTags; - bool itemsVisible = false; + bool itemsVisible = false; std::vector<_RenderItem> items; for (const auto& iter : bucketsMap) { const PxrMayaHdRenderParams& params = iter.second.first; - const _ShapeAdapterSet& shapeAdapters = iter.second.second; + const _ShapeAdapterSet& shapeAdapters = iter.second.second; PxrMayaHdPrimFilterVector primFilters; for (PxrMayaHdShapeAdapter* shapeAdapter : shapeAdapters) { shapeAdapter->UpdateVisibility(view3d); itemsVisible |= shapeAdapter->IsVisible(); - primFilters.push_back(PxrMayaHdPrimFilter { - shapeAdapter, - emptyCollection, - emptyRenderTags - }); + primFilters.push_back( + PxrMayaHdPrimFilter { shapeAdapter, emptyCollection, emptyRenderTags }); } items.push_back(std::make_pair(params, std::move(primFilters))); } if (!itemsVisible) { - TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg( - " *** No objects visible.\n" - " ^^^^^^^^^^^^ RENDER STAGE FINISH ^^^^^^^^^^^^^\n"); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING) + .Msg(" *** No objects visible.\n" + " ^^^^^^^^^^^^ RENDER STAGE FINISH ^^^^^^^^^^^^^\n"); return; } @@ -1511,17 +1368,12 @@ UsdMayaGLBatchRenderer::_RenderBatches( const GfVec4f zeroAmbient(0.0f, 0.0f, 0.0f, 1.0f); glLightModelfv(GL_LIGHT_MODEL_AMBIENT, zeroAmbient.data()); - _taskDelegate->SetLightingStateFromVP1(worldToViewMatrix, - projectionMatrix); + _taskDelegate->SetLightingStateFromVP1(worldToViewMatrix, projectionMatrix); glPopAttrib(); // GL_LIGHTING_BIT } - _Render(worldToViewMatrix, - projectionMatrix, - viewport, - displayStyle, - items); + _Render(worldToViewMatrix, projectionMatrix, viewport, displayStyle, items); // Viewport 2 may be rendering in multiple passes, and we want to make sure // we draw once (and only once) for each of those passes, so we delay @@ -1534,12 +1386,11 @@ UsdMayaGLBatchRenderer::_RenderBatches( _MayaRenderDidEnd(nullptr); } - TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg( - " ^^^^^^^^^^^^ RENDER STAGE FINISH ^^^^^^^^^^^^^\n"); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING) + .Msg(" ^^^^^^^^^^^^ RENDER STAGE FINISH ^^^^^^^^^^^^^\n"); } -bool -UsdMayaGLBatchRenderer::_UpdateIsSelectionPending(const bool isPending) +bool UsdMayaGLBatchRenderer::_UpdateIsSelectionPending(const bool isPending) { if (_isSelectionPending == isPending) { return false; @@ -1550,17 +1401,14 @@ UsdMayaGLBatchRenderer::_UpdateIsSelectionPending(const bool isPending) return true; } -void -UsdMayaGLBatchRenderer::StartBatchingFrameDiagnostics() +void UsdMayaGLBatchRenderer::StartBatchingFrameDiagnostics() { if (!_sharedDiagBatchCtx) { _sharedDiagBatchCtx.reset(new UsdMayaDiagnosticBatchContext()); } } -void -UsdMayaGLBatchRenderer::_MayaRenderDidEnd( - const MHWRender::MDrawContext* /* context */) +void UsdMayaGLBatchRenderer::_MayaRenderDidEnd(const MHWRender::MDrawContext* /* context */) { // Completing a viewport render invalidates any previous selection // computation we may have done, so mark a new one as pending. @@ -1570,5 +1418,4 @@ UsdMayaGLBatchRenderer::_MayaRenderDidEnd( _sharedDiagBatchCtx.reset(); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/batchRenderer.h b/lib/mayaUsd/render/pxrUsdMayaGL/batchRenderer.h index 478d0d7bd8..095db19953 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/batchRenderer.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/batchRenderer.h @@ -33,19 +33,15 @@ // // The X11 include appears to have been removed in Maya 2020+, so this should // no longer be an issue with later versions. -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include -#include #include #include #include @@ -59,16 +55,19 @@ #include #include #include +#include #include +#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #if USD_VERSION_NUM > 2002 #include @@ -104,10 +103,10 @@ using HgiUniquePtr = std::unique_ptr; /// for their shape to participate in batched drawing and selection. /// class UsdMayaGLBatchRenderer - : public TfSingleton, public TfWeakBase + : public TfSingleton + , public TfWeakBase { public: - /// Maya profiler category ID MAYAUSD_CORE_PUBLIC static const int ProfilerCategory; @@ -177,9 +176,7 @@ class UsdMayaGLBatchRenderer /// Legacy shape adapters. You cannot rely on the shape adapters being /// associated with a specific viewport. MAYAUSD_CORE_PUBLIC - bool PopulateCustomPrimFilter( - const MDagPath& dagPath, - PxrMayaHdPrimFilter& primFilter); + bool PopulateCustomPrimFilter(const MDagPath& dagPath, PxrMayaHdPrimFilter& primFilter); /// Render batch in the legacy viewport based on \p request MAYAUSD_CORE_PUBLIC @@ -187,9 +184,7 @@ class UsdMayaGLBatchRenderer /// Render batch in Viewport 2.0 based on \p userData MAYAUSD_CORE_PUBLIC - void Draw( - const MHWRender::MDrawContext& context, - const MUserData* userData); + void Draw(const MHWRender::MDrawContext& context, const MUserData* userData); /// Render bounding box in the legacy viewport based on \p request MAYAUSD_CORE_PUBLIC @@ -197,9 +192,7 @@ class UsdMayaGLBatchRenderer /// Render bounding box in Viewport 2.0 based on \p userData MAYAUSD_CORE_PUBLIC - void DrawBoundingBox( - const MHWRender::MDrawContext& context, - const MUserData* userData); + void DrawBoundingBox(const MHWRender::MDrawContext& context, const MUserData* userData); /// Gets the resolution of the draw target used for computing selections. /// @@ -235,9 +228,8 @@ class UsdMayaGLBatchRenderer /// erased at the next selection, so clients should make copies if they /// need the data to persist. MAYAUSD_CORE_PUBLIC - const HdxPickHitVector* TestIntersection( - const PxrMayaHdShapeAdapter* shapeAdapter, - MSelectInfo& selectInfo); + const HdxPickHitVector* + TestIntersection(const PxrMayaHdShapeAdapter* shapeAdapter, MSelectInfo& selectInfo); /// Tests the object from the given shape adapter for intersection with /// a given draw context in Viewport 2.0. @@ -250,9 +242,9 @@ class UsdMayaGLBatchRenderer /// need the data to persist. MAYAUSD_CORE_PUBLIC const HdxPickHitVector* TestIntersection( - const PxrMayaHdShapeAdapter* shapeAdapter, - const MHWRender::MSelectionInfo& selectionInfo, - const MHWRender::MDrawContext& context); + const PxrMayaHdShapeAdapter* shapeAdapter, + const MHWRender::MSelectionInfo& selectionInfo, + const MHWRender::MDrawContext& context); /// Tests the contents of the given prim filter (previously obtained /// via PopulateCustomFilter) for intersection with the current OpenGL @@ -265,10 +257,10 @@ class UsdMayaGLBatchRenderer /// the intersection result. MAYAUSD_CORE_PUBLIC bool TestIntersectionCustomPrimFilter( - const PxrMayaHdPrimFilter& primFilter, - const GfMatrix4d& viewMatrix, - const GfMatrix4d& projectionMatrix, - HdxPickHitVector* outResult); + const PxrMayaHdPrimFilter& primFilter, + const GfMatrix4d& viewMatrix, + const GfMatrix4d& projectionMatrix, + HdxPickHitVector* outResult); /// Utility function for finding the nearest hit (in terms of /// normalizedDepth) in the given \p hitSet. @@ -276,13 +268,11 @@ class UsdMayaGLBatchRenderer /// If \p hitSet is nullptr or is empty, nullptr is returned. Otherwise a /// pointer to the nearest hit in \p hitSet is returned. MAYAUSD_CORE_PUBLIC - static const HdxPickHit* GetNearestHit( - const HdxPickHitVector* hitSet); + static const HdxPickHit* GetNearestHit(const HdxPickHitVector* hitSet); /// Returns whether soft selection for proxy shapes is currently enabled. MAYAUSD_CORE_PUBLIC - inline bool GetObjectSoftSelectEnabled() - { return _objectSoftSelectEnabled; } + inline bool GetObjectSoftSelectEnabled() { return _objectSoftSelectEnabled; } /// Starts batching all diagnostics until the end of the current frame draw. /// The batch renderer will automatically release the diagnostics when Maya @@ -291,7 +281,6 @@ class UsdMayaGLBatchRenderer void StartBatchingFrameDiagnostics(); private: - friend class TfSingleton; MAYAUSD_CORE_PUBLIC @@ -309,18 +298,17 @@ class UsdMayaGLBatchRenderer /// Allow shape adapters access to the soft selection helper. friend PxrMayaHdShapeAdapter; - typedef std::pair - _RenderItem; + typedef std::pair _RenderItem; /// Private helper function to render the given list of render items. /// Note that this doesn't set lighting, so if you need to update the /// lighting from the scene, you need to do that beforehand. void _Render( - const GfMatrix4d& worldToViewMatrix, - const GfMatrix4d& projectionMatrix, - const GfVec4d& viewport, - unsigned int displayStyle, - const std::vector<_RenderItem>& items); + const GfMatrix4d& worldToViewMatrix, + const GfMatrix4d& projectionMatrix, + const GfVec4d& viewport, + unsigned int displayStyle, + const std::vector<_RenderItem>& items); /// Call to render all queued batches. May be called safely without /// performance hit when no batches are queued. @@ -328,23 +316,23 @@ class UsdMayaGLBatchRenderer /// when determining visibility. If it's null, then assumes that there's no /// isolated selection. void _RenderBatches( - const MHWRender::MDrawContext* vp2Context, - const M3dView* view3d, - const GfMatrix4d& worldToViewMatrix, - const GfMatrix4d& projectionMatrix, - const GfVec4d& viewport); + const MHWRender::MDrawContext* vp2Context, + const M3dView* view3d, + const GfMatrix4d& worldToViewMatrix, + const GfMatrix4d& projectionMatrix, + const GfVec4d& viewport); /// Private helper function for testing intersection on a single collection /// only. /// \returns True if there was at least one hit. All hits are returned in /// the \p *result. bool _TestIntersection( - const HdRprimCollection& rprimCollection, - const TfTokenVector& renderTags, - const GfMatrix4d& viewMatrix, - const GfMatrix4d& projectionMatrix, - const bool singleSelection, - HdxPickHitVector* result); + const HdRprimCollection& rprimCollection, + const TfTokenVector& renderTags, + const GfMatrix4d& viewMatrix, + const GfMatrix4d& projectionMatrix, + const bool singleSelection, + HdxPickHitVector* result); // Handler for Maya scene resets (e.g. new scene or switch scenes). void _OnMayaSceneReset(const UsdMayaSceneResetNotice& notice); @@ -357,9 +345,7 @@ class UsdMayaGLBatchRenderer /// some state in the batch renderer and prepare it for subsequent /// selection. /// For the legacy viewport, there is no such notification sent by Maya. - static void _OnMayaEndRenderCallback( - MHWRender::MDrawContext& context, - void* clientData); + static void _OnMayaEndRenderCallback(MHWRender::MDrawContext& context, void* clientData); /// Record changes to soft select options /// @@ -386,7 +372,7 @@ class UsdMayaGLBatchRenderer /// selection as pending. bool _isSelectionPending; - bool _objectSoftSelectEnabled; + bool _objectSoftSelectEnabled; MCallbackId _softSelectOptionsCallbackId; /// Type definition for a set of pointers to shape adapters. @@ -411,8 +397,7 @@ class UsdMayaGLBatchRenderer /// Mapping of Maya object handles to their shape adapters. /// This is a "secondary" container for storing shape adapters. - typedef UsdMayaUtil::MObjectHandleUnorderedMap - _ShapeAdapterHandleMap; + typedef UsdMayaUtil::MObjectHandleUnorderedMap _ShapeAdapterHandleMap; /// We maintain separate object handle path maps for Viewport 2.0 and the /// legacy viewport. @@ -433,9 +418,9 @@ class UsdMayaGLBatchRenderer /// Otherwise, we test each shape adapter's prim filter individually so that /// occluded shapes will be included in the selection. PxrMayaHdPrimFilterVector _GetIntersectionPrimFilters( - _ShapeAdapterBucketsMap& bucketsMap, - const M3dView* view, - const bool useDepthSelection) const; + _ShapeAdapterBucketsMap& bucketsMap, + const M3dView* view, + const bool useDepthSelection) const; /// Populates the selection results using the given parameters by /// performing intersection tests against all of the shapes in the given @@ -444,11 +429,11 @@ class UsdMayaGLBatchRenderer /// when determining visibility. If it's null, then assumes that there's no /// isolated selection. void _ComputeSelection( - _ShapeAdapterBucketsMap& bucketsMap, - const M3dView* view3d, - const GfMatrix4d& viewMatrix, - const GfMatrix4d& projectionMatrix, - const bool singleSelection); + _ShapeAdapterBucketsMap& bucketsMap, + const M3dView* view3d, + const GfMatrix4d& viewMatrix, + const GfMatrix4d& projectionMatrix, + const bool singleSelection); /// A cache of all selection results gathered since the last selection was /// computed. It maps delegate IDs to a HitSet of all of the intersection @@ -459,7 +444,7 @@ class UsdMayaGLBatchRenderer /// This is used to determine if the results can be shared among multiple /// shapes calling TestIntersection. typedef std::tuple _SelectResultsKey; - _SelectResultsKey _selectResultsKey; + _SelectResultsKey _selectResultsKey; /// Hydra engine objects used to render batches. /// @@ -473,10 +458,10 @@ class UsdMayaGLBatchRenderer /// Hgi and HdDriver should be constructed before HdEngine to ensure they /// are destructed last. Hgi may be used during engine/delegate destruction. HgiUniquePtr _hgi; - HdDriver _hgiDriver; + HdDriver _hgiDriver; #endif - HdEngine _hdEngine; - HdStRenderDelegate _renderDelegate; + HdEngine _hdEngine; + HdStRenderDelegate _renderDelegate; std::unique_ptr _renderIndex; /// The root ID of the batch renderer itself, and the top of the path @@ -494,7 +479,7 @@ class UsdMayaGLBatchRenderer PxrMayaHdSceneDelegateSharedPtr _taskDelegate; GfVec2i _selectionResolution; - bool _enableDepthSelection; + bool _enableDepthSelection; HdxSelectionTrackerSharedPtr _selectionTracker; @@ -509,8 +494,6 @@ class UsdMayaGLBatchRenderer MAYAUSD_TEMPLATE_CLASS(TfSingleton); - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/debugCodes.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/debugCodes.cpp index 1f23e8e1ce..cfa98950ab 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/debugCodes.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/debugCodes.cpp @@ -15,21 +15,19 @@ // #include "debugCodes.h" -#include #include #include +#include PXR_NAMESPACE_OPEN_SCOPE TF_REGISTRY_FUNCTION(TfDebug) { TF_DEBUG_ENVIRONMENT_SYMBOL( - PXRUSDMAYAGL_BATCHED_DRAWING, - "Prints out batched drawing event info."); + PXRUSDMAYAGL_BATCHED_DRAWING, "Prints out batched drawing event info."); TF_DEBUG_ENVIRONMENT_SYMBOL( - PXRUSDMAYAGL_BATCHED_SELECTION, - "Prints out batched selection event info."); + PXRUSDMAYAGL_BATCHED_SELECTION, "Prints out batched selection event info."); TF_DEBUG_ENVIRONMENT_SYMBOL( PXRUSDMAYAGL_INSTANCER_TRACKING, @@ -42,9 +40,7 @@ TF_REGISTRY_FUNCTION(TfDebug) "batch renderer."); TF_DEBUG_ENVIRONMENT_SYMBOL( - PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE, - "Report Maya Hydra shape adapter lifecycle events."); + PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE, "Report Maya Hydra shape adapter lifecycle events."); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/debugCodes.h b/lib/mayaUsd/render/pxrUsdMayaGL/debugCodes.h index b68d73d5b5..4858c2f431 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/debugCodes.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/debugCodes.h @@ -18,8 +18,8 @@ /// \file pxrUsdMayaGL/debugCodes.h -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -28,8 +28,7 @@ TF_DEBUG_CODES( PXRUSDMAYAGL_BATCHED_SELECTION, PXRUSDMAYAGL_INSTANCER_TRACKING, PXRUSDMAYAGL_SHAPE_ADAPTER_BUCKETING, - PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE -); + PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE); PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeDrawOverride.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeDrawOverride.cpp index 2885d38c45..c66ccf7b39 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeDrawOverride.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeDrawOverride.cpp @@ -15,9 +15,21 @@ // #include "hdImagingShapeDrawOverride.h" +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + #include -#include #include +#include #include #include #include @@ -30,27 +42,16 @@ #include #include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE const MString PxrMayaHdImagingShapeDrawOverride::drawDbClassification( - TfStringPrintf("drawdb/geometry/pxrUsdMayaGL/%s", - PxrMayaHdImagingShapeTokens->MayaTypeName.GetText()).c_str()); + TfStringPrintf( + "drawdb/geometry/pxrUsdMayaGL/%s", + PxrMayaHdImagingShapeTokens->MayaTypeName.GetText()) + .c_str()); /* static */ -MHWRender::MPxDrawOverride* -PxrMayaHdImagingShapeDrawOverride::creator(const MObject& obj) +MHWRender::MPxDrawOverride* PxrMayaHdImagingShapeDrawOverride::creator(const MObject& obj) { UsdMayaGLBatchRenderer::Init(); return new PxrMayaHdImagingShapeDrawOverride(obj); @@ -63,17 +64,15 @@ PxrMayaHdImagingShapeDrawOverride::~PxrMayaHdImagingShapeDrawOverride() } /* virtual */ -MHWRender::DrawAPI -PxrMayaHdImagingShapeDrawOverride::supportedDrawAPIs() const +MHWRender::DrawAPI PxrMayaHdImagingShapeDrawOverride::supportedDrawAPIs() const { return MHWRender::kOpenGL | MHWRender::kOpenGLCoreProfile; } /* virtual */ -MMatrix -PxrMayaHdImagingShapeDrawOverride::transform( - const MDagPath& /* objPath */, - const MDagPath& /* cameraPath */) const +MMatrix PxrMayaHdImagingShapeDrawOverride::transform( + const MDagPath& /* objPath */, + const MDagPath& /* cameraPath */) const { // Always ignore any transform on the pxrHdImagingShape and use an identity // transform instead. @@ -81,10 +80,9 @@ PxrMayaHdImagingShapeDrawOverride::transform( } /* virtual */ -MBoundingBox -PxrMayaHdImagingShapeDrawOverride::boundingBox( - const MDagPath& objPath, - const MDagPath& /* cameraPath */) const +MBoundingBox PxrMayaHdImagingShapeDrawOverride::boundingBox( + const MDagPath& objPath, + const MDagPath& /* cameraPath */) const { TRACE_FUNCTION(); @@ -93,8 +91,7 @@ PxrMayaHdImagingShapeDrawOverride::boundingBox( MProfiler::kColorE_L1, "Hydra Imaging Shape Computing Bounding Box (Viewport 2.0)"); - const PxrMayaHdImagingShape* imagingShape = - PxrMayaHdImagingShape::GetShapeAtDagPath(objPath); + const PxrMayaHdImagingShape* imagingShape = PxrMayaHdImagingShape::GetShapeAtDagPath(objPath); if (!imagingShape) { return MBoundingBox(); } @@ -103,13 +100,11 @@ PxrMayaHdImagingShapeDrawOverride::boundingBox( } /* virtual */ -bool -PxrMayaHdImagingShapeDrawOverride::isBounded( - const MDagPath& objPath, - const MDagPath& /* cameraPath */) const +bool PxrMayaHdImagingShapeDrawOverride::isBounded( + const MDagPath& objPath, + const MDagPath& /* cameraPath */) const { - const PxrMayaHdImagingShape* imagingShape = - PxrMayaHdImagingShape::GetShapeAtDagPath(objPath); + const PxrMayaHdImagingShape* imagingShape = PxrMayaHdImagingShape::GetShapeAtDagPath(objPath); if (!imagingShape) { return false; } @@ -118,19 +113,14 @@ PxrMayaHdImagingShapeDrawOverride::isBounded( } /* virtual */ -bool -PxrMayaHdImagingShapeDrawOverride::disableInternalBoundingBoxDraw() const -{ - return true; -} +bool PxrMayaHdImagingShapeDrawOverride::disableInternalBoundingBoxDraw() const { return true; } /* virtual */ -MUserData* -PxrMayaHdImagingShapeDrawOverride::prepareForDraw( - const MDagPath& objPath, - const MDagPath& /* cameraPath */, - const MHWRender::MFrameContext& frameContext, - MUserData* oldData) +MUserData* PxrMayaHdImagingShapeDrawOverride::prepareForDraw( + const MDagPath& objPath, + const MDagPath& /* cameraPath */, + const MHWRender::MFrameContext& frameContext, + MUserData* oldData) { TRACE_FUNCTION(); @@ -139,44 +129,38 @@ PxrMayaHdImagingShapeDrawOverride::prepareForDraw( MProfiler::kColorE_L2, "Hydra Imaging Shape prepareForDraw() (Viewport 2.0)"); - const PxrMayaHdImagingShape* imagingShape = - PxrMayaHdImagingShape::GetShapeAtDagPath(objPath); + const PxrMayaHdImagingShape* imagingShape = PxrMayaHdImagingShape::GetShapeAtDagPath(objPath); if (!imagingShape) { return nullptr; } - TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg( - "PxrMayaHdImagingShapeDrawOverride::prepareForDraw(), objPath: %s\n", - objPath.fullPathName().asChar()); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING) + .Msg( + "PxrMayaHdImagingShapeDrawOverride::prepareForDraw(), objPath: %s\n", + objPath.fullPathName().asChar()); // The HdImagingShape is very rarely marked dirty, but one of the things // that does so is changing batch renderer settings attributes, so we grab // the values from the shape here and pass them along to the batch // renderer. Settings that affect selection should then be set // appropriately for subsequent selections. - MStatus status; + MStatus status; const MFnDependencyNode depNodeFn(imagingShape->thisMObject(), &status); if (status == MS::kSuccess) { - const MPlug selectionResolutionPlug = - depNodeFn.findPlug( - PxrMayaHdImagingShape::selectionResolutionAttr, - &status); + const MPlug selectionResolutionPlug + = depNodeFn.findPlug(PxrMayaHdImagingShape::selectionResolutionAttr, &status); if (status == MS::kSuccess) { - const short selectionResolution = - selectionResolutionPlug.asShort(&status); + const short selectionResolution = selectionResolutionPlug.asShort(&status); if (status == MS::kSuccess) { UsdMayaGLBatchRenderer::GetInstance().SetSelectionResolution( GfVec2i(selectionResolution)); } } - const MPlug enableDepthSelectionPlug = - depNodeFn.findPlug( - PxrMayaHdImagingShape::enableDepthSelectionAttr, - &status); + const MPlug enableDepthSelectionPlug + = depNodeFn.findPlug(PxrMayaHdImagingShape::enableDepthSelectionAttr, &status); if (status == MS::kSuccess) { - const bool enableDepthSelection = - enableDepthSelectionPlug.asBool(&status); + const bool enableDepthSelection = enableDepthSelectionPlug.asBool(&status); if (status == MS::kSuccess) { UsdMayaGLBatchRenderer::GetInstance().SetDepthSelectionEnabled( enableDepthSelection); @@ -185,8 +169,7 @@ PxrMayaHdImagingShapeDrawOverride::prepareForDraw( } // Sync any instancers that need Hydra drawing. - UsdMayaGL_InstancerImager::GetInstance().SyncShapeAdapters( - frameContext.getDisplayStyle()); + UsdMayaGL_InstancerImager::GetInstance().SyncShapeAdapters(frameContext.getDisplayStyle()); PxrMayaHdUserData* newData = dynamic_cast(oldData); if (!newData) { @@ -197,10 +180,9 @@ PxrMayaHdImagingShapeDrawOverride::prepareForDraw( } /* static */ -void -PxrMayaHdImagingShapeDrawOverride::draw( - const MHWRender::MDrawContext& context, - const MUserData* data) +void PxrMayaHdImagingShapeDrawOverride::draw( + const MHWRender::MDrawContext& context, + const MUserData* data) { TRACE_FUNCTION(); @@ -209,20 +191,17 @@ PxrMayaHdImagingShapeDrawOverride::draw( MProfiler::kColorC_L1, "Hydra Imaging Shape draw() (Viewport 2.0)"); - TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg( - "PxrMayaHdImagingShapeDrawOverride::draw()\n"); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg("PxrMayaHdImagingShapeDrawOverride::draw()\n"); UsdMayaGLBatchRenderer::GetInstance().Draw(context, data); } -PxrMayaHdImagingShapeDrawOverride::PxrMayaHdImagingShapeDrawOverride( - const MObject& obj) : - MHWRender::MPxDrawOverride( +PxrMayaHdImagingShapeDrawOverride::PxrMayaHdImagingShapeDrawOverride(const MObject& obj) + : MHWRender::MPxDrawOverride( obj, PxrMayaHdImagingShapeDrawOverride::draw, /* isAlwaysDirty = */ false) { } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeDrawOverride.h b/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeDrawOverride.h index 71dfb1a6fc..b6c72605bf 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeDrawOverride.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeDrawOverride.h @@ -18,6 +18,10 @@ /// \file pxrUsdMayaGL/hdImagingShapeDrawOverride.h +#include + +#include + #include #include #include @@ -29,10 +33,6 @@ #include #include -#include - -#include - PXR_NAMESPACE_OPEN_SCOPE /// Draw override for drawing the pxrHdImagingShape node in Viewport 2.0 @@ -49,62 +49,48 @@ PXR_NAMESPACE_OPEN_SCOPE /// re-compute the selection. class PxrMayaHdImagingShapeDrawOverride : public MHWRender::MPxDrawOverride { - public: - - MAYAUSD_CORE_PUBLIC - static const MString drawDbClassification; +public: + MAYAUSD_CORE_PUBLIC + static const MString drawDbClassification; - MAYAUSD_CORE_PUBLIC - static MHWRender::MPxDrawOverride* creator(const MObject& obj); + MAYAUSD_CORE_PUBLIC + static MHWRender::MPxDrawOverride* creator(const MObject& obj); - MAYAUSD_CORE_PUBLIC - ~PxrMayaHdImagingShapeDrawOverride() override; + MAYAUSD_CORE_PUBLIC + ~PxrMayaHdImagingShapeDrawOverride() override; - MAYAUSD_CORE_PUBLIC - MHWRender::DrawAPI supportedDrawAPIs() const override; + MAYAUSD_CORE_PUBLIC + MHWRender::DrawAPI supportedDrawAPIs() const override; - MAYAUSD_CORE_PUBLIC - MMatrix transform( - const MDagPath& objPath, - const MDagPath& cameraPath) const override; + MAYAUSD_CORE_PUBLIC + MMatrix transform(const MDagPath& objPath, const MDagPath& cameraPath) const override; - MAYAUSD_CORE_PUBLIC - MBoundingBox boundingBox( - const MDagPath& objPath, - const MDagPath& cameraPath) const override; + MAYAUSD_CORE_PUBLIC + MBoundingBox boundingBox(const MDagPath& objPath, const MDagPath& cameraPath) const override; - MAYAUSD_CORE_PUBLIC - bool isBounded( - const MDagPath& objPath, - const MDagPath& cameraPath) const override; + MAYAUSD_CORE_PUBLIC + bool isBounded(const MDagPath& objPath, const MDagPath& cameraPath) const override; - MAYAUSD_CORE_PUBLIC - bool disableInternalBoundingBoxDraw() const override; + MAYAUSD_CORE_PUBLIC + bool disableInternalBoundingBoxDraw() const override; - MAYAUSD_CORE_PUBLIC - MUserData* prepareForDraw( - const MDagPath& objPath, - const MDagPath& cameraPath, - const MHWRender::MFrameContext& frameContext, - MUserData* oldData) override; + MAYAUSD_CORE_PUBLIC + MUserData* prepareForDraw( + const MDagPath& objPath, + const MDagPath& cameraPath, + const MHWRender::MFrameContext& frameContext, + MUserData* oldData) override; - MAYAUSD_CORE_PUBLIC - static void draw( - const MHWRender::MDrawContext& context, - const MUserData* data); + MAYAUSD_CORE_PUBLIC + static void draw(const MHWRender::MDrawContext& context, const MUserData* data); - private: +private: + PxrMayaHdImagingShapeDrawOverride(const MObject& obj); - PxrMayaHdImagingShapeDrawOverride(const MObject& obj); - - PxrMayaHdImagingShapeDrawOverride( - const PxrMayaHdImagingShapeDrawOverride&) = delete; - PxrMayaHdImagingShapeDrawOverride& operator=( - const PxrMayaHdImagingShapeDrawOverride&) = delete; + PxrMayaHdImagingShapeDrawOverride(const PxrMayaHdImagingShapeDrawOverride&) = delete; + PxrMayaHdImagingShapeDrawOverride& operator=(const PxrMayaHdImagingShapeDrawOverride&) = delete; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeUI.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeUI.cpp index 81b85f8b62..4cbd7c0a11 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeUI.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeUI.cpp @@ -15,9 +15,20 @@ // #include "hdImagingShapeUI.h" +#include +#include +#include +#include +#include + +#include +#include +#include +#include + #include -#include #include +#include #include #include #include @@ -28,33 +39,20 @@ #include #include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE /* static */ -void* -PxrMayaHdImagingShapeUI::creator() +void* PxrMayaHdImagingShapeUI::creator() { UsdMayaGLBatchRenderer::Init(); return new PxrMayaHdImagingShapeUI(); } /* virtual */ -void -PxrMayaHdImagingShapeUI::getDrawRequests( - const MDrawInfo& drawInfo, - bool /* objectAndActiveOnly */, - MDrawRequestQueue& requests) +void PxrMayaHdImagingShapeUI::getDrawRequests( + const MDrawInfo& drawInfo, + bool /* objectAndActiveOnly */, + MDrawRequestQueue& requests) { TRACE_FUNCTION(); @@ -63,43 +61,38 @@ PxrMayaHdImagingShapeUI::getDrawRequests( MProfiler::kColorE_L2, "Hydra Imaging Shape getDrawRequests() (Legacy Viewport)"); - const MDagPath shapeDagPath = drawInfo.multiPath(); - const PxrMayaHdImagingShape* imagingShape = - PxrMayaHdImagingShape::GetShapeAtDagPath(shapeDagPath); + const MDagPath shapeDagPath = drawInfo.multiPath(); + const PxrMayaHdImagingShape* imagingShape + = PxrMayaHdImagingShape::GetShapeAtDagPath(shapeDagPath); if (!imagingShape) { return; } - TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg( - "PxrMayaHdImagingShapeUI::getDrawRequests(), shapeDagPath: %s\n", - shapeDagPath.fullPathName().asChar()); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING) + .Msg( + "PxrMayaHdImagingShapeUI::getDrawRequests(), shapeDagPath: %s\n", + shapeDagPath.fullPathName().asChar()); // Grab batch renderer settings values from the shape here and pass them // along to the batch renderer. Settings that affect selection should then // be set appropriately for subsequent selections. - MStatus status; + MStatus status; const MFnDependencyNode depNodeFn(imagingShape->thisMObject(), &status); if (status == MS::kSuccess) { - const MPlug selectionResolutionPlug = - depNodeFn.findPlug( - PxrMayaHdImagingShape::selectionResolutionAttr, - &status); + const MPlug selectionResolutionPlug + = depNodeFn.findPlug(PxrMayaHdImagingShape::selectionResolutionAttr, &status); if (status == MS::kSuccess) { - const short selectionResolution = - selectionResolutionPlug.asShort(&status); + const short selectionResolution = selectionResolutionPlug.asShort(&status); if (status == MS::kSuccess) { UsdMayaGLBatchRenderer::GetInstance().SetSelectionResolution( GfVec2i(selectionResolution)); } } - const MPlug enableDepthSelectionPlug = - depNodeFn.findPlug( - PxrMayaHdImagingShape::enableDepthSelectionAttr, - &status); + const MPlug enableDepthSelectionPlug + = depNodeFn.findPlug(PxrMayaHdImagingShape::enableDepthSelectionAttr, &status); if (status == MS::kSuccess) { - const bool enableDepthSelection = - enableDepthSelectionPlug.asBool(&status); + const bool enableDepthSelection = enableDepthSelectionPlug.asBool(&status); if (status == MS::kSuccess) { UsdMayaGLBatchRenderer::GetInstance().SetDepthSelectionEnabled( enableDepthSelection); @@ -108,8 +101,7 @@ PxrMayaHdImagingShapeUI::getDrawRequests( } // Sync any instancers that need Hydra drawing. - UsdMayaGL_InstancerImager::GetInstance().SyncShapeAdapters( - drawInfo.displayStyle()); + UsdMayaGL_InstancerImager::GetInstance().SyncShapeAdapters(drawInfo.displayStyle()); // The legacy viewport never has an old MUserData we can reuse. It also // does not manage the data allocated in the MDrawData object, so the batch @@ -127,8 +119,7 @@ PxrMayaHdImagingShapeUI::getDrawRequests( } /* virtual */ -void -PxrMayaHdImagingShapeUI::draw(const MDrawRequest& request, M3dView& view) const +void PxrMayaHdImagingShapeUI::draw(const MDrawRequest& request, M3dView& view) const { TRACE_FUNCTION(); @@ -137,8 +128,7 @@ PxrMayaHdImagingShapeUI::draw(const MDrawRequest& request, M3dView& view) const MProfiler::kColorC_L1, "Hydra Imaging Shape draw() (Legacy Viewport)"); - TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg( - "PxrMayaHdImagingShapeUI::draw()\n"); + TF_DEBUG(PXRUSDMAYAGL_BATCHED_DRAWING).Msg("PxrMayaHdImagingShapeUI::draw()\n"); view.beginGL(); @@ -147,7 +137,8 @@ PxrMayaHdImagingShapeUI::draw(const MDrawRequest& request, M3dView& view) const view.endGL(); } -PxrMayaHdImagingShapeUI::PxrMayaHdImagingShapeUI() : MPxSurfaceShapeUI() +PxrMayaHdImagingShapeUI::PxrMayaHdImagingShapeUI() + : MPxSurfaceShapeUI() { } @@ -157,5 +148,4 @@ PxrMayaHdImagingShapeUI::~PxrMayaHdImagingShapeUI() UsdMayaGL_InstancerImager::GetInstance().RemoveShapeAdapters(/*vp2*/ false); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeUI.h b/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeUI.h index 62e734de2d..f3bc7689cc 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeUI.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/hdImagingShapeUI.h @@ -29,6 +29,8 @@ // // The X11 include appears to have been removed in Maya 2020+, so this should // no longer be an issue with later versions. +#include + #include #include @@ -37,8 +39,6 @@ #include #include -#include - PXR_NAMESPACE_OPEN_SCOPE /// Class for drawing the pxrHdImagingShape node in the legacy viewport @@ -51,32 +51,27 @@ PXR_NAMESPACE_OPEN_SCOPE /// responsible for managing that. class PxrMayaHdImagingShapeUI : public MPxSurfaceShapeUI { - public: +public: + MAYAUSD_CORE_PUBLIC + static void* creator(); - MAYAUSD_CORE_PUBLIC - static void* creator(); + MAYAUSD_CORE_PUBLIC + void getDrawRequests( + const MDrawInfo& drawInfo, + bool objectAndActiveOnly, + MDrawRequestQueue& requests) override; - MAYAUSD_CORE_PUBLIC - void getDrawRequests( - const MDrawInfo& drawInfo, - bool objectAndActiveOnly, - MDrawRequestQueue& requests) override; + MAYAUSD_CORE_PUBLIC + void draw(const MDrawRequest& request, M3dView& view) const override; - MAYAUSD_CORE_PUBLIC - void draw(const MDrawRequest& request, M3dView& view) const override; +private: + PxrMayaHdImagingShapeUI(); + ~PxrMayaHdImagingShapeUI() override; - private: - - PxrMayaHdImagingShapeUI(); - ~PxrMayaHdImagingShapeUI() override; - - PxrMayaHdImagingShapeUI(const PxrMayaHdImagingShapeUI&) = delete; - PxrMayaHdImagingShapeUI& operator=( - const PxrMayaHdImagingShapeUI&) = delete; + PxrMayaHdImagingShapeUI(const PxrMayaHdImagingShapeUI&) = delete; + PxrMayaHdImagingShapeUI& operator=(const PxrMayaHdImagingShapeUI&) = delete; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/instancerImager.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/instancerImager.cpp index d7224570b6..517642229b 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/instancerImager.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/instancerImager.cpp @@ -15,6 +15,12 @@ // #include "instancerImager.h" +#include +#include +#include + +#include + #include #include #include @@ -22,49 +28,40 @@ #include #include -#include - -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE TF_INSTANTIATE_SINGLETON(UsdMayaGL_InstancerImager); UsdMayaGL_InstancerImager::ContinueTrackingOnDisconnectDelegate -UsdMayaGL_InstancerImager::_continueTrackingOnDisconnectDelegate = nullptr; + UsdMayaGL_InstancerImager::_continueTrackingOnDisconnectDelegate + = nullptr; UsdMayaGL_InstancerImager::InstancerShapeAdapterFactory -UsdMayaGL_InstancerImager::_instancerShapeAdapterFactory = nullptr; + UsdMayaGL_InstancerImager::_instancerShapeAdapterFactory + = nullptr; /* static */ -UsdMayaGL_InstancerImager& -UsdMayaGL_InstancerImager::GetInstance() +UsdMayaGL_InstancerImager& UsdMayaGL_InstancerImager::GetInstance() { return TfSingleton::GetInstance(); } -void -UsdMayaGL_InstancerImager::SyncShapeAdapters(const unsigned int displayStyle) +void UsdMayaGL_InstancerImager::SyncShapeAdapters(const unsigned int displayStyle) { // Viewport 2.0 sync. _SyncShapeAdapters(true, displayStyle, M3dView::DisplayStyle::kBoundingBox); } -void -UsdMayaGL_InstancerImager::SyncShapeAdapters( - const M3dView::DisplayStyle legacyDisplayStyle) +void UsdMayaGL_InstancerImager::SyncShapeAdapters(const M3dView::DisplayStyle legacyDisplayStyle) { // Legacy sync. _SyncShapeAdapters(false, 0, legacyDisplayStyle); } -void -UsdMayaGL_InstancerImager::_SyncShapeAdapters( - bool vp2, - const unsigned int vp2DisplayStyle, - const M3dView::DisplayStyle legacyDisplayStyle) +void UsdMayaGL_InstancerImager::_SyncShapeAdapters( + bool vp2, + const unsigned int vp2DisplayStyle, + const M3dView::DisplayStyle legacyDisplayStyle) { // Clean up any instancers scheduled for deletion, and remove their shape // adapters. @@ -75,8 +72,8 @@ UsdMayaGL_InstancerImager::_SyncShapeAdapters( // Sync all of the shape adapters. // This will create the shape adapters if they don't yet exist. - UsdMayaUtil::MObjectHandleUnorderedSet& dirtyInstancers = - vp2 ? _dirtyInstancersVp2 : _dirtyInstancersLegacy; + UsdMayaUtil::MObjectHandleUnorderedSet& dirtyInstancers + = vp2 ? _dirtyInstancersVp2 : _dirtyInstancersLegacy; for (const MObjectHandle& handle : dirtyInstancers) { auto iter = _instancers.find(handle); if (iter == _instancers.end()) { @@ -90,41 +87,27 @@ UsdMayaGL_InstancerImager::_SyncShapeAdapters( continue; } - const MDagPath firstInstancePath = - MDagPath::getAPathTo(handle.object()); + const MDagPath firstInstancePath = MDagPath::getAPathTo(handle.object()); // Create the adapter if it doesn't exist yet. _InstancerEntry& entry = iter->second; if (vp2) { - std::unique_ptr& adapter = - entry.adapterVp2; + std::unique_ptr& adapter = entry.adapterVp2; if (!adapter) { - adapter.reset( - CreateInstancerShapeAdapter(/* isViewport2 = */ true)); + adapter.reset(CreateInstancerShapeAdapter(/* isViewport2 = */ true)); } - if (adapter->Sync( - firstInstancePath, - vp2DisplayStyle, - MHWRender::kDormant)) { - UsdMayaGLBatchRenderer::GetInstance().AddShapeAdapter( - adapter.get()); + if (adapter->Sync(firstInstancePath, vp2DisplayStyle, MHWRender::kDormant)) { + UsdMayaGLBatchRenderer::GetInstance().AddShapeAdapter(adapter.get()); } - } - else { - std::unique_ptr& adapter = - entry.adapterLegacy; + } else { + std::unique_ptr& adapter = entry.adapterLegacy; if (!adapter) { - adapter.reset( - CreateInstancerShapeAdapter(/* isViewport2 = */ false)); + adapter.reset(CreateInstancerShapeAdapter(/* isViewport2 = */ false)); } - if (adapter->Sync( - firstInstancePath, - legacyDisplayStyle, - M3dView::kDormant)) { - UsdMayaGLBatchRenderer::GetInstance().AddShapeAdapter( - adapter.get()); + if (adapter->Sync(firstInstancePath, legacyDisplayStyle, M3dView::kDormant)) { + UsdMayaGLBatchRenderer::GetInstance().AddShapeAdapter(adapter.get()); } } } @@ -132,8 +115,8 @@ UsdMayaGL_InstancerImager::_SyncShapeAdapters( // Sync all of the dirty root transforms now. // The shape adapters should already have been created above. - UsdMayaUtil::MObjectHandleUnorderedSet& dirtyInstancerXforms = - vp2 ? _dirtyInstancerXformsVp2 : _dirtyInstancerXformsLegacy; + UsdMayaUtil::MObjectHandleUnorderedSet& dirtyInstancerXforms + = vp2 ? _dirtyInstancerXformsVp2 : _dirtyInstancerXformsLegacy; for (const MObjectHandle& handle : dirtyInstancerXforms) { auto iter = _instancers.find(handle); if (iter == _instancers.end()) { @@ -147,22 +130,21 @@ UsdMayaGL_InstancerImager::_SyncShapeAdapters( continue; } - const MDagPath firstInstancePath = - MDagPath::getAPathTo(handle.object()); + const MDagPath firstInstancePath = MDagPath::getAPathTo(handle.object()); // *Don't* create the adapter if it doesn't exist. // Logically, it should have already been created. - _InstancerEntry& entry = iter->second; - std::unique_ptr& adapter = - vp2 ? entry.adapterVp2 : entry.adapterLegacy; + _InstancerEntry& entry = iter->second; + std::unique_ptr& adapter + = vp2 ? entry.adapterVp2 : entry.adapterLegacy; if (!adapter) { TF_CODING_ERROR( - "Trying to update xform for '%s' but can't find adapter", - firstInstancePath.fullPathName().asChar()); + "Trying to update xform for '%s' but can't find adapter", + firstInstancePath.fullPathName().asChar()); continue; } - MStatus status; + MStatus status; const MMatrix transform = firstInstancePath.inclusiveMatrix(&status); CHECK_MSTATUS(status); adapter->SetRootXform(GfMatrix4d(transform.matrix)); @@ -170,14 +152,12 @@ UsdMayaGL_InstancerImager::_SyncShapeAdapters( dirtyInstancerXforms.clear(); } -void -UsdMayaGL_InstancerImager::RemoveShapeAdapters(bool vp2) +void UsdMayaGL_InstancerImager::RemoveShapeAdapters(bool vp2) { - UsdMayaGLBatchRenderer& renderer = - UsdMayaGLBatchRenderer::GetInstance(); + UsdMayaGLBatchRenderer& renderer = UsdMayaGLBatchRenderer::GetInstance(); for (auto& handleAndEntry : _instancers) { const MObjectHandle& handle = handleAndEntry.first; - _InstancerEntry& entry = handleAndEntry.second; + _InstancerEntry& entry = handleAndEntry.second; // After deleting the shape adapters, insert the handles into the // appropriate dirty queues so that the shape adapters get properly @@ -188,8 +168,7 @@ UsdMayaGL_InstancerImager::RemoveShapeAdapters(bool vp2) _dirtyInstancersVp2.insert(handle); _dirtyInstancerXformsVp2.insert(handle); - } - else if (!vp2 && entry.adapterLegacy) { + } else if (!vp2 && entry.adapterLegacy) { renderer.RemoveShapeAdapter(entry.adapterLegacy.get()); entry.adapterLegacy.reset(); @@ -199,14 +178,12 @@ UsdMayaGL_InstancerImager::RemoveShapeAdapters(bool vp2) } } -void -UsdMayaGL_InstancerImager::_DirtyHdImagingShape(bool createIfNeeded) +void UsdMayaGL_InstancerImager::_DirtyHdImagingShape(bool createIfNeeded) { MObject hdImagingShape; if (_cachedHdImagingShape.isAlive()) { hdImagingShape = _cachedHdImagingShape.object(); - } - else if (createIfNeeded) { + } else if (createIfNeeded) { hdImagingShape = PxrMayaHdImagingShape::GetOrCreateInstance(); _cachedHdImagingShape = MObjectHandle(hdImagingShape); } @@ -216,13 +193,12 @@ UsdMayaGL_InstancerImager::_DirtyHdImagingShape(bool createIfNeeded) } } -void -UsdMayaGL_InstancerImager::_StartTrackingInstancer(const MObject& instancer) +void UsdMayaGL_InstancerImager::_StartTrackingInstancer(const MObject& instancer) { - MObject nonConstInstancer = instancer; - MObjectHandle instancerHandle(instancer); + MObject nonConstInstancer = instancer; + MObjectHandle instancerHandle(instancer); _InstancerEntry& entry = _instancers[instancerHandle]; - const auto iter = _instancers.find(instancerHandle); + const auto iter = _instancers.find(instancerHandle); MDagPath firstInstancePath = MDagPath::getAPathTo(instancer); @@ -235,11 +211,12 @@ UsdMayaGL_InstancerImager::_StartTrackingInstancer(const MObject& instancer) // _any instance_, not just the instance specified by firstInstancePath. // (That's good in this case!) entry.callbacks.append(MDagMessage::addWorldMatrixModifiedCallback( - firstInstancePath, _OnWorldMatrixChanged, &*iter)); - entry.callbacks.append(MNodeMessage::addNodeDirtyCallback( - nonConstInstancer, _OnNodeDirty, nullptr)); + firstInstancePath, _OnWorldMatrixChanged, &*iter)); + entry.callbacks.append( + MNodeMessage::addNodeDirtyCallback(nonConstInstancer, _OnNodeDirty, nullptr)); - TF_DEBUG(PXRUSDMAYAGL_INSTANCER_TRACKING).Msg( + TF_DEBUG(PXRUSDMAYAGL_INSTANCER_TRACKING) + .Msg( "Started tracking instancer '%s' (%u)\n", firstInstancePath.fullPathName().asChar(), instancerHandle.hashCode()); @@ -252,9 +229,7 @@ UsdMayaGL_InstancerImager::_StartTrackingInstancer(const MObject& instancer) _DirtyHdImagingShape(true); } -void -UsdMayaGL_InstancerImager::_StopTrackingInstancer( - const MObjectHandle& instancerHandle) +void UsdMayaGL_InstancerImager::_StopTrackingInstancer(const MObjectHandle& instancerHandle) { auto iter = _instancers.find(instancerHandle); if (iter == _instancers.end()) { @@ -265,20 +240,17 @@ UsdMayaGL_InstancerImager::_StopTrackingInstancer( // Remove shape adapters from batch renderer. _InstancerEntry& entry = iter->second; if (entry.adapterVp2) { - UsdMayaGLBatchRenderer::GetInstance().RemoveShapeAdapter( - entry.adapterVp2.get()); + UsdMayaGLBatchRenderer::GetInstance().RemoveShapeAdapter(entry.adapterVp2.get()); } if (entry.adapterLegacy) { - UsdMayaGLBatchRenderer::GetInstance().RemoveShapeAdapter( - entry.adapterLegacy.get()); + UsdMayaGLBatchRenderer::GetInstance().RemoveShapeAdapter(entry.adapterLegacy.get()); } // Remove it from the master list. This will also remove all callbacks. _instancers.erase(instancerHandle); - TF_DEBUG(PXRUSDMAYAGL_INSTANCER_TRACKING).Msg( - "Stopped tracking instancer (%u)\n", - instancerHandle.hashCode()); + TF_DEBUG(PXRUSDMAYAGL_INSTANCER_TRACKING) + .Msg("Stopped tracking instancer (%u)\n", instancerHandle.hashCode()); // Remove it from any dirty lists so that we don't try to sync it again. _dirtyInstancersVp2.erase(instancerHandle); @@ -288,11 +260,10 @@ UsdMayaGL_InstancerImager::_StopTrackingInstancer( } /* static */ -void -UsdMayaGL_InstancerImager::_OnNodeDirty(MObject& node, void* clientData) +void UsdMayaGL_InstancerImager::_OnNodeDirty(MObject& node, void* clientData) { UsdMayaGL_InstancerImager& me = GetInstance(); - const MObjectHandle handle(node); + const MObjectHandle handle(node); bool inserted = false; inserted |= me._dirtyInstancersVp2.insert(handle).second; @@ -303,15 +274,14 @@ UsdMayaGL_InstancerImager::_OnNodeDirty(MObject& node, void* clientData) } /* static */ -void -UsdMayaGL_InstancerImager::_OnWorldMatrixChanged( - MObject &transformNode, - MDagMessage::MatrixModifiedFlags &modified, - void *clientData) +void UsdMayaGL_InstancerImager::_OnWorldMatrixChanged( + MObject& transformNode, + MDagMessage::MatrixModifiedFlags& modified, + void* clientData) { UsdMayaGL_InstancerImager& me = GetInstance(); - const auto handleEntryPair = - static_cast*>(clientData); + const auto handleEntryPair + = static_cast*>(clientData); const MObjectHandle& handle = handleEntryPair->first; bool inserted = false; @@ -322,22 +292,20 @@ UsdMayaGL_InstancerImager::_OnWorldMatrixChanged( } } -void -UsdMayaGL_InstancerImager::_OnSceneReset(const UsdMayaSceneResetNotice& notice) +void UsdMayaGL_InstancerImager::_OnSceneReset(const UsdMayaSceneResetNotice& notice) { TfSingleton::DeleteInstance(); TfSingleton::GetInstance(); } -void -UsdMayaGL_InstancerImager::_OnConnection( - const UsdMayaAssemblyConnectedToInstancerNotice& notice) +void UsdMayaGL_InstancerImager::_OnConnection( + const UsdMayaAssemblyConnectedToInstancerNotice& notice) { if (MGlobal::mayaState() != MGlobal::kInteractive) { return; } - MObject instancer = notice.GetInstancer(); + MObject instancer = notice.GetInstancer(); const MObjectHandle instancerHandle(instancer); // Remove the instancer from the removal list, if it was previously @@ -351,18 +319,17 @@ UsdMayaGL_InstancerImager::_OnConnection( } } -void -UsdMayaGL_InstancerImager::_OnDisconnection( - const UsdMayaAssemblyDisconnectedFromInstancerNotice& notice) +void UsdMayaGL_InstancerImager::_OnDisconnection( + const UsdMayaAssemblyDisconnectedFromInstancerNotice& notice) { if (MGlobal::mayaState() != MGlobal::kInteractive) { return; } - MObject instancer = notice.GetInstancer(); + MObject instancer = notice.GetInstancer(); const MObjectHandle instancerHandle(instancer); - MStatus status; + MStatus status; MFnDependencyNode instancerDepNode(instancer, &status); if (!status) { return; @@ -413,7 +380,8 @@ UsdMayaGL_InstancerImager::UsdMayaGL_InstancerImager() UsdMayaGL_InstancerImager::~UsdMayaGL_InstancerImager() { - TF_DEBUG(PXRUSDMAYAGL_INSTANCER_TRACKING).Msg( + TF_DEBUG(PXRUSDMAYAGL_INSTANCER_TRACKING) + .Msg( "UsdMayaGL_InstancerImager dying; stopped tracking remaining " " %zu instancers\n", _instancers.size()); @@ -425,9 +393,7 @@ void UsdMayaGL_InstancerImager::SetContinueTrackingOnDisconnectDelegate( _continueTrackingOnDisconnectDelegate = delegate; } -bool UsdMayaGL_InstancerImager::ContinueTrackingOnDisconnect( - const MFnDependencyNode& fn -) +bool UsdMayaGL_InstancerImager::ContinueTrackingOnDisconnect(const MFnDependencyNode& fn) { if (!_continueTrackingOnDisconnectDelegate) { return false; diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/instancerImager.h b/lib/mayaUsd/render/pxrUsdMayaGL/instancerImager.h index 857f0d1b14..f29890af69 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/instancerImager.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/instancerImager.h @@ -18,20 +18,20 @@ /// \file pxrUsdMayaGL/instancerImager.h -#include - -#include -#include -#include - -#include -#include - #include #include #include #include +#include +#include + +#include +#include +#include + +#include + PXR_NAMESPACE_OPEN_SCOPE /// Class for syncing native Maya instancers with the pxrHdImagingShape so that @@ -42,7 +42,8 @@ PXR_NAMESPACE_OPEN_SCOPE /// Maya instancing, we only draw the 0th instance. This behavior is similar to /// the current imaging behavior of USD proxy shapes, where only one instance /// gets drawn by the draw override. -class UsdMayaGL_InstancerImager : public TfWeakBase { +class UsdMayaGL_InstancerImager : public TfWeakBase +{ public: MAYAUSD_CORE_PUBLIC static UsdMayaGL_InstancerImager& GetInstance(); @@ -68,22 +69,22 @@ class UsdMayaGL_InstancerImager : public TfWeakBase { typedef std::function ContinueTrackingOnDisconnectDelegate; MAYAUSD_CORE_PUBLIC - static void SetContinueTrackingOnDisconnectDelegate( - ContinueTrackingOnDisconnectDelegate delegate); + static void + SetContinueTrackingOnDisconnectDelegate(ContinueTrackingOnDisconnectDelegate delegate); /// Factory function for creating instancer shape adapters. - using InstancerShapeAdapterFactory = - std::function; + using InstancerShapeAdapterFactory + = std::function; /// Set the factory function for creating instancer shape adapters. MAYAUSD_CORE_PUBLIC - static void SetInstancerShapeAdapterFactory( - InstancerShapeAdapterFactory factory); + static void SetInstancerShapeAdapterFactory(InstancerShapeAdapterFactory factory); private: /// Helper struct that owns all the data needed to track and draw a /// particular instancer node. - struct _InstancerEntry { + struct _InstancerEntry + { MCallbackIdArray callbacks; // The shape adapter generates an in-memory USD stage, so don't create @@ -117,17 +118,15 @@ class UsdMayaGL_InstancerImager : public TfWeakBase { /// @{ /// Maya callback for when the given \p node becomes dirty. - static void _OnNodeDirty( - MObject& node, - void* clientData); + static void _OnNodeDirty(MObject& node, void* clientData); /// Maya callback for when the \p transformNode's world-space xform changes. /// \p transformNode is either the node for which the callback was /// registered or one of its ancestors. static void _OnWorldMatrixChanged( - MObject &transformNode, - MDagMessage::MatrixModifiedFlags& modified, - void *clientData); + MObject& transformNode, + MDagMessage::MatrixModifiedFlags& modified, + void* clientData); /// @} /// \name Helpers @@ -136,9 +135,9 @@ class UsdMayaGL_InstancerImager : public TfWeakBase { /// Helper method to sync shape adapters for any instancers marked as dirty; /// this handles differences between VP2 and Legacy Viewport. void _SyncShapeAdapters( - bool vp2, - const unsigned int vp2DisplayStyle, - const M3dView::DisplayStyle legacyDisplayStyle); + bool vp2, + const unsigned int vp2DisplayStyle, + const M3dView::DisplayStyle legacyDisplayStyle); /// Marks the global pxrHdImagingShape as dirty. /// If \p createIfNeeded is true, then creates the pxrHdImagingShape if it @@ -160,14 +159,11 @@ class UsdMayaGL_InstancerImager : public TfWeakBase { /// @{ /// Notice listener method for when the Maya scene resets. - void _OnSceneReset( - const UsdMayaSceneResetNotice& notice); + void _OnSceneReset(const UsdMayaSceneResetNotice& notice); /// Notice listener method for assembly-instancer connections. - void _OnConnection( - const UsdMayaAssemblyConnectedToInstancerNotice& notice); + void _OnConnection(const UsdMayaAssemblyConnectedToInstancerNotice& notice); /// Notice listener method for assembly-instancer disconnections. - void _OnDisconnection( - const UsdMayaAssemblyDisconnectedFromInstancerNotice& notice); + void _OnDisconnection(const UsdMayaAssemblyDisconnectedFromInstancerNotice& notice); /// @} diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/instancerShapeAdapter.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/instancerShapeAdapter.cpp index 6323d926cd..4930d6a6ea 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/instancerShapeAdapter.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/instancerShapeAdapter.cpp @@ -15,20 +15,12 @@ // #include "instancerShapeAdapter.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include #include @@ -49,26 +41,29 @@ #include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PRIVATE_TOKENS( _tokens, - ((NativeInstancerType, "instancer")) - (Instancer) - (Prototypes) - (EmptyPrim) -); + ((NativeInstancerType, "instancer"))(Instancer)(Prototypes)(EmptyPrim)); /* virtual */ -bool -UsdMayaGL_InstancerShapeAdapter::UpdateVisibility(const M3dView* view) +bool UsdMayaGL_InstancerShapeAdapter::UpdateVisibility(const M3dView* view) { bool isVisible; if (!_GetVisibility(GetDagPath(), view, &isVisible)) { @@ -84,15 +79,13 @@ UsdMayaGL_InstancerShapeAdapter::UpdateVisibility(const M3dView* view) } /* virtual */ -bool -UsdMayaGL_InstancerShapeAdapter::IsVisible() const +bool UsdMayaGL_InstancerShapeAdapter::IsVisible() const { return (_delegate && _delegate->GetRootVisibility()); } /* virtual */ -void -UsdMayaGL_InstancerShapeAdapter::SetRootXform(const GfMatrix4d& transform) +void UsdMayaGL_InstancerShapeAdapter::SetRootXform(const GfMatrix4d& transform) { _rootXform = transform; @@ -101,23 +94,20 @@ UsdMayaGL_InstancerShapeAdapter::SetRootXform(const GfMatrix4d& transform) } } -static void -_ClearInstancer(const UsdGeomPointInstancer& usdInstancer) +static void _ClearInstancer(const UsdGeomPointInstancer& usdInstancer) { - usdInstancer.GetPrototypesRel().SetTargets({ - SdfPath::AbsoluteRootPath() - .AppendChild(_tokens->Instancer) - .AppendChild(_tokens->EmptyPrim)}); + usdInstancer.GetPrototypesRel().SetTargets({ SdfPath::AbsoluteRootPath() + .AppendChild(_tokens->Instancer) + .AppendChild(_tokens->EmptyPrim) }); usdInstancer.CreateProtoIndicesAttr().Set(VtIntArray()); usdInstancer.CreatePositionsAttr().Set(VtVec3fArray()); usdInstancer.CreateOrientationsAttr().Set(VtQuathArray()); usdInstancer.CreateScalesAttr().Set(VtVec3fArray()); } -size_t -UsdMayaGL_InstancerShapeAdapter::_SyncInstancerPrototypes( - const UsdGeomPointInstancer& usdInstancer, - const MPlug& inputHierarchy) +size_t UsdMayaGL_InstancerShapeAdapter::_SyncInstancerPrototypes( + const UsdGeomPointInstancer& usdInstancer, + const MPlug& inputHierarchy) { usdInstancer.GetPrototypesRel().ClearTargets(/*removeSpec*/ false); @@ -128,22 +118,20 @@ UsdMayaGL_InstancerShapeAdapter::_SyncInstancerPrototypes( stage->MuteAndUnmuteLayers({}, stage->GetMutedLayers()); const SdfPath prototypesGroupPath = SdfPath::AbsoluteRootPath() - .AppendChild(_tokens->Instancer) - .AppendChild(_tokens->Prototypes); + .AppendChild(_tokens->Instancer) + .AppendChild(_tokens->Prototypes); std::vector layerIdsToMute; for (unsigned int i = 0; i < inputHierarchy.numElements(); ++i) { // Set up an empty prim for the prototype reference. // This code path is designed so that, after setting up the prim, // we can just leave it and "continue" if we error trying to set it up. const TfToken prototypeName(TfStringPrintf("prototype_%d", i)); - const SdfPath prototypeUsdPath = - prototypesGroupPath.AppendChild(prototypeName); - UsdPrim prototypePrim = stage->DefinePrim(prototypeUsdPath); + const SdfPath prototypeUsdPath = prototypesGroupPath.AppendChild(prototypeName); + UsdPrim prototypePrim = stage->DefinePrim(prototypeUsdPath); UsdModelAPI(prototypePrim).SetKind(KindTokens->component); usdInstancer.GetPrototypesRel().AddTarget(prototypeUsdPath); - SyncInstancerPerPrototypePostHook( - inputHierarchy[i], prototypePrim, layerIdsToMute); + SyncInstancerPerPrototypePostHook(inputHierarchy[i], prototypePrim, layerIdsToMute); } // Actually do all the muting in a batch. @@ -152,12 +140,11 @@ UsdMayaGL_InstancerShapeAdapter::_SyncInstancerPrototypes( return inputHierarchy.numElements(); } -void -UsdMayaGL_InstancerShapeAdapter::_SyncInstancer( - const UsdGeomPointInstancer& usdInstancer, - const MDagPath& mayaInstancerPath) +void UsdMayaGL_InstancerShapeAdapter::_SyncInstancer( + const UsdGeomPointInstancer& usdInstancer, + const MDagPath& mayaInstancerPath) { - MStatus status; + MStatus status; MFnDagNode dagNode(mayaInstancerPath, &status); if (!status) { _ClearInstancer(usdInstancer); @@ -194,8 +181,7 @@ UsdMayaGL_InstancerShapeAdapter::_SyncInstancer( return; } - size_t numPrototypes = _SyncInstancerPrototypes( - usdInstancer, inputHierarchy); + size_t numPrototypes = _SyncInstancerPrototypes(usdInstancer, inputHierarchy); if (!numPrototypes) { _ClearInstancer(usdInstancer); return; @@ -203,29 +189,25 @@ UsdMayaGL_InstancerShapeAdapter::_SyncInstancer( // Write PointInstancer attrs using export code path. UsdMayaWriteUtil::WriteArrayAttrsToInstancer( - data, usdInstancer, numPrototypes, - UsdTimeCode::Default()); + data, usdInstancer, numPrototypes, UsdTimeCode::Default()); } /* virtual */ -bool -UsdMayaGL_InstancerShapeAdapter::_Sync( - const MDagPath& shapeDagPath, - const unsigned int displayStyle, - const MHWRender::DisplayStatus /* displayStatus */) +bool UsdMayaGL_InstancerShapeAdapter::_Sync( + const MDagPath& shapeDagPath, + const unsigned int displayStyle, + const MHWRender::DisplayStatus /* displayStatus */) { - MStatus status; - UsdPrim usdPrim = _instancerStage->GetDefaultPrim(); + MStatus status; + UsdPrim usdPrim = _instancerStage->GetDefaultPrim(); UsdGeomPointInstancer instancer(usdPrim); _SyncInstancer(instancer, shapeDagPath); // Check for updates to the shape or changes in the batch renderer that // require us to re-initialize the shape adapter. - HdRenderIndex* renderIndex = - UsdMayaGLBatchRenderer::GetInstance().GetRenderIndex(); - if (!(shapeDagPath == GetDagPath()) || - !_delegate || - renderIndex != &_delegate->GetRenderIndex()) { + HdRenderIndex* renderIndex = UsdMayaGLBatchRenderer::GetInstance().GetRenderIndex(); + if (!(shapeDagPath == GetDagPath()) || !_delegate + || renderIndex != &_delegate->GetRenderIndex()) { _SetDagPath(shapeDagPath); if (!_Init(renderIndex)) { @@ -256,10 +238,9 @@ UsdMayaGL_InstancerShapeAdapter::_Sync( // // If the repr selector specifies a wireframe-only repr, then disable // lighting. - const HdReprSelector reprSelector = - GetReprSelectorForDisplayStyle(displayStyle); - if (reprSelector.Contains(HdReprTokens->wire) || - reprSelector.Contains(HdReprTokens->refinedWire)) { + const HdReprSelector reprSelector = GetReprSelectorForDisplayStyle(displayStyle); + if (reprSelector.Contains(HdReprTokens->wire) + || reprSelector.Contains(HdReprTokens->refinedWire)) { _renderParams.enableLighting = false; } @@ -273,29 +254,28 @@ UsdMayaGL_InstancerShapeAdapter::_Sync( return true; } -bool -UsdMayaGL_InstancerShapeAdapter::_Init(HdRenderIndex* renderIndex) +bool UsdMayaGL_InstancerShapeAdapter::_Init(HdRenderIndex* renderIndex) { - if (!TF_VERIFY( - renderIndex, - "Cannot initialize shape adapter with invalid HdRenderIndex")) { + if (!TF_VERIFY(renderIndex, "Cannot initialize shape adapter with invalid HdRenderIndex")) { return false; } - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - "Initializing UsdMayaGL_InstancerShapeAdapter: %p\n" - " shape DAG path : %s\n" - " shape identifier: %s\n" - " delegateId : %s\n", - this, - GetDagPath().fullPathName().asChar(), - _shapeIdentifier.GetText(), - _delegateId.GetText()); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg( + "Initializing UsdMayaGL_InstancerShapeAdapter: %p\n" + " shape DAG path : %s\n" + " shape identifier: %s\n" + " delegateId : %s\n", + this, + GetDagPath().fullPathName().asChar(), + _shapeIdentifier.GetText(), + _delegateId.GetText()); _delegate.reset(new UsdImagingDelegate(renderIndex, _delegateId)); - if (!TF_VERIFY(_delegate, - "Failed to create shape adapter delegate for shape %s", - GetDagPath().fullPathName().asChar())) { + if (!TF_VERIFY( + _delegate, + "Failed to create shape adapter delegate for shape %s", + GetDagPath().fullPathName().asChar())) { return false; } @@ -307,38 +287,30 @@ UsdMayaGL_InstancerShapeAdapter::_Init(HdRenderIndex* renderIndex) /* virtual */ void UsdMayaGL_InstancerShapeAdapter::SyncInstancerPerPrototypePostHook( - const MPlug& , - UsdPrim& prototypePrim, - std::vector& -) + const MPlug&, + UsdPrim& prototypePrim, + std::vector&) { UsdReferences prototypeRefs = prototypePrim.GetReferences(); prototypeRefs.ClearReferences(); } -UsdMayaGL_InstancerShapeAdapter::UsdMayaGL_InstancerShapeAdapter( - bool isViewport2) : - PxrMayaHdShapeAdapter(isViewport2) +UsdMayaGL_InstancerShapeAdapter::UsdMayaGL_InstancerShapeAdapter(bool isViewport2) + : PxrMayaHdShapeAdapter(isViewport2) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - "Constructing UsdMayaGL_InstancerShapeAdapter: %p\n", - this); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg("Constructing UsdMayaGL_InstancerShapeAdapter: %p\n", this); // Set up bare-bones instancer stage. // Populate the required properties for the instancer. _instancerStage = UsdStage::CreateInMemory(); - const SdfPath instancerPath = - SdfPath::AbsoluteRootPath().AppendChild(_tokens->Instancer); - const SdfPath prototypesPath = - instancerPath.AppendChild(_tokens->Prototypes); - const SdfPath emptyPrimPath = - instancerPath.AppendChild(_tokens->EmptyPrim); - const UsdGeomPointInstancer instancer = - UsdGeomPointInstancer::Define(_instancerStage, instancerPath); - const UsdPrim prototypesGroupPrim = - _instancerStage->DefinePrim(prototypesPath); - const UsdPrim emptyPrim = - _instancerStage->DefinePrim(emptyPrimPath); + const SdfPath instancerPath = SdfPath::AbsoluteRootPath().AppendChild(_tokens->Instancer); + const SdfPath prototypesPath = instancerPath.AppendChild(_tokens->Prototypes); + const SdfPath emptyPrimPath = instancerPath.AppendChild(_tokens->EmptyPrim); + const UsdGeomPointInstancer instancer + = UsdGeomPointInstancer::Define(_instancerStage, instancerPath); + const UsdPrim prototypesGroupPrim = _instancerStage->DefinePrim(prototypesPath); + const UsdPrim emptyPrim = _instancerStage->DefinePrim(emptyPrimPath); instancer.CreatePrototypesRel().AddTarget(emptyPrimPath); instancer.CreateProtoIndicesAttr().Set(VtIntArray()); instancer.CreatePositionsAttr().Set(VtVec3fArray()); @@ -352,10 +324,8 @@ UsdMayaGL_InstancerShapeAdapter::UsdMayaGL_InstancerShapeAdapter( /* virtual */ UsdMayaGL_InstancerShapeAdapter::~UsdMayaGL_InstancerShapeAdapter() { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - "Destructing UsdMayaGL_InstancerShapeAdapter: %p\n", - this); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg("Destructing UsdMayaGL_InstancerShapeAdapter: %p\n", this); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/instancerShapeAdapter.h b/lib/mayaUsd/render/pxrUsdMayaGL/instancerShapeAdapter.h index fceba3dd33..c947b49a5b 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/instancerShapeAdapter.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/instancerShapeAdapter.h @@ -30,18 +30,17 @@ // // The X11 include appears to have been removed in Maya 2020+, so this should // no longer be an issue with later versions. -#include - -#include +#include +#include #include #include #include +#include #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -52,114 +51,108 @@ PXR_NAMESPACE_OPEN_SCOPE /// that are not reference assemblies. class UsdMayaGL_InstancerShapeAdapter : public PxrMayaHdShapeAdapter { - public: - - /// Update the shape adapter's visibility state from the display status - /// of its shape. - /// - /// When a Maya shape is made invisible, it may no longer be included - /// in the "prepare" phase of a viewport render (i.e. we get no - /// getDrawRequests() or prepareForDraw() callbacks for that shape). - /// This method can be called on demand to ensure that the shape - /// adapter is updated with the current visibility state of the shape. - /// - /// The optional \p view parameter can be passed to have view-based - /// state such as view and/or plugin object filtering factor into the - /// shape's visibility. - /// - /// Returns true if the visibility state was changed, or false - /// otherwise. - MAYAUSD_CORE_PUBLIC - bool UpdateVisibility(const M3dView* view = nullptr) override; - - /// Gets whether the shape adapter's shape is visible. - /// - /// This should be called after a call to UpdateVisibility() to ensure - /// that the returned value is correct. - MAYAUSD_CORE_PUBLIC - bool IsVisible() const override; - - MAYAUSD_CORE_PUBLIC - void SetRootXform(const GfMatrix4d& transform) override; - - MAYAUSD_CORE_PUBLIC - ~UsdMayaGL_InstancerShapeAdapter() override; - - protected: - - /// Update the shape adapter's state from the shape with the given - /// \p dagPath and display state. - /// - /// This method should be called by both public versions of Sync() and - /// should perform shape data updates that are common to both the - /// legacy viewport and Viewport 2.0. The legacy viewport Sync() method - /// "promotes" the display state parameters to their Viewport 2.0 - /// equivalents before calling this method. - MAYAUSD_CORE_PUBLIC - bool _Sync( - const MDagPath& shapeDagPath, - const unsigned int displayStyle, - const MHWRender::DisplayStatus displayStatus) override; - - /// Construct a new uninitialized UsdMayaGL_InstancerShapeAdapter. - /// - /// Note that only friends of this class are able to construct - /// instances of this class. - MAYAUSD_CORE_PUBLIC - UsdMayaGL_InstancerShapeAdapter(bool isViewport2); - - // Derived class hook to allow derived classes to augment - // _SyncInstancerPrototypes(), for each prototype. The implementation - // in this class clears references on the argument prototypePrim. - MAYAUSD_CORE_PUBLIC - virtual void SyncInstancerPerPrototypePostHook( - const MPlug& hierarchyPlug, - UsdPrim& prototypePrim, - std::vector& layerIdsToMute - ); - - private: - - /// Initialize the shape adapter using the given \p renderIndex. - /// - /// This method is called automatically during Sync() when the shape - /// adapter's "identity" changes. This can happen when the shape - /// managed by this adapter is changed by setting a new DAG path, or - /// otherwise when there is some other fundamental change to the shape - /// or to the delegate or render index. - /// The shape adapter will then query the batch renderer for its render - /// index and use that to re-create its delegate and re-add its rprim - /// collection, if necessary. - bool _Init(HdRenderIndex* renderIndex); - - /// Updates the prototypes prims and the corresponding prototypes rel on - /// the point instancer. Errored or untranslatable prototypes are left - /// as empty prims in the prototype order. Returns the total number of - /// prototypes (including errored or untranslatable prototypes). - size_t _SyncInstancerPrototypes( - const UsdGeomPointInstancer& usdInstancer, - const MPlug& inputHierarchy); - - /// Updates all of the attributes on the \p usdInstancer from the native - /// Maya instancer given by \p mayaInstancerPath. - /// If there was a problem reading prototypes or there are no - /// prototypes, then the whole instancer will be emptied out. - void _SyncInstancer( - const UsdGeomPointInstancer& usdInstancer, - const MDagPath& mayaInstancerPath); - - UsdStageRefPtr _instancerStage; - - std::shared_ptr _delegate; - - /// The classes that maintain ownership of and are responsible for - /// updating the shape adapter for their shape are made friends of - /// UsdMayaGL_InstancerShapeAdapter so that they alone can set - /// properties on the shape adapter. - friend class UsdMayaGL_InstancerImager; +public: + /// Update the shape adapter's visibility state from the display status + /// of its shape. + /// + /// When a Maya shape is made invisible, it may no longer be included + /// in the "prepare" phase of a viewport render (i.e. we get no + /// getDrawRequests() or prepareForDraw() callbacks for that shape). + /// This method can be called on demand to ensure that the shape + /// adapter is updated with the current visibility state of the shape. + /// + /// The optional \p view parameter can be passed to have view-based + /// state such as view and/or plugin object filtering factor into the + /// shape's visibility. + /// + /// Returns true if the visibility state was changed, or false + /// otherwise. + MAYAUSD_CORE_PUBLIC + bool UpdateVisibility(const M3dView* view = nullptr) override; + + /// Gets whether the shape adapter's shape is visible. + /// + /// This should be called after a call to UpdateVisibility() to ensure + /// that the returned value is correct. + MAYAUSD_CORE_PUBLIC + bool IsVisible() const override; + + MAYAUSD_CORE_PUBLIC + void SetRootXform(const GfMatrix4d& transform) override; + + MAYAUSD_CORE_PUBLIC + ~UsdMayaGL_InstancerShapeAdapter() override; + +protected: + /// Update the shape adapter's state from the shape with the given + /// \p dagPath and display state. + /// + /// This method should be called by both public versions of Sync() and + /// should perform shape data updates that are common to both the + /// legacy viewport and Viewport 2.0. The legacy viewport Sync() method + /// "promotes" the display state parameters to their Viewport 2.0 + /// equivalents before calling this method. + MAYAUSD_CORE_PUBLIC + bool _Sync( + const MDagPath& shapeDagPath, + const unsigned int displayStyle, + const MHWRender::DisplayStatus displayStatus) override; + + /// Construct a new uninitialized UsdMayaGL_InstancerShapeAdapter. + /// + /// Note that only friends of this class are able to construct + /// instances of this class. + MAYAUSD_CORE_PUBLIC + UsdMayaGL_InstancerShapeAdapter(bool isViewport2); + + // Derived class hook to allow derived classes to augment + // _SyncInstancerPrototypes(), for each prototype. The implementation + // in this class clears references on the argument prototypePrim. + MAYAUSD_CORE_PUBLIC + virtual void SyncInstancerPerPrototypePostHook( + const MPlug& hierarchyPlug, + UsdPrim& prototypePrim, + std::vector& layerIdsToMute); + +private: + /// Initialize the shape adapter using the given \p renderIndex. + /// + /// This method is called automatically during Sync() when the shape + /// adapter's "identity" changes. This can happen when the shape + /// managed by this adapter is changed by setting a new DAG path, or + /// otherwise when there is some other fundamental change to the shape + /// or to the delegate or render index. + /// The shape adapter will then query the batch renderer for its render + /// index and use that to re-create its delegate and re-add its rprim + /// collection, if necessary. + bool _Init(HdRenderIndex* renderIndex); + + /// Updates the prototypes prims and the corresponding prototypes rel on + /// the point instancer. Errored or untranslatable prototypes are left + /// as empty prims in the prototype order. Returns the total number of + /// prototypes (including errored or untranslatable prototypes). + size_t _SyncInstancerPrototypes( + const UsdGeomPointInstancer& usdInstancer, + const MPlug& inputHierarchy); + + /// Updates all of the attributes on the \p usdInstancer from the native + /// Maya instancer given by \p mayaInstancerPath. + /// If there was a problem reading prototypes or there are no + /// prototypes, then the whole instancer will be emptied out. + void + _SyncInstancer(const UsdGeomPointInstancer& usdInstancer, const MDagPath& mayaInstancerPath); + + UsdStageRefPtr _instancerStage; + + std::shared_ptr _delegate; + + /// The classes that maintain ownership of and are responsible for + /// updating the shape adapter for their shape are made friends of + /// UsdMayaGL_InstancerShapeAdapter so that they alone can set + /// properties on the shape adapter. + friend class UsdMayaGL_InstancerImager; }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/proxyDrawOverride.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/proxyDrawOverride.cpp index a52dc0f248..aa8135f948 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/proxyDrawOverride.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/proxyDrawOverride.cpp @@ -15,6 +15,18 @@ // #include "proxyDrawOverride.h" +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + #include #include #include @@ -32,38 +44,27 @@ #include #include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE const MString UsdMayaProxyDrawOverride::drawDbClassification( - TfStringPrintf("drawdb/geometry/pxrUsdMayaGL/%s", - MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText()).c_str()); + TfStringPrintf( + "drawdb/geometry/pxrUsdMayaGL/%s", + MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText()) + .c_str()); /* static */ -MHWRender::MPxDrawOverride* -UsdMayaProxyDrawOverride::Creator(const MObject& obj) +MHWRender::MPxDrawOverride* UsdMayaProxyDrawOverride::Creator(const MObject& obj) { UsdMayaGLBatchRenderer::Init(); return new UsdMayaProxyDrawOverride(obj); } -UsdMayaProxyDrawOverride::UsdMayaProxyDrawOverride(const MObject& obj) : - MHWRender::MPxDrawOverride( +UsdMayaProxyDrawOverride::UsdMayaProxyDrawOverride(const MObject& obj) + : MHWRender::MPxDrawOverride( obj, UsdMayaProxyDrawOverride::draw, - /* isAlwaysDirty = */ false), - _shapeAdapter(/* isViewport2 = */ true) + /* isAlwaysDirty = */ false) + , _shapeAdapter(/* isViewport2 = */ true) { } @@ -74,35 +75,31 @@ UsdMayaProxyDrawOverride::~UsdMayaProxyDrawOverride() } /* virtual */ -MHWRender::DrawAPI -UsdMayaProxyDrawOverride::supportedDrawAPIs() const +MHWRender::DrawAPI UsdMayaProxyDrawOverride::supportedDrawAPIs() const { return MHWRender::kOpenGL | MHWRender::kOpenGLCoreProfile; } /* virtual */ MMatrix -UsdMayaProxyDrawOverride::transform( - const MDagPath& objPath, - const MDagPath& cameraPath) const +UsdMayaProxyDrawOverride::transform(const MDagPath& objPath, const MDagPath& cameraPath) const { // Propagate changes in the proxy shape's transform to the shape adapter's // delegate. - MStatus status; + MStatus status; const MMatrix transform = objPath.inclusiveMatrix(&status); if (status == MS::kSuccess) { - const_cast(_shapeAdapter).SetRootXform( - GfMatrix4d(transform.matrix)); + const_cast(_shapeAdapter) + .SetRootXform(GfMatrix4d(transform.matrix)); } return MHWRender::MPxDrawOverride::transform(objPath, cameraPath); } /* virtual */ -MBoundingBox -UsdMayaProxyDrawOverride::boundingBox( - const MDagPath& objPath, - const MDagPath& /* cameraPath */) const +MBoundingBox UsdMayaProxyDrawOverride::boundingBox( + const MDagPath& objPath, + const MDagPath& /* cameraPath */) const { TRACE_FUNCTION(); @@ -128,10 +125,8 @@ UsdMayaProxyDrawOverride::boundingBox( } /* virtual */ -bool -UsdMayaProxyDrawOverride::isBounded( - const MDagPath& objPath, - const MDagPath& /* cameraPath */) const +bool UsdMayaProxyDrawOverride::isBounded(const MDagPath& objPath, const MDagPath& /* cameraPath */) + const { // XXX: Ideally, we'd be querying the shape itself using the code below to // determine whether the object is bounded or not. Unfortunately, the @@ -162,8 +157,7 @@ UsdMayaProxyDrawOverride::isBounded( } /* virtual */ -bool -UsdMayaProxyDrawOverride::disableInternalBoundingBoxDraw() const +bool UsdMayaProxyDrawOverride::disableInternalBoundingBoxDraw() const { // Hydra performs its own high-performance frustum culling, so we don't // want to rely on Maya to do it on the CPU. As such, the best performance @@ -172,12 +166,11 @@ UsdMayaProxyDrawOverride::disableInternalBoundingBoxDraw() const } /* virtual */ -MUserData* -UsdMayaProxyDrawOverride::prepareForDraw( - const MDagPath& objPath, - const MDagPath& /* cameraPath */, - const MHWRender::MFrameContext& frameContext, - MUserData* oldData) +MUserData* UsdMayaProxyDrawOverride::prepareForDraw( + const MDagPath& objPath, + const MDagPath& /* cameraPath */, + const MHWRender::MFrameContext& frameContext, + MUserData* oldData) { TRACE_FUNCTION(); @@ -214,8 +207,7 @@ UsdMayaProxyDrawOverride::prepareForDraw( } /* virtual */ -bool -UsdMayaProxyDrawOverride::wantUserSelection() const +bool UsdMayaProxyDrawOverride::wantUserSelection() const { const MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(); if (!renderer) { @@ -226,12 +218,11 @@ UsdMayaProxyDrawOverride::wantUserSelection() const } /* virtual */ -bool -UsdMayaProxyDrawOverride::userSelect( - MHWRender::MSelectionInfo& selectionInfo, - const MHWRender::MDrawContext& context, - MPoint& hitPoint, - const MUserData* data) +bool UsdMayaProxyDrawOverride::userSelect( + MHWRender::MSelectionInfo& selectionInfo, + const MHWRender::MDrawContext& context, + MPoint& hitPoint, + const MUserData* data) { TRACE_FUNCTION(); @@ -240,10 +231,9 @@ UsdMayaProxyDrawOverride::userSelect( MProfiler::kColorE_L2, "USD Proxy Shape userSelect() (Viewport 2.0)"); - M3dView view; + M3dView view; const bool hasView = px_vp20Utils::GetViewFromDrawContext(context, view); - if (hasView && - !view.pluginObjectDisplay(MayaUsdProxyShapeBase::displayFilterName)) { + if (hasView && !view.pluginObjectDisplay(MayaUsdProxyShapeBase::displayFilterName)) { return false; } @@ -252,9 +242,9 @@ UsdMayaProxyDrawOverride::userSelect( return false; } - const unsigned int displayStyle = context.getDisplayStyle(); - const MHWRender::DisplayStatus displayStatus = - MHWRender::MGeometryUtilities::displayStatus(_shapeAdapter.GetDagPath()); + const unsigned int displayStyle = context.getDisplayStyle(); + const MHWRender::DisplayStatus displayStatus + = MHWRender::MGeometryUtilities::displayStatus(_shapeAdapter.GetDagPath()); // At this point, we expect the shape to have already been drawn and our // shape adapter to have been added to the batch renderer, but just in @@ -262,19 +252,14 @@ UsdMayaProxyDrawOverride::userSelect( // first time. We do not add it to the batch renderer though, since that // must have already been done to have caused the shape to be drawn and // become eligible for selection. - if (!_shapeAdapter.Sync( - _shapeAdapter.GetDagPath(), displayStyle, displayStatus)) { + if (!_shapeAdapter.Sync(_shapeAdapter.GetDagPath(), displayStyle, displayStatus)) { return false; } - const HdxPickHitVector* hitSet = - UsdMayaGLBatchRenderer::GetInstance().TestIntersection( - &_shapeAdapter, - selectionInfo, - context); + const HdxPickHitVector* hitSet = UsdMayaGLBatchRenderer::GetInstance().TestIntersection( + &_shapeAdapter, selectionInfo, context); - const HdxPickHit* nearestHit = - UsdMayaGLBatchRenderer::GetNearestHit(hitSet); + const HdxPickHit* nearestHit = UsdMayaGLBatchRenderer::GetNearestHit(hitSet); if (!nearestHit) { return false; @@ -287,10 +272,7 @@ UsdMayaProxyDrawOverride::userSelect( } /* static */ -void -UsdMayaProxyDrawOverride::draw( - const MHWRender::MDrawContext& context, - const MUserData* data) +void UsdMayaProxyDrawOverride::draw(const MHWRender::MDrawContext& context, const MUserData* data) { TRACE_FUNCTION(); @@ -307,5 +289,4 @@ UsdMayaProxyDrawOverride::draw( UsdMayaGLBatchRenderer::GetInstance().DrawBoundingBox(context, data); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/proxyDrawOverride.h b/lib/mayaUsd/render/pxrUsdMayaGL/proxyDrawOverride.h index ae5c64d15d..80954d8d45 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/proxyDrawOverride.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/proxyDrawOverride.h @@ -19,6 +19,9 @@ /// \file pxrUsdMayaGL/proxyDrawOverride.h #include +#include + +#include #include #include @@ -33,78 +36,64 @@ #include #include -#include - -#include - PXR_NAMESPACE_OPEN_SCOPE class UsdMayaProxyDrawOverride : public MHWRender::MPxDrawOverride { - public: - MAYAUSD_CORE_PUBLIC - static const MString drawDbClassification; - - MAYAUSD_CORE_PUBLIC - static MHWRender::MPxDrawOverride* Creator(const MObject& obj); - - MAYAUSD_CORE_PUBLIC - ~UsdMayaProxyDrawOverride() override; - - MAYAUSD_CORE_PUBLIC - MHWRender::DrawAPI supportedDrawAPIs() const override; - - MAYAUSD_CORE_PUBLIC - MMatrix transform( - const MDagPath& objPath, - const MDagPath& cameraPath) const override; - - MAYAUSD_CORE_PUBLIC - MBoundingBox boundingBox( - const MDagPath& objPath, - const MDagPath& cameraPath) const override; - - MAYAUSD_CORE_PUBLIC - bool isBounded( - const MDagPath& objPath, - const MDagPath& cameraPath) const override; - - MAYAUSD_CORE_PUBLIC - bool disableInternalBoundingBoxDraw() const override; - - MAYAUSD_CORE_PUBLIC - MUserData* prepareForDraw( - const MDagPath& objPath, - const MDagPath& cameraPath, - const MHWRender::MFrameContext& frameContext, - MUserData* oldData) override; - - MAYAUSD_CORE_PUBLIC - bool wantUserSelection() const override; - - MAYAUSD_CORE_PUBLIC - bool userSelect( - MHWRender::MSelectionInfo& selectionInfo, - const MHWRender::MDrawContext& context, - MPoint& hitPoint, - const MUserData* data) override; - - MAYAUSD_CORE_PUBLIC - static void draw( - const MHWRender::MDrawContext& context, - const MUserData* data); - - private: - UsdMayaProxyDrawOverride(const MObject& obj); - - UsdMayaProxyDrawOverride(const UsdMayaProxyDrawOverride&) = delete; - UsdMayaProxyDrawOverride& operator=(const UsdMayaProxyDrawOverride&) = delete; - - PxrMayaHdUsdProxyShapeAdapter _shapeAdapter; -}; +public: + MAYAUSD_CORE_PUBLIC + static const MString drawDbClassification; + MAYAUSD_CORE_PUBLIC + static MHWRender::MPxDrawOverride* Creator(const MObject& obj); -PXR_NAMESPACE_CLOSE_SCOPE + MAYAUSD_CORE_PUBLIC + ~UsdMayaProxyDrawOverride() override; + + MAYAUSD_CORE_PUBLIC + MHWRender::DrawAPI supportedDrawAPIs() const override; + + MAYAUSD_CORE_PUBLIC + MMatrix transform(const MDagPath& objPath, const MDagPath& cameraPath) const override; + + MAYAUSD_CORE_PUBLIC + MBoundingBox boundingBox(const MDagPath& objPath, const MDagPath& cameraPath) const override; + MAYAUSD_CORE_PUBLIC + bool isBounded(const MDagPath& objPath, const MDagPath& cameraPath) const override; + + MAYAUSD_CORE_PUBLIC + bool disableInternalBoundingBoxDraw() const override; + + MAYAUSD_CORE_PUBLIC + MUserData* prepareForDraw( + const MDagPath& objPath, + const MDagPath& cameraPath, + const MHWRender::MFrameContext& frameContext, + MUserData* oldData) override; + + MAYAUSD_CORE_PUBLIC + bool wantUserSelection() const override; + + MAYAUSD_CORE_PUBLIC + bool userSelect( + MHWRender::MSelectionInfo& selectionInfo, + const MHWRender::MDrawContext& context, + MPoint& hitPoint, + const MUserData* data) override; + + MAYAUSD_CORE_PUBLIC + static void draw(const MHWRender::MDrawContext& context, const MUserData* data); + +private: + UsdMayaProxyDrawOverride(const MObject& obj); + + UsdMayaProxyDrawOverride(const UsdMayaProxyDrawOverride&) = delete; + UsdMayaProxyDrawOverride& operator=(const UsdMayaProxyDrawOverride&) = delete; + + PxrMayaHdUsdProxyShapeAdapter _shapeAdapter; +}; + +PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeDelegate.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeDelegate.cpp index d11f4406e3..467b98ad60 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeDelegate.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeDelegate.cpp @@ -15,7 +15,8 @@ // #include // This header must absolutely come first. -#include +#include +#include #include #include @@ -27,30 +28,27 @@ #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE static PxrMayaHdPrimFilter _sharedPrimFilter = { - nullptr, - HdRprimCollection( - TfToken("UsdMayaGL_ClosestPointOnProxyShape"), - HdReprSelector(HdReprTokens->refined) - ), - TfTokenVector() // Render Tags + nullptr, + HdRprimCollection( + TfToken("UsdMayaGL_ClosestPointOnProxyShape"), + HdReprSelector(HdReprTokens->refined)), + TfTokenVector() // Render Tags }; /// Delegate for computing a ray intersection against a MayaUsdProxyShapeBase by /// rendering using Hydra via the UsdMayaGLBatchRenderer. -bool -UsdMayaGL_ClosestPointOnProxyShape( +bool UsdMayaGL_ClosestPointOnProxyShape( const MayaUsdProxyShapeBase& shape, - const GfRay& ray, - GfVec3d* outClosestPoint, - GfVec3d* outClosestNormal) + const GfRay& ray, + GfVec3d* outClosestPoint, + GfVec3d* outClosestNormal) { - MStatus status; + MStatus status; const MFnDagNode dagNodeFn(shape.thisMObject(), &status); CHECK_MSTATUS_AND_RETURN(status, false); @@ -61,8 +59,7 @@ UsdMayaGL_ClosestPointOnProxyShape( // Try to populate our shared collection with the shape. If we can't, then // we must bail. UsdMayaGLBatchRenderer& renderer = UsdMayaGLBatchRenderer::GetInstance(); - if (!renderer.PopulateCustomPrimFilter( - shapeDagPath, _sharedPrimFilter)) { + if (!renderer.PopulateCustomPrimFilter(shapeDagPath, _sharedPrimFilter)) { return false; } @@ -70,19 +67,19 @@ UsdMayaGL_ClosestPointOnProxyShape( // everything in world-space and then convert back to local space when // returning the hit point. GfMatrix4d localToWorld(shapeDagPath.inclusiveMatrix().matrix); - GfRay worldRay( - localToWorld.Transform(ray.GetStartPoint()), - localToWorld.TransformDir(ray.GetDirection()).GetNormalized()); + GfRay worldRay( + localToWorld.Transform(ray.GetStartPoint()), + localToWorld.TransformDir(ray.GetDirection()).GetNormalized()); // Create selection frustum (think very thin tube from ray origin towards // ray direction). GfRotation rotation(-GfVec3d::ZAxis(), worldRay.GetDirection()); - GfFrustum frustum( - worldRay.GetStartPoint(), - rotation, - /*window*/ GfRange2d(GfVec2d(-0.1, -0.1), GfVec2d(0.1, 0.1)), - /*nearFar*/ GfRange1d(0.1, 10000.0), - GfFrustum::Orthographic); + GfFrustum frustum( + worldRay.GetStartPoint(), + rotation, + /*window*/ GfRange2d(GfVec2d(-0.1, -0.1), GfVec2d(0.1, 0.1)), + /*nearFar*/ GfRange1d(0.1, 10000.0), + GfFrustum::Orthographic); // Draw the shape into the draw target, and the intersect against the draw // target. Unbind after we're done. @@ -90,11 +87,8 @@ UsdMayaGL_ClosestPointOnProxyShape( GfMatrix4d projectionMatrix = frustum.ComputeProjectionMatrix(); HdxPickHitVector isectResult; - bool didIsect = renderer.TestIntersectionCustomPrimFilter( - _sharedPrimFilter, - viewMatrix, - projectionMatrix, - &isectResult); + bool didIsect = renderer.TestIntersectionCustomPrimFilter( + _sharedPrimFilter, viewMatrix, projectionMatrix, &isectResult); if (!didIsect) { return false; @@ -103,16 +97,19 @@ UsdMayaGL_ClosestPointOnProxyShape( // Our hit point and hit normal are both in world space, so convert back // to local space. const HdxPickHit& hit = isectResult[0]; - const GfMatrix4d worldToLocal = localToWorld.GetInverse(); - const GfVec3d point = worldToLocal.Transform(hit.worldSpaceHitPoint); - const GfVec3d normal = worldToLocal.TransformDir(hit.worldSpaceHitNormal); + const GfMatrix4d worldToLocal = localToWorld.GetInverse(); + const GfVec3d point = worldToLocal.Transform(hit.worldSpaceHitPoint); + const GfVec3d normal = worldToLocal.TransformDir(hit.worldSpaceHitNormal); - if (!std::isfinite(point.GetLengthSq()) || - !std::isfinite(normal.GetLengthSq())) { + if (!std::isfinite(point.GetLengthSq()) || !std::isfinite(normal.GetLengthSq())) { TF_CODING_ERROR( - "point (%f, %f, %f) or normal (%f, %f, %f) is non-finite", - point[0], point[1], point[2], - normal[0], normal[1], normal[2]); + "point (%f, %f, %f) or normal (%f, %f, %f) is non-finite", + point[0], + point[1], + point[2], + normal[0], + normal[1], + normal[2]); return false; } @@ -123,8 +120,7 @@ UsdMayaGL_ClosestPointOnProxyShape( TF_REGISTRY_FUNCTION(MayaUsdProxyShapeBase) { - MayaUsdProxyShapeBase::SetClosestPointDelegate( - UsdMayaGL_ClosestPointOnProxyShape); + MayaUsdProxyShapeBase::SetClosestPointDelegate(UsdMayaGL_ClosestPointOnProxyShape); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeUI.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeUI.cpp index 9aa901b15e..a7a082f5ad 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeUI.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeUI.cpp @@ -15,10 +15,24 @@ // #include "proxyShapeUI.h" +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + #include #include -#include #include +#include #include #include #include @@ -33,36 +47,20 @@ #include #include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE /* static */ -void* -UsdMayaProxyShapeUI::creator() +void* UsdMayaProxyShapeUI::creator() { UsdMayaGLBatchRenderer::Init(); return new UsdMayaProxyShapeUI(); } /* virtual */ -void -UsdMayaProxyShapeUI::getDrawRequests( - const MDrawInfo& drawInfo, - bool /* objectAndActiveOnly */, - MDrawRequestQueue& requests) +void UsdMayaProxyShapeUI::getDrawRequests( + const MDrawInfo& drawInfo, + bool /* objectAndActiveOnly */, + MDrawRequestQueue& requests) { TRACE_FUNCTION(); @@ -71,16 +69,13 @@ UsdMayaProxyShapeUI::getDrawRequests( MProfiler::kColorE_L2, "USD Proxy Shape getDrawRequests() (Legacy Viewport)"); - const MDagPath shapeDagPath = drawInfo.multiPath(); - MayaUsdProxyShapeBase* shape = - MayaUsdProxyShapeBase::GetShapeAtDagPath(shapeDagPath); + const MDagPath shapeDagPath = drawInfo.multiPath(); + MayaUsdProxyShapeBase* shape = MayaUsdProxyShapeBase::GetShapeAtDagPath(shapeDagPath); if (!shape) { return; } - if (!_shapeAdapter.Sync(shapeDagPath, - drawInfo.displayStyle(), - drawInfo.displayStatus())) { + if (!_shapeAdapter.Sync(shapeDagPath, drawInfo.displayStyle(), drawInfo.displayStatus())) { return; } @@ -97,8 +92,7 @@ UsdMayaProxyShapeUI::getDrawRequests( } /* virtual */ -void -UsdMayaProxyShapeUI::draw(const MDrawRequest& request, M3dView& view) const +void UsdMayaProxyShapeUI::draw(const MDrawRequest& request, M3dView& view) const { TRACE_FUNCTION(); @@ -124,11 +118,10 @@ UsdMayaProxyShapeUI::draw(const MDrawRequest& request, M3dView& view) const } /* virtual */ -bool -UsdMayaProxyShapeUI::select( - MSelectInfo& selectInfo, - MSelectionList& selectionList, - MPointArray& worldSpaceSelectedPoints) const +bool UsdMayaProxyShapeUI::select( + MSelectInfo& selectInfo, + MSelectionList& selectionList, + MPointArray& worldSpaceSelectedPoints) const { TRACE_FUNCTION(); @@ -163,26 +156,22 @@ UsdMayaProxyShapeUI::select( return false; } - if (!_shapeAdapter.Sync(shapeDagPath, - view.displayStyle(), - view.displayStatus(selectInfo.selectPath()))) { + if (!_shapeAdapter.Sync( + shapeDagPath, view.displayStyle(), view.displayStatus(selectInfo.selectPath()))) { return false; } - const HdxPickHitVector* hitSet = - UsdMayaGLBatchRenderer::GetInstance().TestIntersection( - &_shapeAdapter, - selectInfo); + const HdxPickHitVector* hitSet + = UsdMayaGLBatchRenderer::GetInstance().TestIntersection(&_shapeAdapter, selectInfo); - const HdxPickHit* nearestHit = - UsdMayaGLBatchRenderer::GetNearestHit(hitSet); + const HdxPickHit* nearestHit = UsdMayaGLBatchRenderer::GetNearestHit(hitSet); if (!nearestHit) { return false; } const GfVec3f& gfHitPoint = nearestHit->worldSpaceHitPoint; - const MPoint mayaHitPoint(gfHitPoint[0], gfHitPoint[1], gfHitPoint[2]); + const MPoint mayaHitPoint(gfHitPoint[0], gfHitPoint[1], gfHitPoint[2]); MSelectionList newSelectionList; newSelectionList.add(selectInfo.selectPath()); @@ -203,16 +192,13 @@ UsdMayaProxyShapeUI::select( return true; } -UsdMayaProxyShapeUI::UsdMayaProxyShapeUI() : - MPxSurfaceShapeUI(), - _shapeAdapter(/* isViewport2 = */ false) +UsdMayaProxyShapeUI::UsdMayaProxyShapeUI() + : MPxSurfaceShapeUI() + , _shapeAdapter(/* isViewport2 = */ false) { MStatus status; _onNodeRemovedCallbackId = MDGMessage::addNodeRemovedCallback( - _OnNodeRemoved, - MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText(), - this, - &status); + _OnNodeRemoved, MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText(), this, &status); CHECK_MSTATUS(status); } @@ -224,21 +210,17 @@ UsdMayaProxyShapeUI::~UsdMayaProxyShapeUI() } /* static */ -void -UsdMayaProxyShapeUI::_OnNodeRemoved(MObject& node, void* clientData) +void UsdMayaProxyShapeUI::_OnNodeRemoved(MObject& node, void* clientData) { - UsdMayaProxyShapeUI* proxyShapeUI = - static_cast(clientData); + UsdMayaProxyShapeUI* proxyShapeUI = static_cast(clientData); if (!proxyShapeUI) { return; } const MObject shapeObj = proxyShapeUI->surfaceShape()->thisMObject(); if (shapeObj == node && UsdMayaGLBatchRenderer::CurrentlyExists()) { - UsdMayaGLBatchRenderer::GetInstance().RemoveShapeAdapter( - &proxyShapeUI->_shapeAdapter); + UsdMayaGLBatchRenderer::GetInstance().RemoveShapeAdapter(&proxyShapeUI->_shapeAdapter); } } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeUI.h b/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeUI.h index 4867b79016..47b9668e19 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeUI.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/proxyShapeUI.h @@ -29,6 +29,10 @@ // // The X11 include appears to have been removed in Maya 2020+, so this should // no longer be an issue with later versions. +#include +#include + +#include #include #include @@ -42,65 +46,54 @@ #include #include -#include - -#include -#include - PXR_NAMESPACE_OPEN_SCOPE class UsdMayaProxyShapeUI : public MPxSurfaceShapeUI { - public: - - MAYAUSD_CORE_PUBLIC - static void* creator(); - - MAYAUSD_CORE_PUBLIC - void getDrawRequests( - const MDrawInfo& drawInfo, - bool objectAndActiveOnly, - MDrawRequestQueue& requests) override; - - MAYAUSD_CORE_PUBLIC - void draw( - const MDrawRequest& request, - M3dView& view) const override; - - MAYAUSD_CORE_PUBLIC - bool select( - MSelectInfo& selectInfo, - MSelectionList& selectionList, - MPointArray& worldSpaceSelectPts) const override; - - private: - - UsdMayaProxyShapeUI(); - ~UsdMayaProxyShapeUI() override; - - UsdMayaProxyShapeUI(const UsdMayaProxyShapeUI&) = delete; - UsdMayaProxyShapeUI& operator=(const UsdMayaProxyShapeUI&) = delete; - - // Note that MPxSurfaceShapeUI::select() is declared as const, so we - // must declare _shapeAdapter as mutable so that we're able to modify - // it. - mutable PxrMayaHdUsdProxyShapeAdapter _shapeAdapter; - - // In Viewport 2.0, the MPxDrawOverride destructor is called when its - // shape is deleted, in which case the shape's adapter is removed from - // the batch renderer. In the legacy viewport though, that's not the - // case. The MPxSurfaceShapeUI destructor may not get called until the - // scene is closed or Maya exits. As a result, MPxSurfaceShapeUI - // objects must listen for node removal messages from Maya and remove - // their shape adapter from the batch renderer if their node is the one - // being removed. Otherwise, deleted shapes may still be drawn. - static void _OnNodeRemoved(MObject& node, void* clientData); - - MCallbackId _onNodeRemovedCallbackId; +public: + MAYAUSD_CORE_PUBLIC + static void* creator(); + + MAYAUSD_CORE_PUBLIC + void getDrawRequests( + const MDrawInfo& drawInfo, + bool objectAndActiveOnly, + MDrawRequestQueue& requests) override; + + MAYAUSD_CORE_PUBLIC + void draw(const MDrawRequest& request, M3dView& view) const override; + + MAYAUSD_CORE_PUBLIC + bool select( + MSelectInfo& selectInfo, + MSelectionList& selectionList, + MPointArray& worldSpaceSelectPts) const override; + +private: + UsdMayaProxyShapeUI(); + ~UsdMayaProxyShapeUI() override; + + UsdMayaProxyShapeUI(const UsdMayaProxyShapeUI&) = delete; + UsdMayaProxyShapeUI& operator=(const UsdMayaProxyShapeUI&) = delete; + + // Note that MPxSurfaceShapeUI::select() is declared as const, so we + // must declare _shapeAdapter as mutable so that we're able to modify + // it. + mutable PxrMayaHdUsdProxyShapeAdapter _shapeAdapter; + + // In Viewport 2.0, the MPxDrawOverride destructor is called when its + // shape is deleted, in which case the shape's adapter is removed from + // the batch renderer. In the legacy viewport though, that's not the + // case. The MPxSurfaceShapeUI destructor may not get called until the + // scene is closed or Maya exits. As a result, MPxSurfaceShapeUI + // objects must listen for node removal messages from Maya and remove + // their shape adapter from the batch renderer if their node is the one + // being removed. Otherwise, deleted shapes may still be drawn. + static void _OnNodeRemoved(MObject& node, void* clientData); + + MCallbackId _onNodeRemovedCallbackId; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/renderParams.h b/lib/mayaUsd/render/pxrUsdMayaGL/renderParams.h index a8e9a94632..3ee2521c7b 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/renderParams.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/renderParams.h @@ -18,15 +18,13 @@ /// \file pxrUsdMayaGL/renderParams.h -#include - -#include #include +#include +#include PXR_NAMESPACE_OPEN_SCOPE - struct PxrMayaHdRenderParams { // Raster Params @@ -35,7 +33,7 @@ struct PxrMayaHdRenderParams // Color Params // - bool useWireframe = false; + bool useWireframe = false; GfVec4f wireframeColor = GfVec4f(0.0f); /// Helper function to find a batch key for the render params @@ -49,8 +47,6 @@ struct PxrMayaHdRenderParams } }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/sceneDelegate.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/sceneDelegate.cpp index 4af6ec6ede..efbff9cdfb 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/sceneDelegate.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/sceneDelegate.cpp @@ -15,12 +15,11 @@ // #include "sceneDelegate.h" -#include -#include - -#include +#include +#include +#include +#include -#include #include #include #include @@ -51,72 +50,67 @@ #include #include #include +#include #include -#include -#include -#include -#include +#include + +#include + +#include PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PRIVATE_TOKENS( _tokens, - (selectionTask) -); - + (selectionTask)); namespace { - class PxrMayaHdShadowMatrix : public HdxShadowMatrixComputation - { - public: +class PxrMayaHdShadowMatrix : public HdxShadowMatrixComputation +{ +public: #if HDX_API_VERSION >= 6 - PxrMayaHdShadowMatrix(const GlfSimpleLight& light) - { - // We use the shadow matrix as provided by Maya directly. - _shadowMatrices = light.GetShadowMatrices(); - } + PxrMayaHdShadowMatrix(const GlfSimpleLight& light) + { + // We use the shadow matrix as provided by Maya directly. + _shadowMatrices = light.GetShadowMatrices(); + } - std::vector Compute( - const GfVec4f& viewport, - CameraUtilConformWindowPolicy policy) override - { - return _shadowMatrices; - } + std::vector + Compute(const GfVec4f& viewport, CameraUtilConformWindowPolicy policy) override + { + return _shadowMatrices; + } #else - PxrMayaHdShadowMatrix(const GlfSimpleLight& light) - { - // We use the shadow matrix as provided by Maya directly. - _shadowMatrices.push_back(light.GetShadowMatrix()); - } + PxrMayaHdShadowMatrix(const GlfSimpleLight& light) + { + // We use the shadow matrix as provided by Maya directly. + _shadowMatrices.push_back(light.GetShadowMatrix()); + } - GfMatrix4d Compute( - const GfVec4f& viewport, - CameraUtilConformWindowPolicy policy) override - { - return _shadowMatrices.back(); - } + GfMatrix4d Compute(const GfVec4f& viewport, CameraUtilConformWindowPolicy policy) override + { + return _shadowMatrices.back(); + } #endif - private: - std::vector _shadowMatrices; - }; -} - +private: + std::vector _shadowMatrices; +}; +} // namespace PxrMayaHdSceneDelegate::PxrMayaHdSceneDelegate( - HdRenderIndex* renderIndex, - const SdfPath& delegateID) : - HdSceneDelegate(renderIndex, delegateID) + HdRenderIndex* renderIndex, + const SdfPath& delegateID) + : HdSceneDelegate(renderIndex, delegateID) { _lightingContext = GlfSimpleLightingContext::New(); // populate tasks in renderindex // create an unique namespace - _rootId = delegateID.AppendChild( - TfToken(TfStringPrintf("_UsdImaging_%p", this))); + _rootId = delegateID.AppendChild(TfToken(TfStringPrintf("_UsdImaging_%p", this))); _simpleLightTaskId = _rootId.AppendChild(HdxPrimitiveTokens->simpleLightTask); _shadowTaskId = _rootId.AppendChild(HdxPrimitiveTokens->shadowTask); @@ -140,7 +134,7 @@ PxrMayaHdSceneDelegate::PxrMayaHdSceneDelegate( // Simple lighting task. { renderIndex->InsertTask(this, _simpleLightTaskId); - _ValueCache& cache = _valueCacheMap[_simpleLightTaskId]; + _ValueCache& cache = _valueCacheMap[_simpleLightTaskId]; HdxSimpleLightTaskParams taskParams; taskParams.cameraPath = _cameraId; taskParams.viewport = GfVec4f(_viewport); @@ -152,11 +146,11 @@ PxrMayaHdSceneDelegate::PxrMayaHdSceneDelegate( { // By default we only want geometry in the shadow pass const TfTokenVector defaultShadowRenderTags = { - HdRenderTagTokens->geometry, + HdRenderTagTokens->geometry, }; renderIndex->InsertTask(this, _shadowTaskId); - _ValueCache& cache = _valueCacheMap[_shadowTaskId]; + _ValueCache& cache = _valueCacheMap[_shadowTaskId]; HdxShadowTaskParams taskParams; taskParams.camera = _cameraId; taskParams.viewport = _viewport; @@ -167,7 +161,7 @@ PxrMayaHdSceneDelegate::PxrMayaHdSceneDelegate( // Picking task. { renderIndex->InsertTask(this, _pickingTaskId); - _ValueCache& cache = _valueCacheMap[_pickingTaskId]; + _ValueCache& cache = _valueCacheMap[_pickingTaskId]; HdxPickTaskParams taskParams; taskParams.enableSceneMaterials = true; cache[HdTokens->params] = VtValue(taskParams); @@ -182,7 +176,7 @@ PxrMayaHdSceneDelegate::PxrMayaHdSceneDelegate( // Selection task. { renderIndex->InsertTask(this, _selectionTaskId); - _ValueCache& cache = _valueCacheMap[_selectionTaskId]; + _ValueCache& cache = _valueCacheMap[_selectionTaskId]; HdxSelectionTaskParams taskParams; taskParams.enableSelection = true; @@ -197,44 +191,37 @@ PxrMayaHdSceneDelegate::PxrMayaHdSceneDelegate( } /*virtual*/ -VtValue -PxrMayaHdSceneDelegate::Get(const SdfPath& id, const TfToken& key) +VtValue PxrMayaHdSceneDelegate::Get(const SdfPath& id, const TfToken& key) { _ValueCache* vcache = TfMapLookupPtr(_valueCacheMap, id); - VtValue ret; + VtValue ret; if (vcache && TfMapLookup(*vcache, key, &ret)) { return ret; } - TF_CODING_ERROR("%s:%s doesn't exist in the value cache\n", - id.GetText(), - key.GetText()); + TF_CODING_ERROR("%s:%s doesn't exist in the value cache\n", id.GetText(), key.GetText()); return VtValue(); } /*virtual*/ VtValue -PxrMayaHdSceneDelegate::GetCameraParamValue( - SdfPath const& cameraId, - TfToken const& paramName) +PxrMayaHdSceneDelegate::GetCameraParamValue(SdfPath const& cameraId, TfToken const& paramName) { return Get(cameraId, paramName); } -TfTokenVector -PxrMayaHdSceneDelegate::GetTaskRenderTags(SdfPath const& taskId) +TfTokenVector PxrMayaHdSceneDelegate::GetTaskRenderTags(SdfPath const& taskId) { VtValue value = Get(taskId, HdTokens->renderTags); return value.Get(); } -void -PxrMayaHdSceneDelegate::SetCameraState( - const GfMatrix4d& worldToViewMatrix, - const GfMatrix4d& projectionMatrix, - const GfVec4d& viewport) +void PxrMayaHdSceneDelegate::SetCameraState( + const GfMatrix4d& worldToViewMatrix, + const GfMatrix4d& projectionMatrix, + const GfVec4d& viewport) { // cache the camera matrices _ValueCache& cache = _valueCacheMap[_cameraId]; @@ -244,60 +231,50 @@ PxrMayaHdSceneDelegate::SetCameraState( cache[HdCameraTokens->clipPlanes] = VtValue(std::vector()); // invalidate the camera to be synced - GetRenderIndex().GetChangeTracker().MarkSprimDirty(_cameraId, - HdCamera::AllDirty); + GetRenderIndex().GetChangeTracker().MarkSprimDirty(_cameraId, HdCamera::AllDirty); if (_viewport != viewport) { _viewport = viewport; // Update the simple light task. - HdxSimpleLightTaskParams simpleLightTaskParams = - _GetValue(_simpleLightTaskId, - HdTokens->params); + HdxSimpleLightTaskParams simpleLightTaskParams + = _GetValue(_simpleLightTaskId, HdTokens->params); simpleLightTaskParams.viewport = GfVec4f(_viewport); _SetValue(_simpleLightTaskId, HdTokens->params, simpleLightTaskParams); GetRenderIndex().GetChangeTracker().MarkTaskDirty( - _simpleLightTaskId, - HdChangeTracker::DirtyParams); + _simpleLightTaskId, HdChangeTracker::DirtyParams); // Update the shadow task. - HdxShadowTaskParams shadowTaskParams = - _GetValue(_shadowTaskId, - HdTokens->params); + HdxShadowTaskParams shadowTaskParams + = _GetValue(_shadowTaskId, HdTokens->params); shadowTaskParams.viewport = _viewport; _SetValue(_shadowTaskId, HdTokens->params, shadowTaskParams); GetRenderIndex().GetChangeTracker().MarkTaskDirty( - _shadowTaskId, - HdChangeTracker::DirtyParams); + _shadowTaskId, HdChangeTracker::DirtyParams); // Update all render setup tasks. for (const auto& it : _renderSetupTaskIdMap) { const SdfPath& renderSetupTaskId = it.second; - HdxRenderTaskParams renderSetupTaskParams = - _GetValue(renderSetupTaskId, - HdTokens->params); + HdxRenderTaskParams renderSetupTaskParams + = _GetValue(renderSetupTaskId, HdTokens->params); renderSetupTaskParams.viewport = _viewport; - _SetValue(renderSetupTaskId, - HdTokens->params, - renderSetupTaskParams); + _SetValue(renderSetupTaskId, HdTokens->params, renderSetupTaskParams); GetRenderIndex().GetChangeTracker().MarkTaskDirty( - renderSetupTaskId, - HdChangeTracker::DirtyParams); + renderSetupTaskId, HdChangeTracker::DirtyParams); } } } -void -PxrMayaHdSceneDelegate::SetLightingStateFromVP1( - const GfMatrix4d& worldToViewMatrix, - const GfMatrix4d& projectionMatrix) +void PxrMayaHdSceneDelegate::SetLightingStateFromVP1( + const GfMatrix4d& worldToViewMatrix, + const GfMatrix4d& projectionMatrix) { // This function should only be called in a VP1.0 context. In VP2.0, we can // translate the lighting state from the MDrawContext directly into Glf, @@ -315,17 +292,15 @@ PxrMayaHdSceneDelegate::SetLightingStateFromVP1( _SetLightingStateFromLightingContext(); } -void -PxrMayaHdSceneDelegate::SetLightingStateFromMayaDrawContext( - const MHWRender::MDrawContext& context) +void PxrMayaHdSceneDelegate::SetLightingStateFromMayaDrawContext( + const MHWRender::MDrawContext& context) { _lightingContext = px_vp20Utils::GetLightingContextFromDrawContext(context); _SetLightingStateFromLightingContext(); } -void -PxrMayaHdSceneDelegate::_SetLightingStateFromLightingContext() +void PxrMayaHdSceneDelegate::_SetLightingStateFromLightingContext() { const GlfSimpleLightVector& lights = _lightingContext->GetLights(); @@ -333,24 +308,21 @@ PxrMayaHdSceneDelegate::_SetLightingStateFromLightingContext() // Insert light Ids into the render index for those that do not yet exist. while (_lightIds.size() < lights.size()) { - const SdfPath lightId = _rootId.AppendChild(TfToken( - TfStringPrintf("light%zu", _lightIds.size()))); + const SdfPath lightId + = _rootId.AppendChild(TfToken(TfStringPrintf("light%zu", _lightIds.size()))); _lightIds.push_back(lightId); // Since we're hardcoded to use HdStRenderDelegate, we expect to have // light Sprims. - TF_VERIFY(GetRenderIndex(). - IsSprimTypeSupported(HdPrimTypeTokens->simpleLight)); + TF_VERIFY(GetRenderIndex().IsSprimTypeSupported(HdPrimTypeTokens->simpleLight)); - GetRenderIndex(). - InsertSprim(HdPrimTypeTokens->simpleLight, this, lightId); + GetRenderIndex().InsertSprim(HdPrimTypeTokens->simpleLight, this, lightId); hasLightingChanged = true; } // Remove unused light Ids from HdRenderIndex while (_lightIds.size() > lights.size()) { - GetRenderIndex(). - RemoveSprim(HdPrimTypeTokens->simpleLight, _lightIds.back()); + GetRenderIndex().RemoveSprim(HdPrimTypeTokens->simpleLight, _lightIds.back()); _lightIds.pop_back(); hasLightingChanged = true; } @@ -361,8 +333,7 @@ PxrMayaHdSceneDelegate::_SetLightingStateFromLightingContext() const VtValue& currLightValue = cache[HdLightTokens->params]; if (currLightValue.IsHolding()) { - const GlfSimpleLight& currLight = - currLightValue.Get(); + const GlfSimpleLight& currLight = currLightValue.Get(); if (lights[i] == currLight) { // This light hasn't changed since the last time it was stored @@ -388,25 +359,19 @@ PxrMayaHdSceneDelegate::_SetLightingStateFromLightingContext() shadowParams.blur = lights[i].GetShadowBlur(); if (lights[i].HasShadow()) { - shadowParams.shadowMatrix = - HdxShadowMatrixComputationSharedPtr( - new PxrMayaHdShadowMatrix(lights[i])); + shadowParams.shadowMatrix + = HdxShadowMatrixComputationSharedPtr(new PxrMayaHdShadowMatrix(lights[i])); } cache[HdLightTokens->shadowParams] = VtValue(shadowParams); - cache[HdLightTokens->shadowCollection] = - VtValue(HdRprimCollection( - HdTokens->geometry, - HdReprSelector(HdReprTokens->refined))); - - GetRenderIndex().GetChangeTracker().MarkSprimDirty( - _lightIds[i], - HdStLight::AllDirty); + cache[HdLightTokens->shadowCollection] + = VtValue(HdRprimCollection(HdTokens->geometry, HdReprSelector(HdReprTokens->refined))); + + GetRenderIndex().GetChangeTracker().MarkSprimDirty(_lightIds[i], HdStLight::AllDirty); } - HdxSimpleLightTaskParams taskParams = - _GetValue(_simpleLightTaskId, - HdTokens->params); + HdxSimpleLightTaskParams taskParams + = _GetValue(_simpleLightTaskId, HdTokens->params); if (taskParams.enableShadows != _lightingContext->GetUseShadows()) { taskParams.enableShadows = _lightingContext->GetUseShadows(); @@ -429,17 +394,14 @@ PxrMayaHdSceneDelegate::_SetLightingStateFromLightingContext() _SetValue(_simpleLightTaskId, HdTokens->params, taskParams); GetRenderIndex().GetChangeTracker().MarkTaskDirty( - _simpleLightTaskId, - HdChangeTracker::DirtyParams); + _simpleLightTaskId, HdChangeTracker::DirtyParams); GetRenderIndex().GetChangeTracker().MarkTaskDirty( - _shadowTaskId, - HdChangeTracker::DirtyParams); + _shadowTaskId, HdChangeTracker::DirtyParams); } } -HdTaskSharedPtrVector -PxrMayaHdSceneDelegate::GetSetupTasks() +HdTaskSharedPtrVector PxrMayaHdSceneDelegate::GetSetupTasks() { HdTaskSharedPtrVector tasks; @@ -449,15 +411,14 @@ PxrMayaHdSceneDelegate::GetSetupTasks() return tasks; } -HdTaskSharedPtrVector -PxrMayaHdSceneDelegate::GetRenderTasks( - const size_t hash, - const PxrMayaHdRenderParams& renderParams, - unsigned int displayStyle, - const PxrMayaHdPrimFilterVector& primFilters) +HdTaskSharedPtrVector PxrMayaHdSceneDelegate::GetRenderTasks( + const size_t hash, + const PxrMayaHdRenderParams& renderParams, + unsigned int displayStyle, + const PxrMayaHdPrimFilterVector& primFilters) { HdTaskSharedPtrVector taskList; - HdRenderIndex& renderIndex = GetRenderIndex(); + HdRenderIndex& renderIndex = GetRenderIndex(); // Task List Consist of: // Render Setup Task @@ -469,9 +430,7 @@ PxrMayaHdSceneDelegate::GetRenderTasks( if (!TfMapLookup(_renderSetupTaskIdMap, hash, &renderSetupTaskId)) { // Create a new render setup task if one does not exist for this hash. renderSetupTaskId = _rootId.AppendChild( - TfToken(TfStringPrintf("%s_%zx", - HdxPrimitiveTokens->renderSetupTask.GetText(), - hash))); + TfToken(TfStringPrintf("%s_%zx", HdxPrimitiveTokens->renderSetupTask.GetText(), hash))); renderIndex.InsertTask(this, renderSetupTaskId); @@ -497,14 +456,13 @@ PxrMayaHdSceneDelegate::GetRenderTasks( taskList.emplace_back(renderIndex.GetTask(renderSetupTaskId)); for (const PxrMayaHdPrimFilter& primFilter : primFilters) { - SdfPath renderTaskId; + SdfPath renderTaskId; HdRprimCollection rprimCollection; - TfTokenVector renderTags; + TfTokenVector renderTags; if (primFilter.shapeAdapter != nullptr) { - const HdReprSelector repr = - primFilter.shapeAdapter->GetReprSelectorForDisplayStyle( - displayStyle); + const HdReprSelector repr + = primFilter.shapeAdapter->GetReprSelectorForDisplayStyle(displayStyle); if (!repr.AnyActiveRepr()) { continue; @@ -527,12 +485,8 @@ PxrMayaHdSceneDelegate::GetRenderTasks( // Note that we expect the collection name to have already been // sanitized for use in SdfPaths. TF_VERIFY(TfIsValidIdentifier(collectionName.GetString())); - renderTaskId = _rootId.AppendChild( - TfToken( - TfStringPrintf( - "%s_%s", - HdxPrimitiveTokens->renderTask.GetText(), - collectionName.GetText()))); + renderTaskId = _rootId.AppendChild(TfToken(TfStringPrintf( + "%s_%s", HdxPrimitiveTokens->renderTask.GetText(), collectionName.GetText()))); _renderTaskIdMap[collectionName] = renderTaskId; } @@ -556,14 +510,13 @@ PxrMayaHdSceneDelegate::GetRenderTasks( cache[HdTokens->renderTags] = VtValue(renderTags); } else { // Update task's render tags - const TfTokenVector& currentRenderTags = - _GetValue(renderTaskId, HdTokens->renderTags); + const TfTokenVector& currentRenderTags + = _GetValue(renderTaskId, HdTokens->renderTags); if (currentRenderTags != renderTags) { _SetValue(renderTaskId, HdTokens->renderTags, renderTags); renderIndex.GetChangeTracker().MarkTaskDirty( - renderTaskId, - HdChangeTracker::DirtyRenderTags); + renderTaskId, HdChangeTracker::DirtyRenderTags); } } @@ -603,11 +556,11 @@ PxrMayaHdSceneDelegate::GetRenderTasks( // // Get the render setup task params from the value cache. - HdxRenderTaskParams renderSetupTaskParams = - _GetValue(renderSetupTaskId, HdTokens->params); + HdxRenderTaskParams renderSetupTaskParams + = _GetValue(renderSetupTaskId, HdTokens->params); - if (renderSetupTaskParams.enableLighting != renderParams.enableLighting || - renderSetupTaskParams.wireframeColor != renderParams.wireframeColor) { + if (renderSetupTaskParams.enableLighting != renderParams.enableLighting + || renderSetupTaskParams.wireframeColor != renderParams.wireframeColor) { // Update the render setup task params. renderSetupTaskParams.enableLighting = renderParams.enableLighting; renderSetupTaskParams.wireframeColor = renderParams.wireframeColor; @@ -616,26 +569,22 @@ PxrMayaHdSceneDelegate::GetRenderTasks( // mark them dirty. _SetValue(renderSetupTaskId, HdTokens->params, renderSetupTaskParams); renderIndex.GetChangeTracker().MarkTaskDirty( - renderSetupTaskId, - HdChangeTracker::DirtyParams); + renderSetupTaskId, HdChangeTracker::DirtyParams); } return taskList; } -HdTaskSharedPtrVector -PxrMayaHdSceneDelegate::GetPickingTasks( - const TfTokenVector& renderTags) +HdTaskSharedPtrVector PxrMayaHdSceneDelegate::GetPickingTasks(const TfTokenVector& renderTags) { // Update tasks render tags to match those specified in the parameter. - const TfTokenVector ¤tRenderTags = - _GetValue(_pickingTaskId, HdTokens->renderTags); + const TfTokenVector& currentRenderTags + = _GetValue(_pickingTaskId, HdTokens->renderTags); if (currentRenderTags != renderTags) { _SetValue(_pickingTaskId, HdTokens->renderTags, renderTags); GetRenderIndex().GetChangeTracker().MarkTaskDirty( - _pickingTaskId, - HdChangeTracker::DirtyRenderTags); + _pickingTaskId, HdChangeTracker::DirtyRenderTags); } HdTaskSharedPtrVector tasks; @@ -645,5 +594,4 @@ PxrMayaHdSceneDelegate::GetPickingTasks( return tasks; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/sceneDelegate.h b/lib/mayaUsd/render/pxrUsdMayaGL/sceneDelegate.h index 08b950104a..9f3188125c 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/sceneDelegate.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/sceneDelegate.h @@ -18,12 +18,10 @@ /// \file pxrUsdMayaGL/sceneDelegate.h -#include -#include - -#include +#include +#include +#include -#include #include #include #include @@ -35,12 +33,13 @@ #include #include #include +#include #include -#include +#include -#include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -53,128 +52,119 @@ PXR_NAMESPACE_OPEN_SCOPE /// set to nullptr, and a collection and set of render tags *must* be /// provided. /// -struct PxrMayaHdPrimFilter { +struct PxrMayaHdPrimFilter +{ PxrMayaHdShapeAdapter* shapeAdapter; - HdRprimCollection collection; - TfTokenVector renderTags; + HdRprimCollection collection; + TfTokenVector renderTags; }; using PxrMayaHdPrimFilterVector = std::vector; class PxrMayaHdSceneDelegate : public HdSceneDelegate { - public: - MAYAUSD_CORE_PUBLIC - PxrMayaHdSceneDelegate( - HdRenderIndex* renderIndex, - const SdfPath& delegateID); - - // HdSceneDelegate interface - MAYAUSD_CORE_PUBLIC - VtValue Get(const SdfPath& id, const TfToken& key) override; - - MAYAUSD_CORE_PUBLIC - VtValue GetCameraParamValue( - SdfPath const& cameraId, - TfToken const& paramName) override; - - MAYAUSD_CORE_PUBLIC - TfTokenVector GetTaskRenderTags(SdfPath const& taskId) override; - - MAYAUSD_CORE_PUBLIC - void SetCameraState( - const GfMatrix4d& worldToViewMatrix, - const GfMatrix4d& projectionMatrix, - const GfVec4d& viewport); - - // VP 1.0 only. - MAYAUSD_CORE_PUBLIC - void SetLightingStateFromVP1( - const GfMatrix4d& worldToViewMatrix, - const GfMatrix4d& projectionMatrix); - - // VP 2.0 only. - MAYAUSD_CORE_PUBLIC - void SetLightingStateFromMayaDrawContext( - const MHWRender::MDrawContext& context); - - MAYAUSD_CORE_PUBLIC - HdTaskSharedPtrVector GetSetupTasks(); - - MAYAUSD_CORE_PUBLIC - HdTaskSharedPtrVector GetRenderTasks( - const size_t hash, - const PxrMayaHdRenderParams& renderParams, - unsigned int displayStyle, - const PxrMayaHdPrimFilterVector& primFilters); - - MAYAUSD_CORE_PUBLIC - HdTaskSharedPtrVector GetPickingTasks( - const TfTokenVector& renderTags); - - protected: - MAYAUSD_CORE_PUBLIC - void _SetLightingStateFromLightingContext(); - - template - const T& _GetValue(const SdfPath& id, const TfToken& key) { - VtValue vParams = _valueCacheMap[id][key]; - if (!TF_VERIFY(vParams.IsHolding(), - "For Id = %s, Key = %s", - id.GetText(), key.GetText())) { - static T ERROR_VALUE; - return ERROR_VALUE; - } - return vParams.UncheckedGet(); +public: + MAYAUSD_CORE_PUBLIC + PxrMayaHdSceneDelegate(HdRenderIndex* renderIndex, const SdfPath& delegateID); + + // HdSceneDelegate interface + MAYAUSD_CORE_PUBLIC + VtValue Get(const SdfPath& id, const TfToken& key) override; + + MAYAUSD_CORE_PUBLIC + VtValue GetCameraParamValue(SdfPath const& cameraId, TfToken const& paramName) override; + + MAYAUSD_CORE_PUBLIC + TfTokenVector GetTaskRenderTags(SdfPath const& taskId) override; + + MAYAUSD_CORE_PUBLIC + void SetCameraState( + const GfMatrix4d& worldToViewMatrix, + const GfMatrix4d& projectionMatrix, + const GfVec4d& viewport); + + // VP 1.0 only. + MAYAUSD_CORE_PUBLIC + void SetLightingStateFromVP1( + const GfMatrix4d& worldToViewMatrix, + const GfMatrix4d& projectionMatrix); + + // VP 2.0 only. + MAYAUSD_CORE_PUBLIC + void SetLightingStateFromMayaDrawContext(const MHWRender::MDrawContext& context); + + MAYAUSD_CORE_PUBLIC + HdTaskSharedPtrVector GetSetupTasks(); + + MAYAUSD_CORE_PUBLIC + HdTaskSharedPtrVector GetRenderTasks( + const size_t hash, + const PxrMayaHdRenderParams& renderParams, + unsigned int displayStyle, + const PxrMayaHdPrimFilterVector& primFilters); + + MAYAUSD_CORE_PUBLIC + HdTaskSharedPtrVector GetPickingTasks(const TfTokenVector& renderTags); + +protected: + MAYAUSD_CORE_PUBLIC + void _SetLightingStateFromLightingContext(); + + template const T& _GetValue(const SdfPath& id, const TfToken& key) + { + VtValue vParams = _valueCacheMap[id][key]; + if (!TF_VERIFY( + vParams.IsHolding(), "For Id = %s, Key = %s", id.GetText(), key.GetText())) { + static T ERROR_VALUE; + return ERROR_VALUE; } + return vParams.UncheckedGet(); + } - template - void _SetValue(const SdfPath& id, const TfToken& key, const T& value) { - _valueCacheMap[id][key] = value; - } + template void _SetValue(const SdfPath& id, const TfToken& key, const T& value) + { + _valueCacheMap[id][key] = value; + } - private: - SdfPath _rootId; +private: + SdfPath _rootId; - SdfPath _cameraId; - GfVec4d _viewport; + SdfPath _cameraId; + GfVec4d _viewport; - SdfPath _simpleLightTaskId; - SdfPathVector _lightIds; - GlfSimpleLightingContextRefPtr _lightingContext; + SdfPath _simpleLightTaskId; + SdfPathVector _lightIds; + GlfSimpleLightingContextRefPtr _lightingContext; - SdfPath _shadowTaskId; + SdfPath _shadowTaskId; - // When prim filters are populated including a shape adapter, the - // adapter is responsible for providing the appropriate render task ID - // for a given repr. When no shape adapter is given, the batch renderer - // manages the render task ID and constructs it using the rprim - // collection name. The batch renderer will ultimately instantiate the - // render task itself for both cases. - // This type maps collection names to render task IDs for tasks in the - // latter case where the task ID is managed by the batch renderer. - using _RenderTaskIdMap = - std::unordered_map; + // When prim filters are populated including a shape adapter, the + // adapter is responsible for providing the appropriate render task ID + // for a given repr. When no shape adapter is given, the batch renderer + // manages the render task ID and constructs it using the rprim + // collection name. The batch renderer will ultimately instantiate the + // render task itself for both cases. + // This type maps collection names to render task IDs for tasks in the + // latter case where the task ID is managed by the batch renderer. + using _RenderTaskIdMap = std::unordered_map; - // For render setup tasks, there is one task per unique set of render - // params, which are hashed to generate a key. - using _RenderParamTaskIdMap = std::unordered_map; + // For render setup tasks, there is one task per unique set of render + // params, which are hashed to generate a key. + using _RenderParamTaskIdMap = std::unordered_map; - _RenderParamTaskIdMap _renderSetupTaskIdMap; - _RenderTaskIdMap _renderTaskIdMap; + _RenderParamTaskIdMap _renderSetupTaskIdMap; + _RenderTaskIdMap _renderTaskIdMap; - SdfPath _pickingTaskId; - SdfPath _selectionTaskId; + SdfPath _pickingTaskId; + SdfPath _selectionTaskId; - typedef TfHashMap _ValueCache; - typedef TfHashMap _ValueCacheMap; - _ValueCacheMap _valueCacheMap; + typedef TfHashMap _ValueCache; + typedef TfHashMap _ValueCacheMap; + _ValueCacheMap _valueCacheMap; }; typedef std::shared_ptr PxrMayaHdSceneDelegateSharedPtr; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/shapeAdapter.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/shapeAdapter.cpp index f9599f9396..3aed576a09 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/shapeAdapter.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/shapeAdapter.cpp @@ -15,8 +15,27 @@ // #include "shapeAdapter.h" -#include -#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -34,86 +53,59 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE // Helper function that converts M3dView::DisplayStatus (legacy viewport) into // MHWRender::DisplayStatus (Viewport 2.0). -static inline -MHWRender::DisplayStatus +static inline MHWRender::DisplayStatus _ToMHWRenderDisplayStatus(const M3dView::DisplayStatus legacyDisplayStatus) { // These enums are equivalent, but statically checking just in case. static_assert( - ((int)M3dView::kActive == (int)MHWRender::kActive) && - ((int)M3dView::kLive == (int)MHWRender::kLive) && - ((int)M3dView::kDormant == (int)MHWRender::kDormant) && - ((int)M3dView::kInvisible == (int)MHWRender::kInvisible) && - ((int)M3dView::kHilite == (int)MHWRender::kHilite) && - ((int)M3dView::kTemplate == (int)MHWRender::kTemplate) && - ((int)M3dView::kActiveTemplate == (int)MHWRender::kActiveTemplate) && - ((int)M3dView::kActiveComponent == (int)MHWRender::kActiveComponent) && - ((int)M3dView::kLead == (int)MHWRender::kLead) && - ((int)M3dView::kIntermediateObject == (int)MHWRender::kIntermediateObject) && - ((int)M3dView::kActiveAffected == (int)MHWRender::kActiveAffected) && - ((int)M3dView::kNoStatus == (int)MHWRender::kNoStatus), - "M3dView::DisplayStatus == MHWRender::DisplayStatus"); + ((int)M3dView::kActive == (int)MHWRender::kActive) + && ((int)M3dView::kLive == (int)MHWRender::kLive) + && ((int)M3dView::kDormant == (int)MHWRender::kDormant) + && ((int)M3dView::kInvisible == (int)MHWRender::kInvisible) + && ((int)M3dView::kHilite == (int)MHWRender::kHilite) + && ((int)M3dView::kTemplate == (int)MHWRender::kTemplate) + && ((int)M3dView::kActiveTemplate == (int)MHWRender::kActiveTemplate) + && ((int)M3dView::kActiveComponent == (int)MHWRender::kActiveComponent) + && ((int)M3dView::kLead == (int)MHWRender::kLead) + && ((int)M3dView::kIntermediateObject == (int)MHWRender::kIntermediateObject) + && ((int)M3dView::kActiveAffected == (int)MHWRender::kActiveAffected) + && ((int)M3dView::kNoStatus == (int)MHWRender::kNoStatus), + "M3dView::DisplayStatus == MHWRender::DisplayStatus"); return MHWRender::DisplayStatus((int)legacyDisplayStatus); } -static inline -bool -_IsActiveDisplayStatus(MHWRender::DisplayStatus displayStatus) +static inline bool _IsActiveDisplayStatus(MHWRender::DisplayStatus displayStatus) { - return - (displayStatus == MHWRender::DisplayStatus::kActive) || - (displayStatus == MHWRender::DisplayStatus::kHilite) || - (displayStatus == MHWRender::DisplayStatus::kActiveTemplate) || - (displayStatus == MHWRender::DisplayStatus::kActiveComponent) || - (displayStatus == MHWRender::DisplayStatus::kLead); + return (displayStatus == MHWRender::DisplayStatus::kActive) + || (displayStatus == MHWRender::DisplayStatus::kHilite) + || (displayStatus == MHWRender::DisplayStatus::kActiveTemplate) + || (displayStatus == MHWRender::DisplayStatus::kActiveComponent) + || (displayStatus == MHWRender::DisplayStatus::kLead); } -bool -PxrMayaHdShapeAdapter::Sync( - const MDagPath& shapeDagPath, - const M3dView::DisplayStyle legacyDisplayStyle, - const M3dView::DisplayStatus legacyDisplayStatus) +bool PxrMayaHdShapeAdapter::Sync( + const MDagPath& shapeDagPath, + const M3dView::DisplayStyle legacyDisplayStyle, + const M3dView::DisplayStatus legacyDisplayStatus) { // Legacy viewport implementation. UsdMayaGLBatchRenderer::GetInstance().StartBatchingFrameDiagnostics(); - const unsigned int displayStyle = - px_LegacyViewportUtils::GetMFrameContextDisplayStyle( - legacyDisplayStyle); - const MHWRender::DisplayStatus displayStatus = - _ToMHWRenderDisplayStatus(legacyDisplayStatus); + const unsigned int displayStyle + = px_LegacyViewportUtils::GetMFrameContextDisplayStyle(legacyDisplayStyle); + const MHWRender::DisplayStatus displayStatus = _ToMHWRenderDisplayStatus(legacyDisplayStatus); - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - "Synchronizing PxrMayaHdShapeAdapter for legacy viewport: %p\n", - this); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg("Synchronizing PxrMayaHdShapeAdapter for legacy viewport: %p\n", this); const bool success = _Sync(shapeDagPath, displayStyle, displayStatus); @@ -129,51 +121,39 @@ PxrMayaHdShapeAdapter::Sync( // _GetWireframeColor() again. if (_renderParams.wireframeColor[3] > 0.0f) { _renderParams.wireframeColor[3] = 1.0f; - _renderParams.wireframeColor = - GfConvertDisplayToLinear(_renderParams.wireframeColor); + _renderParams.wireframeColor = GfConvertDisplayToLinear(_renderParams.wireframeColor); } } return success; } -bool -PxrMayaHdShapeAdapter::Sync( - const MDagPath& shapeDagPath, - const unsigned int displayStyle, - const MHWRender::DisplayStatus displayStatus) +bool PxrMayaHdShapeAdapter::Sync( + const MDagPath& shapeDagPath, + const unsigned int displayStyle, + const MHWRender::DisplayStatus displayStatus) { // Viewport 2.0 implementation. UsdMayaGLBatchRenderer::GetInstance().StartBatchingFrameDiagnostics(); - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - "Synchronizing PxrMayaHdShapeAdapter for Viewport 2.0: %p\n", - this); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg("Synchronizing PxrMayaHdShapeAdapter for Viewport 2.0: %p\n", this); return _Sync(shapeDagPath, displayStyle, displayStatus); } /* virtual */ -bool -PxrMayaHdShapeAdapter::UpdateVisibility(const M3dView* view) -{ - return false; -} +bool PxrMayaHdShapeAdapter::UpdateVisibility(const M3dView* view) { return false; } /* virtual */ -bool -PxrMayaHdShapeAdapter::IsVisible() const -{ - return false; -} +bool PxrMayaHdShapeAdapter::IsVisible() const { return false; } /* virtual */ -void -PxrMayaHdShapeAdapter::GetMayaUserData( - MPxSurfaceShapeUI* shapeUI, - MDrawRequest& drawRequest, - const MBoundingBox* boundingBox) +void PxrMayaHdShapeAdapter::GetMayaUserData( + MPxSurfaceShapeUI* shapeUI, + MDrawRequest& drawRequest, + const MBoundingBox* boundingBox) { // Legacy viewport implementation. @@ -191,9 +171,7 @@ PxrMayaHdShapeAdapter::GetMayaUserData( /* virtual */ PxrMayaHdUserData* -PxrMayaHdShapeAdapter::GetMayaUserData( - MUserData* oldData, - const MBoundingBox* boundingBox) +PxrMayaHdShapeAdapter::GetMayaUserData(MUserData* oldData, const MBoundingBox* boundingBox) { // Viewport 2.0 implementation (also called by legacy viewport // implementation). @@ -219,13 +197,12 @@ PxrMayaHdShapeAdapter::GetMayaUserData( } HdReprSelector -PxrMayaHdShapeAdapter::GetReprSelectorForDisplayStyle( - unsigned int displayStyle) const +PxrMayaHdShapeAdapter::GetReprSelectorForDisplayStyle(unsigned int displayStyle) const { HdReprSelector reprSelector; - const bool boundingBoxStyle = - displayStyle & MHWRender::MFrameContext::DisplayStyle::kBoundingBox; + const bool boundingBoxStyle + = displayStyle & MHWRender::MFrameContext::DisplayStyle::kBoundingBox; if (boundingBoxStyle) { // We don't currently use Hydra to draw bounding boxes, so we return an @@ -238,20 +215,18 @@ PxrMayaHdShapeAdapter::GetReprSelectorForDisplayStyle( return reprSelector; } - const MHWRender::DisplayStatus displayStatus = - MHWRender::MGeometryUtilities::displayStatus(_shapeDagPath); + const MHWRender::DisplayStatus displayStatus + = MHWRender::MGeometryUtilities::displayStatus(_shapeDagPath); const bool isActive = _IsActiveDisplayStatus(displayStatus); - const bool shadeActiveOnlyStyle = - displayStyle & MHWRender::MFrameContext::DisplayStyle::kShadeActiveOnly; + const bool shadeActiveOnlyStyle + = displayStyle & MHWRender::MFrameContext::DisplayStyle::kShadeActiveOnly; - const bool wireframeStyle = - (displayStyle & MHWRender::MFrameContext::DisplayStyle::kWireFrame) || - _renderParams.useWireframe; + const bool wireframeStyle = (displayStyle & MHWRender::MFrameContext::DisplayStyle::kWireFrame) + || _renderParams.useWireframe; - const bool flatShadedStyle = - displayStyle & MHWRender::MFrameContext::DisplayStyle::kFlatShaded; + const bool flatShadedStyle = displayStyle & MHWRender::MFrameContext::DisplayStyle::kFlatShaded; if (flatShadedStyle) { if (!shadeActiveOnlyStyle || isActive) { @@ -264,8 +239,7 @@ PxrMayaHdShapeAdapter::GetReprSelectorForDisplayStyle( // We're in shadeActiveOnly mode but this shape is not active. reprSelector = HdReprSelector(HdReprTokens->wire); } - } - else if (displayStyle & MHWRender::MFrameContext::DisplayStyle::kGouraudShaded) { + } else if (displayStyle & MHWRender::MFrameContext::DisplayStyle::kGouraudShaded) { if (!shadeActiveOnlyStyle || isActive) { if (wireframeStyle) { reprSelector = HdReprSelector(HdReprTokens->refinedWireOnSurf); @@ -276,11 +250,9 @@ PxrMayaHdShapeAdapter::GetReprSelectorForDisplayStyle( // We're in shadeActiveOnly mode but this shape is not active. reprSelector = HdReprSelector(HdReprTokens->refinedWire); } - } - else if (wireframeStyle) { + } else if (wireframeStyle) { reprSelector = HdReprSelector(HdReprTokens->refinedWire); - } - else if (displayStyle & MHWRender::MFrameContext::DisplayStyle::kTwoSidedLighting) { + } else if (displayStyle & MHWRender::MFrameContext::DisplayStyle::kTwoSidedLighting) { // The UV editor uses the kTwoSidedLighting displayStyle. // // For now, to prevent objects from completely disappearing, we just @@ -291,8 +263,7 @@ PxrMayaHdShapeAdapter::GetReprSelectorForDisplayStyle( return reprSelector; } -MStatus -PxrMayaHdShapeAdapter::_SetDagPath(const MDagPath& dagPath) +MStatus PxrMayaHdShapeAdapter::_SetDagPath(const MDagPath& dagPath) { if (_shapeDagPath == dagPath) { return MS::kSuccess; @@ -306,7 +277,7 @@ PxrMayaHdShapeAdapter::_SetDagPath(const MDagPath& dagPath) _rprimCollectionMap.clear(); _renderTaskIdMap.clear(); - MStatus status; + MStatus status; const bool dagPathIsValid = _shapeDagPath.isValid(&status); if (status != MS::kSuccess || !dagPathIsValid) { return status; @@ -323,86 +294,65 @@ PxrMayaHdShapeAdapter::_SetDagPath(const MDagPath& dagPath) const MUuid shapeUuid = dagNodeFn.uuid(&status); CHECK_MSTATUS_AND_RETURN_IT(status); - const std::string uuidString( - shapeUuid.asString().asChar(), - shapeUuid.asString().length()); + const std::string uuidString(shapeUuid.asString().asChar(), shapeUuid.asString().length()); _shapeIdentifier = TfToken(TfMakeValidIdentifier(uuidString)); - const UsdMayaGLBatchRenderer& batchRenderer = - UsdMayaGLBatchRenderer::GetInstance(); - HdRenderIndex* renderIndex = batchRenderer.GetRenderIndex(); + const UsdMayaGLBatchRenderer& batchRenderer = UsdMayaGLBatchRenderer::GetInstance(); + HdRenderIndex* renderIndex = batchRenderer.GetRenderIndex(); - const SdfPath delegatePrefix = - batchRenderer.GetDelegatePrefix(_isViewport2); + const SdfPath delegatePrefix = batchRenderer.GetDelegatePrefix(_isViewport2); _delegateId = delegatePrefix.AppendChild(_shapeIdentifier); // Create entries in the collection and render task ID maps for each repr // we might use. - static const std::vector allMayaReprs({ - HdReprSelector(HdReprTokens->hull), - HdReprSelector(HdReprTokens->refined), - HdReprSelector(HdReprTokens->refinedWire), - HdReprSelector(HdReprTokens->refinedWireOnSurf), - HdReprSelector(HdReprTokens->wire), - HdReprSelector(HdReprTokens->wireOnSurf) - }); + static const std::vector allMayaReprs( + { HdReprSelector(HdReprTokens->hull), + HdReprSelector(HdReprTokens->refined), + HdReprSelector(HdReprTokens->refinedWire), + HdReprSelector(HdReprTokens->refinedWireOnSurf), + HdReprSelector(HdReprTokens->wire), + HdReprSelector(HdReprTokens->wireOnSurf) }); for (const HdReprSelector& reprSelector : allMayaReprs) { - const TfToken rprimCollectionName = TfToken( - TfStringPrintf("%s_%s", - _shapeIdentifier.GetText(), - reprSelector.GetText())); - _rprimCollectionMap.emplace( - std::make_pair( - reprSelector, - HdRprimCollection( - rprimCollectionName, - reprSelector, - _delegateId))); + const TfToken rprimCollectionName + = TfToken(TfStringPrintf("%s_%s", _shapeIdentifier.GetText(), reprSelector.GetText())); + _rprimCollectionMap.emplace(std::make_pair( + reprSelector, HdRprimCollection(rprimCollectionName, reprSelector, _delegateId))); renderIndex->GetChangeTracker().AddCollection(rprimCollectionName); // We only generate the render task ID here. We'll leave it to the // batch renderer to lazily create the task in the render index when // it is first needed. - const TfToken renderTaskName = TfToken( - TfStringPrintf("%s_%s", - HdxPrimitiveTokens->renderTask.GetText(), - rprimCollectionName.GetText())); + const TfToken renderTaskName = TfToken(TfStringPrintf( + "%s_%s", HdxPrimitiveTokens->renderTask.GetText(), rprimCollectionName.GetText())); _renderTaskIdMap.emplace( - std::make_pair( - reprSelector, - _delegateId.AppendChild(renderTaskName))); + std::make_pair(reprSelector, _delegateId.AppendChild(renderTaskName))); } return status; } -void -PxrMayaHdShapeAdapter::_MarkRenderTasksDirty(HdDirtyBits dirtyBits) +void PxrMayaHdShapeAdapter::_MarkRenderTasksDirty(HdDirtyBits dirtyBits) { - HdRenderIndex* renderIndex = - UsdMayaGLBatchRenderer::GetInstance().GetRenderIndex(); + HdRenderIndex* renderIndex = UsdMayaGLBatchRenderer::GetInstance().GetRenderIndex(); for (const auto& iter : _renderTaskIdMap) { // The render tasks represented by the IDs in this map are instantiated // lazily, so check that the task exists before attempting to dirty it. if (renderIndex->HasTask(iter.second)) { - renderIndex->GetChangeTracker().MarkTaskDirty( - iter.second, - dirtyBits); + renderIndex->GetChangeTracker().MarkTaskDirty(iter.second, dirtyBits); } } } /* static */ -bool -PxrMayaHdShapeAdapter::_GetWireframeColor( - MHWRender::DisplayStatus displayStatus, - const MDagPath& shapeDagPath, - GfVec4f* wireframeColor) +bool PxrMayaHdShapeAdapter::_GetWireframeColor( + MHWRender::DisplayStatus displayStatus, + const MDagPath& shapeDagPath, + GfVec4f* wireframeColor) { bool useWireframeColor = false; @@ -412,12 +362,9 @@ PxrMayaHdShapeAdapter::_GetWireframeColor( if (displayStatus == MHWRender::kDormant) { auto& batchRenderer = UsdMayaGLBatchRenderer::GetInstance(); if (batchRenderer.GetObjectSoftSelectEnabled()) { - const UsdMayaGLSoftSelectHelper& softSelectHelper = - UsdMayaGLBatchRenderer::GetInstance().GetSoftSelectHelper(); - useWireframeColor = - softSelectHelper.GetFalloffColor( - shapeDagPath, - &mayaWireframeColor); + const UsdMayaGLSoftSelectHelper& softSelectHelper + = UsdMayaGLBatchRenderer::GetInstance().GetSoftSelectHelper(); + useWireframeColor = softSelectHelper.GetFalloffColor(shapeDagPath, &mayaWireframeColor); } } @@ -425,15 +372,11 @@ PxrMayaHdShapeAdapter::_GetWireframeColor( // The caller wants a color returned. If the object isn't included in a // soft selection, just ask Maya for the wireframe color. if (!useWireframeColor) { - mayaWireframeColor = - MHWRender::MGeometryUtilities::wireframeColor(shapeDagPath); + mayaWireframeColor = MHWRender::MGeometryUtilities::wireframeColor(shapeDagPath); } *wireframeColor = GfVec4f( - mayaWireframeColor.r, - mayaWireframeColor.g, - mayaWireframeColor.b, - mayaWireframeColor.a); + mayaWireframeColor.r, mayaWireframeColor.g, mayaWireframeColor.b, mayaWireframeColor.a); } if (_IsActiveDisplayStatus(displayStatus)) { @@ -444,15 +387,14 @@ PxrMayaHdShapeAdapter::_GetWireframeColor( } /* static */ -bool -PxrMayaHdShapeAdapter::_GetVisibility( - const MDagPath& dagPath, - const M3dView* view, - bool* visibility) +bool PxrMayaHdShapeAdapter::_GetVisibility( + const MDagPath& dagPath, + const M3dView* view, + bool* visibility) { - MStatus status; - const MHWRender::DisplayStatus displayStatus = - MHWRender::MGeometryUtilities::displayStatus(dagPath, &status); + MStatus status; + const MHWRender::DisplayStatus displayStatus + = MHWRender::MGeometryUtilities::displayStatus(dagPath, &status); if (status != MS::kSuccess) { return false; } @@ -491,11 +433,10 @@ PxrMayaHdShapeAdapter::_GetVisibility( return false; } if (somethingIsolated) { - bool isIsolateVisible = false; + bool isIsolateVisible = false; MDagPath curPath(dagPath); while (curPath.length()) { - const bool hasItem = isolatedObjects.hasItem( - curPath, MObject::kNullObj, &status); + const bool hasItem = isolatedObjects.hasItem(curPath, MObject::kNullObj, &status); if (status != MS::kSuccess) { return false; } @@ -514,21 +455,18 @@ PxrMayaHdShapeAdapter::_GetVisibility( return true; } -PxrMayaHdShapeAdapter::PxrMayaHdShapeAdapter(bool isViewport2) : - _isViewport2(isViewport2) +PxrMayaHdShapeAdapter::PxrMayaHdShapeAdapter(bool isViewport2) + : _isViewport2(isViewport2) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - "Constructing PxrMayaHdShapeAdapter: %p\n", - this); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg("Constructing PxrMayaHdShapeAdapter: %p\n", this); } /* virtual */ PxrMayaHdShapeAdapter::~PxrMayaHdShapeAdapter() { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - "Destructing PxrMayaHdShapeAdapter: %p\n", - this); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg("Destructing PxrMayaHdShapeAdapter: %p\n", this); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/shapeAdapter.h b/lib/mayaUsd/render/pxrUsdMayaGL/shapeAdapter.h index ba35b21f7c..ac2522f5a4 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/shapeAdapter.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/shapeAdapter.h @@ -18,10 +18,6 @@ /// \file pxrUsdMayaGL/shapeAdapter.h -#include -#include - -#include #include #include #include @@ -29,8 +25,12 @@ #include #include #include +#include #include +#include +#include + // XXX: With Maya versions up through 2019 on Linux, M3dView.h ends up // indirectly including an X11 header that #define's "Bool" as int: // - includes @@ -45,7 +45,12 @@ #include #include -#undef Always // Defined in /usr/lib/X11/X.h (eventually included by M3dView.h) - breaks pxr/usd/lib/usdUtils/registeredVariantSet.h +#undef Always // Defined in /usr/lib/X11/X.h (eventually included by M3dView.h) - breaks + // pxr/usd/lib/usdUtils/registeredVariantSet.h +#include +#include +#include + #include #include #include @@ -53,338 +58,306 @@ #include #include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE - /// Abstract base class for objects that manage translation of Maya shape node /// data and viewport state for imaging with Hydra. class PxrMayaHdShapeAdapter { - public: - - /// Update the shape adapter's state from the shape with the given - /// \p shapeDagPath and the legacy viewport display state. - MAYAUSD_CORE_PUBLIC - bool Sync( - const MDagPath& shapeDagPath, - const M3dView::DisplayStyle legacyDisplayStyle, - const M3dView::DisplayStatus legacyDisplayStatus); - - /// Update the shape adapter's state from the shape with the given - /// \p shapeDagPath and the Viewport 2.0 display state. - MAYAUSD_CORE_PUBLIC - bool Sync( - const MDagPath& shapeDagPath, - const unsigned int displayStyle, - const MHWRender::DisplayStatus displayStatus); - - /// Update the shape adapter's visibility state from the display status - /// of its shape. - /// - /// When a Maya shape is made invisible, it may no longer be included - /// in the "prepare" phase of a viewport render (i.e. we get no - /// getDrawRequests() or prepareForDraw() callbacks for that shape). - /// This method can be called on demand to ensure that the shape - /// adapter is updated with the current visibility state of the shape. - /// - /// The optional \p view parameter can be passed to have view-based - /// state such as view and/or plugin object filtering factor into the - /// shape's visibility. - /// - /// Returns true if the visibility state was changed, or false - /// otherwise. - MAYAUSD_CORE_PUBLIC - virtual bool UpdateVisibility(const M3dView* view = nullptr); - - /// Gets whether the shape adapter's shape is visible. - /// - /// This should be called after a call to UpdateVisibility() to ensure - /// that the returned value is correct. - MAYAUSD_CORE_PUBLIC - virtual bool IsVisible() const; - - /// Get the Maya user data object for drawing in the legacy viewport. - /// - /// This Maya user data is attached to the given \p drawRequest. Its - /// lifetime is *not* managed by Maya, so the batch renderer deletes it - /// manually at the end of a legacy viewport Draw(). - /// - /// \p boundingBox may be set to nullptr if no box is desired to be - /// drawn. - /// - MAYAUSD_CORE_PUBLIC - virtual void GetMayaUserData( - MPxSurfaceShapeUI* shapeUI, - MDrawRequest& drawRequest, - const MBoundingBox* boundingBox = nullptr); - - /// Get the Maya user data object for drawing in Viewport 2.0. - /// - /// \p oldData should be the same \p oldData parameter that Maya passed - /// into the calling prepareForDraw() method. The return value from - /// this method should then be returned back to Maya in the calling - /// prepareForDraw(). - /// - /// Note that this version of GetMayaUserData() is also invoked by the - /// legacy viewport version, in which case we expect oldData to be - /// nullptr. - /// - /// \p boundingBox may be set to nullptr if no box is desired to be - /// drawn. - /// - /// Returns a pointer to a new PxrMayaHdUserData object populated with - /// the given parameters if oldData is nullptr (or not an instance of - /// PxrMayaHdUserData), otherwise returns oldData after having - /// re-populated it. - MAYAUSD_CORE_PUBLIC - virtual PxrMayaHdUserData* GetMayaUserData( - MUserData* oldData, - const MBoundingBox* boundingBox = nullptr); - - /// Gets the HdReprSelector that corresponds to the given Maya display - /// style. - /// - /// \p displayStyle should be a bitwise combination of - /// MHWRender::MFrameContext::DisplayStyle values, typically either - /// up-converted from a single M3dView::DisplayStyle value obtained - /// using MDrawInfo::displayStyle() for the legacy viewport, or - /// obtained using MHWRender::MFrameContext::getDisplayStyle() for - /// Viewport 2.0. - /// - /// The HdReprSelector chosen is also dependent on the display status - /// (active/selected vs. inactive) which Maya is queried for, as well - /// as whether or not the render params specify that we are using the - /// shape's wireframe, which is influenced by both the display status - /// and whether or not the shape is involved in a soft selection. - /// - /// If there is no corresponding HdReprSelector for the given display - /// style, an empty HdReprSelector is returned. - MAYAUSD_CORE_PUBLIC - HdReprSelector GetReprSelectorForDisplayStyle( - unsigned int displayStyle) const; - - /// Get the render params for the shape adapter's current state. - const PxrMayaHdRenderParams& GetRenderParams() const { - return _renderParams; +public: + /// Update the shape adapter's state from the shape with the given + /// \p shapeDagPath and the legacy viewport display state. + MAYAUSD_CORE_PUBLIC + bool Sync( + const MDagPath& shapeDagPath, + const M3dView::DisplayStyle legacyDisplayStyle, + const M3dView::DisplayStatus legacyDisplayStatus); + + /// Update the shape adapter's state from the shape with the given + /// \p shapeDagPath and the Viewport 2.0 display state. + MAYAUSD_CORE_PUBLIC + bool Sync( + const MDagPath& shapeDagPath, + const unsigned int displayStyle, + const MHWRender::DisplayStatus displayStatus); + + /// Update the shape adapter's visibility state from the display status + /// of its shape. + /// + /// When a Maya shape is made invisible, it may no longer be included + /// in the "prepare" phase of a viewport render (i.e. we get no + /// getDrawRequests() or prepareForDraw() callbacks for that shape). + /// This method can be called on demand to ensure that the shape + /// adapter is updated with the current visibility state of the shape. + /// + /// The optional \p view parameter can be passed to have view-based + /// state such as view and/or plugin object filtering factor into the + /// shape's visibility. + /// + /// Returns true if the visibility state was changed, or false + /// otherwise. + MAYAUSD_CORE_PUBLIC + virtual bool UpdateVisibility(const M3dView* view = nullptr); + + /// Gets whether the shape adapter's shape is visible. + /// + /// This should be called after a call to UpdateVisibility() to ensure + /// that the returned value is correct. + MAYAUSD_CORE_PUBLIC + virtual bool IsVisible() const; + + /// Get the Maya user data object for drawing in the legacy viewport. + /// + /// This Maya user data is attached to the given \p drawRequest. Its + /// lifetime is *not* managed by Maya, so the batch renderer deletes it + /// manually at the end of a legacy viewport Draw(). + /// + /// \p boundingBox may be set to nullptr if no box is desired to be + /// drawn. + /// + MAYAUSD_CORE_PUBLIC + virtual void GetMayaUserData( + MPxSurfaceShapeUI* shapeUI, + MDrawRequest& drawRequest, + const MBoundingBox* boundingBox = nullptr); + + /// Get the Maya user data object for drawing in Viewport 2.0. + /// + /// \p oldData should be the same \p oldData parameter that Maya passed + /// into the calling prepareForDraw() method. The return value from + /// this method should then be returned back to Maya in the calling + /// prepareForDraw(). + /// + /// Note that this version of GetMayaUserData() is also invoked by the + /// legacy viewport version, in which case we expect oldData to be + /// nullptr. + /// + /// \p boundingBox may be set to nullptr if no box is desired to be + /// drawn. + /// + /// Returns a pointer to a new PxrMayaHdUserData object populated with + /// the given parameters if oldData is nullptr (or not an instance of + /// PxrMayaHdUserData), otherwise returns oldData after having + /// re-populated it. + MAYAUSD_CORE_PUBLIC + virtual PxrMayaHdUserData* + GetMayaUserData(MUserData* oldData, const MBoundingBox* boundingBox = nullptr); + + /// Gets the HdReprSelector that corresponds to the given Maya display + /// style. + /// + /// \p displayStyle should be a bitwise combination of + /// MHWRender::MFrameContext::DisplayStyle values, typically either + /// up-converted from a single M3dView::DisplayStyle value obtained + /// using MDrawInfo::displayStyle() for the legacy viewport, or + /// obtained using MHWRender::MFrameContext::getDisplayStyle() for + /// Viewport 2.0. + /// + /// The HdReprSelector chosen is also dependent on the display status + /// (active/selected vs. inactive) which Maya is queried for, as well + /// as whether or not the render params specify that we are using the + /// shape's wireframe, which is influenced by both the display status + /// and whether or not the shape is involved in a soft selection. + /// + /// If there is no corresponding HdReprSelector for the given display + /// style, an empty HdReprSelector is returned. + MAYAUSD_CORE_PUBLIC + HdReprSelector GetReprSelectorForDisplayStyle(unsigned int displayStyle) const; + + /// Get the render params for the shape adapter's current state. + const PxrMayaHdRenderParams& GetRenderParams() const { return _renderParams; } + + /// Get the rprim collection for the given repr. + /// + /// These collections are created when the shape adapter's MDagPath is + /// set to a valid Maya shape. + /// + /// Returns an empty collection if there is no collection for the given + /// repr. + const HdRprimCollection& GetRprimCollection(const HdReprSelector& repr) const + { + const auto& iter = _rprimCollectionMap.find(repr); + if (iter != _rprimCollectionMap.cend()) { + return iter->second; } - /// Get the rprim collection for the given repr. - /// - /// These collections are created when the shape adapter's MDagPath is - /// set to a valid Maya shape. - /// - /// Returns an empty collection if there is no collection for the given - /// repr. - const HdRprimCollection& GetRprimCollection( - const HdReprSelector& repr) const { - const auto& iter = _rprimCollectionMap.find(repr); - if (iter != _rprimCollectionMap.cend()) { - return iter->second; - } - - static const HdRprimCollection emptyCollection; - return emptyCollection; + static const HdRprimCollection emptyCollection; + return emptyCollection; + } + + /// Get the ID of the render task for the collection of the given repr. + /// + /// These render task IDs are created when the shape adapter's MDagPath + /// is set to a valid Maya shape. + /// + /// Returns an empty SdfPath if there is no render task ID for the + /// given repr. + const SdfPath& GetRenderTaskId(const HdReprSelector& repr) const + { + const auto& iter = _renderTaskIdMap.find(repr); + if (iter != _renderTaskIdMap.cend()) { + return iter->second; } - /// Get the ID of the render task for the collection of the given repr. - /// - /// These render task IDs are created when the shape adapter's MDagPath - /// is set to a valid Maya shape. - /// - /// Returns an empty SdfPath if there is no render task ID for the - /// given repr. - const SdfPath& GetRenderTaskId(const HdReprSelector& repr) const { - const auto& iter = _renderTaskIdMap.find(repr); - if (iter != _renderTaskIdMap.cend()) { - return iter->second; - } - - static const SdfPath emptyTaskId; - return emptyTaskId; + static const SdfPath emptyTaskId; + return emptyTaskId; + } + + /// Retrieves the render tags for this shape (i.e. which prim purposes + /// should be drawn, such as geometry, proxy, guide and/or render). + /// + /// This function just returns the _renderTags attribute and it is + /// expected that subclasses update the attribute in _Sync(). + const TfTokenVector& GetRenderTags() const { return _renderTags; } + + const GfMatrix4d& GetRootXform() const { return _rootXform; } + + /// Sets the root transform for the shape adapter. + /// + /// This function is virtual in case the shape adapter needs to update + /// other state in response to a change in the root transform (e.g. + /// updating an HdSceneDelegate). + virtual void SetRootXform(const GfMatrix4d& transform) { _rootXform = transform; } + + const SdfPath& GetDelegateID() const { return _delegateId; } + + const MDagPath& GetDagPath() const { return _shapeDagPath; } + + /// Get whether this shape adapter is for use with Viewport 2.0. + /// + /// The shape adapter's viewport renderer affiliation must be specified + /// when it is constructed. + /// + /// Returns true if the shape adapter should be used for batched + /// drawing/selection in Viewport 2.0, or false if it should be used + /// in the legacy viewport. + bool IsViewport2() const { return _isViewport2; } + +protected: + /// Update the shape adapter's state from the shape with the given + /// \p dagPath and display state. + /// + /// This method should be called by both public versions of Sync() and + /// should perform shape data updates that are common to both the + /// legacy viewport and Viewport 2.0. The legacy viewport Sync() method + /// "promotes" the display state parameters to their Viewport 2.0 + /// equivalents before calling this method. + MAYAUSD_CORE_PUBLIC + virtual bool _Sync( + const MDagPath& shapeDagPath, + const unsigned int displayStyle, + const MHWRender::DisplayStatus displayStatus) + = 0; + + /// Sets the shape adapter's DAG path. + /// + /// This re-computes the "identifier" for the shape, which is used to + /// compute the names of the shape's HdRprimCollections. The batch + /// renderer will create a render task for each of the shape's + /// HdRprimCollections, and those render tasks are identified by an + /// SdfPath constructed using the collection's name. We therefore need + /// the collections to have names that are unique to the shape they + /// represent and also sanitized for use in SdfPaths. + /// + /// The identifier will be a TfToken that is unique to the shape and is + /// a valid SdfPath identifier, or an empty TfToken if there is an + /// error, which can be detected from the returned MStatus. + MAYAUSD_CORE_PUBLIC + MStatus _SetDagPath(const MDagPath& dagPath); + + /// Mark the render tasks for this shape dirty. + /// + /// The batch renderer currently creates a render task for each shape's + /// HdRprimCollection, but it has no knowledge of when the collection + /// is changed, for example. This method should be called to notify the + /// batch renderer when such a change is made. + MAYAUSD_CORE_PUBLIC + void _MarkRenderTasksDirty(HdDirtyBits dirtyBits = HdChangeTracker::AllDirty); + + /// Helper for getting the wireframe color of the shape. + /// + /// Determining the wireframe color may involve inspecting the soft + /// selection, for which the batch renderer manages a helper. This + /// class is made a friend of the batch renderer class so that it can + /// access the soft selection info. + /// + /// Returns true if the wireframe color should be used, that is if the + /// object and/or its component(s) are involved in a selection. + /// Otherwise returns false. + /// + /// Note that we do not factor in the viewport's displayStyle, which + /// may indicate that a wireframe style is being drawn (either + /// kWireFrame or kBoundingBox). The displayStyle can be changed + /// without triggering a re-Sync(), so we want to make sure that shape + /// adapters don't inadvertently "bake in" whether to use the wireframe + /// into their render params based on it. We only want to know whether + /// we need to use the wireframe for a reason *other* than the + /// displayStyle. + /// + /// The wireframe color will always be returned in \p wireframeColor + /// (if it is not nullptr) in case the caller wants to use other + /// criteria for determining whether to use it (e.g. for bounding + /// boxes). + static bool _GetWireframeColor( + MHWRender::DisplayStatus displayStatus, + const MDagPath& shapeDagPath, + GfVec4f* wireframeColor); + + /// Helper for computing the viewport visibility of the shape. + /// + /// Takes into account the visibility attribute on the shape and its + /// DAG ancestors. If an M3dView is provided to \p view, then + /// view-based state such as view and/or plugin object filtering will + /// also be factored into the shape's visibility. + /// + /// Returns true if computing the visibility was successful, false if + /// there was an error. The visibility is returned in \p visibility. + static bool _GetVisibility(const MDagPath& dagPath, const M3dView* view, bool* visibility); + + /// Construct a new uninitialized PxrMayaHdShapeAdapter. + MAYAUSD_CORE_PUBLIC + PxrMayaHdShapeAdapter(bool isViewport2); + + MAYAUSD_CORE_PUBLIC + virtual ~PxrMayaHdShapeAdapter(); + + TfToken _shapeIdentifier; + SdfPath _delegateId; + + PxrMayaHdRenderParams _renderParams; + + struct _ReprHashFunctor + { + size_t operator()(const HdReprSelector& repr) const + { + // Since we currently only use the refinedToken of + // HdReprSelector, we only need to consider that one token when + // hashing. + return repr[0u].Hash(); } + }; - /// Retrieves the render tags for this shape (i.e. which prim purposes - /// should be drawn, such as geometry, proxy, guide and/or render). - /// - /// This function just returns the _renderTags attribute and it is - /// expected that subclasses update the attribute in _Sync(). - const TfTokenVector& GetRenderTags() const { - return _renderTags; - } + // Mapping of HdReprSelector to the rprim collection for that selector. + using _RprimCollectionMap + = std::unordered_map; + _RprimCollectionMap _rprimCollectionMap; - const GfMatrix4d& GetRootXform() const { - return _rootXform; - } + // Mapping of HdReprSelector to the ID of the render task for the + // collection for that selector. + using _RenderTaskIdMap + = std::unordered_map; + _RenderTaskIdMap _renderTaskIdMap; - /// Sets the root transform for the shape adapter. - /// - /// This function is virtual in case the shape adapter needs to update - /// other state in response to a change in the root transform (e.g. - /// updating an HdSceneDelegate). - virtual void SetRootXform(const GfMatrix4d& transform) { - _rootXform = transform; - } + TfTokenVector _renderTags; - const SdfPath& GetDelegateID() const { - return _delegateId; - } - - const MDagPath& GetDagPath() const { - return _shapeDagPath; - } + GfMatrix4d _rootXform; - /// Get whether this shape adapter is for use with Viewport 2.0. - /// - /// The shape adapter's viewport renderer affiliation must be specified - /// when it is constructed. - /// - /// Returns true if the shape adapter should be used for batched - /// drawing/selection in Viewport 2.0, or false if it should be used - /// in the legacy viewport. - bool IsViewport2() const { - return _isViewport2; - } + const bool _isViewport2; - protected: - - /// Update the shape adapter's state from the shape with the given - /// \p dagPath and display state. - /// - /// This method should be called by both public versions of Sync() and - /// should perform shape data updates that are common to both the - /// legacy viewport and Viewport 2.0. The legacy viewport Sync() method - /// "promotes" the display state parameters to their Viewport 2.0 - /// equivalents before calling this method. - MAYAUSD_CORE_PUBLIC - virtual bool _Sync( - const MDagPath& shapeDagPath, - const unsigned int displayStyle, - const MHWRender::DisplayStatus displayStatus) = 0; - - /// Sets the shape adapter's DAG path. - /// - /// This re-computes the "identifier" for the shape, which is used to - /// compute the names of the shape's HdRprimCollections. The batch - /// renderer will create a render task for each of the shape's - /// HdRprimCollections, and those render tasks are identified by an - /// SdfPath constructed using the collection's name. We therefore need - /// the collections to have names that are unique to the shape they - /// represent and also sanitized for use in SdfPaths. - /// - /// The identifier will be a TfToken that is unique to the shape and is - /// a valid SdfPath identifier, or an empty TfToken if there is an - /// error, which can be detected from the returned MStatus. - MAYAUSD_CORE_PUBLIC - MStatus _SetDagPath(const MDagPath& dagPath); - - /// Mark the render tasks for this shape dirty. - /// - /// The batch renderer currently creates a render task for each shape's - /// HdRprimCollection, but it has no knowledge of when the collection - /// is changed, for example. This method should be called to notify the - /// batch renderer when such a change is made. - MAYAUSD_CORE_PUBLIC - void _MarkRenderTasksDirty( - HdDirtyBits dirtyBits = HdChangeTracker::AllDirty); - - /// Helper for getting the wireframe color of the shape. - /// - /// Determining the wireframe color may involve inspecting the soft - /// selection, for which the batch renderer manages a helper. This - /// class is made a friend of the batch renderer class so that it can - /// access the soft selection info. - /// - /// Returns true if the wireframe color should be used, that is if the - /// object and/or its component(s) are involved in a selection. - /// Otherwise returns false. - /// - /// Note that we do not factor in the viewport's displayStyle, which - /// may indicate that a wireframe style is being drawn (either - /// kWireFrame or kBoundingBox). The displayStyle can be changed - /// without triggering a re-Sync(), so we want to make sure that shape - /// adapters don't inadvertently "bake in" whether to use the wireframe - /// into their render params based on it. We only want to know whether - /// we need to use the wireframe for a reason *other* than the - /// displayStyle. - /// - /// The wireframe color will always be returned in \p wireframeColor - /// (if it is not nullptr) in case the caller wants to use other - /// criteria for determining whether to use it (e.g. for bounding - /// boxes). - static bool _GetWireframeColor( - MHWRender::DisplayStatus displayStatus, - const MDagPath& shapeDagPath, - GfVec4f* wireframeColor); - - /// Helper for computing the viewport visibility of the shape. - /// - /// Takes into account the visibility attribute on the shape and its - /// DAG ancestors. If an M3dView is provided to \p view, then - /// view-based state such as view and/or plugin object filtering will - /// also be factored into the shape's visibility. - /// - /// Returns true if computing the visibility was successful, false if - /// there was an error. The visibility is returned in \p visibility. - static bool _GetVisibility( - const MDagPath& dagPath, - const M3dView* view, - bool* visibility); - - /// Construct a new uninitialized PxrMayaHdShapeAdapter. - MAYAUSD_CORE_PUBLIC - PxrMayaHdShapeAdapter(bool isViewport2); - - MAYAUSD_CORE_PUBLIC - virtual ~PxrMayaHdShapeAdapter(); - - TfToken _shapeIdentifier; - SdfPath _delegateId; - - PxrMayaHdRenderParams _renderParams; - - struct _ReprHashFunctor { - size_t operator()(const HdReprSelector& repr) const { - // Since we currently only use the refinedToken of - // HdReprSelector, we only need to consider that one token when - // hashing. - return repr[0u].Hash(); - } - }; - - // Mapping of HdReprSelector to the rprim collection for that selector. - using _RprimCollectionMap = - std::unordered_map< - const HdReprSelector, - const HdRprimCollection, - _ReprHashFunctor>; - _RprimCollectionMap _rprimCollectionMap; - - // Mapping of HdReprSelector to the ID of the render task for the - // collection for that selector. - using _RenderTaskIdMap = - std::unordered_map< - const HdReprSelector, - const SdfPath, - _ReprHashFunctor>; - _RenderTaskIdMap _renderTaskIdMap; - - TfTokenVector _renderTags; - - GfMatrix4d _rootXform; - - const bool _isViewport2; - - private: - - MDagPath _shapeDagPath; +private: + MDagPath _shapeDagPath; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/softSelectHelper.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/softSelectHelper.cpp index a951761cb8..f738afa732 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/softSelectHelper.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/softSelectHelper.cpp @@ -15,14 +15,14 @@ // #include "softSelectHelper.h" +#include +#include + #include #include #include #include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE UsdMayaGLSoftSelectHelper::UsdMayaGLSoftSelectHelper() @@ -32,15 +32,13 @@ UsdMayaGLSoftSelectHelper::UsdMayaGLSoftSelectHelper() #define _PXRUSDMAYA_SOFTSELECT_COLORRAMP 1 -void -UsdMayaGLSoftSelectHelper::Reset() +void UsdMayaGLSoftSelectHelper::Reset() { _populated = false; _dagPathsToWeight.clear(); } -void -UsdMayaGLSoftSelectHelper::Populate() +void UsdMayaGLSoftSelectHelper::Populate() { // only populate if we haven't already if (_populated) { @@ -53,20 +51,19 @@ UsdMayaGLSoftSelectHelper::Populate() _populated = true; } -void -UsdMayaGLSoftSelectHelper::_PopulateWeights() +void UsdMayaGLSoftSelectHelper::_PopulateWeights() { // we don't want to fallback to the active selection if there is no sot // select - bool defaultToActiveSelection = false; + bool defaultToActiveSelection = false; MRichSelection softSelect; MGlobal::getRichSelection(softSelect, defaultToActiveSelection); MSelectionList selection; softSelect.getSelection(selection); - for (MItSelectionList iter( selection, MFn::kInvalid); !iter.isDone(); iter.next() ) { + for (MItSelectionList iter(selection, MFn::kInvalid); !iter.isDone(); iter.next()) { MDagPath dagPath; - MObject component; + MObject component; iter.getDagPath(dagPath, component); // component.isNull() indcates that we're selecting a whole object, as @@ -80,27 +77,24 @@ UsdMayaGLSoftSelectHelper::_PopulateWeights() } } -void -UsdMayaGLSoftSelectHelper::_PopulateSoftSelectColorRamp() +void UsdMayaGLSoftSelectHelper::_PopulateSoftSelectColorRamp() { // Since in we are not able to get the real distance/weight value, we don't // yet store the full color ramp. We just get the first color which at // least gives feedback over which things will be influenced. - bool success = false; + bool success = false; MString commandResult; // it's really unfortunate that we have to go through this instead of having // direct access to this. - if (MGlobal::executeCommand("softSelect -query -softSelectColorCurve", - commandResult)) { + if (MGlobal::executeCommand("softSelect -query -softSelectColorCurve", commandResult)) { // parse only the first tuple. - int interp; + int interp; float r, g, b; float position; - if (sscanf(commandResult.asChar(), - "%f,%f,%f,%f,%d", &r, &g, &b, &position, &interp) == 5) { - _wireColor = MColor(r,g,b); + if (sscanf(commandResult.asChar(), "%f,%f,%f,%f,%d", &r, &g, &b, &position, &interp) == 5) { + _wireColor = MColor(r, g, b); success = true; } } @@ -110,18 +104,12 @@ UsdMayaGLSoftSelectHelper::_PopulateSoftSelectColorRamp() } } -bool -UsdMayaGLSoftSelectHelper::GetWeight( - const MDagPath& dagPath, - float* weight) const +bool UsdMayaGLSoftSelectHelper::GetWeight(const MDagPath& dagPath, float* weight) const { return TfMapLookup(_dagPathsToWeight, dagPath, weight); } -bool -UsdMayaGLSoftSelectHelper::GetFalloffColor( - const MDagPath& dagPath, - MColor* falloffColor) const +bool UsdMayaGLSoftSelectHelper::GetFalloffColor(const MDagPath& dagPath, MColor* falloffColor) const { float weight = 0.f; if (GetWeight(dagPath, &weight)) { @@ -135,5 +123,4 @@ UsdMayaGLSoftSelectHelper::GetFalloffColor( return false; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/softSelectHelper.h b/lib/mayaUsd/render/pxrUsdMayaGL/softSelectHelper.h index 930eb1ef9e..a58487e212 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/softSelectHelper.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/softSelectHelper.h @@ -18,17 +18,17 @@ /// \file pxrUsdMayaGL/softSelectHelper.h -#include +#include + +#include +#include #include #include #include #include -#include -#include - -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -74,24 +74,23 @@ class UsdMayaGLSoftSelectHelper bool GetFalloffColor(const MDagPath& dagPath, MColor* falloffColor) const; private: - void _PopulateWeights(); void _PopulateSoftSelectColorRamp(); - struct _MDagPathHash { - inline size_t operator()(const MDagPath& dagPath) const { + struct _MDagPathHash + { + inline size_t operator()(const MDagPath& dagPath) const + { return TfHash()(std::string(dagPath.fullPathName().asChar())); } }; typedef std::unordered_map _MDagPathsToWeights; _MDagPathsToWeights _dagPathsToWeight; - MColor _wireColor; - bool _populated; + MColor _wireColor; + bool _populated; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif // PXRUSDMAYAGL_SOFT_SELECT_HELPER_H diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/usdProxyShapeAdapter.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/usdProxyShapeAdapter.cpp index 6defac9905..cf82af217c 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/usdProxyShapeAdapter.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/usdProxyShapeAdapter.cpp @@ -15,19 +15,13 @@ // #include "usdProxyShapeAdapter.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include -#include #include #include #include @@ -38,24 +32,29 @@ #include #include #include +#include #include #include #include #include #include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE /* virtual */ -bool -PxrMayaHdUsdProxyShapeAdapter::UpdateVisibility(const M3dView* view) +bool PxrMayaHdUsdProxyShapeAdapter::UpdateVisibility(const M3dView* view) { bool isVisible; @@ -63,8 +62,8 @@ PxrMayaHdUsdProxyShapeAdapter::UpdateVisibility(const M3dView* view) /// const, so we have to cast away the const-ness here. M3dView* nonConstView = const_cast(view); - if (nonConstView && - !nonConstView->pluginObjectDisplay(MayaUsdProxyShapeBase::displayFilterName)) { + if (nonConstView + && !nonConstView->pluginObjectDisplay(MayaUsdProxyShapeBase::displayFilterName)) { // USD proxy shapes are being filtered from this view, so don't bother // checking any other visibility state. isVisible = false; @@ -81,15 +80,13 @@ PxrMayaHdUsdProxyShapeAdapter::UpdateVisibility(const M3dView* view) } /* virtual */ -bool -PxrMayaHdUsdProxyShapeAdapter::IsVisible() const +bool PxrMayaHdUsdProxyShapeAdapter::IsVisible() const { return (_delegate && _delegate->GetRootVisibility()); } /* virtual */ -void -PxrMayaHdUsdProxyShapeAdapter::SetRootXform(const GfMatrix4d& transform) +void PxrMayaHdUsdProxyShapeAdapter::SetRootXform(const GfMatrix4d& transform) { _rootXform = transform; @@ -99,11 +96,10 @@ PxrMayaHdUsdProxyShapeAdapter::SetRootXform(const GfMatrix4d& transform) } /* virtual */ -bool -PxrMayaHdUsdProxyShapeAdapter::_Sync( - const MDagPath& shapeDagPath, - const unsigned int displayStyle, - const MHWRender::DisplayStatus displayStatus) +bool PxrMayaHdUsdProxyShapeAdapter::_Sync( + const MDagPath& shapeDagPath, + const unsigned int displayStyle, + const MHWRender::DisplayStatus displayStatus) { TRACE_FUNCTION(); @@ -112,30 +108,32 @@ PxrMayaHdUsdProxyShapeAdapter::_Sync( MProfiler::kColorE_L2, "USD Proxy Shape Syncing Shape Adapter"); - MayaUsdProxyShapeBase* usdProxyShape = - MayaUsdProxyShapeBase::GetShapeAtDagPath(shapeDagPath); + MayaUsdProxyShapeBase* usdProxyShape = MayaUsdProxyShapeBase::GetShapeAtDagPath(shapeDagPath); if (!usdProxyShape) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg( "Failed to get MayaUsdProxyShapeBase for '%s'\n", shapeDagPath.fullPathName().asChar()); return false; } - UsdPrim usdPrim; + UsdPrim usdPrim; SdfPathVector excludedPrimPaths; - int refineLevel; - UsdTimeCode timeCode; - bool drawRenderPurpose = false; - bool drawProxyPurpose = true; - bool drawGuidePurpose = false; - if (!usdProxyShape->GetAllRenderAttributes(&usdPrim, - &excludedPrimPaths, - &refineLevel, - &timeCode, - &drawRenderPurpose, - &drawProxyPurpose, - &drawGuidePurpose)) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( + int refineLevel; + UsdTimeCode timeCode; + bool drawRenderPurpose = false; + bool drawProxyPurpose = true; + bool drawGuidePurpose = false; + if (!usdProxyShape->GetAllRenderAttributes( + &usdPrim, + &excludedPrimPaths, + &refineLevel, + &timeCode, + &drawRenderPurpose, + &drawProxyPurpose, + &drawGuidePurpose)) { + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg( "Failed to get render attributes for MayaUsdProxyShapeBase '%s'\n", shapeDagPath.fullPathName().asChar()); return false; @@ -143,13 +141,10 @@ PxrMayaHdUsdProxyShapeAdapter::_Sync( // Check for updates to the shape or changes in the batch renderer that // require us to re-initialize the shape adapter. - HdRenderIndex* renderIndex = - UsdMayaGLBatchRenderer::GetInstance().GetRenderIndex(); - if (!(shapeDagPath == GetDagPath()) || - usdPrim != _rootPrim || - excludedPrimPaths != _excludedPrimPaths || - !_delegate || - renderIndex != &_delegate->GetRenderIndex()) { + HdRenderIndex* renderIndex = UsdMayaGLBatchRenderer::GetInstance().GetRenderIndex(); + if (!(shapeDagPath == GetDagPath()) || usdPrim != _rootPrim + || excludedPrimPaths != _excludedPrimPaths || !_delegate + || renderIndex != &_delegate->GetRenderIndex()) { _SetDagPath(shapeDagPath); _rootPrim = usdPrim; _excludedPrimPaths = excludedPrimPaths; @@ -176,7 +171,7 @@ PxrMayaHdUsdProxyShapeAdapter::_Sync( _renderTags.push_back(HdRenderTagTokens->guide); } - MStatus status; + MStatus status; const MMatrix transform = GetDagPath().inclusiveMatrix(&status); if (status == MS::kSuccess) { _rootXform = GfMatrix4d(transform.matrix); @@ -188,11 +183,8 @@ PxrMayaHdUsdProxyShapeAdapter::_Sync( // Will only react if time actually changes. _delegate->SetTime(timeCode); - _renderParams.useWireframe = - _GetWireframeColor( - displayStatus, - GetDagPath(), - &_renderParams.wireframeColor); + _renderParams.useWireframe + = _GetWireframeColor(displayStatus, GetDagPath(), &_renderParams.wireframeColor); // XXX: This is not technically correct. Since the display style can vary // per viewport, this decision of whether or not to enable lighting should @@ -203,10 +195,9 @@ PxrMayaHdUsdProxyShapeAdapter::_Sync( // If the repr selector specifies a wireframe-only repr, then disable // lighting. The useWireframe property of the render params is used to // determine the repr, so be sure to do this *after* that has been set. - const HdReprSelector reprSelector = - GetReprSelectorForDisplayStyle(displayStyle); - if (reprSelector.Contains(HdReprTokens->wire) || - reprSelector.Contains(HdReprTokens->refinedWire)) { + const HdReprSelector reprSelector = GetReprSelectorForDisplayStyle(displayStyle); + if (reprSelector.Contains(HdReprTokens->wire) + || reprSelector.Contains(HdReprTokens->refinedWire)) { _renderParams.enableLighting = false; } @@ -220,8 +211,7 @@ PxrMayaHdUsdProxyShapeAdapter::_Sync( return true; } -bool -PxrMayaHdUsdProxyShapeAdapter::_Init(HdRenderIndex* renderIndex) +bool PxrMayaHdUsdProxyShapeAdapter::_Init(HdRenderIndex* renderIndex) { TRACE_FUNCTION(); @@ -230,39 +220,38 @@ PxrMayaHdUsdProxyShapeAdapter::_Init(HdRenderIndex* renderIndex) MProfiler::kColorE_L2, "USD Proxy Shape Initializing Shape Adapter"); - if (!TF_VERIFY( - renderIndex, - "Cannot initialize shape adapter with invalid HdRenderIndex")) { + if (!TF_VERIFY(renderIndex, "Cannot initialize shape adapter with invalid HdRenderIndex")) { return false; } - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - "Initializing PxrMayaHdUsdProxyShapeAdapter: %p\n" - " shape DAG path : %s\n" - " shape identifier: %s\n" - " delegateId : %s\n", - this, - GetDagPath().fullPathName().asChar(), - _shapeIdentifier.GetText(), - _delegateId.GetText()); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg( + "Initializing PxrMayaHdUsdProxyShapeAdapter: %p\n" + " shape DAG path : %s\n" + " shape identifier: %s\n" + " delegateId : %s\n", + this, + GetDagPath().fullPathName().asChar(), + _shapeIdentifier.GetText(), + _delegateId.GetText()); _delegate.reset(new UsdImagingDelegate(renderIndex, _delegateId)); - if (!TF_VERIFY(_delegate, - "Failed to create shape adapter delegate for shape %s", - GetDagPath().fullPathName().asChar())) { + if (!TF_VERIFY( + _delegate, + "Failed to create shape adapter delegate for shape %s", + GetDagPath().fullPathName().asChar())) { return false; } if (TfDebug::IsEnabled(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE)) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - " Populating delegate:\n" - " rootPrim : %s\n" - " excludedPrimPaths: ", - _rootPrim.GetPath().GetText()); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg( + " Populating delegate:\n" + " rootPrim : %s\n" + " excludedPrimPaths: ", + _rootPrim.GetPath().GetText()); for (const SdfPath& primPath : _excludedPrimPaths) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - "%s ", - primPath.GetText()); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg("%s ", primPath.GetText()); } TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg("\n"); } @@ -272,21 +261,18 @@ PxrMayaHdUsdProxyShapeAdapter::_Init(HdRenderIndex* renderIndex) return true; } -PxrMayaHdUsdProxyShapeAdapter::PxrMayaHdUsdProxyShapeAdapter(bool isViewport2) : - PxrMayaHdShapeAdapter(isViewport2) +PxrMayaHdUsdProxyShapeAdapter::PxrMayaHdUsdProxyShapeAdapter(bool isViewport2) + : PxrMayaHdShapeAdapter(isViewport2) { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - "Constructing PxrMayaHdUsdProxyShapeAdapter: %p\n", - this); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg("Constructing PxrMayaHdUsdProxyShapeAdapter: %p\n", this); } /* virtual */ PxrMayaHdUsdProxyShapeAdapter::~PxrMayaHdUsdProxyShapeAdapter() { - TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE).Msg( - "Destructing PxrMayaHdUsdProxyShapeAdapter: %p\n", - this); + TF_DEBUG(PXRUSDMAYAGL_SHAPE_ADAPTER_LIFECYCLE) + .Msg("Destructing PxrMayaHdUsdProxyShapeAdapter: %p\n", this); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/usdProxyShapeAdapter.h b/lib/mayaUsd/render/pxrUsdMayaGL/usdProxyShapeAdapter.h index 58f5395138..04c9293ee8 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/usdProxyShapeAdapter.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/usdProxyShapeAdapter.h @@ -31,118 +31,111 @@ // // The X11 include appears to have been removed in Maya 2020+, so this should // no longer be an issue with later versions. -#include - -#include -#include -#include +#include +#include -#include #include #include +#include #include +#include #include #include -#include -#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE class UsdMayaProxyDrawOverride; class UsdMayaProxyShapeUI; - /// Class to manage translation of USD proxy shape node data and viewport state /// for imaging with Hydra. class PxrMayaHdUsdProxyShapeAdapter : public PxrMayaHdShapeAdapter { - public: - - /// Update the shape adapter's visibility state from the display status - /// of its shape. - /// - /// When a Maya shape is made invisible, it may no longer be included - /// in the "prepare" phase of a viewport render (i.e. we get no - /// getDrawRequests() or prepareForDraw() callbacks for that shape). - /// This method can be called on demand to ensure that the shape - /// adapter is updated with the current visibility state of the shape. - /// - /// The optional \p view parameter can be passed to have view-based - /// state such as view and/or plugin object filtering factor into the - /// shape's visibility. - /// - /// Returns true if the visibility state was changed, or false - /// otherwise. - MAYAUSD_CORE_PUBLIC - bool UpdateVisibility(const M3dView* view = nullptr) override; - - /// Gets whether the shape adapter's shape is visible. - /// - /// This should be called after a call to UpdateVisibility() to ensure - /// that the returned value is correct. - MAYAUSD_CORE_PUBLIC - bool IsVisible() const override; - - MAYAUSD_CORE_PUBLIC - void SetRootXform(const GfMatrix4d& transform) override; - - protected: - - /// Update the shape adapter's state from the shape with the given - /// \p shapeDagPath and display state. - /// - /// This method should be called by both public versions of Sync() and - /// should perform shape data updates that are common to both the - /// legacy viewport and Viewport 2.0. The legacy viewport Sync() method - /// "promotes" the display state parameters to their Viewport 2.0 - /// equivalents before calling this method. - MAYAUSD_CORE_PUBLIC - bool _Sync( - const MDagPath& shapeDagPath, - const unsigned int displayStyle, - const MHWRender::DisplayStatus displayStatus) override; - - /// Construct a new uninitialized PxrMayaHdUsdProxyShapeAdapter. - /// - /// Note that only friends of this class are able to construct - /// instances of this class. - MAYAUSD_CORE_PUBLIC - PxrMayaHdUsdProxyShapeAdapter(bool isViewport2); - - MAYAUSD_CORE_PUBLIC - ~PxrMayaHdUsdProxyShapeAdapter() override; - - private: - - /// Initialize the shape adapter using the given \p renderIndex. - /// - /// This method is called automatically during Sync() when the shape - /// adapter's "identity" changes. This can happen when the shape - /// managed by this adapter is changed by setting a new DAG path, or - /// otherwise when there is some other fundamental change to the shape - /// or to the delegate or render index. - /// The shape adapter will then query the batch renderer for its render - /// index and use that to re-create its delegate and re-add its rprim - /// collection, if necessary. - MAYAUSD_CORE_PUBLIC - bool _Init(HdRenderIndex* renderIndex); - - UsdPrim _rootPrim; - SdfPathVector _excludedPrimPaths; - - std::shared_ptr _delegate; - - /// The classes that maintain ownership of and are responsible for - /// updating the shape adapter for their shape are made friends of - /// PxrMayaHdUsdProxyShapeAdapter so that they alone can set properties - /// on the shape adapter. - friend class UsdMayaProxyDrawOverride; - friend class UsdMayaProxyShapeUI; +public: + /// Update the shape adapter's visibility state from the display status + /// of its shape. + /// + /// When a Maya shape is made invisible, it may no longer be included + /// in the "prepare" phase of a viewport render (i.e. we get no + /// getDrawRequests() or prepareForDraw() callbacks for that shape). + /// This method can be called on demand to ensure that the shape + /// adapter is updated with the current visibility state of the shape. + /// + /// The optional \p view parameter can be passed to have view-based + /// state such as view and/or plugin object filtering factor into the + /// shape's visibility. + /// + /// Returns true if the visibility state was changed, or false + /// otherwise. + MAYAUSD_CORE_PUBLIC + bool UpdateVisibility(const M3dView* view = nullptr) override; + + /// Gets whether the shape adapter's shape is visible. + /// + /// This should be called after a call to UpdateVisibility() to ensure + /// that the returned value is correct. + MAYAUSD_CORE_PUBLIC + bool IsVisible() const override; + + MAYAUSD_CORE_PUBLIC + void SetRootXform(const GfMatrix4d& transform) override; + +protected: + /// Update the shape adapter's state from the shape with the given + /// \p shapeDagPath and display state. + /// + /// This method should be called by both public versions of Sync() and + /// should perform shape data updates that are common to both the + /// legacy viewport and Viewport 2.0. The legacy viewport Sync() method + /// "promotes" the display state parameters to their Viewport 2.0 + /// equivalents before calling this method. + MAYAUSD_CORE_PUBLIC + bool _Sync( + const MDagPath& shapeDagPath, + const unsigned int displayStyle, + const MHWRender::DisplayStatus displayStatus) override; + + /// Construct a new uninitialized PxrMayaHdUsdProxyShapeAdapter. + /// + /// Note that only friends of this class are able to construct + /// instances of this class. + MAYAUSD_CORE_PUBLIC + PxrMayaHdUsdProxyShapeAdapter(bool isViewport2); + + MAYAUSD_CORE_PUBLIC + ~PxrMayaHdUsdProxyShapeAdapter() override; + +private: + /// Initialize the shape adapter using the given \p renderIndex. + /// + /// This method is called automatically during Sync() when the shape + /// adapter's "identity" changes. This can happen when the shape + /// managed by this adapter is changed by setting a new DAG path, or + /// otherwise when there is some other fundamental change to the shape + /// or to the delegate or render index. + /// The shape adapter will then query the batch renderer for its render + /// index and use that to re-create its delegate and re-add its rprim + /// collection, if necessary. + MAYAUSD_CORE_PUBLIC + bool _Init(HdRenderIndex* renderIndex); + + UsdPrim _rootPrim; + SdfPathVector _excludedPrimPaths; + + std::shared_ptr _delegate; + + /// The classes that maintain ownership of and are responsible for + /// updating the shape adapter for their shape are made friends of + /// PxrMayaHdUsdProxyShapeAdapter so that they alone can set properties + /// on the shape adapter. + friend class UsdMayaProxyDrawOverride; + friend class UsdMayaProxyShapeUI; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/userData.cpp b/lib/mayaUsd/render/pxrUsdMayaGL/userData.cpp index fd63f76e44..6d7b53d83a 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/userData.cpp +++ b/lib/mayaUsd/render/pxrUsdMayaGL/userData.cpp @@ -15,24 +15,21 @@ // #include "userData.h" -#include - #include +#include + PXR_NAMESPACE_OPEN_SCOPE /// Note that we set deleteAfterUse=false when calling the MUserData /// constructor. This ensures that the draw data survives across multiple draw /// passes in Viewport 2.0 (e.g. a shadow pass and a color pass). -PxrMayaHdUserData::PxrMayaHdUserData() : - MUserData(/* deleteAfterUse = */ false) +PxrMayaHdUserData::PxrMayaHdUserData() + : MUserData(/* deleteAfterUse = */ false) { } /* virtual */ -PxrMayaHdUserData::~PxrMayaHdUserData() -{ -} - +PxrMayaHdUserData::~PxrMayaHdUserData() { } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/pxrUsdMayaGL/userData.h b/lib/mayaUsd/render/pxrUsdMayaGL/userData.h index db20d58d05..f24cd43646 100644 --- a/lib/mayaUsd/render/pxrUsdMayaGL/userData.h +++ b/lib/mayaUsd/render/pxrUsdMayaGL/userData.h @@ -18,15 +18,15 @@ /// \file pxrUsdMayaGL/userData.h -#include +#include + +#include +#include #include #include -#include -#include - -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -39,20 +39,17 @@ PXR_NAMESPACE_OPEN_SCOPE /// renderer. class PxrMayaHdUserData : public MUserData { - public: +public: + std::unique_ptr boundingBox; + std::unique_ptr wireframeColor; - std::unique_ptr boundingBox; - std::unique_ptr wireframeColor; + MAYAUSD_CORE_PUBLIC + PxrMayaHdUserData(); - MAYAUSD_CORE_PUBLIC - PxrMayaHdUserData(); - - MAYAUSD_CORE_PUBLIC - ~PxrMayaHdUserData() override; + MAYAUSD_CORE_PUBLIC + ~PxrMayaHdUserData() override; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/render/vp2RenderDelegate/basisCurves.cpp b/lib/mayaUsd/render/vp2RenderDelegate/basisCurves.cpp index 715564bdb5..bab4fc2b9a 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/basisCurves.cpp +++ b/lib/mayaUsd/render/vp2RenderDelegate/basisCurves.cpp @@ -16,9 +16,13 @@ // #include "basisCurves.h" -#include -#include -#include +#include "bboxGeom.h" +#include "debugCodes.h" +#include "draw_item.h" +#include "instancer.h" +#include "material.h" +#include "render_delegate.h" +#include "tokens.h" #include #include @@ -28,13 +32,9 @@ #include #include -#include "bboxGeom.h" -#include "debugCodes.h" -#include "draw_item.h" -#include "instancer.h" -#include "material.h" -#include "render_delegate.h" -#include "tokens.h" +#include +#include +#include // Complete tessellation shader support is avaiable for basisCurves complexity levels #if MAYA_API_VERSION >= 20210000 @@ -45,505 +45,486 @@ PXR_NAMESPACE_OPEN_SCOPE namespace { - //! Required primvars when there is no material binding. - const TfTokenVector sFallbackShaderPrimvars = { - HdTokens->displayColor, - HdTokens->displayOpacity, - HdTokens->normals, - HdTokens->widths - }; - - const MColor kOpaqueGray(.18f, .18f, .18f, 1.0f); //!< The default 18% gray color - const unsigned int kNumColorChannels = 4; //!< The number of color channels - - //! Cached strings for efficiency - const MString kPositionsStr("positions"); - const MString kNormalsStr("normals"); - const MString kWidthStr("U0_1"); - const MString kDiffuseColorStr("diffuseColor"); - const MString kSolidColorStr("solidColor"); - - //! A primvar vertex buffer data map indexed by primvar name. - using PrimvarBufferDataMap = std::unordered_map< - TfToken, - void*, - TfToken::HashFunctor - >; - - //! \brief Helper struct used to package all the changes into single commit task - //! (such commit task will be executed on main-thread) - struct CommitState { - HdVP2DrawItem::RenderItemData& _drawItemData; - - //! If valid, new index buffer data to commit - int* _indexBufferData{ nullptr }; - //! If valid, new color buffer data to commit - void* _colorBufferData{ nullptr }; - //! If valid, new normals buffer data to commit - void* _normalsBufferData{ nullptr }; - //! If valid, new primvar buffer data to commit - PrimvarBufferDataMap _primvarBufferDataMap; - - //! If valid, world matrix to set on the render item - MMatrix* _worldMatrix{ nullptr }; - - //! If valid, bounding box to set on the render item - MBoundingBox* _boundingBox{ nullptr }; - - //! if valid, enable or disable the render item - bool* _enabled{ nullptr }; - - //! if valid, set the primitive type on the render item - MHWRender::MGeometry::Primitive* _primitiveType{ nullptr }; - //! if valid, set the primitive stride on the render item - int* _primitiveStride{ nullptr }; - - //! Instancing doesn't have dirty bits, every time we do update, we must update instance transforms - MMatrixArray _instanceTransforms; - - //! Color array to support per-instance color and selection highlight. - MFloatArray _instanceColors; - - //! If valid, new shader instance to set - MHWRender::MShaderInstance* _shader{ nullptr }; - - //! Is this object transparent - bool _isTransparent{ false }; - - //! If true, associate geometric buffers to the render item and trigger consolidation/instancing update - bool _geometryDirty{ false }; - - //! Construct valid commit state - CommitState(HdVP2DrawItem& item) : _drawItemData(item.GetRenderItemData()) - {} - - //! No default constructor, we need draw item and dirty bits. - CommitState() = delete; - }; - - template VtArray - InterpolateVarying( - size_t numVerts, - VtIntArray const & vertexCounts, - TfToken wrap, - TfToken basis, - VtArray const & authoredValues) +//! Required primvars when there is no material binding. +const TfTokenVector sFallbackShaderPrimvars + = { HdTokens->displayColor, HdTokens->displayOpacity, HdTokens->normals, HdTokens->widths }; + +const MColor kOpaqueGray(.18f, .18f, .18f, 1.0f); //!< The default 18% gray color +const unsigned int kNumColorChannels = 4; //!< The number of color channels + +//! Cached strings for efficiency +const MString kPositionsStr("positions"); +const MString kNormalsStr("normals"); +const MString kWidthStr("U0_1"); +const MString kDiffuseColorStr("diffuseColor"); +const MString kSolidColorStr("solidColor"); + +//! A primvar vertex buffer data map indexed by primvar name. +using PrimvarBufferDataMap = std::unordered_map; + +//! \brief Helper struct used to package all the changes into single commit task +//! (such commit task will be executed on main-thread) +struct CommitState +{ + HdVP2DrawItem::RenderItemData& _drawItemData; + + //! If valid, new index buffer data to commit + int* _indexBufferData { nullptr }; + //! If valid, new color buffer data to commit + void* _colorBufferData { nullptr }; + //! If valid, new normals buffer data to commit + void* _normalsBufferData { nullptr }; + //! If valid, new primvar buffer data to commit + PrimvarBufferDataMap _primvarBufferDataMap; + + //! If valid, world matrix to set on the render item + MMatrix* _worldMatrix { nullptr }; + + //! If valid, bounding box to set on the render item + MBoundingBox* _boundingBox { nullptr }; + + //! if valid, enable or disable the render item + bool* _enabled { nullptr }; + + //! if valid, set the primitive type on the render item + MHWRender::MGeometry::Primitive* _primitiveType { nullptr }; + //! if valid, set the primitive stride on the render item + int* _primitiveStride { nullptr }; + + //! Instancing doesn't have dirty bits, every time we do update, we must update instance + //! transforms + MMatrixArray _instanceTransforms; + + //! Color array to support per-instance color and selection highlight. + MFloatArray _instanceColors; + + //! If valid, new shader instance to set + MHWRender::MShaderInstance* _shader { nullptr }; + + //! Is this object transparent + bool _isTransparent { false }; + + //! If true, associate geometric buffers to the render item and trigger consolidation/instancing + //! update + bool _geometryDirty { false }; + + //! Construct valid commit state + CommitState(HdVP2DrawItem& item) + : _drawItemData(item.GetRenderItemData()) { - VtArray outputValues(numVerts); + } - size_t srcIndex = 0; - size_t dstIndex = 0; + //! No default constructor, we need draw item and dirty bits. + CommitState() = delete; +}; + +template +VtArray InterpolateVarying( + size_t numVerts, + VtIntArray const& vertexCounts, + TfToken wrap, + TfToken basis, + VtArray const& authoredValues) +{ + VtArray outputValues(numVerts); - if (wrap == HdTokens->periodic) { - // XXX : Add support for periodic curves - TF_WARN("Varying data is only supported for non-periodic curves."); - } + size_t srcIndex = 0; + size_t dstIndex = 0; - TF_FOR_ALL(itVertexCount, vertexCounts) { - int nVerts = *itVertexCount; + if (wrap == HdTokens->periodic) { + // XXX : Add support for periodic curves + TF_WARN("Varying data is only supported for non-periodic curves."); + } - // Handling for the case of potentially incorrect vertex counts - if(nVerts < 1) { - continue; - } + TF_FOR_ALL(itVertexCount, vertexCounts) + { + int nVerts = *itVertexCount; - if(basis == HdTokens->catmullRom || basis == HdTokens->bSpline) { - // For splines with a vstep of 1, we are doing linear interpolation - // between segments, so all we do here is duplicate the first and - // last outputValues. Since these are never acutally used during - // drawing, it would also work just to set the to 0. - outputValues[dstIndex] = authoredValues[srcIndex]; - ++dstIndex; - for (int i = 1; i < nVerts - 2; ++i){ - outputValues[dstIndex] = authoredValues[srcIndex]; - ++dstIndex; ++srcIndex; - } + // Handling for the case of potentially incorrect vertex counts + if (nVerts < 1) { + continue; + } + + if (basis == HdTokens->catmullRom || basis == HdTokens->bSpline) { + // For splines with a vstep of 1, we are doing linear interpolation + // between segments, so all we do here is duplicate the first and + // last outputValues. Since these are never acutally used during + // drawing, it would also work just to set the to 0. + outputValues[dstIndex] = authoredValues[srcIndex]; + ++dstIndex; + for (int i = 1; i < nVerts - 2; ++i) { outputValues[dstIndex] = authoredValues[srcIndex]; ++dstIndex; - outputValues[dstIndex] = authoredValues[srcIndex]; - ++dstIndex; ++srcIndex; + ++srcIndex; } - else if (basis == HdTokens->bezier){ - // For bezier splines, we map the linear values to cubic values - // the begin value gets mapped to the first two vertices and - // the end value gets mapped to the last two vertices in a segment. - // shaders can choose to access value[1] and value[2] when linearly - // interpolating a value, which happens to match up with the - // indexing to use for catmullRom and bSpline basis. - int vStep = 3; + outputValues[dstIndex] = authoredValues[srcIndex]; + ++dstIndex; + outputValues[dstIndex] = authoredValues[srcIndex]; + ++dstIndex; + ++srcIndex; + } else if (basis == HdTokens->bezier) { + // For bezier splines, we map the linear values to cubic values + // the begin value gets mapped to the first two vertices and + // the end value gets mapped to the last two vertices in a segment. + // shaders can choose to access value[1] and value[2] when linearly + // interpolating a value, which happens to match up with the + // indexing to use for catmullRom and bSpline basis. + int vStep = 3; + outputValues[dstIndex] = authoredValues[srcIndex]; + ++dstIndex; // don't increment the srcIndex + outputValues[dstIndex] = authoredValues[srcIndex]; + ++dstIndex; + ++srcIndex; + + // vstep - 1 control points will have an interpolated value + for (int i = 2; i < nVerts - 2; i += vStep) { outputValues[dstIndex] = authoredValues[srcIndex]; ++dstIndex; // don't increment the srcIndex outputValues[dstIndex] = authoredValues[srcIndex]; - ++dstIndex; ++ srcIndex; - - // vstep - 1 control points will have an interpolated value - for(int i = 2; i < nVerts - 2; i += vStep) { - outputValues[dstIndex] = authoredValues[srcIndex]; - ++ dstIndex; // don't increment the srcIndex - outputValues[dstIndex] = authoredValues[srcIndex]; - ++ dstIndex; // don't increment the srcIndex - outputValues[dstIndex] = authoredValues[srcIndex]; - ++ dstIndex; ++ srcIndex; - } - outputValues[dstIndex] = authoredValues[srcIndex]; ++dstIndex; // don't increment the srcIndex outputValues[dstIndex] = authoredValues[srcIndex]; - ++dstIndex; ++ srcIndex; - } - else { - TF_WARN("Unsupported basis: '%s'", basis.GetText()); + ++dstIndex; + ++srcIndex; } + outputValues[dstIndex] = authoredValues[srcIndex]; + ++dstIndex; // don't increment the srcIndex + outputValues[dstIndex] = authoredValues[srcIndex]; + ++dstIndex; + ++srcIndex; + } else { + TF_WARN("Unsupported basis: '%s'", basis.GetText()); } - TF_VERIFY(srcIndex == authoredValues.size()); - TF_VERIFY(dstIndex == numVerts); - - return outputValues; } + TF_VERIFY(srcIndex == authoredValues.size()); + TF_VERIFY(dstIndex == numVerts); - VtValue _BuildCubicIndexArray(const HdBasisCurvesTopology& topology) + return outputValues; +} + +VtValue _BuildCubicIndexArray(const HdBasisCurvesTopology& topology) +{ + /* + Here's a diagram of what's happening in this code: + + For open (non periodic, wrap = false) curves: + + bezier (vStep = 3) + 0------1------2------3------4------5------6 (vertex index) + [======= seg0 =======] + [======= seg1 =======] + + + bspline / catmullRom (vStep = 1) + 0------1------2------3------4------5------6 (vertex index) + [======= seg0 =======] + [======= seg1 =======] + [======= seg2 =======] + [======= seg3 =======] + + + For closed (periodic, wrap = true) curves: + + periodic bezier (vStep = 3) + 0------1------2------3------4------5------0 (vertex index) + [======= seg0 =======] + [======= seg1 =======] + + + periodic bspline / catmullRom (vStep = 1) + 0------1------2------3------4------5------0------1------2 (vertex index) + [======= seg0 =======] + [======= seg1 =======] + [======= seg2 =======] + [======= seg3 =======] + [======= seg4 =======] + [======= seg5 =======] + */ + std::vector indices; + + const VtArray vertexCounts = topology.GetCurveVertexCounts(); + bool wrap = topology.GetCurveWrap() == HdTokens->periodic; + int vStep; + TfToken basis = topology.GetCurveBasis(); + if (basis == HdTokens->bezier) { + vStep = 3; + } else { + vStep = 1; + } + + int vertexIndex = 0; + int curveIndex = 0; + TF_FOR_ALL(itCounts, vertexCounts) { - /* - Here's a diagram of what's happening in this code: - - For open (non periodic, wrap = false) curves: - - bezier (vStep = 3) - 0------1------2------3------4------5------6 (vertex index) - [======= seg0 =======] - [======= seg1 =======] - - - bspline / catmullRom (vStep = 1) - 0------1------2------3------4------5------6 (vertex index) - [======= seg0 =======] - [======= seg1 =======] - [======= seg2 =======] - [======= seg3 =======] - - - For closed (periodic, wrap = true) curves: - - periodic bezier (vStep = 3) - 0------1------2------3------4------5------0 (vertex index) - [======= seg0 =======] - [======= seg1 =======] - - - periodic bspline / catmullRom (vStep = 1) - 0------1------2------3------4------5------0------1------2 (vertex index) - [======= seg0 =======] - [======= seg1 =======] - [======= seg2 =======] - [======= seg3 =======] - [======= seg4 =======] - [======= seg5 =======] - */ - std::vector indices; - - const VtArray vertexCounts = topology.GetCurveVertexCounts(); - bool wrap = topology.GetCurveWrap() == HdTokens->periodic; - int vStep; - TfToken basis = topology.GetCurveBasis(); - if(basis == HdTokens->bezier) { - vStep = 3; - } - else { - vStep = 1; + int count = *itCounts; + // The first segment always eats up 4 verts, not just vstep, so to + // compensate, we break at count - 3. + int numSegs; + + // If we're closing the curve, make sure that we have enough + // segments to wrap all the way back to the beginning. + if (wrap) { + numSegs = count / vStep; + } else { + numSegs = ((count - 4) / vStep) + 1; } - int vertexIndex = 0; - int curveIndex = 0; - TF_FOR_ALL(itCounts, vertexCounts) { - int count = *itCounts; - // The first segment always eats up 4 verts, not just vstep, so to - // compensate, we break at count - 3. - int numSegs; - - // If we're closing the curve, make sure that we have enough - // segments to wrap all the way back to the beginning. - if (wrap) { - numSegs = count / vStep; - } else { - numSegs = ((count - 4) / vStep) + 1; - } + for (int i = 0; i < numSegs; ++i) { - for(int i = 0;i < numSegs; ++i) { - - // Set up curve segments based on curve basis - GfVec4i seg; - int offset = i*vStep; - for(int v = 0;v < 4; ++v) { - // If there are not enough verts to round out the segment - // just repeat the last vert. - seg[v] = wrap - ? vertexIndex + ((offset + v) % count) - : vertexIndex + std::min(offset + v, (count -1)); - } - indices.push_back(seg); + // Set up curve segments based on curve basis + GfVec4i seg; + int offset = i * vStep; + for (int v = 0; v < 4; ++v) { + // If there are not enough verts to round out the segment + // just repeat the last vert. + seg[v] = wrap ? vertexIndex + ((offset + v) % count) + : vertexIndex + std::min(offset + v, (count - 1)); } - vertexIndex += count; - curveIndex++; + indices.push_back(seg); } + vertexIndex += count; + curveIndex++; + } - VtVec4iArray finalIndices(indices.size()); - VtIntArray const &curveIndices = topology.GetCurveIndices(); + VtVec4iArray finalIndices(indices.size()); + VtIntArray const& curveIndices = topology.GetCurveIndices(); - // If have topology has indices set, map the generated indices - // with the given indices. - if (curveIndices.empty()) - { - std::copy(indices.begin(), indices.end(), finalIndices.begin()); - } - else - { - size_t lineCount = indices.size(); - int maxIndex = curveIndices.size() - 1; - - for (size_t lineNum = 0; lineNum < lineCount; ++lineNum) - { - const GfVec4i &line = indices[lineNum]; - - int i0 = std::min(line[0], maxIndex); - int i1 = std::min(line[1], maxIndex); - int i2 = std::min(line[2], maxIndex); - int i3 = std::min(line[3], maxIndex); - - int v0 = curveIndices[i0]; - int v1 = curveIndices[i1]; - int v2 = curveIndices[i2]; - int v3 = curveIndices[i3]; - - finalIndices[lineNum].Set(v0, v1, v2, v3); - } - } + // If have topology has indices set, map the generated indices + // with the given indices. + if (curveIndices.empty()) { + std::copy(indices.begin(), indices.end(), finalIndices.begin()); + } else { + size_t lineCount = indices.size(); + int maxIndex = curveIndices.size() - 1; + + for (size_t lineNum = 0; lineNum < lineCount; ++lineNum) { + const GfVec4i& line = indices[lineNum]; - return VtValue(finalIndices); + int i0 = std::min(line[0], maxIndex); + int i1 = std::min(line[1], maxIndex); + int i2 = std::min(line[2], maxIndex); + int i3 = std::min(line[3], maxIndex); + + int v0 = curveIndices[i0]; + int v1 = curveIndices[i1]; + int v2 = curveIndices[i2]; + int v3 = curveIndices[i3]; + + finalIndices[lineNum].Set(v0, v1, v2, v3); + } } - VtValue _BuildLinesIndexArray(const HdBasisCurvesTopology& topology) + return VtValue(finalIndices); +} + +VtValue _BuildLinesIndexArray(const HdBasisCurvesTopology& topology) +{ + std::vector indices; + VtArray vertexCounts = topology.GetCurveVertexCounts(); + + int vertexIndex = 0; + int curveIndex = 0; + TF_FOR_ALL(itCounts, vertexCounts) { - std::vector indices; - VtArray vertexCounts = topology.GetCurveVertexCounts(); - - int vertexIndex = 0; - int curveIndex = 0; - TF_FOR_ALL(itCounts, vertexCounts) { - for(int i = 0; i < *itCounts; i+= 2) { - indices.push_back(GfVec2i(vertexIndex, vertexIndex + 1)); - vertexIndex += 2; - } - curveIndex++; + for (int i = 0; i < *itCounts; i += 2) { + indices.push_back(GfVec2i(vertexIndex, vertexIndex + 1)); + vertexIndex += 2; } + curveIndex++; + } - VtVec2iArray finalIndices(indices.size()); - VtIntArray const &curveIndices = topology.GetCurveIndices(); + VtVec2iArray finalIndices(indices.size()); + VtIntArray const& curveIndices = topology.GetCurveIndices(); - // If have topology has indices set, map the generated indices - // with the given indices. - if (curveIndices.empty()) - { - std::copy(indices.begin(), indices.end(), finalIndices.begin()); - } - else - { - size_t lineCount = indices.size(); - int maxIndex = curveIndices.size() - 1; + // If have topology has indices set, map the generated indices + // with the given indices. + if (curveIndices.empty()) { + std::copy(indices.begin(), indices.end(), finalIndices.begin()); + } else { + size_t lineCount = indices.size(); + int maxIndex = curveIndices.size() - 1; - for (size_t lineNum = 0; lineNum < lineCount; ++lineNum) - { - const GfVec2i &line = indices[lineNum]; + for (size_t lineNum = 0; lineNum < lineCount; ++lineNum) { + const GfVec2i& line = indices[lineNum]; - int i0 = std::min(line[0], maxIndex); - int i1 = std::min(line[1], maxIndex); + int i0 = std::min(line[0], maxIndex); + int i1 = std::min(line[1], maxIndex); - int v0 = curveIndices[i0]; - int v1 = curveIndices[i1]; + int v0 = curveIndices[i0]; + int v1 = curveIndices[i1]; - finalIndices[lineNum].Set(v0, v1); - } + finalIndices[lineNum].Set(v0, v1); } - - return VtValue(finalIndices); } - VtValue _BuildLineSegmentIndexArray(const HdBasisCurvesTopology& topology) + return VtValue(finalIndices); +} + +VtValue _BuildLineSegmentIndexArray(const HdBasisCurvesTopology& topology) +{ + const TfToken basis = topology.GetCurveBasis(); + const bool skipFirstAndLastSegs = (basis == HdTokens->catmullRom); + + std::vector indices; + const VtArray vertexCounts = topology.GetCurveVertexCounts(); + bool wrap = topology.GetCurveWrap() == HdTokens->periodic; + int vertexIndex = 0; // Index of next vertex to emit + int curveIndex = 0; // Index of next curve to emit + // For each curve + TF_FOR_ALL(itCounts, vertexCounts) { - const TfToken basis = topology.GetCurveBasis(); - const bool skipFirstAndLastSegs = (basis == HdTokens->catmullRom); - - std::vector indices; - const VtArray vertexCounts = topology.GetCurveVertexCounts(); - bool wrap = topology.GetCurveWrap() == HdTokens->periodic; - int vertexIndex = 0; // Index of next vertex to emit - int curveIndex = 0; // Index of next curve to emit - // For each curve - TF_FOR_ALL(itCounts, vertexCounts) { - int v0 = vertexIndex; - int v1; - // Store first vert index incase we are wrapping - const int firstVert = v0; - ++ vertexIndex; - for(int i = 1;i < *itCounts; ++i) { - v1 = vertexIndex; - ++ vertexIndex; - if (!skipFirstAndLastSegs || (i > 1 && i < (*itCounts)-1)) { - indices.push_back(GfVec2i(v0, v1)); - } - v0 = v1; - } - if(wrap) { - indices.push_back(GfVec2i(v0, firstVert)); + int v0 = vertexIndex; + int v1; + // Store first vert index incase we are wrapping + const int firstVert = v0; + ++vertexIndex; + for (int i = 1; i < *itCounts; ++i) { + v1 = vertexIndex; + ++vertexIndex; + if (!skipFirstAndLastSegs || (i > 1 && i < (*itCounts) - 1)) { + indices.push_back(GfVec2i(v0, v1)); } - ++curveIndex; + v0 = v1; } + if (wrap) { + indices.push_back(GfVec2i(v0, firstVert)); + } + ++curveIndex; + } - VtVec2iArray finalIndices(indices.size()); - VtIntArray const &curveIndices = topology.GetCurveIndices(); + VtVec2iArray finalIndices(indices.size()); + VtIntArray const& curveIndices = topology.GetCurveIndices(); - // If have topology has indices set, map the generated indices - // with the given indices. - if (curveIndices.empty()) - { - std::copy(indices.begin(), indices.end(), finalIndices.begin()); - } - else - { - size_t lineCount = indices.size(); - int maxIndex = curveIndices.size() - 1; + // If have topology has indices set, map the generated indices + // with the given indices. + if (curveIndices.empty()) { + std::copy(indices.begin(), indices.end(), finalIndices.begin()); + } else { + size_t lineCount = indices.size(); + int maxIndex = curveIndices.size() - 1; - for (size_t lineNum = 0; lineNum < lineCount; ++lineNum) - { - const GfVec2i &line = indices[lineNum]; + for (size_t lineNum = 0; lineNum < lineCount; ++lineNum) { + const GfVec2i& line = indices[lineNum]; - int i0 = std::min(line[0], maxIndex); - int i1 = std::min(line[1], maxIndex); + int i0 = std::min(line[0], maxIndex); + int i1 = std::min(line[1], maxIndex); - int v0 = curveIndices[i0]; - int v1 = curveIndices[i1]; + int v0 = curveIndices[i0]; + int v1 = curveIndices[i1]; - finalIndices[lineNum].Set(v0, v1); - } + finalIndices[lineNum].Set(v0, v1); } - - return VtValue(finalIndices); } - VtVec3fArray _BuildInterpolatedArray( - const HdBasisCurvesTopology& topology, - const VtVec3fArray& authoredData) - { - // We need to interpolate primvar depending on its type - size_t numVerts = topology.CalculateNeededNumberOfControlPoints(); + return VtValue(finalIndices); +} - VtVec3fArray result(numVerts); - size_t size = authoredData.size(); +VtVec3fArray +_BuildInterpolatedArray(const HdBasisCurvesTopology& topology, const VtVec3fArray& authoredData) +{ + // We need to interpolate primvar depending on its type + size_t numVerts = topology.CalculateNeededNumberOfControlPoints(); - if(size == 1) { - // Uniform data - const GfVec3f& elem = authoredData[0]; - for(size_t i = 0; i < numVerts; ++ i) { - result[i] = elem; - } - } - else if(size == numVerts) { - // Vertex data - result = authoredData; - } - else if(size == topology.CalculateNeededNumberOfVaryingControlPoints()) { - // Varying data - result = InterpolateVarying(numVerts, - topology.GetCurveVertexCounts(), - topology.GetCurveWrap(), - topology.GetCurveBasis(), - authoredData); + VtVec3fArray result(numVerts); + size_t size = authoredData.size(); + + if (size == 1) { + // Uniform data + const GfVec3f& elem = authoredData[0]; + for (size_t i = 0; i < numVerts; ++i) { + result[i] = elem; } - else { - // Fallback - const GfVec3f elem(1.0f, 0.0f, 0.0f); - for(size_t i = 0; i < numVerts; ++ i) { - result[i] = elem; - } - TF_WARN("Incorrect number of primvar data, using default GfVec3f(0,0,0) for rendering."); + } else if (size == numVerts) { + // Vertex data + result = authoredData; + } else if (size == topology.CalculateNeededNumberOfVaryingControlPoints()) { + // Varying data + result = InterpolateVarying( + numVerts, + topology.GetCurveVertexCounts(), + topology.GetCurveWrap(), + topology.GetCurveBasis(), + authoredData); + } else { + // Fallback + const GfVec3f elem(1.0f, 0.0f, 0.0f); + for (size_t i = 0; i < numVerts; ++i) { + result[i] = elem; } - - return result; + TF_WARN("Incorrect number of primvar data, using default GfVec3f(0,0,0) for rendering."); } - VtFloatArray _BuildInterpolatedArray( - const HdBasisCurvesTopology& topology, - const VtFloatArray& authoredData) - { - // We need to interpolate primvar depending on its type - size_t numVerts = topology.CalculateNeededNumberOfControlPoints(); + return result; +} - VtFloatArray result(numVerts); - size_t size = authoredData.size(); +VtFloatArray +_BuildInterpolatedArray(const HdBasisCurvesTopology& topology, const VtFloatArray& authoredData) +{ + // We need to interpolate primvar depending on its type + size_t numVerts = topology.CalculateNeededNumberOfControlPoints(); - if(size == 1) { - // Uniform or missing data - float elem = authoredData[0]; - for(size_t i = 0; i < numVerts; ++ i) { - result[i] = elem; - } - } - else if(size == numVerts) { - // Vertex data - result = authoredData; - } - else if(size == topology.CalculateNeededNumberOfVaryingControlPoints()) { - // Varying data - result = InterpolateVarying(numVerts, - topology.GetCurveVertexCounts(), - topology.GetCurveWrap(), - topology.GetCurveBasis(), - authoredData); + VtFloatArray result(numVerts); + size_t size = authoredData.size(); + + if (size == 1) { + // Uniform or missing data + float elem = authoredData[0]; + for (size_t i = 0; i < numVerts; ++i) { + result[i] = elem; } - else { - // Fallback - for(size_t i = 0; i < numVerts; ++ i) { - result[i] = 1.0; - } - TF_WARN("Incorrect number of primvar data, using default 1.0 for rendering."); + } else if (size == numVerts) { + // Vertex data + result = authoredData; + } else if (size == topology.CalculateNeededNumberOfVaryingControlPoints()) { + // Varying data + result = InterpolateVarying( + numVerts, + topology.GetCurveVertexCounts(), + topology.GetCurveWrap(), + topology.GetCurveBasis(), + authoredData); + } else { + // Fallback + for (size_t i = 0; i < numVerts; ++i) { + result[i] = 1.0; } - - return result; + TF_WARN("Incorrect number of primvar data, using default 1.0 for rendering."); } - //! Helper utility function to adapt Maya API changes. - void setWantConsolidation(MHWRender::MRenderItem& renderItem, bool state) - { + return result; +} + +//! Helper utility function to adapt Maya API changes. +void setWantConsolidation(MHWRender::MRenderItem& renderItem, bool state) +{ #if MAYA_API_VERSION >= 20190000 - renderItem.setWantConsolidation(state); + renderItem.setWantConsolidation(state); #else - renderItem.setWantSubSceneConsolidation(state); + renderItem.setWantSubSceneConsolidation(state); #endif - } +} } // anonymous namespace //! \brief Constructor HdVP2BasisCurves::HdVP2BasisCurves( - HdVP2RenderDelegate *delegate, - SdfPath const &id, - SdfPath const &instancerId) -: HdBasisCurves(id, instancerId) -, _delegate(delegate) -, _rprimId(id.GetText()) + HdVP2RenderDelegate* delegate, + SdfPath const& id, + SdfPath const& instancerId) + : HdBasisCurves(id, instancerId) + , _delegate(delegate) + , _rprimId(id.GetText()) { const MHWRender::MVertexBufferDescriptor desc( - "", - MHWRender::MGeometry::kPosition, - MHWRender::MGeometry::kFloat, - 3); + "", MHWRender::MGeometry::kPosition, MHWRender::MGeometry::kFloat, 3); _curvesSharedData._positionsBuffer.reset(new MHWRender::MVertexBuffer(desc)); } //! \brief Synchronize VP2 state with scene delegate state based on dirty bits and repr void HdVP2BasisCurves::Sync( - HdSceneDelegate *delegate, - HdRenderParam *renderParam, - HdDirtyBits *dirtyBits, - TfToken const &reprToken) + HdSceneDelegate* delegate, + HdRenderParam* renderParam, + HdDirtyBits* dirtyBits, + TfToken const& reprToken) { // We don't create a repr for the selection token because this token serves // for selection state update only. Return early to reserve dirty bits so @@ -559,34 +540,35 @@ void HdVP2BasisCurves::Sync( ProxyRenderDelegate& drawScene = param->GetDrawScene(); if (!drawScene.DrawRenderTag(delegate->GetRenderIndex().GetRenderTag(GetId()))) { _HideAllDrawItems(reprToken); - *dirtyBits &= ~( HdChangeTracker::DirtyRenderTag + *dirtyBits &= ~( + HdChangeTracker::DirtyRenderTag #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND - | HdChangeTracker::DirtyVisibility + | HdChangeTracker::DirtyVisibility #endif - ); + ); return; } - MProfilingScope profilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorC_L2, _rprimId.asChar(), "HdVP2BasisCurves::Sync"); + MProfilingScope profilingScope( + HdVP2RenderDelegate::sProfilerCategory, + MProfiler::kColorC_L2, + _rprimId.asChar(), + "HdVP2BasisCurves::Sync"); const SdfPath& id = GetId(); if (*dirtyBits & HdChangeTracker::DirtyMaterialId) { - _SetMaterialId(delegate->GetRenderIndex().GetChangeTracker(), - delegate->GetMaterialId(id)); + _SetMaterialId(delegate->GetRenderIndex().GetChangeTracker(), delegate->GetMaterialId(id)); } - if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->normals) || - HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->primvar)) { + if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->normals) + || HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->primvar)) { const HdVP2Material* material = static_cast( - delegate->GetRenderIndex().GetSprim( - HdPrimTypeTokens->material, GetMaterialId()) - ); + delegate->GetRenderIndex().GetSprim(HdPrimTypeTokens->material, GetMaterialId())); - const TfTokenVector& requiredPrimvars = - (material && material->GetSurfaceShader()) ? - material->GetRequiredPrimvars() : sFallbackShaderPrimvars; + const TfTokenVector& requiredPrimvars = (material && material->GetSurfaceShader()) + ? material->GetRequiredPrimvars() + : sFallbackShaderPrimvars; _UpdatePrimvarSources(delegate, *dirtyBits, requiredPrimvars); } @@ -611,8 +593,7 @@ void HdVP2BasisCurves::Sync( const size_t numControlPoints = topology.CalculateNeededNumberOfControlPoints(); if (!topology.HasIndices() && numVertices != numControlPoints) { - TF_WARN("Topology and vertices do not match for BasisCurve %s", - id.GetName().c_str()); + TF_WARN("Topology and vertices do not match for BasisCurve %s", id.GetName().c_str()); } void* bufferData = _curvesSharedData._positionsBuffer->acquire(numVertices, true); @@ -621,8 +602,8 @@ void HdVP2BasisCurves::Sync( memcpy(bufferData, _curvesSharedData._points.cdata(), numBytes); // Capture class member for lambda - MHWRender::MVertexBuffer* const positionsBuffer = - _curvesSharedData._positionsBuffer.get(); + MHWRender::MVertexBuffer* const positionsBuffer + = _curvesSharedData._positionsBuffer.get(); const MString& rprimId = _rprimId; _delegate->GetVP2ResourceRegistry().EnqueueCommit( @@ -634,8 +615,7 @@ void HdVP2BasisCurves::Sync( "CommitPositions"); positionsBuffer->commit(bufferData); - } - ); + }); } } @@ -651,11 +631,12 @@ void HdVP2BasisCurves::Sync( _sharedData.visible = delegate->GetVisible(id); } - if (*dirtyBits & (HdChangeTracker::DirtyRenderTag + if (*dirtyBits + & (HdChangeTracker::DirtyRenderTag #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND - |HdChangeTracker::DirtyVisibility + | HdChangeTracker::DirtyVisibility #endif - )) { + )) { _curvesSharedData._renderTag = delegate->GetRenderTag(id); } @@ -670,11 +651,10 @@ void HdVP2BasisCurves::Sync( This call happens on worker threads and results of the change are collected in CommitState and enqueued for Commit on main-thread using CommitTasks */ -void -HdVP2BasisCurves::_UpdateDrawItem( - HdSceneDelegate *sceneDelegate, - HdVP2DrawItem *drawItem, - HdBasisCurvesReprDesc const &desc) +void HdVP2BasisCurves::_UpdateDrawItem( + HdSceneDelegate* sceneDelegate, + HdVP2DrawItem* drawItem, + HdBasisCurvesReprDesc const& desc) { const MHWRender::MRenderItem* renderItem = drawItem->GetRenderItem(); if (ARCH_UNLIKELY(!renderItem)) { @@ -683,12 +663,12 @@ HdVP2BasisCurves::_UpdateDrawItem( const HdDirtyBits itemDirtyBits = drawItem->GetDirtyBits(); - CommitState stateToCommit(*drawItem); + CommitState stateToCommit(*drawItem); HdVP2DrawItem::RenderItemData& drawItemData = stateToCommit._drawItemData; const SdfPath& id = GetId(); - auto* const param = static_cast(_delegate->GetRenderParam()); + auto* const param = static_cast(_delegate->GetRenderParam()); ProxyRenderDelegate& drawScene = param->GetDrawScene(); const HdRenderIndex& renderIndex = sceneDelegate->GetRenderIndex(); @@ -696,9 +676,9 @@ HdVP2BasisCurves::_UpdateDrawItem( const auto& primvarSourceMap = _curvesSharedData._primvarSourceMap; const HdBasisCurvesTopology& topology = _curvesSharedData._topology; - const TfToken type = topology.GetCurveType(); - const TfToken wrap = topology.GetCurveWrap(); - const TfToken basis = topology.GetCurveBasis(); + const TfToken type = topology.GetCurveType(); + const TfToken wrap = topology.GetCurveWrap(); + const TfToken basis = topology.GetCurveBasis(); #if defined(HDVP2_ENABLE_BASISCURVES_TESSELLATION) const int refineLevel = _curvesSharedData._displayStyle.refineLevel; @@ -718,48 +698,43 @@ HdVP2BasisCurves::_UpdateDrawItem( // Prepare index buffer. if (requiresIndexUpdate && (itemDirtyBits & HdChangeTracker::DirtyTopology)) { - const bool forceLines = - (refineLevel <= 0) || (drawMode == MHWRender::MGeometry::kWireframe); + const bool forceLines + = (refineLevel <= 0) || (drawMode == MHWRender::MGeometry::kWireframe); VtValue result; if (!forceLines && type == HdTokens->cubic) { result = _BuildCubicIndexArray(topology); - } - else if (wrap == HdTokens->segmented) { + } else if (wrap == HdTokens->segmented) { result = _BuildLinesIndexArray(topology); - } - else { + } else { result = _BuildLineSegmentIndexArray(topology); } - const void* indexData = nullptr; + const void* indexData = nullptr; unsigned int numIndices = 0; if (result.IsHolding()) { indexData = result.UncheckedGet().cdata(); numIndices = result.GetArraySize() * 2; - } - else if (result.IsHolding()) { + } else if (result.IsHolding()) { indexData = result.UncheckedGet().cdata(); numIndices = result.GetArraySize() * 4; } if (drawItemData._indexBuffer && numIndices > 0) { - stateToCommit._indexBufferData = static_cast( - drawItemData._indexBuffer->acquire(numIndices, true)); + stateToCommit._indexBufferData + = static_cast(drawItemData._indexBuffer->acquire(numIndices, true)); if (indexData != nullptr && stateToCommit._indexBufferData != nullptr) { - memcpy(stateToCommit._indexBufferData, indexData, - numIndices * sizeof(int)); + memcpy(stateToCommit._indexBufferData, indexData, numIndices * sizeof(int)); } } } if (desc.geomStyle == HdBasisCurvesGeomStylePatch) { // Prepare normals buffer. - if (itemDirtyBits & - (HdChangeTracker::DirtyNormals | HdChangeTracker::DirtyDisplayStyle)) { + if (itemDirtyBits & (HdChangeTracker::DirtyNormals | HdChangeTracker::DirtyDisplayStyle)) { VtVec3fArray normals; const auto it = primvarSourceMap.find(HdTokens->normals); @@ -779,31 +754,30 @@ HdVP2BasisCurves::_UpdateDrawItem( normals = _BuildInterpolatedArray(topology, normals); if (!drawItemData._normalsBuffer) { - const MHWRender::MVertexBufferDescriptor vbDesc("", - MHWRender::MGeometry::kNormal, - MHWRender::MGeometry::kFloat, - 3); + const MHWRender::MVertexBufferDescriptor vbDesc( + "", MHWRender::MGeometry::kNormal, MHWRender::MGeometry::kFloat, 3); - drawItemData._normalsBuffer.reset( - new MHWRender::MVertexBuffer(vbDesc)); + drawItemData._normalsBuffer.reset(new MHWRender::MVertexBuffer(vbDesc)); } unsigned int numNormals = normals.size(); if (drawItemData._normalsBuffer && numNormals > 0) { - stateToCommit._normalsBufferData = - drawItemData._normalsBuffer->acquire(numNormals, true); + stateToCommit._normalsBufferData + = drawItemData._normalsBuffer->acquire(numNormals, true); if (stateToCommit._normalsBufferData != nullptr) { - memcpy(stateToCommit._normalsBufferData, normals.cdata(), + memcpy( + stateToCommit._normalsBufferData, + normals.cdata(), numNormals * sizeof(GfVec3f)); } } } // Prepare widths buffer. - if ((refineLevel > 0) && - (itemDirtyBits & (HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyDisplayStyle))) { + if ((refineLevel > 0) + && (itemDirtyBits + & (HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyDisplayStyle))) { VtFloatArray widths; const auto it = primvarSourceMap.find(HdTokens->widths); @@ -820,14 +794,12 @@ HdVP2BasisCurves::_UpdateDrawItem( widths = _BuildInterpolatedArray(topology, widths); - MHWRender::MVertexBuffer* widthsBuffer = - drawItemData._primvarBuffers[HdTokens->widths].get(); + MHWRender::MVertexBuffer* widthsBuffer + = drawItemData._primvarBuffers[HdTokens->widths].get(); if (!widthsBuffer) { - const MHWRender::MVertexBufferDescriptor vbDesc("", - MHWRender::MGeometry::kTexture, - MHWRender::MGeometry::kFloat, - 1); + const MHWRender::MVertexBufferDescriptor vbDesc( + "", MHWRender::MGeometry::kTexture, MHWRender::MGeometry::kFloat, 1); widthsBuffer = new MHWRender::MVertexBuffer(vbDesc); drawItemData._primvarBuffers[HdTokens->widths].reset(widthsBuffer); @@ -845,11 +817,9 @@ HdVP2BasisCurves::_UpdateDrawItem( } // Prepare color buffer. - if (itemDirtyBits & (HdChangeTracker::DirtyMaterialId | - DirtySelectionHighlight)) { + if (itemDirtyBits & (HdChangeTracker::DirtyMaterialId | DirtySelectionHighlight)) { const HdVP2Material* material = static_cast( - renderIndex.GetSprim(HdPrimTypeTokens->material, GetMaterialId()) - ); + renderIndex.GetSprim(HdPrimTypeTokens->material, GetMaterialId())); if (material) { MHWRender::MShaderInstance* shader = material->GetSurfaceShader(); @@ -860,10 +830,10 @@ HdVP2BasisCurves::_UpdateDrawItem( } auto primitiveType = MHWRender::MGeometry::kLines; - int primitiveStride = 0; + int primitiveStride = 0; - if (primitiveType != drawItemData._primitiveType || - primitiveStride != drawItemData._primitiveStride) { + if (primitiveType != drawItemData._primitiveType + || primitiveStride != drawItemData._primitiveStride) { drawItemData._primitiveType = primitiveType; stateToCommit._primitiveType = &drawItemData._primitiveType; @@ -874,9 +844,9 @@ HdVP2BasisCurves::_UpdateDrawItem( } } - if (itemDirtyBits & (HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyDisplayStyle | - DirtySelectionHighlight)) { + if (itemDirtyBits + & (HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyDisplayStyle + | DirtySelectionHighlight)) { VtVec3fArray colorArray; VtFloatArray alphaArray; @@ -973,23 +943,20 @@ HdVP2BasisCurves::_UpdateDrawItem( const size_t numVertices = std::min(numColors, numAlphas); if (numColors != numAlphas) { - TF_CODING_ERROR("color and opacity do not match for BasisCurve %s", - id.GetName().c_str()); + TF_CODING_ERROR( + "color and opacity do not match for BasisCurve %s", id.GetName().c_str()); } // Fill color and opacity into the float4 color stream. if (!drawItemData._colorBuffer) { - const MHWRender::MVertexBufferDescriptor vbDesc("", - MHWRender::MGeometry::kColor, - MHWRender::MGeometry::kFloat, - 4); + const MHWRender::MVertexBufferDescriptor vbDesc( + "", MHWRender::MGeometry::kColor, MHWRender::MGeometry::kFloat, 4); - drawItemData._colorBuffer.reset( - new MHWRender::MVertexBuffer(vbDesc)); + drawItemData._colorBuffer.reset(new MHWRender::MVertexBuffer(vbDesc)); } - float* bufferData = static_cast( - drawItemData._colorBuffer->acquire(numVertices, true)); + float* bufferData + = static_cast(drawItemData._colorBuffer->acquire(numVertices, true)); if (bufferData) { unsigned int offset = 0; @@ -1021,14 +988,14 @@ HdVP2BasisCurves::_UpdateDrawItem( bool boundingBoxExpanded = false; const GfVec3d& min = rangeToUse.GetMin(); - const MPoint pntMin(min[0], min[1], min[2]); + const MPoint pntMin(min[0], min[1], min[2]); if (!drawItemData._boundingBox.contains(pntMin)) { drawItemData._boundingBox.expand(pntMin); boundingBoxExpanded = true; } const GfVec3d& max = rangeToUse.GetMax(); - const MPoint pntMax(max[0], max[1], max[2]); + const MPoint pntMax(max[0], max[1], max[2]); if (!drawItemData._boundingBox.contains(pntMax)) { drawItemData._boundingBox.expand(pntMax); boundingBoxExpanded = true; @@ -1046,8 +1013,8 @@ HdVP2BasisCurves::_UpdateDrawItem( // The bounding box draw item uses a globally-shared unit wire cube as the // geometry and transfers scale and offset of the bounds to world matrix. if (isBoundingBoxItem) { - if ((itemDirtyBits & (HdChangeTracker::DirtyExtent | HdChangeTracker::DirtyTransform)) && - !range.IsEmpty()) { + if ((itemDirtyBits & (HdChangeTracker::DirtyExtent | HdChangeTracker::DirtyTransform)) + && !range.IsEmpty()) { const GfVec3d midpoint = range.GetMidpoint(); const GfVec3d size = range.GetSize(); @@ -1055,15 +1022,26 @@ HdVP2BasisCurves::_UpdateDrawItem( midp *= worldMatrix; auto& m = worldMatrix.matrix; - m[0][0] *= size[0]; m[0][1] *= size[0]; m[0][2] *= size[0]; m[0][3] *= size[0]; - m[1][0] *= size[1]; m[1][1] *= size[1]; m[1][2] *= size[1]; m[1][3] *= size[1]; - m[2][0] *= size[2]; m[2][1] *= size[2]; m[2][2] *= size[2]; m[2][3] *= size[2]; - m[3][0] = midp[0]; m[3][1] = midp[1]; m[3][2] = midp[2]; m[3][3] = midp[3]; + m[0][0] *= size[0]; + m[0][1] *= size[0]; + m[0][2] *= size[0]; + m[0][3] *= size[0]; + m[1][0] *= size[1]; + m[1][1] *= size[1]; + m[1][2] *= size[1]; + m[1][3] *= size[1]; + m[2][0] *= size[2]; + m[2][1] *= size[2]; + m[2][2] *= size[2]; + m[2][3] *= size[2]; + m[3][0] = midp[0]; + m[3][1] = midp[1]; + m[3][2] = midp[2]; + m[3][3] = midp[3]; stateToCommit._worldMatrix = &drawItemData._worldMatrix; } - } - else if (itemDirtyBits & HdChangeTracker::DirtyTransform) { + } else if (itemDirtyBits & HdChangeTracker::DirtyTransform) { stateToCommit._worldMatrix = &drawItemData._worldMatrix; } @@ -1077,17 +1055,16 @@ HdVP2BasisCurves::_UpdateDrawItem( if (!GetInstancerId().IsEmpty()) { // Retrieve instance transforms from the instancer. - HdInstancer *instancer = renderIndex.GetInstancer(GetInstancerId()); - VtMatrix4dArray transforms = static_cast(instancer)-> - ComputeInstanceTransforms(id); + HdInstancer* instancer = renderIndex.GetInstancer(GetInstancerId()); + VtMatrix4dArray transforms + = static_cast(instancer)->ComputeInstanceTransforms(id); - MMatrix instanceMatrix; + MMatrix instanceMatrix; const unsigned int instanceCount = transforms.size(); if (0 == instanceCount) { instancerWithNoInstances = true; - } - else { + } else { stateToCommit._instanceTransforms.setLength(instanceCount); for (unsigned int i = 0; i < instanceCount; ++i) { transforms[i].Get(instanceMatrix.matrix); @@ -1098,11 +1075,9 @@ HdVP2BasisCurves::_UpdateDrawItem( // it needs to display both wireframe color and selection highlight // with one color vertex buffer. if (drawItem->ContainsUsage(HdVP2DrawItem::kSelectionHighlight)) { - const MColor colors[] = { - drawScene.GetWireframeColor(), - drawScene.GetSelectionHighlightColor(false), - drawScene.GetSelectionHighlightColor(true) - }; + const MColor colors[] = { drawScene.GetWireframeColor(), + drawScene.GetSelectionHighlightColor(false), + drawScene.GetSelectionHighlightColor(true) }; // Store the indices to colors. std::vector colorIndices; @@ -1141,20 +1116,20 @@ HdVP2BasisCurves::_UpdateDrawItem( } } } - } - else { + } else { // Non-instanced Rprims. if (itemDirtyBits & (DirtySelectionHighlight | HdChangeTracker::DirtyDisplayStyle)) { - if (drawItem->ContainsUsage(HdVP2DrawItem::kRegular) && - drawItem->ContainsUsage(HdVP2DrawItem::kSelectionHighlight)) { + if (drawItem->ContainsUsage(HdVP2DrawItem::kRegular) + && drawItem->ContainsUsage(HdVP2DrawItem::kSelectionHighlight)) { MHWRender::MShaderInstance* shader = nullptr; auto primitiveType = MHWRender::MGeometry::kLines; - int primitiveStride = 0; + int primitiveStride = 0; - const MColor& color = (_selectionStatus != kUnselected ? - drawScene.GetSelectionHighlightColor(_selectionStatus == kFullyLead) : - drawScene.GetWireframeColor()); + const MColor& color + = (_selectionStatus != kUnselected + ? drawScene.GetSelectionHighlightColor(_selectionStatus == kFullyLead) + : drawScene.GetWireframeColor()); if (desc.geomStyle == HdBasisCurvesGeomStylePatch) { if (_selectionStatus != kUnselected) { @@ -1166,8 +1141,7 @@ HdVP2BasisCurves::_UpdateDrawItem( primitiveStride = (type == HdTokens->linear ? 2 : 4); } } - } - else { + } else { shader = _delegate->Get3dSolidShader(color); } @@ -1176,8 +1150,8 @@ HdVP2BasisCurves::_UpdateDrawItem( stateToCommit._shader = shader; stateToCommit._isTransparent = false; - if (primitiveType != drawItemData._primitiveType || - primitiveStride != drawItemData._primitiveStride) { + if (primitiveType != drawItemData._primitiveType + || primitiveStride != drawItemData._primitiveStride) { drawItemData._primitiveType = primitiveType; stateToCommit._primitiveType = &drawItemData._primitiveType; @@ -1190,13 +1164,13 @@ HdVP2BasisCurves::_UpdateDrawItem( } // Determine if the render item should be enabled or not. - if (!GetInstancerId().IsEmpty() || - (itemDirtyBits & (HdChangeTracker::DirtyVisibility | - HdChangeTracker::DirtyRenderTag | - HdChangeTracker::DirtyPoints | - HdChangeTracker::DirtyExtent | - DirtySelectionHighlight))) { - bool enable = drawItem->GetVisible() && !_curvesSharedData._points.empty() && !instancerWithNoInstances; + if (!GetInstancerId().IsEmpty() + || (itemDirtyBits + & (HdChangeTracker::DirtyVisibility | HdChangeTracker::DirtyRenderTag + | HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyExtent + | DirtySelectionHighlight))) { + bool enable = drawItem->GetVisible() && !_curvesSharedData._points.empty() + && !instancerWithNoInstances; if (isPointSnappingItem) { enable = enable && (_selectionStatus == kUnselected); @@ -1212,37 +1186,39 @@ HdVP2BasisCurves::_UpdateDrawItem( } } - stateToCommit._geometryDirty = (itemDirtyBits & ( - HdChangeTracker::DirtyPoints | - HdChangeTracker::DirtyNormals | - HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyTopology | - DirtySelectionHighlight)); + stateToCommit._geometryDirty + = (itemDirtyBits + & (HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyNormals + | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyTopology + | DirtySelectionHighlight)); // Reset dirty bits because we've prepared commit state for this draw item. drawItem->ResetDirtyBits(); // Capture the valid position buffer and index buffer MHWRender::MVertexBuffer* positionsBuffer = _curvesSharedData._positionsBuffer.get(); - MHWRender::MIndexBuffer* indexBuffer = drawItemData._indexBuffer.get(); + MHWRender::MIndexBuffer* indexBuffer = drawItemData._indexBuffer.get(); if (isBoundingBoxItem) { const HdVP2BBoxGeom& sharedBBoxGeom = _delegate->GetSharedBBoxGeom(); - positionsBuffer = const_cast( - sharedBBoxGeom.GetPositionBuffer()); - indexBuffer = const_cast( - sharedBBoxGeom.GetIndexBuffer()); + positionsBuffer = const_cast(sharedBBoxGeom.GetPositionBuffer()); + indexBuffer = const_cast(sharedBBoxGeom.GetIndexBuffer()); } - _delegate->GetVP2ResourceRegistry().EnqueueCommit( - [drawItem, stateToCommit, param, positionsBuffer, indexBuffer]() - { + _delegate->GetVP2ResourceRegistry().EnqueueCommit([drawItem, + stateToCommit, + param, + positionsBuffer, + indexBuffer]() { MHWRender::MRenderItem* renderItem = drawItem->GetRenderItem(); if (ARCH_UNLIKELY(!renderItem)) return; - MProfilingScope profilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorC_L2, drawItem->GetRenderItemName().asChar(), "Commit"); + MProfilingScope profilingScope( + HdVP2RenderDelegate::sProfilerCategory, + MProfiler::kColorC_L2, + drawItem->GetRenderItemName().asChar(), + "Commit"); const HdVP2DrawItem::RenderItemData& drawItemData = stateToCommit._drawItemData; @@ -1262,7 +1238,7 @@ HdVP2BasisCurves::_UpdateDrawItem( // If available, something changed for (const auto& entry : stateToCommit._primvarBufferDataMap) { const TfToken& primvarName = entry.first; - void* primvarBufferData = entry.second; + void* primvarBufferData = entry.second; if (primvarBufferData) { const auto it = primvarBuffers.find(primvarName); if (it != primvarBuffers.end()) { @@ -1291,15 +1267,13 @@ HdVP2BasisCurves::_UpdateDrawItem( #if defined(HDVP2_ENABLE_BASISCURVES_TESSELLATION) // If the primitive type and stride are changed, then update them. - if (stateToCommit._primitiveType != nullptr && - stateToCommit._primitiveStride != nullptr) { + if (stateToCommit._primitiveType != nullptr && stateToCommit._primitiveStride != nullptr) { auto primitive = *stateToCommit._primitiveType; - int stride = *stateToCommit._primitiveStride; + int stride = *stateToCommit._primitiveStride; renderItem->setPrimitive(primitive, stride); - const bool wantConsolidation = - !stateToCommit._drawItemData._usingInstancedDraw && - primitive != MHWRender::MGeometry::kPatch; + const bool wantConsolidation = !stateToCommit._drawItemData._usingInstancedDraw + && primitive != MHWRender::MGeometry::kPatch; setWantConsolidation(*renderItem, wantConsolidation); } #endif @@ -1317,7 +1291,7 @@ HdVP2BasisCurves::_UpdateDrawItem( vertexBuffers.addBuffer(kNormalsStr, normalsBuffer); for (auto& entry : primvarBuffers) { - const TfToken& primvarName = entry.first; + const TfToken& primvarName = entry.first; MHWRender::MVertexBuffer* primvarBuffer = entry.second.get(); if (primvarBuffer) { vertexBuffers.addBuffer(primvarName.GetText(), primvarBuffer); @@ -1328,13 +1302,13 @@ HdVP2BasisCurves::_UpdateDrawItem( // - Associate geometric buffers with the render item. // - Update bounding box. // - Trigger consolidation/instancing update. - drawScene.setGeometryForRenderItem(*renderItem, - vertexBuffers, *indexBuffer, stateToCommit._boundingBox); + drawScene.setGeometryForRenderItem( + *renderItem, vertexBuffers, *indexBuffer, stateToCommit._boundingBox); } // Important, update instance transforms after setting geometry on render items! auto& oldInstanceCount = stateToCommit._drawItemData._instanceCount; - auto newInstanceCount = stateToCommit._instanceTransforms.length(); + auto newInstanceCount = stateToCommit._instanceTransforms.length(); // GPU instancing has been enabled. We cannot switch to consolidation // without recreating render item, so we keep using GPU instancing. @@ -1342,18 +1316,16 @@ HdVP2BasisCurves::_UpdateDrawItem( if (oldInstanceCount == newInstanceCount) { for (unsigned int i = 0; i < newInstanceCount; i++) { // VP2 defines instance ID of the first instance to be 1. - drawScene.updateInstanceTransform(*renderItem, - i+1, stateToCommit._instanceTransforms[i]); + drawScene.updateInstanceTransform( + *renderItem, i + 1, stateToCommit._instanceTransforms[i]); } } else { - drawScene.setInstanceTransformArray(*renderItem, - stateToCommit._instanceTransforms); + drawScene.setInstanceTransformArray(*renderItem, stateToCommit._instanceTransforms); } - if (stateToCommit._instanceColors.length() == - newInstanceCount * kNumColorChannels) { - drawScene.setExtraInstanceData(*renderItem, - kSolidColorStr, stateToCommit._instanceColors); + if (stateToCommit._instanceColors.length() == newInstanceCount * kNumColorChannels) { + drawScene.setExtraInstanceData( + *renderItem, kSolidColorStr, stateToCommit._instanceColors); } } #if MAYA_API_VERSION >= 20210000 @@ -1365,22 +1337,18 @@ HdVP2BasisCurves::_UpdateDrawItem( // instances, we need to disable consolidation to allow GPU instancing to be used. else if (newInstanceCount == 1) { renderItem->setMatrix(&stateToCommit._instanceTransforms[0]); - } - else if (newInstanceCount > 1) { + } else if (newInstanceCount > 1) { setWantConsolidation(*renderItem, false); #endif - drawScene.setInstanceTransformArray(*renderItem, - stateToCommit._instanceTransforms); + drawScene.setInstanceTransformArray(*renderItem, stateToCommit._instanceTransforms); - if (stateToCommit._instanceColors.length() == - newInstanceCount * kNumColorChannels) { - drawScene.setExtraInstanceData(*renderItem, - kSolidColorStr, stateToCommit._instanceColors); + if (stateToCommit._instanceColors.length() == newInstanceCount * kNumColorChannels) { + drawScene.setExtraInstanceData( + *renderItem, kSolidColorStr, stateToCommit._instanceColors); } stateToCommit._drawItemData._usingInstancedDraw = true; - } - else if (stateToCommit._worldMatrix != nullptr) { + } else if (stateToCommit._worldMatrix != nullptr) { // Regular non-instanced prims. Consolidation has been turned on by // default and will be kept enabled on this case. renderItem->setMatrix(stateToCommit._worldMatrix); @@ -1408,14 +1376,13 @@ HdDirtyBits HdVP2BasisCurves::_PropagateDirtyBits(HdDirtyBits bits) const // Propagate dirty bits to all draw items. for (const std::pair& pair : _reprs) { const HdReprSharedPtr& repr = pair.second; - const auto& items = repr->GetDrawItems(); + const auto& items = repr->GetDrawItems(); #if HD_API_VERSION < 35 for (HdDrawItem* item : items) { if (HdVP2DrawItem* drawItem = static_cast(item)) { #else - for (const HdRepr::DrawItemUniquePtr &item : items) { - if (HdVP2DrawItem * const drawItem = - static_cast(item.get())) { + for (const HdRepr::DrawItemUniquePtr& item : items) { + if (HdVP2DrawItem* const drawItem = static_cast(item.get())) { #endif drawItem->SetDirtyBits(bits); } @@ -1442,9 +1409,9 @@ HdDirtyBits HdVP2BasisCurves::_PropagateDirtyBits(HdDirtyBits bits) const See HdRprim::InitRepr() */ -void HdVP2BasisCurves::_InitRepr(TfToken const &reprToken, HdDirtyBits *dirtyBits) +void HdVP2BasisCurves::_InitRepr(TfToken const& reprToken, HdDirtyBits* dirtyBits) { - auto* const param = static_cast(_delegate->GetRenderParam()); + auto* const param = static_cast(_delegate->GetRenderParam()); MSubSceneContainer* subSceneContainer = param->GetContainer(); if (ARCH_UNLIKELY(!subSceneContainer)) return; @@ -1452,13 +1419,12 @@ void HdVP2BasisCurves::_InitRepr(TfToken const &reprToken, HdDirtyBits *dirtyBit // Update selection state on demand or when it is a new Rprim. DirtySelection // will be propagated to all draw items, to trigger sync for each repr. if (reprToken == HdVP2ReprTokens->selection || _reprs.empty()) { - const HdVP2SelectionStatus selectionStatus = - param->GetDrawScene().GetSelectionStatus(GetId()); + const HdVP2SelectionStatus selectionStatus + = param->GetDrawScene().GetSelectionStatus(GetId()); if (_selectionStatus != selectionStatus) { _selectionStatus = selectionStatus; *dirtyBits |= DirtySelection; - } - else if (_selectionStatus == kPartiallySelected) { + } else if (_selectionStatus == kPartiallySelected) { *dirtyBits |= DirtySelection; } @@ -1470,18 +1436,17 @@ void HdVP2BasisCurves::_InitRepr(TfToken const &reprToken, HdDirtyBits *dirtyBit // If the repr has any draw item with the DirtySelection bit, mark the // DirtySelectionHighlight bit to invoke the synchronization call. - _ReprVector::iterator it = std::find_if( - _reprs.begin(), _reprs.end(), _ReprComparator(reprToken)); + _ReprVector::iterator it + = std::find_if(_reprs.begin(), _reprs.end(), _ReprComparator(reprToken)); if (it != _reprs.end()) { const HdReprSharedPtr& repr = it->second; - const auto& items = repr->GetDrawItems(); + const auto& items = repr->GetDrawItems(); #if HD_API_VERSION < 35 for (const HdDrawItem* item : items) { const HdVP2DrawItem* drawItem = static_cast(item); #else - for (const HdRepr::DrawItemUniquePtr &item : items) { - const HdVP2DrawItem * const drawItem = - static_cast(item.get()); + for (const HdRepr::DrawItemUniquePtr& item : items) { + const HdVP2DrawItem* const drawItem = static_cast(item.get()); #endif if (drawItem && (drawItem->GetDirtyBits() & DirtySelection)) { *dirtyBits |= DirtySelectionHighlight; @@ -1513,8 +1478,8 @@ void HdVP2BasisCurves::_InitRepr(TfToken const &reprToken, HdDirtyBits *dirtyBit #if HD_API_VERSION < 35 auto* drawItem = new HdVP2DrawItem(_delegate, &_sharedData); #else - std::unique_ptr drawItem = - std::make_unique(_delegate, &_sharedData); + std::unique_ptr drawItem + = std::make_unique(_delegate, &_sharedData); #endif const MString& renderItemName = drawItem->GetRenderItemName(); @@ -1541,9 +1506,7 @@ void HdVP2BasisCurves::_InitRepr(TfToken const &reprToken, HdDirtyBits *dirtyBit case HdBasisCurvesGeomStylePoints: renderItem = _CreatePointsRenderItem(renderItemName); break; - default: - TF_WARN("Unsupported geomStyle"); - break; + default: TF_WARN("Unsupported geomStyle"); break; } if (renderItem) { @@ -1552,10 +1515,7 @@ void HdVP2BasisCurves::_InitRepr(TfToken const &reprToken, HdDirtyBits *dirtyBit drawItem->SetRenderItem(renderItem); _delegate->GetVP2ResourceRegistry().EnqueueCommit( - [subSceneContainer, renderItem]() { - subSceneContainer->add(renderItem); - } - ); + [subSceneContainer, renderItem]() { subSceneContainer->add(renderItem); }); } #if HD_API_VERSION < 35 repr->AddDrawItem(drawItem); @@ -1570,24 +1530,22 @@ void HdVP2BasisCurves::_InitRepr(TfToken const &reprToken, HdDirtyBits *dirtyBit Repr objects are created to support specific reprName tokens, and contain a list of HdVP2DrawItems and corresponding RenderItems. */ -void HdVP2BasisCurves::_UpdateRepr( - HdSceneDelegate *sceneDelegate, - TfToken const &reprToken) +void HdVP2BasisCurves::_UpdateRepr(HdSceneDelegate* sceneDelegate, TfToken const& reprToken) { - HdReprSharedPtr const &repr = _GetRepr(reprToken); + HdReprSharedPtr const& repr = _GetRepr(reprToken); if (!repr) { return; } - const _BasisCurvesReprConfig::DescArray &descs = _GetReprDesc(reprToken); - const size_t numDescs = descs.size(); - int drawItemIndex = 0; + const _BasisCurvesReprConfig::DescArray& descs = _GetReprDesc(reprToken); + const size_t numDescs = descs.size(); + int drawItemIndex = 0; for (size_t i = 0; i < numDescs; ++i) { - const HdBasisCurvesReprDesc &desc = descs[i]; + const HdBasisCurvesReprDesc& desc = descs[i]; if (desc.geomStyle != HdBasisCurvesGeomStyleInvalid) { - HdVP2DrawItem *drawItem = static_cast( - repr->GetDrawItem(drawItemIndex++)); + HdVP2DrawItem* drawItem + = static_cast(repr->GetDrawItem(drawItemIndex++)); if (drawItem) { _UpdateDrawItem(sceneDelegate, drawItem, desc); } @@ -1600,29 +1558,21 @@ void HdVP2BasisCurves::_UpdateRepr( */ HdDirtyBits HdVP2BasisCurves::GetInitialDirtyBitsMask() const { - constexpr HdDirtyBits bits = - HdChangeTracker::InitRepr | - HdChangeTracker::DirtyExtent | - HdChangeTracker::DirtyInstanceIndex | - HdChangeTracker::DirtyNormals | - HdChangeTracker::DirtyPoints | - HdChangeTracker::DirtyPrimID | - HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyDisplayStyle | - HdChangeTracker::DirtyRepr | - HdChangeTracker::DirtyMaterialId | - HdChangeTracker::DirtyTopology | - HdChangeTracker::DirtyTransform | - HdChangeTracker::DirtyVisibility | - HdChangeTracker::DirtyWidths | - HdChangeTracker::DirtyComputationPrimvarDesc | - HdChangeTracker::DirtyRenderTag | - DirtySelectionHighlight; + constexpr HdDirtyBits bits = HdChangeTracker::InitRepr | HdChangeTracker::DirtyExtent + | HdChangeTracker::DirtyInstanceIndex | HdChangeTracker::DirtyNormals + | HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyPrimID + | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyDisplayStyle + | HdChangeTracker::DirtyRepr | HdChangeTracker::DirtyMaterialId + | HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyTransform + | HdChangeTracker::DirtyVisibility | HdChangeTracker::DirtyWidths + | HdChangeTracker::DirtyComputationPrimvarDesc | HdChangeTracker::DirtyRenderTag + | DirtySelectionHighlight; return bits; } -void HdVP2BasisCurves::_HideAllDrawItems(const TfToken& reprToken) { +void HdVP2BasisCurves::_HideAllDrawItems(const TfToken& reprToken) +{ HdReprSharedPtr const& curRepr = _GetRepr(reprToken); if (!curRepr) { return; @@ -1647,9 +1597,8 @@ void HdVP2BasisCurves::_HideAllDrawItems(const TfToken& reprToken) { drawItem->GetRenderItemData()._enabled = false; - _delegate->GetVP2ResourceRegistry().EnqueueCommit([renderItem]() { - renderItem->enable(false); - }); + _delegate->GetVP2ResourceRegistry().EnqueueCommit( + [renderItem]() { renderItem->enable(false); }); } } @@ -1662,8 +1611,8 @@ void HdVP2BasisCurves::_HideAllDrawItems(const TfToken& reprToken) { only call GetPrimvar on primvars that have been marked dirty. */ void HdVP2BasisCurves::_UpdatePrimvarSources( - HdSceneDelegate* sceneDelegate, - HdDirtyBits dirtyBits, + HdSceneDelegate* sceneDelegate, + HdDirtyBits dirtyBits, const TfTokenVector& requiredPrimvars) { const SdfPath& id = GetId(); @@ -1674,14 +1623,12 @@ void HdVP2BasisCurves::_UpdatePrimvarSources( for (size_t i = 0; i < HdInterpolationCount; i++) { const HdInterpolation interp = static_cast(i); - const HdPrimvarDescriptorVector primvars = - GetPrimvarDescriptors(sceneDelegate, interp); + const HdPrimvarDescriptorVector primvars = GetPrimvarDescriptors(sceneDelegate, interp); - for (const HdPrimvarDescriptor& pv: primvars) { + for (const HdPrimvarDescriptor& pv : primvars) { if (std::find(begin, end, pv.name) == end) { _curvesSharedData._primvarSourceMap.erase(pv.name); - } - else if (HdChangeTracker::IsPrimvarDirty(dirtyBits, id, pv.name)) { + } else if (HdChangeTracker::IsPrimvarDirty(dirtyBits, id, pv.name)) { const VtValue value = GetPrimvar(sceneDelegate, pv.name); _curvesSharedData._primvarSourceMap[pv.name] = { value, interp }; } @@ -1690,15 +1637,11 @@ void HdVP2BasisCurves::_UpdatePrimvarSources( } /*! \brief Create render item for wireframe repr. -*/ -MHWRender::MRenderItem* -HdVP2BasisCurves::_CreateWireRenderItem(const MString& name) const + */ +MHWRender::MRenderItem* HdVP2BasisCurves::_CreateWireRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( - name, - MHWRender::MRenderItem::DecorationItem, - MHWRender::MGeometry::kLines - ); + name, MHWRender::MRenderItem::DecorationItem, MHWRender::MGeometry::kLines); renderItem->setDrawMode(MHWRender::MGeometry::kWireframe); renderItem->depthPriority(MHWRender::MRenderItem::sDormantWireDepthPriority); @@ -1713,15 +1656,11 @@ HdVP2BasisCurves::_CreateWireRenderItem(const MString& name) const } /*! \brief Create render item for bbox repr. -*/ -MHWRender::MRenderItem* -HdVP2BasisCurves::_CreateBBoxRenderItem(const MString& name) const + */ +MHWRender::MRenderItem* HdVP2BasisCurves::_CreateBBoxRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( - name, - MHWRender::MRenderItem::DecorationItem, - MHWRender::MGeometry::kLines - ); + name, MHWRender::MRenderItem::DecorationItem, MHWRender::MGeometry::kLines); renderItem->setDrawMode(MHWRender::MGeometry::kBoundingBox); renderItem->castsShadows(false); @@ -1735,15 +1674,11 @@ HdVP2BasisCurves::_CreateBBoxRenderItem(const MString& name) const } /*! \brief Create render item for smoothHull repr. -*/ -MHWRender::MRenderItem* -HdVP2BasisCurves::_CreatePatchRenderItem(const MString& name) const + */ +MHWRender::MRenderItem* HdVP2BasisCurves::_CreatePatchRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( - name, - MHWRender::MRenderItem::MaterialSceneItem, - MHWRender::MGeometry::kLines - ); + name, MHWRender::MRenderItem::MaterialSceneItem, MHWRender::MGeometry::kLines); renderItem->setDrawMode(static_cast( MHWRender::MGeometry::kShaded | MHWRender::MGeometry::kTextured)); @@ -1758,15 +1693,11 @@ HdVP2BasisCurves::_CreatePatchRenderItem(const MString& name) const } /*! \brief Create render item for points repr. -*/ -MHWRender::MRenderItem* -HdVP2BasisCurves::_CreatePointsRenderItem(const MString& name) const + */ +MHWRender::MRenderItem* HdVP2BasisCurves::_CreatePointsRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( - name, - MHWRender::MRenderItem::DecorationItem, - MHWRender::MGeometry::kPoints - ); + name, MHWRender::MRenderItem::DecorationItem, MHWRender::MGeometry::kPoints); renderItem->setDrawMode(MHWRender::MGeometry::kSelectionOnly); renderItem->castsShadows(false); diff --git a/lib/mayaUsd/render/vp2RenderDelegate/basisCurves.h b/lib/mayaUsd/render/vp2RenderDelegate/basisCurves.h index a01e13f338..af233d4af1 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/basisCurves.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/basisCurves.h @@ -16,17 +16,17 @@ #ifndef HDVP2_BASIS_CURVES_H #define HDVP2_BASIS_CURVES_H -#include - -#include +#include -#include #include #include #include +#include #include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE @@ -51,8 +51,9 @@ struct HdVP2BasisCurvesSharedData //! A local cache of primvar scene data. "data" is a copy-on-write handle to //! the actual primvar buffer, and "interpolation" is the interpolation mode //! to be used. - struct PrimvarSource { - VtValue data; + struct PrimvarSource + { + VtValue data; HdInterpolation interpolation; }; TfHashMap _primvarSourceMap; @@ -85,59 +86,63 @@ struct HdVP2BasisCurvesSharedData in HdVP2RenderDelegate::CommitResources(), which runs on main-thread after all Rprims have been updated. */ -class HdVP2BasisCurves final: public HdBasisCurves +class HdVP2BasisCurves final : public HdBasisCurves { public: HdVP2BasisCurves( - HdVP2RenderDelegate *delegate, - const SdfPath &id, - const SdfPath &instancerId = SdfPath()); + HdVP2RenderDelegate* delegate, + const SdfPath& id, + const SdfPath& instancerId = SdfPath()); //! Destructor. ~HdVP2BasisCurves() override = default; - void Sync(HdSceneDelegate *delegate, - HdRenderParam *renderParam, - HdDirtyBits *dirtyBits, - TfToken const &reprToken) override; + void Sync( + HdSceneDelegate* delegate, + HdRenderParam* renderParam, + HdDirtyBits* dirtyBits, + TfToken const& reprToken) override; HdDirtyBits GetInitialDirtyBitsMask() const override; protected: HdDirtyBits _PropagateDirtyBits(HdDirtyBits bits) const override; - void _InitRepr(TfToken const &reprToken, HdDirtyBits *dirtyBits) override; + void _InitRepr(TfToken const& reprToken, HdDirtyBits* dirtyBits) override; private: - void _UpdateRepr(HdSceneDelegate *sceneDelegate, - TfToken const &reprToken); + void _UpdateRepr(HdSceneDelegate* sceneDelegate, TfToken const& reprToken); - void _UpdateDrawItem(HdSceneDelegate *sceneDelegate, - HdVP2DrawItem *drawItem, - HdBasisCurvesReprDesc const &desc); + void _UpdateDrawItem( + HdSceneDelegate* sceneDelegate, + HdVP2DrawItem* drawItem, + HdBasisCurvesReprDesc const& desc); void _HideAllDrawItems(const TfToken& reprToken); void _UpdatePrimvarSources( - HdSceneDelegate *sceneDelegate, - HdDirtyBits dirtyBits, - TfTokenVector const &requiredPrimvars); + HdSceneDelegate* sceneDelegate, + HdDirtyBits dirtyBits, + TfTokenVector const& requiredPrimvars); MHWRender::MRenderItem* _CreatePatchRenderItem(const MString& name) const; MHWRender::MRenderItem* _CreateWireRenderItem(const MString& name) const; MHWRender::MRenderItem* _CreateBBoxRenderItem(const MString& name) const; MHWRender::MRenderItem* _CreatePointsRenderItem(const MString& name) const; - enum DirtyBits : HdDirtyBits { - DirtySelection = HdChangeTracker::CustomBitsBegin, - DirtySelectionHighlight = (DirtySelection << 1) + enum DirtyBits : HdDirtyBits + { + DirtySelection = HdChangeTracker::CustomBitsBegin, + DirtySelectionHighlight = (DirtySelection << 1) }; - HdVP2RenderDelegate* _delegate { nullptr }; //!< VP2 render delegate for which this mesh was created - const MString _rprimId; //!< Rprim id cached as a maya string for easier debugging and profiling + HdVP2RenderDelegate* _delegate { + nullptr + }; //!< VP2 render delegate for which this mesh was created + const MString _rprimId; //!< Rprim id cached as a maya string for easier debugging and profiling //! Shared data for all draw items of the Rprim - HdVP2BasisCurvesSharedData _curvesSharedData; + HdVP2BasisCurvesSharedData _curvesSharedData; //! Selection status of the Rprim HdVP2SelectionStatus _selectionStatus { kUnselected }; diff --git a/lib/mayaUsd/render/vp2RenderDelegate/bboxGeom.cpp b/lib/mayaUsd/render/vp2RenderDelegate/bboxGeom.cpp index e38dae004a..39c397ab6d 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/bboxGeom.cpp +++ b/lib/mayaUsd/render/vp2RenderDelegate/bboxGeom.cpp @@ -22,56 +22,55 @@ PXR_NAMESPACE_OPEN_SCOPE //! Constructor. Call from main thread only. HdVP2BBoxGeom::HdVP2BBoxGeom() -: _range(GfVec3d(-0.5, -0.5, -0.5), GfVec3d(0.5, 0.5, 0.5)) + : _range(GfVec3d(-0.5, -0.5, -0.5), GfVec3d(0.5, 0.5, 0.5)) { - // MVertexBuffer::commit() & MIndexBuffer::commit() can work only when being - // called from main thread. - TF_VERIFY(ArchIsMainThread(), "Creating HdVP2BBoxGeom from worker threads"); + // MVertexBuffer::commit() & MIndexBuffer::commit() can work only when being + // called from main thread. + TF_VERIFY(ArchIsMainThread(), "Creating HdVP2BBoxGeom from worker threads"); - const MHWRender::MVertexBufferDescriptor vbDesc( - "", MGeometry::kPosition, MGeometry::kFloat, 3); + const MHWRender::MVertexBufferDescriptor vbDesc("", MGeometry::kPosition, MGeometry::kFloat, 3); - _positionBuffer.reset(new MHWRender::MVertexBuffer(vbDesc)); + _positionBuffer.reset(new MHWRender::MVertexBuffer(vbDesc)); - if (void* buffer = _positionBuffer->acquire(8, true)) { - constexpr float vertexData[] = { - -0.5f, -0.5f, -0.5f, // vtx 0 - -0.5f, -0.5f, 0.5f, // vtx 1 - -0.5f, 0.5f, -0.5f, // vtx 2 - -0.5f, 0.5f, 0.5f, // vtx 3 - 0.5f, -0.5f, -0.5f, // vtx 4 - 0.5f, -0.5f, 0.5f, // vtx 5 - 0.5f, 0.5f, -0.5f, // vtx 6 - 0.5f, 0.5f, 0.5f // vtx 7 - }; + if (void* buffer = _positionBuffer->acquire(8, true)) { + constexpr float vertexData[] = { + -0.5f, -0.5f, -0.5f, // vtx 0 + -0.5f, -0.5f, 0.5f, // vtx 1 + -0.5f, 0.5f, -0.5f, // vtx 2 + -0.5f, 0.5f, 0.5f, // vtx 3 + 0.5f, -0.5f, -0.5f, // vtx 4 + 0.5f, -0.5f, 0.5f, // vtx 5 + 0.5f, 0.5f, -0.5f, // vtx 6 + 0.5f, 0.5f, 0.5f // vtx 7 + }; - memcpy(buffer, vertexData, sizeof(vertexData)); + memcpy(buffer, vertexData, sizeof(vertexData)); - _positionBuffer->commit(buffer); - } + _positionBuffer->commit(buffer); + } - _indexBuffer.reset(new MHWRender::MIndexBuffer(MGeometry::kUnsignedInt32)); + _indexBuffer.reset(new MHWRender::MIndexBuffer(MGeometry::kUnsignedInt32)); - if (void* buffer = _indexBuffer->acquire(24, true)) { - constexpr unsigned int indexData[] = { - 0, 4, // edge 0 - 1, 5, // edge 1 - 2, 6, // edge 2 - 3, 7, // edge 3 - 0, 2, // edge 4 - 1, 3, // edge 5 - 4, 6, // edge 6 - 5, 7, // edge 7 - 0, 1, // edge 8 - 2, 3, // edge 9 - 4, 5, // edge 10 - 6, 7 // edge 11 - }; + if (void* buffer = _indexBuffer->acquire(24, true)) { + constexpr unsigned int indexData[] = { + 0, 4, // edge 0 + 1, 5, // edge 1 + 2, 6, // edge 2 + 3, 7, // edge 3 + 0, 2, // edge 4 + 1, 3, // edge 5 + 4, 6, // edge 6 + 5, 7, // edge 7 + 0, 1, // edge 8 + 2, 3, // edge 9 + 4, 5, // edge 10 + 6, 7 // edge 11 + }; - memcpy(buffer, indexData, sizeof(indexData)); + memcpy(buffer, indexData, sizeof(indexData)); - _indexBuffer->commit(buffer); - } + _indexBuffer->commit(buffer); + } } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/bboxGeom.h b/lib/mayaUsd/render/vp2RenderDelegate/bboxGeom.h index 74ef0efcf3..99d8b21a4c 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/bboxGeom.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/bboxGeom.h @@ -16,13 +16,13 @@ #ifndef HD_VP2_BBOX_GEOM #define HD_VP2_BBOX_GEOM +#include +#include + #include #include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE /*! \brief Geometry used for bounding box display in VP2. @@ -38,13 +38,9 @@ class HdVP2BBoxGeom final HdVP2BBoxGeom(); ~HdVP2BBoxGeom() = default; - const MHWRender::MVertexBuffer* GetPositionBuffer() const { - return _positionBuffer.get(); - } + const MHWRender::MVertexBuffer* GetPositionBuffer() const { return _positionBuffer.get(); } - const MHWRender::MIndexBuffer* GetIndexBuffer() const { - return _indexBuffer.get(); - } + const MHWRender::MIndexBuffer* GetIndexBuffer() const { return _indexBuffer.get(); } const GfRange3d& GetRange() const { return _range; } diff --git a/lib/mayaUsd/render/vp2RenderDelegate/debugCodes.h b/lib/mayaUsd/render/vp2RenderDelegate/debugCodes.h index 029c910adf..04f618a752 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/debugCodes.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/debugCodes.h @@ -16,16 +16,12 @@ #ifndef HD_VP2_DEBUGCODES_H #define HD_VP2_DEBUGCODES_H -#include - #include +#include PXR_NAMESPACE_OPEN_SCOPE -TF_DEBUG_CODES( - HDVP2_DEBUG_MATERIAL, - HDVP2_DEBUG_MESH -); +TF_DEBUG_CODES(HDVP2_DEBUG_MATERIAL, HDVP2_DEBUG_MESH); PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/draw_item.cpp b/lib/mayaUsd/render/vp2RenderDelegate/draw_item.cpp index 918fd7195e..f974432342 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/draw_item.cpp +++ b/lib/mayaUsd/render/vp2RenderDelegate/draw_item.cpp @@ -15,21 +15,19 @@ // #include "draw_item.h" -#include - #include "render_delegate.h" +#include + PXR_NAMESPACE_OPEN_SCOPE /*! \brief Constructor. Data holder for its corresponding render item to facilitate parallelized evaluation. */ -HdVP2DrawItem::HdVP2DrawItem( - HdVP2RenderDelegate* delegate, - const HdRprimSharedData* sharedData) -: HdDrawItem(sharedData) -, _delegate(delegate) +HdVP2DrawItem::HdVP2DrawItem(HdVP2RenderDelegate* delegate, const HdRprimSharedData* sharedData) + : HdDrawItem(sharedData) + , _delegate(delegate) { // In the case of instancing, the ID of a proto has an attribute at the end, // we keep this info in _renderItemName so if needed we can extract proto ID @@ -37,7 +35,7 @@ HdVP2DrawItem::HdVP2DrawItem( // // "/Proxy/TreePatch/Tree_1.proto_leaves_id0" // - _renderItemName = GetRprimID().GetText(); + _renderItemName = GetRprimID().GetText(); _renderItemName += TfStringPrintf("/DrawItem_%p", this).c_str(); _renderItemData._indexBuffer.reset( @@ -45,11 +43,12 @@ HdVP2DrawItem::HdVP2DrawItem( } //! \brief Destructor. -HdVP2DrawItem::~HdVP2DrawItem() { +HdVP2DrawItem::~HdVP2DrawItem() +{ if (_delegate) { - auto* const param = static_cast(_delegate->GetRenderParam()); + auto* const param = static_cast(_delegate->GetRenderParam()); MSubSceneContainer* subSceneContainer = param ? param->GetContainer() : nullptr; - if(subSceneContainer) { + if (subSceneContainer) { subSceneContainer->remove(GetRenderItemName()); } } diff --git a/lib/mayaUsd/render/vp2RenderDelegate/draw_item.h b/lib/mayaUsd/render/vp2RenderDelegate/draw_item.h index f9196bd8fc..3f922c873b 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/draw_item.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/draw_item.h @@ -16,18 +16,18 @@ #ifndef HD_VP2_DRAW_ITEM #define HD_VP2_DRAW_ITEM -#include -#include -#include -#include - -#include #include #include #include #include +#include #include +#include +#include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE class HdVP2RenderDelegate; @@ -39,51 +39,49 @@ class HdVP2DrawItem final : public HdDrawItem { public: //! A primvar vertex buffer map indexed by primvar name. - using PrimvarBufferMap = std::unordered_map< - TfToken, - std::unique_ptr, - TfToken::HashFunctor - >; + using PrimvarBufferMap = std:: + unordered_map, TfToken::HashFunctor>; //! Helper struct providing storage for render item data - struct RenderItemData { + struct RenderItemData + { //! Render item color buffer - use when updating data - std::unique_ptr _colorBuffer; + std::unique_ptr _colorBuffer; //! Render item normals buffer - use when updating data - std::unique_ptr _normalsBuffer; + std::unique_ptr _normalsBuffer; //! Render item primvar buffers - use when updating data - PrimvarBufferMap _primvarBuffers; + PrimvarBufferMap _primvarBuffers; //! Render item index buffer - use when updating data - std::unique_ptr _indexBuffer; + std::unique_ptr _indexBuffer; //! Bounding box of the render item. - MBoundingBox _boundingBox; + MBoundingBox _boundingBox; //! World matrix of the render item. - MMatrix _worldMatrix; + MMatrix _worldMatrix; //! Shader instance assigned to the render item. No ownership is held. - MHWRender::MShaderInstance* _shader{ nullptr }; + MHWRender::MShaderInstance* _shader { nullptr }; //! Whether or not the render item is enabled - bool _enabled{ true }; + bool _enabled { true }; //! Primitive type of the render item - MHWRender::MGeometry::Primitive _primitiveType{ MHWRender::MGeometry::kInvalidPrimitive }; + MHWRender::MGeometry::Primitive _primitiveType { MHWRender::MGeometry::kInvalidPrimitive }; //! Primitive stride of the render item (valid only if the primitive type is kPatch) - int _primitiveStride{ 0 }; + int _primitiveStride { 0 }; //! Number of instances currently allocated for render item - unsigned int _instanceCount{ 0 }; + unsigned int _instanceCount { 0 }; //! Whether or not the render item is using GPU instanced draw. - bool _usingInstancedDraw{ false }; + bool _usingInstancedDraw { false }; }; //! Bit fields indicating what the render item is created for. A render item //! can be created for multiple usages. enum RenderItemUsage { - kRegular = 1 << 0, //!< Regular drawing (shaded, wireframe etc.) - kSelectionHighlight = 1 << 1 //!< Selection highlight. + kRegular = 1 << 0, //!< Regular drawing (shaded, wireframe etc.) + kSelectionHighlight = 1 << 1 //!< Selection highlight. }; public: @@ -92,64 +90,63 @@ class HdVP2DrawItem final : public HdDrawItem ~HdVP2DrawItem(); /*! \brief Get access to render item data. - */ + */ RenderItemData& GetRenderItemData() { return _renderItemData; } /*! \brief Get render item name - */ + */ const MString& GetRenderItemName() const { return _renderItemName; } /*! \brief Get pointer of the associated render item - */ + */ MHWRender::MRenderItem* GetRenderItem() const { return _renderItem; } /*! \brief Set pointer of the associated render item - */ + */ void SetRenderItem(MHWRender::MRenderItem* item) { _renderItem = item; } /*! \brief Set a usage to the render item - */ + */ void SetUsage(RenderItemUsage usage) { _renderItemUsage = usage; } /*! \brief Add a usage to the render item - */ + */ void AddUsage(RenderItemUsage usage) { _renderItemUsage |= usage; } /*! \brief Is the render item created for this usage? - */ + */ bool ContainsUsage(RenderItemUsage usage) const { return (_renderItemUsage & usage) != 0; } /*! \brief Is the render item created for this usage only? - */ + */ bool MatchesUsage(RenderItemUsage usage) const { return _renderItemUsage == usage; } /*! \brief Bitwise OR with the input dirty bits. - */ - void SetDirtyBits(HdDirtyBits bits) { - _dirtyBits |= bits; - } + */ + void SetDirtyBits(HdDirtyBits bits) { _dirtyBits |= bits; } /*! \brief Reset the dirty bits to clean. - */ - void ResetDirtyBits() { - _dirtyBits = 0; - } + */ + void ResetDirtyBits() { _dirtyBits = 0; } /*! \brief Get the dirty bits of the draw items. - */ - HdDirtyBits GetDirtyBits() const { - return _dirtyBits; - } + */ + HdDirtyBits GetDirtyBits() const { return _dirtyBits; } private: - - HdVP2RenderDelegate* _delegate{ nullptr }; //!< VP2 render delegate for which this draw item was created - MString _renderItemName; //!< Unique name for easier debugging and profiling. - MHWRender::MRenderItem* _renderItem{ nullptr }; //!< Pointer of the render item for fast access. No ownership is held. - RenderItemData _renderItemData; //!< VP2 render item data - - uint32_t _renderItemUsage{ kRegular }; //!< What is the render item created for - HdDirtyBits _dirtyBits{ HdChangeTracker::AllDirty }; //!< Dirty bits to control data update of render item + HdVP2RenderDelegate* _delegate { + nullptr + }; //!< VP2 render delegate for which this draw item was created + MString _renderItemName; //!< Unique name for easier debugging and profiling. + MHWRender::MRenderItem* _renderItem { + nullptr + }; //!< Pointer of the render item for fast access. No ownership is held. + RenderItemData _renderItemData; //!< VP2 render item data + + uint32_t _renderItemUsage { kRegular }; //!< What is the render item created for + HdDirtyBits _dirtyBits { + HdChangeTracker::AllDirty + }; //!< Dirty bits to control data update of render item }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/instancer.cpp b/lib/mayaUsd/render/vp2RenderDelegate/instancer.cpp index c4b4b84e6f..9c6d5f96a5 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/instancer.cpp +++ b/lib/mayaUsd/render/vp2RenderDelegate/instancer.cpp @@ -19,6 +19,8 @@ #include "instancer.h" +#include "sampler.h" + #include #include #include @@ -27,20 +29,12 @@ #include #include -#include "sampler.h" - PXR_NAMESPACE_OPEN_SCOPE // Define local tokens for the names of the primvars the instancer // consumes. // XXX: These should be hydra tokens... -TF_DEFINE_PRIVATE_TOKENS( - _tokens, - (instanceTransform) - (rotate) - (scale) - (translate) -); +TF_DEFINE_PRIVATE_TOKENS(_tokens, (instanceTransform)(rotate)(scale)(translate)); /*! \brief Constructor. @@ -49,29 +43,27 @@ TF_DEFINE_PRIVATE_TOKENS( \param parentId The unique id of the parent instancer, or an empty id if not applicable. */ -HdVP2Instancer::HdVP2Instancer(HdSceneDelegate* delegate, - SdfPath const& id, - SdfPath const &parentId) +HdVP2Instancer::HdVP2Instancer( + HdSceneDelegate* delegate, + SdfPath const& id, + SdfPath const& parentId) : HdInstancer(delegate, id, parentId) { } /*! \brief Destructor. -*/ + */ HdVP2Instancer::~HdVP2Instancer() { - TF_FOR_ALL(it, _primvarMap) { - delete it->second; - } + TF_FOR_ALL(it, _primvarMap) { delete it->second; } _primvarMap.clear(); } - /*! \brief Checks the change tracker to determine whether instance primvars are - dirty, and if so pulls them. - - Since primvars can only be pulled once, and are cached, this function is not - re-entrant. However, this function is called by ComputeInstanceTransforms, + dirty, and if so pulls them. + + Since primvars can only be pulled once, and are cached, this function is not + re-entrant. However, this function is called by ComputeInstanceTransforms, which is called by HdVP2Mesh::Sync(), which is dispatched in parallel, so it needs to be guarded by _instanceLock. */ @@ -80,9 +72,8 @@ void HdVP2Instancer::_SyncPrimvars() HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); - HdChangeTracker &changeTracker = - GetDelegate()->GetRenderIndex().GetChangeTracker(); - SdfPath const& id = GetId(); + HdChangeTracker& changeTracker = GetDelegate()->GetRenderIndex().GetChangeTracker(); + SdfPath const& id = GetId(); // Use the double-checked locking pattern to check if this instancer's // primvars are dirty. @@ -97,19 +88,18 @@ void HdVP2Instancer::_SyncPrimvars() // If this instancer has dirty primvars, get the list of // primvar names and then cache each one. - TfTokenVector primvarNames; - HdPrimvarDescriptorVector primvars = GetDelegate() - ->GetPrimvarDescriptors(id, HdInterpolationInstance); + TfTokenVector primvarNames; + HdPrimvarDescriptorVector primvars + = GetDelegate()->GetPrimvarDescriptors(id, HdInterpolationInstance); - for (HdPrimvarDescriptor const& pv: primvars) { + for (HdPrimvarDescriptor const& pv : primvars) { if (HdChangeTracker::IsPrimvarDirty(dirtyBits, id, pv.name)) { VtValue value = GetDelegate()->Get(id, pv.name); if (!value.IsEmpty()) { if (_primvarMap.count(pv.name) > 0) { delete _primvarMap[pv.name]; } - _primvarMap[pv.name] = - new HdVtBufferSource(pv.name, value); + _primvarMap[pv.name] = new HdVtBufferSource(pv.name, value); } } } @@ -127,10 +117,10 @@ void HdVP2Instancer::_SyncPrimvars() Computes and flattens nested transforms, if necessary. \param prototypeId The prototype to compute transforms for. - + \return One transform per instance, to apply when drawing. */ -VtMatrix4dArray HdVP2Instancer::ComputeInstanceTransforms(SdfPath const &prototypeId) +VtMatrix4dArray HdVP2Instancer::ComputeInstanceTransforms(SdfPath const& prototypeId) { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); @@ -144,10 +134,8 @@ VtMatrix4dArray HdVP2Instancer::ComputeInstanceTransforms(SdfPath const &prototy // } // If any transform isn't provided, it's assumed to be the identity. - GfMatrix4d instancerTransform = - GetDelegate()->GetInstancerTransform(GetId()); - VtIntArray instanceIndices = - GetDelegate()->GetInstanceIndices(GetId(), prototypeId); + GfMatrix4d instancerTransform = GetDelegate()->GetInstancerTransform(GetId()); + VtIntArray instanceIndices = GetDelegate()->GetInstanceIndices(GetId(), prototypeId); VtMatrix4dArray transforms(instanceIndices.size()); for (size_t i = 0; i < instanceIndices.size(); ++i) { @@ -174,8 +162,8 @@ VtMatrix4dArray HdVP2Instancer::ComputeInstanceTransforms(SdfPath const &prototy GfVec4f quat; if (sampler.Sample(instanceIndices[i], &quat)) { GfMatrix4d rotateMat(1); - rotateMat.SetRotate(GfRotation(GfQuaternion( - quat[0], GfVec3d(quat[1], quat[2], quat[3])))); + rotateMat.SetRotate( + GfRotation(GfQuaternion(quat[0], GfVec3d(quat[1], quat[2], quat[3])))); transforms[i] = rotateMat * transforms[i]; } } @@ -209,8 +197,7 @@ VtMatrix4dArray HdVP2Instancer::ComputeInstanceTransforms(SdfPath const &prototy return transforms; } - HdInstancer *parentInstancer = - GetDelegate()->GetRenderIndex().GetInstancer(GetParentId()); + HdInstancer* parentInstancer = GetDelegate()->GetRenderIndex().GetInstancer(GetParentId()); if (!TF_VERIFY(parentInstancer)) { return transforms; } @@ -220,19 +207,16 @@ VtMatrix4dArray HdVP2Instancer::ComputeInstanceTransforms(SdfPath const &prototy // foreach (parentXf : parentTransforms, xf : transforms) { // parentXf * xf // } - VtMatrix4dArray parentTransforms = - static_cast(parentInstancer)-> - ComputeInstanceTransforms(GetId()); + VtMatrix4dArray parentTransforms + = static_cast(parentInstancer)->ComputeInstanceTransforms(GetId()); VtMatrix4dArray final(parentTransforms.size() * transforms.size()); for (size_t i = 0; i < parentTransforms.size(); ++i) { for (size_t j = 0; j < transforms.size(); ++j) { - final[i * transforms.size() + j] = transforms[j] * - parentTransforms[i]; + final[i * transforms.size() + j] = transforms[j] * parentTransforms[i]; } } return final; } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/render/vp2RenderDelegate/instancer.h b/lib/mayaUsd/render/vp2RenderDelegate/instancer.h index 4cda3e674c..d5e4159745 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/instancer.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/instancer.h @@ -18,13 +18,13 @@ #ifndef HD_VP2_INSTANCER #define HD_VP2_INSTANCER -#include - -#include #include #include #include #include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE @@ -35,15 +35,14 @@ PXR_NAMESPACE_OPEN_SCOPE cartesian product of the transform arrays at each nesting level, to create a flattened transform array. */ -class HdVP2Instancer final : public HdInstancer +class HdVP2Instancer final : public HdInstancer { public: - HdVP2Instancer(HdSceneDelegate* delegate, SdfPath const& id, - SdfPath const &parentInstancerId); + HdVP2Instancer(HdSceneDelegate* delegate, SdfPath const& id, SdfPath const& parentInstancerId); ~HdVP2Instancer(); - VtMatrix4dArray ComputeInstanceTransforms(SdfPath const &prototypeId); + VtMatrix4dArray ComputeInstanceTransforms(SdfPath const& prototypeId); private: void _SyncPrimvars(); diff --git a/lib/mayaUsd/render/vp2RenderDelegate/material.cpp b/lib/mayaUsd/render/vp2RenderDelegate/material.cpp index eef9fe3db0..4baecefc7c 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/material.cpp +++ b/lib/mayaUsd/render/vp2RenderDelegate/material.cpp @@ -15,10 +15,13 @@ // #include "material.h" -#include -#include - -#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -30,13 +33,10 @@ #include #include -#include -#include -#include -#include -#include -#include -#include +#include + +#include +#include #if USD_VERSION_NUM >= 2002 #include #endif @@ -58,45 +58,28 @@ namespace { TF_DEFINE_PRIVATE_TOKENS( _tokens, - (file) - (opacity) - (st) - (varname) + (file)(opacity)(st)(varname) - (input) - (output) + (input)(output) - (rgb) - (r) - (g) - (b) - (a) + (rgb)(r)(g)(b)(a) - (xyz) - (x) - (y) - (z) - (w) + (xyz)(x)(y)(z)(w) - (Float4ToFloatX) - (Float4ToFloatY) - (Float4ToFloatZ) - (Float4ToFloatW) - (Float4ToFloat3) + (Float4ToFloatX)(Float4ToFloatY)(Float4ToFloatZ)(Float4ToFloatW)(Float4ToFloat3) - (UsdPrimvarReader_color) - (UsdPrimvarReader_vector) -); + (UsdPrimvarReader_color)(UsdPrimvarReader_vector)); //! Helper utility function to test whether a node is a UsdShade primvar reader. bool _IsUsdPrimvarReader(const HdMaterialNode& node) { const TfToken& id = node.identifier; - return (id == UsdImagingTokens->UsdPrimvarReader_float || - id == UsdImagingTokens->UsdPrimvarReader_float2 || - id == UsdImagingTokens->UsdPrimvarReader_float3 || - id == UsdImagingTokens->UsdPrimvarReader_float4 || - id == _tokens->UsdPrimvarReader_vector); + return ( + id == UsdImagingTokens->UsdPrimvarReader_float + || id == UsdImagingTokens->UsdPrimvarReader_float2 + || id == UsdImagingTokens->UsdPrimvarReader_float3 + || id == UsdImagingTokens->UsdPrimvarReader_float4 + || id == _tokens->UsdPrimvarReader_vector); } //! Helper utility function to test whether a node is a UsdShade UV texture. @@ -108,31 +91,30 @@ inline bool _IsUsdUVTexture(const HdMaterialNode& node) //! Helper utility function to print nodes, connections and primvars in the //! specified material network. void _PrintMaterialNetwork( - const std::string& label, - const SdfPath& id, + const std::string& label, + const SdfPath& id, const HdMaterialNetwork& mat) { std::cout << label << " material network for " << id << "\n"; std::cout << " --Node--\n"; - for (HdMaterialNode const& node: mat.nodes) { + for (HdMaterialNode const& node : mat.nodes) { std::cout << " " << node.path << "\n"; std::cout << " " << node.identifier << "\n"; - for (auto const& entry: node.parameters) { - std::cout << " param " << entry.first << ": " - << TfStringify(entry.second) << "\n"; + for (auto const& entry : node.parameters) { + std::cout << " param " << entry.first << ": " << TfStringify(entry.second) << "\n"; } } std::cout << " --Connections--\n"; - for (const HdMaterialRelationship& rel: mat.relationships) { - std::cout << " " << rel.inputId << "." << rel.inputName - << "->" << rel.outputId << "." << rel.outputName << "\n"; + for (const HdMaterialRelationship& rel : mat.relationships) { + std::cout << " " << rel.inputId << "." << rel.inputName << "->" << rel.outputId << "." + << rel.outputName << "\n"; } std::cout << " --Primvars--\n"; - for (TfToken const& primvar: mat.primvars) { + for (TfToken const& primvar : mat.primvars) { std::cout << " " << primvar << "\n"; } } @@ -153,8 +135,7 @@ void _ApplyVP2Fixes(HdMaterialNetwork& outNet, const HdMaterialNetwork& inNet) outNet.relationships.reserve(numRelationships * 2); outNet.primvars.reserve(numNodes); - for (const HdMaterialNode &node : inNet.nodes) - { + for (const HdMaterialNode& node : inNet.nodes) { TfToken primvarToRead; const bool isUsdPrimvarReader = _IsUsdPrimvarReader(node); @@ -170,8 +151,7 @@ void _ApplyVP2Fixes(HdMaterialNetwork& outNet, const HdMaterialNetwork& inNet) // If the primvar reader is reading color or opacity, change it to // UsdPrimvarReader_color which can create COLOR stream requirement // instead of generic TEXCOORD stream. - if (primvarToRead == HdTokens->displayColor || - primvarToRead == HdTokens->displayOpacity) { + if (primvarToRead == HdTokens->displayColor || primvarToRead == HdTokens->displayOpacity) { auto& nodeToChange = outNet.nodes.back(); nodeToChange.identifier = _tokens->UsdPrimvarReader_color; } @@ -185,46 +165,34 @@ void _ApplyVP2Fixes(HdMaterialNetwork& outNet, const HdMaterialNetwork& inNet) TfToken passThroughId; if (rel.inputName == _tokens->rgb || rel.inputName == _tokens->xyz) { passThroughId = _tokens->Float4ToFloat3; - } - else if (rel.inputName == _tokens->r || rel.inputName == _tokens->x) { + } else if (rel.inputName == _tokens->r || rel.inputName == _tokens->x) { passThroughId = _tokens->Float4ToFloatX; - } - else if (rel.inputName == _tokens->g || rel.inputName == _tokens->y) { + } else if (rel.inputName == _tokens->g || rel.inputName == _tokens->y) { passThroughId = _tokens->Float4ToFloatY; - } - else if (rel.inputName == _tokens->b || rel.inputName == _tokens->z) { + } else if (rel.inputName == _tokens->b || rel.inputName == _tokens->z) { passThroughId = _tokens->Float4ToFloatZ; - } - else if (rel.inputName == _tokens->a || rel.inputName == _tokens->w) { + } else if (rel.inputName == _tokens->a || rel.inputName == _tokens->w) { passThroughId = _tokens->Float4ToFloatW; - } - else if (primvarToRead == HdTokens->displayColor) { + } else if (primvarToRead == HdTokens->displayColor) { passThroughId = _tokens->Float4ToFloat3; - } - else if (primvarToRead == HdTokens->displayOpacity) { + } else if (primvarToRead == HdTokens->displayOpacity) { passThroughId = _tokens->Float4ToFloatW; - } - else { + } else { outNet.relationships.push_back(rel); continue; } - const SdfPath passThroughPath = rel.inputId.ReplaceName(TfToken( - TfStringPrintf("HdVP2PassThrough%d", numPassThroughNodes++))); + const SdfPath passThroughPath = rel.inputId.ReplaceName( + TfToken(TfStringPrintf("HdVP2PassThrough%d", numPassThroughNodes++))); - const HdMaterialNode passThroughNode = { - passThroughPath, passThroughId, {} - }; + const HdMaterialNode passThroughNode = { passThroughPath, passThroughId, {} }; outNet.nodes.push_back(passThroughNode); - HdMaterialRelationship newRel = { - rel.inputId, _tokens->output, passThroughPath, _tokens->input - }; + HdMaterialRelationship newRel + = { rel.inputId, _tokens->output, passThroughPath, _tokens->input }; outNet.relationships.push_back(newRel); - newRel = { - passThroughPath, _tokens->output, rel.outputId, rel.outputName - }; + newRel = { passThroughPath, _tokens->output, rel.outputId, rel.outputName }; outNet.relationships.push_back(newRel); } @@ -246,21 +214,17 @@ void _ApplyVP2Fixes(HdMaterialNetwork& outNet, const HdMaterialNetwork& inNet) } //! Helper utility function to convert Hydra texture addressing token to VP2 enum. -MHWRender::MSamplerState::TextureAddress _ConvertToTextureSamplerAddressEnum( - const TfToken& token) +MHWRender::MSamplerState::TextureAddress _ConvertToTextureSamplerAddressEnum(const TfToken& token) { MHWRender::MSamplerState::TextureAddress address; if (token == UsdHydraTokens->clamp) { address = MHWRender::MSamplerState::kTexClamp; - } - else if (token == UsdHydraTokens->mirror) { + } else if (token == UsdHydraTokens->mirror) { address = MHWRender::MSamplerState::kTexMirror; - } - else if (token == UsdHydraTokens->black) { + } else if (token == UsdHydraTokens->black) { address = MHWRender::MSamplerState::kTexBorder; - } - else { + } else { address = MHWRender::MSamplerState::kTexWrap; } @@ -297,8 +261,8 @@ MHWRender::MSamplerStateDesc _GetSamplerStateDesc(const HdMaterialNode& node) } #if USD_VERSION_NUM >= 2002 -MHWRender::MTexture* _LoadUdimTexture( - const std::string& path, bool& isColorSpaceSRGB, MFloatArray& uvScaleOffset) +MHWRender::MTexture* +_LoadUdimTexture(const std::string& path, bool& isColorSpaceSRGB, MFloatArray& uvScaleOffset) { /* For this method to work path needs to be an absolute file path, not an asset path. @@ -313,7 +277,7 @@ MHWRender::MTexture* _LoadUdimTexture( // test for a UDIM texture if (!GlfIsSupportedUdimTexture(path)) return nullptr; - + /* Maya's tiled texture support is implemented quite differently from Usd's UDIM support. In Maya the texture tiles get combined into a single big texture, downscaling each tile @@ -322,26 +286,25 @@ MHWRender::MTexture* _LoadUdimTexture( In USD the UDIM textures are stored in a texture array that the shader uses to draw. */ - MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); - MHWRender::MTextureManager* const textureMgr = - renderer ? renderer->getTextureManager() : nullptr; + MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); + MHWRender::MTextureManager* const textureMgr + = renderer ? renderer->getTextureManager() : nullptr; if (!TF_VERIFY(textureMgr)) { return nullptr; } - // HdSt sets the tile limit to the max number of textures in an array of 2d textures. OpenGL says - // the minimum number of layers in 2048 so I'll use that. - int tileLimit = 2048; + // HdSt sets the tile limit to the max number of textures in an array of 2d textures. OpenGL + // says the minimum number of layers in 2048 so I'll use that. + int tileLimit = 2048; std::vector> tiles = UsdImaging_GetUdimTiles(path, tileLimit); - if (tiles.size() == 0) - { + if (tiles.size() == 0) { TF_WARN("Unable to find UDIM tiles for %s", path.c_str()); return nullptr; } // I don't think there is a downside to setting a very high limit. // Maya will clamp the texture size to the VP2 texture clamp resolution and the hardware's - // max texture size. And Maya doesn't make the tiled texture unnecessarily large. When I + // max texture size. And Maya doesn't make the tiled texture unnecessarily large. When I // try loading two 1k textures I end up with a tiled texture that is 2k x 1k. unsigned int maxWidth = 0; unsigned int maxHeight = 0; @@ -363,50 +326,52 @@ MHWRender::MTexture* _LoadUdimTexture( int maxU = maxTileId % 10; int maxV = (maxTileId - maxU) / 10; if ((tileWidth * maxU > maxWidth) || (tileHeight * maxV > maxHeight)) - TF_WARN("UDIM texture %s creates a tiled texture larger than the maximum texture size. Some" - "resolution will be lost.", path.c_str()); + TF_WARN( + "UDIM texture %s creates a tiled texture larger than the maximum texture size. Some" + "resolution will be lost.", + path.c_str()); } - MString textureName(path.c_str()); // used for caching, using the string with in it is fine + MString textureName( + path.c_str()); // used for caching, using the string with in it is fine MStringArray tilePaths; - MFloatArray tilePositions; - for(auto& tile : tiles) - { + MFloatArray tilePositions; + for (auto& tile : tiles) { tilePaths.append(MString(std::get<1>(tile).GetText())); GlfImageSharedPtr image = GlfImage::OpenForReading(std::get<1>(tile).GetString()); if (!TF_VERIFY(image)) { return nullptr; } - if (isColorSpaceSRGB != image->IsColorSpaceSRGB()) - { - TF_WARN("UDIM texture %s color space doesn't match %s color space", - std::get<1>(tile).GetText(), std::get<1>(tiles[0]).GetText()); + if (isColorSpaceSRGB != image->IsColorSpaceSRGB()) { + TF_WARN( + "UDIM texture %s color space doesn't match %s color space", + std::get<1>(tile).GetText(), + std::get<1>(tiles[0]).GetText()); } // The image labeled 1001 will have id 0, 1002 will have id 1, 1011 will have id 10. // image 1001 starts with UV (0.0f, 0.0f), 1002 is (1.0f, 0.0f) and 1011 is (0.0f, 1.0f) - int tileId = std::get<0>(tile); + int tileId = std::get<0>(tile); float u = (float)(tileId % 10); float v = (float)((tileId - u) / 10); tilePositions.append(u); tilePositions.append(v); } - MColor undefinedColor(0.0f, 1.0f, 0.0f, 1.0f); - MStringArray failedTilePaths; + MColor undefinedColor(0.0f, 1.0f, 0.0f, 1.0f); + MStringArray failedTilePaths; MHWRender::MTexture* texture = textureMgr->acquireTiledTexture( textureName, tilePaths, tilePositions, undefinedColor, - maxWidth, maxHeight, + maxWidth, + maxHeight, failedTilePaths, - uvScaleOffset - ); + uvScaleOffset); - for(unsigned int i=0; i texture tile %s", failedTilePaths[i].asChar()); } @@ -415,10 +380,8 @@ MHWRender::MTexture* _LoadUdimTexture( #endif //! Load texture from the specified path -MHWRender::MTexture* _LoadTexture( - const std::string& path, - bool& isColorSpaceSRGB, - MFloatArray& uvScaleOffset) +MHWRender::MTexture* +_LoadTexture(const std::string& path, bool& isColorSpaceSRGB, MFloatArray& uvScaleOffset) { #if USD_VERSION_NUM >= 2002 // If it is a UDIM texture we need to modify the path before calling OpenForReading @@ -426,9 +389,9 @@ MHWRender::MTexture* _LoadTexture( return _LoadUdimTexture(path, isColorSpaceSRGB, uvScaleOffset); #endif - MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); - MHWRender::MTextureManager* const textureMgr = - renderer ? renderer->getTextureManager() : nullptr; + MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); + MHWRender::MTextureManager* const textureMgr + = renderer ? renderer->getTextureManager() : nullptr; if (!TF_VERIFY(textureMgr)) { return nullptr; } @@ -475,76 +438,71 @@ MHWRender::MTexture* _LoadTexture( #if USD_VERSION_NUM > 2008 switch (spec.hioFormat) { - // Single Channel - case HioFormatFloat32: - desc.fFormat = MHWRender::kR32_FLOAT; - texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); - break; - case HioFormatUNorm8: - desc.fFormat = MHWRender::kR8_UNORM; - texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); - break; + // Single Channel + case HioFormatFloat32: + desc.fFormat = MHWRender::kR32_FLOAT; + texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); + break; + case HioFormatUNorm8: + desc.fFormat = MHWRender::kR8_UNORM; + texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); + break; - // 3-Channel - case HioFormatFloat32Vec3: - desc.fFormat = MHWRender::kR32G32B32_FLOAT; - texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); - break; - case HioFormatUNorm8Vec3: - case HioFormatUNorm8Vec3srgb: - { - // R8G8B8 is not supported by VP2. Converted to R8G8B8A8. - constexpr int bpp_4 = 4; + // 3-Channel + case HioFormatFloat32Vec3: + desc.fFormat = MHWRender::kR32G32B32_FLOAT; + texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); + break; + case HioFormatUNorm8Vec3: + case HioFormatUNorm8Vec3srgb: { + // R8G8B8 is not supported by VP2. Converted to R8G8B8A8. + constexpr int bpp_4 = 4; - desc.fFormat = MHWRender::kR8G8B8A8_UNORM; - desc.fBytesPerRow = spec.width * bpp_4; - desc.fBytesPerSlice = desc.fBytesPerRow * spec.height; + desc.fFormat = MHWRender::kR8G8B8A8_UNORM; + desc.fBytesPerRow = spec.width * bpp_4; + desc.fBytesPerSlice = desc.fBytesPerRow * spec.height; - std::vector texels(desc.fBytesPerSlice); + std::vector texels(desc.fBytesPerSlice); - for (int y = 0; y < spec.height; y++) { - for (int x = 0; x < spec.width; x++) { - const int t = spec.width * y + x; - texels[t*bpp_4] = storage[t*bpp]; - texels[t*bpp_4 + 1] = storage[t*bpp + 1]; - texels[t*bpp_4 + 2] = storage[t*bpp + 2]; - texels[t*bpp_4 + 3] = 255; - } + for (int y = 0; y < spec.height; y++) { + for (int x = 0; x < spec.width; x++) { + const int t = spec.width * y + x; + texels[t * bpp_4] = storage[t * bpp]; + texels[t * bpp_4 + 1] = storage[t * bpp + 1]; + texels[t * bpp_4 + 2] = storage[t * bpp + 2]; + texels[t * bpp_4 + 3] = 255; } + } - texture = textureMgr->acquireTexture(path.c_str(), desc, texels.data()); - isColorSpaceSRGB = image->IsColorSpaceSRGB(); - break; - } + texture = textureMgr->acquireTexture(path.c_str(), desc, texels.data()); + isColorSpaceSRGB = image->IsColorSpaceSRGB(); + break; + } - // 4-Channel - case HioFormatFloat32Vec4: - desc.fFormat = MHWRender::kR32G32B32A32_FLOAT; - texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); - break; - case HioFormatUNorm8Vec4: - case HioFormatUNorm8Vec4srgb: - desc.fFormat = MHWRender::kR8G8B8A8_UNORM; - isColorSpaceSRGB = image->IsColorSpaceSRGB(); - texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); - break; - default: - break; + // 4-Channel + case HioFormatFloat32Vec4: + desc.fFormat = MHWRender::kR32G32B32A32_FLOAT; + texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); + break; + case HioFormatUNorm8Vec4: + case HioFormatUNorm8Vec4srgb: + desc.fFormat = MHWRender::kR8G8B8A8_UNORM; + isColorSpaceSRGB = image->IsColorSpaceSRGB(); + texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); + break; + default: break; } #else - switch (spec.format) - { + switch (spec.format) { case GL_RED: - desc.fFormat = (spec.type == GL_FLOAT ? - MHWRender::kR32_FLOAT : MHWRender::kR8_UNORM); + desc.fFormat = (spec.type == GL_FLOAT ? MHWRender::kR32_FLOAT : MHWRender::kR8_UNORM); texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; case GL_RGB: if (spec.type == GL_FLOAT) { desc.fFormat = MHWRender::kR32G32B32_FLOAT; texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); - } - else { + } else { // R8G8B8 is not supported by VP2. Converted to R8G8B8A8. constexpr int bpp_4 = 4; @@ -557,10 +515,10 @@ MHWRender::MTexture* _LoadTexture( for (int y = 0; y < spec.height; y++) { for (int x = 0; x < spec.width; x++) { const int t = spec.width * y + x; - texels[t*bpp_4] = storage[t*bpp]; - texels[t*bpp_4 + 1] = storage[t*bpp + 1]; - texels[t*bpp_4 + 2] = storage[t*bpp + 2]; - texels[t*bpp_4 + 3] = 255; + texels[t * bpp_4] = storage[t * bpp]; + texels[t * bpp_4 + 1] = storage[t * bpp + 1]; + texels[t * bpp_4 + 2] = storage[t * bpp + 2]; + texels[t * bpp_4 + 3] = 255; } } @@ -571,51 +529,46 @@ MHWRender::MTexture* _LoadTexture( case GL_RGBA: if (spec.type == GL_FLOAT) { desc.fFormat = MHWRender::kR32G32B32A32_FLOAT; - } - else { + } else { desc.fFormat = MHWRender::kR8G8B8A8_UNORM; isColorSpaceSRGB = image->IsColorSpaceSRGB(); } texture = textureMgr->acquireTexture(path.c_str(), desc, spec.data); break; - default: - break; + default: break; } #endif return texture; } -} //anonymous namespace +} // anonymous namespace /*! \brief Releases the reference to the shader owned by a smart pointer. -*/ -void -HdVP2ShaderDeleter::operator()(MHWRender::MShaderInstance* shader) + */ +void HdVP2ShaderDeleter::operator()(MHWRender::MShaderInstance* shader) { - MRenderer* const renderer = MRenderer::theRenderer(); - const MShaderManager* const shaderMgr = - renderer ? renderer->getShaderManager() : nullptr; + MRenderer* const renderer = MRenderer::theRenderer(); + const MShaderManager* const shaderMgr = renderer ? renderer->getShaderManager() : nullptr; if (TF_VERIFY(shaderMgr)) { shaderMgr->releaseShader(shader); } } /*! \brief Releases the reference to the texture owned by a smart pointer. -*/ -void -HdVP2TextureDeleter::operator()(MHWRender::MTexture* texture) + */ +void HdVP2TextureDeleter::operator()(MHWRender::MTexture* texture) { - MRenderer* const renderer = MRenderer::theRenderer(); - MHWRender::MTextureManager* const textureMgr = - renderer ? renderer->getTextureManager() : nullptr; + MRenderer* const renderer = MRenderer::theRenderer(); + MHWRender::MTextureManager* const textureMgr + = renderer ? renderer->getTextureManager() : nullptr; if (TF_VERIFY(textureMgr)) { textureMgr->releaseTexture(texture); } } /*! \brief Constructor -*/ + */ HdVP2Material::HdVP2Material(HdVP2RenderDelegate* renderDelegate, const SdfPath& id) : HdMaterial(id) , _renderDelegate(renderDelegate) @@ -623,7 +576,7 @@ HdVP2Material::HdVP2Material(HdVP2RenderDelegate* renderDelegate, const SdfPath& } /*! \brief Synchronize VP2 state with scene delegate state based on dirty bits -*/ + */ void HdVP2Material::Sync( HdSceneDelegate* sceneDelegate, HdRenderParam* /*renderParam*/, @@ -631,11 +584,11 @@ void HdVP2Material::Sync( { if (*dirtyBits & (HdMaterial::DirtyResource | HdMaterial::DirtyParams)) { const SdfPath& id = GetId(); - VtValue vtMatResource = sceneDelegate->GetMaterialResource(id); + VtValue vtMatResource = sceneDelegate->GetMaterialResource(id); if (vtMatResource.IsHolding()) { - const HdMaterialNetworkMap& networkMap = - vtMatResource.UncheckedGet(); + const HdMaterialNetworkMap& networkMap + = vtMatResource.UncheckedGet(); HdMaterialNetwork bxdfNet, dispNet; @@ -672,11 +625,12 @@ void HdVP2Material::Sync( } _UpdateShaderInstance(bxdfNet); - } - else { - TF_WARN("Expected material resource for <%s> to hold HdMaterialNetworkMap," + } else { + TF_WARN( + "Expected material resource for <%s> to hold HdMaterialNetworkMap," "but found %s instead.", - id.GetText(), vtMatResource.GetTypeName().c_str()); + id.GetText(), + vtMatResource.GetTypeName().c_str()); } } @@ -686,15 +640,12 @@ void HdVP2Material::Sync( /*! \brief Returns the minimal set of dirty bits to place in the change tracker for use in the first sync of this prim. */ -HdDirtyBits -HdVP2Material::GetInitialDirtyBitsMask() const { - return HdMaterial::AllDirty; -} +HdDirtyBits HdVP2Material::GetInitialDirtyBitsMask() const { return HdMaterial::AllDirty; } /*! \brief Creates a shader instance for the surface shader. -*/ -MHWRender::MShaderInstance* -HdVP2Material::_CreateShaderInstance(const HdMaterialNetwork& mat) { + */ +MHWRender::MShaderInstance* HdVP2Material::_CreateShaderInstance(const HdMaterialNetwork& mat) +{ MHWRender::MRenderer* const renderer = MHWRender::MRenderer::theRenderer(); if (!TF_VERIFY(renderer)) { return nullptr; @@ -709,7 +660,8 @@ HdVP2Material::_CreateShaderInstance(const HdMaterialNetwork& mat) { // MShaderInstance supports multiple connections between shaders on Maya 2018.7, 2019.3, 2020 // and above. -#if (MAYA_API_VERSION >= 20190300) || ((MAYA_API_VERSION >= 20180700) && (MAYA_API_VERSION < 20190000)) +#if (MAYA_API_VERSION >= 20190300) \ + || ((MAYA_API_VERSION >= 20180700) && (MAYA_API_VERSION < 20190000)) // UsdImagingMaterialAdapter has walked the shader graph and emitted nodes // and relationships in topological order to avoid forward-references, thus @@ -745,8 +697,7 @@ HdVP2Material::_CreateShaderInstance(const HdMaterialNetwork& mat) { std::string str = rel.outputId.GetName(); str += rel.outputName.GetString(); inputNames.append(str.c_str()); - } - else { + } else { inputNames.append(rel.outputName.GetText()); if (rel.outputName == _tokens->opacity) { @@ -758,16 +709,18 @@ HdVP2Material::_CreateShaderInstance(const HdMaterialNetwork& mat) { if (outputNames.length() > 0) { MUintArray invalidParamIndices; - MStatus status = shaderInstance->addInputFragmentForMultiParams( + MStatus status = shaderInstance->addInputFragmentForMultiParams( nodeId, nodeName, outputNames, inputNames, &invalidParamIndices); if (!status && TfDebug::IsEnabled(HDVP2_DEBUG_MATERIAL)) { - TF_WARN("Error %s happened when connecting shader %s", - status.errorString().asChar(), node.path.GetText()); + TF_WARN( + "Error %s happened when connecting shader %s", + status.errorString().asChar(), + node.path.GetText()); const unsigned int len = invalidParamIndices.length(); for (unsigned int i = 0; i < len; i++) { - unsigned int index = invalidParamIndices[i]; + unsigned int index = invalidParamIndices[i]; const MString& outputName = outputNames[index]; const MString& inputName = inputNames[index]; TF_WARN(" %s -> %s", outputName.asChar(), inputName.asChar()); @@ -782,10 +735,9 @@ HdVP2Material::_CreateShaderInstance(const HdMaterialNetwork& mat) { shaderInstance->renameParameter(paramName, varname); } } - } - else { - TF_DEBUG(HDVP2_DEBUG_MATERIAL).Msg("Failed to connect shader %s\n", - node.path.GetText()); + } else { + TF_DEBUG(HDVP2_DEBUG_MATERIAL) + .Msg("Failed to connect shader %s\n", node.path.GetText()); } } @@ -829,8 +781,7 @@ HdVP2Material::_CreateShaderInstance(const HdMaterialNetwork& mat) { } if (_IsUsdUVTexture(node)) { - if (rel.outputId == node.path && - rel.outputName == _tokens->st) { + if (rel.outputId == node.path && rel.outputName == _tokens->st) { for (const HdMaterialNode& n : mat.nodes) { if (n.path == rel.inputId && _IsUsdPrimvarReader(n)) { auto it = n.parameters.find(_tokens->varname); @@ -849,19 +800,20 @@ HdVP2Material::_CreateShaderInstance(const HdMaterialNetwork& mat) { // a UsdUVTexture is connected to a single input of a USD Preview Surface. // More generic fix is coming. if (outputNames.length() == 1) { - MStatus status = shaderInstance->addInputFragment( - nodeId, outputNames[0], inputNames[0]); + MStatus status + = shaderInstance->addInputFragment(nodeId, outputNames[0], inputNames[0]); if (!status) { - TF_DEBUG(HDVP2_DEBUG_MATERIAL).Msg( - "Error %s happened when connecting shader %s\n", - status.errorString().asChar(), node.path.GetText()); + TF_DEBUG(HDVP2_DEBUG_MATERIAL) + .Msg( + "Error %s happened when connecting shader %s\n", + status.errorString().asChar(), + node.path.GetText()); } if (_IsUsdUVTexture(node)) { - const MString paramNames[] = { - "file", "fileSampler", "isColorSpaceSRGB", "fallback", "scale", "bias" - }; + const MString paramNames[] + = { "file", "fileSampler", "isColorSpaceSRGB", "fallback", "scale", "bias" }; for (const MString& paramName : paramNames) { const MString resolvedName = nodeName + paramName; @@ -873,14 +825,14 @@ HdVP2Material::_CreateShaderInstance(const HdMaterialNetwork& mat) { shaderInstance->setAsVarying(paramName, true); shaderInstance->renameParameter(paramName, primvarname.c_str()); } - } - else { - TF_DEBUG(HDVP2_DEBUG_MATERIAL).Msg( - "Failed to connect shader %s\n", node.path.GetText()); + } else { + TF_DEBUG(HDVP2_DEBUG_MATERIAL) + .Msg("Failed to connect shader %s\n", node.path.GetText()); if (outputNames.length() > 1) { - TF_DEBUG(HDVP2_DEBUG_MATERIAL).Msg("MShaderInstance doesn't support " - "multiple connections between shaders on the current Maya version.\n"); + TF_DEBUG(HDVP2_DEBUG_MATERIAL) + .Msg("MShaderInstance doesn't support " + "multiple connections between shaders on the current Maya version.\n"); } } } @@ -891,7 +843,7 @@ HdVP2Material::_CreateShaderInstance(const HdMaterialNetwork& mat) { } /*! \brief Updates parameters for the surface shader. -*/ + */ void HdVP2Material::_UpdateShaderInstance(const HdMaterialNetwork& mat) { if (!_surfaceShader) { @@ -899,22 +851,20 @@ void HdVP2Material::_UpdateShaderInstance(const HdMaterialNetwork& mat) } for (const HdMaterialNode& node : mat.nodes) { - const MString nodeName = - node.path != _surfaceShaderId ? node.path.GetName().c_str() : ""; + const MString nodeName = node.path != _surfaceShaderId ? node.path.GetName().c_str() : ""; MStatus samplerStatus = MStatus::kFailure; if (_IsUsdUVTexture(node)) { const MHWRender::MSamplerStateDesc desc = _GetSamplerStateDesc(node); - const MHWRender::MSamplerState* sampler = - _renderDelegate->GetSamplerState(desc); + const MHWRender::MSamplerState* sampler = _renderDelegate->GetSamplerState(desc); if (sampler) { const MString paramName = nodeName + "fileSampler"; samplerStatus = _surfaceShader->setParameter(paramName, *sampler); } } - for (auto const& entry: node.parameters) { + for (auto const& entry : node.parameters) { const TfToken& token = entry.first; const VtValue& value = entry.second; @@ -932,35 +882,29 @@ void HdVP2Material::_UpdateShaderInstance(const HdMaterialNetwork& mat) if (nodeName.length() == 0 && token == _tokens->opacity) { _surfaceShader->setIsTransparent(!status || val < 0.999f); } - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { const float* val = value.UncheckedGet().data(); status = _surfaceShader->setParameter(paramName, val); - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { const float* val = value.UncheckedGet().data(); status = _surfaceShader->setParameter(paramName, val); - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { const float* val = value.UncheckedGet().data(); status = _surfaceShader->setParameter(paramName, val); - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { // The two parameters have been converted to sampler state // before entering this loop. - if (_IsUsdUVTexture(node) && - (token == UsdHydraTokens->wrapS || - token == UsdHydraTokens->wrapT)) { + if (_IsUsdUVTexture(node) + && (token == UsdHydraTokens->wrapS || token == UsdHydraTokens->wrapT)) { status = samplerStatus; } - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { const SdfAssetPath& val = value.UncheckedGet(); - const std::string& resolvedPath = val.GetResolvedPath(); - const std::string& assetPath = val.GetAssetPath(); + const std::string& resolvedPath = val.GetResolvedPath(); + const std::string& assetPath = val.GetAssetPath(); if (_IsUsdUVTexture(node) && token == _tokens->file) { - const HdVP2TextureInfo& info = _AcquireTexture( - !resolvedPath.empty() ? resolvedPath : assetPath); + const HdVP2TextureInfo& info + = _AcquireTexture(!resolvedPath.empty() ? resolvedPath : assetPath); MHWRender::MTextureAssignment assignment; assignment.texture = info._texture.get(); @@ -968,8 +912,7 @@ void HdVP2Material::_UpdateShaderInstance(const HdMaterialNetwork& mat) if (status) { paramName = nodeName + "isColorSpaceSRGB"; - status = _surfaceShader->setParameter(paramName, - info._isColorSpaceSRGB); + status = _surfaceShader->setParameter(paramName, info._isColorSpaceSRGB); } if (status) { paramName = nodeName + "stScale"; @@ -980,45 +923,40 @@ void HdVP2Material::_UpdateShaderInstance(const HdMaterialNetwork& mat) status = _surfaceShader->setParameter(paramName, info._stOffset.data()); } } - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { const int& val = value.UncheckedGet(); status = _surfaceShader->setParameter(paramName, val); - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { const bool& val = value.UncheckedGet(); status = _surfaceShader->setParameter(paramName, val); - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { MMatrix matrix; value.UncheckedGet().Get(matrix.matrix); status = _surfaceShader->setParameter(paramName, matrix); - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { MFloatMatrix matrix; value.UncheckedGet().Get(matrix.matrix); status = _surfaceShader->setParameter(paramName, matrix); } if (!status) { - TF_DEBUG(HDVP2_DEBUG_MATERIAL).Msg( - "Failed to set shader parameter %s\n", paramName.asChar()); + TF_DEBUG(HDVP2_DEBUG_MATERIAL) + .Msg("Failed to set shader parameter %s\n", paramName.asChar()); } } } } /*! \brief Acquires a texture for the given image path. -*/ -const HdVP2TextureInfo& -HdVP2Material::_AcquireTexture(const std::string& path) + */ +const HdVP2TextureInfo& HdVP2Material::_AcquireTexture(const std::string& path) { const auto it = _textureMap.find(path); if (it != _textureMap.end()) { return it->second; } - bool isSRGB = false; + bool isSRGB = false; MFloatArray uvScaleOffset; MHWRender::MTexture* texture = _LoadTexture(path, isSRGB, uvScaleOffset); @@ -1028,7 +966,8 @@ HdVP2Material::_AcquireTexture(const std::string& path) if (uvScaleOffset.length() > 0) { TF_VERIFY(uvScaleOffset.length() == 4); info._stScale.Set(uvScaleOffset[0], uvScaleOffset[1]); // The first 2 elements are the scale - info._stOffset.Set(uvScaleOffset[2], uvScaleOffset[3]);// The next two elements are the offset + info._stOffset.Set( + uvScaleOffset[2], uvScaleOffset[3]); // The next two elements are the offset } return info; } diff --git a/lib/mayaUsd/render/vp2RenderDelegate/material.h b/lib/mayaUsd/render/vp2RenderDelegate/material.h index 2b6ed6a73c..14dbde3c7b 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/material.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/material.h @@ -16,13 +16,13 @@ #ifndef HD_VP2_MATERIAL #define HD_VP2_MATERIAL -#include +#include +#include +#include #include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -30,45 +30,39 @@ class HdSceneDelegate; class HdVP2RenderDelegate; /*! \brief A deleter for MShaderInstance, for use with smart pointers. -*/ + */ struct HdVP2ShaderDeleter { - void operator () (MHWRender::MShaderInstance*); + void operator()(MHWRender::MShaderInstance*); }; /*! \brief A MShaderInstance owned by a std unique pointer. -*/ -using HdVP2ShaderUniquePtr = std::unique_ptr< - MHWRender::MShaderInstance, - HdVP2ShaderDeleter ->; + */ +using HdVP2ShaderUniquePtr = std::unique_ptr; /*! \brief A deleter for MTexture, for use with smart pointers. -*/ + */ struct HdVP2TextureDeleter { - void operator () (MHWRender::MTexture*); + void operator()(MHWRender::MTexture*); }; /*! \brief A MTexture owned by a std unique pointer. -*/ -using HdVP2TextureUniquePtr = std::unique_ptr< - MHWRender::MTexture, - HdVP2TextureDeleter ->; + */ +using HdVP2TextureUniquePtr = std::unique_ptr; /*! \brief Information about the texture. -*/ + */ struct HdVP2TextureInfo { - HdVP2TextureUniquePtr _texture; //!< Unique pointer of the texture - GfVec2f _stScale{1.0f,1.0f}; //!< UV scale for tiled textures - GfVec2f _stOffset{0.0f, 0.0f}; //!< UV offset for tiled textures - bool _isColorSpaceSRGB{false};//!< Whether sRGB linearization is needed + HdVP2TextureUniquePtr _texture; //!< Unique pointer of the texture + GfVec2f _stScale { 1.0f, 1.0f }; //!< UV scale for tiled textures + GfVec2f _stOffset { 0.0f, 0.0f }; //!< UV offset for tiled textures + bool _isColorSpaceSRGB { false }; //!< Whether sRGB linearization is needed }; /*! \brief An unordered string-indexed map to cache texture information. -*/ + */ using HdVP2TextureMap = std::unordered_map; /*! \brief A VP2-specific implementation for a Hydra material prim. @@ -76,7 +70,8 @@ using HdVP2TextureMap = std::unordered_map; Provides a basic implementation of a Hydra material. */ -class HdVP2Material final : public HdMaterial { +class HdVP2Material final : public HdMaterial +{ public: HdVP2Material(HdVP2RenderDelegate*, const SdfPath&); @@ -92,26 +87,23 @@ class HdVP2Material final : public HdMaterial { #endif //! Get the surface shader instance. - MHWRender::MShaderInstance* GetSurfaceShader() const { - return _surfaceShader.get(); - } + MHWRender::MShaderInstance* GetSurfaceShader() const { return _surfaceShader.get(); } //! Get primvar tokens required by this material. - const TfTokenVector& GetRequiredPrimvars() const { - return _requiredPrimvars; - } + const TfTokenVector& GetRequiredPrimvars() const { return _requiredPrimvars; } private: MHWRender::MShaderInstance* _CreateShaderInstance(const HdMaterialNetwork& mat); - void _UpdateShaderInstance(const HdMaterialNetwork& mat); - const HdVP2TextureInfo& _AcquireTexture(const std::string& path); + void _UpdateShaderInstance(const HdMaterialNetwork& mat); + const HdVP2TextureInfo& _AcquireTexture(const std::string& path); - HdVP2RenderDelegate* const _renderDelegate; //!< VP2 render delegate for which this material was created + HdVP2RenderDelegate* const + _renderDelegate; //!< VP2 render delegate for which this material was created - HdVP2ShaderUniquePtr _surfaceShader; //!< VP2 surface shader instance - SdfPath _surfaceShaderId; //!< Path of the surface shader - HdVP2TextureMap _textureMap; //!< Textures used by this material - TfTokenVector _requiredPrimvars; //!< primvars required by this material + HdVP2ShaderUniquePtr _surfaceShader; //!< VP2 surface shader instance + SdfPath _surfaceShaderId; //!< Path of the surface shader + HdVP2TextureMap _textureMap; //!< Textures used by this material + TfTokenVector _requiredPrimvars; //!< primvars required by this material }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/mesh.cpp b/lib/mayaUsd/render/vp2RenderDelegate/mesh.cpp index d1523769d0..23671ea153 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/mesh.cpp +++ b/lib/mayaUsd/render/vp2RenderDelegate/mesh.cpp @@ -15,20 +15,6 @@ // #include "mesh.h" -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - #include "bboxGeom.h" #include "debugCodes.h" #include "draw_item.h" @@ -40,284 +26,312 @@ #include #include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + PXR_NAMESPACE_OPEN_SCOPE namespace { - //! Required primvars when there is no material binding. - const TfTokenVector sFallbackShaderPrimvars = { - HdTokens->displayColor, - HdTokens->displayOpacity, - HdTokens->normals - }; - - const MColor kOpaqueBlue(0.0f, 0.0f, 1.0f, 1.0f); //!< Opaque blue - const MColor kOpaqueGray(.18f, .18f, .18f, 1.0f); //!< Opaque gray - const unsigned int kNumColorChannels = 4; //!< The number of color channels - - const MString kPositionsStr("positions"); //!< Cached string for efficiency - const MString kNormalsStr("normals"); //!< Cached string for efficiency - const MString kDiffuseColorStr("diffuseColor"); //!< Cached string for efficiency - const MString kSolidColorStr("solidColor"); //!< Cached string for efficiency - - //! A primvar vertex buffer data map indexed by primvar name. - using PrimvarBufferDataMap = std::unordered_map< - TfToken, - void*, - TfToken::HashFunctor - >; - - //! \brief Helper struct used to package all the changes into single commit task - //! (such commit task will be executed on main-thread) - struct CommitState { - HdVP2DrawItem::RenderItemData& _drawItemData; - - //! If valid, new index buffer data to commit - int* _indexBufferData{ nullptr }; - //! If valid, new color buffer data to commit - void* _colorBufferData{ nullptr }; - //! If valid, new normals buffer data to commit - void* _normalsBufferData{ nullptr }; - //! If valid, new primvar buffer data to commit - PrimvarBufferDataMap _primvarBufferDataMap; - - //! If valid, world matrix to set on the render item - MMatrix* _worldMatrix{ nullptr }; - - //! If valid, bounding box to set on the render item - MBoundingBox* _boundingBox{ nullptr }; - - //! if valid, enable or disable the render item - bool* _enabled{ nullptr }; - - //! Instancing doesn't have dirty bits, every time we do update, we must update instance transforms - MMatrixArray _instanceTransforms; - - //! Color array to support per-instance color and selection highlight. - MFloatArray _instanceColors; - - //! If valid, new shader instance to set - MHWRender::MShaderInstance* _shader{ nullptr }; - - //! Is this object transparent - bool _isTransparent{ false }; - - //! If true, associate geometric buffers to the render item and trigger consolidation/instancing update - bool _geometryDirty{ false }; - - //! Construct valid commit state - CommitState(HdVP2DrawItem& item) : _drawItemData(item.GetRenderItemData()) - {} - - //! No default constructor, we need draw item and dirty bits. - CommitState() = delete; - }; - - //! Helper utility function to fill primvar data to vertex buffer. - template - void _FillPrimvarData(DEST_TYPE* vertexBuffer, - size_t numVertices, - size_t channelOffset, - const VtIntArray& renderingToSceneFaceVtxIds, - const MString& rprimId, - const HdMeshTopology& topology, - const TfToken& primvarName, - const VtArray& primvarData, - const HdInterpolation& primvarInterp) +//! Required primvars when there is no material binding. +const TfTokenVector sFallbackShaderPrimvars + = { HdTokens->displayColor, HdTokens->displayOpacity, HdTokens->normals }; + +const MColor kOpaqueBlue(0.0f, 0.0f, 1.0f, 1.0f); //!< Opaque blue +const MColor kOpaqueGray(.18f, .18f, .18f, 1.0f); //!< Opaque gray +const unsigned int kNumColorChannels = 4; //!< The number of color channels + +const MString kPositionsStr("positions"); //!< Cached string for efficiency +const MString kNormalsStr("normals"); //!< Cached string for efficiency +const MString kDiffuseColorStr("diffuseColor"); //!< Cached string for efficiency +const MString kSolidColorStr("solidColor"); //!< Cached string for efficiency + +//! A primvar vertex buffer data map indexed by primvar name. +using PrimvarBufferDataMap = std::unordered_map; + +//! \brief Helper struct used to package all the changes into single commit task +//! (such commit task will be executed on main-thread) +struct CommitState +{ + HdVP2DrawItem::RenderItemData& _drawItemData; + + //! If valid, new index buffer data to commit + int* _indexBufferData { nullptr }; + //! If valid, new color buffer data to commit + void* _colorBufferData { nullptr }; + //! If valid, new normals buffer data to commit + void* _normalsBufferData { nullptr }; + //! If valid, new primvar buffer data to commit + PrimvarBufferDataMap _primvarBufferDataMap; + + //! If valid, world matrix to set on the render item + MMatrix* _worldMatrix { nullptr }; + + //! If valid, bounding box to set on the render item + MBoundingBox* _boundingBox { nullptr }; + + //! if valid, enable or disable the render item + bool* _enabled { nullptr }; + + //! Instancing doesn't have dirty bits, every time we do update, we must update instance + //! transforms + MMatrixArray _instanceTransforms; + + //! Color array to support per-instance color and selection highlight. + MFloatArray _instanceColors; + + //! If valid, new shader instance to set + MHWRender::MShaderInstance* _shader { nullptr }; + + //! Is this object transparent + bool _isTransparent { false }; + + //! If true, associate geometric buffers to the render item and trigger consolidation/instancing + //! update + bool _geometryDirty { false }; + + //! Construct valid commit state + CommitState(HdVP2DrawItem& item) + : _drawItemData(item.GetRenderItemData()) { - switch (primvarInterp) { - case HdInterpolationConstant: + } + + //! No default constructor, we need draw item and dirty bits. + CommitState() = delete; +}; + +//! Helper utility function to fill primvar data to vertex buffer. +template +void _FillPrimvarData( + DEST_TYPE* vertexBuffer, + size_t numVertices, + size_t channelOffset, + const VtIntArray& renderingToSceneFaceVtxIds, + const MString& rprimId, + const HdMeshTopology& topology, + const TfToken& primvarName, + const VtArray& primvarData, + const HdInterpolation& primvarInterp) +{ + switch (primvarInterp) { + case HdInterpolationConstant: + for (size_t v = 0; v < numVertices; v++) { + SRC_TYPE* pointer = reinterpret_cast( + reinterpret_cast(&vertexBuffer[v]) + channelOffset); + *pointer = primvarData[0]; + } + break; + case HdInterpolationVarying: + case HdInterpolationVertex: + if (numVertices <= renderingToSceneFaceVtxIds.size()) { + const unsigned int dataSize = primvarData.size(); for (size_t v = 0; v < numVertices; v++) { - SRC_TYPE* pointer = reinterpret_cast( - reinterpret_cast(&vertexBuffer[v]) + channelOffset); - *pointer = primvarData[0]; - } - break; - case HdInterpolationVarying: - case HdInterpolationVertex: - if (numVertices <= renderingToSceneFaceVtxIds.size()) { - const unsigned int dataSize = primvarData.size(); - for (size_t v = 0; v < numVertices; v++) { - unsigned int index = renderingToSceneFaceVtxIds[v]; - if (index < dataSize) { - SRC_TYPE* pointer = reinterpret_cast( - reinterpret_cast(&vertexBuffer[v]) + channelOffset); - *pointer = primvarData[index]; - } - else { - TF_DEBUG(HDVP2_DEBUG_MESH).Msg("Invalid Hydra prim '%s': " + unsigned int index = renderingToSceneFaceVtxIds[v]; + if (index < dataSize) { + SRC_TYPE* pointer = reinterpret_cast( + reinterpret_cast(&vertexBuffer[v]) + channelOffset); + *pointer = primvarData[index]; + } else { + TF_DEBUG(HDVP2_DEBUG_MESH) + .Msg( + "Invalid Hydra prim '%s': " "primvar %s has %u elements, while its topology " "references face vertex index %u.\n", - rprimId.asChar(), primvarName.GetText(), - dataSize, index); - } + rprimId.asChar(), + primvarName.GetText(), + dataSize, + index); } } - else { - TF_CODING_ERROR("Invalid Hydra prim '%s': " - "requires %zu vertices, while the number of elements in " - "renderingToSceneFaceVtxIds is %zu. Skipping primvar update.", - rprimId.asChar(), numVertices, renderingToSceneFaceVtxIds.size()); - - memset(vertexBuffer, 0, sizeof(DEST_TYPE) * numVertices); - } - break; - case HdInterpolationUniform: - { - const VtIntArray& faceVertexCounts = topology.GetFaceVertexCounts(); - const size_t numFaces = faceVertexCounts.size(); - if (numFaces <= primvarData.size()) { - // The primvar has more data than needed, we issue a warning but - // don't skip update. Truncate the buffer to the expected length. - if (numFaces < primvarData.size()) { - TF_DEBUG(HDVP2_DEBUG_MESH).Msg("Invalid Hydra prim '%s': " + } else { + TF_CODING_ERROR( + "Invalid Hydra prim '%s': " + "requires %zu vertices, while the number of elements in " + "renderingToSceneFaceVtxIds is %zu. Skipping primvar update.", + rprimId.asChar(), + numVertices, + renderingToSceneFaceVtxIds.size()); + + memset(vertexBuffer, 0, sizeof(DEST_TYPE) * numVertices); + } + break; + case HdInterpolationUniform: { + const VtIntArray& faceVertexCounts = topology.GetFaceVertexCounts(); + const size_t numFaces = faceVertexCounts.size(); + if (numFaces <= primvarData.size()) { + // The primvar has more data than needed, we issue a warning but + // don't skip update. Truncate the buffer to the expected length. + if (numFaces < primvarData.size()) { + TF_DEBUG(HDVP2_DEBUG_MESH) + .Msg( + "Invalid Hydra prim '%s': " "primvar %s has %zu elements, while its topology " "references only upto element index %zu.\n", - rprimId.asChar(), primvarName.GetText(), - primvarData.size(), numFaces); - } + rprimId.asChar(), + primvarName.GetText(), + primvarData.size(), + numFaces); + } - for (size_t f = 0, v = 0; f < numFaces; f++) { - const size_t faceVertexCount = faceVertexCounts[f]; - const size_t faceVertexEnd = v + faceVertexCount; - for (; v < faceVertexEnd; v++) { - SRC_TYPE* pointer = reinterpret_cast( - reinterpret_cast(&vertexBuffer[v]) + channelOffset); - *pointer = primvarData[f]; - } + for (size_t f = 0, v = 0; f < numFaces; f++) { + const size_t faceVertexCount = faceVertexCounts[f]; + const size_t faceVertexEnd = v + faceVertexCount; + for (; v < faceVertexEnd; v++) { + SRC_TYPE* pointer = reinterpret_cast( + reinterpret_cast(&vertexBuffer[v]) + channelOffset); + *pointer = primvarData[f]; } } - else { - // The primvar has less data than needed. Issue warning and skip - // update like what is done in HdStMesh. - TF_DEBUG(HDVP2_DEBUG_MESH).Msg("Invalid Hydra prim '%s': " + } else { + // The primvar has less data than needed. Issue warning and skip + // update like what is done in HdStMesh. + TF_DEBUG(HDVP2_DEBUG_MESH) + .Msg( + "Invalid Hydra prim '%s': " "primvar %s has only %zu elements, while its topology expects " "at least %zu elements. Skipping primvar update.\n", - rprimId.asChar(), primvarName.GetText(), - primvarData.size(), numFaces); + rprimId.asChar(), + primvarName.GetText(), + primvarData.size(), + numFaces); - memset(vertexBuffer, 0, sizeof(DEST_TYPE) * numVertices); - } - break; + memset(vertexBuffer, 0, sizeof(DEST_TYPE) * numVertices); } - case HdInterpolationFaceVarying: - // Unshared vertex layout is required for face-varying primvars, in - // this case renderingToSceneFaceVtxIds is a natural sequence starting - // from 0, thus we can save a lookup into the table. If the assumption - // about the natural sequence is changed, we will need the lookup and - // remap indices. - if (numVertices <= primvarData.size()) { - // If the primvar has more data than needed, we issue a warning, - // but don't skip the primvar update. Truncate the buffer to the - // expected length. - if (numVertices < primvarData.size()) { - TF_DEBUG(HDVP2_DEBUG_MESH).Msg("Invalid Hydra prim '%s': " + break; + } + case HdInterpolationFaceVarying: + // Unshared vertex layout is required for face-varying primvars, in + // this case renderingToSceneFaceVtxIds is a natural sequence starting + // from 0, thus we can save a lookup into the table. If the assumption + // about the natural sequence is changed, we will need the lookup and + // remap indices. + if (numVertices <= primvarData.size()) { + // If the primvar has more data than needed, we issue a warning, + // but don't skip the primvar update. Truncate the buffer to the + // expected length. + if (numVertices < primvarData.size()) { + TF_DEBUG(HDVP2_DEBUG_MESH) + .Msg( + "Invalid Hydra prim '%s': " "primvar %s has %zu elements, while its topology references " "only upto element index %zu.\n", - rprimId.asChar(), primvarName.GetText(), - primvarData.size(), numVertices); - } + rprimId.asChar(), + primvarName.GetText(), + primvarData.size(), + numVertices); + } - if (channelOffset == 0 && std::is_same::value) { - const void* source = static_cast(primvarData.cdata()); - memcpy(vertexBuffer, source, sizeof(DEST_TYPE) * numVertices); - } - else { - for (size_t v = 0; v < numVertices; v++) { - SRC_TYPE* pointer = reinterpret_cast( - reinterpret_cast(&vertexBuffer[v]) + channelOffset); - *pointer = primvarData[v]; - } + if (channelOffset == 0 && std::is_same::value) { + const void* source = static_cast(primvarData.cdata()); + memcpy(vertexBuffer, source, sizeof(DEST_TYPE) * numVertices); + } else { + for (size_t v = 0; v < numVertices; v++) { + SRC_TYPE* pointer = reinterpret_cast( + reinterpret_cast(&vertexBuffer[v]) + channelOffset); + *pointer = primvarData[v]; } } - else { - // It is unexpected to have less data than we index into. Issue - // a warning and skip update. - TF_DEBUG(HDVP2_DEBUG_MESH).Msg("Invalid Hydra prim '%s': " + } else { + // It is unexpected to have less data than we index into. Issue + // a warning and skip update. + TF_DEBUG(HDVP2_DEBUG_MESH) + .Msg( + "Invalid Hydra prim '%s': " "primvar %s has only %zu elements, while its topology expects " "at least %zu elements. Skipping primvar update.\n", - rprimId.asChar(), primvarName.GetText(), - primvarData.size(), numVertices); + rprimId.asChar(), + primvarName.GetText(), + primvarData.size(), + numVertices); - memset(vertexBuffer, 0, sizeof(DEST_TYPE) * numVertices); - } - break; - default: - TF_CODING_ERROR("Invalid Hydra prim '%s': " - "unimplemented interpolation %d for primvar %s", - rprimId.asChar(), (int)primvarInterp, primvarName.GetText()); - break; + memset(vertexBuffer, 0, sizeof(DEST_TYPE) * numVertices); } + break; + default: + TF_CODING_ERROR( + "Invalid Hydra prim '%s': " + "unimplemented interpolation %d for primvar %s", + rprimId.asChar(), + (int)primvarInterp, + primvarName.GetText()); + break; } +} - //! If there is uniform or face-varying primvar, we have to create unshared - //! vertex layout on CPU because SSBO technique is not widely supported by - //! GPUs and 3D APIs. - bool _IsUnsharedVertexLayoutRequired(const PrimvarSourceMap& primvarSources) - { - for (const auto& it : primvarSources) { - const HdInterpolation interp = it.second.interpolation; - if (interp == HdInterpolationUniform || - interp == HdInterpolationFaceVarying) { - return true; - } +//! If there is uniform or face-varying primvar, we have to create unshared +//! vertex layout on CPU because SSBO technique is not widely supported by +//! GPUs and 3D APIs. +bool _IsUnsharedVertexLayoutRequired(const PrimvarSourceMap& primvarSources) +{ + for (const auto& it : primvarSources) { + const HdInterpolation interp = it.second.interpolation; + if (interp == HdInterpolationUniform || interp == HdInterpolationFaceVarying) { + return true; } - - return false; } - //! Helper utility function to get number of edge indices - unsigned int _GetNumOfEdgeIndices(const HdMeshTopology& topology) - { - const VtIntArray &faceVertexCounts = topology.GetFaceVertexCounts(); + return false; +} - unsigned int numIndex = 0; - for (std::size_t i = 0; i < faceVertexCounts.size(); i++) - { - numIndex += faceVertexCounts[i]; - } - numIndex *= 2; // each edge has two ends. - return numIndex; +//! Helper utility function to get number of edge indices +unsigned int _GetNumOfEdgeIndices(const HdMeshTopology& topology) +{ + const VtIntArray& faceVertexCounts = topology.GetFaceVertexCounts(); + + unsigned int numIndex = 0; + for (std::size_t i = 0; i < faceVertexCounts.size(); i++) { + numIndex += faceVertexCounts[i]; } + numIndex *= 2; // each edge has two ends. + return numIndex; +} - //! Helper utility function to extract edge indices - void _FillEdgeIndices(int* indices, const HdMeshTopology& topology) - { - const VtIntArray &faceVertexCounts = topology.GetFaceVertexCounts(); - const int* currentFaceStart = topology.GetFaceVertexIndices().cdata(); - for (std::size_t faceId = 0; faceId < faceVertexCounts.size(); faceId++) - { - int numVertexIndicesInFace = faceVertexCounts[faceId]; - if (numVertexIndicesInFace >= 2) - { - for (int faceVertexId = 0; faceVertexId < numVertexIndicesInFace; faceVertexId++) - { - bool isLastVertex = faceVertexId == numVertexIndicesInFace - 1; - *(indices++) = *(currentFaceStart + faceVertexId); - *(indices++) = isLastVertex ? *currentFaceStart : *(currentFaceStart + faceVertexId + 1); - } +//! Helper utility function to extract edge indices +void _FillEdgeIndices(int* indices, const HdMeshTopology& topology) +{ + const VtIntArray& faceVertexCounts = topology.GetFaceVertexCounts(); + const int* currentFaceStart = topology.GetFaceVertexIndices().cdata(); + for (std::size_t faceId = 0; faceId < faceVertexCounts.size(); faceId++) { + int numVertexIndicesInFace = faceVertexCounts[faceId]; + if (numVertexIndicesInFace >= 2) { + for (int faceVertexId = 0; faceVertexId < numVertexIndicesInFace; faceVertexId++) { + bool isLastVertex = faceVertexId == numVertexIndicesInFace - 1; + *(indices++) = *(currentFaceStart + faceVertexId); + *(indices++) + = isLastVertex ? *currentFaceStart : *(currentFaceStart + faceVertexId + 1); } - currentFaceStart += numVertexIndicesInFace; } + currentFaceStart += numVertexIndicesInFace; } +} - //! Helper utility function to adapt Maya API changes. - void setWantConsolidation(MHWRender::MRenderItem& renderItem, bool state) - { +//! Helper utility function to adapt Maya API changes. +void setWantConsolidation(MHWRender::MRenderItem& renderItem, bool state) +{ #if MAYA_API_VERSION >= 20190000 - renderItem.setWantConsolidation(state); + renderItem.setWantConsolidation(state); #else - renderItem.setWantSubSceneConsolidation(state); + renderItem.setWantSubSceneConsolidation(state); #endif - } -} //namespace - +} +} // namespace //! \brief Constructor HdVP2Mesh::HdVP2Mesh(HdVP2RenderDelegate* delegate, const SdfPath& id, const SdfPath& instancerId) -: HdMesh(id, instancerId) -, _delegate(delegate) -, _rprimId(id.GetText()) + : HdMesh(id, instancerId) + , _delegate(delegate) + , _rprimId(id.GetText()) { const MHWRender::MVertexBufferDescriptor vbDesc( "", MHWRender::MGeometry::kPosition, MHWRender::MGeometry::kFloat, 3); @@ -327,9 +341,9 @@ HdVP2Mesh::HdVP2Mesh(HdVP2RenderDelegate* delegate, const SdfPath& id, const Sdf //! \brief Synchronize VP2 state with scene delegate state based on dirty bits and representation void HdVP2Mesh::Sync( HdSceneDelegate* delegate, - HdRenderParam* renderParam, - HdDirtyBits* dirtyBits, - const TfToken& reprToken) + HdRenderParam* renderParam, + HdDirtyBits* dirtyBits, + const TfToken& reprToken) { // We don't create a repr for the selection token because this token serves // for selection state update only. Return early to reserve dirty bits so @@ -345,34 +359,35 @@ void HdVP2Mesh::Sync( ProxyRenderDelegate& drawScene = param->GetDrawScene(); if (!drawScene.DrawRenderTag(delegate->GetRenderIndex().GetRenderTag(GetId()))) { _HideAllDrawItems(reprToken); - *dirtyBits &= ~( HdChangeTracker::DirtyRenderTag + *dirtyBits &= ~( + HdChangeTracker::DirtyRenderTag #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND - | HdChangeTracker::DirtyVisibility + | HdChangeTracker::DirtyVisibility #endif - ); + ); return; } - MProfilingScope profilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorC_L2, _rprimId.asChar(), "HdVP2Mesh::Sync"); + MProfilingScope profilingScope( + HdVP2RenderDelegate::sProfilerCategory, + MProfiler::kColorC_L2, + _rprimId.asChar(), + "HdVP2Mesh::Sync"); const SdfPath& id = GetId(); if (*dirtyBits & HdChangeTracker::DirtyMaterialId) { - _SetMaterialId(delegate->GetRenderIndex().GetChangeTracker(), - delegate->GetMaterialId(id)); + _SetMaterialId(delegate->GetRenderIndex().GetChangeTracker(), delegate->GetMaterialId(id)); } - if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->normals) || - HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->primvar)) { + if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->normals) + || HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->primvar)) { const HdVP2Material* material = static_cast( - delegate->GetRenderIndex().GetSprim( - HdPrimTypeTokens->material, GetMaterialId()) - ); + delegate->GetRenderIndex().GetSprim(HdPrimTypeTokens->material, GetMaterialId())); - const TfTokenVector& requiredPrimvars = - material && material->GetSurfaceShader() ? - material->GetRequiredPrimvars() : sFallbackShaderPrimvars; + const TfTokenVector& requiredPrimvars = material && material->GetSurfaceShader() + ? material->GetRequiredPrimvars() + : sFallbackShaderPrimvars; _UpdatePrimvarSources(delegate, *dirtyBits, requiredPrimvars); } @@ -381,8 +396,8 @@ void HdVP2Mesh::Sync( _meshSharedData._topology = GetMeshTopology(delegate); const HdMeshTopology& topology = _meshSharedData._topology; - const VtIntArray& faceVertexIndices = topology.GetFaceVertexIndices(); - const size_t numFaceVertexIndices = faceVertexIndices.size(); + const VtIntArray& faceVertexIndices = topology.GetFaceVertexIndices(); + const size_t numFaceVertexIndices = faceVertexIndices.size(); VtIntArray newFaceVertexIndices; newFaceVertexIndices.resize(numFaceVertexIndices); @@ -398,8 +413,7 @@ void HdVP2Mesh::Sync( // with _renderingToSceneFaceVtxIds, so in case we change the array we // should update _FillPrimvarData() code to remap indices correctly. std::iota(newFaceVertexIndices.begin(), newFaceVertexIndices.end(), 0); - } - else { + } else { _meshSharedData._numVertices = topology.GetNumPoints(); _meshSharedData._renderingToSceneFaceVtxIds.clear(); @@ -440,28 +454,36 @@ void HdVP2Mesh::Sync( _meshSharedData._points = value.Get(); const HdMeshTopology& topology = _meshSharedData._topology; - const size_t numVertices = _meshSharedData._numVertices; + const size_t numVertices = _meshSharedData._numVertices; void* bufferData = _meshSharedData._positionsBuffer->acquire(numVertices, true); if (bufferData) { - _FillPrimvarData(static_cast(bufferData), - numVertices, 0, _meshSharedData._renderingToSceneFaceVtxIds, - _rprimId, topology, - HdTokens->points, _meshSharedData._points, HdInterpolationVertex); + _FillPrimvarData( + static_cast(bufferData), + numVertices, + 0, + _meshSharedData._renderingToSceneFaceVtxIds, + _rprimId, + topology, + HdTokens->points, + _meshSharedData._points, + HdInterpolationVertex); // Capture class member for lambda - MHWRender::MVertexBuffer* const positionsBuffer = - _meshSharedData._positionsBuffer.get(); + MHWRender::MVertexBuffer* const positionsBuffer + = _meshSharedData._positionsBuffer.get(); const MString& rprimId = _rprimId; _delegate->GetVP2ResourceRegistry().EnqueueCommit( [positionsBuffer, bufferData, rprimId]() { - MProfilingScope profilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorC_L2, rprimId.asChar(), "CommitPositions"); + MProfilingScope profilingScope( + HdVP2RenderDelegate::sProfilerCategory, + MProfiler::kColorC_L2, + rprimId.asChar(), + "CommitPositions"); positionsBuffer->commit(bufferData); - } - ); + }); } } @@ -477,11 +499,12 @@ void HdVP2Mesh::Sync( _sharedData.visible = delegate->GetVisible(id); } - if (*dirtyBits & (HdChangeTracker::DirtyRenderTag + if (*dirtyBits + & (HdChangeTracker::DirtyRenderTag #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND - |HdChangeTracker::DirtyVisibility + | HdChangeTracker::DirtyVisibility #endif - )) { + )) { _meshSharedData._renderTag = delegate->GetRenderTag(id); } @@ -496,17 +519,11 @@ void HdVP2Mesh::Sync( */ HdDirtyBits HdVP2Mesh::GetInitialDirtyBitsMask() const { - constexpr HdDirtyBits bits = - HdChangeTracker::InitRepr | - HdChangeTracker::DirtyPoints | - HdChangeTracker::DirtyTopology | - HdChangeTracker::DirtyTransform | - HdChangeTracker::DirtyMaterialId | - HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyVisibility | - HdChangeTracker::DirtyInstanceIndex | - HdChangeTracker::DirtyRenderTag | - DirtySelectionHighlight; + constexpr HdDirtyBits bits = HdChangeTracker::InitRepr | HdChangeTracker::DirtyPoints + | HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyTransform + | HdChangeTracker::DirtyMaterialId | HdChangeTracker::DirtyPrimvar + | HdChangeTracker::DirtyVisibility | HdChangeTracker::DirtyInstanceIndex + | HdChangeTracker::DirtyRenderTag | DirtySelectionHighlight; return bits; } @@ -524,47 +541,40 @@ HdDirtyBits HdVP2Mesh::GetInitialDirtyBitsMask() const See HdRprim::PropagateRprimDirtyBits() */ -HdDirtyBits HdVP2Mesh::_PropagateDirtyBits(HdDirtyBits bits) const { +HdDirtyBits HdVP2Mesh::_PropagateDirtyBits(HdDirtyBits bits) const +{ // If subdiv tags are dirty, topology needs to be recomputed. // The latter implies we'll need to recompute all primvar data. // Any data fetched by the scene delegate should be marked dirty here. if (bits & HdChangeTracker::DirtySubdivTags) { - bits |= (HdChangeTracker::DirtyPoints | - HdChangeTracker::DirtyNormals | - HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyTopology | - HdChangeTracker::DirtyDisplayStyle); - } - else if (bits & HdChangeTracker::DirtyTopology) { + bits + |= (HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyNormals + | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyTopology + | HdChangeTracker::DirtyDisplayStyle); + } else if (bits & HdChangeTracker::DirtyTopology) { // Unlike basis curves, we always request refineLevel when topology is // dirty - bits |= HdChangeTracker::DirtySubdivTags | - HdChangeTracker::DirtyDisplayStyle; + bits |= HdChangeTracker::DirtySubdivTags | HdChangeTracker::DirtyDisplayStyle; } // A change of material means that the Quadrangulate state may have // changed. if (bits & HdChangeTracker::DirtyMaterialId) { - bits |= (HdChangeTracker::DirtyPoints | - HdChangeTracker::DirtyNormals | - HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyTopology); + bits + |= (HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyNormals + | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyTopology); } // If points, display style, or topology changed, recompute normals. - if (bits & (HdChangeTracker::DirtyPoints | - HdChangeTracker::DirtyDisplayStyle | - HdChangeTracker::DirtyTopology)) { - bits |= _customDirtyBitsInUse & - (DirtySmoothNormals | DirtyFlatNormals); + if (bits + & (HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyDisplayStyle + | HdChangeTracker::DirtyTopology)) { + bits |= _customDirtyBitsInUse & (DirtySmoothNormals | DirtyFlatNormals); } // If the topology is dirty, recompute custom indices resources. if (bits & HdChangeTracker::DirtyTopology) { - bits |= _customDirtyBitsInUse & - (DirtyIndices | - DirtyHullIndices | - DirtyPointsIndices); + bits |= _customDirtyBitsInUse & (DirtyIndices | DirtyHullIndices | DirtyPointsIndices); } // If normals are dirty and we are doing CPU normals @@ -584,14 +594,13 @@ HdDirtyBits HdVP2Mesh::_PropagateDirtyBits(HdDirtyBits bits) const { // Propagate dirty bits to all draw items. for (const std::pair& pair : _reprs) { const HdReprSharedPtr& repr = pair.second; - const auto& items = repr->GetDrawItems(); + const auto& items = repr->GetDrawItems(); #if HD_API_VERSION < 35 for (HdDrawItem* item : items) { if (HdVP2DrawItem* drawItem = static_cast(item)) { #else - for (const HdRepr::DrawItemUniquePtr &item : items) { - if (HdVP2DrawItem* const drawItem = - static_cast(item.get())) { + for (const HdRepr::DrawItemUniquePtr& item : items) { + if (HdVP2DrawItem* const drawItem = static_cast(item.get())) { #endif drawItem->SetDirtyBits(bits); } @@ -618,8 +627,9 @@ HdDirtyBits HdVP2Mesh::_PropagateDirtyBits(HdDirtyBits bits) const { See HdRprim::InitRepr() */ -void HdVP2Mesh::_InitRepr(const TfToken& reprToken, HdDirtyBits* dirtyBits) { - auto* const param = static_cast(_delegate->GetRenderParam()); +void HdVP2Mesh::_InitRepr(const TfToken& reprToken, HdDirtyBits* dirtyBits) +{ + auto* const param = static_cast(_delegate->GetRenderParam()); MSubSceneContainer* subSceneContainer = param->GetContainer(); if (ARCH_UNLIKELY(!subSceneContainer)) return; @@ -627,13 +637,12 @@ void HdVP2Mesh::_InitRepr(const TfToken& reprToken, HdDirtyBits* dirtyBits) { // Update selection state on demand or when it is a new Rprim. DirtySelection // will be propagated to all draw items, to trigger sync for each repr. if (reprToken == HdVP2ReprTokens->selection || _reprs.empty()) { - const HdVP2SelectionStatus selectionStatus = - param->GetDrawScene().GetSelectionStatus(GetId()); + const HdVP2SelectionStatus selectionStatus + = param->GetDrawScene().GetSelectionStatus(GetId()); if (_selectionStatus != selectionStatus) { _selectionStatus = selectionStatus; *dirtyBits |= DirtySelection; - } - else if (_selectionStatus == kPartiallySelected) { + } else if (_selectionStatus == kPartiallySelected) { *dirtyBits |= DirtySelection; } @@ -645,18 +654,17 @@ void HdVP2Mesh::_InitRepr(const TfToken& reprToken, HdDirtyBits* dirtyBits) { // If the repr has any draw item with the DirtySelection bit, mark the // DirtySelectionHighlight bit to invoke the synchronization call. - _ReprVector::iterator it = std::find_if( - _reprs.begin(), _reprs.end(), _ReprComparator(reprToken)); + _ReprVector::iterator it + = std::find_if(_reprs.begin(), _reprs.end(), _ReprComparator(reprToken)); if (it != _reprs.end()) { const HdReprSharedPtr& repr = it->second; - const auto& items = repr->GetDrawItems(); + const auto& items = repr->GetDrawItems(); #if HD_API_VERSION < 35 for (const HdDrawItem* item : items) { const HdVP2DrawItem* drawItem = static_cast(item); #else - for (const HdRepr::DrawItemUniquePtr &item : items) { - const HdVP2DrawItem* const drawItem = - static_cast(item.get()); + for (const HdRepr::DrawItemUniquePtr& item : items) { + const HdVP2DrawItem* const drawItem = static_cast(item.get()); #endif if (drawItem && (drawItem->GetDirtyBits() & DirtySelection)) { *dirtyBits |= DirtySelectionHighlight; @@ -687,8 +695,8 @@ void HdVP2Mesh::_InitRepr(const TfToken& reprToken, HdDirtyBits* dirtyBits) { #if HD_API_VERSION < 35 auto* drawItem = new HdVP2DrawItem(_delegate, &_sharedData); #else - std::unique_ptr drawItem = - std::make_unique(_delegate, &_sharedData); + std::unique_ptr drawItem + = std::make_unique(_delegate, &_sharedData); #endif const MString& renderItemName = drawItem->GetRenderItemName(); @@ -696,9 +704,7 @@ void HdVP2Mesh::_InitRepr(const TfToken& reprToken, HdDirtyBits* dirtyBits) { MHWRender::MRenderItem* renderItem = nullptr; switch (desc.geomStyle) { - case HdMeshGeomStyleHull: - renderItem = _CreateSmoothHullRenderItem(renderItemName); - break; + case HdMeshGeomStyleHull: renderItem = _CreateSmoothHullRenderItem(renderItemName); break; case HdMeshGeomStyleHullEdgeOnly: // The smoothHull repr uses the wireframe item for selection // highlight only. @@ -717,12 +723,8 @@ void HdVP2Mesh::_InitRepr(const TfToken& reprToken, HdDirtyBits* dirtyBits) { drawItem->AddUsage(HdVP2DrawItem::kSelectionHighlight); } break; - case HdMeshGeomStylePoints: - renderItem = _CreatePointsRenderItem(renderItemName); - break; - default: - TF_WARN("Unsupported geomStyle"); - break; + case HdMeshGeomStylePoints: renderItem = _CreatePointsRenderItem(renderItemName); break; + default: TF_WARN("Unsupported geomStyle"); break; } if (renderItem) { @@ -731,10 +733,7 @@ void HdVP2Mesh::_InitRepr(const TfToken& reprToken, HdDirtyBits* dirtyBits) { drawItem->SetRenderItem(renderItem); _delegate->GetVP2ResourceRegistry().EnqueueCommit( - [subSceneContainer, renderItem]() { - subSceneContainer->add(renderItem); - } - ); + [subSceneContainer, renderItem]() { subSceneContainer->add(renderItem); }); } if (desc.geomStyle == HdMeshGeomStyleHull) { @@ -743,8 +742,7 @@ void HdVP2Mesh::_InitRepr(const TfToken& reprToken, HdDirtyBits* dirtyBits) { _customDirtyBitsInUse |= DirtyFlatNormals; *dirtyBits |= DirtyFlatNormals; } - } - else { + } else { if (!(_customDirtyBitsInUse & DirtySmoothNormals)) { _customDirtyBitsInUse |= DirtySmoothNormals; *dirtyBits |= DirtySmoothNormals; @@ -765,9 +763,9 @@ void HdVP2Mesh::_InitRepr(const TfToken& reprToken, HdDirtyBits* dirtyBits) { Repr objects are created to support specific reprName tokens, and contain a list of HdVP2DrawItems and corresponding RenderItems. */ -void HdVP2Mesh::_UpdateRepr(HdSceneDelegate *sceneDelegate, const TfToken& reprToken) +void HdVP2Mesh::_UpdateRepr(HdSceneDelegate* sceneDelegate, const TfToken& reprToken) { - HdReprSharedPtr const &curRepr = _GetRepr(reprToken); + HdReprSharedPtr const& curRepr = _GetRepr(reprToken); if (!curRepr) { return; } @@ -784,8 +782,7 @@ void HdVP2Mesh::_UpdateRepr(HdSceneDelegate *sceneDelegate, const TfToken& reprT if (desc.geomStyle == HdMeshGeomStyleHull) { if (desc.flatShadingEnabled) { requireFlatNormals = true; - } - else { + } else { requireSmoothNormals = true; } } @@ -794,16 +791,15 @@ void HdVP2Mesh::_UpdateRepr(HdSceneDelegate *sceneDelegate, const TfToken& reprT // For each relevant draw item, update dirty buffer sources. int drawItemIndex = 0; for (size_t descIdx = 0; descIdx < reprDescs.size(); ++descIdx) { - const HdMeshReprDesc &desc = reprDescs[descIdx]; + const HdMeshReprDesc& desc = reprDescs[descIdx]; if (desc.geomStyle == HdMeshGeomStyleInvalid) { continue; } - auto* drawItem = static_cast( - curRepr->GetDrawItem(drawItemIndex++)); + auto* drawItem = static_cast(curRepr->GetDrawItem(drawItemIndex++)); if (drawItem) { - _UpdateDrawItem(sceneDelegate, drawItem, desc, - requireSmoothNormals, requireFlatNormals); + _UpdateDrawItem( + sceneDelegate, drawItem, desc, requireSmoothNormals, requireFlatNormals); } } } @@ -814,11 +810,11 @@ void HdVP2Mesh::_UpdateRepr(HdSceneDelegate *sceneDelegate, const TfToken& reprT in CommitState and enqueued for Commit on main-thread using CommitTasks */ void HdVP2Mesh::_UpdateDrawItem( - HdSceneDelegate* sceneDelegate, - HdVP2DrawItem* drawItem, + HdSceneDelegate* sceneDelegate, + HdVP2DrawItem* drawItem, const HdMeshReprDesc& desc, - bool requireSmoothNormals, - bool requireFlatNormals) + bool requireSmoothNormals, + bool requireFlatNormals) { const MHWRender::MRenderItem* renderItem = drawItem->GetRenderItem(); if (ARCH_UNLIKELY(!renderItem)) { @@ -830,35 +826,32 @@ void HdVP2Mesh::_UpdateDrawItem( // We don't need to update the dedicated selection highlight item when there // is no selection highlight change and the mesh is not selected. Draw item // has its own dirty bits, so update will be done when it shows in viewport. - const bool isDedicatedSelectionHighlightItem = - drawItem->MatchesUsage(HdVP2DrawItem::kSelectionHighlight); - if (isDedicatedSelectionHighlightItem && - ((itemDirtyBits & DirtySelectionHighlight) == 0) && - (_selectionStatus == kUnselected)) { + const bool isDedicatedSelectionHighlightItem + = drawItem->MatchesUsage(HdVP2DrawItem::kSelectionHighlight); + if (isDedicatedSelectionHighlightItem && ((itemDirtyBits & DirtySelectionHighlight) == 0) + && (_selectionStatus == kUnselected)) { return; } - CommitState stateToCommit(*drawItem); + CommitState stateToCommit(*drawItem); HdVP2DrawItem::RenderItemData& drawItemData = stateToCommit._drawItemData; const SdfPath& id = GetId(); - auto* const param = static_cast(_delegate->GetRenderParam()); + auto* const param = static_cast(_delegate->GetRenderParam()); ProxyRenderDelegate& drawScene = param->GetDrawScene(); const HdRenderIndex& renderIndex = sceneDelegate->GetRenderIndex(); const HdMeshTopology& topology = _meshSharedData._topology; - const auto& primvarSourceMap = _meshSharedData._primvarSourceMap; - const size_t numVertices = _meshSharedData._numVertices; + const auto& primvarSourceMap = _meshSharedData._primvarSourceMap; + const size_t numVertices = _meshSharedData._numVertices; // The bounding box item uses a globally-shared geometry data therefore it // doesn't need to extract index data from topology. Points use non-indexed // draw. - const bool isBBoxItem = - (renderItem->drawMode() == MHWRender::MGeometry::kBoundingBox); - const bool isPointSnappingItem = - (renderItem->primitive() == MHWRender::MGeometry::kPoints); + const bool isBBoxItem = (renderItem->drawMode() == MHWRender::MGeometry::kBoundingBox); + const bool isPointSnappingItem = (renderItem->primitive() == MHWRender::MGeometry::kPoints); const bool requiresIndexUpdate = !isBBoxItem && !isPointSnappingItem; // Prepare index buffer. @@ -866,23 +859,25 @@ void HdVP2Mesh::_UpdateDrawItem( const HdMeshTopology& topologyToUse = _meshSharedData._renderingTopology; if (desc.geomStyle == HdMeshGeomStyleHull) { - HdMeshUtil meshUtil(&topologyToUse, id); + HdMeshUtil meshUtil(&topologyToUse, id); VtVec3iArray trianglesFaceVertexIndices; - VtIntArray primitiveParam; + VtIntArray primitiveParam; meshUtil.ComputeTriangleIndices(&trianglesFaceVertexIndices, &primitiveParam, nullptr); const int numIndex = trianglesFaceVertexIndices.size() * 3; - stateToCommit._indexBufferData = static_cast( - drawItemData._indexBuffer->acquire(numIndex, true)); + stateToCommit._indexBufferData + = static_cast(drawItemData._indexBuffer->acquire(numIndex, true)); - memcpy(stateToCommit._indexBufferData, trianglesFaceVertexIndices.data(), numIndex * sizeof(int)); - } - else if (desc.geomStyle == HdMeshGeomStyleHullEdgeOnly) { + memcpy( + stateToCommit._indexBufferData, + trianglesFaceVertexIndices.data(), + numIndex * sizeof(int)); + } else if (desc.geomStyle == HdMeshGeomStyleHullEdgeOnly) { unsigned int numIndex = _GetNumOfEdgeIndices(topologyToUse); - stateToCommit._indexBufferData = static_cast( - drawItemData._indexBuffer->acquire(numIndex, true)); + stateToCommit._indexBufferData + = static_cast(drawItemData._indexBuffer->acquire(numIndex, true)); _FillEdgeIndices(stateToCommit._indexBufferData, topologyToUse); } @@ -890,7 +885,7 @@ void HdVP2Mesh::_UpdateDrawItem( if (desc.geomStyle == HdMeshGeomStyleHull) { // Prepare normal buffer. - VtVec3fArray normals; + VtVec3fArray normals; HdInterpolation interp = HdInterpolationConstant; const auto it = primvarSourceMap.find(HdTokens->normals); @@ -909,23 +904,20 @@ void HdVP2Mesh::_UpdateDrawItem( // have a custom dirty bit to determine whether update is needed. if (!normals.empty()) { prepareNormals = ((itemDirtyBits & HdChangeTracker::DirtyNormals) != 0); - } - else if (requireSmoothNormals && (itemDirtyBits & DirtySmoothNormals)) { + } else if (requireSmoothNormals && (itemDirtyBits & DirtySmoothNormals)) { // note: normals gets dirty when points are marked as dirty, // at change tracker. // HdC_TODO: move the normals computation to GPU to save expensive // computation and buffer transfer. Hd_VertexAdjacencySharedPtr adjacency(new Hd_VertexAdjacency()); - HdBufferSourceSharedPtr adjacencyComputation = - adjacency->GetSharedAdjacencyBuilderComputation(&topology); + HdBufferSourceSharedPtr adjacencyComputation + = adjacency->GetSharedAdjacencyBuilderComputation(&topology); adjacencyComputation->Resolve(); // IS the adjacency updated now? // Only the points referenced by the topology are used to compute // smooth normals. normals = Hd_SmoothNormals::ComputeSmoothNormals( - adjacency.get(), - _meshSharedData._points.size(), - _meshSharedData._points.cdata()); + adjacency.get(), _meshSharedData._points.size(), _meshSharedData._points.cdata()); interp = HdInterpolationVertex; @@ -934,20 +926,24 @@ void HdVP2Mesh::_UpdateDrawItem( if (prepareNormals) { if (!drawItemData._normalsBuffer) { - const MHWRender::MVertexBufferDescriptor vbDesc("", - MHWRender::MGeometry::kNormal, - MHWRender::MGeometry::kFloat, - 3); + const MHWRender::MVertexBufferDescriptor vbDesc( + "", MHWRender::MGeometry::kNormal, MHWRender::MGeometry::kFloat, 3); - drawItemData._normalsBuffer.reset( - new MHWRender::MVertexBuffer(vbDesc)); + drawItemData._normalsBuffer.reset(new MHWRender::MVertexBuffer(vbDesc)); } void* bufferData = drawItemData._normalsBuffer->acquire(numVertices, true); if (bufferData) { - _FillPrimvarData(static_cast(bufferData), - numVertices, 0, _meshSharedData._renderingToSceneFaceVtxIds, - _rprimId, topology, HdTokens->normals, normals, interp); + _FillPrimvarData( + static_cast(bufferData), + numVertices, + 0, + _meshSharedData._renderingToSceneFaceVtxIds, + _rprimId, + topology, + HdTokens->normals, + normals, + interp); stateToCommit._normalsBufferData = bufferData; } @@ -956,8 +952,7 @@ void HdVP2Mesh::_UpdateDrawItem( // Prepare color buffer. if ((itemDirtyBits & HdChangeTracker::DirtyMaterialId) != 0) { const HdVP2Material* material = static_cast( - renderIndex.GetSprim(HdPrimTypeTokens->material, GetMaterialId()) - ); + renderIndex.GetSprim(HdPrimTypeTokens->material, GetMaterialId())); if (material) { MHWRender::MShaderInstance* shader = material->GetSurfaceShader(); @@ -972,9 +967,8 @@ void HdVP2Mesh::_UpdateDrawItem( auto itColor = primvarSourceMap.find(HdTokens->displayColor); auto itOpacity = primvarSourceMap.find(HdTokens->displayOpacity); - if (((itemDirtyBits & HdChangeTracker::DirtyPrimvar) != 0) && - (itColor != primvarSourceMap.end() || - itOpacity != primvarSourceMap.end())) { + if (((itemDirtyBits & HdChangeTracker::DirtyPrimvar) != 0) + && (itColor != primvarSourceMap.end() || itOpacity != primvarSourceMap.end())) { VtVec3fArray colorArray; VtFloatArray alphaArray; @@ -1035,27 +1029,37 @@ void HdVP2Mesh::_UpdateDrawItem( if (prepareCPVBuffer) { if (!drawItemData._colorBuffer) { - const MHWRender::MVertexBufferDescriptor vbDesc("", - MHWRender::MGeometry::kColor, - MHWRender::MGeometry::kFloat, - 4); + const MHWRender::MVertexBufferDescriptor vbDesc( + "", MHWRender::MGeometry::kColor, MHWRender::MGeometry::kFloat, 4); - drawItemData._colorBuffer.reset( - new MHWRender::MVertexBuffer(vbDesc)); + drawItemData._colorBuffer.reset(new MHWRender::MVertexBuffer(vbDesc)); } - void* bufferData = - drawItemData._colorBuffer->acquire(numVertices, true); + void* bufferData = drawItemData._colorBuffer->acquire(numVertices, true); // Fill color and opacity into the float4 color stream. if (bufferData) { - _FillPrimvarData(static_cast(bufferData), - numVertices, 0, _meshSharedData._renderingToSceneFaceVtxIds, - _rprimId, topology, HdTokens->displayColor, colorArray, colorInterp); - - _FillPrimvarData(static_cast(bufferData), - numVertices, 3, _meshSharedData._renderingToSceneFaceVtxIds, - _rprimId, topology, HdTokens->displayOpacity, alphaArray, alphaInterp); + _FillPrimvarData( + static_cast(bufferData), + numVertices, + 0, + _meshSharedData._renderingToSceneFaceVtxIds, + _rprimId, + topology, + HdTokens->displayColor, + colorArray, + colorInterp); + + _FillPrimvarData( + static_cast(bufferData), + numVertices, + 3, + _meshSharedData._renderingToSceneFaceVtxIds, + _rprimId, + topology, + HdTokens->displayOpacity, + alphaArray, + alphaInterp); stateToCommit._colorBufferData = bufferData; } @@ -1067,8 +1071,7 @@ void HdVP2Mesh::_UpdateDrawItem( if (!stateToCommit._isTransparent) { if (alphaInterp == HdInterpolationConstant) { stateToCommit._isTransparent = (alphaArray[0] < 0.999f); - } - else { + } else { for (size_t i = 0; i < alphaArray.size(); i++) { if (alphaArray[i] < 0.999f) { stateToCommit._isTransparent = true; @@ -1081,32 +1084,29 @@ void HdVP2Mesh::_UpdateDrawItem( } // Prepare primvar buffers. - if ((desc.geomStyle == HdMeshGeomStyleHull) && - (itemDirtyBits & HdChangeTracker::DirtyPrimvar)) { + if ((desc.geomStyle == HdMeshGeomStyleHull) + && (itemDirtyBits & HdChangeTracker::DirtyPrimvar)) { for (const auto& it : primvarSourceMap) { const TfToken& token = it.first; // Color, opacity and normal have been prepared separately. - if ((token == HdTokens->displayColor) || - (token == HdTokens->displayOpacity) || - (token == HdTokens->normals)) + if ((token == HdTokens->displayColor) || (token == HdTokens->displayOpacity) + || (token == HdTokens->normals)) continue; - const VtValue& value = it.second.data; + const VtValue& value = it.second.data; const HdInterpolation& interp = it.second.interpolation; if (!value.IsArrayValued() || value.GetArraySize() == 0) continue; - MHWRender::MVertexBuffer* buffer = - drawItemData._primvarBuffers[token].get(); + MHWRender::MVertexBuffer* buffer = drawItemData._primvarBuffers[token].get(); void* bufferData = nullptr; if (value.IsHolding()) { if (!buffer) { - const MHWRender::MVertexBufferDescriptor vbDesc("", - MHWRender::MGeometry::kTexture, - MHWRender::MGeometry::kFloat, 1); + const MHWRender::MVertexBufferDescriptor vbDesc( + "", MHWRender::MGeometry::kTexture, MHWRender::MGeometry::kFloat, 1); buffer = new MHWRender::MVertexBuffer(vbDesc); drawItemData._primvarBuffers[token].reset(buffer); @@ -1115,18 +1115,22 @@ void HdVP2Mesh::_UpdateDrawItem( if (buffer) { bufferData = buffer->acquire(numVertices, true); if (bufferData) { - _FillPrimvarData(static_cast(bufferData), - numVertices, 0, _meshSharedData._renderingToSceneFaceVtxIds, - _rprimId, topology, - token, value.UncheckedGet(), interp); + _FillPrimvarData( + static_cast(bufferData), + numVertices, + 0, + _meshSharedData._renderingToSceneFaceVtxIds, + _rprimId, + topology, + token, + value.UncheckedGet(), + interp); } } - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { if (!buffer) { - const MHWRender::MVertexBufferDescriptor vbDesc("", - MHWRender::MGeometry::kTexture, - MHWRender::MGeometry::kFloat, 2); + const MHWRender::MVertexBufferDescriptor vbDesc( + "", MHWRender::MGeometry::kTexture, MHWRender::MGeometry::kFloat, 2); buffer = new MHWRender::MVertexBuffer(vbDesc); drawItemData._primvarBuffers[token].reset(buffer); @@ -1135,18 +1139,22 @@ void HdVP2Mesh::_UpdateDrawItem( if (buffer) { bufferData = buffer->acquire(numVertices, true); if (bufferData) { - _FillPrimvarData(static_cast(bufferData), - numVertices, 0, _meshSharedData._renderingToSceneFaceVtxIds, - _rprimId, topology, - token, value.UncheckedGet(), interp); + _FillPrimvarData( + static_cast(bufferData), + numVertices, + 0, + _meshSharedData._renderingToSceneFaceVtxIds, + _rprimId, + topology, + token, + value.UncheckedGet(), + interp); } } - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { if (!buffer) { - const MHWRender::MVertexBufferDescriptor vbDesc("", - MHWRender::MGeometry::kTexture, - MHWRender::MGeometry::kFloat, 3); + const MHWRender::MVertexBufferDescriptor vbDesc( + "", MHWRender::MGeometry::kTexture, MHWRender::MGeometry::kFloat, 3); buffer = new MHWRender::MVertexBuffer(vbDesc); drawItemData._primvarBuffers[token].reset(buffer); @@ -1155,18 +1163,22 @@ void HdVP2Mesh::_UpdateDrawItem( if (buffer) { bufferData = buffer->acquire(numVertices, true); if (bufferData) { - _FillPrimvarData(static_cast(bufferData), - numVertices, 0, _meshSharedData._renderingToSceneFaceVtxIds, - _rprimId, topology, - token, value.UncheckedGet(), interp); + _FillPrimvarData( + static_cast(bufferData), + numVertices, + 0, + _meshSharedData._renderingToSceneFaceVtxIds, + _rprimId, + topology, + token, + value.UncheckedGet(), + interp); } } - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { if (!buffer) { - const MHWRender::MVertexBufferDescriptor vbDesc("", - MHWRender::MGeometry::kTexture, - MHWRender::MGeometry::kFloat, 4); + const MHWRender::MVertexBufferDescriptor vbDesc( + "", MHWRender::MGeometry::kTexture, MHWRender::MGeometry::kFloat, 4); buffer = new MHWRender::MVertexBuffer(vbDesc); drawItemData._primvarBuffers[token].reset(buffer); @@ -1175,14 +1187,19 @@ void HdVP2Mesh::_UpdateDrawItem( if (buffer) { bufferData = buffer->acquire(numVertices, true); if (bufferData) { - _FillPrimvarData(static_cast(bufferData), - numVertices, 0, _meshSharedData._renderingToSceneFaceVtxIds, - _rprimId, topology, - token, value.UncheckedGet(), interp); + _FillPrimvarData( + static_cast(bufferData), + numVertices, + 0, + _meshSharedData._renderingToSceneFaceVtxIds, + _rprimId, + topology, + token, + value.UncheckedGet(), + interp); } } - } - else { + } else { TF_WARN("Unsupported primvar array"); } @@ -1197,20 +1214,20 @@ void HdVP2Mesh::_UpdateDrawItem( // which is expensive, so it is updated only when it gets expanded in order // to reduce calling frequence. if (itemDirtyBits & HdChangeTracker::DirtyExtent) { - const GfRange3d& rangeToUse = isBBoxItem ? - _delegate->GetSharedBBoxGeom().GetRange() : range; + const GfRange3d& rangeToUse + = isBBoxItem ? _delegate->GetSharedBBoxGeom().GetRange() : range; bool boundingBoxExpanded = false; const GfVec3d& min = rangeToUse.GetMin(); - const MPoint pntMin(min[0], min[1], min[2]); + const MPoint pntMin(min[0], min[1], min[2]); if (!drawItemData._boundingBox.contains(pntMin)) { drawItemData._boundingBox.expand(pntMin); boundingBoxExpanded = true; } const GfVec3d& max = rangeToUse.GetMax(); - const MPoint pntMax(max[0], max[1], max[2]); + const MPoint pntMax(max[0], max[1], max[2]); if (!drawItemData._boundingBox.contains(pntMax)) { drawItemData._boundingBox.expand(pntMax); boundingBoxExpanded = true; @@ -1228,8 +1245,8 @@ void HdVP2Mesh::_UpdateDrawItem( // The bounding box draw item uses a globally-shared unit wire cube as the // geometry and transfers scale and offset of the bounds to world matrix. if (isBBoxItem) { - if ((itemDirtyBits & (HdChangeTracker::DirtyExtent | HdChangeTracker::DirtyTransform)) && - !range.IsEmpty()) { + if ((itemDirtyBits & (HdChangeTracker::DirtyExtent | HdChangeTracker::DirtyTransform)) + && !range.IsEmpty()) { const GfVec3d midpoint = range.GetMidpoint(); const GfVec3d size = range.GetSize(); @@ -1237,15 +1254,26 @@ void HdVP2Mesh::_UpdateDrawItem( midp *= worldMatrix; auto& m = worldMatrix.matrix; - m[0][0] *= size[0]; m[0][1] *= size[0]; m[0][2] *= size[0]; m[0][3] *= size[0]; - m[1][0] *= size[1]; m[1][1] *= size[1]; m[1][2] *= size[1]; m[1][3] *= size[1]; - m[2][0] *= size[2]; m[2][1] *= size[2]; m[2][2] *= size[2]; m[2][3] *= size[2]; - m[3][0] = midp[0]; m[3][1] = midp[1]; m[3][2] = midp[2]; m[3][3] = midp[3]; + m[0][0] *= size[0]; + m[0][1] *= size[0]; + m[0][2] *= size[0]; + m[0][3] *= size[0]; + m[1][0] *= size[1]; + m[1][1] *= size[1]; + m[1][2] *= size[1]; + m[1][3] *= size[1]; + m[2][0] *= size[2]; + m[2][1] *= size[2]; + m[2][2] *= size[2]; + m[2][3] *= size[2]; + m[3][0] = midp[0]; + m[3][1] = midp[1]; + m[3][2] = midp[2]; + m[3][3] = midp[3]; stateToCommit._worldMatrix = &drawItemData._worldMatrix; } - } - else if (itemDirtyBits & HdChangeTracker::DirtyTransform) { + } else if (itemDirtyBits & HdChangeTracker::DirtyTransform) { stateToCommit._worldMatrix = &drawItemData._worldMatrix; } @@ -1259,27 +1287,25 @@ void HdVP2Mesh::_UpdateDrawItem( if (!GetInstancerId().IsEmpty()) { // Retrieve instance transforms from the instancer. - HdInstancer *instancer = renderIndex.GetInstancer(GetInstancerId()); - VtMatrix4dArray transforms = static_cast(instancer)-> - ComputeInstanceTransforms(id); + HdInstancer* instancer = renderIndex.GetInstancer(GetInstancerId()); + VtMatrix4dArray transforms + = static_cast(instancer)->ComputeInstanceTransforms(id); - MMatrix instanceMatrix; + MMatrix instanceMatrix; const unsigned int instanceCount = transforms.size(); if (0 == instanceCount) { instancerWithNoInstances = true; - } - else if (!drawItem->ContainsUsage(HdVP2DrawItem::kSelectionHighlight)) { + } else if (!drawItem->ContainsUsage(HdVP2DrawItem::kSelectionHighlight)) { stateToCommit._instanceTransforms.setLength(instanceCount); for (unsigned int i = 0; i < instanceCount; ++i) { transforms[i].Get(instanceMatrix.matrix); stateToCommit._instanceTransforms[i] = worldMatrix * instanceMatrix; } - } - else if (_selectionStatus == kFullyLead || _selectionStatus == kFullyActive) { - const bool lead = (_selectionStatus == kFullyLead); + } else if (_selectionStatus == kFullyLead || _selectionStatus == kFullyActive) { + const bool lead = (_selectionStatus == kFullyLead); const MColor& color = drawScene.GetSelectionHighlightColor(lead); - unsigned int offset = 0; + unsigned int offset = 0; stateToCommit._instanceTransforms.setLength(instanceCount); stateToCommit._instanceColors.setLength(instanceCount * kNumColorChannels); @@ -1292,13 +1318,10 @@ void HdVP2Mesh::_UpdateDrawItem( stateToCommit._instanceColors[offset++] = color[j]; } } - } - else { - const MColor colors[] = { - drawScene.GetWireframeColor(), - drawScene.GetSelectionHighlightColor(false), - drawScene.GetSelectionHighlightColor(true) - }; + } else { + const MColor colors[] = { drawScene.GetWireframeColor(), + drawScene.GetSelectionHighlightColor(false), + drawScene.GetSelectionHighlightColor(true) }; // Store the indices to colors. std::vector colorIndices; @@ -1340,14 +1363,14 @@ void HdVP2Mesh::_UpdateDrawItem( } } } - } - else { + } else { // Non-instanced Rprims. - if ((itemDirtyBits & DirtySelectionHighlight) && - drawItem->ContainsUsage(HdVP2DrawItem::kSelectionHighlight)) { - const MColor& color = (_selectionStatus != kUnselected ? - drawScene.GetSelectionHighlightColor(_selectionStatus == kFullyLead) : - drawScene.GetWireframeColor()); + if ((itemDirtyBits & DirtySelectionHighlight) + && drawItem->ContainsUsage(HdVP2DrawItem::kSelectionHighlight)) { + const MColor& color + = (_selectionStatus != kUnselected + ? drawScene.GetSelectionHighlightColor(_selectionStatus == kFullyLead) + : drawScene.GetWireframeColor()); MHWRender::MShaderInstance* shader = _delegate->Get3dSolidShader(color); if (shader != nullptr && shader != drawItemData._shader) { @@ -1359,13 +1382,13 @@ void HdVP2Mesh::_UpdateDrawItem( } // Determine if the render item should be enabled or not. - if (!GetInstancerId().IsEmpty() || - (itemDirtyBits & (HdChangeTracker::DirtyVisibility | - HdChangeTracker::DirtyRenderTag | - HdChangeTracker::DirtyPoints | - HdChangeTracker::DirtyExtent | - DirtySelectionHighlight))) { - bool enable = drawItem->GetVisible() && !_meshSharedData._points.empty() && !instancerWithNoInstances; + if (!GetInstancerId().IsEmpty() + || (itemDirtyBits + & (HdChangeTracker::DirtyVisibility | HdChangeTracker::DirtyRenderTag + | HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyExtent + | DirtySelectionHighlight))) { + bool enable = drawItem->GetVisible() && !_meshSharedData._points.empty() + && !instancerWithNoInstances; if (isDedicatedSelectionHighlightItem) { enable = enable && (_selectionStatus != kUnselected); @@ -1383,36 +1406,38 @@ void HdVP2Mesh::_UpdateDrawItem( } } - stateToCommit._geometryDirty = (itemDirtyBits & ( - HdChangeTracker::DirtyPoints | - HdChangeTracker::DirtyNormals | - HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyTopology)); + stateToCommit._geometryDirty + = (itemDirtyBits + & (HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyNormals + | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyTopology)); // Reset dirty bits because we've prepared commit state for this draw item. drawItem->ResetDirtyBits(); // Capture the valid position buffer and index buffer MHWRender::MVertexBuffer* positionsBuffer = _meshSharedData._positionsBuffer.get(); - MHWRender::MIndexBuffer* indexBuffer = drawItemData._indexBuffer.get(); + MHWRender::MIndexBuffer* indexBuffer = drawItemData._indexBuffer.get(); if (isBBoxItem) { const HdVP2BBoxGeom& sharedBBoxGeom = _delegate->GetSharedBBoxGeom(); - positionsBuffer = const_cast( - sharedBBoxGeom.GetPositionBuffer()); - indexBuffer = const_cast( - sharedBBoxGeom.GetIndexBuffer()); + positionsBuffer = const_cast(sharedBBoxGeom.GetPositionBuffer()); + indexBuffer = const_cast(sharedBBoxGeom.GetIndexBuffer()); } - _delegate->GetVP2ResourceRegistry().EnqueueCommit( - [drawItem, stateToCommit, param, positionsBuffer, indexBuffer]() - { + _delegate->GetVP2ResourceRegistry().EnqueueCommit([drawItem, + stateToCommit, + param, + positionsBuffer, + indexBuffer]() { MHWRender::MRenderItem* renderItem = drawItem->GetRenderItem(); if (ARCH_UNLIKELY(!renderItem)) return; - MProfilingScope profilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorC_L2, drawItem->GetRenderItemName().asChar(), "Commit"); + MProfilingScope profilingScope( + HdVP2RenderDelegate::sProfilerCategory, + MProfiler::kColorC_L2, + drawItem->GetRenderItemName().asChar(), + "Commit"); const HdVP2DrawItem::RenderItemData& drawItemData = stateToCommit._drawItemData; @@ -1432,7 +1457,7 @@ void HdVP2Mesh::_UpdateDrawItem( // If available, something changed for (const auto& entry : stateToCommit._primvarBufferDataMap) { const TfToken& primvarName = entry.first; - void* primvarBufferData = entry.second; + void* primvarBufferData = entry.second; if (primvarBufferData) { const auto it = primvarBuffers.find(primvarName); if (it != primvarBuffers.end()) { @@ -1472,7 +1497,7 @@ void HdVP2Mesh::_UpdateDrawItem( vertexBuffers.addBuffer(kNormalsStr, normalsBuffer); for (auto& entry : primvarBuffers) { - const TfToken& primvarName = entry.first; + const TfToken& primvarName = entry.first; MHWRender::MVertexBuffer* primvarBuffer = entry.second.get(); if (primvarBuffer) { vertexBuffers.addBuffer(primvarName.GetText(), primvarBuffer); @@ -1483,13 +1508,13 @@ void HdVP2Mesh::_UpdateDrawItem( // - Associate geometric buffers with the render item. // - Update bounding box. // - Trigger consolidation/instancing update. - drawScene.setGeometryForRenderItem(*renderItem, - vertexBuffers, *indexBuffer, stateToCommit._boundingBox); + drawScene.setGeometryForRenderItem( + *renderItem, vertexBuffers, *indexBuffer, stateToCommit._boundingBox); } // Important, update instance transforms after setting geometry on render items! auto& oldInstanceCount = stateToCommit._drawItemData._instanceCount; - auto newInstanceCount = stateToCommit._instanceTransforms.length(); + auto newInstanceCount = stateToCommit._instanceTransforms.length(); // GPU instancing has been enabled. We cannot switch to consolidation // without recreating render item, so we keep using GPU instancing. @@ -1497,18 +1522,16 @@ void HdVP2Mesh::_UpdateDrawItem( if (oldInstanceCount == newInstanceCount) { for (unsigned int i = 0; i < newInstanceCount; i++) { // VP2 defines instance ID of the first instance to be 1. - drawScene.updateInstanceTransform(*renderItem, - i+1, stateToCommit._instanceTransforms[i]); + drawScene.updateInstanceTransform( + *renderItem, i + 1, stateToCommit._instanceTransforms[i]); } } else { - drawScene.setInstanceTransformArray(*renderItem, - stateToCommit._instanceTransforms); + drawScene.setInstanceTransformArray(*renderItem, stateToCommit._instanceTransforms); } - if (stateToCommit._instanceColors.length() == - newInstanceCount * kNumColorChannels) { - drawScene.setExtraInstanceData(*renderItem, - kSolidColorStr, stateToCommit._instanceColors); + if (stateToCommit._instanceColors.length() == newInstanceCount * kNumColorChannels) { + drawScene.setExtraInstanceData( + *renderItem, kSolidColorStr, stateToCommit._instanceColors); } } #if MAYA_API_VERSION >= 20210000 @@ -1520,22 +1543,18 @@ void HdVP2Mesh::_UpdateDrawItem( // instances, we need to disable consolidation to allow GPU instancing to be used. else if (newInstanceCount == 1) { renderItem->setMatrix(&stateToCommit._instanceTransforms[0]); - } - else if (newInstanceCount > 1) { + } else if (newInstanceCount > 1) { setWantConsolidation(*renderItem, false); #endif - drawScene.setInstanceTransformArray(*renderItem, - stateToCommit._instanceTransforms); + drawScene.setInstanceTransformArray(*renderItem, stateToCommit._instanceTransforms); - if (stateToCommit._instanceColors.length() == - newInstanceCount * kNumColorChannels) { - drawScene.setExtraInstanceData(*renderItem, - kSolidColorStr, stateToCommit._instanceColors); + if (stateToCommit._instanceColors.length() == newInstanceCount * kNumColorChannels) { + drawScene.setExtraInstanceData( + *renderItem, kSolidColorStr, stateToCommit._instanceColors); } stateToCommit._drawItemData._usingInstancedDraw = true; - } - else if (stateToCommit._worldMatrix != nullptr) { + } else if (stateToCommit._worldMatrix != nullptr) { // Regular non-instanced prims. Consolidation has been turned on by // default and will be kept enabled on this case. renderItem->setMatrix(stateToCommit._worldMatrix); @@ -1545,7 +1564,8 @@ void HdVP2Mesh::_UpdateDrawItem( }); } -void HdVP2Mesh::_HideAllDrawItems(const TfToken& reprToken) { +void HdVP2Mesh::_HideAllDrawItems(const TfToken& reprToken) +{ HdReprSharedPtr const& curRepr = _GetRepr(reprToken); if (!curRepr) { return; @@ -1570,9 +1590,8 @@ void HdVP2Mesh::_HideAllDrawItems(const TfToken& reprToken) { drawItem->GetRenderItemData()._enabled = false; - _delegate->GetVP2ResourceRegistry().EnqueueCommit([renderItem]() { - renderItem->enable(false); - }); + _delegate->GetVP2ResourceRegistry().EnqueueCommit( + [renderItem]() { renderItem->enable(false); }); } } @@ -1585,8 +1604,8 @@ void HdVP2Mesh::_HideAllDrawItems(const TfToken& reprToken) { only call GetPrimvar on primvars that have been marked dirty. */ void HdVP2Mesh::_UpdatePrimvarSources( - HdSceneDelegate* sceneDelegate, - HdDirtyBits dirtyBits, + HdSceneDelegate* sceneDelegate, + HdDirtyBits dirtyBits, const TfTokenVector& requiredPrimvars) { const SdfPath& id = GetId(); @@ -1595,18 +1614,16 @@ void HdVP2Mesh::_UpdatePrimvarSources( TfTokenVector::const_iterator end = requiredPrimvars.cend(); for (size_t i = 0; i < HdInterpolationCount; i++) { - const HdInterpolation interp = static_cast(i); - const HdPrimvarDescriptorVector primvars = - GetPrimvarDescriptors(sceneDelegate, interp); + const HdInterpolation interp = static_cast(i); + const HdPrimvarDescriptorVector primvars = GetPrimvarDescriptors(sceneDelegate, interp); - for (const HdPrimvarDescriptor& pv: primvars) { + for (const HdPrimvarDescriptor& pv : primvars) { if (std::find(begin, end, pv.name) != end) { if (HdChangeTracker::IsPrimvarDirty(dirtyBits, id, pv.name)) { const VtValue value = GetPrimvar(sceneDelegate, pv.name); _meshSharedData._primvarSourceMap[pv.name] = { value, interp }; } - } - else { + } else { _meshSharedData._primvarSourceMap.erase(pv.name); } } @@ -1614,14 +1631,11 @@ void HdVP2Mesh::_UpdatePrimvarSources( } /*! \brief Create render item for points repr. -*/ + */ MHWRender::MRenderItem* HdVP2Mesh::_CreatePointsRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( - name, - MHWRender::MRenderItem::DecorationItem, - MHWRender::MGeometry::kPoints - ); + name, MHWRender::MRenderItem::DecorationItem, MHWRender::MGeometry::kPoints); renderItem->setDrawMode(MHWRender::MGeometry::kSelectionOnly); renderItem->castsShadows(false); @@ -1638,15 +1652,11 @@ MHWRender::MRenderItem* HdVP2Mesh::_CreatePointsRenderItem(const MString& name) } /*! \brief Create render item for wireframe repr. -*/ -MHWRender::MRenderItem* HdVP2Mesh::_CreateWireframeRenderItem( - const MString& name) const + */ +MHWRender::MRenderItem* HdVP2Mesh::_CreateWireframeRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( - name, - MHWRender::MRenderItem::DecorationItem, - MHWRender::MGeometry::kLines - ); + name, MHWRender::MRenderItem::DecorationItem, MHWRender::MGeometry::kLines); renderItem->setDrawMode(MHWRender::MGeometry::kWireframe); renderItem->depthPriority(MHWRender::MRenderItem::sDormantWireDepthPriority); @@ -1661,15 +1671,11 @@ MHWRender::MRenderItem* HdVP2Mesh::_CreateWireframeRenderItem( } /*! \brief Create render item for bbox repr. -*/ -MHWRender::MRenderItem* HdVP2Mesh::_CreateBoundingBoxRenderItem( - const MString& name) const + */ +MHWRender::MRenderItem* HdVP2Mesh::_CreateBoundingBoxRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( - name, - MHWRender::MRenderItem::DecorationItem, - MHWRender::MGeometry::kLines - ); + name, MHWRender::MRenderItem::DecorationItem, MHWRender::MGeometry::kLines); renderItem->setDrawMode(MHWRender::MGeometry::kBoundingBox); renderItem->castsShadows(false); @@ -1683,18 +1689,14 @@ MHWRender::MRenderItem* HdVP2Mesh::_CreateBoundingBoxRenderItem( } /*! \brief Create render item for smoothHull repr. -*/ + */ MHWRender::MRenderItem* HdVP2Mesh::_CreateSmoothHullRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( - name, - MHWRender::MRenderItem::MaterialSceneItem, - MHWRender::MGeometry::kTriangles - ); - - constexpr MHWRender::MGeometry::DrawMode drawMode = - static_cast( - MHWRender::MGeometry::kShaded | MHWRender::MGeometry::kTextured); + name, MHWRender::MRenderItem::MaterialSceneItem, MHWRender::MGeometry::kTriangles); + + constexpr MHWRender::MGeometry::DrawMode drawMode = static_cast( + MHWRender::MGeometry::kShaded | MHWRender::MGeometry::kTextured); renderItem->setDrawMode(drawMode); renderItem->setExcludedFromPostEffects(false); renderItem->castsShadows(true); @@ -1708,19 +1710,14 @@ MHWRender::MRenderItem* HdVP2Mesh::_CreateSmoothHullRenderItem(const MString& na } /*! \brief Create render item to support selection highlight for smoothHull repr. -*/ -MHWRender::MRenderItem* HdVP2Mesh::_CreateSelectionHighlightRenderItem( - const MString& name) const + */ +MHWRender::MRenderItem* HdVP2Mesh::_CreateSelectionHighlightRenderItem(const MString& name) const { MHWRender::MRenderItem* const renderItem = MHWRender::MRenderItem::Create( - name, - MHWRender::MRenderItem::DecorationItem, - MHWRender::MGeometry::kLines - ); - - constexpr MHWRender::MGeometry::DrawMode drawMode = - static_cast( - MHWRender::MGeometry::kShaded | MHWRender::MGeometry::kTextured); + name, MHWRender::MRenderItem::DecorationItem, MHWRender::MGeometry::kLines); + + constexpr MHWRender::MGeometry::DrawMode drawMode = static_cast( + MHWRender::MGeometry::kShaded | MHWRender::MGeometry::kTextured); renderItem->setDrawMode(drawMode); renderItem->depthPriority(MHWRender::MRenderItem::sActiveWireDepthPriority); renderItem->castsShadows(false); diff --git a/lib/mayaUsd/render/vp2RenderDelegate/mesh.h b/lib/mayaUsd/render/vp2RenderDelegate/mesh.h index 95dac5cb75..f643f39a19 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/mesh.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/mesh.h @@ -16,12 +16,12 @@ #ifndef HD_VP2_MESH #define HD_VP2_MESH -#include +#include -#include #include +#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -30,8 +30,9 @@ class HdVP2DrawItem; class HdVP2RenderDelegate; //! Primvar data and interpolation. -struct PrimvarSource { - VtValue data; +struct PrimvarSource +{ + VtValue data; HdInterpolation interpolation; }; @@ -45,7 +46,8 @@ typedef TfHashMap PrimvarSourceMap USD scene delegate during synchronization. Then each draw item can prepare draw data from these shared data as needed. */ -struct HdVP2MeshSharedData { +struct HdVP2MeshSharedData +{ //! Cached scene topology. VtArrays are reference counted, so as long as we //! only call const accessors keeping them around doesn't incur a buffer //! copy. @@ -92,16 +94,15 @@ struct HdVP2MeshSharedData { in HdVP2RenderDelegate::CommitResources(), which runs on main-thread after all prims have been updated. */ -class HdVP2Mesh final : public HdMesh { +class HdVP2Mesh final : public HdMesh +{ public: HdVP2Mesh(HdVP2RenderDelegate*, const SdfPath&, const SdfPath& instancerId = SdfPath()); //! Destructor. ~HdVP2Mesh() override = default; - void Sync( - HdSceneDelegate*, HdRenderParam*, - HdDirtyBits*, const TfToken& reprToken) override; + void Sync(HdSceneDelegate*, HdRenderParam*, HdDirtyBits*, const TfToken& reprToken) override; HdDirtyBits GetInitialDirtyBitsMask() const override; @@ -113,15 +114,17 @@ class HdVP2Mesh final : public HdMesh { void _UpdateRepr(HdSceneDelegate*, const TfToken&); void _UpdateDrawItem( - HdSceneDelegate*, HdVP2DrawItem*, + HdSceneDelegate*, + HdVP2DrawItem*, const HdMeshReprDesc& desc, - bool requireSmoothNormals, bool requireFlatNormals); + bool requireSmoothNormals, + bool requireFlatNormals); void _HideAllDrawItems(const TfToken& reprToken); void _UpdatePrimvarSources( - HdSceneDelegate* sceneDelegate, - HdDirtyBits dirtyBits, + HdSceneDelegate* sceneDelegate, + HdDirtyBits dirtyBits, const TfTokenVector& requiredPrimvars); MHWRender::MRenderItem* _CreateSelectionHighlightRenderItem(const MString& name) const; @@ -131,7 +134,8 @@ class HdVP2Mesh final : public HdMesh { MHWRender::MRenderItem* _CreateBoundingBoxRenderItem(const MString& name) const; //! Custom dirty bits used by this mesh - enum DirtyBits : HdDirtyBits { + enum DirtyBits : HdDirtyBits + { DirtySmoothNormals = HdChangeTracker::CustomBitsBegin, DirtyFlatNormals = (DirtySmoothNormals << 1), DirtyIndices = (DirtyFlatNormals << 1), @@ -140,14 +144,18 @@ class HdVP2Mesh final : public HdMesh { DirtySelection = (DirtyPointsIndices << 1), DirtySelectionHighlight = (DirtySelection << 1) }; - - HdVP2RenderDelegate* _delegate{ nullptr }; //!< VP2 render delegate for which this mesh was created - HdDirtyBits _customDirtyBitsInUse{ 0 }; //!< Storage for custom dirty bits. See _PropagateDirtyBits for details. - const MString _rprimId; //!< Rprim id cached as a maya string for easier debugging and profiling - HdVP2MeshSharedData _meshSharedData; //!< Shared data for all draw items of the Rprim + + HdVP2RenderDelegate* _delegate { + nullptr + }; //!< VP2 render delegate for which this mesh was created + HdDirtyBits _customDirtyBitsInUse { + 0 + }; //!< Storage for custom dirty bits. See _PropagateDirtyBits for details. + const MString _rprimId; //!< Rprim id cached as a maya string for easier debugging and profiling + HdVP2MeshSharedData _meshSharedData; //!< Shared data for all draw items of the Rprim //! Selection status of the Rprim - HdVP2SelectionStatus _selectionStatus{ kUnselected }; + HdVP2SelectionStatus _selectionStatus { kUnselected }; }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.cpp b/lib/mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.cpp index ec24d59259..39b6c3ed06 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.cpp +++ b/lib/mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.cpp @@ -15,35 +15,35 @@ // #include "proxyRenderDelegate.h" -#include -#include -#include -#include -#include -#include +#include "render_delegate.h" +#include "tokens.h" + +#include +#include +#include #include #include -#include -#include -#include -#include -#include -#include -#include #include #include #include +#include #include #include -#include - -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include -#include "render_delegate.h" -#include "tokens.h" +#include +#include +#include +#include +#include +#include #if defined(WANT_UFE_BUILD) #include @@ -59,199 +59,189 @@ PXR_NAMESPACE_OPEN_SCOPE -namespace -{ - //! Representation selector for shaded and textured viewport mode - const HdReprSelector kSmoothHullReprSelector(HdReprTokens->smoothHull); +namespace { +//! Representation selector for shaded and textured viewport mode +const HdReprSelector kSmoothHullReprSelector(HdReprTokens->smoothHull); - //! Representation selector for wireframe viewport mode - const HdReprSelector kWireReprSelector(TfToken(), HdReprTokens->wire); +//! Representation selector for wireframe viewport mode +const HdReprSelector kWireReprSelector(TfToken(), HdReprTokens->wire); - //! Representation selector for bounding box viewport mode - const HdReprSelector kBBoxReprSelector(TfToken(), HdVP2ReprTokens->bbox); +//! Representation selector for bounding box viewport mode +const HdReprSelector kBBoxReprSelector(TfToken(), HdVP2ReprTokens->bbox); - //! Representation selector for point snapping - const HdReprSelector kPointsReprSelector(TfToken(), TfToken(), HdReprTokens->points); +//! Representation selector for point snapping +const HdReprSelector kPointsReprSelector(TfToken(), TfToken(), HdReprTokens->points); - //! Representation selector for selection update - const HdReprSelector kSelectionReprSelector(HdVP2ReprTokens->selection); +//! Representation selector for selection update +const HdReprSelector kSelectionReprSelector(HdVP2ReprTokens->selection); #if defined(WANT_UFE_BUILD) - //! \brief Query the global selection list adjustment. - MGlobal::ListAdjustment GetListAdjustment() - { - // Keyboard modifiers can be queried from QApplication::keyboardModifiers() - // in case running MEL command leads to performance hit. On the other hand - // the advantage of using MEL command is the platform-agnostic state of the - // CONTROL key that it provides for aligning to Maya's implementation. - int modifiers = 0; - MGlobal::executeCommand("getModifiers", modifiers); - - const bool shiftHeld = (modifiers % 2); - const bool ctrlHeld = (modifiers / 4 % 2); +//! \brief Query the global selection list adjustment. +MGlobal::ListAdjustment GetListAdjustment() +{ + // Keyboard modifiers can be queried from QApplication::keyboardModifiers() + // in case running MEL command leads to performance hit. On the other hand + // the advantage of using MEL command is the platform-agnostic state of the + // CONTROL key that it provides for aligning to Maya's implementation. + int modifiers = 0; + MGlobal::executeCommand("getModifiers", modifiers); + + const bool shiftHeld = (modifiers % 2); + const bool ctrlHeld = (modifiers / 4 % 2); + + MGlobal::ListAdjustment listAdjustment = MGlobal::kReplaceList; + + if (shiftHeld && ctrlHeld) { + listAdjustment = MGlobal::kAddToList; + } else if (ctrlHeld) { + listAdjustment = MGlobal::kRemoveFromList; + } else if (shiftHeld) { + listAdjustment = MGlobal::kXORWithList; + } - MGlobal::ListAdjustment listAdjustment = MGlobal::kReplaceList; + return listAdjustment; +} - if (shiftHeld && ctrlHeld) - { - listAdjustment = MGlobal::kAddToList; - } - else if (ctrlHeld) - { - listAdjustment = MGlobal::kRemoveFromList; - } - else if (shiftHeld) - { - listAdjustment = MGlobal::kXORWithList; - } +//! \brief Query the Kind to be selected from viewport. +//! \return A Kind token (https://graphics.pixar.com/usd/docs/api/kind_page_front.html). If the +//! token is empty or non-existing in the hierarchy, the exact prim that gets picked +//! in the viewport will be selected. +TfToken GetSelectionKind() +{ + static const MString kOptionVarName("UsdSelectionKind"); - return listAdjustment; + if (MGlobal::optionVarExists(kOptionVarName)) { + MString optionVarValue = MGlobal::optionVarStringValue(kOptionVarName); + return TfToken(optionVarValue.asChar()); } + return TfToken(); +} - //! \brief Query the Kind to be selected from viewport. - //! \return A Kind token (https://graphics.pixar.com/usd/docs/api/kind_page_front.html). If the - //! token is empty or non-existing in the hierarchy, the exact prim that gets picked - //! in the viewport will be selected. - TfToken GetSelectionKind() - { - static const MString kOptionVarName("UsdSelectionKind"); - - if (MGlobal::optionVarExists(kOptionVarName)) { - MString optionVarValue = MGlobal::optionVarStringValue(kOptionVarName); - return TfToken(optionVarValue.asChar()); - } - return TfToken(); +//! \brief Populate Rprims into the Hydra selection from the UFE scene item. +void PopulateSelection( + const Ufe::SceneItem::Ptr& item, + const Ufe::Path& proxyPath, + UsdImagingDelegate& sceneDelegate, + const HdSelectionSharedPtr& result) +{ + // Filter out items which are not under the current proxy shape. + if (!item->path().startsWith(proxyPath)) { + return; } - //! \brief Populate Rprims into the Hydra selection from the UFE scene item. - void PopulateSelection( - const Ufe::SceneItem::Ptr& item, - const Ufe::Path& proxyPath, - UsdImagingDelegate& sceneDelegate, - const HdSelectionSharedPtr& result) - { - // Filter out items which are not under the current proxy shape. - if (!item->path().startsWith(proxyPath)) { - return; - } - - // Filter out non-USD items. - auto usdItem = std::dynamic_pointer_cast(item); - if (!usdItem) { - return; - } + // Filter out non-USD items. + auto usdItem = std::dynamic_pointer_cast(item); + if (!usdItem) { + return; + } - SdfPath usdPath = usdItem->prim().GetPath(); + SdfPath usdPath = usdItem->prim().GetPath(); #if !defined(USD_IMAGING_API_VERSION) || USD_IMAGING_API_VERSION < 11 - usdPath = sceneDelegate.ConvertCachePathToIndexPath(usdPath); + usdPath = sceneDelegate.ConvertCachePathToIndexPath(usdPath); #endif - sceneDelegate.PopulateSelection(HdSelection::HighlightModeSelect, - usdPath, UsdImagingDelegate::ALL_INSTANCES, result); - } + sceneDelegate.PopulateSelection( + HdSelection::HighlightModeSelect, usdPath, UsdImagingDelegate::ALL_INSTANCES, result); +} #endif // defined(WANT_UFE_BUILD) - //! \brief Append the selected prim paths to the result list. - void AppendSelectedPrimPaths( - const HdSelectionSharedPtr& selection, - SdfPathVector& result) - { - if (!selection) { - return; - } +//! \brief Append the selected prim paths to the result list. +void AppendSelectedPrimPaths(const HdSelectionSharedPtr& selection, SdfPathVector& result) +{ + if (!selection) { + return; + } - SdfPathVector paths = selection->GetSelectedPrimPaths(HdSelection::HighlightModeSelect); - if (paths.empty()) { - return; - } + SdfPathVector paths = selection->GetSelectedPrimPaths(HdSelection::HighlightModeSelect); + if (paths.empty()) { + return; + } - if (result.empty()) { - result.swap(paths); - } - else { - result.reserve(result.size() + paths.size()); - result.insert(result.end(), paths.begin(), paths.end()); - } + if (result.empty()) { + result.swap(paths); + } else { + result.reserve(result.size() + paths.size()); + result.insert(result.end(), paths.begin(), paths.end()); } +} + +//! \brief Configure repr descriptions +void _ConfigureReprs() +{ + const HdMeshReprDesc reprDescHull( + HdMeshGeomStyleHull, + HdCullStyleDontCare, + HdMeshReprDescTokens->surfaceShader, + /*flatShadingEnabled=*/false, + /*blendWireframeColor=*/false); + + const HdMeshReprDesc reprDescEdge( + HdMeshGeomStyleHullEdgeOnly, + HdCullStyleDontCare, + HdMeshReprDescTokens->surfaceShader, + /*flatShadingEnabled=*/false, + /*blendWireframeColor=*/false); + + // Hull desc for shaded display, edge desc for selection highlight. + HdMesh::ConfigureRepr(HdReprTokens->smoothHull, reprDescHull, reprDescEdge); + + // Edge desc for bbox display. + HdMesh::ConfigureRepr(HdVP2ReprTokens->bbox, reprDescEdge); + + // Special token for selection update and no need to create repr. Adding + // the empty desc to remove Hydra warning. + HdMesh::ConfigureRepr(HdVP2ReprTokens->selection, HdMeshReprDesc()); + + // Wireframe desc for bbox display. + HdBasisCurves::ConfigureRepr(HdVP2ReprTokens->bbox, HdBasisCurvesGeomStyleWire); + + // Special token for selection update and no need to create repr. Adding + // the null desc to remove Hydra warning. + HdBasisCurves::ConfigureRepr(HdVP2ReprTokens->selection, HdBasisCurvesGeomStyleInvalid); +} - //! \brief Configure repr descriptions - void _ConfigureReprs() +#if defined(WANT_UFE_BUILD) +class UfeObserver : public Ufe::Observer +{ +public: + UfeObserver(ProxyRenderDelegate& proxyRenderDelegate) + : Ufe::Observer() + , _proxyRenderDelegate(proxyRenderDelegate) { - const HdMeshReprDesc reprDescHull( - HdMeshGeomStyleHull, - HdCullStyleDontCare, - HdMeshReprDescTokens->surfaceShader, - /*flatShadingEnabled=*/false, - /*blendWireframeColor=*/false); - - const HdMeshReprDesc reprDescEdge( - HdMeshGeomStyleHullEdgeOnly, - HdCullStyleDontCare, - HdMeshReprDescTokens->surfaceShader, - /*flatShadingEnabled=*/false, - /*blendWireframeColor=*/false - ); - - // Hull desc for shaded display, edge desc for selection highlight. - HdMesh::ConfigureRepr(HdReprTokens->smoothHull, reprDescHull, reprDescEdge); - - // Edge desc for bbox display. - HdMesh::ConfigureRepr(HdVP2ReprTokens->bbox, reprDescEdge); - - // Special token for selection update and no need to create repr. Adding - // the empty desc to remove Hydra warning. - HdMesh::ConfigureRepr(HdVP2ReprTokens->selection, HdMeshReprDesc()); - - // Wireframe desc for bbox display. - HdBasisCurves::ConfigureRepr(HdVP2ReprTokens->bbox, - HdBasisCurvesGeomStyleWire); - - // Special token for selection update and no need to create repr. Adding - // the null desc to remove Hydra warning. - HdBasisCurves::ConfigureRepr(HdVP2ReprTokens->selection, - HdBasisCurvesGeomStyleInvalid); } -#if defined(WANT_UFE_BUILD) - class UfeObserver : public Ufe::Observer + void operator()(const Ufe::Notification& notification) override { - public: - UfeObserver(ProxyRenderDelegate& proxyRenderDelegate) - : Ufe::Observer() - , _proxyRenderDelegate(proxyRenderDelegate) - { + // During Maya file read, each node will be selected in turn, so we get + // notified for each node in the scene. Prune this out. + if (MFileIO::isOpeningFile()) { + return; } - void operator()(const Ufe::Notification& notification) override - { - // During Maya file read, each node will be selected in turn, so we get - // notified for each node in the scene. Prune this out. - if (MFileIO::isOpeningFile()) { - return; - } - - if (dynamic_cast(¬ification) || - dynamic_cast(¬ification)) { - _proxyRenderDelegate.SelectionChanged(); - } + if (dynamic_cast(¬ification) + || dynamic_cast(¬ification)) { + _proxyRenderDelegate.SelectionChanged(); } + } - private: - ProxyRenderDelegate& _proxyRenderDelegate; - }; +private: + ProxyRenderDelegate& _proxyRenderDelegate; +}; #else - void SelectionChangedCB(void* data) - { - ProxyRenderDelegate* prd = static_cast(data); - if (prd) { - prd->SelectionChanged(); - } +void SelectionChangedCB(void* data) +{ + ProxyRenderDelegate* prd = static_cast(data); + if (prd) { + prd->SelectionChanged(); } +} #endif -// Copied from renderIndex.cpp, the code that does HdRenderIndex::GetDrawItems. But I just want the rprimIds, I don't want to go all the way to draw items. -struct _FilterParam { +// Copied from renderIndex.cpp, the code that does HdRenderIndex::GetDrawItems. But I just want the +// rprimIds, I don't want to go all the way to draw items. +struct _FilterParam +{ const HdRprimCollection& collection; const TfTokenVector& renderTags; const HdRenderIndex* renderIndex; @@ -310,27 +300,32 @@ bool _DrawItemFilterPredicate(const SdfPath& rprimID, const void* predicateParam //! \brief Draw classification used during plugin load to register in VP2 const MString ProxyRenderDelegate::drawDbClassification( - TfStringPrintf("drawdb/subscene/vp2RenderDelegate/%s", - MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText()).c_str()); + TfStringPrintf( + "drawdb/subscene/vp2RenderDelegate/%s", + MayaUsdProxyShapeBaseTokens->MayaTypeName.GetText()) + .c_str()); //! \brief Factory method registered at plugin load -MHWRender::MPxSubSceneOverride* ProxyRenderDelegate::Creator(const MObject& obj) { +MHWRender::MPxSubSceneOverride* ProxyRenderDelegate::Creator(const MObject& obj) +{ return new ProxyRenderDelegate(obj); } //! \brief Constructor ProxyRenderDelegate::ProxyRenderDelegate(const MObject& obj) -: MHWRender::MPxSubSceneOverride(obj) + : MHWRender::MPxSubSceneOverride(obj) { MDagPath proxyDagPath; MDagPath::getAPathTo(obj, proxyDagPath); const MFnDependencyNode fnDepNode(obj); - _proxyShapeData.reset(new ProxyShapeData(static_cast(fnDepNode.userNode()), proxyDagPath)); + _proxyShapeData.reset(new ProxyShapeData( + static_cast(fnDepNode.userNode()), proxyDagPath)); } //! \brief Destructor -ProxyRenderDelegate::~ProxyRenderDelegate() { +ProxyRenderDelegate::~ProxyRenderDelegate() +{ _ClearRenderDelegate(); #if !defined(WANT_UFE_BUILD) @@ -341,19 +336,20 @@ ProxyRenderDelegate::~ProxyRenderDelegate() { } //! \brief This drawing routine supports all devices (DirectX and OpenGL) -MHWRender::DrawAPI ProxyRenderDelegate::supportedDrawAPIs() const { - return MHWRender::kAllDevices; -} +MHWRender::DrawAPI ProxyRenderDelegate::supportedDrawAPIs() const { return MHWRender::kAllDevices; } #if defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) -//! \brief Enable subscene update in selection passes for deferred update of selection render items. -bool ProxyRenderDelegate::enableUpdateForSelection() const { - return true; -} +//! \brief Enable subscene update in selection passes for deferred update of selection render +//! items. +bool ProxyRenderDelegate::enableUpdateForSelection() const { return true; } #endif -//! \brief Always requires update since changes are tracked by Hydraw change tracker and it will guarantee minimal update -bool ProxyRenderDelegate::requiresUpdate(const MSubSceneContainer& container, const MFrameContext& frameContext) const { +//! \brief Always requires update since changes are tracked by Hydraw change tracker and it will +//! guarantee minimal update +bool ProxyRenderDelegate::requiresUpdate( + const MSubSceneContainer& container, + const MFrameContext& frameContext) const +{ return true; } @@ -387,8 +383,7 @@ void ProxyRenderDelegate::_ClearInvalidData(MSubSceneContainer& container) // from excluded prims & so must be re-added to the render index, so we take the easy way out // and clear everything. If this is a performance problem we can probably store the old value // of excluded prims, compare it to the new value and only add back the difference. - if (!_proxyShapeData->IsUsdStageUpToDate() || !_proxyShapeData->IsExcludePrimsUpToDate()) - { + if (!_proxyShapeData->IsUsdStageUpToDate() || !_proxyShapeData->IsExcludePrimsUpToDate()) { // delete everything so we can re-initialize with the new stage _ClearRenderDelegate(); container.clear(); @@ -408,14 +403,16 @@ void ProxyRenderDelegate::_InitRenderDelegate() _proxyShapeData->UsdStageUpdated(); if (!_renderDelegate) { - MProfilingScope subProfilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorD_L1, "Allocate VP2RenderDelegate"); + MProfilingScope subProfilingScope( + HdVP2RenderDelegate::sProfilerCategory, + MProfiler::kColorD_L1, + "Allocate VP2RenderDelegate"); _renderDelegate.reset(new HdVP2RenderDelegate(*this)); } if (!_renderIndex) { - MProfilingScope subProfilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorD_L1, "Allocate RenderIndex"); + MProfilingScope subProfilingScope( + HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L1, "Allocate RenderIndex"); #if USD_VERSION_NUM > 2002 _renderIndex.reset(HdRenderIndex::New(_renderDelegate.get(), HdDriverVector())); #else @@ -428,24 +425,24 @@ void ProxyRenderDelegate::_InitRenderDelegate() } if (!_sceneDelegate) { - MProfilingScope subProfilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorD_L1, "Allocate SceneDelegate"); + MProfilingScope subProfilingScope( + HdVP2RenderDelegate::sProfilerCategory, + MProfiler::kColorD_L1, + "Allocate SceneDelegate"); // Make sure the delegate name is a valid identifier, since it may // include colons if the proxy node is in a Maya namespace. - const std::string delegateName = - TfMakeValidIdentifier( - TfStringPrintf( - "Proxy_%s_%p", - _proxyShapeData->ProxyShape()->name().asChar(), - _proxyShapeData->ProxyShape())); - const SdfPath delegateID = - SdfPath::AbsoluteRootPath().AppendChild(TfToken(delegateName)); + const std::string delegateName = TfMakeValidIdentifier(TfStringPrintf( + "Proxy_%s_%p", + _proxyShapeData->ProxyShape()->name().asChar(), + _proxyShapeData->ProxyShape())); + const SdfPath delegateID = SdfPath::AbsoluteRootPath().AppendChild(TfToken(delegateName)); _sceneDelegate.reset(new UsdImagingDelegate(_renderIndex.get(), delegateID)); - _taskController.reset(new HdxTaskController(_renderIndex.get(), - delegateID.AppendChild(TfToken(TfStringPrintf("_UsdImaging_VP2_%p", this))) )); + _taskController.reset(new HdxTaskController( + _renderIndex.get(), + delegateID.AppendChild(TfToken(TfStringPrintf("_UsdImaging_VP2_%p", this))))); _defaultCollection.reset(new HdRprimCollection()); _defaultCollection->SetName(HdTokens->geometry); @@ -459,18 +456,17 @@ void ProxyRenderDelegate::_InitRenderDelegate() globalSelection->addObserver(_observer); } - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE Ufe::Scene::instance().addObserver(_observer); - #else +#else Ufe::Scene::instance().addObjectAddObserver(_observer); - #endif +#endif } #else // Without UFE, support basic selection highlight at proxy shape level. - if (!_mayaSelectionCallbackId) - { - _mayaSelectionCallbackId = MEventMessage::addEventCallback( - "SelectionChanged", SelectionChangedCB, this); + if (!_mayaSelectionCallbackId) { + _mayaSelectionCallbackId + = MEventMessage::addEventCallback("SelectionChanged", SelectionChangedCB, this); } #endif @@ -492,13 +488,13 @@ void ProxyRenderDelegate::_InitRenderDelegate() bool ProxyRenderDelegate::_Populate() { TF_VERIFY(_proxyShapeData->ProxyShape()); - + if (!_isInitialized()) return false; - if (_proxyShapeData->UsdStage() && !_isPopulated ) { - MProfilingScope subProfilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorD_L1, "Populate"); + if (_proxyShapeData->UsdStage() && !_isPopulated) { + MProfilingScope subProfilingScope( + HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L1, "Populate"); // Remove any excluded prims before populating SdfPathVector excludePrimPaths = _proxyShapeData->ProxyShape()->getExcludePrimPaths(); @@ -509,8 +505,8 @@ bool ProxyRenderDelegate::_Populate() } } _proxyShapeData->ExcludePrimsUpdated(); - - _sceneDelegate->Populate(_proxyShapeData->UsdStage()->GetPseudoRoot(),excludePrimPaths); + + _sceneDelegate->Populate(_proxyShapeData->UsdStage()->GetPseudoRoot(), excludePrimPaths); _isPopulated = true; } @@ -525,30 +521,30 @@ void ProxyRenderDelegate::_UpdateSceneDelegate() if (!_sceneDelegate) return; - MProfilingScope profilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorC_L1, "UpdateSceneDelegate"); + MProfilingScope profilingScope( + HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "UpdateSceneDelegate"); { - MProfilingScope subProfilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorC_L1, "SetTime"); + MProfilingScope subProfilingScope( + HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "SetTime"); const UsdTimeCode timeCode = _proxyShapeData->ProxyShape()->getTime(); _sceneDelegate->SetTime(timeCode); } - const MMatrix inclusiveMatrix = _proxyShapeData->ProxyDagPath().inclusiveMatrix(); + const MMatrix inclusiveMatrix = _proxyShapeData->ProxyDagPath().inclusiveMatrix(); const GfMatrix4d transform(inclusiveMatrix.matrix); constexpr double tolerance = 1e-9; if (!GfIsClose(transform, _sceneDelegate->GetRootTransform(), tolerance)) { - MProfilingScope subProfilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorC_L1, "SetRootTransform"); + MProfilingScope subProfilingScope( + HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "SetRootTransform"); _sceneDelegate->SetRootTransform(transform); } const bool isVisible = _proxyShapeData->ProxyDagPath().isVisible(); if (isVisible != _sceneDelegate->GetRootVisibility()) { - MProfilingScope subProfilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorC_L1, "SetRootVisibility"); + MProfilingScope subProfilingScope( + HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "SetRootVisibility"); _sceneDelegate->SetRootVisibility(isVisible); // Trigger selection update when a hidden proxy shape gets shown. @@ -558,10 +554,11 @@ void ProxyRenderDelegate::_UpdateSceneDelegate() } const int refineLevel = _proxyShapeData->ProxyShape()->getComplexity(); - if (refineLevel != _sceneDelegate->GetRefineLevelFallback()) - { - MProfilingScope subProfilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorC_L1, "SetRefineLevelFallback"); + if (refineLevel != _sceneDelegate->GetRefineLevelFallback()) { + MProfilingScope subProfilingScope( + HdVP2RenderDelegate::sProfilerCategory, + MProfiler::kColorC_L1, + "SetRefineLevelFallback"); _sceneDelegate->SetRefineLevelFallback(refineLevel); } @@ -570,8 +567,8 @@ void ProxyRenderDelegate::_UpdateSceneDelegate() //! \brief Execute Hydra engine to perform minimal VP2 draw data update based on change tracker. void ProxyRenderDelegate::_Execute(const MHWRender::MFrameContext& frameContext) { - MProfilingScope profilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorC_L1, "Execute"); + MProfilingScope profilingScope( + HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorC_L1, "Execute"); _UpdateRenderTags(); @@ -589,14 +586,13 @@ void ProxyRenderDelegate::_Execute(const MHWRender::MFrameContext& frameContext) if (inSelectionPass && !inPointSnapping) { _globalListAdjustment = GetListAdjustment(); _selectionKind = GetSelectionKind(); - } - else { + } else { _globalListAdjustment = MGlobal::kReplaceList; _selectionKind = TfToken(); } #endif // defined(WANT_UFE_BUILD) -#else // !defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) +#else // !defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) HdReprSelector reprSelector = kPointsReprSelector; constexpr bool inSelectionPass = false; @@ -607,8 +603,7 @@ void ProxyRenderDelegate::_Execute(const MHWRender::MFrameContext& frameContext) if (inPointSnapping && !reprSelector.Contains(HdReprTokens->points)) { reprSelector = reprSelector.CompositeOver(kPointsReprSelector); } - } - else { + } else { if (_selectionChanged) { _UpdateSelectionStates(); _selectionChanged = false; @@ -617,11 +612,10 @@ void ProxyRenderDelegate::_Execute(const MHWRender::MFrameContext& frameContext) const unsigned int displayStyle = frameContext.getDisplayStyle(); // Query the wireframe color assigned to proxy shape. - if (displayStyle & ( - MHWRender::MFrameContext::kBoundingBox | - MHWRender::MFrameContext::kWireFrame)) - { - _wireframeColor = MHWRender::MGeometryUtilities::wireframeColor(_proxyShapeData->ProxyDagPath()); + if (displayStyle + & (MHWRender::MFrameContext::kBoundingBox | MHWRender::MFrameContext::kWireFrame)) { + _wireframeColor + = MHWRender::MGeometryUtilities::wireframeColor(_proxyShapeData->ProxyDagPath()); } // Update repr selector based on display style of the current viewport @@ -629,8 +623,7 @@ void ProxyRenderDelegate::_Execute(const MHWRender::MFrameContext& frameContext) if (!reprSelector.Contains(HdVP2ReprTokens->bbox)) { reprSelector = reprSelector.CompositeOver(kBBoxReprSelector); } - } - else { + } else { // To support Wireframe on Shaded mode, the two displayStyle checks // should not be mutually excluded. if (displayStyle & MHWRender::MFrameContext::kGouraudShaded) { @@ -656,9 +649,12 @@ void ProxyRenderDelegate::_Execute(const MHWRender::MFrameContext& frameContext) } //! \brief Main update entry from subscene override. -void ProxyRenderDelegate::update(MSubSceneContainer& container, const MFrameContext& frameContext) { - MProfilingScope profilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorD_L1, "ProxyRenderDelegate::update"); +void ProxyRenderDelegate::update(MSubSceneContainer& container, const MFrameContext& frameContext) +{ + MProfilingScope profilingScope( + HdVP2RenderDelegate::sProfilerCategory, + MProfiler::kColorD_L1, + "ProxyRenderDelegate::update"); // Without a proxy shape we can't do anything if (_proxyShapeData->ProxyShape() == nullptr) @@ -668,7 +664,8 @@ void ProxyRenderDelegate::update(MSubSceneContainer& container, const MFrameCont _InitRenderDelegate(); - // Give access to current time and subscene container to the rest of render delegate world via render param's. + // Give access to current time and subscene container to the rest of render delegate world via + // render param's. auto* param = reinterpret_cast(_renderDelegate->GetRenderParam()); param->BeginUpdate(container, _sceneDelegate->GetTime()); @@ -681,20 +678,19 @@ void ProxyRenderDelegate::update(MSubSceneContainer& container, const MFrameCont //! \brief Switch to component-level selection for point snapping. void ProxyRenderDelegate::updateSelectionGranularity( - const MDagPath& path, + const MDagPath& path, MHWRender::MSelectionContext& selectionContext) { - if (pointSnappingActive()) - { + if (pointSnappingActive()) { selectionContext.setSelectionLevel(MHWRender::MSelectionContext::kComponent); } } //! \brief Selection for both instanced and non-instanced cases. bool ProxyRenderDelegate::getInstancedSelectionPath( - const MHWRender::MRenderItem& renderItem, + const MHWRender::MRenderItem& renderItem, const MHWRender::MIntersection& intersection, - MDagPath& dagPath) const + MDagPath& dagPath) const { #if defined(WANT_UFE_BUILD) if (_proxyShapeData->ProxyShape() == nullptr) { @@ -720,8 +716,8 @@ bool ProxyRenderDelegate::getInstancedSelectionPath( // "/TreePatch/Tree_1.proto_leaves_id0/DrawItem_xxxxxxxx". Thus std::string // is used instead to extract Rprim id. const std::string renderItemName = renderItem.name().asChar(); - const auto pos = renderItemName.find_last_of(USD_UFE_SEPARATOR); - const SdfPath rprimId(renderItemName.substr(0, pos)); + const auto pos = renderItemName.find_last_of(USD_UFE_SEPARATOR); + const SdfPath rprimId(renderItemName.substr(0, pos)); // If drawInstID is positive, it means the selection hit comes from one instanced render item, // in this case its instance transform matrices have been sorted w.r.t. USD instance ID, thus @@ -733,14 +729,13 @@ bool ProxyRenderDelegate::getInstancedSelectionPath( #if defined(USD_IMAGING_API_VERSION) && USD_IMAGING_API_VERSION >= 13 const int usdInstID = drawInstID > 0 ? drawInstID - 1 : 0; - SdfPath usdPath = _sceneDelegate->GetScenePrimPath(rprimId, usdInstID); + SdfPath usdPath = _sceneDelegate->GetScenePrimPath(rprimId, usdInstID); #else SdfPath indexPath; if (drawInstID > 0) { const int usdInstID = drawInstID - 1; indexPath = _sceneDelegate->GetPathForInstanceIndex(rprimId, usdInstID, nullptr); - } - else { + } else { indexPath = rprimId; } @@ -759,7 +754,7 @@ bool ProxyRenderDelegate::getInstancedSelectionPath( // once per selection update to avoid cost of executing MEL command or searching optionVar for // each intersection. #if defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) - const TfToken& selectionKind = _selectionKind; + const TfToken& selectionKind = _selectionKind; const MGlobal::ListAdjustment& listAdjustment = _globalListAdjustment; #else const TfToken selectionKind = GetSelectionKind(); @@ -781,7 +776,8 @@ bool ProxyRenderDelegate::getInstancedSelectionPath( } const Ufe::PathSegment pathSegment(usdPath.GetText(), USD_UFE_RUNTIME_ID, USD_UFE_SEPARATOR); - const Ufe::SceneItem::Ptr& si = handler->createItem(_proxyShapeData->ProxyShape()->ufePath() + pathSegment); + const Ufe::SceneItem::Ptr& si + = handler->createItem(_proxyShapeData->ProxyShape()->ufePath() + pathSegment); if (!si) { TF_WARN("Failed to create UFE scene item for Rprim '%s'", rprimId.GetText()); return false; @@ -797,20 +793,14 @@ bool ProxyRenderDelegate::getInstancedSelectionPath( // selection list would clear Maya selection list. globalSelection->append(si); break; - case MGlobal::kAddToList: - globalSelection->append(si); - break; - case MGlobal::kRemoveFromList: - globalSelection->remove(si); - break; + case MGlobal::kAddToList: globalSelection->append(si); break; + case MGlobal::kRemoveFromList: globalSelection->remove(si); break; case MGlobal::kXORWithList: if (!globalSelection->remove(si)) { globalSelection->append(si); } break; - default: - TF_WARN("Unexpected MGlobal::ListAdjustment enum for selection."); - break; + default: TF_WARN("Unexpected MGlobal::ListAdjustment enum for selection."); break; } #else dagPath = _proxyShapeData->ProxyDagPath(); @@ -820,10 +810,7 @@ bool ProxyRenderDelegate::getInstancedSelectionPath( } //! \brief Notify of selection change. -void ProxyRenderDelegate::SelectionChanged() -{ - _selectionChanged = true; -} +void ProxyRenderDelegate::SelectionChanged() { _selectionChanged = true; } //! \brief Polulate lead and active selection for Rprims under the proxy shape. void ProxyRenderDelegate::_PopulateSelection() @@ -854,7 +841,7 @@ void ProxyRenderDelegate::_PopulateSelection() } /*! \brief Notify selection change to rprims. -*/ + */ void ProxyRenderDelegate::_UpdateSelectionStates() { const MHWRender::DisplayStatus previousStatus = _displayStatus; @@ -866,12 +853,10 @@ void ProxyRenderDelegate::_UpdateSelectionStates() if (_displayStatus != previousStatus) { rootPaths.push_back(SdfPath::AbsoluteRootPath()); } - } - else if (previousStatus == MHWRender::kLead || previousStatus == MHWRender::kActive) { + } else if (previousStatus == MHWRender::kLead || previousStatus == MHWRender::kActive) { rootPaths.push_back(SdfPath::AbsoluteRootPath()); _PopulateSelection(); - } - else { + } else { // Append pre-update lead and active selection. AppendSelectedPrimPaths(_leadSelection, rootPaths); AppendSelectedPrimPaths(_activeSelection, rootPaths); @@ -894,7 +879,7 @@ void ProxyRenderDelegate::_UpdateSelectionStates() } /*! \brief Trigger rprim update for rprims whose visibility changed because of render tags change -*/ + */ void ProxyRenderDelegate::_UpdateRenderTags() { // USD pulls the required render tags from the task list passed into execute. @@ -923,15 +908,14 @@ void ProxyRenderDelegate::_UpdateRenderTags() // marked dirty. This will ensure the upcoming execute call will update // the visibility of the MRenderItems in MPxSubSceneOverride. HdChangeTracker& changeTracker = _renderIndex->GetChangeTracker(); - bool renderPurposeChanged = false; - bool proxyPurposeChanged = false; - bool guidePurposeChanged = false; + bool renderPurposeChanged = false; + bool proxyPurposeChanged = false; + bool guidePurposeChanged = false; _proxyShapeData->UpdatePurpose( &renderPurposeChanged, &proxyPurposeChanged, &guidePurposeChanged); - if (renderPurposeChanged || proxyPurposeChanged || guidePurposeChanged) - { - MProfilingScope subProfilingScope(HdVP2RenderDelegate::sProfilerCategory, - MProfiler::kColorD_L1, "Update Purpose"); + if (renderPurposeChanged || proxyPurposeChanged || guidePurposeChanged) { + MProfilingScope subProfilingScope( + HdVP2RenderDelegate::sProfilerCategory, MProfiler::kColorD_L1, "Update Purpose"); // Build the list of render tags which were added or removed (changed) // and the list of render tags which were removed. @@ -947,8 +931,8 @@ void ProxyRenderDelegate::_UpdateRenderTags() } // Mark all the rprims which have a render tag which changed dirty - SdfPathVector rprimsToDirty = _GetFilteredRprims(*_defaultCollection, changedRenderTags); - + SdfPathVector rprimsToDirty = _GetFilteredRprims(*_defaultCollection, changedRenderTags); + for (auto& id : rprimsToDirty) { changeTracker.MarkRprimDirty(id, HdChangeTracker::DirtyRenderTag); } @@ -960,18 +944,18 @@ void ProxyRenderDelegate::_UpdateRenderTags() // rprim or not. bool rprimRenderTagChanged = (_renderTagVersion != changeTracker.GetRenderTagVersion()); #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND - rprimRenderTagChanged = rprimRenderTagChanged || ( _visibilityVersion != changeTracker.GetVisibilityChangeCount()); + rprimRenderTagChanged + = rprimRenderTagChanged || (_visibilityVersion != changeTracker.GetVisibilityChangeCount()); #endif // Vp2RenderDelegate implements render tags as a per-render item setting. // To handle cases when an rprim changes from a displayed tag to a hidden tag // we need to visit all the rprims and set the enable flag correctly on - // all their render items. Do visit all the rprims we need to set the + // all their render items. Do visit all the rprims we need to set the // render tags to be all the tags. // When an rprim has it's renderTag changed the global render tag version // id will change. - if (rprimRenderTagChanged) - { + if (rprimRenderTagChanged) { TfTokenVector renderTags = { HdRenderTagTokens->geometry, HdRenderTagTokens->render, HdRenderTagTokens->proxy, @@ -983,7 +967,8 @@ void ProxyRenderDelegate::_UpdateRenderTags() // their visibility. The frame after we do the pass over all the tags, set the tags back to // the minimum set of tags. else if (!_taskRenderTagsValid) { - TfTokenVector renderTags = { HdRenderTagTokens->geometry }; // always draw geometry render tag purpose. + TfTokenVector renderTags + = { HdRenderTagTokens->geometry }; // always draw geometry render tag purpose. if (_proxyShapeData->DrawRenderPurpose()) { renderTags.push_back(HdRenderTagTokens->render); } @@ -1007,7 +992,7 @@ SdfPathVector ProxyRenderDelegate::_GetFilteredRprims( HdRprimCollection const& collection, TfTokenVector const& renderTags) { - SdfPathVector rprimIds; + SdfPathVector rprimIds; const SdfPathVector& paths = _renderIndex->GetRprimIds(); const SdfPathVector& includePaths = collection.GetRootPaths(); const SdfPathVector& excludePaths = collection.GetExcludePaths(); @@ -1023,21 +1008,22 @@ SdfPathVector ProxyRenderDelegate::_GetFilteredRprims( const HdSelection::PrimSelectionState* ProxyRenderDelegate::GetLeadSelectionState(const SdfPath& path) const { - return (_leadSelection == nullptr) ? nullptr : - _leadSelection->GetPrimSelectionState(HdSelection::HighlightModeSelect, path); + return (_leadSelection == nullptr) + ? nullptr + : _leadSelection->GetPrimSelectionState(HdSelection::HighlightModeSelect, path); } //! \brief Qeury the selection state of a given prim from the active selection. const HdSelection::PrimSelectionState* ProxyRenderDelegate::GetActiveSelectionState(const SdfPath& path) const { - return (_activeSelection == nullptr) ? nullptr : - _activeSelection->GetPrimSelectionState(HdSelection::HighlightModeSelect, path); + return (_activeSelection == nullptr) + ? nullptr + : _activeSelection->GetPrimSelectionState(HdSelection::HighlightModeSelect, path); } //! \brief Query the selection status of a given prim. -HdVP2SelectionStatus -ProxyRenderDelegate::GetSelectionStatus(const SdfPath& path) const +HdVP2SelectionStatus ProxyRenderDelegate::GetSelectionStatus(const SdfPath& path) const { if (_displayStatus == MHWRender::kLead) { return kFullyLead; @@ -1061,12 +1047,9 @@ ProxyRenderDelegate::GetSelectionStatus(const SdfPath& path) const } //! \brief Query the wireframe color assigned to the proxy shape. -const MColor& ProxyRenderDelegate::GetWireframeColor() const -{ - return _wireframeColor; -} +const MColor& ProxyRenderDelegate::GetWireframeColor() const { return _wireframeColor; } -//! \brief +//! \brief const MColor& ProxyRenderDelegate::GetSelectionHighlightColor(bool lead) const { static const MColor kLeadColor(0.056f, 1.0f, 0.366f, 1.0f); @@ -1094,26 +1077,41 @@ bool ProxyRenderDelegate::DrawRenderTag(const TfToken& renderTag) const } // ProxyShapeData -ProxyRenderDelegate::ProxyShapeData::ProxyShapeData(const MayaUsdProxyShapeBase* proxyShape, const MDagPath& proxyDagPath) +ProxyRenderDelegate::ProxyShapeData::ProxyShapeData( + const MayaUsdProxyShapeBase* proxyShape, + const MDagPath& proxyDagPath) : _proxyShape(proxyShape) , _proxyDagPath(proxyDagPath) { assert(_proxyShape); } -inline const MayaUsdProxyShapeBase* ProxyRenderDelegate::ProxyShapeData::ProxyShape() const { return _proxyShape; } -inline const MDagPath& ProxyRenderDelegate::ProxyShapeData::ProxyDagPath() const { return _proxyDagPath; } +inline const MayaUsdProxyShapeBase* ProxyRenderDelegate::ProxyShapeData::ProxyShape() const +{ + return _proxyShape; +} +inline const MDagPath& ProxyRenderDelegate::ProxyShapeData::ProxyDagPath() const +{ + return _proxyDagPath; +} inline UsdStageRefPtr ProxyRenderDelegate::ProxyShapeData::UsdStage() const { return _usdStage; } -inline void ProxyRenderDelegate::ProxyShapeData::UpdateUsdStage() { _usdStage = _proxyShape->getUsdStage(); } -inline bool ProxyRenderDelegate::ProxyShapeData::IsUsdStageUpToDate() const { +inline void ProxyRenderDelegate::ProxyShapeData::UpdateUsdStage() +{ + _usdStage = _proxyShape->getUsdStage(); +} +inline bool ProxyRenderDelegate::ProxyShapeData::IsUsdStageUpToDate() const +{ return _proxyShape->getUsdStageVersion() == _usdStageVersion; } -inline void ProxyRenderDelegate::ProxyShapeData::UsdStageUpdated() { +inline void ProxyRenderDelegate::ProxyShapeData::UsdStageUpdated() +{ _usdStageVersion = _proxyShape->getUsdStageVersion(); } -inline bool ProxyRenderDelegate::ProxyShapeData::IsExcludePrimsUpToDate() const { +inline bool ProxyRenderDelegate::ProxyShapeData::IsExcludePrimsUpToDate() const +{ return _proxyShape->getExcludePrimPathsVersion() == _excludePrimsVersion; } -inline void ProxyRenderDelegate::ProxyShapeData::ExcludePrimsUpdated() { +inline void ProxyRenderDelegate::ProxyShapeData::ExcludePrimsUpdated() +{ _excludePrimsVersion = _proxyShape->getExcludePrimPathsVersion(); } inline void ProxyRenderDelegate::ProxyShapeData::UpdatePurpose( diff --git a/lib/mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.h b/lib/mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.h index 456abeaa45..acc44f89a3 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/proxyRenderDelegate.h @@ -16,7 +16,14 @@ #ifndef PROXY_RENDER_DELEGATE #define PROXY_RENDER_DELEGATE -#include +#include + +#include +#include +#include +#include +#include +#include #include #include @@ -27,14 +34,7 @@ #include #include -#include -#include -#include -#include -#include -#include - -#include +#include #if defined(WANT_UFE_BUILD) #include @@ -48,7 +48,7 @@ #define ENABLE_RENDERTAG_VISIBILITY_WORKAROUND /* In USD v20.05 and earlier when the purpose of an rprim changes the visibility gets dirtied, and that doesn't update the render tag version. - + Pixar is in the process of fixing this one as noted in: https://groups.google.com/forum/#!topic/usd-interest/9pzFbtCEY-Y @@ -66,8 +66,9 @@ class MayaUsdProxyShapeBase; class HdxTaskController; /*! \brief Enumerations for selection status -*/ -enum HdVP2SelectionStatus { + */ +enum HdVP2SelectionStatus +{ kUnselected, //!< A Rprim is not selected kPartiallySelected, //!< A Rprim is partially selected (only applicable for instanced Rprims) kFullyActive, //!< A Rprim is active (meaning fully active for instanced Rprims) @@ -107,21 +108,21 @@ class ProxyRenderDelegate : public MHWRender::MPxSubSceneOverride #endif MAYAUSD_CORE_PUBLIC - bool requiresUpdate(const MSubSceneContainer& container, const MFrameContext& frameContext) const override; + bool requiresUpdate(const MSubSceneContainer& container, const MFrameContext& frameContext) + const override; MAYAUSD_CORE_PUBLIC void update(MSubSceneContainer& container, const MFrameContext& frameContext) override; MAYAUSD_CORE_PUBLIC - void updateSelectionGranularity( - const MDagPath& path, - MSelectionContext& selectionContext) override; + void + updateSelectionGranularity(const MDagPath& path, MSelectionContext& selectionContext) override; MAYAUSD_CORE_PUBLIC bool getInstancedSelectionPath( - const MRenderItem& renderItem, + const MRenderItem& renderItem, const MIntersection& intersection, - MDagPath& dagPath) const override; + MDagPath& dagPath) const override; MAYAUSD_CORE_PUBLIC void SelectionChanged(); @@ -160,76 +161,99 @@ class ProxyRenderDelegate : public MHWRender::MPxSubSceneOverride void _UpdateSelectionStates(); void _UpdateRenderTags(); void _ClearRenderDelegate(); - SdfPathVector _GetFilteredRprims(HdRprimCollection const& collection, TfTokenVector const& renderTags); + SdfPathVector + _GetFilteredRprims(HdRprimCollection const& collection, TfTokenVector const& renderTags); /*! \brief Hold all data related to the proxy shape. - In addition to holding data read from the proxy shape, ProxyShapeData tracks when data read from the - proxy shape changes. For simple numeric types cache the last value read from _proxyShape & compare to - the current value. For complicated types we keep a version number of the last value we read to make - fast comparisons. + In addition to holding data read from the proxy shape, ProxyShapeData tracks when data read + from the proxy shape changes. For simple numeric types cache the last value read from + _proxyShape & compare to the current value. For complicated types we keep a version number of + the last value we read to make fast comparisons. */ class ProxyShapeData { - const MayaUsdProxyShapeBase* const _proxyShape{ nullptr }; //!< DG proxy shape node - const MDagPath _proxyDagPath; //!< DAG path of the proxy shape (assuming no DAG instancing) - UsdStageRefPtr _usdStage; //!< USD stage pointer - size_t _excludePrimsVersion{ 0 }; //!< Last version of exluded prims used during render index populate - size_t _usdStageVersion{ 0 }; //!< Last version of stage used during render index populate - bool _drawRenderPurpose { false }; //!< Should the render delegate draw rprims with the "render" purpose - bool _drawProxyPurpose { false }; //!< Should the render delegate draw rprims with the "proxy" purpose - bool _drawGuidePurpose { false }; //!< Should the render delegate draw rprims with the "guide" purpose + const MayaUsdProxyShapeBase* const _proxyShape { nullptr }; //!< DG proxy shape node + const MDagPath _proxyDagPath; //!< DAG path of the proxy shape (assuming no DAG instancing) + UsdStageRefPtr _usdStage; //!< USD stage pointer + size_t _excludePrimsVersion { + 0 + }; //!< Last version of exluded prims used during render index populate + size_t _usdStageVersion { 0 }; //!< Last version of stage used during render index populate + bool _drawRenderPurpose { + false + }; //!< Should the render delegate draw rprims with the "render" purpose + bool _drawProxyPurpose { + false + }; //!< Should the render delegate draw rprims with the "proxy" purpose + bool _drawGuidePurpose { + false + }; //!< Should the render delegate draw rprims with the "guide" purpose public: ProxyShapeData(const MayaUsdProxyShapeBase* proxyShape, const MDagPath& proxyDagPath); const MayaUsdProxyShapeBase* ProxyShape() const; - const MDagPath& ProxyDagPath() const; - UsdStageRefPtr UsdStage() const; - void UpdateUsdStage(); - bool IsUsdStageUpToDate() const; - void UsdStageUpdated(); - bool IsExcludePrimsUpToDate() const; - void ExcludePrimsUpdated(); - void UpdatePurpose(bool* drawRenderPurposeChanged, bool* drawProxyPurposeChanged, bool* drawGuidePurposeChanged); + const MDagPath& ProxyDagPath() const; + UsdStageRefPtr UsdStage() const; + void UpdateUsdStage(); + bool IsUsdStageUpToDate() const; + void UsdStageUpdated(); + bool IsExcludePrimsUpToDate() const; + void ExcludePrimsUpdated(); + void UpdatePurpose( + bool* drawRenderPurposeChanged, + bool* drawProxyPurposeChanged, + bool* drawGuidePurposeChanged); bool DrawRenderPurpose() const; bool DrawProxyPurpose() const; bool DrawGuidePurpose() const; }; - std::unique_ptr _proxyShapeData; + std::unique_ptr _proxyShapeData; // USD & Hydra Objects - HdEngine _engine; //!< Hydra engine responsible for running synchronization between scene delegate and VP2RenderDelegate - HdTaskSharedPtrVector _dummyTasks; //!< Dummy task to bootstrap data preparation inside Hydra engine - - std::unique_ptr _renderDelegate; //!< VP2RenderDelegate - std::unique_ptr _renderIndex; //!< Flattened representation of client scene graph - std::unique_ptr _taskController; //!< Task controller necessary for execution with hydra engine (we don't really need it, but there doesn't seem to be a way to get synchronization running without it) + HdEngine _engine; //!< Hydra engine responsible for running synchronization between scene + //!< delegate and VP2RenderDelegate + HdTaskSharedPtrVector + _dummyTasks; //!< Dummy task to bootstrap data preparation inside Hydra engine + + std::unique_ptr _renderDelegate; //!< VP2RenderDelegate + std::unique_ptr _renderIndex; //!< Flattened representation of client scene graph + std::unique_ptr + _taskController; //!< Task controller necessary for execution with hydra engine (we don't + //!< really need it, but there doesn't seem to be a way to get + //!< synchronization running without it) std::unique_ptr _sceneDelegate; //!< USD scene delegate - bool _isPopulated{ false }; //!< If false, scene delegate wasn't populated yet within render index - bool _selectionChanged{ true }; //!< Whether there is any selection change or not - MColor _wireframeColor; //!< Wireframe color assigned to the proxy shape + bool _isPopulated { + false + }; //!< If false, scene delegate wasn't populated yet within render index + bool _selectionChanged { true }; //!< Whether there is any selection change or not + MColor _wireframeColor; //!< Wireframe color assigned to the proxy shape //! A collection of Rprims to prepare render data for specified reprs std::unique_ptr _defaultCollection; //! The render tag version used the last time render tags were updated - unsigned int _renderTagVersion { 0 }; // initialized to 1 in HdChangeTracker, so we'll always have an - // invalid version the first update. + unsigned int _renderTagVersion { 0 }; // initialized to 1 in HdChangeTracker, so we'll always + // have an invalid version the first update. #ifdef ENABLE_RENDERTAG_VISIBILITY_WORKAROUND unsigned int _visibilityVersion { 0 }; // initialized to 1 in HdChangeTracker. #endif - bool _taskRenderTagsValid { false }; //!< If false the render tags on the dummy render task are not the minimum set of tags. + bool _taskRenderTagsValid { + false + }; //!< If false the render tags on the dummy render task are not the minimum set of tags. - MHWRender::DisplayStatus _displayStatus{ MHWRender::kNoStatus }; //!< The display status of the proxy shape - HdSelectionSharedPtr _leadSelection; //!< A collection of Rprims being lead selection - HdSelectionSharedPtr _activeSelection; //!< A collection of Rprims being active selection + MHWRender::DisplayStatus _displayStatus { + MHWRender::kNoStatus + }; //!< The display status of the proxy shape + HdSelectionSharedPtr _leadSelection; //!< A collection of Rprims being lead selection + HdSelectionSharedPtr _activeSelection; //!< A collection of Rprims being active selection #if defined(WANT_UFE_BUILD) //! Observer to listen to UFE changes - Ufe::Observer::Ptr _observer; + Ufe::Observer::Ptr _observer; #else //! Minimum support for proxy selection when UFE is not available. - MCallbackId _mayaSelectionCallbackId{ 0 }; + MCallbackId _mayaSelectionCallbackId { 0 }; #endif #if defined(WANT_UFE_BUILD) && defined(MAYA_ENABLE_UPDATE_FOR_SELECTION) @@ -237,15 +261,14 @@ class ProxyRenderDelegate : public MHWRender::MPxSubSceneOverride MGlobal::ListAdjustment _globalListAdjustment; //! Token of the Kind to be selected from viewport. If it empty, select the exact prims. - TfToken _selectionKind; + TfToken _selectionKind; #endif }; -/*! \brief Is this object properly initialized and can start receiving updates. Once this is done, render index needs to be populated and then we rely on change tracker. -*/ -inline bool ProxyRenderDelegate::_isInitialized() { - return (_sceneDelegate != nullptr); -} +/*! \brief Is this object properly initialized and can start receiving updates. Once this is done, + * render index needs to be populated and then we rely on change tracker. + */ +inline bool ProxyRenderDelegate::_isInitialized() { return (_sceneDelegate != nullptr); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/render_delegate.cpp b/lib/mayaUsd/render/vp2RenderDelegate/render_delegate.cpp index 77ed7c8c50..c99fd0a5f3 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/render_delegate.cpp +++ b/lib/mayaUsd/render/vp2RenderDelegate/render_delegate.cpp @@ -15,14 +15,14 @@ // #include "render_delegate.h" -#include - -#include -#include - -#include +#include "basisCurves.h" +#include "bboxGeom.h" +#include "instancer.h" +#include "material.h" +#include "mesh.h" +#include "render_pass.h" -#include +#include #include #include @@ -31,419 +31,402 @@ #include #include -#include +#include -#include "basisCurves.h" -#include "bboxGeom.h" -#include "instancer.h" -#include "material.h" -#include "mesh.h" -#include "render_pass.h" +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -namespace +namespace { +/*! \brief List of supported Rprims by VP2 render delegate + */ +inline const TfTokenVector& _SupportedRprimTypes() { - /*! \brief List of supported Rprims by VP2 render delegate - */ - inline const TfTokenVector& _SupportedRprimTypes() { - static const TfTokenVector SUPPORTED_RPRIM_TYPES = - { - HdPrimTypeTokens->basisCurves, - HdPrimTypeTokens->mesh - }; - return SUPPORTED_RPRIM_TYPES; - } + static const TfTokenVector SUPPORTED_RPRIM_TYPES + = { HdPrimTypeTokens->basisCurves, HdPrimTypeTokens->mesh }; + return SUPPORTED_RPRIM_TYPES; +} - /*! \brief List of supported Sprims by VP2 render delegate - */ - inline const TfTokenVector& _SupportedSprimTypes() { - static const TfTokenVector r{ - HdPrimTypeTokens->material, HdPrimTypeTokens->camera }; - return r; - } +/*! \brief List of supported Sprims by VP2 render delegate + */ +inline const TfTokenVector& _SupportedSprimTypes() +{ + static const TfTokenVector r { HdPrimTypeTokens->material, HdPrimTypeTokens->camera }; + return r; +} - /*! \brief List of supported Bprims by VP2 render delegate - */ - inline const TfTokenVector& _SupportedBprimTypes() { - static const TfTokenVector r{ HdPrimTypeTokens->texture }; - return r; - } - - const MString _diffuseColorParameterName = "diffuseColor"; //!< Shader parameter name - const MString _solidColorParameterName = "solidColor"; //!< Shader parameter name - const MString _pointSizeParameterName = "pointSize"; //!< Shader parameter name - const MString _curveBasisParameterName = "curveBasis"; //!< Shader parameter name - const MString _structOutputName = "outSurfaceFinal"; //!< Output struct name of the fallback shader - - //! Enum class for fallback shader types - enum class FallbackShaderType { - kCommon = 0, - kBasisCurvesLinear, - kBasisCurvesCubicBezier, - kBasisCurvesCubicBSpline, - kBasisCurvesCubicCatmullRom, - kCount - }; - - //! Total number of fallback shader types - constexpr size_t FallbackShaderTypeCount = static_cast(FallbackShaderType::kCount); - - //! Array of constant-color shader fragment names indexed by FallbackShaderType - const MString _fallbackShaderNames[] = { "FallbackShader", - "BasisCurvesLinearFallbackShader", - "BasisCurvesCubicFallbackShader", - "BasisCurvesCubicFallbackShader", - "BasisCurvesCubicFallbackShader" }; - - //! Array of varying-color shader fragment names indexed by FallbackShaderType - const MString _cpvFallbackShaderNames[] = { "FallbackCPVShader", - "BasisCurvesLinearCPVShader", - "BasisCurvesCubicCPVShader", - "BasisCurvesCubicCPVShader", - "BasisCurvesCubicCPVShader" }; - - //! "curveBasis" parameter values for three different cubic curves - const std::unordered_map _curveBasisParameterValueMapping - = { { FallbackShaderType::kBasisCurvesCubicBezier, 0 }, - { FallbackShaderType::kBasisCurvesCubicBSpline, 1 }, - { FallbackShaderType::kBasisCurvesCubicCatmullRom, 2 } }; - - //! Get the shader type needed by the given curveType and curveBasis - FallbackShaderType - GetBasisCurvesShaderType(const TfToken& curveType, const TfToken& curveBasis) - { - FallbackShaderType type = FallbackShaderType::kCount; - - if (curveType == HdTokens->linear) { - type = FallbackShaderType::kBasisCurvesLinear; - } else if (curveType == HdTokens->cubic) { - if (curveBasis == HdTokens->bezier) { - type = FallbackShaderType::kBasisCurvesCubicBezier; - } else if (curveBasis == HdTokens->bSpline) { - type = FallbackShaderType::kBasisCurvesCubicBSpline; - } else if (curveBasis == HdTokens->catmullRom) { - type = FallbackShaderType::kBasisCurvesCubicCatmullRom; - } - } +/*! \brief List of supported Bprims by VP2 render delegate + */ +inline const TfTokenVector& _SupportedBprimTypes() +{ + static const TfTokenVector r { HdPrimTypeTokens->texture }; + return r; +} - return type; - } +const MString _diffuseColorParameterName = "diffuseColor"; //!< Shader parameter name +const MString _solidColorParameterName = "solidColor"; //!< Shader parameter name +const MString _pointSizeParameterName = "pointSize"; //!< Shader parameter name +const MString _curveBasisParameterName = "curveBasis"; //!< Shader parameter name +const MString _structOutputName = "outSurfaceFinal"; //!< Output struct name of the fallback shader - /*! \brief Color hash helper class, used by shader registry - */ - struct MColorHash - { - std::size_t operator()(const MColor& color) const - { - std::size_t seed = 0; - boost::hash_combine(seed, color.r); - boost::hash_combine(seed, color.g); - boost::hash_combine(seed, color.b); - boost::hash_combine(seed, color.a); - return seed; +//! Enum class for fallback shader types +enum class FallbackShaderType +{ + kCommon = 0, + kBasisCurvesLinear, + kBasisCurvesCubicBezier, + kBasisCurvesCubicBSpline, + kBasisCurvesCubicCatmullRom, + kCount +}; + +//! Total number of fallback shader types +constexpr size_t FallbackShaderTypeCount = static_cast(FallbackShaderType::kCount); + +//! Array of constant-color shader fragment names indexed by FallbackShaderType +const MString _fallbackShaderNames[] = { "FallbackShader", + "BasisCurvesLinearFallbackShader", + "BasisCurvesCubicFallbackShader", + "BasisCurvesCubicFallbackShader", + "BasisCurvesCubicFallbackShader" }; + +//! Array of varying-color shader fragment names indexed by FallbackShaderType +const MString _cpvFallbackShaderNames[] = { "FallbackCPVShader", + "BasisCurvesLinearCPVShader", + "BasisCurvesCubicCPVShader", + "BasisCurvesCubicCPVShader", + "BasisCurvesCubicCPVShader" }; + +//! "curveBasis" parameter values for three different cubic curves +const std::unordered_map _curveBasisParameterValueMapping + = { { FallbackShaderType::kBasisCurvesCubicBezier, 0 }, + { FallbackShaderType::kBasisCurvesCubicBSpline, 1 }, + { FallbackShaderType::kBasisCurvesCubicCatmullRom, 2 } }; + +//! Get the shader type needed by the given curveType and curveBasis +FallbackShaderType GetBasisCurvesShaderType(const TfToken& curveType, const TfToken& curveBasis) +{ + FallbackShaderType type = FallbackShaderType::kCount; + + if (curveType == HdTokens->linear) { + type = FallbackShaderType::kBasisCurvesLinear; + } else if (curveType == HdTokens->cubic) { + if (curveBasis == HdTokens->bezier) { + type = FallbackShaderType::kBasisCurvesCubicBezier; + } else if (curveBasis == HdTokens->bSpline) { + type = FallbackShaderType::kBasisCurvesCubicBSpline; + } else if (curveBasis == HdTokens->catmullRom) { + type = FallbackShaderType::kBasisCurvesCubicCatmullRom; } - }; + } - /*! \brief Color-indexed shader map. - */ - struct MShaderMap + return type; +} + +/*! \brief Color hash helper class, used by shader registry + */ +struct MColorHash +{ + std::size_t operator()(const MColor& color) const { - //! Shader registry - std::unordered_map _map; + std::size_t seed = 0; + boost::hash_combine(seed, color.r); + boost::hash_combine(seed, color.g); + boost::hash_combine(seed, color.b); + boost::hash_combine(seed, color.a); + return seed; + } +}; + +/*! \brief Color-indexed shader map. + */ +struct MShaderMap +{ + //! Shader registry + std::unordered_map _map; - //! Synchronization used to protect concurrent read from serial writes - tbb::spin_rw_mutex _mutex; - }; + //! Synchronization used to protect concurrent read from serial writes + tbb::spin_rw_mutex _mutex; +}; - /*! \brief Shader cache. - */ - class MShaderCache final +/*! \brief Shader cache. + */ +class MShaderCache final +{ +public: + /*! \brief Initialize shaders. + */ + void Initialize() { - public: - /*! \brief Initialize shaders. - */ - void Initialize() - { - if (_isInitialized) - return; - - MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(); - const MHWRender::MShaderManager* shaderMgr = - renderer ? renderer->getShaderManager() : nullptr; - if (!TF_VERIFY(shaderMgr)) - return; - - _3dCPVSolidShader = shaderMgr->getStockShader( - MHWRender::MShaderManager::k3dCPVSolidShader); - - TF_VERIFY(_3dCPVSolidShader); - - _3dFatPointShader = shaderMgr->getStockShader( - MHWRender::MShaderManager::k3dFatPointShader); - - if (TF_VERIFY(_3dFatPointShader)) { - constexpr float white[] = { 1.0f, 1.0f, 1.0f, 1.0f }; - constexpr float size[] = { 5.0, 5.0 }; - - _3dFatPointShader->setParameter(_solidColorParameterName, white); - _3dFatPointShader->setParameter(_pointSizeParameterName, size); - } + if (_isInitialized) + return; - for (size_t i = 0; i < FallbackShaderTypeCount; i++) { - MHWRender::MShaderInstance* shader = shaderMgr->getFragmentShader( - _cpvFallbackShaderNames[i], _structOutputName, true); + MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(); + const MHWRender::MShaderManager* shaderMgr + = renderer ? renderer->getShaderManager() : nullptr; + if (!TF_VERIFY(shaderMgr)) + return; - if (TF_VERIFY(shader)) { - FallbackShaderType type = static_cast(i); - const auto it = _curveBasisParameterValueMapping.find(type); - if (it != _curveBasisParameterValueMapping.end()) { - shader->setParameter(_curveBasisParameterName, it->second); - } - } + _3dCPVSolidShader = shaderMgr->getStockShader(MHWRender::MShaderManager::k3dCPVSolidShader); - _fallbackCPVShaders[i] = shader; - } + TF_VERIFY(_3dCPVSolidShader); + + _3dFatPointShader = shaderMgr->getStockShader(MHWRender::MShaderManager::k3dFatPointShader); - _isInitialized = true; + if (TF_VERIFY(_3dFatPointShader)) { + constexpr float white[] = { 1.0f, 1.0f, 1.0f, 1.0f }; + constexpr float size[] = { 5.0, 5.0 }; + + _3dFatPointShader->setParameter(_solidColorParameterName, white); + _3dFatPointShader->setParameter(_pointSizeParameterName, size); } - /*! \brief Returns a fallback CPV shader instance when no material is bound. - */ - MHWRender::MShaderInstance* GetFallbackCPVShader(FallbackShaderType type) const { - if (type >= FallbackShaderType::kCount) { - return nullptr; + for (size_t i = 0; i < FallbackShaderTypeCount; i++) { + MHWRender::MShaderInstance* shader + = shaderMgr->getFragmentShader(_cpvFallbackShaderNames[i], _structOutputName, true); + + if (TF_VERIFY(shader)) { + FallbackShaderType type = static_cast(i); + const auto it = _curveBasisParameterValueMapping.find(type); + if (it != _curveBasisParameterValueMapping.end()) { + shader->setParameter(_curveBasisParameterName, it->second); + } } - const size_t index = static_cast(type); - return _fallbackCPVShaders[index]; + _fallbackCPVShaders[i] = shader; } - /*! \brief Returns a white 3d fat point shader. - */ - MHWRender::MShaderInstance* Get3dFatPointShader() const { - return _3dFatPointShader; - } + _isInitialized = true; + } - /*! \brief Returns a 3d CPV solid-color shader instance. - */ - MHWRender::MShaderInstance* Get3dCPVSolidShader() const { - return _3dCPVSolidShader; + /*! \brief Returns a fallback CPV shader instance when no material is bound. + */ + MHWRender::MShaderInstance* GetFallbackCPVShader(FallbackShaderType type) const + { + if (type >= FallbackShaderType::kCount) { + return nullptr; } - /*! \brief Returns a 3d solid shader with the specified color. - */ - MHWRender::MShaderInstance* Get3dSolidShader(const MColor& color) - { - // Look for it first with reader lock - tbb::spin_rw_mutex::scoped_lock lock(_3dSolidShaders._mutex, false/*write*/); - auto it = _3dSolidShaders._map.find(color); - if (it != _3dSolidShaders._map.end()) { - return it->second; - } + const size_t index = static_cast(type); + return _fallbackCPVShaders[index]; + } - // Upgrade to writer lock. - lock.upgrade_to_writer(); + /*! \brief Returns a white 3d fat point shader. + */ + MHWRender::MShaderInstance* Get3dFatPointShader() const { return _3dFatPointShader; } - // Double check that it wasn't inserted by another thread - it = _3dSolidShaders._map.find(color); - if (it != _3dSolidShaders._map.end()) { - return it->second; - } + /*! \brief Returns a 3d CPV solid-color shader instance. + */ + MHWRender::MShaderInstance* Get3dCPVSolidShader() const { return _3dCPVSolidShader; } - MHWRender::MShaderInstance* shader = nullptr; + /*! \brief Returns a 3d solid shader with the specified color. + */ + MHWRender::MShaderInstance* Get3dSolidShader(const MColor& color) + { + // Look for it first with reader lock + tbb::spin_rw_mutex::scoped_lock lock(_3dSolidShaders._mutex, false /*write*/); + auto it = _3dSolidShaders._map.find(color); + if (it != _3dSolidShaders._map.end()) { + return it->second; + } - MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(); - const MHWRender::MShaderManager* shaderMgr = - renderer ? renderer->getShaderManager() : nullptr; - if (TF_VERIFY(shaderMgr)) { - shader = shaderMgr->getStockShader( - MHWRender::MShaderManager::k3dSolidShader); + // Upgrade to writer lock. + lock.upgrade_to_writer(); - if (TF_VERIFY(shader)) { - const float solidColor[] = { color.r, color.g, color.b, color.a }; - shader->setParameter(_solidColorParameterName, solidColor); + // Double check that it wasn't inserted by another thread + it = _3dSolidShaders._map.find(color); + if (it != _3dSolidShaders._map.end()) { + return it->second; + } - // Insert instance we just created - _3dSolidShaders._map[color] = shader; - } - } + MHWRender::MShaderInstance* shader = nullptr; + + MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(); + const MHWRender::MShaderManager* shaderMgr + = renderer ? renderer->getShaderManager() : nullptr; + if (TF_VERIFY(shaderMgr)) { + shader = shaderMgr->getStockShader(MHWRender::MShaderManager::k3dSolidShader); + + if (TF_VERIFY(shader)) { + const float solidColor[] = { color.r, color.g, color.b, color.a }; + shader->setParameter(_solidColorParameterName, solidColor); - return shader; + // Insert instance we just created + _3dSolidShaders._map[color] = shader; + } } - /*! \brief Returns a fallback shader instance when no material is bound. + return shader; + } - This method is keeping registry of all fallback shaders generated, - allowing only one instance per color which enables consolidation of - draw calls with same shader instance. + /*! \brief Returns a fallback shader instance when no material is bound. - \param color Color to set on given shader instance - \param index Index to the required shader name in _fallbackShaderNames + This method is keeping registry of all fallback shaders generated, + allowing only one instance per color which enables consolidation of + draw calls with same shader instance. - \return A new or existing copy of shader instance with given color - */ - MHWRender::MShaderInstance* GetFallbackShader(const MColor& color, FallbackShaderType type) - { - if (type >= FallbackShaderType::kCount) { - return nullptr; - } + \param color Color to set on given shader instance + \param index Index to the required shader name in _fallbackShaderNames - const size_t index = static_cast(type); - auto& shaderMap = _fallbackShaders[index]; + \return A new or existing copy of shader instance with given color + */ + MHWRender::MShaderInstance* GetFallbackShader(const MColor& color, FallbackShaderType type) + { + if (type >= FallbackShaderType::kCount) { + return nullptr; + } - // Look for it first with reader lock - tbb::spin_rw_mutex::scoped_lock lock(shaderMap._mutex, false/*write*/); - auto it = shaderMap._map.find(color); - if (it != shaderMap._map.end()) { - return it->second; - } + const size_t index = static_cast(type); + auto& shaderMap = _fallbackShaders[index]; - // Upgrade to writer lock. - lock.upgrade_to_writer(); + // Look for it first with reader lock + tbb::spin_rw_mutex::scoped_lock lock(shaderMap._mutex, false /*write*/); + auto it = shaderMap._map.find(color); + if (it != shaderMap._map.end()) { + return it->second; + } - // Double check that it wasn't inserted by another thread - it = shaderMap._map.find(color); - if (it != shaderMap._map.end()) { - return it->second; - } + // Upgrade to writer lock. + lock.upgrade_to_writer(); - MHWRender::MShaderInstance* shader = nullptr; + // Double check that it wasn't inserted by another thread + it = shaderMap._map.find(color); + if (it != shaderMap._map.end()) { + return it->second; + } - // If the map is not empty, clone any existing shader instance in the - // map instead of acquiring via MShaderManager::getFragmentShader(), - // which creates new shader fragment graph for each shader instance - // and causes expensive shader compilation and rebinding. - it = shaderMap._map.begin(); - if (it != shaderMap._map.end()) { - shader = it->second->clone(); - } - else { - MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(); - const MHWRender::MShaderManager* shaderMgr = - renderer ? renderer->getShaderManager() : nullptr; - if (TF_VERIFY(shaderMgr)) { - shader = shaderMgr->getFragmentShader( - _fallbackShaderNames[index], _structOutputName, true); - - if (TF_VERIFY(shader)) { - const auto it = _curveBasisParameterValueMapping.find(type); - if (it != _curveBasisParameterValueMapping.end()) { - shader->setParameter(_curveBasisParameterName, it->second); - } + MHWRender::MShaderInstance* shader = nullptr; + + // If the map is not empty, clone any existing shader instance in the + // map instead of acquiring via MShaderManager::getFragmentShader(), + // which creates new shader fragment graph for each shader instance + // and causes expensive shader compilation and rebinding. + it = shaderMap._map.begin(); + if (it != shaderMap._map.end()) { + shader = it->second->clone(); + } else { + MHWRender::MRenderer* renderer = MHWRender::MRenderer::theRenderer(); + const MHWRender::MShaderManager* shaderMgr + = renderer ? renderer->getShaderManager() : nullptr; + if (TF_VERIFY(shaderMgr)) { + shader = shaderMgr->getFragmentShader( + _fallbackShaderNames[index], _structOutputName, true); + + if (TF_VERIFY(shader)) { + const auto it = _curveBasisParameterValueMapping.find(type); + if (it != _curveBasisParameterValueMapping.end()) { + shader->setParameter(_curveBasisParameterName, it->second); } } } + } - // Insert the new shader instance - if (TF_VERIFY(shader)) { - float diffuseColor[] = { color.r, color.g, color.b, color.a }; - shader->setParameter(_diffuseColorParameterName, diffuseColor); - shaderMap._map[color] = shader; - } - - return shader; + // Insert the new shader instance + if (TF_VERIFY(shader)) { + float diffuseColor[] = { color.r, color.g, color.b, color.a }; + shader->setParameter(_diffuseColorParameterName, diffuseColor); + shaderMap._map[color] = shader; } - private: - bool _isInitialized { false }; //!< Whether the shader cache is initialized + return shader; + } - //! Shader registry used by fallback shaders - MShaderMap _fallbackShaders[FallbackShaderTypeCount]; - MShaderMap _3dSolidShaders; +private: + bool _isInitialized { false }; //!< Whether the shader cache is initialized - //!< Fallback shaders with CPV support - MHWRender::MShaderInstance* _fallbackCPVShaders[FallbackShaderTypeCount] { nullptr }; + //! Shader registry used by fallback shaders + MShaderMap _fallbackShaders[FallbackShaderTypeCount]; + MShaderMap _3dSolidShaders; - MHWRender::MShaderInstance* _3dFatPointShader { nullptr }; //!< 3d shader for points - MHWRender::MShaderInstance* _3dCPVSolidShader { nullptr }; //!< 3d CPV solid-color shader - }; + //!< Fallback shaders with CPV support + MHWRender::MShaderInstance* _fallbackCPVShaders[FallbackShaderTypeCount] { nullptr }; - MShaderCache sShaderCache; //!< Global shader cache to minimize the number of unique shaders. + MHWRender::MShaderInstance* _3dFatPointShader { nullptr }; //!< 3d shader for points + MHWRender::MShaderInstance* _3dCPVSolidShader { nullptr }; //!< 3d CPV solid-color shader +}; - /*! \brief Sampler state desc hash helper class, used by sampler state cache. - */ - struct MSamplerStateDescHash - { - std::size_t operator()(const MHWRender::MSamplerStateDesc& desc) const - { - std::size_t seed = 0; - boost::hash_combine(seed, desc.filter); - boost::hash_combine(seed, desc.comparisonFn); - boost::hash_combine(seed, desc.addressU); - boost::hash_combine(seed, desc.addressV); - boost::hash_combine(seed, desc.addressW); - boost::hash_combine(seed, desc.borderColor[0]); - boost::hash_combine(seed, desc.borderColor[1]); - boost::hash_combine(seed, desc.borderColor[2]); - boost::hash_combine(seed, desc.borderColor[3]); - boost::hash_combine(seed, desc.mipLODBias); - boost::hash_combine(seed, desc.minLOD); - boost::hash_combine(seed, desc.maxLOD); - boost::hash_combine(seed, desc.maxAnisotropy); - boost::hash_combine(seed, desc.coordCount); - boost::hash_combine(seed, desc.elementIndex); - return seed; - } - }; +MShaderCache sShaderCache; //!< Global shader cache to minimize the number of unique shaders. - /*! Sampler state desc equality helper class, used by sampler state cache. - */ - struct MSamplerStateDescEquality +/*! \brief Sampler state desc hash helper class, used by sampler state cache. + */ +struct MSamplerStateDescHash +{ + std::size_t operator()(const MHWRender::MSamplerStateDesc& desc) const { - bool operator() ( - const MHWRender::MSamplerStateDesc& a, - const MHWRender::MSamplerStateDesc& b) const - { - return ( - a.filter == b.filter && - a.comparisonFn == b.comparisonFn && - a.addressU == b.addressU && - a.addressV == b.addressV && - a.addressW == b.addressW && - a.borderColor[0] == b.borderColor[0] && - a.borderColor[1] == b.borderColor[1] && - a.borderColor[2] == b.borderColor[2] && - a.borderColor[3] == b.borderColor[3] && - a.mipLODBias == b.mipLODBias && - a.minLOD == b.minLOD && - a.maxLOD == b.maxLOD && - a.maxAnisotropy == b.maxAnisotropy && - a.coordCount == b.coordCount && - a.elementIndex == b.elementIndex - ); - } - }; - - using MSamplerStateCache = std::unordered_map< - MHWRender::MSamplerStateDesc, - const MHWRender::MSamplerState*, - MSamplerStateDescHash, - MSamplerStateDescEquality - >; - - MSamplerStateCache sSamplerStates; //!< Sampler state cache - tbb::spin_rw_mutex sSamplerRWMutex; //!< Synchronization used to protect concurrent read from serial writes - - const HdVP2BBoxGeom* sSharedBBoxGeom = nullptr; //!< Shared geometry for all Rprims to display bounding box + std::size_t seed = 0; + boost::hash_combine(seed, desc.filter); + boost::hash_combine(seed, desc.comparisonFn); + boost::hash_combine(seed, desc.addressU); + boost::hash_combine(seed, desc.addressV); + boost::hash_combine(seed, desc.addressW); + boost::hash_combine(seed, desc.borderColor[0]); + boost::hash_combine(seed, desc.borderColor[1]); + boost::hash_combine(seed, desc.borderColor[2]); + boost::hash_combine(seed, desc.borderColor[3]); + boost::hash_combine(seed, desc.mipLODBias); + boost::hash_combine(seed, desc.minLOD); + boost::hash_combine(seed, desc.maxLOD); + boost::hash_combine(seed, desc.maxAnisotropy); + boost::hash_combine(seed, desc.coordCount); + boost::hash_combine(seed, desc.elementIndex); + return seed; + } +}; + +/*! Sampler state desc equality helper class, used by sampler state cache. + */ +struct MSamplerStateDescEquality +{ + bool + operator()(const MHWRender::MSamplerStateDesc& a, const MHWRender::MSamplerStateDesc& b) const + { + return ( + a.filter == b.filter && a.comparisonFn == b.comparisonFn && a.addressU == b.addressU + && a.addressV == b.addressV && a.addressW == b.addressW + && a.borderColor[0] == b.borderColor[0] && a.borderColor[1] == b.borderColor[1] + && a.borderColor[2] == b.borderColor[2] && a.borderColor[3] == b.borderColor[3] + && a.mipLODBias == b.mipLODBias && a.minLOD == b.minLOD && a.maxLOD == b.maxLOD + && a.maxAnisotropy == b.maxAnisotropy && a.coordCount == b.coordCount + && a.elementIndex == b.elementIndex); + } +}; + +using MSamplerStateCache = std::unordered_map< + MHWRender::MSamplerStateDesc, + const MHWRender::MSamplerState*, + MSamplerStateDescHash, + MSamplerStateDescEquality>; + +MSamplerStateCache sSamplerStates; //!< Sampler state cache +tbb::spin_rw_mutex + sSamplerRWMutex; //!< Synchronization used to protect concurrent read from serial writes + +const HdVP2BBoxGeom* sSharedBBoxGeom + = nullptr; //!< Shared geometry for all Rprims to display bounding box } // namespace const int HdVP2RenderDelegate::sProfilerCategory = MProfiler::addCategory( #if MAYA_API_VERSION >= 20190000 - "HdVP2RenderDelegate", "HdVP2RenderDelegate" + "HdVP2RenderDelegate", + "HdVP2RenderDelegate" #else "HdVP2RenderDelegate" #endif ); -std::mutex HdVP2RenderDelegate::_renderDelegateMutex; -std::atomic_int HdVP2RenderDelegate::_renderDelegateCounter; +std::mutex HdVP2RenderDelegate::_renderDelegateMutex; +std::atomic_int HdVP2RenderDelegate::_renderDelegateCounter; HdResourceRegistrySharedPtr HdVP2RenderDelegate::_resourceRegistry; /*! \brief Constructor. -*/ -HdVP2RenderDelegate::HdVP2RenderDelegate(ProxyRenderDelegate& drawScene) { + */ +HdVP2RenderDelegate::HdVP2RenderDelegate(ProxyRenderDelegate& drawScene) +{ _id = SdfPath(TfToken(TfStringPrintf("/HdVP2RenderDelegate_%p", this))); std::lock_guard guard(_renderDelegateMutex); @@ -471,8 +454,9 @@ HdVP2RenderDelegate::HdVP2RenderDelegate(ProxyRenderDelegate& drawScene) { } /*! \brief Destructor. -*/ -HdVP2RenderDelegate::~HdVP2RenderDelegate() { + */ +HdVP2RenderDelegate::~HdVP2RenderDelegate() +{ std::lock_guard guard(_renderDelegateMutex); if (_renderDelegateCounter.fetch_sub(1) == 1) { _resourceRegistry.reset(); @@ -485,10 +469,8 @@ HdVP2RenderDelegate::~HdVP2RenderDelegate() { } /*! \brief Return delegate's HdVP2RenderParam, giving access to things like MPxSubSceneOverride. -*/ -HdRenderParam* HdVP2RenderDelegate::GetRenderParam() const { - return _renderParam.get(); -} + */ +HdRenderParam* HdVP2RenderDelegate::GetRenderParam() const { return _renderParam.get(); } /*! \brief Notification to commit resources to GPU & compute before rendering @@ -500,7 +482,8 @@ HdRenderParam* HdVP2RenderDelegate::GetRenderParam() const { of data and allow main-thread task execution during the compute as it's done for the rest of VP2 synchronization with DG data. */ -void HdVP2RenderDelegate::CommitResources(HdChangeTracker* tracker) { +void HdVP2RenderDelegate::CommitResources(HdChangeTracker* tracker) +{ TF_UNUSED(tracker); MProfilingScope profilingScope(sProfilerCategory, MProfiler::kColorC_L2, "Commit resources"); @@ -518,38 +501,45 @@ void HdVP2RenderDelegate::CommitResources(HdChangeTracker* tracker) { } /*! \brief Return a list of which Rprim types can be created by this class's. -*/ -const TfTokenVector& HdVP2RenderDelegate::GetSupportedRprimTypes() const { + */ +const TfTokenVector& HdVP2RenderDelegate::GetSupportedRprimTypes() const +{ return _SupportedRprimTypes(); } /*! \brief Return a list of which Sprim types can be created by this class's. -*/ -const TfTokenVector& HdVP2RenderDelegate::GetSupportedSprimTypes() const { + */ +const TfTokenVector& HdVP2RenderDelegate::GetSupportedSprimTypes() const +{ return _SupportedSprimTypes(); } /*! \brief Return a list of which Bprim types can be created by this class's. -*/ -const TfTokenVector& HdVP2RenderDelegate::GetSupportedBprimTypes() const { + */ +const TfTokenVector& HdVP2RenderDelegate::GetSupportedBprimTypes() const +{ return _SupportedBprimTypes(); } /*! \brief Return unused global resource registry. -*/ -HdResourceRegistrySharedPtr HdVP2RenderDelegate::GetResourceRegistry() const { + */ +HdResourceRegistrySharedPtr HdVP2RenderDelegate::GetResourceRegistry() const +{ return _resourceRegistry; } /*! \brief Return VP2 resource registry, holding access to commit execution enqueue. -*/ -HdVP2ResourceRegistry& HdVP2RenderDelegate::GetVP2ResourceRegistry() { + */ +HdVP2ResourceRegistry& HdVP2RenderDelegate::GetVP2ResourceRegistry() +{ return _resourceRegistryVP2; } /*! \brief Create a renderpass for rendering a given collection. -*/ -HdRenderPassSharedPtr HdVP2RenderDelegate::CreateRenderPass(HdRenderIndex* index, const HdRprimCollection& collection) { + */ +HdRenderPassSharedPtr +HdVP2RenderDelegate::CreateRenderPass(HdRenderIndex* index, const HdRprimCollection& collection) +{ return HdRenderPassSharedPtr(new HdVP2RenderPass(this, index, collection)); } @@ -562,16 +552,17 @@ HdRenderPassSharedPtr HdVP2RenderDelegate::CreateRenderPass(HdRenderIndex* index \return A pointer to the new instancer or nullptr on error. */ HdInstancer* HdVP2RenderDelegate::CreateInstancer( - HdSceneDelegate* delegate, const SdfPath& id, const SdfPath& instancerId) { - + HdSceneDelegate* delegate, + const SdfPath& id, + const SdfPath& instancerId) +{ + return new HdVP2Instancer(delegate, id, instancerId); } /*! \brief Destroy instancer instance -*/ -void HdVP2RenderDelegate::DestroyInstancer(HdInstancer* instancer) { - delete instancer; -} + */ +void HdVP2RenderDelegate::DestroyInstancer(HdInstancer* instancer) { delete instancer; } /*! \brief Request to Allocate and Construct a new, VP2 specialized Rprim. @@ -583,14 +574,17 @@ void HdVP2RenderDelegate::DestroyInstancer(HdInstancer* instancer) { \return A pointer to the new prim or nullptr on error. */ HdRprim* HdVP2RenderDelegate::CreateRprim( - const TfToken& typeId, const SdfPath& rprimId, const SdfPath& instancerId) { + const TfToken& typeId, + const SdfPath& rprimId, + const SdfPath& instancerId) +{ if (typeId == HdPrimTypeTokens->mesh) { return new HdVP2Mesh(this, rprimId, instancerId); } if (typeId == HdPrimTypeTokens->basisCurves) { return new HdVP2BasisCurves(this, rprimId, instancerId); } - //if (typeId == HdPrimTypeTokens->volume) { + // if (typeId == HdPrimTypeTokens->volume) { // return new HdVP2Volume(this, rprimId, instancerId); //} TF_CODING_ERROR("Unknown Rprim Type %s", typeId.GetText()); @@ -598,10 +592,8 @@ HdRprim* HdVP2RenderDelegate::CreateRprim( } /*! \brief Destroy & deallocate Rprim instance -*/ -void HdVP2RenderDelegate::DestroyRprim(HdRprim* rPrim) { - delete rPrim; -} + */ +void HdVP2RenderDelegate::DestroyRprim(HdRprim* rPrim) { delete rPrim; } /*! \brief Request to Allocate and Construct a new, VP2 specialized Sprim. @@ -610,13 +602,13 @@ void HdVP2RenderDelegate::DestroyRprim(HdRprim* rPrim) { \return A pointer to the new prim or nullptr on error. */ -HdSprim* HdVP2RenderDelegate::CreateSprim( - const TfToken& typeId, const SdfPath& sprimId) { +HdSprim* HdVP2RenderDelegate::CreateSprim(const TfToken& typeId, const SdfPath& sprimId) +{ if (typeId == HdPrimTypeTokens->material) { return new HdVP2Material(this, sprimId); } - if (typeId == HdPrimTypeTokens->camera) { - return new HdCamera(sprimId); + if (typeId == HdPrimTypeTokens->camera) { + return new HdCamera(sprimId); } /* if (typeId == HdPrimTypeTokens->sphereLight) { @@ -651,7 +643,8 @@ HdSprim* HdVP2RenderDelegate::CreateSprim( \return A pointer to the new prim or nullptr on error. */ -HdSprim* HdVP2RenderDelegate::CreateFallbackSprim(const TfToken& typeId) { +HdSprim* HdVP2RenderDelegate::CreateFallbackSprim(const TfToken& typeId) +{ if (typeId == HdPrimTypeTokens->material) { return new HdVP2Material(this, SdfPath::EmptyPath()); } @@ -683,20 +676,18 @@ HdSprim* HdVP2RenderDelegate::CreateFallbackSprim(const TfToken& typeId) { } /*! \brief Destroy & deallocate Sprim instance -*/ -void HdVP2RenderDelegate::DestroySprim(HdSprim* sPrim) { - delete sPrim; -} + */ +void HdVP2RenderDelegate::DestroySprim(HdSprim* sPrim) { delete sPrim; } /*! \brief Request to Allocate and Construct a new, VP2 specialized Bprim. - + \param typeId the type identifier of the prim to allocate \param sprimId a unique identifier for the prim \return A pointer to the new prim or nullptr on error. */ -HdBprim* HdVP2RenderDelegate::CreateBprim( - const TfToken& typeId, const SdfPath& bprimId) { +HdBprim* HdVP2RenderDelegate::CreateBprim(const TfToken& typeId, const SdfPath& bprimId) +{ /* if (typeId == HdPrimTypeTokens->texture) { return new HdVP2Texture(this, bprimId); @@ -721,7 +712,8 @@ HdBprim* HdVP2RenderDelegate::CreateBprim( \return A pointer to the new prim or nullptr on error. */ -HdBprim* HdVP2RenderDelegate::CreateFallbackBprim(const TfToken& typeId) { +HdBprim* HdVP2RenderDelegate::CreateFallbackBprim(const TfToken& typeId) +{ /* if (typeId == HdPrimTypeTokens->texture) { return new HdVP2Texture(this, SdfPath::EmptyPath()); @@ -738,23 +730,20 @@ HdBprim* HdVP2RenderDelegate::CreateFallbackBprim(const TfToken& typeId) { } /*! \brief Destroy & deallocate Bprim instance -*/ -void HdVP2RenderDelegate::DestroyBprim(HdBprim* bPrim) { - delete bPrim; -} + */ +void HdVP2RenderDelegate::DestroyBprim(HdBprim* bPrim) { delete bPrim; } /*! \brief Returns a token that indicates material bindings purpose. The full material purpose is suggested according to https://github.com/PixarAnimationStudios/USD/pull/853 */ -TfToken HdVP2RenderDelegate::GetMaterialBindingPurpose() const { - return HdTokens->full; -} +TfToken HdVP2RenderDelegate::GetMaterialBindingPurpose() const { return HdTokens->full; } /*! \brief Returns a node name made as a child of delegate's id. -*/ -MString HdVP2RenderDelegate::GetLocalNodeName(const MString& name) const { + */ +MString HdVP2RenderDelegate::GetLocalNodeName(const MString& name) const +{ return MString(_id.AppendChild(TfToken(name.asChar())).GetText()); } @@ -768,8 +757,7 @@ MString HdVP2RenderDelegate::GetLocalNodeName(const MString& name) const { \return A new or existing copy of shader instance with given color parameter set */ -MHWRender::MShaderInstance* HdVP2RenderDelegate::GetFallbackShader( - const MColor& color) const +MHWRender::MShaderInstance* HdVP2RenderDelegate::GetFallbackShader(const MColor& color) const { return sShaderCache.GetFallbackShader(color, FallbackShaderType::kCommon); } @@ -815,41 +803,40 @@ MHWRender::MShaderInstance* HdVP2RenderDelegate::GetBasisCurvesCPVShader( } /*! \brief Returns a fallback CPV shader instance when no material is bound. -*/ + */ MHWRender::MShaderInstance* HdVP2RenderDelegate::GetFallbackCPVShader() const { return sShaderCache.GetFallbackCPVShader(FallbackShaderType::kCommon); } /*! \brief Returns a 3d solid-color shader. -*/ -MHWRender::MShaderInstance* HdVP2RenderDelegate::Get3dSolidShader( - const MColor& color) const + */ +MHWRender::MShaderInstance* HdVP2RenderDelegate::Get3dSolidShader(const MColor& color) const { return sShaderCache.Get3dSolidShader(color); } /*! \brief Returns a 3d CPV solid-color shader. -*/ + */ MHWRender::MShaderInstance* HdVP2RenderDelegate::Get3dCPVSolidShader() const { return sShaderCache.Get3dCPVSolidShader(); } /*! \brief Returns a white 3d fat point shader. -*/ + */ MHWRender::MShaderInstance* HdVP2RenderDelegate::Get3dFatPointShader() const { return sShaderCache.Get3dFatPointShader(); } /*! \brief Returns a sampler state as specified by the description. -*/ -const MHWRender::MSamplerState* HdVP2RenderDelegate::GetSamplerState( - const MHWRender::MSamplerStateDesc& desc) const + */ +const MHWRender::MSamplerState* +HdVP2RenderDelegate::GetSamplerState(const MHWRender::MSamplerStateDesc& desc) const { // Look for it first with reader lock - tbb::spin_rw_mutex::scoped_lock lock(sSamplerRWMutex, false/*write*/); + tbb::spin_rw_mutex::scoped_lock lock(sSamplerRWMutex, false /*write*/); auto it = sSamplerStates.find(desc); if (it != sSamplerStates.end()) { @@ -866,17 +853,14 @@ const MHWRender::MSamplerState* HdVP2RenderDelegate::GetSamplerState( } // Create and cache. - const MHWRender::MSamplerState* samplerState = - MHWRender::MStateManager::acquireSamplerState(desc); + const MHWRender::MSamplerState* samplerState + = MHWRender::MStateManager::acquireSamplerState(desc); sSamplerStates[desc] = samplerState; return samplerState; } /*! \brief Returns the shared bbox geometry. -*/ -const HdVP2BBoxGeom& HdVP2RenderDelegate::GetSharedBBoxGeom() const -{ - return *sSharedBBoxGeom; -} + */ +const HdVP2BBoxGeom& HdVP2RenderDelegate::GetSharedBBoxGeom() const { return *sSharedBBoxGeom; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/render_delegate.h b/lib/mayaUsd/render/vp2RenderDelegate/render_delegate.h index d232514515..9120d8fff3 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/render_delegate.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/render_delegate.h @@ -16,18 +16,18 @@ #ifndef HD_VP2_RENDER_DELEGATE #define HD_VP2_RENDER_DELEGATE -#include -#include - -#include -#include +#include "render_param.h" +#include "resource_registry.h" -#include #include #include +#include -#include "render_param.h" -#include "resource_registry.h" +#include +#include + +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -59,13 +59,14 @@ class ProxyRenderDelegate; The render delegate also has a hook for the main hydra execution algorithm (HdEngine::Execute()): between HdRenderIndex::SyncAll(), which pulls new scene data, and execution of tasks, the engine calls back to - CommitResources(). This commit is perfoming execution which must happen + CommitResources(). This commit is perfoming execution which must happen on the main-thread. In the future we will further split engine execution, - levering evaluation time to do HdRenderIndex::SyncAll together with + levering evaluation time to do HdRenderIndex::SyncAll together with parallel DG computation and perform commit from reserved thread via main-thread tasks. */ -class HdVP2RenderDelegate final : public HdRenderDelegate { +class HdVP2RenderDelegate final : public HdRenderDelegate +{ public: HdVP2RenderDelegate(ProxyRenderDelegate& proxyDraw); @@ -83,21 +84,26 @@ class HdVP2RenderDelegate final : public HdRenderDelegate { HdVP2ResourceRegistry& GetVP2ResourceRegistry(); - HdRenderPassSharedPtr CreateRenderPass(HdRenderIndex* index, HdRprimCollection const& collection) override; + HdRenderPassSharedPtr + CreateRenderPass(HdRenderIndex* index, HdRprimCollection const& collection) override; - HdInstancer* CreateInstancer(HdSceneDelegate* delegate, SdfPath const& id, SdfPath const& instancerId) override; + HdInstancer* CreateInstancer( + HdSceneDelegate* delegate, + SdfPath const& id, + SdfPath const& instancerId) override; void DestroyInstancer(HdInstancer* instancer) override; - HdRprim* CreateRprim(TfToken const& typeId, SdfPath const& rprimId, SdfPath const& instancerId) override; + HdRprim* + CreateRprim(TfToken const& typeId, SdfPath const& rprimId, SdfPath const& instancerId) override; void DestroyRprim(HdRprim* rPrim) override; HdSprim* CreateSprim(TfToken const& typeId, SdfPath const& sprimId) override; HdSprim* CreateFallbackSprim(TfToken const& typeId) override; - void DestroySprim(HdSprim* sPrim) override; + void DestroySprim(HdSprim* sPrim) override; HdBprim* CreateBprim(TfToken const& typeId, SdfPath const& bprimId) override; HdBprim* CreateFallbackBprim(TfToken const& typeId) override; - void DestroyBprim(HdBprim* bPrim) override; + void DestroyBprim(HdBprim* bPrim) override; void CommitResources(HdChangeTracker* tracker) override; @@ -119,24 +125,29 @@ class HdVP2RenderDelegate final : public HdRenderDelegate { MHWRender::MShaderInstance* GetBasisCurvesCPVShader(const TfToken& curveType, const TfToken& curveBasis) const; - const MHWRender::MSamplerState* GetSamplerState( - const MHWRender::MSamplerStateDesc& desc) const; + const MHWRender::MSamplerState* GetSamplerState(const MHWRender::MSamplerStateDesc& desc) const; const HdVP2BBoxGeom& GetSharedBBoxGeom() const; - static const int sProfilerCategory; //!< Profiler category + static const int sProfilerCategory; //!< Profiler category private: HdVP2RenderDelegate(const HdVP2RenderDelegate&) = delete; HdVP2RenderDelegate& operator=(const HdVP2RenderDelegate&) = delete; - static std::atomic_int _renderDelegateCounter; //!< Number of render delegates. First one creates shared resources and last one deletes them. - static std::mutex _renderDelegateMutex; //!< Mutex protecting construction/destruction of render delegate - static HdResourceRegistrySharedPtr _resourceRegistry; //!< Shared and unused by VP2 resource registry - - std::unique_ptr _renderParam; //!< Render param used to provided access to VP2 during prim synchronization - SdfPath _id; //!< Render delegate IDs - HdVP2ResourceRegistry _resourceRegistryVP2; //!< VP2 resource registry used for enqueue and execution of commits + static std::atomic_int + _renderDelegateCounter; //!< Number of render delegates. First one creates shared resources + //!< and last one deletes them. + static std::mutex + _renderDelegateMutex; //!< Mutex protecting construction/destruction of render delegate + static HdResourceRegistrySharedPtr + _resourceRegistry; //!< Shared and unused by VP2 resource registry + + std::unique_ptr + _renderParam; //!< Render param used to provided access to VP2 during prim synchronization + SdfPath _id; //!< Render delegate IDs + HdVP2ResourceRegistry + _resourceRegistryVP2; //!< VP2 resource registry used for enqueue and execution of commits }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/render_param.cpp b/lib/mayaUsd/render/vp2RenderDelegate/render_param.cpp index d155c0383f..ccc0687f6a 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/render_param.cpp +++ b/lib/mayaUsd/render/vp2RenderDelegate/render_param.cpp @@ -19,17 +19,16 @@ PXR_NAMESPACE_OPEN_SCOPE -/*! \brief Begin update before rendering of VP2 starts. -*/ -void HdVP2RenderParam::BeginUpdate(MSubSceneContainer& container, UsdTimeCode frame) { +/*! \brief Begin update before rendering of VP2 starts. + */ +void HdVP2RenderParam::BeginUpdate(MSubSceneContainer& container, UsdTimeCode frame) +{ _container = &container; _frame = frame; } /*! \brief End update & clear access to render item container which pass this point won't be valid. -*/ -void HdVP2RenderParam::EndUpdate() { - _container = nullptr; -} + */ +void HdVP2RenderParam::EndUpdate() { _container = nullptr; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/render_param.h b/lib/mayaUsd/render/vp2RenderDelegate/render_param.h index 02cbddf817..7da672085c 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/render_param.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/render_param.h @@ -16,12 +16,12 @@ #ifndef HD_VP2_RENDER_PARAM #define HD_VP2_RENDER_PARAM -#include - -#include #include +#include #include +#include + PXR_NAMESPACE_OPEN_SCOPE class ProxyRenderDelegate; @@ -30,36 +30,43 @@ class ProxyRenderDelegate; during Sync processing and providing access to VP2. \class HdVP2RenderParam */ -class HdVP2RenderParam final : public HdRenderParam { +class HdVP2RenderParam final : public HdRenderParam +{ public: /*! \brief Constructor - */ - HdVP2RenderParam(ProxyRenderDelegate& drawScene) - : _drawScene(drawScene) {} + */ + HdVP2RenderParam(ProxyRenderDelegate& drawScene) + : _drawScene(drawScene) + { + } /*! \brief Destructor - */ + */ ~HdVP2RenderParam() override = default; void BeginUpdate(MSubSceneContainer& container, UsdTimeCode frame); void EndUpdate(); /*! \brief Get access to subscene override used to draw the scene - */ + */ ProxyRenderDelegate& GetDrawScene() const { return _drawScene; } /*! \brief Get access to render item container - only valid during draw update - */ - MSubSceneContainer* GetContainer() const { return _container; } - + */ + MSubSceneContainer* GetContainer() const { return _container; } + /*! \brief Refreshed during each update, provides info about currently refreshed frame - */ - UsdTimeCode GetFrame() const { return _frame; } + */ + UsdTimeCode GetFrame() const { return _frame; } protected: - ProxyRenderDelegate& _drawScene; //!< Subscene override used as integration interface for HdVP2RenderDelegate - MSubSceneContainer* _container{ nullptr }; //!< Container to all render items, only valid between begin and end update of subscene override. - UsdTimeCode _frame{ UsdTimeCode::Default() }; //!< Rendered frame (useful for caching of data) + ProxyRenderDelegate& + _drawScene; //!< Subscene override used as integration interface for HdVP2RenderDelegate + MSubSceneContainer* _container { + nullptr + }; //!< Container to all render items, only valid between begin and end update of subscene + //!< override. + UsdTimeCode _frame { UsdTimeCode::Default() }; //!< Rendered frame (useful for caching of data) }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/render_pass.h b/lib/mayaUsd/render/vp2RenderDelegate/render_pass.h index 58933d4839..5ee6fbdc0a 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/render_pass.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/render_pass.h @@ -16,31 +16,37 @@ #ifndef HD_VP2_RENDER_PASS #define HD_VP2_RENDER_PASS -#include - #include +#include PXR_NAMESPACE_OPEN_SCOPE class HdVP2RenderDelegate; -/*! \brief Empty render pass class. Unused for rendering with VP2 but required by HdEngine & HdRenderDelegate. - \class HdVP2RenderPass +/*! \brief Empty render pass class. Unused for rendering with VP2 but required by HdEngine & + HdRenderDelegate. \class HdVP2RenderPass */ class HdVP2RenderPass final : public HdRenderPass { public: //! \brief Constructor - HdVP2RenderPass(HdVP2RenderDelegate* delegate, HdRenderIndex *index, HdRprimCollection const &collection) + HdVP2RenderPass( + HdVP2RenderDelegate* delegate, + HdRenderIndex* index, + HdRprimCollection const& collection) : HdRenderPass(index, collection) - {} + { + } //! \brief Destructor - virtual ~HdVP2RenderPass() {} + virtual ~HdVP2RenderPass() { } //! \brief Empty execute - void _Execute(HdRenderPassStateSharedPtr const &renderPassState, TfTokenVector const &renderTags) override {} - + void _Execute( + HdRenderPassStateSharedPtr const& renderPassState, + TfTokenVector const& renderTags) override + { + } }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/resource_registry.h b/lib/mayaUsd/render/vp2RenderDelegate/resource_registry.h index eea61f8926..e0326d092c 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/resource_registry.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/resource_registry.h @@ -16,15 +16,15 @@ #ifndef HD_VP2_RESOURCE_REGISTRY #define HD_VP2_RESOURCE_REGISTRY +#include "task_commit.h" + #include #include -#include "task_commit.h" - PXR_NAMESPACE_OPEN_SCOPE -/*! \brief Central place to manage GPU resources commits and any resources not managed by VP2 directly - \class HdVP2ResourceRegistry +/*! \brief Central place to manage GPU resources commits and any resources not managed by VP2 + directly \class HdVP2ResourceRegistry */ class HdVP2ResourceRegistry { @@ -35,19 +35,21 @@ class HdVP2ResourceRegistry ~HdVP2ResourceRegistry() = default; //! \brief Execute commit tasks (called by render delegate) - void Commit() { + void Commit() + { HdVP2TaskCommit* commitTask; while (_commitTasks.try_pop(commitTask)) { (*commitTask)(); commitTask->destroy(); } } - + //! \brief Enqueue commit task. Call is thread safe. - template - void EnqueueCommit(Body taskBody) { + template void EnqueueCommit(Body taskBody) + { _commitTasks.push(HdVP2TaskCommitBody::construct(taskBody)); } + private: //! Concurrent queue for commit tasks tbb::concurrent_queue> _commitTasks; diff --git a/lib/mayaUsd/render/vp2RenderDelegate/sampler.cpp b/lib/mayaUsd/render/vp2RenderDelegate/sampler.cpp index a9e5d60475..9cb4363c46 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/sampler.cpp +++ b/lib/mayaUsd/render/vp2RenderDelegate/sampler.cpp @@ -27,7 +27,9 @@ PXR_NAMESPACE_OPEN_SCOPE \param buffer The buffer being sampled. */ HdVP2BufferSampler::HdVP2BufferSampler(HdVtBufferSource const& buffer) - : _buffer(buffer) {} + : _buffer(buffer) +{ +} /*! \brief Sample the buffer at given element index @@ -46,14 +48,12 @@ HdVP2BufferSampler::HdVP2BufferSampler(HdVtBufferSource const& buffer) \return True if the value was successfully sampled. */ -bool HdVP2BufferSampler::Sample(int index, void* value, - HdTupleType dataType) const +bool HdVP2BufferSampler::Sample(int index, void* value, HdTupleType dataType) const { // Sanity checks: index is within the bounds of buffer, // and the sample type and buffer type (defined by the dataType) // are the same. - if (_buffer.GetNumElements() <= (size_t)index || - _buffer.GetTupleType() != dataType) { + if (_buffer.GetNumElements() <= (size_t)index || _buffer.GetTupleType() != dataType) { return false; } @@ -64,16 +64,15 @@ bool HdVP2BufferSampler::Sample(int index, void* value, // Equivalent to: // *static_cast(value) = // static_cast(_buffer.GetData())[index]; - memcpy(value, - static_cast(_buffer.GetData()) + offset, elemSize); + memcpy(value, static_cast(_buffer.GetData()) + offset, elemSize); return true; } -template +template static void -_InterpolateImpl(void* out, void** samples, float* weights, - size_t sampleCount, short numComponents) { +_InterpolateImpl(void* out, void** samples, float* weights, size_t sampleCount, short numComponents) +{ // This is an implementation of a general blend of samples: // out = sum_j { sample[j] * weights[j] }. // Since the vector length comes in as a parameter, and not part @@ -81,8 +80,7 @@ _InterpolateImpl(void* out, void** samples, float* weights, for (short i = 0; i < numComponents; ++i) { static_cast(out)[i] = 0; for (size_t j = 0; j < sampleCount; ++j) { - static_cast(out)[i] += - static_cast(samples[j])[i] * weights[j]; + static_cast(out)[i] += static_cast(samples[j])[i] * weights[j]; } } } @@ -95,11 +93,16 @@ _InterpolateImpl(void* out, void** samples, float* weights, \param weights The array of sample weights (length \p sampleCount). \param sampleCount The number of samples to combine. \param dataType The HdTupleType describing element values. - + \return True if the samples were successfully combined. */ -bool HdVP2PrimvarSampler::_Interpolate(void* out, void** samples, float* weights, - size_t sampleCount, HdTupleType dataType) { +bool HdVP2PrimvarSampler::_Interpolate( + void* out, + void** samples, + float* weights, + size_t sampleCount, + HdTupleType dataType) +{ // Combine maps from component type tag to C++ type, and delegates to // the templated _InterpolateImpl. @@ -108,41 +111,33 @@ bool HdVP2PrimvarSampler::_Interpolate(void* out, void** samples, float* weights HdType componentType = HdGetComponentType(dataType.type); - switch(componentType) { - case HdTypeBool: - /* This function isn't meaningful on boolean types. */ - return false; - case HdTypeInt8: - _InterpolateImpl(out, samples, weights, sampleCount, - numComponents); - case HdTypeInt16: - _InterpolateImpl(out, samples, weights, sampleCount, - numComponents); - return true; - case HdTypeUInt16: - _InterpolateImpl(out, samples, weights, sampleCount, - numComponents); - return true; - case HdTypeInt32: - _InterpolateImpl(out, samples, weights, sampleCount, - numComponents); - return true; - case HdTypeUInt32: - _InterpolateImpl(out, samples, weights, sampleCount, - numComponents); - return true; - case HdTypeFloat: - _InterpolateImpl(out, samples, weights, sampleCount, - numComponents); - return true; - case HdTypeDouble: - _InterpolateImpl(out, samples, weights, sampleCount, - numComponents); - return true; - default: - TF_CODING_ERROR("Unsupported type '%s' passed to _Interpolate", - TfEnum::GetName(componentType).c_str()); - return false; + switch (componentType) { + case HdTypeBool: + /* This function isn't meaningful on boolean types. */ + return false; + case HdTypeInt8: _InterpolateImpl(out, samples, weights, sampleCount, numComponents); + case HdTypeInt16: + _InterpolateImpl(out, samples, weights, sampleCount, numComponents); + return true; + case HdTypeUInt16: + _InterpolateImpl(out, samples, weights, sampleCount, numComponents); + return true; + case HdTypeInt32: + _InterpolateImpl(out, samples, weights, sampleCount, numComponents); + return true; + case HdTypeUInt32: + _InterpolateImpl(out, samples, weights, sampleCount, numComponents); + return true; + case HdTypeFloat: + _InterpolateImpl(out, samples, weights, sampleCount, numComponents); + return true; + case HdTypeDouble: + _InterpolateImpl(out, samples, weights, sampleCount, numComponents); + return true; + default: + TF_CODING_ERROR( + "Unsupported type '%s' passed to _Interpolate", TfEnum::GetName(componentType).c_str()); + return false; } } diff --git a/lib/mayaUsd/render/vp2RenderDelegate/sampler.h b/lib/mayaUsd/render/vp2RenderDelegate/sampler.h index 274547f2df..8b54e4ff80 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/sampler.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/sampler.h @@ -18,9 +18,8 @@ #ifndef HD_VP2_SAMPLER_H #define HD_VP2_SAMPLER_H -#include +#include -#include #include #include #include @@ -32,53 +31,56 @@ #include #include #include -#include #include #include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE /*! \brief A utility class that helps map between C++ types and Hd type tags. \class HdVP2TypeHelper */ -class HdVP2TypeHelper { +class HdVP2TypeHelper +{ public: //! Define a type that can hold one sample of any primvar. using PrimvarTypeContainer = char[sizeof(GfMatrix4d)]; /*! \brief Return the HdTupleType corresponding to the given C++ type. - */ - template - static HdTupleType GetTupleType(); + */ + template static HdTupleType GetTupleType(); }; // Define template specializations of HdVP2TypeHelper methods for // all our supported types... -#define TYPE_HELPER(T,type)\ -template<> inline HdTupleType \ -HdVP2TypeHelper::GetTupleType() { return HdTupleType{type, 1}; } - - TYPE_HELPER(bool, HdTypeBool) - TYPE_HELPER(char, HdTypeInt8) - TYPE_HELPER(short, HdTypeInt16) - TYPE_HELPER(unsigned short, HdTypeUInt16) - TYPE_HELPER(int, HdTypeInt32) - TYPE_HELPER(GfVec2i, HdTypeInt32Vec2) - TYPE_HELPER(GfVec3i, HdTypeInt32Vec3) - TYPE_HELPER(GfVec4i, HdTypeInt32Vec4) - TYPE_HELPER(unsigned int, HdTypeUInt32) - TYPE_HELPER(float, HdTypeFloat) - TYPE_HELPER(GfVec2f, HdTypeFloatVec2) - TYPE_HELPER(GfVec3f, HdTypeFloatVec3) - TYPE_HELPER(GfVec4f, HdTypeFloatVec4) - TYPE_HELPER(double, HdTypeDouble) - TYPE_HELPER(GfVec2d, HdTypeDoubleVec2) - TYPE_HELPER(GfVec3d, HdTypeDoubleVec3) - TYPE_HELPER(GfVec4d, HdTypeDoubleVec4) - TYPE_HELPER(GfMatrix4f, HdTypeFloatMat4) - TYPE_HELPER(GfMatrix4d, HdTypeDoubleMat4) -#undef TYPE_HELPER +#define TYPE_HELPER(T, type) \ + template <> inline HdTupleType HdVP2TypeHelper::GetTupleType() \ + { \ + return HdTupleType { type, 1 }; \ + } +TYPE_HELPER(bool, HdTypeBool) +TYPE_HELPER(char, HdTypeInt8) +TYPE_HELPER(short, HdTypeInt16) +TYPE_HELPER(unsigned short, HdTypeUInt16) +TYPE_HELPER(int, HdTypeInt32) +TYPE_HELPER(GfVec2i, HdTypeInt32Vec2) +TYPE_HELPER(GfVec3i, HdTypeInt32Vec3) +TYPE_HELPER(GfVec4i, HdTypeInt32Vec4) +TYPE_HELPER(unsigned int, HdTypeUInt32) +TYPE_HELPER(float, HdTypeFloat) +TYPE_HELPER(GfVec2f, HdTypeFloatVec2) +TYPE_HELPER(GfVec3f, HdTypeFloatVec3) +TYPE_HELPER(GfVec4f, HdTypeFloatVec4) +TYPE_HELPER(double, HdTypeDouble) +TYPE_HELPER(GfVec2d, HdTypeDoubleVec2) +TYPE_HELPER(GfVec3d, HdTypeDoubleVec3) +TYPE_HELPER(GfVec4d, HdTypeDoubleVec4) +TYPE_HELPER(GfMatrix4f, HdTypeFloatMat4) +TYPE_HELPER(GfMatrix4d, HdTypeDoubleMat4) +#undef TYPE_HELPER /*! \brief A utility class that knows how to sample an element from a type-tagged buffer (like HdVtBufferSource). @@ -87,16 +89,17 @@ HdVP2TypeHelper::GetTupleType() { return HdTupleType{type, 1}; } This class provides templated accessors to let the caller directly get the final sample type; it also does bounds checks and type checks. */ -class HdVP2BufferSampler { +class HdVP2BufferSampler +{ public: HdVP2BufferSampler(HdVtBufferSource const& buffer); bool Sample(int index, void* value, HdTupleType dataType) const; // Convenient, templated frontend for Sample(). - template bool Sample(int index, T* value) const { - return Sample(index, static_cast(value), - HdVP2TypeHelper::GetTupleType()); + template bool Sample(int index, T* value) const + { + return Sample(index, static_cast(value), HdVP2TypeHelper::GetTupleType()); } private: @@ -111,7 +114,8 @@ class HdVP2BufferSampler { accessors, but derived classes are responsible for implementing appropriate sampling or interpolation modes. */ -class HdVP2PrimvarSampler { +class HdVP2PrimvarSampler +{ public: //! Default constructor. HdVP2PrimvarSampler() = default; @@ -125,11 +129,11 @@ class HdVP2PrimvarSampler { having arity \p numComponents, each of type \p componentType. These parameters may not match the datatype declaration of the underlying buffer. - + Derived classes are responsible for implementing sampling logic for their particular interpolation modes. Sample returns true if a value was successfully retrieved. - + \param element The element index to sample. \param u The u coordinate to sample. \param v The v coordinate to sample. @@ -138,19 +142,22 @@ class HdVP2PrimvarSampler { \return True if the value was successfully sampled. */ - virtual bool Sample(unsigned int element, float u, float v, void* value, - HdTupleType dataType) const = 0; + virtual bool + Sample(unsigned int element, float u, float v, void* value, HdTupleType dataType) const = 0; //! Convenient, templated frontend for Sample(). - template bool Sample(unsigned int element, float u, float v, - T* value) const { - return Sample(element, u, v, static_cast(value), - HdVP2TypeHelper::GetTupleType()); + template bool Sample(unsigned int element, float u, float v, T* value) const + { + return Sample(element, u, v, static_cast(value), HdVP2TypeHelper::GetTupleType()); } protected: - static bool _Interpolate(void* out, void** samples, float* weights, - size_t sampleCount, HdTupleType dataType); + static bool _Interpolate( + void* out, + void** samples, + float* weights, + size_t sampleCount, + HdTupleType dataType); }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/render/vp2RenderDelegate/task_commit.h b/lib/mayaUsd/render/vp2RenderDelegate/task_commit.h index 108da6da24..1e8eb05e72 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/task_commit.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/task_commit.h @@ -38,26 +38,28 @@ class HdVP2TaskCommit /*! \brief Wrapper of a task body into commit task. \class HdVP2TaskCommit */ -template -class HdVP2TaskCommitBody final : public HdVP2TaskCommit { +template class HdVP2TaskCommitBody final : public HdVP2TaskCommit +{ //! Use scalable allocator to prevent heap contention using my_allocator_type = tbb::tbb_allocator>; - //! Private constructor to force usage of construct method & allocation with + //! Private constructor to force usage of construct method & allocation with //! scalable allocator. - HdVP2TaskCommitBody(const Body& body) : fBody(body) {} + HdVP2TaskCommitBody(const Body& body) + : fBody(body) + { + } public: ~HdVP2TaskCommitBody() override = default; //! Execute body task. - void operator()() override { - fBody(); - } + void operator()() override { fBody(); } //! Objects of this type are allocated with tbb_allocator. //! Release the memory using same allocator by calling destroy method. - void destroy() override { + void destroy() override + { my_allocator_type().destroy(this); my_allocator_type().deallocate(this, 1); } @@ -65,7 +67,8 @@ class HdVP2TaskCommitBody final : public HdVP2TaskCommit { /*! Allocate a new object of type Body using scalable allocator. Always free this object by calling destroy method! */ - static HdVP2TaskCommitBody* construct(const Body& body) { + static HdVP2TaskCommitBody* construct(const Body& body) + { void* mem = my_allocator_type().allocate(1); return new (mem) HdVP2TaskCommitBody(body); } diff --git a/lib/mayaUsd/render/vp2RenderDelegate/tokens.h b/lib/mayaUsd/render/vp2RenderDelegate/tokens.h index 67ff2fc241..b0742af7a1 100644 --- a/lib/mayaUsd/render/vp2RenderDelegate/tokens.h +++ b/lib/mayaUsd/render/vp2RenderDelegate/tokens.h @@ -16,15 +16,12 @@ #ifndef HD_VP2_TOKENS_H #define HD_VP2_TOKENS_H -#include - #include +#include PXR_NAMESPACE_OPEN_SCOPE -#define HDVP2_REPR_TOKENS \ - (bbox) \ - (selection) +#define HDVP2_REPR_TOKENS (bbox)(selection) TF_DECLARE_PUBLIC_TOKENS(HdVP2ReprTokens, , HDVP2_REPR_TOKENS); diff --git a/lib/mayaUsd/render/vp2ShaderFragments/shaderFragments.cpp b/lib/mayaUsd/render/vp2ShaderFragments/shaderFragments.cpp index 47167e0d63..8dac7ced06 100644 --- a/lib/mayaUsd/render/vp2ShaderFragments/shaderFragments.cpp +++ b/lib/mayaUsd/render/vp2ShaderFragments/shaderFragments.cpp @@ -15,189 +15,159 @@ // #include "shaderFragments.h" -#include -#include -#include -#include - #include #include #include #include +#include +#include +#include +#include + #include #include PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_PUBLIC_TOKENS( - HdVP2ShaderFragmentsTokens, - MAYAUSD_CORE_PUBLIC_USD_PREVIEW_SURFACE_TOKENS); +TF_DEFINE_PUBLIC_TOKENS(HdVP2ShaderFragmentsTokens, MAYAUSD_CORE_PUBLIC_USD_PREVIEW_SURFACE_TOKENS); TF_DEFINE_PRIVATE_TOKENS( _tokens, - (BasisCurvesCubicColorDomain) - (BasisCurvesCubicCPVHull) - (BasisCurvesCubicCPVPassing) - (BasisCurvesCubicCPVShader) - (BasisCurvesCubicDomain) - (BasisCurvesCubicFallbackShader) - (BasisCurvesCubicHull) - (BasisCurvesLinearColorDomain) - (BasisCurvesLinearCPVHull) - (BasisCurvesLinearCPVPassing) - (BasisCurvesLinearCPVShader) - (BasisCurvesLinearDomain) - (BasisCurvesLinearFallbackShader) - (BasisCurvesLinearHull) - - (FallbackCPVShader) - (FallbackShader) - - (Float4ToFloatX) - (Float4ToFloatY) - (Float4ToFloatZ) - (Float4ToFloatW) - (Float4ToFloat3) - (Float4ToFloat4) - - (NwFaceCameraIfNAN) - - (lightingContributions) - (scaledDiffusePassThrough) - (scaledSpecularPassThrough) - (opacityToTransparency) - (usdPreviewSurfaceLighting) - (usdPreviewSurfaceCombiner) - - (UsdPrimvarColor) - - (UsdUVTexture) - - (UsdPrimvarReader_color) - (UsdPrimvarReader_float) - (UsdPrimvarReader_float2) - (UsdPrimvarReader_float3) - (UsdPrimvarReader_float4) - (UsdPrimvarReader_vector) -); - -static const TfTokenVector _LanguageSpecificFragmentNames = { - _tokens->BasisCurvesLinearDomain, - _tokens->BasisCurvesCubicDomain -}; + (BasisCurvesCubicColorDomain)(BasisCurvesCubicCPVHull)(BasisCurvesCubicCPVPassing)( + BasisCurvesCubicCPVShader)(BasisCurvesCubicDomain)(BasisCurvesCubicFallbackShader)( + BasisCurvesCubicHull)(BasisCurvesLinearColorDomain)(BasisCurvesLinearCPVHull)( + BasisCurvesLinearCPVPassing)(BasisCurvesLinearCPVShader)(BasisCurvesLinearDomain)( + BasisCurvesLinearFallbackShader)(BasisCurvesLinearHull) -static const TfTokenVector _FragmentNames = { - _tokens->BasisCurvesCubicColorDomain, - _tokens->BasisCurvesCubicCPVHull, - _tokens->BasisCurvesCubicCPVPassing, - _tokens->BasisCurvesCubicHull, - _tokens->BasisCurvesLinearColorDomain, - _tokens->BasisCurvesLinearCPVHull, - _tokens->BasisCurvesLinearCPVPassing, - _tokens->BasisCurvesLinearHull, - - _tokens->UsdPrimvarColor, - - _tokens->UsdUVTexture, - - _tokens->UsdPrimvarReader_color, - _tokens->UsdPrimvarReader_float, - _tokens->UsdPrimvarReader_float2, - _tokens->UsdPrimvarReader_float3, - _tokens->UsdPrimvarReader_float4, - _tokens->UsdPrimvarReader_vector, - - _tokens->Float4ToFloatX, - _tokens->Float4ToFloatY, - _tokens->Float4ToFloatZ, - _tokens->Float4ToFloatW, - _tokens->Float4ToFloat3, - _tokens->Float4ToFloat4, - - _tokens->NwFaceCameraIfNAN, - - _tokens->lightingContributions, - _tokens->scaledDiffusePassThrough, - _tokens->scaledSpecularPassThrough, - _tokens->opacityToTransparency, - _tokens->usdPreviewSurfaceLighting, - _tokens->usdPreviewSurfaceCombiner -}; + (FallbackCPVShader)(FallbackShader) -static const TfTokenVector _FragmentGraphNames = { - _tokens->BasisCurvesCubicCPVShader, - _tokens->BasisCurvesCubicFallbackShader, - _tokens->BasisCurvesLinearCPVShader, - _tokens->BasisCurvesLinearFallbackShader, - _tokens->FallbackCPVShader, - _tokens->FallbackShader, - HdVP2ShaderFragmentsTokens->CoreFragmentGraphName, - HdVP2ShaderFragmentsTokens->SurfaceFragmentGraphName -}; + (Float4ToFloatX)(Float4ToFloatY)(Float4ToFloatZ)(Float4ToFloatW)(Float4ToFloat3)( + Float4ToFloat4) + (NwFaceCameraIfNAN) -namespace -{ - //! Get the file path of the shader fragment. - std::string _GetResourcePath(const std::string& resource) - { - static PlugPluginPtr plugin = - PlugRegistry::GetInstance().GetPluginWithName("mayaUsd_ShaderFragments"); - if (!TF_VERIFY(plugin, "Could not get plugin\n")) { - return std::string(); - } + (lightingContributions)(scaledDiffusePassThrough)(scaledSpecularPassThrough)( + opacityToTransparency)(usdPreviewSurfaceLighting)(usdPreviewSurfaceCombiner) + + (UsdPrimvarColor) + + (UsdUVTexture) + + (UsdPrimvarReader_color)(UsdPrimvarReader_float)( + UsdPrimvarReader_float2)(UsdPrimvarReader_float3)( + UsdPrimvarReader_float4)(UsdPrimvarReader_vector)); - const std::string path = PlugFindPluginResource(plugin, resource); - TF_VERIFY(!path.empty(), "Could not find resource: %s\n", resource.c_str()); +static const TfTokenVector _LanguageSpecificFragmentNames + = { _tokens->BasisCurvesLinearDomain, _tokens->BasisCurvesCubicDomain }; - return path; +static const TfTokenVector _FragmentNames = { _tokens->BasisCurvesCubicColorDomain, + _tokens->BasisCurvesCubicCPVHull, + _tokens->BasisCurvesCubicCPVPassing, + _tokens->BasisCurvesCubicHull, + _tokens->BasisCurvesLinearColorDomain, + _tokens->BasisCurvesLinearCPVHull, + _tokens->BasisCurvesLinearCPVPassing, + _tokens->BasisCurvesLinearHull, + + _tokens->UsdPrimvarColor, + + _tokens->UsdUVTexture, + + _tokens->UsdPrimvarReader_color, + _tokens->UsdPrimvarReader_float, + _tokens->UsdPrimvarReader_float2, + _tokens->UsdPrimvarReader_float3, + _tokens->UsdPrimvarReader_float4, + _tokens->UsdPrimvarReader_vector, + + _tokens->Float4ToFloatX, + _tokens->Float4ToFloatY, + _tokens->Float4ToFloatZ, + _tokens->Float4ToFloatW, + _tokens->Float4ToFloat3, + _tokens->Float4ToFloat4, + + _tokens->NwFaceCameraIfNAN, + + _tokens->lightingContributions, + _tokens->scaledDiffusePassThrough, + _tokens->scaledSpecularPassThrough, + _tokens->opacityToTransparency, + _tokens->usdPreviewSurfaceLighting, + _tokens->usdPreviewSurfaceCombiner }; + +static const TfTokenVector _FragmentGraphNames + = { _tokens->BasisCurvesCubicCPVShader, + _tokens->BasisCurvesCubicFallbackShader, + _tokens->BasisCurvesLinearCPVShader, + _tokens->BasisCurvesLinearFallbackShader, + _tokens->FallbackCPVShader, + _tokens->FallbackShader, + HdVP2ShaderFragmentsTokens->CoreFragmentGraphName, + HdVP2ShaderFragmentsTokens->SurfaceFragmentGraphName }; + +namespace { +//! Get the file path of the shader fragment. +std::string _GetResourcePath(const std::string& resource) +{ + static PlugPluginPtr plugin + = PlugRegistry::GetInstance().GetPluginWithName("mayaUsd_ShaderFragments"); + if (!TF_VERIFY(plugin, "Could not get plugin\n")) { + return std::string(); } + const std::string path = PlugFindPluginResource(plugin, resource); + TF_VERIFY(!path.empty(), "Could not find resource: %s\n", resource.c_str()); + + return path; +} + #if MAYA_API_VERSION >= 20210000 - //! Structure for Automatic shader stage input parameter to register in VP2. - struct AutomaticShaderStageInput { - MHWRender::MFragmentManager::ShaderStage _shaderStage; - MString _parameterName; - MString _parameterSemantic; - MHWRender::MShaderInstance::ParameterType _parameterType; - bool _isVaryingInput; - }; - - //! List of automatic shader stage input parameters to register in VP2. - std::vector _automaticShaderStageInputs - = { { MHWRender::MFragmentManager::kVertexShader, - "UsdPrimvarColor", - "COLOR0", - MHWRender::MShaderInstance::kFloat4, - true }, - { MHWRender::MFragmentManager::kHullShader, - "UsdPrimvarColor", - "COLOR0", - MHWRender::MShaderInstance::kFloat4, - true }, - { MHWRender::MFragmentManager::kDomainShader, - "UsdPrimvarColor", - "COLOR0", - MHWRender::MShaderInstance::kFloat4, - false }, - { MHWRender::MFragmentManager::kPixelShader, - "BasisCurvesCubicColor", - "COLOR0", - MHWRender::MShaderInstance::kFloat4, - true }, - { MHWRender::MFragmentManager::kPixelShader, - "BasisCurvesLinearColor", - "COLOR0", - MHWRender::MShaderInstance::kFloat4, - true } }; - - //! Name mapping between a parameter and a desired domain shader fragment to register in VP2. - std::vector> _domainShaderInputNameMappings - = { { "BasisCurvesCubicColor", "BasisCurvesCubicColorDomain" }, - { "BasisCurvesLinearColor", "BasisCurvesLinearColorDomain" } }; +//! Structure for Automatic shader stage input parameter to register in VP2. +struct AutomaticShaderStageInput +{ + MHWRender::MFragmentManager::ShaderStage _shaderStage; + MString _parameterName; + MString _parameterSemantic; + MHWRender::MShaderInstance::ParameterType _parameterType; + bool _isVaryingInput; +}; + +//! List of automatic shader stage input parameters to register in VP2. +std::vector _automaticShaderStageInputs + = { { MHWRender::MFragmentManager::kVertexShader, + "UsdPrimvarColor", + "COLOR0", + MHWRender::MShaderInstance::kFloat4, + true }, + { MHWRender::MFragmentManager::kHullShader, + "UsdPrimvarColor", + "COLOR0", + MHWRender::MShaderInstance::kFloat4, + true }, + { MHWRender::MFragmentManager::kDomainShader, + "UsdPrimvarColor", + "COLOR0", + MHWRender::MShaderInstance::kFloat4, + false }, + { MHWRender::MFragmentManager::kPixelShader, + "BasisCurvesCubicColor", + "COLOR0", + MHWRender::MShaderInstance::kFloat4, + true }, + { MHWRender::MFragmentManager::kPixelShader, + "BasisCurvesLinearColor", + "COLOR0", + MHWRender::MShaderInstance::kFloat4, + true } }; + +//! Name mapping between a parameter and a desired domain shader fragment to register in VP2. +std::vector> _domainShaderInputNameMappings + = { { "BasisCurvesCubicColor", "BasisCurvesCubicColorDomain" }, + { "BasisCurvesLinearColor", "BasisCurvesLinearColorDomain" } }; #endif @@ -222,8 +192,7 @@ MStatus HdVP2ShaderFragments::registerFragments() return MS::kFailure; } - MHWRender::MFragmentManager* fragmentManager = - theRenderer->getFragmentManager(); + MHWRender::MFragmentManager* fragmentManager = theRenderer->getFragmentManager(); if (!fragmentManager) { return MS::kFailure; } @@ -232,9 +201,9 @@ MStatus HdVP2ShaderFragments::registerFragments() switch (theRenderer->drawAPI()) { case MHWRender::kOpenGLCoreProfile: language = "GLSL"; break; - case MHWRender::kDirectX11: language = "HLSL"; break; - case MHWRender::kOpenGL: language = "Cg"; break; - default: MGlobal::displayError("Unknown draw API"); break; + case MHWRender::kDirectX11: language = "HLSL"; break; + case MHWRender::kOpenGL: language = "Cg"; break; + default: MGlobal::displayError("Unknown draw API"); break; } // Register all fragments. @@ -245,20 +214,19 @@ MStatus HdVP2ShaderFragments::registerFragments() continue; } - const std::string fragXmlFile = - TfStringPrintf("%s_%s.xml", fragName.asChar(), language.c_str()); + const std::string fragXmlFile + = TfStringPrintf("%s_%s.xml", fragName.asChar(), language.c_str()); const std::string fragXmlPath = _GetResourcePath(fragXmlFile); - const MString addedName = - fragmentManager->addShadeFragmentFromFile( - fragXmlPath.c_str(), - false); + const MString addedName + = fragmentManager->addShadeFragmentFromFile(fragXmlPath.c_str(), false); if (addedName != fragName) { - MGlobal::displayError( - TfStringPrintf("Failed to register fragment '%s' from file: %s", - fragName.asChar(), - fragXmlPath.c_str()).c_str()); + MGlobal::displayError(TfStringPrintf( + "Failed to register fragment '%s' from file: %s", + fragName.asChar(), + fragXmlPath.c_str()) + .c_str()); return MS::kFailure; } } @@ -270,20 +238,18 @@ MStatus HdVP2ShaderFragments::registerFragments() continue; } - const std::string fragXmlFile = - TfStringPrintf("%s.xml", fragName.asChar()); + const std::string fragXmlFile = TfStringPrintf("%s.xml", fragName.asChar()); const std::string fragXmlPath = _GetResourcePath(fragXmlFile); - const MString addedName = - fragmentManager->addShadeFragmentFromFile( - fragXmlPath.c_str(), - false); + const MString addedName + = fragmentManager->addShadeFragmentFromFile(fragXmlPath.c_str(), false); if (addedName != fragName) { - MGlobal::displayError( - TfStringPrintf("Failed to register fragment '%s' from file: %s", - fragName.asChar(), - fragXmlPath.c_str()).c_str()); + MGlobal::displayError(TfStringPrintf( + "Failed to register fragment '%s' from file: %s", + fragName.asChar(), + fragXmlPath.c_str()) + .c_str()); return MS::kFailure; } } @@ -296,17 +262,17 @@ MStatus HdVP2ShaderFragments::registerFragments() continue; } - const std::string fragGraphXmlFile = - TfStringPrintf("%s.xml", fragGraphName.asChar()); + const std::string fragGraphXmlFile = TfStringPrintf("%s.xml", fragGraphName.asChar()); const std::string fragGraphXmlPath = _GetResourcePath(fragGraphXmlFile); - const MString addedName = - fragmentManager->addFragmentGraphFromFile(fragGraphXmlPath.c_str()); + const MString addedName + = fragmentManager->addFragmentGraphFromFile(fragGraphXmlPath.c_str()); if (addedName != fragGraphName) { - MGlobal::displayError( - TfStringPrintf("Failed to register fragment graph '%s' from file: %s", - fragGraphName.asChar(), - fragGraphXmlPath.c_str()).c_str()); + MGlobal::displayError(TfStringPrintf( + "Failed to register fragment graph '%s' from file: %s", + fragGraphName.asChar(), + fragGraphXmlPath.c_str()) + .c_str()); return MS::kFailure; } } @@ -325,8 +291,7 @@ MStatus HdVP2ShaderFragments::registerFragments() // Register a desired domain shader fragment for each input parameter. for (const auto& mapping : _domainShaderInputNameMappings) { - fragmentManager->addDomainShaderInputNameMapping( - mapping.first, mapping.second); + fragmentManager->addDomainShaderInputNameMapping(mapping.first, mapping.second); } #endif @@ -354,8 +319,7 @@ MStatus HdVP2ShaderFragments::deregisterFragments() return MS::kFailure; } - MHWRender::MFragmentManager* fragmentManager = - theRenderer->getFragmentManager(); + MHWRender::MFragmentManager* fragmentManager = theRenderer->getFragmentManager(); if (!fragmentManager) { return MS::kFailure; } @@ -380,8 +344,8 @@ MStatus HdVP2ShaderFragments::deregisterFragments() if (!fragmentManager->removeFragment(fragGraphName)) { MGlobal::displayWarning( - TfStringPrintf("Failed to remove fragment graph: %s", - fragGraphName.asChar()).c_str()); + TfStringPrintf("Failed to remove fragment graph: %s", fragGraphName.asChar()) + .c_str()); return MS::kFailure; } } @@ -392,8 +356,7 @@ MStatus HdVP2ShaderFragments::deregisterFragments() if (!fragmentManager->removeFragment(fragName)) { MGlobal::displayWarning( - TfStringPrintf("Failed to remove fragment: %s", - fragName.asChar()).c_str()); + TfStringPrintf("Failed to remove fragment: %s", fragName.asChar()).c_str()); return MS::kFailure; } } @@ -402,13 +365,11 @@ MStatus HdVP2ShaderFragments::deregisterFragments() // Clear the shader manager's effect cache as well so that any changes to // the fragments will get picked up if they are re-registered. - const MHWRender::MShaderManager* shaderMgr = - theRenderer->getShaderManager(); + const MHWRender::MShaderManager* shaderMgr = theRenderer->getShaderManager(); if (shaderMgr) { MStatus status = shaderMgr->clearEffectCache(); if (status != MS::kSuccess) { - MGlobal::displayWarning( - "Failed to clear shader manager effect cache"); + MGlobal::displayWarning("Failed to clear shader manager effect cache"); return status; } } diff --git a/lib/mayaUsd/render/vp2ShaderFragments/shaderFragments.h b/lib/mayaUsd/render/vp2ShaderFragments/shaderFragments.h index 7c83ab5949..8190e2652a 100644 --- a/lib/mayaUsd/render/vp2ShaderFragments/shaderFragments.h +++ b/lib/mayaUsd/render/vp2ShaderFragments/shaderFragments.h @@ -16,18 +16,18 @@ #ifndef HD_VP2_SHADER_FRAGMENTS #define HD_VP2_SHADER_FRAGMENTS -#include -#include - #include +#include +#include + #include PXR_NAMESPACE_OPEN_SCOPE -#define MAYAUSD_CORE_PUBLIC_USD_PREVIEW_SURFACE_TOKENS \ - ((CoreFragmentGraphName, "UsdPreviewSurfaceCore")) \ - ((SurfaceFragmentGraphName, "UsdPreviewSurface")) +#define MAYAUSD_CORE_PUBLIC_USD_PREVIEW_SURFACE_TOKENS \ + ((CoreFragmentGraphName, "UsdPreviewSurfaceCore"))( \ + (SurfaceFragmentGraphName, "UsdPreviewSurface")) TF_DECLARE_PUBLIC_TOKENS( HdVP2ShaderFragmentsTokens, diff --git a/lib/mayaUsd/ufe/Global.cpp b/lib/mayaUsd/ufe/Global.cpp index 1a0398e927..122e20b8a1 100644 --- a/lib/mayaUsd/ufe/Global.cpp +++ b/lib/mayaUsd/ufe/Global.cpp @@ -15,11 +15,7 @@ // #include "Global.h" -#include -#include - -#include -#include +#include "private/UfeNotifGuard.h" #include #include @@ -28,14 +24,18 @@ #include #include -#include "private/UfeNotifGuard.h" +#include +#include + +#include +#include #ifdef UFE_V2_FEATURES_AVAILABLE // Note: must come after include of ufe files so we have the define. +#include #include -#include #include -#include +#include #if UFE_PREVIEW_VERSION_NUM >= 2022 #include #endif @@ -45,7 +45,7 @@ #endif namespace { - int gRegistrationCount = 0; +int gRegistrationCount = 0; } namespace MAYAUSD_NS_DEF { @@ -57,7 +57,7 @@ namespace ufe { // Maya's UFE run-time name and ID. static const std::string kMayaRunTimeName("Maya-DG"); -Ufe::Rtid g_MayaRtid = 0; +Ufe::Rtid g_MayaRtid = 0; // Register this run-time with UFE under the following name. static const std::string kUSDRunTimeName("USD"); @@ -90,92 +90,87 @@ bool InAddOrDeleteOperation::inGuard = false; // initialize the stage model. MStatus initialize() { - // If we're already registered, do nothing. - if (gRegistrationCount++ > 0) - return MS::kSuccess; + // If we're already registered, do nothing. + if (gRegistrationCount++ > 0) + return MS::kSuccess; - // Replace the Maya hierarchy handler with ours. - g_MayaRtid = Ufe::RunTimeMgr::instance().getId(kMayaRunTimeName); + // Replace the Maya hierarchy handler with ours. + g_MayaRtid = Ufe::RunTimeMgr::instance().getId(kMayaRunTimeName); #if !defined(NDEBUG) - assert(g_MayaRtid != 0); + assert(g_MayaRtid != 0); #endif - if (g_MayaRtid == 0) - return MS::kFailure; + if (g_MayaRtid == 0) + return MS::kFailure; - g_MayaHierarchyHandler = Ufe::RunTimeMgr::instance().hierarchyHandler(g_MayaRtid); - auto proxyShapeHierHandler = ProxyShapeHierarchyHandler::create(g_MayaHierarchyHandler); - Ufe::RunTimeMgr::instance().setHierarchyHandler(g_MayaRtid, proxyShapeHierHandler); + g_MayaHierarchyHandler = Ufe::RunTimeMgr::instance().hierarchyHandler(g_MayaRtid); + auto proxyShapeHierHandler = ProxyShapeHierarchyHandler::create(g_MayaHierarchyHandler); + Ufe::RunTimeMgr::instance().setHierarchyHandler(g_MayaRtid, proxyShapeHierHandler); #ifdef UFE_V2_FEATURES_AVAILABLE - g_MayaContextOpsHandler = Ufe::RunTimeMgr::instance().contextOpsHandler(g_MayaRtid); - auto proxyShapeContextOpsHandler = ProxyShapeContextOpsHandler::create(g_MayaContextOpsHandler); - Ufe::RunTimeMgr::instance().setContextOpsHandler(g_MayaRtid, proxyShapeContextOpsHandler); + g_MayaContextOpsHandler = Ufe::RunTimeMgr::instance().contextOpsHandler(g_MayaRtid); + auto proxyShapeContextOpsHandler = ProxyShapeContextOpsHandler::create(g_MayaContextOpsHandler); + Ufe::RunTimeMgr::instance().setContextOpsHandler(g_MayaRtid, proxyShapeContextOpsHandler); #endif - auto usdHierHandler = UsdHierarchyHandler::create(); - auto usdTrans3dHandler = UsdTransform3dHandler::create(); - auto usdSceneItemOpsHandler = UsdSceneItemOpsHandler::create(); - UFE_V2(auto usdAttributesHandler = UsdAttributesHandler::create();) - UFE_V2(auto usdObject3dHandler = UsdObject3dHandler::create();) - UFE_V2(auto usdContextOpsHandler = UsdContextOpsHandler::create();) + auto usdHierHandler = UsdHierarchyHandler::create(); + auto usdTrans3dHandler = UsdTransform3dHandler::create(); + auto usdSceneItemOpsHandler = UsdSceneItemOpsHandler::create(); + UFE_V2(auto usdAttributesHandler = UsdAttributesHandler::create();) + UFE_V2(auto usdObject3dHandler = UsdObject3dHandler::create();) + UFE_V2(auto usdContextOpsHandler = UsdContextOpsHandler::create();) #if UFE_PREVIEW_VERSION_NUM >= 2022 - UFE_V2(auto usdUIInfoHandler = UsdUIInfoHandler::create();) + UFE_V2(auto usdUIInfoHandler = UsdUIInfoHandler::create();) #endif - g_USDRtid = Ufe::RunTimeMgr::instance().register_( - kUSDRunTimeName, usdHierHandler, usdTrans3dHandler, - usdSceneItemOpsHandler - UFE_V2(, usdAttributesHandler, usdObject3dHandler) - UFE_V2(, usdContextOpsHandler) + g_USDRtid = Ufe::RunTimeMgr::instance().register_( + kUSDRunTimeName, + usdHierHandler, + usdTrans3dHandler, + usdSceneItemOpsHandler UFE_V2(, usdAttributesHandler, usdObject3dHandler) + UFE_V2(, usdContextOpsHandler) #if UFE_PREVIEW_VERSION_NUM >= 2022 - UFE_V2(, usdUIInfoHandler) + UFE_V2(, usdUIInfoHandler) #endif ); #if !defined(NDEBUG) - assert(g_USDRtid != 0); + assert(g_USDRtid != 0); #endif - if (g_USDRtid == 0) - return MS::kFailure; + if (g_USDRtid == 0) + return MS::kFailure; - g_StagesSubject = StagesSubject::create(); + g_StagesSubject = StagesSubject::create(); // Register for UFE string to path service using path component separator '/' UFE_V2(Ufe::PathString::registerPathComponentSeparator(g_USDRtid, '/');) - return MS::kSuccess; + return MS::kSuccess; } MStatus finalize() { - // If more than one plugin still has us registered, do nothing. - if (gRegistrationCount-- > 1) - return MS::kSuccess; + // If more than one plugin still has us registered, do nothing. + if (gRegistrationCount-- > 1) + return MS::kSuccess; - // Restore the normal Maya hierarchy handler, and unregister. - Ufe::RunTimeMgr::instance().setHierarchyHandler(g_MayaRtid, g_MayaHierarchyHandler); + // Restore the normal Maya hierarchy handler, and unregister. + Ufe::RunTimeMgr::instance().setHierarchyHandler(g_MayaRtid, g_MayaHierarchyHandler); #ifdef UFE_V2_FEATURES_AVAILABLE - // Restore the normal Maya context ops handler (can be empty). - if (g_MayaContextOpsHandler) - Ufe::RunTimeMgr::instance().setContextOpsHandler(g_MayaRtid, g_MayaContextOpsHandler); - g_MayaContextOpsHandler.reset(); + // Restore the normal Maya context ops handler (can be empty). + if (g_MayaContextOpsHandler) + Ufe::RunTimeMgr::instance().setContextOpsHandler(g_MayaRtid, g_MayaContextOpsHandler); + g_MayaContextOpsHandler.reset(); #endif - Ufe::RunTimeMgr::instance().unregister(g_USDRtid); - g_MayaHierarchyHandler.reset(); + Ufe::RunTimeMgr::instance().unregister(g_USDRtid); + g_MayaHierarchyHandler.reset(); - g_StagesSubject.Reset(); + g_StagesSubject.Reset(); - return MS::kSuccess; + return MS::kSuccess; } -Ufe::Rtid getUsdRunTimeId() -{ - return g_USDRtid; -} +Ufe::Rtid getUsdRunTimeId() { return g_USDRtid; } -Ufe::Rtid getMayaRunTimeId() -{ - return g_MayaRtid; -} +Ufe::Rtid getMayaRunTimeId() { return g_MayaRtid; } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/Global.h b/lib/mayaUsd/ufe/Global.h index bf2c242c9c..b6035aea01 100644 --- a/lib/mayaUsd/ufe/Global.h +++ b/lib/mayaUsd/ufe/Global.h @@ -15,12 +15,11 @@ // #pragma once -#include +#include +#include #include -#include - namespace MAYAUSD_NS_DEF { namespace ufe { @@ -43,4 +42,4 @@ MAYAUSD_CORE_PUBLIC Ufe::Rtid getMayaRunTimeId(); } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/ProxyShapeContextOpsHandler.cpp b/lib/mayaUsd/ufe/ProxyShapeContextOpsHandler.cpp index 4cd5ca14b9..01e941e20f 100644 --- a/lib/mayaUsd/ufe/ProxyShapeContextOpsHandler.cpp +++ b/lib/mayaUsd/ufe/ProxyShapeContextOpsHandler.cpp @@ -15,28 +15,29 @@ // #include "ProxyShapeContextOpsHandler.h" -#include - #include #include #include +#include + namespace MAYAUSD_NS_DEF { namespace ufe { -ProxyShapeContextOpsHandler::ProxyShapeContextOpsHandler(const Ufe::ContextOpsHandler::Ptr& mayaContextOpsHandler) - : Ufe::ContextOpsHandler() - , _mayaContextOpsHandler(mayaContextOpsHandler) -{} - -ProxyShapeContextOpsHandler::~ProxyShapeContextOpsHandler() +ProxyShapeContextOpsHandler::ProxyShapeContextOpsHandler( + const Ufe::ContextOpsHandler::Ptr& mayaContextOpsHandler) + : Ufe::ContextOpsHandler() + , _mayaContextOpsHandler(mayaContextOpsHandler) { } +ProxyShapeContextOpsHandler::~ProxyShapeContextOpsHandler() { } + /*static*/ -ProxyShapeContextOpsHandler::Ptr ProxyShapeContextOpsHandler::create(const Ufe::ContextOpsHandler::Ptr& mayaContextOpsHandler) +ProxyShapeContextOpsHandler::Ptr +ProxyShapeContextOpsHandler::create(const Ufe::ContextOpsHandler::Ptr& mayaContextOpsHandler) { - return std::make_shared(mayaContextOpsHandler); + return std::make_shared(mayaContextOpsHandler); } //------------------------------------------------------------------------------ @@ -45,36 +46,32 @@ ProxyShapeContextOpsHandler::Ptr ProxyShapeContextOpsHandler::create(const Ufe:: Ufe::ContextOps::Ptr ProxyShapeContextOpsHandler::contextOps(const Ufe::SceneItem::Ptr& item) const { - if (isAGatewayType(item->nodeType())) - { - // UsdContextOps expects a UsdSceneItem which wraps a prim, so - // create one using the pseudo-root and our own path. - UsdStageWeakPtr stage = getStage(item->path()); - if (stage) - { - auto usdItem = UsdSceneItem::create(item->path(), stage->GetPseudoRoot()); - auto usdContextOpsHandler = UsdContextOpsHandler::create(); - auto cOps = usdContextOpsHandler->contextOps(usdItem); - UsdContextOps::Ptr usdCOps = std::dynamic_pointer_cast(cOps); + if (isAGatewayType(item->nodeType())) { + // UsdContextOps expects a UsdSceneItem which wraps a prim, so + // create one using the pseudo-root and our own path. + UsdStageWeakPtr stage = getStage(item->path()); + if (stage) { + auto usdItem = UsdSceneItem::create(item->path(), stage->GetPseudoRoot()); + auto usdContextOpsHandler = UsdContextOpsHandler::create(); + auto cOps = usdContextOpsHandler->contextOps(usdItem); + UsdContextOps::Ptr usdCOps = std::dynamic_pointer_cast(cOps); - // We explicitly set the context ops as a gateway type because we created a - // new UsdSceneItem with a USD prim. Thus the scene item is no longer from - // the derived class in Maya and we cannot properly query the node type. - if (usdCOps) - usdCOps->setIsAGatewayType(true); - return cOps; - } + // We explicitly set the context ops as a gateway type because we created a + // new UsdSceneItem with a USD prim. Thus the scene item is no longer from + // the derived class in Maya and we cannot properly query the node type. + if (usdCOps) + usdCOps->setIsAGatewayType(true); + return cOps; + } - return nullptr; - } - else if (_mayaContextOpsHandler) - { - return _mayaContextOpsHandler->contextOps(item); - } + return nullptr; + } else if (_mayaContextOpsHandler) { + return _mayaContextOpsHandler->contextOps(item); + } - // Context ops handler is not mandatory. - return nullptr; + // Context ops handler is not mandatory. + return nullptr; } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/ProxyShapeContextOpsHandler.h b/lib/mayaUsd/ufe/ProxyShapeContextOpsHandler.h index 24dad09dca..4cfd7410b3 100644 --- a/lib/mayaUsd/ufe/ProxyShapeContextOpsHandler.h +++ b/lib/mayaUsd/ufe/ProxyShapeContextOpsHandler.h @@ -15,10 +15,10 @@ // #pragma once -#include - #include +#include + namespace MAYAUSD_NS_DEF { namespace ufe { @@ -36,27 +36,28 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC ProxyShapeContextOpsHandler : public Ufe::ContextOpsHandler { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - ProxyShapeContextOpsHandler(const Ufe::ContextOpsHandler::Ptr& mayaContextOpsHandler); - ~ProxyShapeContextOpsHandler() override; + ProxyShapeContextOpsHandler(const Ufe::ContextOpsHandler::Ptr& mayaContextOpsHandler); + ~ProxyShapeContextOpsHandler() override; - // Delete the copy/move constructors assignment operators. - ProxyShapeContextOpsHandler(const ProxyShapeContextOpsHandler&) = delete; - ProxyShapeContextOpsHandler& operator=(const ProxyShapeContextOpsHandler&) = delete; - ProxyShapeContextOpsHandler(ProxyShapeContextOpsHandler&&) = delete; - ProxyShapeContextOpsHandler& operator=(ProxyShapeContextOpsHandler&&) = delete; + // Delete the copy/move constructors assignment operators. + ProxyShapeContextOpsHandler(const ProxyShapeContextOpsHandler&) = delete; + ProxyShapeContextOpsHandler& operator=(const ProxyShapeContextOpsHandler&) = delete; + ProxyShapeContextOpsHandler(ProxyShapeContextOpsHandler&&) = delete; + ProxyShapeContextOpsHandler& operator=(ProxyShapeContextOpsHandler&&) = delete; - //! Create a ProxyShapeContextOpsHandler from a UFE hierarchy handler. - static ProxyShapeContextOpsHandler::Ptr create(const Ufe::ContextOpsHandler::Ptr& mayaContextOpsHandler); + //! Create a ProxyShapeContextOpsHandler from a UFE hierarchy handler. + static ProxyShapeContextOpsHandler::Ptr + create(const Ufe::ContextOpsHandler::Ptr& mayaContextOpsHandler); - // Ufe::ContextOpsHandler overrides - Ufe::ContextOps::Ptr contextOps(const Ufe::SceneItem::Ptr& item) const override; + // Ufe::ContextOpsHandler overrides + Ufe::ContextOps::Ptr contextOps(const Ufe::SceneItem::Ptr& item) const override; private: - Ufe::ContextOpsHandler::Ptr _mayaContextOpsHandler; + Ufe::ContextOpsHandler::Ptr _mayaContextOpsHandler; }; // ProxyShapeContextOpsHandler } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/ProxyShapeHandler.cpp b/lib/mayaUsd/ufe/ProxyShapeHandler.cpp index f180072bb6..1cfd3ce9c3 100644 --- a/lib/mayaUsd/ufe/ProxyShapeHandler.cpp +++ b/lib/mayaUsd/ufe/ProxyShapeHandler.cpp @@ -15,12 +15,12 @@ // #include "ProxyShapeHandler.h" +#include + #include #include #include -#include - namespace MAYAUSD_NS_DEF { namespace ufe { @@ -34,60 +34,53 @@ const std::string ProxyShapeHandler::fMayaUsdGatewayNodeType = "mayaUsdProxyShap //------------------------------------------------------------------------------ /*static*/ -const std::string& ProxyShapeHandler::gatewayNodeType() -{ - return fMayaUsdGatewayNodeType; -} +const std::string& ProxyShapeHandler::gatewayNodeType() { return fMayaUsdGatewayNodeType; } /*static*/ std::vector ProxyShapeHandler::getAllNames() { - std::vector names; - MString cmd; - MStringArray result; - cmd.format("ls -type ^1s -long", fMayaUsdGatewayNodeType.c_str()); - if (MS::kSuccess == MGlobal::executeCommand(cmd, result)) - { - names.reserve(result.length()); - for (MString& name : result) - { - names.push_back(name.asChar()); - } - } - return names; + std::vector names; + MString cmd; + MStringArray result; + cmd.format("ls -type ^1s -long", fMayaUsdGatewayNodeType.c_str()); + if (MS::kSuccess == MGlobal::executeCommand(cmd, result)) { + names.reserve(result.length()); + for (MString& name : result) { + names.push_back(name.asChar()); + } + } + return names; } /*static*/ UsdStageWeakPtr ProxyShapeHandler::dagPathToStage(const std::string& dagPath) { - auto prim = UsdMayaQuery::GetPrim(dagPath); - return prim ? prim.GetStage() : nullptr; + auto prim = UsdMayaQuery::GetPrim(dagPath); + return prim ? prim.GetStage() : nullptr; } /*static*/ std::vector ProxyShapeHandler::getAllStages() { - // According to Pixar, the following should work: - // return UsdMayaStageCache::Get().GetAllStages(); - // but after a file open of a scene with one or more Pixar proxy shapes, - // returns an empty list. To be investigated, PPT, 28-Feb-2019. + // According to Pixar, the following should work: + // return UsdMayaStageCache::Get().GetAllStages(); + // but after a file open of a scene with one or more Pixar proxy shapes, + // returns an empty list. To be investigated, PPT, 28-Feb-2019. - // When using an unmodified AL plugin, the following line crashes - // Maya, so it requires the AL proxy shape inheritance from - // MayaUsdProxyShapeBase. PPT, 12-Apr-2019. - std::vector stages; - auto allNames = getAllNames(); - stages.reserve(allNames.size()); - for (const auto& name : allNames) - { - UsdStageWeakPtr stage = dagPathToStage(name); - if (stage) - { - stages.push_back(stage); - } - } - return stages; + // When using an unmodified AL plugin, the following line crashes + // Maya, so it requires the AL proxy shape inheritance from + // MayaUsdProxyShapeBase. PPT, 12-Apr-2019. + std::vector stages; + auto allNames = getAllNames(); + stages.reserve(allNames.size()); + for (const auto& name : allNames) { + UsdStageWeakPtr stage = dagPathToStage(name); + if (stage) { + stages.push_back(stage); + } + } + return stages; } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/ProxyShapeHandler.h b/lib/mayaUsd/ufe/ProxyShapeHandler.h index 1373df1948..584f0e9f38 100644 --- a/lib/mayaUsd/ufe/ProxyShapeHandler.h +++ b/lib/mayaUsd/ufe/ProxyShapeHandler.h @@ -15,13 +15,13 @@ // #pragma once -#include -#include +#include #include #include -#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -29,34 +29,34 @@ namespace MAYAUSD_NS_DEF { namespace ufe { /*! - Proxy shape abstraction, to support use of USD proxy shape with any plugin - that has a proxy shape derived from MayaUsdProxyShapeBase. + Proxy shape abstraction, to support use of USD proxy shape with any plugin + that has a proxy shape derived from MayaUsdProxyShapeBase. */ class MAYAUSD_CORE_PUBLIC ProxyShapeHandler { public: - ProxyShapeHandler() = default; - ~ProxyShapeHandler() = default; + ProxyShapeHandler() = default; + ~ProxyShapeHandler() = default; - // Delete the copy/move constructors assignment operators. - ProxyShapeHandler(const ProxyShapeHandler&) = delete; - ProxyShapeHandler& operator=(const ProxyShapeHandler&) = delete; - ProxyShapeHandler(ProxyShapeHandler&&) = delete; - ProxyShapeHandler& operator=(ProxyShapeHandler&&) = delete; + // Delete the copy/move constructors assignment operators. + ProxyShapeHandler(const ProxyShapeHandler&) = delete; + ProxyShapeHandler& operator=(const ProxyShapeHandler&) = delete; + ProxyShapeHandler(ProxyShapeHandler&&) = delete; + ProxyShapeHandler& operator=(ProxyShapeHandler&&) = delete; - //! \return Type of the Maya shape node at the root of a USD hierarchy. - static const std::string& gatewayNodeType(); + //! \return Type of the Maya shape node at the root of a USD hierarchy. + static const std::string& gatewayNodeType(); - static std::vector getAllNames(); + static std::vector getAllNames(); - static UsdStageWeakPtr dagPathToStage(const std::string& dagPath); + static UsdStageWeakPtr dagPathToStage(const std::string& dagPath); - static std::vector getAllStages(); + static std::vector getAllStages(); private: - static const std::string fMayaUsdGatewayNodeType; + static const std::string fMayaUsdGatewayNodeType; }; // ProxyShapeHandler } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/ProxyShapeHierarchy.cpp b/lib/mayaUsd/ufe/ProxyShapeHierarchy.cpp index 125a3a22ed..a84d4dca88 100644 --- a/lib/mayaUsd/ufe/ProxyShapeHierarchy.cpp +++ b/lib/mayaUsd/ufe/ProxyShapeHierarchy.cpp @@ -15,35 +15,37 @@ // #include "ProxyShapeHierarchy.h" -#include -#include +#include +#include + +#include #include #include #include #include -#include - -#include -#include +#include +#include #ifdef UFE_V2_FEATURES_AVAILABLE -#include #include +#include #include #endif namespace { - UsdPrimSiblingRange getUSDFilteredChildren(const UsdPrim& prim, const Usd_PrimFlagsPredicate pred = UsdPrimDefaultPredicate) - { - // Since the equivalent of GetChildren is - // GetFilteredChildren( UsdPrimDefaultPredicate ), - // we will use that as the initial value. - // - return prim.GetFilteredChildren(pred); - } +UsdPrimSiblingRange getUSDFilteredChildren( + const UsdPrim& prim, + const Usd_PrimFlagsPredicate pred = UsdPrimDefaultPredicate) +{ + // Since the equivalent of GetChildren is + // GetFilteredChildren( UsdPrimDefaultPredicate ), + // we will use that as the initial value. + // + return prim.GetFilteredChildren(pred); } +} // namespace namespace MAYAUSD_NS_DEF { namespace ufe { @@ -57,29 +59,25 @@ extern Ufe::Rtid g_USDRtid; // ProxyShapeHierarchy //------------------------------------------------------------------------------ -ProxyShapeHierarchy::ProxyShapeHierarchy( - const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler -) - : Ufe::Hierarchy() - , fMayaHierarchyHandler(mayaHierarchyHandler) +ProxyShapeHierarchy::ProxyShapeHierarchy(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler) + : Ufe::Hierarchy() + , fMayaHierarchyHandler(mayaHierarchyHandler) { } -ProxyShapeHierarchy::~ProxyShapeHierarchy() -{ -} +ProxyShapeHierarchy::~ProxyShapeHierarchy() { } /*static*/ -ProxyShapeHierarchy::Ptr ProxyShapeHierarchy::create(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler) +ProxyShapeHierarchy::Ptr +ProxyShapeHierarchy::create(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler) { - return std::make_shared(mayaHierarchyHandler); + return std::make_shared(mayaHierarchyHandler); } /*static*/ ProxyShapeHierarchy::Ptr ProxyShapeHierarchy::create( const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler, - const Ufe::SceneItem::Ptr& item -) + const Ufe::SceneItem::Ptr& item) { auto hierarchy = create(mayaHierarchyHandler); hierarchy->setItem(item); @@ -88,84 +86,78 @@ ProxyShapeHierarchy::Ptr ProxyShapeHierarchy::create( void ProxyShapeHierarchy::setItem(const Ufe::SceneItem::Ptr& item) { - // Our USD root prim is from the stage, which is from the item. So if we are - // changing the item, it's possible that we won't have the same stage (and - // thus the same root prim). To be safe, clear our stored root prim. - if (fItem != item) - { - fUsdRootPrim = UsdPrim(); - } - fItem = item; - fMayaHierarchy = fMayaHierarchyHandler->hierarchy(item); + // Our USD root prim is from the stage, which is from the item. So if we are + // changing the item, it's possible that we won't have the same stage (and + // thus the same root prim). To be safe, clear our stored root prim. + if (fItem != item) { + fUsdRootPrim = UsdPrim(); + } + fItem = item; + fMayaHierarchy = fMayaHierarchyHandler->hierarchy(item); } const UsdPrim& ProxyShapeHierarchy::getUsdRootPrim() const { - if (!fUsdRootPrim.IsValid()) - { - // FIXME During AL_usdmaya_ProxyShapeImport, nodes (both Maya - // and USD) are being added (e.g. the proxy shape itself), but - // there is no stage yet, and there is no way to detect that a - // proxy shape import command is under way. PPT, 28-Sep-2018. - UsdStageWeakPtr stage = getStage(fItem->path()); - if (stage) - { - fUsdRootPrim = stage->GetPseudoRoot(); - } - } - return fUsdRootPrim; + if (!fUsdRootPrim.IsValid()) { + // FIXME During AL_usdmaya_ProxyShapeImport, nodes (both Maya + // and USD) are being added (e.g. the proxy shape itself), but + // there is no stage yet, and there is no way to detect that a + // proxy shape import command is under way. PPT, 28-Sep-2018. + UsdStageWeakPtr stage = getStage(fItem->path()); + if (stage) { + fUsdRootPrim = stage->GetPseudoRoot(); + } + } + return fUsdRootPrim; } //------------------------------------------------------------------------------ // Ufe::Hierarchy overrides //------------------------------------------------------------------------------ -Ufe::SceneItem::Ptr ProxyShapeHierarchy::sceneItem() const -{ - return fItem; -} +Ufe::SceneItem::Ptr ProxyShapeHierarchy::sceneItem() const { return fItem; } bool ProxyShapeHierarchy::hasChildren() const { - const UsdPrim& rootPrim = getUsdRootPrim(); - if (!rootPrim.IsValid()) { - UFE_LOG("invalid root prim in ProxyShapeHierarchy::hasChildren()"); - return false; - } - return !getUSDFilteredChildren(rootPrim).empty(); + const UsdPrim& rootPrim = getUsdRootPrim(); + if (!rootPrim.IsValid()) { + UFE_LOG("invalid root prim in ProxyShapeHierarchy::hasChildren()"); + return false; + } + return !getUSDFilteredChildren(rootPrim).empty(); } Ufe::SceneItemList ProxyShapeHierarchy::children() const { - // Return children of the USD root. - const UsdPrim& rootPrim = getUsdRootPrim(); - if (!rootPrim.IsValid()) - return Ufe::SceneItemList(); + // Return children of the USD root. + const UsdPrim& rootPrim = getUsdRootPrim(); + if (!rootPrim.IsValid()) + return Ufe::SceneItemList(); - return createUFEChildList(getUSDFilteredChildren(rootPrim)); + return createUFEChildList(getUSDFilteredChildren(rootPrim)); } #ifdef UFE_V2_FEATURES_AVAILABLE #if UFE_PREVIEW_VERSION_NUM >= 2022 Ufe::SceneItemList ProxyShapeHierarchy::filteredChildren(const ChildFilter& childFilter) const { - // Return filtered children of the USD root. - const UsdPrim& rootPrim = getUsdRootPrim(); - if (!rootPrim.IsValid()) - return Ufe::SceneItemList(); - - // Note: for now the only child filter flag we support is "Inactive Prims". - // See UsdHierarchyHandler::childFilter() - if ((childFilter.size() == 1) && (childFilter.front().name == "InactivePrims")) - { - // See uniqueChildName() for explanation of USD filter predicate. - Usd_PrimFlagsPredicate flags = childFilter.front().value ? UsdPrimIsDefined && !UsdPrimIsAbstract - : UsdPrimDefaultPredicate; - return createUFEChildList(getUSDFilteredChildren(rootPrim, flags)); - } - - UFE_LOG("Unknown child filter"); - return Ufe::SceneItemList(); + // Return filtered children of the USD root. + const UsdPrim& rootPrim = getUsdRootPrim(); + if (!rootPrim.IsValid()) + return Ufe::SceneItemList(); + + // Note: for now the only child filter flag we support is "Inactive Prims". + // See UsdHierarchyHandler::childFilter() + if ((childFilter.size() == 1) && (childFilter.front().name == "InactivePrims")) { + // See uniqueChildName() for explanation of USD filter predicate. + Usd_PrimFlagsPredicate flags = childFilter.front().value + ? UsdPrimIsDefined && !UsdPrimIsAbstract + : UsdPrimDefaultPredicate; + return createUFEChildList(getUSDFilteredChildren(rootPrim, flags)); + } + + UFE_LOG("Unknown child filter"); + return Ufe::SceneItemList(); } #endif #endif @@ -173,29 +165,27 @@ Ufe::SceneItemList ProxyShapeHierarchy::filteredChildren(const ChildFilter& chil // Return UFE child list from input USD child list. Ufe::SceneItemList ProxyShapeHierarchy::createUFEChildList(const UsdPrimSiblingRange& range) const { - // We must create selection items for our children. These will have as - // path the path of the proxy shape, with a single path segment of a - // single component appended to it. - auto parentPath = fItem->path(); - Ufe::SceneItemList children; - for (const auto& child : range) - { - children.emplace_back(UsdSceneItem::create(parentPath + Ufe::PathSegment( - Ufe::PathComponent(child.GetName().GetString()), g_USDRtid, '/'), child)); - } - return children; + // We must create selection items for our children. These will have as + // path the path of the proxy shape, with a single path segment of a + // single component appended to it. + auto parentPath = fItem->path(); + Ufe::SceneItemList children; + for (const auto& child : range) { + children.emplace_back(UsdSceneItem::create( + parentPath + + Ufe::PathSegment(Ufe::PathComponent(child.GetName().GetString()), g_USDRtid, '/'), + child)); + } + return children; } -Ufe::SceneItem::Ptr ProxyShapeHierarchy::parent() const -{ - return fMayaHierarchy->parent(); -} +Ufe::SceneItem::Ptr ProxyShapeHierarchy::parent() const { return fMayaHierarchy->parent(); } #ifndef UFE_V2_FEATURES_AVAILABLE // UFE v1 specific method Ufe::AppendedChild ProxyShapeHierarchy::appendChild(const Ufe::SceneItem::Ptr& child) { - throw std::runtime_error("ProxyShapeHierarchy::appendChild() not implemented"); + throw std::runtime_error("ProxyShapeHierarchy::appendChild() not implemented"); } #endif @@ -203,58 +193,60 @@ Ufe::AppendedChild ProxyShapeHierarchy::appendChild(const Ufe::SceneItem::Ptr& c Ufe::InsertChildCommand::Ptr ProxyShapeHierarchy::insertChildCmd( const Ufe::SceneItem::Ptr& child, - const Ufe::SceneItem::Ptr& pos -) + const Ufe::SceneItem::Ptr& pos) { // UsdUndoInsertChildCommand expects a UsdSceneItem which wraps a prim, so // create one using the pseudo-root and our own path. auto usdItem = UsdSceneItem::create(sceneItem()->path(), getUsdRootPrim()); - return UsdUndoInsertChildCommand::create( - usdItem, downcast(child), downcast(pos)); + return UsdUndoInsertChildCommand::create(usdItem, downcast(child), downcast(pos)); } -Ufe::SceneItem::Ptr ProxyShapeHierarchy::insertChild( - const Ufe::SceneItem::Ptr& child, - const Ufe::SceneItem::Ptr& pos -) +Ufe::SceneItem::Ptr +ProxyShapeHierarchy::insertChild(const Ufe::SceneItem::Ptr& child, const Ufe::SceneItem::Ptr& pos) { auto insertChildCommand = insertChildCmd(child, pos); return insertChildCommand->insertedChild(); } -Ufe::SceneItem::Ptr ProxyShapeHierarchy::createGroup(const Ufe::Selection& selection, const Ufe::PathComponent& name) const +Ufe::SceneItem::Ptr ProxyShapeHierarchy::createGroup( + const Ufe::Selection& selection, + const Ufe::PathComponent& name) const { - Ufe::SceneItem::Ptr createdItem; + Ufe::SceneItem::Ptr createdItem; - auto usdItem = UsdSceneItem::create(sceneItem()->path(), getUsdRootPrim()); - UsdUndoCreateGroupCommand::Ptr cmd = UsdUndoCreateGroupCommand::create(usdItem, selection, name.string()); - if (cmd) { - cmd->execute(); - createdItem = cmd->group(); - } - - return createdItem; + auto usdItem = UsdSceneItem::create(sceneItem()->path(), getUsdRootPrim()); + UsdUndoCreateGroupCommand::Ptr cmd + = UsdUndoCreateGroupCommand::create(usdItem, selection, name.string()); + if (cmd) { + cmd->execute(); + createdItem = cmd->group(); + } + + return createdItem; } -Ufe::UndoableCommand::Ptr ProxyShapeHierarchy::createGroupCmd(const Ufe::Selection& selection, const Ufe::PathComponent& name) const +Ufe::UndoableCommand::Ptr ProxyShapeHierarchy::createGroupCmd( + const Ufe::Selection& selection, + const Ufe::PathComponent& name) const { - auto usdItem = UsdSceneItem::create(sceneItem()->path(), getUsdRootPrim()); + auto usdItem = UsdSceneItem::create(sceneItem()->path(), getUsdRootPrim()); - return UsdUndoCreateGroupCommand::create(usdItem, selection, name.string()); + return UsdUndoCreateGroupCommand::create(usdItem, selection, name.string()); } #if UFE_PREVIEW_VERSION_NUM >= 2026 -Ufe::UndoableCommand::Ptr ProxyShapeHierarchy::reorderCmd(const Ufe::SceneItemList& orderedList) const +Ufe::UndoableCommand::Ptr +ProxyShapeHierarchy::reorderCmd(const Ufe::SceneItemList& orderedList) const { - std::vector orderedTokens; + std::vector orderedTokens; - for (const auto& item : orderedList) { - orderedTokens.emplace_back(downcast(item)->prim().GetPath().GetNameToken()); - } + for (const auto& item : orderedList) { + orderedTokens.emplace_back(downcast(item)->prim().GetPath().GetNameToken()); + } - // create a reorder command and pass in the parent and its ordered children list - return UsdUndoReorderCommand::create(getUsdRootPrim(), orderedTokens); + // create a reorder command and pass in the parent and its ordered children list + return UsdUndoReorderCommand::create(getUsdRootPrim(), orderedTokens); } #endif @@ -267,4 +259,4 @@ Ufe::SceneItem::Ptr ProxyShapeHierarchy::defaultParent() const #endif // UFE_V2_FEATURES_AVAILABLE } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/ProxyShapeHierarchy.h b/lib/mayaUsd/ufe/ProxyShapeHierarchy.h index ded3a946aa..e949d23579 100644 --- a/lib/mayaUsd/ufe/ProxyShapeHierarchy.h +++ b/lib/mayaUsd/ufe/ProxyShapeHierarchy.h @@ -15,13 +15,13 @@ // #pragma once +#include +#include + #include #include #include -#include -#include - PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { @@ -36,46 +36,48 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC ProxyShapeHierarchy : public Ufe::Hierarchy { public: - typedef std::shared_ptr Ptr; - - ProxyShapeHierarchy(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler); - ~ProxyShapeHierarchy() override; - - // Delete the copy/move constructors assignment operators. - ProxyShapeHierarchy(const ProxyShapeHierarchy&) = delete; - ProxyShapeHierarchy& operator=(const ProxyShapeHierarchy&) = delete; - ProxyShapeHierarchy(ProxyShapeHierarchy&&) = delete; - ProxyShapeHierarchy& operator=(ProxyShapeHierarchy&&) = delete; - - //! Create a ProxyShapeHierarchy from a UFE hierarchy handler. - static ProxyShapeHierarchy::Ptr create(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler); - static ProxyShapeHierarchy::Ptr create( - const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler, - const Ufe::SceneItem::Ptr& item - ); - - void setItem(const Ufe::SceneItem::Ptr& item); - - // Ufe::Hierarchy overrides - Ufe::SceneItem::Ptr sceneItem() const override; - bool hasChildren() const override; - Ufe::SceneItemList children() const override; + typedef std::shared_ptr Ptr; + + ProxyShapeHierarchy(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler); + ~ProxyShapeHierarchy() override; + + // Delete the copy/move constructors assignment operators. + ProxyShapeHierarchy(const ProxyShapeHierarchy&) = delete; + ProxyShapeHierarchy& operator=(const ProxyShapeHierarchy&) = delete; + ProxyShapeHierarchy(ProxyShapeHierarchy&&) = delete; + ProxyShapeHierarchy& operator=(ProxyShapeHierarchy&&) = delete; + + //! Create a ProxyShapeHierarchy from a UFE hierarchy handler. + static ProxyShapeHierarchy::Ptr create(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler); + static ProxyShapeHierarchy::Ptr + create(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler, const Ufe::SceneItem::Ptr& item); + + void setItem(const Ufe::SceneItem::Ptr& item); + + // Ufe::Hierarchy overrides + Ufe::SceneItem::Ptr sceneItem() const override; + bool hasChildren() const override; + Ufe::SceneItemList children() const override; #if UFE_PREVIEW_VERSION_NUM >= 2022 UFE_V2(Ufe::SceneItemList filteredChildren(const ChildFilter&) const override;) #endif - Ufe::SceneItem::Ptr parent() const override; + Ufe::SceneItem::Ptr parent() const override; #ifndef UFE_V2_FEATURES_AVAILABLE - Ufe::AppendedChild appendChild(const Ufe::SceneItem::Ptr& child) override; + Ufe::AppendedChild appendChild(const Ufe::SceneItem::Ptr& child) override; #endif #ifdef UFE_V2_FEATURES_AVAILABLE - Ufe::SceneItem::Ptr createGroup(const Ufe::Selection& selection, const Ufe::PathComponent& name) const override; - Ufe::UndoableCommand::Ptr createGroupCmd(const Ufe::Selection& selection, const Ufe::PathComponent& name) const override; + Ufe::SceneItem::Ptr + createGroup(const Ufe::Selection& selection, const Ufe::PathComponent& name) const override; + Ufe::UndoableCommand::Ptr + createGroupCmd(const Ufe::Selection& selection, const Ufe::PathComponent& name) const override; Ufe::SceneItem::Ptr defaultParent() const override; - Ufe::SceneItem::Ptr insertChild(const Ufe::SceneItem::Ptr& child,const Ufe::SceneItem::Ptr& pos) override; - Ufe::InsertChildCommand::Ptr insertChildCmd(const Ufe::SceneItem::Ptr& child, const Ufe::SceneItem::Ptr& pos) override; + Ufe::SceneItem::Ptr + insertChild(const Ufe::SceneItem::Ptr& child, const Ufe::SceneItem::Ptr& pos) override; + Ufe::InsertChildCommand::Ptr + insertChildCmd(const Ufe::SceneItem::Ptr& child, const Ufe::SceneItem::Ptr& pos) override; #if UFE_PREVIEW_VERSION_NUM >= 2026 Ufe::UndoableCommand::Ptr reorderCmd(const Ufe::SceneItemList& orderedList) const override; @@ -83,17 +85,17 @@ class MAYAUSD_CORE_PUBLIC ProxyShapeHierarchy : public Ufe::Hierarchy #endif private: - const UsdPrim& getUsdRootPrim() const; - Ufe::SceneItemList createUFEChildList(const UsdPrimSiblingRange& range) const; + const UsdPrim& getUsdRootPrim() const; + Ufe::SceneItemList createUFEChildList(const UsdPrimSiblingRange& range) const; private: - Ufe::SceneItem::Ptr fItem; - Hierarchy::Ptr fMayaHierarchy; - Ufe::HierarchyHandler::Ptr fMayaHierarchyHandler; + Ufe::SceneItem::Ptr fItem; + Hierarchy::Ptr fMayaHierarchy; + Ufe::HierarchyHandler::Ptr fMayaHierarchyHandler; - // The root prim is initialized on first use and therefore mutable. - mutable UsdPrim fUsdRootPrim; + // The root prim is initialized on first use and therefore mutable. + mutable UsdPrim fUsdRootPrim; }; // ProxyShapeHierarchy } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/ProxyShapeHierarchyHandler.cpp b/lib/mayaUsd/ufe/ProxyShapeHierarchyHandler.cpp index 0ec4e92553..b6489a4d02 100644 --- a/lib/mayaUsd/ufe/ProxyShapeHierarchyHandler.cpp +++ b/lib/mayaUsd/ufe/ProxyShapeHierarchyHandler.cpp @@ -21,19 +21,20 @@ namespace MAYAUSD_NS_DEF { namespace ufe { -ProxyShapeHierarchyHandler::ProxyShapeHierarchyHandler(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler) - : Ufe::HierarchyHandler() - , fMayaHierarchyHandler(mayaHierarchyHandler) -{} - -ProxyShapeHierarchyHandler::~ProxyShapeHierarchyHandler() +ProxyShapeHierarchyHandler::ProxyShapeHierarchyHandler( + const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler) + : Ufe::HierarchyHandler() + , fMayaHierarchyHandler(mayaHierarchyHandler) { } +ProxyShapeHierarchyHandler::~ProxyShapeHierarchyHandler() { } + /*static*/ -ProxyShapeHierarchyHandler::Ptr ProxyShapeHierarchyHandler::create(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler) +ProxyShapeHierarchyHandler::Ptr +ProxyShapeHierarchyHandler::create(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler) { - return std::make_shared(mayaHierarchyHandler); + return std::make_shared(mayaHierarchyHandler); } //------------------------------------------------------------------------------ @@ -42,31 +43,28 @@ ProxyShapeHierarchyHandler::Ptr ProxyShapeHierarchyHandler::create(const Ufe::Hi Ufe::Hierarchy::Ptr ProxyShapeHierarchyHandler::hierarchy(const Ufe::SceneItem::Ptr& item) const { - if (isAGatewayType(item->nodeType())) - { - return ProxyShapeHierarchy::create(fMayaHierarchyHandler, item); - } - else - { - return fMayaHierarchyHandler->hierarchy(item); - } + if (isAGatewayType(item->nodeType())) { + return ProxyShapeHierarchy::create(fMayaHierarchyHandler, item); + } else { + return fMayaHierarchyHandler->hierarchy(item); + } } Ufe::SceneItem::Ptr ProxyShapeHierarchyHandler::createItem(const Ufe::Path& path) const { - return fMayaHierarchyHandler->createItem(path); + return fMayaHierarchyHandler->createItem(path); } #ifdef UFE_V2_FEATURES_AVAILABLE #if UFE_PREVIEW_VERSION_NUM >= 2022 Ufe::Hierarchy::ChildFilter ProxyShapeHierarchyHandler::childFilter() const { - Ufe::Hierarchy::ChildFilter childFilters; - childFilters.emplace_back("InactivePrims", "Inactive Prims", true); - return childFilters; + Ufe::Hierarchy::ChildFilter childFilters; + childFilters.emplace_back("InactivePrims", "Inactive Prims", true); + return childFilters; } #endif #endif } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/ProxyShapeHierarchyHandler.h b/lib/mayaUsd/ufe/ProxyShapeHierarchyHandler.h index 6c11b3ff78..ff0799ca32 100644 --- a/lib/mayaUsd/ufe/ProxyShapeHierarchyHandler.h +++ b/lib/mayaUsd/ufe/ProxyShapeHierarchyHandler.h @@ -15,10 +15,10 @@ // #pragma once -#include - #include +#include + namespace MAYAUSD_NS_DEF { namespace ufe { @@ -38,31 +38,32 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC ProxyShapeHierarchyHandler : public Ufe::HierarchyHandler { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - ProxyShapeHierarchyHandler(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler); - ~ProxyShapeHierarchyHandler() override; + ProxyShapeHierarchyHandler(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler); + ~ProxyShapeHierarchyHandler() override; - // Delete the copy/move constructors assignment operators. - ProxyShapeHierarchyHandler(const ProxyShapeHierarchyHandler&) = delete; - ProxyShapeHierarchyHandler& operator=(const ProxyShapeHierarchyHandler&) = delete; - ProxyShapeHierarchyHandler(ProxyShapeHierarchyHandler&&) = delete; - ProxyShapeHierarchyHandler& operator=(ProxyShapeHierarchyHandler&&) = delete; + // Delete the copy/move constructors assignment operators. + ProxyShapeHierarchyHandler(const ProxyShapeHierarchyHandler&) = delete; + ProxyShapeHierarchyHandler& operator=(const ProxyShapeHierarchyHandler&) = delete; + ProxyShapeHierarchyHandler(ProxyShapeHierarchyHandler&&) = delete; + ProxyShapeHierarchyHandler& operator=(ProxyShapeHierarchyHandler&&) = delete; - //! Create a ProxyShapeHierarchyHandler from a UFE hierarchy handler. - static ProxyShapeHierarchyHandler::Ptr create(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler); + //! Create a ProxyShapeHierarchyHandler from a UFE hierarchy handler. + static ProxyShapeHierarchyHandler::Ptr + create(const Ufe::HierarchyHandler::Ptr& mayaHierarchyHandler); - // Ufe::HierarchyHandler overrides - Ufe::Hierarchy::Ptr hierarchy(const Ufe::SceneItem::Ptr& item) const override; - Ufe::SceneItem::Ptr createItem(const Ufe::Path& path) const override; + // Ufe::HierarchyHandler overrides + Ufe::Hierarchy::Ptr hierarchy(const Ufe::SceneItem::Ptr& item) const override; + Ufe::SceneItem::Ptr createItem(const Ufe::Path& path) const override; #if UFE_PREVIEW_VERSION_NUM >= 2022 - UFE_V2(Ufe::Hierarchy::ChildFilter childFilter() const override;) + UFE_V2(Ufe::Hierarchy::ChildFilter childFilter() const override;) #endif private: - Ufe::HierarchyHandler::Ptr fMayaHierarchyHandler; + Ufe::HierarchyHandler::Ptr fMayaHierarchyHandler; }; // ProxyShapeHierarchyHandler } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/StagesSubject.cpp b/lib/mayaUsd/ufe/StagesSubject.cpp index 3aa1a603b7..ffc21a46d3 100644 --- a/lib/mayaUsd/ufe/StagesSubject.cpp +++ b/lib/mayaUsd/ufe/StagesSubject.cpp @@ -15,44 +15,44 @@ // #include "StagesSubject.h" -#include -#include - -#include -#include - -#include -#include +#include "private/UfeNotifGuard.h" +#include #include #include #include -#include -#include "private/UfeNotifGuard.h" +#include +#include +#include +#include #include #include #include #include #include +#include +#include + #ifdef UFE_V2_FEATURES_AVAILABLE +#include #include #include + #include -#include #endif namespace { // Prevent re-entrant stage set. -std::atomic_bool stageSetGuardCount{false}; +std::atomic_bool stageSetGuardCount { false }; #ifdef UFE_V2_FEATURES_AVAILABLE // The attribute change notification guard is not meant to be nested, but // use a counter nonetheless to provide consistent behavior in such cases. -std::atomic_int attributeChangedNotificationGuardCount{0}; +std::atomic_int attributeChangedNotificationGuardCount { 0 }; bool inAttributeChangedNotificationGuard() { @@ -62,7 +62,7 @@ bool inAttributeChangedNotificationGuard() std::unordered_map pendingAttributeChangedNotifications; #endif -} +} // namespace namespace MAYAUSD_NS_DEF { namespace ufe { @@ -71,7 +71,7 @@ namespace ufe { // Global variables & macros //------------------------------------------------------------------------------ extern UsdStageMap g_StageMap; -extern Ufe::Rtid g_USDRtid; +extern Ufe::Rtid g_USDRtid; //------------------------------------------------------------------------------ // StagesSubject @@ -79,308 +79,280 @@ extern Ufe::Rtid g_USDRtid; StagesSubject::StagesSubject() { - // Workaround to MAYA-65920: at startup, MSceneMessage.kAfterNew file - // callback is incorrectly called by Maya before the - // MSceneMessage.kBeforeNew file callback, which should be illegal. - // Detect this and ignore illegal calls to after new file callbacks. - // PPT, 19-Jan-16. - fBeforeNewCallback = false; - - MStatus res; - fCbIds.append(MSceneMessage::addCallback( - MSceneMessage::kBeforeNew, beforeNewCallback, this, &res)); - CHECK_MSTATUS(res); - fCbIds.append(MSceneMessage::addCallback( - MSceneMessage::kBeforeOpen, beforeOpenCallback, this, &res)); - CHECK_MSTATUS(res); - fCbIds.append(MSceneMessage::addCallback( - MSceneMessage::kAfterOpen, afterOpenCallback, this, &res)); - CHECK_MSTATUS(res); - fCbIds.append(MSceneMessage::addCallback( - MSceneMessage::kAfterNew, afterNewCallback, this, &res)); - CHECK_MSTATUS(res); - - TfWeakPtr me(this); - TfNotice::Register(me, &StagesSubject::onStageSet); - TfNotice::Register(me, &StagesSubject::onStageInvalidate); + // Workaround to MAYA-65920: at startup, MSceneMessage.kAfterNew file + // callback is incorrectly called by Maya before the + // MSceneMessage.kBeforeNew file callback, which should be illegal. + // Detect this and ignore illegal calls to after new file callbacks. + // PPT, 19-Jan-16. + fBeforeNewCallback = false; + + MStatus res; + fCbIds.append( + MSceneMessage::addCallback(MSceneMessage::kBeforeNew, beforeNewCallback, this, &res)); + CHECK_MSTATUS(res); + fCbIds.append( + MSceneMessage::addCallback(MSceneMessage::kBeforeOpen, beforeOpenCallback, this, &res)); + CHECK_MSTATUS(res); + fCbIds.append( + MSceneMessage::addCallback(MSceneMessage::kAfterOpen, afterOpenCallback, this, &res)); + CHECK_MSTATUS(res); + fCbIds.append( + MSceneMessage::addCallback(MSceneMessage::kAfterNew, afterNewCallback, this, &res)); + CHECK_MSTATUS(res); + + TfWeakPtr me(this); + TfNotice::Register(me, &StagesSubject::onStageSet); + TfNotice::Register(me, &StagesSubject::onStageInvalidate); } StagesSubject::~StagesSubject() { - MMessage::removeCallbacks(fCbIds); - fCbIds.clear(); + MMessage::removeCallbacks(fCbIds); + fCbIds.clear(); } /*static*/ -StagesSubject::Ptr StagesSubject::create() -{ - return TfCreateWeakPtr(new StagesSubject); -} +StagesSubject::Ptr StagesSubject::create() { return TfCreateWeakPtr(new StagesSubject); } -bool StagesSubject::beforeNewCallback() const -{ - return fBeforeNewCallback; -} +bool StagesSubject::beforeNewCallback() const { return fBeforeNewCallback; } -void StagesSubject::beforeNewCallback(bool b) -{ - fBeforeNewCallback = b; -} +void StagesSubject::beforeNewCallback(bool b) { fBeforeNewCallback = b; } /*static*/ void StagesSubject::beforeNewCallback(void* clientData) { - StagesSubject* ss = static_cast(clientData); - ss->beforeNewCallback(true); + StagesSubject* ss = static_cast(clientData); + ss->beforeNewCallback(true); } /*static*/ void StagesSubject::beforeOpenCallback(void* clientData) { - //StagesSubject* ss = static_cast(clientData); - StagesSubject::beforeNewCallback(clientData); + // StagesSubject* ss = static_cast(clientData); + StagesSubject::beforeNewCallback(clientData); } /*static*/ void StagesSubject::afterNewCallback(void* clientData) { - StagesSubject* ss = static_cast(clientData); + StagesSubject* ss = static_cast(clientData); - // Workaround to MAYA-65920: detect and avoid illegal callback sequence. - if (!ss->beforeNewCallback()) - return; + // Workaround to MAYA-65920: detect and avoid illegal callback sequence. + if (!ss->beforeNewCallback()) + return; - ss->beforeNewCallback(false); - StagesSubject::afterOpenCallback(clientData); + ss->beforeNewCallback(false); + StagesSubject::afterOpenCallback(clientData); } /*static*/ void StagesSubject::afterOpenCallback(void* clientData) { - StagesSubject* ss = static_cast(clientData); - ss->afterOpen(); + StagesSubject* ss = static_cast(clientData); + ss->afterOpen(); } void StagesSubject::afterOpen() { - // Observe stage changes, for all stages. Return listener object can - // optionally be used to call Revoke() to remove observation, but must - // keep reference to it, otherwise its reference count is immediately - // decremented, falls to zero, and no observation occurs. - - // Ideally, we would observe the data model only if there are observers, - // to minimize cost of observation. However, since observation is - // frequent, we won't implement this for now. PPT, 22-Dec-2017. - std::for_each(std::begin(fStageListeners), std::end(fStageListeners), - [](StageListenerMap::value_type element) { TfNotice::Revoke(element.second); } ); - fStageListeners.clear(); - - // Set up our stage to proxy shape UFE path (and reverse) - // mapping. We do this with the following steps: - // - get all proxyShape nodes in the scene. - // - get their Dag paths. - // - convert the Dag paths to UFE paths. - // - get their stage. - g_StageMap.setDirty(); + // Observe stage changes, for all stages. Return listener object can + // optionally be used to call Revoke() to remove observation, but must + // keep reference to it, otherwise its reference count is immediately + // decremented, falls to zero, and no observation occurs. + + // Ideally, we would observe the data model only if there are observers, + // to minimize cost of observation. However, since observation is + // frequent, we won't implement this for now. PPT, 22-Dec-2017. + std::for_each( + std::begin(fStageListeners), + std::end(fStageListeners), + [](StageListenerMap::value_type element) { TfNotice::Revoke(element.second); }); + fStageListeners.clear(); + + // Set up our stage to proxy shape UFE path (and reverse) + // mapping. We do this with the following steps: + // - get all proxyShape nodes in the scene. + // - get their Dag paths. + // - convert the Dag paths to UFE paths. + // - get their stage. + g_StageMap.setDirty(); } -void StagesSubject::stageChanged(UsdNotice::ObjectsChanged const& notice, UsdStageWeakPtr const& sender) +void StagesSubject::stageChanged( + UsdNotice::ObjectsChanged const& notice, + UsdStageWeakPtr const& sender) { - // If the stage path has not been initialized yet, do nothing - if (stagePath(sender).empty()) - return; - - auto stage = notice.GetStage(); - for (const auto& changedPath : notice.GetResyncedPaths()) - { - // When visibility is toggled for the first time or you add a xformop we enter - // here with a resync path. However the changedPath is not a prim path, so we - // don't care about it. In those cases, the changePath will contain something like: - // "/.visibility" - // "/.xformOp:translate" - if (changedPath.IsPropertyPath()) - continue; - - // Assume proxy shapes (and thus stages) cannot be instanced. We can - // therefore map the stage to a single UFE path. Lifting this - // restriction would mean sending one add or delete notification for - // each Maya Dag path instancing the proxy shape / stage. - Ufe::Path ufePath; - UsdPrim prim; - if (changedPath == SdfPath::AbsoluteRootPath()) - { - ufePath = stagePath(sender); - prim = stage->GetPseudoRoot(); - } - else - { - const std::string& usdPrimPathStr = changedPath.GetPrimPath().GetString(); - ufePath = stagePath(sender) + Ufe::PathSegment(usdPrimPathStr, g_USDRtid, '/'); - prim = stage->GetPrimAtPath(changedPath); - } - - if (prim.IsValid() && !InPathChange::inPathChange()) - { - auto sceneItem = Ufe::Hierarchy::createItem(ufePath); - - // AL LayerCommands.addSubLayer test will cause Maya to crash - // if we don't filter invalid sceneItems. This patch is provided - // to prevent crashes, but more investigation will have to be - // done to understand why ufePath in case of sub layer - // creation causes Ufe::Hierarchy::createItem to fail. - if (!sceneItem) - continue; - - // Special case when we know the operation came from either - // the add or delete of our UFE/USD implementation. - if (InAddOrDeleteOperation::inAddOrDeleteOperation()) - { - if (prim.IsActive()) - { - #ifdef UFE_V2_FEATURES_AVAILABLE - Ufe::Scene::instance().notify(Ufe::ObjectAdd(sceneItem)); - #else - auto notification = Ufe::ObjectAdd(sceneItem); - Ufe::Scene::notifyObjectAdd(notification); - #endif - } - else - { - #ifdef UFE_V2_FEATURES_AVAILABLE - Ufe::Scene::instance().notify(Ufe::ObjectPostDelete(sceneItem)); - #else - auto notification = Ufe::ObjectPostDelete(sceneItem); - Ufe::Scene::notifyObjectDelete(notification); - #endif - } - } + // If the stage path has not been initialized yet, do nothing + if (stagePath(sender).empty()) + return; + + auto stage = notice.GetStage(); + for (const auto& changedPath : notice.GetResyncedPaths()) { + // When visibility is toggled for the first time or you add a xformop we enter + // here with a resync path. However the changedPath is not a prim path, so we + // don't care about it. In those cases, the changePath will contain something like: + // "/.visibility" + // "/.xformOp:translate" + if (changedPath.IsPropertyPath()) + continue; + + // Assume proxy shapes (and thus stages) cannot be instanced. We can + // therefore map the stage to a single UFE path. Lifting this + // restriction would mean sending one add or delete notification for + // each Maya Dag path instancing the proxy shape / stage. + Ufe::Path ufePath; + UsdPrim prim; + if (changedPath == SdfPath::AbsoluteRootPath()) { + ufePath = stagePath(sender); + prim = stage->GetPseudoRoot(); + } else { + const std::string& usdPrimPathStr = changedPath.GetPrimPath().GetString(); + ufePath = stagePath(sender) + Ufe::PathSegment(usdPrimPathStr, g_USDRtid, '/'); + prim = stage->GetPrimAtPath(changedPath); + } + + if (prim.IsValid() && !InPathChange::inPathChange()) { + auto sceneItem = Ufe::Hierarchy::createItem(ufePath); + + // AL LayerCommands.addSubLayer test will cause Maya to crash + // if we don't filter invalid sceneItems. This patch is provided + // to prevent crashes, but more investigation will have to be + // done to understand why ufePath in case of sub layer + // creation causes Ufe::Hierarchy::createItem to fail. + if (!sceneItem) + continue; + + // Special case when we know the operation came from either + // the add or delete of our UFE/USD implementation. + if (InAddOrDeleteOperation::inAddOrDeleteOperation()) { + if (prim.IsActive()) { +#ifdef UFE_V2_FEATURES_AVAILABLE + Ufe::Scene::instance().notify(Ufe::ObjectAdd(sceneItem)); +#else + auto notification = Ufe::ObjectAdd(sceneItem); + Ufe::Scene::notifyObjectAdd(notification); +#endif + } else { +#ifdef UFE_V2_FEATURES_AVAILABLE + Ufe::Scene::instance().notify(Ufe::ObjectPostDelete(sceneItem)); +#else + auto notification = Ufe::ObjectPostDelete(sceneItem); + Ufe::Scene::notifyObjectDelete(notification); +#endif + } + } #ifdef UFE_V2_FEATURES_AVAILABLE - else - { - // According to USD docs for GetResyncedPaths(): - // - Resyncs imply entire subtree invalidation of all descendant prims and properties. - // So we send the UFE subtree invalidate notif. - Ufe::Scene::instance().notify(Ufe::SubtreeInvalidate(sceneItem)); - } + else { + // According to USD docs for GetResyncedPaths(): + // - Resyncs imply entire subtree invalidation of all descendant prims and + // properties. So we send the UFE subtree invalidate notif. + Ufe::Scene::instance().notify(Ufe::SubtreeInvalidate(sceneItem)); + } #endif - } + } #ifdef UFE_V2_FEATURES_AVAILABLE - else if (!prim.IsValid() && !InPathChange::inPathChange()) - { - Ufe::SceneItem::Ptr sceneItem = Ufe::Hierarchy::createItem(ufePath); - if (!sceneItem || InAddOrDeleteOperation::inAddOrDeleteOperation()) - { - Ufe::Scene::instance().notify(Ufe::ObjectDestroyed(ufePath)); - } - else - { - Ufe::Scene::instance().notify(Ufe::SubtreeInvalidate(sceneItem)); - } - } + else if (!prim.IsValid() && !InPathChange::inPathChange()) { + Ufe::SceneItem::Ptr sceneItem = Ufe::Hierarchy::createItem(ufePath); + if (!sceneItem || InAddOrDeleteOperation::inAddOrDeleteOperation()) { + Ufe::Scene::instance().notify(Ufe::ObjectDestroyed(ufePath)); + } else { + Ufe::Scene::instance().notify(Ufe::SubtreeInvalidate(sceneItem)); + } + } #endif - } + } - for (const auto& changedPath : notice.GetChangedInfoOnlyPaths()) - { - auto usdPrimPathStr = changedPath.GetPrimPath().GetString(); - auto ufePath = stagePath(sender) + Ufe::PathSegment(usdPrimPathStr, g_USDRtid, '/'); + for (const auto& changedPath : notice.GetChangedInfoOnlyPaths()) { + auto usdPrimPathStr = changedPath.GetPrimPath().GetString(); + auto ufePath = stagePath(sender) + Ufe::PathSegment(usdPrimPathStr, g_USDRtid, '/'); #ifdef UFE_V2_FEATURES_AVAILABLE - // isPrimPropertyPath() does not consider relational attributes - // isPropertyPath() does consider relational attributes - // isRelationalAttributePath() considers only relational attributes - if (changedPath.IsPrimPropertyPath()) { - if (inAttributeChangedNotificationGuard()) { - pendingAttributeChangedNotifications[ufePath] = - changedPath.GetName(); - } - else { - Ufe::Attributes::notify(ufePath, changedPath.GetName()); - } - } - - // Send a special message when visibility has changed. - if (changedPath.GetNameToken() == UsdGeomTokens->visibility) - { - Ufe::VisibilityChanged vis(ufePath); - Ufe::Object3d::notify(vis); - } + // isPrimPropertyPath() does not consider relational attributes + // isPropertyPath() does consider relational attributes + // isRelationalAttributePath() considers only relational attributes + if (changedPath.IsPrimPropertyPath()) { + if (inAttributeChangedNotificationGuard()) { + pendingAttributeChangedNotifications[ufePath] = changedPath.GetName(); + } else { + Ufe::Attributes::notify(ufePath, changedPath.GetName()); + } + } + + // Send a special message when visibility has changed. + if (changedPath.GetNameToken() == UsdGeomTokens->visibility) { + Ufe::VisibilityChanged vis(ufePath); + Ufe::Object3d::notify(vis); + } #endif - // We need to determine if the change is a Transform3d change. - // We must at least pick up xformOp:translate, xformOp:rotateXYZ, - // and xformOp:scale. - const TfToken nameToken = changedPath.GetNameToken(); - if(nameToken == UsdGeomTokens->xformOpOrder || UsdGeomXformOp::IsXformOp(nameToken)) - { - Ufe::Transform3d::notify(ufePath); - } - } + // We need to determine if the change is a Transform3d change. + // We must at least pick up xformOp:translate, xformOp:rotateXYZ, + // and xformOp:scale. + const TfToken nameToken = changedPath.GetNameToken(); + if (nameToken == UsdGeomTokens->xformOpOrder || UsdGeomXformOp::IsXformOp(nameToken)) { + Ufe::Transform3d::notify(ufePath); + } + } } void StagesSubject::onStageSet(const MayaUsdProxyStageSetNotice& notice) { - // Handle re-entrant onStageSet - bool expectedState = false; - if (stageSetGuardCount.compare_exchange_strong(expectedState,true)) - { - // We should have no listeners and stage map is dirty. - TF_VERIFY(g_StageMap.isDirty()); - TF_VERIFY(fStageListeners.empty()); - - StagesSubject::Ptr me(this); - for (auto stage : ProxyShapeHandler::getAllStages()) - { - fStageListeners[stage] = TfNotice::Register( - me, &StagesSubject::stageChanged, stage); - } - stageSetGuardCount = false; - } + // Handle re-entrant onStageSet + bool expectedState = false; + if (stageSetGuardCount.compare_exchange_strong(expectedState, true)) { + // We should have no listeners and stage map is dirty. + TF_VERIFY(g_StageMap.isDirty()); + TF_VERIFY(fStageListeners.empty()); + + StagesSubject::Ptr me(this); + for (auto stage : ProxyShapeHandler::getAllStages()) { + fStageListeners[stage] = TfNotice::Register(me, &StagesSubject::stageChanged, stage); + } + stageSetGuardCount = false; + } } void StagesSubject::onStageInvalidate(const MayaUsdProxyStageInvalidateNotice& notice) { - afterOpen(); + afterOpen(); #ifdef UFE_V2_FEATURES_AVAILABLE - Ufe::SceneItem::Ptr sceneItem = Ufe::Hierarchy::createItem(notice.GetProxyShape().ufePath()); - Ufe::Scene::instance().notify(Ufe::SubtreeInvalidate(sceneItem)); + Ufe::SceneItem::Ptr sceneItem = Ufe::Hierarchy::createItem(notice.GetProxyShape().ufePath()); + Ufe::Scene::instance().notify(Ufe::SubtreeInvalidate(sceneItem)); #endif } #ifdef UFE_V2_FEATURES_AVAILABLE AttributeChangedNotificationGuard::AttributeChangedNotificationGuard() { - if (inAttributeChangedNotificationGuard()) { - TF_CODING_ERROR("Attribute changed notification guard cannot be nested."); - } - - if (attributeChangedNotificationGuardCount.load() == 0 && - !pendingAttributeChangedNotifications.empty()) { - TF_CODING_ERROR("Stale pending attribute changed notifications."); - } + if (inAttributeChangedNotificationGuard()) { + TF_CODING_ERROR("Attribute changed notification guard cannot be nested."); + } - ++attributeChangedNotificationGuardCount; + if (attributeChangedNotificationGuardCount.load() == 0 + && !pendingAttributeChangedNotifications.empty()) { + TF_CODING_ERROR("Stale pending attribute changed notifications."); + } + ++attributeChangedNotificationGuardCount; } AttributeChangedNotificationGuard::~AttributeChangedNotificationGuard() { - if (--attributeChangedNotificationGuardCount < 0) { - TF_CODING_ERROR("Corrupt attribute changed notification guard."); - } + if (--attributeChangedNotificationGuardCount < 0) { + TF_CODING_ERROR("Corrupt attribute changed notification guard."); + } - if (attributeChangedNotificationGuardCount.load() > 0 ) { - return; - } + if (attributeChangedNotificationGuardCount.load() > 0) { + return; + } - for (const auto& notificationInfo : pendingAttributeChangedNotifications) { - Ufe::Attributes::notify(notificationInfo.first, notificationInfo.second); - } + for (const auto& notificationInfo : pendingAttributeChangedNotifications) { + Ufe::Attributes::notify(notificationInfo.first, notificationInfo.second); + } - pendingAttributeChangedNotifications.clear(); + pendingAttributeChangedNotifications.clear(); } #endif } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/StagesSubject.h b/lib/mayaUsd/ufe/StagesSubject.h index 2770af70b0..644c2e013f 100644 --- a/lib/mayaUsd/ufe/StagesSubject.h +++ b/lib/mayaUsd/ufe/StagesSubject.h @@ -15,18 +15,17 @@ // #pragma once -#include - -#include // For UFE_V2_FEATURES_AVAILABLE +#include +#include -#include -#include #include #include +#include #include +#include -#include -#include +#include +#include // For UFE_V2_FEATURES_AVAILABLE PXR_NAMESPACE_USING_DIRECTIVE @@ -35,85 +34,86 @@ namespace ufe { //! \brief Subject class to observe Maya scene. /*! - This class observes Maya file open, to register a USD observer on each - stage the Maya scene contains. This USD observer translates USD - notifications into UFE notifications. + This class observes Maya file open, to register a USD observer on each + stage the Maya scene contains. This USD observer translates USD + notifications into UFE notifications. */ class MAYAUSD_CORE_PUBLIC StagesSubject : public TfWeakBase { public: - typedef TfWeakPtr Ptr; + typedef TfWeakPtr Ptr; - //! Constructor - StagesSubject(); + //! Constructor + StagesSubject(); - //! Destructor - ~StagesSubject(); + //! Destructor + ~StagesSubject(); - //! Create the StagesSubject. - static StagesSubject::Ptr create(); + //! Create the StagesSubject. + static StagesSubject::Ptr create(); - // Delete the copy/move constructors assignment operators. - StagesSubject(const StagesSubject&) = delete; - StagesSubject& operator=(const StagesSubject&) = delete; - StagesSubject(StagesSubject&&) = delete; - StagesSubject& operator=(StagesSubject&&) = delete; + // Delete the copy/move constructors assignment operators. + StagesSubject(const StagesSubject&) = delete; + StagesSubject& operator=(const StagesSubject&) = delete; + StagesSubject(StagesSubject&&) = delete; + StagesSubject& operator=(StagesSubject&&) = delete; - bool beforeNewCallback() const; - void beforeNewCallback(bool b); + bool beforeNewCallback() const; + void beforeNewCallback(bool b); - void afterOpen(); + void afterOpen(); private: - // Maya scene message callbacks - static void beforeNewCallback(void* clientData); - static void beforeOpenCallback(void* clientData); - static void afterNewCallback(void* clientData); - static void afterOpenCallback(void* clientData); + // Maya scene message callbacks + static void beforeNewCallback(void* clientData); + static void beforeOpenCallback(void* clientData); + static void afterNewCallback(void* clientData); + static void afterOpenCallback(void* clientData); - //! Call the stageChanged() methods on stage observers. - void stageChanged(UsdNotice::ObjectsChanged const& notice, UsdStageWeakPtr const& sender); + //! Call the stageChanged() methods on stage observers. + void stageChanged(UsdNotice::ObjectsChanged const& notice, UsdStageWeakPtr const& sender); private: - // Notice listener method for proxy stage set - void onStageSet(const MayaUsdProxyStageSetNotice& notice); + // Notice listener method for proxy stage set + void onStageSet(const MayaUsdProxyStageSetNotice& notice); - // Notice listener method for proxy stage invalidate. - void onStageInvalidate(const MayaUsdProxyStageInvalidateNotice& notice); + // Notice listener method for proxy stage invalidate. + void onStageInvalidate(const MayaUsdProxyStageInvalidateNotice& notice); - // Map of per-stage listeners, indexed by stage. - typedef TfHashMap StageListenerMap; - StageListenerMap fStageListeners; + // Map of per-stage listeners, indexed by stage. + typedef TfHashMap StageListenerMap; + StageListenerMap fStageListeners; - bool fBeforeNewCallback = false; + bool fBeforeNewCallback = false; - MCallbackIdArray fCbIds; + MCallbackIdArray fCbIds; }; // StagesSubject #ifdef UFE_V2_FEATURES_AVAILABLE //! \brief Guard to delay attribute changed notifications. /*! - Instantiating an object of this class allows the attribute changed - notifications to be delayed until the guard expires. + Instantiating an object of this class allows the attribute changed + notifications to be delayed until the guard expires. The guard collapses down notifications for a given UFE path, which is - desirable to avoid duplicate notifications. However, it is an error to - have notifications for more than one attribute within a single guard. + desirable to avoid duplicate notifications. However, it is an error to + have notifications for more than one attribute within a single guard. */ -class MAYAUSD_CORE_PUBLIC AttributeChangedNotificationGuard { +class MAYAUSD_CORE_PUBLIC AttributeChangedNotificationGuard +{ public: - AttributeChangedNotificationGuard(); ~AttributeChangedNotificationGuard(); //@{ //! Cannot be copied or assigned. AttributeChangedNotificationGuard(const AttributeChangedNotificationGuard&) = delete; - const AttributeChangedNotificationGuard& operator&(const AttributeChangedNotificationGuard&) = delete; + const AttributeChangedNotificationGuard& operator&(const AttributeChangedNotificationGuard&) + = delete; //@} }; #endif } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdAttribute.cpp b/lib/mayaUsd/ufe/UsdAttribute.cpp index 5b3731e587..5e480512d3 100644 --- a/lib/mayaUsd/ufe/UsdAttribute.cpp +++ b/lib/mayaUsd/ufe/UsdAttribute.cpp @@ -15,42 +15,42 @@ // #include "UsdAttribute.h" -#include -#include -#include - #include #include #include #include +#include +#include +#include + // We unconditionally want the UFE asserts here (even in release builds). // The UFE_ASSERT_MSG has a built-in throw which we want to use for error handling. #define UFE_ENABLE_ASSERTS -#include - #include #include +#include + // Note: normally we would use this using directive, but here we cannot because // our class is called UsdAttribute which is exactly the same as the one // in USD. // PXR_NAMESPACE_USING_DIRECTIVE static constexpr char kErrorMsgFailedSet[] = "Failed to set USD attribute with new value"; -static constexpr char kErrorMsgFailedConvertToString[] = "Could not convert the attribute to a string"; -static constexpr char kErrorMsgInvalidType[] = "USD attribute does not match created attribute class type"; +static constexpr char kErrorMsgFailedConvertToString[] + = "Could not convert the attribute to a string"; +static constexpr char kErrorMsgInvalidType[] + = "USD attribute does not match created attribute class type"; static constexpr char kErrorMsgEnumNoValue[] = "Enum string attribute has no value"; //------------------------------------------------------------------------------ // Helper functions //------------------------------------------------------------------------------ -namespace -{ +namespace { -template -bool setUsdAttr(const PXR_NS::UsdAttribute& attr, const T& value) +template bool setUsdAttr(const PXR_NS::UsdAttribute& attr, const T& value) { // USD Attribute Notification doubling problem: // As of 24-Nov-2019, calling Set() on a UsdAttribute causes two "info only" @@ -63,11 +63,11 @@ bool setUsdAttr(const PXR_NS::UsdAttribute& attr, const T& value) // expiry causes a notification to be sent. // These two calls appear to be made on all calls to UsdAttribute::Set(), // not just on the first call. - // + // // Trying to wrap the call to UsdAttribute::Set() inside an additional // SdfChangeBlock fails: no notifications are sent at all. This is most // likely because of the warning given in the SdfChangeBlock documentation: - // + // // https://graphics.pixar.com/usd/docs/api/class_sdf_change_block.html // // which stages that "it is not safe to use [...] [a] downstream API [such @@ -75,66 +75,69 @@ bool setUsdAttr(const PXR_NS::UsdAttribute& attr, const T& value) // // Therefore, we have implemented an attribute change block notification of // our own in the StagesSubject, which we invoke here, so that only a - // single UFE attribute changed notification is generated. + // single UFE attribute changed notification is generated. MayaUsd::ufe::AttributeChangedNotificationGuard guard; - return attr.Set(value); + return attr.Set(value); } PXR_NS::UsdTimeCode getCurrentTime(const Ufe::SceneItem::Ptr& item) { - // Attributes with time samples will fail when calling Get with default time code. - // So we'll always use the current time when calling Get. If there are no time - // samples, it will fall-back to the default time code. - return MayaUsd::ufe::getTime(item->path()); + // Attributes with time samples will fail when calling Get with default time code. + // So we'll always use the current time when calling Get. If there are no time + // samples, it will fall-back to the default time code. + return MayaUsd::ufe::getTime(item->path()); } -std::string getUsdAttributeValueAsString(const PXR_NS::UsdAttribute& attr, const PXR_NS::UsdTimeCode& time) +std::string +getUsdAttributeValueAsString(const PXR_NS::UsdAttribute& attr, const PXR_NS::UsdTimeCode& time) { - if (!attr.HasValue()) return std::string(); + if (!attr.HasValue()) + return std::string(); - PXR_NS::VtValue v; - if (attr.Get(&v, time)) - { - if (v.CanCast()) - { - PXR_NS::VtValue v_str = v.Cast(); - return v_str.Get(); - } + PXR_NS::VtValue v; + if (attr.Get(&v, time)) { + if (v.CanCast()) { + PXR_NS::VtValue v_str = v.Cast(); + return v_str.Get(); + } - std::ostringstream os; - os << v; - return os.str(); - } + std::ostringstream os; + os << v; + return os.str(); + } - UFE_ASSERT_MSG(false, kErrorMsgFailedConvertToString); - return std::string(); + UFE_ASSERT_MSG(false, kErrorMsgFailedConvertToString); + return std::string(); } -template +template U getUsdAttributeVectorAsUfe(const PXR_NS::UsdAttribute& attr, const PXR_NS::UsdTimeCode& time) { - if (!attr.HasValue()) return U(); + if (!attr.HasValue()) + return U(); - PXR_NS::VtValue vt; - if (attr.Get(&vt, time) && vt.IsHolding()) - { - T gfVec = vt.UncheckedGet(); - U ret(gfVec[0], gfVec[1], gfVec[2]); - return ret; - } + PXR_NS::VtValue vt; + if (attr.Get(&vt, time) && vt.IsHolding()) { + T gfVec = vt.UncheckedGet(); + U ret(gfVec[0], gfVec[1], gfVec[2]); + return ret; + } - UFE_ASSERT_MSG(false, kErrorMsgInvalidType); - return U(); + UFE_ASSERT_MSG(false, kErrorMsgInvalidType); + return U(); } -template -void setUsdAttributeVectorFromUfe(PXR_NS::UsdAttribute& attr, const U& value, const PXR_NS::UsdTimeCode& time) +template +void setUsdAttributeVectorFromUfe( + PXR_NS::UsdAttribute& attr, + const U& value, + const PXR_NS::UsdTimeCode& time) { - T vec; - UFE_ASSERT_MSG(attr.Get(&vec, time), kErrorMsgInvalidType); - vec.Set(value.x(), value.y(), value.z()); - bool b = setUsdAttr(attr, vec); - UFE_ASSERT_MSG(b, kErrorMsgFailedSet); + T vec; + UFE_ASSERT_MSG(attr.Get(&vec, time), kErrorMsgInvalidType); + vec.Set(value.x(), value.y(), value.z()); + bool b = setUsdAttr(attr, vec); + UFE_ASSERT_MSG(b, kErrorMsgFailedSet); } } // end namespace @@ -147,51 +150,46 @@ namespace ufe { //------------------------------------------------------------------------------ UsdAttribute::UsdAttribute(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) - : fUsdAttr(usdAttr) + : fUsdAttr(usdAttr) { - fPrim = item->prim(); + fPrim = item->prim(); } -UsdAttribute::~UsdAttribute() -{ -} +UsdAttribute::~UsdAttribute() { } -bool UsdAttribute::hasValue() const -{ - return fUsdAttr.HasValue(); -} +bool UsdAttribute::hasValue() const { return fUsdAttr.HasValue(); } std::string UsdAttribute::name() const { - // Should be the same as the name we were created with. - return fUsdAttr.GetName().GetString(); + // Should be the same as the name we were created with. + return fUsdAttr.GetName().GetString(); } -std::string UsdAttribute::documentation() const -{ - return fUsdAttr.GetDocumentation(); -} +std::string UsdAttribute::documentation() const { return fUsdAttr.GetDocumentation(); } std::string UsdAttribute::string(const Ufe::SceneItem::Ptr& item) const { - return getUsdAttributeValueAsString(fUsdAttr, getCurrentTime(item)); + return getUsdAttributeValueAsString(fUsdAttr, getCurrentTime(item)); } //------------------------------------------------------------------------------ // UsdAttributeGeneric: //------------------------------------------------------------------------------ -UsdAttributeGeneric::UsdAttributeGeneric(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) - : Ufe::AttributeGeneric(item) - , UsdAttribute(item, usdAttr) +UsdAttributeGeneric::UsdAttributeGeneric( + const UsdSceneItem::Ptr& item, + const PXR_NS::UsdAttribute& usdAttr) + : Ufe::AttributeGeneric(item) + , UsdAttribute(item, usdAttr) { } /*static*/ -UsdAttributeGeneric::Ptr UsdAttributeGeneric::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) +UsdAttributeGeneric::Ptr +UsdAttributeGeneric::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { - auto attr = std::make_shared(item, usdAttr); - return attr; + auto attr = std::make_shared(item, usdAttr); + return attr; } //------------------------------------------------------------------------------ @@ -200,24 +198,27 @@ UsdAttributeGeneric::Ptr UsdAttributeGeneric::create(const UsdSceneItem::Ptr& it std::string UsdAttributeGeneric::nativeType() const { - return fUsdAttr.GetTypeName().GetType().GetTypeName(); + return fUsdAttr.GetTypeName().GetType().GetTypeName(); } //------------------------------------------------------------------------------ // UsdAttributeEnumString: //------------------------------------------------------------------------------ -UsdAttributeEnumString::UsdAttributeEnumString(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) - : Ufe::AttributeEnumString(item) - , UsdAttribute(item, usdAttr) +UsdAttributeEnumString::UsdAttributeEnumString( + const UsdSceneItem::Ptr& item, + const PXR_NS::UsdAttribute& usdAttr) + : Ufe::AttributeEnumString(item) + , UsdAttribute(item, usdAttr) { } /*static*/ -UsdAttributeEnumString::Ptr UsdAttributeEnumString::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) +UsdAttributeEnumString::Ptr +UsdAttributeEnumString::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { - auto attr = std::make_shared(item, usdAttr); - return attr; + auto attr = std::make_shared(item, usdAttr); + return attr; } //------------------------------------------------------------------------------ @@ -226,54 +227,55 @@ UsdAttributeEnumString::Ptr UsdAttributeEnumString::create(const UsdSceneItem::P std::string UsdAttributeEnumString::get() const { - UFE_ASSERT_MSG(hasValue(), kErrorMsgEnumNoValue); - PXR_NS::VtValue vt; - if (fUsdAttr.Get(&vt, getCurrentTime(sceneItem())) && vt.IsHolding()) - { - TfToken tok = vt.UncheckedGet(); - return tok.GetString(); - } + UFE_ASSERT_MSG(hasValue(), kErrorMsgEnumNoValue); + PXR_NS::VtValue vt; + if (fUsdAttr.Get(&vt, getCurrentTime(sceneItem())) && vt.IsHolding()) { + TfToken tok = vt.UncheckedGet(); + return tok.GetString(); + } - UFE_ASSERT_MSG(false, kErrorMsgInvalidType); - return std::string(); + UFE_ASSERT_MSG(false, kErrorMsgInvalidType); + return std::string(); } void UsdAttributeEnumString::set(const std::string& value) { - PXR_NS::TfToken dummy; - UFE_ASSERT_MSG(fUsdAttr.Get(&dummy, getCurrentTime(sceneItem())), kErrorMsgInvalidType); - PXR_NS::TfToken tok(value); - bool b = setUsdAttr(fUsdAttr, tok); - UFE_ASSERT_MSG(b, kErrorMsgFailedSet); + PXR_NS::TfToken dummy; + UFE_ASSERT_MSG( + fUsdAttr.Get(&dummy, getCurrentTime(sceneItem())), kErrorMsgInvalidType); + PXR_NS::TfToken tok(value); + bool b = setUsdAttr(fUsdAttr, tok); + UFE_ASSERT_MSG(b, kErrorMsgFailedSet); } Ufe::AttributeEnumString::EnumValues UsdAttributeEnumString::getEnumValues() const { - PXR_NS::TfToken tk(name()); + PXR_NS::TfToken tk(name()); #if USD_VERSION_NUM > 2002 - auto attrDefn = fPrim.GetPrimDefinition().GetSchemaAttributeSpec(tk); + auto attrDefn = fPrim.GetPrimDefinition().GetSchemaAttributeSpec(tk); #else - auto attrDefn = PXR_NS::UsdSchemaRegistry::GetAttributeDefinition(fPrim.GetTypeName(), tk); + auto attrDefn = PXR_NS::UsdSchemaRegistry::GetAttributeDefinition(fPrim.GetTypeName(), tk); #endif - if (attrDefn && attrDefn->HasAllowedTokens()) - { - auto tokenArray = attrDefn->GetAllowedTokens(); - std::vector tokenVec(tokenArray.begin(), tokenArray.end()); - EnumValues tokens = PXR_NS::TfToStringVector(tokenVec); - return tokens; - } + if (attrDefn && attrDefn->HasAllowedTokens()) { + auto tokenArray = attrDefn->GetAllowedTokens(); + std::vector tokenVec(tokenArray.begin(), tokenArray.end()); + EnumValues tokens = PXR_NS::TfToStringVector(tokenVec); + return tokens; + } - return EnumValues(); + return EnumValues(); } //------------------------------------------------------------------------------ // TypedUsdAttribute: //------------------------------------------------------------------------------ -template -TypedUsdAttribute::TypedUsdAttribute(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) - : Ufe::TypedAttribute(item) - , UsdAttribute(item, usdAttr) +template +TypedUsdAttribute::TypedUsdAttribute( + const UsdSceneItem::Ptr& item, + const PXR_NS::UsdAttribute& usdAttr) + : Ufe::TypedAttribute(item) + , UsdAttribute(item, usdAttr) { } @@ -281,132 +283,124 @@ TypedUsdAttribute::TypedUsdAttribute(const UsdSceneItem::Ptr& item, const PXR // TypedUsdAttribute - Ufe::TypedAttribute overrides //------------------------------------------------------------------------------ -template<> -std::string TypedUsdAttribute::get() const +template <> std::string TypedUsdAttribute::get() const { - if (!hasValue()) return std::string(); + if (!hasValue()) + return std::string(); - PXR_NS::VtValue vt; - if (fUsdAttr.Get(&vt, getCurrentTime(sceneItem()))) - { - // The USDAttribute can be holding either TfToken or string. - if (vt.IsHolding()) - { - TfToken tok = vt.UncheckedGet(); - return tok.GetString(); - } - else if (vt.IsHolding()) - { - return vt.UncheckedGet(); - } - } + PXR_NS::VtValue vt; + if (fUsdAttr.Get(&vt, getCurrentTime(sceneItem()))) { + // The USDAttribute can be holding either TfToken or string. + if (vt.IsHolding()) { + TfToken tok = vt.UncheckedGet(); + return tok.GetString(); + } else if (vt.IsHolding()) { + return vt.UncheckedGet(); + } + } - UFE_ASSERT_MSG(false, kErrorMsgInvalidType); - return std::string(); + UFE_ASSERT_MSG(false, kErrorMsgInvalidType); + return std::string(); } -template <> -void TypedUsdAttribute::set(const std::string& value) +template <> void TypedUsdAttribute::set(const std::string& value) { - // We need to figure out if the USDAttribute is holding a TfToken or string. - const PXR_NS::SdfValueTypeName typeName = fUsdAttr.GetTypeName(); - if (typeName.GetHash() == SdfValueTypeNames->String.GetHash()) - { - std::string dummy; - UFE_ASSERT_MSG(fUsdAttr.Get(&dummy, getCurrentTime(sceneItem())), kErrorMsgInvalidType); - bool b = setUsdAttr(fUsdAttr, value); - UFE_ASSERT_MSG(b, kErrorMsgFailedSet); - return; - } - else if (typeName.GetHash() == SdfValueTypeNames->Token.GetHash()) - { - PXR_NS::TfToken dummy; - UFE_ASSERT_MSG(fUsdAttr.Get(&dummy, getCurrentTime(sceneItem())), kErrorMsgInvalidType); - PXR_NS::TfToken tok(value); - bool b = setUsdAttr(fUsdAttr, tok); - UFE_ASSERT_MSG(b, kErrorMsgFailedSet); - return; - } + // We need to figure out if the USDAttribute is holding a TfToken or string. + const PXR_NS::SdfValueTypeName typeName = fUsdAttr.GetTypeName(); + if (typeName.GetHash() == SdfValueTypeNames->String.GetHash()) { + std::string dummy; + UFE_ASSERT_MSG( + fUsdAttr.Get(&dummy, getCurrentTime(sceneItem())), kErrorMsgInvalidType); + bool b = setUsdAttr(fUsdAttr, value); + UFE_ASSERT_MSG(b, kErrorMsgFailedSet); + return; + } else if (typeName.GetHash() == SdfValueTypeNames->Token.GetHash()) { + PXR_NS::TfToken dummy; + UFE_ASSERT_MSG( + fUsdAttr.Get(&dummy, getCurrentTime(sceneItem())), + kErrorMsgInvalidType); + PXR_NS::TfToken tok(value); + bool b = setUsdAttr(fUsdAttr, tok); + UFE_ASSERT_MSG(b, kErrorMsgFailedSet); + return; + } - // If we get here it means the USDAttribute type wasn't TfToken or string. - UFE_ASSERT_MSG(false, kErrorMsgInvalidType); + // If we get here it means the USDAttribute type wasn't TfToken or string. + UFE_ASSERT_MSG(false, kErrorMsgInvalidType); } -template<> -Ufe::Color3f TypedUsdAttribute::get() const +template <> Ufe::Color3f TypedUsdAttribute::get() const { - return getUsdAttributeVectorAsUfe(fUsdAttr, getCurrentTime(sceneItem())); + return getUsdAttributeVectorAsUfe(fUsdAttr, getCurrentTime(sceneItem())); } // Note: cannot use setUsdAttributeVectorFromUfe since it relies on x/y/z -template<> -void TypedUsdAttribute::set(const Ufe::Color3f& value) +template <> void TypedUsdAttribute::set(const Ufe::Color3f& value) { - GfVec3f vec; - UFE_ASSERT_MSG(fUsdAttr.Get(&vec, getCurrentTime(sceneItem())), kErrorMsgInvalidType); - vec.Set(value.r(), value.g(), value.b()); - bool b = setUsdAttr(fUsdAttr, vec); - UFE_ASSERT_MSG(b, kErrorMsgFailedSet); + GfVec3f vec; + UFE_ASSERT_MSG(fUsdAttr.Get(&vec, getCurrentTime(sceneItem())), kErrorMsgInvalidType); + vec.Set(value.r(), value.g(), value.b()); + bool b = setUsdAttr(fUsdAttr, vec); + UFE_ASSERT_MSG(b, kErrorMsgFailedSet); } -template<> -Ufe::Vector3i TypedUsdAttribute::get() const +template <> Ufe::Vector3i TypedUsdAttribute::get() const { - return getUsdAttributeVectorAsUfe(fUsdAttr, getCurrentTime(sceneItem())); + return getUsdAttributeVectorAsUfe( + fUsdAttr, getCurrentTime(sceneItem())); } -template<> -void TypedUsdAttribute::set(const Ufe::Vector3i& value) +template <> void TypedUsdAttribute::set(const Ufe::Vector3i& value) { - setUsdAttributeVectorFromUfe(fUsdAttr, value, getCurrentTime(sceneItem())); + setUsdAttributeVectorFromUfe( + fUsdAttr, value, getCurrentTime(sceneItem())); } -template<> -Ufe::Vector3f TypedUsdAttribute::get() const +template <> Ufe::Vector3f TypedUsdAttribute::get() const { - return getUsdAttributeVectorAsUfe(fUsdAttr, getCurrentTime(sceneItem())); + return getUsdAttributeVectorAsUfe( + fUsdAttr, getCurrentTime(sceneItem())); } -template<> -void TypedUsdAttribute::set(const Ufe::Vector3f& value) +template <> void TypedUsdAttribute::set(const Ufe::Vector3f& value) { - setUsdAttributeVectorFromUfe(fUsdAttr, value, getCurrentTime(sceneItem())); + setUsdAttributeVectorFromUfe( + fUsdAttr, value, getCurrentTime(sceneItem())); } -template<> -Ufe::Vector3d TypedUsdAttribute::get() const +template <> Ufe::Vector3d TypedUsdAttribute::get() const { - return getUsdAttributeVectorAsUfe(fUsdAttr, getCurrentTime(sceneItem())); + return getUsdAttributeVectorAsUfe( + fUsdAttr, getCurrentTime(sceneItem())); } -template<> -void TypedUsdAttribute::set(const Ufe::Vector3d& value) +template <> void TypedUsdAttribute::set(const Ufe::Vector3d& value) { - setUsdAttributeVectorFromUfe(fUsdAttr, value, getCurrentTime(sceneItem())); + setUsdAttributeVectorFromUfe( + fUsdAttr, value, getCurrentTime(sceneItem())); } -template -T TypedUsdAttribute::get() const +template T TypedUsdAttribute::get() const { - if (!hasValue()) return T(); + if (!hasValue()) + return T(); - PXR_NS::VtValue vt; - if (fUsdAttr.Get(&vt, getCurrentTime(Ufe::Attribute::sceneItem())) && vt.IsHolding()) - { - return vt.UncheckedGet(); - } + PXR_NS::VtValue vt; + if (fUsdAttr.Get(&vt, getCurrentTime(Ufe::Attribute::sceneItem())) && vt.IsHolding()) { + return vt.UncheckedGet(); + } - UFE_ASSERT_MSG(false, kErrorMsgInvalidType); - return T(); + UFE_ASSERT_MSG(false, kErrorMsgInvalidType); + return T(); } -template -void TypedUsdAttribute::set(const T& value) +template void TypedUsdAttribute::set(const T& value) { - T dummy; - UFE_ASSERT_MSG(fUsdAttr.Get(&dummy, getCurrentTime(Ufe::Attribute::sceneItem())), kErrorMsgInvalidType); - bool b = setUsdAttr(fUsdAttr, value); - UFE_ASSERT_MSG(b, kErrorMsgFailedSet); + T dummy; + UFE_ASSERT_MSG( + fUsdAttr.Get(&dummy, getCurrentTime(Ufe::Attribute::sceneItem())), kErrorMsgInvalidType); + bool b = setUsdAttr(fUsdAttr, value); + UFE_ASSERT_MSG(b, kErrorMsgFailedSet); } //------------------------------------------------------------------------------ @@ -414,10 +408,11 @@ void TypedUsdAttribute::set(const T& value) //------------------------------------------------------------------------------ /*static*/ -UsdAttributeBool::Ptr UsdAttributeBool::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) +UsdAttributeBool::Ptr +UsdAttributeBool::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { - auto attr = std::make_shared(item, usdAttr); - return attr; + auto attr = std::make_shared(item, usdAttr); + return attr; } //------------------------------------------------------------------------------ @@ -425,10 +420,11 @@ UsdAttributeBool::Ptr UsdAttributeBool::create(const UsdSceneItem::Ptr& item, co //------------------------------------------------------------------------------ /*static*/ -UsdAttributeInt::Ptr UsdAttributeInt::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) +UsdAttributeInt::Ptr +UsdAttributeInt::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { - auto attr = std::make_shared(item, usdAttr); - return attr; + auto attr = std::make_shared(item, usdAttr); + return attr; } //------------------------------------------------------------------------------ @@ -436,10 +432,11 @@ UsdAttributeInt::Ptr UsdAttributeInt::create(const UsdSceneItem::Ptr& item, cons //------------------------------------------------------------------------------ /*static*/ -UsdAttributeFloat::Ptr UsdAttributeFloat::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) +UsdAttributeFloat::Ptr +UsdAttributeFloat::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { - auto attr = std::make_shared(item, usdAttr); - return attr; + auto attr = std::make_shared(item, usdAttr); + return attr; } //------------------------------------------------------------------------------ @@ -447,10 +444,11 @@ UsdAttributeFloat::Ptr UsdAttributeFloat::create(const UsdSceneItem::Ptr& item, //------------------------------------------------------------------------------ /*static*/ -UsdAttributeDouble::Ptr UsdAttributeDouble::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) +UsdAttributeDouble::Ptr +UsdAttributeDouble::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { - auto attr = std::make_shared(item, usdAttr); - return attr; + auto attr = std::make_shared(item, usdAttr); + return attr; } //------------------------------------------------------------------------------ @@ -458,10 +456,11 @@ UsdAttributeDouble::Ptr UsdAttributeDouble::create(const UsdSceneItem::Ptr& item //------------------------------------------------------------------------------ /*static*/ -UsdAttributeString::Ptr UsdAttributeString::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) +UsdAttributeString::Ptr +UsdAttributeString::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { - auto attr = std::make_shared(item, usdAttr); - return attr; + auto attr = std::make_shared(item, usdAttr); + return attr; } //------------------------------------------------------------------------------ @@ -469,10 +468,11 @@ UsdAttributeString::Ptr UsdAttributeString::create(const UsdSceneItem::Ptr& item //------------------------------------------------------------------------------ /*static*/ -UsdAttributeColorFloat3::Ptr UsdAttributeColorFloat3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) +UsdAttributeColorFloat3::Ptr +UsdAttributeColorFloat3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { - auto attr = std::make_shared(item, usdAttr); - return attr; + auto attr = std::make_shared(item, usdAttr); + return attr; } //------------------------------------------------------------------------------ @@ -480,10 +480,11 @@ UsdAttributeColorFloat3::Ptr UsdAttributeColorFloat3::create(const UsdSceneItem: //------------------------------------------------------------------------------ /*static*/ -UsdAttributeInt3::Ptr UsdAttributeInt3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) +UsdAttributeInt3::Ptr +UsdAttributeInt3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { - auto attr = std::make_shared(item, usdAttr); - return attr; + auto attr = std::make_shared(item, usdAttr); + return attr; } //------------------------------------------------------------------------------ @@ -491,10 +492,11 @@ UsdAttributeInt3::Ptr UsdAttributeInt3::create(const UsdSceneItem::Ptr& item, co //------------------------------------------------------------------------------ /*static*/ -UsdAttributeFloat3::Ptr UsdAttributeFloat3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) +UsdAttributeFloat3::Ptr +UsdAttributeFloat3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { - auto attr = std::make_shared(item, usdAttr); - return attr; + auto attr = std::make_shared(item, usdAttr); + return attr; } //------------------------------------------------------------------------------ @@ -502,10 +504,11 @@ UsdAttributeFloat3::Ptr UsdAttributeFloat3::create(const UsdSceneItem::Ptr& item //------------------------------------------------------------------------------ /*static*/ -UsdAttributeDouble3::Ptr UsdAttributeDouble3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) +UsdAttributeDouble3::Ptr +UsdAttributeDouble3::create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr) { - auto attr = std::make_shared(item, usdAttr); - return attr; + auto attr = std::make_shared(item, usdAttr); + return attr; } #if 0 @@ -531,4 +534,4 @@ bool UsdAttribute::setValue(const std::string& value) #endif } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdAttribute.h b/lib/mayaUsd/ufe/UsdAttribute.h index 4933edc89b..afc143b965 100644 --- a/lib/mayaUsd/ufe/UsdAttribute.h +++ b/lib/mayaUsd/ufe/UsdAttribute.h @@ -15,19 +15,22 @@ // #pragma once -#include +#include -#include #include +#include -#include +#include // Ufe::Attribute overrides (minus the type method) -#define UFE_ATTRIBUTE_OVERRIDES \ - bool hasValue() const override { return UsdAttribute::hasValue(); } \ - std::string name() const override { return UsdAttribute::name(); } \ - std::string documentation() const override { return UsdAttribute::documentation(); } \ - std::string string() const override { return UsdAttribute::string(Ufe::Attribute::sceneItem()); } +#define UFE_ATTRIBUTE_OVERRIDES \ + bool hasValue() const override { return UsdAttribute::hasValue(); } \ + std::string name() const override { return UsdAttribute::name(); } \ + std::string documentation() const override { return UsdAttribute::documentation(); } \ + std::string string() const override \ + { \ + return UsdAttribute::string(Ufe::Attribute::sceneItem()); \ + } namespace MAYAUSD_NS_DEF { namespace ufe { @@ -36,180 +39,197 @@ namespace ufe { class UsdAttribute { public: - UsdAttribute(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); - ~UsdAttribute(); + UsdAttribute(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + ~UsdAttribute(); - // Ufe::Attribute override methods that we've mimic'd here. - bool hasValue() const; - std::string name() const; - std::string documentation() const; - std::string string(const Ufe::SceneItem::Ptr& item) const; + // Ufe::Attribute override methods that we've mimic'd here. + bool hasValue() const; + std::string name() const; + std::string documentation() const; + std::string string(const Ufe::SceneItem::Ptr& item) const; protected: - PXR_NS::UsdPrim fPrim; - PXR_NS::UsdAttribute fUsdAttr; + PXR_NS::UsdPrim fPrim; + PXR_NS::UsdAttribute fUsdAttr; }; // UsdAttribute //! \brief Interface for USD attributes which don't match any defined type. -class UsdAttributeGeneric : public Ufe::AttributeGeneric, private UsdAttribute +class UsdAttributeGeneric + : public Ufe::AttributeGeneric + , private UsdAttribute { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdAttributeGeneric(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + UsdAttributeGeneric(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); - //! Create a UsdAttributeGeneric. - static UsdAttributeGeneric::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + //! Create a UsdAttributeGeneric. + static UsdAttributeGeneric::Ptr + create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); - // Ufe::Attribute overrides - UFE_ATTRIBUTE_OVERRIDES + // Ufe::Attribute overrides + UFE_ATTRIBUTE_OVERRIDES - // Ufe::AttributeGeneric overrides - std::string nativeType() const override; + // Ufe::AttributeGeneric overrides + std::string nativeType() const override; }; // UsdAttributeGeneric //! \brief Interface for USD token attributes. -class UsdAttributeEnumString : public Ufe::AttributeEnumString, private UsdAttribute +class UsdAttributeEnumString + : public Ufe::AttributeEnumString + , private UsdAttribute { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdAttributeEnumString(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + UsdAttributeEnumString(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); - //! Create a UsdAttributeEnumString. - static UsdAttributeEnumString::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + //! Create a UsdAttributeEnumString. + static UsdAttributeEnumString::Ptr + create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); - // Ufe::Attribute overrides - UFE_ATTRIBUTE_OVERRIDES + // Ufe::Attribute overrides + UFE_ATTRIBUTE_OVERRIDES - // Ufe::AttributeEnumString overrides - std::string get() const override; - void set(const std::string& value) override; - EnumValues getEnumValues() const override; + // Ufe::AttributeEnumString overrides + std::string get() const override; + void set(const std::string& value) override; + EnumValues getEnumValues() const override; }; // UsdAttributeEnumString //! \brief Internal helper template class to implement the get/set methods from Ufe::TypeAttribute. -template -class TypedUsdAttribute : public Ufe::TypedAttribute, private UsdAttribute +template +class TypedUsdAttribute + : public Ufe::TypedAttribute + , private UsdAttribute { public: - TypedUsdAttribute(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + TypedUsdAttribute(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); - // Ufe::Attribute overrides - UFE_ATTRIBUTE_OVERRIDES + // Ufe::Attribute overrides + UFE_ATTRIBUTE_OVERRIDES - // Ufe::TypedAttribute overrides - T get() const override; - void set(const T& value) override; + // Ufe::TypedAttribute overrides + T get() const override; + void set(const T& value) override; }; // TypedUsdAttribute //! \brief Interface for USD bool attributes. class UsdAttributeBool : public TypedUsdAttribute { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - using TypedUsdAttribute::TypedUsdAttribute; + using TypedUsdAttribute::TypedUsdAttribute; - //! Create a UsdAttributeBool. - static UsdAttributeBool::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + //! Create a UsdAttributeBool. + static UsdAttributeBool::Ptr + create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeBool //! \brief Interface for USD int attributes. class UsdAttributeInt : public TypedUsdAttribute { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - using TypedUsdAttribute::TypedUsdAttribute; + using TypedUsdAttribute::TypedUsdAttribute; - //! Create a UsdAttributeInt. - static UsdAttributeInt::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + //! Create a UsdAttributeInt. + static UsdAttributeInt::Ptr + create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeInt //! \brief Interface for USD float attributes. class UsdAttributeFloat : public TypedUsdAttribute { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - using TypedUsdAttribute::TypedUsdAttribute; + using TypedUsdAttribute::TypedUsdAttribute; - //! Create a UsdAttributeFloat. - static UsdAttributeFloat::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + //! Create a UsdAttributeFloat. + static UsdAttributeFloat::Ptr + create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeFloat //! \brief Interface for USD double attributes. class UsdAttributeDouble : public TypedUsdAttribute { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - using TypedUsdAttribute::TypedUsdAttribute; + using TypedUsdAttribute::TypedUsdAttribute; - //! Create a UsdAttributeDouble. - static UsdAttributeDouble::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + //! Create a UsdAttributeDouble. + static UsdAttributeDouble::Ptr + create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeDouble //! \brief Interface for USD string/token attributes. class UsdAttributeString : public TypedUsdAttribute { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - using TypedUsdAttribute::TypedUsdAttribute; + using TypedUsdAttribute::TypedUsdAttribute; - //! Create a UsdAttributeString. - static UsdAttributeString::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + //! Create a UsdAttributeString. + static UsdAttributeString::Ptr + create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeString //! \brief Interface for USD RGB color (float) attributes. class UsdAttributeColorFloat3 : public TypedUsdAttribute { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - using TypedUsdAttribute::TypedUsdAttribute; + using TypedUsdAttribute::TypedUsdAttribute; - //! Create a UsdAttributeColorFloat3. - static UsdAttributeColorFloat3::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + //! Create a UsdAttributeColorFloat3. + static UsdAttributeColorFloat3::Ptr + create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeColorFloat3 //! \brief Interface for USD Vector3i (int) attributes. class UsdAttributeInt3 : public TypedUsdAttribute { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - using TypedUsdAttribute::TypedUsdAttribute; + using TypedUsdAttribute::TypedUsdAttribute; - //! Create a UsdAttributeInt3. - static UsdAttributeInt3::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + //! Create a UsdAttributeInt3. + static UsdAttributeInt3::Ptr + create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeInt3 //! \brief Interface for USD Vector3f (float) attributes. class UsdAttributeFloat3 : public TypedUsdAttribute { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - using TypedUsdAttribute::TypedUsdAttribute; + using TypedUsdAttribute::TypedUsdAttribute; - //! Create a UsdAttributeFloat3. - static UsdAttributeFloat3::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + //! Create a UsdAttributeFloat3. + static UsdAttributeFloat3::Ptr + create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeFloat3 //! \brief Interface for USD Vector3d (double) attributes. class UsdAttributeDouble3 : public TypedUsdAttribute { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - using TypedUsdAttribute::TypedUsdAttribute; + using TypedUsdAttribute::TypedUsdAttribute; - //! Create a UsdAttributeDouble3. - static UsdAttributeDouble3::Ptr create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); + //! Create a UsdAttributeDouble3. + static UsdAttributeDouble3::Ptr + create(const UsdSceneItem::Ptr& item, const PXR_NS::UsdAttribute& usdAttr); }; // UsdAttributeDouble3 } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdAttributes.cpp b/lib/mayaUsd/ufe/UsdAttributes.cpp index 6f94f437b6..5c85e0a581 100644 --- a/lib/mayaUsd/ufe/UsdAttributes.cpp +++ b/lib/mayaUsd/ufe/UsdAttributes.cpp @@ -15,12 +15,12 @@ // #include "UsdAttributes.h" -#include - #include #include #include +#include + // Note: normally we would use this using directive, but here we cannot because // one of our classes is called UsdAttribute which is exactly the same as // the one in USD. @@ -35,222 +35,212 @@ namespace MAYAUSD_NS_DEF { namespace ufe { UsdAttributes::UsdAttributes(const UsdSceneItem::Ptr& item) - : Ufe::Attributes() - , fItem(item) + : Ufe::Attributes() + , fItem(item) { - fPrim = item->prim(); + fPrim = item->prim(); } -UsdAttributes::~UsdAttributes() -{ -} +UsdAttributes::~UsdAttributes() { } /*static*/ UsdAttributes::Ptr UsdAttributes::create(const UsdSceneItem::Ptr& item) { - auto attrs = std::make_shared(item); - return attrs; + auto attrs = std::make_shared(item); + return attrs; } //------------------------------------------------------------------------------ // Ufe::Attributes overrides //------------------------------------------------------------------------------ -Ufe::SceneItem::Ptr UsdAttributes::sceneItem() const -{ - return fItem; -} +Ufe::SceneItem::Ptr UsdAttributes::sceneItem() const { return fItem; } Ufe::Attribute::Type UsdAttributes::attributeType(const std::string& name) { - PXR_NS::TfToken tok(name); - PXR_NS::UsdAttribute usdAttr = fPrim.GetAttribute(tok); - return getUfeTypeForAttribute(usdAttr); + PXR_NS::TfToken tok(name); + PXR_NS::UsdAttribute usdAttr = fPrim.GetAttribute(tok); + return getUfeTypeForAttribute(usdAttr); } Ufe::Attribute::Ptr UsdAttributes::attribute(const std::string& name) { - // If we've already created an attribute for this name, just return it. - auto iter = fAttributes.find(name); - if (iter != std::end(fAttributes)) - return iter->second; - - // No attribute for the input name was found -> create one. - PXR_NS::TfToken tok(name); - PXR_NS::UsdAttribute usdAttr = fPrim.GetAttribute(tok); - Ufe::Attribute::Type newAttrType = getUfeTypeForAttribute(usdAttr); - Ufe::Attribute::Ptr newAttr; - - if (newAttrType == Ufe::Attribute::kBool) { - newAttr = UsdAttributeBool::create(fItem, usdAttr); - } - else if (newAttrType == Ufe::Attribute::kInt) { - newAttr = UsdAttributeInt::create(fItem, usdAttr); - } - else if (newAttrType == Ufe::Attribute::kFloat) { - newAttr = UsdAttributeFloat::create(fItem, usdAttr); - } - else if (newAttrType == Ufe::Attribute::kDouble) { - newAttr = UsdAttributeDouble::create(fItem, usdAttr); - } - else if (newAttrType == Ufe::Attribute::kString) { - newAttr = UsdAttributeString::create(fItem, usdAttr); - } - else if (newAttrType == Ufe::Attribute::kColorFloat3) { - newAttr = UsdAttributeColorFloat3::create(fItem, usdAttr); - } - else if (newAttrType == Ufe::Attribute::kEnumString) { - newAttr = UsdAttributeEnumString::create(fItem, usdAttr); - } - else if (newAttrType == Ufe::Attribute::kInt3) { - newAttr = UsdAttributeInt3::create(fItem, usdAttr); - } - else if (newAttrType == Ufe::Attribute::kFloat3) { - newAttr = UsdAttributeFloat3::create(fItem, usdAttr); - } - else if (newAttrType == Ufe::Attribute::kDouble3) { - newAttr = UsdAttributeDouble3::create(fItem, usdAttr); - } - else if (newAttrType == Ufe::Attribute::kGeneric) { - newAttr = UsdAttributeGeneric::create(fItem, usdAttr); - } - else { - UFE_ASSERT_MSG(false, kErrorMsgUnknown); - } - fAttributes[name] = newAttr; - return newAttr; + // If we've already created an attribute for this name, just return it. + auto iter = fAttributes.find(name); + if (iter != std::end(fAttributes)) + return iter->second; + + // No attribute for the input name was found -> create one. + PXR_NS::TfToken tok(name); + PXR_NS::UsdAttribute usdAttr = fPrim.GetAttribute(tok); + Ufe::Attribute::Type newAttrType = getUfeTypeForAttribute(usdAttr); + Ufe::Attribute::Ptr newAttr; + + if (newAttrType == Ufe::Attribute::kBool) { + newAttr = UsdAttributeBool::create(fItem, usdAttr); + } else if (newAttrType == Ufe::Attribute::kInt) { + newAttr = UsdAttributeInt::create(fItem, usdAttr); + } else if (newAttrType == Ufe::Attribute::kFloat) { + newAttr = UsdAttributeFloat::create(fItem, usdAttr); + } else if (newAttrType == Ufe::Attribute::kDouble) { + newAttr = UsdAttributeDouble::create(fItem, usdAttr); + } else if (newAttrType == Ufe::Attribute::kString) { + newAttr = UsdAttributeString::create(fItem, usdAttr); + } else if (newAttrType == Ufe::Attribute::kColorFloat3) { + newAttr = UsdAttributeColorFloat3::create(fItem, usdAttr); + } else if (newAttrType == Ufe::Attribute::kEnumString) { + newAttr = UsdAttributeEnumString::create(fItem, usdAttr); + } else if (newAttrType == Ufe::Attribute::kInt3) { + newAttr = UsdAttributeInt3::create(fItem, usdAttr); + } else if (newAttrType == Ufe::Attribute::kFloat3) { + newAttr = UsdAttributeFloat3::create(fItem, usdAttr); + } else if (newAttrType == Ufe::Attribute::kDouble3) { + newAttr = UsdAttributeDouble3::create(fItem, usdAttr); + } else if (newAttrType == Ufe::Attribute::kGeneric) { + newAttr = UsdAttributeGeneric::create(fItem, usdAttr); + } else { + UFE_ASSERT_MSG(false, kErrorMsgUnknown); + } + fAttributes[name] = newAttr; + return newAttr; } std::vector UsdAttributes::attributeNames() const { - auto primAttrs = fPrim.GetAttributes(); - std::vector names; - names.reserve(primAttrs.size()); - for (const auto& attr : primAttrs) - { - names.push_back(attr.GetName()); - } - return names; + auto primAttrs = fPrim.GetAttributes(); + std::vector names; + names.reserve(primAttrs.size()); + for (const auto& attr : primAttrs) { + names.push_back(attr.GetName()); + } + return names; } bool UsdAttributes::hasAttribute(const std::string& name) const { - TfToken tkName(name); - return fPrim.HasAttribute(tkName); + TfToken tkName(name); + return fPrim.HasAttribute(tkName); } -Ufe::Attribute::Type UsdAttributes::getUfeTypeForAttribute(const PXR_NS::UsdAttribute& usdAttr) const +Ufe::Attribute::Type +UsdAttributes::getUfeTypeForAttribute(const PXR_NS::UsdAttribute& usdAttr) const { - // Map the USD type into UFE type. - static const std::unordered_map sUsdTypeToUfe - { - {SdfValueTypeNames->Bool.GetHash(), Ufe::Attribute::kBool}, // bool -// {SdfValueTypeNames->UChar.GetHash(), Ufe::Attribute::kUnknown}, // uint8_t - {SdfValueTypeNames->Int.GetHash(), Ufe::Attribute::kInt}, // int32_t -// {SdfValueTypeNames->UInt.GetHash(), Ufe::Attribute::kUnknown}, // uint32_t -// {SdfValueTypeNames->Int64.GetHash(), Ufe::Attribute::kInt}, // int64_t -// {SdfValueTypeNames->UInt64.GetHash(), Ufe::Attribute::kUnknown}, // uint64_t -// {SdfValueTypeNames->Half.GetHash(), Ufe::Attribute::kUnknown}, // GfHalf - {SdfValueTypeNames->Float.GetHash(), Ufe::Attribute::kFloat}, // float - {SdfValueTypeNames->Double.GetHash(), Ufe::Attribute::kDouble}, // double - {SdfValueTypeNames->String.GetHash(), Ufe::Attribute::kString}, // std::string - {SdfValueTypeNames->Token.GetHash(), Ufe::Attribute::kEnumString}, // TfToken -// {SdfValueTypeNames->Asset.GetHash(), Ufe::Attribute::kUnknown}, // SdfAssetPath -// {SdfValueTypeNames->Int2.GetHash(), Ufe::Attribute::kInt2}, // GfVec2i -// {SdfValueTypeNames->Half2.GetHash(), Ufe::Attribute::kUnknown}, // GfVec2h -// {SdfValueTypeNames->Float2.GetHash(), Ufe::Attribute::kFloat2}, // GfVec2f -// {SdfValueTypeNames->Double2.GetHash(), Ufe::Attribute::kDouble2}, // GfVec2d - {SdfValueTypeNames->Int3.GetHash(), Ufe::Attribute::kInt3}, // GfVec3i -// {SdfValueTypeNames->Half3.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3h - {SdfValueTypeNames->Float3.GetHash(), Ufe::Attribute::kFloat3}, // GfVec3f - {SdfValueTypeNames->Double3.GetHash(), Ufe::Attribute::kDouble3}, // GfVec3d -// {SdfValueTypeNames->Int4.GetHash(), Ufe::Attribute::kInt4}, // GfVec4i -// {SdfValueTypeNames->Half4.GetHash(), Ufe::Attribute::kUnknown}, // GfVec4h -// {SdfValueTypeNames->Float4.GetHash(), Ufe::Attribute::kFloat4}, // GfVec4f -// {SdfValueTypeNames->Double4.GetHash(), Ufe::Attribute::kDouble4}, // GfVec4d -// {SdfValueTypeNames->Point3h.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3h -// {SdfValueTypeNames->Point3f.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3f -// {SdfValueTypeNames->Point3d.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3d -// {SdfValueTypeNames->Vector3h.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3h -// {SdfValueTypeNames->Vector3f.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3f -// {SdfValueTypeNames->Vector3d.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3d -// {SdfValueTypeNames->Normal3h.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3h -// {SdfValueTypeNames->Normal3f.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3f -// {SdfValueTypeNames->Normal3d.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3d -// {SdfValueTypeNames->Color3h.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3h - {SdfValueTypeNames->Color3f.GetHash(), Ufe::Attribute::kColorFloat3}, // GfVec3f - {SdfValueTypeNames->Color3d.GetHash(), Ufe::Attribute::kColorFloat3}, // GfVec3d -// {SdfValueTypeNames->Color4h.GetHash(), Ufe::Attribute::kUnknown}, // GfVec4h -// {SdfValueTypeNames->Color4f.GetHash(), Ufe::Attribute::kUnknown}, // GfVec4f -// {SdfValueTypeNames->Color4d.GetHash(), Ufe::Attribute::kUnknown}, // GfVec4d -// {SdfValueTypeNames->Quath.GetHash(), Ufe::Attribute::kUnknown}, // GfQuath -// {SdfValueTypeNames->Quatf.GetHash(), Ufe::Attribute::kUnknown}, // GfQuatf -// {SdfValueTypeNames->Quatd.GetHash(), Ufe::Attribute::kUnknown}, // GfQuatd -// {SdfValueTypeNames->Matrix2d.GetHash(), Ufe::Attribute::kUnknown}, // GfMatrix2d -// {SdfValueTypeNames->Matrix3d.GetHash(), Ufe::Attribute::kUnknown}, // GfMatrix3d -// {SdfValueTypeNames->Matrix4d.GetHash(), Ufe::Attribute::kUnknown}, // GfMatrix4d -// {SdfValueTypeNames->Frame4d.GetHash(), Ufe::Attribute::kUnknown}, // GfMatrix4d -// {SdfValueTypeNames->TexCoord2f.GetHash(), Ufe::Attribute::kUnknown}, // GfVec2f -// {SdfValueTypeNames->TexCoord2d.GetHash(), Ufe::Attribute::kUnknown}, // GfVec2d -// {SdfValueTypeNames->TexCoord2h.GetHash(), Ufe::Attribute::kUnknown}, // GfVec2h -// {SdfValueTypeNames->TexCoord3f.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3f -// {SdfValueTypeNames->TexCoord3d.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3d -// {SdfValueTypeNames->TexCoord3h.GetHash(), Ufe::Attribute::kUnknown}, // GfVec3h -// To add? -// SdfValueTypeName BoolArray; -// SdfValueTypeName UCharArray, IntArray, UIntArray, Int64Array, UInt64Array; -// SdfValueTypeName HalfArray, FloatArray, DoubleArray; -// SdfValueTypeName StringArray, TokenArray, AssetArray; -// SdfValueTypeName Int2Array, Int3Array, Int4Array; -// SdfValueTypeName Half2Array, Half3Array, Half4Array; -// SdfValueTypeName Float2Array, Float3Array, Float4Array; -// SdfValueTypeName Double2Array, Double3Array, Double4Array; -// SdfValueTypeName Point3hArray, Point3fArray, Point3dArray; -// SdfValueTypeName Vector3hArray, Vector3fArray, Vector3dArray; -// SdfValueTypeName Normal3hArray, Normal3fArray, Normal3dArray; -// SdfValueTypeName Color3hArray, Color3fArray, Color3dArray; -// SdfValueTypeName Color4hArray, Color4fArray, Color4dArray; -// SdfValueTypeName QuathArray, QuatfArray, QuatdArray; -// SdfValueTypeName Matrix2dArray, Matrix3dArray, Matrix4dArray; -// SdfValueTypeName Frame4dArray; -// SdfValueTypeName TexCoord2hArray, TexCoord2fArray, TexCoord2dArray; -// SdfValueTypeName TexCoord3hArray, TexCoord3fArray, TexCoord3dArray; - }; - - if (usdAttr.IsValid()) - { - const PXR_NS::SdfValueTypeName typeName = usdAttr.GetTypeName(); - const auto iter = sUsdTypeToUfe.find(typeName.GetHash()); - - // ** TEMP - for debugging purposes only - // std::string cppName = typeName.GetCPPTypeName(); - - if (iter != sUsdTypeToUfe.end()) - { - // Special case for TfToken -> Enum. If it doesn't have any allowed - // tokens, then use String instead. - if (iter->second == Ufe::Attribute::kEnumString) - { + // Map the USD type into UFE type. + static const std:: + unordered_map + sUsdTypeToUfe { + { SdfValueTypeNames->Bool.GetHash(), Ufe::Attribute::kBool }, // bool + // {SdfValueTypeNames->UChar.GetHash(), Ufe::Attribute::kUnknown}, + //// uint8_t + { SdfValueTypeNames->Int.GetHash(), Ufe::Attribute::kInt }, // int32_t + // {SdfValueTypeNames->UInt.GetHash(), Ufe::Attribute::kUnknown}, + //// uint32_t + // {SdfValueTypeNames->Int64.GetHash(), Ufe::Attribute::kInt}, + //// int64_t {SdfValueTypeNames->UInt64.GetHash(), Ufe::Attribute::kUnknown}, + //// uint64_t + // {SdfValueTypeNames->Half.GetHash(), Ufe::Attribute::kUnknown}, + //// GfHalf + { SdfValueTypeNames->Float.GetHash(), Ufe::Attribute::kFloat }, // float + { SdfValueTypeNames->Double.GetHash(), Ufe::Attribute::kDouble }, // double + { SdfValueTypeNames->String.GetHash(), Ufe::Attribute::kString }, // std::string + { SdfValueTypeNames->Token.GetHash(), Ufe::Attribute::kEnumString }, // TfToken + // {SdfValueTypeNames->Asset.GetHash(), Ufe::Attribute::kUnknown}, + //// SdfAssetPath {SdfValueTypeNames->Int2.GetHash(), Ufe::Attribute::kInt2}, + //// GfVec2i {SdfValueTypeNames->Half2.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec2h {SdfValueTypeNames->Float2.GetHash(), Ufe::Attribute::kFloat2}, + //// GfVec2f {SdfValueTypeNames->Double2.GetHash(), Ufe::Attribute::kDouble2}, + //// GfVec2d + { SdfValueTypeNames->Int3.GetHash(), Ufe::Attribute::kInt3 }, // GfVec3i + // {SdfValueTypeNames->Half3.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3h + { SdfValueTypeNames->Float3.GetHash(), Ufe::Attribute::kFloat3 }, // GfVec3f + { SdfValueTypeNames->Double3.GetHash(), Ufe::Attribute::kDouble3 }, // GfVec3d + // {SdfValueTypeNames->Int4.GetHash(), Ufe::Attribute::kInt4}, + //// GfVec4i {SdfValueTypeNames->Half4.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec4h {SdfValueTypeNames->Float4.GetHash(), Ufe::Attribute::kFloat4}, + //// GfVec4f {SdfValueTypeNames->Double4.GetHash(), Ufe::Attribute::kDouble4}, + //// GfVec4d {SdfValueTypeNames->Point3h.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3h {SdfValueTypeNames->Point3f.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3f {SdfValueTypeNames->Point3d.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3d {SdfValueTypeNames->Vector3h.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3h {SdfValueTypeNames->Vector3f.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3f {SdfValueTypeNames->Vector3d.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3d {SdfValueTypeNames->Normal3h.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3h {SdfValueTypeNames->Normal3f.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3f {SdfValueTypeNames->Normal3d.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3d {SdfValueTypeNames->Color3h.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3h + { SdfValueTypeNames->Color3f.GetHash(), Ufe::Attribute::kColorFloat3 }, // GfVec3f + { SdfValueTypeNames->Color3d.GetHash(), Ufe::Attribute::kColorFloat3 }, // GfVec3d + // {SdfValueTypeNames->Color4h.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec4h {SdfValueTypeNames->Color4f.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec4f {SdfValueTypeNames->Color4d.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec4d {SdfValueTypeNames->Quath.GetHash(), Ufe::Attribute::kUnknown}, + //// GfQuath {SdfValueTypeNames->Quatf.GetHash(), Ufe::Attribute::kUnknown}, + //// GfQuatf {SdfValueTypeNames->Quatd.GetHash(), Ufe::Attribute::kUnknown}, + //// GfQuatd {SdfValueTypeNames->Matrix2d.GetHash(), Ufe::Attribute::kUnknown}, + //// GfMatrix2d {SdfValueTypeNames->Matrix3d.GetHash(), Ufe::Attribute::kUnknown}, + //// GfMatrix3d {SdfValueTypeNames->Matrix4d.GetHash(), Ufe::Attribute::kUnknown}, + //// GfMatrix4d {SdfValueTypeNames->Frame4d.GetHash(), Ufe::Attribute::kUnknown}, + //// GfMatrix4d {SdfValueTypeNames->TexCoord2f.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec2f {SdfValueTypeNames->TexCoord2d.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec2d {SdfValueTypeNames->TexCoord2h.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec2h {SdfValueTypeNames->TexCoord3f.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3f {SdfValueTypeNames->TexCoord3d.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3d {SdfValueTypeNames->TexCoord3h.GetHash(), Ufe::Attribute::kUnknown}, + //// GfVec3h + // To add? + // SdfValueTypeName BoolArray; + // SdfValueTypeName UCharArray, IntArray, UIntArray, Int64Array, UInt64Array; + // SdfValueTypeName HalfArray, FloatArray, DoubleArray; + // SdfValueTypeName StringArray, TokenArray, AssetArray; + // SdfValueTypeName Int2Array, Int3Array, Int4Array; + // SdfValueTypeName Half2Array, Half3Array, Half4Array; + // SdfValueTypeName Float2Array, Float3Array, Float4Array; + // SdfValueTypeName Double2Array, Double3Array, Double4Array; + // SdfValueTypeName Point3hArray, Point3fArray, Point3dArray; + // SdfValueTypeName Vector3hArray, Vector3fArray, Vector3dArray; + // SdfValueTypeName Normal3hArray, Normal3fArray, Normal3dArray; + // SdfValueTypeName Color3hArray, Color3fArray, Color3dArray; + // SdfValueTypeName Color4hArray, Color4fArray, Color4dArray; + // SdfValueTypeName QuathArray, QuatfArray, QuatdArray; + // SdfValueTypeName Matrix2dArray, Matrix3dArray, Matrix4dArray; + // SdfValueTypeName Frame4dArray; + // SdfValueTypeName TexCoord2hArray, TexCoord2fArray, TexCoord2dArray; + // SdfValueTypeName TexCoord3hArray, TexCoord3fArray, TexCoord3dArray; + }; + + if (usdAttr.IsValid()) { + const PXR_NS::SdfValueTypeName typeName = usdAttr.GetTypeName(); + const auto iter = sUsdTypeToUfe.find(typeName.GetHash()); + + // ** TEMP - for debugging purposes only + // std::string cppName = typeName.GetCPPTypeName(); + + if (iter != sUsdTypeToUfe.end()) { + // Special case for TfToken -> Enum. If it doesn't have any allowed + // tokens, then use String instead. + if (iter->second == Ufe::Attribute::kEnumString) { #if USD_VERSION_NUM > 2002 - auto attrDefn = fPrim.GetPrimDefinition().GetSchemaAttributeSpec(usdAttr.GetName()); + auto attrDefn = fPrim.GetPrimDefinition().GetSchemaAttributeSpec(usdAttr.GetName()); #else - auto attrDefn = PXR_NS::UsdSchemaRegistry::GetAttributeDefinition(fPrim.GetTypeName(), usdAttr.GetName()); + auto attrDefn = PXR_NS::UsdSchemaRegistry::GetAttributeDefinition( + fPrim.GetTypeName(), usdAttr.GetName()); #endif - if (!attrDefn || !attrDefn->HasAllowedTokens()) - return Ufe::Attribute::kString; - } + if (!attrDefn || !attrDefn->HasAllowedTokens()) + return Ufe::Attribute::kString; + } - return iter->second; - } + return iter->second; + } - // We use the generic type to show a Usd attribute's value and native type. - return Ufe::Attribute::kGeneric; - } + // We use the generic type to show a Usd attribute's value and native type. + return Ufe::Attribute::kGeneric; + } - UFE_ASSERT_MSG(false, kErrorMsgInvalidAttribute); - return Ufe::Attribute::kInvalid; + UFE_ASSERT_MSG(false, kErrorMsgInvalidAttribute); + return Ufe::Attribute::kInvalid; } - } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdAttributes.h b/lib/mayaUsd/ufe/UsdAttributes.h index e49dd9ef04..c92a3fd7b9 100644 --- a/lib/mayaUsd/ufe/UsdAttributes.h +++ b/lib/mayaUsd/ufe/UsdAttributes.h @@ -15,15 +15,15 @@ // #pragma once -#include - -#include +#include +#include +#include #include -#include -#include -#include +#include + +#include namespace MAYAUSD_NS_DEF { namespace ufe { @@ -32,38 +32,38 @@ namespace ufe { class UsdAttributes : public Ufe::Attributes { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdAttributes(const UsdSceneItem::Ptr& item); - ~UsdAttributes() override; + UsdAttributes(const UsdSceneItem::Ptr& item); + ~UsdAttributes() override; - // Delete the copy/move constructors assignment operators. - UsdAttributes(const UsdAttributes&) = delete; - UsdAttributes& operator=(const UsdAttributes&) = delete; - UsdAttributes(UsdAttributes&&) = delete; - UsdAttributes& operator=(UsdAttributes&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdAttributes(const UsdAttributes&) = delete; + UsdAttributes& operator=(const UsdAttributes&) = delete; + UsdAttributes(UsdAttributes&&) = delete; + UsdAttributes& operator=(UsdAttributes&&) = delete; - //! Create a UsdAttributes. - static UsdAttributes::Ptr create(const UsdSceneItem::Ptr& item); + //! Create a UsdAttributes. + static UsdAttributes::Ptr create(const UsdSceneItem::Ptr& item); - // Ufe::Attributes overrides - Ufe::SceneItem::Ptr sceneItem() const override; - Ufe::Attribute::Type attributeType(const std::string& name) override; - Ufe::Attribute::Ptr attribute(const std::string& name) override; - std::vector attributeNames() const override; - bool hasAttribute(const std::string& name) const override; + // Ufe::Attributes overrides + Ufe::SceneItem::Ptr sceneItem() const override; + Ufe::Attribute::Type attributeType(const std::string& name) override; + Ufe::Attribute::Ptr attribute(const std::string& name) override; + std::vector attributeNames() const override; + bool hasAttribute(const std::string& name) const override; private: - Ufe::Attribute::Type getUfeTypeForAttribute(const PXR_NS::UsdAttribute& usdAttr) const; + Ufe::Attribute::Type getUfeTypeForAttribute(const PXR_NS::UsdAttribute& usdAttr) const; private: - UsdSceneItem::Ptr fItem; - PXR_NS::UsdPrim fPrim; + UsdSceneItem::Ptr fItem; + PXR_NS::UsdPrim fPrim; - typedef std::unordered_map AttributeMap; - AttributeMap fAttributes; + typedef std::unordered_map AttributeMap; + AttributeMap fAttributes; }; // UsdAttributes } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdAttributesHandler.cpp b/lib/mayaUsd/ufe/UsdAttributesHandler.cpp index cea2ef3ec3..7d2a84ba81 100644 --- a/lib/mayaUsd/ufe/UsdAttributesHandler.cpp +++ b/lib/mayaUsd/ufe/UsdAttributesHandler.cpp @@ -21,18 +21,16 @@ namespace MAYAUSD_NS_DEF { namespace ufe { UsdAttributesHandler::UsdAttributesHandler() - : Ufe::AttributesHandler() + : Ufe::AttributesHandler() { } -UsdAttributesHandler::~UsdAttributesHandler() -{ -} +UsdAttributesHandler::~UsdAttributesHandler() { } /*static*/ UsdAttributesHandler::Ptr UsdAttributesHandler::create() { - return std::make_shared(); + return std::make_shared(); } //------------------------------------------------------------------------------ @@ -41,13 +39,13 @@ UsdAttributesHandler::Ptr UsdAttributesHandler::create() Ufe::Attributes::Ptr UsdAttributesHandler::attributes(const Ufe::SceneItem::Ptr& item) const { - UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); + UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); #if !defined(NDEBUG) - assert(usdItem); + assert(usdItem); #endif - auto usdAttributes = UsdAttributes::create(usdItem); - return usdAttributes; + auto usdAttributes = UsdAttributes::create(usdItem); + return usdAttributes; } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdAttributesHandler.h b/lib/mayaUsd/ufe/UsdAttributesHandler.h index a71bbafd23..152ec2f507 100644 --- a/lib/mayaUsd/ufe/UsdAttributesHandler.h +++ b/lib/mayaUsd/ufe/UsdAttributesHandler.h @@ -15,11 +15,11 @@ // #pragma once -#include - #include #include +#include + namespace MAYAUSD_NS_DEF { namespace ufe { @@ -27,26 +27,25 @@ namespace ufe { class UsdAttributesHandler : public Ufe::AttributesHandler { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdAttributesHandler(); - ~UsdAttributesHandler(); + UsdAttributesHandler(); + ~UsdAttributesHandler(); - // Delete the copy/move constructors assignment operators. - UsdAttributesHandler(const UsdAttributesHandler&) = delete; - UsdAttributesHandler& operator=(const UsdAttributesHandler&) = delete; - UsdAttributesHandler(UsdAttributesHandler&&) = delete; - UsdAttributesHandler& operator=(UsdAttributesHandler&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdAttributesHandler(const UsdAttributesHandler&) = delete; + UsdAttributesHandler& operator=(const UsdAttributesHandler&) = delete; + UsdAttributesHandler(UsdAttributesHandler&&) = delete; + UsdAttributesHandler& operator=(UsdAttributesHandler&&) = delete; - //! Create a UsdAttributesHandler. - static UsdAttributesHandler::Ptr create(); + //! Create a UsdAttributesHandler. + static UsdAttributesHandler::Ptr create(); - // Ufe::AttributesHandler overrides - Ufe::Attributes::Ptr attributes(const Ufe::SceneItem::Ptr& item) const override; + // Ufe::AttributesHandler overrides + Ufe::Attributes::Ptr attributes(const Ufe::SceneItem::Ptr& item) const override; private: - }; // UsdAttributesHandler } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdContextOps.cpp b/lib/mayaUsd/ufe/UsdContextOps.cpp index 94f1846973..f538010c5c 100644 --- a/lib/mayaUsd/ufe/UsdContextOps.cpp +++ b/lib/mayaUsd/ufe/UsdContextOps.cpp @@ -17,32 +17,30 @@ #include "private/UfeNotifGuard.h" -#include -#include -#include -#include - -#include - -#include -#include -#include +#include +#include +#include +#include #include #include #include #include #include -#include #include +#include #include #include -#include +#include +#include +#include +#include -#include -#include -#include +#include +#include +#include +#include namespace { @@ -52,59 +50,59 @@ namespace { // - the "Image" is used for icon in the context menu. Directly used std::string // for these so the emplace_back() will choose the right constructor. With char[] // it would convert that param to a bool and choose the wrong constructor. -static constexpr char kUSDLayerEditorItem[] = "USD Layer Editor"; -static constexpr char kUSDLayerEditorLabel[] = "USD Layer Editor..."; -static const std::string kUSDLayerEditorImage{"USD_generic.png"}; -static constexpr char kUSDLoadItem[] = "Load"; -static constexpr char kUSDLoadLabel[] = "Load"; -static constexpr char kUSDLoadWithDescendantsItem[] = "Load with Descendants"; -static constexpr char kUSDLoadWithDescendantsLabel[] = "Load with Descendants"; -static constexpr char kUSDUnloadItem[] = "Unload"; -static constexpr char kUSDUnloadLabel[] = "Unload"; -static constexpr char kUSDVariantSetsItem[] = "Variant Sets"; -static constexpr char kUSDVariantSetsLabel[] = "Variant Sets"; -static constexpr char kUSDToggleVisibilityItem[] = "Toggle Visibility"; -static constexpr char kUSDMakeVisibleLabel[] = "Make Visible"; -static constexpr char kUSDMakeInvisibleLabel[] = "Make Invisible"; -static constexpr char kUSDToggleActiveStateItem[] = "Toggle Active State"; -static constexpr char kUSDActivatePrimLabel[] = "Activate Prim"; -static constexpr char kUSDDeactivatePrimLabel[] = "Deactivate Prim"; -static constexpr char kUSDAddNewPrimItem[] = "Add New Prim"; -static constexpr char kUSDAddNewPrimLabel[] = "Add New Prim"; -static constexpr char kUSDDefPrimItem[] = "Def"; -static constexpr char kUSDDefPrimLabel[] = "Def"; -static const std::string kUSDDefPrimImage{"out_USD_Def.png"}; -static constexpr char kUSDScopePrimItem[] = "Scope"; -static constexpr char kUSDScopePrimLabel[] = "Scope"; -static const std::string kUSDScopePrimImage{"out_USD_Scope.png"}; -static constexpr char kUSDXformPrimItem[] = "Xform"; -static constexpr char kUSDXformPrimLabel[] = "Xform"; -static const std::string kUSDXformPrimImage{"out_USD_UsdGeomXformable.png"}; -static constexpr char kUSDCapsulePrimItem[] = "Capsule"; -static constexpr char kUSDCapsulePrimLabel[] = "Capsule"; -static const std::string kUSDCapsulePrimImage{"out_USD_Capsule.png"}; -static constexpr char kUSDConePrimItem[] = "Cone"; -static constexpr char kUSDConePrimLabel[] = "Cone"; -static const std::string kUSDConePrimImage{"out_USD_Cone.png"}; -static constexpr char kUSDCubePrimItem[] = "Cube"; -static constexpr char kUSDCubePrimLabel[] = "Cube"; -static const std::string kUSDCubePrimImage{"out_USD_Cube.png"}; -static constexpr char kUSDCylinderPrimItem[] = "Cylinder"; -static constexpr char kUSDCylinderPrimLabel[] = "Cylinder"; -static const std::string kUSDCylinderPrimImage{"out_USD_Cylinder.png"}; -static constexpr char kUSDSpherePrimItem[] = "Sphere"; -static constexpr char kUSDSpherePrimLabel[] = "Sphere"; -static const std::string kUSDSpherePrimImage{"out_USD_Sphere.png"}; +static constexpr char kUSDLayerEditorItem[] = "USD Layer Editor"; +static constexpr char kUSDLayerEditorLabel[] = "USD Layer Editor..."; +static const std::string kUSDLayerEditorImage { "USD_generic.png" }; +static constexpr char kUSDLoadItem[] = "Load"; +static constexpr char kUSDLoadLabel[] = "Load"; +static constexpr char kUSDLoadWithDescendantsItem[] = "Load with Descendants"; +static constexpr char kUSDLoadWithDescendantsLabel[] = "Load with Descendants"; +static constexpr char kUSDUnloadItem[] = "Unload"; +static constexpr char kUSDUnloadLabel[] = "Unload"; +static constexpr char kUSDVariantSetsItem[] = "Variant Sets"; +static constexpr char kUSDVariantSetsLabel[] = "Variant Sets"; +static constexpr char kUSDToggleVisibilityItem[] = "Toggle Visibility"; +static constexpr char kUSDMakeVisibleLabel[] = "Make Visible"; +static constexpr char kUSDMakeInvisibleLabel[] = "Make Invisible"; +static constexpr char kUSDToggleActiveStateItem[] = "Toggle Active State"; +static constexpr char kUSDActivatePrimLabel[] = "Activate Prim"; +static constexpr char kUSDDeactivatePrimLabel[] = "Deactivate Prim"; +static constexpr char kUSDAddNewPrimItem[] = "Add New Prim"; +static constexpr char kUSDAddNewPrimLabel[] = "Add New Prim"; +static constexpr char kUSDDefPrimItem[] = "Def"; +static constexpr char kUSDDefPrimLabel[] = "Def"; +static const std::string kUSDDefPrimImage { "out_USD_Def.png" }; +static constexpr char kUSDScopePrimItem[] = "Scope"; +static constexpr char kUSDScopePrimLabel[] = "Scope"; +static const std::string kUSDScopePrimImage { "out_USD_Scope.png" }; +static constexpr char kUSDXformPrimItem[] = "Xform"; +static constexpr char kUSDXformPrimLabel[] = "Xform"; +static const std::string kUSDXformPrimImage { "out_USD_UsdGeomXformable.png" }; +static constexpr char kUSDCapsulePrimItem[] = "Capsule"; +static constexpr char kUSDCapsulePrimLabel[] = "Capsule"; +static const std::string kUSDCapsulePrimImage { "out_USD_Capsule.png" }; +static constexpr char kUSDConePrimItem[] = "Cone"; +static constexpr char kUSDConePrimLabel[] = "Cone"; +static const std::string kUSDConePrimImage { "out_USD_Cone.png" }; +static constexpr char kUSDCubePrimItem[] = "Cube"; +static constexpr char kUSDCubePrimLabel[] = "Cube"; +static const std::string kUSDCubePrimImage { "out_USD_Cube.png" }; +static constexpr char kUSDCylinderPrimItem[] = "Cylinder"; +static constexpr char kUSDCylinderPrimLabel[] = "Cylinder"; +static const std::string kUSDCylinderPrimImage { "out_USD_Cylinder.png" }; +static constexpr char kUSDSpherePrimItem[] = "Sphere"; +static constexpr char kUSDSpherePrimLabel[] = "Sphere"; +static const std::string kUSDSpherePrimImage { "out_USD_Sphere.png" }; //! \brief Undoable command for loading a USD prim. class LoadUndoableCommand : public Ufe::UndoableCommand { public: - LoadUndoableCommand(const UsdPrim& prim, UsdLoadPolicy policy) : - _stage(prim.GetStage()), - _primPath(prim.GetPath()), - _oldLoadSet(prim.GetStage()->GetLoadSet()), - _policy(policy) + LoadUndoableCommand(const UsdPrim& prim, UsdLoadPolicy policy) + : _stage(prim.GetStage()) + , _primPath(prim.GetPath()) + , _oldLoadSet(prim.GetStage()->GetLoadSet()) + , _policy(policy) { } @@ -114,7 +112,7 @@ class LoadUndoableCommand : public Ufe::UndoableCommand return; } - _stage->LoadAndUnload(_oldLoadSet, SdfPathSet({_primPath})); + _stage->LoadAndUnload(_oldLoadSet, SdfPathSet({ _primPath })); } void redo() override @@ -128,19 +126,19 @@ class LoadUndoableCommand : public Ufe::UndoableCommand private: const UsdStageWeakPtr _stage; - const SdfPath _primPath; - const SdfPathSet _oldLoadSet; - const UsdLoadPolicy _policy; + const SdfPath _primPath; + const SdfPathSet _oldLoadSet; + const UsdLoadPolicy _policy; }; //! \brief Undoable command for unloading a USD prim. class UnloadUndoableCommand : public Ufe::UndoableCommand { public: - UnloadUndoableCommand(const UsdPrim& prim) : - _stage(prim.GetStage()), - _primPath({prim.GetPath()}), - _oldLoadSet(prim.GetStage()->GetLoadSet()) + UnloadUndoableCommand(const UsdPrim& prim) + : _stage(prim.GetStage()) + , _primPath({ prim.GetPath() }) + , _oldLoadSet(prim.GetStage()->GetLoadSet()) { } @@ -164,29 +162,28 @@ class UnloadUndoableCommand : public Ufe::UndoableCommand private: const UsdStageWeakPtr _stage; - const SdfPath _primPath; - const SdfPathSet _oldLoadSet; + const SdfPath _primPath; + const SdfPathSet _oldLoadSet; }; //! \brief Undoable command for variant selection change class SetVariantSelectionUndoableCommand : public Ufe::UndoableCommand { public: - SetVariantSelectionUndoableCommand( const UsdPrim& prim, - const Ufe::ContextOps::ItemPath& itemPath - ) : fVarSet(prim.GetVariantSets().GetVariantSet(itemPath[1])), - fOldSelection(fVarSet.GetVariantSelection()), - fNewSelection(itemPath[2]) - {} + const Ufe::ContextOps::ItemPath& itemPath) + : fVarSet(prim.GetVariantSets().GetVariantSet(itemPath[1])) + , fOldSelection(fVarSet.GetVariantSelection()) + , fNewSelection(itemPath[2]) + { + } void undo() override { fVarSet.SetVariantSelection(fOldSelection); } void redo() override { fVarSet.SetVariantSelection(fNewSelection); } private: - UsdVariantSet fVarSet; const std::string fOldSelection; const std::string fNewSelection; @@ -227,8 +224,8 @@ class ToggleActiveStateCommand : public Ufe::UndoableCommand private: PXR_NS::UsdStageWeakPtr _stage; - PXR_NS::SdfPath _primPath; - bool _active; + PXR_NS::SdfPath _primPath; + bool _active; }; const char* selectUSDFileScript = R"( @@ -264,22 +261,23 @@ class AddReferenceUndoableCommand : public Ufe::UndoableCommand public: static const std::string commandName; - AddReferenceUndoableCommand( - const UsdPrim& prim, - const std::string& filePath - ) : _prim(prim), - _sdfRef(), - _filePath(filePath) - {} + AddReferenceUndoableCommand(const UsdPrim& prim, const std::string& filePath) + : _prim(prim) + , _sdfRef() + , _filePath(filePath) + { + } - void undo() override { + void undo() override + { if (_prim.IsValid()) { UsdReferences primRefs = _prim.GetReferences(); primRefs.RemoveReference(_sdfRef); } } - void redo() override { + void redo() override + { if (_prim.IsValid()) { _sdfRef = SdfReference(_filePath); UsdReferences primRefs = _prim.GetReferences(); @@ -288,8 +286,8 @@ class AddReferenceUndoableCommand : public Ufe::UndoableCommand } private: - UsdPrim _prim; - SdfReference _sdfRef; + UsdPrim _prim; + SdfReference _sdfRef; const std::string _filePath; }; const std::string AddReferenceUndoableCommand::commandName("Add Reference..."); @@ -298,18 +296,17 @@ class ClearAllReferencesUndoableCommand : public Ufe::UndoableCommand { public: static const std::string commandName; - static const MString cancelRemoval; - - ClearAllReferencesUndoableCommand( - const UsdPrim& prim - ) : _prim(prim) - {} - - void undo() override { + static const MString cancelRemoval; + ClearAllReferencesUndoableCommand(const UsdPrim& prim) + : _prim(prim) + { } - void redo() override { + void undo() override { } + + void redo() override + { if (_prim.IsValid()) { UsdReferences primRefs = _prim.GetReferences(); primRefs.ClearReferences(); @@ -320,7 +317,7 @@ class ClearAllReferencesUndoableCommand : public Ufe::UndoableCommand UsdPrim _prim; }; const std::string ClearAllReferencesUndoableCommand::commandName("Clear All References"); -const MString ClearAllReferencesUndoableCommand::cancelRemoval("No"); +const MString ClearAllReferencesUndoableCommand::cancelRemoval("No"); std::vector> _computeLoadAndUnloadItems(const UsdPrim& prim) @@ -338,7 +335,7 @@ _computeLoadAndUnloadItems(const UsdPrim& prim) return itemLabelPairs; } - UsdStageWeakPtr stage = prim.GetStage(); + UsdStageWeakPtr stage = prim.GetStage(); const SdfPathSet stageLoadSet = stage->GetLoadSet(); const SdfPathSet loadableSet = stage->FindLoadable(prim.GetPath()); @@ -347,8 +344,10 @@ _computeLoadAndUnloadItems(const UsdPrim& prim) // contain all paths that are loaded at or below this prim path. SdfPathSet loadedSet; std::set_intersection( - loadableSet.cbegin(), loadableSet.cend(), - stageLoadSet.cbegin(), stageLoadSet.cend(), + loadableSet.cbegin(), + loadableSet.cend(), + stageLoadSet.cbegin(), + stageLoadSet.cend(), std::inserter(loadedSet, loadedSet.end())); // Subtract the set of what *is* loaded on the stage from the set of what @@ -357,16 +356,17 @@ _computeLoadAndUnloadItems(const UsdPrim& prim) // below this prim path. SdfPathSet unloadedSet; std::set_difference( - loadableSet.cbegin(), loadableSet.cend(), - stageLoadSet.cbegin(), stageLoadSet.cend(), + loadableSet.cbegin(), + loadableSet.cend(), + stageLoadSet.cbegin(), + stageLoadSet.cend(), std::inserter(unloadedSet, unloadedSet.end())); if (!unloadedSet.empty()) { // Loading without descendants is only meaningful for context ops when // the current prim has an unloaded payload. if (prim.HasPayload() && !prim.IsLoaded()) { - itemLabelPairs.emplace_back( - std::make_pair(kUSDLoadItem, kUSDLoadLabel)); + itemLabelPairs.emplace_back(std::make_pair(kUSDLoadItem, kUSDLoadLabel)); } // We always add an item for loading with descendants when there are @@ -380,69 +380,53 @@ _computeLoadAndUnloadItems(const UsdPrim& prim) // - The current prim does not have a payload, so there must be paths // below it that are still unloaded. itemLabelPairs.emplace_back( - std::make_pair( - kUSDLoadWithDescendantsItem, - kUSDLoadWithDescendantsLabel)); + std::make_pair(kUSDLoadWithDescendantsItem, kUSDLoadWithDescendantsLabel)); } // If anything is loaded at this prim path or any of its descendants, add // an item for unload. if (!loadedSet.empty()) { - itemLabelPairs.emplace_back( - std::make_pair(kUSDUnloadItem, kUSDUnloadLabel)); + itemLabelPairs.emplace_back(std::make_pair(kUSDUnloadItem, kUSDUnloadLabel)); } return itemLabelPairs; } -} +} // namespace namespace MAYAUSD_NS_DEF { namespace ufe { UsdContextOps::UsdContextOps(const UsdSceneItem::Ptr& item) - : Ufe::ContextOps() + : Ufe::ContextOps() , fItem(item) { } -UsdContextOps::~UsdContextOps() -{ -} +UsdContextOps::~UsdContextOps() { } /*static*/ UsdContextOps::Ptr UsdContextOps::create(const UsdSceneItem::Ptr& item) { - return std::make_shared(item); + return std::make_shared(item); } -void UsdContextOps::setItem(const UsdSceneItem::Ptr& item) -{ - fItem = item; -} +void UsdContextOps::setItem(const UsdSceneItem::Ptr& item) { fItem = item; } -const Ufe::Path& UsdContextOps::path() const -{ - return fItem->path(); -} +const Ufe::Path& UsdContextOps::path() const { return fItem->path(); } //------------------------------------------------------------------------------ // Ufe::ContextOps overrides //------------------------------------------------------------------------------ -Ufe::SceneItem::Ptr UsdContextOps::sceneItem() const -{ - return fItem; -} +Ufe::SceneItem::Ptr UsdContextOps::sceneItem() const { return fItem; } -Ufe::ContextOps::Items UsdContextOps::getItems( - const Ufe::ContextOps::ItemPath& itemPath -) const +Ufe::ContextOps::Items UsdContextOps::getItems(const Ufe::ContextOps::ItemPath& itemPath) const { Ufe::ContextOps::Items items; if (itemPath.empty()) { // Top-level item - USD Layer editor (for all context op types). - int hasLayerEditorCmd{0}; + int hasLayerEditorCmd { 0 }; MGlobal::executeCommand("runTimeCommand -exists UsdLayerEditor", hasLayerEditorCmd); if (hasLayerEditorCmd) { #if UFE_PREVIEW_VERSION_NUM >= 2023 @@ -471,34 +455,35 @@ Ufe::ContextOps::Items UsdContextOps::getItems( // Note: certain prim types such as shaders & materials don't support visibility. auto attributes = Ufe::Attributes::attributes(sceneItem()); if (attributes && attributes->hasAttribute(UsdGeomTokens->visibility)) { - auto visibility = - std::dynamic_pointer_cast( - attributes->attribute(UsdGeomTokens->visibility)); + auto visibility = std::dynamic_pointer_cast( + attributes->attribute(UsdGeomTokens->visibility)); if (visibility) { - auto current = visibility->get(); - const std::string l = (current == UsdGeomTokens->invisible) ? - std::string(kUSDMakeVisibleLabel) : std::string(kUSDMakeInvisibleLabel); + auto current = visibility->get(); + const std::string l = (current == UsdGeomTokens->invisible) + ? std::string(kUSDMakeVisibleLabel) + : std::string(kUSDMakeInvisibleLabel); items.emplace_back(kUSDToggleVisibilityItem, l); } } // Prim active state: - items.emplace_back(kUSDToggleActiveStateItem, prim().IsActive() ? kUSDDeactivatePrimLabel : kUSDActivatePrimLabel); + items.emplace_back( + kUSDToggleActiveStateItem, + prim().IsActive() ? kUSDDeactivatePrimLabel : kUSDActivatePrimLabel); } // Top level item - Add New Prim (for all context op types). - items.emplace_back( - kUSDAddNewPrimItem, kUSDAddNewPrimLabel, Ufe::ContextItem::kHasChildren); + items.emplace_back(kUSDAddNewPrimItem, kUSDAddNewPrimLabel, Ufe::ContextItem::kHasChildren); if (!fIsAGatewayType) { - items.emplace_back(AddReferenceUndoableCommand::commandName, - AddReferenceUndoableCommand::commandName); - items.emplace_back(ClearAllReferencesUndoableCommand::commandName, - ClearAllReferencesUndoableCommand::commandName); + items.emplace_back( + AddReferenceUndoableCommand::commandName, AddReferenceUndoableCommand::commandName); + items.emplace_back( + ClearAllReferencesUndoableCommand::commandName, + ClearAllReferencesUndoableCommand::commandName); } - } - else { + } else { if (itemPath[0] == kUSDVariantSetsItem) { - UsdVariantSets varSets = prim().GetVariantSets(); + UsdVariantSets varSets = prim().GetVariantSets(); std::vector varSetsNames; varSets.GetNames(&varSetsNames); @@ -507,27 +492,31 @@ Ufe::ContextOps::Items UsdContextOps::getItems( for (auto i = varSetsNames.crbegin(); i != varSetsNames.crend(); ++i) { items.emplace_back(*i, *i, Ufe::ContextItem::kHasChildren); } - } - else { + } else { // Variants of a given variant set. Second item in the path is // the variant set name. assert(itemPath.size() == 2u); UsdVariantSet varSet = varSets.GetVariantSet(itemPath[1]); - auto selected = varSet.GetVariantSelection(); + auto selected = varSet.GetVariantSelection(); const auto varNames = varSet.GetVariantNames(); for (const auto& vn : varNames) { const bool checked(vn == selected); - items.emplace_back(vn, vn, Ufe::ContextItem::kNoChildren, - Ufe::ContextItem::kCheckable, checked, - Ufe::ContextItem::kExclusive); + items.emplace_back( + vn, + vn, + Ufe::ContextItem::kNoChildren, + Ufe::ContextItem::kCheckable, + checked, + Ufe::ContextItem::kExclusive); } } // Variants of a variant set - } // Variant sets + } // Variant sets else if (itemPath[0] == kUSDAddNewPrimItem) { #if UFE_PREVIEW_VERSION_NUM >= 2023 - items.emplace_back(kUSDDefPrimItem, kUSDDefPrimLabel, kUSDDefPrimImage); // typeless prim + items.emplace_back( + kUSDDefPrimItem, kUSDDefPrimLabel, kUSDDefPrimImage); // typeless prim items.emplace_back(kUSDScopePrimItem, kUSDScopePrimLabel, kUSDScopePrimImage); items.emplace_back(kUSDXformPrimItem, kUSDXformPrimLabel, kUSDXformPrimImage); items.emplace_back(Ufe::ContextItem::kSeparator); @@ -537,7 +526,7 @@ Ufe::ContextOps::Items UsdContextOps::getItems( items.emplace_back(kUSDCylinderPrimItem, kUSDCylinderPrimLabel, kUSDCylinderPrimImage); items.emplace_back(kUSDSpherePrimItem, kUSDSpherePrimLabel, kUSDSpherePrimImage); #else - items.emplace_back(kUSDDefPrimItem, kUSDDefPrimLabel); // typeless prim + items.emplace_back(kUSDDefPrimItem, kUSDDefPrimLabel); // typeless prim items.emplace_back(kUSDScopePrimItem, kUSDScopePrimLabel); items.emplace_back(kUSDXformPrimItem, kUSDXformPrimLabel); items.emplace_back(Ufe::ContextItem::kSeparator); @@ -561,19 +550,15 @@ Ufe::UndoableCommand::Ptr UsdContextOps::doOpCmd(const ItemPath& itemPath) return nullptr; } - if (itemPath[0u] == kUSDLoadItem || - itemPath[0u] == kUSDLoadWithDescendantsItem) { - const UsdLoadPolicy policy = - (itemPath[0u] == kUSDLoadWithDescendantsItem) ? - UsdLoadWithDescendants : - UsdLoadWithoutDescendants; + if (itemPath[0u] == kUSDLoadItem || itemPath[0u] == kUSDLoadWithDescendantsItem) { + const UsdLoadPolicy policy = (itemPath[0u] == kUSDLoadWithDescendantsItem) + ? UsdLoadWithDescendants + : UsdLoadWithoutDescendants; return std::make_shared(prim(), policy); - } - else if (itemPath[0u] == kUSDUnloadItem) { + } else if (itemPath[0u] == kUSDUnloadItem) { return std::make_shared(prim()); - } - else if (itemPath[0] == kUSDVariantSetsItem) { + } else if (itemPath[0] == kUSDVariantSetsItem) { // Operation is to set a variant in a variant set. Need both the // variant set and the variant as arguments to the operation. if (itemPath.size() != 3u) { @@ -583,8 +568,7 @@ Ufe::UndoableCommand::Ptr UsdContextOps::doOpCmd(const ItemPath& itemPath) // At this point we know we have enough arguments to execute the // operation. - return std::make_shared( - prim(), itemPath); + return std::make_shared(prim(), itemPath); } // Variant sets else if (itemPath[0] == kUSDToggleVisibilityItem) { auto attributes = Ufe::Attributes::attributes(sceneItem()); @@ -594,7 +578,8 @@ Ufe::UndoableCommand::Ptr UsdContextOps::doOpCmd(const ItemPath& itemPath) assert(visibility); auto current = visibility->get(); return visibility->setCmd( - current == UsdGeomTokens->invisible ? UsdGeomTokens->inherited : UsdGeomTokens->invisible); + current == UsdGeomTokens->invisible ? UsdGeomTokens->inherited + : UsdGeomTokens->invisible); } // Visibility else if (itemPath[0] == kUSDToggleActiveStateItem) { return std::make_shared(prim()); @@ -609,23 +594,19 @@ Ufe::UndoableCommand::Ptr UsdContextOps::doOpCmd(const ItemPath& itemPath) // At this point we know we have 2 arguments to execute the operation. // itemPath[1] contains the new prim type to create. return UsdUndoAddNewPrimCommand::create(fItem, itemPath[1], itemPath[1]); - } - else if (itemPath[0] == kUSDLayerEditorItem) { + } else if (itemPath[0] == kUSDLayerEditorItem) { // Just open the editor directly and return null so we don't have undo. MGlobal::executeCommand("UsdLayerEditor"); return nullptr; - } - else if (itemPath[0] == AddReferenceUndoableCommand::commandName) { + } else if (itemPath[0] == AddReferenceUndoableCommand::commandName) { MString fileRef = MGlobal::executeCommandStringResult(selectUSDFileScript); std::string path = UsdMayaUtil::convert(fileRef); if (path.empty()) return nullptr; - return std::make_shared( - prim(), path); - } - else if (itemPath[0] == ClearAllReferencesUndoableCommand::commandName) { + return std::make_shared(prim(), path); + } else if (itemPath[0] == ClearAllReferencesUndoableCommand::commandName) { MString confirmation = MGlobal::executeCommandStringResult(clearAllReferencesConfirmScript); if (ClearAllReferencesUndoableCommand::cancelRemoval == confirmation) return nullptr; @@ -637,4 +618,4 @@ Ufe::UndoableCommand::Ptr UsdContextOps::doOpCmd(const ItemPath& itemPath) } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdContextOps.h b/lib/mayaUsd/ufe/UsdContextOps.h index 34103a6c97..b05ed48262 100644 --- a/lib/mayaUsd/ufe/UsdContextOps.h +++ b/lib/mayaUsd/ufe/UsdContextOps.h @@ -15,13 +15,13 @@ // #pragma once -#include -#include +#include +#include #include -#include -#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -40,40 +40,44 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdContextOps : public Ufe::ContextOps { public: - typedef std::shared_ptr Ptr; - - UsdContextOps(const UsdSceneItem::Ptr& item); - ~UsdContextOps() override; - - // Delete the copy/move constructors assignment operators. - UsdContextOps(const UsdContextOps&) = delete; - UsdContextOps& operator=(const UsdContextOps&) = delete; - UsdContextOps(UsdContextOps&&) = delete; - UsdContextOps& operator=(UsdContextOps&&) = delete; - - //! Create a UsdContextOps. - static UsdContextOps::Ptr create(const UsdSceneItem::Ptr& item); - - void setItem(const UsdSceneItem::Ptr& item); - const Ufe::Path& path() const; - inline UsdPrim prim() const { TF_AXIOM(fItem != nullptr); return fItem->prim(); } - - // When we are created from the ProxyShapeContextOpsHandler we do not have the proper - // Maya UFE scene item. So it won't return the correct node type. Therefore we set - // this flag directly. - void setIsAGatewayType(bool t) { fIsAGatewayType = t; } - bool isAGatewayType() const { return fIsAGatewayType; } - - // Ufe::ContextOps overrides - Ufe::SceneItem::Ptr sceneItem() const override; - Items getItems(const ItemPath& itemPath) const override; + typedef std::shared_ptr Ptr; + + UsdContextOps(const UsdSceneItem::Ptr& item); + ~UsdContextOps() override; + + // Delete the copy/move constructors assignment operators. + UsdContextOps(const UsdContextOps&) = delete; + UsdContextOps& operator=(const UsdContextOps&) = delete; + UsdContextOps(UsdContextOps&&) = delete; + UsdContextOps& operator=(UsdContextOps&&) = delete; + + //! Create a UsdContextOps. + static UsdContextOps::Ptr create(const UsdSceneItem::Ptr& item); + + void setItem(const UsdSceneItem::Ptr& item); + const Ufe::Path& path() const; + inline UsdPrim prim() const + { + TF_AXIOM(fItem != nullptr); + return fItem->prim(); + } + + // When we are created from the ProxyShapeContextOpsHandler we do not have the proper + // Maya UFE scene item. So it won't return the correct node type. Therefore we set + // this flag directly. + void setIsAGatewayType(bool t) { fIsAGatewayType = t; } + bool isAGatewayType() const { return fIsAGatewayType; } + + // Ufe::ContextOps overrides + Ufe::SceneItem::Ptr sceneItem() const override; + Items getItems(const ItemPath& itemPath) const override; Ufe::UndoableCommand::Ptr doOpCmd(const ItemPath& itemPath) override; private: - UsdSceneItem::Ptr fItem; - bool fIsAGatewayType{false}; + UsdSceneItem::Ptr fItem; + bool fIsAGatewayType { false }; }; // UsdContextOps } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdContextOpsHandler.cpp b/lib/mayaUsd/ufe/UsdContextOpsHandler.cpp index 10fc9f9304..175113443b 100644 --- a/lib/mayaUsd/ufe/UsdContextOpsHandler.cpp +++ b/lib/mayaUsd/ufe/UsdContextOpsHandler.cpp @@ -19,17 +19,16 @@ namespace MAYAUSD_NS_DEF { namespace ufe { UsdContextOpsHandler::UsdContextOpsHandler() - : Ufe::ContextOpsHandler() -{} - -UsdContextOpsHandler::~UsdContextOpsHandler() + : Ufe::ContextOpsHandler() { } +UsdContextOpsHandler::~UsdContextOpsHandler() { } + /*static*/ UsdContextOpsHandler::Ptr UsdContextOpsHandler::create() { - return std::make_shared(); + return std::make_shared(); } //------------------------------------------------------------------------------ @@ -38,12 +37,12 @@ UsdContextOpsHandler::Ptr UsdContextOpsHandler::create() Ufe::ContextOps::Ptr UsdContextOpsHandler::contextOps(const Ufe::SceneItem::Ptr& item) const { - UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); + UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); #if !defined(NDEBUG) - assert(usdItem); + assert(usdItem); #endif - return UsdContextOps::create(usdItem); + return UsdContextOps::create(usdItem); } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdContextOpsHandler.h b/lib/mayaUsd/ufe/UsdContextOpsHandler.h index a1bb730aaa..7d8dcd5efb 100644 --- a/lib/mayaUsd/ufe/UsdContextOpsHandler.h +++ b/lib/mayaUsd/ufe/UsdContextOpsHandler.h @@ -15,12 +15,12 @@ // #pragma once -#include - #include #include -//PXR_NAMESPACE_USING_DIRECTIVE +#include + +// PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { namespace ufe { @@ -29,23 +29,23 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdContextOpsHandler : public Ufe::ContextOpsHandler { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdContextOpsHandler(); - ~UsdContextOpsHandler() override; + UsdContextOpsHandler(); + ~UsdContextOpsHandler() override; - // Delete the copy/move constructors assignment operators. - UsdContextOpsHandler(const UsdContextOpsHandler&) = delete; - UsdContextOpsHandler& operator=(const UsdContextOpsHandler&) = delete; - UsdContextOpsHandler(UsdContextOpsHandler&&) = delete; - UsdContextOpsHandler& operator=(UsdContextOpsHandler&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdContextOpsHandler(const UsdContextOpsHandler&) = delete; + UsdContextOpsHandler& operator=(const UsdContextOpsHandler&) = delete; + UsdContextOpsHandler(UsdContextOpsHandler&&) = delete; + UsdContextOpsHandler& operator=(UsdContextOpsHandler&&) = delete; - //! Create a UsdContextOpsHandler. - static UsdContextOpsHandler::Ptr create(); + //! Create a UsdContextOpsHandler. + static UsdContextOpsHandler::Ptr create(); - // Ufe::ContextOpsHandler overrides - Ufe::ContextOps::Ptr contextOps(const Ufe::SceneItem::Ptr& item) const override; + // Ufe::ContextOpsHandler overrides + Ufe::ContextOps::Ptr contextOps(const Ufe::SceneItem::Ptr& item) const override; }; // UsdContextOpsHandler } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdHierarchy.cpp b/lib/mayaUsd/ufe/UsdHierarchy.cpp index f3895d6415..ad81ab96f7 100644 --- a/lib/mayaUsd/ufe/UsdHierarchy.cpp +++ b/lib/mayaUsd/ufe/UsdHierarchy.cpp @@ -15,26 +15,26 @@ // #include "UsdHierarchy.h" -#include -#include +#include "private/UfeNotifGuard.h" +#include "private/Utils.h" -#include -#include -#include +#include +#include +#include +#include #include #include -#include -#include #include -#include -#include +#include +#include +#include #include -#include "private/UfeNotifGuard.h" -#include "private/Utils.h" +#include +#include #ifdef UFE_V2_FEATURES_AVAILABLE #include @@ -43,65 +43,50 @@ #endif namespace { - UsdPrimSiblingRange getUSDFilteredChildren(const UsdPrim& prim, const Usd_PrimFlagsPredicate pred = UsdPrimDefaultPredicate) - { - // We need to be able to traverse down to instance proxies, so turn - // on that part of the predicate, since by default, it is off. Since - // the equivalent of GetChildren is - // GetFilteredChildren( UsdPrimDefaultPredicate ), - // we will use that as the initial value. - // - return prim.GetFilteredChildren(UsdTraverseInstanceProxies(pred)); - } +UsdPrimSiblingRange getUSDFilteredChildren( + const UsdPrim& prim, + const Usd_PrimFlagsPredicate pred = UsdPrimDefaultPredicate) +{ + // We need to be able to traverse down to instance proxies, so turn + // on that part of the predicate, since by default, it is off. Since + // the equivalent of GetChildren is + // GetFilteredChildren( UsdPrimDefaultPredicate ), + // we will use that as the initial value. + // + return prim.GetFilteredChildren(UsdTraverseInstanceProxies(pred)); } +} // namespace namespace MAYAUSD_NS_DEF { namespace ufe { UsdHierarchy::UsdHierarchy(const UsdSceneItem::Ptr& item) - : Ufe::Hierarchy() + : Ufe::Hierarchy() , fItem(item) { } -UsdHierarchy::~UsdHierarchy() -{ -} +UsdHierarchy::~UsdHierarchy() { } /*static*/ UsdHierarchy::Ptr UsdHierarchy::create(const UsdSceneItem::Ptr& item) { - return std::make_shared(item); + return std::make_shared(item); } -void UsdHierarchy::setItem(const UsdSceneItem::Ptr& item) -{ - fItem = item; -} +void UsdHierarchy::setItem(const UsdSceneItem::Ptr& item) { fItem = item; } -const Ufe::Path& UsdHierarchy::path() const -{ - return fItem->path(); -} +const Ufe::Path& UsdHierarchy::path() const { return fItem->path(); } -UsdSceneItem::Ptr UsdHierarchy::usdSceneItem() const -{ - return fItem; -} +UsdSceneItem::Ptr UsdHierarchy::usdSceneItem() const { return fItem; } //------------------------------------------------------------------------------ // Ufe::Hierarchy overrides //------------------------------------------------------------------------------ -Ufe::SceneItem::Ptr UsdHierarchy::sceneItem() const -{ - return fItem; -} +Ufe::SceneItem::Ptr UsdHierarchy::sceneItem() const { return fItem; } -bool UsdHierarchy::hasChildren() const -{ - return !getUSDFilteredChildren(prim()).empty(); -} +bool UsdHierarchy::hasChildren() const { return !getUSDFilteredChildren(prim()).empty(); } Ufe::SceneItemList UsdHierarchy::children() const { @@ -114,11 +99,11 @@ Ufe::SceneItemList UsdHierarchy::filteredChildren(const ChildFilter& childFilter { // Note: for now the only child filter flag we support is "Inactive Prims". // See UsdHierarchyHandler::childFilter() - if ((childFilter.size() == 1) && (childFilter.front().name == "InactivePrims")) - { + if ((childFilter.size() == 1) && (childFilter.front().name == "InactivePrims")) { // See uniqueChildName() for explanation of USD filter predicate. - Usd_PrimFlagsPredicate flags = childFilter.front().value ? UsdPrimIsDefined && !UsdPrimIsAbstract - : UsdPrimDefaultPredicate; + Usd_PrimFlagsPredicate flags = childFilter.front().value + ? UsdPrimIsDefined && !UsdPrimIsAbstract + : UsdPrimDefaultPredicate; return createUFEChildList(getUSDFilteredChildren(prim(), flags)); } @@ -132,8 +117,7 @@ Ufe::SceneItemList UsdHierarchy::createUFEChildList(const UsdPrimSiblingRange& r { // Return UFE child list from input USD child list. Ufe::SceneItemList children; - for (const auto& child : range) - { + for (const auto& child : range) { children.emplace_back(UsdSceneItem::create(fItem->path() + child.GetName(), child)); } return children; @@ -141,101 +125,101 @@ Ufe::SceneItemList UsdHierarchy::createUFEChildList(const UsdPrimSiblingRange& r Ufe::SceneItem::Ptr UsdHierarchy::parent() const { - return UsdSceneItem::create(fItem->path().pop(), prim().GetParent()); + return UsdSceneItem::create(fItem->path().pop(), prim().GetParent()); } #ifndef UFE_V2_FEATURES_AVAILABLE // UFE v1 specific method Ufe::AppendedChild UsdHierarchy::appendChild(const Ufe::SceneItem::Ptr& child) { - auto usdChild = std::dynamic_pointer_cast(child); + auto usdChild = std::dynamic_pointer_cast(child); #if !defined(NDEBUG) - assert(usdChild); + assert(usdChild); #endif - // First, check if we need to rename the child. - std::string childName = uniqueChildName(fItem->prim(), child->path().back().string()); - - // Set up all paths to perform the reparent. - auto childPrim = usdChild->prim(); - auto stage = childPrim.GetStage(); - auto ufeSrcPath = usdChild->path(); - auto usdSrcPath = childPrim.GetPath(); - auto ufeDstPath = fItem->path() + childName; - auto usdDstPath = prim().GetPath().AppendChild(TfToken(childName)); - SdfLayerHandle layer = MayaUsdUtils::defPrimSpecLayer(childPrim); - if (!layer) { - std::string err = TfStringPrintf("No prim found at %s", usdSrcPath.GetString().c_str()); - throw std::runtime_error(err.c_str()); - } - - // In USD, reparent is implemented like rename, using copy to - // destination, then remove from source. - // See UsdUndoRenameCommand._rename comments for details. - InPathChange pc; - - auto status = SdfCopySpec(layer, usdSrcPath, layer, usdDstPath); - if (!status) { - std::string err = TfStringPrintf("Appending child %s to parent %s failed.", - ufeSrcPath.string().c_str(), fItem->path().string().c_str()); - throw std::runtime_error(err.c_str()); - } - - stage->RemovePrim(usdSrcPath); - auto ufeDstItem = UsdSceneItem::create(ufeDstPath, ufePathToPrim(ufeDstPath)); - - sendNotification(ufeDstItem, ufeSrcPath); - - // FIXME No idea how to get the child prim index yet. PPT, 16-Aug-2018. - return Ufe::AppendedChild(ufeDstItem, ufeSrcPath, 0); + // First, check if we need to rename the child. + std::string childName = uniqueChildName(fItem->prim(), child->path().back().string()); + + // Set up all paths to perform the reparent. + auto childPrim = usdChild->prim(); + auto stage = childPrim.GetStage(); + auto ufeSrcPath = usdChild->path(); + auto usdSrcPath = childPrim.GetPath(); + auto ufeDstPath = fItem->path() + childName; + auto usdDstPath = prim().GetPath().AppendChild(TfToken(childName)); + SdfLayerHandle layer = MayaUsdUtils::defPrimSpecLayer(childPrim); + if (!layer) { + std::string err = TfStringPrintf("No prim found at %s", usdSrcPath.GetString().c_str()); + throw std::runtime_error(err.c_str()); + } + + // In USD, reparent is implemented like rename, using copy to + // destination, then remove from source. + // See UsdUndoRenameCommand._rename comments for details. + InPathChange pc; + + auto status = SdfCopySpec(layer, usdSrcPath, layer, usdDstPath); + if (!status) { + std::string err = TfStringPrintf( + "Appending child %s to parent %s failed.", + ufeSrcPath.string().c_str(), + fItem->path().string().c_str()); + throw std::runtime_error(err.c_str()); + } + + stage->RemovePrim(usdSrcPath); + auto ufeDstItem = UsdSceneItem::create(ufeDstPath, ufePathToPrim(ufeDstPath)); + + sendNotification(ufeDstItem, ufeSrcPath); + + // FIXME No idea how to get the child prim index yet. PPT, 16-Aug-2018. + return Ufe::AppendedChild(ufeDstItem, ufeSrcPath, 0); } #endif #ifdef UFE_V2_FEATURES_AVAILABLE -Ufe::InsertChildCommand::Ptr UsdHierarchy::insertChildCmd( - const Ufe::SceneItem::Ptr& child, - const Ufe::SceneItem::Ptr& pos -) +Ufe::InsertChildCommand::Ptr +UsdHierarchy::insertChildCmd(const Ufe::SceneItem::Ptr& child, const Ufe::SceneItem::Ptr& pos) { - return UsdUndoInsertChildCommand::create( - fItem, downcast(child), downcast(pos)); + return UsdUndoInsertChildCommand::create(fItem, downcast(child), downcast(pos)); } -Ufe::SceneItem::Ptr UsdHierarchy::insertChild( - const Ufe::SceneItem::Ptr& child, - const Ufe::SceneItem::Ptr& pos -) +Ufe::SceneItem::Ptr +UsdHierarchy::insertChild(const Ufe::SceneItem::Ptr& child, const Ufe::SceneItem::Ptr& pos) { auto insertChildCommand = insertChildCmd(child, pos); return insertChildCommand->insertedChild(); } // Create a transform. -Ufe::SceneItem::Ptr UsdHierarchy::createGroup(const Ufe::Selection& selection, const Ufe::PathComponent& name) const +Ufe::SceneItem::Ptr +UsdHierarchy::createGroup(const Ufe::Selection& selection, const Ufe::PathComponent& name) const { - Ufe::SceneItem::Ptr createdItem = nullptr; + Ufe::SceneItem::Ptr createdItem = nullptr; - UsdUndoCreateGroupCommand::Ptr cmd = UsdUndoCreateGroupCommand::create(fItem, selection, name.string()); - if (cmd) { - cmd->execute(); - createdItem = cmd->group(); - } + UsdUndoCreateGroupCommand::Ptr cmd + = UsdUndoCreateGroupCommand::create(fItem, selection, name.string()); + if (cmd) { + cmd->execute(); + createdItem = cmd->group(); + } - return createdItem; + return createdItem; } -Ufe::UndoableCommand::Ptr UsdHierarchy::createGroupCmd(const Ufe::Selection& selection, const Ufe::PathComponent& name) const +Ufe::UndoableCommand::Ptr +UsdHierarchy::createGroupCmd(const Ufe::Selection& selection, const Ufe::PathComponent& name) const { - return UsdUndoCreateGroupCommand::create(fItem, selection, name.string()); + return UsdUndoCreateGroupCommand::create(fItem, selection, name.string()); } Ufe::SceneItem::Ptr UsdHierarchy::defaultParent() const { // Default parent for USD nodes is the pseudo-root of their stage, which is // represented by the proxy shape. - auto path = fItem->path(); + auto path = fItem->path(); #if !defined(NDEBUG) - assert(path.nbSegments() == 2); + assert(path.nbSegments() == 2); #endif auto proxyShapePath = path.popSegment(); return createItem(proxyShapePath); @@ -244,18 +228,18 @@ Ufe::SceneItem::Ptr UsdHierarchy::defaultParent() const #if UFE_PREVIEW_VERSION_NUM >= 2026 Ufe::UndoableCommand::Ptr UsdHierarchy::reorderCmd(const Ufe::SceneItemList& orderedList) const { - std::vector orderedTokens; + std::vector orderedTokens; - for (const auto& item : orderedList) { - orderedTokens.emplace_back(downcast(item)->prim().GetPath().GetNameToken()); - } + for (const auto& item : orderedList) { + orderedTokens.emplace_back(downcast(item)->prim().GetPath().GetNameToken()); + } - // create a reorder command and pass in the parent and its reordered children list - return UsdUndoReorderCommand::create(downcast(sceneItem())->prim(), orderedTokens); + // create a reorder command and pass in the parent and its reordered children list + return UsdUndoReorderCommand::create(downcast(sceneItem())->prim(), orderedTokens); } #endif #endif // UFE_V2_FEATURES_AVAILABLE } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdHierarchy.h b/lib/mayaUsd/ufe/UsdHierarchy.h index aa14a57bc9..8f9a332731 100644 --- a/lib/mayaUsd/ufe/UsdHierarchy.h +++ b/lib/mayaUsd/ufe/UsdHierarchy.h @@ -15,13 +15,13 @@ // #pragma once +#include +#include + #include #include #include -#include -#include - namespace MAYAUSD_NS_DEF { namespace ufe { @@ -33,46 +33,54 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdHierarchy : public Ufe::Hierarchy { public: - typedef std::shared_ptr Ptr; - - UsdHierarchy(const UsdSceneItem::Ptr& item); - ~UsdHierarchy() override; - - // Delete the copy/move constructors assignment operators. - UsdHierarchy(const UsdHierarchy&) = delete; - UsdHierarchy& operator=(const UsdHierarchy&) = delete; - UsdHierarchy(UsdHierarchy&&) = delete; - UsdHierarchy& operator=(UsdHierarchy&&) = delete; - - //! Create a UsdHierarchy. - static UsdHierarchy::Ptr create(const UsdSceneItem::Ptr& item); - - void setItem(const UsdSceneItem::Ptr& item); - const Ufe::Path& path() const; - inline UsdPrim prim() const { TF_AXIOM(fItem != nullptr); return fItem->prim(); } - - UsdSceneItem::Ptr usdSceneItem() const; - - // Ufe::Hierarchy overrides - Ufe::SceneItem::Ptr sceneItem() const override; - bool hasChildren() const override; - Ufe::SceneItemList children() const override; + typedef std::shared_ptr Ptr; + + UsdHierarchy(const UsdSceneItem::Ptr& item); + ~UsdHierarchy() override; + + // Delete the copy/move constructors assignment operators. + UsdHierarchy(const UsdHierarchy&) = delete; + UsdHierarchy& operator=(const UsdHierarchy&) = delete; + UsdHierarchy(UsdHierarchy&&) = delete; + UsdHierarchy& operator=(UsdHierarchy&&) = delete; + + //! Create a UsdHierarchy. + static UsdHierarchy::Ptr create(const UsdSceneItem::Ptr& item); + + void setItem(const UsdSceneItem::Ptr& item); + const Ufe::Path& path() const; + inline UsdPrim prim() const + { + TF_AXIOM(fItem != nullptr); + return fItem->prim(); + } + + UsdSceneItem::Ptr usdSceneItem() const; + + // Ufe::Hierarchy overrides + Ufe::SceneItem::Ptr sceneItem() const override; + bool hasChildren() const override; + Ufe::SceneItemList children() const override; #if UFE_PREVIEW_VERSION_NUM >= 2022 UFE_V2(Ufe::SceneItemList filteredChildren(const ChildFilter&) const override;) #endif - Ufe::SceneItem::Ptr parent() const override; + Ufe::SceneItem::Ptr parent() const override; #ifndef UFE_V2_FEATURES_AVAILABLE - Ufe::AppendedChild appendChild(const Ufe::SceneItem::Ptr& child) override; + Ufe::AppendedChild appendChild(const Ufe::SceneItem::Ptr& child) override; #endif #ifdef UFE_V2_FEATURES_AVAILABLE - Ufe::SceneItem::Ptr createGroup(const Ufe::Selection& selection, const Ufe::PathComponent& name) const override; - Ufe::UndoableCommand::Ptr createGroupCmd(const Ufe::Selection& selection, const Ufe::PathComponent& name) const override; + Ufe::SceneItem::Ptr + createGroup(const Ufe::Selection& selection, const Ufe::PathComponent& name) const override; + Ufe::UndoableCommand::Ptr + createGroupCmd(const Ufe::Selection& selection, const Ufe::PathComponent& name) const override; Ufe::SceneItem::Ptr defaultParent() const override; - Ufe::SceneItem::Ptr insertChild(const Ufe::SceneItem::Ptr& child,const Ufe::SceneItem::Ptr& pos) override; - Ufe::InsertChildCommand::Ptr insertChildCmd(const Ufe::SceneItem::Ptr& child, const Ufe::SceneItem::Ptr& pos) override; + Ufe::SceneItem::Ptr + insertChild(const Ufe::SceneItem::Ptr& child, const Ufe::SceneItem::Ptr& pos) override; + Ufe::InsertChildCommand::Ptr + insertChildCmd(const Ufe::SceneItem::Ptr& child, const Ufe::SceneItem::Ptr& pos) override; #if UFE_PREVIEW_VERSION_NUM >= 2026 Ufe::UndoableCommand::Ptr reorderCmd(const Ufe::SceneItemList& orderedList) const override; @@ -83,9 +91,9 @@ class MAYAUSD_CORE_PUBLIC UsdHierarchy : public Ufe::Hierarchy Ufe::SceneItemList createUFEChildList(const UsdPrimSiblingRange& range) const; private: - UsdSceneItem::Ptr fItem; + UsdSceneItem::Ptr fItem; }; // UsdHierarchy } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdHierarchyHandler.cpp b/lib/mayaUsd/ufe/UsdHierarchyHandler.cpp index c8f7b5d958..a67a885c66 100644 --- a/lib/mayaUsd/ufe/UsdHierarchyHandler.cpp +++ b/lib/mayaUsd/ufe/UsdHierarchyHandler.cpp @@ -22,17 +22,16 @@ namespace MAYAUSD_NS_DEF { namespace ufe { UsdHierarchyHandler::UsdHierarchyHandler() - : Ufe::HierarchyHandler() -{} - -UsdHierarchyHandler::~UsdHierarchyHandler() + : Ufe::HierarchyHandler() { } +UsdHierarchyHandler::~UsdHierarchyHandler() { } + /*static*/ UsdHierarchyHandler::Ptr UsdHierarchyHandler::create() { - return std::make_shared(); + return std::make_shared(); } //------------------------------------------------------------------------------ @@ -41,27 +40,27 @@ UsdHierarchyHandler::Ptr UsdHierarchyHandler::create() Ufe::Hierarchy::Ptr UsdHierarchyHandler::hierarchy(const Ufe::SceneItem::Ptr& item) const { - UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); - return isRootChild(usdItem->path()) ? - UsdRootChildHierarchy::create(usdItem) : UsdHierarchy::create(usdItem); + UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); + return isRootChild(usdItem->path()) ? UsdRootChildHierarchy::create(usdItem) + : UsdHierarchy::create(usdItem); } Ufe::SceneItem::Ptr UsdHierarchyHandler::createItem(const Ufe::Path& path) const { - const UsdPrim prim = ufePathToPrim(path); - return prim.IsValid() ? UsdSceneItem::create(path, prim) : nullptr; + const UsdPrim prim = ufePathToPrim(path); + return prim.IsValid() ? UsdSceneItem::create(path, prim) : nullptr; } #ifdef UFE_V2_FEATURES_AVAILABLE #if UFE_PREVIEW_VERSION_NUM >= 2022 Ufe::Hierarchy::ChildFilter UsdHierarchyHandler::childFilter() const { - Ufe::Hierarchy::ChildFilter childFilters; - childFilters.emplace_back("InactivePrims", "Inactive Prims", true); - return childFilters; + Ufe::Hierarchy::ChildFilter childFilters; + childFilters.emplace_back("InactivePrims", "Inactive Prims", true); + return childFilters; } #endif #endif } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdHierarchyHandler.h b/lib/mayaUsd/ufe/UsdHierarchyHandler.h index ae23b3ab91..d4eb17f561 100644 --- a/lib/mayaUsd/ufe/UsdHierarchyHandler.h +++ b/lib/mayaUsd/ufe/UsdHierarchyHandler.h @@ -15,49 +15,49 @@ // #pragma once -#include - #include #include #include -//PXR_NAMESPACE_USING_DIRECTIVE +#include + +// PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { namespace ufe { //! \brief USD run-time hierarchy handler. /*! - This hierarchy handler is the standard USD run-time hierarchy handler. Its - only special behavior is to return a UsdRootChildHierarchy interface object - if it is asked for a hierarchy interface for a child of the USD root prim. - These prims are special because we define their parent to be the Maya USD - gateway node, which the UsdRootChildHierarchy interface implements. + This hierarchy handler is the standard USD run-time hierarchy handler. Its + only special behavior is to return a UsdRootChildHierarchy interface object + if it is asked for a hierarchy interface for a child of the USD root prim. + These prims are special because we define their parent to be the Maya USD + gateway node, which the UsdRootChildHierarchy interface implements. */ class MAYAUSD_CORE_PUBLIC UsdHierarchyHandler : public Ufe::HierarchyHandler { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdHierarchyHandler(); - ~UsdHierarchyHandler() override; + UsdHierarchyHandler(); + ~UsdHierarchyHandler() override; - // Delete the copy/move constructors assignment operators. - UsdHierarchyHandler(const UsdHierarchyHandler&) = delete; - UsdHierarchyHandler& operator=(const UsdHierarchyHandler&) = delete; - UsdHierarchyHandler(UsdHierarchyHandler&&) = delete; - UsdHierarchyHandler& operator=(UsdHierarchyHandler&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdHierarchyHandler(const UsdHierarchyHandler&) = delete; + UsdHierarchyHandler& operator=(const UsdHierarchyHandler&) = delete; + UsdHierarchyHandler(UsdHierarchyHandler&&) = delete; + UsdHierarchyHandler& operator=(UsdHierarchyHandler&&) = delete; - //! Create a UsdHierarchyHandler. - static UsdHierarchyHandler::Ptr create(); + //! Create a UsdHierarchyHandler. + static UsdHierarchyHandler::Ptr create(); - // UsdHierarchyHandler overrides - Ufe::Hierarchy::Ptr hierarchy(const Ufe::SceneItem::Ptr& item) const override; - Ufe::SceneItem::Ptr createItem(const Ufe::Path& path) const override; + // UsdHierarchyHandler overrides + Ufe::Hierarchy::Ptr hierarchy(const Ufe::SceneItem::Ptr& item) const override; + Ufe::SceneItem::Ptr createItem(const Ufe::Path& path) const override; #if UFE_PREVIEW_VERSION_NUM >= 2022 UFE_V2(Ufe::Hierarchy::ChildFilter childFilter() const override;) #endif }; // UsdHierarchyHandler } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdObject3d.cpp b/lib/mayaUsd/ufe/UsdObject3d.cpp index ad4ee71b92..a03c144bd7 100644 --- a/lib/mayaUsd/ufe/UsdObject3d.cpp +++ b/lib/mayaUsd/ufe/UsdObject3d.cpp @@ -15,64 +15,63 @@ // #include "UsdObject3d.h" -#include -#include - -#include +#include -#include #include +#include #include -#include +#include +#include + +#include namespace { -Ufe::Vector3d toVector3d(const GfVec3d& v) -{ - return Ufe::Vector3d(v[0], v[1], v[2]); -} +Ufe::Vector3d toVector3d(const GfVec3d& v) { return Ufe::Vector3d(v[0], v[1], v[2]); } Ufe::AttributeEnumString::Ptr getVisibilityAttribute(Ufe::SceneItem::Ptr item) { auto objAttrs = Ufe::Attributes::attributes(item); - if (objAttrs) - { - auto visAttr = std::dynamic_pointer_cast(objAttrs->attribute(UsdGeomTokens->visibility)); + if (objAttrs) { + auto visAttr = std::dynamic_pointer_cast( + objAttrs->attribute(UsdGeomTokens->visibility)); if (visAttr) - return visAttr; + return visAttr; } // Getting here is considered a serious error. In UsdObject3dHandler::object3d() // we only create and return a valid Ufe::Object3d interface for imageable geometry. // Those kind of prims must have a visibility attribute. - std::string err = TfStringPrintf("Could not get visibility attribute for Object3d: %s", item->path().string().c_str()); + std::string err = TfStringPrintf( + "Could not get visibility attribute for Object3d: %s", item->path().string().c_str()); throw std::runtime_error(err.c_str()); } -} +} // namespace namespace MAYAUSD_NS_DEF { namespace ufe { UsdObject3d::UsdObject3d(const UsdSceneItem::Ptr& item) - : Ufe::Object3d(), fItem(item), fPrim(item->prim()) {} + : Ufe::Object3d() + , fItem(item) + , fPrim(item->prim()) +{ +} -UsdObject3d::~UsdObject3d() {} +UsdObject3d::~UsdObject3d() { } /*static*/ UsdObject3d::Ptr UsdObject3d::create(const UsdSceneItem::Ptr& item) { - return std::make_shared(item); + return std::make_shared(item); } //------------------------------------------------------------------------------ // Ufe::Object3d overrides //------------------------------------------------------------------------------ -Ufe::SceneItem::Ptr UsdObject3d::sceneItem() const -{ - return fItem; -} +Ufe::SceneItem::Ptr UsdObject3d::sceneItem() const { return fItem; } Ufe::BBox3d UsdObject3d::boundingBox() const { @@ -90,11 +89,12 @@ Ufe::BBox3d UsdObject3d::boundingBox() const // we can bypass time computation and simply use UsdTimeCode::Default() // as the time. - auto bbox = UsdGeomImageable(fPrim).ComputeUntransformedBound(getTime(sceneItem()->path()), UsdGeomTokens->default_); + auto bbox = UsdGeomImageable(fPrim).ComputeUntransformedBound( + getTime(sceneItem()->path()), UsdGeomTokens->default_); auto range = bbox.ComputeAlignedRange(); auto min = range.GetMin(); auto max = range.GetMax(); - return Ufe::BBox3d(toVector3d(min), toVector3d(max)); + return Ufe::BBox3d(toVector3d(min), toVector3d(max)); } bool UsdObject3d::visibility() const @@ -115,4 +115,4 @@ void UsdObject3d::setVisibility(bool vis) } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdObject3d.h b/lib/mayaUsd/ufe/UsdObject3d.h index d2ac83c59b..528b1e139b 100644 --- a/lib/mayaUsd/ufe/UsdObject3d.h +++ b/lib/mayaUsd/ufe/UsdObject3d.h @@ -7,11 +7,11 @@ // =========================================================================== #pragma once -#include - #include #include +#include + namespace MAYAUSD_NS_DEF { namespace ufe { @@ -22,31 +22,31 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdObject3d : public Ufe::Object3d { public: - using Ptr = std::shared_ptr; + using Ptr = std::shared_ptr; - UsdObject3d(const UsdSceneItem::Ptr& item); - ~UsdObject3d() override; + UsdObject3d(const UsdSceneItem::Ptr& item); + ~UsdObject3d() override; - // Delete the copy/move constructors assignment operators. - UsdObject3d(const UsdObject3d&) = delete; - UsdObject3d& operator=(const UsdObject3d&) = delete; - UsdObject3d(UsdObject3d&&) = delete; - UsdObject3d& operator=(UsdObject3d&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdObject3d(const UsdObject3d&) = delete; + UsdObject3d& operator=(const UsdObject3d&) = delete; + UsdObject3d(UsdObject3d&&) = delete; + UsdObject3d& operator=(UsdObject3d&&) = delete; - //! Create a UsdObject3d. - static UsdObject3d::Ptr create(const UsdSceneItem::Ptr& item); + //! Create a UsdObject3d. + static UsdObject3d::Ptr create(const UsdSceneItem::Ptr& item); - // Ufe::Object3d overrides - Ufe::SceneItem::Ptr sceneItem() const override; - Ufe::BBox3d boundingBox() const override; - bool visibility() const override; - void setVisibility(bool vis) override; + // Ufe::Object3d overrides + Ufe::SceneItem::Ptr sceneItem() const override; + Ufe::BBox3d boundingBox() const override; + bool visibility() const override; + void setVisibility(bool vis) override; private: - UsdSceneItem::Ptr fItem; - UsdPrim fPrim; + UsdSceneItem::Ptr fItem; + UsdPrim fPrim; }; // UsdObject3d } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdObject3dHandler.cpp b/lib/mayaUsd/ufe/UsdObject3dHandler.cpp index d1f3373fb9..7d41f6ab56 100644 --- a/lib/mayaUsd/ufe/UsdObject3dHandler.cpp +++ b/lib/mayaUsd/ufe/UsdObject3dHandler.cpp @@ -8,21 +8,24 @@ #include "UsdObject3dHandler.h" -#include - #include +#include + namespace MAYAUSD_NS_DEF { namespace ufe { -UsdObject3dHandler::UsdObject3dHandler() : Ufe::Object3dHandler() {} +UsdObject3dHandler::UsdObject3dHandler() + : Ufe::Object3dHandler() +{ +} -UsdObject3dHandler::~UsdObject3dHandler() {} +UsdObject3dHandler::~UsdObject3dHandler() { } /*static*/ UsdObject3dHandler::Ptr UsdObject3dHandler::create() { - return std::make_shared(); + return std::make_shared(); } //------------------------------------------------------------------------------ @@ -31,18 +34,19 @@ UsdObject3dHandler::Ptr UsdObject3dHandler::create() Ufe::Object3d::Ptr UsdObject3dHandler::object3d(const Ufe::SceneItem::Ptr& item) const { - UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); + UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); #if !defined(NDEBUG) - assert(usdItem); + assert(usdItem); #endif - // Test if this item is imageable. If not, then we cannot create an object3d - // interface for it, which is a valid case (such as for a material node type). - UsdGeomImageable primSchema(usdItem->prim()); - if (!primSchema) return nullptr; + // Test if this item is imageable. If not, then we cannot create an object3d + // interface for it, which is a valid case (such as for a material node type). + UsdGeomImageable primSchema(usdItem->prim()); + if (!primSchema) + return nullptr; - return UsdObject3d::create(usdItem); + return UsdObject3d::create(usdItem); } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdObject3dHandler.h b/lib/mayaUsd/ufe/UsdObject3dHandler.h index b4f645ed2c..7bea72358f 100644 --- a/lib/mayaUsd/ufe/UsdObject3dHandler.h +++ b/lib/mayaUsd/ufe/UsdObject3dHandler.h @@ -7,39 +7,39 @@ // =========================================================================== #pragma once -#include - #include #include +#include + namespace MAYAUSD_NS_DEF { namespace ufe { //! \brief USD run-time 3D object handler. /*! - Factory object for Object3d interfaces. + Factory object for Object3d interfaces. */ class MAYAUSD_CORE_PUBLIC UsdObject3dHandler : public Ufe::Object3dHandler { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdObject3dHandler(); - ~UsdObject3dHandler() override; + UsdObject3dHandler(); + ~UsdObject3dHandler() override; - // Delete the copy/move constructors assignment operators. - UsdObject3dHandler(const UsdObject3dHandler&) = delete; - UsdObject3dHandler& operator=(const UsdObject3dHandler&) = delete; - UsdObject3dHandler(UsdObject3dHandler&&) = delete; - UsdObject3dHandler& operator=(UsdObject3dHandler&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdObject3dHandler(const UsdObject3dHandler&) = delete; + UsdObject3dHandler& operator=(const UsdObject3dHandler&) = delete; + UsdObject3dHandler(UsdObject3dHandler&&) = delete; + UsdObject3dHandler& operator=(UsdObject3dHandler&&) = delete; - //! Create a UsdObject3dHandler. - static UsdObject3dHandler::Ptr create(); + //! Create a UsdObject3dHandler. + static UsdObject3dHandler::Ptr create(); - // UsdObject3dHandler overrides - Ufe::Object3d::Ptr object3d(const Ufe::SceneItem::Ptr& item) const override; + // UsdObject3dHandler overrides + Ufe::Object3d::Ptr object3d(const Ufe::SceneItem::Ptr& item) const override; }; // UsdObject3dHandler } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdRootChildHierarchy.cpp b/lib/mayaUsd/ufe/UsdRootChildHierarchy.cpp index 6cb3c93f07..66aa42adef 100644 --- a/lib/mayaUsd/ufe/UsdRootChildHierarchy.cpp +++ b/lib/mayaUsd/ufe/UsdRootChildHierarchy.cpp @@ -15,32 +15,30 @@ // #include "UsdRootChildHierarchy.h" -#include - #include +#include + namespace MAYAUSD_NS_DEF { namespace ufe { //------------------------------------------------------------------------------ // Global variables //------------------------------------------------------------------------------ -extern Ufe::Rtid g_MayaRtid; +extern Ufe::Rtid g_MayaRtid; const char* const kNotGatewayNodePath = "Tail of path %s is not a gateway node."; UsdRootChildHierarchy::UsdRootChildHierarchy(const UsdSceneItem::Ptr& item) - : UsdHierarchy(item) + : UsdHierarchy(item) { } -UsdRootChildHierarchy::~UsdRootChildHierarchy() -{ -} +UsdRootChildHierarchy::~UsdRootChildHierarchy() { } /*static*/ UsdRootChildHierarchy::Ptr UsdRootChildHierarchy::create(const UsdSceneItem::Ptr& item) { - return std::make_shared(item); + return std::make_shared(item); } //------------------------------------------------------------------------------ @@ -49,19 +47,19 @@ UsdRootChildHierarchy::Ptr UsdRootChildHierarchy::create(const UsdSceneItem::Ptr Ufe::SceneItem::Ptr UsdRootChildHierarchy::parent() const { - // If we're a child of the root, our parent node in the path is a Maya - // node. Ask the Maya hierarchy interface to create a selection item - // for that path. - auto parentPath = path().pop(); + // If we're a child of the root, our parent node in the path is a Maya + // node. Ask the Maya hierarchy interface to create a selection item + // for that path. + auto parentPath = path().pop(); #if !defined(NDEBUG) - assert(parentPath.runTimeId() == g_MayaRtid); + assert(parentPath.runTimeId() == g_MayaRtid); #endif - if (parentPath.runTimeId() != g_MayaRtid) - TF_WARN(kNotGatewayNodePath, path().string().c_str()); + if (parentPath.runTimeId() != g_MayaRtid) + TF_WARN(kNotGatewayNodePath, path().string().c_str()); - auto mayaHierarchyHandler = Ufe::RunTimeMgr::instance().hierarchyHandler(g_MayaRtid); - return mayaHierarchyHandler->createItem(parentPath); + auto mayaHierarchyHandler = Ufe::RunTimeMgr::instance().hierarchyHandler(g_MayaRtid); + return mayaHierarchyHandler->createItem(parentPath); } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdRootChildHierarchy.h b/lib/mayaUsd/ufe/UsdRootChildHierarchy.h index 1da42e386e..4b793ae407 100644 --- a/lib/mayaUsd/ufe/UsdRootChildHierarchy.h +++ b/lib/mayaUsd/ufe/UsdRootChildHierarchy.h @@ -18,7 +18,7 @@ #include #include -//PXR_NAMESPACE_USING_DIRECTIVE +// PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { namespace ufe { @@ -31,24 +31,24 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdRootChildHierarchy : public UsdHierarchy { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdRootChildHierarchy(const UsdSceneItem::Ptr& item); - ~UsdRootChildHierarchy() override; + UsdRootChildHierarchy(const UsdSceneItem::Ptr& item); + ~UsdRootChildHierarchy() override; - // Delete the copy/move constructors assignment operators. - UsdRootChildHierarchy(const UsdRootChildHierarchy&) = delete; - UsdRootChildHierarchy& operator=(const UsdRootChildHierarchy&) = delete; - UsdRootChildHierarchy(UsdRootChildHierarchy&&) = delete; - UsdRootChildHierarchy& operator=(UsdRootChildHierarchy&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdRootChildHierarchy(const UsdRootChildHierarchy&) = delete; + UsdRootChildHierarchy& operator=(const UsdRootChildHierarchy&) = delete; + UsdRootChildHierarchy(UsdRootChildHierarchy&&) = delete; + UsdRootChildHierarchy& operator=(UsdRootChildHierarchy&&) = delete; - //! Create a UsdRootChildHierarchy. - static UsdRootChildHierarchy::Ptr create(const UsdSceneItem::Ptr& item); + //! Create a UsdRootChildHierarchy. + static UsdRootChildHierarchy::Ptr create(const UsdSceneItem::Ptr& item); - // Ufe::Hierarchy overrides - Ufe::SceneItem::Ptr parent() const override; + // Ufe::Hierarchy overrides + Ufe::SceneItem::Ptr parent() const override; }; // UsdRootChildHierarchy } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdRotatePivotTranslateUndoableCommand.cpp b/lib/mayaUsd/ufe/UsdRotatePivotTranslateUndoableCommand.cpp index c259f2f8c2..4acd3768f2 100644 --- a/lib/mayaUsd/ufe/UsdRotatePivotTranslateUndoableCommand.cpp +++ b/lib/mayaUsd/ufe/UsdRotatePivotTranslateUndoableCommand.cpp @@ -21,56 +21,58 @@ namespace MAYAUSD_NS_DEF { namespace ufe { #ifdef UFE_V2_FEATURES_AVAILABLE -UsdRotatePivotTranslateUndoableCommand::UsdRotatePivotTranslateUndoableCommand(const Ufe::Path& path) +UsdRotatePivotTranslateUndoableCommand::UsdRotatePivotTranslateUndoableCommand( + const Ufe::Path& path) : Ufe::TranslateUndoableCommand(path) , fPath(path) , fNoPivotOp(false) #else -UsdRotatePivotTranslateUndoableCommand::UsdRotatePivotTranslateUndoableCommand(const UsdPrim& prim, const Ufe::Path& path, const Ufe::SceneItem::Ptr& item) +UsdRotatePivotTranslateUndoableCommand::UsdRotatePivotTranslateUndoableCommand( + const UsdPrim& prim, + const Ufe::Path& path, + const Ufe::SceneItem::Ptr& item) : Ufe::TranslateUndoableCommand(item) , fPrim(prim) , fPath(path) , fNoPivotOp(false) #endif { - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE // create a sceneItem on first access sceneItem(); - #endif +#endif // Prim does not have a pivot translate attribute const TfToken xpivot("xformOp:translate:pivot"); - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE if (!prim().HasAttribute(xpivot)) - #else +#else if (!fPrim.HasAttribute(xpivot)) - #endif +#endif { fNoPivotOp = true; - // Add an empty pivot translate. - #ifdef UFE_V2_FEATURES_AVAILABLE +// Add an empty pivot translate. +#ifdef UFE_V2_FEATURES_AVAILABLE rotatePivotTranslateOp(prim(), fPath, 0, 0, 0); - #else +#else rotatePivotTranslateOp(fPrim, fPath, 0, 0, 0); - #endif +#endif } - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE fPivotAttrib = prim().GetAttribute(xpivot); - #else +#else fPivotAttrib = fPrim.GetAttribute(xpivot); - #endif +#endif fPivotAttrib.Get(&fPrevPivotValue); } -UsdRotatePivotTranslateUndoableCommand::~UsdRotatePivotTranslateUndoableCommand() -{ -} +UsdRotatePivotTranslateUndoableCommand::~UsdRotatePivotTranslateUndoableCommand() { } #ifdef UFE_V2_FEATURES_AVAILABLE -UsdSceneItem::Ptr -UsdRotatePivotTranslateUndoableCommand::sceneItem() const { +UsdSceneItem::Ptr UsdRotatePivotTranslateUndoableCommand::sceneItem() const +{ if (!fItem) { fItem = std::dynamic_pointer_cast(Ufe::Hierarchy::createItem(fPath)); } @@ -80,12 +82,16 @@ UsdRotatePivotTranslateUndoableCommand::sceneItem() const { /*static*/ #ifdef UFE_V2_FEATURES_AVAILABLE -UsdRotatePivotTranslateUndoableCommand::Ptr UsdRotatePivotTranslateUndoableCommand::create(const Ufe::Path& path) +UsdRotatePivotTranslateUndoableCommand::Ptr +UsdRotatePivotTranslateUndoableCommand::create(const Ufe::Path& path) { return std::make_shared(path); } #else -UsdRotatePivotTranslateUndoableCommand::Ptr UsdRotatePivotTranslateUndoableCommand::create(const UsdPrim& prim, const Ufe::Path& ufePath, const Ufe::SceneItem::Ptr& item) +UsdRotatePivotTranslateUndoableCommand::Ptr UsdRotatePivotTranslateUndoableCommand::create( + const UsdPrim& prim, + const Ufe::Path& ufePath, + const Ufe::SceneItem::Ptr& item) { return std::make_shared(prim, ufePath, item); } @@ -116,14 +122,14 @@ bool UsdRotatePivotTranslateUndoableCommand::set(double x, double y, double z) bool UsdRotatePivotTranslateUndoableCommand::translate(double x, double y, double z) #endif { - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE rotatePivotTranslateOp(prim(), fPath, x, y, z); - #else +#else rotatePivotTranslateOp(fPrim, fPath, x, y, z); - #endif - +#endif + return true; } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdRotatePivotTranslateUndoableCommand.h b/lib/mayaUsd/ufe/UsdRotatePivotTranslateUndoableCommand.h index 47b8925f9b..adb456a5b1 100644 --- a/lib/mayaUsd/ufe/UsdRotatePivotTranslateUndoableCommand.h +++ b/lib/mayaUsd/ufe/UsdRotatePivotTranslateUndoableCommand.h @@ -15,12 +15,12 @@ // #pragma once -#include +#include +#include #include -#include -#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -31,60 +31,71 @@ namespace ufe { /*! Ability to perform undo to restore the original pivot value. */ -class MAYAUSD_CORE_PUBLIC UsdRotatePivotTranslateUndoableCommand : public Ufe::TranslateUndoableCommand +class MAYAUSD_CORE_PUBLIC UsdRotatePivotTranslateUndoableCommand + : public Ufe::TranslateUndoableCommand { public: typedef std::shared_ptr Ptr; - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE UsdRotatePivotTranslateUndoableCommand(const Ufe::Path& path); - #else - UsdRotatePivotTranslateUndoableCommand(const UsdPrim& prim, const Ufe::Path& ufePath, const Ufe::SceneItem::Ptr& item); - #endif +#else + UsdRotatePivotTranslateUndoableCommand( + const UsdPrim& prim, + const Ufe::Path& ufePath, + const Ufe::SceneItem::Ptr& item); +#endif ~UsdRotatePivotTranslateUndoableCommand() override; // Delete the copy/move constructors assignment operators. UsdRotatePivotTranslateUndoableCommand(const UsdRotatePivotTranslateUndoableCommand&) = delete; - UsdRotatePivotTranslateUndoableCommand& operator=(const UsdRotatePivotTranslateUndoableCommand&) = delete; + UsdRotatePivotTranslateUndoableCommand& operator=(const UsdRotatePivotTranslateUndoableCommand&) + = delete; UsdRotatePivotTranslateUndoableCommand(UsdRotatePivotTranslateUndoableCommand&&) = delete; - UsdRotatePivotTranslateUndoableCommand& operator=(UsdRotatePivotTranslateUndoableCommand&&) = delete; + UsdRotatePivotTranslateUndoableCommand& operator=(UsdRotatePivotTranslateUndoableCommand&&) + = delete; - //! Create a UsdRotatePivotTranslateUndoableCommand from a USD prim, UFE path and UFE scene item. - #ifdef UFE_V2_FEATURES_AVAILABLE +//! Create a UsdRotatePivotTranslateUndoableCommand from a USD prim, UFE path and UFE scene item. +#ifdef UFE_V2_FEATURES_AVAILABLE static UsdRotatePivotTranslateUndoableCommand::Ptr create(const Ufe::Path& path); - #else - static UsdRotatePivotTranslateUndoableCommand::Ptr create(const UsdPrim& prim, const Ufe::Path& ufePath, const Ufe::SceneItem::Ptr& item); - #endif +#else + static UsdRotatePivotTranslateUndoableCommand::Ptr + create(const UsdPrim& prim, const Ufe::Path& ufePath, const Ufe::SceneItem::Ptr& item); +#endif // Ufe::TranslateUndoableCommand overrides void undo() override; void redo() override; #if UFE_PREVIEW_VERSION_NUM >= 2025 -//#ifdef UFE_V2_FEATURES_AVAILABLE + //#ifdef UFE_V2_FEATURES_AVAILABLE bool set(double x, double y, double z) override; #else bool translate(double x, double y, double z) override; #endif - inline UsdPrim prim() const { TF_AXIOM(fItem != nullptr); return fItem->prim(); } + inline UsdPrim prim() const + { + TF_AXIOM(fItem != nullptr); + return fItem->prim(); + } private: - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE UsdSceneItem::Ptr sceneItem() const; - #endif +#endif private: - #if UFE_PREVIEW_VERSION_NUM < 2021 +#if UFE_PREVIEW_VERSION_NUM < 2021 UsdPrim fPrim; - #endif - Ufe::Path fPath; - mutable UsdSceneItem::Ptr fItem{nullptr}; - UsdAttribute fPivotAttrib; - GfVec3f fPrevPivotValue; - bool fNoPivotOp; +#endif + Ufe::Path fPath; + mutable UsdSceneItem::Ptr fItem { nullptr }; + UsdAttribute fPivotAttrib; + GfVec3f fPrevPivotValue; + bool fNoPivotOp; }; // UsdRotatePivotTranslateUndoableCommand } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdRotateUndoableCommand.cpp b/lib/mayaUsd/ufe/UsdRotateUndoableCommand.cpp index ac61eef4e3..f1f3da0c05 100644 --- a/lib/mayaUsd/ufe/UsdRotateUndoableCommand.cpp +++ b/lib/mayaUsd/ufe/UsdRotateUndoableCommand.cpp @@ -24,76 +24,73 @@ TfToken UsdRotateUndoableCommand::rotXYZ("xformOp:rotateXYZ"); #ifdef UFE_V2_FEATURES_AVAILABLE UsdRotateUndoableCommand::UsdRotateUndoableCommand( - const Ufe::Path& path, double x, double y, double z) - : Ufe::RotateUndoableCommand(path), - UsdTRSUndoableCommandBase(x, y, z) + const Ufe::Path& path, + double x, + double y, + double z) + : Ufe::RotateUndoableCommand(path) + , UsdTRSUndoableCommandBase(x, y, z) #else UsdRotateUndoableCommand::UsdRotateUndoableCommand( - const UsdSceneItem::Ptr& item, double x, double y, double z) - : Ufe::RotateUndoableCommand(item), - UsdTRSUndoableCommandBase(item, x, y, z) + const UsdSceneItem::Ptr& item, + double x, + double y, + double z) + : Ufe::RotateUndoableCommand(item) + , UsdTRSUndoableCommandBase(item, x, y, z) #endif { - // Since we want to change xformOp:rotateXYZ, and we need to store the - // prevRotate for undo purposes, we need to make sure we convert it to - // common API xformOps (In case we have rotateX, rotateY or rotateZ ops) - try { - if(!UsdGeomXformCommonAPI(prim())) + // Since we want to change xformOp:rotateXYZ, and we need to store the + // prevRotate for undo purposes, we need to make sure we convert it to + // common API xformOps (In case we have rotateX, rotateY or rotateZ ops) + try { + if (!UsdGeomXformCommonAPI(prim())) convertToCompatibleCommonAPI(prim()); - } - catch (...) { - // Since Maya cannot catch this error at this moment, store it until we - // actually rotate. - fFailedInit = std::current_exception(); // capture - } + } catch (...) { + // Since Maya cannot catch this error at this moment, store it until we + // actually rotate. + fFailedInit = std::current_exception(); // capture + } } -UsdRotateUndoableCommand::~UsdRotateUndoableCommand() -{} +UsdRotateUndoableCommand::~UsdRotateUndoableCommand() { } #ifdef UFE_V2_FEATURES_AVAILABLE -UsdRotateUndoableCommand::Ptr UsdRotateUndoableCommand::create( - const Ufe::Path& path, double x, double y, double z) +UsdRotateUndoableCommand::Ptr +UsdRotateUndoableCommand::create(const Ufe::Path& path, double x, double y, double z) { - auto cmd = std::make_shared>( - path, x, y, z); + auto cmd = std::make_shared>(path, x, y, z); cmd->initialize(); return cmd; } #else -UsdRotateUndoableCommand::Ptr UsdRotateUndoableCommand::create( - const UsdSceneItem::Ptr& item, double x, double y, double z) +UsdRotateUndoableCommand::Ptr +UsdRotateUndoableCommand::create(const UsdSceneItem::Ptr& item, double x, double y, double z) { - auto cmd = std::make_shared>( - item, x, y, z); + auto cmd = std::make_shared>(item, x, y, z); cmd->initialize(); return cmd; } #endif - void UsdRotateUndoableCommand::undo() { - // Check if initialization went ok. - if (!fFailedInit) - { + // Check if initialization went ok. + if (!fFailedInit) { UsdTRSUndoableCommandBase::undoImp(); - } + } } -void UsdRotateUndoableCommand::redo() -{ - redoImp(); -} +void UsdRotateUndoableCommand::redo() { redoImp(); } void UsdRotateUndoableCommand::addEmptyAttribute() { - performImp(0, 0, 0); // Add an empty rotate + performImp(0, 0, 0); // Add an empty rotate } void UsdRotateUndoableCommand::performImp(double x, double y, double z) { - rotateOp(prim(), path(), x, y, z); + rotateOp(prim(), path(), x, y, z); } //------------------------------------------------------------------------------ @@ -107,14 +104,13 @@ bool UsdRotateUndoableCommand::set(double x, double y, double z) bool UsdRotateUndoableCommand::rotate(double x, double y, double z) #endif { - // Fail early - Initialization did not go as expected. - if (fFailedInit) - { - std::rethrow_exception(fFailedInit); - } - perform(x, y, z); - return true; + // Fail early - Initialization did not go as expected. + if (fFailedInit) { + std::rethrow_exception(fFailedInit); + } + perform(x, y, z); + return true; } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdRotateUndoableCommand.h b/lib/mayaUsd/ufe/UsdRotateUndoableCommand.h index d16da69f62..eb4a165e36 100644 --- a/lib/mayaUsd/ufe/UsdRotateUndoableCommand.h +++ b/lib/mayaUsd/ufe/UsdRotateUndoableCommand.h @@ -15,14 +15,14 @@ // #pragma once -#include - -#include +#include +#include #include -#include -#include +#include + +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -31,67 +31,67 @@ namespace ufe { //! \brief Absolute rotation command of the given prim. /*! - Ability to perform undo to restore the original rotation value. + Ability to perform undo to restore the original rotation value. */ -class MAYAUSD_CORE_PUBLIC UsdRotateUndoableCommand : public Ufe::RotateUndoableCommand, public UsdTRSUndoableCommandBase +class MAYAUSD_CORE_PUBLIC UsdRotateUndoableCommand + : public Ufe::RotateUndoableCommand + , public UsdTRSUndoableCommandBase { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdRotateUndoableCommand(const UsdRotateUndoableCommand&) = delete; - UsdRotateUndoableCommand& operator=(const UsdRotateUndoableCommand&) = delete; - UsdRotateUndoableCommand(UsdRotateUndoableCommand&&) = delete; - UsdRotateUndoableCommand& operator=(UsdRotateUndoableCommand&&) = delete; + UsdRotateUndoableCommand(const UsdRotateUndoableCommand&) = delete; + UsdRotateUndoableCommand& operator=(const UsdRotateUndoableCommand&) = delete; + UsdRotateUndoableCommand(UsdRotateUndoableCommand&&) = delete; + UsdRotateUndoableCommand& operator=(UsdRotateUndoableCommand&&) = delete; - #ifdef UFE_V2_FEATURES_AVAILABLE - //! Create a UsdRotateUndoableCommand from a UFE scene path. The command is +#ifdef UFE_V2_FEATURES_AVAILABLE + //! Create a UsdRotateUndoableCommand from a UFE scene path. The command is //! not executed. - static UsdRotateUndoableCommand::Ptr create( - const Ufe::Path& path, double x, double y, double z); - #else - //! Create a UsdRotateUndoableCommand from a UFE scene item. The command is + static UsdRotateUndoableCommand::Ptr + create(const Ufe::Path& path, double x, double y, double z); +#else + //! Create a UsdRotateUndoableCommand from a UFE scene item. The command is //! not executed. - static UsdRotateUndoableCommand::Ptr create( - const UsdSceneItem::Ptr& item, double x, double y, double z); - #endif - - // Ufe::RotateUndoableCommand overrides. rotate() sets the command's - // rotation value and executes the command. - void undo() override; - void redo() override; + static UsdRotateUndoableCommand::Ptr + create(const UsdSceneItem::Ptr& item, double x, double y, double z); +#endif + + // Ufe::RotateUndoableCommand overrides. rotate() sets the command's + // rotation value and executes the command. + void undo() override; + void redo() override; #if UFE_PREVIEW_VERSION_NUM >= 2025 -//#ifdef UFE_V2_FEATURES_AVAILABLE - bool set(double x, double y, double z) override; + //#ifdef UFE_V2_FEATURES_AVAILABLE + bool set(double x, double y, double z) override; #else - bool rotate(double x, double y, double z) override; + bool rotate(double x, double y, double z) override; #endif - #ifdef UFE_V2_FEATURES_AVAILABLE - Ufe::Path getPath() const override { return path(); } - #endif +#ifdef UFE_V2_FEATURES_AVAILABLE + Ufe::Path getPath() const override { return path(); } +#endif protected: - //! Construct a UsdRotateUndoableCommand. The command is not executed. - #ifdef UFE_V2_FEATURES_AVAILABLE - UsdRotateUndoableCommand(const Ufe::Path& path, double x, double y, double z); - #else - UsdRotateUndoableCommand(const UsdSceneItem::Ptr& item, double x, double y, double z); - #endif - ~UsdRotateUndoableCommand() override; +#ifdef UFE_V2_FEATURES_AVAILABLE + UsdRotateUndoableCommand(const Ufe::Path& path, double x, double y, double z); +#else + UsdRotateUndoableCommand(const UsdSceneItem::Ptr& item, double x, double y, double z); +#endif + ~UsdRotateUndoableCommand() override; private: - static TfToken rotXYZ; TfToken attributeName() const override { return rotXYZ; } - void performImp(double x, double y, double z) override; - void addEmptyAttribute() override; - bool cannotInit() const override { return bool(fFailedInit); } + void performImp(double x, double y, double z) override; + void addEmptyAttribute() override; + bool cannotInit() const override { return bool(fFailedInit); } - std::exception_ptr fFailedInit; + std::exception_ptr fFailedInit; }; // UsdRotateUndoableCommand } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdScaleUndoableCommand.cpp b/lib/mayaUsd/ufe/UsdScaleUndoableCommand.cpp index 5a09a80596..6aea04c7ee 100644 --- a/lib/mayaUsd/ufe/UsdScaleUndoableCommand.cpp +++ b/lib/mayaUsd/ufe/UsdScaleUndoableCommand.cpp @@ -24,67 +24,61 @@ TfToken UsdScaleUndoableCommand::scaleTok("xformOp:scale"); #ifdef UFE_V2_FEATURES_AVAILABLE UsdScaleUndoableCommand::UsdScaleUndoableCommand( - const Ufe::Path& path, double x, double y, double z -) : Ufe::ScaleUndoableCommand(path), - UsdTRSUndoableCommandBase(x, y, z) -{} + const Ufe::Path& path, + double x, + double y, + double z) + : Ufe::ScaleUndoableCommand(path) + , UsdTRSUndoableCommandBase(x, y, z) +{ +} #else UsdScaleUndoableCommand::UsdScaleUndoableCommand( - const UsdSceneItem::Ptr& item, double x, double y, double z -) : Ufe::ScaleUndoableCommand(item), - UsdTRSUndoableCommandBase(item, x, y, z) -{} + const UsdSceneItem::Ptr& item, + double x, + double y, + double z) + : Ufe::ScaleUndoableCommand(item) + , UsdTRSUndoableCommandBase(item, x, y, z) +{ +} #endif -UsdScaleUndoableCommand::~UsdScaleUndoableCommand() -{} +UsdScaleUndoableCommand::~UsdScaleUndoableCommand() { } /*static*/ #ifdef UFE_V2_FEATURES_AVAILABLE -UsdScaleUndoableCommand::Ptr UsdScaleUndoableCommand::create( - const Ufe::Path& path, double x, double y, double z -) +UsdScaleUndoableCommand::Ptr +UsdScaleUndoableCommand::create(const Ufe::Path& path, double x, double y, double z) { - auto cmd = std::make_shared>( - path, x, y, z); + auto cmd = std::make_shared>(path, x, y, z); cmd->initialize(); return cmd; - } #else -UsdScaleUndoableCommand::Ptr UsdScaleUndoableCommand::create( - const UsdSceneItem::Ptr& item, double x, double y, double z -) +UsdScaleUndoableCommand::Ptr +UsdScaleUndoableCommand::create(const UsdSceneItem::Ptr& item, double x, double y, double z) { - auto cmd = std::make_shared>( - item, x, y, z); + auto cmd = std::make_shared>(item, x, y, z); cmd->initialize(); return cmd; - } #endif -void UsdScaleUndoableCommand::undo() -{ - undoImp(); -} +void UsdScaleUndoableCommand::undo() { undoImp(); } -void UsdScaleUndoableCommand::redo() -{ - redoImp(); -} +void UsdScaleUndoableCommand::redo() { redoImp(); } void UsdScaleUndoableCommand::addEmptyAttribute() { - performImp(1, 1, 1); // Add a neutral scale + performImp(1, 1, 1); // Add a neutral scale } void UsdScaleUndoableCommand::performImp(double x, double y, double z) { - scaleOp(prim(), path(), x, y, z); + scaleOp(prim(), path(), x, y, z); } - //------------------------------------------------------------------------------ // Ufe::ScaleUndoableCommand overrides //------------------------------------------------------------------------------ @@ -96,9 +90,9 @@ bool UsdScaleUndoableCommand::set(double x, double y, double z) bool UsdScaleUndoableCommand::scale(double x, double y, double z) #endif { - perform(x, y, z); - return true; + perform(x, y, z); + return true; } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdScaleUndoableCommand.h b/lib/mayaUsd/ufe/UsdScaleUndoableCommand.h index bdb9391a33..590e71e005 100644 --- a/lib/mayaUsd/ufe/UsdScaleUndoableCommand.h +++ b/lib/mayaUsd/ufe/UsdScaleUndoableCommand.h @@ -15,12 +15,12 @@ // #pragma once -#include +#include +#include #include -#include -#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -29,64 +29,63 @@ namespace ufe { //! \brief Absolute scale command of the given prim. /*! - Ability to perform undo to restore the original scale value. + Ability to perform undo to restore the original scale value. */ -class MAYAUSD_CORE_PUBLIC UsdScaleUndoableCommand : public Ufe::ScaleUndoableCommand, public UsdTRSUndoableCommandBase +class MAYAUSD_CORE_PUBLIC UsdScaleUndoableCommand + : public Ufe::ScaleUndoableCommand + , public UsdTRSUndoableCommandBase { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdScaleUndoableCommand(const UsdScaleUndoableCommand&) = delete; - UsdScaleUndoableCommand& operator=(const UsdScaleUndoableCommand&) = delete; - UsdScaleUndoableCommand(UsdScaleUndoableCommand&&) = delete; - UsdScaleUndoableCommand& operator=(UsdScaleUndoableCommand&&) = delete; + UsdScaleUndoableCommand(const UsdScaleUndoableCommand&) = delete; + UsdScaleUndoableCommand& operator=(const UsdScaleUndoableCommand&) = delete; + UsdScaleUndoableCommand(UsdScaleUndoableCommand&&) = delete; + UsdScaleUndoableCommand& operator=(UsdScaleUndoableCommand&&) = delete; - #ifdef UFE_V2_FEATURES_AVAILABLE - //! Create a UsdScaleUndoableCommand from a UFE scene path. The command is +#ifdef UFE_V2_FEATURES_AVAILABLE + //! Create a UsdScaleUndoableCommand from a UFE scene path. The command is //! not executed. - static UsdScaleUndoableCommand::Ptr create( - const Ufe::Path& path, double x, double y, double z); - #else - //! Create a UsdScaleUndoableCommand from a UFE scene item. The command is + static UsdScaleUndoableCommand::Ptr create(const Ufe::Path& path, double x, double y, double z); +#else + //! Create a UsdScaleUndoableCommand from a UFE scene item. The command is //! not executed. - static UsdScaleUndoableCommand::Ptr create( - const UsdSceneItem::Ptr& item, double x, double y, double z); - #endif + static UsdScaleUndoableCommand::Ptr + create(const UsdSceneItem::Ptr& item, double x, double y, double z); +#endif - // Ufe::ScaleUndoableCommand overrides - void undo() override; - void redo() override; + // Ufe::ScaleUndoableCommand overrides + void undo() override; + void redo() override; #if UFE_PREVIEW_VERSION_NUM >= 2025 -//#ifdef UFE_V2_FEATURES_AVAILABLE - bool set(double x, double y, double z) override; + //#ifdef UFE_V2_FEATURES_AVAILABLE + bool set(double x, double y, double z) override; #else - bool scale(double x, double y, double z) override; + bool scale(double x, double y, double z) override; #endif - #ifdef UFE_V2_FEATURES_AVAILABLE - Ufe::Path getPath() const override { return path(); } - #endif +#ifdef UFE_V2_FEATURES_AVAILABLE + Ufe::Path getPath() const override { return path(); } +#endif protected: - //! Construct a UsdScaleUndoableCommand. The command is not executed. - #ifdef UFE_V2_FEATURES_AVAILABLE - UsdScaleUndoableCommand(const Ufe::Path& path, double x, double y, double z); - #else - UsdScaleUndoableCommand(const UsdSceneItem::Ptr& item, double x, double y, double z); - #endif +#ifdef UFE_V2_FEATURES_AVAILABLE + UsdScaleUndoableCommand(const Ufe::Path& path, double x, double y, double z); +#else + UsdScaleUndoableCommand(const UsdSceneItem::Ptr& item, double x, double y, double z); +#endif - ~UsdScaleUndoableCommand() override; + ~UsdScaleUndoableCommand() override; private: - static TfToken scaleTok; TfToken attributeName() const override { return scaleTok; } - void performImp(double x, double y, double z) override; - void addEmptyAttribute() override; + void performImp(double x, double y, double z) override; + void addEmptyAttribute() override; }; // UsdScaleUndoableCommand } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdSceneItem.cpp b/lib/mayaUsd/ufe/UsdSceneItem.cpp index cc5e1070cc..e234cfdbe8 100644 --- a/lib/mayaUsd/ufe/UsdSceneItem.cpp +++ b/lib/mayaUsd/ufe/UsdSceneItem.cpp @@ -27,63 +27,60 @@ namespace MAYAUSD_NS_DEF { namespace ufe { UsdSceneItem::UsdSceneItem(const Ufe::Path& path, const UsdPrim& prim) - : Ufe::SceneItem(path) - , fPrim(prim) + : Ufe::SceneItem(path) + , fPrim(prim) { } /*static*/ UsdSceneItem::Ptr UsdSceneItem::create(const Ufe::Path& path, const UsdPrim& prim) { - return std::make_shared(path, prim); + return std::make_shared(path, prim); } //------------------------------------------------------------------------------ // Ufe::SceneItem overrides //------------------------------------------------------------------------------ -std::string UsdSceneItem::nodeType() const -{ - return fPrim.GetTypeName(); -} +std::string UsdSceneItem::nodeType() const { return fPrim.GetTypeName(); } #ifdef UFE_V2_FEATURES_AVAILABLE std::vector UsdSceneItem::ancestorNodeTypes() const { - std::vector strAncestorTypes; + std::vector strAncestorTypes; #if USD_VERSION_NUM < 2008 - static const TfType schemaBaseType = TfType::Find(); - const TfType schemaType = schemaBaseType.FindDerivedByName(fPrim.GetTypeName().GetString()); + static const TfType schemaBaseType = TfType::Find(); + const TfType schemaType = schemaBaseType.FindDerivedByName(fPrim.GetTypeName().GetString()); #else - // Get the actual schema type from the prim definition. - const TfType& schemaType = fPrim.GetPrimTypeInfo().GetSchemaType(); + // Get the actual schema type from the prim definition. + const TfType& schemaType = fPrim.GetPrimTypeInfo().GetSchemaType(); #endif - if (!schemaType) { - // No schema type, return empty ancestor types. - return strAncestorTypes; - } + if (!schemaType) { + // No schema type, return empty ancestor types. + return strAncestorTypes; + } - // According to the USD docs GetAllAncestorTypes() is expensive, so we keep a cache. - static std::map> ancestorTypesCache; - const auto iter = ancestorTypesCache.find(schemaType); - if (iter != ancestorTypesCache.end()) { - return iter->second; - } + // According to the USD docs GetAllAncestorTypes() is expensive, so we keep a cache. + static std::map> ancestorTypesCache; + const auto iter = ancestorTypesCache.find(schemaType); + if (iter != ancestorTypesCache.end()) { + return iter->second; + } - const auto& schemaReg = UsdSchemaRegistry::GetInstance(); - std::vector tfAncestorTypes; - schemaType.GetAllAncestorTypes(&tfAncestorTypes); - for (const TfType& ty : tfAncestorTypes) - { - // If there is a concrete schema type name, we'll return that since it is what - // is used/shown in the UI (ex: 'Xform' vs 'UsdGeomXform'). - strAncestorTypes.emplace_back(schemaReg.IsConcrete(ty) ? schemaReg.GetSchemaTypeName(ty) : ty.GetTypeName()); - } - ancestorTypesCache[schemaType] = strAncestorTypes; - return strAncestorTypes; + const auto& schemaReg = UsdSchemaRegistry::GetInstance(); + std::vector tfAncestorTypes; + schemaType.GetAllAncestorTypes(&tfAncestorTypes); + for (const TfType& ty : tfAncestorTypes) { + // If there is a concrete schema type name, we'll return that since it is what + // is used/shown in the UI (ex: 'Xform' vs 'UsdGeomXform'). + strAncestorTypes.emplace_back( + schemaReg.IsConcrete(ty) ? schemaReg.GetSchemaTypeName(ty) : ty.GetTypeName()); + } + ancestorTypesCache[schemaType] = strAncestorTypes; + return strAncestorTypes; } #endif } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdSceneItem.h b/lib/mayaUsd/ufe/UsdSceneItem.h index 608284e306..5782e48d7b 100644 --- a/lib/mayaUsd/ufe/UsdSceneItem.h +++ b/lib/mayaUsd/ufe/UsdSceneItem.h @@ -15,11 +15,11 @@ // #pragma once -#include +#include #include -#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -30,31 +30,31 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdSceneItem : public Ufe::SceneItem { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdSceneItem(const Ufe::Path& path, const UsdPrim& prim); - ~UsdSceneItem() override = default; + UsdSceneItem(const Ufe::Path& path, const UsdPrim& prim); + ~UsdSceneItem() override = default; - // Delete the copy/move constructors assignment operators. - UsdSceneItem(const UsdSceneItem&) = delete; - UsdSceneItem& operator=(const UsdSceneItem&) = delete; - UsdSceneItem(UsdSceneItem&&) = delete; - UsdSceneItem& operator=(UsdSceneItem&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdSceneItem(const UsdSceneItem&) = delete; + UsdSceneItem& operator=(const UsdSceneItem&) = delete; + UsdSceneItem(UsdSceneItem&&) = delete; + UsdSceneItem& operator=(UsdSceneItem&&) = delete; - //! Create a UsdSceneItem from a UFE path and a USD prim. - static UsdSceneItem::Ptr create(const Ufe::Path& path, const UsdPrim& prim); + //! Create a UsdSceneItem from a UFE path and a USD prim. + static UsdSceneItem::Ptr create(const Ufe::Path& path, const UsdPrim& prim); - const UsdPrim& prim() const { return fPrim; } + const UsdPrim& prim() const { return fPrim; } - // Ufe::SceneItem overrides - std::string nodeType() const override; - #ifdef UFE_V2_FEATURES_AVAILABLE - std::vector ancestorNodeTypes() const override; - #endif + // Ufe::SceneItem overrides + std::string nodeType() const override; +#ifdef UFE_V2_FEATURES_AVAILABLE + std::vector ancestorNodeTypes() const override; +#endif private: - UsdPrim fPrim; + UsdPrim fPrim; }; // UsdSceneItem } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdSceneItemOps.cpp b/lib/mayaUsd/ufe/UsdSceneItemOps.cpp index ae7b9f3b7a..95557998bb 100644 --- a/lib/mayaUsd/ufe/UsdSceneItemOps.cpp +++ b/lib/mayaUsd/ufe/UsdSceneItemOps.cpp @@ -24,7 +24,8 @@ namespace { // Warning: If a user tries to delete a prim that is deactivated (can be localized). -static constexpr char kWarningCannotDeactivePrim[] = "Cannot deactivate \"^1s\" because it is already inactive."; +static constexpr char kWarningCannotDeactivePrim[] + = "Cannot deactivate \"^1s\" because it is already inactive."; void displayWarning(const UsdPrim& prim, const MString& fmt) { @@ -33,103 +34,92 @@ void displayWarning(const UsdPrim& prim, const MString& fmt) MGlobal::displayWarning(msg); } -} +} // namespace namespace MAYAUSD_NS_DEF { namespace ufe { UsdSceneItemOps::UsdSceneItemOps(const UsdSceneItem::Ptr& item) - : Ufe::SceneItemOps() + : Ufe::SceneItemOps() , fItem(item) { } -UsdSceneItemOps::~UsdSceneItemOps() -{ -} +UsdSceneItemOps::~UsdSceneItemOps() { } /*static*/ UsdSceneItemOps::Ptr UsdSceneItemOps::create(const UsdSceneItem::Ptr& item) { - return std::make_shared(item); + return std::make_shared(item); } -void UsdSceneItemOps::setItem(const UsdSceneItem::Ptr& item) -{ - fItem = item; -} +void UsdSceneItemOps::setItem(const UsdSceneItem::Ptr& item) { fItem = item; } -const Ufe::Path& UsdSceneItemOps::path() const -{ - return fItem->path(); -} +const Ufe::Path& UsdSceneItemOps::path() const { return fItem->path(); } //------------------------------------------------------------------------------ // Ufe::SceneItemOps overrides //------------------------------------------------------------------------------ -Ufe::SceneItem::Ptr UsdSceneItemOps::sceneItem() const -{ - return fItem; -} +Ufe::SceneItem::Ptr UsdSceneItemOps::sceneItem() const { return fItem; } Ufe::UndoableCommand::Ptr UsdSceneItemOps::deleteItemCmd() { - if (prim().IsActive()) { - auto deleteCmd = UsdUndoDeleteCommand::create(prim()); - deleteCmd->execute(); - return deleteCmd; - } - - displayWarning(prim(), kWarningCannotDeactivePrim); - return nullptr; + if (prim().IsActive()) { + auto deleteCmd = UsdUndoDeleteCommand::create(prim()); + deleteCmd->execute(); + return deleteCmd; + } + + displayWarning(prim(), kWarningCannotDeactivePrim); + return nullptr; } bool UsdSceneItemOps::deleteItem() { - if (prim().IsActive()) { - return prim().SetActive(false); - } + if (prim().IsActive()) { + return prim().SetActive(false); + } - displayWarning(prim(), kWarningCannotDeactivePrim); - return false; + displayWarning(prim(), kWarningCannotDeactivePrim); + return false; } Ufe::Duplicate UsdSceneItemOps::duplicateItemCmd() { - auto duplicateCmd = UsdUndoDuplicateCommand::create(prim(), fItem->path()); - duplicateCmd->execute(); - auto item = createSiblingSceneItem(path(), duplicateCmd->usdDstPath().GetElementString()); - return Ufe::Duplicate(item, duplicateCmd); + auto duplicateCmd = UsdUndoDuplicateCommand::create(prim(), fItem->path()); + duplicateCmd->execute(); + auto item = createSiblingSceneItem(path(), duplicateCmd->usdDstPath().GetElementString()); + return Ufe::Duplicate(item, duplicateCmd); } Ufe::SceneItem::Ptr UsdSceneItemOps::duplicateItem() { - SdfPath usdDstPath; - SdfLayerHandle layer; - UsdUndoDuplicateCommand::primInfo(prim(), usdDstPath, layer); - bool status = UsdUndoDuplicateCommand::duplicate(layer, prim().GetPath(), usdDstPath); + SdfPath usdDstPath; + SdfLayerHandle layer; + UsdUndoDuplicateCommand::primInfo(prim(), usdDstPath, layer); + bool status = UsdUndoDuplicateCommand::duplicate(layer, prim().GetPath(), usdDstPath); - // The duplicate is a sibling of the source. - if (status) - return createSiblingSceneItem(path(), usdDstPath.GetElementString()); + // The duplicate is a sibling of the source. + if (status) + return createSiblingSceneItem(path(), usdDstPath.GetElementString()); - return nullptr; + return nullptr; } Ufe::SceneItem::Ptr UsdSceneItemOps::renameItem(const Ufe::PathComponent& newName) { - auto renameCmd = UsdUndoRenameCommand::create(fItem, newName); - renameCmd->execute(); - return renameCmd->renamedItem(); + auto renameCmd = UsdUndoRenameCommand::create(fItem, newName); + renameCmd->execute(); + return renameCmd->renamedItem(); } Ufe::Rename UsdSceneItemOps::renameItemCmd(const Ufe::PathComponent& newName) { - auto renameCmd = UsdUndoRenameCommand::create(fItem, newName); - renameCmd->execute(); - return Ufe::Rename(renameCmd->renamedItem(), renameCmd); + auto renameCmd = UsdUndoRenameCommand::create(fItem, newName); + renameCmd->execute(); + return Ufe::Rename(renameCmd->renamedItem(), renameCmd); } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdSceneItemOps.h b/lib/mayaUsd/ufe/UsdSceneItemOps.h index 94215de492..46e07eadb4 100644 --- a/lib/mayaUsd/ufe/UsdSceneItemOps.h +++ b/lib/mayaUsd/ufe/UsdSceneItemOps.h @@ -15,13 +15,13 @@ // #pragma once -#include -#include +#include +#include #include -#include -#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -32,37 +32,41 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdSceneItemOps : public Ufe::SceneItemOps { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdSceneItemOps(const UsdSceneItem::Ptr& item); - ~UsdSceneItemOps() override; + UsdSceneItemOps(const UsdSceneItem::Ptr& item); + ~UsdSceneItemOps() override; - // Delete the copy/move constructors assignment operators. - UsdSceneItemOps(const UsdSceneItemOps&) = delete; - UsdSceneItemOps& operator=(const UsdSceneItemOps&) = delete; - UsdSceneItemOps(UsdSceneItemOps&&) = delete; - UsdSceneItemOps& operator=(UsdSceneItemOps&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdSceneItemOps(const UsdSceneItemOps&) = delete; + UsdSceneItemOps& operator=(const UsdSceneItemOps&) = delete; + UsdSceneItemOps(UsdSceneItemOps&&) = delete; + UsdSceneItemOps& operator=(UsdSceneItemOps&&) = delete; - //! Create a UsdSceneItemOps. - static UsdSceneItemOps::Ptr create(const UsdSceneItem::Ptr& item); + //! Create a UsdSceneItemOps. + static UsdSceneItemOps::Ptr create(const UsdSceneItem::Ptr& item); - void setItem(const UsdSceneItem::Ptr& item); - const Ufe::Path& path() const; - inline UsdPrim prim() const { TF_AXIOM(fItem != nullptr); return fItem->prim(); } + void setItem(const UsdSceneItem::Ptr& item); + const Ufe::Path& path() const; + inline UsdPrim prim() const + { + TF_AXIOM(fItem != nullptr); + return fItem->prim(); + } - // Ufe::SceneItemOps overrides - Ufe::SceneItem::Ptr sceneItem() const override; - Ufe::UndoableCommand::Ptr deleteItemCmd() override; - bool deleteItem() override; - Ufe::Duplicate duplicateItemCmd() override; - Ufe::SceneItem::Ptr duplicateItem() override; - Ufe::Rename renameItemCmd(const Ufe::PathComponent& newName) override; - Ufe::SceneItem::Ptr renameItem(const Ufe::PathComponent& newName) override; + // Ufe::SceneItemOps overrides + Ufe::SceneItem::Ptr sceneItem() const override; + Ufe::UndoableCommand::Ptr deleteItemCmd() override; + bool deleteItem() override; + Ufe::Duplicate duplicateItemCmd() override; + Ufe::SceneItem::Ptr duplicateItem() override; + Ufe::Rename renameItemCmd(const Ufe::PathComponent& newName) override; + Ufe::SceneItem::Ptr renameItem(const Ufe::PathComponent& newName) override; private: - UsdSceneItem::Ptr fItem; + UsdSceneItem::Ptr fItem; }; // UsdSceneItemOps } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdSceneItemOpsHandler.cpp b/lib/mayaUsd/ufe/UsdSceneItemOpsHandler.cpp index 38f0a8f964..3889fbf1c9 100644 --- a/lib/mayaUsd/ufe/UsdSceneItemOpsHandler.cpp +++ b/lib/mayaUsd/ufe/UsdSceneItemOpsHandler.cpp @@ -19,17 +19,16 @@ namespace MAYAUSD_NS_DEF { namespace ufe { UsdSceneItemOpsHandler::UsdSceneItemOpsHandler() - : Ufe::SceneItemOpsHandler() -{} - -UsdSceneItemOpsHandler::~UsdSceneItemOpsHandler() + : Ufe::SceneItemOpsHandler() { } +UsdSceneItemOpsHandler::~UsdSceneItemOpsHandler() { } + /*static*/ UsdSceneItemOpsHandler::Ptr UsdSceneItemOpsHandler::create() { - return std::make_shared(); + return std::make_shared(); } //------------------------------------------------------------------------------ @@ -38,12 +37,12 @@ UsdSceneItemOpsHandler::Ptr UsdSceneItemOpsHandler::create() Ufe::SceneItemOps::Ptr UsdSceneItemOpsHandler::sceneItemOps(const Ufe::SceneItem::Ptr& item) const { - UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); + UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); #if !defined(NDEBUG) - assert(usdItem); + assert(usdItem); #endif - return UsdSceneItemOps::create(usdItem); + return UsdSceneItemOps::create(usdItem); } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdSceneItemOpsHandler.h b/lib/mayaUsd/ufe/UsdSceneItemOpsHandler.h index b80aee501f..e53dc2d26e 100644 --- a/lib/mayaUsd/ufe/UsdSceneItemOpsHandler.h +++ b/lib/mayaUsd/ufe/UsdSceneItemOpsHandler.h @@ -15,12 +15,12 @@ // #pragma once -#include - #include #include -//PXR_NAMESPACE_USING_DIRECTIVE +#include + +// PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { namespace ufe { @@ -29,23 +29,23 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdSceneItemOpsHandler : public Ufe::SceneItemOpsHandler { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdSceneItemOpsHandler(); - ~UsdSceneItemOpsHandler() override; + UsdSceneItemOpsHandler(); + ~UsdSceneItemOpsHandler() override; - // Delete the copy/move constructors assignment operators. - UsdSceneItemOpsHandler(const UsdSceneItemOpsHandler&) = delete; - UsdSceneItemOpsHandler& operator=(const UsdSceneItemOpsHandler&) = delete; - UsdSceneItemOpsHandler(UsdSceneItemOpsHandler&&) = delete; - UsdSceneItemOpsHandler& operator=(UsdSceneItemOpsHandler&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdSceneItemOpsHandler(const UsdSceneItemOpsHandler&) = delete; + UsdSceneItemOpsHandler& operator=(const UsdSceneItemOpsHandler&) = delete; + UsdSceneItemOpsHandler(UsdSceneItemOpsHandler&&) = delete; + UsdSceneItemOpsHandler& operator=(UsdSceneItemOpsHandler&&) = delete; - //! Create a UsdSceneItemOpsHandler. - static UsdSceneItemOpsHandler::Ptr create(); + //! Create a UsdSceneItemOpsHandler. + static UsdSceneItemOpsHandler::Ptr create(); - // Ufe::SceneItemOpsHandler overrides - Ufe::SceneItemOps::Ptr sceneItemOps(const Ufe::SceneItem::Ptr& item) const override; + // Ufe::SceneItemOpsHandler overrides + Ufe::SceneItemOps::Ptr sceneItemOps(const Ufe::SceneItem::Ptr& item) const override; }; // UsdSceneItemOpsHandler } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdStageMap.cpp b/lib/mayaUsd/ufe/UsdStageMap.cpp index 90a82534e9..84171f1307 100644 --- a/lib/mayaUsd/ufe/UsdStageMap.cpp +++ b/lib/mayaUsd/ufe/UsdStageMap.cpp @@ -15,45 +15,43 @@ // #include "UsdStageMap.h" -#include - -#include - #include #include #include +#include + +#include + namespace { MObjectHandle proxyShapeHandle(const Ufe::Path& path) { - // Get the MObjectHandle from the tail of the MDagPath. Remove the leading - // '|world' component. - auto noWorld = path.popHead().string(); - auto dagPath = UsdMayaUtil::nameToDagPath(noWorld); - MObjectHandle handle(dagPath.node()); - if (!handle.isValid()) { - TF_CODING_ERROR("'%s' is not a path to a proxy shape node.", - noWorld.c_str()); - } - return handle; + // Get the MObjectHandle from the tail of the MDagPath. Remove the leading + // '|world' component. + auto noWorld = path.popHead().string(); + auto dagPath = UsdMayaUtil::nameToDagPath(noWorld); + MObjectHandle handle(dagPath.node()); + if (!handle.isValid()) { + TF_CODING_ERROR("'%s' is not a path to a proxy shape node.", noWorld.c_str()); + } + return handle; } // Assuming proxy shape nodes cannot be instanced, simply return the first path. Ufe::Path firstPath(const MObjectHandle& handle) { - if (!TF_VERIFY(handle.isValid(), - "Cannot get path from invalid object handle")) { - return Ufe::Path(); - } - - MDagPath dagPath; - auto status = MFnDagNode(handle.object()).getPath(dagPath); - CHECK_MSTATUS(status); - return MayaUsd::ufe::dagPathToUfe(dagPath); + if (!TF_VERIFY(handle.isValid(), "Cannot get path from invalid object handle")) { + return Ufe::Path(); + } + + MDagPath dagPath; + auto status = MFnDagNode(handle.object()).getPath(dagPath); + CHECK_MSTATUS(status); + return MayaUsd::ufe::dagPathToUfe(dagPath); } -} +} // namespace namespace MAYAUSD_NS_DEF { namespace ufe { @@ -70,78 +68,81 @@ UsdStageMap g_StageMap; void UsdStageMap::addItem(const Ufe::Path& path, UsdStageWeakPtr stage) { - // We expect a path to the proxy shape node, therefore a single segment. - auto nbSegments = + // We expect a path to the proxy shape node, therefore a single segment. + auto nbSegments = #ifdef UFE_V0_2_6_FEATURES_AVAILABLE path.nbSegments(); #else path.getSegments().size(); #endif - if (nbSegments != 1) { - TF_CODING_ERROR("A proxy shape node path can have only one segment, path '%s' has %lu", path.string().c_str(), nbSegments); - return; - } - - // Convert the tail of the UFE path to an MObjectHandle. - auto proxyShape = proxyShapeHandle(path); - if (!proxyShape.isValid()) { - return; - } - - // Could get the stage from the proxy shape object in the stage() method, - // but since it's given here, simply store it. - fObjectToStage[proxyShape] = stage; - fStageToObject[stage] = proxyShape; + if (nbSegments != 1) { + TF_CODING_ERROR( + "A proxy shape node path can have only one segment, path '%s' has %lu", + path.string().c_str(), + nbSegments); + return; + } + + // Convert the tail of the UFE path to an MObjectHandle. + auto proxyShape = proxyShapeHandle(path); + if (!proxyShape.isValid()) { + return; + } + + // Could get the stage from the proxy shape object in the stage() method, + // but since it's given here, simply store it. + fObjectToStage[proxyShape] = stage; + fStageToObject[stage] = proxyShape; } UsdStageWeakPtr UsdStageMap::stage(const Ufe::Path& path) { - rebuildIfDirty(); - - auto proxyShape = proxyShapeHandle(path); - if (!proxyShape.isValid()) { - return nullptr; - } - - // A stage is bound to a single Dag proxy shape. - auto iter = fObjectToStage.find(proxyShape); - if (iter != std::end(fObjectToStage)) - return iter->second; - return nullptr; + rebuildIfDirty(); + + auto proxyShape = proxyShapeHandle(path); + if (!proxyShape.isValid()) { + return nullptr; + } + + // A stage is bound to a single Dag proxy shape. + auto iter = fObjectToStage.find(proxyShape); + if (iter != std::end(fObjectToStage)) + return iter->second; + return nullptr; } Ufe::Path UsdStageMap::path(UsdStageWeakPtr stage) { - rebuildIfDirty(); + rebuildIfDirty(); - // A stage is bound to a single Dag proxy shape. - auto iter = fStageToObject.find(stage); - if (iter != std::end(fStageToObject)) - return firstPath(iter->second); - return Ufe::Path(); + // A stage is bound to a single Dag proxy shape. + auto iter = fStageToObject.find(stage); + if (iter != std::end(fStageToObject)) + return firstPath(iter->second); + return Ufe::Path(); } void UsdStageMap::setDirty() { - fObjectToStage.clear(); - fStageToObject.clear(); - fDirty = true; + fObjectToStage.clear(); + fStageToObject.clear(); + fDirty = true; } void UsdStageMap::rebuildIfDirty() { - if (!fDirty) return; - - auto proxyShapeNames = ProxyShapeHandler::getAllNames(); - for (const auto& psn : proxyShapeNames) - { - MDagPath dag = UsdMayaUtil::nameToDagPath(psn); - Ufe::Path ufePath = dagPathToUfe(dag); - auto stage = ProxyShapeHandler::dagPathToStage(psn); - addItem(ufePath, stage); - } - fDirty = false; + if (!fDirty) + return; + + auto proxyShapeNames = ProxyShapeHandler::getAllNames(); + for (const auto& psn : proxyShapeNames) { + MDagPath dag = UsdMayaUtil::nameToDagPath(psn); + Ufe::Path ufePath = dagPathToUfe(dag); + auto stage = ProxyShapeHandler::dagPathToStage(psn); + addItem(ufePath, stage); + } + fDirty = false; } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdStageMap.h b/lib/mayaUsd/ufe/UsdStageMap.h index bb0194ae80..0095ac943e 100644 --- a/lib/mayaUsd/ufe/UsdStageMap.h +++ b/lib/mayaUsd/ufe/UsdStageMap.h @@ -15,25 +15,26 @@ // #pragma once -#include +#include -#include +#include +#include #include +#include -#include -#include - -#include +#include // Allow for use of MObjectHandle with std::unordered_map. namespace std { -template <> struct hash { - std::size_t operator()(const MObjectHandle& handle) const { - return static_cast(handle.hashCode()); +template <> struct hash +{ + std::size_t operator()(const MObjectHandle& handle) const + { + return static_cast(handle.hashCode()); } }; -} +} // namespace std PXR_NAMESPACE_USING_DIRECTIVE @@ -42,56 +43,56 @@ namespace ufe { //! \brief USD Stage Map /*! - Two-way map of proxy shape UFE path to corresponding stage. - - We will assume that a USD proxy shape will not be instanced (even though - nothing in the data model prevents it). To support renaming and repathing, - we store an MObjectHandle in the maps, which is invariant to renaming and - repathing, and compute the path on access. This is slower than a scheme - where we cache using the Ufe::Path, but such a cache must be refreshed on - rename and repath, which is non-trivial, since there is no guarantee on the - order of notification of Ufe observers. An earlier implementation with - rename observation had the Maya Outliner (which observes rename) access the - UsdStageMap on rename before the UsdStageMap had been updated. + Two-way map of proxy shape UFE path to corresponding stage. + + We will assume that a USD proxy shape will not be instanced (even though + nothing in the data model prevents it). To support renaming and repathing, + we store an MObjectHandle in the maps, which is invariant to renaming and + repathing, and compute the path on access. This is slower than a scheme + where we cache using the Ufe::Path, but such a cache must be refreshed on + rename and repath, which is non-trivial, since there is no guarantee on the + order of notification of Ufe observers. An earlier implementation with + rename observation had the Maya Outliner (which observes rename) access the + UsdStageMap on rename before the UsdStageMap had been updated. */ class MAYAUSD_CORE_PUBLIC UsdStageMap { public: - UsdStageMap() = default; - ~UsdStageMap() = default; + UsdStageMap() = default; + ~UsdStageMap() = default; - // Delete the copy/move constructors assignment operators. - UsdStageMap(const UsdStageMap&) = delete; - UsdStageMap& operator=(const UsdStageMap&) = delete; - UsdStageMap(UsdStageMap&&) = delete; - UsdStageMap& operator=(UsdStageMap&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdStageMap(const UsdStageMap&) = delete; + UsdStageMap& operator=(const UsdStageMap&) = delete; + UsdStageMap(UsdStageMap&&) = delete; + UsdStageMap& operator=(UsdStageMap&&) = delete; - //! Get USD stage corresponding to argument Maya Dag path. - UsdStageWeakPtr stage(const Ufe::Path& path); + //! Get USD stage corresponding to argument Maya Dag path. + UsdStageWeakPtr stage(const Ufe::Path& path); - //! Return the ProxyShape node UFE path for the argument stage. - Ufe::Path path(UsdStageWeakPtr stage); + //! Return the ProxyShape node UFE path for the argument stage. + Ufe::Path path(UsdStageWeakPtr stage); - //! Set the stage map as dirty. It will be cleared immediately, but - //! only repopulated when stage info is requested. - void setDirty(); + //! Set the stage map as dirty. It will be cleared immediately, but + //! only repopulated when stage info is requested. + void setDirty(); - //! Returns true if the stage map is dirty (meaning it needs to be filled in). - bool isDirty() const { return fDirty; } + //! Returns true if the stage map is dirty (meaning it needs to be filled in). + bool isDirty() const { return fDirty; } private: - void addItem(const Ufe::Path& path, UsdStageWeakPtr stage); - void rebuildIfDirty(); + void addItem(const Ufe::Path& path, UsdStageWeakPtr stage); + void rebuildIfDirty(); private: - // We keep two maps for fast lookup when there are many proxy shapes. - using ObjectToStage = std::unordered_map; - using StageToObject = TfHashMap; - ObjectToStage fObjectToStage; - StageToObject fStageToObject; - bool fDirty{true}; + // We keep two maps for fast lookup when there are many proxy shapes. + using ObjectToStage = std::unordered_map; + using StageToObject = TfHashMap; + ObjectToStage fObjectToStage; + StageToObject fStageToObject; + bool fDirty { true }; }; // UsdStageMap } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdTRSUndoableCommandBase.cpp b/lib/mayaUsd/ufe/UsdTRSUndoableCommandBase.cpp index 72badcfd0d..a06e60dd48 100644 --- a/lib/mayaUsd/ufe/UsdTRSUndoableCommandBase.cpp +++ b/lib/mayaUsd/ufe/UsdTRSUndoableCommandBase.cpp @@ -15,6 +15,7 @@ // #include "UsdTRSUndoableCommandBase.h" + #include "private/Utils.h" #include @@ -23,95 +24,90 @@ namespace MAYAUSD_NS_DEF { namespace ufe { -template +template #ifdef UFE_V2_FEATURES_AVAILABLE UsdTRSUndoableCommandBase::UsdTRSUndoableCommandBase(double x, double y, double z) : fNewValue(x, y, z) #else UsdTRSUndoableCommandBase::UsdTRSUndoableCommandBase( - const UsdSceneItem::Ptr& item, double x, double y, double z -) : fItem(item), fNewValue(x, y, z) + const UsdSceneItem::Ptr& item, + double x, + double y, + double z) + : fItem(item) + , fNewValue(x, y, z) #endif { } #ifdef UFE_V2_FEATURES_AVAILABLE -template -void UsdTRSUndoableCommandBase::updateItem() const +template void UsdTRSUndoableCommandBase::updateItem() const { - if(!fItem) { + if (!fItem) { auto ufeSceneItemPtr = Ufe::Hierarchy::createItem(getPath()); fItem = std::dynamic_pointer_cast(ufeSceneItemPtr); } } #endif -template -void UsdTRSUndoableCommandBase::initialize() +template void UsdTRSUndoableCommandBase::initialize() { if (cannotInit()) { return; } // If prim does not have the attribute, add it. - if (!prim().HasAttribute(attributeName())) - { + if (!prim().HasAttribute(attributeName())) { fOpAdded = true; addEmptyAttribute(); } attribute().Get(&fPrevValue); - #if UFE_PREVIEW_VERSION_NUM < 2021 +#if UFE_PREVIEW_VERSION_NUM < 2021 Ufe::Scene::instance().addObjectPathChangeObserver(this->shared_from_this()); - #endif +#endif } #if UFE_PREVIEW_VERSION_NUM < 2021 -template -void UsdTRSUndoableCommandBase::operator()( - const Ufe::Notification& n -) +template void UsdTRSUndoableCommandBase::operator()(const Ufe::Notification& n) { if (auto renamed = dynamic_cast(&n)) { checkNotification(renamed); - } - else if (auto reparented = dynamic_cast(&n)) { + } else if (auto reparented = dynamic_cast(&n)) { checkNotification(reparented); } } #endif -template -void UsdTRSUndoableCommandBase::undoImp() +template void UsdTRSUndoableCommandBase::undoImp() { - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE // Set fItem to nullptr because the command does not know what can go on with the prim inside - // its item after their own undo() or redo(). Setting it back to nullptr is safer because it means - // that the next time the command is used, it will be forced to create a new item from the path, - // or the command will crash on a null pointer. + // its item after their own undo() or redo(). Setting it back to nullptr is safer because it + // means that the next time the command is used, it will be forced to create a new item from the + // path, or the command will crash on a null pointer. fItem = nullptr; updateItem(); - #endif +#endif attribute().Set(fPrevValue); // Todo : We would want to remove the xformOp // (SD-06/07/2018) Haven't found a clean way to do it - would need to investigate } -template -void UsdTRSUndoableCommandBase::redoImp() +template void UsdTRSUndoableCommandBase::redoImp() { - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE // Set fItem to nullptr because the command does not know what can go on with the prim inside - // its item after their own undo() or redo(). Setting it back to nullptr is safer because it means - // that the next time the command is used, it will be forced to create a new item from the path, - // or the command will crash on a null pointer. + // its item after their own undo() or redo(). Setting it back to nullptr is safer because it + // means that the next time the command is used, it will be forced to create a new item from the + // path, or the command will crash on a null pointer. fItem = nullptr; updateItem(); - #endif +#endif // We must go through conversion to the common transform API by calling // perform(), otherwise we get "Empty typeName" USD assertions for rotate @@ -125,8 +121,8 @@ void UsdTRSUndoableCommandBase::redoImp() } #if UFE_PREVIEW_VERSION_NUM < 2021 -template -template +template +template void UsdTRSUndoableCommandBase::checkNotification(const N* notification) { if (notification->previousPath() == path()) { @@ -135,22 +131,17 @@ void UsdTRSUndoableCommandBase::checkNotification(const N* notification) } #endif -template -void UsdTRSUndoableCommandBase::perform(double x, double y, double z) +template void UsdTRSUndoableCommandBase::perform(double x, double y, double z) { fNewValue = V(x, y, z); performImp(x, y, z); fDoneOnce = true; } -template -bool UsdTRSUndoableCommandBase::cannotInit() const -{ - return false; -} +template bool UsdTRSUndoableCommandBase::cannotInit() const { return false; } template class UsdTRSUndoableCommandBase; template class UsdTRSUndoableCommandBase; } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdTRSUndoableCommandBase.h b/lib/mayaUsd/ufe/UsdTRSUndoableCommandBase.h index 53cc7b9395..4c8253aa27 100644 --- a/lib/mayaUsd/ufe/UsdTRSUndoableCommandBase.h +++ b/lib/mayaUsd/ufe/UsdTRSUndoableCommandBase.h @@ -46,22 +46,22 @@ namespace ufe { // reparented. In such a case, the prim in the command's scene item // becomes stale, and the prim in the updated scene item should be used. // -template +template #ifdef UFE_V2_FEATURES_AVAILABLE -class MAYAUSD_CORE_PUBLIC UsdTRSUndoableCommandBase +class MAYAUSD_CORE_PUBLIC UsdTRSUndoableCommandBase : public std::enable_shared_from_this> #else -class MAYAUSD_CORE_PUBLIC UsdTRSUndoableCommandBase : public Ufe::Observer, - public std::enable_shared_from_this > +class MAYAUSD_CORE_PUBLIC UsdTRSUndoableCommandBase + : public Ufe::Observer + , public std::enable_shared_from_this> #endif { protected: - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE UsdTRSUndoableCommandBase(double x, double y, double z); - #else - UsdTRSUndoableCommandBase( - const UsdSceneItem::Ptr& item, double x, double y, double z); - #endif +#else + UsdTRSUndoableCommandBase(const UsdSceneItem::Ptr& item, double x, double y, double z); +#endif ~UsdTRSUndoableCommandBase() = default; @@ -79,62 +79,73 @@ class MAYAUSD_CORE_PUBLIC UsdTRSUndoableCommandBase : public Ufe::Observer, // parenting change caused by undo / redo of other commands in the undo // stack), so always return current data. - #ifdef UFE_V2_FEATURES_AVAILABLE - inline UsdPrim prim() const { updateItem(); return fItem->prim(); }; - #else - inline UsdPrim prim() const { return fItem->prim(); } +#ifdef UFE_V2_FEATURES_AVAILABLE + inline UsdPrim prim() const + { + updateItem(); + return fItem->prim(); + }; +#else + inline UsdPrim prim() const { return fItem->prim(); } inline Ufe::Path path() const { return fItem->path(); } - #endif +#endif // Hooks to be implemented by the derived class: name of the attribute set // by the command, implementation of perform(), and add empty attribute. // Implementation of cannotInit() in this class returns false. virtual TfToken attributeName() const = 0; - virtual void performImp(double x, double y, double z) = 0; - virtual void addEmptyAttribute() = 0; - virtual bool cannotInit() const; + virtual void performImp(double x, double y, double z) = 0; + virtual void addEmptyAttribute() = 0; + virtual bool cannotInit() const; - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE // Conditionally create a UsdSceneItem::Ptr from the Ufe::Path, if null. void updateItem() const; // Returns the new Ufe::Path overriden by derived classes (e.g TRS) virtual Ufe::Path getPath() const = 0; - #endif +#endif private: - - #if UFE_PREVIEW_VERSION_NUM < 2021 +#if UFE_PREVIEW_VERSION_NUM < 2021 // Overridden from Ufe::Observer void operator()(const Ufe::Notification& notification) override; - template void checkNotification(const N* notification); - #endif + template void checkNotification(const N* notification); +#endif - inline UsdAttribute attribute() const { - return prim().GetAttribute(attributeName()); - } + inline UsdAttribute attribute() const { return prim().GetAttribute(attributeName()); } - mutable UsdSceneItem::Ptr fItem{nullptr}; + mutable UsdSceneItem::Ptr fItem { nullptr }; V fPrevValue; V fNewValue; - bool fOpAdded{false}; - bool fDoneOnce{false}; + bool fOpAdded { false }; + bool fDoneOnce { false }; }; // UsdTRSUndoableCommandBase // shared_ptr requires public ctor, dtor, so derive a class for it. -template -struct MakeSharedEnabler : public T { +template struct MakeSharedEnabler : public T +{ MakeSharedEnabler( #ifdef UFE_V2_FEATURES_AVAILABLE - const Ufe::Path& path, double x, double y, double z) - : T(path, x, y, z) {} + const Ufe::Path& path, + double x, + double y, + double z) + : T(path, x, y, z) + { + } }; #else - const UsdSceneItem::Ptr& item, double x, double y, double z) - : T(item, x, y, z) {} + const UsdSceneItem::Ptr& item, + double x, + double y, + double z) + : T(item, x, y, z) + { + } }; #endif } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdTransform3d.cpp b/lib/mayaUsd/ufe/UsdTransform3d.cpp index daa4964fec..fbceaf6449 100644 --- a/lib/mayaUsd/ufe/UsdTransform3d.cpp +++ b/lib/mayaUsd/ufe/UsdTransform3d.cpp @@ -15,7 +15,7 @@ // #include "UsdTransform3d.h" -#include +#include "private/Utils.h" #include #include @@ -23,82 +23,72 @@ #include #include -#include "private/Utils.h" +#include namespace MAYAUSD_NS_DEF { namespace ufe { namespace { - Ufe::Matrix4d convertFromUsd(const GfMatrix4d& matrix) - { - // Even though memory layout of Ufe::Matrix4d and double[4][4] are identical - // we need to return a copy of the matrix so we cannot cast. - double m[4][4]; - matrix.Get(m); - Ufe::Matrix4d uMat; - uMat.matrix = {{ {{m[0][0], m[0][1], m[0][2], m[0][3]}}, - {{m[1][0], m[1][1], m[1][2], m[1][3]}}, - {{m[2][0], m[2][1], m[2][2], m[2][3]}}, - {{m[3][0], m[3][1], m[3][2], m[3][3]}} }}; - return uMat; - } +Ufe::Matrix4d convertFromUsd(const GfMatrix4d& matrix) +{ + // Even though memory layout of Ufe::Matrix4d and double[4][4] are identical + // we need to return a copy of the matrix so we cannot cast. + double m[4][4]; + matrix.Get(m); + Ufe::Matrix4d uMat; + uMat.matrix = { { { { m[0][0], m[0][1], m[0][2], m[0][3] } }, + { { m[1][0], m[1][1], m[1][2], m[1][3] } }, + { { m[2][0], m[2][1], m[2][2], m[2][3] } }, + { { m[3][0], m[3][1], m[3][2], m[3][3] } } } }; + return uMat; +} - Ufe::Matrix4d primToUfeXform(const UsdPrim& prim, const UsdTimeCode& time) - { - UsdGeomXformCache xformCache(time); - GfMatrix4d usdMatrix = xformCache.GetLocalToWorldTransform(prim); - Ufe::Matrix4d xform = convertFromUsd(usdMatrix); - return xform; - } +Ufe::Matrix4d primToUfeXform(const UsdPrim& prim, const UsdTimeCode& time) +{ + UsdGeomXformCache xformCache(time); + GfMatrix4d usdMatrix = xformCache.GetLocalToWorldTransform(prim); + Ufe::Matrix4d xform = convertFromUsd(usdMatrix); + return xform; +} - Ufe::Matrix4d primToUfeExclusiveXform(const UsdPrim& prim, const UsdTimeCode& time) - { - UsdGeomXformCache xformCache(time); - GfMatrix4d usdMatrix = xformCache.GetParentToWorldTransform(prim); - Ufe::Matrix4d xform = convertFromUsd(usdMatrix); - return xform; - } +Ufe::Matrix4d primToUfeExclusiveXform(const UsdPrim& prim, const UsdTimeCode& time) +{ + UsdGeomXformCache xformCache(time); + GfMatrix4d usdMatrix = xformCache.GetParentToWorldTransform(prim); + Ufe::Matrix4d xform = convertFromUsd(usdMatrix); + return xform; } +} // namespace -UsdTransform3d::UsdTransform3d() : Transform3d() +UsdTransform3d::UsdTransform3d() + : Transform3d() { } UsdTransform3d::UsdTransform3d(const UsdSceneItem::Ptr& item) : Transform3d() , fItem(item) -{} - -/*static*/ -UsdTransform3d::Ptr UsdTransform3d::create() { - return std::make_shared(); } +/*static*/ +UsdTransform3d::Ptr UsdTransform3d::create() { return std::make_shared(); } + /* static */ UsdTransform3d::Ptr UsdTransform3d::create(const UsdSceneItem::Ptr& item) { return std::make_shared(item); } -void UsdTransform3d::setItem(const UsdSceneItem::Ptr& item) -{ - fItem = item; -} +void UsdTransform3d::setItem(const UsdSceneItem::Ptr& item) { fItem = item; } //------------------------------------------------------------------------------ // Ufe::Transform3d overrides //------------------------------------------------------------------------------ -const Ufe::Path& UsdTransform3d::path() const -{ - return fItem->path(); -} +const Ufe::Path& UsdTransform3d::path() const { return fItem->path(); } -Ufe::SceneItem::Ptr UsdTransform3d::sceneItem() const -{ - return fItem; -} +Ufe::SceneItem::Ptr UsdTransform3d::sceneItem() const { return fItem; } #ifdef UFE_V2_FEATURES_AVAILABLE Ufe::TranslateUndoableCommand::Ptr UsdTransform3d::translateCmd(double x, double y, double z) @@ -114,15 +104,15 @@ void UsdTransform3d::translate(double x, double y, double z) Ufe::Vector3d UsdTransform3d::translation() const { - double x{0}, y{0}, z{0}; + double x { 0 }, y { 0 }, z { 0 }; const TfToken xlate("xformOp:translate"); - if (prim().HasAttribute(xlate)) - { + if (prim().HasAttribute(xlate)) { // Initially, attribute can be created, but have no value. GfVec3d v; - if (prim().GetAttribute(xlate).Get(&v,getTime(path()))) - { - x = v[0]; y = v[1]; z = v[2]; + if (prim().GetAttribute(xlate).Get(&v, getTime(path()))) { + x = v[0]; + y = v[1]; + z = v[2]; } } return Ufe::Vector3d(x, y, z); @@ -131,15 +121,15 @@ Ufe::Vector3d UsdTransform3d::translation() const #ifdef UFE_V2_FEATURES_AVAILABLE Ufe::Vector3d UsdTransform3d::rotation() const { - double x{0}, y{0}, z{0}; + double x { 0 }, y { 0 }, z { 0 }; const TfToken rotXYZ("xformOp:rotateXYZ"); - if (prim().HasAttribute(rotXYZ)) - { + if (prim().HasAttribute(rotXYZ)) { // Initially, attribute can be created, but have no value. GfVec3f v; - if (prim().GetAttribute(rotXYZ).Get(&v,getTime(path()))) - { - x = v[0]; y = v[1]; z = v[2]; + if (prim().GetAttribute(rotXYZ).Get(&v, getTime(path()))) { + x = v[0]; + y = v[1]; + z = v[2]; } } return Ufe::Vector3d(x, y, z); @@ -147,15 +137,15 @@ Ufe::Vector3d UsdTransform3d::rotation() const Ufe::Vector3d UsdTransform3d::scale() const { - double x{0}, y{0}, z{0}; + double x { 0 }, y { 0 }, z { 0 }; const TfToken scaleTok("xformOp:scale"); - if (prim().HasAttribute(scaleTok)) - { + if (prim().HasAttribute(scaleTok)) { // Initially, attribute can be created, but have no value. GfVec3f v; - if (prim().GetAttribute(scaleTok).Get(&v,getTime(path()))) - { - x = v[0]; y = v[1]; z = v[2]; + if (prim().GetAttribute(scaleTok).Get(&v, getTime(path()))) { + x = v[0]; + y = v[1]; + z = v[2]; } } return Ufe::Vector3d(x, y, z); @@ -209,7 +199,7 @@ Ufe::SetMatrixUndoableCommand::Ptr UsdTransform3d::setMatrixCmd(const Ufe::Matri Ufe::Matrix4d UsdTransform3d::matrix() const { // TODO: HS Aug25,2020 dummy code to pass the compiler errors - Ufe::Matrix4d m{}; + Ufe::Matrix4d m {}; return m; } #endif @@ -235,12 +225,13 @@ void UsdTransform3d::rotatePivot(double x, double y, double z) #else Ufe::TranslateUndoableCommand::Ptr UsdTransform3d::rotatePivotTranslateCmd() { - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE return UsdRotatePivotTranslateUndoableCommand::create(fItem->path()); - #else - auto translateCmd = UsdRotatePivotTranslateUndoableCommand::create(prim(), fItem->path(), fItem); +#else + auto translateCmd + = UsdRotatePivotTranslateUndoableCommand::create(prim(), fItem->path(), fItem); return translateCmd; - #endif +#endif } void UsdTransform3d::rotatePivotTranslate(double x, double y, double z) @@ -251,15 +242,15 @@ void UsdTransform3d::rotatePivotTranslate(double x, double y, double z) Ufe::Vector3d UsdTransform3d::rotatePivot() const { - double x{0}, y{0}, z{0}; + double x { 0 }, y { 0 }, z { 0 }; const TfToken xpivot("xformOp:translate:pivot"); - if (prim().HasAttribute(xpivot)) - { + if (prim().HasAttribute(xpivot)) { // Initially, attribute can be created, but have no value. GfVec3f v; - if (prim().GetAttribute(xpivot).Get(&v,getTime(path()))) - { - x = v[0]; y = v[1]; z = v[2]; + if (prim().GetAttribute(xpivot).Get(&v, getTime(path()))) { + x = v[0]; + y = v[1]; + z = v[2]; } } return Ufe::Vector3d(x, y, z); @@ -272,10 +263,7 @@ Ufe::TranslateUndoableCommand::Ptr UsdTransform3d::scalePivotCmd(double, double, return nullptr; } -void UsdTransform3d::scalePivot(double x, double y, double z) -{ - return rotatePivot(x, y, z); -} +void UsdTransform3d::scalePivot(double x, double y, double z) { return rotatePivot(x, y, z); } #else Ufe::TranslateUndoableCommand::Ptr UsdTransform3d::scalePivotTranslateCmd() { @@ -288,20 +276,17 @@ void UsdTransform3d::scalePivotTranslate(double x, double y, double z) } #endif -Ufe::Vector3d UsdTransform3d::scalePivot() const -{ - return rotatePivot(); -} +Ufe::Vector3d UsdTransform3d::scalePivot() const { return rotatePivot(); } Ufe::Matrix4d UsdTransform3d::segmentInclusiveMatrix() const { - return primToUfeXform(prim(),getTime(path())); + return primToUfeXform(prim(), getTime(path())); } - + Ufe::Matrix4d UsdTransform3d::segmentExclusiveMatrix() const { - return primToUfeExclusiveXform(prim(),getTime(path())); + return primToUfeExclusiveXform(prim(), getTime(path())); } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdTransform3d.h b/lib/mayaUsd/ufe/UsdTransform3d.h index 9aea06c994..cc86ae77d2 100644 --- a/lib/mayaUsd/ufe/UsdTransform3d.h +++ b/lib/mayaUsd/ufe/UsdTransform3d.h @@ -15,13 +15,13 @@ // #pragma once -#include -#include +#include +#include #include -#include -#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -32,75 +32,79 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdTransform3d : public Ufe::Transform3d { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdTransform3d(); - UsdTransform3d(const UsdSceneItem::Ptr& item); - ~UsdTransform3d() override = default; + UsdTransform3d(); + UsdTransform3d(const UsdSceneItem::Ptr& item); + ~UsdTransform3d() override = default; - // Delete the copy/move constructors assignment operators. - UsdTransform3d(const UsdTransform3d&) = delete; - UsdTransform3d& operator=(const UsdTransform3d&) = delete; - UsdTransform3d(UsdTransform3d&&) = delete; - UsdTransform3d& operator=(UsdTransform3d&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdTransform3d(const UsdTransform3d&) = delete; + UsdTransform3d& operator=(const UsdTransform3d&) = delete; + UsdTransform3d(UsdTransform3d&&) = delete; + UsdTransform3d& operator=(UsdTransform3d&&) = delete; - //! Create a UsdTransform3d. - static UsdTransform3d::Ptr create(); - static UsdTransform3d::Ptr create(const UsdSceneItem::Ptr& item); + //! Create a UsdTransform3d. + static UsdTransform3d::Ptr create(); + static UsdTransform3d::Ptr create(const UsdSceneItem::Ptr& item); - void setItem(const UsdSceneItem::Ptr& item); + void setItem(const UsdSceneItem::Ptr& item); - // Ufe::Transform3d overrides - const Ufe::Path& path() const override; - Ufe::SceneItem::Ptr sceneItem() const override; - inline UsdPrim prim() const { TF_AXIOM(fItem != nullptr); return fItem->prim(); } + // Ufe::Transform3d overrides + const Ufe::Path& path() const override; + Ufe::SceneItem::Ptr sceneItem() const override; + inline UsdPrim prim() const + { + TF_AXIOM(fItem != nullptr); + return fItem->prim(); + } #ifdef UFE_V2_FEATURES_AVAILABLE - Ufe::TranslateUndoableCommand::Ptr translateCmd(double x, double y, double z) override; - Ufe::RotateUndoableCommand::Ptr rotateCmd(double x, double y, double z) override; - Ufe::ScaleUndoableCommand::Ptr scaleCmd(double x, double y, double z) override; - Ufe::Vector3d rotation() const override; - Ufe::Vector3d scale() const override; + Ufe::TranslateUndoableCommand::Ptr translateCmd(double x, double y, double z) override; + Ufe::RotateUndoableCommand::Ptr rotateCmd(double x, double y, double z) override; + Ufe::ScaleUndoableCommand::Ptr scaleCmd(double x, double y, double z) override; + Ufe::Vector3d rotation() const override; + Ufe::Vector3d scale() const override; #else - Ufe::TranslateUndoableCommand::Ptr translateCmd() override; - Ufe::RotateUndoableCommand::Ptr rotateCmd() override; - Ufe::ScaleUndoableCommand::Ptr scaleCmd() override; + Ufe::TranslateUndoableCommand::Ptr translateCmd() override; + Ufe::RotateUndoableCommand::Ptr rotateCmd() override; + Ufe::ScaleUndoableCommand::Ptr scaleCmd() override; #endif #ifdef UFE_V2_FEATURES_AVAILABLE #if UFE_PREVIEW_VERSION_NUM >= 2025 - Ufe::SetMatrix4dUndoableCommand::Ptr setMatrixCmd(const Ufe::Matrix4d& m) override; + Ufe::SetMatrix4dUndoableCommand::Ptr setMatrixCmd(const Ufe::Matrix4d& m) override; #else - Ufe::SetMatrixUndoableCommand::Ptr setMatrixCmd(const Ufe::Matrix4d& m) override; + Ufe::SetMatrixUndoableCommand::Ptr setMatrixCmd(const Ufe::Matrix4d& m) override; #endif - Ufe::Matrix4d matrix() const override; + Ufe::Matrix4d matrix() const override; #endif - void translate(double x, double y, double z) override; - Ufe::Vector3d translation() const override; - void rotate(double x, double y, double z) override; - void scale(double x, double y, double z) override; + void translate(double x, double y, double z) override; + Ufe::Vector3d translation() const override; + void rotate(double x, double y, double z) override; + void scale(double x, double y, double z) override; #if UFE_PREVIEW_VERSION_NUM >= 2025 -//#ifdef UFE_V2_FEATURES_AVAILABLE - Ufe::TranslateUndoableCommand::Ptr rotatePivotCmd(double x, double y, double z) override; - void rotatePivot(double x, double y, double z) override; - Ufe::TranslateUndoableCommand::Ptr scalePivotCmd(double x, double y, double z) override; - void scalePivot(double x, double y, double z) override; + //#ifdef UFE_V2_FEATURES_AVAILABLE + Ufe::TranslateUndoableCommand::Ptr rotatePivotCmd(double x, double y, double z) override; + void rotatePivot(double x, double y, double z) override; + Ufe::TranslateUndoableCommand::Ptr scalePivotCmd(double x, double y, double z) override; + void scalePivot(double x, double y, double z) override; #else - Ufe::TranslateUndoableCommand::Ptr rotatePivotTranslateCmd() override; - void rotatePivotTranslate(double x, double y, double z) override; - Ufe::TranslateUndoableCommand::Ptr scalePivotTranslateCmd() override; - void scalePivotTranslate(double x, double y, double z) override; + Ufe::TranslateUndoableCommand::Ptr rotatePivotTranslateCmd() override; + void rotatePivotTranslate(double x, double y, double z) override; + Ufe::TranslateUndoableCommand::Ptr scalePivotTranslateCmd() override; + void scalePivotTranslate(double x, double y, double z) override; #endif - Ufe::Vector3d rotatePivot() const override; - Ufe::Vector3d scalePivot() const override; - Ufe::Matrix4d segmentInclusiveMatrix() const override; - Ufe::Matrix4d segmentExclusiveMatrix() const override; + Ufe::Vector3d rotatePivot() const override; + Ufe::Vector3d scalePivot() const override; + Ufe::Matrix4d segmentInclusiveMatrix() const override; + Ufe::Matrix4d segmentExclusiveMatrix() const override; private: - UsdSceneItem::Ptr fItem; + UsdSceneItem::Ptr fItem; }; // UsdTransform3d } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdTransform3dHandler.cpp b/lib/mayaUsd/ufe/UsdTransform3dHandler.cpp index c31aa94ffe..f62f5b32f8 100644 --- a/lib/mayaUsd/ufe/UsdTransform3dHandler.cpp +++ b/lib/mayaUsd/ufe/UsdTransform3dHandler.cpp @@ -20,17 +20,17 @@ namespace MAYAUSD_NS_DEF { namespace ufe { -UsdTransform3dHandler::UsdTransform3dHandler() : Ufe::Transform3dHandler() -{} - -UsdTransform3dHandler::~UsdTransform3dHandler() +UsdTransform3dHandler::UsdTransform3dHandler() + : Ufe::Transform3dHandler() { } +UsdTransform3dHandler::~UsdTransform3dHandler() { } + /*static*/ UsdTransform3dHandler::Ptr UsdTransform3dHandler::create() { - return std::make_shared(); + return std::make_shared(); } //------------------------------------------------------------------------------ @@ -39,12 +39,12 @@ UsdTransform3dHandler::Ptr UsdTransform3dHandler::create() Ufe::Transform3d::Ptr UsdTransform3dHandler::transform3d(const Ufe::SceneItem::Ptr& item) const { - UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); + UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); #if !defined(NDEBUG) - assert(usdItem); + assert(usdItem); #endif - return UsdTransform3d::create(usdItem); + return UsdTransform3d::create(usdItem); } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdTransform3dHandler.h b/lib/mayaUsd/ufe/UsdTransform3dHandler.h index 13524e16da..13b0d5e047 100644 --- a/lib/mayaUsd/ufe/UsdTransform3dHandler.h +++ b/lib/mayaUsd/ufe/UsdTransform3dHandler.h @@ -15,11 +15,11 @@ // #pragma once -#include - #include #include +#include + namespace MAYAUSD_NS_DEF { namespace ufe { @@ -27,24 +27,24 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdTransform3dHandler : public Ufe::Transform3dHandler { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdTransform3dHandler(); - ~UsdTransform3dHandler(); + UsdTransform3dHandler(); + ~UsdTransform3dHandler(); - // Delete the copy/move constructors assignment operators. - UsdTransform3dHandler(const UsdTransform3dHandler&) = delete; - UsdTransform3dHandler& operator=(const UsdTransform3dHandler&) = delete; - UsdTransform3dHandler(UsdTransform3dHandler&&) = delete; - UsdTransform3dHandler& operator=(UsdTransform3dHandler&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdTransform3dHandler(const UsdTransform3dHandler&) = delete; + UsdTransform3dHandler& operator=(const UsdTransform3dHandler&) = delete; + UsdTransform3dHandler(UsdTransform3dHandler&&) = delete; + UsdTransform3dHandler& operator=(UsdTransform3dHandler&&) = delete; - //! Create a UsdTransform3dHandler. - static UsdTransform3dHandler::Ptr create(); + //! Create a UsdTransform3dHandler. + static UsdTransform3dHandler::Ptr create(); - // Ufe::Transform3dHandler overrides - Ufe::Transform3d::Ptr transform3d(const Ufe::SceneItem::Ptr& item) const override; + // Ufe::Transform3dHandler overrides + Ufe::Transform3d::Ptr transform3d(const Ufe::SceneItem::Ptr& item) const override; }; // UsdTransform3dHandler } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdTranslateUndoableCommand.cpp b/lib/mayaUsd/ufe/UsdTranslateUndoableCommand.cpp index 5e3519ec21..ae4563bac0 100644 --- a/lib/mayaUsd/ufe/UsdTranslateUndoableCommand.cpp +++ b/lib/mayaUsd/ufe/UsdTranslateUndoableCommand.cpp @@ -23,57 +23,55 @@ namespace ufe { TfToken UsdTranslateUndoableCommand::xlate("xformOp:translate"); #ifdef UFE_V2_FEATURES_AVAILABLE -UsdTranslateUndoableCommand::UsdTranslateUndoableCommand(const Ufe::Path& path, double x, double y, double z) +UsdTranslateUndoableCommand::UsdTranslateUndoableCommand( + const Ufe::Path& path, + double x, + double y, + double z) : Ufe::TranslateUndoableCommand(path) , UsdTRSUndoableCommandBase(x, y, z) -{} +{ +} #else UsdTranslateUndoableCommand::UsdTranslateUndoableCommand( - const UsdSceneItem::Ptr& item, double x, double y, double z -) : Ufe::TranslateUndoableCommand(item), - UsdTRSUndoableCommandBase(item, x, y, z) -{} + const UsdSceneItem::Ptr& item, + double x, + double y, + double z) + : Ufe::TranslateUndoableCommand(item) + , UsdTRSUndoableCommandBase(item, x, y, z) +{ +} #endif -UsdTranslateUndoableCommand::~UsdTranslateUndoableCommand() -{} +UsdTranslateUndoableCommand::~UsdTranslateUndoableCommand() { } /*static*/ #ifdef UFE_V2_FEATURES_AVAILABLE -UsdTranslateUndoableCommand::Ptr UsdTranslateUndoableCommand::create( - const Ufe::Path& path, double x, double y, double z -) +UsdTranslateUndoableCommand::Ptr +UsdTranslateUndoableCommand::create(const Ufe::Path& path, double x, double y, double z) { - auto cmd = std::make_shared>( - path, x, y, z); + auto cmd = std::make_shared>(path, x, y, z); cmd->initialize(); return cmd; } #else -UsdTranslateUndoableCommand::Ptr UsdTranslateUndoableCommand::create( - const UsdSceneItem::Ptr& item, double x, double y, double z -) +UsdTranslateUndoableCommand::Ptr +UsdTranslateUndoableCommand::create(const UsdSceneItem::Ptr& item, double x, double y, double z) { - auto cmd = std::make_shared>( - item, x, y, z); + auto cmd = std::make_shared>(item, x, y, z); cmd->initialize(); return cmd; } #endif -void UsdTranslateUndoableCommand::undo() -{ - undoImp(); -} +void UsdTranslateUndoableCommand::undo() { undoImp(); } -void UsdTranslateUndoableCommand::redo() -{ - redoImp(); -} +void UsdTranslateUndoableCommand::redo() { redoImp(); } void UsdTranslateUndoableCommand::addEmptyAttribute() { - performImp(0, 0, 0); // Add an empty translate + performImp(0, 0, 0); // Add an empty translate } void UsdTranslateUndoableCommand::performImp(double x, double y, double z) @@ -97,4 +95,4 @@ bool UsdTranslateUndoableCommand::translate(double x, double y, double z) } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdTranslateUndoableCommand.h b/lib/mayaUsd/ufe/UsdTranslateUndoableCommand.h index 2ea47d18c0..0db39f71a3 100644 --- a/lib/mayaUsd/ufe/UsdTranslateUndoableCommand.h +++ b/lib/mayaUsd/ufe/UsdTranslateUndoableCommand.h @@ -15,12 +15,12 @@ // #pragma once -#include +#include +#include #include -#include -#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -29,65 +29,65 @@ namespace ufe { //! \brief Translation command of the given prim. /*! - Ability to perform undo to restore the original translate value. + Ability to perform undo to restore the original translate value. */ -class MAYAUSD_CORE_PUBLIC UsdTranslateUndoableCommand : public Ufe::TranslateUndoableCommand, public UsdTRSUndoableCommandBase +class MAYAUSD_CORE_PUBLIC UsdTranslateUndoableCommand + : public Ufe::TranslateUndoableCommand + , public UsdTRSUndoableCommandBase { public: - typedef std::shared_ptr Ptr; - - UsdTranslateUndoableCommand(const UsdTranslateUndoableCommand&) = delete; - UsdTranslateUndoableCommand& operator=(const UsdTranslateUndoableCommand&) = delete; - UsdTranslateUndoableCommand(UsdTranslateUndoableCommand&&) = delete; - UsdTranslateUndoableCommand& operator=(UsdTranslateUndoableCommand&&) = delete; - - #ifdef UFE_V2_FEATURES_AVAILABLE - //! Create a UsdTranslateUndoableCommand from a UFE scene path. The - //! command is not executed. - static UsdTranslateUndoableCommand::Ptr create( - const Ufe::Path& path, double x, double y, double z); - #else - //! Create a UsdTranslateUndoableCommand from a UFE scene item. The - //! command is not executed. - static UsdTranslateUndoableCommand::Ptr create( - const UsdSceneItem::Ptr& item, double x, double y, double z); - #endif - - // Ufe::TranslateUndoableCommand overrides. translate() sets the command's - // translation value and executes the command. - void undo() override; - void redo() override; + typedef std::shared_ptr Ptr; + + UsdTranslateUndoableCommand(const UsdTranslateUndoableCommand&) = delete; + UsdTranslateUndoableCommand& operator=(const UsdTranslateUndoableCommand&) = delete; + UsdTranslateUndoableCommand(UsdTranslateUndoableCommand&&) = delete; + UsdTranslateUndoableCommand& operator=(UsdTranslateUndoableCommand&&) = delete; + +#ifdef UFE_V2_FEATURES_AVAILABLE + //! Create a UsdTranslateUndoableCommand from a UFE scene path. The + //! command is not executed. + static UsdTranslateUndoableCommand::Ptr + create(const Ufe::Path& path, double x, double y, double z); +#else + //! Create a UsdTranslateUndoableCommand from a UFE scene item. The + //! command is not executed. + static UsdTranslateUndoableCommand::Ptr + create(const UsdSceneItem::Ptr& item, double x, double y, double z); +#endif + + // Ufe::TranslateUndoableCommand overrides. translate() sets the command's + // translation value and executes the command. + void undo() override; + void redo() override; #if UFE_PREVIEW_VERSION_NUM >= 2025 -//#ifdef UFE_V2_FEATURES_AVAILABLE - bool set(double x, double y, double z) override; + //#ifdef UFE_V2_FEATURES_AVAILABLE + bool set(double x, double y, double z) override; #else - bool translate(double x, double y, double z) override; + bool translate(double x, double y, double z) override; #endif - #ifdef UFE_V2_FEATURES_AVAILABLE - Ufe::Path getPath() const override { return path(); } - #endif +#ifdef UFE_V2_FEATURES_AVAILABLE + Ufe::Path getPath() const override { return path(); } +#endif protected: - //! Construct a UsdTranslateUndoableCommand. The command is not executed. - #ifdef UFE_V2_FEATURES_AVAILABLE - UsdTranslateUndoableCommand(const Ufe::Path& path, double x, double y, double z); - #else - UsdTranslateUndoableCommand(const UsdSceneItem::Ptr& item, double x, double y, double z); - #endif +#ifdef UFE_V2_FEATURES_AVAILABLE + UsdTranslateUndoableCommand(const Ufe::Path& path, double x, double y, double z); +#else + UsdTranslateUndoableCommand(const UsdSceneItem::Ptr& item, double x, double y, double z); +#endif - ~UsdTranslateUndoableCommand() override; + ~UsdTranslateUndoableCommand() override; private: - static TfToken xlate; TfToken attributeName() const override { return xlate; } - void performImp(double x, double y, double z) override; - void addEmptyAttribute() override; + void performImp(double x, double y, double z) override; + void addEmptyAttribute() override; }; // UsdTranslateUndoableCommand } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUIInfoHandler.cpp b/lib/mayaUsd/ufe/UsdUIInfoHandler.cpp index 333642f51f..ccca12d502 100644 --- a/lib/mayaUsd/ufe/UsdUIInfoHandler.cpp +++ b/lib/mayaUsd/ufe/UsdUIInfoHandler.cpp @@ -14,12 +14,13 @@ // limitations under the License. // #include "UsdUIInfoHandler.h" + #include "UsdSceneItem.h" #if UFE_PREVIEW_VERSION_NUM >= 2024 +#include // SdfReferenceListOp/SdfPayloadListOp/SdfPathListOp +#include // SdfFieldKeys #include -#include // SdfFieldKeys -#include // SdfReferenceListOp/SdfPayloadListOp/SdfPathListOp #endif #include @@ -29,57 +30,62 @@ #include #if UFE_PREVIEW_VERSION_NUM >= 2024 -namespace +namespace { +// Simple helper to add the metadata strings to the end of the input tooltip string. +// Depending on the count, will add singular string or plural (with count). +void addMetadataStrings( + const int nb, + std::string& tooltip, + bool& needComma, + const std::string& singular, + const std::string& plural) +{ + if (nb <= 0) + return; + if (tooltip.empty()) + tooltip += "Introduced Composition Arcs: "; + if (needComma) + tooltip += ", "; + if (nb == 1) { + tooltip += singular; + } else { + tooltip += std::to_string(nb); + tooltip += " "; + tooltip += plural; + } + needComma = true; +} + +// Simple template helper function to handle all the various types of listOps. +template +void addMetadataCount( + const T& op, + std::string& tooltip, + bool& needComma, + const std::string& singular, + const std::string& plural) { - // Simple helper to add the metadata strings to the end of the input tooltip string. - // Depending on the count, will add singular string or plural (with count). - void addMetadataStrings(const int nb, std::string& tooltip, bool& needComma, const std::string& singular, const std::string& plural) - { - if (nb <= 0) return; - if (tooltip.empty()) - tooltip += "Introduced Composition Arcs: "; - if (needComma) - tooltip += ", "; - if (nb == 1) { - tooltip += singular; - } - else { - tooltip += std::to_string(nb); - tooltip += " "; - tooltip += plural; - } - needComma = true; - } - - // Simple template helper function to handle all the various types of listOps. - template - void addMetadataCount(const T& op, std::string& tooltip, bool& needComma, const std::string& singular, const std::string& plural) - { - typename T::ItemVector refs; - op.ApplyOperations(&refs); - if (!refs.empty()) { - addMetadataStrings(refs.size(), tooltip, needComma, singular, plural); - } - } + typename T::ItemVector refs; + op.ApplyOperations(&refs); + if (!refs.empty()) { + addMetadataStrings(refs.size(), tooltip, needComma, singular, plural); + } } +} // namespace #endif namespace MAYAUSD_NS_DEF { namespace ufe { UsdUIInfoHandler::UsdUIInfoHandler() - : Ufe::UIInfoHandler() -{} - -UsdUIInfoHandler::~UsdUIInfoHandler() + : Ufe::UIInfoHandler() { } +UsdUIInfoHandler::~UsdUIInfoHandler() { } + /*static*/ -UsdUIInfoHandler::Ptr UsdUIInfoHandler::create() -{ - return std::make_shared(); -} +UsdUIInfoHandler::Ptr UsdUIInfoHandler::create() { return std::make_shared(); } //------------------------------------------------------------------------------ // Ufe::UIInfoHandler overrides @@ -87,33 +93,32 @@ UsdUIInfoHandler::Ptr UsdUIInfoHandler::create() bool UsdUIInfoHandler::treeViewCellInfo(const Ufe::SceneItem::Ptr& item, Ufe::CellInfo& info) const { - bool changed = false; - UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); + bool changed = false; + UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); #if !defined(NDEBUG) - assert(usdItem); + assert(usdItem); #endif - if (usdItem) - { - if (!usdItem->prim().IsActive()) - { - changed = true; - info.fontStrikeout = true; - MDoubleArray outlinerInvisibleColor; - if (MGlobal::executeCommand("displayRGBColor -q \"outlinerInvisibleColor\"", outlinerInvisibleColor) && - (outlinerInvisibleColor.length() == 3)) - { - double rgb[3]; - outlinerInvisibleColor.get(rgb); - info.textFgColor.set(static_cast(rgb[0]), static_cast(rgb[1]), static_cast(rgb[2])); - } - else - { - info.textFgColor.set(0.403922f, 0.403922f, 0.403922f); - } - } - } - - return changed; + if (usdItem) { + if (!usdItem->prim().IsActive()) { + changed = true; + info.fontStrikeout = true; + MDoubleArray outlinerInvisibleColor; + if (MGlobal::executeCommand( + "displayRGBColor -q \"outlinerInvisibleColor\"", outlinerInvisibleColor) + && (outlinerInvisibleColor.length() == 3)) { + double rgb[3]; + outlinerInvisibleColor.get(rgb); + info.textFgColor.set( + static_cast(rgb[0]), + static_cast(rgb[1]), + static_cast(rgb[2])); + } else { + info.textFgColor.set(0.403922f, 0.403922f, 0.403922f); + } + } + } + + return changed; } #if UFE_PREVIEW_VERSION_NUM >= 2024 @@ -122,134 +127,129 @@ Ufe::UIInfoHandler::Icon UsdUIInfoHandler::treeViewIcon(const Ufe::SceneItem::Pt std::string UsdUIInfoHandler::treeViewIcon(const Ufe::SceneItem::Ptr& item) const #endif { - // Special case for nullptr input. - if (!item) { + // Special case for nullptr input. + if (!item) { #if UFE_PREVIEW_VERSION_NUM >= 2024 - return Ufe::UIInfoHandler::Icon("out_USD_UsdTyped.png"); // Default USD icon + return Ufe::UIInfoHandler::Icon("out_USD_UsdTyped.png"); // Default USD icon #else - return "out_USD_UsdTyped.png"; // Default USD icon + return "out_USD_UsdTyped.png"; // Default USD icon #endif - } - - // We support these node types directly. - static const std::map supportedTypes{ - {"", "out_USD_Def.png"}, // No node type - {"BlendShape", "out_USD_BlendShape.png"}, - {"Camera", "out_USD_Camera.png"}, - {"Capsule", "out_USD_Capsule.png"}, - {"Cone", "out_USD_Cone.png"}, - {"Cube", "out_USD_Cube.png"}, - {"Cylinder", "out_USD_Cylinder.png"}, - {"GeomSubset", "out_USD_GeomSubset.png"}, - {"LightFilter", "out_USD_LightFilter.png"}, - {"LightPortal", "out_USD_LightPortal.png"}, - {"mayaReference", "out_USD_mayaReference.png"}, - {"AL_MayaReference", "out_USD_mayaReference.png"}, // Same as mayaRef - {"Mesh", "out_USD_Mesh.png"}, - {"NurbsPatch", "out_USD_NurbsPatch.png"}, - {"PointInstancer", "out_USD_PointInstancer.png"}, - {"Points", "out_USD_Points.png"}, - {"Scope", "out_USD_Scope.png"}, - {"SkelAnimation", "out_USD_SkelAnimation.png"}, - {"Skeleton", "out_USD_Skeleton.png"}, - {"SkelRoot", "out_USD_SkelRoot.png"}, - {"Sphere", "out_USD_Sphere.png"}, - {"Volume", "out_USD_Volume.png"} - }; + } + + // We support these node types directly. + static const std::map supportedTypes { + { "", "out_USD_Def.png" }, // No node type + { "BlendShape", "out_USD_BlendShape.png" }, + { "Camera", "out_USD_Camera.png" }, + { "Capsule", "out_USD_Capsule.png" }, + { "Cone", "out_USD_Cone.png" }, + { "Cube", "out_USD_Cube.png" }, + { "Cylinder", "out_USD_Cylinder.png" }, + { "GeomSubset", "out_USD_GeomSubset.png" }, + { "LightFilter", "out_USD_LightFilter.png" }, + { "LightPortal", "out_USD_LightPortal.png" }, + { "mayaReference", "out_USD_mayaReference.png" }, + { "AL_MayaReference", "out_USD_mayaReference.png" }, // Same as mayaRef + { "Mesh", "out_USD_Mesh.png" }, + { "NurbsPatch", "out_USD_NurbsPatch.png" }, + { "PointInstancer", "out_USD_PointInstancer.png" }, + { "Points", "out_USD_Points.png" }, + { "Scope", "out_USD_Scope.png" }, + { "SkelAnimation", "out_USD_SkelAnimation.png" }, + { "Skeleton", "out_USD_Skeleton.png" }, + { "SkelRoot", "out_USD_SkelRoot.png" }, + { "Sphere", "out_USD_Sphere.png" }, + { "Volume", "out_USD_Volume.png" } + }; #if UFE_PREVIEW_VERSION_NUM >= 2024 - Ufe::UIInfoHandler::Icon icon; // Default is empty (no icon and no badge). + Ufe::UIInfoHandler::Icon icon; // Default is empty (no icon and no badge). #endif - const auto search = supportedTypes.find(item->nodeType()); - if (search != supportedTypes.cend()) { + const auto search = supportedTypes.find(item->nodeType()); + if (search != supportedTypes.cend()) { #if UFE_PREVIEW_VERSION_NUM >= 2024 - icon.baseIcon = search->second; + icon.baseIcon = search->second; #else - return search->second; + return search->second; #endif - } + } #if UFE_PREVIEW_VERSION_NUM >= 2024 - // Check if we have any composition meta data - if yes we display a special badge. - UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); - if (usdItem) - { - // Variants - if (!usdItem->prim().GetVariantSets().GetNames().empty()) - { - icon.badgeIcon = "out_USD_CompArcBadgeV.png"; - icon.pos = Ufe::UIInfoHandler::LowerRight; - } - else - { - // Composition related metadata. - static const std::vector compKeys = { - PXR_NS::SdfFieldKeys->References, SdfFieldKeys->Payload, SdfFieldKeys->InheritPaths, SdfFieldKeys->Specializes}; - for (const auto& k : compKeys) - { - if (usdItem->prim().HasMetadata(k)) - { - icon.badgeIcon = "out_USD_CompArcBadge.png"; - icon.pos = Ufe::UIInfoHandler::LowerRight; - break; - } - } - } - } - - return icon; + // Check if we have any composition meta data - if yes we display a special badge. + UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); + if (usdItem) { + // Variants + if (!usdItem->prim().GetVariantSets().GetNames().empty()) { + icon.badgeIcon = "out_USD_CompArcBadgeV.png"; + icon.pos = Ufe::UIInfoHandler::LowerRight; + } else { + // Composition related metadata. + static const std::vector compKeys = { PXR_NS::SdfFieldKeys->References, + SdfFieldKeys->Payload, + SdfFieldKeys->InheritPaths, + SdfFieldKeys->Specializes }; + for (const auto& k : compKeys) { + if (usdItem->prim().HasMetadata(k)) { + icon.badgeIcon = "out_USD_CompArcBadge.png"; + icon.pos = Ufe::UIInfoHandler::LowerRight; + break; + } + } + } + } + + return icon; #else - // No specific node type icon was found. - return ""; + // No specific node type icon was found. + return ""; #endif } #if UFE_PREVIEW_VERSION_NUM >= 2024 std::string UsdUIInfoHandler::treeViewTooltip(const Ufe::SceneItem::Ptr& item) const { - std::string tooltip; - - UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); - if (usdItem) - { - // Composition related metadata. - bool needComma = false; - PXR_NS::SdfReferenceListOp referenceOp; - if (usdItem->prim().GetMetadata(PXR_NS::SdfFieldKeys->References, &referenceOp)) { - addMetadataCount(referenceOp, tooltip, needComma, "Reference", "References"); - } - - PXR_NS::SdfPayloadListOp payloadOp; - if (usdItem->prim().GetMetadata(PXR_NS::SdfFieldKeys->Payload, &payloadOp)) { - addMetadataCount(payloadOp, tooltip, needComma, "Payload", "Payloads"); - } - - PXR_NS::SdfPathListOp inheritOp; - if (usdItem->prim().GetMetadata(PXR_NS::SdfFieldKeys->InheritPaths, &inheritOp)) { - addMetadataCount(inheritOp, tooltip, needComma, "Inherit", "Inherits"); - } - - PXR_NS::SdfPathListOp specializeOp; - if (usdItem->prim().GetMetadata(PXR_NS::SdfFieldKeys->Specializes, &specializeOp)) { - addMetadataCount(specializeOp, tooltip, needComma, "Specialize", "Specializes"); - } - - // Variants - const auto& variants = usdItem->prim().GetVariantSets().GetNames(); - if (!variants.empty()) { - addMetadataStrings(variants.size(), tooltip, needComma, "Variant", "Variants"); - } - } - return tooltip; + std::string tooltip; + + UsdSceneItem::Ptr usdItem = std::dynamic_pointer_cast(item); + if (usdItem) { + // Composition related metadata. + bool needComma = false; + PXR_NS::SdfReferenceListOp referenceOp; + if (usdItem->prim().GetMetadata(PXR_NS::SdfFieldKeys->References, &referenceOp)) { + addMetadataCount( + referenceOp, tooltip, needComma, "Reference", "References"); + } + + PXR_NS::SdfPayloadListOp payloadOp; + if (usdItem->prim().GetMetadata(PXR_NS::SdfFieldKeys->Payload, &payloadOp)) { + addMetadataCount( + payloadOp, tooltip, needComma, "Payload", "Payloads"); + } + + PXR_NS::SdfPathListOp inheritOp; + if (usdItem->prim().GetMetadata(PXR_NS::SdfFieldKeys->InheritPaths, &inheritOp)) { + addMetadataCount( + inheritOp, tooltip, needComma, "Inherit", "Inherits"); + } + + PXR_NS::SdfPathListOp specializeOp; + if (usdItem->prim().GetMetadata(PXR_NS::SdfFieldKeys->Specializes, &specializeOp)) { + addMetadataCount( + specializeOp, tooltip, needComma, "Specialize", "Specializes"); + } + + // Variants + const auto& variants = usdItem->prim().GetVariantSets().GetNames(); + if (!variants.empty()) { + addMetadataStrings(variants.size(), tooltip, needComma, "Variant", "Variants"); + } + } + return tooltip; } #endif -std::string UsdUIInfoHandler::getLongRunTimeLabel() const -{ - return "Universal Scene Description"; -} - +std::string UsdUIInfoHandler::getLongRunTimeLabel() const { return "Universal Scene Description"; } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUIInfoHandler.h b/lib/mayaUsd/ufe/UsdUIInfoHandler.h index 9fe069eed5..4ef8ae1dae 100644 --- a/lib/mayaUsd/ufe/UsdUIInfoHandler.h +++ b/lib/mayaUsd/ufe/UsdUIInfoHandler.h @@ -17,10 +17,9 @@ // limitations under the License. // -#include - #include +#include namespace MAYAUSD_NS_DEF { namespace ufe { @@ -29,32 +28,32 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdUIInfoHandler : public Ufe::UIInfoHandler { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdUIInfoHandler(); - ~UsdUIInfoHandler() override; + UsdUIInfoHandler(); + ~UsdUIInfoHandler() override; - // Delete the copy/move constructors assignment operators. - UsdUIInfoHandler(const UsdUIInfoHandler&) = delete; - UsdUIInfoHandler& operator=(const UsdUIInfoHandler&) = delete; - UsdUIInfoHandler(UsdUIInfoHandler&&) = delete; - UsdUIInfoHandler& operator=(UsdUIInfoHandler&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdUIInfoHandler(const UsdUIInfoHandler&) = delete; + UsdUIInfoHandler& operator=(const UsdUIInfoHandler&) = delete; + UsdUIInfoHandler(UsdUIInfoHandler&&) = delete; + UsdUIInfoHandler& operator=(UsdUIInfoHandler&&) = delete; - //! Create a UsdUIInfoHandler. - static UsdUIInfoHandler::Ptr create(); + //! Create a UsdUIInfoHandler. + static UsdUIInfoHandler::Ptr create(); - // Ufe::UIInfoHandler overrides - bool treeViewCellInfo(const Ufe::SceneItem::Ptr& item, Ufe::CellInfo& info) const override; + // Ufe::UIInfoHandler overrides + bool treeViewCellInfo(const Ufe::SceneItem::Ptr& item, Ufe::CellInfo& info) const override; #if UFE_PREVIEW_VERSION_NUM >= 2024 - Ufe::UIInfoHandler::Icon treeViewIcon(const Ufe::SceneItem::Ptr& item) const override; - std::string treeViewTooltip(const Ufe::SceneItem::Ptr& item) const override; + Ufe::UIInfoHandler::Icon treeViewIcon(const Ufe::SceneItem::Ptr& item) const override; + std::string treeViewTooltip(const Ufe::SceneItem::Ptr& item) const override; #else - std::string treeViewIcon(const Ufe::SceneItem::Ptr& item) const override; + std::string treeViewIcon(const Ufe::SceneItem::Ptr& item) const override; #endif - std::string getLongRunTimeLabel() const override; + std::string getLongRunTimeLabel() const override; }; // UsdUIInfoHandler } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF #endif // USDUIINFOHANDLER_H diff --git a/lib/mayaUsd/ufe/UsdUndoAddNewPrimCommand.cpp b/lib/mayaUsd/ufe/UsdUndoAddNewPrimCommand.cpp index 4fbfeb5a8c..935ea55c88 100644 --- a/lib/mayaUsd/ufe/UsdUndoAddNewPrimCommand.cpp +++ b/lib/mayaUsd/ufe/UsdUndoAddNewPrimCommand.cpp @@ -15,33 +15,35 @@ // #include "UsdUndoAddNewPrimCommand.h" +#include "private/UfeNotifGuard.h" + #include #include -#include "private/UfeNotifGuard.h" - namespace { Ufe::Path appendToPath(const Ufe::Path& path, const std::string& name) { Ufe::Path newUfePath; if (1 == path.getSegments().size()) { - newUfePath = path + Ufe::PathSegment( - Ufe::PathComponent(name), MayaUsd::ufe::getUsdRunTimeId(), '/'); + newUfePath = path + + Ufe::PathSegment(Ufe::PathComponent(name), MayaUsd::ufe::getUsdRunTimeId(), '/'); } else { newUfePath = path + name; } return newUfePath; } -} +} // namespace namespace MAYAUSD_NS_DEF { namespace ufe { -UsdUndoAddNewPrimCommand::UsdUndoAddNewPrimCommand(const UsdSceneItem::Ptr& usdSceneItem, - const std::string& name, const std::string& type) -: Ufe::UndoableCommand() +UsdUndoAddNewPrimCommand::UsdUndoAddNewPrimCommand( + const UsdSceneItem::Ptr& usdSceneItem, + const std::string& name, + const std::string& type) + : Ufe::UndoableCommand() { // First get the stage from the proxy shape. auto ufePath = usdSceneItem->path(); @@ -82,32 +84,31 @@ void UsdUndoAddNewPrimCommand::redo() { if (_stage) { MayaUsd::ufe::InAddOrDeleteOperation ad; - auto prim = _stage->DefinePrim(_primPath, _primToken); + auto prim = _stage->DefinePrim(_primPath, _primToken); if (!prim.IsValid()) TF_RUNTIME_ERROR("Failed to create new prim type: %s", _primToken.GetText()); } } -const Ufe::Path& UsdUndoAddNewPrimCommand::newUfePath() const -{ - return _newUfePath; -} +const Ufe::Path& UsdUndoAddNewPrimCommand::newUfePath() const { return _newUfePath; } PXR_NS::UsdPrim UsdUndoAddNewPrimCommand::newPrim() const { if (!_stage) { return UsdPrim(); } - + return _stage->GetPrimAtPath(_primPath); } /*static*/ -UsdUndoAddNewPrimCommand::Ptr UsdUndoAddNewPrimCommand::create(const UsdSceneItem::Ptr& usdSceneItem, - const std::string& name, const std::string& type) +UsdUndoAddNewPrimCommand::Ptr UsdUndoAddNewPrimCommand::create( + const UsdSceneItem::Ptr& usdSceneItem, + const std::string& name, + const std::string& type) { - return std::make_shared(usdSceneItem, name, type); + return std::make_shared(usdSceneItem, name, type); } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoAddNewPrimCommand.h b/lib/mayaUsd/ufe/UsdUndoAddNewPrimCommand.h index 5dfea003e2..fa26399418 100644 --- a/lib/mayaUsd/ufe/UsdUndoAddNewPrimCommand.h +++ b/lib/mayaUsd/ufe/UsdUndoAddNewPrimCommand.h @@ -16,12 +16,12 @@ #ifndef USD_ADD_NEW_PRIM_COMMAND #define USD_ADD_NEW_PRIM_COMMAND -#include -#include - #include #include +#include +#include + PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { @@ -33,27 +33,29 @@ class MAYAUSD_CORE_PUBLIC UsdUndoAddNewPrimCommand : public Ufe::UndoableCommand public: typedef std::shared_ptr Ptr; - UsdUndoAddNewPrimCommand(const UsdSceneItem::Ptr& usdSceneItem, - const std::string& name, - const std::string& type); + UsdUndoAddNewPrimCommand( + const UsdSceneItem::Ptr& usdSceneItem, + const std::string& name, + const std::string& type); void undo() override; void redo() override; const Ufe::Path& newUfePath() const; - UsdPrim newPrim() const; + UsdPrim newPrim() const; + + static UsdUndoAddNewPrimCommand::Ptr + create(const UsdSceneItem::Ptr& usdSceneItem, const std::string& name, const std::string& type); - static UsdUndoAddNewPrimCommand::Ptr create(const UsdSceneItem::Ptr& usdSceneItem, - const std::string& name, const std::string& type); private: PXR_NS::UsdStageWeakPtr _stage; - PXR_NS::SdfPath _primPath; - PXR_NS::TfToken _primToken; - Ufe::Path _newUfePath; + PXR_NS::SdfPath _primPath; + PXR_NS::TfToken _primToken; + Ufe::Path _newUfePath; }; // UsdUndoAddNewPrimCommand } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/mayaUsd/ufe/UsdUndoCreateGroupCommand.cpp b/lib/mayaUsd/ufe/UsdUndoCreateGroupCommand.cpp index 5f81f600bf..2266427c6b 100644 --- a/lib/mayaUsd/ufe/UsdUndoCreateGroupCommand.cpp +++ b/lib/mayaUsd/ufe/UsdUndoCreateGroupCommand.cpp @@ -15,39 +15,40 @@ // #include "UsdUndoCreateGroupCommand.h" -#include -#include -#include +#include #include #include -#include +#include +#include +#include namespace MAYAUSD_NS_DEF { namespace ufe { -UsdUndoCreateGroupCommand::UsdUndoCreateGroupCommand(const UsdSceneItem::Ptr& parentItem, const Ufe::Selection& selection, const Ufe::PathComponent& name) - : Ufe::CompositeUndoableCommand() - , _parentItem(parentItem) - , _name(name) - , _selection(selection) +UsdUndoCreateGroupCommand::UsdUndoCreateGroupCommand( + const UsdSceneItem::Ptr& parentItem, + const Ufe::Selection& selection, + const Ufe::PathComponent& name) + : Ufe::CompositeUndoableCommand() + , _parentItem(parentItem) + , _name(name) + , _selection(selection) { } -UsdUndoCreateGroupCommand::~UsdUndoCreateGroupCommand() -{ -} +UsdUndoCreateGroupCommand::~UsdUndoCreateGroupCommand() { } -UsdUndoCreateGroupCommand::Ptr UsdUndoCreateGroupCommand::create(const UsdSceneItem::Ptr& parentItem, const Ufe::Selection& selection, const Ufe::PathComponent& name) +UsdUndoCreateGroupCommand::Ptr UsdUndoCreateGroupCommand::create( + const UsdSceneItem::Ptr& parentItem, + const Ufe::Selection& selection, + const Ufe::PathComponent& name) { - return std::make_shared(parentItem, selection, name); + return std::make_shared(parentItem, selection, name); } -Ufe::SceneItem::Ptr UsdUndoCreateGroupCommand::group() const -{ - return _group; -} +Ufe::SceneItem::Ptr UsdUndoCreateGroupCommand::group() const { return _group; } //------------------------------------------------------------------------------ // UsdUndoCreateGroupCommand overrides @@ -55,21 +56,21 @@ Ufe::SceneItem::Ptr UsdUndoCreateGroupCommand::group() const void UsdUndoCreateGroupCommand::execute() { - auto addPrimCmd = UsdUndoAddNewPrimCommand::create(_parentItem, _name.string(), "Xform"); - append(addPrimCmd); - addPrimCmd->execute(); - - _group = UsdSceneItem::create(addPrimCmd->newUfePath(), addPrimCmd->newPrim()); + auto addPrimCmd = UsdUndoAddNewPrimCommand::create(_parentItem, _name.string(), "Xform"); + append(addPrimCmd); + addPrimCmd->execute(); + + _group = UsdSceneItem::create(addPrimCmd->newUfePath(), addPrimCmd->newPrim()); - auto newParentHierarchy = Ufe::Hierarchy::hierarchy(_group); - if (newParentHierarchy) { - for (auto child : _selection) { - auto parentCmd = newParentHierarchy->appendChildCmd(child); - parentCmd->execute(); - append(parentCmd); - } - } + auto newParentHierarchy = Ufe::Hierarchy::hierarchy(_group); + if (newParentHierarchy) { + for (auto child : _selection) { + auto parentCmd = newParentHierarchy->appendChildCmd(child); + parentCmd->execute(); + append(parentCmd); + } + } } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoCreateGroupCommand.h b/lib/mayaUsd/ufe/UsdUndoCreateGroupCommand.h index c51fe7381a..f1521d456f 100644 --- a/lib/mayaUsd/ufe/UsdUndoCreateGroupCommand.h +++ b/lib/mayaUsd/ufe/UsdUndoCreateGroupCommand.h @@ -15,14 +15,14 @@ // #pragma once -#include -#include -#include - #include #include -//PXR_NAMESPACE_USING_DIRECTIVE +#include +#include +#include + +// PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { namespace ufe { @@ -31,31 +31,37 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdUndoCreateGroupCommand : public Ufe::CompositeUndoableCommand { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdUndoCreateGroupCommand(const UsdSceneItem::Ptr& parentItem, const Ufe::Selection& selection, const Ufe::PathComponent& name); - ~UsdUndoCreateGroupCommand() override; + UsdUndoCreateGroupCommand( + const UsdSceneItem::Ptr& parentItem, + const Ufe::Selection& selection, + const Ufe::PathComponent& name); + ~UsdUndoCreateGroupCommand() override; - // Delete the copy/move constructors assignment operators. - UsdUndoCreateGroupCommand(const UsdUndoCreateGroupCommand&) = delete; - UsdUndoCreateGroupCommand& operator=(const UsdUndoCreateGroupCommand&) = delete; - UsdUndoCreateGroupCommand(UsdUndoCreateGroupCommand&&) = delete; - UsdUndoCreateGroupCommand& operator=(UsdUndoCreateGroupCommand&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdUndoCreateGroupCommand(const UsdUndoCreateGroupCommand&) = delete; + UsdUndoCreateGroupCommand& operator=(const UsdUndoCreateGroupCommand&) = delete; + UsdUndoCreateGroupCommand(UsdUndoCreateGroupCommand&&) = delete; + UsdUndoCreateGroupCommand& operator=(UsdUndoCreateGroupCommand&&) = delete; - //! Create a UsdUndoCreateGroupCommand from a USD scene item and a UFE path component. - static UsdUndoCreateGroupCommand::Ptr create(const UsdSceneItem::Ptr& parentItem, const Ufe::Selection& selection, const Ufe::PathComponent& name); - Ufe::SceneItem::Ptr group() const; + //! Create a UsdUndoCreateGroupCommand from a USD scene item and a UFE path component. + static UsdUndoCreateGroupCommand::Ptr create( + const UsdSceneItem::Ptr& parentItem, + const Ufe::Selection& selection, + const Ufe::PathComponent& name); + Ufe::SceneItem::Ptr group() const; - // UsdUndoCreateGroupCommand overrides - void execute() override; + // UsdUndoCreateGroupCommand overrides + void execute() override; private: - UsdSceneItem::Ptr _parentItem; - Ufe::PathComponent _name; - UsdSceneItem::Ptr _group; - Ufe::Selection _selection; + UsdSceneItem::Ptr _parentItem; + Ufe::PathComponent _name; + UsdSceneItem::Ptr _group; + Ufe::Selection _selection; }; // UsdUndoCreateGroupCommand } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoDeleteCommand.cpp b/lib/mayaUsd/ufe/UsdUndoDeleteCommand.cpp index e961c4985d..99d362462d 100644 --- a/lib/mayaUsd/ufe/UsdUndoDeleteCommand.cpp +++ b/lib/mayaUsd/ufe/UsdUndoDeleteCommand.cpp @@ -21,40 +21,32 @@ namespace MAYAUSD_NS_DEF { namespace ufe { UsdUndoDeleteCommand::UsdUndoDeleteCommand(const UsdPrim& prim) - : Ufe::UndoableCommand() - , fPrim(prim) + : Ufe::UndoableCommand() + , fPrim(prim) { } -UsdUndoDeleteCommand::~UsdUndoDeleteCommand() -{ -} +UsdUndoDeleteCommand::~UsdUndoDeleteCommand() { } /*static*/ UsdUndoDeleteCommand::Ptr UsdUndoDeleteCommand::create(const UsdPrim& prim) { - return std::make_shared(prim); + return std::make_shared(prim); } void UsdUndoDeleteCommand::perform(bool state) { - MayaUsd::ufe::InAddOrDeleteOperation ad; - fPrim.SetActive(state); + MayaUsd::ufe::InAddOrDeleteOperation ad; + fPrim.SetActive(state); } //------------------------------------------------------------------------------ // UsdUndoDeleteCommand overrides //------------------------------------------------------------------------------ -void UsdUndoDeleteCommand::undo() -{ - perform(true); -} +void UsdUndoDeleteCommand::undo() { perform(true); } -void UsdUndoDeleteCommand::redo() -{ - perform(false); -} +void UsdUndoDeleteCommand::redo() { perform(false); } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoDeleteCommand.h b/lib/mayaUsd/ufe/UsdUndoDeleteCommand.h index 6d444fceb2..19967713ff 100644 --- a/lib/mayaUsd/ufe/UsdUndoDeleteCommand.h +++ b/lib/mayaUsd/ufe/UsdUndoDeleteCommand.h @@ -15,12 +15,12 @@ // #pragma once -#include +#include +#include #include -#include -#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -31,31 +31,31 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdUndoDeleteCommand : public Ufe::UndoableCommand { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdUndoDeleteCommand(const UsdPrim& prim); - ~UsdUndoDeleteCommand() override; + UsdUndoDeleteCommand(const UsdPrim& prim); + ~UsdUndoDeleteCommand() override; - // Delete the copy/move constructors assignment operators. - UsdUndoDeleteCommand(const UsdUndoDeleteCommand&) = delete; - UsdUndoDeleteCommand& operator=(const UsdUndoDeleteCommand&) = delete; - UsdUndoDeleteCommand(UsdUndoDeleteCommand&&) = delete; - UsdUndoDeleteCommand& operator=(UsdUndoDeleteCommand&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdUndoDeleteCommand(const UsdUndoDeleteCommand&) = delete; + UsdUndoDeleteCommand& operator=(const UsdUndoDeleteCommand&) = delete; + UsdUndoDeleteCommand(UsdUndoDeleteCommand&&) = delete; + UsdUndoDeleteCommand& operator=(UsdUndoDeleteCommand&&) = delete; - //! Create a UsdUndoDeleteCommand from a USD prim. - static UsdUndoDeleteCommand::Ptr create(const UsdPrim& prim); + //! Create a UsdUndoDeleteCommand from a USD prim. + static UsdUndoDeleteCommand::Ptr create(const UsdPrim& prim); - // UsdUndoDeleteCommand overrides - void undo() override; - void redo() override; + // UsdUndoDeleteCommand overrides + void undo() override; + void redo() override; private: - void perform(bool state); + void perform(bool state); private: - UsdPrim fPrim; + UsdPrim fPrim; }; // UsdUndoDeleteCommand } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoDuplicateCommand.cpp b/lib/mayaUsd/ufe/UsdUndoDuplicateCommand.cpp index 868a8d1fcc..07f69be0ea 100644 --- a/lib/mayaUsd/ufe/UsdUndoDuplicateCommand.cpp +++ b/lib/mayaUsd/ufe/UsdUndoDuplicateCommand.cpp @@ -15,83 +15,87 @@ // #include "UsdUndoDuplicateCommand.h" -#include -#include -#include +#include "private/UfeNotifGuard.h" + +#include #include #include #include -#include +#include +#include +#include #include -#include "private/UfeNotifGuard.h" - namespace MAYAUSD_NS_DEF { namespace ufe { -UsdUndoDuplicateCommand::UsdUndoDuplicateCommand(const UsdPrim& srcPrim, const Ufe::Path& ufeSrcPath) - : Ufe::UndoableCommand() - , fSrcPrim(srcPrim) - , fUfeSrcPath(ufeSrcPath) +UsdUndoDuplicateCommand::UsdUndoDuplicateCommand( + const UsdPrim& srcPrim, + const Ufe::Path& ufeSrcPath) + : Ufe::UndoableCommand() + , fSrcPrim(srcPrim) + , fUfeSrcPath(ufeSrcPath) { - fStage = fSrcPrim.GetStage(); - primInfo(srcPrim, fUsdDstPath, fLayer); + fStage = fSrcPrim.GetStage(); + primInfo(srcPrim, fUsdDstPath, fLayer); } -UsdUndoDuplicateCommand::~UsdUndoDuplicateCommand() -{ -} +UsdUndoDuplicateCommand::~UsdUndoDuplicateCommand() { } /*static*/ -UsdUndoDuplicateCommand::Ptr UsdUndoDuplicateCommand::create(const UsdPrim& srcPrim, const Ufe::Path& ufeSrcPath) +UsdUndoDuplicateCommand::Ptr +UsdUndoDuplicateCommand::create(const UsdPrim& srcPrim, const Ufe::Path& ufeSrcPath) { - return std::make_shared(srcPrim, ufeSrcPath); + return std::make_shared(srcPrim, ufeSrcPath); } -const SdfPath& UsdUndoDuplicateCommand::usdDstPath() const -{ - return fUsdDstPath; -} +const SdfPath& UsdUndoDuplicateCommand::usdDstPath() const { return fUsdDstPath; } /*static*/ -void UsdUndoDuplicateCommand::primInfo(const UsdPrim& srcPrim, SdfPath& usdDstPath, SdfLayerHandle& srcLayer) +void UsdUndoDuplicateCommand::primInfo( + const UsdPrim& srcPrim, + SdfPath& usdDstPath, + SdfLayerHandle& srcLayer) { - auto parent = srcPrim.GetParent(); - TfToken::HashSet childrenNames; - for(auto child : parent.GetFilteredChildren(UsdPrimIsDefined && !UsdPrimIsAbstract)) - { - childrenNames.insert(child.GetName()); - } - - // Find a unique name for the destination. If the source name already - // has a numerical suffix, increment it, otherwise append "1" to it. - auto dstName = uniqueName(childrenNames, srcPrim.GetName()); - usdDstPath = parent.GetPath().AppendChild(TfToken(dstName)); - - // Iterate over the layer stack, starting at the highest-priority layer. - // The source layer is the one in which there exists a def primSpec, not - // an over. An alternative would have beeen to call Sdf.CopySpec for - // each layer in which there is an over or a def, until we reach the - // layer with a def primSpec. This would preserve the visual appearance - // of the duplicate. PPT, 12-Jun-2018. - srcLayer = MayaUsdUtils::defPrimSpecLayer(srcPrim); - if (!srcLayer) { - std::string err = TfStringPrintf("No prim found at %s", srcPrim.GetPath().GetString().c_str()); - throw std::runtime_error(err.c_str()); - } + auto parent = srcPrim.GetParent(); + TfToken::HashSet childrenNames; + for (auto child : parent.GetFilteredChildren(UsdPrimIsDefined && !UsdPrimIsAbstract)) { + childrenNames.insert(child.GetName()); + } + + // Find a unique name for the destination. If the source name already + // has a numerical suffix, increment it, otherwise append "1" to it. + auto dstName = uniqueName(childrenNames, srcPrim.GetName()); + usdDstPath = parent.GetPath().AppendChild(TfToken(dstName)); + + // Iterate over the layer stack, starting at the highest-priority layer. + // The source layer is the one in which there exists a def primSpec, not + // an over. An alternative would have beeen to call Sdf.CopySpec for + // each layer in which there is an over or a def, until we reach the + // layer with a def primSpec. This would preserve the visual appearance + // of the duplicate. PPT, 12-Jun-2018. + srcLayer = MayaUsdUtils::defPrimSpecLayer(srcPrim); + if (!srcLayer) { + std::string err + = TfStringPrintf("No prim found at %s", srcPrim.GetPath().GetString().c_str()); + throw std::runtime_error(err.c_str()); + } } /*static*/ -bool UsdUndoDuplicateCommand::duplicate(const SdfLayerHandle& layer, const SdfPath& usdSrcPath, const SdfPath& usdDstPath) +bool UsdUndoDuplicateCommand::duplicate( + const SdfLayerHandle& layer, + const SdfPath& usdSrcPath, + const SdfPath& usdDstPath) { - // We use the source layer as the destination. An alternate workflow - // would be the edit target layer be the destination: - // layer = self._stage.GetEditTarget().GetLayer() - MayaUsd::ufe::InAddOrDeleteOperation ad; - return SdfCopySpec(layer, usdSrcPath, layer, usdDstPath); + // We use the source layer as the destination. An alternate workflow + // would be the edit target layer be the destination: + // layer = self._stage.GetEditTarget().GetLayer() + MayaUsd::ufe::InAddOrDeleteOperation ad; + return SdfCopySpec(layer, usdSrcPath, layer, usdDstPath); } //------------------------------------------------------------------------------ @@ -100,35 +104,34 @@ bool UsdUndoDuplicateCommand::duplicate(const SdfLayerHandle& layer, const SdfPa void UsdUndoDuplicateCommand::undo() { - // USD sends a ResyncedPaths notification after the prim is removed, but - // at that point the prim is no longer valid, and thus a UFE post delete - // notification is no longer possible. To respect UFE object delete - // notification semantics, which require the object to be alive when - // the notification is sent, we send a pre delete notification here. - Ufe::ObjectPreDelete notification(createSiblingSceneItem( - fUfeSrcPath, fUsdDstPath.GetElementString())); + // USD sends a ResyncedPaths notification after the prim is removed, but + // at that point the prim is no longer valid, and thus a UFE post delete + // notification is no longer possible. To respect UFE object delete + // notification semantics, which require the object to be alive when + // the notification is sent, we send a pre delete notification here. + Ufe::ObjectPreDelete notification( + createSiblingSceneItem(fUfeSrcPath, fUsdDstPath.GetElementString())); #ifdef UFE_V2_FEATURES_AVAILABLE - Ufe::Scene::instance().notify(notification); + Ufe::Scene::instance().notify(notification); #else - Ufe::Scene::notifyObjectDelete(notification); + Ufe::Scene::notifyObjectDelete(notification); #endif - fStage->RemovePrim(fUsdDstPath); + fStage->RemovePrim(fUsdDstPath); } void UsdUndoDuplicateCommand::redo() { - // MAYA-92264: Pixar bug prevents redo from working. Try again with USD - // version 0.8.5 or later. PPT, 28-May-2018. - try { - duplicate(fLayer, fSrcPrim.GetPath(), fUsdDstPath); - } - catch (const std::exception& e) { - UFE_LOG(e.what()); - throw; // re-throw the same exception - } + // MAYA-92264: Pixar bug prevents redo from working. Try again with USD + // version 0.8.5 or later. PPT, 28-May-2018. + try { + duplicate(fLayer, fSrcPrim.GetPath(), fUsdDstPath); + } catch (const std::exception& e) { + UFE_LOG(e.what()); + throw; // re-throw the same exception + } } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoDuplicateCommand.h b/lib/mayaUsd/ufe/UsdUndoDuplicateCommand.h index 5ee0d0c491..81f1f8162d 100644 --- a/lib/mayaUsd/ufe/UsdUndoDuplicateCommand.h +++ b/lib/mayaUsd/ufe/UsdUndoDuplicateCommand.h @@ -15,14 +15,14 @@ // #pragma once -#include -#include +#include +#include #include #include -#include -#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -33,44 +33,45 @@ namespace ufe { class MAYAUSD_CORE_PUBLIC UsdUndoDuplicateCommand : public Ufe::UndoableCommand { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - UsdUndoDuplicateCommand(const UsdPrim& srcPrim, const Ufe::Path& ufeSrcPath); - ~UsdUndoDuplicateCommand() override; + UsdUndoDuplicateCommand(const UsdPrim& srcPrim, const Ufe::Path& ufeSrcPath); + ~UsdUndoDuplicateCommand() override; - // Delete the copy/move constructors assignment operators. - UsdUndoDuplicateCommand(const UsdUndoDuplicateCommand&) = delete; - UsdUndoDuplicateCommand& operator=(const UsdUndoDuplicateCommand&) = delete; - UsdUndoDuplicateCommand(UsdUndoDuplicateCommand&&) = delete; - UsdUndoDuplicateCommand& operator=(UsdUndoDuplicateCommand&&) = delete; + // Delete the copy/move constructors assignment operators. + UsdUndoDuplicateCommand(const UsdUndoDuplicateCommand&) = delete; + UsdUndoDuplicateCommand& operator=(const UsdUndoDuplicateCommand&) = delete; + UsdUndoDuplicateCommand(UsdUndoDuplicateCommand&&) = delete; + UsdUndoDuplicateCommand& operator=(UsdUndoDuplicateCommand&&) = delete; - //! Create a UsdUndoDuplicateCommand from a USD prim and UFE path. - static UsdUndoDuplicateCommand::Ptr create(const UsdPrim& srcPrim, const Ufe::Path& ufeSrcPath); + //! Create a UsdUndoDuplicateCommand from a USD prim and UFE path. + static UsdUndoDuplicateCommand::Ptr create(const UsdPrim& srcPrim, const Ufe::Path& ufeSrcPath); - const SdfPath& usdDstPath() const; + const SdfPath& usdDstPath() const; - //! Return the USD destination path and layer. - static void primInfo(const UsdPrim& srcPrim, SdfPath& usdDstPath, SdfLayerHandle& srcLayer); + //! Return the USD destination path and layer. + static void primInfo(const UsdPrim& srcPrim, SdfPath& usdDstPath, SdfLayerHandle& srcLayer); - //! Duplicate the prim hierarchy at usdSrcPath. - //! \return True for success. - static bool duplicate(const SdfLayerHandle& layer, const SdfPath& usdSrcPath, const SdfPath& usdDstPath); + //! Duplicate the prim hierarchy at usdSrcPath. + //! \return True for success. + static bool + duplicate(const SdfLayerHandle& layer, const SdfPath& usdSrcPath, const SdfPath& usdDstPath); - //! Return the USD destination path and layer. - static void primInfo(); + //! Return the USD destination path and layer. + static void primInfo(); - // UsdUndoDuplicateCommand overrides - void undo() override; - void redo() override; + // UsdUndoDuplicateCommand overrides + void undo() override; + void redo() override; private: - UsdPrim fSrcPrim; - UsdStageWeakPtr fStage; - SdfLayerHandle fLayer; - Ufe::Path fUfeSrcPath; - SdfPath fUsdDstPath; + UsdPrim fSrcPrim; + UsdStageWeakPtr fStage; + SdfLayerHandle fLayer; + Ufe::Path fUfeSrcPath; + SdfPath fUsdDstPath; }; // UsdUndoDuplicateCommand } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoInsertChildCommand.cpp b/lib/mayaUsd/ufe/UsdUndoInsertChildCommand.cpp index f63ebe0446..494628aa39 100644 --- a/lib/mayaUsd/ufe/UsdUndoInsertChildCommand.cpp +++ b/lib/mayaUsd/ufe/UsdUndoInsertChildCommand.cpp @@ -15,13 +15,10 @@ // #include "UsdUndoInsertChildCommand.h" + +#include "Utils.h" #include "private/UfeNotifGuard.h" #include "private/Utils.h" -#include "Utils.h" - -#include -#include -#include #include #include @@ -29,6 +26,10 @@ #include #include +#include +#include +#include + #include #define UFE_ENABLE_ASSERTS @@ -36,22 +37,25 @@ namespace { // shared_ptr requires public ctor, dtor, so derive a class for it. -template -struct MakeSharedEnabler : public T { +template struct MakeSharedEnabler : public T +{ MakeSharedEnabler( const MayaUsd::ufe::UsdSceneItem::Ptr& parent, const MayaUsd::ufe::UsdSceneItem::Ptr& child, - const MayaUsd::ufe::UsdSceneItem::Ptr& pos - ) : T(parent, child, pos) {} + const MayaUsd::ufe::UsdSceneItem::Ptr& pos) + : T(parent, child, pos) + { + } }; -} +} // namespace namespace MAYAUSD_NS_DEF { namespace ufe { -UsdUndoInsertChildCommand::UsdUndoInsertChildCommand(const UsdSceneItem::Ptr& parent, - const UsdSceneItem::Ptr& child, - const UsdSceneItem::Ptr& /* pos */) +UsdUndoInsertChildCommand::UsdUndoInsertChildCommand( + const UsdSceneItem::Ptr& parent, + const UsdSceneItem::Ptr& child, + const UsdSceneItem::Ptr& /* pos */) : Ufe::InsertChildCommand() , _ufeDstItem(nullptr) , _ufeSrcPath(child->path()) @@ -64,10 +68,11 @@ UsdUndoInsertChildCommand::UsdUndoInsertChildCommand(const UsdSceneItem::Ptr& pa // USD strongly discourages parenting of one gprim to another. // https://graphics.pixar.com/usd/docs/USD-Glossary.html#USDGlossary-Gprim if (parentPrim.IsA()) { - std::string err = TfStringPrintf("Parenting geometric prim [%s] under geometric prim [%s] is not allowed " - "Please parent geometric prims under separate XForms and reparent between XForms.", - childPrim.GetName().GetString().c_str(), - parentPrim.GetName().GetString().c_str()); + std::string err = TfStringPrintf( + "Parenting geometric prim [%s] under geometric prim [%s] is not allowed " + "Please parent geometric prims under separate XForms and reparent between XForms.", + childPrim.GetName().GetString().c_str(), + parentPrim.GetName().GetString().c_str()); throw std::runtime_error(err.c_str()); } @@ -83,28 +88,24 @@ UsdUndoInsertChildCommand::UsdUndoInsertChildCommand(const UsdSceneItem::Ptr& pa auto cRtId = child->path().runTimeId(); if (parent->path().runTimeId() == cRtId) { _ufeDstPath = parent->path() + childName; - } - else { + } else { auto cSep = child->path().getSegments().back().separator(); - _ufeDstPath = parent->path() + Ufe::PathSegment( - Ufe::PathComponent(childName), cRtId, cSep); + _ufeDstPath = parent->path() + Ufe::PathSegment(Ufe::PathComponent(childName), cRtId, cSep); } _usdDstPath = parentPrim.GetPath().AppendChild(TfToken(childName)); _childLayer = childPrim.GetStage()->GetEditTarget().GetLayer(); - _parentLayer = parentPrim.GetStage()->GetEditTarget().GetLayer(); + _parentLayer = parentPrim.GetStage()->GetEditTarget().GetLayer(); } -UsdUndoInsertChildCommand::~UsdUndoInsertChildCommand() -{ -} +UsdUndoInsertChildCommand::~UsdUndoInsertChildCommand() { } /*static*/ -UsdUndoInsertChildCommand::Ptr -UsdUndoInsertChildCommand::create(const UsdSceneItem::Ptr& parent, - const UsdSceneItem::Ptr& child, - const UsdSceneItem::Ptr& pos) +UsdUndoInsertChildCommand::Ptr UsdUndoInsertChildCommand::create( + const UsdSceneItem::Ptr& parent, + const UsdSceneItem::Ptr& child, + const UsdSceneItem::Ptr& pos) { if (!parent || !child) { return nullptr; @@ -114,23 +115,21 @@ UsdUndoInsertChildCommand::create(const UsdSceneItem::Ptr& parent, if (parent->path().startsWith(child->path())) { return nullptr; } - return std::make_shared>( - parent, child, pos); + return std::make_shared>(parent, child, pos); } bool UsdUndoInsertChildCommand::insertChildRedo() { bool status = SdfCopySpec(_childLayer, _usdSrcPath, _parentLayer, _usdDstPath); - if (status) - { - // remove all scene description for the given path and - // its subtree in the current UsdEditTarget + if (status) { + // remove all scene description for the given path and + // its subtree in the current UsdEditTarget { - // we shouldn't rely on UsdSceneItem to access the UsdPrim since + // we shouldn't rely on UsdSceneItem to access the UsdPrim since // it could be stale. Instead we should get the USDPrim from the Ufe::Path const auto& usdSrcPrim = ufePathToPrim(_ufeSrcPath); - auto stage = usdSrcPrim.GetStage(); + auto stage = usdSrcPrim.GetStage(); UsdEditContext ctx(stage, _childLayer); status = stage->RemovePrim(_usdSrcPath); } @@ -139,10 +138,10 @@ bool UsdUndoInsertChildCommand::insertChildRedo() _ufeDstItem = UsdSceneItem::create(_ufeDstPath, ufePathToPrim(_ufeDstPath)); sendNotification(_ufeDstItem, _ufeSrcPath); } - } - else { - UFE_LOG(std::string("Warning: SdfCopySpec(") + - _usdSrcPath.GetString() + std::string(") failed.")); + } else { + UFE_LOG( + std::string("Warning: SdfCopySpec(") + _usdSrcPath.GetString() + + std::string(") failed.")); } return status; @@ -151,16 +150,15 @@ bool UsdUndoInsertChildCommand::insertChildRedo() bool UsdUndoInsertChildCommand::insertChildUndo() { bool status = SdfCopySpec(_parentLayer, _usdDstPath, _childLayer, _usdSrcPath); - if (status) - { - // remove all scene description for the given path and + if (status) { + // remove all scene description for the given path and // its subtree in the current UsdEditTarget { - // we shouldn't rely on UsdSceneItem to access the UsdPrim since + // we shouldn't rely on UsdSceneItem to access the UsdPrim since // it could be stale. Instead we should get the USDPrim from the Ufe::Path const auto& usdDstPrim = ufePathToPrim(_ufeDstPath); - auto stage = usdDstPrim.GetStage(); + auto stage = usdDstPrim.GetStage(); UsdEditContext ctx(stage, _parentLayer); status = stage->RemovePrim(_usdDstPath); } @@ -169,10 +167,10 @@ bool UsdUndoInsertChildCommand::insertChildUndo() auto ufeSrcItem = UsdSceneItem::create(_ufeSrcPath, ufePathToPrim(_ufeSrcPath)); sendNotification(ufeSrcItem, _ufeDstPath); } - } - else { - UFE_LOG(std::string("Warning: RemovePrim(") + - _usdDstPath.GetString() + std::string(") failed.")); + } else { + UFE_LOG( + std::string("Warning: RemovePrim(") + _usdDstPath.GetString() + + std::string(") failed.")); } return status; @@ -185,10 +183,9 @@ void UsdUndoInsertChildCommand::undo() if (!insertChildUndo()) { UFE_LOG("insert child undo failed"); } - } - catch (const std::exception& e) { + } catch (const std::exception& e) { UFE_LOG(e.what()); - throw; // re-throw the same exception + throw; // re-throw the same exception } } @@ -201,4 +198,4 @@ void UsdUndoInsertChildCommand::redo() } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoInsertChildCommand.h b/lib/mayaUsd/ufe/UsdUndoInsertChildCommand.h index 246c7760d8..7744079417 100644 --- a/lib/mayaUsd/ufe/UsdUndoInsertChildCommand.h +++ b/lib/mayaUsd/ufe/UsdUndoInsertChildCommand.h @@ -15,12 +15,12 @@ // #pragma once -#include +#include +#include #include -#include -#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -43,18 +43,20 @@ class MAYAUSD_CORE_PUBLIC UsdUndoInsertChildCommand : public Ufe::InsertChildCom //! Create a UsdUndoInsertChildCommand. Note that as of 4-May-2020 the //! pos argument is ignored, and only append is supported. - static UsdUndoInsertChildCommand::Ptr create(const UsdSceneItem::Ptr& parent, - const UsdSceneItem::Ptr& child, - const UsdSceneItem::Ptr& pos); + static UsdUndoInsertChildCommand::Ptr create( + const UsdSceneItem::Ptr& parent, + const UsdSceneItem::Ptr& child, + const UsdSceneItem::Ptr& pos); - Ufe::SceneItem::Ptr insertedChild() const override {return _ufeDstItem;} + Ufe::SceneItem::Ptr insertedChild() const override { return _ufeDstItem; } protected: //! Construct a UsdUndoInsertChildCommand. Note that as of 4-May-2020 the //! pos argument is ignored, and only append is supported. - UsdUndoInsertChildCommand(const UsdSceneItem::Ptr& parent, - const UsdSceneItem::Ptr& child, - const UsdSceneItem::Ptr& pos); + UsdUndoInsertChildCommand( + const UsdSceneItem::Ptr& parent, + const UsdSceneItem::Ptr& child, + const UsdSceneItem::Ptr& pos); private: void undo() override; @@ -77,4 +79,4 @@ class MAYAUSD_CORE_PUBLIC UsdUndoInsertChildCommand : public Ufe::InsertChildCom }; // UsdUndoInsertChildCommand } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoRenameCommand.cpp b/lib/mayaUsd/ufe/UsdUndoRenameCommand.cpp index 4a868c4de3..870d9c5449 100644 --- a/lib/mayaUsd/ufe/UsdUndoRenameCommand.cpp +++ b/lib/mayaUsd/ufe/UsdUndoRenameCommand.cpp @@ -14,26 +14,26 @@ // limitations under the License. // #include "UsdUndoRenameCommand.h" + +#include "private/UfeNotifGuard.h" #include "private/Utils.h" -#include -#include -#include +#include #include +#include #include #include #include #include #include -#include -#include +#include +#include +#include #include -#include "private/UfeNotifGuard.h" - #ifdef UFE_V2_FEATURES_AVAILABLE #define UFE_ENABLE_ASSERTS #include @@ -51,13 +51,16 @@ namespace ufe { See usd-interest: Question around SdfPrimSepc's SetName routine - SdfPrimSpec::SetName() will rename any prim in the layer, but it does not allow you to reparent the prim, - nor will it update any relationship or connection targets in the layer that targeted the prim or any of its - decendants (they will all break unless you fix them up yourself.Renaming and reparenting prims destructively - in composed scenes is pretty tricky stuff that cannot really practically be done with 100% guarantees. + SdfPrimSpec::SetName() will rename any prim in the layer, but it does not allow you to reparent + the prim, nor will it update any relationship or connection targets in the layer that targeted + the prim or any of its decendants (they will all break unless you fix them up yourself.Renaming + and reparenting prims destructively in composed scenes is pretty tricky stuff that cannot really + practically be done with 100% guarantees. */ -UsdUndoRenameCommand::UsdUndoRenameCommand(const UsdSceneItem::Ptr& srcItem, const Ufe::PathComponent& newName) +UsdUndoRenameCommand::UsdUndoRenameCommand( + const UsdSceneItem::Ptr& srcItem, + const Ufe::PathComponent& newName) : Ufe::UndoableCommand() , _ufeSrcItem(srcItem) , _ufeDstItem(nullptr) @@ -71,30 +74,28 @@ UsdUndoRenameCommand::UsdUndoRenameCommand(const UsdSceneItem::Ptr& srcItem, con _newName = uniqueChildName(prim.GetParent(), newName.string()); // names are not allowed to start to digit numbers - if(std::isdigit(_newName.at(0))){ + if (std::isdigit(_newName.at(0))) { _newName = prim.GetName(); } // all special characters are replaced with `_` - const std::string specialChars{"~!@#$%^&*()-=+,.?`':{}|<>[]/ "}; - std::replace_if(_newName.begin(), _newName.end(), [&](auto c){ - return std::string::npos != specialChars.find(c); - }, '_'); + const std::string specialChars { "~!@#$%^&*()-=+,.?`':{}|<>[]/ " }; + std::replace_if( + _newName.begin(), + _newName.end(), + [&](auto c) { return std::string::npos != specialChars.find(c); }, + '_'); } -UsdUndoRenameCommand::~UsdUndoRenameCommand() -{ -} +UsdUndoRenameCommand::~UsdUndoRenameCommand() { } -UsdUndoRenameCommand::Ptr UsdUndoRenameCommand::create(const UsdSceneItem::Ptr& srcItem, const Ufe::PathComponent& newName) +UsdUndoRenameCommand::Ptr +UsdUndoRenameCommand::create(const UsdSceneItem::Ptr& srcItem, const Ufe::PathComponent& newName) { return std::make_shared(srcItem, newName); } -UsdSceneItem::Ptr UsdUndoRenameCommand::renamedItem() const -{ - return _ufeDstItem; -} +UsdSceneItem::Ptr UsdUndoRenameCommand::renamedItem() const { return _ufeDstItem; } bool UsdUndoRenameCommand::renameRedo() { @@ -112,7 +113,8 @@ bool UsdUndoRenameCommand::renameRedo() const UsdPrim& prim = _stage->GetPrimAtPath(_ufeSrcItem->prim().GetPath()); auto ufeSiblingPath = _ufeSrcItem->path().sibling(Ufe::PathComponent(_newName)); - bool status = MayaUsdUtils::updateInternalReferencesPath(prim, SdfPath(ufeSiblingPath.getSegments()[1].string())); + bool status = MayaUsdUtils::updateInternalReferencesPath( + prim, SdfPath(ufeSiblingPath.getSegments()[1].string())); if (!status) { return false; } @@ -129,7 +131,7 @@ bool UsdUndoRenameCommand::renameRedo() _ufeDstItem = createSiblingSceneItem(_ufeSrcItem->path(), _newName); // update stage's default prim - if(_ufeSrcItem->prim().GetPath() == defaultPrimPath) { + if (_ufeSrcItem->prim().GetPath() == defaultPrimPath) { _stage->SetDefaultPrim(_ufeDstItem->prim()); } @@ -154,8 +156,10 @@ bool UsdUndoRenameCommand::renameUndo() const UsdPrim& prim = _stage->GetPrimAtPath(_ufeDstItem->prim().GetPath()); - auto ufeSiblingPath = _ufeSrcItem->path().sibling(Ufe::PathComponent(_ufeSrcItem->prim().GetName())); - bool status = MayaUsdUtils::updateInternalReferencesPath(prim, SdfPath(ufeSiblingPath.getSegments()[1].string())); + auto ufeSiblingPath + = _ufeSrcItem->path().sibling(Ufe::PathComponent(_ufeSrcItem->prim().GetName())); + bool status = MayaUsdUtils::updateInternalReferencesPath( + prim, SdfPath(ufeSiblingPath.getSegments()[1].string())); if (!status) { return false; } @@ -171,7 +175,7 @@ bool UsdUndoRenameCommand::renameUndo() _ufeSrcItem = createSiblingSceneItem(_ufeDstItem->path(), _ufeSrcItem->prim().GetName()); // update stage's default prim - if(_ufeDstItem->prim().GetPath() == defaultPrimPath) { + if (_ufeDstItem->prim().GetPath() == defaultPrimPath) { _stage->SetDefaultPrim(_ufeSrcItem->prim()); } @@ -188,10 +192,9 @@ void UsdUndoRenameCommand::undo() if (!renameUndo()) { UFE_LOG("rename undo failed"); } - } - catch (const std::exception& e) { + } catch (const std::exception& e) { UFE_LOG(e.what()); - throw; // re-throw the same exception + throw; // re-throw the same exception } } @@ -204,4 +207,4 @@ void UsdUndoRenameCommand::redo() } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoRenameCommand.h b/lib/mayaUsd/ufe/UsdUndoRenameCommand.h index 1d60a32043..1358404f5d 100644 --- a/lib/mayaUsd/ufe/UsdUndoRenameCommand.h +++ b/lib/mayaUsd/ufe/UsdUndoRenameCommand.h @@ -15,13 +15,13 @@ // #pragma once +#include +#include + #include #include #include -#include -#include - PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { @@ -43,7 +43,8 @@ class MAYAUSD_CORE_PUBLIC UsdUndoRenameCommand : public Ufe::UndoableCommand UsdUndoRenameCommand& operator=(UsdUndoRenameCommand&&) = delete; //! Create a UsdUndoRenameCommand from a USD scene item and UFE pathcomponent. - static UsdUndoRenameCommand::Ptr create(const UsdSceneItem::Ptr& srcItem, const Ufe::PathComponent& newName); + static UsdUndoRenameCommand::Ptr + create(const UsdSceneItem::Ptr& srcItem, const Ufe::PathComponent& newName); UsdSceneItem::Ptr renamedItem() const; @@ -58,9 +59,9 @@ class MAYAUSD_CORE_PUBLIC UsdUndoRenameCommand : public Ufe::UndoableCommand UsdSceneItem::Ptr _ufeDstItem; UsdStageWeakPtr _stage; - std::string _newName; + std::string _newName; }; // UsdUndoRenameCommand } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoReorderCommand.cpp b/lib/mayaUsd/ufe/UsdUndoReorderCommand.cpp index 1cc23be08e..9d45b0e775 100644 --- a/lib/mayaUsd/ufe/UsdUndoReorderCommand.cpp +++ b/lib/mayaUsd/ufe/UsdUndoReorderCommand.cpp @@ -22,18 +22,19 @@ namespace MAYAUSD_NS_DEF { namespace ufe { -UsdUndoReorderCommand::UsdUndoReorderCommand(const UsdPrim& parentPrim, const std::vector& tokenList) +UsdUndoReorderCommand::UsdUndoReorderCommand( + const UsdPrim& parentPrim, + const std::vector& tokenList) : Ufe::UndoableCommand() , _parentPrim(parentPrim) , _orderedTokens(tokenList) { } -UsdUndoReorderCommand::~UsdUndoReorderCommand() -{ -} +UsdUndoReorderCommand::~UsdUndoReorderCommand() { } -UsdUndoReorderCommand::Ptr UsdUndoReorderCommand::create(const UsdPrim& parentPrim, const std::vector& tokenList) +UsdUndoReorderCommand::Ptr +UsdUndoReorderCommand::create(const UsdPrim& parentPrim, const std::vector& tokenList) { if (!parentPrim) { return nullptr; @@ -56,10 +57,9 @@ void UsdUndoReorderCommand::undo() if (!reorder()) { UFE_LOG("reorder undo failed"); } - } - catch (const std::exception& e) { + } catch (const std::exception& e) { UFE_LOG(e.what()); - throw; // re-throw the same exception + throw; // re-throw the same exception } } @@ -71,4 +71,4 @@ void UsdUndoReorderCommand::redo() } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/UsdUndoReorderCommand.h b/lib/mayaUsd/ufe/UsdUndoReorderCommand.h index ea64caa956..3ce3579776 100644 --- a/lib/mayaUsd/ufe/UsdUndoReorderCommand.h +++ b/lib/mayaUsd/ufe/UsdUndoReorderCommand.h @@ -15,12 +15,12 @@ // #pragma once -#include - #include #include +#include + PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { @@ -42,7 +42,8 @@ class MAYAUSD_CORE_PUBLIC UsdUndoReorderCommand : public Ufe::UndoableCommand UsdUndoReorderCommand& operator=(UsdUndoReorderCommand&&) = delete; //! Create a UsdUndoReorderCommand - static UsdUndoReorderCommand::Ptr create(const UsdPrim& parentPrim, const std::vector& orderedTokens); + static UsdUndoReorderCommand::Ptr + create(const UsdPrim& parentPrim, const std::vector& orderedTokens); private: bool reorder(); @@ -57,4 +58,4 @@ class MAYAUSD_CORE_PUBLIC UsdUndoReorderCommand : public Ufe::UndoableCommand }; // UsdUndoReorderCommand } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/Utils.cpp b/lib/mayaUsd/ufe/Utils.cpp index 002dad1706..f5b9360c6e 100644 --- a/lib/mayaUsd/ufe/Utils.cpp +++ b/lib/mayaUsd/ufe/Utils.cpp @@ -15,40 +15,38 @@ // #include "Utils.h" -#include -#include -#include -#include -#include -#include - -#include - -#include -#include - -#include -#include +#include "private/Utils.h" #include #include #include #include -#include "private/Utils.h" +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE #ifndef MAYA_MSTRINGARRAY_ITERATOR_CATEGORY // MStringArray::Iterator is not standard-compliant in Maya 2019, needs the // following workaround. Fixed in Maya 2020. PPT, 20-Jun-2019. -namespace std +namespace std { +template <> struct iterator_traits { - template<> - struct iterator_traits { - typedef std::bidirectional_iterator_tag iterator_category; - }; -} + typedef std::bidirectional_iterator_tag iterator_category; +}; +} // namespace std #endif namespace MAYAUSD_NS_DEF { @@ -59,7 +57,7 @@ namespace ufe { //------------------------------------------------------------------------------ extern UsdStageMap g_StageMap; -extern Ufe::Rtid g_MayaRtid; +extern Ufe::Rtid g_MayaRtid; // Cache of Maya node types we've queried before for inheritance from the // gateway node type. @@ -69,136 +67,126 @@ std::unordered_map g_GatewayType; // Utility Functions //------------------------------------------------------------------------------ -UsdStageWeakPtr getStage(const Ufe::Path& path) -{ - return g_StageMap.stage(path); -} +UsdStageWeakPtr getStage(const Ufe::Path& path) { return g_StageMap.stage(path); } -Ufe::Path stagePath(UsdStageWeakPtr stage) -{ - return g_StageMap.path(stage); -} +Ufe::Path stagePath(UsdStageWeakPtr stage) { return g_StageMap.path(stage); } UsdPrim ufePathToPrim(const Ufe::Path& path) { - // Assume that there are only two segments in the path, the first a Maya - // Dag path segment to the proxy shape, which identifies the stage, and - // the second the USD segment. - const Ufe::Path::Segments& segments = path.getSegments(); - TEST_USD_PATH(segments, path); - - UsdPrim prim; - if (auto stage = getStage(Ufe::Path(segments[0]))) - { - prim = stage->GetPrimAtPath(SdfPath(segments[1].string())); - } - return prim; + // Assume that there are only two segments in the path, the first a Maya + // Dag path segment to the proxy shape, which identifies the stage, and + // the second the USD segment. + const Ufe::Path::Segments& segments = path.getSegments(); + TEST_USD_PATH(segments, path); + + UsdPrim prim; + if (auto stage = getStage(Ufe::Path(segments[0]))) { + prim = stage->GetPrimAtPath(SdfPath(segments[1].string())); + } + return prim; } bool isRootChild(const Ufe::Path& path) { - auto segments = path.getSegments(); - TEST_USD_PATH(segments, path); - return(segments[1].size() == 1); + auto segments = path.getSegments(); + TEST_USD_PATH(segments, path); + return (segments[1].size() == 1); } -UsdSceneItem::Ptr createSiblingSceneItem(const Ufe::Path& ufeSrcPath, const std::string& siblingName) +UsdSceneItem::Ptr +createSiblingSceneItem(const Ufe::Path& ufeSrcPath, const std::string& siblingName) { - auto ufeSiblingPath = ufeSrcPath.sibling(Ufe::PathComponent(siblingName)); - return UsdSceneItem::create(ufeSiblingPath, ufePathToPrim(ufeSiblingPath)); + auto ufeSiblingPath = ufeSrcPath.sibling(Ufe::PathComponent(siblingName)); + return UsdSceneItem::create(ufeSiblingPath, ufePathToPrim(ufeSiblingPath)); } std::string uniqueName(const TfToken::HashSet& existingNames, std::string srcName) { - // Compiled regular expression to find a numerical suffix to a path component. - // It searches for any number of characters followed by a single non-numeric, - // then one or more digits at end of string. - std::regex re("(.*)([^0-9])([0-9]+)$"); - std::string base{srcName}; - int suffix{1}; - std::smatch match; - if (std::regex_match(srcName, match, re)) - { - base = match[1].str() + match[2].str(); - suffix = std::stoi(match[3].str()) + 1; - } - std::string dstName = base + std::to_string(suffix); - while (existingNames.count(TfToken(dstName)) > 0) - { - dstName = base + std::to_string(++suffix); - } - return dstName; + // Compiled regular expression to find a numerical suffix to a path component. + // It searches for any number of characters followed by a single non-numeric, + // then one or more digits at end of string. + std::regex re("(.*)([^0-9])([0-9]+)$"); + std::string base { srcName }; + int suffix { 1 }; + std::smatch match; + if (std::regex_match(srcName, match, re)) { + base = match[1].str() + match[2].str(); + suffix = std::stoi(match[3].str()) + 1; + } + std::string dstName = base + std::to_string(suffix); + while (existingNames.count(TfToken(dstName)) > 0) { + dstName = base + std::to_string(++suffix); + } + return dstName; } std::string uniqueChildName(const UsdPrim& usdParent, const std::string& name) { - if (!usdParent.IsValid()) return std::string(); - - TfToken::HashSet childrenNames; - - // The prim GetChildren method used the UsdPrimDefaultPredicate which includes - // active prims. We also need the inactive ones. - // - // const Usd_PrimFlagsConjunction UsdPrimDefaultPredicate = - // UsdPrimIsActive && UsdPrimIsDefined && - // UsdPrimIsLoaded && !UsdPrimIsAbstract; - // Note: removed 'UsdPrimIsLoaded' from the predicate. When it is present the - // filter doesn't properly return the inactive prims. UsdView doesn't - // use loaded either in _computeDisplayPredicate(). - // - // Note: our UsdHierarchy uses instance proxies, so we also use them here. - for (auto child : usdParent.GetFilteredChildren(UsdTraverseInstanceProxies(UsdPrimIsDefined && !UsdPrimIsAbstract))) - { - childrenNames.insert(child.GetName()); - } - std::string childName{name}; - if (childrenNames.find(TfToken(childName)) != childrenNames.end()) - { - childName = uniqueName(childrenNames, childName); - } - return childName; + if (!usdParent.IsValid()) + return std::string(); + + TfToken::HashSet childrenNames; + + // The prim GetChildren method used the UsdPrimDefaultPredicate which includes + // active prims. We also need the inactive ones. + // + // const Usd_PrimFlagsConjunction UsdPrimDefaultPredicate = + // UsdPrimIsActive && UsdPrimIsDefined && + // UsdPrimIsLoaded && !UsdPrimIsAbstract; + // Note: removed 'UsdPrimIsLoaded' from the predicate. When it is present the + // filter doesn't properly return the inactive prims. UsdView doesn't + // use loaded either in _computeDisplayPredicate(). + // + // Note: our UsdHierarchy uses instance proxies, so we also use them here. + for (auto child : usdParent.GetFilteredChildren( + UsdTraverseInstanceProxies(UsdPrimIsDefined && !UsdPrimIsAbstract))) { + childrenNames.insert(child.GetName()); + } + std::string childName { name }; + if (childrenNames.find(TfToken(childName)) != childrenNames.end()) { + childName = uniqueName(childrenNames, childName); + } + return childName; } bool isAGatewayType(const std::string& mayaNodeType) { - // If we've seen this node type before, return the cached value. - auto iter = g_GatewayType.find(mayaNodeType); - if (iter != std::end(g_GatewayType)) - { - return iter->second; - } - - // Note: we are calling the MEL interpreter to determine the inherited types, - // but we are then caching the result. So MEL will only be called once - // for each node type. - // Not seen before, so ask Maya. - // When the inherited flag is used, the command returns a string array containing - // the names of all the base node types inherited by the the given node. - MString cmd; - MStringArray inherited; - bool isInherited = false; - cmd.format("nodeType -inherited -isTypeName ^1s", mayaNodeType.c_str()); - if (MS::kSuccess == MGlobal::executeCommand(cmd, inherited)) - { - MString gatewayNodeType(ProxyShapeHandler::gatewayNodeType().c_str()); - auto iter2 = std::find(inherited.begin(), inherited.end(), gatewayNodeType); - isInherited = (iter2 != inherited.end()); - g_GatewayType[mayaNodeType] = isInherited; - } - return isInherited; + // If we've seen this node type before, return the cached value. + auto iter = g_GatewayType.find(mayaNodeType); + if (iter != std::end(g_GatewayType)) { + return iter->second; + } + + // Note: we are calling the MEL interpreter to determine the inherited types, + // but we are then caching the result. So MEL will only be called once + // for each node type. + // Not seen before, so ask Maya. + // When the inherited flag is used, the command returns a string array containing + // the names of all the base node types inherited by the the given node. + MString cmd; + MStringArray inherited; + bool isInherited = false; + cmd.format("nodeType -inherited -isTypeName ^1s", mayaNodeType.c_str()); + if (MS::kSuccess == MGlobal::executeCommand(cmd, inherited)) { + MString gatewayNodeType(ProxyShapeHandler::gatewayNodeType().c_str()); + auto iter2 = std::find(inherited.begin(), inherited.end(), gatewayNodeType); + isInherited = (iter2 != inherited.end()); + g_GatewayType[mayaNodeType] = isInherited; + } + return isInherited; } Ufe::Path dagPathToUfe(const MDagPath& dagPath) { - // This function can only create UFE Maya scene items with a single - // segment, as it is only given a Dag path as input. - return Ufe::Path(dagPathToPathSegment(dagPath)); + // This function can only create UFE Maya scene items with a single + // segment, as it is only given a Dag path as input. + return Ufe::Path(dagPathToPathSegment(dagPath)); } Ufe::PathSegment dagPathToPathSegment(const MDagPath& dagPath) { - std::string fullPathName = dagPath.fullPathName().asChar(); - return Ufe::PathSegment("world" + fullPathName, g_MayaRtid, '|'); + std::string fullPathName = dagPath.fullPathName().asChar(); + return Ufe::PathSegment("world" + fullPathName, g_MayaRtid, '|'); } UsdTimeCode getTime(const Ufe::Path& path) @@ -220,26 +208,23 @@ UsdTimeCode getTime(const Ufe::Path& path) if (cache.first == proxyShapePath && cache.second.isValid()) { proxyShapeObj = cache.second.object(); - } - else { + } else { // Not found in the cache, or no longer valid. Get the proxy shape // MObject from its path, and put it in the cache. Pop the head of the // UFE path to get rid of "|world", which is implicit in Maya. - auto proxyShapeDagPath = UsdMayaUtil::nameToDagPath( - proxyShapePath.popHead().string()); + auto proxyShapeDagPath = UsdMayaUtil::nameToDagPath(proxyShapePath.popHead().string()); TF_VERIFY(proxyShapeDagPath.isValid()); proxyShapeObj = proxyShapeDagPath.node(); - cache = std::pair( - proxyShapePath, MObjectHandle(proxyShapeObj)); + cache = std::pair(proxyShapePath, MObjectHandle(proxyShapeObj)); } - + // Get time from the proxy shape. MFnDependencyNode fn(proxyShapeObj); - auto proxyShape = dynamic_cast(fn.userNode()); + auto proxyShape = dynamic_cast(fn.userNode()); TF_VERIFY(proxyShape); return proxyShape->getTime(); } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/Utils.h b/lib/mayaUsd/ufe/Utils.h index a2ad4f3f40..92426586ba 100644 --- a/lib/mayaUsd/ufe/Utils.h +++ b/lib/mayaUsd/ufe/Utils.h @@ -15,19 +15,18 @@ // #pragma once -#include -#include -#include - -#include +#include +#include +#include +#include #include #include -#include -#include -#include -#include +#include +#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -54,7 +53,8 @@ MAYAUSD_CORE_PUBLIC bool isRootChild(const Ufe::Path& path); MAYAUSD_CORE_PUBLIC -UsdSceneItem::Ptr createSiblingSceneItem(const Ufe::Path& ufeSrcPath, const std::string& siblingName); +UsdSceneItem::Ptr +createSiblingSceneItem(const Ufe::Path& ufeSrcPath, const std::string& siblingName); //! Split the source name into a base name and a numerical suffix (set to //! 1 if absent). Increment the numerical suffix until name is unique. @@ -80,23 +80,23 @@ Ufe::PathSegment dagPathToPathSegment(const MDagPath& dagPath); MAYAUSD_CORE_PUBLIC UsdTimeCode getTime(const Ufe::Path& path); -//! Send notification for data model changes +//! Send notification for data model changes template void sendNotification(const Ufe::SceneItem::Ptr& item, const Ufe::Path& previousPath) { T notification(item, previousPath); - #ifdef UFE_V2_FEATURES_AVAILABLE +#ifdef UFE_V2_FEATURES_AVAILABLE Ufe::Scene::instance().notify(notification); - #else +#else Ufe::Scene::notifyObjectPathChange(notification); - #endif +#endif } //! Readability function to downcast a SceneItem::Ptr to a UsdSceneItem::Ptr. -inline -UsdSceneItem::Ptr downcast(const Ufe::SceneItem::Ptr& item) { +inline UsdSceneItem::Ptr downcast(const Ufe::SceneItem::Ptr& item) +{ return std::dynamic_pointer_cast(item); } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/module.cpp b/lib/mayaUsd/ufe/module.cpp index 055c7cc80a..02fbeb68a2 100644 --- a/lib/mayaUsd/ufe/module.cpp +++ b/lib/mayaUsd/ufe/module.cpp @@ -13,12 +13,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include #include +#include PXR_NAMESPACE_USING_DIRECTIVE -TF_WRAP_MODULE { +TF_WRAP_MODULE +{ TF_WRAP(Global); TF_WRAP(Utils); TF_WRAP(Notice); diff --git a/lib/mayaUsd/ufe/moduleDeps.cpp b/lib/mayaUsd/ufe/moduleDeps.cpp index 41a42ef7f9..135bd3ffa1 100644 --- a/lib/mayaUsd/ufe/moduleDeps.cpp +++ b/lib/mayaUsd/ufe/moduleDeps.cpp @@ -13,27 +13,22 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include #include #include #include +#include #include PXR_NAMESPACE_OPEN_SCOPE -TF_REGISTRY_FUNCTION(TfScriptModuleLoader) { +TF_REGISTRY_FUNCTION(TfScriptModuleLoader) +{ // List of direct dependencies for this library. - const std::vector reqs = { - TfToken("mayaUsd"), - TfToken("sdf"), - TfToken("tf"), - TfToken("usd"), - TfToken("usdGeom"), - TfToken("vt") - }; - TfScriptModuleLoader::GetInstance(). - RegisterLibrary(TfToken("ufe"), TfToken("mayaUsd.ufe"), reqs); + const std::vector reqs = { TfToken("mayaUsd"), TfToken("sdf"), TfToken("tf"), + TfToken("usd"), TfToken("usdGeom"), TfToken("vt") }; + TfScriptModuleLoader::GetInstance().RegisterLibrary( + TfToken("ufe"), TfToken("mayaUsd.ufe"), reqs); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/ufe/private/UfeNotifGuard.h b/lib/mayaUsd/ufe/private/UfeNotifGuard.h index 230a8fdc53..979b485a64 100644 --- a/lib/mayaUsd/ufe/private/UfeNotifGuard.h +++ b/lib/mayaUsd/ufe/private/UfeNotifGuard.h @@ -25,42 +25,41 @@ namespace ufe { class InPathChange { public: - InPathChange() { inGuard = true; } - ~InPathChange() { inGuard = false; } + InPathChange() { inGuard = true; } + ~InPathChange() { inGuard = false; } - // Delete the copy/move constructors assignment operators. - InPathChange(const InPathChange&) = delete; - InPathChange& operator=(const InPathChange&) = delete; - InPathChange(InPathChange&&) = delete; - InPathChange& operator=(InPathChange&&) = delete; + // Delete the copy/move constructors assignment operators. + InPathChange(const InPathChange&) = delete; + InPathChange& operator=(const InPathChange&) = delete; + InPathChange(InPathChange&&) = delete; + InPathChange& operator=(InPathChange&&) = delete; - static bool inPathChange() { return inGuard; } + static bool inPathChange() { return inGuard; } private: - static bool inGuard; + static bool inGuard; }; //! \brief Helper class to scope when we are in an add or delete operation. class InAddOrDeleteOperation { public: - InAddOrDeleteOperation() { inGuard = true; } - ~InAddOrDeleteOperation() { inGuard = false; } + InAddOrDeleteOperation() { inGuard = true; } + ~InAddOrDeleteOperation() { inGuard = false; } - // Delete the copy/move constructors assignment operators. - InAddOrDeleteOperation(const InAddOrDeleteOperation&) = delete; - InAddOrDeleteOperation& operator=(const InAddOrDeleteOperation&) = delete; - InAddOrDeleteOperation(InAddOrDeleteOperation&&) = delete; - InAddOrDeleteOperation& operator=(InAddOrDeleteOperation&&) = delete; + // Delete the copy/move constructors assignment operators. + InAddOrDeleteOperation(const InAddOrDeleteOperation&) = delete; + InAddOrDeleteOperation& operator=(const InAddOrDeleteOperation&) = delete; + InAddOrDeleteOperation(InAddOrDeleteOperation&&) = delete; + InAddOrDeleteOperation& operator=(InAddOrDeleteOperation&&) = delete; - static bool inAddOrDeleteOperation() { return inGuard; } + static bool inAddOrDeleteOperation() { return inGuard; } private: - static bool inGuard; + static bool inGuard; }; - } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF #endif // UFENOTIFGUARD_H diff --git a/lib/mayaUsd/ufe/private/Utils.cpp b/lib/mayaUsd/ufe/private/Utils.cpp index efd05a5769..24a367c6e7 100644 --- a/lib/mayaUsd/ufe/private/Utils.cpp +++ b/lib/mayaUsd/ufe/private/Utils.cpp @@ -15,16 +15,16 @@ // #include "Utils.h" -#include -#include - -#include - #include #include +#include + #include +#include +#include + PXR_NAMESPACE_USING_DIRECTIVE namespace MAYAUSD_NS_DEF { @@ -37,7 +37,8 @@ namespace ufe { UsdGeomXformCommonAPI convertToCompatibleCommonAPI(const UsdPrim& prim) { // As we are using USD's XformCommonAPI which supports only the following xformOps : - // ["xformOp:translate", "xformOp:translate:pivot", "xformOp:rotateXYZ", "xformOp:scale", "!invert!xformOp:translate:pivot"] + // ["xformOp:translate", "xformOp:translate:pivot", "xformOp:rotateXYZ", "xformOp:scale", + // "!invert!xformOp:translate:pivot"] // We are extending the supported xform Operations with : // ["xformOp:rotateX", "xformOp:rotateY", "xformOp:rotateZ"] // Where we convert these into xformOp:rotateXYZ. @@ -56,16 +57,13 @@ UsdGeomXformCommonAPI convertToCompatibleCommonAPI(const UsdPrim& prim) auto xformOps = xformable.GetOrderedXformOps(&resetsXformStack); xformable.ClearXformOpOrder(); auto primXform = UsdGeomXformCommonAPI(prim); - for (const auto& op : xformOps) - { + for (const auto& op : xformOps) { auto opName = op.GetOpName(); // RotateX, RotateY, RotateZ - if ((opName == rotX) || (opName == rotY) || (opName == rotZ)) - { + if ((opName == rotX) || (opName == rotY) || (opName == rotZ)) { float retValue; - if (op.Get(&retValue)) - { + if (op.Get(&retValue)) { if (opName == rotX) primXform.SetRotate(GfVec3f(retValue, 0, 0)); else if (opName == rotY) @@ -75,52 +73,43 @@ UsdGeomXformCommonAPI convertToCompatibleCommonAPI(const UsdPrim& prim) } } // RotateXYZ - else if (opName == rotXYZ) - { + else if (opName == rotXYZ) { GfVec3f retValue; - if (op.Get(&retValue)) - { + if (op.Get(&retValue)) { primXform.SetRotate(retValue); } } // Scale - else if (opName == scale) - { + else if (opName == scale) { GfVec3f retValue; - if (op.Get(&retValue)) - { + if (op.Get(&retValue)) { primXform.SetScale(retValue); } } // Translate - else if (opName == trans) - { + else if (opName == trans) { GfVec3d retValue; - if (op.Get(&retValue)) - { + if (op.Get(&retValue)) { primXform.SetTranslate(retValue); } } // Scale / rotate pivot - else if (opName == pivot) - { + else if (opName == pivot) { GfVec3f retValue; - if (op.Get(&retValue)) - { + if (op.Get(&retValue)) { primXform.SetPivot(retValue); } } // Scale / rotate pivot inverse - else if (opName == notPivot) - { + else if (opName == notPivot) { // automatically added, nothing to do. } // Not compatible - else - { + else { // Restore old xformable.SetXformOpOrder(xformOps); - std::string err = TfStringPrintf("Incompatible xform op %s:", op.GetOpName().GetString().c_str()); + std::string err + = TfStringPrintf("Incompatible xform op %s:", op.GetOpName().GetString().c_str()); throw std::runtime_error(err.c_str()); } } @@ -130,42 +119,44 @@ UsdGeomXformCommonAPI convertToCompatibleCommonAPI(const UsdPrim& prim) void applyCommandRestriction(const UsdPrim& prim, const std::string& commandName) { // return early if prim is the pseudo-root. - // this is a special case and could happen when one tries to drag a prim under the + // this is a special case and could happen when one tries to drag a prim under the // proxy shape in outliner. Also note if prim is the pseudo-root, no def primSpec will be found. - if (prim.IsPseudoRoot()){ + if (prim.IsPseudoRoot()) { return; } - auto primSpec = MayaUsdUtils::getPrimSpecAtEditTarget(prim); - auto primStack = prim.GetPrimStack(); + auto primSpec = MayaUsdUtils::getPrimSpecAtEditTarget(prim); + auto primStack = prim.GetPrimStack(); std::string layerDisplayName; - std::string message{"It is defined on another layer"}; + std::string message { "It is defined on another layer" }; // iterate over the prim stack, starting at the highest-priority layer. - for (const auto& spec : primStack) - { + for (const auto& spec : primStack) { const auto& layerName = spec->GetLayer()->GetDisplayName(); // skip if there is no primSpec for the selected prim in the current stage's local layer. - if(!primSpec){ + if (!primSpec) { // add "," separator for multiple layers - if(!layerDisplayName.empty()) { layerDisplayName.append(","); } + if (!layerDisplayName.empty()) { + layerDisplayName.append(","); + } layerDisplayName.append("[" + layerName + "]"); continue; } - // one reason for skipping the reference is to not clash + // one reason for skipping the reference is to not clash // with the over that may be created in the stage's sessionLayer. // another reason is that one should be able to edit a referenced prim that // either as over/def as long as it has a primSpec in the selected edit target layer. - if(spec->HasReferences()) { + if (spec->HasReferences()) { break; } // if exists a def/over specs if (spec->GetSpecifier() == SdfSpecifierDef || spec->GetSpecifier() == SdfSpecifierOver) { - // if spec exists in another layer ( e.g sessionLayer or layer other than stage's local layers ). - if(primSpec->GetLayer() != spec->GetLayer()) { + // if spec exists in another layer ( e.g sessionLayer or layer other than stage's local + // layers ). + if (primSpec->GetLayer() != spec->GetLayer()) { layerDisplayName.append("[" + layerName + "]"); message = "It has a stronger opinion on another layer"; break; @@ -174,12 +165,13 @@ void applyCommandRestriction(const UsdPrim& prim, const std::string& commandName } } - if(!layerDisplayName.empty()) { - std::string err = TfStringPrintf("Cannot %s [%s]. %s. Please set %s as the target layer to proceed.", - commandName.c_str(), - prim.GetName().GetString().c_str(), - message.c_str(), - layerDisplayName.c_str()); + if (!layerDisplayName.empty()) { + std::string err = TfStringPrintf( + "Cannot %s [%s]. %s. Please set %s as the target layer to proceed.", + commandName.c_str(), + prim.GetName().GetString().c_str(), + message.c_str(), + layerDisplayName.c_str()); throw std::runtime_error(err.c_str()); } } @@ -191,17 +183,15 @@ void applyCommandRestriction(const UsdPrim& prim, const std::string& commandName void translateOp(const UsdPrim& prim, const Ufe::Path& path, double x, double y, double z) { auto primXform = UsdGeomXformCommonAPI(prim); - if (!primXform.SetTranslate(GfVec3d(x, y, z))) - { + if (!primXform.SetTranslate(GfVec3d(x, y, z))) { // This could mean that we have an incompatible xformOp in the stack try { primXform = convertToCompatibleCommonAPI(prim); - if (!primXform.SetTranslate(GfVec3d(x,y,z))) + if (!primXform.SetTranslate(GfVec3d(x, y, z))) throw std::runtime_error("Unable to SetTranslate after conversion to CommonAPI."); - } - catch (const std::exception& e) { - std::string err = TfStringPrintf("Failed to translate prim %s - %s", - path.string().c_str(), e.what()); + } catch (const std::exception& e) { + std::string err = TfStringPrintf( + "Failed to translate prim %s - %s", path.string().c_str(), e.what()); UFE_LOG(err.c_str()); throw; } @@ -211,17 +201,15 @@ void translateOp(const UsdPrim& prim, const Ufe::Path& path, double x, double y, void rotateOp(const UsdPrim& prim, const Ufe::Path& path, double x, double y, double z) { auto primXform = UsdGeomXformCommonAPI(prim); - if (!primXform.SetRotate(GfVec3f(x, y, z))) - { + if (!primXform.SetRotate(GfVec3f(x, y, z))) { // This could mean that we have an incompatible xformOp in the stack try { primXform = convertToCompatibleCommonAPI(prim); if (!primXform.SetRotate(GfVec3f(x, y, z))) throw std::runtime_error("Unable to SetRotate after conversion to CommonAPI."); - } - catch (const std::exception& e) { - std::string err = TfStringPrintf("Failed to rotate prim %s - %s", - path.string().c_str(), e.what()); + } catch (const std::exception& e) { + std::string err + = TfStringPrintf("Failed to rotate prim %s - %s", path.string().c_str(), e.what()); UFE_LOG(err.c_str()); throw; } @@ -231,37 +219,38 @@ void rotateOp(const UsdPrim& prim, const Ufe::Path& path, double x, double y, do void scaleOp(const UsdPrim& prim, const Ufe::Path& path, double x, double y, double z) { auto primXform = UsdGeomXformCommonAPI(prim); - if (!primXform.SetScale(GfVec3f(x, y, z))) - { + if (!primXform.SetScale(GfVec3f(x, y, z))) { // This could mean that we have an incompatible xformOp in the stack try { primXform = convertToCompatibleCommonAPI(prim); if (!primXform.SetScale(GfVec3f(x, y, z))) throw std::runtime_error("Unable to SetScale after conversion to CommonAPI."); - } - catch (const std::exception& e) { - std::string err = TfStringPrintf("Failed to scale prim %s - %s", - path.string().c_str(), e.what()); + } catch (const std::exception& e) { + std::string err + = TfStringPrintf("Failed to scale prim %s - %s", path.string().c_str(), e.what()); UFE_LOG(err.c_str()); throw; } } } -void rotatePivotTranslateOp(const UsdPrim& prim, const Ufe::Path& path, double x, double y, double z) +void rotatePivotTranslateOp( + const UsdPrim& prim, + const Ufe::Path& path, + double x, + double y, + double z) { auto primXform = UsdGeomXformCommonAPI(prim); - if (!primXform.SetPivot(GfVec3f(x, y, z))) - { + if (!primXform.SetPivot(GfVec3f(x, y, z))) { // This could mean that we have an incompatible xformOp in the stack try { primXform = convertToCompatibleCommonAPI(prim); if (!primXform.SetPivot(GfVec3f(x, y, z))) throw std::runtime_error("Unable to SetPivot after conversion to CommonAPI."); - } - catch (const std::exception& e) { - std::string err = TfStringPrintf("Failed to set pivot for prim %s - %s", - path.string().c_str(), e.what()); + } catch (const std::exception& e) { + std::string err = TfStringPrintf( + "Failed to set pivot for prim %s - %s", path.string().c_str(), e.what()); UFE_LOG(err.c_str()); throw; } @@ -269,4 +258,4 @@ void rotatePivotTranslateOp(const UsdPrim& prim, const Ufe::Path& path, double x } } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/private/Utils.h b/lib/mayaUsd/ufe/private/Utils.h index 33df9cffb4..44f7528f60 100644 --- a/lib/mayaUsd/ufe/private/Utils.h +++ b/lib/mayaUsd/ufe/private/Utils.h @@ -15,13 +15,13 @@ // #pragma once -#include +#include -#include #include +#include #include -#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -34,14 +34,14 @@ namespace ufe { const std::string kIllegalUSDPath = "Illegal USD run-time path %s."; #if !defined(NDEBUG) - #define TEST_USD_PATH(SEG, PATH) \ - assert(SEG.size() == 2); \ - if (SEG.size() != 2) \ - TF_WARN(kIllegalUSDPath.c_str(), PATH.string().c_str()); +#define TEST_USD_PATH(SEG, PATH) \ + assert(SEG.size() == 2); \ + if (SEG.size() != 2) \ + TF_WARN(kIllegalUSDPath.c_str(), PATH.string().c_str()); #else - #define TEST_USD_PATH(SEG, PATH) \ - if (SEG.size() != 2) \ - TF_WARN(kIllegalUSDPath.c_str(), PATH.string().c_str()); +#define TEST_USD_PATH(SEG, PATH) \ + if (SEG.size() != 2) \ + TF_WARN(kIllegalUSDPath.c_str(), PATH.string().c_str()); #endif //------------------------------------------------------------------------------ @@ -68,7 +68,12 @@ void rotateOp(const UsdPrim& prim, const Ufe::Path& path, double x, double y, do void scaleOp(const UsdPrim& prim, const Ufe::Path& path, double x, double y, double z); //! Absolute translation of the given prim's pivot point. -void rotatePivotTranslateOp(const UsdPrim& prim, const Ufe::Path& path, double x, double y, double z); +void rotatePivotTranslateOp( + const UsdPrim& prim, + const Ufe::Path& path, + double x, + double y, + double z); } // namespace ufe -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/ufe/wrapGlobal.cpp b/lib/mayaUsd/ufe/wrapGlobal.cpp index b22dcf93e9..2056d3f154 100644 --- a/lib/mayaUsd/ufe/wrapGlobal.cpp +++ b/lib/mayaUsd/ufe/wrapGlobal.cpp @@ -20,9 +20,7 @@ using namespace MayaUsd; using namespace boost::python; - -void -wrapGlobal() +void wrapGlobal() { def("getMayaRunTimeId", ufe::getMayaRunTimeId); diff --git a/lib/mayaUsd/ufe/wrapNotice.cpp b/lib/mayaUsd/ufe/wrapNotice.cpp index b305b8e259..daab36023b 100644 --- a/lib/mayaUsd/ufe/wrapNotice.cpp +++ b/lib/mayaUsd/ufe/wrapNotice.cpp @@ -35,13 +35,13 @@ void wrapNotice() { typedef MayaUsdProxyStageSetNotice This; TfPyNoticeWrapper::Wrap() - .add_property("shapePath", &This::GetShapePath) - .add_property("stage", &This::GetStage); + .add_property("shapePath", &This::GetShapePath) + .add_property("stage", &This::GetStage); } { typedef MayaUsdProxyStageInvalidateNotice This; TfPyNoticeWrapper::Wrap() - .add_property("shapePath", &This::GetShapePath) - .add_property("stage", &This::GetStage); + .add_property("shapePath", &This::GetShapePath) + .add_property("stage", &This::GetStage); } } diff --git a/lib/mayaUsd/ufe/wrapUtils.cpp b/lib/mayaUsd/ufe/wrapUtils.cpp index 342f064e4a..fb4c845566 100644 --- a/lib/mayaUsd/ufe/wrapUtils.cpp +++ b/lib/mayaUsd/ufe/wrapUtils.cpp @@ -13,26 +13,25 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include -#include - -#include - #include #include #include +#include + +#include +#include + +#include + using namespace MayaUsd; using namespace boost::python; UsdPrim getPrimFromRawItem(uint64_t rawItem) { - Ufe::SceneItem* item = reinterpret_cast(rawItem); + Ufe::SceneItem* item = reinterpret_cast(rawItem); ufe::UsdSceneItem* usdItem = dynamic_cast(item); - if (nullptr != usdItem) - { + if (nullptr != usdItem) { return usdItem->prim(); } return UsdPrim(); @@ -41,7 +40,7 @@ UsdPrim getPrimFromRawItem(uint64_t rawItem) #ifdef UFE_V2_FEATURES_AVAILABLE std::string getNodeNameFromRawItem(uint64_t rawItem) { - std::string name; + std::string name; Ufe::SceneItem* item = reinterpret_cast(rawItem); if (nullptr != item) name = item->nodeName(); @@ -51,10 +50,9 @@ std::string getNodeNameFromRawItem(uint64_t rawItem) std::string getNodeTypeFromRawItem(uint64_t rawItem) { - std::string type; + std::string type; Ufe::SceneItem* item = reinterpret_cast(rawItem); - if (nullptr != item) - { + if (nullptr != item) { // Prepend the name of the runtime manager of this item to the type. type = Ufe::RunTimeMgr::instance().getName(item->runTimeId()) + item->nodeType(); } @@ -92,25 +90,23 @@ UsdPrim ufePathToPrim(const std::string& ufePathString) // segment at a time. The path segment separator is the first character // of each segment. We know that USD's separator is '/' and Maya's // separator is '|', so use a map to get the corresponding UFE run-time ID. - Ufe::Path path; - static std::map sepToRtid = { - {'/', ufe::getUsdRunTimeId()}, {'|', 1}}; + Ufe::Path path; + static std::map sepToRtid = { { '/', ufe::getUsdRunTimeId() }, { '|', 1 } }; for (std::size_t i = 0; i < segmentStrings.size(); ++i) { const auto& segmentString = segmentStrings[i]; - char sep = segmentString[0]; + char sep = segmentString[0]; path = path + Ufe::PathSegment(segmentString, sepToRtid.at(sep), sep); } return ufe::ufePathToPrim(path); } -void -wrapUtils() +void wrapUtils() { def("getPrimFromRawItem", getPrimFromRawItem); - - #ifdef UFE_V2_FEATURES_AVAILABLE - def("getNodeNameFromRawItem", getNodeNameFromRawItem); - #endif + +#ifdef UFE_V2_FEATURES_AVAILABLE + def("getNodeNameFromRawItem", getNodeNameFromRawItem); +#endif def("getNodeTypeFromRawItem", getNodeTypeFromRawItem); diff --git a/lib/mayaUsd/utils/blockSceneModificationContext.cpp b/lib/mayaUsd/utils/blockSceneModificationContext.cpp index b4c3b6ade9..ce23653373 100644 --- a/lib/mayaUsd/utils/blockSceneModificationContext.cpp +++ b/lib/mayaUsd/utils/blockSceneModificationContext.cpp @@ -15,20 +15,20 @@ // #include "blockSceneModificationContext.h" +#include +#include + #include #include #include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE UsdMayaBlockSceneModificationContext::UsdMayaBlockSceneModificationContext() { const MString fileModifiedCmd("file -query -modified"); - int cmdResult = 0; - MStatus status = MGlobal::executeCommand(fileModifiedCmd, cmdResult); + int cmdResult = 0; + MStatus status = MGlobal::executeCommand(fileModifiedCmd, cmdResult); CHECK_MSTATUS(status); _sceneWasModified = (cmdResult != 0); @@ -38,13 +38,10 @@ UsdMayaBlockSceneModificationContext::UsdMayaBlockSceneModificationContext() UsdMayaBlockSceneModificationContext::~UsdMayaBlockSceneModificationContext() { const MString setFileModifiedCmd( - TfStringPrintf( - "file -modified %d", - _sceneWasModified ? 1 : 0).c_str()); + TfStringPrintf("file -modified %d", _sceneWasModified ? 1 : 0).c_str()); MStatus status = MGlobal::executeCommand(setFileModifiedCmd); CHECK_MSTATUS(status); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/mayaUsd/utils/blockSceneModificationContext.h b/lib/mayaUsd/utils/blockSceneModificationContext.h index 08c219c6de..0535fe1cfc 100644 --- a/lib/mayaUsd/utils/blockSceneModificationContext.h +++ b/lib/mayaUsd/utils/blockSceneModificationContext.h @@ -16,37 +16,32 @@ #ifndef PXRUSDMAYA_BLOCK_SCENE_MODIFICATION_CONTEXT_H #define PXRUSDMAYA_BLOCK_SCENE_MODIFICATION_CONTEXT_H -#include - #include +#include + PXR_NAMESPACE_OPEN_SCOPE /// Utility class for wrapping a scope of Maya operations such that the /// modification status of the Maya scene is preserved. class UsdMayaBlockSceneModificationContext { - public: +public: + MAYAUSD_CORE_PUBLIC + UsdMayaBlockSceneModificationContext(); - MAYAUSD_CORE_PUBLIC - UsdMayaBlockSceneModificationContext(); + MAYAUSD_CORE_PUBLIC + virtual ~UsdMayaBlockSceneModificationContext(); - MAYAUSD_CORE_PUBLIC - virtual ~UsdMayaBlockSceneModificationContext(); +private: + /// Modification status of the scene when the context was created. + bool _sceneWasModified; - private: - - /// Modification status of the scene when the context was created. - bool _sceneWasModified; - - UsdMayaBlockSceneModificationContext( - const UsdMayaBlockSceneModificationContext&) = delete; - UsdMayaBlockSceneModificationContext& operator=( - const UsdMayaBlockSceneModificationContext&) = delete; + UsdMayaBlockSceneModificationContext(const UsdMayaBlockSceneModificationContext&) = delete; + UsdMayaBlockSceneModificationContext& operator=(const UsdMayaBlockSceneModificationContext&) + = delete; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/utils/colorSpace.cpp b/lib/mayaUsd/utils/colorSpace.cpp index 8ed847f3cc..40453fed1e 100644 --- a/lib/mayaUsd/utils/colorSpace.cpp +++ b/lib/mayaUsd/utils/colorSpace.cpp @@ -19,12 +19,13 @@ PXR_NAMESPACE_USING_DIRECTIVE -TF_DEFINE_ENV_SETTING(PIXMAYA_LINEAR_COLORS, false, - "If colors from maya should be treated as linear. " - "When false, colors are assumed to be gamma-corrected."); +TF_DEFINE_ENV_SETTING( + PIXMAYA_LINEAR_COLORS, + false, + "If colors from maya should be treated as linear. " + "When false, colors are assumed to be gamma-corrected."); -bool -UsdMayaColorSpace::IsColorManaged() +bool UsdMayaColorSpace::IsColorManaged() { // in theory this could vary per scene, but we think mixing that within any // given pipeline is likely confusing. Also, we want to avoid this function diff --git a/lib/mayaUsd/utils/colorSpace.h b/lib/mayaUsd/utils/colorSpace.h index aff84a00a0..746362d4a8 100644 --- a/lib/mayaUsd/utils/colorSpace.h +++ b/lib/mayaUsd/utils/colorSpace.h @@ -16,18 +16,17 @@ #ifndef PXRUSDMAYA_COLORSPACE_H #define PXRUSDMAYA_COLORSPACE_H -#include -#include - #include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE /// Helper functions for dealing with colors stored in Maya. /// /// Technically, this doesn't need to be tied to Usd. -namespace UsdMayaColorSpace -{ +namespace UsdMayaColorSpace { /// Returns true if we treat colors from Maya as linear colors. /// @@ -48,29 +47,23 @@ namespace UsdMayaColorSpace /// Viewport 2.0 (as proper color management is only supported there). /// MAYAUSD_CORE_PUBLIC -bool -IsColorManaged(); +bool IsColorManaged(); /// Converts a linear color into the appropriate Maya color space as determined by /// the above \c IsColorManaged. -template -T -ConvertLinearToMaya(const T& linearColor) +template T ConvertLinearToMaya(const T& linearColor) { return IsColorManaged() ? linearColor : GfConvertLinearToDisplay(linearColor); } /// Converts a Maya color space into a linear color. -template -T -ConvertMayaToLinear(const T& mayaColor) +template T ConvertMayaToLinear(const T& mayaColor) { return IsColorManaged() ? mayaColor : GfConvertDisplayToLinear(mayaColor); } -}; // UsdMayaColorSpace +}; // namespace UsdMayaColorSpace PXR_NAMESPACE_CLOSE_SCOPE #endif - diff --git a/lib/mayaUsd/utils/converter.cpp b/lib/mayaUsd/utils/converter.cpp index 3263aab4bc..2f0da517c2 100644 --- a/lib/mayaUsd/utils/converter.cpp +++ b/lib/mayaUsd/utils/converter.cpp @@ -62,1156 +62,1219 @@ Useful links when adding new types to the converter: */ // clang-format on -namespace MAYAUSD_NS_DEF +namespace MAYAUSD_NS_DEF { + +namespace { +//--------------------------------------------------------------------------------- +//! \brief Retrieve Maya's attribute numeric and unit data types +//! \return True on success, False otherwise. +bool getMayaAttributeNumericTypedAndUnitDataTypes( + const MPlug& attrPlug, + MFnNumericData::Type& numericDataType, + MFnData::Type& typedDataType, + MFnUnitAttribute::Type& unitDataType) { + numericDataType = MFnNumericData::kInvalid; + typedDataType = MFnData::kInvalid; + unitDataType = MFnUnitAttribute::kInvalid; - namespace { - //--------------------------------------------------------------------------------- - //! \brief Retrieve Maya's attribute numeric and unit data types - //! \return True on success, False otherwise. - bool getMayaAttributeNumericTypedAndUnitDataTypes( - const MPlug& attrPlug, - MFnNumericData::Type& numericDataType, - MFnData::Type& typedDataType, - MFnUnitAttribute::Type& unitDataType) - { - numericDataType = MFnNumericData::kInvalid; - typedDataType = MFnData::kInvalid; - unitDataType = MFnUnitAttribute::kInvalid; - - MObject attrObj(attrPlug.attribute()); - if (attrObj.isNull()) { - return false; - } + MObject attrObj(attrPlug.attribute()); + if (attrObj.isNull()) { + return false; + } - if (attrObj.hasFn(MFn::kNumericAttribute)) { - MFnNumericAttribute numericAttrFn(attrObj); - numericDataType = numericAttrFn.unitType(); - } else if (attrObj.hasFn(MFn::kTypedAttribute)) { - MFnTypedAttribute typedAttrFn(attrObj); - typedDataType = typedAttrFn.attrType(); - - if (typedDataType == MFnData::kNumeric) { - // Inspect the type of the data itself to find the actual type. - MObject plugObj = attrPlug.asMObject(); - if (plugObj.hasFn(MFn::kNumericData)) { - MFnNumericData numericDataFn(plugObj); - numericDataType = numericDataFn.numericType(); - } + if (attrObj.hasFn(MFn::kNumericAttribute)) { + MFnNumericAttribute numericAttrFn(attrObj); + numericDataType = numericAttrFn.unitType(); + } else if (attrObj.hasFn(MFn::kTypedAttribute)) { + MFnTypedAttribute typedAttrFn(attrObj); + typedDataType = typedAttrFn.attrType(); + + if (typedDataType == MFnData::kNumeric) { + // Inspect the type of the data itself to find the actual type. + MObject plugObj = attrPlug.asMObject(); + if (plugObj.hasFn(MFn::kNumericData)) { + MFnNumericData numericDataFn(plugObj); + numericDataType = numericDataFn.numericType(); } - } else if (attrObj.hasFn(MFn::kUnitAttribute)) { - MFnUnitAttribute unitAttrFn(attrObj); - unitDataType = unitAttrFn.unitType(); } - - return true; + } else if (attrObj.hasFn(MFn::kUnitAttribute)) { + MFnUnitAttribute unitAttrFn(attrObj); + unitDataType = unitAttrFn.unitType(); } - //--------------------------------------------------------------------------------- - //! \brief Type tranformation class to obtain at compile time array type for a given Maya - //! templated type. - template struct MakeMayaArray { - }; + return true; +} - //! \brief Type tranformation class to obtain at compile time array type for a given Maya - //! templated type. - template <> struct MakeMayaArray { - using Type = MMatrixArray; - }; +//--------------------------------------------------------------------------------- +//! \brief Type tranformation class to obtain at compile time array type for a given Maya +//! templated type. +template struct MakeMayaArray +{ +}; - //! \brief Type tranformation class to obtain at compile time array type for a given Maya - //! templated type. - template <> struct MakeMayaArray { - using Type = MStringArray; - }; +//! \brief Type tranformation class to obtain at compile time array type for a given Maya +//! templated type. +template <> struct MakeMayaArray +{ + using Type = MMatrixArray; +}; - //! \brief Helper type to save on typing. - template using MakeMayaArrayT = typename MakeMayaArray::Type; +//! \brief Type tranformation class to obtain at compile time array type for a given Maya +//! templated type. +template <> struct MakeMayaArray +{ + using Type = MStringArray; +}; - //--------------------------------------------------------------------------------- - //! \brief Type tranformation class to obtain at compile time array type for a given Usd - //! templated type. - template struct MakeUsdArray { - using Type = VtArray; - }; +//! \brief Helper type to save on typing. +template using MakeMayaArrayT = typename MakeMayaArray::Type; - //! \brief Helper type to save on typing. - template using MakeUsdArrayT = typename MakeUsdArray::Type; +//--------------------------------------------------------------------------------- +//! \brief Type tranformation class to obtain at compile time array type for a given Usd +//! templated type. +template struct MakeUsdArray +{ + using Type = VtArray; +}; - //--------------------------------------------------------------------------------- - //! \brief Type trait declaration for simple data types. Each specialized type will inherit - //! from std::true_type - //! to enable compile time code generation. - template struct MakeMayaSimpleData : public std::false_type { +//! \brief Helper type to save on typing. +template using MakeUsdArrayT = typename MakeUsdArray::Type; + +//--------------------------------------------------------------------------------- +//! \brief Type trait declaration for simple data types. Each specialized type will inherit +//! from std::true_type +//! to enable compile time code generation. +template struct MakeMayaSimpleData : public std::false_type +{ +}; + +//! \brief Type trait for Maya's bool type providing get and set methods for data handle and +//! plugs. +template <> struct MakeMayaSimpleData : public std::true_type +{ + using Type = bool; + enum + { + kNumericType = MFnNumericData::kBoolean }; - //! \brief Type trait for Maya's bool type providing get and set methods for data handle and - //! plugs. - template <> struct MakeMayaSimpleData : public std::true_type { - using Type = bool; - enum { kNumericType = MFnNumericData::kBoolean }; + static void get(const MDataHandle& handle, Type& value) { value = handle.asBool(); } - static void get(const MDataHandle& handle, Type& value) { value = handle.asBool(); } + static void set(MDataHandle& handle, const Type& value) { handle.setBool(value); } - static void set(MDataHandle& handle, const Type& value) { handle.setBool(value); } + static void set(const MPlug& plug, MDGModifier& dst, const Type& value) + { + dst.newPlugValueBool(plug, value); + } +}; - static void set(const MPlug& plug, MDGModifier& dst, const Type& value) - { - dst.newPlugValueBool(plug, value); - } +//! \brief Type trait for Maya's int type providing get and set methods for data handle and +//! plugs. +template <> struct MakeMayaSimpleData : public std::true_type +{ + using Type = int; + enum + { + kNumericType = MFnNumericData::kInt }; - //! \brief Type trait for Maya's int type providing get and set methods for data handle and - //! plugs. - template <> struct MakeMayaSimpleData : public std::true_type { - using Type = int; - enum { kNumericType = MFnNumericData::kInt }; + static void get(const MDataHandle& handle, Type& value) { value = handle.asInt(); } - static void get(const MDataHandle& handle, Type& value) { value = handle.asInt(); } + static void set(MDataHandle& handle, const Type& value) { handle.setInt(value); } - static void set(MDataHandle& handle, const Type& value) { handle.setInt(value); } + static void set(const MPlug& plug, MDGModifier& dst, const Type& value) + { + dst.newPlugValueInt(plug, value); + } +}; - static void set(const MPlug& plug, MDGModifier& dst, const Type& value) - { - dst.newPlugValueInt(plug, value); - } - }; +//--------------------------------------------------------------------------------- +//! \brief Type trait declaration for complex data types. Each specialized type will inherit +//! from std::true_type +//! to enable compile time code generation. +template struct MakeMayaFnData : public std::false_type +{ +}; - //--------------------------------------------------------------------------------- - //! \brief Type trait declaration for complex data types. Each specialized type will inherit - //! from std::true_type - //! to enable compile time code generation. - template struct MakeMayaFnData : public std::false_type { +//! \brief Type trait for Maya's MMatrixArray type providing get and set methods for data +//! handle and plugs. +template <> struct MakeMayaFnData : public std::true_type +{ + using Type = MMatrixArray; + using FnType = MFnMatrixArrayData; + enum + { + kDataType = MFnData::kMatrixArray + }; + enum + { + kApiType = MFn::kMatrixArrayData }; - //! \brief Type trait for Maya's MMatrixArray type providing get and set methods for data - //! handle and plugs. - template <> struct MakeMayaFnData : public std::true_type { - using Type = MMatrixArray; - using FnType = MFnMatrixArrayData; - enum { kDataType = MFnData::kMatrixArray }; - enum { kApiType = MFn::kMatrixArrayData }; + static MObject create(FnType& data) { return data.create(); } - static MObject create(FnType& data) { return data.create(); } + static void get(const FnType& data, Type& value) { data.copyTo(value); } - static void get(const FnType& data, Type& value) { data.copyTo(value); } + static void set(FnType& data, const Type& value) { data.set(value); } - static void set(FnType& data, const Type& value) { data.set(value); } + static void get(const MDataHandle& handle, Type& value) + { + MObject dataObj = const_cast(handle).data(); + FnType dataFn(dataObj); + get(dataFn, value); + } - static void get(const MDataHandle& handle, Type& value) - { - MObject dataObj = const_cast(handle).data(); - FnType dataFn(dataObj); - get(dataFn, value); - } + static void set(MDataHandle& handle, const Type& value) + { + FnType dataFn; + MObject dataObj = create(dataFn); + set(dataFn, value); - static void set(MDataHandle& handle, const Type& value) - { - FnType dataFn; - MObject dataObj = create(dataFn); - set(dataFn, value); + handle.setMObject(dataObj); + } +}; - handle.setMObject(dataObj); - } +//! \brief Type trait for Maya's MIntArray type providing get and set methods for data handle +//! and plugs. +template <> struct MakeMayaFnData : public std::true_type +{ + using Type = MIntArray; + using FnType = MFnIntArrayData; + enum + { + kDataType = MFnData::kIntArray + }; + enum + { + kApiType = MFn::kIntArrayData }; - //! \brief Type trait for Maya's MIntArray type providing get and set methods for data handle - //! and plugs. - template <> struct MakeMayaFnData : public std::true_type { - using Type = MIntArray; - using FnType = MFnIntArrayData; - enum { kDataType = MFnData::kIntArray }; - enum { kApiType = MFn::kIntArrayData }; + static MObject create(FnType& data) { return data.create(); } - static MObject create(FnType& data) { return data.create(); } + static void get(const FnType& data, Type& value) { data.copyTo(value); } - static void get(const FnType& data, Type& value) { data.copyTo(value); } + static void set(FnType& data, const Type& value) { data.set(value); } - static void set(FnType& data, const Type& value) { data.set(value); } + static void get(const MDataHandle& handle, Type& value) + { + MObject dataObj = const_cast(handle).data(); + FnType dataFn(dataObj); + get(dataFn, value); + } - static void get(const MDataHandle& handle, Type& value) - { - MObject dataObj = const_cast(handle).data(); - FnType dataFn(dataObj); - get(dataFn, value); - } + static void set(MDataHandle& handle, const Type& value) + { + FnType dataFn; + MObject dataObj = create(dataFn); + set(dataFn, value); - static void set(MDataHandle& handle, const Type& value) - { - FnType dataFn; - MObject dataObj = create(dataFn); - set(dataFn, value); + handle.setMObject(dataObj); + } +}; - handle.setMObject(dataObj); - } +//! \brief Type trait for Maya's MPointArray type providing get and set methods for data handle +//! and plugs. +template <> struct MakeMayaFnData : public std::true_type +{ + using Type = MPointArray; + using FnType = MFnPointArrayData; + enum + { + kDataType = MFnData::kPointArray + }; + enum + { + kApiType = MFn::kPointArrayData }; - //! \brief Type trait for Maya's MPointArray type providing get and set methods for data handle - //! and plugs. - template <> struct MakeMayaFnData : public std::true_type { - using Type = MPointArray; - using FnType = MFnPointArrayData; - enum { kDataType = MFnData::kPointArray }; - enum { kApiType = MFn::kPointArrayData }; + static MObject create(FnType& data) { return data.create(); } - static MObject create(FnType& data) { return data.create(); } + static void get(const FnType& data, Type& value) { data.copyTo(value); } - static void get(const FnType& data, Type& value) { data.copyTo(value); } + static void set(FnType& data, const Type& value) { data.set(value); } - static void set(FnType& data, const Type& value) { data.set(value); } + static void get(const MDataHandle& handle, Type& value) + { + MObject dataObj = const_cast(handle).data(); + FnType dataFn(dataObj); + get(dataFn, value); + } - static void get(const MDataHandle& handle, Type& value) - { - MObject dataObj = const_cast(handle).data(); - FnType dataFn(dataObj); - get(dataFn, value); - } + static void set(MDataHandle& handle, const Type& value) + { + FnType dataFn; + MObject dataObj = create(dataFn); + set(dataFn, value); - static void set(MDataHandle& handle, const Type& value) - { - FnType dataFn; - MObject dataObj = create(dataFn); - set(dataFn, value); + handle.setMObject(dataObj); + } +}; - handle.setMObject(dataObj); - } +//! \brief Type trait for Maya's MMatrix type providing get and set methods for data handle and +//! plugs. +template <> struct MakeMayaFnData : public std::true_type +{ + using Type = MMatrix; + using FnType = MFnMatrixData; + enum + { + kDataType = MFnData::kMatrix + }; + enum + { + kApiType = MFn::kMatrixData }; - //! \brief Type trait for Maya's MMatrix type providing get and set methods for data handle and - //! plugs. - template <> struct MakeMayaFnData : public std::true_type { - using Type = MMatrix; - using FnType = MFnMatrixData; - enum { kDataType = MFnData::kMatrix }; - enum { kApiType = MFn::kMatrixData }; + static MObject create(FnType& data) { return data.create(); } - static MObject create(FnType& data) { return data.create(); } + static void get(const FnType& data, Type& value) { value = data.matrix(); } - static void get(const FnType& data, Type& value) { value = data.matrix(); } + static void set(FnType& data, const Type& value) { data.set(value); } - static void set(FnType& data, const Type& value) { data.set(value); } + static void get(const MDataHandle& handle, Type& value) + { + MObject dataObj = const_cast(handle).data(); + FnType dataFn(dataObj); + get(dataFn, value); + } - static void get(const MDataHandle& handle, Type& value) - { - MObject dataObj = const_cast(handle).data(); - FnType dataFn(dataObj); - get(dataFn, value); - } + static void set(MDataHandle& handle, const Type& value) + { + FnType dataFn; + MObject dataObj = create(dataFn); + set(dataFn, value); - static void set(MDataHandle& handle, const Type& value) - { - FnType dataFn; - MObject dataObj = create(dataFn); - set(dataFn, value); + handle.setMObject(dataObj); + } +}; - handle.setMObject(dataObj); - } +//! \brief Type trait for Maya's float3 type providing get and set methods for data handle and +//! plugs. +template <> struct MakeMayaFnData : public std::true_type +{ + using Type = float3; + using FnType = MFnNumericData; + enum + { + kDataType = MFnData::kNumeric + }; + enum + { + kApiType = MFn::kNumericData }; - //! \brief Type trait for Maya's float3 type providing get and set methods for data handle and - //! plugs. - template <> struct MakeMayaFnData : public std::true_type { - using Type = float3; - using FnType = MFnNumericData; - enum { kDataType = MFnData::kNumeric }; - enum { kApiType = MFn::kNumericData }; + static MObject create(FnType& data) { return data.create(MFnNumericData::k3Float); } - static MObject create(FnType& data) { return data.create(MFnNumericData::k3Float); } + static void get(FnType& data, Type& value) { data.getData(value[0], value[1], value[2]); } - static void get(FnType& data, Type& value) { data.getData(value[0], value[1], value[2]); } + static void set(FnType& data, const Type& value) { data.setData(value[0], value[1], value[2]); } - static void set(FnType& data, const Type& value) - { - data.setData(value[0], value[1], value[2]); - } + static void get(const MDataHandle& handle, Type& value) + { + memcpy(&value, &handle.asFloat3(), sizeof(float3)); + } - static void get(const MDataHandle& handle, Type& value) - { - memcpy(&value, &handle.asFloat3(), sizeof(float3)); - } + static void set(MDataHandle& handle, const Type& value) + { + handle.set3Float(value[0], value[1], value[2]); + } +}; - static void set(MDataHandle& handle, const Type& value) - { - handle.set3Float(value[0], value[1], value[2]); - } +//! \brief Type trait for Maya's double3 type providing get and set methods for data handle and +//! plugs. +template <> struct MakeMayaFnData : public std::true_type +{ + using Type = double3; + using FnType = MFnNumericData; + enum + { + kDataType = MFnData::kNumeric + }; + enum + { + kApiType = MFn::kNumericData }; - //! \brief Type trait for Maya's double3 type providing get and set methods for data handle and - //! plugs. - template <> struct MakeMayaFnData : public std::true_type { - using Type = double3; - using FnType = MFnNumericData; - enum { kDataType = MFnData::kNumeric }; - enum { kApiType = MFn::kNumericData }; + static MObject create(FnType& data) { return data.create(MFnNumericData::k3Double); } - static MObject create(FnType& data) { return data.create(MFnNumericData::k3Double); } + static void get(FnType& data, Type& value) { data.getData(value[0], value[1], value[2]); } - static void get(FnType& data, Type& value) { data.getData(value[0], value[1], value[2]); } + static void set(FnType& data, const Type& value) { data.setData(value[0], value[1], value[2]); } - static void set(FnType& data, const Type& value) - { - data.setData(value[0], value[1], value[2]); - } + static void get(const MDataHandle& handle, Type& value) + { + memcpy(&value, &handle.asDouble3(), sizeof(double3)); + } - static void get(const MDataHandle& handle, Type& value) - { - memcpy(&value, &handle.asDouble3(), sizeof(double3)); - } + static void set(MDataHandle& handle, const Type& value) + { + handle.set3Double(value[0], value[1], value[2]); + } +}; - static void set(MDataHandle& handle, const Type& value) - { - handle.set3Double(value[0], value[1], value[2]); - } +//! \brief Type trait for Maya's MString type providing get and set methods for data handle and +//! plugs. +template <> struct MakeMayaFnData : public std::true_type +{ + using Type = MString; + using FnType = MFnStringData; + enum + { + kDataType = MFnData::kString + }; + enum + { + kApiType = MFn::kStringData }; - //! \brief Type trait for Maya's MString type providing get and set methods for data handle and - //! plugs. - template <> struct MakeMayaFnData : public std::true_type { - using Type = MString; - using FnType = MFnStringData; - enum { kDataType = MFnData::kString }; - enum { kApiType = MFn::kStringData }; + static MObject create(FnType& data) { return data.create(); } - static MObject create(FnType& data) { return data.create(); } + static void get(FnType& data, Type& value) { value = data.string(); } - static void get(FnType& data, Type& value) { value = data.string(); } + static void set(FnType& data, const Type& value) { data.set(value); } - static void set(FnType& data, const Type& value) { data.set(value); } + static void get(const MDataHandle& handle, Type& value) { value = handle.asString(); } - static void get(const MDataHandle& handle, Type& value) { value = handle.asString(); } + static void set(MDataHandle& handle, const Type& value) { handle.setString(value); } +}; - static void set(MDataHandle& handle, const Type& value) { handle.setString(value); } - }; +//--------------------------------------------------------------------------------- +//! \brief Helper classe to provide single a interface for data handles of simple and complex +//! types. +template struct MDataHandleUtils +{ +}; + +//! \brief Specialization of helper classe to provide a single interface for data handles of +//! simple types. +template +struct MDataHandleUtils< + MAYA_Type, + typename std::enable_if::value>::type> +{ + using SimpleTypeHelper = MakeMayaSimpleData; - //--------------------------------------------------------------------------------- - //! \brief Helper classe to provide single a interface for data handles of simple and complex - //! types. - template struct MDataHandleUtils { - }; + static bool valid(const MDataHandle& handle) + { + return (handle.isNumeric() && handle.numericType() == SimpleTypeHelper::kNumericType); + } - //! \brief Specialization of helper classe to provide a single interface for data handles of - //! simple types. - template - struct MDataHandleUtils< - MAYA_Type, - typename std::enable_if::value>::type> { - using SimpleTypeHelper = MakeMayaSimpleData; - - static bool valid(const MDataHandle& handle) - { - return (handle.isNumeric() && handle.numericType() == SimpleTypeHelper::kNumericType); - } + static void get(const MDataHandle& handle, MAYA_Type& value) + { + SimpleTypeHelper::get(handle, value); + } - static void get(const MDataHandle& handle, MAYA_Type& value) - { - SimpleTypeHelper::get(handle, value); - } + static void set(MDataHandle& handle, const MAYA_Type& value) + { + SimpleTypeHelper::set(handle, value); + } +}; - static void set(MDataHandle& handle, const MAYA_Type& value) - { - SimpleTypeHelper::set(handle, value); - } - }; +//! \brief Specialization of helper classe to provide a single interface for data handles of +//! complex types. +template +struct MDataHandleUtils::value>::type> +{ + using FnTypeHelper = MakeMayaFnData; - //! \brief Specialization of helper classe to provide a single interface for data handles of - //! complex types. - template - struct MDataHandleUtils< - MAYA_Type, - typename std::enable_if::value>::type> { - using FnTypeHelper = MakeMayaFnData; - - static bool valid(const MDataHandle& handle) - { - return (handle.type() == FnTypeHelper::kDataType); - } + static bool valid(const MDataHandle& handle) + { + return (handle.type() == FnTypeHelper::kDataType); + } - static void get(const MDataHandle& handle, MAYA_Type& value) - { - FnTypeHelper::get(handle, value); - } + static void get(const MDataHandle& handle, MAYA_Type& value) + { + FnTypeHelper::get(handle, value); + } - static void set(MDataHandle& handle, const MAYA_Type& value) - { - FnTypeHelper::set(handle, value); - } - }; + static void set(MDataHandle& handle, const MAYA_Type& value) + { + FnTypeHelper::set(handle, value); + } +}; - //--------------------------------------------------------------------------------- - //! \brief Helper classe to provide single a interface for plugs of simple and complex types. - template struct MPlugUtils { - }; +//--------------------------------------------------------------------------------- +//! \brief Helper classe to provide single a interface for plugs of simple and complex types. +template struct MPlugUtils +{ +}; - //! \brief Specialization of helper classe to provide a single interface for plugs of simple - //! types. - template - struct MPlugUtils< - MAYA_Type, - typename std::enable_if::value>::type> { - using SimpleTypeHelper = MakeMayaSimpleData; - - static bool valid(const MPlug& plug) - { - return Converter::hasNumericType(plug, SimpleTypeHelper::kNumericType); - } +//! \brief Specialization of helper classe to provide a single interface for plugs of simple +//! types. +template +struct MPlugUtils::value>::type> +{ + using SimpleTypeHelper = MakeMayaSimpleData; - static void get(const MPlug& plug, MAYA_Type& value) { plug.getValue(value); } + static bool valid(const MPlug& plug) + { + return Converter::hasNumericType(plug, SimpleTypeHelper::kNumericType); + } - static void set(MPlug& plug, const MAYA_Type& value) { plug.setValue(value); } - }; + static void get(const MPlug& plug, MAYA_Type& value) { plug.getValue(value); } - //! \brief Specialization of helper classe to provide a single interface for plugs of complex - //! types. - template - struct MPlugUtils::value>::type> { - using FnTypeHelper = MakeMayaFnData; + static void set(MPlug& plug, const MAYA_Type& value) { plug.setValue(value); } +}; - static bool valid(const MPlug& plug) - { - return Converter::hasAttrType(FnTypeHelper::kDataType); - } +//! \brief Specialization of helper classe to provide a single interface for plugs of complex +//! types. +template +struct MPlugUtils::value>::type> +{ + using FnTypeHelper = MakeMayaFnData; - static void get(const MPlug& plug, MAYA_Type& value) - { - typename FnTypeHelper::FnType dataFn(plug.asMObject()); - FnTypeHelper::get(dataFn, value); - } + static bool valid(const MPlug& plug) { return Converter::hasAttrType(FnTypeHelper::kDataType); } - static void set(MPlug& plug, const MAYA_Type& value) - { - typename FnTypeHelper::FnType dataFn; - MObject dataObj = FnTypeHelper::create(dataFn); - FnTypeHelper::set(dataFn, value); + static void get(const MPlug& plug, MAYA_Type& value) + { + typename FnTypeHelper::FnType dataFn(plug.asMObject()); + FnTypeHelper::get(dataFn, value); + } - plug.setMObject(dataObj); - } - }; + static void set(MPlug& plug, const MAYA_Type& value) + { + typename FnTypeHelper::FnType dataFn; + MObject dataObj = FnTypeHelper::create(dataFn); + FnTypeHelper::set(dataFn, value); - //--------------------------------------------------------------------------------- - //! \brief Helper classe to provide single a interface for modifying plugs of simple and - //! complex types with DG modifier. - template struct MDGModifierUtils { - }; + plug.setMObject(dataObj); + } +}; - //! \brief Specialization of helper classe to provide a single interface for modifying plugs of - //! simple types with DG modifier. - template - struct MDGModifierUtils< - MAYA_Type, - typename std::enable_if::value>::type> { - using SimpleTypeHelper = MakeMayaSimpleData; - - static void set(const MPlug& plug, MDGModifier& dst, const MAYA_Type& value) - { - SimpleTypeHelper::set(plug, dst, value); - } - }; +//--------------------------------------------------------------------------------- +//! \brief Helper classe to provide single a interface for modifying plugs of simple and +//! complex types with DG modifier. +template struct MDGModifierUtils +{ +}; + +//! \brief Specialization of helper classe to provide a single interface for modifying plugs of +//! simple types with DG modifier. +template +struct MDGModifierUtils< + MAYA_Type, + typename std::enable_if::value>::type> +{ + using SimpleTypeHelper = MakeMayaSimpleData; - //! \brief Specialization of helper classe to provide a single interface for modifying plugs of - //! complex types with DG modifier. - template - struct MDGModifierUtils< - MAYA_Type, - typename std::enable_if::value>::type> { - using FnTypeHelper = MakeMayaFnData; - - static void set(const MPlug& plug, MDGModifier& dst, const MAYA_Type& value) - { - typename FnTypeHelper::FnType dataFn; - MObject dataObj = FnTypeHelper::create(dataFn); - FnTypeHelper::set(dataFn, value); - - dst.newPlugValue(plug, dataObj); - } - }; + static void set(const MPlug& plug, MDGModifier& dst, const MAYA_Type& value) + { + SimpleTypeHelper::set(plug, dst, value); + } +}; - //! \brief Specialization for MString class which has a different way of setting new string - //! value on a plug. - template <> struct MDGModifierUtils { - static void set(const MPlug& plug, MDGModifier& dst, const MString& value) - { - dst.newPlugValueString(plug, value); - } - }; +//! \brief Specialization of helper classe to provide a single interface for modifying plugs of +//! complex types with DG modifier. +template +struct MDGModifierUtils::value>::type> +{ + using FnTypeHelper = MakeMayaFnData; - //--------------------------------------------------------------------------------- - //! \brief Switch used to conditionally enable or disable gamma correction support at compile - //! time for types - //! supporting it. - enum class NeedsGammaCorrection { kYes, kNo }; - - //! \brief Utility class for conversion between data handles and Usd. - template - struct MDataHandleConvert { - // MDataHandle <--> USD_Type - template - static typename std::enable_if::type - convert(const USD_Type& src, MDataHandle& dst, const ConverterArgs&) - { - MAYA_Type tmpDst; - TypedConverter::convert(src, tmpDst); - MDataHandleUtils::set(dst, tmpDst); - } - template - static typename std::enable_if::type - convert(const MDataHandle& src, USD_Type& dst, const ConverterArgs&) - { - MAYA_Type tmpSrc; - MDataHandleUtils::get(src, tmpSrc); - TypedConverter::convert(tmpSrc, dst); - } + static void set(const MPlug& plug, MDGModifier& dst, const MAYA_Type& value) + { + typename FnTypeHelper::FnType dataFn; + MObject dataObj = FnTypeHelper::create(dataFn); + FnTypeHelper::set(dataFn, value); - template - static typename std::enable_if::type - convert(const USD_Type& src, MDataHandle& dst, const ConverterArgs& args) - { - MAYA_Type tmpDst; - USD_Type tmpSrc - = args._doGammaCorrection ? UsdMayaColorSpace::ConvertLinearToMaya(src) : src; - TypedConverter::convert(tmpSrc, tmpDst); - MDataHandleUtils::set(dst, tmpDst); - } - template - static typename std::enable_if::type - convert(const MDataHandle& src, USD_Type& dst, const ConverterArgs& args) - { - MAYA_Type tmpSrc; - MDataHandleUtils::get(src, tmpSrc); - TypedConverter::convert(tmpSrc, dst); - - if (args._doGammaCorrection) - dst = UsdMayaColorSpace::ConvertMayaToLinear(dst); - } + dst.newPlugValue(plug, dataObj); + } +}; - // MDataHandle <--> UsdAttribute - static void convert(const MDataHandle& src, UsdAttribute& dst, const ConverterArgs& args) - { - USD_Type tmpDst; - convert(src, tmpDst, args); - dst.Set(tmpDst, args._timeCode); - } - static void convert(const UsdAttribute& src, MDataHandle& dst, const ConverterArgs& args) - { - USD_Type tmpSrc; - src.Get(&tmpSrc, args._timeCode); - convert(tmpSrc, dst, args); - } +//! \brief Specialization for MString class which has a different way of setting new string +//! value on a plug. +template <> struct MDGModifierUtils +{ + static void set(const MPlug& plug, MDGModifier& dst, const MString& value) + { + dst.newPlugValueString(plug, value); + } +}; - // MDataHandle <--> VtValue - static void convert(const MDataHandle& src, VtValue& dst, const ConverterArgs& args) - { - USD_Type tmpDst; - convert(src, tmpDst, args); - dst = tmpDst; - } - static void convert(const VtValue& src, MDataHandle& dst, const ConverterArgs& args) - { - const USD_Type& tmpSrc = src.Get(); - convert(tmpSrc, dst, args); - } - }; +//--------------------------------------------------------------------------------- +//! \brief Switch used to conditionally enable or disable gamma correction support at compile +//! time for types +//! supporting it. +enum class NeedsGammaCorrection +{ + kYes, + kNo +}; - //! \brief Utility class for conversion between plugs and Usd. - template - struct MPlugConvert { - // MPlug <--> USD_Type - template - static typename std::enable_if::type - convert(const USD_Type& src, MPlug& dst, const ConverterArgs&) - { - MAYA_Type tmpDst; - TypedConverter::convert(src, tmpDst); - MPlugUtils::set(dst, tmpDst); - } - template - static typename std::enable_if::type - convert(const MPlug& src, USD_Type& dst, const ConverterArgs&) - { - MAYA_Type tmpSrc; - MPlugUtils::get(src, tmpSrc); - TypedConverter::convert(tmpSrc, dst); - } - template - static typename std::enable_if::type - convert(const USD_Type& src, const MPlug& plug, MDGModifier& dst, const ConverterArgs&) - { - MAYA_Type tmpDst; - TypedConverter::convert(src, tmpDst); - MDGModifierUtils::set(plug, dst, tmpDst); - } +//! \brief Utility class for conversion between data handles and Usd. +template +struct MDataHandleConvert +{ + // MDataHandle <--> USD_Type + template + static typename std::enable_if::type + convert(const USD_Type& src, MDataHandle& dst, const ConverterArgs&) + { + MAYA_Type tmpDst; + TypedConverter::convert(src, tmpDst); + MDataHandleUtils::set(dst, tmpDst); + } + template + static typename std::enable_if::type + convert(const MDataHandle& src, USD_Type& dst, const ConverterArgs&) + { + MAYA_Type tmpSrc; + MDataHandleUtils::get(src, tmpSrc); + TypedConverter::convert(tmpSrc, dst); + } - template - static typename std::enable_if::type - convert(const USD_Type& src, MPlug& dst, const ConverterArgs& args) - { - MAYA_Type tmpDst; - USD_Type tmpSrc - = args._doGammaCorrection ? UsdMayaColorSpace::ConvertLinearToMaya(src) : src; - TypedConverter::convert(tmpSrc, tmpDst); + template + static typename std::enable_if::type + convert(const USD_Type& src, MDataHandle& dst, const ConverterArgs& args) + { + MAYA_Type tmpDst; + USD_Type tmpSrc + = args._doGammaCorrection ? UsdMayaColorSpace::ConvertLinearToMaya(src) : src; + TypedConverter::convert(tmpSrc, tmpDst); + MDataHandleUtils::set(dst, tmpDst); + } + template + static typename std::enable_if::type + convert(const MDataHandle& src, USD_Type& dst, const ConverterArgs& args) + { + MAYA_Type tmpSrc; + MDataHandleUtils::get(src, tmpSrc); + TypedConverter::convert(tmpSrc, dst); - MPlugUtils::set(dst, tmpDst); - } - template - static typename std::enable_if::type - convert(const MPlug& src, USD_Type& dst, const ConverterArgs& args) - { - MAYA_Type tmpSrc; - MPlugUtils::get(src, tmpSrc); - TypedConverter::convert(tmpSrc, dst); - - if (args._doGammaCorrection) - dst = UsdMayaColorSpace::ConvertMayaToLinear(dst); - } - template - static typename std::enable_if::type - convert(const USD_Type& src, const MPlug& plug, MDGModifier& dst, const ConverterArgs& args) - { - MAYA_Type tmpDst; - USD_Type tmpSrc - = args._doGammaCorrection ? UsdMayaColorSpace::ConvertLinearToMaya(src) : src; - TypedConverter::convert(tmpSrc, tmpDst); - - MDGModifierUtils::set(plug, dst, tmpDst); - } + if (args._doGammaCorrection) + dst = UsdMayaColorSpace::ConvertMayaToLinear(dst); + } - // MPlug <--> UsdAttribute - static void convert(const MPlug& src, UsdAttribute& dst, const ConverterArgs& args) - { - USD_Type tmpDst; - convert(src, tmpDst, args); - dst.Set(tmpDst, args._timeCode); - } - static void convert(const UsdAttribute& src, MPlug& dst, const ConverterArgs& args) - { - USD_Type tmpSrc; - src.Get(&tmpSrc, args._timeCode); - convert(tmpSrc, dst, args); - } - static void - convert(const UsdAttribute& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) - { - USD_Type tmpSrc; - src.Get(&tmpSrc, args._timeCode); - convert(tmpSrc, plug, dst, args); - } + // MDataHandle <--> UsdAttribute + static void convert(const MDataHandle& src, UsdAttribute& dst, const ConverterArgs& args) + { + USD_Type tmpDst; + convert(src, tmpDst, args); + dst.Set(tmpDst, args._timeCode); + } + static void convert(const UsdAttribute& src, MDataHandle& dst, const ConverterArgs& args) + { + USD_Type tmpSrc; + src.Get(&tmpSrc, args._timeCode); + convert(tmpSrc, dst, args); + } - // MPlug <--> VtValue - static void convert(const MPlug& src, VtValue& dst, const ConverterArgs& args) - { - USD_Type tmpDst; - convert(src, tmpDst, args); - dst = tmpDst; - } - static void convert(const VtValue& src, MPlug& dst, const ConverterArgs& args) - { - const USD_Type& tmpSrc = src.Get(); - convert(tmpSrc, dst, args); - } - static void - convert(const VtValue& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) - { - const USD_Type& tmpSrc = src.Get(); - convert(tmpSrc, plug, dst, args); - } - }; + // MDataHandle <--> VtValue + static void convert(const MDataHandle& src, VtValue& dst, const ConverterArgs& args) + { + USD_Type tmpDst; + convert(src, tmpDst, args); + dst = tmpDst; + } + static void convert(const VtValue& src, MDataHandle& dst, const ConverterArgs& args) + { + const USD_Type& tmpSrc = src.Get(); + convert(tmpSrc, dst, args); + } +}; + +//! \brief Utility class for conversion between plugs and Usd. +template struct MPlugConvert +{ + // MPlug <--> USD_Type + template + static typename std::enable_if::type + convert(const USD_Type& src, MPlug& dst, const ConverterArgs&) + { + MAYA_Type tmpDst; + TypedConverter::convert(src, tmpDst); + MPlugUtils::set(dst, tmpDst); + } + template + static typename std::enable_if::type + convert(const MPlug& src, USD_Type& dst, const ConverterArgs&) + { + MAYA_Type tmpSrc; + MPlugUtils::get(src, tmpSrc); + TypedConverter::convert(tmpSrc, dst); + } + template + static typename std::enable_if::type + convert(const USD_Type& src, const MPlug& plug, MDGModifier& dst, const ConverterArgs&) + { + MAYA_Type tmpDst; + TypedConverter::convert(src, tmpDst); + MDGModifierUtils::set(plug, dst, tmpDst); + } + + template + static typename std::enable_if::type + convert(const USD_Type& src, MPlug& dst, const ConverterArgs& args) + { + MAYA_Type tmpDst; + USD_Type tmpSrc + = args._doGammaCorrection ? UsdMayaColorSpace::ConvertLinearToMaya(src) : src; + TypedConverter::convert(tmpSrc, tmpDst); + + MPlugUtils::set(dst, tmpDst); + } + template + static typename std::enable_if::type + convert(const MPlug& src, USD_Type& dst, const ConverterArgs& args) + { + MAYA_Type tmpSrc; + MPlugUtils::get(src, tmpSrc); + TypedConverter::convert(tmpSrc, dst); + + if (args._doGammaCorrection) + dst = UsdMayaColorSpace::ConvertMayaToLinear(dst); + } + template + static typename std::enable_if::type + convert(const USD_Type& src, const MPlug& plug, MDGModifier& dst, const ConverterArgs& args) + { + MAYA_Type tmpDst; + USD_Type tmpSrc + = args._doGammaCorrection ? UsdMayaColorSpace::ConvertLinearToMaya(src) : src; + TypedConverter::convert(tmpSrc, tmpDst); + + MDGModifierUtils::set(plug, dst, tmpDst); + } + + // MPlug <--> UsdAttribute + static void convert(const MPlug& src, UsdAttribute& dst, const ConverterArgs& args) + { + USD_Type tmpDst; + convert(src, tmpDst, args); + dst.Set(tmpDst, args._timeCode); + } + static void convert(const UsdAttribute& src, MPlug& dst, const ConverterArgs& args) + { + USD_Type tmpSrc; + src.Get(&tmpSrc, args._timeCode); + convert(tmpSrc, dst, args); + } + static void + convert(const UsdAttribute& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) + { + USD_Type tmpSrc; + src.Get(&tmpSrc, args._timeCode); + convert(tmpSrc, plug, dst, args); + } + + // MPlug <--> VtValue + static void convert(const MPlug& src, VtValue& dst, const ConverterArgs& args) + { + USD_Type tmpDst; + convert(src, tmpDst, args); + dst = tmpDst; + } + static void convert(const VtValue& src, MPlug& dst, const ConverterArgs& args) + { + const USD_Type& tmpSrc = src.Get(); + convert(tmpSrc, dst, args); + } + static void + convert(const VtValue& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) + { + const USD_Type& tmpSrc = src.Get(); + convert(tmpSrc, plug, dst, args); + } +}; // Missing attribute method for MDataHandle prior to Maya 2020. For now disable all // array converters to avoid complicating interface and error handling. If needed, // we should be able to back-port the change to an update. #if MAYA_API_VERSION >= 20200000 - //! \brief Utility class for conversion between array data handles and Usd. - template - struct MArrayDataHandleConvert { - using MAYA_TypeArray = MakeMayaArrayT; - using USD_TypeArray = MakeUsdArrayT; - using ElementConverter = MDataHandleConvert; - - // MDataHandle <--> UsdAttribute - static void convert(const MDataHandle& src, UsdAttribute& dst, const ConverterArgs& args) - { - MArrayDataHandle srcArray(src); - const unsigned int srcSize = srcArray.elementCount(); - - USD_TypeArray tmpDst; - tmpDst.resize(srcSize); - - srcArray.jumpToElement(0); - for (unsigned int i = 0; i < srcSize; i++) { - MDataHandle srcHandle = srcArray.inputValue(); - ElementConverter::convert(srcHandle, tmpDst[i], args); - - srcArray.next(); - } +//! \brief Utility class for conversion between array data handles and Usd. +template +struct MArrayDataHandleConvert +{ + using MAYA_TypeArray = MakeMayaArrayT; + using USD_TypeArray = MakeUsdArrayT; + using ElementConverter = MDataHandleConvert; - dst.Set(tmpDst, args._timeCode); + // MDataHandle <--> UsdAttribute + static void convert(const MDataHandle& src, UsdAttribute& dst, const ConverterArgs& args) + { + MArrayDataHandle srcArray(src); + const unsigned int srcSize = srcArray.elementCount(); + + USD_TypeArray tmpDst; + tmpDst.resize(srcSize); + + srcArray.jumpToElement(0); + for (unsigned int i = 0; i < srcSize; i++) { + MDataHandle srcHandle = srcArray.inputValue(); + ElementConverter::convert(srcHandle, tmpDst[i], args); + + srcArray.next(); } - static void convert(const UsdAttribute& src, MDataHandle& dst, const ConverterArgs& args) - { - USD_TypeArray tmpSrc; - src.Get(&tmpSrc, args._timeCode); - const size_t srcSize = tmpSrc.size(); - MArrayDataHandle dstArray(dst); + dst.Set(tmpDst, args._timeCode); + } + static void convert(const UsdAttribute& src, MDataHandle& dst, const ConverterArgs& args) + { + USD_TypeArray tmpSrc; + src.Get(&tmpSrc, args._timeCode); + const size_t srcSize = tmpSrc.size(); - MDataBlock dstDataBlock = dst.datablock(); - MObject dstAttribute = dst.attribute(); - MArrayDataBuilder dstArrayBuilder(&dstDataBlock, dstAttribute, srcSize); + MArrayDataHandle dstArray(dst); - for (size_t i = 0; i < srcSize; i++) { - MDataHandle dstElement = dstArrayBuilder.addElement(i); - ElementConverter::convert(tmpSrc[i], dstElement, args); - } + MDataBlock dstDataBlock = dst.datablock(); + MObject dstAttribute = dst.attribute(); + MArrayDataBuilder dstArrayBuilder(&dstDataBlock, dstAttribute, srcSize); - dstArray.set(dstArrayBuilder); + for (size_t i = 0; i < srcSize; i++) { + MDataHandle dstElement = dstArrayBuilder.addElement(i); + ElementConverter::convert(tmpSrc[i], dstElement, args); } - // MDataHandle <--> VtValue - static void convert(const MDataHandle& src, VtValue& dst, const ConverterArgs& args) - { - MArrayDataHandle srcArray(src); - const unsigned int srcSize = srcArray.elementCount(); + dstArray.set(dstArrayBuilder); + } - USD_TypeArray tmpDst; - tmpDst.resize(srcSize); + // MDataHandle <--> VtValue + static void convert(const MDataHandle& src, VtValue& dst, const ConverterArgs& args) + { + MArrayDataHandle srcArray(src); + const unsigned int srcSize = srcArray.elementCount(); - srcArray.jumpToElement(0); - for (unsigned int i = 0; i < srcSize; i++) { - MDataHandle srcHandle = srcArray.inputValue(); - ElementConverter::convert(srcHandle, tmpDst[i], args); + USD_TypeArray tmpDst; + tmpDst.resize(srcSize); - srcArray.next(); - } + srcArray.jumpToElement(0); + for (unsigned int i = 0; i < srcSize; i++) { + MDataHandle srcHandle = srcArray.inputValue(); + ElementConverter::convert(srcHandle, tmpDst[i], args); - dst = tmpDst; + srcArray.next(); } - static void convert(const VtValue& src, MDataHandle& dst, const ConverterArgs& args) - { - const USD_TypeArray& tmpSrc = src.Get(); - const size_t srcSize = tmpSrc.size(); - MArrayDataHandle dstArray(dst); + dst = tmpDst; + } + static void convert(const VtValue& src, MDataHandle& dst, const ConverterArgs& args) + { + const USD_TypeArray& tmpSrc = src.Get(); + const size_t srcSize = tmpSrc.size(); - MDataBlock dstDataBlock = dst.datablock(); - MObject dstAttribute = dst.attribute(); - MArrayDataBuilder dstArrayBuilder(&dstDataBlock, dstAttribute, srcSize); + MArrayDataHandle dstArray(dst); - for (size_t i = 0; i < srcSize; i++) { - MDataHandle dstElement = dstArrayBuilder.addElement(i); - ElementConverter::convert(tmpSrc[i], dstElement, args); - } + MDataBlock dstDataBlock = dst.datablock(); + MObject dstAttribute = dst.attribute(); + MArrayDataBuilder dstArrayBuilder(&dstDataBlock, dstAttribute, srcSize); - dstArray.set(dstArrayBuilder); + for (size_t i = 0; i < srcSize; i++) { + MDataHandle dstElement = dstArrayBuilder.addElement(i); + ElementConverter::convert(tmpSrc[i], dstElement, args); } - }; - //! \brief Utility class for conversion between array attribute plugs and Usd. - template - struct MArrayPlugConvert { - using MAYA_TypeArray = MakeMayaArrayT; - using USD_TypeArray = MakeUsdArrayT; - using ElementConverter = MPlugConvert; + dstArray.set(dstArrayBuilder); + } +}; - // MPlug <--> UsdAttribute - static void convert(const MPlug& src, UsdAttribute& dst, const ConverterArgs& args) - { - const unsigned int srcSize = src.numElements(); +//! \brief Utility class for conversion between array attribute plugs and Usd. +template +struct MArrayPlugConvert +{ + using MAYA_TypeArray = MakeMayaArrayT; + using USD_TypeArray = MakeUsdArrayT; + using ElementConverter = MPlugConvert; - USD_TypeArray tmpDst; - tmpDst.resize(srcSize); + // MPlug <--> UsdAttribute + static void convert(const MPlug& src, UsdAttribute& dst, const ConverterArgs& args) + { + const unsigned int srcSize = src.numElements(); - for (unsigned int i = 0; i < srcSize; i++) { - MPlug srcElement = src.elementByPhysicalIndex(i); - ElementConverter::convert(srcElement, tmpDst[i], args); - } + USD_TypeArray tmpDst; + tmpDst.resize(srcSize); - dst.Set(tmpDst, args._timeCode); - } - static void convert(const UsdAttribute& src, MPlug& dst, const ConverterArgs& args) - { - USD_TypeArray tmpSrc; - src.Get(&tmpSrc, args._timeCode); - - const size_t srcSize = tmpSrc.size(); - dst.setNumElements(srcSize); - for (size_t i = 0; i < srcSize; i++) { - MPlug srcElement = dst.elementByLogicalIndex(i); - ElementConverter::convert(tmpSrc[i], srcElement, args); - } + for (unsigned int i = 0; i < srcSize; i++) { + MPlug srcElement = src.elementByPhysicalIndex(i); + ElementConverter::convert(srcElement, tmpDst[i], args); } - static void - convert(const UsdAttribute& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) - { - USD_TypeArray tmpSrc; - src.Get(&tmpSrc, args._timeCode); - - const size_t srcSize = tmpSrc.size(); - plug.setNumElements(srcSize); - for (size_t i = 0; i < srcSize; i++) { - MPlug srcElement = plug.elementByLogicalIndex(i); - ElementConverter::convert(tmpSrc[i], srcElement, dst, args); - } + + dst.Set(tmpDst, args._timeCode); + } + static void convert(const UsdAttribute& src, MPlug& dst, const ConverterArgs& args) + { + USD_TypeArray tmpSrc; + src.Get(&tmpSrc, args._timeCode); + + const size_t srcSize = tmpSrc.size(); + dst.setNumElements(srcSize); + for (size_t i = 0; i < srcSize; i++) { + MPlug srcElement = dst.elementByLogicalIndex(i); + ElementConverter::convert(tmpSrc[i], srcElement, args); } + } + static void + convert(const UsdAttribute& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) + { + USD_TypeArray tmpSrc; + src.Get(&tmpSrc, args._timeCode); - // MPlug <--> VtValue - static void convert(const MPlug& src, VtValue& dst, const ConverterArgs& args) - { - const unsigned int srcSize = src.numElements(); + const size_t srcSize = tmpSrc.size(); + plug.setNumElements(srcSize); + for (size_t i = 0; i < srcSize; i++) { + MPlug srcElement = plug.elementByLogicalIndex(i); + ElementConverter::convert(tmpSrc[i], srcElement, dst, args); + } + } - USD_TypeArray tmpDst; - tmpDst.resize(srcSize); + // MPlug <--> VtValue + static void convert(const MPlug& src, VtValue& dst, const ConverterArgs& args) + { + const unsigned int srcSize = src.numElements(); - for (unsigned int i = 0; i < srcSize; i++) { - MPlug srcElement = src.elementByPhysicalIndex(i); - ElementConverter::convert(srcElement, tmpDst[i], args); - } + USD_TypeArray tmpDst; + tmpDst.resize(srcSize); - dst = tmpDst; + for (unsigned int i = 0; i < srcSize; i++) { + MPlug srcElement = src.elementByPhysicalIndex(i); + ElementConverter::convert(srcElement, tmpDst[i], args); } - static void convert(const VtValue& src, MPlug& dst, const ConverterArgs& args) - { - const USD_TypeArray& tmpSrc = src.Get(); - - const size_t srcSize = tmpSrc.size(); - dst.setNumElements(srcSize); - for (size_t i = 0; i < srcSize; i++) { - MPlug srcElement = dst.elementByLogicalIndex(i); - ElementConverter::convert(tmpSrc[i], srcElement, args); - } + + dst = tmpDst; + } + static void convert(const VtValue& src, MPlug& dst, const ConverterArgs& args) + { + const USD_TypeArray& tmpSrc = src.Get(); + + const size_t srcSize = tmpSrc.size(); + dst.setNumElements(srcSize); + for (size_t i = 0; i < srcSize; i++) { + MPlug srcElement = dst.elementByLogicalIndex(i); + ElementConverter::convert(tmpSrc[i], srcElement, args); } - static void - convert(const VtValue& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) - { - const USD_TypeArray& tmpSrc = src.Get(); - - const size_t srcSize = tmpSrc.size(); - plug.setNumElements(srcSize); - for (size_t i = 0; i < srcSize; i++) { - MPlug srcElement = plug.elementByLogicalIndex(i); - ElementConverter::convert(tmpSrc[i], srcElement, dst, args); - } + } + static void + convert(const VtValue& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) + { + const USD_TypeArray& tmpSrc = src.Get(); + + const size_t srcSize = tmpSrc.size(); + plug.setNumElements(srcSize); + for (size_t i = 0; i < srcSize; i++) { + MPlug srcElement = plug.elementByLogicalIndex(i); + ElementConverter::convert(tmpSrc[i], srcElement, dst, args); } - }; + } +}; #endif - //--------------------------------------------------------------------------------- - //! \brief Storage for generated instances of converters. - using ConvertStorage - = std::unordered_map; - } // namespace - - //! \brief Utility class responsible for generating all supported converters. This list - //! excludes all array attribute types. - struct Converter::GenerateConverters { - template < - class MAYA_Type, - class USD_Type, - NeedsGammaCorrection ColorCorrection = NeedsGammaCorrection::kNo> - static void createConverter(ConvertStorage& converters, const SdfValueTypeName& typeName) - { - converters.emplace( +//--------------------------------------------------------------------------------- +//! \brief Storage for generated instances of converters. +using ConvertStorage = std::unordered_map; +} // namespace + +//! \brief Utility class responsible for generating all supported converters. This list +//! excludes all array attribute types. +struct Converter::GenerateConverters +{ + template < + class MAYA_Type, + class USD_Type, + NeedsGammaCorrection ColorCorrection = NeedsGammaCorrection::kNo> + static void createConverter(ConvertStorage& converters, const SdfValueTypeName& typeName) + { + converters.emplace( + typeName, + Converter( typeName, - Converter( - typeName, - &MPlugConvert::convert // MPlugToUsdAttrFn - , - &MPlugConvert::convert // UsdAttrToMPlugFn - , - &MPlugConvert:: - convert // UsdAttrToMDGModifierFn - , - &MPlugConvert::convert // MPlugToVtValueFn - , - &MPlugConvert::convert // VtValueToMPlugFn - , - &MPlugConvert:: - convert // VtValueToMDGModifierFn - , - &MDataHandleConvert:: - convert // MDataHandleToUsdAttrFn - , - &MDataHandleConvert:: - convert // UsdAttrToMDataHandleFn - , - &MDataHandleConvert:: - convert // MDataHandleToVtValueFn - , - &MDataHandleConvert:: - convert // VtValueToMDataHandleFn - )); - } + &MPlugConvert::convert // MPlugToUsdAttrFn + , + &MPlugConvert::convert // UsdAttrToMPlugFn + , + &MPlugConvert:: + convert // UsdAttrToMDGModifierFn + , + &MPlugConvert::convert // MPlugToVtValueFn + , + &MPlugConvert::convert // VtValueToMPlugFn + , + &MPlugConvert:: + convert // VtValueToMDGModifierFn + , + &MDataHandleConvert:: + convert // MDataHandleToUsdAttrFn + , + &MDataHandleConvert:: + convert // UsdAttrToMDataHandleFn + , + &MDataHandleConvert:: + convert // MDataHandleToVtValueFn + , + &MDataHandleConvert:: + convert // VtValueToMDataHandleFn + )); + } - static ConvertStorage generate() - { - ConvertStorage converters; + static ConvertStorage generate() + { + ConvertStorage converters; - createConverter(converters, SdfValueTypeNames->Bool); - createConverter(converters, SdfValueTypeNames->Int); + createConverter(converters, SdfValueTypeNames->Bool); + createConverter(converters, SdfValueTypeNames->Int); - createConverter(converters, SdfValueTypeNames->String); - createConverter(converters, SdfValueTypeNames->Float3); - createConverter(converters, SdfValueTypeNames->Double3); - createConverter(converters, SdfValueTypeNames->Matrix4d); + createConverter(converters, SdfValueTypeNames->String); + createConverter(converters, SdfValueTypeNames->Float3); + createConverter(converters, SdfValueTypeNames->Double3); + createConverter(converters, SdfValueTypeNames->Matrix4d); - createConverter( - converters, SdfValueTypeNames->Color3f); - createConverter( - converters, SdfValueTypeNames->Color3d); + createConverter( + converters, SdfValueTypeNames->Color3f); + createConverter( + converters, SdfValueTypeNames->Color3d); - createConverter>(converters, SdfValueTypeNames->IntArray); - createConverter>( - converters, SdfValueTypeNames->Point3fArray); - createConverter>( - converters, SdfValueTypeNames->Matrix4dArray); + createConverter>(converters, SdfValueTypeNames->IntArray); + createConverter>(converters, SdfValueTypeNames->Point3fArray); + createConverter>( + converters, SdfValueTypeNames->Matrix4dArray); - return converters; - } - }; + return converters; + } +}; - //! \brief Utility class responsible for generating all supported array attribute converters. - struct Converter::GenerateArrayPlugConverters { +//! \brief Utility class responsible for generating all supported array attribute converters. +struct Converter::GenerateArrayPlugConverters +{ #if MAYA_API_VERSION >= 20200000 - template < - class MAYA_Type, - class USD_Type, - NeedsGammaCorrection ColorCorrection = NeedsGammaCorrection::kNo> - static void - createArrayConverter(ConvertStorage& converters, const SdfValueTypeName& typeName) - { - converters.emplace( + template < + class MAYA_Type, + class USD_Type, + NeedsGammaCorrection ColorCorrection = NeedsGammaCorrection::kNo> + static void createArrayConverter(ConvertStorage& converters, const SdfValueTypeName& typeName) + { + converters.emplace( + typeName, + Converter( typeName, - Converter( - typeName, - &MArrayPlugConvert:: - convert // MPlugToUsdAttrFn - , - &MArrayPlugConvert:: - convert // UsdAttrToMPlugFn - , - &MArrayPlugConvert:: - convert // UsdAttrToMDGModifierFn - , - &MArrayPlugConvert:: - convert // MPlugToVtValueFn - , - &MArrayPlugConvert:: - convert // VtValueToMPlugFn - , - &MArrayPlugConvert:: - convert // VtValueToMDGModifierFn - , - &MArrayDataHandleConvert:: - convert // MDataHandleToUsdAttrFn - , - &MArrayDataHandleConvert:: - convert // UsdAttrToMDataHandleFn - , - &MArrayDataHandleConvert:: - convert // MDataHandleToVtValueFn - , - &MArrayDataHandleConvert:: - convert // VtValueToMDataHandleFn - )); - } + &MArrayPlugConvert:: + convert // MPlugToUsdAttrFn + , + &MArrayPlugConvert:: + convert // UsdAttrToMPlugFn + , + &MArrayPlugConvert:: + convert // UsdAttrToMDGModifierFn + , + &MArrayPlugConvert:: + convert // MPlugToVtValueFn + , + &MArrayPlugConvert:: + convert // VtValueToMPlugFn + , + &MArrayPlugConvert:: + convert // VtValueToMDGModifierFn + , + &MArrayDataHandleConvert:: + convert // MDataHandleToUsdAttrFn + , + &MArrayDataHandleConvert:: + convert // UsdAttrToMDataHandleFn + , + &MArrayDataHandleConvert:: + convert // MDataHandleToVtValueFn + , + &MArrayDataHandleConvert:: + convert // VtValueToMDataHandleFn + )); + } - static ConvertStorage generate() - { - ConvertStorage converters; - createArrayConverter(converters, SdfValueTypeNames->Matrix4dArray); - return converters; - } + static ConvertStorage generate() + { + ConvertStorage converters; + createArrayConverter(converters, SdfValueTypeNames->Matrix4dArray); + return converters; + } #else - static ConvertStorage generate() - { - ConvertStorage converters; - return converters; - } + static ConvertStorage generate() + { + ConvertStorage converters; + return converters; + } #endif - }; +}; - namespace { - //! \brief Global storage for non-array attribute converters - ConvertStorage _converters = Converter::GenerateConverters::generate(); - //! \brief Global storage for array attribute converters - ConvertStorage _convertersForArrayPlug = Converter::GenerateArrayPlugConverters::generate(); - } // namespace +namespace { +//! \brief Global storage for non-array attribute converters +ConvertStorage _converters = Converter::GenerateConverters::generate(); +//! \brief Global storage for array attribute converters +ConvertStorage _convertersForArrayPlug = Converter::GenerateArrayPlugConverters::generate(); +} // namespace - const Converter* Converter::find(const SdfValueTypeName& typeName, bool isArrayPlug) - { - auto& container = isArrayPlug ? _convertersForArrayPlug : _converters; +const Converter* Converter::find(const SdfValueTypeName& typeName, bool isArrayPlug) +{ + auto& container = isArrayPlug ? _convertersForArrayPlug : _converters; - auto findIt = container.find(typeName); - if (findIt != container.end()) - return &findIt->second; - else - return nullptr; - } + auto findIt = container.find(typeName); + if (findIt != container.end()) + return &findIt->second; + else + return nullptr; +} - const Converter* Converter::find(const MPlug& plug, const UsdAttribute& attr) - { - auto valueTypeName = getUsdTypeName(plug, false); +const Converter* Converter::find(const MPlug& plug, const UsdAttribute& attr) +{ + auto valueTypeName = getUsdTypeName(plug, false); - if (attr.GetTypeName() != valueTypeName) - return nullptr; + if (attr.GetTypeName() != valueTypeName) + return nullptr; - return find(valueTypeName, plug.isArray()); - } + return find(valueTypeName, plug.isArray()); +} - SdfValueTypeName Converter::getUsdTypeName( - const MPlug& attrPlug, const bool translateMayaDoubleToUsdSinglePrecision) - { - // The various types of Maya attributes that can be created are spread - // across a handful of MFn function sets. Some are a straightforward - // translation such as MFnEnumAttributes or MFnMatrixAttributes, but others - // are interesting mixes of function sets. For example, an attribute created - // with addAttr and 'double' as the type results in an MFnNumericAttribute - // while 'double2' as the type results in an MFnTypedAttribute that has - // MFnData::Type kNumeric. +SdfValueTypeName +Converter::getUsdTypeName(const MPlug& attrPlug, const bool translateMayaDoubleToUsdSinglePrecision) +{ + // The various types of Maya attributes that can be created are spread + // across a handful of MFn function sets. Some are a straightforward + // translation such as MFnEnumAttributes or MFnMatrixAttributes, but others + // are interesting mixes of function sets. For example, an attribute created + // with addAttr and 'double' as the type results in an MFnNumericAttribute + // while 'double2' as the type results in an MFnTypedAttribute that has + // MFnData::Type kNumeric. + + MObject attrObj(attrPlug.attribute()); + if (attrObj.isNull()) { + return SdfValueTypeName(); + } - MObject attrObj(attrPlug.attribute()); - if (attrObj.isNull()) { - return SdfValueTypeName(); - } + if (attrObj.hasFn(MFn::kEnumAttribute)) { + return SdfValueTypeNames->Int; + } - if (attrObj.hasFn(MFn::kEnumAttribute)) { - return SdfValueTypeNames->Int; - } + MFnNumericData::Type numericDataType; + MFnData::Type typedDataType; + MFnUnitAttribute::Type unitDataType; - MFnNumericData::Type numericDataType; - MFnData::Type typedDataType; - MFnUnitAttribute::Type unitDataType; + getMayaAttributeNumericTypedAndUnitDataTypes( + attrPlug, numericDataType, typedDataType, unitDataType); - getMayaAttributeNumericTypedAndUnitDataTypes( - attrPlug, numericDataType, typedDataType, unitDataType); + if (attrObj.hasFn(MFn::kMatrixAttribute)) { + // Using type "fltMatrix" with addAttr results in an MFnMatrixAttribute + // while using type "matrix" results in an MFnTypedAttribute with type + // kMatrix, but the data is extracted the same way for both. + typedDataType = MFnData::kMatrix; + } - if (attrObj.hasFn(MFn::kMatrixAttribute)) { - // Using type "fltMatrix" with addAttr results in an MFnMatrixAttribute - // while using type "matrix" results in an MFnTypedAttribute with type - // kMatrix, but the data is extracted the same way for both. - typedDataType = MFnData::kMatrix; - } + // Deal with the MFnTypedAttribute attributes first. If it is numeric, it + // will fall through to the numericDataType switch below. + switch (typedDataType) { + case MFnData::kString: + // If the attribute is marked as a filename, then return Asset + if (MFnAttribute(attrObj).isUsedAsFilename()) { + return SdfValueTypeNames->Asset; + } else { + return SdfValueTypeNames->String; + } + break; + case MFnData::kMatrix: + // This must be a Matrix4d even if + // translateMayaDoubleToUsdSinglePrecision is true, since Matrix4f + // is not supported in Sdf. + return SdfValueTypeNames->Matrix4d; + break; + case MFnData::kMatrixArray: return SdfValueTypeNames->Matrix4dArray; break; + case MFnData::kStringArray: return SdfValueTypeNames->StringArray; break; + case MFnData::kDoubleArray: + if (translateMayaDoubleToUsdSinglePrecision) { + return SdfValueTypeNames->FloatArray; + } else { + return SdfValueTypeNames->DoubleArray; + } + break; + case MFnData::kFloatArray: return SdfValueTypeNames->FloatArray; break; + case MFnData::kIntArray: return SdfValueTypeNames->IntArray; break; + case MFnData::kPointArray: + // Sdf does not have a 4-float point type, so we'll divide out W + // and export the points as 3 floats. + if (translateMayaDoubleToUsdSinglePrecision) { + return SdfValueTypeNames->Point3fArray; + } else { + return SdfValueTypeNames->Point3dArray; + } + break; + case MFnData::kVectorArray: + if (translateMayaDoubleToUsdSinglePrecision) { + return SdfValueTypeNames->Vector3fArray; + } else { + return SdfValueTypeNames->Vector3dArray; + } + break; + default: break; + } - // Deal with the MFnTypedAttribute attributes first. If it is numeric, it - // will fall through to the numericDataType switch below. - switch (typedDataType) { - case MFnData::kString: - // If the attribute is marked as a filename, then return Asset - if (MFnAttribute(attrObj).isUsedAsFilename()) { - return SdfValueTypeNames->Asset; - } else { - return SdfValueTypeNames->String; - } - break; - case MFnData::kMatrix: - // This must be a Matrix4d even if - // translateMayaDoubleToUsdSinglePrecision is true, since Matrix4f - // is not supported in Sdf. - return SdfValueTypeNames->Matrix4d; - break; - case MFnData::kMatrixArray: return SdfValueTypeNames->Matrix4dArray; break; - case MFnData::kStringArray: return SdfValueTypeNames->StringArray; break; - case MFnData::kDoubleArray: - if (translateMayaDoubleToUsdSinglePrecision) { - return SdfValueTypeNames->FloatArray; - } else { - return SdfValueTypeNames->DoubleArray; - } - break; - case MFnData::kFloatArray: return SdfValueTypeNames->FloatArray; break; - case MFnData::kIntArray: return SdfValueTypeNames->IntArray; break; - case MFnData::kPointArray: - // Sdf does not have a 4-float point type, so we'll divide out W - // and export the points as 3 floats. + switch (numericDataType) { + case MFnNumericData::kBoolean: return SdfValueTypeNames->Bool; break; + case MFnNumericData::kByte: + case MFnNumericData::kChar: + case MFnNumericData::kShort: + // Maya treats longs the same as ints, since long is not + // platform-consistent. The Maya constants MFnNumericData::kInt and + // MFnNumericData::kLong have the same value. The same is true of + // k2Int/k2Long and k3Int/k3Long. + case MFnNumericData::kInt: return SdfValueTypeNames->Int; break; + case MFnNumericData::k2Short: + case MFnNumericData::k2Int: return SdfValueTypeNames->Int2; break; + case MFnNumericData::k3Short: + case MFnNumericData::k3Int: return SdfValueTypeNames->Int3; break; + case MFnNumericData::kFloat: return SdfValueTypeNames->Float; break; + case MFnNumericData::k2Float: return SdfValueTypeNames->Float2; break; + case MFnNumericData::k3Float: + if (MFnAttribute(attrObj).isUsedAsColor()) { + return SdfValueTypeNames->Color3f; + } else { + return SdfValueTypeNames->Float3; + } + break; + case MFnNumericData::kDouble: + if (translateMayaDoubleToUsdSinglePrecision) { + return SdfValueTypeNames->Float; + } else { + return SdfValueTypeNames->Double; + } + break; + case MFnNumericData::k2Double: + if (translateMayaDoubleToUsdSinglePrecision) { + return SdfValueTypeNames->Float2; + } else { + return SdfValueTypeNames->Double2; + } + break; + case MFnNumericData::k3Double: + if (MFnAttribute(attrObj).isUsedAsColor()) { if (translateMayaDoubleToUsdSinglePrecision) { - return SdfValueTypeNames->Point3fArray; - } else { - return SdfValueTypeNames->Point3dArray; - } - break; - case MFnData::kVectorArray: - if (translateMayaDoubleToUsdSinglePrecision) { - return SdfValueTypeNames->Vector3fArray; - } else { - return SdfValueTypeNames->Vector3dArray; - } - break; - default: break; - } - - switch (numericDataType) { - case MFnNumericData::kBoolean: return SdfValueTypeNames->Bool; break; - case MFnNumericData::kByte: - case MFnNumericData::kChar: - case MFnNumericData::kShort: - // Maya treats longs the same as ints, since long is not - // platform-consistent. The Maya constants MFnNumericData::kInt and - // MFnNumericData::kLong have the same value. The same is true of - // k2Int/k2Long and k3Int/k3Long. - case MFnNumericData::kInt: return SdfValueTypeNames->Int; break; - case MFnNumericData::k2Short: - case MFnNumericData::k2Int: return SdfValueTypeNames->Int2; break; - case MFnNumericData::k3Short: - case MFnNumericData::k3Int: return SdfValueTypeNames->Int3; break; - case MFnNumericData::kFloat: return SdfValueTypeNames->Float; break; - case MFnNumericData::k2Float: return SdfValueTypeNames->Float2; break; - case MFnNumericData::k3Float: - if (MFnAttribute(attrObj).isUsedAsColor()) { return SdfValueTypeNames->Color3f; } else { - return SdfValueTypeNames->Float3; - } - break; - case MFnNumericData::kDouble: - if (translateMayaDoubleToUsdSinglePrecision) { - return SdfValueTypeNames->Float; - } else { - return SdfValueTypeNames->Double; - } - break; - case MFnNumericData::k2Double: - if (translateMayaDoubleToUsdSinglePrecision) { - return SdfValueTypeNames->Float2; - } else { - return SdfValueTypeNames->Double2; - } - break; - case MFnNumericData::k3Double: - if (MFnAttribute(attrObj).isUsedAsColor()) { - if (translateMayaDoubleToUsdSinglePrecision) { - return SdfValueTypeNames->Color3f; - } else { - return SdfValueTypeNames->Color3d; - } - } else { - if (translateMayaDoubleToUsdSinglePrecision) { - return SdfValueTypeNames->Float3; - } else { - return SdfValueTypeNames->Double3; - } + return SdfValueTypeNames->Color3d; } - break; - case MFnNumericData::k4Double: + } else { if (translateMayaDoubleToUsdSinglePrecision) { - return SdfValueTypeNames->Float4; + return SdfValueTypeNames->Float3; } else { - return SdfValueTypeNames->Double4; + return SdfValueTypeNames->Double3; } - break; - default: break; } - - switch (unitDataType) { - case MFnUnitAttribute::kAngle: - case MFnUnitAttribute::kDistance: - if (translateMayaDoubleToUsdSinglePrecision) { - return SdfValueTypeNames->Float; - } else { - return SdfValueTypeNames->Double; - } - break; - default: break; + break; + case MFnNumericData::k4Double: + if (translateMayaDoubleToUsdSinglePrecision) { + return SdfValueTypeNames->Float4; + } else { + return SdfValueTypeNames->Double4; } + break; + default: break; + } - return SdfValueTypeName(); + switch (unitDataType) { + case MFnUnitAttribute::kAngle: + case MFnUnitAttribute::kDistance: + if (translateMayaDoubleToUsdSinglePrecision) { + return SdfValueTypeNames->Float; + } else { + return SdfValueTypeNames->Double; + } + break; + default: break; } -} // namespace MayaUsd + return SdfValueTypeName(); +} + +} // namespace MAYAUSD_NS_DEF diff --git a/lib/mayaUsd/utils/converter.h b/lib/mayaUsd/utils/converter.h index 0989582ace..3c7e13652f 100644 --- a/lib/mayaUsd/utils/converter.h +++ b/lib/mayaUsd/utils/converter.h @@ -39,424 +39,439 @@ PXR_NAMESPACE_USING_DIRECTIVE -namespace MAYAUSD_NS_DEF -{ +namespace MAYAUSD_NS_DEF { - /*! \brief Converter arguments are passed together using this convenient struct. +/*! \brief Converter arguments are passed together using this convenient struct. - \note Not all arguments will be applicable to all conversions. - */ - struct MAYAUSD_CORE_PUBLIC ConverterArgs final { - //! When conversion needs to read / write to time, following argument will be used. - UsdTimeCode _timeCode { UsdTimeCode::Default() }; - //! For types supporting gamma correction, following argument controls if it should be - //! applied - bool _doGammaCorrection { true }; - }; + \note Not all arguments will be applicable to all conversions. + */ +struct MAYAUSD_CORE_PUBLIC ConverterArgs final +{ + //! When conversion needs to read / write to time, following argument will be used. + UsdTimeCode _timeCode { UsdTimeCode::Default() }; + //! For types supporting gamma correction, following argument controls if it should be + //! applied + bool _doGammaCorrection { true }; +}; - /*! \brief Performant converter, providing several interfaces to translate between Maya and Usd - data types. +/*! \brief Performant converter, providing several interfaces to translate between Maya and Usd + data types. - Instances of converter class are initialized once for all supported types. To use the - converter, use static find methods to validate if the required converter is available. - Pointer to converter class is safe to cache in acceleration structures to reduce runtime cost - when the same conversion happens often (e.g. every frame). + Instances of converter class are initialized once for all supported types. To use the + converter, use static find methods to validate if the required converter is available. + Pointer to converter class is safe to cache in acceleration structures to reduce runtime cost + when the same conversion happens often (e.g. every frame). - The converter will avoid using expensive or intermediate conversion like for example - type-erased Get method on Usd attribute. This means VtValue is not used as an intermediate - type unless it's the source or destination type. + The converter will avoid using expensive or intermediate conversion like for example + type-erased Get method on Usd attribute. This means VtValue is not used as an intermediate + type unless it's the source or destination type. - The converter takes destination containers as a reference to allow fetching the data to the - same container. + The converter takes destination containers as a reference to allow fetching the data to the + same container. - Type checking should be performed when retrieving data converter, no extra penalty at - runtime should be necessary. + Type checking should be performed when retrieving data converter, no extra penalty at + runtime should be necessary. - Usage example: - const Converter* myConverter = Converter::find(mayaPlug, usdAttribute); - if(myConverter) { - // ... some code to fetch data handle, or usd attribute, or plugs... - // ... + Usage example: + const Converter* myConverter = Converter::find(mayaPlug, usdAttribute); + if(myConverter) { + // ... some code to fetch data handle, or usd attribute, or plugs... + // ... - // Configure if dealing with time, gamma correction, etc - ConverterArgs args; + // Configure if dealing with time, gamma correction, etc + ConverterArgs args; - // Convert data handle value directly to usd attribute - myConverter->convert(dataHandle, usdAttribute, args); + // Convert data handle value directly to usd attribute + myConverter->convert(dataHandle, usdAttribute, args); - // OR, convert usd attribute value directly to plug - myConverter->convert(usdAttribute, plug, args); + // OR, convert usd attribute value directly to plug + myConverter->convert(usdAttribute, plug, args); - // OR, convert plug value to VtValue - myConverter->convert(plug, vtValue, args); - } - - \note See the list of currently implemented data converters in converter.cpp file - */ - class MAYAUSD_CORE_PUBLIC Converter final { - using MPlugToUsdAttrFn - = std::add_pointer::type; - using UsdAttrToMPlugFn - = std::add_pointer::type; - using UsdAttrToMDGModifierFn = std::add_pointer< - void(const UsdAttribute&, MPlug&, MDGModifier&, const ConverterArgs&)>::type; - using MPlugToVtValueFn - = std::add_pointer::type; - using VtValueToMPlugFn - = std::add_pointer::type; - using VtValueToMDGModifierFn = std::add_pointer< - void(const VtValue&, MPlug&, MDGModifier&, const ConverterArgs&)>::type; - - using MDataHandleToUsdAttrFn - = std::add_pointer::type; - using UsdAttrToMDataHandleFn - = std::add_pointer::type; - using MDataHandleToVtValueFn - = std::add_pointer::type; - using VtValueToMDataHandleFn - = std::add_pointer::type; - - //! \brief Construct new converter. This should never be called directly other than during - //! generation of all supported converters. - Converter( - const SdfValueTypeName& usdTypeName, - MPlugToUsdAttrFn plugToAttr, - UsdAttrToMPlugFn attrToPlug, - UsdAttrToMDGModifierFn attrToModifier, - MPlugToVtValueFn plugToVtValue, - VtValueToMPlugFn vtValueToPlug, - VtValueToMDGModifierFn vtValueToModifier, - MDataHandleToUsdAttrFn handleToAttr, - UsdAttrToMDataHandleFn attrToHandle, - MDataHandleToVtValueFn handleToVtValue, - VtValueToMDataHandleFn vtValueoHandle) - : _usdTypeName(usdTypeName) - , _plugToAttr(plugToAttr) - , _attrToPlug(attrToPlug) - , _attrToModifier(attrToModifier) - , _plugToVtValue { plugToVtValue } - , _vtValueToPlug { vtValueToPlug } - , _vtValueToModifier(vtValueToModifier) - , _handleToAttr(handleToAttr) - , _attrToHandle(attrToHandle) - , _handleToVtValue { handleToVtValue } - , _vtValueToHandle { vtValueoHandle } - { - } + // OR, convert plug value to VtValue + myConverter->convert(plug, vtValue, args); + } - //! \brief Default constructor makes no sense for this class - Converter() = delete; - public: - //! \brief Nothing special to do in the destructor. - ~Converter() = default; - - //! \brief Look for converter which allows translation for given \p typeName - //! \return Valid pointer if conversion is supported. - static const Converter* find(const SdfValueTypeName& typeName, bool isArrayPlug); - //! \brief Look for converter which allows translation for given pair of Maya's plug and - //! Usd attribute. \return Valid pointer if conversion is supported. - static const Converter* find(const MPlug& plug, const UsdAttribute& attr); - - //! \brief Return sdf value type name this converter is registered for. - const SdfValueTypeName& usdType() const { return _usdTypeName; } - - //! \brief Validate if given pair of Maya's plug and Usd attribute is supported by this - //! converter. - bool validate(const MPlug& plug, const UsdAttribute& usdAttr) const - { - return (usdAttr.GetTypeName() == _usdTypeName) - && (getUsdTypeName(plug, false) == _usdTypeName); + \note See the list of currently implemented data converters in converter.cpp file +*/ +class MAYAUSD_CORE_PUBLIC Converter final +{ + using MPlugToUsdAttrFn + = std::add_pointer::type; + using UsdAttrToMPlugFn + = std::add_pointer::type; + using UsdAttrToMDGModifierFn = std::add_pointer< + void(const UsdAttribute&, MPlug&, MDGModifier&, const ConverterArgs&)>::type; + using MPlugToVtValueFn + = std::add_pointer::type; + using VtValueToMPlugFn + = std::add_pointer::type; + using VtValueToMDGModifierFn + = std::add_pointer::type; + + using MDataHandleToUsdAttrFn + = std::add_pointer::type; + using UsdAttrToMDataHandleFn + = std::add_pointer::type; + using MDataHandleToVtValueFn + = std::add_pointer::type; + using VtValueToMDataHandleFn + = std::add_pointer::type; + + //! \brief Construct new converter. This should never be called directly other than during + //! generation of all supported converters. + Converter( + const SdfValueTypeName& usdTypeName, + MPlugToUsdAttrFn plugToAttr, + UsdAttrToMPlugFn attrToPlug, + UsdAttrToMDGModifierFn attrToModifier, + MPlugToVtValueFn plugToVtValue, + VtValueToMPlugFn vtValueToPlug, + VtValueToMDGModifierFn vtValueToModifier, + MDataHandleToUsdAttrFn handleToAttr, + UsdAttrToMDataHandleFn attrToHandle, + MDataHandleToVtValueFn handleToVtValue, + VtValueToMDataHandleFn vtValueoHandle) + : _usdTypeName(usdTypeName) + , _plugToAttr(plugToAttr) + , _attrToPlug(attrToPlug) + , _attrToModifier(attrToModifier) + , _plugToVtValue { plugToVtValue } + , _vtValueToPlug { vtValueToPlug } + , _vtValueToModifier(vtValueToModifier) + , _handleToAttr(handleToAttr) + , _attrToHandle(attrToHandle) + , _handleToVtValue { handleToVtValue } + , _vtValueToHandle { vtValueoHandle } + { + } + + //! \brief Default constructor makes no sense for this class + Converter() = delete; + +public: + //! \brief Nothing special to do in the destructor. + ~Converter() = default; + + //! \brief Look for converter which allows translation for given \p typeName + //! \return Valid pointer if conversion is supported. + static const Converter* find(const SdfValueTypeName& typeName, bool isArrayPlug); + //! \brief Look for converter which allows translation for given pair of Maya's plug and + //! Usd attribute. \return Valid pointer if conversion is supported. + static const Converter* find(const MPlug& plug, const UsdAttribute& attr); + + //! \brief Return sdf value type name this converter is registered for. + const SdfValueTypeName& usdType() const { return _usdTypeName; } + + //! \brief Validate if given pair of Maya's plug and Usd attribute is supported by this + //! converter. + bool validate(const MPlug& plug, const UsdAttribute& usdAttr) const + { + return (usdAttr.GetTypeName() == _usdTypeName) + && (getUsdTypeName(plug, false) == _usdTypeName); + } + + //! \brief Read current value from given plug and set it on destination attribute. Use + //! arguments to control converter behavior, like the time for setting value on attribute. + void convert(const MPlug& src, UsdAttribute& dst, const ConverterArgs& args) const + { + _plugToAttr(src, dst, args); + } + //! \brief Read current value from given attribute and set it on destination plug. Use + //! arguments to control converter behavior. + void convert(const UsdAttribute& src, MPlug& dst, const ConverterArgs& args) const + { + _attrToPlug(src, dst, args); + } + //! \brief Read current value from given attribute and set it on destination plug using + //! provided DG modifier. Use arguments to control converter behavior. + void + convert(const UsdAttribute& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) const + { + _attrToModifier(src, plug, dst, args); + } + + //! \brief Read current value from given plug and set it on destination VtValue. Use + //! arguments to control converter behavior. + void convert(const MPlug& src, VtValue& dst, const ConverterArgs& args) const + { + _plugToVtValue(src, dst, args); + } + //! \brief Read current value from given VtValue and set it on destination plug. Use + //! arguments to control converter behavior. + void convert(const VtValue& src, MPlug& dst, const ConverterArgs& args) const + { + _vtValueToPlug(src, dst, args); + } + //! \brief Read current value from given VtValue and set it on destination plug using + //! provided DG modifier. Use arguments to control converter behavior. + void convert(const VtValue& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) const + { + _vtValueToModifier(src, plug, dst, args); + } + + //! \brief Read current value from given data handle and set it on destination attribute. + //! Use arguments to control converter behavior, like the time for setting value on + //! attribute. + void convert(const MDataHandle& src, UsdAttribute& dst, const ConverterArgs& args) const + { + _handleToAttr(src, dst, args); + } + //! \brief Read current value from given attribute and set it on destination data handle. + //! Use arguments to control converter behavior, like the time for reading value from + //! attribute. + void convert(const UsdAttribute& src, MDataHandle& dst, const ConverterArgs& args) const + { + _attrToHandle(src, dst, args); + } + + //! \brief Read current value from given data handle and set it on destination VtValue. Use + //! arguments to control converter behavior. + void convert(const MDataHandle& src, VtValue& dst, const ConverterArgs& args) const + { + _handleToVtValue(src, dst, args); + } + //! \brief Read current value from given VtValue and set it on destination data handle. Use + //! arguments to control converter behavior. + void convert(const VtValue& src, MDataHandle& dst, const ConverterArgs& args) const + { + _vtValueToHandle(src, dst, args); + } + + //! \brief Return whether a plug's attribute is a typed attribute with given type. + static bool hasAttrType(const MPlug& plug, MFnData::Type type) + { + MObject object = plug.attribute(); + if (!object.hasFn(MFn::kTypedAttribute)) { + return false; } - //! \brief Read current value from given plug and set it on destination attribute. Use - //! arguments to control converter behavior, like the time for setting value on attribute. - void convert(const MPlug& src, UsdAttribute& dst, const ConverterArgs& args) const - { - _plugToAttr(src, dst, args); - } - //! \brief Read current value from given attribute and set it on destination plug. Use - //! arguments to control converter behavior. - void convert(const UsdAttribute& src, MPlug& dst, const ConverterArgs& args) const - { - _attrToPlug(src, dst, args); - } - //! \brief Read current value from given attribute and set it on destination plug using - //! provided DG modifier. Use arguments to control converter behavior. - void - convert(const UsdAttribute& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) - const - { - _attrToModifier(src, plug, dst, args); - } + MFnTypedAttribute attr(object); + return attr.attrType() == type; + } - //! \brief Read current value from given plug and set it on destination VtValue. Use - //! arguments to control converter behavior. - void convert(const MPlug& src, VtValue& dst, const ConverterArgs& args) const - { - _plugToVtValue(src, dst, args); - } - //! \brief Read current value from given VtValue and set it on destination plug. Use - //! arguments to control converter behavior. - void convert(const VtValue& src, MPlug& dst, const ConverterArgs& args) const - { - _vtValueToPlug(src, dst, args); - } - //! \brief Read current value from given VtValue and set it on destination plug using - //! provided DG modifier. Use arguments to control converter behavior. - void - convert(const VtValue& src, MPlug& plug, MDGModifier& dst, const ConverterArgs& args) const - { - _vtValueToModifier(src, plug, dst, args); + //! \brief Return whether a plug's attribute is a numeric attribute with given type. + static bool hasNumericType(const MPlug& plug, MFnNumericData::Type type) + { + MObject object = plug.attribute(); + if (!object.hasFn(MFn::kNumericAttribute)) { + return false; } - //! \brief Read current value from given data handle and set it on destination attribute. - //! Use arguments to control converter behavior, like the time for setting value on - //! attribute. - void convert(const MDataHandle& src, UsdAttribute& dst, const ConverterArgs& args) const - { - _handleToAttr(src, dst, args); - } - //! \brief Read current value from given attribute and set it on destination data handle. - //! Use arguments to control converter behavior, like the time for reading value from - //! attribute. - void convert(const UsdAttribute& src, MDataHandle& dst, const ConverterArgs& args) const - { - _attrToHandle(src, dst, args); - } + MFnNumericAttribute attr(object); + return attr.unitType() == type; + } - //! \brief Read current value from given data handle and set it on destination VtValue. Use - //! arguments to control converter behavior. - void convert(const MDataHandle& src, VtValue& dst, const ConverterArgs& args) const - { - _handleToVtValue(src, dst, args); - } - //! \brief Read current value from given VtValue and set it on destination data handle. Use - //! arguments to control converter behavior. - void convert(const VtValue& src, MDataHandle& dst, const ConverterArgs& args) const - { - _vtValueToHandle(src, dst, args); - } + //! \brief Return whether a plug's attribute is an enum type. + static bool hasEnumType(const MPlug& plug) + { + MObject object = plug.attribute(); + return object.hasFn(MFn::kEnumAttribute); + } - //! \brief Return whether a plug's attribute is a typed attribute with given type. - static bool hasAttrType(const MPlug& plug, MFnData::Type type) - { - MObject object = plug.attribute(); - if (!object.hasFn(MFn::kTypedAttribute)) { - return false; - } + /*! \brief Get the SdfValueTypeName that corresponds to the given plug \p attrPlug. - MFnTypedAttribute attr(object); - return attr.attrType() == type; - } + If \p translateMayaDoubleToUsdSinglePrecision is true, Maya plugs that + contain double data will return the appropriate float-based type. + Otherwise, the type returned will be the appropriate double-based type. + */ + static SdfValueTypeName getUsdTypeName( + const MPlug& attrPlug, + const bool translateMayaDoubleToUsdSinglePrecision + = UsdMayaUserTaggedAttribute::GetFallbackTranslateMayaDoubleToUsdSinglePrecision()); + + struct GenerateConverters; + struct GenerateArrayPlugConverters; + +private: + //! Usd type this converter is operating with. + const SdfValueTypeName& _usdTypeName; + + // MPlug <--> UsdAttribute + //! Pointer to a function responsible for converting plug value to given usd attribute. + MPlugToUsdAttrFn _plugToAttr { nullptr }; + //! Pointer to a function responsible for converting usd attribute value to a given plug. + UsdAttrToMPlugFn _attrToPlug { nullptr }; + //! Pointer to a function responsible for converting usd attribute value to a given plug + //! using provided DG modifier. + UsdAttrToMDGModifierFn _attrToModifier { nullptr }; + + // MPlug <--> VtValue + //! Pointer to a function responsible for converting plug value to VtValue. + MPlugToVtValueFn _plugToVtValue { nullptr }; + //! Pointer to a function responsible for converting VtValue to a given plug. + VtValueToMPlugFn _vtValueToPlug { nullptr }; + //! Pointer to a function responsible for converting VtValue to a given plug using provided + //! DG modifier. + VtValueToMDGModifierFn _vtValueToModifier { nullptr }; + + // MDataBlock <--> UsdAttribute + //! Pointer to a function responsible for converting data handle value to given usd + //! attribute. + MDataHandleToUsdAttrFn _handleToAttr { nullptr }; + //! Pointer to a function responsible for converting usd attribute value to a given data + //! handle. + UsdAttrToMDataHandleFn _attrToHandle { nullptr }; + + // MDataBlock <--> VtValue + //! Pointer to a function responsible for converting data handle value to VtValue. + MDataHandleToVtValueFn _handleToVtValue { nullptr }; + //! Pointer to a function responsible for converting VtValue to a given data handle. + VtValueToMDataHandleFn _vtValueToHandle { nullptr }; +}; + +//! \brief Declaration of base typed converter struct. Each supported type will specialize this +//! struct and provide +//! two conversion methods. All specializations will be available in converter header +//! file to allow reuse when both types are already known. +template struct TypedConverter +{ +}; + +//! \brief Specialization of TypedConverter for case where MAYA_Type and USD_Type are exactly +//! the same type. +template +struct TypedConverter< + MAYA_Type, + USD_Type, + typename std::enable_if::value>::type> +{ + static void convert(const USD_Type& src, MAYA_Type& dst) { dst = src; } +}; - //! \brief Return whether a plug's attribute is a numeric attribute with given type. - static bool hasNumericType(const MPlug& plug, MFnNumericData::Type type) - { - MObject object = plug.attribute(); - if (!object.hasFn(MFn::kNumericAttribute)) { - return false; - } +//! \brief Specialization of TypedConverter for float3 <--> GfVec3f +template <> struct TypedConverter +{ + static void convert(const GfVec3f& src, float3& dst) + { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + } + static void convert(const float3& src, GfVec3f& dst) + { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + } +}; + +//! \brief Specialization of TypedConverter for double3 <--> GfVec3d +template <> struct TypedConverter +{ + static void convert(const GfVec3d& src, double3& dst) + { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + } + static void convert(const double3& src, GfVec3d& dst) + { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + } +}; + +//! \brief Specialization of TypedConverter for MPoint <--> GfVec3f +template <> struct TypedConverter +{ + static void convert(const GfVec3f& src, MPoint& dst) + { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + } + static void convert(const MPoint& src, GfVec3f& dst) + { + dst[0] = src[0]; + dst[1] = src[1]; + dst[2] = src[2]; + } +}; + +//! \brief Specialization of TypedConverter for MString <--> std::string +template <> struct TypedConverter +{ + static void convert(const std::string& src, MString& dst) { dst = src.c_str(); } + static void convert(const MString& src, std::string& dst) { dst = src.asChar(); } +}; - MFnNumericAttribute attr(object); - return attr.unitType() == type; +//! \brief Specialization of TypedConverter for MMatrix <--> GfMatrix4d +template <> struct TypedConverter +{ + static void convert(const GfMatrix4d& src, MMatrix& dst) + { + memcpy(dst[0], src.GetArray(), sizeof(double) * 16); + } + static void convert(const MMatrix& src, GfMatrix4d& dst) + { + memcpy(dst.GetArray(), src[0], sizeof(double) * 16); + } +}; + +//! \brief Specialization of TypedConverter for MIntArray <--> VtArray +template <> struct TypedConverter> +{ + static void convert(const VtArray& src, MIntArray& dst) + { + const size_t srcSize = src.size(); + dst.setLength(srcSize); + for (size_t i = 0; i < srcSize; i++) { + dst[i] = src[i]; } - - //! \brief Return whether a plug's attribute is an enum type. - static bool hasEnumType(const MPlug& plug) - { - MObject object = plug.attribute(); - return object.hasFn(MFn::kEnumAttribute); + } + static void convert(const MIntArray& src, VtArray& dst) + { + const size_t srcSize = src.length(); + dst.resize(srcSize); + for (size_t i = 0; i < srcSize; i++) { + dst[i] = src[i]; } + } +}; - /*! \brief Get the SdfValueTypeName that corresponds to the given plug \p attrPlug. - - If \p translateMayaDoubleToUsdSinglePrecision is true, Maya plugs that - contain double data will return the appropriate float-based type. - Otherwise, the type returned will be the appropriate double-based type. - */ - static SdfValueTypeName getUsdTypeName( - const MPlug& attrPlug, - const bool translateMayaDoubleToUsdSinglePrecision - = UsdMayaUserTaggedAttribute::GetFallbackTranslateMayaDoubleToUsdSinglePrecision()); - - struct GenerateConverters; - struct GenerateArrayPlugConverters; - private: - //! Usd type this converter is operating with. - const SdfValueTypeName& _usdTypeName; - - // MPlug <--> UsdAttribute - //! Pointer to a function responsible for converting plug value to given usd attribute. - MPlugToUsdAttrFn _plugToAttr { nullptr }; - //! Pointer to a function responsible for converting usd attribute value to a given plug. - UsdAttrToMPlugFn _attrToPlug { nullptr }; - //! Pointer to a function responsible for converting usd attribute value to a given plug - //! using provided DG modifier. - UsdAttrToMDGModifierFn _attrToModifier { nullptr }; - - // MPlug <--> VtValue - //! Pointer to a function responsible for converting plug value to VtValue. - MPlugToVtValueFn _plugToVtValue { nullptr }; - //! Pointer to a function responsible for converting VtValue to a given plug. - VtValueToMPlugFn _vtValueToPlug { nullptr }; - //! Pointer to a function responsible for converting VtValue to a given plug using provided - //! DG modifier. - VtValueToMDGModifierFn _vtValueToModifier { nullptr }; - - // MDataBlock <--> UsdAttribute - //! Pointer to a function responsible for converting data handle value to given usd - //! attribute. - MDataHandleToUsdAttrFn _handleToAttr { nullptr }; - //! Pointer to a function responsible for converting usd attribute value to a given data - //! handle. - UsdAttrToMDataHandleFn _attrToHandle { nullptr }; - - // MDataBlock <--> VtValue - //! Pointer to a function responsible for converting data handle value to VtValue. - MDataHandleToVtValueFn _handleToVtValue { nullptr }; - //! Pointer to a function responsible for converting VtValue to a given data handle. - VtValueToMDataHandleFn _vtValueToHandle { nullptr }; - }; - - //! \brief Declaration of base typed converter struct. Each supported type will specialize this - //! struct and provide - //! two conversion methods. All specializations will be available in converter header - //! file to allow reuse when both types are already known. - template struct TypedConverter { - }; - - //! \brief Specialization of TypedConverter for case where MAYA_Type and USD_Type are exactly - //! the same type. - template - struct TypedConverter< - MAYA_Type, - USD_Type, - typename std::enable_if::value>::type> { - static void convert(const USD_Type& src, MAYA_Type& dst) { dst = src; } - }; - - //! \brief Specialization of TypedConverter for float3 <--> GfVec3f - template <> struct TypedConverter { - static void convert(const GfVec3f& src, float3& dst) - { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - } - static void convert(const float3& src, GfVec3f& dst) - { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - } - }; - - //! \brief Specialization of TypedConverter for double3 <--> GfVec3d - template <> struct TypedConverter { - static void convert(const GfVec3d& src, double3& dst) - { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - } - static void convert(const double3& src, GfVec3d& dst) - { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - } - }; - - //! \brief Specialization of TypedConverter for MPoint <--> GfVec3f - template <> struct TypedConverter { - static void convert(const GfVec3f& src, MPoint& dst) - { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - } - static void convert(const MPoint& src, GfVec3f& dst) - { - dst[0] = src[0]; - dst[1] = src[1]; - dst[2] = src[2]; - } - }; - - //! \brief Specialization of TypedConverter for MString <--> std::string - template <> struct TypedConverter { - static void convert(const std::string& src, MString& dst) { dst = src.c_str(); } - static void convert(const MString& src, std::string& dst) { dst = src.asChar(); } - }; - - //! \brief Specialization of TypedConverter for MMatrix <--> GfMatrix4d - template <> struct TypedConverter { - static void convert(const GfMatrix4d& src, MMatrix& dst) - { - memcpy(dst[0], src.GetArray(), sizeof(double) * 16); - } - static void convert(const MMatrix& src, GfMatrix4d& dst) - { - memcpy(dst.GetArray(), src[0], sizeof(double) * 16); - } - }; - - //! \brief Specialization of TypedConverter for MIntArray <--> VtArray - template <> struct TypedConverter> { - static void convert(const VtArray& src, MIntArray& dst) - { - const size_t srcSize = src.size(); - dst.setLength(srcSize); - for (size_t i = 0; i < srcSize; i++) { dst[i] = src[i]; } - } - static void convert(const MIntArray& src, VtArray& dst) - { - const size_t srcSize = src.length(); - dst.resize(srcSize); - for (size_t i = 0; i < srcSize; i++) { dst[i] = src[i]; } - } - }; - - //! \brief Specialization of TypedConverter for MPointArray <--> VtArray - template <> struct TypedConverter> { - static void convert(const VtArray& src, MPointArray& dst) - { - const size_t srcSize = src.size(); - dst.setLength(srcSize); - for (size_t i = 0; i < srcSize; i++) { - TypedConverter::convert(src[i], dst[i]); - } +//! \brief Specialization of TypedConverter for MPointArray <--> VtArray +template <> struct TypedConverter> +{ + static void convert(const VtArray& src, MPointArray& dst) + { + const size_t srcSize = src.size(); + dst.setLength(srcSize); + for (size_t i = 0; i < srcSize; i++) { + TypedConverter::convert(src[i], dst[i]); } - static void convert(const MPointArray& src, VtArray& dst) - { - const size_t srcSize = src.length(); - dst.resize(srcSize); - for (size_t i = 0; i < srcSize; i++) { - TypedConverter::convert(src[i], dst[i]); - } + } + static void convert(const MPointArray& src, VtArray& dst) + { + const size_t srcSize = src.length(); + dst.resize(srcSize); + for (size_t i = 0; i < srcSize; i++) { + TypedConverter::convert(src[i], dst[i]); } - }; - - //! \brief Specialization of TypedConverter for MMatrixArray <--> VtArray - template <> struct TypedConverter> { - static void convert(const VtArray& src, MMatrixArray& dst) - { - const size_t srcSize = src.size(); - dst.setLength(srcSize); - for (size_t i = 0; i < srcSize; i++) { - TypedConverter::convert(src[i], dst[i]); - } + } +}; + +//! \brief Specialization of TypedConverter for MMatrixArray <--> VtArray +template <> struct TypedConverter> +{ + static void convert(const VtArray& src, MMatrixArray& dst) + { + const size_t srcSize = src.size(); + dst.setLength(srcSize); + for (size_t i = 0; i < srcSize; i++) { + TypedConverter::convert(src[i], dst[i]); } - static void convert(const MMatrixArray& src, VtArray& dst) - { - const size_t srcSize = src.length(); - dst.resize(srcSize); - for (size_t i = 0; i < srcSize; i++) { - TypedConverter::convert(src[i], dst[i]); - } + } + static void convert(const MMatrixArray& src, VtArray& dst) + { + const size_t srcSize = src.length(); + dst.resize(srcSize); + for (size_t i = 0; i < srcSize; i++) { + TypedConverter::convert(src[i], dst[i]); } - }; + } +}; -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/mayaUsd/utils/diagnosticDelegate.cpp b/lib/mayaUsd/utils/diagnosticDelegate.cpp index 271cde5e1e..5905f2bd28 100644 --- a/lib/mayaUsd/utils/diagnosticDelegate.cpp +++ b/lib/mayaUsd/utils/diagnosticDelegate.cpp @@ -15,74 +15,71 @@ // #include "diagnosticDelegate.h" -#include - -#include +#include #include #include #include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_ENV_SETTING(PIXMAYA_DIAGNOSTICS_BATCH, true, - "Whether to batch diagnostics coming from the same call site. " - "If batching is off, all secondary threads' diagnostics will be " - "printed to stderr."); +TF_DEFINE_ENV_SETTING( + PIXMAYA_DIAGNOSTICS_BATCH, + true, + "Whether to batch diagnostics coming from the same call site. " + "If batching is off, all secondary threads' diagnostics will be " + "printed to stderr."); // Globally-shared delegate. Uses shared_ptr so we can have weak ptrs. static std::shared_ptr _sharedDelegate; namespace { -class _StatusOnlyDelegate : public UsdUtilsCoalescingDiagnosticDelegate { - void IssueWarning(const TfWarning&) override {} - void IssueFatalError(const TfCallContext&, const std::string&) override {} +class _StatusOnlyDelegate : public UsdUtilsCoalescingDiagnosticDelegate +{ + void IssueWarning(const TfWarning&) override { } + void IssueFatalError(const TfCallContext&, const std::string&) override { } }; -class _WarningOnlyDelegate : public UsdUtilsCoalescingDiagnosticDelegate { - void IssueStatus(const TfStatus&) override {} - void IssueFatalError(const TfCallContext&, const std::string&) override {} +class _WarningOnlyDelegate : public UsdUtilsCoalescingDiagnosticDelegate +{ + void IssueStatus(const TfStatus&) override { } + void IssueFatalError(const TfCallContext&, const std::string&) override { } }; } // anonymous namespace -static MString -_FormatDiagnostic(const TfDiagnosticBase& d) +static MString _FormatDiagnostic(const TfDiagnosticBase& d) { const std::string msg = TfStringPrintf( - "%s -- %s in %s at line %zu of %s", - d.GetCommentary().c_str(), - TfDiagnosticMgr::GetCodeName(d.GetDiagnosticCode()).c_str(), - d.GetContext().GetFunction(), - d.GetContext().GetLine(), - d.GetContext().GetFile()); + "%s -- %s in %s at line %zu of %s", + d.GetCommentary().c_str(), + TfDiagnosticMgr::GetCodeName(d.GetDiagnosticCode()).c_str(), + d.GetContext().GetFunction(), + d.GetContext().GetLine(), + d.GetContext().GetFile()); return msg.c_str(); } -static MString -_FormatCoalescedDiagnostic(const UsdUtilsCoalescingDiagnosticDelegateItem& item) +static MString _FormatCoalescedDiagnostic(const UsdUtilsCoalescingDiagnosticDelegateItem& item) { - const size_t numItems = item.unsharedItems.size(); - const std::string suffix = numItems == 1 - ? std::string() - : TfStringPrintf(" -- and %zu similar", numItems - 1); - const std::string message = TfStringPrintf("%s%s", - item.unsharedItems[0].commentary.c_str(), - suffix.c_str()); + const size_t numItems = item.unsharedItems.size(); + const std::string suffix + = numItems == 1 ? std::string() : TfStringPrintf(" -- and %zu similar", numItems - 1); + const std::string message + = TfStringPrintf("%s%s", item.unsharedItems[0].commentary.c_str(), suffix.c_str()); return message.c_str(); } -static bool -_IsDiagnosticBatchingEnabled() -{ - return TfGetEnvSetting(PIXMAYA_DIAGNOSTICS_BATCH); -} +static bool _IsDiagnosticBatchingEnabled() { return TfGetEnvSetting(PIXMAYA_DIAGNOSTICS_BATCH); } -UsdMayaDiagnosticDelegate::UsdMayaDiagnosticDelegate() : _batchCount(0) +UsdMayaDiagnosticDelegate::UsdMayaDiagnosticDelegate() + : _batchCount(0) { TfDiagnosticMgr::GetInstance().AddDelegate(this); } @@ -97,8 +94,7 @@ UsdMayaDiagnosticDelegate::~UsdMayaDiagnosticDelegate() TfDiagnosticMgr::GetInstance().RemoveDelegate(this); } -void -UsdMayaDiagnosticDelegate::IssueError(const TfError& err) +void UsdMayaDiagnosticDelegate::IssueError(const TfError& err) { // Errors are never batched. They should be rare, and in those cases, we // want to see them separately. @@ -106,14 +102,12 @@ UsdMayaDiagnosticDelegate::IssueError(const TfError& err) // through _FormatDiagnostic. if (ArchIsMainThread()) { MGlobal::displayError(_FormatDiagnostic(err)); - } - else { + } else { std::cerr << _FormatDiagnostic(err) << std::endl; } } -void -UsdMayaDiagnosticDelegate::IssueStatus(const TfStatus& status) +void UsdMayaDiagnosticDelegate::IssueStatus(const TfStatus& status) { if (_batchCount.load() > 0) { return; // Batched. @@ -121,14 +115,12 @@ UsdMayaDiagnosticDelegate::IssueStatus(const TfStatus& status) if (ArchIsMainThread()) { MGlobal::displayInfo(status.GetCommentary().c_str()); - } - else { + } else { std::cerr << _FormatDiagnostic(status) << std::endl; } } -void -UsdMayaDiagnosticDelegate::IssueWarning(const TfWarning& warning) +void UsdMayaDiagnosticDelegate::IssueWarning(const TfWarning& warning) { if (_batchCount.load() > 0) { return; // Batched. @@ -136,29 +128,26 @@ UsdMayaDiagnosticDelegate::IssueWarning(const TfWarning& warning) if (ArchIsMainThread()) { MGlobal::displayWarning(warning.GetCommentary().c_str()); - } - else { + } else { std::cerr << _FormatDiagnostic(warning) << std::endl; } } -void -UsdMayaDiagnosticDelegate::IssueFatalError( +void UsdMayaDiagnosticDelegate::IssueFatalError( const TfCallContext& context, - const std::string& msg) + const std::string& msg) { TfLogCrash( - "FATAL ERROR", - msg, - /*additionalInfo*/ std::string(), - context, - /*logToDb*/ true); + "FATAL ERROR", + msg, + /*additionalInfo*/ std::string(), + context, + /*logToDb*/ true); _UnhandledAbort(); } /* static */ -void -UsdMayaDiagnosticDelegate::InstallDelegate() +void UsdMayaDiagnosticDelegate::InstallDelegate() { if (!ArchIsMainThread()) { TF_FATAL_CODING_ERROR("Cannot install delegate from secondary thread"); @@ -167,8 +156,7 @@ UsdMayaDiagnosticDelegate::InstallDelegate() } /* static */ -void -UsdMayaDiagnosticDelegate::RemoveDelegate() +void UsdMayaDiagnosticDelegate::RemoveDelegate() { if (!ArchIsMainThread()) { TF_FATAL_CODING_ERROR("Cannot remove delegate from secondary thread"); @@ -177,8 +165,7 @@ UsdMayaDiagnosticDelegate::RemoveDelegate() } /* static */ -int -UsdMayaDiagnosticDelegate::GetBatchCount() +int UsdMayaDiagnosticDelegate::GetBatchCount() { if (std::shared_ptr ptr = _sharedDelegate) { return ptr->_batchCount.load(); @@ -188,8 +175,7 @@ UsdMayaDiagnosticDelegate::GetBatchCount() return 0; } -void -UsdMayaDiagnosticDelegate::_StartBatch() +void UsdMayaDiagnosticDelegate::_StartBatch() { TF_AXIOM(ArchIsMainThread()); @@ -200,16 +186,14 @@ UsdMayaDiagnosticDelegate::_StartBatch() } } -void -UsdMayaDiagnosticDelegate::_EndBatch() +void UsdMayaDiagnosticDelegate::_EndBatch() { TF_AXIOM(ArchIsMainThread()); const int prevValue = _batchCount.fetch_sub(1); if (prevValue <= 0) { TF_FATAL_ERROR("_EndBatch invoked before _StartBatch"); - } - else if (prevValue == 1) { + } else if (prevValue == 1) { // This is the last _EndBatch; print the diagnostic messages. // and remove the batching delegates. _FlushBatch(); @@ -218,19 +202,16 @@ UsdMayaDiagnosticDelegate::_EndBatch() } } -void -UsdMayaDiagnosticDelegate::_FlushBatch() +void UsdMayaDiagnosticDelegate::_FlushBatch() { TF_AXIOM(ArchIsMainThread()); - const UsdUtilsCoalescingDiagnosticDelegateVector statuses = - _batchedStatuses - ? _batchedStatuses->TakeCoalescedDiagnostics() - : UsdUtilsCoalescingDiagnosticDelegateVector(); - const UsdUtilsCoalescingDiagnosticDelegateVector warnings = - _batchedWarnings - ? _batchedWarnings->TakeCoalescedDiagnostics() - : UsdUtilsCoalescingDiagnosticDelegateVector(); + const UsdUtilsCoalescingDiagnosticDelegateVector statuses = _batchedStatuses + ? _batchedStatuses->TakeCoalescedDiagnostics() + : UsdUtilsCoalescingDiagnosticDelegateVector(); + const UsdUtilsCoalescingDiagnosticDelegateVector warnings = _batchedWarnings + ? _batchedWarnings->TakeCoalescedDiagnostics() + : UsdUtilsCoalescingDiagnosticDelegateVector(); // Note that we must be in the main thread here, so it's safe to call // displayInfo/displayWarning. diff --git a/lib/mayaUsd/utils/diagnosticDelegate.h b/lib/mayaUsd/utils/diagnosticDelegate.h index b034bc06c1..df52c1e2f6 100644 --- a/lib/mayaUsd/utils/diagnosticDelegate.h +++ b/lib/mayaUsd/utils/diagnosticDelegate.h @@ -16,16 +16,16 @@ #ifndef PXRUSDMAYA_DIAGNOSTICDELEGATE_H #define PXRUSDMAYA_DIAGNOSTICDELEGATE_H -#include -#include - -#include +#include -#include #include +#include #include -#include +#include + +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -46,7 +46,8 @@ class UsdMayaDiagnosticBatchContext; /// /// Installing and removing this diagnostic delegate is not thread-safe, and /// must be done only on the main thread. -class UsdMayaDiagnosticDelegate : TfDiagnosticMgr::Delegate { +class UsdMayaDiagnosticDelegate : TfDiagnosticMgr::Delegate +{ public: MAYAUSD_CORE_PUBLIC ~UsdMayaDiagnosticDelegate() override; @@ -58,9 +59,7 @@ class UsdMayaDiagnosticDelegate : TfDiagnosticMgr::Delegate { MAYAUSD_CORE_PUBLIC void IssueWarning(const TfWarning& warning) override; MAYAUSD_CORE_PUBLIC - void IssueFatalError( - const TfCallContext& context, - const std::string& msg) override; + void IssueFatalError(const TfCallContext& context, const std::string& msg) override; /// Installs a shared delegate globally. /// If this is invoked on a secondary thread, issues a fatal coding error. @@ -79,7 +78,7 @@ class UsdMayaDiagnosticDelegate : TfDiagnosticMgr::Delegate { private: friend class UsdMayaDiagnosticBatchContext; - std::atomic_int _batchCount; + std::atomic_int _batchCount; std::unique_ptr _batchedStatuses; std::unique_ptr _batchedWarnings; @@ -117,10 +116,8 @@ class UsdMayaDiagnosticBatchContext MAYAUSD_CORE_PUBLIC ~UsdMayaDiagnosticBatchContext(); - UsdMayaDiagnosticBatchContext( - const UsdMayaDiagnosticBatchContext&) = delete; - UsdMayaDiagnosticBatchContext& operator=( - const UsdMayaDiagnosticBatchContext&) = delete; + UsdMayaDiagnosticBatchContext(const UsdMayaDiagnosticBatchContext&) = delete; + UsdMayaDiagnosticBatchContext& operator=(const UsdMayaDiagnosticBatchContext&) = delete; private: /// This pointer is used to "bind" this context to a specific delegate in diff --git a/lib/mayaUsd/utils/plugRegistryHelper.h b/lib/mayaUsd/utils/plugRegistryHelper.h index 887b382a72..8e236f6fde 100644 --- a/lib/mayaUsd/utils/plugRegistryHelper.h +++ b/lib/mayaUsd/utils/plugRegistryHelper.h @@ -27,41 +27,42 @@ PXR_NAMESPACE_USING_DIRECTIVE -namespace MAYAUSD_NS_DEF -{ - /*! \brief Register USD plugins matching USD version distributed with MayaUSD. - - USD Plugins registered in the plug registry via PXR_PLUGINPATH_NAME have to link against - the same version of USD as MayaUSD. Plugins distributed separately from MayaUSD can use - MAYA_PXR_PLUGINPATH_NAME env variable to point to a folder with multiple binaries organized - in folders per USD versions. MayaUSD will append to each path USD version and call plug registry - to register the plugins. - */ - inline void registerVersionedPlugins() - { - static std::once_flag once; - std::call_once(once, [](){ - static std::string usd_version = std::to_string(PXR_VERSION); +namespace MAYAUSD_NS_DEF { +/*! \brief Register USD plugins matching USD version distributed with MayaUSD. - std::vector pluginsToRegister; + USD Plugins registered in the plug registry via PXR_PLUGINPATH_NAME have to link against + the same version of USD as MayaUSD. Plugins distributed separately from MayaUSD can use + MAYA_PXR_PLUGINPATH_NAME env variable to point to a folder with multiple binaries organized + in folders per USD versions. MayaUSD will append to each path USD version and call plug registry + to register the plugins. + */ +inline void registerVersionedPlugins() +{ + static std::once_flag once; + std::call_once(once, []() { + static std::string usd_version = std::to_string(PXR_VERSION); - const std::string paths = TfGetenv("MAYA_PXR_PLUGINPATH_NAME"); - for (const auto& path: TfStringSplit(paths, ARCH_PATH_LIST_SEP)) { - if (path.empty()) { - continue; - } + std::vector pluginsToRegister; - if(TfIsRelativePath(path)) { - TF_CODING_ERROR("Relative paths are unsupported for MAYA_PXR_PLUGINPATH_NAME: '%s'", path.c_str()); - continue; - } + const std::string paths = TfGetenv("MAYA_PXR_PLUGINPATH_NAME"); + for (const auto& path : TfStringSplit(paths, ARCH_PATH_LIST_SEP)) { + if (path.empty()) { + continue; + } - pluginsToRegister.push_back(TfStringCatPaths(path, usd_version)); + if (TfIsRelativePath(path)) { + TF_CODING_ERROR( + "Relative paths are unsupported for MAYA_PXR_PLUGINPATH_NAME: '%s'", + path.c_str()); + continue; } - PlugRegistry::GetInstance().RegisterPlugins(pluginsToRegister); - }); - } -} // namespace MayaUsd + pluginsToRegister.push_back(TfStringCatPaths(path, usd_version)); + } + + PlugRegistry::GetInstance().RegisterPlugins(pluginsToRegister); + }); +} +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/mayaUsd/utils/query.cpp b/lib/mayaUsd/utils/query.cpp index 365c695b6e..c53c2c6802 100644 --- a/lib/mayaUsd/utils/query.cpp +++ b/lib/mayaUsd/utils/query.cpp @@ -15,13 +15,8 @@ // #include "query.h" -#include - -#include -#include -#include -#include -#include +#include +#include #include #include @@ -29,13 +24,17 @@ #include #include -#include -#include +#include +#include +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -UsdPrim -UsdMayaQuery::GetPrim(const std::string& shapeName) +UsdPrim UsdMayaQuery::GetPrim(const std::string& shapeName) { UsdPrim usdPrim; @@ -45,16 +44,15 @@ UsdMayaQuery::GetPrim(const std::string& shapeName) MFnDagNode dagNode(shapeObj, &status); CHECK_MSTATUS_AND_RETURN(status, usdPrim); - if (const UsdMayaUsdPrimProvider* usdPrimProvider = - dynamic_cast(dagNode.userNode())) { + if (const UsdMayaUsdPrimProvider* usdPrimProvider + = dynamic_cast(dagNode.userNode())) { return usdPrimProvider->usdPrim(); } return usdPrim; } -void -UsdMayaQuery::ReloadStage(const std::string& shapeName) +void UsdMayaQuery::ReloadStage(const std::string& shapeName) { MStatus status; @@ -65,6 +63,4 @@ UsdMayaQuery::ReloadStage(const std::string& shapeName) } } - PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/mayaUsd/utils/query.h b/lib/mayaUsd/utils/query.h index 704929204e..3cd7b4b824 100644 --- a/lib/mayaUsd/utils/query.h +++ b/lib/mayaUsd/utils/query.h @@ -16,14 +16,14 @@ #ifndef PXRUSDMAYA_QUERY_H #define PXRUSDMAYA_QUERY_H -#include -#include +#include #include #include #include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -37,7 +37,6 @@ struct UsdMayaQuery static void ReloadStage(const std::string& shapeName); }; - PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/mayaUsd/utils/stageCache.cpp b/lib/mayaUsd/utils/stageCache.cpp index 7d1eecac6b..773013a530 100644 --- a/lib/mayaUsd/utils/stageCache.cpp +++ b/lib/mayaUsd/utils/stageCache.cpp @@ -15,14 +15,7 @@ // #include "stageCache.h" -#include -#include -#include -#include -#include - -#include -#include +#include #include #include @@ -31,16 +24,24 @@ #include #include -#include +#include +#include + +#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE namespace { static std::map _sharedSessionLayers; -static std::mutex _sharedSessionLayersMutex; +static std::mutex _sharedSessionLayersMutex; -struct _OnSceneResetListener : public TfWeakBase { +struct _OnSceneResetListener : public TfWeakBase +{ _OnSceneResetListener() { TfWeakPtr<_OnSceneResetListener> me(this); @@ -60,27 +61,26 @@ struct _OnSceneResetListener : public TfWeakBase { } // anonymous namespace /* static */ -UsdStageCache& -UsdMayaStageCache::Get(const bool loadAll) +UsdStageCache& UsdMayaStageCache::Get(const bool loadAll) { - static UsdStageCache theCacheLoadAll; // used when UsdStage::Open() will be called with UsdStage::InitialLoadSet::LoadAll - static UsdStageCache theCache; // used when UsdStage::Open() will be called with UsdStage::InitialLoadSet::LoadNode + static UsdStageCache theCacheLoadAll; // used when UsdStage::Open() will be called with + // UsdStage::InitialLoadSet::LoadAll + static UsdStageCache theCache; // used when UsdStage::Open() will be called with + // UsdStage::InitialLoadSet::LoadNode static _OnSceneResetListener onSceneResetListener; return loadAll ? theCacheLoadAll : theCache; } /* static */ -void -UsdMayaStageCache::Clear() +void UsdMayaStageCache::Clear() { Get(true).Clear(); Get(false).Clear(); } /* static */ -size_t -UsdMayaStageCache::EraseAllStagesWithRootLayerPath(const std::string& layerPath) +size_t UsdMayaStageCache::EraseAllStagesWithRootLayerPath(const std::string& layerPath) { size_t erasedStages = 0u; @@ -95,11 +95,10 @@ UsdMayaStageCache::EraseAllStagesWithRootLayerPath(const std::string& layerPath) return erasedStages; } -SdfLayerRefPtr -UsdMayaStageCache::GetSharedSessionLayer( - const SdfPath& rootPath, +SdfLayerRefPtr UsdMayaStageCache::GetSharedSessionLayer( + const SdfPath& rootPath, const std::map& variantSelections, - const TfToken& drawMode) + const TfToken& drawMode) { // Example key: "/Root/Path:modelingVariant=round|shadingVariant=red|:cards" std::ostringstream key; @@ -111,9 +110,9 @@ UsdMayaStageCache::GetSharedSessionLayer( key << ":"; key << drawMode; - std::string keyString = key.str(); + std::string keyString = key.str(); std::lock_guard lock(_sharedSessionLayersMutex); - auto iter = _sharedSessionLayers.find(keyString); + auto iter = _sharedSessionLayers.find(keyString); if (iter == _sharedSessionLayers.end()) { SdfLayerRefPtr newLayer = SdfLayer::CreateAnonymous(); @@ -126,23 +125,22 @@ UsdMayaStageCache::GetSharedSessionLayer( if (!drawMode.IsEmpty()) { SdfAttributeSpecHandle drawModeAttr = SdfAttributeSpec::New( - over, - UsdGeomTokens->modelDrawMode, - SdfValueTypeNames->Token, - SdfVariabilityUniform); + over, + UsdGeomTokens->modelDrawMode, + SdfValueTypeNames->Token, + SdfVariabilityUniform); drawModeAttr->SetDefaultValue(VtValue(drawMode)); SdfAttributeSpecHandle applyDrawModeAttr = SdfAttributeSpec::New( - over, - UsdGeomTokens->modelApplyDrawMode, - SdfValueTypeNames->Bool, - SdfVariabilityUniform); + over, + UsdGeomTokens->modelApplyDrawMode, + SdfValueTypeNames->Bool, + SdfVariabilityUniform); applyDrawModeAttr->SetDefaultValue(VtValue(true)); } _sharedSessionLayers[keyString] = newLayer; return newLayer; - } - else { + } else { return iter->second; } } diff --git a/lib/mayaUsd/utils/stageCache.h b/lib/mayaUsd/utils/stageCache.h index 7b32d5a157..da4a377a1e 100644 --- a/lib/mayaUsd/utils/stageCache.h +++ b/lib/mayaUsd/utils/stageCache.h @@ -16,23 +16,22 @@ #ifndef PXRUSDMAYA_STAGECACHE_H #define PXRUSDMAYA_STAGECACHE_H -#include +#include #include #include #include -#include +#include PXR_NAMESPACE_OPEN_SCOPE class UsdMayaStageCache { public: - /// Return the singleton stage cache for use by all USD clients within Maya. /// 2 stage caches are maintained; 1 for stages that have been opened with - /// UsdStage::InitialLoadSet::LoadAll, and 1 for stages that have been + /// UsdStage::InitialLoadSet::LoadAll, and 1 for stages that have been /// opened with UsdStage::InitialLoadSet::LoadNode. MAYAUSD_CORE_PUBLIC static UsdStageCache& Get(const bool loadAll); @@ -46,21 +45,18 @@ class UsdMayaStageCache /// /// The number of stages erased from the caches is returned. MAYAUSD_CORE_PUBLIC - static size_t EraseAllStagesWithRootLayerPath( - const std::string& layerPath); + static size_t EraseAllStagesWithRootLayerPath(const std::string& layerPath); /// Gets (or creates) a shared session layer tied with the given variant /// selections and draw mode on the given root path. /// The stage is cached for the lifetime of the current Maya scene. MAYAUSD_CORE_PUBLIC static SdfLayerRefPtr GetSharedSessionLayer( - const SdfPath& rootPath, - const std::map& variantSelections, - const TfToken& drawMode); + const SdfPath& rootPath, + const std::map& variantSelections, + const TfToken& drawMode); }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/mayaUsd/utils/undoHelperCommand.cpp b/lib/mayaUsd/utils/undoHelperCommand.cpp index 0f7a4bb707..ad8ceec8ce 100644 --- a/lib/mayaUsd/utils/undoHelperCommand.cpp +++ b/lib/mayaUsd/utils/undoHelperCommand.cpp @@ -22,7 +22,6 @@ // This is added to prevent multiple definitions of the MApiVersion string. #define MNoVersionString #include - #include namespace { @@ -32,16 +31,15 @@ int _registrationCount = 0; // Name of the plugin registering the command. MString _registrantPluginName; -} +} // namespace PXR_NAMESPACE_OPEN_SCOPE -const UsdMayaUndoHelperCommand::UndoableFunction* -UsdMayaUndoHelperCommand::_dgModifierFunc = nullptr; +const UsdMayaUndoHelperCommand::UndoableFunction* UsdMayaUndoHelperCommand::_dgModifierFunc + = nullptr; /* static */ -MStatus -UsdMayaUndoHelperCommand::initialize(MFnPlugin& plugin) +MStatus UsdMayaUndoHelperCommand::initialize(MFnPlugin& plugin) { if (_registrationCount < 0) { MGlobal::displayError("Illegal initialization of " CMD_NAME); @@ -56,14 +54,11 @@ UsdMayaUndoHelperCommand::initialize(MFnPlugin& plugin) _registrantPluginName = plugin.name(); return plugin.registerCommand( - CMD_NAME, - UsdMayaUndoHelperCommand::creator, - UsdMayaUndoHelperCommand::createSyntax); + CMD_NAME, UsdMayaUndoHelperCommand::creator, UsdMayaUndoHelperCommand::createSyntax); } /* static */ -MStatus -UsdMayaUndoHelperCommand::finalize(MFnPlugin& plugin) +MStatus UsdMayaUndoHelperCommand::finalize(MFnPlugin& plugin) { if (_registrationCount <= 0) { MGlobal::displayError("Illegal finalization of " CMD_NAME); @@ -80,8 +75,8 @@ UsdMayaUndoHelperCommand::finalize(MFnPlugin& plugin) // deregister. if (plugin.name() != _registrantPluginName) { MGlobal::displayWarning( - CMD_NAME " cannot be deregistered, registering plugin " - + _registrantPluginName + " is unloaded."); + CMD_NAME " cannot be deregistered, registering plugin " + _registrantPluginName + + " is unloaded."); return MS::kSuccess; } @@ -89,22 +84,16 @@ UsdMayaUndoHelperCommand::finalize(MFnPlugin& plugin) } /* static */ -const char* -UsdMayaUndoHelperCommand::name() -{ - return CMD_NAME; -} +const char* UsdMayaUndoHelperCommand::name() { return CMD_NAME; } -UsdMayaUndoHelperCommand::UsdMayaUndoHelperCommand() : _undoable(false) +UsdMayaUndoHelperCommand::UsdMayaUndoHelperCommand() + : _undoable(false) { } -UsdMayaUndoHelperCommand::~UsdMayaUndoHelperCommand() -{ -} +UsdMayaUndoHelperCommand::~UsdMayaUndoHelperCommand() { } -MStatus -UsdMayaUndoHelperCommand::doIt(const MArgList& /*args*/) +MStatus UsdMayaUndoHelperCommand::doIt(const MArgList& /*args*/) { if (!_dgModifierFunc) { _undoable = false; @@ -119,25 +108,13 @@ UsdMayaUndoHelperCommand::doIt(const MArgList& /*args*/) return MS::kSuccess; } -MStatus -UsdMayaUndoHelperCommand::redoIt() -{ - return _modifier.doIt(); -} +MStatus UsdMayaUndoHelperCommand::redoIt() { return _modifier.doIt(); } -MStatus -UsdMayaUndoHelperCommand::undoIt() -{ - return _modifier.undoIt(); -} +MStatus UsdMayaUndoHelperCommand::undoIt() { return _modifier.undoIt(); } -bool -UsdMayaUndoHelperCommand::isUndoable() const { - return _undoable; -}; +bool UsdMayaUndoHelperCommand::isUndoable() const { return _undoable; }; -MSyntax -UsdMayaUndoHelperCommand::createSyntax() +MSyntax UsdMayaUndoHelperCommand::createSyntax() { MSyntax syntax; syntax.enableQuery(false); @@ -145,21 +122,16 @@ UsdMayaUndoHelperCommand::createSyntax() return syntax; } -void* -UsdMayaUndoHelperCommand::creator() -{ - return new UsdMayaUndoHelperCommand(); -} +void* UsdMayaUndoHelperCommand::creator() { return new UsdMayaUndoHelperCommand(); } /* static */ -void -UsdMayaUndoHelperCommand::ExecuteWithUndo(const UndoableFunction& func) +void UsdMayaUndoHelperCommand::ExecuteWithUndo(const UndoableFunction& func) { int cmdExists = 0; MGlobal::executeCommand("exists " CMD_NAME, cmdExists); if (!cmdExists) { TF_WARN(CMD_NAME " is unavailable; " - "function will run without undo support"); + "function will run without undo support"); MDGModifier modifier; func(modifier); return; diff --git a/lib/mayaUsd/utils/undoHelperCommand.h b/lib/mayaUsd/utils/undoHelperCommand.h index 954c60d9a0..c9a9c20aa1 100644 --- a/lib/mayaUsd/utils/undoHelperCommand.h +++ b/lib/mayaUsd/utils/undoHelperCommand.h @@ -16,17 +16,17 @@ #ifndef PXRUSDMAYA_UNDO_HELPER_CMD_H #define PXRUSDMAYA_UNDO_HELPER_CMD_H -#include // For MFnPlugin -#include -#include -#include +#include +#include -#include #include #include +#include -#include -#include +#include // For MFnPlugin +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -38,8 +38,7 @@ PXR_NAMESPACE_OPEN_SCOPE class UsdMayaUndoHelperCommand : public MPxCommand { public: - template - using UndoableResultFunction = std::function; + template using UndoableResultFunction = std::function; using UndoableFunction = UndoableResultFunction; MAYAUSD_CORE_PUBLIC @@ -80,19 +79,16 @@ class UsdMayaUndoHelperCommand : public MPxCommand /// This overload of ExecuteWithUndo() supports a \p func that returns a /// value of type \p T. - template - static T ExecuteWithUndo(const UndoableResultFunction& func) + template static T ExecuteWithUndo(const UndoableResultFunction& func) { T result; - ExecuteWithUndo([&result, &func](MDGModifier& modifier) { - result = func(modifier); - }); + ExecuteWithUndo([&result, &func](MDGModifier& modifier) { result = func(modifier); }); return result; } private: MDGModifier _modifier; - bool _undoable; + bool _undoable; static const UndoableFunction* _dgModifierFunc; }; diff --git a/lib/mayaUsd/utils/util.cpp b/lib/mayaUsd/utils/util.cpp index 2b35f6663e..5671070021 100644 --- a/lib/mayaUsd/utils/util.cpp +++ b/lib/mayaUsd/utils/util.cpp @@ -15,21 +15,14 @@ // #include "util.h" -#include -#include -#include -#include - -#include - #include #include #include #include #include #include -#include #include +#include #include #include #include @@ -54,10 +47,19 @@ #include #include +#include + +#include +#include +#include +#include + #if MAYA_API_VERSION >= 20200000 #include #endif +#include + #include #include #include @@ -75,74 +77,58 @@ #include #include -#include - PXR_NAMESPACE_USING_DIRECTIVE namespace { - bool shouldAddToSet(const MDagPath& toAdd, const UsdMayaUtil::MDagPathSet& dagPaths) - // Utility function to check if an object should be added to the set of objects to - // export. An object should not be added if it's invalid, or if any of it's parent - // objects are already in the set. - { - if (!toAdd.isValid()) - return false; - - MStatus status = MS::kSuccess; - bool pathIsValid = true; - MDagPath dp = toAdd; +bool shouldAddToSet(const MDagPath& toAdd, const UsdMayaUtil::MDagPathSet& dagPaths) +// Utility function to check if an object should be added to the set of objects to +// export. An object should not be added if it's invalid, or if any of it's parent +// objects are already in the set. +{ + if (!toAdd.isValid()) + return false; - UsdMayaUtil::MDagPathSet::const_iterator end = dagPaths.end(); + MStatus status = MS::kSuccess; + bool pathIsValid = true; + MDagPath dp = toAdd; - // Travel up the hierarchy looking for a parent object that is already in the set. - // That is our only reason to return false. Not finding any ancestors in the set - // will eventually hit the world root, which will be an invalid path and in that case - // we just exit the loop and return true. - while (pathIsValid && status == MS::kSuccess) - { - UsdMayaUtil::MDagPathSet::const_iterator dpIter = dagPaths.find(dp); - if (dpIter != end) - return false; + UsdMayaUtil::MDagPathSet::const_iterator end = dagPaths.end(); - status = dp.pop(); - pathIsValid = dp.isValid(); - } + // Travel up the hierarchy looking for a parent object that is already in the set. + // That is our only reason to return false. Not finding any ancestors in the set + // will eventually hit the world root, which will be an invalid path and in that case + // we just exit the loop and return true. + while (pathIsValid && status == MS::kSuccess) { + UsdMayaUtil::MDagPathSet::const_iterator dpIter = dagPaths.find(dp); + if (dpIter != end) + return false; - return true; + status = dp.pop(); + pathIsValid = dp.isValid(); } + + return true; } +} // namespace -double -UsdMayaUtil::ConvertMDistanceUnitToUsdGeomLinearUnit( - const MDistance::Unit mdistanceUnit) +double UsdMayaUtil::ConvertMDistanceUnitToUsdGeomLinearUnit(const MDistance::Unit mdistanceUnit) { switch (mdistanceUnit) { - case MDistance::kInches: - return UsdGeomLinearUnits::inches; - case MDistance::kFeet: - return UsdGeomLinearUnits::feet; - case MDistance::kYards: - return UsdGeomLinearUnits::yards; - case MDistance::kMiles: - return UsdGeomLinearUnits::miles; - case MDistance::kMillimeters: - return UsdGeomLinearUnits::millimeters; - case MDistance::kCentimeters: - return UsdGeomLinearUnits::centimeters; - case MDistance::kKilometers: - return UsdGeomLinearUnits::kilometers; - case MDistance::kMeters: - return UsdGeomLinearUnits::meters; - default: - TF_CODING_ERROR("Invalid MDistance unit %d. Assuming centimeters", - mdistanceUnit); - return UsdGeomLinearUnits::centimeters; - } -} - -MDistance::Unit -UsdMayaUtil::ConvertUsdGeomLinearUnitToMDistanceUnit( - const double linearUnit) + case MDistance::kInches: return UsdGeomLinearUnits::inches; + case MDistance::kFeet: return UsdGeomLinearUnits::feet; + case MDistance::kYards: return UsdGeomLinearUnits::yards; + case MDistance::kMiles: return UsdGeomLinearUnits::miles; + case MDistance::kMillimeters: return UsdGeomLinearUnits::millimeters; + case MDistance::kCentimeters: return UsdGeomLinearUnits::centimeters; + case MDistance::kKilometers: return UsdGeomLinearUnits::kilometers; + case MDistance::kMeters: return UsdGeomLinearUnits::meters; + default: + TF_CODING_ERROR("Invalid MDistance unit %d. Assuming centimeters", mdistanceUnit); + return UsdGeomLinearUnits::centimeters; + } +} + +MDistance::Unit UsdMayaUtil::ConvertUsdGeomLinearUnitToMDistanceUnit(const double linearUnit) { if (UsdGeomLinearUnitsAre(linearUnit, UsdGeomLinearUnits::millimeters)) { return MDistance::kMillimeters; @@ -169,13 +155,11 @@ UsdMayaUtil::ConvertUsdGeomLinearUnitToMDistanceUnit( return MDistance::kMiles; } - TF_CODING_ERROR("Invalid UsdGeomLinearUnit %f. Assuming centimeters", - linearUnit); + TF_CODING_ERROR("Invalid UsdGeomLinearUnit %f. Assuming centimeters", linearUnit); return MDistance::kCentimeters; } -std::string -UsdMayaUtil::GetMayaNodeName(const MObject& mayaNode) +std::string UsdMayaUtil::GetMayaNodeName(const MObject& mayaNode) { MString nodeName; MStatus status; @@ -201,11 +185,10 @@ UsdMayaUtil::GetMayaNodeName(const MObject& mayaNode) return nodeName.asChar(); } -MStatus -UsdMayaUtil::GetMObjectByName(const std::string& nodeName, MObject& mObj) +MStatus UsdMayaUtil::GetMObjectByName(const std::string& nodeName, MObject& mObj) { MSelectionList selectionList; - MStatus status = selectionList.add(MString(nodeName.c_str())); + MStatus status = selectionList.add(MString(nodeName.c_str())); if (status != MS::kSuccess) { return status; } @@ -215,11 +198,10 @@ UsdMayaUtil::GetMObjectByName(const std::string& nodeName, MObject& mObj) return status; } -MStatus -UsdMayaUtil::GetDagPathByName(const std::string& nodeName, MDagPath& dagPath) +MStatus UsdMayaUtil::GetDagPathByName(const std::string& nodeName, MDagPath& dagPath) { MSelectionList selectionList; - MStatus status = selectionList.add(MString(nodeName.c_str())); + MStatus status = selectionList.add(MString(nodeName.c_str())); if (status != MS::kSuccess) { return status; } @@ -229,13 +211,11 @@ UsdMayaUtil::GetDagPathByName(const std::string& nodeName, MDagPath& dagPath) return status; } -MStatus -UsdMayaUtil::GetPlugByName(const std::string& attrPath, MPlug& plug) +MStatus UsdMayaUtil::GetPlugByName(const std::string& attrPath, MPlug& plug) { std::vector comps = TfStringSplit(attrPath, "."); if (comps.size() != 2) { - TF_RUNTIME_ERROR("'%s' is not a valid Maya attribute path", - attrPath.c_str()); + TF_RUNTIME_ERROR("'%s' is not a valid Maya attribute path", attrPath.c_str()); return MStatus::kFailure; } @@ -259,10 +239,9 @@ UsdMayaUtil::GetPlugByName(const std::string& attrPath, MPlug& plug) return status; } -MPlug -UsdMayaUtil::GetMayaTimePlug() +MPlug UsdMayaUtil::GetMayaTimePlug() { - MPlug timePlug; + MPlug timePlug; MStatus status; // As an extra sanity check, we only return a discovered plug if its @@ -296,10 +275,9 @@ UsdMayaUtil::GetMayaTimePlug() return timePlug; } -MPlug -UsdMayaUtil::GetMayaShaderListPlug() +MPlug UsdMayaUtil::GetMayaShaderListPlug() { - MPlug shadersPlug; + MPlug shadersPlug; MStatus status; MItDependencyNodes iter(MFn::kShaderList, &status); @@ -325,8 +303,7 @@ UsdMayaUtil::GetMayaShaderListPlug() return shadersPlug; } -MObject -UsdMayaUtil::GetDefaultLightSetObject() +MObject UsdMayaUtil::GetDefaultLightSetObject() { MObject node; MStatus status; @@ -334,7 +311,7 @@ UsdMayaUtil::GetDefaultLightSetObject() MItDependencyNodes setIter(MFn::kSet, &status); CHECK_MSTATUS_AND_RETURN(status, node); - while(!setIter.isDone()) { + while (!setIter.isDone()) { node = setIter.thisNode(); setIter.next(); @@ -351,10 +328,7 @@ UsdMayaUtil::GetDefaultLightSetObject() return node; } -bool -UsdMayaUtil::isAncestorDescendentRelationship( - const MDagPath& path1, - const MDagPath& path2) +bool UsdMayaUtil::isAncestorDescendentRelationship(const MDagPath& path1, const MDagPath& path2) { unsigned int length1 = path1.length(); unsigned int length2 = path2.length(); @@ -363,14 +337,11 @@ UsdMayaUtil::isAncestorDescendentRelationship( if (length1 == length2 && !(path1 == path2)) return false; MDagPath ancestor, descendent; - if (length1 > length2) - { + if (length1 > length2) { ancestor = path2; descendent = path1; diff = length1 - length2; - } - else - { + } else { ancestor = path1; descendent = path2; diff = length2 - length1; @@ -382,10 +353,7 @@ UsdMayaUtil::isAncestorDescendentRelationship( } // returns 0 if static, 1 if sampled, and 2 if a curve -int -UsdMayaUtil::getSampledType( - const MPlug& iPlug, - const bool includeConnectedChildren) +int UsdMayaUtil::getSampledType(const MPlug& iPlug, const bool includeConnectedChildren) { MPlugArray conns; @@ -393,28 +361,21 @@ UsdMayaUtil::getSampledType( // it's possible that only some element of an array plug or // some component of a compound plus is connected - if (conns.length() == 0) - { - if (iPlug.isArray()) - { + if (conns.length() == 0) { + if (iPlug.isArray()) { unsigned int numConnectedElements = iPlug.numConnectedElements(); - for (unsigned int e = 0; e < numConnectedElements; e++) - { + for (unsigned int e = 0; e < numConnectedElements; e++) { // For now we assume that when you encounter an array of plugs, // we always want to include connected children. - int retVal = getSampledType(iPlug.connectionByPhysicalIndex(e), - true); + int retVal = getSampledType(iPlug.connectionByPhysicalIndex(e), true); if (retVal > 0) { return retVal; } } - } - else if (iPlug.isCompound() && iPlug.numConnectedChildren() > 0 - && includeConnectedChildren) - { + } else if ( + iPlug.isCompound() && iPlug.numConnectedChildren() > 0 && includeConnectedChildren) { unsigned int numChildren = iPlug.numChildren(); - for (unsigned int c = 0; c < numChildren; c++) - { + for (unsigned int c = 0; c < numChildren; c++) { int retVal = getSampledType(iPlug.child(c), true); if (retVal > 0) return retVal; @@ -423,49 +384,42 @@ UsdMayaUtil::getSampledType( return 0; } - MObject ob; + MObject ob; MFnDependencyNode nodeFn; - for (unsigned i = 0; i < conns.length(); i++) - { + for (unsigned i = 0; i < conns.length(); i++) { ob = conns[i].node(); MFn::Type type = ob.apiType(); - switch (type) - { - case MFn::kAnimCurveTimeToAngular: - case MFn::kAnimCurveTimeToDistance: - case MFn::kAnimCurveTimeToTime: - case MFn::kAnimCurveTimeToUnitless: - { - nodeFn.setObject(ob); - MPlug incoming = nodeFn.findPlug("i", true); - - // sampled - if (incoming.isConnected()) - return 1; - - // curve - else - return 2; - } - break; + switch (type) { + case MFn::kAnimCurveTimeToAngular: + case MFn::kAnimCurveTimeToDistance: + case MFn::kAnimCurveTimeToTime: + case MFn::kAnimCurveTimeToUnitless: { + nodeFn.setObject(ob); + MPlug incoming = nodeFn.findPlug("i", true); - case MFn::kMute: - { - nodeFn.setObject(ob); - MPlug mutePlug = nodeFn.findPlug("mute", true); - - // static - if (mutePlug.asBool()) - return 0; - // curve - else - return 2; - } - break; + // sampled + if (incoming.isConnected()) + return 1; - default: - break; + // curve + else + return 2; + } break; + + case MFn::kMute: { + nodeFn.setObject(ob); + MPlug mutePlug = nodeFn.findPlug("mute", true); + + // static + if (mutePlug.asBool()) + return 0; + // curve + else + return 2; + } break; + + default: break; } } @@ -473,14 +427,13 @@ UsdMayaUtil::getSampledType( } // does this cover all cases? -bool -UsdMayaUtil::isAnimated(const MObject& mayaObject, const bool checkParent) +bool UsdMayaUtil::isAnimated(const MObject& mayaObject, const bool checkParent) { // MItDependencyGraph takes a non-const MObject as a constructor parameter, // so we have to make a copy of mayaObject here. MObject mayaObjectCopy(mayaObject); - MStatus status; + MStatus status; MItDependencyGraph iter( mayaObjectCopy, MFn::kInvalid, @@ -490,8 +443,7 @@ UsdMayaUtil::isAnimated(const MObject& mayaObject, const bool checkParent) &status); if (status != MS::kSuccess) { TF_RUNTIME_ERROR( - "Unable to create DG iterator for Maya node '%s'", - GetMayaNodeName(mayaObject).c_str()); + "Unable to create DG iterator for Maya node '%s'", GetMayaNodeName(mayaObject).c_str()); } // MAnimUtil::isAnimated(node) will search the history of the node @@ -504,28 +456,16 @@ UsdMayaUtil::isAnimated(const MObject& mayaObject, const bool checkParent) for (; !iter.isDone(); iter.next()) { MObject node = iter.thisNode(); - if (node.hasFn(MFn::kPluginDependNode) || - node.hasFn(MFn::kConstraint) || - node.hasFn(MFn::kPointConstraint) || - node.hasFn(MFn::kAimConstraint) || - node.hasFn(MFn::kOrientConstraint) || - node.hasFn(MFn::kScaleConstraint) || - node.hasFn(MFn::kGeometryConstraint) || - node.hasFn(MFn::kNormalConstraint) || - node.hasFn(MFn::kTangentConstraint) || - node.hasFn(MFn::kParentConstraint) || - node.hasFn(MFn::kPoleVectorConstraint) || - node.hasFn(MFn::kParentConstraint) || - node.hasFn(MFn::kTime) || - node.hasFn(MFn::kJoint) || - node.hasFn(MFn::kGeometryFilt) || - node.hasFn(MFn::kTweak) || - node.hasFn(MFn::kPolyTweak) || - node.hasFn(MFn::kSubdTweak) || - node.hasFn(MFn::kCluster) || - node.hasFn(MFn::kFluid) || - node.hasFn(MFn::kPolyBoolOp)) - { + if (node.hasFn(MFn::kPluginDependNode) || node.hasFn(MFn::kConstraint) + || node.hasFn(MFn::kPointConstraint) || node.hasFn(MFn::kAimConstraint) + || node.hasFn(MFn::kOrientConstraint) || node.hasFn(MFn::kScaleConstraint) + || node.hasFn(MFn::kGeometryConstraint) || node.hasFn(MFn::kNormalConstraint) + || node.hasFn(MFn::kTangentConstraint) || node.hasFn(MFn::kParentConstraint) + || node.hasFn(MFn::kPoleVectorConstraint) || node.hasFn(MFn::kParentConstraint) + || node.hasFn(MFn::kTime) || node.hasFn(MFn::kJoint) || node.hasFn(MFn::kGeometryFilt) + || node.hasFn(MFn::kTweak) || node.hasFn(MFn::kPolyTweak) || node.hasFn(MFn::kSubdTweak) + || node.hasFn(MFn::kCluster) || node.hasFn(MFn::kFluid) + || node.hasFn(MFn::kPolyBoolOp)) { return true; } @@ -548,8 +488,7 @@ UsdMayaUtil::isAnimated(const MObject& mayaObject, const bool checkParent) return false; } -bool -UsdMayaUtil::isPlugAnimated(const MPlug& plug) +bool UsdMayaUtil::isPlugAnimated(const MPlug& plug) { if (plug.isNull()) { return false; @@ -566,8 +505,7 @@ UsdMayaUtil::isPlugAnimated(const MPlug& plug) return false; } -bool -UsdMayaUtil::isIntermediate(const MObject& object) +bool UsdMayaUtil::isIntermediate(const MObject& object) { MStatus status; @@ -584,10 +522,9 @@ UsdMayaUtil::isIntermediate(const MObject& object) return isIntermediateObj; } -bool -UsdMayaUtil::isRenderable(const MObject& object) +bool UsdMayaUtil::isRenderable(const MObject& object) { - MStatus stat; + MStatus stat; MFnDagNode mFn(object); // templated turned on? return false @@ -597,27 +534,23 @@ UsdMayaUtil::isRenderable(const MObject& object) // visibility or lodVisibility off? return false plug = mFn.findPlug("visibility", false, &stat); - if (stat == MS::kSuccess && !plug.asBool()) - { + if (stat == MS::kSuccess && !plug.asBool()) { // the value is off. let's check if it has any in-connection, // otherwise, it means it is not animated. MPlugArray arrayIn; plug.connectedTo(arrayIn, true, false, &stat); - if (stat == MS::kSuccess && arrayIn.length() == 0) - { + if (stat == MS::kSuccess && arrayIn.length() == 0) { return false; } } plug = mFn.findPlug("lodVisibility", false, &stat); - if (stat == MS::kSuccess && !plug.asBool()) - { + if (stat == MS::kSuccess && !plug.asBool()) { MPlugArray arrayIn; plug.connectedTo(arrayIn, true, false, &stat); - if (stat == MS::kSuccess && arrayIn.length() == 0) - { + if (stat == MS::kSuccess && arrayIn.length() == 0) { return false; } } @@ -626,8 +559,7 @@ UsdMayaUtil::isRenderable(const MObject& object) return true; } -bool -UsdMayaUtil::isWritable(const MObject& object) +bool UsdMayaUtil::isWritable(const MObject& object) { MStatus status; @@ -649,8 +581,7 @@ UsdMayaUtil::isWritable(const MObject& object) return (!isDefaultNode && canBeWritten); } -std::string -UsdMayaUtil::stripNamespaces(const std::string& nodeName, const int nsDepth) +std::string UsdMayaUtil::stripNamespaces(const std::string& nodeName, const int nsDepth) { if (nodeName.empty() || nsDepth == 0) { return nodeName; @@ -658,11 +589,10 @@ UsdMayaUtil::stripNamespaces(const std::string& nodeName, const int nsDepth) std::stringstream ss; - const std::vector nodeNameParts = - TfStringSplit(nodeName, UsdMayaUtil::MayaDagDelimiter); + const std::vector nodeNameParts + = TfStringSplit(nodeName, UsdMayaUtil::MayaDagDelimiter); - const bool isAbsolute = - TfStringStartsWith(nodeName, UsdMayaUtil::MayaDagDelimiter); + const bool isAbsolute = TfStringStartsWith(nodeName, UsdMayaUtil::MayaDagDelimiter); for (size_t i = 0u; i < nodeNameParts.size(); ++i) { if (i == 0u && isAbsolute) { @@ -676,10 +606,8 @@ UsdMayaUtil::stripNamespaces(const std::string& nodeName, const int nsDepth) ss << UsdMayaUtil::MayaDagDelimiter; } - const std::vector nsNameParts = - TfStringSplit( - nodeNameParts[i], - UsdMayaUtil::MayaNamespaceDelimiter); + const std::vector nsNameParts + = TfStringSplit(nodeNameParts[i], UsdMayaUtil::MayaNamespaceDelimiter); const size_t nodeNameIndex = nsNameParts.size() - 1u; @@ -696,28 +624,24 @@ UsdMayaUtil::stripNamespaces(const std::string& nodeName, const int nsDepth) } ss << TfStringJoin( - startIter, - nsNameParts.end(), - UsdMayaUtil::MayaNamespaceDelimiter.c_str()); + startIter, nsNameParts.end(), UsdMayaUtil::MayaNamespaceDelimiter.c_str()); } return ss.str(); } -std::string -UsdMayaUtil::SanitizeName(const std::string& name) +std::string UsdMayaUtil::SanitizeName(const std::string& name) { return TfStringReplace(name, ":", "_"); } // This to allow various pipeline to sanitize the colorset name for output -std::string -UsdMayaUtil::SanitizeColorSetName(const std::string& name) +std::string UsdMayaUtil::SanitizeColorSetName(const std::string& name) { // We sanitize the name since certain pipeline like Pixar's, we have rman_ // in front of all color sets that need to be exportred. We now export all // colorsets. - size_t namePos = 0u; + size_t namePos = 0u; static const std::string RMAN_PREFIX("rman_"); if (name.find(RMAN_PREFIX) == 0) { namePos = RMAN_PREFIX.size(); @@ -733,15 +657,13 @@ UsdMayaUtil::SanitizeColorSetName(const std::string& name) // numComponents, with values indexing into shaderObjs. // When numComponents is zero, shaderObjs will be of length 1 and // assignmentIndices will be empty. -static -bool -_getAttachedMayaShaderObjects( - const MFnDagNode& node, - const unsigned int numComponents, - MObjectArray* shaderObjs, - VtIntArray* assignmentIndices) -{ - bool hasShader=false; +static bool _getAttachedMayaShaderObjects( + const MFnDagNode& node, + const unsigned int numComponents, + MObjectArray* shaderObjs, + VtIntArray* assignmentIndices) +{ + bool hasShader = false; MStatus status; // This structure maps shader object names to their indices in the @@ -754,22 +676,22 @@ _getAttachedMayaShaderObjects( MObjectArray setObjs; MObjectArray compObjs; - node.getConnectedSetsAndMembers(0, setObjs, compObjs, true); // Assuming that not using instancing + node.getConnectedSetsAndMembers( + 0, setObjs, compObjs, true); // Assuming that not using instancing // If we have multiple components and either multiple sets or one set with // only a subset of the object in it, we'll keep track of the assignments // for all components in assignmentIndices. We initialize all of the // assignments as unassigned using a value of -1. - if (numComponents > 1 && - (setObjs.length() > 1 || - (setObjs.length() == 1 && !compObjs[0].isNull()))) { + if (numComponents > 1 + && (setObjs.length() > 1 || (setObjs.length() == 1 && !compObjs[0].isNull()))) { assignmentIndices->assign((size_t)numComponents, -1); } - for (unsigned int i=0; i < setObjs.length(); ++i) { + for (unsigned int i = 0; i < setObjs.length(); ++i) { // Get associated Set and Shading Group MFnSet setFn(setObjs[i], &status); - MPlug seSurfaceShaderPlg = setFn.findPlug("surfaceShader", true, &status); + MPlug seSurfaceShaderPlg = setFn.findPlug("surfaceShader", true, &status); // Find connection shader->shadingGroup MPlugArray plgCons; @@ -779,12 +701,11 @@ _getAttachedMayaShaderObjects( } hasShader = true; - MPlug shaderPlug = plgCons[0]; + MPlug shaderPlug = plgCons[0]; MObject shaderObj = shaderPlug.node(); auto inserted = shaderPlugsMap.insert( - std::pair(shaderPlug.name().asChar(), - shaderObjs->length())); + std::pair(shaderPlug.name().asChar(), shaderObjs->length())); if (inserted.second) { shaderObjs->append(shaderObj); } @@ -804,19 +725,15 @@ _getAttachedMayaShaderObjects( return hasShader; } -bool -_GetColorAndTransparencyFromLambert( - const MObject& shaderObj, - GfVec3f* rgb, - float* alpha) +bool _GetColorAndTransparencyFromLambert(const MObject& shaderObj, GfVec3f* rgb, float* alpha) { - MStatus status; + MStatus status; MFnLambertShader lambertFn(shaderObj, &status); - if (status == MS::kSuccess ) { + if (status == MS::kSuccess) { if (rgb) { GfVec3f displayColor; - MColor color = lambertFn.color(); - for (int j=0;j<3;j++) { + MColor color = lambertFn.color(); + for (int j = 0; j < 3; j++) { displayColor[j] = color[j]; } displayColor *= lambertFn.diffuseCoeff(); @@ -834,20 +751,19 @@ _GetColorAndTransparencyFromLambert( return false; } -bool -_GetColorAndTransparencyFromStandardSurface( - const MObject& shaderObj, - GfVec3f* rgb, - float* alpha) +bool _GetColorAndTransparencyFromStandardSurface( + const MObject& shaderObj, + GfVec3f* rgb, + float* alpha) { #if MAYA_API_VERSION >= 20200000 - MStatus status; + MStatus status; MFnStandardSurfaceShader surfaceFn(shaderObj, &status); - if (status == MS::kSuccess ) { + if (status == MS::kSuccess) { if (rgb) { GfVec3f displayColor; - MColor color = surfaceFn.baseColor(); - for (int j=0;j<3;j++) { + MColor color = surfaceFn.baseColor(); + for (int j = 0; j < 3; j++) { displayColor[j] = color[j]; } displayColor *= surfaceFn.base(); @@ -862,13 +778,9 @@ _GetColorAndTransparencyFromStandardSurface( return false; } -bool -_GetColorAndTransparencyFromDepNode( - const MObject& shaderObj, - GfVec3f* rgb, - float* alpha) +bool _GetColorAndTransparencyFromDepNode(const MObject& shaderObj, GfVec3f* rgb, float* alpha) { - MStatus status; + MStatus status; MFnDependencyNode d(shaderObj); if (rgb) { MPlug colorPlug = d.findPlug("color", true, &status); @@ -880,7 +792,7 @@ _GetColorAndTransparencyFromDepNode( } } GfVec3f displayColor; - for (int j=0; j<3; j++) { + for (int j = 0; j < 3; j++) { colorPlug.child(j).getValue(displayColor[j]); } *rgb = UsdMayaColorSpace::ConvertMayaToLinear(displayColor); @@ -890,10 +802,10 @@ _GetColorAndTransparencyFromDepNode( MPlug transparencyPlug = d.findPlug("transparency", true, &status); if (status) { float trans = 0.f; - for (int j=0; j<3; j++) { + for (int j = 0; j < 3; j++) { float t = 0.f; transparencyPlug.child(j).getValue(t); - trans += t/3.f; + trans += t / 3.f; } *alpha = 1.f - trans; } else { @@ -908,12 +820,8 @@ _GetColorAndTransparencyFromDepNode( return true; } -static -bool -_getMayaShadersColor( - const MObjectArray& shaderObjs, - VtVec3fArray* RGBData, - VtFloatArray* AlphaData) +static bool +_getMayaShadersColor(const MObjectArray& shaderObjs, VtVec3fArray* RGBData, VtFloatArray* AlphaData) { if (shaderObjs.length() == 0u) { return false; @@ -949,21 +857,20 @@ _getMayaShadersColor( // First, we assume the shader is a lambert and try that API. If not, // we try our next best guess. - const bool gotShaderValues = - _GetColorAndTransparencyFromLambert( - shaderObjs[i], - RGBData ? &(*RGBData)[i] : nullptr, - AlphaData ? &(*AlphaData)[i] : nullptr) + const bool gotShaderValues = _GetColorAndTransparencyFromLambert( + shaderObjs[i], + RGBData ? &(*RGBData)[i] : nullptr, + AlphaData ? &(*AlphaData)[i] : nullptr) || _GetColorAndTransparencyFromStandardSurface( - shaderObjs[i], - RGBData ? &(*RGBData)[i] : nullptr, - AlphaData ? &(*AlphaData)[i] : nullptr) + shaderObjs[i], + RGBData ? &(*RGBData)[i] : nullptr, + AlphaData ? &(*AlphaData)[i] : nullptr) || _GetColorAndTransparencyFromDepNode( - shaderObjs[i], - RGBData ? &(*RGBData)[i] : nullptr, - AlphaData ? &(*AlphaData)[i] : nullptr); + shaderObjs[i], + RGBData ? &(*RGBData)[i] : nullptr, + AlphaData ? &(*AlphaData)[i] : nullptr); gotValues |= gotShaderValues; } @@ -971,19 +878,17 @@ _getMayaShadersColor( return gotValues; } -static -bool -_GetLinearShaderColor( - const MFnDagNode& node, - const unsigned int numComponents, - VtVec3fArray* RGBData, - VtFloatArray* AlphaData, - TfToken* interpolation, - VtIntArray* assignmentIndices) +static bool _GetLinearShaderColor( + const MFnDagNode& node, + const unsigned int numComponents, + VtVec3fArray* RGBData, + VtFloatArray* AlphaData, + TfToken* interpolation, + VtIntArray* assignmentIndices) { MObjectArray shaderObjs; - bool hasAttachedShader = _getAttachedMayaShaderObjects( - node, numComponents, &shaderObjs, assignmentIndices); + bool hasAttachedShader + = _getAttachedMayaShaderObjects(node, numComponents, &shaderObjs, assignmentIndices); if (hasAttachedShader) { _getMayaShadersColor(shaderObjs, RGBData, AlphaData); } @@ -999,75 +904,51 @@ _GetLinearShaderColor( return hasAttachedShader; } -bool -UsdMayaUtil::GetLinearShaderColor( - const MFnDagNode& node, - VtVec3fArray* RGBData, - VtFloatArray* AlphaData, - TfToken* interpolation, - VtIntArray* assignmentIndices) +bool UsdMayaUtil::GetLinearShaderColor( + const MFnDagNode& node, + VtVec3fArray* RGBData, + VtFloatArray* AlphaData, + TfToken* interpolation, + VtIntArray* assignmentIndices) { - return _GetLinearShaderColor(node, - 0, - RGBData, - AlphaData, - interpolation, - assignmentIndices); + return _GetLinearShaderColor(node, 0, RGBData, AlphaData, interpolation, assignmentIndices); } -bool -UsdMayaUtil::GetLinearShaderColor( - const MFnMesh& mesh, - VtVec3fArray* RGBData, - VtFloatArray* AlphaData, - TfToken* interpolation, - VtIntArray* assignmentIndices) +bool UsdMayaUtil::GetLinearShaderColor( + const MFnMesh& mesh, + VtVec3fArray* RGBData, + VtFloatArray* AlphaData, + TfToken* interpolation, + VtIntArray* assignmentIndices) { unsigned int numComponents = mesh.numPolygons(); - return _GetLinearShaderColor(mesh, - numComponents, - RGBData, - AlphaData, - interpolation, - assignmentIndices); + return _GetLinearShaderColor( + mesh, numComponents, RGBData, AlphaData, interpolation, assignmentIndices); } namespace { -template -struct _ValuesHash +template struct _ValuesHash { - std::size_t operator() (const T& value) const { - return hash_value(value); - } + std::size_t operator()(const T& value) const { return hash_value(value); } }; // There is no globally defined hash_value for numeric types // so we need an explicit opt-in here. -template <> -struct _ValuesHash +template <> struct _ValuesHash { - std::size_t operator() (const float& value) const { - return boost::hash_value(value); - } + std::size_t operator()(const float& value) const { return boost::hash_value(value); } }; -template -struct _ValuesEqual +template struct _ValuesEqual { - bool operator() (const T& a, const T& b) const { - return GfIsClose(a, b, 1e-9); - } + bool operator()(const T& a, const T& b) const { return GfIsClose(a, b, 1e-9); } }; } // anonymous namespace template -static -void -_MergeEquivalentIndexedValues( - VtArray* valueData, - VtIntArray* assignmentIndices) +static void _MergeEquivalentIndexedValues(VtArray* valueData, VtIntArray* assignmentIndices) { if (!valueData || !assignmentIndices) { return; @@ -1080,9 +961,9 @@ _MergeEquivalentIndexedValues( // We maintain a map of values to that value's index in our uniqueValues // array. - std::unordered_map, _ValuesEqual > valuesMap; - VtArray uniqueValues; - VtIntArray uniqueIndices; + std::unordered_map, _ValuesEqual> valuesMap; + VtArray uniqueValues; + VtIntArray uniqueIndices; for (int index : *assignmentIndices) { if (index < 0 || static_cast(index) >= numValues) { @@ -1095,8 +976,7 @@ _MergeEquivalentIndexedValues( int uniqueIndex = -1; - auto inserted = valuesMap.insert( - std::pair(value, uniqueValues.size())); + auto inserted = valuesMap.insert(std::pair(value, uniqueValues.size())); if (inserted.second) { // This is a new value, so add it to the array. uniqueValues.push_back(value); @@ -1116,53 +996,50 @@ _MergeEquivalentIndexedValues( } } -void -UsdMayaUtil::MergeEquivalentIndexedValues( - VtFloatArray* valueData, - VtIntArray* assignmentIndices) { +void UsdMayaUtil::MergeEquivalentIndexedValues( + VtFloatArray* valueData, + VtIntArray* assignmentIndices) +{ return _MergeEquivalentIndexedValues(valueData, assignmentIndices); } -void -UsdMayaUtil::MergeEquivalentIndexedValues( - VtVec2fArray* valueData, - VtIntArray* assignmentIndices) { +void UsdMayaUtil::MergeEquivalentIndexedValues( + VtVec2fArray* valueData, + VtIntArray* assignmentIndices) +{ return _MergeEquivalentIndexedValues(valueData, assignmentIndices); } -void -UsdMayaUtil::MergeEquivalentIndexedValues( - VtVec3fArray* valueData, - VtIntArray* assignmentIndices) { +void UsdMayaUtil::MergeEquivalentIndexedValues( + VtVec3fArray* valueData, + VtIntArray* assignmentIndices) +{ return _MergeEquivalentIndexedValues(valueData, assignmentIndices); } -void -UsdMayaUtil::MergeEquivalentIndexedValues( - VtVec4fArray* valueData, - VtIntArray* assignmentIndices) { +void UsdMayaUtil::MergeEquivalentIndexedValues( + VtVec4fArray* valueData, + VtIntArray* assignmentIndices) +{ return _MergeEquivalentIndexedValues(valueData, assignmentIndices); } -void -UsdMayaUtil::CompressFaceVaryingPrimvarIndices( - const MFnMesh& mesh, - TfToken* interpolation, - VtIntArray* assignmentIndices) +void UsdMayaUtil::CompressFaceVaryingPrimvarIndices( + const MFnMesh& mesh, + TfToken* interpolation, + VtIntArray* assignmentIndices) { - if (!interpolation || - !assignmentIndices || - assignmentIndices->size() == 0u) { + if (!interpolation || !assignmentIndices || assignmentIndices->size() == 0u) { return; } // Use -2 as the initial "un-stored" sentinel value, since -1 is the // default unauthored value index for primvars. - int numPolygons = mesh.numPolygons(); + int numPolygons = mesh.numPolygons(); VtIntArray uniformAssignments; uniformAssignments.assign((size_t)numPolygons, -2); - int numVertices = mesh.numVertices(); + int numVertices = mesh.numVertices(); VtIntArray vertexAssignments; vertexAssignments.assign((size_t)numVertices, -2); @@ -1173,7 +1050,7 @@ UsdMayaUtil::CompressFaceVaryingPrimvarIndices( bool isVertex = true; MItMeshFaceVertex itFV(mesh.object()); - unsigned int fvi = 0; + unsigned int fvi = 0; for (itFV.reset(); !itFV.isDone(); itFV.next(), ++fvi) { int faceIndex = itFV.faceId(); int vertexIndex = itFV.vertId(); @@ -1216,7 +1093,7 @@ UsdMayaUtil::CompressFaceVaryingPrimvarIndices( } else if (isUniform) { *assignmentIndices = uniformAssignments; *interpolation = UsdGeomTokens->uniform; - } else if(isVertex) { + } else if (isVertex) { *assignmentIndices = vertexAssignments; *interpolation = UsdGeomTokens->vertex; } else { @@ -1224,8 +1101,7 @@ UsdMayaUtil::CompressFaceVaryingPrimvarIndices( } } -bool -UsdMayaUtil::IsAuthored(const MPlug& plug) +bool UsdMayaUtil::IsAuthored(const MPlug& plug) { MStatus status; @@ -1258,10 +1134,9 @@ UsdMayaUtil::IsAuthored(const MPlug& plug) return false; } -MPlug -UsdMayaUtil::GetConnected(const MPlug& plug) +MPlug UsdMayaUtil::GetConnected(const MPlug& plug) { - MStatus status = MS::kFailure; + MStatus status = MS::kFailure; MPlugArray conn; plug.connectedTo(conn, true, false, &status); if (!status || conn.length() != 1) { @@ -1270,19 +1145,15 @@ UsdMayaUtil::GetConnected(const MPlug& plug) return conn[0]; } -void -UsdMayaUtil::Connect( - const MPlug& srcPlug, - const MPlug& dstPlug, - const bool clearDstPlug) +void UsdMayaUtil::Connect(const MPlug& srcPlug, const MPlug& dstPlug, const bool clearDstPlug) { - MStatus status; + MStatus status; MDGModifier dgMod; if (clearDstPlug) { MPlugArray plgCons; dstPlug.connectedTo(plgCons, true, false, &status); - for (unsigned int i=0; i < plgCons.length(); ++i) { + for (unsigned int i = 0; i < plgCons.length(); ++i) { status = dgMod.disconnect(plgCons[i], dstPlug); } } @@ -1292,23 +1163,21 @@ UsdMayaUtil::Connect( dgMod.doIt(); } -MPlug -UsdMayaUtil::FindChildPlugByName(const MPlug& plug, const MString& name) +MPlug UsdMayaUtil::FindChildPlugByName(const MPlug& plug, const MString& name) { unsigned int numChildren = plug.numChildren(); - for(unsigned int i = 0; i < numChildren; ++i) { + for (unsigned int i = 0; i < numChildren; ++i) { MPlug child = plug.child(i); // We can't get at the name of just the *component* // plug.name() gives us node.plug[index].compound, etc. // partialName() also has no form that just gives us the name. MString childName = child.name(); - if(childName.length() > name.length()) { + if (childName.length() > name.length()) { int index = childName.rindex('.'); - if(index >= 0) { - MString childSuffix = - childName.substring(index+1, childName.length()); - if(childSuffix == name) { + if (index >= 0) { + MString childSuffix = childName.substring(index + 1, childName.length()); + if (childSuffix == name) { return child; } } @@ -1319,9 +1188,7 @@ UsdMayaUtil::FindChildPlugByName(const MPlug& plug, const MString& name) // XXX: see logic in UsdMayaTransformWriter. It's unfortunate that this // logic is in 2 places. we should merge. -static -bool -_IsShape(const MDagPath& dagPath) +static bool _IsShape(const MDagPath& dagPath) { if (dagPath.hasFn(MFn::kTransform)) { return false; @@ -1339,10 +1206,7 @@ _IsShape(const MDagPath& dagPath) return (numberOfShapesDirectlyBelow == 1); } -SdfPath -UsdMayaUtil::MayaNodeNameToSdfPath( - const std::string& nodeName, - const bool stripNamespaces) +SdfPath UsdMayaUtil::MayaNodeNameToSdfPath(const std::string& nodeName, const bool stripNamespaces) { std::string pathString = nodeName; @@ -1356,25 +1220,18 @@ UsdMayaUtil::MayaNodeNameToSdfPath( pathString.end(), UsdMayaUtil::MayaDagDelimiter[0], SdfPathTokens->childDelimiter.GetString()[0]); - std::replace( - pathString.begin(), - pathString.end(), - UsdMayaUtil::MayaNamespaceDelimiter[0], - '_'); + std::replace(pathString.begin(), pathString.end(), UsdMayaUtil::MayaNamespaceDelimiter[0], '_'); return SdfPath(pathString); } -SdfPath -UsdMayaUtil::MDagPathToUsdPath( - const MDagPath& dagPath, - const bool mergeTransformAndShape, - const bool stripNamespaces) +SdfPath UsdMayaUtil::MDagPathToUsdPath( + const MDagPath& dagPath, + const bool mergeTransformAndShape, + const bool stripNamespaces) { - SdfPath usdPath = - UsdMayaUtil::MayaNodeNameToSdfPath( - dagPath.fullPathName().asChar(), - stripNamespaces); + SdfPath usdPath + = UsdMayaUtil::MayaNodeNameToSdfPath(dagPath.fullPathName().asChar(), stripNamespaces); if (mergeTransformAndShape && _IsShape(dagPath)) { usdPath = usdPath.GetParentPath(); @@ -1383,29 +1240,25 @@ UsdMayaUtil::MDagPathToUsdPath( return usdPath; } -bool -UsdMayaUtil::GetBoolCustomData( - const UsdAttribute& obj, - const TfToken& key, - const bool defaultValue) +bool UsdMayaUtil::GetBoolCustomData( + const UsdAttribute& obj, + const TfToken& key, + const bool defaultValue) { - bool returnValue = defaultValue; + bool returnValue = defaultValue; VtValue data = obj.GetCustomDataByKey(key); if (!data.IsEmpty()) { if (data.IsHolding()) { return data.Get(); } else { TF_RUNTIME_ERROR( - "customData at key '%s' is not of type bool. Skipping...", - key.GetText()); + "customData at key '%s' is not of type bool. Skipping...", key.GetText()); } } return returnValue; } -template -static T -_GetVec(const UsdAttribute& attr, const VtValue& val) +template static T _GetVec(const UsdAttribute& attr, const VtValue& val) { const T ret = val.UncheckedGet(); @@ -1416,22 +1269,20 @@ _GetVec(const UsdAttribute& attr, const VtValue& val) return ret; } -MMatrix -UsdMayaUtil::GfMatrixToMMatrix(const GfMatrix4d& mx) +MMatrix UsdMayaUtil::GfMatrixToMMatrix(const GfMatrix4d& mx) { MMatrix mayaMx; - std::copy(mx.GetArray(), mx.GetArray()+16, mayaMx[0]); + std::copy(mx.GetArray(), mx.GetArray() + 16, mayaMx[0]); return mayaMx; } -bool -UsdMayaUtil::getPlugMatrix( - const MFnDependencyNode& depNode, - const MString& attr, - MMatrix* outVal) +bool UsdMayaUtil::getPlugMatrix( + const MFnDependencyNode& depNode, + const MString& attr, + MMatrix* outVal) { MStatus status; - MPlug plug = depNode.findPlug(attr, true, &status); + MPlug plug = depNode.findPlug(attr, true, &status); if (!status) { return false; } @@ -1450,20 +1301,18 @@ UsdMayaUtil::getPlugMatrix( return true; } -bool -UsdMayaUtil::setPlugMatrix( - const MFnDependencyNode& depNode, - const MString& attr, - const GfMatrix4d& mx) +bool UsdMayaUtil::setPlugMatrix( + const MFnDependencyNode& depNode, + const MString& attr, + const GfMatrix4d& mx) { MStatus status; - MPlug plug = depNode.findPlug(attr, true, &status); + MPlug plug = depNode.findPlug(attr, true, &status); CHECK_MSTATUS_AND_RETURN(status, false); return setPlugMatrix(mx, plug); } -bool -UsdMayaUtil::setPlugMatrix(const GfMatrix4d& mx, MPlug& plug) +bool UsdMayaUtil::setPlugMatrix(const GfMatrix4d& mx, MPlug& plug) { MStatus status; MObject mxObj = MFnMatrixData().create(GfMatrixToMMatrix(mx), &status); @@ -1473,17 +1322,12 @@ UsdMayaUtil::setPlugMatrix(const GfMatrix4d& mx, MPlug& plug) return true; } -bool -UsdMayaUtil::setPlugValue(const UsdAttribute& usdAttr, MPlug& attrPlug) +bool UsdMayaUtil::setPlugValue(const UsdAttribute& usdAttr, MPlug& attrPlug) { return setPlugValue(usdAttr, UsdTimeCode::Default(), attrPlug); } -bool -UsdMayaUtil::setPlugValue( - const UsdAttribute& usdAttr, - const UsdTimeCode time, - MPlug& attrPlug) +bool UsdMayaUtil::setPlugValue(const UsdAttribute& usdAttr, const UsdTimeCode time, MPlug& attrPlug) { VtValue val; if (!usdAttr.Get(&val, time)) { @@ -1494,28 +1338,21 @@ UsdMayaUtil::setPlugValue( if (val.IsHolding()) { status = attrPlug.setDouble(val.UncheckedGet()); - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { status = attrPlug.setFloat(val.UncheckedGet()); - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { status = attrPlug.setInt(val.UncheckedGet()); - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { status = attrPlug.setShort(val.UncheckedGet()); - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { status = attrPlug.setBool(val.UncheckedGet()); - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { // Assume that Ar and Maya will resolve paths the same. This the best // we can do w.r.t. to round-tripping. status = attrPlug.setString(val.UncheckedGet().GetAssetPath().c_str()); - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { status = attrPlug.setString(val.UncheckedGet().c_str()); - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const TfToken token(val.UncheckedGet()); const MObject attrObj = attrPlug.attribute(&status); CHECK_MSTATUS_AND_RETURN(status, false); @@ -1527,80 +1364,67 @@ UsdMayaUtil::setPlugValue( status = attrPlug.setShort(enumVal); CHECK_MSTATUS_AND_RETURN(status, false); } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { if (attrPlug.isCompound()) { const GfVec2d& vecVal = val.UncheckedGet(); for (size_t i = 0u; i < GfVec2d::dimension; ++i) { - MPlug childPlug = attrPlug.child(static_cast(i), - &status); + MPlug childPlug = attrPlug.child(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setDouble(vecVal[i]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { if (attrPlug.isCompound()) { const GfVec2f& vecVal = val.UncheckedGet(); for (size_t i = 0u; i < GfVec2f::dimension; ++i) { - MPlug childPlug = attrPlug.child(static_cast(i), - &status); + MPlug childPlug = attrPlug.child(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setFloat(vecVal[i]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { if (attrPlug.isCompound()) { const GfVec3d vecVal = _GetVec(usdAttr, val); for (size_t i = 0u; i < GfVec3d::dimension; ++i) { - MPlug childPlug = attrPlug.child(static_cast(i), - &status); + MPlug childPlug = attrPlug.child(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setDouble(vecVal[i]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { if (attrPlug.isCompound()) { const GfVec3f vecVal = _GetVec(usdAttr, val); for (size_t i = 0u; i < GfVec3f::dimension; ++i) { - MPlug childPlug = attrPlug.child(static_cast(i), - &status); + MPlug childPlug = attrPlug.child(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setFloat(vecVal[i]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { if (attrPlug.isCompound()) { const GfVec4d vecVal = _GetVec(usdAttr, val); for (size_t i = 0u; i < GfVec4d::dimension; ++i) { - MPlug childPlug = attrPlug.child(static_cast(i), - &status); + MPlug childPlug = attrPlug.child(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setDouble(vecVal[i]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { if (attrPlug.isCompound()) { const GfVec4f vecVal = _GetVec(usdAttr, val); for (size_t i = 0u; i < GfVec4f::dimension; ++i) { - MPlug childPlug = attrPlug.child(static_cast(i), - &status); + MPlug childPlug = attrPlug.child(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setFloat(vecVal[i]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { MObject object = attrPlug.attribute(); if (object.hasFn(MFn::kTypedAttribute) && MFnTypedAttribute(object).attrType() == MFnData::kMatrix) { @@ -1621,118 +1445,92 @@ UsdMayaUtil::setPlugValue( status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t i = 0u; i < valArray.size(); ++i) { - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = elemPlug.setDouble(valArray[i]); CHECK_MSTATUS_AND_RETURN(status, false); } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const VtFloatArray& valArray = val.UncheckedGet(); status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t i = 0u; i < valArray.size(); ++i) { - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = elemPlug.setFloat(valArray[i]); CHECK_MSTATUS_AND_RETURN(status, false); } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const VtIntArray& valArray = val.UncheckedGet(); status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t i = 0u; i < valArray.size(); ++i) { - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = elemPlug.setInt(valArray[i]); CHECK_MSTATUS_AND_RETURN(status, false); } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const VtShortArray& valArray = val.UncheckedGet(); status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t i = 0u; i < valArray.size(); ++i) { - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = elemPlug.setShort(valArray[i]); CHECK_MSTATUS_AND_RETURN(status, false); } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const VtBoolArray& valArray = val.UncheckedGet(); status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t i = 0u; i < valArray.size(); ++i) { - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = elemPlug.setBool(valArray[i]); CHECK_MSTATUS_AND_RETURN(status, false); } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const VtStringArray& valArray = val.UncheckedGet(); status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t i = 0u; i < valArray.size(); ++i) { - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = elemPlug.setString(valArray[i].c_str()); CHECK_MSTATUS_AND_RETURN(status, false); } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const VtVec2dArray valArray = val.UncheckedGet(); status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t i = 0u; i < valArray.size(); ++i) { const GfVec2d& vecVal = valArray[i]; - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t j = 0u; j < GfVec2d::dimension; ++j) { - MPlug childPlug = elemPlug.child(static_cast(j), - &status); + MPlug childPlug = elemPlug.child(static_cast(j), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setDouble(vecVal[j]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const VtVec2fArray valArray = val.UncheckedGet(); status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t i = 0u; i < valArray.size(); ++i) { const GfVec2f& vecVal = valArray[i]; - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t j = 0u; j < GfVec2f::dimension; ++j) { - MPlug childPlug = elemPlug.child(static_cast(j), - &status); + MPlug childPlug = elemPlug.child(static_cast(j), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setFloat(vecVal[j]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const VtVec3dArray valArray = val.UncheckedGet(); status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); @@ -1741,20 +1539,16 @@ UsdMayaUtil::setPlugValue( if (usdAttr.GetRoleName() == SdfValueRoleNames->Color) { vecVal = UsdMayaColorSpace::ConvertMayaToLinear(vecVal); } - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t j = 0u; j < GfVec3d::dimension; ++j) { - MPlug childPlug = elemPlug.child(static_cast(j), - &status); + MPlug childPlug = elemPlug.child(static_cast(j), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setDouble(vecVal[j]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const VtVec3fArray valArray = val.UncheckedGet(); status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); @@ -1763,20 +1557,16 @@ UsdMayaUtil::setPlugValue( if (usdAttr.GetRoleName() == SdfValueRoleNames->Color) { vecVal = UsdMayaColorSpace::ConvertMayaToLinear(vecVal); } - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t j = 0u; j < GfVec3f::dimension; ++j) { - MPlug childPlug = elemPlug.child(static_cast(j), - &status); + MPlug childPlug = elemPlug.child(static_cast(j), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setFloat(vecVal[j]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const VtVec4dArray valArray = val.UncheckedGet(); status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); @@ -1785,20 +1575,16 @@ UsdMayaUtil::setPlugValue( if (usdAttr.GetRoleName() == SdfValueRoleNames->Color) { vecVal = UsdMayaColorSpace::ConvertMayaToLinear(vecVal); } - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t j = 0u; j < GfVec4d::dimension; ++j) { - MPlug childPlug = elemPlug.child(static_cast(j), - &status); + MPlug childPlug = elemPlug.child(static_cast(j), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setDouble(vecVal[j]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else if (val.IsHolding()) { + } else if (val.IsHolding()) { const VtVec4fArray valArray = val.UncheckedGet(); status = attrPlug.setNumElements(static_cast(valArray.size())); CHECK_MSTATUS_AND_RETURN(status, false); @@ -1807,23 +1593,20 @@ UsdMayaUtil::setPlugValue( if (usdAttr.GetRoleName() == SdfValueRoleNames->Color) { vecVal = UsdMayaColorSpace::ConvertMayaToLinear(vecVal); } - MPlug elemPlug = attrPlug.elementByPhysicalIndex( - static_cast(i), - &status); + MPlug elemPlug = attrPlug.elementByPhysicalIndex(static_cast(i), &status); CHECK_MSTATUS_AND_RETURN(status, false); for (size_t j = 0u; j < GfVec4f::dimension; ++j) { - MPlug childPlug = elemPlug.child(static_cast(j), - &status); + MPlug childPlug = elemPlug.child(static_cast(j), &status); CHECK_MSTATUS_AND_RETURN(status, false); status = childPlug.setFloat(vecVal[j]); CHECK_MSTATUS_AND_RETURN(status, false); } } - } - else { - TF_CODING_ERROR("Unsupported type '%s' for USD attribute '%s'", - usdAttr.GetTypeName().GetAsToken().GetText(), - usdAttr.GetPath().GetText()); + } else { + TF_CODING_ERROR( + "Unsupported type '%s' for USD attribute '%s'", + usdAttr.GetTypeName().GetAsToken().GetText(), + usdAttr.GetPath().GetText()); return false; } @@ -1832,19 +1615,12 @@ UsdMayaUtil::setPlugValue( return true; } -bool -UsdMayaUtil::SetNotes( - MFnDependencyNode& depNode, - const std::string& notes) +bool UsdMayaUtil::SetNotes(MFnDependencyNode& depNode, const std::string& notes) { - MStatus status = MStatus::kFailure; + MStatus status = MStatus::kFailure; MFnTypedAttribute typedAttrFn; - MObject attrObj = typedAttrFn.create( - "notes", - "nts", - MFnData::kString, - MObject::kNullObj, - &status); + MObject attrObj + = typedAttrFn.create("notes", "nts", MFnData::kString, MObject::kNullObj, &status); CHECK_MSTATUS_AND_RETURN(status, false); status = depNode.addAttribute(attrObj); @@ -1854,8 +1630,7 @@ UsdMayaUtil::SetNotes( return true; } -bool -UsdMayaUtil::SetHiddenInOutliner(MFnDependencyNode& depNode, const bool hidden) +bool UsdMayaUtil::SetHiddenInOutliner(MFnDependencyNode& depNode, const bool hidden) { MPlug plug = depNode.findPlug("hiddenInOutliner", true); if (!plug.isNull()) { @@ -1865,11 +1640,9 @@ UsdMayaUtil::SetHiddenInOutliner(MFnDependencyNode& depNode, const bool hidden) return false; } -UsdMayaUtil::MDataHandleHolder::MDataHandleHolder( - const MPlug& plug, - MDataHandle dataHandle) : - _plug(plug), - _dataHandle(dataHandle) +UsdMayaUtil::MDataHandleHolder::MDataHandleHolder(const MPlug& plug, MDataHandle dataHandle) + : _plug(plug) + , _dataHandle(dataHandle) { } @@ -1880,31 +1653,26 @@ UsdMayaUtil::MDataHandleHolder::~MDataHandleHolder() } } -TfRefPtr -UsdMayaUtil::MDataHandleHolder::New(const MPlug& plug) +TfRefPtr UsdMayaUtil::MDataHandleHolder::New(const MPlug& plug) { MStatus status; MDataHandle dataHandle = plug.asMDataHandle(&status); if (!status.error()) { - return TfCreateRefPtr( - new UsdMayaUtil::MDataHandleHolder(plug, dataHandle)); - } - else { + return TfCreateRefPtr(new UsdMayaUtil::MDataHandleHolder(plug, dataHandle)); + } else { return nullptr; } } -TfRefPtr -UsdMayaUtil::GetPlugDataHandle(const MPlug& plug) +TfRefPtr UsdMayaUtil::GetPlugDataHandle(const MPlug& plug) { return UsdMayaUtil::MDataHandleHolder::New(plug); } -VtDictionary -UsdMayaUtil::GetDictionaryFromArgDatabase( - const MArgDatabase& argData, - const VtDictionary& guideDict) +VtDictionary UsdMayaUtil::GetDictionaryFromArgDatabase( + const MArgDatabase& argData, + const VtDictionary& guideDict) { // We handle three types of arguments: // 1 - bools: Some bools are actual boolean flags (t/f) in Maya, and others @@ -1916,7 +1684,7 @@ UsdMayaUtil::GetDictionaryFromArgDatabase( VtDictionary args; for (const std::pair& entry : guideDict) { const std::string& key = entry.first; - const VtValue& guideValue = entry.second; + const VtValue& guideValue = entry.second; if (!argData.isFlagSet(key.c_str())) { continue; } @@ -1930,13 +1698,10 @@ UsdMayaUtil::GetDictionaryFromArgDatabase( bool val = true; argData.getFlagArgument(key.c_str(), 0, val); args[key] = val; - } - else if (guideValue.IsHolding()) { - const std::string val = - argData.flagArgumentString(key.c_str(), 0).asChar(); + } else if (guideValue.IsHolding()) { + const std::string val = argData.flagArgumentString(key.c_str(), 0).asChar(); args[key] = val; - } - else if (guideValue.IsHolding>()) { + } else if (guideValue.IsHolding>()) { unsigned int count = argData.numberOfFlagUses(entry.first.c_str()); if (!TF_VERIFY(count > 0)) { // There should be at least one use if isFlagSet() = true. @@ -1957,8 +1722,7 @@ UsdMayaUtil::GetDictionaryFromArgDatabase( const std::string arg = argList.asString(0).asChar(); val.emplace_back(arg); } - } - else { + } else { for (const MArgList& argList : argLists) { std::vector subList; for (unsigned int i = 0; i < argList.length(); ++i) { @@ -1969,10 +1733,8 @@ UsdMayaUtil::GetDictionaryFromArgDatabase( } } args[key] = val; - } - else { - TF_CODING_ERROR("Can't handle type '%s'", - guideValue.GetTypeName().c_str()); + } else { + TF_CODING_ERROR("Can't handle type '%s'", guideValue.GetTypeName().c_str()); } } @@ -2029,10 +1791,10 @@ VtValue _ParseArgumentValue(const std::string& value, const VtValue& guideValue) // [none,default] // [[useRegistry,UsdPreviewSurface],[displayColors,default]] // So, to be able to parse this as valid JSON, we need to add quotes at - // each "[[," to alphanumeric transition. + // each "[[," to alphanumeric transition. // NOTE: The array contains *tokens*, not freeform strings. So we can // skip spaces and consider all commas to be element separators. - bool wasArrayDelimiter = true; + bool wasArrayDelimiter = true; std::string quotedString; for (auto c = value.cbegin(); c != value.cend(); ++c) { if (*c == ' ') { @@ -2084,24 +1846,22 @@ VtValue UsdMayaUtil::ParseArgumentValue( return VtValue(); } -std::pair -UsdMayaUtil::ValueToArgument(const VtValue& value) { +std::pair UsdMayaUtil::ValueToArgument(const VtValue& value) +{ if (value.IsHolding()) { return std::make_pair(true, std::string(value.Get() ? "1" : "0")); - } - else if (value.IsHolding()) { + } else if (value.IsHolding()) { return std::make_pair(true, value.Get()); - } - else if (value.IsHolding>()) { - std::string arrayValue{"["}; - bool firstElement = true; - for (auto const & elemValue: value.Get>()) { + } else if (value.IsHolding>()) { + std::string arrayValue { "[" }; + bool firstElement = true; + for (auto const& elemValue : value.Get>()) { if (firstElement) { firstElement = false; } else { arrayValue += ","; } - bool canConvert; + bool canConvert; std::string elemString; std::tie(canConvert, elemString) = ValueToArgument(elemValue); if (canConvert) { @@ -2116,18 +1876,16 @@ UsdMayaUtil::ValueToArgument(const VtValue& value) { return std::make_pair(false, std::string()); } -std::vector -UsdMayaUtil::GetAllAncestorMayaNodeTypes(const std::string& ty) +std::vector UsdMayaUtil::GetAllAncestorMayaNodeTypes(const std::string& ty) { - const MString inheritedTypesMel = TfStringPrintf( - "nodeType -isTypeName -inherited %s", ty.c_str()).c_str(); + const MString inheritedTypesMel + = TfStringPrintf("nodeType -isTypeName -inherited %s", ty.c_str()).c_str(); MStringArray inheritedTypes; - if (!MGlobal::executeCommand( - inheritedTypesMel, inheritedTypes, false, false)) { + if (!MGlobal::executeCommand(inheritedTypesMel, inheritedTypes, false, false)) { TF_RUNTIME_ERROR( - "Failed to query ancestor types of '%s' via MEL (does the type " - "exist?)", - ty.c_str()); + "Failed to query ancestor types of '%s' via MEL (does the type " + "exist?)", + ty.c_str()); return std::vector(); } @@ -2139,10 +1897,7 @@ UsdMayaUtil::GetAllAncestorMayaNodeTypes(const std::string& ty) return inheritedTypesVector; } -bool -UsdMayaUtil::FindAncestorSceneAssembly( - const MDagPath& dagPath, - MDagPath* assemblyPath) +bool UsdMayaUtil::FindAncestorSceneAssembly(const MDagPath& dagPath, MDagPath* assemblyPath) { MDagPath currentPath(dagPath); while (currentPath.length()) { @@ -2157,39 +1912,33 @@ UsdMayaUtil::FindAncestorSceneAssembly( return false; } -MBoundingBox -UsdMayaUtil::GetInfiniteBoundingBox() +MBoundingBox UsdMayaUtil::GetInfiniteBoundingBox() { constexpr double inf = std::numeric_limits::infinity(); return MBoundingBox(MPoint(-inf, -inf, -inf), MPoint(inf, inf, inf)); } -MString -UsdMayaUtil::convert(const TfToken& token) +MString UsdMayaUtil::convert(const TfToken& token) { - return MString(token.GetText(), token.size()); + return MString(token.GetText(), token.size()); } -std::string -UsdMayaUtil::convert(const MString& str) +std::string UsdMayaUtil::convert(const MString& str) { return std::string(str.asChar(), str.length()); } -MString -UsdMayaUtil::convert(const std::string& str) +MString UsdMayaUtil::convert(const std::string& str) { return MString(str.data(), static_cast(str.size())); } -MDagPath -UsdMayaUtil::getDagPath(const MFnDependencyNode& depNodeFn, const bool reportError) +MDagPath UsdMayaUtil::getDagPath(const MFnDependencyNode& depNodeFn, const bool reportError) { try { - const MFnDagNode& dagNodeFn = - dynamic_cast(depNodeFn); + const MFnDagNode& dagNodeFn = dynamic_cast(depNodeFn); - MStatus status; + MStatus status; const MDagPath dagPath = dagNodeFn.dagPath(&status); if (status == MS::kSuccess) { const bool dagPathIsValid = dagPath.isValid(&status); @@ -2204,27 +1953,25 @@ UsdMayaUtil::getDagPath(const MFnDependencyNode& depNodeFn, const bool reportErr "constructed using an MDagPath.", dagNodeFn.fullPathName().asChar()); } - } - catch (const std::bad_cast& /* e */) { + } catch (const std::bad_cast& /* e */) { // This is not a DAG node, so it can't have a DAG path. } return MDagPath(); } -UsdMayaUtil::MDagPathMap +UsdMayaUtil::MDagPathMap UsdMayaUtil::getDagPathMap(const MFnDependencyNode& depNodeFn, const SdfPath& usdPath) { const MDagPath dagPath = UsdMayaUtil::getDagPath(depNodeFn, /* reportError = */ false); if (dagPath.isValid()) { - return UsdMayaUtil::MDagPathMap({{dagPath, usdPath}}); + return UsdMayaUtil::MDagPathMap({ { dagPath, usdPath } }); } return UsdMayaUtil::MDagPathMap({}); } -VtIntArray -UsdMayaUtil::shiftIndices(const VtIntArray& array, int shift) +VtIntArray UsdMayaUtil::shiftIndices(const VtIntArray& array, int shift) { VtIntArray output(array.size()); for (size_t i = 0; i < array.size(); ++i) { @@ -2233,51 +1980,35 @@ UsdMayaUtil::shiftIndices(const VtIntArray& array, int shift) return output; } -VtValue -UsdMayaUtil::pushFirstValue(const VtValue& arr, const VtValue& defaultValue) +VtValue UsdMayaUtil::pushFirstValue(const VtValue& arr, const VtValue& defaultValue) { - if (arr.IsHolding>() && - defaultValue.IsHolding()) { + if (arr.IsHolding>() && defaultValue.IsHolding()) { return UsdMayaUtil::PushFirstValue( - arr.UncheckedGet>(), - defaultValue.UncheckedGet()); - } - else if (arr.IsHolding>() && - defaultValue.IsHolding()) { + arr.UncheckedGet>(), defaultValue.UncheckedGet()); + } else if (arr.IsHolding>() && defaultValue.IsHolding()) { return UsdMayaUtil::PushFirstValue( - arr.UncheckedGet>(), - defaultValue.UncheckedGet()); - } - else if (arr.IsHolding>() && - defaultValue.IsHolding()) { + arr.UncheckedGet>(), defaultValue.UncheckedGet()); + } else if (arr.IsHolding>() && defaultValue.IsHolding()) { return UsdMayaUtil::PushFirstValue( - arr.UncheckedGet>(), - defaultValue.UncheckedGet()); - } - else if (arr.IsHolding>() && - defaultValue.IsHolding()) { + arr.UncheckedGet>(), defaultValue.UncheckedGet()); + } else if (arr.IsHolding>() && defaultValue.IsHolding()) { return UsdMayaUtil::PushFirstValue( - arr.UncheckedGet>(), - defaultValue.UncheckedGet()); + arr.UncheckedGet>(), defaultValue.UncheckedGet()); } TF_CODING_ERROR("Unsupported type"); return VtValue(); }; -VtValue -UsdMayaUtil::popFirstValue(const VtValue& arr) +VtValue UsdMayaUtil::popFirstValue(const VtValue& arr) { if (arr.IsHolding>()) { return UsdMayaUtil::PopFirstValue(arr.UncheckedGet>()); - } - else if (arr.IsHolding>()) { + } else if (arr.IsHolding>()) { return UsdMayaUtil::PopFirstValue(arr.UncheckedGet>()); - } - else if (arr.IsHolding>()) { + } else if (arr.IsHolding>()) { return UsdMayaUtil::PopFirstValue(arr.UncheckedGet>()); - } - else if (arr.IsHolding>()) { + } else if (arr.IsHolding>()) { return UsdMayaUtil::PopFirstValue(arr.UncheckedGet>()); } @@ -2285,28 +2016,25 @@ UsdMayaUtil::popFirstValue(const VtValue& arr) return VtValue(); }; -bool -UsdMayaUtil::containsUnauthoredValues(const VtIntArray& indices) +bool UsdMayaUtil::containsUnauthoredValues(const VtIntArray& indices) { - return std::any_of( - indices.begin(), - indices.end(), - [](const int& i) { return i < 0; }); + return std::any_of(indices.begin(), indices.end(), [](const int& i) { return i < 0; }); } -MDagPath -UsdMayaUtil::nameToDagPath(const std::string& name) +MDagPath UsdMayaUtil::nameToDagPath(const std::string& name) { MSelectionList selection; selection.add(MString(name.c_str())); MDagPath dag; - MStatus status = selection.getDagPath(0, dag); + MStatus status = selection.getDagPath(0, dag); CHECK_MSTATUS(status); return dag; } -void -UsdMayaUtil::GetFilteredSelectionToExport(bool exportSelected, MSelectionList& objectList, UsdMayaUtil::MDagPathSet& dagPaths) +void UsdMayaUtil::GetFilteredSelectionToExport( + bool exportSelected, + MSelectionList& objectList, + UsdMayaUtil::MDagPathSet& dagPaths) { dagPaths.clear(); @@ -2315,7 +2043,8 @@ UsdMayaUtil::GetFilteredSelectionToExport(bool exportSelected, MSelectionList& o // There are three cases depending on the input: // If exportSelected is true then we will grab the active selection // If objectList is empty then we will grab all immediate children of the world root. - // Else there was a populated list of objects to use, most likely passed explicitly to the command. + // Else there was a populated list of objects to use, most likely passed explicitly to the + // command. if (exportSelected) { MGlobal::getActiveSelectionList(objectList); } else if (objectList.isEmpty()) { @@ -2337,14 +2066,14 @@ UsdMayaUtil::GetFilteredSelectionToExport(bool exportSelected, MSelectionList& o // 2. For each input object we iterate up its hierarchy checking if any parent is in the set. // 3. If no parent is in the set then we can add it. UsdMayaUtil::MDagPathSet sortedInput; - for (unsigned int i=0; i < nbObj; i++) { + for (unsigned int i = 0; i < nbObj; i++) { MDagPath dagPath; status = objectList.getDagPath(i, dagPath); if (status == MS::kSuccess) sortedInput.emplace(dagPath); } - for(auto pIter : sortedInput) { + for (auto pIter : sortedInput) { if (!filterInput || shouldAddToSet(pIter, dagPaths)) dagPaths.emplace(pIter); } diff --git a/lib/mayaUsd/utils/util.h b/lib/mayaUsd/utils/util.h index 1acd4ed4bb..1f2059a1d4 100644 --- a/lib/mayaUsd/utils/util.h +++ b/lib/mayaUsd/utils/util.h @@ -16,12 +16,21 @@ #ifndef PXRUSDMAYA_UTIL_H #define PXRUSDMAYA_UTIL_H -#include -#include -#include -#include -#include -#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -40,35 +49,26 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include +#include +#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE /// General utilities for working with the Maya API. -namespace UsdMayaUtil -{ +namespace UsdMayaUtil { struct _CmpDag { bool operator()(const MDagPath& lhs, const MDagPath& rhs) const { int pathCountDiff = lhs.pathCount() - rhs.pathCount(); - return (0 != pathCountDiff) ? (pathCountDiff < 0) : - (strcmp(lhs.fullPathName().asChar(), rhs.fullPathName().asChar()) < 0); + return (0 != pathCountDiff) + ? (pathCountDiff < 0) + : (strcmp(lhs.fullPathName().asChar(), rhs.fullPathName().asChar()) < 0); } }; @@ -84,31 +84,25 @@ using MDagPathSet = std::set; /// may change over time. Only use this class if you can guarantee that DAG /// nodes won't be renamed or reparented while class instances are alive. /// Otherwise, you may see inconsistent results. -template -using MDagPathMap = std::map; +template using MDagPathMap = std::map; struct _HashObjectHandle { - unsigned long operator()(const MObjectHandle& handle) const - { - return handle.hashCode(); - } + unsigned long operator()(const MObjectHandle& handle) const { return handle.hashCode(); } }; /// Unordered set of Maya object handles. -using MObjectHandleUnorderedSet = - std::unordered_set; +using MObjectHandleUnorderedSet = std::unordered_set; /// Unordered mapping of Maya object handles to an arbitrary type. template -using MObjectHandleUnorderedMap = - std::unordered_map; +using MObjectHandleUnorderedMap = std::unordered_map; /// RAII-style helper for destructing an MDataHandle obtained from a plug /// once it goes out of scope. class MDataHandleHolder : public TfRefBase { - MPlug _plug; + MPlug _plug; MDataHandle _dataHandle; public: @@ -126,53 +120,31 @@ const double MillimetersPerInch = 25.4; /// Converts the given value \p mm in millimeters to the equivalent value /// in inches. -inline -double -ConvertMMToInches(const double mm) -{ - return mm / MillimetersPerInch; -} +inline double ConvertMMToInches(const double mm) { return mm / MillimetersPerInch; } /// Converts the given value \p inches in inches to the equivalent value /// in millimeters. -inline -double -ConvertInchesToMM(const double inches) -{ - return inches * MillimetersPerInch; -} +inline double ConvertInchesToMM(const double inches) { return inches * MillimetersPerInch; } const double MillimetersPerCentimeter = 10.0; /// Converts the given value \p mm in millimeters to the equivalent value /// in centimeters. -inline -double -ConvertMMToCM(const double mm) -{ - return mm / MillimetersPerCentimeter; -} +inline double ConvertMMToCM(const double mm) { return mm / MillimetersPerCentimeter; } /// Converts the given value \p cm in centimeters to the equivalent value /// in millimeters. -inline -double -ConvertCMToMM(const double cm) -{ - return cm * MillimetersPerCentimeter; -} +inline double ConvertCMToMM(const double cm) { return cm * MillimetersPerCentimeter; } -/// Converts the given value \p mdistance in Maya's MDistance units to the +/// Converts the given value \p mdistance in Maya's MDistance units to the /// equivalent value in USD's metersPerUnit. MAYAUSD_CORE_PUBLIC -double ConvertMDistanceUnitToUsdGeomLinearUnit( - const MDistance::Unit mdistanceUnit); +double ConvertMDistanceUnitToUsdGeomLinearUnit(const MDistance::Unit mdistanceUnit); -/// Coverts the given value \p linearUnit in USD's metersPerUnit to the +/// Coverts the given value \p linearUnit in USD's metersPerUnit to the /// equivalent value in Maya's MDistance units. MAYAUSD_CORE_PUBLIC -MDistance::Unit ConvertUsdGeomLinearUnitToMDistanceUnit( - const double linearUnit); +MDistance::Unit ConvertUsdGeomLinearUnitToMDistanceUnit(const double linearUnit); /// Get the full name of the Maya node \p mayaNode. /// @@ -229,9 +201,7 @@ MAYAUSD_CORE_PUBLIC MObject GetDefaultLightSetObject(); MAYAUSD_CORE_PUBLIC -bool isAncestorDescendentRelationship( - const MDagPath& path1, - const MDagPath& path2); +bool isAncestorDescendentRelationship(const MDagPath& path1, const MDagPath& path2); // returns 0 if static, 1 if sampled, and 2 if a curve MAYAUSD_CORE_PUBLIC @@ -279,9 +249,7 @@ const std::string MayaNamespaceDelimiter(":"); /// "taco:foo:bar" into "bar" for \p nsDepth > 1. /// If \p nsDepth is -1, all namespaces are stripped. MAYAUSD_CORE_PUBLIC -std::string stripNamespaces( - const std::string& nodeName, - const int nsDepth = -1); +std::string stripNamespaces(const std::string& nodeName, const int nsDepth = -1); MAYAUSD_CORE_PUBLIC std::string SanitizeName(const std::string& name); @@ -298,11 +266,11 @@ std::string SanitizeColorSetName(const std::string& name); /// MAYAUSD_CORE_PUBLIC bool GetLinearShaderColor( - const MFnDagNode& node, - PXR_NS::VtVec3fArray* RGBData, - PXR_NS::VtFloatArray* AlphaData, - PXR_NS::TfToken* interpolation, - PXR_NS::VtIntArray* assignmentIndices); + const MFnDagNode& node, + PXR_NS::VtVec3fArray* RGBData, + PXR_NS::VtFloatArray* AlphaData, + PXR_NS::TfToken* interpolation, + PXR_NS::VtIntArray* assignmentIndices); /// Get the base colors and opacities from the shader(s) bound to \p mesh. /// Returned colors will be in linear color space. @@ -319,39 +287,39 @@ bool GetLinearShaderColor( /// MAYAUSD_CORE_PUBLIC bool GetLinearShaderColor( - const MFnMesh& mesh, - PXR_NS::VtVec3fArray* RGBData, - PXR_NS::VtFloatArray* AlphaData, - PXR_NS::TfToken* interpolation, - PXR_NS::VtIntArray* assignmentIndices); + const MFnMesh& mesh, + PXR_NS::VtVec3fArray* RGBData, + PXR_NS::VtFloatArray* AlphaData, + PXR_NS::TfToken* interpolation, + PXR_NS::VtIntArray* assignmentIndices); /// Combine distinct indices that point to the same values to all point to the /// same index for that value. This will potentially shrink the data array. MAYAUSD_CORE_PUBLIC void MergeEquivalentIndexedValues( - PXR_NS::VtFloatArray* valueData, - PXR_NS::VtIntArray* assignmentIndices); + PXR_NS::VtFloatArray* valueData, + PXR_NS::VtIntArray* assignmentIndices); /// Combine distinct indices that point to the same values to all point to the /// same index for that value. This will potentially shrink the data array. MAYAUSD_CORE_PUBLIC void MergeEquivalentIndexedValues( - PXR_NS::VtVec2fArray* valueData, - PXR_NS::VtIntArray* assignmentIndices); + PXR_NS::VtVec2fArray* valueData, + PXR_NS::VtIntArray* assignmentIndices); /// Combine distinct indices that point to the same values to all point to the /// same index for that value. This will potentially shrink the data array. MAYAUSD_CORE_PUBLIC void MergeEquivalentIndexedValues( - PXR_NS::VtVec3fArray* valueData, - PXR_NS::VtIntArray* assignmentIndices); + PXR_NS::VtVec3fArray* valueData, + PXR_NS::VtIntArray* assignmentIndices); /// Combine distinct indices that point to the same values to all point to the /// same index for that value. This will potentially shrink the data array. MAYAUSD_CORE_PUBLIC void MergeEquivalentIndexedValues( - PXR_NS::VtVec4fArray* valueData, - PXR_NS::VtIntArray* assignmentIndices); + PXR_NS::VtVec4fArray* valueData, + PXR_NS::VtIntArray* assignmentIndices); /// Attempt to compress faceVarying primvar indices to uniform, vertex, or /// constant interpolation if possible. This will potentially shrink the @@ -359,9 +327,9 @@ void MergeEquivalentIndexedValues( /// possible. MAYAUSD_CORE_PUBLIC void CompressFaceVaryingPrimvarIndices( - const MFnMesh& mesh, - PXR_NS::TfToken* interpolation, - PXR_NS::VtIntArray* assignmentIndices); + const MFnMesh& mesh, + PXR_NS::TfToken* interpolation, + PXR_NS::VtIntArray* assignmentIndices); /// Get whether \p plug is authored in the Maya scene. /// @@ -376,10 +344,7 @@ MAYAUSD_CORE_PUBLIC MPlug GetConnected(const MPlug& plug); MAYAUSD_CORE_PUBLIC -void Connect( - const MPlug& srcPlug, - const MPlug& dstPlug, - const bool clearDstPlug); +void Connect(const MPlug& srcPlug, const MPlug& dstPlug, const bool clearDstPlug); /// Get a named child plug of \p plug by name. MAYAUSD_CORE_PUBLIC @@ -391,9 +356,7 @@ MPlug FindChildPlugByName(const MPlug& plug, const MString& name); /// This means it will replace Maya's namespace delimiter (':') with /// underscores ('_'). MAYAUSD_CORE_PUBLIC -SdfPath MayaNodeNameToSdfPath( - const std::string& nodeName, - const bool stripNamespaces); +SdfPath MayaNodeNameToSdfPath(const std::string& nodeName, const bool stripNamespaces); /// Converts the given Maya MDagPath \p dagPath into an SdfPath. /// @@ -406,24 +369,24 @@ SdfPath MayaNodeNameToSdfPath( /// underscores ('_'). MAYAUSD_CORE_PUBLIC SdfPath MDagPathToUsdPath( - const MDagPath& dagPath, - const bool mergeTransformAndShape, - const bool stripNamespaces); + const MDagPath& dagPath, + const bool mergeTransformAndShape, + const bool stripNamespaces); /// Convenience function to retrieve custom data MAYAUSD_CORE_PUBLIC bool GetBoolCustomData( - const PXR_NS::UsdAttribute& obj, - const PXR_NS::TfToken& key, - const bool defaultValue); + const PXR_NS::UsdAttribute& obj, + const PXR_NS::TfToken& key, + const bool defaultValue); /// Compute the value of \p attr, returning true upon success. template bool getPlugValue( - const MFnDependencyNode& depNode, - const MString& attr, - T* val, - bool* isAnimated = nullptr) + const MFnDependencyNode& depNode, + const MString& attr, + T* val, + bool* isAnimated = nullptr) { MPlug plg = depNode.findPlug(attr, /* wantNetworkedPlug = */ true); if (plg.isNull()) { @@ -445,18 +408,12 @@ MMatrix GfMatrixToMMatrix(const GfMatrix4d& mx); // plug. // Returns true upon success, placing the matrix in the outVal parameter. MAYAUSD_CORE_PUBLIC -bool getPlugMatrix( - const MFnDependencyNode& depNode, - const MString& attr, - MMatrix* outVal); +bool getPlugMatrix(const MFnDependencyNode& depNode, const MString& attr, MMatrix* outVal); /// Set a matrix value on plug name \p attr, of \p depNode. /// Returns true if the value was set on the plug successfully, false otherwise. MAYAUSD_CORE_PUBLIC -bool setPlugMatrix( - const MFnDependencyNode& depNode, - const MString& attr, - const GfMatrix4d& mx); +bool setPlugMatrix(const MFnDependencyNode& depNode, const MString& attr, const GfMatrix4d& mx); MAYAUSD_CORE_PUBLIC bool setPlugMatrix(const GfMatrix4d& mx, MPlug& plug); @@ -476,17 +433,14 @@ bool setPlugValue(const PXR_NS::UsdAttribute& attr, MPlug& attrPlug); /// Returns true if the value was set on the plug successfully, false otherwise. MAYAUSD_CORE_PUBLIC bool setPlugValue( - const PXR_NS::UsdAttribute& attr, - const PXR_NS::UsdTimeCode time, - MPlug& attrPlug); + const PXR_NS::UsdAttribute& attr, + const PXR_NS::UsdTimeCode time, + MPlug& attrPlug); /// \brief sets \p attr to have value \p val, assuming it exists on \p /// depNode. Returns true if successful. template -bool setPlugValue( - const MFnDependencyNode& depNode, - const MString& attr, - const T& val) +bool setPlugValue(const MFnDependencyNode& depNode, const MString& attr, const T& val) { MPlug plg = depNode.findPlug(attr, /* findNetworked = */ false); if (plg.isNull()) { @@ -514,9 +468,8 @@ bool SetHiddenInOutliner(MFnDependencyNode& depNode, const bool hidden); /// from \p argData. /// Mainly useful for parsing arguments in commands all at once. MAYAUSD_CORE_PUBLIC -VtDictionary GetDictionaryFromArgDatabase( - const MArgDatabase& argData, - const VtDictionary& guideDict); +VtDictionary +GetDictionaryFromArgDatabase(const MArgDatabase& argData, const VtDictionary& guideDict); /// Parses \p value based on the type of \p key in \p guideDict, returning the /// parsed value wrapped in a VtValue. @@ -525,10 +478,8 @@ VtDictionary GetDictionaryFromArgDatabase( /// strings. If you have an MArgList/MArgParser/MArgDatabase, it's going to be /// way simpler to use GetDictionaryFromArgDatabase() instead. MAYAUSD_CORE_PUBLIC -VtValue ParseArgumentValue( - const std::string& key, - const std::string& value, - const VtDictionary& guideDict); +VtValue +ParseArgumentValue(const std::string& key, const std::string& value, const VtDictionary& guideDict); /// Converts a value into a string that can be parsed back using ParseArgumentValue. /// Should be used when generating argument strings that are to be used by translators. @@ -550,9 +501,7 @@ std::vector GetAllAncestorMayaNodeTypes(const std::string& ty); /// the \p *assemblyPath with the assembly path and returns \c true. /// Otherwise, returns \c false. MAYAUSD_CORE_PUBLIC -bool FindAncestorSceneAssembly( - const MDagPath& dagPath, - MDagPath* assemblyPath = nullptr); +bool FindAncestorSceneAssembly(const MDagPath& dagPath, MDagPath* assemblyPath = nullptr); MAYAUSD_CORE_PUBLIC MBoundingBox GetInfiniteBoundingBox(); @@ -575,8 +524,7 @@ MDagPathMap getDagPathMap(const MFnDependencyNode& depNodeFn, const Sdf MAYAUSD_CORE_PUBLIC VtIntArray shiftIndices(const VtIntArray& array, int shift); -template -VtValue PushFirstValue(VtArray arr, const T& value) +template VtValue PushFirstValue(VtArray arr, const T& value) { arr.resize(arr.size() + 1); std::move_backward(arr.begin(), arr.end() - 1, arr.end()); @@ -587,8 +535,7 @@ VtValue PushFirstValue(VtArray arr, const T& value) MAYAUSD_CORE_PUBLIC VtValue pushFirstValue(const VtValue& arr, const VtValue& defaultValue); -template -VtValue PopFirstValue(VtArray arr) +template VtValue PopFirstValue(VtArray arr) { std::move(arr.begin() + 1, arr.end(), arr.begin()); arr.pop_back(); @@ -617,7 +564,10 @@ MDagPath nameToDagPath(const std::string& name); /// the objects to be exported. /// MAYAUSD_CORE_PUBLIC -void GetFilteredSelectionToExport(bool exportSelected, MSelectionList& objectList, UsdMayaUtil::MDagPathSet& dagPaths); +void GetFilteredSelectionToExport( + bool exportSelected, + MSelectionList& objectList, + UsdMayaUtil::MDagPathSet& dagPaths); } // namespace UsdMayaUtil diff --git a/lib/mayaUsd/utils/utilFileSystem.cpp b/lib/mayaUsd/utils/utilFileSystem.cpp index b4ae70ced6..dcacc235ec 100644 --- a/lib/mayaUsd/utils/utilFileSystem.cpp +++ b/lib/mayaUsd/utils/utilFileSystem.cpp @@ -15,54 +15,54 @@ // #include "utilFileSystem.h" -#include -#include -#include +#include #include -#include +#include +#include +#include #include PXR_NAMESPACE_USING_DIRECTIVE -std::string -UsdMayaUtilFileSystem::resolvePath(const std::string& filePath) +std::string UsdMayaUtilFileSystem::resolvePath(const std::string& filePath) { ArResolver& resolver = ArGetResolver(); return resolver.Resolve(filePath); } -std::string -UsdMayaUtilFileSystem::getDir(const std::string &fullFilePath) +std::string UsdMayaUtilFileSystem::getDir(const std::string& fullFilePath) { return boost::filesystem::path(fullFilePath).parent_path().string(); } -std::string -UsdMayaUtilFileSystem::getMayaReferencedFileDir(const MObject &proxyShapeNode) +std::string UsdMayaUtilFileSystem::getMayaReferencedFileDir(const MObject& proxyShapeNode) { - // Can not use MFnDependencyNode(proxyShapeNode).isFromReferencedFile() to test if it is reference node or not, - // which always return false even the proxyShape node is referenced... + // Can not use MFnDependencyNode(proxyShapeNode).isFromReferencedFile() to test if it is + // reference node or not, which always return false even the proxyShape node is referenced... - MStatus stat; - MFnReference refFn; + MStatus stat; + MFnReference refFn; MItDependencyNodes dgIter(MFn::kReference, &stat); - for (; !dgIter.isDone(); dgIter.next()) - { + for (; !dgIter.isDone(); dgIter.next()) { MObject cRefNode = dgIter.thisNode(); refFn.setObject(cRefNode); - if(refFn.containsNodeExactly(proxyShapeNode, &stat)) - { - // According to Maya API document, the second argument is 'includePath' and set it to true to include the file path. - // However, I have to set it to false to return the full file path otherwise I get a file name only... + if (refFn.containsNodeExactly(proxyShapeNode, &stat)) { + // According to Maya API document, the second argument is 'includePath' and set it to + // true to include the file path. However, I have to set it to false to return the full + // file path otherwise I get a file name only... MString refFilePath = refFn.fileName(true, false, false, &stat); - if(!refFilePath.length()) - return std::string(); + if (!refFilePath.length()) + return std::string(); std::string referencedFilePath = refFilePath.asChar(); - TF_DEBUG(USDMAYA_PROXYSHAPEBASE).Msg("getMayaReferencedFileDir: The reference file that contains the proxyShape node is : %s\n", referencedFilePath.c_str()); + TF_DEBUG(USDMAYA_PROXYSHAPEBASE) + .Msg( + "getMayaReferencedFileDir: The reference file that contains the proxyShape " + "node is : %s\n", + referencedFilePath.c_str()); return getDir(referencedFilePath); } @@ -71,46 +71,45 @@ UsdMayaUtilFileSystem::getMayaReferencedFileDir(const MObject &proxyShapeNode) return std::string(); } -std::string -UsdMayaUtilFileSystem::getMayaSceneFileDir() +std::string UsdMayaUtilFileSystem::getMayaSceneFileDir() { - std::string currentFile = std::string(MFileIO::currentFile().asChar(), MFileIO::currentFile().length()); + std::string currentFile + = std::string(MFileIO::currentFile().asChar(), MFileIO::currentFile().length()); size_t filePathSize = currentFile.size(); - if(filePathSize < 4) + if (filePathSize < 4) return std::string(); // If scene is untitled, the maya file will be MayaWorkspaceDir/untitled : constexpr char ma_ext[] = ".ma"; constexpr char mb_ext[] = ".mb"; - auto ext_start = currentFile.end() - 3; - if(std::equal(ma_ext, ma_ext + 3, ext_start) || std::equal(mb_ext, mb_ext + 3, ext_start)) + auto ext_start = currentFile.end() - 3; + if (std::equal(ma_ext, ma_ext + 3, ext_start) || std::equal(mb_ext, mb_ext + 3, ext_start)) return getDir(currentFile); return std::string(); } -std::string -UsdMayaUtilFileSystem::resolveRelativePathWithinMayaContext(const MObject &proxyShape, const std::string& relativeFilePath) +std::string UsdMayaUtilFileSystem::resolveRelativePathWithinMayaContext( + const MObject& proxyShape, + const std::string& relativeFilePath) { if (relativeFilePath.length() < 3) return relativeFilePath; std::string currentFileDir = getMayaReferencedFileDir(proxyShape); - if(currentFileDir.empty()) + if (currentFileDir.empty()) currentFileDir = getMayaSceneFileDir(); - if(currentFileDir.empty()) + if (currentFileDir.empty()) return relativeFilePath; boost::system::error_code errorCode; auto path = boost::filesystem::canonical(relativeFilePath, currentFileDir, errorCode); - if (errorCode) - { + if (errorCode) { // file does not exist return std::string(); } return path.string(); } - diff --git a/lib/mayaUsd/utils/utilFileSystem.h b/lib/mayaUsd/utils/utilFileSystem.h index 5c4a255535..479e372749 100644 --- a/lib/mayaUsd/utils/utilFileSystem.h +++ b/lib/mayaUsd/utils/utilFileSystem.h @@ -13,43 +13,43 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include +#include #include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -namespace UsdMayaUtilFileSystem -{ - /*! \brief returns the resolved filesystem path for the file identified by the given path - */ - MAYAUSD_CORE_PUBLIC - std::string resolvePath(const std::string& filePath); - - /*! \brief returns the path to the - */ - MAYAUSD_CORE_PUBLIC - std::string getDir(const std::string &fullFilePath); - - /*! \brief returns parent directory of a maya scene file opened by reference - */ - MAYAUSD_CORE_PUBLIC - std::string getMayaReferencedFileDir(const MObject& proxyShapeNode); - - /*! \brief returns parent directory of opened maya scene file - */ - MAYAUSD_CORE_PUBLIC - std::string getMayaSceneFileDir(); - - /*! \brief returns the aboluste path relative to the maya file - */ - MAYAUSD_CORE_PUBLIC - std::string resolveRelativePathWithinMayaContext(const MObject& proxyShape, - const std::string& relativeFilePath); +namespace UsdMayaUtilFileSystem { +/*! \brief returns the resolved filesystem path for the file identified by the given path + */ +MAYAUSD_CORE_PUBLIC +std::string resolvePath(const std::string& filePath); + +/*! \brief returns the path to the + */ +MAYAUSD_CORE_PUBLIC +std::string getDir(const std::string& fullFilePath); + +/*! \brief returns parent directory of a maya scene file opened by reference + */ +MAYAUSD_CORE_PUBLIC +std::string getMayaReferencedFileDir(const MObject& proxyShapeNode); + +/*! \brief returns parent directory of opened maya scene file + */ +MAYAUSD_CORE_PUBLIC +std::string getMayaSceneFileDir(); + +/*! \brief returns the aboluste path relative to the maya file + */ +MAYAUSD_CORE_PUBLIC +std::string resolveRelativePathWithinMayaContext( + const MObject& proxyShape, + const std::string& relativeFilePath); } // namespace UsdMayaUtilFileSystem diff --git a/lib/usd/hdMaya/adapters/adapter.cpp b/lib/usd/hdMaya/adapters/adapter.cpp index ad03a9173e..234daeb8a8 100644 --- a/lib/usd/hdMaya/adapters/adapter.cpp +++ b/lib/usd/hdMaya/adapters/adapter.cpp @@ -15,96 +15,103 @@ // #include "adapter.h" -#include - -#include - #include #include #include +#include + +#include + PXR_NAMESPACE_OPEN_SCOPE TF_REGISTRY_FUNCTION(TfType) { TfType::Define(); } namespace { -void _preRemoval(MObject& node, void* clientData) { +void _preRemoval(MObject& node, void* clientData) +{ TF_UNUSED(node); auto* adapter = reinterpret_cast(clientData); TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) - .Msg( - "Pre-removal callback triggered for prim (%s)\n", - adapter->GetID().GetText()); + .Msg("Pre-removal callback triggered for prim (%s)\n", adapter->GetID().GetText()); adapter->GetDelegate()->RemoveAdapter(adapter->GetID()); } -void _nameChanged(MObject& node, const MString& str, void* clientData) { +void _nameChanged(MObject& node, const MString& str, void* clientData) +{ TF_UNUSED(node); TF_UNUSED(str); auto* adapter = reinterpret_cast(clientData); TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) - .Msg( - "Name-changed callback triggered for prim (%s)\n", - adapter->GetID().GetText()); + .Msg("Name-changed callback triggered for prim (%s)\n", adapter->GetID().GetText()); adapter->RemoveCallbacks(); - adapter->GetDelegate()->RecreateAdapterOnIdle( - adapter->GetID(), adapter->GetNode()); + adapter->GetDelegate()->RecreateAdapterOnIdle(adapter->GetID(), adapter->GetNode()); } } // namespace -HdMayaAdapter::HdMayaAdapter( - const MObject& node, const SdfPath& id, HdMayaDelegateCtx* delegate) - : _id(id), _delegate(delegate), _node(node) {} +HdMayaAdapter::HdMayaAdapter(const MObject& node, const SdfPath& id, HdMayaDelegateCtx* delegate) + : _id(id) + , _delegate(delegate) + , _node(node) +{ +} HdMayaAdapter::~HdMayaAdapter() { RemoveCallbacks(); } -void HdMayaAdapter::AddCallback(MCallbackId callbackId) { - _callbacks.push_back(callbackId); -} +void HdMayaAdapter::AddCallback(MCallbackId callbackId) { _callbacks.push_back(callbackId); } -void HdMayaAdapter::RemoveCallbacks() { - if (_callbacks.empty()) { return; } +void HdMayaAdapter::RemoveCallbacks() +{ + if (_callbacks.empty()) { + return; + } TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) - .Msg( - "Removing all adapter callbacks for prim (%s).\n", - GetID().GetText()); - for (auto c : _callbacks) { MMessage::removeCallback(c); } + .Msg("Removing all adapter callbacks for prim (%s).\n", GetID().GetText()); + for (auto c : _callbacks) { + MMessage::removeCallback(c); + } std::vector().swap(_callbacks); } -VtValue HdMayaAdapter::Get(const TfToken& key) { +VtValue HdMayaAdapter::Get(const TfToken& key) +{ TF_UNUSED(key); return {}; }; -bool HdMayaAdapter::HasType(const TfToken& typeId) const { +bool HdMayaAdapter::HasType(const TfToken& typeId) const +{ TF_UNUSED(typeId); return false; } -void HdMayaAdapter::CreateCallbacks() { +void HdMayaAdapter::CreateCallbacks() +{ if (_node != MObject::kNullObj) { TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) - .Msg( - "Creating generic adapter callbacks for prim (%s).\n", - GetID().GetText()); + .Msg("Creating generic adapter callbacks for prim (%s).\n", GetID().GetText()); MStatus status; - auto id = MNodeMessage::addNodePreRemovalCallback( - _node, _preRemoval, this, &status); - if (status) { AddCallback(id); } - id = MNodeMessage::addNameChangedCallback( - _node, _nameChanged, this, &status); - if (status) { AddCallback(id); } + auto id = MNodeMessage::addNodePreRemovalCallback(_node, _preRemoval, this, &status); + if (status) { + AddCallback(id); + } + id = MNodeMessage::addNameChangedCallback(_node, _nameChanged, this, &status); + if (status) { + AddCallback(id); + } } } -MStatus HdMayaAdapter::Initialize() { +MStatus HdMayaAdapter::Initialize() +{ auto status = MayaAttrs::initialize(); - if (status) { HdMayaMaterialNetworkConverter::initialize(); } + if (status) { + HdMayaMaterialNetworkConverter::initialize(); + } return status; } diff --git a/lib/usd/hdMaya/adapters/adapter.h b/lib/usd/hdMaya/adapters/adapter.h index 3da6a8b67e..0b485b564f 100644 --- a/lib/usd/hdMaya/adapters/adapter.h +++ b/lib/usd/hdMaya/adapters/adapter.h @@ -16,27 +16,27 @@ #ifndef HDMAYA_ADAPTER_H #define HDMAYA_ADAPTER_H -#include - -#include +#include +#include #include #include -#include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -class HdMayaAdapter { +class HdMayaAdapter +{ public: HDMAYA_API - HdMayaAdapter( - const MObject& node, const SdfPath& id, HdMayaDelegateCtx* delegate); + HdMayaAdapter(const MObject& node, const SdfPath& id, HdMayaDelegateCtx* delegate); HDMAYA_API virtual ~HdMayaAdapter(); - const SdfPath& GetID() const { return _id; } + const SdfPath& GetID() const { return _id; } HdMayaDelegateCtx* GetDelegate() const { return _delegate; } HDMAYA_API void AddCallback(MCallbackId callbackId); @@ -44,7 +44,7 @@ class HdMayaAdapter { virtual void RemoveCallbacks(); HDMAYA_API virtual VtValue Get(const TfToken& key); - const MObject& GetNode() const { return _node; } + const MObject& GetNode() const { return _node; } HDMAYA_API virtual bool IsSupported() const = 0; HDMAYA_API @@ -62,10 +62,10 @@ class HdMayaAdapter { bool IsPopulated() const { return _isPopulated; } protected: - SdfPath _id; + SdfPath _id; std::vector _callbacks; - HdMayaDelegateCtx* _delegate; - MObject _node; + HdMayaDelegateCtx* _delegate; + MObject _node; bool _isPopulated = false; }; diff --git a/lib/usd/hdMaya/adapters/adapterDebugCodes.cpp b/lib/usd/hdMaya/adapters/adapterDebugCodes.cpp index bc053e9cd5..3a77d64e99 100644 --- a/lib/usd/hdMaya/adapters/adapterDebugCodes.cpp +++ b/lib/usd/hdMaya/adapters/adapterDebugCodes.cpp @@ -19,10 +19,10 @@ PXR_NAMESPACE_OPEN_SCOPE -TF_REGISTRY_FUNCTION(TfDebug) { +TF_REGISTRY_FUNCTION(TfDebug) +{ TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_ADAPTER_CALLBACKS, - "Print information adding and removal of adapter callbacks."); + HDMAYA_ADAPTER_CALLBACKS, "Print information adding and removal of adapter callbacks."); TF_DEBUG_ENVIRONMENT_SYMBOL( HDMAYA_ADAPTER_CURVE_PLUG_DIRTY, @@ -35,16 +35,13 @@ TF_REGISTRY_FUNCTION(TfDebug) { "a plug was dirtied."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_ADAPTER_DAG_HIERARCHY, - "Print information related to dag hierarchy changes."); + HDMAYA_ADAPTER_DAG_HIERARCHY, "Print information related to dag hierarchy changes."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_ADAPTER_DAG_PLUG_DIRTY, - "Print information about the dag node plug dirtying."); + HDMAYA_ADAPTER_DAG_PLUG_DIRTY, "Print information about the dag node plug dirtying."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_ADAPTER_GET, - "Print information about 'Get' calls to the adapter."); + HDMAYA_ADAPTER_GET, "Print information about 'Get' calls to the adapter."); TF_DEBUG_ENVIRONMENT_SYMBOL( HDMAYA_ADAPTER_GET_LIGHT_PARAM_VALUE, @@ -52,20 +49,16 @@ TF_REGISTRY_FUNCTION(TfDebug) { "calls to the light adapters."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_ADAPTER_IMAGEPLANES, - "Print information about drawing image planes."); + HDMAYA_ADAPTER_IMAGEPLANES, "Print information about drawing image planes."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_ADAPTER_LIGHT_SHADOWS, - "Print information about shadow rendering."); + HDMAYA_ADAPTER_LIGHT_SHADOWS, "Print information about shadow rendering."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_ADAPTER_MATERIALS, - "Print information about converting materials."); + HDMAYA_ADAPTER_MATERIALS, "Print information about converting materials."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_ADAPTER_MESH_PLUG_DIRTY, - "Print information about the mesh plug dirtying handled."); + HDMAYA_ADAPTER_MESH_PLUG_DIRTY, "Print information about the mesh plug dirtying handled."); TF_DEBUG_ENVIRONMENT_SYMBOL( HDMAYA_ADAPTER_MESH_UNHANDLED_PLUG_DIRTY, diff --git a/lib/usd/hdMaya/adapters/adapterDebugCodes.h b/lib/usd/hdMaya/adapters/adapterDebugCodes.h index f8ad916284..4323c3a1df 100644 --- a/lib/usd/hdMaya/adapters/adapterDebugCodes.h +++ b/lib/usd/hdMaya/adapters/adapterDebugCodes.h @@ -16,8 +16,8 @@ #ifndef HDMAYA_ADAPTER_DEBUG_CODES_H #define HDMAYA_ADAPTER_DEBUG_CODES_H -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE diff --git a/lib/usd/hdMaya/adapters/adapterRegistry.cpp b/lib/usd/hdMaya/adapters/adapterRegistry.cpp index 57fbbeb858..0887577d3f 100644 --- a/lib/usd/hdMaya/adapters/adapterRegistry.cpp +++ b/lib/usd/hdMaya/adapters/adapterRegistry.cpp @@ -15,41 +15,42 @@ // #include "adapterRegistry.h" -#include - -#include +#include #include #include #include #include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE TF_INSTANTIATE_SINGLETON(HdMayaAdapterRegistry); -void HdMayaAdapterRegistry::RegisterShapeAdapter( - const TfToken& type, ShapeAdapterCreator creator) { - GetInstance()._dagAdapters.insert({type, creator}); +void HdMayaAdapterRegistry::RegisterShapeAdapter(const TfToken& type, ShapeAdapterCreator creator) +{ + GetInstance()._dagAdapters.insert({ type, creator }); } HdMayaAdapterRegistry::ShapeAdapterCreator -HdMayaAdapterRegistry::GetShapeAdapterCreator(const MDagPath& dag) { - MFnDependencyNode depNode(dag.node()); +HdMayaAdapterRegistry::GetShapeAdapterCreator(const MDagPath& dag) +{ + MFnDependencyNode depNode(dag.node()); ShapeAdapterCreator ret = nullptr; - TfMapLookup( - GetInstance()._dagAdapters, TfToken(depNode.typeName().asChar()), &ret); + TfMapLookup(GetInstance()._dagAdapters, TfToken(depNode.typeName().asChar()), &ret); return ret; } HdMayaAdapterRegistry::ShapeAdapterCreator -HdMayaAdapterRegistry::GetProxyShapeAdapterCreator(const MDagPath& dag) { - MFnDependencyNode depNode(dag.node()); +HdMayaAdapterRegistry::GetProxyShapeAdapterCreator(const MDagPath& dag) +{ + MFnDependencyNode depNode(dag.node()); ShapeAdapterCreator ret = nullptr; - + // Temporary workaround for proxy shapes which may not have exact matching type in registration auto* proxyBase = dynamic_cast(depNode.userNode()); if (proxyBase) { @@ -60,37 +61,38 @@ HdMayaAdapterRegistry::GetProxyShapeAdapterCreator(const MDagPath& dag) { return ret; } -void HdMayaAdapterRegistry::RegisterLightAdapter( - const TfToken& type, LightAdapterCreator creator) { - GetInstance()._lightAdapters.insert({type, creator}); +void HdMayaAdapterRegistry::RegisterLightAdapter(const TfToken& type, LightAdapterCreator creator) +{ + GetInstance()._lightAdapters.insert({ type, creator }); } HdMayaAdapterRegistry::LightAdapterCreator -HdMayaAdapterRegistry::GetLightAdapterCreator(const MDagPath& dag) { - MFnDependencyNode depNode(dag.node()); +HdMayaAdapterRegistry::GetLightAdapterCreator(const MDagPath& dag) +{ + MFnDependencyNode depNode(dag.node()); LightAdapterCreator ret = nullptr; - TfMapLookup( - GetInstance()._lightAdapters, TfToken(depNode.typeName().asChar()), - &ret); + TfMapLookup(GetInstance()._lightAdapters, TfToken(depNode.typeName().asChar()), &ret); return ret; } void HdMayaAdapterRegistry::RegisterMaterialAdapter( - const TfToken& type, MaterialAdapterCreator creator) { - GetInstance()._materialAdapters.insert({type, creator}); + const TfToken& type, + MaterialAdapterCreator creator) +{ + GetInstance()._materialAdapters.insert({ type, creator }); } HdMayaAdapterRegistry::MaterialAdapterCreator -HdMayaAdapterRegistry::GetMaterialAdapterCreator(const MObject& node) { - MFnDependencyNode depNode(node); +HdMayaAdapterRegistry::GetMaterialAdapterCreator(const MObject& node) +{ + MFnDependencyNode depNode(node); MaterialAdapterCreator ret = nullptr; - TfMapLookup( - GetInstance()._materialAdapters, TfToken(depNode.typeName().asChar()), - &ret); + TfMapLookup(GetInstance()._materialAdapters, TfToken(depNode.typeName().asChar()), &ret); return ret; } -void HdMayaAdapterRegistry::LoadAllPlugin() { +void HdMayaAdapterRegistry::LoadAllPlugin() +{ static std::once_flag loadAllOnce; std::call_once(loadAllOnce, []() { TfRegistryManager::GetInstance().SubscribeTo(); @@ -107,12 +109,9 @@ void HdMayaAdapterRegistry::LoadAllPlugin() { PlugRegistry& plugReg = PlugRegistry::GetInstance(); for (auto& subType : adapterTypes) { - const PlugPluginPtr pluginForType = - plugReg.GetPluginForType(subType); + const PlugPluginPtr pluginForType = plugReg.GetPluginForType(subType); if (!pluginForType) { - TF_CODING_ERROR( - "Could not find plugin for '%s'", - subType.GetTypeName().c_str()); + TF_CODING_ERROR("Could not find plugin for '%s'", subType.GetTypeName().c_str()); return; } pluginForType->Load(); diff --git a/lib/usd/hdMaya/adapters/adapterRegistry.h b/lib/usd/hdMaya/adapters/adapterRegistry.h index 6bbcdc25f2..4786f6b71a 100644 --- a/lib/usd/hdMaya/adapters/adapterRegistry.h +++ b/lib/usd/hdMaya/adapters/adapterRegistry.h @@ -16,67 +16,61 @@ #ifndef HDMAYA_ADAPTER_REGISTRY_H #define HDMAYA_ADAPTER_REGISTRY_H -#include - -#include - -#include -#include - #include #include #include #include +#include +#include + +#include + +#include + PXR_NAMESPACE_OPEN_SCOPE -class HdMayaAdapterRegistry : public TfSingleton { +class HdMayaAdapterRegistry : public TfSingleton +{ friend class TfSingleton; HDMAYA_API HdMayaAdapterRegistry() = default; public: - using ShapeAdapterCreator = std::function; + using ShapeAdapterCreator + = std::function; HDMAYA_API - static void RegisterShapeAdapter( - const TfToken& type, ShapeAdapterCreator creator); + static void RegisterShapeAdapter(const TfToken& type, ShapeAdapterCreator creator); HDMAYA_API static ShapeAdapterCreator GetShapeAdapterCreator(const MDagPath& dag); HDMAYA_API static ShapeAdapterCreator GetProxyShapeAdapterCreator(const MDagPath& dag); - using LightAdapterCreator = std::function; + using LightAdapterCreator + = std::function; HDMAYA_API - static void RegisterLightAdapter( - const TfToken& type, LightAdapterCreator creator); + static void RegisterLightAdapter(const TfToken& type, LightAdapterCreator creator); HDMAYA_API static LightAdapterCreator GetLightAdapterCreator(const MDagPath& dag); - using MaterialAdapterCreator = std::function; + using MaterialAdapterCreator = std::function< + HdMayaMaterialAdapterPtr(const SdfPath&, HdMayaDelegateCtx*, const MObject&)>; HDMAYA_API - static void RegisterMaterialAdapter( - const TfToken& type, MaterialAdapterCreator creator); + static void RegisterMaterialAdapter(const TfToken& type, MaterialAdapterCreator creator); HDMAYA_API - static MaterialAdapterCreator GetMaterialAdapterCreator( - const MObject& node); + static MaterialAdapterCreator GetMaterialAdapterCreator(const MObject& node); // Find all HdMayaAdapter plugins, and load them all HDMAYA_API static void LoadAllPlugin(); private: - std::unordered_map - _dagAdapters; - std::unordered_map - _lightAdapters; - std::unordered_map - _materialAdapters; + std::unordered_map _dagAdapters; + std::unordered_map _lightAdapters; + std::unordered_map _materialAdapters; }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/hdMaya/adapters/aiSkydomeLightAdapter.cpp b/lib/usd/hdMaya/adapters/aiSkydomeLightAdapter.cpp index 6ef82fe4a0..06eeb209e6 100644 --- a/lib/usd/hdMaya/adapters/aiSkydomeLightAdapter.cpp +++ b/lib/usd/hdMaya/adapters/aiSkydomeLightAdapter.cpp @@ -13,14 +13,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include -#include -#include -#include -#include - #include #include #include @@ -28,22 +20,33 @@ #include #include +#include +#include +#include +#include +#include + +#include + PXR_NAMESPACE_OPEN_SCOPE -class HdMayaAiSkyDomeLightAdapter : public HdMayaLightAdapter { +class HdMayaAiSkyDomeLightAdapter : public HdMayaLightAdapter +{ public: - HdMayaAiSkyDomeLightAdapter( - HdMayaDelegateCtx* delegate, const MDagPath& dag) - : HdMayaLightAdapter(delegate, dag) {} - - const TfToken& LightType() const override { - return HdPrimTypeTokens->domeLight; + HdMayaAiSkyDomeLightAdapter(HdMayaDelegateCtx* delegate, const MDagPath& dag) + : HdMayaLightAdapter(delegate, dag) + { } - VtValue GetLightParamValue(const TfToken& paramName) override { - MStatus status; + const TfToken& LightType() const override { return HdPrimTypeTokens->domeLight; } + + VtValue GetLightParamValue(const TfToken& paramName) override + { + MStatus status; MFnDependencyNode light(GetNode(), &status); - if (ARCH_UNLIKELY(!status)) { return {}; } + if (ARCH_UNLIKELY(!status)) { + return {}; + } // We are not using precomputed attributes here, because we don't have // a guarantee that mtoa will be loaded before mtoh. @@ -55,8 +58,7 @@ class HdMayaAiSkyDomeLightAdapter : public HdMayaLightAdapter { conns.length() > 0 ? GfVec3f(1.0f, 1.0f, 1.0f) : GfVec3f( - plug.child(0).asFloat(), plug.child(1).asFloat(), - plug.child(2).asFloat())); + plug.child(0).asFloat(), plug.child(1).asFloat(), plug.child(2).asFloat())); } else if (paramName == HdLightTokens->intensity) { return VtValue(light.findPlug("intensity", true).asFloat()); } else if (paramName == HdLightTokens->exposure) { @@ -78,49 +80,49 @@ class HdMayaAiSkyDomeLightAdapter : public HdMayaLightAdapter { } else if (paramName == HdLightTokens->textureFile) { MPlugArray conns; light.findPlug("color", true).connectedTo(conns, true, false); - if (conns.length() < 1) { return VtValue(SdfAssetPath()); } + if (conns.length() < 1) { + return VtValue(SdfAssetPath()); + } MFnDependencyNode file(conns[0].node(), &status); if (ARCH_UNLIKELY( - !status || - (file.typeName() != HdMayaAdapterTokens->file.GetText()))) { + !status || (file.typeName() != HdMayaAdapterTokens->file.GetText()))) { return VtValue(SdfAssetPath()); } return VtValue(SdfAssetPath( - file.findPlug(MayaAttrs::file::fileTextureName, true) - .asString() - .asChar())); + file.findPlug(MayaAttrs::file::fileTextureName, true).asString().asChar())); } else if (paramName == HdLightTokens->enableColorTemperature) { return VtValue(false); #if USD_VERSION_NUM >= 1910 } else if (paramName == HdLightTokens->textureResource) { - auto fileObj = - GetConnectedFileNode(GetNode(), HdMayaAdapterTokens->color); + auto fileObj = GetConnectedFileNode(GetNode(), HdMayaAdapterTokens->color); // TODO: Return a default, white texture? // Ideally we would want to return a custom texture resource based // on the color, but not sure how easy that would be. - if (fileObj == MObject::kNullObj) { return {}; } - return VtValue{GetFileTextureResource( - fileObj, GetFileTexturePath(MFnDependencyNode(fileObj)), - GetDelegate()->GetParams().textureMemoryPerTexture)}; + if (fileObj == MObject::kNullObj) { + return {}; + } + return VtValue { GetFileTextureResource( + fileObj, + GetFileTexturePath(MFnDependencyNode(fileObj)), + GetDelegate()->GetParams().textureMemoryPerTexture) }; #endif // USD_VERSION_NUM >= 1910 } return {}; } }; -TF_REGISTRY_FUNCTION(TfType) { - TfType::Define< - HdMayaAiSkyDomeLightAdapter, TfType::Bases >(); +TF_REGISTRY_FUNCTION(TfType) +{ + TfType::Define>(); } -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, domeLight) { +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, domeLight) +{ HdMayaAdapterRegistry::RegisterLightAdapter( TfToken("aiSkyDomeLight"), - [](HdMayaDelegateCtx* delegate, - const MDagPath& dag) -> HdMayaLightAdapterPtr { - return HdMayaLightAdapterPtr( - new HdMayaAiSkyDomeLightAdapter(delegate, dag)); + [](HdMayaDelegateCtx* delegate, const MDagPath& dag) -> HdMayaLightAdapterPtr { + return HdMayaLightAdapterPtr(new HdMayaAiSkyDomeLightAdapter(delegate, dag)); }); } diff --git a/lib/usd/hdMaya/adapters/areaLightAdapter.cpp b/lib/usd/hdMaya/adapters/areaLightAdapter.cpp index 3ccd3c46f4..25b633dbd6 100644 --- a/lib/usd/hdMaya/adapters/areaLightAdapter.cpp +++ b/lib/usd/hdMaya/adapters/areaLightAdapter.cpp @@ -13,26 +13,28 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include -#include - #include #include #include +#include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE -class HdMayaAreaLightAdapter : public HdMayaLightAdapter { +class HdMayaAreaLightAdapter : public HdMayaLightAdapter +{ public: HdMayaAreaLightAdapter(HdMayaDelegateCtx* delegate, const MDagPath& dag) - : HdMayaLightAdapter(delegate, dag) {} - - void _CalculateLightParams(GlfSimpleLight& light) override { - light.SetSpotCutoff(90.0f); + : HdMayaLightAdapter(delegate, dag) + { } - const TfToken& LightType() const override { + void _CalculateLightParams(GlfSimpleLight& light) override { light.SetSpotCutoff(90.0f); } + + const TfToken& LightType() const override + { if (GetDelegate()->IsHdSt()) { return HdPrimTypeTokens->simpleLight; } else { @@ -40,11 +42,13 @@ class HdMayaAreaLightAdapter : public HdMayaLightAdapter { } } - VtValue GetLightParamValue(const TfToken& paramName) override { + VtValue GetLightParamValue(const TfToken& paramName) override + { TF_DEBUG(HDMAYA_ADAPTER_GET_LIGHT_PARAM_VALUE) .Msg( "Called HdMayaAreaLightAdapter::GetLightParamValue(%s) - %s\n", - paramName.GetText(), GetDagPath().partialPathName().asChar()); + paramName.GetText(), + GetDagPath().partialPathName().asChar()); if (paramName == HdLightTokens->width) { return VtValue(2.0f); @@ -55,18 +59,17 @@ class HdMayaAreaLightAdapter : public HdMayaLightAdapter { } }; -TF_REGISTRY_FUNCTION(TfType) { - TfType::Define< - HdMayaAreaLightAdapter, TfType::Bases >(); +TF_REGISTRY_FUNCTION(TfType) +{ + TfType::Define>(); } -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, pointLight) { +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, pointLight) +{ HdMayaAdapterRegistry::RegisterLightAdapter( TfToken("areaLight"), - [](HdMayaDelegateCtx* delegate, - const MDagPath& dag) -> HdMayaLightAdapterPtr { - return HdMayaLightAdapterPtr( - new HdMayaAreaLightAdapter(delegate, dag)); + [](HdMayaDelegateCtx* delegate, const MDagPath& dag) -> HdMayaLightAdapterPtr { + return HdMayaLightAdapterPtr(new HdMayaAreaLightAdapter(delegate, dag)); }); } diff --git a/lib/usd/hdMaya/adapters/constantShadowMatrix.h b/lib/usd/hdMaya/adapters/constantShadowMatrix.h index 1491a3e37c..77f820155d 100644 --- a/lib/usd/hdMaya/adapters/constantShadowMatrix.h +++ b/lib/usd/hdMaya/adapters/constantShadowMatrix.h @@ -16,31 +16,34 @@ #ifndef HDMAYA_SHADOW_MATRIX_H #define HDMAYA_SHADOW_MATRIX_H -#include +#include +#include +#include #include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE -class HdMayaConstantShadowMatrix : public HdxShadowMatrixComputation { +class HdMayaConstantShadowMatrix : public HdxShadowMatrixComputation +{ public: explicit HdMayaConstantShadowMatrix(const GfMatrix4d& mat) - : _shadowMatrix(mat) {} + : _shadowMatrix(mat) + { + } #if HDX_API_VERSION >= 6 - inline std::vector Compute( - const GfVec4f& viewport, - CameraUtilConformWindowPolicy policy) override { - return {_shadowMatrix}; + inline std::vector + Compute(const GfVec4f& viewport, CameraUtilConformWindowPolicy policy) override + { + return { _shadowMatrix }; } #else - inline GfMatrix4d Compute( - const GfVec4f& viewport, - CameraUtilConformWindowPolicy policy) override { + inline GfMatrix4d + Compute(const GfVec4f& viewport, CameraUtilConformWindowPolicy policy) override + { return _shadowMatrix; } #endif diff --git a/lib/usd/hdMaya/adapters/dagAdapter.cpp b/lib/usd/hdMaya/adapters/dagAdapter.cpp index f8540e8d17..bf45de7431 100644 --- a/lib/usd/hdMaya/adapters/dagAdapter.cpp +++ b/lib/usd/hdMaya/adapters/dagAdapter.cpp @@ -15,27 +15,25 @@ // #include "dagAdapter.h" +#include +#include + +#include +#include + #include -#include -#include #include #include +#include +#include #include #include #include #include -#include -#include - -#include -#include - PXR_NAMESPACE_OPEN_SCOPE -TF_REGISTRY_FUNCTION(TfType) { - TfType::Define >(); -} +TF_REGISTRY_FUNCTION(TfType) { TfType::Define>(); } // clang-format off TF_DEFINE_PRIVATE_TOKENS( @@ -51,17 +49,18 @@ TF_DEFINE_PRIVATE_TOKENS( namespace { -void _TransformNodeDirty(MObject& node, MPlug& plug, void* clientData) { +void _TransformNodeDirty(MObject& node, MPlug& plug, void* clientData) +{ auto* adapter = reinterpret_cast(clientData); TF_DEBUG(HDMAYA_ADAPTER_DAG_PLUG_DIRTY) .Msg( "Dag adapter marking prim (%s) dirty because .%s plug was " "dirtied.\n", - adapter->GetID().GetText(), plug.partialName().asChar()); - if (plug == MayaAttrs::dagNode::visibility || - plug == MayaAttrs::dagNode::intermediateObject || - plug == MayaAttrs::dagNode::overrideEnabled || - plug == MayaAttrs::dagNode::overrideVisibility) { + adapter->GetID().GetText(), + plug.partialName().asChar()); + if (plug == MayaAttrs::dagNode::visibility || plug == MayaAttrs::dagNode::intermediateObject + || plug == MayaAttrs::dagNode::overrideEnabled + || plug == MayaAttrs::dagNode::overrideVisibility) { // Unfortunately, during this callback, we can't actually // query the new object's visiblity - the plug dirty hasn't // really propagated yet. So we just mark our own _visibility @@ -72,9 +71,7 @@ void _TransformNodeDirty(MObject& node, MPlug& plug, void* clientData) { // that dirty as well... if (adapter->IsVisible(false)) { // Transform can change while dag path is hidden. - adapter->MarkDirty( - HdChangeTracker::DirtyVisibility | - HdChangeTracker::DirtyTransform); + adapter->MarkDirty(HdChangeTracker::DirtyVisibility | HdChangeTracker::DirtyTransform); adapter->InvalidateTransform(); } else { adapter->MarkDirty(HdChangeTracker::DirtyVisibility); @@ -88,50 +85,57 @@ void _TransformNodeDirty(MObject& node, MPlug& plug, void* clientData) { } } -void _HierarchyChanged(MDagPath& child, MDagPath& parent, void* clientData) { +void _HierarchyChanged(MDagPath& child, MDagPath& parent, void* clientData) +{ TF_UNUSED(child); auto* adapter = reinterpret_cast(clientData); TF_DEBUG(HDMAYA_ADAPTER_DAG_HIERARCHY) .Msg( "Dag hierarchy changed for prim (%s) because %s had parent %s " "added/removed.\n", - adapter->GetID().GetText(), child.partialPathName().asChar(), + adapter->GetID().GetText(), + child.partialPathName().asChar(), parent.partialPathName().asChar()); adapter->RemoveCallbacks(); adapter->RemovePrim(); - adapter->GetDelegate()->RecreateAdapterOnIdle( - adapter->GetID(), adapter->GetNode()); + adapter->GetDelegate()->RecreateAdapterOnIdle(adapter->GetID(), adapter->GetNode()); } -void _InstancerNodeDirty(MObject& node, MPlug& plug, void* clientData) { +void _InstancerNodeDirty(MObject& node, MPlug& plug, void* clientData) +{ auto* adapter = reinterpret_cast(clientData); TF_DEBUG(HDMAYA_ADAPTER_DAG_PLUG_DIRTY) .Msg( "Dag instancer adapter marking prim (%s) dirty because %s plug was " "dirtied.\n", - adapter->GetID().GetText(), plug.partialName().asChar()); + adapter->GetID().GetText(), + plug.partialName().asChar()); adapter->MarkDirty( - HdChangeTracker::DirtyInstancer | HdChangeTracker::DirtyInstanceIndex | - HdChangeTracker::DirtyPrimvar); + HdChangeTracker::DirtyInstancer | HdChangeTracker::DirtyInstanceIndex + | HdChangeTracker::DirtyPrimvar); } -const auto _instancePrimvarDescriptors = HdPrimvarDescriptorVector{ - {_tokens->instanceTransform, HdInterpolationInstance, - HdPrimvarRoleTokens->none}, +const auto _instancePrimvarDescriptors = HdPrimvarDescriptorVector { + { _tokens->instanceTransform, HdInterpolationInstance, HdPrimvarRoleTokens->none }, }; } // namespace HdMayaDagAdapter::HdMayaDagAdapter( - const SdfPath& id, HdMayaDelegateCtx* delegate, const MDagPath& dagPath) - : HdMayaAdapter(dagPath.node(), id, delegate), _dagPath(dagPath) { + const SdfPath& id, + HdMayaDelegateCtx* delegate, + const MDagPath& dagPath) + : HdMayaAdapter(dagPath.node(), id, delegate) + , _dagPath(dagPath) +{ // We shouldn't call virtual functions in constructors. _isVisible = GetDagPath().isVisible(); _visibilityDirty = false; _isInstanced = _dagPath.isInstanced() && _dagPath.instanceNumber() == 0; } -void HdMayaDagAdapter::_CalculateTransform() { +void HdMayaDagAdapter::_CalculateTransform() +{ if (_invalidTransform) { if (IsInstanced()) { _transform[0].SetIdentity(); @@ -149,23 +153,23 @@ void HdMayaDagAdapter::_CalculateTransform() { } }; -const GfMatrix4d& HdMayaDagAdapter::GetTransform() { +const GfMatrix4d& HdMayaDagAdapter::GetTransform() +{ TF_DEBUG(HDMAYA_ADAPTER_GET) - .Msg( - "Called HdMayaDagAdapter::GetTransform() - %s\n", - _dagPath.partialPathName().asChar()); + .Msg("Called HdMayaDagAdapter::GetTransform() - %s\n", _dagPath.partialPathName().asChar()); _CalculateTransform(); return _transform[0]; } -size_t HdMayaDagAdapter::SampleTransform( - size_t maxSampleCount, float* times, GfMatrix4d* samples) { +size_t HdMayaDagAdapter::SampleTransform(size_t maxSampleCount, float* times, GfMatrix4d* samples) +{ _CalculateTransform(); - if (maxSampleCount < 1) { return 0; } + if (maxSampleCount < 1) { + return 0; + } times[0] = 0.0f; samples[0] = _transform[0]; - if (maxSampleCount == 1 || - !GetDelegate()->GetParams().enableMotionSamples) { + if (maxSampleCount == 1 || !GetDelegate()->GetParams().enableMotionSamples) { return 1; } else { times[1] = 1.0f; @@ -174,27 +178,27 @@ size_t HdMayaDagAdapter::SampleTransform( } } -void HdMayaDagAdapter::CreateCallbacks() { +void HdMayaDagAdapter::CreateCallbacks() +{ MStatus status; TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) - .Msg( - "Creating dag adapter callbacks for prim (%s).\n", - GetID().GetText()); + .Msg("Creating dag adapter callbacks for prim (%s).\n", GetID().GetText()); MDagPathArray dags; if (MDagPath::getAllPathsTo(GetDagPath().node(), dags)) { const auto numDags = dags.length(); - auto dagNodeDirtyCallback = - numDags > 1 ? _InstancerNodeDirty : _TransformNodeDirty; - for (auto i = decltype(numDags){0}; i < numDags; ++i) { + auto dagNodeDirtyCallback = numDags > 1 ? _InstancerNodeDirty : _TransformNodeDirty; + for (auto i = decltype(numDags) { 0 }; i < numDags; ++i) { auto dag = dags[i]; for (; dag.length() > 0; dag.pop()) { MObject obj = dag.node(); if (obj != MObject::kNullObj) { auto id = MNodeMessage::addNodeDirtyPlugCallback( obj, dagNodeDirtyCallback, this, &status); - if (status) { AddCallback(id); } + if (status) { + AddCallback(id); + } TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) .Msg( "- Added _InstancerNodeDirty callback for " @@ -208,12 +212,12 @@ void HdMayaDagAdapter::CreateCallbacks() { HdMayaAdapter::CreateCallbacks(); } -void HdMayaDagAdapter::MarkDirty(HdDirtyBits dirtyBits) { +void HdMayaDagAdapter::MarkDirty(HdDirtyBits dirtyBits) +{ if (dirtyBits != 0) { GetDelegate()->GetChangeTracker().MarkRprimDirty(GetID(), dirtyBits); if (IsInstanced()) { - GetDelegate()->GetChangeTracker().MarkInstancerDirty( - GetInstancerID(), dirtyBits); + GetDelegate()->GetChangeTracker().MarkInstancerDirty(GetInstancerID(), dirtyBits); } if (dirtyBits & HdChangeTracker::DirtyVisibility) { _visibilityDirty = true; @@ -221,18 +225,23 @@ void HdMayaDagAdapter::MarkDirty(HdDirtyBits dirtyBits) { } } -void HdMayaDagAdapter::RemovePrim() { - if (!_isPopulated) { return; } +void HdMayaDagAdapter::RemovePrim() +{ + if (!_isPopulated) { + return; + } GetDelegate()->RemoveRprim(GetID()); if (_isInstanced) { - GetDelegate()->RemoveInstancer( - GetID().AppendProperty(_tokens->instancer)); + GetDelegate()->RemoveInstancer(GetID().AppendProperty(_tokens->instancer)); } _isPopulated = false; } -bool HdMayaDagAdapter::UpdateVisibility() { - if (ARCH_UNLIKELY(!GetDagPath().isValid())) { return false; } +bool HdMayaDagAdapter::UpdateVisibility() +{ + if (ARCH_UNLIKELY(!GetDagPath().isValid())) { + return false; + } const auto visible = _GetVisibility(); _visibilityDirty = false; if (visible != _isVisible) { @@ -242,19 +251,27 @@ bool HdMayaDagAdapter::UpdateVisibility() { return false; } -bool HdMayaDagAdapter::IsVisible(bool checkDirty) { - if (checkDirty && _visibilityDirty) { UpdateVisibility(); } +bool HdMayaDagAdapter::IsVisible(bool checkDirty) +{ + if (checkDirty && _visibilityDirty) { + UpdateVisibility(); + } return _isVisible; } -VtIntArray HdMayaDagAdapter::GetInstanceIndices(const SdfPath& prototypeId) { - if (!IsInstanced()) { return {}; } +VtIntArray HdMayaDagAdapter::GetInstanceIndices(const SdfPath& prototypeId) +{ + if (!IsInstanced()) { + return {}; + } MDagPathArray dags; - if (!MDagPath::getAllPathsTo(GetDagPath().node(), dags)) { return {}; } + if (!MDagPath::getAllPathsTo(GetDagPath().node(), dags)) { + return {}; + } const auto numDags = dags.length(); VtIntArray ret; ret.reserve(numDags); - for (auto i = decltype(numDags){0}; i < numDags; ++i) { + for (auto i = decltype(numDags) { 0 }; i < numDags; ++i) { if (dags[i].isValid() && dags[i].isVisible()) { ret.push_back(static_cast(ret.size())); } @@ -262,15 +279,15 @@ VtIntArray HdMayaDagAdapter::GetInstanceIndices(const SdfPath& prototypeId) { return ret; } -void HdMayaDagAdapter::_AddHierarchyChangedCallbacks(MDagPath& dag) { +void HdMayaDagAdapter::_AddHierarchyChangedCallbacks(MDagPath& dag) +{ MStatus status; - auto id = MDagMessage::addParentAddedDagPathCallback( - dag, _HierarchyChanged, this, &status); - if (status) { AddCallback(id); } + auto id = MDagMessage::addParentAddedDagPathCallback(dag, _HierarchyChanged, this, &status); + if (status) { + AddCallback(id); + } TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) - .Msg( - "- Added parent added callback for dagPath (%s).\n", - dag.partialPathName().asChar()); + .Msg("- Added parent added callback for dagPath (%s).\n", dag.partialPathName().asChar()); // We need a parent removed callback, even for non-instances, // because when an object is removed from the scene due to an @@ -278,23 +295,26 @@ void HdMayaDagAdapter::_AddHierarchyChangedCallbacks(MDagPath& dag) { // callbacks are triggered. The parent-removed callback IS // triggered, though, so it's a way to catch deletion due to // undo... - id = MDagMessage::addParentRemovedDagPathCallback( - dag, _HierarchyChanged, this, &status); - if (status) { AddCallback(id); } + id = MDagMessage::addParentRemovedDagPathCallback(dag, _HierarchyChanged, this, &status); + if (status) { + AddCallback(id); + } TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) - .Msg( - "- Added parent removed callback for dagPath (%s).\n", - dag.partialPathName().asChar()); + .Msg("- Added parent removed callback for dagPath (%s).\n", dag.partialPathName().asChar()); } -SdfPath HdMayaDagAdapter::GetInstancerID() const { - if (!_isInstanced) { return {}; } +SdfPath HdMayaDagAdapter::GetInstancerID() const +{ + if (!_isInstanced) { + return {}; + } return GetID().AppendProperty(_tokens->instancer); } -HdPrimvarDescriptorVector HdMayaDagAdapter::GetInstancePrimvarDescriptors( - HdInterpolation interpolation) const { +HdPrimvarDescriptorVector +HdMayaDagAdapter::GetInstancePrimvarDescriptors(HdInterpolation interpolation) const +{ if (interpolation == HdInterpolationInstance) { return _instancePrimvarDescriptors; } else { @@ -302,18 +322,19 @@ HdPrimvarDescriptorVector HdMayaDagAdapter::GetInstancePrimvarDescriptors( } } -bool HdMayaDagAdapter::_GetVisibility() const { - return GetDagPath().isVisible(); -} +bool HdMayaDagAdapter::_GetVisibility() const { return GetDagPath().isVisible(); } -VtValue HdMayaDagAdapter::GetInstancePrimvar(const TfToken& key) { +VtValue HdMayaDagAdapter::GetInstancePrimvar(const TfToken& key) +{ if (key == _tokens->instanceTransform) { MDagPathArray dags; - if (!MDagPath::getAllPathsTo(GetDagPath().node(), dags)) { return {}; } - const auto numDags = dags.length(); + if (!MDagPath::getAllPathsTo(GetDagPath().node(), dags)) { + return {}; + } + const auto numDags = dags.length(); VtArray ret; ret.reserve(numDags); - for (auto i = decltype(numDags){0}; i < numDags; ++i) { + for (auto i = decltype(numDags) { 0 }; i < numDags; ++i) { if (dags[i].isValid() && dags[i].isVisible()) { ret.push_back(GetGfMatrixFromMaya(dags[i].inclusiveMatrix())); } diff --git a/lib/usd/hdMaya/adapters/dagAdapter.h b/lib/usd/hdMaya/adapters/dagAdapter.h index 2bb15007dd..060c2f1d92 100644 --- a/lib/usd/hdMaya/adapters/dagAdapter.h +++ b/lib/usd/hdMaya/adapters/dagAdapter.h @@ -16,35 +16,34 @@ #ifndef HDMAYA_DG_ADAPTER_H #define HDMAYA_DG_ADAPTER_H -#include - -#include -#include -#include -#include -#include -#include +#include +#include +#include -#include #include #include #include #include #include #include +#include -#include -#include -#include +#include +#include +#include +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -class HdMayaDagAdapter : public HdMayaAdapter { +class HdMayaDagAdapter : public HdMayaAdapter +{ protected: HDMAYA_API - HdMayaDagAdapter( - const SdfPath& id, HdMayaDelegateCtx* delegate, - const MDagPath& dagPath); + HdMayaDagAdapter(const SdfPath& id, HdMayaDelegateCtx* delegate, const MDagPath& dagPath); public: HDMAYA_API @@ -60,21 +59,19 @@ class HdMayaDagAdapter : public HdMayaAdapter { HDMAYA_API const GfMatrix4d& GetTransform(); HDMAYA_API - size_t SampleTransform( - size_t maxSampleCount, float* times, GfMatrix4d* samples); + size_t SampleTransform(size_t maxSampleCount, float* times, GfMatrix4d* samples); HDMAYA_API - bool UpdateVisibility(); - bool IsVisible(bool checkDirty = true); + bool UpdateVisibility(); + bool IsVisible(bool checkDirty = true); const MDagPath& GetDagPath() const { return _dagPath; } - void InvalidateTransform() { _invalidTransform = true; } - bool IsInstanced() const { return _isInstanced; } + void InvalidateTransform() { _invalidTransform = true; } + bool IsInstanced() const { return _isInstanced; } HDMAYA_API SdfPath GetInstancerID() const; HDMAYA_API virtual VtIntArray GetInstanceIndices(const SdfPath& prototypeId); HDMAYA_API - HdPrimvarDescriptorVector GetInstancePrimvarDescriptors( - HdInterpolation interpolation) const; + HdPrimvarDescriptorVector GetInstancePrimvarDescriptors(HdInterpolation interpolation) const; HDMAYA_API VtValue GetInstancePrimvar(const TfToken& key); @@ -87,12 +84,12 @@ class HdMayaDagAdapter : public HdMayaAdapter { virtual bool _GetVisibility() const; private: - MDagPath _dagPath; + MDagPath _dagPath; GfMatrix4d _transform[2]; - bool _isVisible = true; - bool _visibilityDirty = true; - bool _invalidTransform = true; - bool _isInstanced = false; + bool _isVisible = true; + bool _visibilityDirty = true; + bool _invalidTransform = true; + bool _isInstanced = false; }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/hdMaya/adapters/directionalLightAdapter.cpp b/lib/usd/hdMaya/adapters/directionalLightAdapter.cpp index 1c9777522c..c2cab3eaaa 100644 --- a/lib/usd/hdMaya/adapters/directionalLightAdapter.cpp +++ b/lib/usd/hdMaya/adapters/directionalLightAdapter.cpp @@ -13,29 +13,32 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include +#include +#include +#include +#include -#include #include #include +#include #include -#include -#include -#include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -class HdMayaDirectionalLightAdapter : public HdMayaLightAdapter { +class HdMayaDirectionalLightAdapter : public HdMayaLightAdapter +{ public: - HdMayaDirectionalLightAdapter( - HdMayaDelegateCtx* delegate, const MDagPath& dag) - : HdMayaLightAdapter(delegate, dag) {} + HdMayaDirectionalLightAdapter(HdMayaDelegateCtx* delegate, const MDagPath& dag) + : HdMayaLightAdapter(delegate, dag) + { + } - const TfToken& LightType() const override { + const TfToken& LightType() const override + { if (GetDelegate()->IsHdSt()) { return HdPrimTypeTokens->simpleLight; } else { @@ -43,22 +46,25 @@ class HdMayaDirectionalLightAdapter : public HdMayaLightAdapter { } } - void _CalculateLightParams(GlfSimpleLight& light) override { + void _CalculateLightParams(GlfSimpleLight& light) override + { // Directional lights point toward -Z, but we need the opposite // for the position so the light acts as a directional light. const auto direction = GfVec4f(0.0, 0.0, 1.0, 0.0) * GetTransform(); light.SetHasShadow(true); - light.SetPosition({direction[0], direction[1], direction[2], 0.0f}); + light.SetPosition({ direction[0], direction[1], direction[2], 0.0f }); } - VtValue Get(const TfToken& key) override { + VtValue Get(const TfToken& key) override + { TF_DEBUG(HDMAYA_ADAPTER_GET) .Msg( - "Called HdMayaSpotLightAdapter::Get(%s) - %s\n", key.GetText(), + "Called HdMayaSpotLightAdapter::Get(%s) - %s\n", + key.GetText(), GetDagPath().partialPathName().asChar()); if (key == HdLightTokens->shadowParams) { - HdxShadowParams shadowParams; + HdxShadowParams shadowParams; MFnDirectionalLight mayaLight(GetDagPath()); if (!GetShadowsEnabled(mayaLight)) { shadowParams.enabled = false; @@ -74,33 +80,33 @@ class HdMayaDirectionalLightAdapter : public HdMayaLightAdapter { return HdMayaLightAdapter::Get(key); } - VtValue GetLightParamValue(const TfToken& paramName) override { + VtValue GetLightParamValue(const TfToken& paramName) override + { if (paramName == HdLightTokens->angle) { - MStatus status; + MStatus status; MFnDependencyNode lightNode(GetNode(), &status); - if (ARCH_UNLIKELY(!status)) { return VtValue(0.0f); } + if (ARCH_UNLIKELY(!status)) { + return VtValue(0.0f); + } return VtValue( - lightNode - .findPlug(MayaAttrs::directionalLight::lightAngle, true) - .asFloat()); + lightNode.findPlug(MayaAttrs::directionalLight::lightAngle, true).asFloat()); } else { return HdMayaLightAdapter::GetLightParamValue(paramName); } } }; -TF_REGISTRY_FUNCTION(TfType) { - TfType::Define< - HdMayaDirectionalLightAdapter, TfType::Bases >(); +TF_REGISTRY_FUNCTION(TfType) +{ + TfType::Define>(); } -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, pointLight) { +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, pointLight) +{ HdMayaAdapterRegistry::RegisterLightAdapter( TfToken("directionalLight"), - [](HdMayaDelegateCtx* delegate, - const MDagPath& dag) -> HdMayaLightAdapterPtr { - return HdMayaLightAdapterPtr( - new HdMayaDirectionalLightAdapter(delegate, dag)); + [](HdMayaDelegateCtx* delegate, const MDagPath& dag) -> HdMayaLightAdapterPtr { + return HdMayaLightAdapterPtr(new HdMayaDirectionalLightAdapter(delegate, dag)); }); } diff --git a/lib/usd/hdMaya/adapters/lightAdapter.cpp b/lib/usd/hdMaya/adapters/lightAdapter.cpp index 0c75c72ac5..edfb58ebd6 100644 --- a/lib/usd/hdMaya/adapters/lightAdapter.cpp +++ b/lib/usd/hdMaya/adapters/lightAdapter.cpp @@ -15,7 +15,14 @@ // #include "lightAdapter.h" -#include +#include +#include +#include + +#include +#include +#include +#include #include #include @@ -24,32 +31,28 @@ #include #include -#include -#include -#include -#include - -#include -#include -#include +#include #if HDX_API_VERSION < 7 -#include #include +#include #endif - PXR_NAMESPACE_OPEN_SCOPE -TF_REGISTRY_FUNCTION(TfType) { - TfType::Define >(); +TF_REGISTRY_FUNCTION(TfType) +{ + TfType::Define>(); } namespace { void _changeVisibility( - MNodeMessage::AttributeMessage msg, MPlug& plug, MPlug& otherPlug, - void* clientData) { + MNodeMessage::AttributeMessage msg, + MPlug& plug, + MPlug& otherPlug, + void* clientData) +{ TF_UNUSED(msg); TF_UNUSED(otherPlug); if (plug == MayaAttrs::dagNode::visibility) { @@ -62,18 +65,19 @@ void _changeVisibility( } } -void _dirtyTransform(MObject& node, void* clientData) { +void _dirtyTransform(MObject& node, void* clientData) +{ TF_UNUSED(node); auto* adapter = reinterpret_cast(clientData); if (adapter->IsVisible()) { adapter->MarkDirty( - HdLight::DirtyTransform | HdLight::DirtyParams | - HdLight::DirtyShadowParams); + HdLight::DirtyTransform | HdLight::DirtyParams | HdLight::DirtyShadowParams); adapter->InvalidateTransform(); } } -void _dirtyParams(MObject& node, void* clientData) { +void _dirtyParams(MObject& node, void* clientData) +{ TF_UNUSED(node); auto* adapter = reinterpret_cast(clientData); if (adapter->IsVisible()) { @@ -86,88 +90,85 @@ const MString defaultLightSet("defaultLightSet"); } // namespace -HdMayaLightAdapter::HdMayaLightAdapter( - HdMayaDelegateCtx* delegate, const MDagPath& dag) - : HdMayaDagAdapter(delegate->GetPrimPath(dag, true), delegate, dag) { +HdMayaLightAdapter::HdMayaLightAdapter(HdMayaDelegateCtx* delegate, const MDagPath& dag) + : HdMayaDagAdapter(delegate->GetPrimPath(dag, true), delegate, dag) +{ // This should be avoided, not a good idea to call virtual functions // directly or indirectly in a constructor. UpdateVisibility(); _shadowProjectionMatrix.SetIdentity(); } -bool HdMayaLightAdapter::IsSupported() const { +bool HdMayaLightAdapter::IsSupported() const +{ return GetDelegate()->GetRenderIndex().IsSprimTypeSupported(LightType()); } -void HdMayaLightAdapter::Populate() { - if (_isPopulated) { return; } +void HdMayaLightAdapter::Populate() +{ + if (_isPopulated) { + return; + } if (IsVisible()) { GetDelegate()->InsertSprim(LightType(), GetID(), HdLight::AllDirty); _isPopulated = true; } } -void HdMayaLightAdapter::MarkDirty(HdDirtyBits dirtyBits) { +void HdMayaLightAdapter::MarkDirty(HdDirtyBits dirtyBits) +{ if (dirtyBits != 0) { GetDelegate()->GetChangeTracker().MarkSprimDirty(GetID(), dirtyBits); } } -void HdMayaLightAdapter::RemovePrim() { - if (!_isPopulated) { return; } +void HdMayaLightAdapter::RemovePrim() +{ + if (!_isPopulated) { + return; + } GetDelegate()->RemoveSprim(LightType(), GetID()); _isPopulated = false; } -bool HdMayaLightAdapter::HasType(const TfToken& typeId) const { - return typeId == LightType(); -} +bool HdMayaLightAdapter::HasType(const TfToken& typeId) const { return typeId == LightType(); } -VtValue HdMayaLightAdapter::Get(const TfToken& key) { +VtValue HdMayaLightAdapter::Get(const TfToken& key) +{ TF_DEBUG(HDMAYA_ADAPTER_GET) .Msg( - "Called HdMayaLightAdapter::Get(%s) - %s\n", key.GetText(), + "Called HdMayaLightAdapter::Get(%s) - %s\n", + key.GetText(), GetDagPath().partialPathName().asChar()); if (key == HdLightTokens->params) { - MFnLight mayaLight(GetDagPath()); + MFnLight mayaLight(GetDagPath()); GlfSimpleLight light; - const auto color = mayaLight.color(); - const auto intensity = mayaLight.intensity(); - MPoint pt(0.0, 0.0, 0.0, 1.0); - const auto inclusiveMatrix = GetDagPath().inclusiveMatrix(); - const auto position = pt * inclusiveMatrix; + const auto color = mayaLight.color(); + const auto intensity = mayaLight.intensity(); + MPoint pt(0.0, 0.0, 0.0, 1.0); + const auto inclusiveMatrix = GetDagPath().inclusiveMatrix(); + const auto position = pt * inclusiveMatrix; // This will return zero / false if the plug is nonexistent. - const auto decayRate = - mayaLight - .findPlug(MayaAttrs::nonAmbientLightShapeNode::decayRate, true) - .asShort(); - const auto emitDiffuse = - mayaLight - .findPlug( - MayaAttrs::nonAmbientLightShapeNode::emitDiffuse, true) - .asBool(); - const auto emitSpecular = - mayaLight - .findPlug( - MayaAttrs::nonAmbientLightShapeNode::emitSpecular, true) - .asBool(); - MVector pv(0.0, 0.0, -1.0); + const auto decayRate + = mayaLight.findPlug(MayaAttrs::nonAmbientLightShapeNode::decayRate, true).asShort(); + const auto emitDiffuse + = mayaLight.findPlug(MayaAttrs::nonAmbientLightShapeNode::emitDiffuse, true).asBool(); + const auto emitSpecular + = mayaLight.findPlug(MayaAttrs::nonAmbientLightShapeNode::emitSpecular, true).asBool(); + MVector pv(0.0, 0.0, -1.0); const auto lightDirection = (pv * inclusiveMatrix).normal(); light.SetHasShadow(false); const GfVec4f zeroColor(0.0f, 0.0f, 0.0f, 1.0f); const GfVec4f lightColor( - color.r * intensity, color.g * intensity, color.b * intensity, - 1.0f); + color.r * intensity, color.g * intensity, color.b * intensity, 1.0f); light.SetDiffuse(emitDiffuse ? lightColor : zeroColor); light.SetAmbient(zeroColor); light.SetSpecular(emitSpecular ? lightColor : zeroColor); light.SetShadowResolution(1024); light.SetID(GetID()); - light.SetPosition( - GfVec4f(position.x, position.y, position.z, position.w)); - light.SetSpotDirection( - GfVec3f(lightDirection.x, lightDirection.y, lightDirection.z)); + light.SetPosition(GfVec4f(position.x, position.y, position.z, position.w)); + light.SetSpotDirection(GfVec3f(lightDirection.x, lightDirection.y, lightDirection.z)); if (decayRate == 0) { light.SetAttenuation(GfVec3f(1.0f, 0.0f, 0.0f)); } else if (decayRate == 1) { @@ -175,15 +176,13 @@ VtValue HdMayaLightAdapter::Get(const TfToken& key) { } else if (decayRate == 2) { light.SetAttenuation(GfVec3f(0.0f, 0.0f, 1.0f)); } - light.SetTransform( - GetGfMatrixFromMaya(GetDagPath().inclusiveMatrixInverse())); + light.SetTransform(GetGfMatrixFromMaya(GetDagPath().inclusiveMatrixInverse())); _CalculateLightParams(light); return VtValue(light); } else if (key == HdTokens->transform) { return VtValue(HdMayaDagAdapter::GetTransform()); } else if (key == HdLightTokens->shadowCollection) { - HdRprimCollection coll( - HdTokens->geometry, HdReprSelector(HdReprTokens->refined)); + HdRprimCollection coll(HdTokens->geometry, HdReprSelector(HdReprTokens->refined)); return VtValue(coll); } else if (key == HdLightTokens->shadowParams) { HdxShadowParams shadowParams; @@ -193,15 +192,16 @@ VtValue HdMayaLightAdapter::Get(const TfToken& key) { return {}; } -VtValue HdMayaLightAdapter::GetLightParamValue(const TfToken& paramName) { +VtValue HdMayaLightAdapter::GetLightParamValue(const TfToken& paramName) +{ TF_DEBUG(HDMAYA_ADAPTER_GET_LIGHT_PARAM_VALUE) .Msg( "Called HdMayaLightAdapter::GetLightParamValue(%s) - %s\n", - paramName.GetText(), GetDagPath().partialPathName().asChar()); + paramName.GetText(), + GetDagPath().partialPathName().asChar()); MFnLight light(GetDagPath()); - if (paramName == HdLightTokens->color || - paramName == HdTokens->displayColor) { + if (paramName == HdLightTokens->color || paramName == HdTokens->displayColor) { const auto color = light.color(); return VtValue(GfVec3f(color.r, color.g, color.b)); } else if (paramName == HdLightTokens->intensity) { @@ -220,79 +220,77 @@ VtValue HdMayaLightAdapter::GetLightParamValue(const TfToken& paramName) { return {}; } -void HdMayaLightAdapter::CreateCallbacks() { +void HdMayaLightAdapter::CreateCallbacks() +{ TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) - .Msg( - "Creating light adapter callbacks for prim (%s).\n", - GetID().GetText()); + .Msg("Creating light adapter callbacks for prim (%s).\n", GetID().GetText()); MStatus status; - auto dag = GetDagPath(); - auto obj = dag.node(); - auto id = - MNodeMessage::addNodeDirtyCallback(obj, _dirtyParams, this, &status); - if (status) { AddCallback(id); } + auto dag = GetDagPath(); + auto obj = dag.node(); + auto id = MNodeMessage::addNodeDirtyCallback(obj, _dirtyParams, this, &status); + if (status) { + AddCallback(id); + } dag.pop(); for (; dag.length() > 0; dag.pop()) { // The adapter itself will free the callbacks, so we don't have to worry // about passing raw pointers to the callbacks. Hopefully. obj = dag.node(); if (obj != MObject::kNullObj) { - id = MNodeMessage::addAttributeChangedCallback( - obj, _changeVisibility, this, &status); - if (status) { AddCallback(id); } - id = MNodeMessage::addNodeDirtyCallback( - obj, _dirtyTransform, this, &status); - if (status) { AddCallback(id); } + id = MNodeMessage::addAttributeChangedCallback(obj, _changeVisibility, this, &status); + if (status) { + AddCallback(id); + } + id = MNodeMessage::addNodeDirtyCallback(obj, _dirtyTransform, this, &status); + if (status) { + AddCallback(id); + } _AddHierarchyChangedCallbacks(dag); } } HdMayaAdapter::CreateCallbacks(); } -void HdMayaLightAdapter::SetShadowProjectionMatrix(const GfMatrix4d& matrix) { +void HdMayaLightAdapter::SetShadowProjectionMatrix(const GfMatrix4d& matrix) +{ if (!GfIsClose(_shadowProjectionMatrix, matrix, 0.0001)) { MarkDirty(HdLight::DirtyShadowParams); _shadowProjectionMatrix = matrix; } } -void HdMayaLightAdapter::_CalculateShadowParams( - MFnLight& light, HdxShadowParams& params) { +void HdMayaLightAdapter::_CalculateShadowParams(MFnLight& light, HdxShadowParams& params) +{ TF_DEBUG(HDMAYA_ADAPTER_LIGHT_SHADOWS) .Msg( "Called HdMayaLightAdapter::_CalculateShadowParams - %s\n", GetDagPath().partialPathName().asChar()); - const auto dmapResolutionPlug = light.findPlug( - MayaAttrs::nonExtendedLightShapeNode::dmapResolution, true); - const auto dmapBiasPlug = - light.findPlug(MayaAttrs::nonExtendedLightShapeNode::dmapBias, true); - const auto dmapFilterSizePlug = light.findPlug( - MayaAttrs::nonExtendedLightShapeNode::dmapFilterSize, true); + const auto dmapResolutionPlug + = light.findPlug(MayaAttrs::nonExtendedLightShapeNode::dmapResolution, true); + const auto dmapBiasPlug = light.findPlug(MayaAttrs::nonExtendedLightShapeNode::dmapBias, true); + const auto dmapFilterSizePlug + = light.findPlug(MayaAttrs::nonExtendedLightShapeNode::dmapFilterSize, true); params.enabled = true; - params.resolution = - dmapResolutionPlug.isNull() - ? GetDelegate()->GetParams().maximumShadowMapResolution - : std::min( - GetDelegate()->GetParams().maximumShadowMapResolution, - dmapResolutionPlug.asInt()); + params.resolution = dmapResolutionPlug.isNull() + ? GetDelegate()->GetParams().maximumShadowMapResolution + : std::min( + GetDelegate()->GetParams().maximumShadowMapResolution, dmapResolutionPlug.asInt()); params.shadowMatrix = #if HDX_API_VERSION >= 7 - std::make_shared( - GetTransform() * _shadowProjectionMatrix); + std::make_shared(GetTransform() * _shadowProjectionMatrix); #else boost::static_pointer_cast( boost::make_shared( GetTransform() * _shadowProjectionMatrix)); #endif params.bias = dmapBiasPlug.isNull() ? -0.001 : -dmapBiasPlug.asFloat(); - params.blur = dmapFilterSizePlug.isNull() - ? 0.0 - : (static_cast(dmapFilterSizePlug.asInt())) / - static_cast(params.resolution); + params.blur = dmapFilterSizePlug.isNull() ? 0.0 + : (static_cast(dmapFilterSizePlug.asInt())) + / static_cast(params.resolution); if (TfDebug::IsEnabled(HDMAYA_ADAPTER_LIGHT_SHADOWS)) { std::cout << "Resulting HdxShadowParams:\n"; @@ -300,27 +298,40 @@ void HdMayaLightAdapter::_CalculateShadowParams( } } -bool HdMayaLightAdapter::_GetVisibility() const { - if (!GetDagPath().isVisible()) { return false; } +bool HdMayaLightAdapter::_GetVisibility() const +{ + if (!GetDagPath().isVisible()) { + return false; + } // Shapes are not part of the default light set. - if (!GetNode().hasFn(MFn::kLight)) { return true; } - MStatus status; + if (!GetNode().hasFn(MFn::kLight)) { + return true; + } + MStatus status; MFnDependencyNode node(GetDagPath().transform(), &status); - if (ARCH_UNLIKELY(!status)) { return true; } + if (ARCH_UNLIKELY(!status)) { + return true; + } auto p = node.findPlug(MayaAttrs::dagNode::instObjGroups, true); - if (ARCH_UNLIKELY(p.isNull())) { return true; } + if (ARCH_UNLIKELY(p.isNull())) { + return true; + } const auto numElements = p.numElements(); MPlugArray conns; - for (auto i = decltype(numElements){0}; i < numElements; ++i) { + for (auto i = decltype(numElements) { 0 }; i < numElements; ++i) { auto ep = p[i]; // == elementByPhysicalIndex if (!ep.connectedTo(conns, false, true) || conns.length() < 1) { continue; } const auto numConns = conns.length(); - for (auto j = decltype(numConns){0}; j < numConns; ++j) { + for (auto j = decltype(numConns) { 0 }; j < numConns; ++j) { MFnDependencyNode otherNode(conns[j].node(), &status); - if (!status) { continue; } - if (otherNode.name() == defaultLightSet) { return true; } + if (!status) { + continue; + } + if (otherNode.name() == defaultLightSet) { + return true; + } } } return false; diff --git a/lib/usd/hdMaya/adapters/lightAdapter.h b/lib/usd/hdMaya/adapters/lightAdapter.h index 799b81d77e..c3c80b4bda 100644 --- a/lib/usd/hdMaya/adapters/lightAdapter.h +++ b/lib/usd/hdMaya/adapters/lightAdapter.h @@ -16,22 +16,24 @@ #ifndef HDMAYA_LIGHT_ADAPTER_H #define HDMAYA_LIGHT_ADAPTER_H -#include -#include +#include -#include #include #include #include #include +#include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -class HdMayaLightAdapter : public HdMayaDagAdapter { +class HdMayaLightAdapter : public HdMayaDagAdapter +{ public: - inline bool GetShadowsEnabled(MFnNonExtendedLight& light) { + inline bool GetShadowsEnabled(MFnNonExtendedLight& light) + { return light.useDepthMapShadows() || light.useRayTraceShadows(); } @@ -62,7 +64,7 @@ class HdMayaLightAdapter : public HdMayaDagAdapter { protected: HDMAYA_API - virtual void _CalculateLightParams(GlfSimpleLight& light) {} + virtual void _CalculateLightParams(GlfSimpleLight& light) { } HDMAYA_API void _CalculateShadowParams(MFnLight& light, HdxShadowParams& params); HDMAYA_API diff --git a/lib/usd/hdMaya/adapters/materialAdapter.cpp b/lib/usd/hdMaya/adapters/materialAdapter.cpp index 74158b390d..4eb6c27e7b 100644 --- a/lib/usd/hdMaya/adapters/materialAdapter.cpp +++ b/lib/usd/hdMaya/adapters/materialAdapter.cpp @@ -15,9 +15,11 @@ // #include "materialAdapter.h" -#include -#include -#include +#include +#include +#include +#include +#include #include #include @@ -28,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -35,26 +38,23 @@ #include #include -#include -#include -#include -#include -#include - -#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE namespace { -const VtValue _emptyValue; -const TfToken _emptyToken; -const TfTokenVector _stSamplerCoords = {TfToken("st")}; +const VtValue _emptyValue; +const TfToken _emptyToken; +const TfTokenVector _stSamplerCoords = { TfToken("st") }; // const TfTokenVector _stSamplerCoords; -struct _ShaderSourceAndMeta { - std::string surfaceCode; - std::string displacementCode; +struct _ShaderSourceAndMeta +{ + std::string surfaceCode; + std::string displacementCode; VtDictionary metadata; #ifdef HDMAYA_OIT_ENABLED VtDictionary translucentMetadata; @@ -64,34 +64,44 @@ struct _ShaderSourceAndMeta { } // namespace HdMayaMaterialAdapter::HdMayaMaterialAdapter( - const SdfPath& id, HdMayaDelegateCtx* delegate, const MObject& node) - : HdMayaAdapter(node, id, delegate) {} + const SdfPath& id, + HdMayaDelegateCtx* delegate, + const MObject& node) + : HdMayaAdapter(node, id, delegate) +{ +} -bool HdMayaMaterialAdapter::IsSupported() const { - return GetDelegate()->GetRenderIndex().IsSprimTypeSupported( - HdPrimTypeTokens->material); +bool HdMayaMaterialAdapter::IsSupported() const +{ + return GetDelegate()->GetRenderIndex().IsSprimTypeSupported(HdPrimTypeTokens->material); } -bool HdMayaMaterialAdapter::HasType(const TfToken& typeId) const { +bool HdMayaMaterialAdapter::HasType(const TfToken& typeId) const +{ return typeId == HdPrimTypeTokens->material; } -void HdMayaMaterialAdapter::MarkDirty(HdDirtyBits dirtyBits) { +void HdMayaMaterialAdapter::MarkDirty(HdDirtyBits dirtyBits) +{ GetDelegate()->GetChangeTracker().MarkSprimDirty(GetID(), dirtyBits); } -void HdMayaMaterialAdapter::RemovePrim() { - if (!_isPopulated) { return; } +void HdMayaMaterialAdapter::RemovePrim() +{ + if (!_isPopulated) { + return; + } GetDelegate()->RemoveSprim(HdPrimTypeTokens->material, GetID()); _isPopulated = false; } -void HdMayaMaterialAdapter::Populate() { - TF_DEBUG(HDMAYA_ADAPTER_GET) - .Msg("HdMayaMaterialAdapter::Populate() - %s\n", GetID().GetText()); - if (_isPopulated) { return; } - GetDelegate()->InsertSprim( - HdPrimTypeTokens->material, GetID(), HdMaterial::AllDirty); +void HdMayaMaterialAdapter::Populate() +{ + TF_DEBUG(HDMAYA_ADAPTER_GET).Msg("HdMayaMaterialAdapter::Populate() - %s\n", GetID().GetText()); + if (_isPopulated) { + return; + } + GetDelegate()->InsertSprim(HdPrimTypeTokens->material, GetID(), HdMaterial::AllDirty); _isPopulated = true; } @@ -102,160 +112,160 @@ void HdMayaMaterialAdapter::Populate() { auto _PreviewShader = []() -> const _ShaderSourceAndMeta& { static const auto ret = []() -> _ShaderSourceAndMeta { auto& registry = SdrRegistry::GetInstance(); - auto sdrNode = registry.GetShaderNodeByIdentifierAndType( + auto sdrNode = registry.GetShaderNodeByIdentifierAndType( UsdImagingTokens->UsdPreviewSurface, HioGlslfxTokens->glslfx); - if (!sdrNode) { return {"", ""}; } - HioGlslfx gfx(sdrNode->GetSourceURI()); + if (!sdrNode) { + return { "", "" }; + } + HioGlslfx gfx(sdrNode->GetSourceURI()); _ShaderSourceAndMeta ret; ret.surfaceCode = gfx.GetSurfaceSource(); ret.displacementCode = gfx.GetDisplacementSource(); ret.metadata = gfx.GetMetadata(); #ifdef HDMAYA_OIT_ENABLED ret.translucentMetadata = gfx.GetMetadata(); - ret.translucentMetadata[HdShaderTokens->materialTag] = - VtValue(HdxMaterialTagTokens->translucent); + ret.translucentMetadata[HdShaderTokens->materialTag] + = VtValue(HdxMaterialTagTokens->translucent); #endif return ret; }(); return ret; }; -std::string HdMayaMaterialAdapter::GetSurfaceShaderSource() { - return GetPreviewSurfaceSource(); -} +std::string HdMayaMaterialAdapter::GetSurfaceShaderSource() { return GetPreviewSurfaceSource(); } -std::string HdMayaMaterialAdapter::GetDisplacementShaderSource() { +std::string HdMayaMaterialAdapter::GetDisplacementShaderSource() +{ return GetPreviewDisplacementSource(); } -VtValue HdMayaMaterialAdapter::GetMaterialParamValue(const TfToken& paramName) { +VtValue HdMayaMaterialAdapter::GetMaterialParamValue(const TfToken& paramName) +{ return GetPreviewMaterialParamValue(paramName); } -HdMaterialParamVector HdMayaMaterialAdapter::GetMaterialParams() { +HdMaterialParamVector HdMayaMaterialAdapter::GetMaterialParams() +{ return GetPreviewMaterialParams(); } -VtDictionary HdMayaMaterialAdapter::GetMaterialMetadata() { - return _PreviewShader().metadata; -} +VtDictionary HdMayaMaterialAdapter::GetMaterialMetadata() { return _PreviewShader().metadata; } -const HdMaterialParamVector& HdMayaMaterialAdapter::GetPreviewMaterialParams() { +const HdMaterialParamVector& HdMayaMaterialAdapter::GetPreviewMaterialParams() +{ return HdMayaMaterialNetworkConverter::GetPreviewMaterialParamVector(); } -const std::string& HdMayaMaterialAdapter::GetPreviewSurfaceSource() { +const std::string& HdMayaMaterialAdapter::GetPreviewSurfaceSource() +{ return _PreviewShader().surfaceCode; } -const std::string& HdMayaMaterialAdapter::GetPreviewDisplacementSource() { +const std::string& HdMayaMaterialAdapter::GetPreviewDisplacementSource() +{ return _PreviewShader().displacementCode; } -HdMayaShaderParams::const_iterator _FindPreviewParam(const TfToken& id) { - TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) - .Msg("_FindPreviewParam(id=%s)\n", id.GetText()); +HdMayaShaderParams::const_iterator _FindPreviewParam(const TfToken& id) +{ + TF_DEBUG(HDMAYA_ADAPTER_MATERIALS).Msg("_FindPreviewParam(id=%s)\n", id.GetText()); - const auto& previewShaderParams = - HdMayaMaterialNetworkConverter::GetPreviewShaderParams(); + const auto& previewShaderParams = HdMayaMaterialNetworkConverter::GetPreviewShaderParams(); return std::lower_bound( - previewShaderParams.cbegin(), previewShaderParams.cend(), id, - [](const HdMayaShaderParam& param, const TfToken& id){ - return param.name < id; - } - ); + previewShaderParams.cbegin(), + previewShaderParams.cend(), + id, + [](const HdMayaShaderParam& param, const TfToken& id) { return param.name < id; }); } -const VtValue& HdMayaMaterialAdapter::GetPreviewMaterialParamValue( - const TfToken& paramName) { +const VtValue& HdMayaMaterialAdapter::GetPreviewMaterialParamValue(const TfToken& paramName) +{ const auto it = _FindPreviewParam(paramName); - if (ARCH_UNLIKELY( - it == - HdMayaMaterialNetworkConverter::GetPreviewShaderParams().cend())) { - TF_CODING_ERROR( - "Incorrect name passed to GetMaterialParamValue: %s", - paramName.GetText()); + if (ARCH_UNLIKELY(it == HdMayaMaterialNetworkConverter::GetPreviewShaderParams().cend())) { + TF_CODING_ERROR("Incorrect name passed to GetMaterialParamValue: %s", paramName.GetText()); return _emptyValue; } return it->fallbackValue; } -HdTextureResourceSharedPtr HdMayaMaterialAdapter::GetTextureResource( - const TfToken& paramName) { +HdTextureResourceSharedPtr HdMayaMaterialAdapter::GetTextureResource(const TfToken& paramName) +{ return {}; } #else // USD_VERSION_NUM > 1911 -HdTextureResourceSharedPtr HdMayaMaterialAdapter::GetTextureResource( - const SdfPath& textureShaderId) { +HdTextureResourceSharedPtr HdMayaMaterialAdapter::GetTextureResource(const SdfPath& textureShaderId) +{ return {}; } #endif // USD_VERSION_NUM <= 1911 -HdTextureResource::ID HdMayaMaterialAdapter::GetTextureResourceID( - const TfToken& paramName) { +HdTextureResource::ID HdMayaMaterialAdapter::GetTextureResourceID(const TfToken& paramName) +{ return {}; } -VtValue HdMayaMaterialAdapter::GetMaterialResource() { - TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) - .Msg("HdMayaMaterialAdapter::GetMaterialResource()\n"); +VtValue HdMayaMaterialAdapter::GetMaterialResource() +{ + TF_DEBUG(HDMAYA_ADAPTER_MATERIALS).Msg("HdMayaMaterialAdapter::GetMaterialResource()\n"); return GetPreviewMaterialResource(GetID()); } -VtValue HdMayaMaterialAdapter::GetPreviewMaterialResource( - const SdfPath& materialID) { +VtValue HdMayaMaterialAdapter::GetPreviewMaterialResource(const SdfPath& materialID) +{ HdMaterialNetworkMap map; - HdMaterialNetwork network; - HdMaterialNode node; + HdMaterialNetwork network; + HdMaterialNode node; node.path = materialID; node.identifier = UsdImagingTokens->UsdPreviewSurface; map.terminals.push_back(node.path); - for (const auto& it : - HdMayaMaterialNetworkConverter::GetPreviewShaderParams()) { - node.parameters.emplace( - it.name, it.fallbackValue); + for (const auto& it : HdMayaMaterialNetworkConverter::GetPreviewShaderParams()) { + node.parameters.emplace(it.name, it.fallbackValue); } network.nodes.push_back(node); map.map.emplace(HdMaterialTerminalTokens->surface, network); return VtValue(map); } -class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { +class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter +{ public: typedef HdMayaMaterialNetworkConverter::PathToMobjMap PathToMobjMap; - HdMayaShadingEngineAdapter( - const SdfPath& id, HdMayaDelegateCtx* delegate, const MObject& obj) - : HdMayaMaterialAdapter(id, delegate, obj), _surfaceShaderCallback(0) { + HdMayaShadingEngineAdapter(const SdfPath& id, HdMayaDelegateCtx* delegate, const MObject& obj) + : HdMayaMaterialAdapter(id, delegate, obj) + , _surfaceShaderCallback(0) + { _CacheNodeAndTypes(); } - ~HdMayaShadingEngineAdapter() override { + ~HdMayaShadingEngineAdapter() override + { if (_surfaceShaderCallback != 0) { MNodeMessage::removeCallback(_surfaceShaderCallback); } } - void CreateCallbacks() override { + void CreateCallbacks() override + { TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) - .Msg( - "Creating shading engine adapter callbacks for prim (%s).\n", - GetID().GetText()); + .Msg("Creating shading engine adapter callbacks for prim (%s).\n", GetID().GetText()); MStatus status; - auto obj = GetNode(); - auto id = MNodeMessage::addNodeDirtyCallback( - obj, _DirtyMaterialParams, this, &status); - if (ARCH_LIKELY(status)) { AddCallback(id); } + auto obj = GetNode(); + auto id = MNodeMessage::addNodeDirtyCallback(obj, _DirtyMaterialParams, this, &status); + if (ARCH_LIKELY(status)) { + AddCallback(id); + } _CreateSurfaceMaterialCallback(); HdMayaAdapter::CreateCallbacks(); } - void Populate() override { + void Populate() override + { HdMayaMaterialAdapter::Populate(); #ifdef HDMAYA_OIT_ENABLED _isTranslucent = IsTranslucent(); @@ -263,40 +273,46 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { } private: - static void _DirtyMaterialParams(MObject& /*node*/, void* clientData) { - auto* adapter = - reinterpret_cast(clientData); + static void _DirtyMaterialParams(MObject& /*node*/, void* clientData) + { + auto* adapter = reinterpret_cast(clientData); adapter->_CreateSurfaceMaterialCallback(); adapter->MarkDirty(HdMaterial::AllDirty); } - static void _DirtyShaderParams(MObject& /*node*/, void* clientData) { - auto* adapter = - reinterpret_cast(clientData); + static void _DirtyShaderParams(MObject& /*node*/, void* clientData) + { + auto* adapter = reinterpret_cast(clientData); adapter->MarkDirty(HdMaterial::AllDirty); if (adapter->GetDelegate()->IsHdSt()) { adapter->GetDelegate()->MaterialTagChanged(adapter->GetID()); } } - void _CacheNodeAndTypes() { + void _CacheNodeAndTypes() + { _surfaceShader = MObject::kNullObj; _surfaceShaderType = _emptyToken; - MStatus status; + MStatus status; MFnDependencyNode node(GetNode(), &status); - if (ARCH_UNLIKELY(!status)) { return; } + if (ARCH_UNLIKELY(!status)) { + return; + } - auto p = node.findPlug(MayaAttrs::shadingEngine::surfaceShader, true); + auto p = node.findPlug(MayaAttrs::shadingEngine::surfaceShader, true); MPlugArray conns; p.connectedTo(conns, true, false); if (conns.length() > 0) { _surfaceShader = conns[0].node(); MFnDependencyNode surfaceNode(_surfaceShader, &status); - if (ARCH_UNLIKELY(!status)) { return; } + if (ARCH_UNLIKELY(!status)) { + return; + } _surfaceShaderType = TfToken(surfaceNode.typeName().asChar()); TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) .Msg( - "Found surfaceShader %s[%s]\n", surfaceNode.name().asChar(), + "Found surfaceShader %s[%s]\n", + surfaceNode.name().asChar(), _surfaceShaderType.GetText()); } } @@ -304,104 +320,89 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { #if USD_VERSION_NUM <= 1911 inline bool _RegisterTexture( - const MFnDependencyNode& node, const TfToken& paramName, - HdTextureType& textureType) { - if(!GetDelegate()->IsHdSt()) { return false; } + const MFnDependencyNode& node, + const TfToken& paramName, + HdTextureType& textureType) + { + if (!GetDelegate()->IsHdSt()) { + return false; + } const auto connectedFileObj = GetConnectedFileNode(node, paramName); if (connectedFileObj != MObject::kNullObj) { - const auto filePath = - GetFileTexturePath(MFnDependencyNode(connectedFileObj)); + const auto filePath = GetFileTexturePath(MFnDependencyNode(connectedFileObj)); if (TfDebug::IsEnabled(HDMAYA_ADAPTER_MATERIALS)) { const char* textureTypeName; switch (textureType) { - case HdTextureType::Uv: - textureTypeName = "Uv"; - break; - case HdTextureType::Ptex: - textureTypeName = "Ptex"; - break; - case HdTextureType::Udim: - textureTypeName = "Udim"; - break; - default: - textureTypeName = ""; + case HdTextureType::Uv: textureTypeName = "Uv"; break; + case HdTextureType::Ptex: textureTypeName = "Ptex"; break; + case HdTextureType::Udim: textureTypeName = "Udim"; break; + default: textureTypeName = ""; } TfDebug::Helper().Msg( "HdMayaShadingEngineAdapter::_RegisterTexture(%s, %s, " "%s)\n", - node.name().asChar(), paramName.GetText(), textureTypeName); - TfDebug::Helper().Msg( - " texture filepath: %s\n", filePath.GetText()); + node.name().asChar(), + paramName.GetText(), + textureTypeName); + TfDebug::Helper().Msg(" texture filepath: %s\n", filePath.GetText()); } auto& renderIndex = GetDelegate()->GetRenderIndex(); auto textureId = _GetTextureResourceID(connectedFileObj, filePath); if (textureId != HdTextureResource::ID(-1)) { - HdResourceRegistry::TextureKey textureKey = - renderIndex.GetTextureKey(textureId); - const auto& resourceRegistry = - boost::static_pointer_cast( - renderIndex.GetResourceRegistry()); - - HdInstance< - HdResourceRegistry::TextureKey, HdTextureResourceSharedPtr> - textureInstance; - auto regLock = resourceRegistry->RegisterTextureResource( - textureKey, &textureInstance); + HdResourceRegistry::TextureKey textureKey = renderIndex.GetTextureKey(textureId); + const auto& resourceRegistry = boost::static_pointer_cast( + renderIndex.GetResourceRegistry()); + + HdInstance + textureInstance; + auto regLock + = resourceRegistry->RegisterTextureResource(textureKey, &textureInstance); if (textureInstance.IsFirstInstance()) { auto textureResource = GetFileTextureResource( - connectedFileObj, filePath, + connectedFileObj, + filePath, GetDelegate()->GetParams().textureMemoryPerTexture); textureInstance.SetValue(textureResource); } - HdStTextureResourceSharedPtr texResource = - boost::static_pointer_cast( - textureInstance.GetValue()); + HdStTextureResourceSharedPtr texResource + = boost::static_pointer_cast(textureInstance.GetValue()); - SdfPath connectionPath = GetID().AppendProperty(paramName); - HdResourceRegistry::TextureKey handleKey = - HdStTextureResourceHandle::GetHandleKey( - &renderIndex, connectionPath); + SdfPath connectionPath = GetID().AppendProperty(paramName); + HdResourceRegistry::TextureKey handleKey + = HdStTextureResourceHandle::GetHandleKey(&renderIndex, connectionPath); boost::hash_combine(textureId, &renderIndex); - HdInstance handleInstance; + HdInstance + handleInstance; - std::unique_lock regLock2 = - resourceRegistry->RegisterTextureResourceHandle(handleKey, - &handleInstance); + std::unique_lock regLock2 + = resourceRegistry->RegisterTextureResourceHandle(handleKey, &handleInstance); if (handleInstance.IsFirstInstance()) { - handleInstance.SetValue( - HdStTextureResourceHandleSharedPtr( - new HdStTextureResourceHandle( - texResource))); - } - else { + handleInstance.SetValue(HdStTextureResourceHandleSharedPtr( + new HdStTextureResourceHandle(texResource))); + } else { handleInstance.GetValue()->SetTextureResource(texResource); } _textureResourceHandles[paramName] = handleInstance.GetValue(); if (GlfIsSupportedUdimTexture(filePath)) { - if (TfDebug::IsEnabled(HDMAYA_ADAPTER_MATERIALS) && - textureType != HdTextureType::Udim) { - TfDebug::Helper().Msg( - " ...changing textureType to Udim\n"); + if (TfDebug::IsEnabled(HDMAYA_ADAPTER_MATERIALS) + && textureType != HdTextureType::Udim) { + TfDebug::Helper().Msg(" ...changing textureType to Udim\n"); } textureType = HdTextureType::Udim; } TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) - .Msg( - " ...successfully registered texture with id: %lu\n", - textureId); + .Msg(" ...successfully registered texture with id: %lu\n", textureId); return true; } else { TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) - .Msg( - " ...failed registering texture - could not get " - "textureID\n"); + .Msg(" ...failed registering texture - could not get " + "textureID\n"); _textureResourceHandles[paramName].reset(); } @@ -409,33 +410,40 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { return false; } - HdMaterialParamVector GetMaterialParams() override { - MStatus status; + HdMaterialParamVector GetMaterialParams() override + { + MStatus status; MFnDependencyNode node(_surfaceShader, &status); - if (ARCH_UNLIKELY(!status)) { return GetPreviewMaterialParams(); } + if (ARCH_UNLIKELY(!status)) { + return GetPreviewMaterialParams(); + } - auto* nodeConverter = - HdMayaMaterialNodeConverter::GetNodeConverter(_surfaceShaderType); - if (!nodeConverter) { return GetPreviewMaterialParams(); } + auto* nodeConverter = HdMayaMaterialNodeConverter::GetNodeConverter(_surfaceShaderType); + if (!nodeConverter) { + return GetPreviewMaterialParams(); + } HdMaterialParamVector ret; ret.reserve(GetPreviewMaterialParams().size()); - for (const auto& it : - HdMayaMaterialNetworkConverter::GetPreviewShaderParams()) { + for (const auto& it : HdMayaMaterialNetworkConverter::GetPreviewShaderParams()) { auto textureType = HdTextureType::Uv; auto remappedName = it.name; auto attrConverter = nodeConverter->GetAttrConverter(remappedName); if (attrConverter) { TfToken tempName = attrConverter->GetPlugName(remappedName); - if (!tempName.IsEmpty()) { remappedName = tempName; } + if (!tempName.IsEmpty()) { + remappedName = tempName; + } } if (_RegisterTexture(node, remappedName, textureType)) { ret.emplace_back( - HdMaterialParam::ParamTypeTexture, it.name, + HdMaterialParam::ParamTypeTexture, + it.name, it.fallbackValue, - GetID().AppendProperty(remappedName), _stSamplerCoords, + GetID().AppendProperty(remappedName), + _stSamplerCoords, textureType); TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) @@ -445,22 +453,20 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { ret.back().connection.GetText()); } else { - ret.emplace_back( - HdMaterialParam::ParamTypeTexture, - it.name, - it.fallbackValue); + ret.emplace_back(HdMaterialParam::ParamTypeTexture, it.name, it.fallbackValue); } } return ret; } - VtValue GetMaterialParamValue(const TfToken& paramName) override { + VtValue GetMaterialParamValue(const TfToken& paramName) override + { if (ARCH_UNLIKELY(_surfaceShaderType.IsEmpty())) { return GetPreviewMaterialParamValue(paramName); } - MStatus status; + MStatus status; MFnDependencyNode node(_surfaceShader, &status); if (ARCH_UNLIKELY(!status)) { return GetPreviewMaterialParamValue(paramName); @@ -468,48 +474,52 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { const auto previewIt = _FindPreviewParam(paramName); if (ARCH_UNLIKELY( - previewIt == - HdMayaMaterialNetworkConverter::GetPreviewShaderParams() - .cend())) { - return HdMayaMaterialAdapter::GetPreviewMaterialParamValue( - paramName); + previewIt == HdMayaMaterialNetworkConverter::GetPreviewShaderParams().cend())) { + return HdMayaMaterialAdapter::GetPreviewMaterialParamValue(paramName); } - auto* nodeConverter = - HdMayaMaterialNodeConverter::GetNodeConverter(_surfaceShaderType); - if (!nodeConverter) { return GetPreviewMaterialParamValue(paramName); } + auto* nodeConverter = HdMayaMaterialNodeConverter::GetNodeConverter(_surfaceShaderType); + if (!nodeConverter) { + return GetPreviewMaterialParamValue(paramName); + } auto attrConverter = nodeConverter->GetAttrConverter(paramName); if (attrConverter) { return attrConverter->GetValue( - node, previewIt->name, previewIt->type, - &previewIt->fallbackValue); + node, previewIt->name, previewIt->type, &previewIt->fallbackValue); } else { return GetPreviewMaterialParamValue(paramName); } } - HdTextureResource::ID GetTextureResourceID( - const TfToken& paramName) override { + HdTextureResource::ID GetTextureResourceID(const TfToken& paramName) override + { TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) - .Msg("HdMayaShadingEngineAdapter::GetTextureResourceID(%s): %s\n", - paramName.GetText(), GetID().GetText()); + .Msg( + "HdMayaShadingEngineAdapter::GetTextureResourceID(%s): %s\n", + paramName.GetText(), + GetID().GetText()); auto fileObj = GetConnectedFileNode(_surfaceShader, paramName); - if (fileObj == MObject::kNullObj) { return HdTextureResource::ID(-1); } - return _GetTextureResourceID( - fileObj, GetFileTexturePath(MFnDependencyNode(fileObj))); + if (fileObj == MObject::kNullObj) { + return HdTextureResource::ID(-1); + } + return _GetTextureResourceID(fileObj, GetFileTexturePath(MFnDependencyNode(fileObj))); } - - HdTextureResourceSharedPtr GetTextureResource( - const TfToken& paramName) override { + HdTextureResourceSharedPtr GetTextureResource(const TfToken& paramName) override + { TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) - .Msg("HdMayaShadingEngineAdapter::GetTextureResource(%s): %s\n", - paramName.GetText(), GetID().GetText()); - if(GetDelegate()->IsHdSt()) { + .Msg( + "HdMayaShadingEngineAdapter::GetTextureResource(%s): %s\n", + paramName.GetText(), + GetID().GetText()); + if (GetDelegate()->IsHdSt()) { auto fileObj = GetConnectedFileNode(_surfaceShader, paramName); - if (fileObj == MObject::kNullObj) { return {}; } + if (fileObj == MObject::kNullObj) { + return {}; + } return GetFileTextureResource( - fileObj, GetFileTexturePath(MFnDependencyNode(fileObj)), + fileObj, + GetFileTexturePath(MFnDependencyNode(fileObj)), GetDelegate()->GetParams().textureMemoryPerTexture); } return {}; @@ -517,26 +527,30 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { #else // USD_VERSION_NUM > 1911 - HdTextureResourceSharedPtr GetTextureResource( - const SdfPath& textureShaderId) override { + HdTextureResourceSharedPtr GetTextureResource(const SdfPath& textureShaderId) override + { TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) - .Msg("HdMayaShadingEngineAdapter::GetTextureResource(%s): %s\n", - textureShaderId.GetText(), GetID().GetText()); - if(GetDelegate()->IsHdSt()) { - auto* mObjPtr = TfMapLookupPtr(_materialPathToMobj, - textureShaderId); - if (!mObjPtr || (*mObjPtr) == MObject::kNullObj) { return {}; } + .Msg( + "HdMayaShadingEngineAdapter::GetTextureResource(%s): %s\n", + textureShaderId.GetText(), + GetID().GetText()); + if (GetDelegate()->IsHdSt()) { + auto* mObjPtr = TfMapLookupPtr(_materialPathToMobj, textureShaderId); + if (!mObjPtr || (*mObjPtr) == MObject::kNullObj) { + return {}; + } return GetFileTextureResource( - *mObjPtr, GetFileTexturePath(MFnDependencyNode(*mObjPtr)), + *mObjPtr, + GetFileTexturePath(MFnDependencyNode(*mObjPtr)), GetDelegate()->GetParams().textureMemoryPerTexture); } return {}; } - #endif // USD_VERSION_NUM <= 1911 - void _CreateSurfaceMaterialCallback() { + void _CreateSurfaceMaterialCallback() + { _CacheNodeAndTypes(); if (_surfaceShaderCallback != 0) { MNodeMessage::removeCallback(_surfaceShaderCallback); @@ -544,29 +558,28 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { } if (_surfaceShader != MObject::kNullObj) { - _surfaceShaderCallback = MNodeMessage::addNodeDirtyCallback( - _surfaceShader, _DirtyShaderParams, this); + _surfaceShaderCallback + = MNodeMessage::addNodeDirtyCallback(_surfaceShader, _DirtyShaderParams, this); } } - inline HdTextureResource::ID _GetTextureResourceID( - const MObject& fileObj, const TfToken& filePath) { - auto hash = filePath.Hash(); + inline HdTextureResource::ID + _GetTextureResourceID(const MObject& fileObj, const TfToken& filePath) + { + auto hash = filePath.Hash(); const auto wrapping = GetFileTextureWrappingParams(fileObj); - boost::hash_combine( - hash, GetDelegate()->GetParams().textureMemoryPerTexture); + boost::hash_combine(hash, GetDelegate()->GetParams().textureMemoryPerTexture); boost::hash_combine(hash, std::get<0>(wrapping)); boost::hash_combine(hash, std::get<1>(wrapping)); return HdTextureResource::ID(hash); } - VtValue GetMaterialResource() override { + VtValue GetMaterialResource() override + { TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) - .Msg("HdMayaShadingEngineAdapter::GetMaterialResource(): %s\n", - GetID().GetText()); - HdMaterialNetwork materialNetwork; - HdMayaMaterialNetworkConverter converter(materialNetwork, GetID(), - &_materialPathToMobj); + .Msg("HdMayaShadingEngineAdapter::GetMaterialResource(): %s\n", GetID().GetText()); + HdMaterialNetwork materialNetwork; + HdMayaMaterialNetworkConverter converter(materialNetwork, GetID(), &_materialPathToMobj); if (!converter.GetMaterial(_surfaceShader)) { return GetPreviewMaterialResource(GetID()); } @@ -574,8 +587,7 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { HdMaterialNetworkMap materialNetworkMap; materialNetworkMap.map[HdMaterialTerminalTokens->surface] = materialNetwork; if (!materialNetwork.nodes.empty()) { - materialNetworkMap.terminals.push_back( - materialNetwork.nodes.back().path); + materialNetworkMap.terminals.push_back(materialNetwork.nodes.back().path); } // HdMaterialNetwork displacementNetwork; @@ -586,7 +598,8 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { }; #ifdef HDMAYA_OIT_ENABLED - bool UpdateMaterialTag() override { + bool UpdateMaterialTag() override + { if (IsTranslucent() != _isTranslucent) { _isTranslucent = !_isTranslucent; return true; @@ -594,14 +607,13 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { return false; } - bool IsTranslucent() { - if (_surfaceShaderType == HdMayaAdapterTokens->usdPreviewSurface || - _surfaceShaderType == HdMayaAdapterTokens->pxrUsdPreviewSurface) { + bool IsTranslucent() + { + if (_surfaceShaderType == HdMayaAdapterTokens->usdPreviewSurface + || _surfaceShaderType == HdMayaAdapterTokens->pxrUsdPreviewSurface) { MFnDependencyNode node(_surfaceShader); - const auto plug = - node.findPlug(HdMayaAdapterTokens->opacity.GetText(), true); - if (!plug.isNull() && - (plug.asFloat() < 1.0f || plug.isConnected())) { + const auto plug = node.findPlug(HdMayaAdapterTokens->opacity.GetText(), true); + if (!plug.isNull() && (plug.asFloat() < 1.0f || plug.isConnected())) { return true; } } @@ -610,11 +622,13 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { #if USD_VERSION_NUM <= 1911 - VtDictionary GetMaterialMetadata() override { + VtDictionary GetMaterialMetadata() override + { // We only need the delayed update of the tag for the HdSt backend. - if (!GetDelegate()->IsHdSt()) { _isTranslucent = IsTranslucent(); } - return _isTranslucent ? _PreviewShader().translucentMetadata - : _PreviewShader().metadata; + if (!GetDelegate()->IsHdSt()) { + _isTranslucent = IsTranslucent(); + } + return _isTranslucent ? _PreviewShader().translucentMetadata : _PreviewShader().metadata; }; #endif // USD_VERSION_NUM <= 1911 @@ -627,8 +641,7 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { TfToken _surfaceShaderType; // So they live long enough - std::unordered_map< - TfToken, HdStTextureResourceHandleSharedPtr, TfToken::HashFunctor> + std::unordered_map _textureResourceHandles; MCallbackId _surfaceShaderCallback; @@ -637,19 +650,20 @@ class HdMayaShadingEngineAdapter : public HdMayaMaterialAdapter { #endif }; -TF_REGISTRY_FUNCTION(TfType) { +TF_REGISTRY_FUNCTION(TfType) +{ TfType::Define>(); - TfType::Define< - HdMayaShadingEngineAdapter, TfType::Bases>(); + TfType::Define>(); } -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, shadingEngine) { +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, shadingEngine) +{ HdMayaAdapterRegistry::RegisterMaterialAdapter( TfToken("shadingEngine"), - [](const SdfPath& id, HdMayaDelegateCtx* delegate, - const MObject& obj) -> HdMayaMaterialAdapterPtr { - return HdMayaMaterialAdapterPtr( - new HdMayaShadingEngineAdapter(id, delegate, obj)); + [](const SdfPath& id, + HdMayaDelegateCtx* delegate, + const MObject& obj) -> HdMayaMaterialAdapterPtr { + return HdMayaMaterialAdapterPtr(new HdMayaShadingEngineAdapter(id, delegate, obj)); }); } diff --git a/lib/usd/hdMaya/adapters/materialAdapter.h b/lib/usd/hdMaya/adapters/materialAdapter.h index 1a9903d9ea..8b7d6c3624 100644 --- a/lib/usd/hdMaya/adapters/materialAdapter.h +++ b/lib/usd/hdMaya/adapters/materialAdapter.h @@ -16,17 +16,17 @@ #ifndef HDMAYA_MATERIAL_ADAPTER_H #define HDMAYA_MATERIAL_ADAPTER_H -#include - #include +#include + PXR_NAMESPACE_OPEN_SCOPE -class HdMayaMaterialAdapter : public HdMayaAdapter { +class HdMayaMaterialAdapter : public HdMayaAdapter +{ public: HDMAYA_API - HdMayaMaterialAdapter( - const SdfPath& id, HdMayaDelegateCtx* delegate, const MObject& node); + HdMayaMaterialAdapter(const SdfPath& id, HdMayaDelegateCtx* delegate, const MObject& node); HDMAYA_API virtual ~HdMayaMaterialAdapter() = default; @@ -66,24 +66,19 @@ class HdMayaMaterialAdapter : public HdMayaAdapter { HDMAYA_API static const std::string& GetPreviewDisplacementSource(); HDMAYA_API - static const VtValue& GetPreviewMaterialParamValue( - const TfToken& paramName); + static const VtValue& GetPreviewMaterialParamValue(const TfToken& paramName); HDMAYA_API - virtual HdTextureResourceSharedPtr GetTextureResource( - const TfToken& paramName); + virtual HdTextureResourceSharedPtr GetTextureResource(const TfToken& paramName); #else // USD_VERSION_NUM > 1911 HDMAYA_API - virtual HdTextureResourceSharedPtr GetTextureResource( - const SdfPath& textureShaderId); - + virtual HdTextureResourceSharedPtr GetTextureResource(const SdfPath& textureShaderId); #endif // USD_VERSION_NUM <= 1911 HDMAYA_API - virtual HdTextureResource::ID GetTextureResourceID( - const TfToken& paramName); + virtual HdTextureResource::ID GetTextureResourceID(const TfToken& paramName); HDMAYA_API virtual VtValue GetMaterialResource(); diff --git a/lib/usd/hdMaya/adapters/materialNetworkConverter.cpp b/lib/usd/hdMaya/adapters/materialNetworkConverter.cpp index f16d730df9..b9a75b277a 100644 --- a/lib/usd/hdMaya/adapters/materialNetworkConverter.cpp +++ b/lib/usd/hdMaya/adapters/materialNetworkConverter.cpp @@ -15,24 +15,23 @@ // #include "materialNetworkConverter.h" -#include - -#include -#include -#include +#include +#include +#include +#include +#include +#include #include #include #include #include -#include +#include +#include +#include -#include -#include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -43,36 +42,46 @@ constexpr float defaultTextureMemoryLimit = 1e8f; // Lists of preferred shader output names, from SdfValueTypeName to list of // preferred output names for that type. The list that has an empty token for // SdfValueTypeName is used as a default. -const std::vector>> - preferredOutputNamesByType{ - {SdfValueTypeNames->Float3, - {HdMayaAdapterTokens->result, HdMayaAdapterTokens->out, - HdMayaAdapterTokens->output, HdMayaAdapterTokens->rgb, - HdMayaAdapterTokens->xyz}}, - {SdfValueTypeNames->Float2, - {HdMayaAdapterTokens->result, HdMayaAdapterTokens->out, - HdMayaAdapterTokens->output, HdMayaAdapterTokens->st, - HdMayaAdapterTokens->uv}}, - {SdfValueTypeNames->Float, - {HdMayaAdapterTokens->result, HdMayaAdapterTokens->out, - HdMayaAdapterTokens->output, HdMayaAdapterTokens->r, - HdMayaAdapterTokens->x}}}; +const std::vector>> preferredOutputNamesByType { + { SdfValueTypeNames->Float3, + { HdMayaAdapterTokens->result, + HdMayaAdapterTokens->out, + HdMayaAdapterTokens->output, + HdMayaAdapterTokens->rgb, + HdMayaAdapterTokens->xyz } }, + { SdfValueTypeNames->Float2, + { HdMayaAdapterTokens->result, + HdMayaAdapterTokens->out, + HdMayaAdapterTokens->output, + HdMayaAdapterTokens->st, + HdMayaAdapterTokens->uv } }, + { SdfValueTypeNames->Float, + { HdMayaAdapterTokens->result, + HdMayaAdapterTokens->out, + HdMayaAdapterTokens->output, + HdMayaAdapterTokens->r, + HdMayaAdapterTokens->x } } +}; // Default set of preferred output names, if type not in // preferredOutputNamesByType -const std::vector defaultPreferredOutputNames{ - HdMayaAdapterTokens->result, HdMayaAdapterTokens->out, - HdMayaAdapterTokens->output}; +const std::vector defaultPreferredOutputNames { HdMayaAdapterTokens->result, + HdMayaAdapterTokens->out, + HdMayaAdapterTokens->output }; -SdfValueTypeName GetStandardTypeName(SdfValueTypeName type) { +SdfValueTypeName GetStandardTypeName(SdfValueTypeName type) +{ // Will map, ie, Vector3f to Float3, TexCoord2f to Float2 return SdfGetValueTypeNameForValue(type.GetDefaultValue()); } -const std::vector& GetPreferredOutputNames( - SdfValueTypeName type, bool useStandardType = true) { +const std::vector& +GetPreferredOutputNames(SdfValueTypeName type, bool useStandardType = true) +{ for (const auto& typeAndNames : preferredOutputNamesByType) { - if (typeAndNames.first == type) { return typeAndNames.second; } + if (typeAndNames.first == type) { + return typeAndNames.second; + } } if (useStandardType) { @@ -86,32 +95,35 @@ const std::vector& GetPreferredOutputNames( return defaultPreferredOutputNames; } -TfToken GetOutputName(const HdMaterialNode& material, SdfValueTypeName type) { +TfToken GetOutputName(const HdMaterialNode& material, SdfValueTypeName type) +{ TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) .Msg( - "GetOutputName(%s - %s, %s)\n", material.path.GetText(), - material.identifier.GetText(), type.GetAsToken().GetText()); + "GetOutputName(%s - %s, %s)\n", + material.path.GetText(), + material.identifier.GetText(), + type.GetAsToken().GetText()); auto& shaderReg = SdrRegistry::GetInstance(); - if (SdrShaderNodeConstPtr sdrNode = - shaderReg.GetShaderNodeByIdentifier(material.identifier)) { + if (SdrShaderNodeConstPtr sdrNode = shaderReg.GetShaderNodeByIdentifier(material.identifier)) { // First, get the list off all outputs of the correct type. std::vector validOutputs; - auto outputNames = sdrNode->GetOutputNames(); + auto outputNames = sdrNode->GetOutputNames(); auto addMatchingOutputs = [&](SdfValueTypeName matchingType) { for (const auto& outName : outputNames) { auto* sdrInfo = sdrNode->GetShaderOutput(outName); - if (sdrInfo && - sdrInfo->GetTypeAsSdfType().first == matchingType) { + if (sdrInfo && sdrInfo->GetTypeAsSdfType().first == matchingType) { validOutputs.push_back(outName); } } - }; + }; addMatchingOutputs(type); if (validOutputs.empty()) { auto standardType = GetStandardTypeName(type); - if (standardType != type) { addMatchingOutputs(standardType); } + if (standardType != type) { + addMatchingOutputs(standardType); + } } // If there's only one, use that @@ -129,9 +141,8 @@ TfToken GetOutputName(const HdMaterialNode& material, SdfValueTypeName type) { if (!validOutputs.empty()) { const auto& preferredNames = GetPreferredOutputNames(type); for (const auto preferredName : preferredNames) { - if (std::find( - validOutputs.begin(), validOutputs.end(), - preferredName) != validOutputs.end()) { + if (std::find(validOutputs.begin(), validOutputs.end(), preferredName) + != validOutputs.end()) { TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) .Msg( " found preferred name of correct type in " @@ -167,7 +178,8 @@ TfToken GetOutputName(const HdMaterialNode& material, SdfValueTypeName type) { return HdMayaAdapterTokens->result; } -class HdMayaGenericMaterialAttrConverter : public HdMayaMaterialAttrConverter { +class HdMayaGenericMaterialAttrConverter : public HdMayaMaterialAttrConverter +{ public: /// Generic attr converter has no fixed type SdfValueTypeName GetType() override { return SdfValueTypeName(); } @@ -175,31 +187,37 @@ class HdMayaGenericMaterialAttrConverter : public HdMayaMaterialAttrConverter { TfToken GetPlugName(const TfToken& usdName) override { return usdName; } VtValue GetValue( - MFnDependencyNode& node, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr) override { + MFnDependencyNode& node, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr) override + { return HdMayaMaterialNetworkConverter::ConvertMayaAttrToValue( node, paramName.GetText(), type, fallback, outPlug); } }; -class HdMayaNewDefaultMaterialAttrConverter - : public HdMayaMaterialAttrConverter { +class HdMayaNewDefaultMaterialAttrConverter : public HdMayaMaterialAttrConverter +{ public: template HdMayaNewDefaultMaterialAttrConverter(const T& defaultValue) - : _defaultValue(defaultValue) {} - - SdfValueTypeName GetType() override { - return SdfGetValueTypeNameForValue(_defaultValue); + : _defaultValue(defaultValue) + { } + SdfValueTypeName GetType() override { return SdfGetValueTypeNameForValue(_defaultValue); } + TfToken GetPlugName(const TfToken& usdName) override { return usdName; } VtValue GetValue( - MFnDependencyNode& node, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr) override { + MFnDependencyNode& node, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr) override + { return HdMayaMaterialNetworkConverter::ConvertMayaAttrToValue( node, paramName.GetText(), type, &_defaultValue, outPlug); } @@ -207,33 +225,37 @@ class HdMayaNewDefaultMaterialAttrConverter const VtValue _defaultValue; }; -class HdMayaRemappingMaterialAttrConverter - : public HdMayaMaterialAttrConverter { +class HdMayaRemappingMaterialAttrConverter : public HdMayaMaterialAttrConverter +{ public: - HdMayaRemappingMaterialAttrConverter( - const TfToken& remappedName, const SdfValueTypeName& type) - : _remappedName(remappedName), _type(type) {} + HdMayaRemappingMaterialAttrConverter(const TfToken& remappedName, const SdfValueTypeName& type) + : _remappedName(remappedName) + , _type(type) + { + } SdfValueTypeName GetType() override { return _type; } - TfToken GetPlugName(const TfToken& usdName) override { - return _remappedName; - } + TfToken GetPlugName(const TfToken& usdName) override { return _remappedName; } VtValue GetValue( - MFnDependencyNode& node, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr) override { + MFnDependencyNode& node, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr) override + { return HdMayaMaterialNetworkConverter::ConvertMayaAttrToValue( node, _remappedName.GetText(), type, fallback, outPlug); } protected: - const TfToken& _remappedName; + const TfToken& _remappedName; const SdfValueTypeName& _type; }; -class HdMayaScaledRemappingMaterialAttrConverter : public HdMayaRemappingMaterialAttrConverter { +class HdMayaScaledRemappingMaterialAttrConverter : public HdMayaRemappingMaterialAttrConverter +{ public: HdMayaScaledRemappingMaterialAttrConverter( const TfToken& remappedName, @@ -256,10 +278,11 @@ class HdMayaScaledRemappingMaterialAttrConverter : public HdMayaRemappingMateria } private: - const TfToken& _scaleName; + const TfToken& _scaleName; }; -class HdMayaComputedMaterialAttrConverter : public HdMayaMaterialAttrConverter { +class HdMayaComputedMaterialAttrConverter : public HdMayaMaterialAttrConverter +{ public: /// Classes which derive from this use some sort of calculation to get /// the right value for the node, and so don't have a single plug that @@ -267,20 +290,24 @@ class HdMayaComputedMaterialAttrConverter : public HdMayaMaterialAttrConverter { TfToken GetPlugName(const TfToken& usdName) override { return TfToken(); } }; -class HdMayaFixedMaterialAttrConverter - : public HdMayaComputedMaterialAttrConverter { +class HdMayaFixedMaterialAttrConverter : public HdMayaComputedMaterialAttrConverter +{ public: template - HdMayaFixedMaterialAttrConverter(const T& value) : _value(value) {} - - SdfValueTypeName GetType() override { - return SdfGetValueTypeNameForValue(_value); + HdMayaFixedMaterialAttrConverter(const T& value) + : _value(value) + { } + SdfValueTypeName GetType() override { return SdfGetValueTypeNameForValue(_value); } + VtValue GetValue( - MFnDependencyNode& node, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr) override { + MFnDependencyNode& node, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr) override + { return _value; } @@ -288,22 +315,25 @@ class HdMayaFixedMaterialAttrConverter const VtValue _value; }; -class HdMayaUvAttrConverter : public HdMayaMaterialAttrConverter { +class HdMayaUvAttrConverter : public HdMayaMaterialAttrConverter +{ public: - HdMayaUvAttrConverter() : _value(GfVec2f(0.0f, 0.0f)) {} - - SdfValueTypeName GetType() override { - return SdfValueTypeNames->TexCoord2f; + HdMayaUvAttrConverter() + : _value(GfVec2f(0.0f, 0.0f)) + { } - TfToken GetPlugName(const TfToken& usdName) override { - return HdMayaAdapterTokens->uvCoord; - } + SdfValueTypeName GetType() override { return SdfValueTypeNames->TexCoord2f; } + + TfToken GetPlugName(const TfToken& usdName) override { return HdMayaAdapterTokens->uvCoord; } VtValue GetValue( - MFnDependencyNode& node, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr) override { + MFnDependencyNode& node, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr) override + { if (outPlug) { // TODO: create a UsdPrimvarReader_float2 even if there's no // connected maya place2dTexture node @@ -311,13 +341,15 @@ class HdMayaUvAttrConverter : public HdMayaMaterialAttrConverter { // Find a connected place2dTexture node, and set that as the // outPlug, so that the place2dTexture node will trigger // creation of a UsdPrimvarReader_float2 - MStatus status; + MStatus status; MPlugArray connections; status = node.getConnections(connections); if (status) { for (size_t i = 0, len = connections.length(); i < len; ++i) { MPlug source = connections[i].source(); - if (source.isNull()) { continue; } + if (source.isNull()) { + continue; + } if (source.node().hasFn(MFn::kPlace2dTexture)) { *outPlug = connections[i]; break; @@ -332,56 +364,61 @@ class HdMayaUvAttrConverter : public HdMayaMaterialAttrConverter { const VtValue _value; }; // namespace -class HdMayaCosinePowerMaterialAttrConverter - : public HdMayaComputedMaterialAttrConverter { +class HdMayaCosinePowerMaterialAttrConverter : public HdMayaComputedMaterialAttrConverter +{ public: SdfValueTypeName GetType() override { return SdfValueTypeNames->Float; } VtValue GetValue( - MFnDependencyNode& node, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr) override { - VtValue cosinePower = - HdMayaMaterialNetworkConverter::ConvertMayaAttrToValue( - node, "cosinePower", type, nullptr); + MFnDependencyNode& node, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr) override + { + VtValue cosinePower = HdMayaMaterialNetworkConverter::ConvertMayaAttrToValue( + node, "cosinePower", type, nullptr); if (!cosinePower.IsHolding()) { - if (fallback) { return *fallback; } + if (fallback) { + return *fallback; + } TF_DEBUG(HDMAYA_ADAPTER_GET) - .Msg( - "HdMayaCosinePowerMaterialAttrConverter::GetValue(): " - "No float plug found with name: cosinePower and no " - "fallback given"); + .Msg("HdMayaCosinePowerMaterialAttrConverter::GetValue(): " + "No float plug found with name: cosinePower and no " + "fallback given"); return VtValue(); } else { // In the maya UI, cosinePower goes from 2.0 to 100.0 ... // so for now, we just do a dumb linear mapping from that onto // 1 to 0 for roughness - float roughnessFloat = - 1.0f - (cosinePower.UncheckedGet() - 2.0f) / 98.0f; + float roughnessFloat = 1.0f - (cosinePower.UncheckedGet() - 2.0f) / 98.0f; return VtValue(roughnessFloat); } } }; -class HdMayaTransmissionMaterialAttrConverter - : public HdMayaComputedMaterialAttrConverter { +class HdMayaTransmissionMaterialAttrConverter : public HdMayaComputedMaterialAttrConverter +{ public: SdfValueTypeName GetType() override { return SdfValueTypeNames->Float; } VtValue GetValue( - MFnDependencyNode& node, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr) override { - VtValue transmission = - HdMayaMaterialNetworkConverter::ConvertMayaAttrToValue( - node, "transmission", type, nullptr); + MFnDependencyNode& node, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr) override + { + VtValue transmission = HdMayaMaterialNetworkConverter::ConvertMayaAttrToValue( + node, "transmission", type, nullptr); if (!transmission.IsHolding()) { - if (fallback) { return *fallback; } + if (fallback) { + return *fallback; + } TF_DEBUG(HDMAYA_ADAPTER_GET) - .Msg( - "HdMayaTransmissionMaterialAttrConverter::GetValue(): " - "No float plug found with name: transmission and no " - "fallback given"); + .Msg("HdMayaTransmissionMaterialAttrConverter::GetValue(): " + "No float plug found with name: transmission and no " + "fallback given"); return VtValue(); } else { return VtValue(1.0f - transmission.UncheckedGet()); @@ -389,32 +426,41 @@ class HdMayaTransmissionMaterialAttrConverter } }; -class HdMayaFilenameMaterialAttrConverter - : public HdMayaComputedMaterialAttrConverter { +class HdMayaFilenameMaterialAttrConverter : public HdMayaComputedMaterialAttrConverter +{ public: SdfValueTypeName GetType() override { return SdfValueTypeNames->Asset; } VtValue GetValue( - MFnDependencyNode& node, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr) override { + MFnDependencyNode& node, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr) override + { auto path = GetFileTexturePath(node); return VtValue(SdfAssetPath(path.GetText(), path.GetText())); } }; -class HdMayaWrapMaterialAttrConverter - : public HdMayaComputedMaterialAttrConverter { +class HdMayaWrapMaterialAttrConverter : public HdMayaComputedMaterialAttrConverter +{ public: HdMayaWrapMaterialAttrConverter(MObject& wrapAttr, MObject& mirrorAttr) - : _wrapAttr(wrapAttr), _mirrorAttr(mirrorAttr) {} + : _wrapAttr(wrapAttr) + , _mirrorAttr(mirrorAttr) + { + } SdfValueTypeName GetType() override { return SdfValueTypeNames->Token; } VtValue GetValue( - MFnDependencyNode& node, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr) override { + MFnDependencyNode& node, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr) override + { if (node.findPlug(_wrapAttr, true).asBool()) { if (node.findPlug(_mirrorAttr, true).asBool()) { return VtValue(UsdHydraTokens->mirror); @@ -431,11 +477,9 @@ class HdMayaWrapMaterialAttrConverter MObject _mirrorAttr; }; -auto _genericAttrConverter = - std::make_shared(); +auto _genericAttrConverter = std::make_shared(); -typedef std::unordered_map< - TfToken, HdMayaMaterialNodeConverter, TfToken::HashFunctor> +typedef std::unordered_map NameToNodeConverterMap; NameToNodeConverterMap _nodeConverters; @@ -443,21 +487,19 @@ NameToNodeConverterMap _nodeConverters; } // namespace /*static*/ -void HdMayaMaterialNetworkConverter::initialize() { +void HdMayaMaterialNetworkConverter::initialize() +{ auto colorConverter = std::make_shared( HdMayaAdapterTokens->color, HdMayaAdapterTokens->diffuse, SdfValueTypeNames->Vector3f); auto incandescenceConverter = std::make_shared( HdMayaAdapterTokens->incandescence, SdfValueTypeNames->Vector3f); - auto eccentricityConverter = - std::make_shared( - HdMayaAdapterTokens->eccentricity, SdfValueTypeNames->Float); + auto eccentricityConverter = std::make_shared( + HdMayaAdapterTokens->eccentricity, SdfValueTypeNames->Float); auto uvConverter = std::make_shared(); // Standard surface: auto baseColorConverter = std::make_shared( - HdMayaAdapterTokens->baseColor, - HdMayaAdapterTokens->base, - SdfValueTypeNames->Vector3f); + HdMayaAdapterTokens->baseColor, HdMayaAdapterTokens->base, SdfValueTypeNames->Vector3f); auto emissionColorConverter = std::make_shared( HdMayaAdapterTokens->emissionColor, HdMayaAdapterTokens->emission, @@ -466,218 +508,226 @@ void HdMayaMaterialNetworkConverter::initialize() { HdMayaAdapterTokens->specularColor, HdMayaAdapterTokens->specular, SdfValueTypeNames->Vector3f); - auto specularIORConverter = - std::make_shared( - HdMayaAdapterTokens->specularIOR, SdfValueTypeNames->Float); - auto specularRoughnessConverter = - std::make_shared( - HdMayaAdapterTokens->specularRoughness, SdfValueTypeNames->Float); - auto coatConverter = - std::make_shared( - HdMayaAdapterTokens->coat, SdfValueTypeNames->Float); - auto coatRoughnessConverter = - std::make_shared( - HdMayaAdapterTokens->coatRoughness, SdfValueTypeNames->Float); - auto transmissionToOpacity = - std::make_shared(); - - auto fixedZeroFloat = - std::make_shared(0.0f); - auto fixedOneFloat = - std::make_shared(1.0f); + auto specularIORConverter = std::make_shared( + HdMayaAdapterTokens->specularIOR, SdfValueTypeNames->Float); + auto specularRoughnessConverter = std::make_shared( + HdMayaAdapterTokens->specularRoughness, SdfValueTypeNames->Float); + auto coatConverter = std::make_shared( + HdMayaAdapterTokens->coat, SdfValueTypeNames->Float); + auto coatRoughnessConverter = std::make_shared( + HdMayaAdapterTokens->coatRoughness, SdfValueTypeNames->Float); + auto transmissionToOpacity = std::make_shared(); + + auto fixedZeroFloat = std::make_shared(0.0f); + auto fixedOneFloat = std::make_shared(1.0f); auto fixedZeroInt = std::make_shared(0); auto fixedOneInt = std::make_shared(1); - auto fixedStToken = std::make_shared( - HdMayaAdapterTokens->st); + auto fixedStToken = std::make_shared(HdMayaAdapterTokens->st); - auto cosinePowerToRoughness = - std::make_shared(); - auto filenameConverter = - std::make_shared(); + auto cosinePowerToRoughness = std::make_shared(); + auto filenameConverter = std::make_shared(); auto wrapUConverter = std::make_shared( MayaAttrs::file::wrapU, MayaAttrs::file::mirrorU); auto wrapVConverter = std::make_shared( MayaAttrs::file::wrapV, MayaAttrs::file::mirrorV); - auto textureMemoryConverter = - std::make_shared( - defaultTextureMemoryLimit); + auto textureMemoryConverter + = std::make_shared(defaultTextureMemoryLimit); _nodeConverters = { - {HdMayaAdapterTokens->usdPreviewSurface, - {UsdImagingTokens->UsdPreviewSurface, {}}}, - {HdMayaAdapterTokens->pxrUsdPreviewSurface, - {UsdImagingTokens->UsdPreviewSurface, {}}}, - {HdMayaAdapterTokens->lambert, - {UsdImagingTokens->UsdPreviewSurface, - { - {HdMayaAdapterTokens->diffuseColor, colorConverter}, - {HdMayaAdapterTokens->emissiveColor, incandescenceConverter}, - {HdMayaAdapterTokens->roughness, fixedOneFloat}, - {HdMayaAdapterTokens->metallic, fixedZeroFloat}, - {HdMayaAdapterTokens->useSpecularWorkflow, fixedZeroInt}, - }}}, - {HdMayaAdapterTokens->blinn, - {UsdImagingTokens->UsdPreviewSurface, - { - {HdMayaAdapterTokens->diffuseColor, colorConverter}, - {HdMayaAdapterTokens->emissiveColor, incandescenceConverter}, - {HdMayaAdapterTokens->roughness, eccentricityConverter}, - {HdMayaAdapterTokens->metallic, fixedZeroFloat}, - {HdMayaAdapterTokens->useSpecularWorkflow, fixedOneInt}, - }}}, - {HdMayaAdapterTokens->phong, - {UsdImagingTokens->UsdPreviewSurface, - { - {HdMayaAdapterTokens->diffuseColor, colorConverter}, - {HdMayaAdapterTokens->emissiveColor, incandescenceConverter}, - {HdMayaAdapterTokens->roughness, cosinePowerToRoughness}, - {HdMayaAdapterTokens->metallic, fixedZeroFloat}, - {HdMayaAdapterTokens->useSpecularWorkflow, fixedOneInt}, - }}}, - {HdMayaAdapterTokens->standardSurface, - {UsdImagingTokens->UsdPreviewSurface, - { - {HdMayaAdapterTokens->diffuseColor, baseColorConverter}, - {HdMayaAdapterTokens->emissiveColor, emissionColorConverter}, - {HdMayaAdapterTokens->specularColor, specularColorConverter}, - {HdMayaAdapterTokens->ior, specularIORConverter}, - {HdMayaAdapterTokens->roughness, specularRoughnessConverter}, - {HdMayaAdapterTokens->clearcoat, coatConverter}, - {HdMayaAdapterTokens->clearcoatRoughness, coatRoughnessConverter}, - {HdMayaAdapterTokens->opacity, transmissionToOpacity}, - {HdMayaAdapterTokens->metallic, fixedZeroFloat}, - {HdMayaAdapterTokens->useSpecularWorkflow, fixedOneInt}, - }}}, - {HdMayaAdapterTokens->file, - {UsdImagingTokens->UsdUVTexture, - { - {HdMayaAdapterTokens->file, filenameConverter}, - {HdMayaAdapterTokens->st, uvConverter}, - {UsdHydraTokens->wrapS, wrapUConverter}, - {UsdHydraTokens->wrapT, wrapVConverter}, - {UsdHydraTokens->textureMemory, textureMemoryConverter}, - }}}, - {HdMayaAdapterTokens->place2dTexture, - {UsdImagingTokens->UsdPrimvarReader_float2, - { - {HdMayaAdapterTokens->varname, fixedStToken}, - }}}, + { HdMayaAdapterTokens->usdPreviewSurface, { UsdImagingTokens->UsdPreviewSurface, {} } }, + { HdMayaAdapterTokens->pxrUsdPreviewSurface, { UsdImagingTokens->UsdPreviewSurface, {} } }, + { HdMayaAdapterTokens->lambert, + { UsdImagingTokens->UsdPreviewSurface, + { + { HdMayaAdapterTokens->diffuseColor, colorConverter }, + { HdMayaAdapterTokens->emissiveColor, incandescenceConverter }, + { HdMayaAdapterTokens->roughness, fixedOneFloat }, + { HdMayaAdapterTokens->metallic, fixedZeroFloat }, + { HdMayaAdapterTokens->useSpecularWorkflow, fixedZeroInt }, + } } }, + { HdMayaAdapterTokens->blinn, + { UsdImagingTokens->UsdPreviewSurface, + { + { HdMayaAdapterTokens->diffuseColor, colorConverter }, + { HdMayaAdapterTokens->emissiveColor, incandescenceConverter }, + { HdMayaAdapterTokens->roughness, eccentricityConverter }, + { HdMayaAdapterTokens->metallic, fixedZeroFloat }, + { HdMayaAdapterTokens->useSpecularWorkflow, fixedOneInt }, + } } }, + { HdMayaAdapterTokens->phong, + { UsdImagingTokens->UsdPreviewSurface, + { + { HdMayaAdapterTokens->diffuseColor, colorConverter }, + { HdMayaAdapterTokens->emissiveColor, incandescenceConverter }, + { HdMayaAdapterTokens->roughness, cosinePowerToRoughness }, + { HdMayaAdapterTokens->metallic, fixedZeroFloat }, + { HdMayaAdapterTokens->useSpecularWorkflow, fixedOneInt }, + } } }, + { HdMayaAdapterTokens->standardSurface, + { UsdImagingTokens->UsdPreviewSurface, + { + { HdMayaAdapterTokens->diffuseColor, baseColorConverter }, + { HdMayaAdapterTokens->emissiveColor, emissionColorConverter }, + { HdMayaAdapterTokens->specularColor, specularColorConverter }, + { HdMayaAdapterTokens->ior, specularIORConverter }, + { HdMayaAdapterTokens->roughness, specularRoughnessConverter }, + { HdMayaAdapterTokens->clearcoat, coatConverter }, + { HdMayaAdapterTokens->clearcoatRoughness, coatRoughnessConverter }, + { HdMayaAdapterTokens->opacity, transmissionToOpacity }, + { HdMayaAdapterTokens->metallic, fixedZeroFloat }, + { HdMayaAdapterTokens->useSpecularWorkflow, fixedOneInt }, + } } }, + { HdMayaAdapterTokens->file, + { UsdImagingTokens->UsdUVTexture, + { + { HdMayaAdapterTokens->file, filenameConverter }, + { HdMayaAdapterTokens->st, uvConverter }, + { UsdHydraTokens->wrapS, wrapUConverter }, + { UsdHydraTokens->wrapT, wrapVConverter }, + { UsdHydraTokens->textureMemory, textureMemoryConverter }, + } } }, + { HdMayaAdapterTokens->place2dTexture, + { UsdImagingTokens->UsdPrimvarReader_float2, + { + { HdMayaAdapterTokens->varname, fixedStToken }, + } } }, }; } HdMayaMaterialNodeConverter::HdMayaMaterialNodeConverter( - const TfToken& identifier, const NameToAttrConverterMap& attrConverters) - : _attrConverters(attrConverters), _identifier(identifier) {} + const TfToken& identifier, + const NameToAttrConverterMap& attrConverters) + : _attrConverters(attrConverters) + , _identifier(identifier) +{ +} HdMayaMaterialAttrConverter::RefPtr -HdMayaMaterialNodeConverter::GetAttrConverter(const TfToken& paramName) { +HdMayaMaterialNodeConverter::GetAttrConverter(const TfToken& paramName) +{ auto it = _attrConverters.find(paramName); - if (it == _attrConverters.end()) { return _genericAttrConverter; } + if (it == _attrConverters.end()) { + return _genericAttrConverter; + } return it->second; } -HdMayaMaterialNodeConverter* HdMayaMaterialNodeConverter::GetNodeConverter( - const TfToken& nodeType) { +HdMayaMaterialNodeConverter* HdMayaMaterialNodeConverter::GetNodeConverter(const TfToken& nodeType) +{ auto it = _nodeConverters.find(nodeType); - if (it == _nodeConverters.end()) { return nullptr; } + if (it == _nodeConverters.end()) { + return nullptr; + } return &(it->second); } HdMayaShaderParam::HdMayaShaderParam( - const TfToken& name, const VtValue& value, const SdfValueTypeName& type) - : - name(name) + const TfToken& name, + const VtValue& value, + const SdfValueTypeName& type) + : name(name) , fallbackValue(value) - , type(type) {} + , type(type) +{ +} HdMayaMaterialNetworkConverter::HdMayaMaterialNetworkConverter( - HdMaterialNetwork& network, const SdfPath& prefix, - PathToMobjMap* pathToMobj) - : _network(network), _prefix(prefix), _pathToMobj(pathToMobj) {} + HdMaterialNetwork& network, + const SdfPath& prefix, + PathToMobjMap* pathToMobj) + : _network(network) + , _prefix(prefix) + , _pathToMobj(pathToMobj) +{ +} -HdMaterialNode* HdMayaMaterialNetworkConverter::GetMaterial( - const MObject& mayaNode) { - MStatus status; +HdMaterialNode* HdMayaMaterialNetworkConverter::GetMaterial(const MObject& mayaNode) +{ + MStatus status; MFnDependencyNode node(mayaNode, &status); - if (ARCH_UNLIKELY(!status)) { return nullptr; } + if (ARCH_UNLIKELY(!status)) { + return nullptr; + } const auto* chr = node.name().asChar(); - if (chr == nullptr || chr[0] == '\0') { return nullptr; } + if (chr == nullptr || chr[0] == '\0') { + return nullptr; + } TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) .Msg("HdMayaMaterialNetworkConverter::GetMaterial(node=%s)\n", chr); std::string usdNameStr = UsdMayaUtil::SanitizeName(chr); - const auto materialPath = _prefix.AppendChild(TfToken(usdNameStr)); + const auto materialPath = _prefix.AppendChild(TfToken(usdNameStr)); auto findResult = std::find_if( - _network.nodes.begin(), _network.nodes.end(), - [&materialPath](const HdMaterialNode& m) -> bool { - return m.path == materialPath; - }); - if (findResult != _network.nodes.end()) { return &(*findResult); } - - auto* nodeConverter = HdMayaMaterialNodeConverter::GetNodeConverter( - TfToken(node.typeName().asChar())); - if (!nodeConverter) { return nullptr; } - HdMaterialNode material{}; + _network.nodes.begin(), + _network.nodes.end(), + [&materialPath](const HdMaterialNode& m) -> bool { return m.path == materialPath; }); + if (findResult != _network.nodes.end()) { + return &(*findResult); + } + + auto* nodeConverter + = HdMayaMaterialNodeConverter::GetNodeConverter(TfToken(node.typeName().asChar())); + if (!nodeConverter) { + return nullptr; + } + HdMaterialNode material {}; material.path = materialPath; material.identifier = nodeConverter->GetIdentifier(); if (material.identifier == UsdImagingTokens->UsdPreviewSurface) { - for (const auto& param : - HdMayaMaterialNetworkConverter::GetPreviewShaderParams()) { + for (const auto& param : HdMayaMaterialNetworkConverter::GetPreviewShaderParams()) { this->ConvertParameter( - node, *nodeConverter, material, param.name, - param.type, ¶m.fallbackValue); + node, *nodeConverter, material, param.name, param.type, ¶m.fallbackValue); } } else { for (auto& nameAttrConverterPair : nodeConverter->GetAttrConverters()) { auto& name = nameAttrConverterPair.first; auto& attrConverter = nameAttrConverterPair.second; - this->ConvertParameter( - node, *nodeConverter, material, name, attrConverter->GetType()); - - if (name == HdMayaAdapterTokens->varname && - (material.identifier == - UsdImagingTokens->UsdPrimvarReader_float || - material.identifier == - UsdImagingTokens->UsdPrimvarReader_float2 || - material.identifier == - UsdImagingTokens->UsdPrimvarReader_float3 || - material.identifier == - UsdImagingTokens->UsdPrimvarReader_float4)) { + this->ConvertParameter(node, *nodeConverter, material, name, attrConverter->GetType()); + + if (name == HdMayaAdapterTokens->varname + && (material.identifier == UsdImagingTokens->UsdPrimvarReader_float + || material.identifier == UsdImagingTokens->UsdPrimvarReader_float2 + || material.identifier == UsdImagingTokens->UsdPrimvarReader_float3 + || material.identifier == UsdImagingTokens->UsdPrimvarReader_float4)) { VtValue& primVarName = material.parameters[name]; if (TF_VERIFY(primVarName.IsHolding())) { AddPrimvar(primVarName.UncheckedGet()); } else { - TF_WARN( - "Converter identified as a UsdPrimvarReader*, but " - "it's " - "varname did not hold a TfToken"); + TF_WARN("Converter identified as a UsdPrimvarReader*, but " + "it's " + "varname did not hold a TfToken"); } } } } - if(_pathToMobj) { (*_pathToMobj)[materialPath] = mayaNode; } + if (_pathToMobj) { + (*_pathToMobj)[materialPath] = mayaNode; + } _network.nodes.push_back(material); return &_network.nodes.back(); } -void HdMayaMaterialNetworkConverter::AddPrimvar(const TfToken& primvar) { - if (std::find( - _network.primvars.begin(), _network.primvars.end(), primvar) == - _network.primvars.end()) { +void HdMayaMaterialNetworkConverter::AddPrimvar(const TfToken& primvar) +{ + if (std::find(_network.primvars.begin(), _network.primvars.end(), primvar) + == _network.primvars.end()) { _network.primvars.push_back(primvar); } } void HdMayaMaterialNetworkConverter::ConvertParameter( - MFnDependencyNode& node, HdMayaMaterialNodeConverter& nodeConverter, - HdMaterialNode& material, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback) { - MPlug plug; + MFnDependencyNode& node, + HdMayaMaterialNodeConverter& nodeConverter, + HdMaterialNode& material, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback) +{ + MPlug plug; VtValue val; - TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) - .Msg("ConvertParameter(%s)\n", paramName.GetText()); + TF_DEBUG(HDMAYA_ADAPTER_MATERIALS).Msg("ConvertParameter(%s)\n", paramName.GetText()); auto attrConverter = nodeConverter.GetAttrConverter(paramName); if (attrConverter) { @@ -695,13 +745,19 @@ void HdMayaMaterialNetworkConverter::ConvertParameter( } material.parameters[paramName] = val; - if (plug.isNull()) { return; } + if (plug.isNull()) { + return; + } MPlug source = plug.source(); if (!source.isNull()) { auto* sourceMat = GetMaterial(source.node()); - if (!sourceMat) { return; } + if (!sourceMat) { + return; + } const auto& sourceMatPath = sourceMat->path; - if (sourceMatPath.IsEmpty()) { return; } + if (sourceMatPath.IsEmpty()) { + return; + } HdMaterialRelationship rel; rel.inputId = sourceMatPath; rel.inputName = GetOutputName(*sourceMat, type); @@ -712,13 +768,19 @@ void HdMayaMaterialNetworkConverter::ConvertParameter( } VtValue HdMayaMaterialNetworkConverter::ConvertMayaAttrToValue( - MFnDependencyNode& node, const MString& plugName, - const SdfValueTypeName& type, const VtValue* fallback, MPlug* outPlug) { + MFnDependencyNode& node, + const MString& plugName, + const SdfValueTypeName& type, + const VtValue* fallback, + MPlug* outPlug) +{ MStatus status; - auto p = node.findPlug(plugName, true, &status); + auto p = node.findPlug(plugName, true, &status); VtValue val; if (status) { - if (outPlug) { *outPlug = p; } + if (outPlug) { + *outPlug = p; + } val = ConvertPlugToValue(p, type, fallback); } else if (fallback) { val = *fallback; @@ -734,11 +796,16 @@ VtValue HdMayaMaterialNetworkConverter::ConvertMayaAttrToValue( } VtValue HdMayaMaterialNetworkConverter::ConvertMayaAttrToScaledValue( - MFnDependencyNode& node, const MString& plugName, const MString& scaleName, - const SdfValueTypeName& type, const VtValue* fallback, MPlug* outPlug) { + MFnDependencyNode& node, + const MString& plugName, + const MString& scaleName, + const SdfValueTypeName& type, + const VtValue* fallback, + MPlug* outPlug) +{ VtValue val = ConvertMayaAttrToValue(node, plugName, type, fallback, outPlug); MStatus status; - auto p = node.findPlug(scaleName, true, &status); + auto p = node.findPlug(scaleName, true, &status); if (status) { if (type.GetType() == SdfValueTypeNames->Vector3f.GetType()) { val = val.UncheckedGet() * p.asFloat(); @@ -758,16 +825,17 @@ VtValue HdMayaMaterialNetworkConverter::ConvertMayaAttrToScaledValue( } VtValue HdMayaMaterialNetworkConverter::ConvertPlugToValue( - const MPlug& plug, const SdfValueTypeName& type, const VtValue* fallback) { + const MPlug& plug, + const SdfValueTypeName& type, + const VtValue* fallback) +{ if (type.GetType() == SdfValueTypeNames->Vector3f.GetType()) { - return VtValue(GfVec3f( - plug.child(0).asFloat(), plug.child(1).asFloat(), - plug.child(2).asFloat())); + return VtValue( + GfVec3f(plug.child(0).asFloat(), plug.child(1).asFloat(), plug.child(2).asFloat())); } else if (type == SdfValueTypeNames->Float) { return VtValue(plug.asFloat()); } else if (type.GetType() == SdfValueTypeNames->Float2.GetType()) { - return VtValue( - GfVec2f(plug.child(0).asFloat(), plug.child(1).asFloat())); + return VtValue(GfVec2f(plug.child(0).asFloat(), plug.child(1).asFloat())); } else if (type == SdfValueTypeNames->Int) { return VtValue(plug.asInt()); } @@ -775,40 +843,44 @@ VtValue HdMayaMaterialNetworkConverter::ConvertPlugToValue( .Msg( "HdMayaMaterialNetworkConverter::ConvertPlugToValue(): do not " "know how to handle type: %s (cpp type: %s)\n", - type.GetAsToken().GetText(), type.GetCPPTypeName().c_str()); - if (fallback) { return *fallback; } + type.GetAsToken().GetText(), + type.GetCPPTypeName().c_str()); + if (fallback) { + return *fallback; + } return {}; }; -std::mutex _previewShaderParams_mutex; -bool _previewShaderParams_initialized = false; +std::mutex _previewShaderParams_mutex; +bool _previewShaderParams_initialized = false; HdMayaShaderParams _previewShaderParams; -const HdMayaShaderParams& -HdMayaMaterialNetworkConverter::GetPreviewShaderParams() { +const HdMayaShaderParams& HdMayaMaterialNetworkConverter::GetPreviewShaderParams() +{ if (!_previewShaderParams_initialized) { std::lock_guard lock(_previewShaderParams_mutex); // Once we have the lock, recheck to make sure it's still // uninitialized... if (!_previewShaderParams_initialized) { - auto& shaderReg = SdrRegistry::GetInstance(); - SdrShaderNodeConstPtr sdrNode = shaderReg.GetShaderNodeByIdentifier( - UsdImagingTokens->UsdPreviewSurface); + auto& shaderReg = SdrRegistry::GetInstance(); + SdrShaderNodeConstPtr sdrNode + = shaderReg.GetShaderNodeByIdentifier(UsdImagingTokens->UsdPreviewSurface); if (TF_VERIFY(sdrNode)) { auto inputNames = sdrNode->GetInputNames(); _previewShaderParams.reserve(inputNames.size()); for (auto& inputName : inputNames) { auto property = sdrNode->GetInput(inputName); - if (!TF_VERIFY(property)) { continue; } + if (!TF_VERIFY(property)) { + continue; + } _previewShaderParams.emplace_back( - inputName, property->GetDefaultValue(), - property->GetTypeAsSdfType().first); + inputName, property->GetDefaultValue(), property->GetTypeAsSdfType().first); } std::sort( - _previewShaderParams.begin(), _previewShaderParams.end(), - [](const HdMayaShaderParam& a, - const HdMayaShaderParam& b) -> bool { + _previewShaderParams.begin(), + _previewShaderParams.end(), + [](const HdMayaShaderParam& a, const HdMayaShaderParam& b) -> bool { return a.name < b.name; }); _previewShaderParams_initialized = true; @@ -821,25 +893,22 @@ HdMayaMaterialNetworkConverter::GetPreviewShaderParams() { #if USD_VERSION_NUM <= 1911 // This is required quite often, so we precalc. -std::mutex _previewMaterialParamVector_mutex; -bool _previewMaterialParamVector_initialized = false; +std::mutex _previewMaterialParamVector_mutex; +bool _previewMaterialParamVector_initialized = false; HdMaterialParamVector _previewMaterialParamVector; -const HdMaterialParamVector& -HdMayaMaterialNetworkConverter::GetPreviewMaterialParamVector() { +const HdMaterialParamVector& HdMayaMaterialNetworkConverter::GetPreviewMaterialParamVector() +{ if (!_previewMaterialParamVector_initialized) { std::lock_guard lock(_previewMaterialParamVector_mutex); // Once we have the lock, recheck to make sure it's still // uninitialized... if (!_previewMaterialParamVector_initialized) { - auto& shaderParams = - HdMayaMaterialNetworkConverter::GetPreviewShaderParams(); + auto& shaderParams = HdMayaMaterialNetworkConverter::GetPreviewShaderParams(); _previewMaterialParamVector.reserve(shaderParams.size()); for (const auto& it : shaderParams) { _previewMaterialParamVector.emplace_back( - HdMaterialParam::ParamTypeFallback, - it.name, - it.fallbackValue); + HdMaterialParam::ParamTypeFallback, it.name, it.fallbackValue); } _previewMaterialParamVector_initialized = true; } diff --git a/lib/usd/hdMaya/adapters/materialNetworkConverter.h b/lib/usd/hdMaya/adapters/materialNetworkConverter.h index 6582fecfc4..4487f9b747 100644 --- a/lib/usd/hdMaya/adapters/materialNetworkConverter.h +++ b/lib/usd/hdMaya/adapters/materialNetworkConverter.h @@ -16,28 +16,27 @@ #ifndef HDMAYA_MATERIAL_NETWORK_CONVERTER_H #define HDMAYA_MATERIAL_NETWORK_CONVERTER_H -#include -#include +#include #include #include #include #include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -struct HdMayaShaderParam { +struct HdMayaShaderParam +{ TfToken name; VtValue fallbackValue; SdfValueTypeName type; HDMAYA_API - HdMayaShaderParam( - const TfToken& name, const VtValue& value, - const SdfValueTypeName& type); + HdMayaShaderParam(const TfToken& name, const VtValue& value, const SdfValueTypeName& type); }; using HdMayaShaderParams = std::vector; @@ -45,11 +44,12 @@ using HdMayaShaderParams = std::vector; /// Class which provides basic name and value translation for an attribute. /// Used by both HdMayaMaterialNetworkConverter (for to-usd file export /// translation) and HdMayaMaterialAdapter (for translation to Hydra). -class HdMayaMaterialAttrConverter { +class HdMayaMaterialAttrConverter +{ public: typedef std::shared_ptr RefPtr; - virtual ~HdMayaMaterialAttrConverter(){}; + virtual ~HdMayaMaterialAttrConverter() {}; /// Returns the default type for this attr converter - if an /// implementation returns an invalid type, this indicates the attr @@ -74,23 +74,26 @@ class HdMayaMaterialAttrConverter { HDMAYA_API virtual VtValue GetValue( - MFnDependencyNode& node, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr) = 0; + MFnDependencyNode& node, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr) + = 0; }; /// Class which provides basic name and value translation for a maya node /// type. Used by both HdMayaMaterialNetworkConverter (for to-usd file /// export translation) and HdMayaMaterialAdapter (for translation to Hydra). -class HdMayaMaterialNodeConverter { +class HdMayaMaterialNodeConverter +{ public: - typedef std::unordered_map< - TfToken, HdMayaMaterialAttrConverter::RefPtr, TfToken::HashFunctor> + typedef std::unordered_map NameToAttrConverterMap; HDMAYA_API HdMayaMaterialNodeConverter( - const TfToken& identifier, + const TfToken& identifier, const NameToAttrConverterMap& attrConverters); inline TfToken GetIdentifier() { return _identifier; } @@ -100,30 +103,28 @@ class HdMayaMaterialNodeConverter { /// that will look for an attribute on the maya node with the same name, and /// use that if possible. HDMAYA_API - HdMayaMaterialAttrConverter::RefPtr GetAttrConverter( - const TfToken& paramName); + HdMayaMaterialAttrConverter::RefPtr GetAttrConverter(const TfToken& paramName); - inline NameToAttrConverterMap& GetAttrConverters() { - return _attrConverters; - } + inline NameToAttrConverterMap& GetAttrConverters() { return _attrConverters; } HDMAYA_API - static HdMayaMaterialNodeConverter* GetNodeConverter( - const TfToken& nodeType); + static HdMayaMaterialNodeConverter* GetNodeConverter(const TfToken& nodeType); private: NameToAttrConverterMap _attrConverters; - mutable TfToken _identifier; + mutable TfToken _identifier; }; -class HdMayaMaterialNetworkConverter { +class HdMayaMaterialNetworkConverter +{ public: typedef std::unordered_map PathToMobjMap; HDMAYA_API HdMayaMaterialNetworkConverter( - HdMaterialNetwork& network, const SdfPath& prefix, - PathToMobjMap* pathToMobj = nullptr); + HdMaterialNetwork& network, + const SdfPath& prefix, + PathToMobjMap* pathToMobj = nullptr); HDMAYA_API HdMaterialNode* GetMaterial(const MObject& mayaNode); @@ -133,27 +134,36 @@ class HdMayaMaterialNetworkConverter { HDMAYA_API void ConvertParameter( - MFnDependencyNode& node, HdMayaMaterialNodeConverter& nodeConverter, - HdMaterialNode& material, const TfToken& paramName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr); + MFnDependencyNode& node, + HdMayaMaterialNodeConverter& nodeConverter, + HdMaterialNode& material, + const TfToken& paramName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr); HDMAYA_API static VtValue ConvertMayaAttrToValue( - MFnDependencyNode& node, const MString& plugName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr); + MFnDependencyNode& node, + const MString& plugName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr); HDMAYA_API static VtValue ConvertMayaAttrToScaledValue( - MFnDependencyNode& node, const MString& plugName, const MString& scaleName, - const SdfValueTypeName& type, const VtValue* fallback = nullptr, - MPlug* outPlug = nullptr); + MFnDependencyNode& node, + const MString& plugName, + const MString& scaleName, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr, + MPlug* outPlug = nullptr); HDMAYA_API static void initialize(); HDMAYA_API static VtValue ConvertPlugToValue( - const MPlug& plug, const SdfValueTypeName& type, - const VtValue* fallback = nullptr); + const MPlug& plug, + const SdfValueTypeName& type, + const VtValue* fallback = nullptr); HDMAYA_API static const HdMayaShaderParams& GetPreviewShaderParams(); @@ -167,8 +177,8 @@ class HdMayaMaterialNetworkConverter { private: HdMaterialNetwork& _network; - const SdfPath& _prefix; - PathToMobjMap* _pathToMobj; + const SdfPath& _prefix; + PathToMobjMap* _pathToMobj; }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/hdMaya/adapters/mayaAttrs.cpp b/lib/usd/hdMaya/adapters/mayaAttrs.cpp index 84341cf6fb..b6aa1de5a1 100644 --- a/lib/usd/hdMaya/adapters/mayaAttrs.cpp +++ b/lib/usd/hdMaya/adapters/mayaAttrs.cpp @@ -13,20 +13,24 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include #include -#include +#include -#define SET_NODE_CLASS(nodeTypeName) \ - using namespace nodeTypeName; \ - MNodeClass nodeClass(#nodeTypeName); \ - if (!TF_VERIFY(nodeClass.typeId() != 0)) { return MStatus::kFailure; } +#define SET_NODE_CLASS(nodeTypeName) \ + using namespace nodeTypeName; \ + MNodeClass nodeClass(#nodeTypeName); \ + if (!TF_VERIFY(nodeClass.typeId() != 0)) { \ + return MStatus::kFailure; \ + } #define SET_ATTR_OBJ(attr) \ setAttrObj(attr, nodeClass, #attr); \ - if (!TF_VERIFY(status)) { return status; } + if (!TF_VERIFY(status)) { \ + return status; \ + } PXR_NAMESPACE_OPEN_SCOPE @@ -145,14 +149,15 @@ MObject imageCenter; } // namespace imagePlane -MStatus initialize() { +MStatus initialize() +{ MStatus status; - auto setAttrObj = [&status]( - MObject& attrObj, MNodeClass& nodeClass, - const MString& name) { + auto setAttrObj = [&status](MObject& attrObj, MNodeClass& nodeClass, const MString& name) { attrObj = nodeClass.attribute(name, &status); - if (!TF_VERIFY(status)) { return; } + if (!TF_VERIFY(status)) { + return; + } if (!TF_VERIFY(!attrObj.isNull())) { status = MS::kFailure; MString errMsg("Error finding '"); diff --git a/lib/usd/hdMaya/adapters/mayaAttrs.h b/lib/usd/hdMaya/adapters/mayaAttrs.h index 3d6143d3e9..5f7cf6acf9 100644 --- a/lib/usd/hdMaya/adapters/mayaAttrs.h +++ b/lib/usd/hdMaya/adapters/mayaAttrs.h @@ -16,12 +16,12 @@ #ifndef HDMAYA_ATTRS_H #define HDMAYA_ATTRS_H -#include -#include +#include #include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE diff --git a/lib/usd/hdMaya/adapters/meshAdapter.cpp b/lib/usd/hdMaya/adapters/meshAdapter.cpp index 40c4b011fa..a31d0708df 100644 --- a/lib/usd/hdMaya/adapters/meshAdapter.cpp +++ b/lib/usd/hdMaya/adapters/meshAdapter.cpp @@ -13,6 +13,18 @@ // See the License for the specific language governing permissions and // limitations under the License. // +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + #include #include #include @@ -26,91 +38,92 @@ #include #include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE namespace { -const std::pair _dirtyBits[]{ - {MayaAttrs::mesh::pnts, - // This is useful when the user edits the mesh. - HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyExtent | - HdChangeTracker::DirtySubdivTags}, - {MayaAttrs::mesh::inMesh, - // We are tracking topology changes and uv changes separately - HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyExtent | - HdChangeTracker::DirtySubdivTags}, - {MayaAttrs::mesh::worldMatrix, HdChangeTracker::DirtyTransform}, - {MayaAttrs::mesh::doubleSided, HdChangeTracker::DirtyDoubleSided}, - {MayaAttrs::mesh::intermediateObject, HdChangeTracker::DirtyVisibility}, - {MayaAttrs::mesh::uvPivot, - // Tracking manual edits to uvs. - HdChangeTracker::DirtyPrimvar}, - {MayaAttrs::mesh::displaySmoothMesh, HdChangeTracker::DirtyDisplayStyle}, - {MayaAttrs::mesh::smoothLevel, HdChangeTracker::DirtyDisplayStyle} +const std::pair _dirtyBits[] { + { MayaAttrs::mesh::pnts, + // This is useful when the user edits the mesh. + HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyExtent + | HdChangeTracker::DirtySubdivTags }, + { MayaAttrs::mesh::inMesh, + // We are tracking topology changes and uv changes separately + HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyExtent + | HdChangeTracker::DirtySubdivTags }, + { MayaAttrs::mesh::worldMatrix, HdChangeTracker::DirtyTransform }, + { MayaAttrs::mesh::doubleSided, HdChangeTracker::DirtyDoubleSided }, + { MayaAttrs::mesh::intermediateObject, HdChangeTracker::DirtyVisibility }, + { MayaAttrs::mesh::uvPivot, + // Tracking manual edits to uvs. + HdChangeTracker::DirtyPrimvar }, + { MayaAttrs::mesh::displaySmoothMesh, HdChangeTracker::DirtyDisplayStyle }, + { MayaAttrs::mesh::smoothLevel, HdChangeTracker::DirtyDisplayStyle } }; } // namespace -class HdMayaMeshAdapter : public HdMayaShapeAdapter { +class HdMayaMeshAdapter : public HdMayaShapeAdapter +{ public: HdMayaMeshAdapter(HdMayaDelegateCtx* delegate, const MDagPath& dag) - : HdMayaShapeAdapter(delegate->GetPrimPath(dag, false), delegate, dag) { + : HdMayaShapeAdapter(delegate->GetPrimPath(dag, false), delegate, dag) + { } ~HdMayaMeshAdapter() = default; - void Populate() override { - if (_isPopulated) { return; } - GetDelegate()->InsertRprim( - HdPrimTypeTokens->mesh, GetID(), GetInstancerID()); + void Populate() override + { + if (_isPopulated) { + return; + } + GetDelegate()->InsertRprim(HdPrimTypeTokens->mesh, GetID(), GetInstancerID()); _isPopulated = true; } void AddBuggyCallback(MCallbackId id) { _buggyCallbacks.append(id); } - void CreateCallbacks() override { + void CreateCallbacks() override + { MStatus status; - auto obj = GetNode(); + auto obj = GetNode(); if (obj != MObject::kNullObj) { TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) - .Msg( - "Creating mesh adapter callbacks for prim (%s).\n", - GetID().GetText()); + .Msg("Creating mesh adapter callbacks for prim (%s).\n", GetID().GetText()); - auto id = MNodeMessage::addNodeDirtyPlugCallback( - obj, NodeDirtiedCallback, this, &status); - if (status) { AddCallback(id); } + auto id + = MNodeMessage::addNodeDirtyPlugCallback(obj, NodeDirtiedCallback, this, &status); + if (status) { + AddCallback(id); + } id = MNodeMessage::addAttributeChangedCallback( obj, AttributeChangedCallback, this, &status); - if (status) { AddCallback(id); } + if (status) { + AddCallback(id); + } id = MPolyMessage::addPolyTopologyChangedCallback( obj, TopologyChangedCallback, this, &status); - if (status) { AddCallback(id); } - bool wantModifications[3] = {true, true, true}; + if (status) { + AddCallback(id); + } + bool wantModifications[3] = { true, true, true }; id = MPolyMessage::addPolyComponentIdChangedCallback( obj, wantModifications, 3, ComponentIdChanged, this, &status); - if (status) { AddBuggyCallback(id); } - id = MPolyMessage::addUVSetChangedCallback( - obj, UVSetChangedCallback, this, &status); - if (status) { AddBuggyCallback(id); } + if (status) { + AddBuggyCallback(id); + } + id = MPolyMessage::addUVSetChangedCallback(obj, UVSetChangedCallback, this, &status); + if (status) { + AddBuggyCallback(id); + } } HdMayaDagAdapter::CreateCallbacks(); } HDMAYA_API - void RemoveCallbacks() override { + void RemoveCallbacks() override + { if (_buggyCallbacks.length() > 0) { TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) .Msg("Removing buggy PolyComponentIdChangedCallbacks\n"); @@ -122,21 +135,24 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { HdMayaAdapter::RemoveCallbacks(); } - bool IsSupported() const override { - return GetDelegate()->GetRenderIndex().IsRprimTypeSupported( - HdPrimTypeTokens->mesh); + bool IsSupported() const override + { + return GetDelegate()->GetRenderIndex().IsRprimTypeSupported(HdPrimTypeTokens->mesh); } - VtValue GetUVs() { + VtValue GetUVs() + { MStatus status; MFnMesh mesh(GetDagPath(), &status); - if (ARCH_UNLIKELY(!status)) { return {}; } + if (ARCH_UNLIKELY(!status)) { + return {}; + } VtArray uvs; uvs.reserve(static_cast(mesh.numFaceVertices())); for (MItMeshPolygon pit(GetDagPath()); !pit.isDone(); pit.next()) { const auto vertexCount = pit.polygonVertexCount(); - for (auto i = decltype(vertexCount){0}; i < vertexCount; ++i) { - float2 uv = {0.0f, 0.0f}; + for (auto i = decltype(vertexCount) { 0 }; i < vertexCount; ++i) { + float2 uv = { 0.0f, 0.0f }; pit.getUV(i, uv); uvs.push_back(GfVec2f(uv[0], uv[1])); } @@ -145,26 +161,32 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { return VtValue(uvs); } - VtValue GetPoints(const MFnMesh& mesh) { - MStatus status; - const auto* rawPoints = - reinterpret_cast(mesh.getRawPoints(&status)); - if (ARCH_UNLIKELY(!status)) { return {}; } + VtValue GetPoints(const MFnMesh& mesh) + { + MStatus status; + const auto* rawPoints = reinterpret_cast(mesh.getRawPoints(&status)); + if (ARCH_UNLIKELY(!status)) { + return {}; + } VtVec3fArray ret; ret.assign(rawPoints, rawPoints + mesh.numVertices()); return VtValue(ret); } - VtValue Get(const TfToken& key) override { + VtValue Get(const TfToken& key) override + { TF_DEBUG(HDMAYA_ADAPTER_GET) .Msg( - "Called HdMayaMeshAdapter::Get(%s) - %s\n", key.GetText(), + "Called HdMayaMeshAdapter::Get(%s) - %s\n", + key.GetText(), GetDagPath().partialPathName().asChar()); if (key == HdTokens->points) { MStatus status; MFnMesh mesh(GetDagPath(), &status); - if (ARCH_UNLIKELY(!status)) { return {}; } + if (ARCH_UNLIKELY(!status)) { + return {}; + } return GetPoints(mesh); } else if (key == HdMayaAdapterTokens->st) { return GetUVs(); @@ -172,19 +194,22 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { return {}; } - size_t SamplePrimvar( - const TfToken& key, size_t maxSampleCount, float* times, - VtValue* samples) override { - if (maxSampleCount < 1) { return 0; } + size_t SamplePrimvar(const TfToken& key, size_t maxSampleCount, float* times, VtValue* samples) + override + { + if (maxSampleCount < 1) { + return 0; + } if (key == HdTokens->points) { MStatus status; MFnMesh mesh(GetDagPath(), &status); - if (ARCH_UNLIKELY(!status)) { return 0; } + if (ARCH_UNLIKELY(!status)) { + return 0; + } times[0] = 0.0f; samples[0] = GetPoints(mesh); - if (maxSampleCount == 1 || - !GetDelegate()->GetParams().enableMotionSamples) { + if (maxSampleCount == 1 || !GetDelegate()->GetParams().enableMotionSamples) { return 1; } times[1] = 1.0f; @@ -200,8 +225,9 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { return 0; } - HdMeshTopology GetMeshTopology() override { - MFnMesh mesh(GetDagPath()); + HdMeshTopology GetMeshTopology() override + { + MFnMesh mesh(GetDagPath()); const auto numPolygons = mesh.numPolygons(); VtIntArray faceVertexCounts; faceVertexCounts.reserve(static_cast(numPolygons)); @@ -210,7 +236,7 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { for (MItMeshPolygon pit(GetDagPath()); !pit.isDone(); pit.next()) { const auto vc = pit.polygonVertexCount(); faceVertexCounts.push_back(vc); - for (auto i = decltype(vc){0}; i < vc; ++i) { + for (auto i = decltype(vc) { 0 }; i < vc; ++i) { faceVertexIndices.push_back(pit.vertexIndex(i)); } } @@ -218,44 +244,54 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { // TODO: Maybe we could use the flat shading of the display style? return HdMeshTopology( #if MAYA_APP_VERSION >= 2019 - (GetDelegate()->GetParams().displaySmoothMeshes || - GetDisplayStyle().refineLevel > 0) + (GetDelegate()->GetParams().displaySmoothMeshes || GetDisplayStyle().refineLevel > 0) ? PxOsdOpenSubdivTokens->catmullClark : PxOsdOpenSubdivTokens->none, #else - GetDelegate()->GetParams().displaySmoothMeshes - ? PxOsdOpenSubdivTokens->catmullClark - : PxOsdOpenSubdivTokens->none, + GetDelegate()->GetParams().displaySmoothMeshes ? PxOsdOpenSubdivTokens->catmullClark + : PxOsdOpenSubdivTokens->none, #endif - UsdGeomTokens->rightHanded, faceVertexCounts, faceVertexIndices); + UsdGeomTokens->rightHanded, + faceVertexCounts, + faceVertexIndices); } - HdDisplayStyle GetDisplayStyle() override { + HdDisplayStyle GetDisplayStyle() override + { #if MAYA_APP_VERSION >= 2019 - MStatus status; + MStatus status; MFnDependencyNode node(GetNode(), &status); - if (ARCH_UNLIKELY(!status)) { return {0, false, false}; } - const auto displaySmoothMesh = - node.findPlug(MayaAttrs::mesh::displaySmoothMesh, true).asShort(); - if (displaySmoothMesh == 0) { return {0, false, false}; } - const auto smoothLevel = std::max( - 0, node.findPlug(MayaAttrs::mesh::smoothLevel, true).asInt()); - return {smoothLevel, false, false}; + if (ARCH_UNLIKELY(!status)) { + return { 0, false, false }; + } + const auto displaySmoothMesh + = node.findPlug(MayaAttrs::mesh::displaySmoothMesh, true).asShort(); + if (displaySmoothMesh == 0) { + return { 0, false, false }; + } + const auto smoothLevel + = std::max(0, node.findPlug(MayaAttrs::mesh::smoothLevel, true).asInt()); + return { smoothLevel, false, false }; #else - return {0, false, false}; + return { 0, false, false }; #endif } - PxOsdSubdivTags GetSubdivTags() override { + PxOsdSubdivTags GetSubdivTags() override + { #if MAYA_APP_VERSION >= 2019 PxOsdSubdivTags tags; - if (GetDisplayStyle().refineLevel < 1) { return tags; } + if (GetDisplayStyle().refineLevel < 1) { + return tags; + } MStatus status; MFnMesh mesh(GetNode(), &status); - if (ARCH_UNLIKELY(!status)) { return tags; } - MUintArray creaseVertIds; + if (ARCH_UNLIKELY(!status)) { + return tags; + } + MUintArray creaseVertIds; MDoubleArray creaseVertValues; mesh.getCreaseVertices(creaseVertIds, creaseVertValues); const auto creaseVertIdCount = creaseVertIds.length(); @@ -263,7 +299,7 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { return tags; } - MUintArray creaseEdgeIds; + MUintArray creaseEdgeIds; MDoubleArray creaseEdgeValues; mesh.getCreaseEdges(creaseEdgeIds, creaseEdgeValues); const auto creaseEdgeIdCount = creaseEdgeIds.length(); @@ -272,10 +308,9 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { } if (creaseVertIdCount > 0) { - VtIntArray cornerIndices(creaseVertIdCount); + VtIntArray cornerIndices(creaseVertIdCount); VtFloatArray cornerWeights(creaseVertIdCount); - for (auto i = decltype(creaseVertIdCount){0}; i < creaseVertIdCount; - ++i) { + for (auto i = decltype(creaseVertIdCount) { 0 }; i < creaseVertIdCount; ++i) { cornerIndices[i] = static_cast(creaseVertIds[i]); cornerWeights[i] = static_cast(creaseVertValues[i]); } @@ -287,11 +322,10 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { // TODO: Do a similar compression to usdMaya: // meshWrite_Subdiv.cpp:_CompressCreases. if (creaseEdgeIdCount > 0) { - VtIntArray edgeIndices(creaseEdgeIdCount * 2); + VtIntArray edgeIndices(creaseEdgeIdCount * 2); VtFloatArray edgeWeights(creaseEdgeIdCount); - int edgeVertices[2] = {0, 0}; - for (auto i = decltype(creaseEdgeIdCount){0}; i < creaseEdgeIdCount; - ++i) { + int edgeVertices[2] = { 0, 0 }; + for (auto i = decltype(creaseEdgeIdCount) { 0 }; i < creaseEdgeIdCount; ++i) { mesh.getEdgeVertices(creaseEdgeIds[i], edgeVertices); edgeIndices[i * 2] = edgeVertices[0]; edgeIndices[i * 2 + 1] = edgeVertices[1]; @@ -313,14 +347,14 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { #endif } - HdPrimvarDescriptorVector GetPrimvarDescriptors( - HdInterpolation interpolation) override { + HdPrimvarDescriptorVector GetPrimvarDescriptors(HdInterpolation interpolation) override + { if (interpolation == HdInterpolationVertex) { HdPrimvarDescriptor desc; desc.name = UsdGeomTokens->points; desc.interpolation = interpolation; desc.role = HdPrimvarRoleTokens->point; - return {desc}; + return { desc }; } else if (interpolation == HdInterpolationFaceVarying) { // UVs are face varying in maya. MFnMesh mesh(GetDagPath()); @@ -329,28 +363,29 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { desc.name = HdMayaAdapterTokens->st; desc.interpolation = interpolation; desc.role = HdPrimvarRoleTokens->textureCoordinate; - return {desc}; + return { desc }; } } return {}; } - bool GetDoubleSided() override { + bool GetDoubleSided() override + { MFnMesh mesh(GetDagPath()); - auto p = mesh.findPlug(MayaAttrs::mesh::doubleSided, true); - if (ARCH_UNLIKELY(p.isNull())) { return true; } + auto p = mesh.findPlug(MayaAttrs::mesh::doubleSided, true); + if (ARCH_UNLIKELY(p.isNull())) { + return true; + } bool doubleSided = true; p.getValue(doubleSided); return doubleSided; } - bool HasType(const TfToken& typeId) const override { - return typeId == HdPrimTypeTokens->mesh; - } + bool HasType(const TfToken& typeId) const override { return typeId == HdPrimTypeTokens->mesh; } private: - static void NodeDirtiedCallback( - MObject& node, MPlug& plug, void* clientData) { + static void NodeDirtiedCallback(MObject& node, MPlug& plug, void* clientData) + { auto* adapter = reinterpret_cast(clientData); for (const auto& it : _dirtyBits) { if (it.first == plug) { @@ -359,7 +394,8 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { .Msg( "Marking prim dirty with bits %u because %s plug was " "dirtied.\n", - it.second, plug.partialName().asChar()); + it.second, + plug.partialName().asChar()); return; } } @@ -368,13 +404,17 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { .Msg( "%s (%s) plug dirtying was not handled by " "HdMayaMeshAdapter::NodeDirtiedCallback.\n", - plug.name().asChar(), plug.partialName().asChar()); + plug.name().asChar(), + plug.partialName().asChar()); } // For material assignments for now. static void AttributeChangedCallback( - MNodeMessage::AttributeMessage msg, MPlug& plug, MPlug& otherPlug, - void* clientData) { + MNodeMessage::AttributeMessage msg, + MPlug& plug, + MPlug& otherPlug, + void* clientData) + { auto* adapter = reinterpret_cast(clientData); if (plug == MayaAttrs::mesh::instObjGroups) { adapter->MarkDirty(HdChangeTracker::DirtyMaterialId); @@ -383,28 +423,33 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { .Msg( "%s (%s) plug dirtying was not handled by " "HdMayaMeshAdapter::attributeChangedCallback.\n", - plug.name().asChar(), plug.name().asChar()); + plug.name().asChar(), + plug.name().asChar()); } } - static void TopologyChangedCallback(MObject& node, void* clientData) { + static void TopologyChangedCallback(MObject& node, void* clientData) + { auto* adapter = reinterpret_cast(clientData); adapter->MarkDirty( - HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyPoints); + HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyPrimvar + | HdChangeTracker::DirtyPoints); } - static void ComponentIdChanged( - MUintArray componentIds[], unsigned int count, void* clientData) { + static void ComponentIdChanged(MUintArray componentIds[], unsigned int count, void* clientData) + { auto* adapter = reinterpret_cast(clientData); adapter->MarkDirty( - HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyPoints); + HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyPrimvar + | HdChangeTracker::DirtyPoints); } static void UVSetChangedCallback( - MObject& node, const MString& name, MPolyMessage::MessageType type, - void* clientData) { + MObject& node, + const MString& name, + MPolyMessage::MessageType type, + void* clientData) + { // TODO: Only track the uvset we care about. auto* adapter = reinterpret_cast(clientData); adapter->MarkDirty(HdChangeTracker::DirtyPrimvar); @@ -421,15 +466,16 @@ class HdMayaMeshAdapter : public HdMayaShapeAdapter { MCallbackIdArray _buggyCallbacks; }; -TF_REGISTRY_FUNCTION(TfType) { +TF_REGISTRY_FUNCTION(TfType) +{ TfType::Define>(); } -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, mesh) { +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, mesh) +{ HdMayaAdapterRegistry::RegisterShapeAdapter( TfToken("mesh"), - [](HdMayaDelegateCtx* delegate, - const MDagPath& dag) -> HdMayaShapeAdapterPtr { + [](HdMayaDelegateCtx* delegate, const MDagPath& dag) -> HdMayaShapeAdapterPtr { return HdMayaShapeAdapterPtr(new HdMayaMeshAdapter(delegate, dag)); }); } diff --git a/lib/usd/hdMaya/adapters/nurbsCurveAdapter.cpp b/lib/usd/hdMaya/adapters/nurbsCurveAdapter.cpp index 0a218119ed..b25514f621 100644 --- a/lib/usd/hdMaya/adapters/nurbsCurveAdapter.cpp +++ b/lib/usd/hdMaya/adapters/nurbsCurveAdapter.cpp @@ -13,10 +13,15 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include +#include +#include +#include + #include #include #include +#include #include #include @@ -25,126 +30,134 @@ #include #include -#include -#include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE namespace { -const std::array, 4> _dirtyBits{{ - {MayaAttrs::nurbsCurve::controlPoints, - HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyExtent}, - {MayaAttrs::nurbsCurve::worldMatrix, HdChangeTracker::DirtyTransform}, - {MayaAttrs::nurbsCurve::doubleSided, HdChangeTracker::DirtyDoubleSided}, - {MayaAttrs::nurbsCurve::intermediateObject, - HdChangeTracker::DirtyVisibility}, -}}; +const std::array, 4> _dirtyBits { { + { MayaAttrs::nurbsCurve::controlPoints, + HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyExtent }, + { MayaAttrs::nurbsCurve::worldMatrix, HdChangeTracker::DirtyTransform }, + { MayaAttrs::nurbsCurve::doubleSided, HdChangeTracker::DirtyDoubleSided }, + { MayaAttrs::nurbsCurve::intermediateObject, HdChangeTracker::DirtyVisibility }, +} }; } // namespace -class HdMayaNurbsCurveAdapter : public HdMayaShapeAdapter { +class HdMayaNurbsCurveAdapter : public HdMayaShapeAdapter +{ public: HdMayaNurbsCurveAdapter(HdMayaDelegateCtx* delegate, const MDagPath& dag) - : HdMayaShapeAdapter(delegate->GetPrimPath(dag, false), delegate, dag) { + : HdMayaShapeAdapter(delegate->GetPrimPath(dag, false), delegate, dag) + { } ~HdMayaNurbsCurveAdapter() = default; - bool IsSupported() const override { - return GetDelegate()->GetRenderIndex().IsRprimTypeSupported( - HdPrimTypeTokens->basisCurves); + bool IsSupported() const override + { + return GetDelegate()->GetRenderIndex().IsRprimTypeSupported(HdPrimTypeTokens->basisCurves); } - void Populate() override { - GetDelegate()->InsertRprim( - HdPrimTypeTokens->basisCurves, GetID()); - } + void Populate() override { GetDelegate()->InsertRprim(HdPrimTypeTokens->basisCurves, GetID()); } - void CreateCallbacks() override { + void CreateCallbacks() override + { MStatus status; - auto obj = GetNode(); + auto obj = GetNode(); if (obj != MObject::kNullObj) { TF_DEBUG(HDMAYA_ADAPTER_CALLBACKS) - .Msg( - "Creating nurbs curve adapter callbacks for prim (%s).\n", - GetID().GetText()); + .Msg("Creating nurbs curve adapter callbacks for prim (%s).\n", GetID().GetText()); - auto id = MNodeMessage::addNodeDirtyPlugCallback( - obj, NodeDirtiedCallback, this, &status); - if (status) { AddCallback(id); } + auto id + = MNodeMessage::addNodeDirtyPlugCallback(obj, NodeDirtiedCallback, this, &status); + if (status) { + AddCallback(id); + } id = MNodeMessage::addAttributeChangedCallback( obj, AttributeChangedCallback, this, &status); - if (status) { AddCallback(id); } + if (status) { + AddCallback(id); + } id = MPolyMessage::addPolyTopologyChangedCallback( obj, TopologyChangedCallback, this, &status); - if (status) { AddCallback(id); } - bool wantModifications[3] = {true, true, true}; + if (status) { + AddCallback(id); + } + bool wantModifications[3] = { true, true, true }; id = MPolyMessage::addPolyComponentIdChangedCallback( obj, wantModifications, 3, ComponentIdChanged, this, &status); - if (status) { AddCallback(id); } + if (status) { + AddCallback(id); + } } HdMayaDagAdapter::CreateCallbacks(); } - VtValue Get(const TfToken& key) override { + VtValue Get(const TfToken& key) override + { TF_DEBUG(HDMAYA_ADAPTER_GET) .Msg( - "Called HdMayaNurbsCurveAdapter::Get(%s) - %s\n", key.GetText(), + "Called HdMayaNurbsCurveAdapter::Get(%s) - %s\n", + key.GetText(), GetDagPath().partialPathName().asChar()); if (key == HdTokens->points) { MFnNurbsCurve curve(GetDagPath()); - MStatus status; - MPointArray pointArray; + MStatus status; + MPointArray pointArray; status = curve.getCVs(pointArray); - if (!status) { return {}; } + if (!status) { + return {}; + } VtVec3fArray ret(pointArray.length()); - const auto pointCount = pointArray.length(); - for (auto i = decltype(pointCount){0}; i < pointCount; i++) { + const auto pointCount = pointArray.length(); + for (auto i = decltype(pointCount) { 0 }; i < pointCount; i++) { const auto pt = pointArray[i]; ret[i] = GfVec3f( - static_cast(pt.x), static_cast(pt.y), - static_cast(pt.z)); + static_cast(pt.x), static_cast(pt.y), static_cast(pt.z)); } return VtValue(ret); } return {}; } - HdBasisCurvesTopology GetBasisCurvesTopology() override { + HdBasisCurvesTopology GetBasisCurvesTopology() override + { MFnNurbsCurve curve(GetDagPath()); - const auto pointCount = curve.numCVs(); + const auto pointCount = curve.numCVs(); VtIntArray curveVertexCounts; const auto numIndices = (pointCount - 1) * 2; curveVertexCounts.push_back(numIndices); VtIntArray curveIndices(static_cast(numIndices)); - for (auto i = decltype(numIndices){0}; i < numIndices / 2; i++) { + for (auto i = decltype(numIndices) { 0 }; i < numIndices / 2; i++) { curveIndices[i * 2] = i; curveIndices[i * 2 + 1] = i + 1; } return HdBasisCurvesTopology( - HdTokens->linear, HdTokens->bezier, HdTokens->segmented, - curveVertexCounts, curveIndices); + HdTokens->linear, + HdTokens->bezier, + HdTokens->segmented, + curveVertexCounts, + curveIndices); } - HdPrimvarDescriptorVector GetPrimvarDescriptors( - HdInterpolation interpolation) override { + HdPrimvarDescriptorVector GetPrimvarDescriptors(HdInterpolation interpolation) override + { if (interpolation == HdInterpolationVertex) { HdPrimvarDescriptor desc; desc.name = UsdGeomTokens->points; desc.interpolation = interpolation; desc.role = HdPrimvarRoleTokens->point; - return {desc}; + return { desc }; } return {}; } - TfToken GetRenderTag() const override { + TfToken GetRenderTag() const override + { #if USD_VERSION_NUM >= 1910 return HdRenderTagTokens->guide; #else @@ -153,8 +166,8 @@ class HdMayaNurbsCurveAdapter : public HdMayaShapeAdapter { } private: - static void NodeDirtiedCallback( - MObject& node, MPlug& plug, void* clientData) { + static void NodeDirtiedCallback(MObject& node, MPlug& plug, void* clientData) + { auto* adapter = reinterpret_cast(clientData); for (const auto& it : _dirtyBits) { if (it.first == plug) { @@ -163,7 +176,8 @@ class HdMayaNurbsCurveAdapter : public HdMayaShapeAdapter { .Msg( "Marking prim dirty with bits %u because %s plug was " "dirtied.\n", - it.second, plug.partialName().asChar()); + it.second, + plug.partialName().asChar()); return; } } @@ -172,13 +186,17 @@ class HdMayaNurbsCurveAdapter : public HdMayaShapeAdapter { .Msg( "%s (%s) plug dirtying was not handled by " "HdMayaNurbsCurveAdapter::NodeDirtiedCallback.\n", - plug.name().asChar(), plug.partialName().asChar()); + plug.name().asChar(), + plug.partialName().asChar()); } // For material assignments for now. static void AttributeChangedCallback( - MNodeMessage::AttributeMessage msg, MPlug& plug, MPlug& otherPlug, - void* clientData) { + MNodeMessage::AttributeMessage msg, + MPlug& plug, + MPlug& otherPlug, + void* clientData) + { auto* adapter = reinterpret_cast(clientData); if (plug == MayaAttrs::mesh::instObjGroups) { adapter->MarkDirty(HdChangeTracker::DirtyMaterialId); @@ -187,38 +205,39 @@ class HdMayaNurbsCurveAdapter : public HdMayaShapeAdapter { .Msg( "%s (%s) plug dirtying was not handled by " "HdMayaNurbsCurveAdapter::attributeChangedCallback.\n", - plug.name().asChar(), plug.name().asChar()); + plug.name().asChar(), + plug.name().asChar()); } } - static void TopologyChangedCallback(MObject& node, void* clientData) { + static void TopologyChangedCallback(MObject& node, void* clientData) + { auto* adapter = reinterpret_cast(clientData); adapter->MarkDirty( - HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyPoints); + HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyPrimvar + | HdChangeTracker::DirtyPoints); } - static void ComponentIdChanged( - MUintArray componentIds[], unsigned int count, void* clientData) { + static void ComponentIdChanged(MUintArray componentIds[], unsigned int count, void* clientData) + { auto* adapter = reinterpret_cast(clientData); adapter->MarkDirty( - HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyPrimvar | - HdChangeTracker::DirtyPoints); + HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyPrimvar + | HdChangeTracker::DirtyPoints); } }; -TF_REGISTRY_FUNCTION(TfType) { - TfType::Define< - HdMayaNurbsCurveAdapter, TfType::Bases>(); +TF_REGISTRY_FUNCTION(TfType) +{ + TfType::Define>(); } -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, mesh) { +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, mesh) +{ HdMayaAdapterRegistry::RegisterShapeAdapter( TfToken("nurbsCurve"), - [](HdMayaDelegateCtx* delegate, - const MDagPath& dag) -> HdMayaShapeAdapterPtr { - return HdMayaShapeAdapterPtr( - new HdMayaNurbsCurveAdapter(delegate, dag)); + [](HdMayaDelegateCtx* delegate, const MDagPath& dag) -> HdMayaShapeAdapterPtr { + return HdMayaShapeAdapterPtr(new HdMayaNurbsCurveAdapter(delegate, dag)); }); } diff --git a/lib/usd/hdMaya/adapters/pointLightAdapter.cpp b/lib/usd/hdMaya/adapters/pointLightAdapter.cpp index a8826dd0fc..26c47afacd 100644 --- a/lib/usd/hdMaya/adapters/pointLightAdapter.cpp +++ b/lib/usd/hdMaya/adapters/pointLightAdapter.cpp @@ -13,27 +13,31 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include +#include +#include +#include -#include #include #include +#include #include -#include -#include -#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE -class HdMayaPointLightAdapter : public HdMayaLightAdapter { +class HdMayaPointLightAdapter : public HdMayaLightAdapter +{ public: HdMayaPointLightAdapter(HdMayaDelegateCtx* delegate, const MDagPath& dag) - : HdMayaLightAdapter(delegate, dag) {} + : HdMayaLightAdapter(delegate, dag) + { + } - const TfToken& LightType() const override { + const TfToken& LightType() const override + { if (GetDelegate()->IsHdSt()) { return HdPrimTypeTokens->simpleLight; } else { @@ -41,11 +45,13 @@ class HdMayaPointLightAdapter : public HdMayaLightAdapter { } } - VtValue GetLightParamValue(const TfToken& paramName) override { + VtValue GetLightParamValue(const TfToken& paramName) override + { TF_DEBUG(HDMAYA_ADAPTER_GET_LIGHT_PARAM_VALUE) .Msg( "Called HdMayaPointLightAdapter::GetLightParamValue(%s) - %s\n", - paramName.GetText(), GetDagPath().partialPathName().asChar()); + paramName.GetText(), + GetDagPath().partialPathName().asChar()); MFnPointLight light(GetDagPath()); if (paramName == UsdLuxTokens->radius) { @@ -59,18 +65,17 @@ class HdMayaPointLightAdapter : public HdMayaLightAdapter { } }; -TF_REGISTRY_FUNCTION(TfType) { - TfType::Define< - HdMayaPointLightAdapter, TfType::Bases >(); +TF_REGISTRY_FUNCTION(TfType) +{ + TfType::Define>(); } -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, pointLight) { +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, pointLight) +{ HdMayaAdapterRegistry::RegisterLightAdapter( TfToken("pointLight"), - [](HdMayaDelegateCtx* delegate, - const MDagPath& dag) -> HdMayaLightAdapterPtr { - return HdMayaLightAdapterPtr( - new HdMayaPointLightAdapter(delegate, dag)); + [](HdMayaDelegateCtx* delegate, const MDagPath& dag) -> HdMayaLightAdapterPtr { + return HdMayaLightAdapterPtr(new HdMayaPointLightAdapter(delegate, dag)); }); } diff --git a/lib/usd/hdMaya/adapters/proxyAdapter.cpp b/lib/usd/hdMaya/adapters/proxyAdapter.cpp index 15644a1a24..67546731f2 100644 --- a/lib/usd/hdMaya/adapters/proxyAdapter.cpp +++ b/lib/usd/hdMaya/adapters/proxyAdapter.cpp @@ -15,15 +15,15 @@ // #include "proxyAdapter.h" -#include -#include - #include #include #include #include #include +#include +#include + #if WANT_UFE_BUILD #include #include @@ -31,17 +31,18 @@ PXR_NAMESPACE_OPEN_SCOPE -HdMayaProxyAdapter::HdMayaProxyAdapter( - HdMayaDelegateCtx* delegate, const MDagPath& dag) - : HdMayaShapeAdapter(delegate->GetPrimPath(dag, false), delegate, dag) { - MStatus status; +HdMayaProxyAdapter::HdMayaProxyAdapter(HdMayaDelegateCtx* delegate, const MDagPath& dag) + : HdMayaShapeAdapter(delegate->GetPrimPath(dag, false), delegate, dag) +{ + MStatus status; MFnDependencyNode mfnNode(_node, &status); - if (!TF_VERIFY(status, "Error getting MFnDependencyNode")) { return; } + if (!TF_VERIFY(status, "Error getting MFnDependencyNode")) { + return; + } _proxy = dynamic_cast(mfnNode.userNode()); if (!TF_VERIFY( - _proxy, "Error getting MayaUsdProxyShapeBase* for %s", - mfnNode.name().asChar())) { + _proxy, "Error getting MayaUsdProxyShapeBase* for %s", mfnNode.name().asChar())) { return; } @@ -51,25 +52,29 @@ HdMayaProxyAdapter::HdMayaProxyAdapter( HdMayaProxyDelegate::AddAdapter(this); } -HdMayaProxyAdapter::~HdMayaProxyAdapter() { - HdMayaProxyDelegate::RemoveAdapter(this); -} +HdMayaProxyAdapter::~HdMayaProxyAdapter() { HdMayaProxyDelegate::RemoveAdapter(this); } -void HdMayaProxyAdapter::Populate() { - if (_isPopulated || !_proxy) { return; } +void HdMayaProxyAdapter::Populate() +{ + if (_isPopulated || !_proxy) { + return; + } TF_DEBUG(HDMAYA_AL_POPULATE) .Msg("HdMayaProxyDelegate::Populating %s\n", _proxy->name().asChar()); auto stage = _proxy->getUsdStage(); if (!stage) { - MGlobal::displayError( - MString("Could not get stage for proxyShape: ") + _proxy->name()); + MGlobal::displayError(MString("Could not get stage for proxyShape: ") + _proxy->name()); return; } - if (!_usdDelegate) { CreateUsdImagingDelegate(); } - if (!TF_VERIFY(_usdDelegate)) { return; } + if (!_usdDelegate) { + CreateUsdImagingDelegate(); + } + if (!TF_VERIFY(_usdDelegate)) { + return; + } _usdDelegate->Populate(stage->GetPseudoRoot()); @@ -78,7 +83,8 @@ void HdMayaProxyAdapter::Populate() { bool HdMayaProxyAdapter::IsSupported() const { return _proxy != nullptr; } -void HdMayaProxyAdapter::MarkDirty(HdDirtyBits dirtyBits) { +void HdMayaProxyAdapter::MarkDirty(HdDirtyBits dirtyBits) +{ if (dirtyBits != 0) { if (dirtyBits & HdChangeTracker::DirtyTransform) { // At the time this is called, the proxy shape's transform may not @@ -98,35 +104,41 @@ void HdMayaProxyAdapter::MarkDirty(HdDirtyBits dirtyBits) { } } -VtValue HdMayaProxyAdapter::Get(const TfToken& key) { +VtValue HdMayaProxyAdapter::Get(const TfToken& key) +{ TF_DEBUG(HDMAYA_ADAPTER_GET) .Msg( - "Called HdMayaProxyAdapter::Get(%s) - %s\n", key.GetText(), + "Called HdMayaProxyAdapter::Get(%s) - %s\n", + key.GetText(), GetDagPath().partialPathName().asChar()); return {}; } -bool HdMayaProxyAdapter::HasType(const TfToken& typeId) const { - return false; -} +bool HdMayaProxyAdapter::HasType(const TfToken& typeId) const { return false; } void HdMayaProxyAdapter::PopulateSelectedPaths( - const MDagPath& selectedDag, SdfPathVector& selectedSdfPaths, + const MDagPath& selectedDag, + SdfPathVector& selectedSdfPaths, std::unordered_set& selectedMasters, - const HdSelectionSharedPtr& selection) { + const HdSelectionSharedPtr& selection) +{ // TODO: if the AL proxy shape is ever updated to work properly // when instanced, update this to work with instances as well. // May require a fair amount of reworking... perhaps instance // handling should be moved up (into the non-virtual-overridden // code) if possible? - MStatus status; - MObject proxyMObj; + MStatus status; + MObject proxyMObj; MFnDagNode proxyMFnDag; proxyMObj = _proxy->thisMObject(); - if (!TF_VERIFY(!proxyMObj.isNull())) { return; } - if (!TF_VERIFY(proxyMFnDag.setObject(proxyMObj))) { return; } + if (!TF_VERIFY(!proxyMObj.isNull())) { + return; + } + if (!TF_VERIFY(proxyMFnDag.setObject(proxyMObj))) { + return; + } // First, we check to see if the entire proxy shape is selected if (selectedDag.node() == proxyMObj) { @@ -136,13 +148,16 @@ void HdMayaProxyAdapter::PopulateSelectedPaths( selectedSdfPaths.push_back(_usdDelegate->GetDelegateID()); #endif _usdDelegate->PopulateSelection( - HdSelection::HighlightModeSelect, selectedSdfPaths.back(), - UsdImagingDelegate::ALL_INSTANCES, selection); + HdSelection::HighlightModeSelect, + selectedSdfPaths.back(), + UsdImagingDelegate::ALL_INSTANCES, + selection); return; } } -void HdMayaProxyAdapter::CreateUsdImagingDelegate() { +void HdMayaProxyAdapter::CreateUsdImagingDelegate() +{ // Why do this reset when we do another right below? Because we want // to make sure we delete the old delegate before creating a new one // (the reset statement below will first create a new one, THEN delete @@ -152,14 +167,17 @@ void HdMayaProxyAdapter::CreateUsdImagingDelegate() { _usdDelegate.reset(); _usdDelegate.reset(new HdMayaProxyUsdImagingDelegate( &GetDelegate()->GetRenderIndex(), - _id.AppendChild(TfToken(TfStringPrintf( - "ProxyDelegate_%s_%p", _proxy->name().asChar(), _proxy))), - _proxy, GetDagPath())); + _id.AppendChild( + TfToken(TfStringPrintf("ProxyDelegate_%s_%p", _proxy->name().asChar(), _proxy))), + _proxy, + GetDagPath())); _isPopulated = false; } -void HdMayaProxyAdapter::PreFrame(const MHWRender::MDrawContext& context) { - _usdDelegate->SetSceneMaterialsEnabled(!(context.getDisplayStyle() & MHWRender::MFrameContext::kDefaultMaterial)); +void HdMayaProxyAdapter::PreFrame(const MHWRender::MDrawContext& context) +{ + _usdDelegate->SetSceneMaterialsEnabled( + !(context.getDisplayStyle() & MHWRender::MFrameContext::kDefaultMaterial)); _usdDelegate->ApplyPendingUpdates(); // TODO: set this only when time is actually changed _usdDelegate->SetTime(_proxy->getTime()); @@ -168,8 +186,7 @@ void HdMayaProxyAdapter::PreFrame(const MHWRender::MDrawContext& context) { void HdMayaProxyAdapter::_OnStageSet(const MayaUsdProxyStageSetNotice& notice) { - if(¬ice.GetProxyShape() == _proxy) - { + if (¬ice.GetProxyShape() == _proxy) { // Real work done by delegate->createUsdImagingDelegate TF_DEBUG(HDMAYA_AL_CALLBACKS) .Msg( @@ -187,17 +204,17 @@ void HdMayaProxyAdapter::_OnStageSet(const MayaUsdProxyStageSetNotice& notice) } } -TF_REGISTRY_FUNCTION(TfType) { +TF_REGISTRY_FUNCTION(TfType) +{ TfType::Define>(); } -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, MayaUsd_ProxyShape) { +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, MayaUsd_ProxyShape) +{ HdMayaAdapterRegistry::RegisterShapeAdapter( TfToken(MayaUsdProxyShapeBase::typeName.asChar()), - [](HdMayaDelegateCtx* delegate, - const MDagPath& dag) -> HdMayaShapeAdapterPtr { - return HdMayaShapeAdapterPtr( - new HdMayaProxyAdapter(delegate, dag)); + [](HdMayaDelegateCtx* delegate, const MDagPath& dag) -> HdMayaShapeAdapterPtr { + return HdMayaShapeAdapterPtr(new HdMayaProxyAdapter(delegate, dag)); }); } diff --git a/lib/usd/hdMaya/adapters/proxyAdapter.h b/lib/usd/hdMaya/adapters/proxyAdapter.h index 15a26ebaff..4cf853c5e9 100644 --- a/lib/usd/hdMaya/adapters/proxyAdapter.h +++ b/lib/usd/hdMaya/adapters/proxyAdapter.h @@ -1,20 +1,22 @@ #ifndef HDMAYA_AL_PROXY_ADAPTER_H #define HDMAYA_AL_PROXY_ADAPTER_H -#include -#include -#include - -#include - #include #include +#include + +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE class MayaUsdProxyShapeBase; -class HdMayaProxyAdapter : public HdMayaShapeAdapter, public TfWeakBase { +class HdMayaProxyAdapter + : public HdMayaShapeAdapter + , public TfWeakBase +{ public: HdMayaProxyAdapter(HdMayaDelegateCtx* delegate, const MDagPath& dag); @@ -25,9 +27,10 @@ class HdMayaProxyAdapter : public HdMayaShapeAdapter, public TfWeakBase { void Populate() override; void PopulateSelectedPaths( - const MDagPath& selectedDag, SdfPathVector& selectedSdfPaths, + const MDagPath& selectedDag, + SdfPathVector& selectedSdfPaths, std::unordered_set& selectedMasters, - const HdSelectionSharedPtr& selection) override; + const HdSelectionSharedPtr& selection) override; bool IsSupported() const override; @@ -43,41 +46,46 @@ class HdMayaProxyAdapter : public HdMayaShapeAdapter, public TfWeakBase { #if defined(USD_IMAGING_API_VERSION) && USD_IMAGING_API_VERSION >= 14 SdfPath GetScenePrimPath( - const SdfPath& rprimId, int instanceIndex, - HdInstancerContext *instancerContext) { - return _usdDelegate->GetScenePrimPath( - rprimId, instanceIndex, instancerContext); + const SdfPath& rprimId, + int instanceIndex, + HdInstancerContext* instancerContext) + { + return _usdDelegate->GetScenePrimPath(rprimId, instanceIndex, instancerContext); } #elif defined(USD_IMAGING_API_VERSION) && USD_IMAGING_API_VERSION >= 13 - SdfPath GetScenePrimPath( - const SdfPath& rprimId, int instanceIndex) { - return _usdDelegate->GetScenePrimPath( - rprimId, instanceIndex); + SdfPath GetScenePrimPath(const SdfPath& rprimId, int instanceIndex) + { + return _usdDelegate->GetScenePrimPath(rprimId, instanceIndex); } #else SdfPath GetPathForInstanceIndex( - const SdfPath& protoPrimPath, int instanceIndex, - int* absoluteInstanceIndex, SdfPath* rprimPath = NULL, - SdfPathVector* instanceContext = NULL) { + const SdfPath& protoPrimPath, + int instanceIndex, + int* absoluteInstanceIndex, + SdfPath* rprimPath = NULL, + SdfPathVector* instanceContext = NULL) + { return _usdDelegate->GetPathForInstanceIndex( - protoPrimPath, instanceIndex, absoluteInstanceIndex, rprimPath, - instanceContext); + protoPrimPath, instanceIndex, absoluteInstanceIndex, rprimPath, instanceContext); } #endif - SdfPath ConvertIndexPathToCachePath(SdfPath const& indexPath) { + SdfPath ConvertIndexPathToCachePath(SdfPath const& indexPath) + { return _usdDelegate->ConvertIndexPathToCachePath(indexPath); } - SdfPath ConvertCachePathToIndexPath(SdfPath const& cachePath) { + SdfPath ConvertCachePathToIndexPath(SdfPath const& cachePath) + { return _usdDelegate->ConvertCachePathToIndexPath(cachePath); } bool PopulateSelection( HdSelection::HighlightMode const& highlightMode, - const SdfPath& usdPath, - int instanceIndex, - HdSelectionSharedPtr const& result) { + const SdfPath& usdPath, + int instanceIndex, + HdSelectionSharedPtr const& result) + { return _usdDelegate->PopulateSelection(highlightMode, usdPath, instanceIndex, result); } @@ -87,7 +95,7 @@ class HdMayaProxyAdapter : public HdMayaShapeAdapter, public TfWeakBase { /// Notice listener method for proxy stage set void _OnStageSet(const MayaUsdProxyStageSetNotice& notice); - MayaUsdProxyShapeBase* _proxy{ nullptr }; + MayaUsdProxyShapeBase* _proxy { nullptr }; std::unique_ptr _usdDelegate; }; diff --git a/lib/usd/hdMaya/adapters/shapeAdapter.cpp b/lib/usd/hdMaya/adapters/shapeAdapter.cpp index 2db7896ccc..ecbb637e94 100644 --- a/lib/usd/hdMaya/adapters/shapeAdapter.cpp +++ b/lib/usd/hdMaya/adapters/shapeAdapter.cpp @@ -15,42 +15,53 @@ // #include "shapeAdapter.h" -#include -#include +#include +#include #include -#include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -TF_REGISTRY_FUNCTION(TfType) { - TfType::Define >(); +TF_REGISTRY_FUNCTION(TfType) +{ + TfType::Define>(); } HdMayaShapeAdapter::HdMayaShapeAdapter( - const SdfPath& id, HdMayaDelegateCtx* delegate, const MDagPath& dagPath) - : HdMayaDagAdapter(id, delegate, dagPath) { + const SdfPath& id, + HdMayaDelegateCtx* delegate, + const MDagPath& dagPath) + : HdMayaDagAdapter(id, delegate, dagPath) +{ _CalculateExtent(); } -void HdMayaShapeAdapter::_CalculateExtent() { - MStatus status; +void HdMayaShapeAdapter::_CalculateExtent() +{ + MStatus status; MFnDagNode dagNode(GetDagPath(), &status); if (ARCH_LIKELY(status)) { const auto bb = dagNode.boundingBox(); const auto mn = bb.min(); const auto mx = bb.max(); - _extent.SetMin({mn.x, mn.y, mn.z}); - _extent.SetMax({mx.x, mx.y, mx.z}); + _extent.SetMin({ mn.x, mn.y, mn.z }); + _extent.SetMax({ mx.x, mx.y, mx.z }); _extentDirty = false; } }; size_t HdMayaShapeAdapter::SamplePrimvar( - const TfToken& key, size_t maxSampleCount, float* times, VtValue* samples) { - if (maxSampleCount < 1) { return 0; } + const TfToken& key, + size_t maxSampleCount, + float* times, + VtValue* samples) +{ + if (maxSampleCount < 1) { + return 0; + } times[0] = 0.0f; samples[0] = Get(key); return 1; @@ -58,60 +69,72 @@ size_t HdMayaShapeAdapter::SamplePrimvar( HdMeshTopology HdMayaShapeAdapter::GetMeshTopology() { return {}; }; -HdBasisCurvesTopology HdMayaShapeAdapter::GetBasisCurvesTopology() { - return {}; -}; +HdBasisCurvesTopology HdMayaShapeAdapter::GetBasisCurvesTopology() { return {}; }; -HdDisplayStyle HdMayaShapeAdapter::GetDisplayStyle() { - return {0, false, false}; -} +HdDisplayStyle HdMayaShapeAdapter::GetDisplayStyle() { return { 0, false, false }; } PxOsdSubdivTags HdMayaShapeAdapter::GetSubdivTags() { return {}; } -void HdMayaShapeAdapter::MarkDirty(HdDirtyBits dirtyBits) { +void HdMayaShapeAdapter::MarkDirty(HdDirtyBits dirtyBits) +{ HdMayaDagAdapter::MarkDirty(dirtyBits); - if (dirtyBits & HdChangeTracker::DirtyPoints) { _extentDirty = true; } + if (dirtyBits & HdChangeTracker::DirtyPoints) { + _extentDirty = true; + } } -MObject HdMayaShapeAdapter::GetMaterial() { +MObject HdMayaShapeAdapter::GetMaterial() +{ TF_DEBUG(HDMAYA_ADAPTER_GET) .Msg( "Called HdMayaShapeAdapter::GetMaterial() - %s\n", GetDagPath().partialPathName().asChar()); - MStatus status; + MStatus status; MFnDagNode dagNode(GetDagPath(), &status); - if (!status) { return MObject::kNullObj; } + if (!status) { + return MObject::kNullObj; + } - auto instObjGroups = - dagNode.findPlug(MayaAttrs::dagNode::instObjGroups, true); - if (instObjGroups.isNull()) { return MObject::kNullObj; } + auto instObjGroups = dagNode.findPlug(MayaAttrs::dagNode::instObjGroups, true); + if (instObjGroups.isNull()) { + return MObject::kNullObj; + } MPlugArray conns; // TODO: deal with instancing properly. instObjGroups.elementByLogicalIndex(0).connectedTo(conns, false, true); const auto numConnections = conns.length(); - if (numConnections == 0) { return MObject::kNullObj; } - for (auto i = decltype(numConnections){0}; i < numConnections; ++i) { + if (numConnections == 0) { + return MObject::kNullObj; + } + for (auto i = decltype(numConnections) { 0 }; i < numConnections; ++i) { auto sg = conns[i].node(); - if (sg.apiType() == MFn::kShadingEngine) { return sg; } + if (sg.apiType() == MFn::kShadingEngine) { + return sg; + } } return MObject::kNullObj; } -const GfRange3d& HdMayaShapeAdapter::GetExtent() { - if (_extentDirty) { _CalculateExtent(); } +const GfRange3d& HdMayaShapeAdapter::GetExtent() +{ + if (_extentDirty) { + _CalculateExtent(); + } return _extent; } TfToken HdMayaShapeAdapter::GetRenderTag() const { return HdTokens->geometry; } void HdMayaShapeAdapter::PopulateSelectedPaths( - const MDagPath& selectedDag, SdfPathVector& selectedSdfPaths, + const MDagPath& selectedDag, + SdfPathVector& selectedSdfPaths, std::unordered_set& selectedMasters, - const HdSelectionSharedPtr& selection) { + const HdSelectionSharedPtr& selection) +{ VtIntArray indices(1); if (IsInstanced()) { indices[0] = selectedDag.instanceNumber(); diff --git a/lib/usd/hdMaya/adapters/shapeAdapter.h b/lib/usd/hdMaya/adapters/shapeAdapter.h index b21586c14f..746c68f914 100644 --- a/lib/usd/hdMaya/adapters/shapeAdapter.h +++ b/lib/usd/hdMaya/adapters/shapeAdapter.h @@ -16,27 +16,25 @@ #ifndef HDMAYA_SHAPE_ADAPTER_H #define HDMAYA_SHAPE_ADAPTER_H -#include - #include +#include + PXR_NAMESPACE_OPEN_SCOPE -class HdMayaShapeAdapter : public HdMayaDagAdapter { +class HdMayaShapeAdapter : public HdMayaDagAdapter +{ protected: HDMAYA_API - HdMayaShapeAdapter( - const SdfPath& id, HdMayaDelegateCtx* delegate, - const MDagPath& dagPath); + HdMayaShapeAdapter(const SdfPath& id, HdMayaDelegateCtx* delegate, const MDagPath& dagPath); public: HDMAYA_API virtual ~HdMayaShapeAdapter() = default; HDMAYA_API - virtual size_t SamplePrimvar( - const TfToken& key, size_t maxSampleCount, float* times, - VtValue* samples); + virtual size_t + SamplePrimvar(const TfToken& key, size_t maxSampleCount, float* times, VtValue* samples); HDMAYA_API virtual HdMeshTopology GetMeshTopology(); HDMAYA_API @@ -46,8 +44,8 @@ class HdMayaShapeAdapter : public HdMayaDagAdapter { HDMAYA_API virtual PxOsdSubdivTags GetSubdivTags(); HDMAYA_API - virtual HdPrimvarDescriptorVector GetPrimvarDescriptors( - HdInterpolation interpolation) { + virtual HdPrimvarDescriptorVector GetPrimvarDescriptors(HdInterpolation interpolation) + { return {}; } HDMAYA_API @@ -66,9 +64,10 @@ class HdMayaShapeAdapter : public HdMayaDagAdapter { HDMAYA_API virtual void PopulateSelectedPaths( - const MDagPath& selectedDag, SdfPathVector& selectedSdfPaths, + const MDagPath& selectedDag, + SdfPathVector& selectedSdfPaths, std::unordered_set& selectedMasters, - const HdSelectionSharedPtr& selection); + const HdSelectionSharedPtr& selection); protected: HDMAYA_API @@ -76,7 +75,7 @@ class HdMayaShapeAdapter : public HdMayaDagAdapter { private: GfRange3d _extent; - bool _extentDirty; + bool _extentDirty; }; using HdMayaShapeAdapterPtr = std::shared_ptr; diff --git a/lib/usd/hdMaya/adapters/spotLightAdapter.cpp b/lib/usd/hdMaya/adapters/spotLightAdapter.cpp index 417018039b..5b603bd404 100644 --- a/lib/usd/hdMaya/adapters/spotLightAdapter.cpp +++ b/lib/usd/hdMaya/adapters/spotLightAdapter.cpp @@ -13,64 +13,66 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include -#include -#include +#include +#include +#include +#include +#include -#include #include #include #include #include #include +#include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE namespace { -void GetSpotCutoffAndSoftness( - MFnSpotLight& mayaLight, float& cutoffOut, float& softnessOut) { +void GetSpotCutoffAndSoftness(MFnSpotLight& mayaLight, float& cutoffOut, float& softnessOut) +{ // Divided by two. - auto coneAngle = - static_cast(GfRadiansToDegrees(mayaLight.coneAngle())) * 0.5f; - auto penumbraAngle = - static_cast(GfRadiansToDegrees(mayaLight.penumbraAngle())); + auto coneAngle = static_cast(GfRadiansToDegrees(mayaLight.coneAngle())) * 0.5f; + auto penumbraAngle = static_cast(GfRadiansToDegrees(mayaLight.penumbraAngle())); cutoffOut = coneAngle + penumbraAngle; softnessOut = cutoffOut == 0 ? 0 : penumbraAngle / cutoffOut; } -float GetSpotCutoff(MFnSpotLight& mayaLight) { +float GetSpotCutoff(MFnSpotLight& mayaLight) +{ float cutoff; float softness; GetSpotCutoffAndSoftness(mayaLight, cutoff, softness); return cutoff; } -float GetSpotSoftness(MFnSpotLight& mayaLight) { +float GetSpotSoftness(MFnSpotLight& mayaLight) +{ float cutoff; float softness; GetSpotCutoffAndSoftness(mayaLight, cutoff, softness); return softness; } -float GetSpotFalloff(MFnSpotLight& mayaLight) { - return static_cast(mayaLight.dropOff()); -} +float GetSpotFalloff(MFnSpotLight& mayaLight) { return static_cast(mayaLight.dropOff()); } } // namespace -class HdMayaSpotLightAdapter : public HdMayaLightAdapter { +class HdMayaSpotLightAdapter : public HdMayaLightAdapter +{ public: HdMayaSpotLightAdapter(HdMayaDelegateCtx* delegate, const MDagPath& dag) - : HdMayaLightAdapter(delegate, dag) {} + : HdMayaLightAdapter(delegate, dag) + { + } - const TfToken& LightType() const override { + const TfToken& LightType() const override + { if (GetDelegate()->IsHdSt()) { return HdPrimTypeTokens->simpleLight; } else { @@ -79,8 +81,9 @@ class HdMayaSpotLightAdapter : public HdMayaLightAdapter { } protected: - void _CalculateLightParams(GlfSimpleLight& light) override { - MStatus status; + void _CalculateLightParams(GlfSimpleLight& light) override + { + MStatus status; MFnSpotLight mayaLight(GetDagPath(), &status); if (TF_VERIFY(status)) { light.SetHasShadow(true); @@ -89,15 +92,17 @@ class HdMayaSpotLightAdapter : public HdMayaLightAdapter { } } - VtValue Get(const TfToken& key) override { + VtValue Get(const TfToken& key) override + { TF_DEBUG(HDMAYA_ADAPTER_GET) .Msg( - "Called HdMayaSpotLightAdapter::Get(%s) - %s\n", key.GetText(), + "Called HdMayaSpotLightAdapter::Get(%s) - %s\n", + key.GetText(), GetDagPath().partialPathName().asChar()); if (key == HdLightTokens->shadowParams) { HdxShadowParams shadowParams; - MFnSpotLight mayaLight(GetDagPath()); + MFnSpotLight mayaLight(GetDagPath()); if (!GetShadowsEnabled(mayaLight)) { shadowParams.enabled = false; return VtValue(shadowParams); @@ -112,13 +117,15 @@ class HdMayaSpotLightAdapter : public HdMayaLightAdapter { return HdMayaLightAdapter::Get(key); } - VtValue GetLightParamValue(const TfToken& paramName) override { + VtValue GetLightParamValue(const TfToken& paramName) override + { TF_DEBUG(HDMAYA_ADAPTER_GET_LIGHT_PARAM_VALUE) .Msg( "Called HdMayaSpotLightAdapter::GetLightParamValue(%s) - %s\n", - paramName.GetText(), GetDagPath().partialPathName().asChar()); + paramName.GetText(), + GetDagPath().partialPathName().asChar()); - MStatus status; + MStatus status; MFnSpotLight light(GetDagPath(), &status); if (TF_VERIFY(status)) { if (paramName == UsdLuxTokens->radius) { @@ -139,18 +146,17 @@ class HdMayaSpotLightAdapter : public HdMayaLightAdapter { } }; -TF_REGISTRY_FUNCTION(TfType) { - TfType::Define< - HdMayaSpotLightAdapter, TfType::Bases >(); +TF_REGISTRY_FUNCTION(TfType) +{ + TfType::Define>(); } -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, pointLight) { +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaAdapterRegistry, pointLight) +{ HdMayaAdapterRegistry::RegisterLightAdapter( TfToken("spotLight"), - [](HdMayaDelegateCtx* delegate, - const MDagPath& dag) -> HdMayaLightAdapterPtr { - return HdMayaLightAdapterPtr( - new HdMayaSpotLightAdapter(delegate, dag)); + [](HdMayaDelegateCtx* delegate, const MDagPath& dag) -> HdMayaLightAdapterPtr { + return HdMayaLightAdapterPtr(new HdMayaSpotLightAdapter(delegate, dag)); }); } diff --git a/lib/usd/hdMaya/adapters/tokens.h b/lib/usd/hdMaya/adapters/tokens.h index 9dd4102ca2..e496694a06 100644 --- a/lib/usd/hdMaya/adapters/tokens.h +++ b/lib/usd/hdMaya/adapters/tokens.h @@ -16,11 +16,11 @@ #ifndef HDMAYA_ADAPTER_TOKENS_H #define HDMAYA_ADAPTER_TOKENS_H -#include -#include - #include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE // clang-format off @@ -75,8 +75,7 @@ PXR_NAMESPACE_OPEN_SCOPE (pxrUsdPreviewSurface) // clang-format on -TF_DECLARE_PUBLIC_TOKENS( - HdMayaAdapterTokens, HDMAYA_API, HDMAYA_ADAPTER_TOKENS); +TF_DECLARE_PUBLIC_TOKENS(HdMayaAdapterTokens, HDMAYA_API, HDMAYA_ADAPTER_TOKENS); PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/hdMaya/debugCodes.cpp b/lib/usd/hdMaya/debugCodes.cpp index 510442dacf..277a0431e1 100644 --- a/lib/usd/hdMaya/debugCodes.cpp +++ b/lib/usd/hdMaya/debugCodes.cpp @@ -19,23 +19,20 @@ PXR_NAMESPACE_OPEN_SCOPE -TF_REGISTRY_FUNCTION(TfDebug) { +TF_REGISTRY_FUNCTION(TfDebug) +{ TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_AL_CALLBACKS, - "Print info about the various callbacks used by hdMaya_al"); + HDMAYA_AL_CALLBACKS, "Print info about the various callbacks used by hdMaya_al"); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_AL_PLUGIN, - "Print info about the loading of the hdMaya_al plugin"); + HDMAYA_AL_PLUGIN, "Print info about the loading of the hdMaya_al plugin"); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_AL_POPULATE, - "Print info about populating the delegate from the stage"); + HDMAYA_AL_POPULATE, "Print info about populating the delegate from the stage"); TF_DEBUG_ENVIRONMENT_SYMBOL( HDMAYA_AL_PROXY_DELEGATE, "Print misc info about (ie, creation / destruction) of the delegate " "object"); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_AL_SELECTION, - "Print info about selecting AL objects in the maya-to-hydra viewport"); + HDMAYA_AL_SELECTION, "Print info about selecting AL objects in the maya-to-hydra viewport"); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/hdMaya/delegates/delegate.cpp b/lib/usd/hdMaya/delegates/delegate.cpp index 6f277f6343..6ae5b0ccf0 100644 --- a/lib/usd/hdMaya/delegates/delegate.cpp +++ b/lib/usd/hdMaya/delegates/delegate.cpp @@ -22,11 +22,13 @@ PXR_NAMESPACE_OPEN_SCOPE TF_REGISTRY_FUNCTION(TfType) { TfType::Define(); } HdMayaDelegate::HdMayaDelegate(const InitData& initData) - : _mayaDelegateID(initData.delegateID), - _name(initData.name), - _engine(initData.engine), - _taskController(initData.taskController), - _isHdSt(initData.isHdSt) {} + : _mayaDelegateID(initData.delegateID) + , _name(initData.name) + , _engine(initData.engine) + , _taskController(initData.taskController) + , _isHdSt(initData.isHdSt) +{ +} void HdMayaDelegate::SetParams(const HdMayaParams& params) { _params = params; } diff --git a/lib/usd/hdMaya/delegates/delegate.h b/lib/usd/hdMaya/delegates/delegate.h index 648c4dfff9..e39313ff3d 100644 --- a/lib/usd/hdMaya/delegates/delegate.h +++ b/lib/usd/hdMaya/delegates/delegate.h @@ -16,26 +16,26 @@ #ifndef HDMAYA_DELEGATE_H #define HDMAYA_DELEGATE_H -#include +#include -#include -#include -#include -#include +#include +#include -#include -#include #include #include +#include #include #include #include +#include #include -#include -#include +#include +#include +#include +#include -#include +#include #if WANT_UFE_BUILD #include @@ -43,29 +43,36 @@ PXR_NAMESPACE_OPEN_SCOPE -class HdMayaDelegate { +class HdMayaDelegate +{ public: - struct InitData { + struct InitData + { inline InitData( - TfToken nameIn, HdEngine& engineIn, HdRenderIndex* renderIndexIn, - HdRendererPlugin* rendererPluginIn, - HdxTaskController* taskControllerIn, const SdfPath& delegateIDIn, - bool isHdStIn) - : name(nameIn), - engine(engineIn), - renderIndex(renderIndexIn), - rendererPlugin(rendererPluginIn), - taskController(taskControllerIn), - delegateID(delegateIDIn), - isHdSt(isHdStIn) {} - - TfToken name; - HdEngine& engine; - HdRenderIndex* renderIndex; - HdRendererPlugin* rendererPlugin; + TfToken nameIn, + HdEngine& engineIn, + HdRenderIndex* renderIndexIn, + HdRendererPlugin* rendererPluginIn, + HdxTaskController* taskControllerIn, + const SdfPath& delegateIDIn, + bool isHdStIn) + : name(nameIn) + , engine(engineIn) + , renderIndex(renderIndexIn) + , rendererPlugin(rendererPluginIn) + , taskController(taskControllerIn) + , delegateID(delegateIDIn) + , isHdSt(isHdStIn) + { + } + + TfToken name; + HdEngine& engine; + HdRenderIndex* renderIndex; + HdRendererPlugin* rendererPlugin; HdxTaskController* taskController; - SdfPath delegateID; - bool isHdSt; + SdfPath delegateID; + bool isHdSt; }; HDMAYA_API @@ -74,35 +81,41 @@ class HdMayaDelegate { virtual ~HdMayaDelegate() = default; virtual void Populate() = 0; - virtual void PreFrame(const MHWRender::MDrawContext& context) {} - virtual void PostFrame() {} + virtual void PreFrame(const MHWRender::MDrawContext& context) { } + virtual void PostFrame() { } HDMAYA_API - virtual void SetParams(const HdMayaParams& params); + virtual void SetParams(const HdMayaParams& params); const HdMayaParams& GetParams() { return _params; } const SdfPath& GetMayaDelegateID() { return _mayaDelegateID; } - TfToken GetName() { return _name; } - bool IsHdSt() { return _isHdSt; } + TfToken GetName() { return _name; } + bool IsHdSt() { return _isHdSt; } virtual void PopulateSelectedPaths( - const MSelectionList& mayaSelection, SdfPathVector& selectedSdfPaths, - const HdSelectionSharedPtr& selection) {} + const MSelectionList& mayaSelection, + SdfPathVector& selectedSdfPaths, + const HdSelectionSharedPtr& selection) + { + } #if WANT_UFE_BUILD virtual void PopulateSelectedPaths( - const UFE_NS::Selection& ufeSelection, SdfPathVector& selectedSdfPaths, - const HdSelectionSharedPtr& selection) {} + const UFE_NS::Selection& ufeSelection, + SdfPathVector& selectedSdfPaths, + const HdSelectionSharedPtr& selection) + { + } virtual bool SupportsUfeSelection() { return false; } #endif // WANT_UFE_BUILD #if MAYA_API_VERSION >= 20210000 virtual void PopulateSelectionList( - const HdxPickHitVector& hits, + const HdxPickHitVector& hits, const MHWRender::MSelectionInfo& selectInfo, - MSelectionList& mayaSelection, - MPointArray& worldSpaceHitPts) + MSelectionList& mayaSelection, + MPointArray& worldSpaceHitPts) { } #endif @@ -110,7 +123,7 @@ class HdMayaDelegate { void SetLightsEnabled(const bool enabled) { _lightsEnabled = enabled; } bool GetLightsEnabled() { return _lightsEnabled; } - inline HdEngine& GetEngine() { return _engine; } + inline HdEngine& GetEngine() { return _engine; } inline HdxTaskController* GetTaskController() { return _taskController; } private: @@ -123,12 +136,12 @@ class HdMayaDelegate { // HdMayaALProxyDelegate, for which there are multiple HdSceneDelegates // for each HdMayaDelegate, the _mayaDelegateID is different from each // HdSceneDelegate's id. - const SdfPath _mayaDelegateID; - TfToken _name; - HdEngine& _engine; + const SdfPath _mayaDelegateID; + TfToken _name; + HdEngine& _engine; HdxTaskController* _taskController; - bool _isHdSt = false; - bool _lightsEnabled = true; + bool _isHdSt = false; + bool _lightsEnabled = true; }; using HdMayaDelegatePtr = std::shared_ptr; diff --git a/lib/usd/hdMaya/delegates/delegateCtx.cpp b/lib/usd/hdMaya/delegates/delegateCtx.cpp index 38b1d1984b..b2b595c2c4 100644 --- a/lib/usd/hdMaya/delegates/delegateCtx.cpp +++ b/lib/usd/hdMaya/delegates/delegateCtx.cpp @@ -15,9 +15,7 @@ // #include "delegateCtx.h" -#include - -#include +#include "mayaUsd/utils/util.h" #include #include @@ -26,28 +24,42 @@ #include #include -#include "mayaUsd/utils/util.h" +#include + +#include PXR_NAMESPACE_OPEN_SCOPE namespace { -SdfPath _GetPrimPath(const SdfPath& base, const MDagPath& dg) { +SdfPath _GetPrimPath(const SdfPath& base, const MDagPath& dg) +{ const auto mayaPath = UsdMayaUtil::MDagPathToUsdPath(dg, false, false); - if (mayaPath.IsEmpty()) { return {}; } + if (mayaPath.IsEmpty()) { + return {}; + } const auto* chr = mayaPath.GetText(); - if (chr == nullptr) { return {}; }; + if (chr == nullptr) { + return {}; + }; std::string s(chr + 1); - if (s.empty()) { return {}; } + if (s.empty()) { + return {}; + } return base.AppendPath(SdfPath(s)); } -SdfPath _GetMaterialPath(const SdfPath& base, const MObject& obj) { - MStatus status; +SdfPath _GetMaterialPath(const SdfPath& base, const MObject& obj) +{ + MStatus status; MFnDependencyNode node(obj, &status); - if (!status) { return {}; } + if (!status) { + return {}; + } const auto* chr = node.name().asChar(); - if (chr == nullptr || chr[0] == '\0') { return {}; } + if (chr == nullptr || chr[0] == '\0') { + return {}; + } std::string usdPathStr(chr); // replace namespace ":" with "_" std::replace(usdPathStr.begin(), usdPathStr.end(), ':', '_'); @@ -57,19 +69,20 @@ SdfPath _GetMaterialPath(const SdfPath& base, const MObject& obj) { } // namespace HdMayaDelegateCtx::HdMayaDelegateCtx(const InitData& initData) - : HdSceneDelegate(initData.renderIndex, initData.delegateID), - HdMayaDelegate(initData), - _rprimPath( - initData.delegateID.AppendPath(SdfPath(std::string("rprims")))), - _sprimPath( - initData.delegateID.AppendPath(SdfPath(std::string("sprims")))), - _materialPath( - initData.delegateID.AppendPath(SdfPath(std::string("materials")))) { + : HdSceneDelegate(initData.renderIndex, initData.delegateID) + , HdMayaDelegate(initData) + , _rprimPath(initData.delegateID.AppendPath(SdfPath(std::string("rprims")))) + , _sprimPath(initData.delegateID.AppendPath(SdfPath(std::string("sprims")))) + , _materialPath(initData.delegateID.AppendPath(SdfPath(std::string("materials")))) +{ GetChangeTracker().AddCollection(TfToken("visible")); } void HdMayaDelegateCtx::InsertRprim( - const TfToken& typeId, const SdfPath& id, const SdfPath& instancerId) { + const TfToken& typeId, + const SdfPath& id, + const SdfPath& instancerId) +{ if (!instancerId.IsEmpty()) { GetRenderIndex().InsertInstancer(this, instancerId); GetChangeTracker().InstancerInserted(id); @@ -78,24 +91,25 @@ void HdMayaDelegateCtx::InsertRprim( } void HdMayaDelegateCtx::InsertSprim( - const TfToken& typeId, const SdfPath& id, HdDirtyBits initialBits) { + const TfToken& typeId, + const SdfPath& id, + HdDirtyBits initialBits) +{ GetRenderIndex().InsertSprim(typeId, this, id); GetChangeTracker().SprimInserted(id, initialBits); } -void HdMayaDelegateCtx::RemoveRprim(const SdfPath& id) { - GetRenderIndex().RemoveRprim(id); -} +void HdMayaDelegateCtx::RemoveRprim(const SdfPath& id) { GetRenderIndex().RemoveRprim(id); } -void HdMayaDelegateCtx::RemoveSprim(const TfToken& typeId, const SdfPath& id) { +void HdMayaDelegateCtx::RemoveSprim(const TfToken& typeId, const SdfPath& id) +{ GetRenderIndex().RemoveSprim(typeId, id); } -void HdMayaDelegateCtx::RemoveInstancer(const SdfPath& id) { - GetRenderIndex().RemoveInstancer(id); -} +void HdMayaDelegateCtx::RemoveInstancer(const SdfPath& id) { GetRenderIndex().RemoveInstancer(id); } -SdfPath HdMayaDelegateCtx::GetPrimPath(const MDagPath& dg, bool isLight) { +SdfPath HdMayaDelegateCtx::GetPrimPath(const MDagPath& dg, bool isLight) +{ if (isLight) { return _GetPrimPath(_sprimPath, dg); } else { @@ -103,7 +117,8 @@ SdfPath HdMayaDelegateCtx::GetPrimPath(const MDagPath& dg, bool isLight) { } } -SdfPath HdMayaDelegateCtx::GetMaterialPath(const MObject& obj) { +SdfPath HdMayaDelegateCtx::GetMaterialPath(const MObject& obj) +{ return _GetMaterialPath(_materialPath, obj); } diff --git a/lib/usd/hdMaya/delegates/delegateCtx.h b/lib/usd/hdMaya/delegates/delegateCtx.h index c131330c42..00bb90eae4 100644 --- a/lib/usd/hdMaya/delegates/delegateCtx.h +++ b/lib/usd/hdMaya/delegates/delegateCtx.h @@ -16,54 +16,53 @@ #ifndef HDMAYA_DELEGATE_BASE_H #define HDMAYA_DELEGATE_BASE_H -#include +#include -#include #include #include +#include #include -#include +#include PXR_NAMESPACE_OPEN_SCOPE -class HdMayaDelegateCtx : public HdSceneDelegate, public HdMayaDelegate { +class HdMayaDelegateCtx + : public HdSceneDelegate + , public HdMayaDelegate +{ protected: HDMAYA_API HdMayaDelegateCtx(const InitData& initData); public: - enum RebuildFlags : uint32_t { + enum RebuildFlags : uint32_t + { RebuildFlagPrim = 1 << 1, RebuildFlagCallbacks = 1 << 2, }; using HdSceneDelegate::GetRenderIndex; - HdChangeTracker& GetChangeTracker() { - return GetRenderIndex().GetChangeTracker(); - } + HdChangeTracker& GetChangeTracker() { return GetRenderIndex().GetChangeTracker(); } HDMAYA_API - void InsertRprim( - const TfToken& typeId, const SdfPath& id, - const SdfPath& instancerId = {}); + void InsertRprim(const TfToken& typeId, const SdfPath& id, const SdfPath& instancerId = {}); HDMAYA_API - void InsertSprim( - const TfToken& typeId, const SdfPath& id, HdDirtyBits initialBits); + void InsertSprim(const TfToken& typeId, const SdfPath& id, HdDirtyBits initialBits); HDMAYA_API void RemoveRprim(const SdfPath& id); HDMAYA_API void RemoveSprim(const TfToken& typeId, const SdfPath& id); HDMAYA_API - void RemoveInstancer(const SdfPath& id); - virtual void RemoveAdapter(const SdfPath& id) {} - virtual void RecreateAdapter(const SdfPath& id, const MObject& obj) {} - virtual void RecreateAdapterOnIdle(const SdfPath& id, const MObject& obj) {} - virtual void RebuildAdapterOnIdle(const SdfPath& id, uint32_t flags) {} + void RemoveInstancer(const SdfPath& id); + virtual void RemoveAdapter(const SdfPath& id) { } + virtual void RecreateAdapter(const SdfPath& id, const MObject& obj) { } + virtual void RecreateAdapterOnIdle(const SdfPath& id, const MObject& obj) { } + virtual void RebuildAdapterOnIdle(const SdfPath& id, uint32_t flags) { } /// \brief Notifies the scene delegate when a material tag changes. /// /// \param id Id of the Material that changed its tag. - virtual void MaterialTagChanged(const SdfPath& id) {} + virtual void MaterialTagChanged(const SdfPath& id) { } HDMAYA_API SdfPath GetPrimPath(const MDagPath& dg, bool isLight); HDMAYA_API diff --git a/lib/usd/hdMaya/delegates/delegateDebugCodes.cpp b/lib/usd/hdMaya/delegates/delegateDebugCodes.cpp index 8a9ad4f74c..be9ce9359f 100644 --- a/lib/usd/hdMaya/delegates/delegateDebugCodes.cpp +++ b/lib/usd/hdMaya/delegates/delegateDebugCodes.cpp @@ -19,10 +19,10 @@ PXR_NAMESPACE_OPEN_SCOPE -TF_REGISTRY_FUNCTION(TfDebug) { +TF_REGISTRY_FUNCTION(TfDebug) +{ TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_DELEGATE_GET, - "Print information about 'Get' calls to the delegates."); + HDMAYA_DELEGATE_GET, "Print information about 'Get' calls to the delegates."); TF_DEBUG_ENVIRONMENT_SYMBOL( HDMAYA_DELEGATE_GET_CULL_STYLE, @@ -41,8 +41,7 @@ TF_REGISTRY_FUNCTION(TfDebug) { "Print information about 'GetDoubleSided' calls to the delegates."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_DELEGATE_GET_EXTENT, - "Print information about 'GetExtent' calls to the delegates."); + HDMAYA_DELEGATE_GET_EXTENT, "Print information about 'GetExtent' calls to the delegates."); TF_DEBUG_ENVIRONMENT_SYMBOL( HDMAYA_DELEGATE_GET_INSTANCE_INDICES, @@ -96,20 +95,17 @@ TF_REGISTRY_FUNCTION(TfDebug) { "Print information about 'GetVisible' calls to the delegates."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_DELEGATE_INSERTDAG, - "Print information about 'InsertDag' calls to the delegates."); + HDMAYA_DELEGATE_INSERTDAG, "Print information about 'InsertDag' calls to the delegates."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_DELEGATE_IS_ENABLED, - "Print information about 'IsEnabled' calls to the delegates."); + HDMAYA_DELEGATE_IS_ENABLED, "Print information about 'IsEnabled' calls to the delegates."); TF_DEBUG_ENVIRONMENT_SYMBOL( HDMAYA_DELEGATE_RECREATE_ADAPTER, "Print information when the delegate recreates adapters."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_DELEGATE_REGISTRY, - "Print information about registration of HdMayaDelegates."); + HDMAYA_DELEGATE_REGISTRY, "Print information about registration of HdMayaDelegates."); TF_DEBUG_ENVIRONMENT_SYMBOL( HDMAYA_DELEGATE_SAMPLE_PRIMVAR, @@ -120,8 +116,7 @@ TF_REGISTRY_FUNCTION(TfDebug) { "Print information about 'SampleTransform' calls to the delegates."); TF_DEBUG_ENVIRONMENT_SYMBOL( - HDMAYA_DELEGATE_SELECTION, - "Print information about hdMaya delegate selection."); + HDMAYA_DELEGATE_SELECTION, "Print information about hdMaya delegate selection."); #if USD_VERSION_NUM <= 1911 diff --git a/lib/usd/hdMaya/delegates/delegateDebugCodes.h b/lib/usd/hdMaya/delegates/delegateDebugCodes.h index ee40dd9176..84bf766c69 100644 --- a/lib/usd/hdMaya/delegates/delegateDebugCodes.h +++ b/lib/usd/hdMaya/delegates/delegateDebugCodes.h @@ -16,8 +16,8 @@ #ifndef HDMAYA_DELEGATE_DEBUG_CODES_H #define HDMAYA_DELEGATE_DEBUG_CODES_H -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -65,7 +65,6 @@ TF_DEBUG_CODES( // clang-format on #endif // USD_VERSION_NUM <= 1911 - PXR_NAMESPACE_CLOSE_SCOPE #endif // HDMAYA_DELEGATE_DEBUG_CODES_H diff --git a/lib/usd/hdMaya/delegates/delegateRegistry.cpp b/lib/usd/hdMaya/delegates/delegateRegistry.cpp index 7c2a122b55..09f8332df6 100644 --- a/lib/usd/hdMaya/delegates/delegateRegistry.cpp +++ b/lib/usd/hdMaya/delegates/delegateRegistry.cpp @@ -15,21 +15,21 @@ // #include "delegateRegistry.h" -#include +#include #include #include #include #include -#include +#include PXR_NAMESPACE_OPEN_SCOPE TF_INSTANTIATE_SINGLETON(HdMayaDelegateRegistry); -void HdMayaDelegateRegistry::RegisterDelegate( - const TfToken& name, DelegateCreator creator) { +void HdMayaDelegateRegistry::RegisterDelegate(const TfToken& name, DelegateCreator creator) +{ auto& instance = GetInstance(); for (auto it : instance._delegates) { if (name == std::get<0>(it)) { @@ -43,48 +43,55 @@ void HdMayaDelegateRegistry::RegisterDelegate( } TF_DEBUG(HDMAYA_DELEGATE_REGISTRY) - .Msg( - "HdMayaDelegateRegistry::RegisterDelegate(%s) - new delegate\n", - name.GetText()); + .Msg("HdMayaDelegateRegistry::RegisterDelegate(%s) - new delegate\n", name.GetText()); instance._delegates.emplace_back(name, creator); } -std::vector HdMayaDelegateRegistry::GetDelegateNames() { +std::vector HdMayaDelegateRegistry::GetDelegateNames() +{ LoadAllDelegates(); - const auto& instance = GetInstance(); + const auto& instance = GetInstance(); std::vector ret; ret.reserve(instance._delegates.size()); - for (auto it : instance._delegates) { ret.push_back(std::get<0>(it)); } + for (auto it : instance._delegates) { + ret.push_back(std::get<0>(it)); + } return ret; } -std::vector -HdMayaDelegateRegistry::GetDelegateCreators() { +std::vector HdMayaDelegateRegistry::GetDelegateCreators() +{ LoadAllDelegates(); - const auto& instance = GetInstance(); + const auto& instance = GetInstance(); std::vector ret; ret.reserve(instance._delegates.size()); - for (auto it : instance._delegates) { ret.push_back(std::get<1>(it)); } + for (auto it : instance._delegates) { + ret.push_back(std::get<1>(it)); + } return ret; } -void HdMayaDelegateRegistry::SignalDelegatesChanged() { - for (const auto& s : GetInstance()._signals) { s(); } +void HdMayaDelegateRegistry::SignalDelegatesChanged() +{ + for (const auto& s : GetInstance()._signals) { + s(); + } } -void HdMayaDelegateRegistry::LoadAllDelegates() { +void HdMayaDelegateRegistry::LoadAllDelegates() +{ static std::once_flag loadAllOnce; std::call_once(loadAllOnce, _LoadAllDelegates); } -void HdMayaDelegateRegistry::InstallDelegatesChangedSignal( - DelegatesChangedSignal signal) { +void HdMayaDelegateRegistry::InstallDelegatesChangedSignal(DelegatesChangedSignal signal) +{ GetInstance()._signals.emplace_back(signal); } -void HdMayaDelegateRegistry::_LoadAllDelegates() { - TF_DEBUG(HDMAYA_DELEGATE_REGISTRY) - .Msg("HdMayaDelegateRegistry::_LoadAllDelegates()\n"); +void HdMayaDelegateRegistry::_LoadAllDelegates() +{ + TF_DEBUG(HDMAYA_DELEGATE_REGISTRY).Msg("HdMayaDelegateRegistry::_LoadAllDelegates()\n"); TfRegistryManager::GetInstance().SubscribeTo(); @@ -102,9 +109,7 @@ void HdMayaDelegateRegistry::_LoadAllDelegates() { for (auto& subType : delegateTypes) { const PlugPluginPtr pluginForType = plugReg.GetPluginForType(subType); if (!pluginForType) { - TF_CODING_ERROR( - "Could not find plugin for '%s'", - subType.GetTypeName().c_str()); + TF_CODING_ERROR("Could not find plugin for '%s'", subType.GetTypeName().c_str()); return; } pluginForType->Load(); diff --git a/lib/usd/hdMaya/delegates/delegateRegistry.h b/lib/usd/hdMaya/delegates/delegateRegistry.h index cb40f23b25..b4ee0f75fc 100644 --- a/lib/usd/hdMaya/delegates/delegateRegistry.h +++ b/lib/usd/hdMaya/delegates/delegateRegistry.h @@ -16,18 +16,19 @@ #ifndef HDMAYA_DELEGATE_REGISTRY_H #define HDMAYA_DELEGATE_REGISTRY_H -#include -#include +#include -#include #include +#include #include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE -class HdMayaDelegateRegistry : public TfSingleton { +class HdMayaDelegateRegistry : public TfSingleton +{ friend class TfSingleton; HDMAYA_API HdMayaDelegateRegistry() = default; @@ -35,8 +36,7 @@ class HdMayaDelegateRegistry : public TfSingleton { public: // function creates and returns a pointer to a HdMayaDelegate - may return // a nullptr indicate failure, or that the delegate is currently disabled - using DelegateCreator = - std::function; + using DelegateCreator = std::function; HDMAYA_API static void RegisterDelegate(const TfToken& name, DelegateCreator creator); @@ -65,7 +65,7 @@ class HdMayaDelegateRegistry : public TfSingleton { static void _LoadAllDelegates(); std::vector> _delegates; - std::vector _signals; + std::vector _signals; }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/hdMaya/delegates/params.h b/lib/usd/hdMaya/delegates/params.h index dba6a58db7..2d6891038d 100644 --- a/lib/usd/hdMaya/delegates/params.h +++ b/lib/usd/hdMaya/delegates/params.h @@ -22,9 +22,10 @@ PXR_NAMESPACE_OPEN_SCOPE -struct HdMayaParams { - int textureMemoryPerTexture = 4 * 1024 * 1024; - int maximumShadowMapResolution = 2048; +struct HdMayaParams +{ + int textureMemoryPerTexture = 4 * 1024 * 1024; + int maximumShadowMapResolution = 2048; bool displaySmoothMeshes = true; bool enableMotionSamples = false; }; diff --git a/lib/usd/hdMaya/delegates/proxyDelegate.cpp b/lib/usd/hdMaya/delegates/proxyDelegate.cpp index eb82d1dbdb..2feb104626 100644 --- a/lib/usd/hdMaya/delegates/proxyDelegate.cpp +++ b/lib/usd/hdMaya/delegates/proxyDelegate.cpp @@ -15,9 +15,13 @@ // #include "proxyDelegate.h" -#include -#include -#include +#include +#include +#include +#include + +#include +#include #include #include @@ -28,13 +32,9 @@ #include #include -#include -#include - -#include -#include -#include -#include +#include +#include +#include #if WANT_UFE_BUILD #include @@ -47,15 +47,15 @@ PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PRIVATE_TOKENS(_tokens, (HdMayaProxyDelegate)); -TF_REGISTRY_FUNCTION(TfType) { - TF_DEBUG(HDMAYA_AL_PLUGIN) - .Msg("Calling TfType::Define for HdMayaProxyDelegate\n"); - TfType::Define >(); +TF_REGISTRY_FUNCTION(TfType) +{ + TF_DEBUG(HDMAYA_AL_PLUGIN).Msg("Calling TfType::Define for HdMayaProxyDelegate\n"); + TfType::Define>(); } -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaDelegateRegistry, HdMayaProxyDelegate) { - TF_DEBUG(HDMAYA_AL_PLUGIN) - .Msg("Calling RegisterDelegate for HdMayaProxyDelegate\n"); +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaDelegateRegistry, HdMayaProxyDelegate) +{ + TF_DEBUG(HDMAYA_AL_PLUGIN).Msg("Calling RegisterDelegate for HdMayaProxyDelegate\n"); HdMayaDelegateRegistry::RegisterDelegate( _tokens->HdMayaProxyDelegate, HdMayaProxyDelegate::Creator); } @@ -63,7 +63,7 @@ TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaDelegateRegistry, HdMayaProxyDelegate) { namespace { #if WANT_UFE_BUILD -constexpr auto USD_UFE_RUNTIME_NAME = "USD"; +constexpr auto USD_UFE_RUNTIME_NAME = "USD"; static UFE_NS::Rtid usdUfeRtid = 0; #endif // WANT_UFE_BUILD @@ -74,16 +74,18 @@ std::atomic isALPluginLoaded(false); // Not sure if we actually need a mutex guarding _allAdapters, but // I'd rather be safe.... -std::mutex _allAdaptersMutex; +std::mutex _allAdaptersMutex; std::unordered_set _allAdapters; -bool IsALPluginLoaded() { +bool IsALPluginLoaded() +{ auto nodeClass = MNodeClass(MayaUsdProxyShapeBase::typeId); // if not loaded yet, typeName() will be an empty string return nodeClass.typeName() == MayaUsdProxyShapeBase::typeName; } -void PluginCallback(const MStringArray& strs, void* clientData) { +void PluginCallback(const MStringArray& strs, void* clientData) +{ // Considered having separate plugin loaded/unloaded callbacks, but that // would mean checking for the plugin "name", which seems somewhat // unreliable - it's just the name of the built library, which seems too @@ -112,21 +114,20 @@ void PluginCallback(const MStringArray& strs, void* clientData) { } } -void SetupPluginCallbacks() { +void SetupPluginCallbacks() +{ MStatus status; isALPluginLoaded.store(IsALPluginLoaded()); // Set up callback to notify of plugin load - TF_DEBUG(HDMAYA_AL_CALLBACKS) - .Msg("HdMayaProxyDelegate - creating PluginLoaded callback\n"); + TF_DEBUG(HDMAYA_AL_CALLBACKS).Msg("HdMayaProxyDelegate - creating PluginLoaded callback\n"); MSceneMessage::addStringArrayCallback( MSceneMessage::kAfterPluginLoad, PluginCallback, nullptr, &status); TF_VERIFY(status, "Could not set pluginLoaded callback"); // Set up callback to notify of plugin unload - TF_DEBUG(HDMAYA_AL_CALLBACKS) - .Msg("HdMayaProxyDelegate - creating PluginUnloaded callback\n"); + TF_DEBUG(HDMAYA_AL_CALLBACKS).Msg("HdMayaProxyDelegate - creating PluginUnloaded callback\n"); MSceneMessage::addStringArrayCallback( MSceneMessage::kAfterPluginUnload, PluginCallback, nullptr, &status); TF_VERIFY(status, "Could not set pluginUnloaded callback"); @@ -162,19 +163,17 @@ MGlobal::ListAdjustment GetListAdjustment() } // namespace HdMayaProxyDelegate::HdMayaProxyDelegate(const InitData& initData) - : HdMayaDelegate(initData) { + : HdMayaDelegate(initData) +{ TF_DEBUG(HDMAYA_AL_PROXY_DELEGATE) - .Msg( - "HdMayaProxyDelegate - creating with delegateID %s\n", - GetMayaDelegateID().GetText()); + .Msg("HdMayaProxyDelegate - creating with delegateID %s\n", GetMayaDelegateID().GetText()); MStatus status; #if WANT_UFE_BUILD if (usdUfeRtid == 0) { try { - usdUfeRtid = - UFE_NS::RunTimeMgr::instance().getId(USD_UFE_RUNTIME_NAME); + usdUfeRtid = UFE_NS::RunTimeMgr::instance().getId(USD_UFE_RUNTIME_NAME); } // This shoudl catch ufe's InvalidRunTimeName exception, but they don't // expose that! @@ -185,49 +184,60 @@ HdMayaProxyDelegate::HdMayaProxyDelegate(const InitData& initData) #endif // WANT_UFE_BUILD } -HdMayaProxyDelegate::~HdMayaProxyDelegate() { +HdMayaProxyDelegate::~HdMayaProxyDelegate() +{ TF_DEBUG(HDMAYA_AL_PROXY_DELEGATE) .Msg( - "HdMayaProxyDelegate - destroying with delegateID %s\n", - GetMayaDelegateID().GetText()); + "HdMayaProxyDelegate - destroying with delegateID %s\n", GetMayaDelegateID().GetText()); } -HdMayaDelegatePtr HdMayaProxyDelegate::Creator(const InitData& initData) { +HdMayaDelegatePtr HdMayaProxyDelegate::Creator(const InitData& initData) +{ static std::once_flag setupPluginCallbacksOnce; std::call_once(setupPluginCallbacksOnce, SetupPluginCallbacks); - if (!isALPluginLoaded.load()) { return nullptr; } + if (!isALPluginLoaded.load()) { + return nullptr; + } return std::static_pointer_cast( std::make_shared(initData)); } -void HdMayaProxyDelegate::AddAdapter(HdMayaProxyAdapter* adapter) { +void HdMayaProxyDelegate::AddAdapter(HdMayaProxyAdapter* adapter) +{ std::lock_guard lock(_allAdaptersMutex); _allAdapters.insert(adapter); } -void HdMayaProxyDelegate::RemoveAdapter(HdMayaProxyAdapter* adapter) { +void HdMayaProxyDelegate::RemoveAdapter(HdMayaProxyAdapter* adapter) +{ std::lock_guard lock(_allAdaptersMutex); _allAdapters.erase(adapter); } -void HdMayaProxyDelegate::Populate() { +void HdMayaProxyDelegate::Populate() +{ // Does nothing - delegate exists only for PreFrame and // PopulateSelectedPaths } -void HdMayaProxyDelegate::PreFrame(const MHWRender::MDrawContext& context) { +void HdMayaProxyDelegate::PreFrame(const MHWRender::MDrawContext& context) +{ std::lock_guard lock(_allAdaptersMutex); - for (auto adapter : _allAdapters) { adapter->PreFrame(context); } + for (auto adapter : _allAdapters) { + adapter->PreFrame(context); + } } #if WANT_UFE_BUILD void HdMayaProxyDelegate::PopulateSelectedPaths( - const UFE_NS::Selection& ufeSelection, SdfPathVector& selectedSdfPaths, - const HdSelectionSharedPtr& selection) { - MStatus status; - MObject proxyMObj; + const UFE_NS::Selection& ufeSelection, + SdfPathVector& selectedSdfPaths, + const HdSelectionSharedPtr& selection) +{ + MStatus status; + MObject proxyMObj; MFnDagNode proxyMFnDag; TF_DEBUG(HDMAYA_AL_SELECTION) @@ -248,7 +258,7 @@ void HdMayaProxyDelegate::PopulateSelectedPaths( std::lock_guard lock(_allAdaptersMutex); for (auto adapter : _allAdapters) { // First, we check to see if the entire proxy shape is selected - bool wholeProxySelected = false; + bool wholeProxySelected = false; const MDagPath& dagPath = adapter->GetDagPath(); // Loop over all parents MDagPath parentDag = dagPath; @@ -258,9 +268,7 @@ void HdMayaProxyDelegate::PopulateSelectedPaths( // PopulateSelectedPaths will handle this case. we can // skip this shape... TF_DEBUG(HDMAYA_AL_SELECTION) - .Msg( - "proxy node %s was selected\n", - parentDag.fullPathName().asChar()); + .Msg("proxy node %s was selected\n", parentDag.fullPathName().asChar()); wholeProxySelected = true; break; } @@ -272,25 +280,27 @@ void HdMayaProxyDelegate::PopulateSelectedPaths( "HdMayaProxyDelegate::PopulateSelectedPaths - adding " "proxy to lookup: %s\n", dagPath.fullPathName().asChar()); - proxyPathToAdapter.emplace( - dagPath.fullPathName().asChar(), adapter); + proxyPathToAdapter.emplace(dagPath.fullPathName().asChar(), adapter); } } } for (auto item : ufeSelection) { - if (item->runTimeId() != usdUfeRtid) { continue; } + if (item->runTimeId() != usdUfeRtid) { + continue; + } auto& pathSegments = item->path().getSegments(); if (pathSegments.size() != 2) { TF_WARN( "Found invalid usd-ufe path (had %lu segments - should have " "2): %s\n", - item->path().size(), item->path().string().c_str()); + item->path().size(), + item->path().string().c_str()); continue; } // We popHead for maya pathSegment because it always starts with // "|world", which makes it non-standard... - auto mayaPathSegment = pathSegments[0].popHead(); + auto mayaPathSegment = pathSegments[0].popHead(); auto& usdPathSegment = pathSegments[1]; auto findResult = proxyPathToAdapter.find(mayaPathSegment.string()); @@ -301,14 +311,19 @@ void HdMayaProxyDelegate::PopulateSelectedPaths( "proxy: %s\n", mayaPathSegment.string().c_str()); - if (findResult == proxyPathToAdapter.cend()) { continue; } + if (findResult == proxyPathToAdapter.cend()) { + continue; + } auto proxyAdapter = findResult->second; const SdfPath usdPath(usdPathSegment.string()); selectedSdfPaths.push_back(proxyAdapter->ConvertCachePathToIndexPath(usdPath)); - proxyAdapter->PopulateSelection(HdSelection::HighlightModeSelect, - usdPath, UsdImagingDelegate::ALL_INSTANCES, selection); + proxyAdapter->PopulateSelection( + HdSelection::HighlightModeSelect, + usdPath, + UsdImagingDelegate::ALL_INSTANCES, + selection); TF_DEBUG(HDMAYA_AL_SELECTION) .Msg( "HdMayaProxyDelegate::PopulateSelectedPaths - selecting %s\n", @@ -358,7 +373,7 @@ void HdMayaProxyDelegate::PopulateSelectionList( for (const HdxPickHit& hit : hits) { const SdfPath& objectId = hit.objectId; - const int instanceIndex = hit.instanceIndex; + const int instanceIndex = hit.instanceIndex; for (auto adapter : _allAdapters) { const SdfPath& delegateId = adapter->GetUsdDelegateID(); @@ -382,8 +397,8 @@ void HdMayaProxyDelegate::PopulateSelectionList( const Ufe::PathSegment pathSegment( usdPath.GetText(), USD_UFE_RUNTIME_ID, USD_UFE_SEPARATOR); - const Ufe::SceneItem::Ptr& si = - handler->createItem(adapter->GetProxy()->ufePath() + pathSegment); + const Ufe::SceneItem::Ptr& si + = handler->createItem(adapter->GetProxy()->ufePath() + pathSegment); if (!si) { TF_WARN("Failed to create UFE scene item for '%s'", objectId.GetText()); break; @@ -399,20 +414,14 @@ void HdMayaProxyDelegate::PopulateSelectionList( // selection list would clear Maya selection list. globalSelection->append(si); break; - case MGlobal::kAddToList: - globalSelection->append(si); - break; - case MGlobal::kRemoveFromList: - globalSelection->remove(si); - break; + case MGlobal::kAddToList: globalSelection->append(si); break; + case MGlobal::kRemoveFromList: globalSelection->remove(si); break; case MGlobal::kXORWithList: if (!globalSelection->remove(si)) { globalSelection->append(si); } break; - default: - TF_WARN("Unexpected MGlobal::ListAdjustment enum for selection."); - break; + default: TF_WARN("Unexpected MGlobal::ListAdjustment enum for selection."); break; } break; diff --git a/lib/usd/hdMaya/delegates/proxyDelegate.h b/lib/usd/hdMaya/delegates/proxyDelegate.h index 3b92e74234..a5356c7d19 100644 --- a/lib/usd/hdMaya/delegates/proxyDelegate.h +++ b/lib/usd/hdMaya/delegates/proxyDelegate.h @@ -16,17 +16,17 @@ #ifndef HDMAYA_AL_PROXY_DELEGATE_H #define HDMAYA_AL_PROXY_DELEGATE_H -#include - -#include +#include -#include #include +#include #include #include #include -#include +#include + +#include #if WANT_UFE_BUILD #include @@ -37,7 +37,8 @@ PXR_NAMESPACE_OPEN_SCOPE class HdMayaProxyAdapter; class MayaUsdProxyShapeBase; -class HdMayaProxyDelegate : public HdMayaDelegate { +class HdMayaProxyDelegate : public HdMayaDelegate +{ public: HdMayaProxyDelegate(const InitData& initData); @@ -53,23 +54,24 @@ class HdMayaProxyDelegate : public HdMayaDelegate { // TODO: implement this override this to add selection support // for non-ufe -// void PopulateSelectedPaths( -// const MSelectionList& mayaSelection, SdfPathVector& selectedSdfPaths, -// const HdSelectionSharedPtr& selection) override; + // void PopulateSelectedPaths( + // const MSelectionList& mayaSelection, SdfPathVector& selectedSdfPaths, + // const HdSelectionSharedPtr& selection) override; #if WANT_UFE_BUILD void PopulateSelectedPaths( - const UFE_NS::Selection& ufeSelection, SdfPathVector& selectedSdfPaths, + const UFE_NS::Selection& ufeSelection, + SdfPathVector& selectedSdfPaths, const HdSelectionSharedPtr& selection) override; bool SupportsUfeSelection() override; #endif // WANT_UFE_BUILD #if MAYA_API_VERSION >= 20210000 void PopulateSelectionList( - const HdxPickHitVector& hits, + const HdxPickHitVector& hits, const MHWRender::MSelectionInfo& selectInfo, - MSelectionList& selectionList, - MPointArray& worldSpaceHitPts) override; + MSelectionList& selectionList, + MPointArray& worldSpaceHitPts) override; #endif }; diff --git a/lib/usd/hdMaya/delegates/proxyUsdImagingDelegate.cpp b/lib/usd/hdMaya/delegates/proxyUsdImagingDelegate.cpp index 8776a04d34..e3a3039964 100644 --- a/lib/usd/hdMaya/delegates/proxyUsdImagingDelegate.cpp +++ b/lib/usd/hdMaya/delegates/proxyUsdImagingDelegate.cpp @@ -15,42 +15,53 @@ // #include "proxyUsdImagingDelegate.h" -#include - #include +#include + PXR_NAMESPACE_OPEN_SCOPE HdMayaProxyUsdImagingDelegate::HdMayaProxyUsdImagingDelegate( - HdRenderIndex* parentIndex, SdfPath const& delegateID, - MayaUsdProxyShapeBase* proxy, const MDagPath& dagPath) - : UsdImagingDelegate(parentIndex, delegateID), - _dagPath(dagPath), - _proxy(proxy) { + HdRenderIndex* parentIndex, + SdfPath const& delegateID, + MayaUsdProxyShapeBase* proxy, + const MDagPath& dagPath) + : UsdImagingDelegate(parentIndex, delegateID) + , _dagPath(dagPath) + , _proxy(proxy) +{ // TODO Auto-generated constructor stub } -HdMayaProxyUsdImagingDelegate::~HdMayaProxyUsdImagingDelegate() { +HdMayaProxyUsdImagingDelegate::~HdMayaProxyUsdImagingDelegate() +{ // TODO Auto-generated destructor stub } -GfMatrix4d HdMayaProxyUsdImagingDelegate::GetTransform(SdfPath const& id) { - if (_rootTransformDirty) { UpdateRootTransform(); } +GfMatrix4d HdMayaProxyUsdImagingDelegate::GetTransform(SdfPath const& id) +{ + if (_rootTransformDirty) { + UpdateRootTransform(); + } return UsdImagingDelegate::GetTransform(id); } -bool HdMayaProxyUsdImagingDelegate::GetVisible(SdfPath const& id) { - if (_rootVisibilityDirty) { UpdateRootVisibility(); } +bool HdMayaProxyUsdImagingDelegate::GetVisible(SdfPath const& id) +{ + if (_rootVisibilityDirty) { + UpdateRootVisibility(); + } return UsdImagingDelegate::GetVisible(id); } -void HdMayaProxyUsdImagingDelegate::UpdateRootTransform() { - SetRootTransform( - GfMatrix4d(_proxy->parentTransform().inclusiveMatrix().matrix)); +void HdMayaProxyUsdImagingDelegate::UpdateRootTransform() +{ + SetRootTransform(GfMatrix4d(_proxy->parentTransform().inclusiveMatrix().matrix)); _rootTransformDirty = false; } -void HdMayaProxyUsdImagingDelegate::UpdateRootVisibility() { +void HdMayaProxyUsdImagingDelegate::UpdateRootVisibility() +{ SetRootVisibility(_dagPath.isVisible()); _rootVisibilityDirty = false; } diff --git a/lib/usd/hdMaya/delegates/proxyUsdImagingDelegate.h b/lib/usd/hdMaya/delegates/proxyUsdImagingDelegate.h index 2682794c89..5d96c50084 100644 --- a/lib/usd/hdMaya/delegates/proxyUsdImagingDelegate.h +++ b/lib/usd/hdMaya/delegates/proxyUsdImagingDelegate.h @@ -16,19 +16,22 @@ #ifndef HDMAYA_AL_PROXY_USDIMAGING_DELEGATE_H #define HDMAYA_AL_PROXY_USDIMAGING_DELEGATE_H -#include - #include +#include + PXR_NAMESPACE_OPEN_SCOPE class MayaUsdProxyShapeBase; -class HdMayaProxyUsdImagingDelegate : public UsdImagingDelegate { +class HdMayaProxyUsdImagingDelegate : public UsdImagingDelegate +{ public: HdMayaProxyUsdImagingDelegate( - HdRenderIndex* parentIndex, SdfPath const& delegateID, - MayaUsdProxyShapeBase* proxy, const MDagPath& dagPath); + HdRenderIndex* parentIndex, + SdfPath const& delegateID, + MayaUsdProxyShapeBase* proxy, + const MDagPath& dagPath); virtual ~HdMayaProxyUsdImagingDelegate(); // We override this just because it's point that we can @@ -59,10 +62,10 @@ class HdMayaProxyUsdImagingDelegate : public UsdImagingDelegate { void UpdateRootVisibility(); private: - const MDagPath& _dagPath; - MayaUsdProxyShapeBase* _proxy{ nullptr }; - bool _rootTransformDirty{ false }; - bool _rootVisibilityDirty{ false }; + const MDagPath& _dagPath; + MayaUsdProxyShapeBase* _proxy { nullptr }; + bool _rootTransformDirty { false }; + bool _rootVisibilityDirty { false }; }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/hdMaya/delegates/sceneDelegate.cpp b/lib/usd/hdMaya/delegates/sceneDelegate.cpp index 91dfa8d87e..83dca2ee64 100644 --- a/lib/usd/hdMaya/delegates/sceneDelegate.cpp +++ b/lib/usd/hdMaya/delegates/sceneDelegate.cpp @@ -15,13 +15,11 @@ // #include "sceneDelegate.h" -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include @@ -38,17 +36,20 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE namespace { -void _nodeAdded(MObject& obj, void* clientData) { +void _nodeAdded(MObject& obj, void* clientData) +{ // In case of creating new instances, the instance below the // dag will be empty and not initialized properly. auto* delegate = reinterpret_cast(clientData); @@ -57,38 +58,48 @@ void _nodeAdded(MObject& obj, void* clientData) { const MString defaultLightSet("defaultLightSet"); -void _connectionChanged( - MPlug& srcPlug, MPlug& destPlug, bool made, void* clientData) { +void _connectionChanged(MPlug& srcPlug, MPlug& destPlug, bool made, void* clientData) +{ TF_UNUSED(made); const auto srcObj = srcPlug.node(); - if (!srcObj.hasFn(MFn::kTransform)) { return; } + if (!srcObj.hasFn(MFn::kTransform)) { + return; + } const auto destObj = destPlug.node(); - if (!destObj.hasFn(MFn::kSet)) { return; } - if (srcPlug != MayaAttrs::dagNode::instObjGroups) { return; } - MStatus status; + if (!destObj.hasFn(MFn::kSet)) { + return; + } + if (srcPlug != MayaAttrs::dagNode::instObjGroups) { + return; + } + MStatus status; MFnDependencyNode destNode(destObj, &status); - if (ARCH_UNLIKELY(!status)) { return; } - if (destNode.name() != defaultLightSet) { return; } - auto* delegate = reinterpret_cast(clientData); + if (ARCH_UNLIKELY(!status)) { + return; + } + if (destNode.name() != defaultLightSet) { + return; + } + auto* delegate = reinterpret_cast(clientData); MDagPath dag; status = MDagPath::getAPathTo(srcObj, dag); - if (ARCH_UNLIKELY(!status)) { return; } + if (ARCH_UNLIKELY(!status)) { + return; + } unsigned int shapesBelow = 0; dag.numberOfShapesDirectlyBelow(shapesBelow); - for (auto i = decltype(shapesBelow){0}; i < shapesBelow; ++i) { + for (auto i = decltype(shapesBelow) { 0 }; i < shapesBelow; ++i) { auto dagCopy = dag; dagCopy.extendToShapeDirectlyBelow(i); delegate->UpdateLightVisibility(dagCopy); } } -template -inline bool _FindAdapter(const SdfPath&, F) { - return false; -} +template inline bool _FindAdapter(const SdfPath&, F) { return false; } template -inline bool _FindAdapter(const SdfPath& id, F f, const M0& m0, const M&... m) { +inline bool _FindAdapter(const SdfPath& id, F f, const M0& m0, const M&... m) +{ auto* adapterPtr = TfMapLookupPtr(m0, id); if (adapterPtr == nullptr) { return _FindAdapter(id, f, m...); @@ -98,13 +109,11 @@ inline bool _FindAdapter(const SdfPath& id, F f, const M0& m0, const M&... m) { } } -template -inline bool _RemoveAdapter(const SdfPath&, F) { - return false; -} +template inline bool _RemoveAdapter(const SdfPath&, F) { return false; } template -inline bool _RemoveAdapter(const SdfPath& id, F f, M0& m0, M&... m) { +inline bool _RemoveAdapter(const SdfPath& id, F f, M0& m0, M&... m) +{ auto* adapterPtr = TfMapLookupPtr(m0, id); if (adapterPtr == nullptr) { return _RemoveAdapter(id, f, m...); @@ -115,27 +124,25 @@ inline bool _RemoveAdapter(const SdfPath& id, F f, M0& m0, M&... m) { } } -template -inline R _GetDefaultValue() { - return {}; -} +template inline R _GetDefaultValue() { return {}; } // Default return value for HdTextureResource::ID, if not found, should be // -1, not {} - which would be 0 -template <> -inline HdTextureResource::ID _GetDefaultValue() { +template <> inline HdTextureResource::ID _GetDefaultValue() +{ return HdTextureResource::ID(-1); } // This will be nicer to use with automatic parameter deduction for lambdas in // C++14. -template -inline R _GetValue(const SdfPath&, F) { +template inline R _GetValue(const SdfPath&, F) +{ return _GetDefaultValue(); } template -inline R _GetValue(const SdfPath& id, F f, const M0& m0, const M&... m) { +inline R _GetValue(const SdfPath& id, F f, const M0& m0, const M&... m) +{ auto* adapterPtr = TfMapLookupPtr(m0, id); if (adapterPtr == nullptr) { return _GetValue(id, f, m...); @@ -144,14 +151,17 @@ inline R _GetValue(const SdfPath& id, F f, const M0& m0, const M&... m) { } } -template -inline void _MapAdapter(F) { +template inline void _MapAdapter(F) +{ // Do nothing. } template -inline void _MapAdapter(F f, const M0& m0, const M&... m) { - for (auto& it : m0) { f(static_cast(it.second.get())); } +inline void _MapAdapter(F f, const M0& m0, const M&... m) +{ + for (auto& it : m0) { + f(static_cast(it.second.get())); + } _MapAdapter(f, m...); } @@ -161,11 +171,13 @@ TF_DEFINE_PRIVATE_TOKENS( _tokens, (HdMayaSceneDelegate)((FallbackMaterial, "__fallback_material__"))); -TF_REGISTRY_FUNCTION(TfType) { - TfType::Define >(); +TF_REGISTRY_FUNCTION(TfType) +{ + TfType::Define>(); } -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaDelegateRegistry, HdMayaSceneDelegate) { +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaDelegateRegistry, HdMayaSceneDelegate) +{ HdMayaDelegateRegistry::RegisterDelegate( _tokens->HdMayaSceneDelegate, [](const HdMayaDelegate::InitData& initData) -> HdMayaDelegatePtr { @@ -175,20 +187,27 @@ TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaDelegateRegistry, HdMayaSceneDelegate) { } HdMayaSceneDelegate::HdMayaSceneDelegate(const InitData& initData) - : HdMayaDelegateCtx(initData), - _fallbackMaterial( - initData.delegateID.AppendChild(_tokens->FallbackMaterial)) {} + : HdMayaDelegateCtx(initData) + , _fallbackMaterial(initData.delegateID.AppendChild(_tokens->FallbackMaterial)) +{ +} -HdMayaSceneDelegate::~HdMayaSceneDelegate() { - for (auto callback : _callbacks) { MMessage::removeCallback(callback); } +HdMayaSceneDelegate::~HdMayaSceneDelegate() +{ + for (auto callback : _callbacks) { + MMessage::removeCallback(callback); + } _MapAdapter( - [](HdMayaAdapter* a) { a->RemoveCallbacks(); }, _shapeAdapters, - _lightAdapters, _materialAdapters); + [](HdMayaAdapter* a) { a->RemoveCallbacks(); }, + _shapeAdapters, + _lightAdapters, + _materialAdapters); } -void HdMayaSceneDelegate::Populate() { +void HdMayaSceneDelegate::Populate() +{ HdMayaAdapterRegistry::LoadAllPlugin(); - auto& renderIndex = GetRenderIndex(); + auto& renderIndex = GetRenderIndex(); MItDag dagIt(MItDag::kDepthFirst, MFn::kInvalid); dagIt.traverseUnderWorld(true); for (; !dagIt.isDone(); dagIt.next()) { @@ -197,21 +216,25 @@ void HdMayaSceneDelegate::Populate() { InsertDag(path); } MStatus status; - auto id = - MDGMessage::addNodeAddedCallback(_nodeAdded, "dagNode", this, &status); - if (status) { _callbacks.push_back(id); } + auto id = MDGMessage::addNodeAddedCallback(_nodeAdded, "dagNode", this, &status); + if (status) { + _callbacks.push_back(id); + } id = MDGMessage::addConnectionCallback(_connectionChanged, this, &status); - if (status) { _callbacks.push_back(id); } + if (status) { + _callbacks.push_back(id); + } // Adding fallback material sprim to the render index. if (renderIndex.IsSprimTypeSupported(HdPrimTypeTokens->material)) { - renderIndex.InsertSprim( - HdPrimTypeTokens->material, this, _fallbackMaterial); + renderIndex.InsertSprim(HdPrimTypeTokens->material, this, _fallbackMaterial); } } -void HdMayaSceneDelegate::PreFrame(const MHWRender::MDrawContext& context) { - bool enableMaterials = !(context.getDisplayStyle() & MHWRender::MFrameContext::kDefaultMaterial); +void HdMayaSceneDelegate::PreFrame(const MHWRender::MDrawContext& context) +{ + bool enableMaterials + = !(context.getDisplayStyle() & MHWRender::MFrameContext::kDefaultMaterial); if (enableMaterials != _enableMaterials) { _enableMaterials = enableMaterials; for (const auto& shape : _shapeAdapters) @@ -223,17 +246,14 @@ void HdMayaSceneDelegate::PreFrame(const MHWRender::MDrawContext& context) { for (const auto& id : _materialTagsChanged) { if (_GetValue( id, - [](HdMayaMaterialAdapter* a) { - return a->UpdateMaterialTag(); - }, + [](HdMayaMaterialAdapter* a) { return a->UpdateMaterialTag(); }, _materialAdapters)) { auto& renderIndex = GetRenderIndex(); for (const auto& rprimId : renderIndex.GetRprimIds()) { const auto* rprim = renderIndex.GetRprim(rprimId); if (rprim != nullptr && rprim->GetMaterialId() == id) { RebuildAdapterOnIdle( - rprim->GetId(), - HdMayaDelegateCtx::RebuildFlagPrim); + rprim->GetId(), HdMayaDelegateCtx::RebuildFlagPrim); } } } @@ -243,16 +263,19 @@ void HdMayaSceneDelegate::PreFrame(const MHWRender::MDrawContext& context) { } if (!_addedNodes.empty()) { for (const auto& obj : _addedNodes) { - if (obj.isNull()) { continue; } + if (obj.isNull()) { + continue; + } MDagPath dag; - MStatus status = MDagPath::getAPathTo(obj, dag); - if (!status) { return; } + MStatus status = MDagPath::getAPathTo(obj, dag); + if (!status) { + return; + } // We need to check if there is an instanced shape below this dag // and insert it as well, because they won't be inserted. if (dag.hasFn(MFn::kTransform)) { const auto childCount = dag.childCount(); - for (auto child = decltype(childCount){0}; child < childCount; - ++child) { + for (auto child = decltype(childCount) { 0 }; child < childCount; ++child) { auto dagCopy = dag; dagCopy.push(dag.child(child)); if (dagCopy.isInstanced() && dagCopy.instanceNumber() > 0) { @@ -271,8 +294,7 @@ void HdMayaSceneDelegate::PreFrame(const MHWRender::MDrawContext& context) { if (!_adaptersToRecreate.empty()) { for (const auto& it : _adaptersToRecreate) { RecreateAdapter(std::get<0>(it), std::get<1>(it)); - for (auto itr = _adaptersToRebuild.begin(); - itr != _adaptersToRebuild.end(); ++itr) { + for (auto itr = _adaptersToRebuild.begin(); itr != _adaptersToRebuild.end(); ++itr) { if (std::get<0>(it) == std::get<0>(*itr)) { _adaptersToRebuild.erase(itr); break; @@ -286,8 +308,7 @@ void HdMayaSceneDelegate::PreFrame(const MHWRender::MDrawContext& context) { _FindAdapter( std::get<0>(it), [&](HdMayaAdapter* a) { - if (std::get<1>(it) & - HdMayaDelegateCtx::RebuildFlagCallbacks) { + if (std::get<1>(it) & HdMayaDelegateCtx::RebuildFlagCallbacks) { a->RemoveCallbacks(); a->CreateCallbacks(); } @@ -296,61 +317,66 @@ void HdMayaSceneDelegate::PreFrame(const MHWRender::MDrawContext& context) { a->Populate(); } }, - _shapeAdapters, _lightAdapters, _materialAdapters); + _shapeAdapters, + _lightAdapters, + _materialAdapters); } _adaptersToRebuild.clear(); } - if (!IsHdSt()) { return; } - constexpr auto considerAllSceneLights = - MHWRender::MDrawContext::kFilteredIgnoreLightLimit; - MStatus status; - const auto numLights = - context.numberOfActiveLights(considerAllSceneLights, &status); - if (!status || numLights == 0) { return; } + if (!IsHdSt()) { + return; + } + constexpr auto considerAllSceneLights = MHWRender::MDrawContext::kFilteredIgnoreLightLimit; + MStatus status; + const auto numLights = context.numberOfActiveLights(considerAllSceneLights, &status); + if (!status || numLights == 0) { + return; + } MIntArray intVals; - MMatrix matrixVal; - for (auto i = decltype(numLights){0}; i < numLights; ++i) { - auto* lightParam = - context.getLightParameterInformation(i, considerAllSceneLights); - if (lightParam == nullptr) { continue; } + MMatrix matrixVal; + for (auto i = decltype(numLights) { 0 }; i < numLights; ++i) { + auto* lightParam = context.getLightParameterInformation(i, considerAllSceneLights); + if (lightParam == nullptr) { + continue; + } const auto lightPath = lightParam->lightPath(); - if (!lightPath.isValid()) { continue; } - if (!lightParam->getParameter( - MHWRender::MLightParameterInformation::kShadowOn, intVals) || - intVals.length() < 1 || intVals[0] != 1) { + if (!lightPath.isValid()) { + continue; + } + if (!lightParam->getParameter(MHWRender::MLightParameterInformation::kShadowOn, intVals) + || intVals.length() < 1 || intVals[0] != 1) { continue; } if (lightParam->getParameter( - MHWRender::MLightParameterInformation::kShadowViewProj, - matrixVal)) { + MHWRender::MLightParameterInformation::kShadowViewProj, matrixVal)) { _FindAdapter( GetPrimPath(lightPath, true), [&matrixVal](HdMayaLightAdapter* a) { // TODO: Mark Dirty? - a->SetShadowProjectionMatrix( - GetGfMatrixFromMaya(matrixVal)); + a->SetShadowProjectionMatrix(GetGfMatrixFromMaya(matrixVal)); }, _lightAdapters); } } } -void HdMayaSceneDelegate::RemoveAdapter(const SdfPath& id) { +void HdMayaSceneDelegate::RemoveAdapter(const SdfPath& id) +{ if (!_RemoveAdapter( id, [](HdMayaAdapter* a) { a->RemoveCallbacks(); a->RemovePrim(); }, - _shapeAdapters, _lightAdapters, _materialAdapters)) { - TF_WARN( - "HdMayaSceneDelegate::RemoveAdapter(%s) -- Adapter does not exists", - id.GetText()); + _shapeAdapters, + _lightAdapters, + _materialAdapters)) { + TF_WARN("HdMayaSceneDelegate::RemoveAdapter(%s) -- Adapter does not exists", id.GetText()); } } -void HdMayaSceneDelegate::RecreateAdapterOnIdle( - const SdfPath& id, const MObject& obj) { +void HdMayaSceneDelegate::RecreateAdapterOnIdle(const SdfPath& id, const MObject& obj) +{ // TODO: Thread safety? // We expect this to be a small number of objects, so using a simple linear // search and a vector is generally a good choice. @@ -363,16 +389,16 @@ void HdMayaSceneDelegate::RecreateAdapterOnIdle( _adaptersToRecreate.emplace_back(id, obj); } -void HdMayaSceneDelegate::MaterialTagChanged(const SdfPath& id) { - if (std::find( - _materialTagsChanged.begin(), _materialTagsChanged.end(), id) == - _materialTagsChanged.end()) { +void HdMayaSceneDelegate::MaterialTagChanged(const SdfPath& id) +{ + if (std::find(_materialTagsChanged.begin(), _materialTagsChanged.end(), id) + == _materialTagsChanged.end()) { _materialTagsChanged.push_back(id); } } -void HdMayaSceneDelegate::RebuildAdapterOnIdle( - const SdfPath& id, uint32_t flags) { +void HdMayaSceneDelegate::RebuildAdapterOnIdle(const SdfPath& id, uint32_t flags) +{ // We expect this to be a small number of objects, so using a simple linear // search and a vector is generally a good choice. for (auto& it : _adaptersToRebuild) { @@ -384,23 +410,25 @@ void HdMayaSceneDelegate::RebuildAdapterOnIdle( _adaptersToRebuild.emplace_back(id, flags); } -void HdMayaSceneDelegate::RecreateAdapter( - const SdfPath& id, const MObject& obj) { +void HdMayaSceneDelegate::RecreateAdapter(const SdfPath& id, const MObject& obj) +{ if (_RemoveAdapter( id, [](HdMayaAdapter* a) { a->RemoveCallbacks(); a->RemovePrim(); }, - _shapeAdapters, _lightAdapters)) { + _shapeAdapters, + _lightAdapters)) { MFnDagNode dgNode(obj); - MDagPath path; + MDagPath path; dgNode.getPath(path); if (path.isValid() && MObjectHandle(obj).isValid()) { TF_DEBUG(HDMAYA_DELEGATE_RECREATE_ADAPTER) .Msg( "Shape/light prim (%s) re-created for dag path (%s)\n", - id.GetText(), path.fullPathName().asChar()); + id.GetText(), + path.fullPathName().asChar()); InsertDag(path); } else { TF_DEBUG(HDMAYA_DELEGATE_RECREATE_ADAPTER) @@ -423,15 +451,15 @@ void HdMayaSceneDelegate::RecreateAdapter( for (const auto& rprimId : renderIndex.GetRprimIds()) { const auto* rprim = renderIndex.GetRprim(rprimId); if (rprim != nullptr && rprim->GetMaterialId() == id) { - changeTracker.MarkRprimDirty( - rprimId, HdChangeTracker::DirtyMaterialId); + changeTracker.MarkRprimDirty(rprimId, HdChangeTracker::DirtyMaterialId); } } if (MObjectHandle(obj).isValid()) { TF_DEBUG(HDMAYA_DELEGATE_RECREATE_ADAPTER) .Msg( "Material prim (%s) re-created for node (%s)\n", - id.GetText(), MFnDependencyNode(obj).name().asChar()); + id.GetText(), + MFnDependencyNode(obj).name().asChar()); _CreateMaterial(GetMaterialPath(obj), obj); } else { TF_DEBUG(HDMAYA_DELEGATE_RECREATE_ADAPTER) @@ -449,38 +477,44 @@ void HdMayaSceneDelegate::RecreateAdapter( } } -HdMayaShapeAdapterPtr HdMayaSceneDelegate::GetShapeAdapter(const SdfPath& id) { +HdMayaShapeAdapterPtr HdMayaSceneDelegate::GetShapeAdapter(const SdfPath& id) +{ auto iter = _shapeAdapters.find(id); return iter == _shapeAdapters.end() ? nullptr : iter->second; } -HdMayaLightAdapterPtr HdMayaSceneDelegate::GetLightAdapter(const SdfPath& id) { +HdMayaLightAdapterPtr HdMayaSceneDelegate::GetLightAdapter(const SdfPath& id) +{ auto iter = _lightAdapters.find(id); return iter == _lightAdapters.end() ? nullptr : iter->second; } -HdMayaMaterialAdapterPtr HdMayaSceneDelegate::GetMaterialAdapter( - const SdfPath& id) { +HdMayaMaterialAdapterPtr HdMayaSceneDelegate::GetMaterialAdapter(const SdfPath& id) +{ auto iter = _materialAdapters.find(id); return iter == _materialAdapters.end() ? nullptr : iter->second; } -void HdMayaSceneDelegate::InsertDag(const MDagPath& dag) { +void HdMayaSceneDelegate::InsertDag(const MDagPath& dag) +{ TF_DEBUG(HDMAYA_DELEGATE_INSERTDAG) .Msg( "HdMayaSceneDelegate::InsertDag::" "GetLightsEnabled()=%i\n", GetLightsEnabled()); // We don't care about transforms. - if (dag.hasFn(MFn::kTransform)) { return; } + if (dag.hasFn(MFn::kTransform)) { + return; + } MFnDagNode dagNode(dag); - if (dagNode.isIntermediateObject()) { return; } + if (dagNode.isIntermediateObject()) { + return; + } // Custom lights don't have MFn::kLight. if (GetLightsEnabled()) { - auto adapterCreator = - HdMayaAdapterRegistry::GetLightAdapterCreator(dag); + auto adapterCreator = HdMayaAdapterRegistry::GetLightAdapterCreator(dag); if (adapterCreator != nullptr) { TF_DEBUG(HDMAYA_DELEGATE_INSERTDAG) .Msg( @@ -488,12 +522,16 @@ void HdMayaSceneDelegate::InsertDag(const MDagPath& dag) { "found light: %s\n", dag.fullPathName().asChar()); const auto id = GetPrimPath(dag, true); - if (TfMapLookupPtr(_lightAdapters, id) != nullptr) { return; } + if (TfMapLookupPtr(_lightAdapters, id) != nullptr) { + return; + } auto adapter = adapterCreator(this, dag); - if (adapter == nullptr || !adapter->IsSupported()) { return; } + if (adapter == nullptr || !adapter->IsSupported()) { + return; + } adapter->Populate(); adapter->CreateCallbacks(); - _lightAdapters.insert({id, adapter}); + _lightAdapters.insert({ id, adapter }); return; } } @@ -504,19 +542,25 @@ void HdMayaSceneDelegate::InsertDag(const MDagPath& dag) { dag.fullPathName().asChar()); // We are inserting a single prim and // instancer for every instanced mesh. - if (dag.isInstanced() && dag.instanceNumber() > 0) { return; } + if (dag.isInstanced() && dag.instanceNumber() > 0) { + return; + } auto adapterCreator = HdMayaAdapterRegistry::GetShapeAdapterCreator(dag); - if (adapterCreator == nullptr) { + if (adapterCreator == nullptr) { // Proxy shape is registered as base class type but plugins can derrive from it // Check the object type and if matches proxy base class find an adapter for it. adapterCreator = HdMayaAdapterRegistry::GetProxyShapeAdapterCreator(dag); - if(adapterCreator == nullptr) - return; + if (adapterCreator == nullptr) + return; } const auto id = GetPrimPath(dag, false); - if (TfMapLookupPtr(_shapeAdapters, id) != nullptr) { return; } + if (TfMapLookupPtr(_shapeAdapters, id) != nullptr) { + return; + } auto adapter = adapterCreator(this, dag); - if (adapter == nullptr || !adapter->IsSupported()) { return; } + if (adapter == nullptr || !adapter->IsSupported()) { + return; + } auto material = adapter->GetMaterial(); if (material != MObject::kNullObj) { @@ -527,14 +571,13 @@ void HdMayaSceneDelegate::InsertDag(const MDagPath& dag) { } adapter->Populate(); adapter->CreateCallbacks(); - _shapeAdapters.insert({id, adapter}); + _shapeAdapters.insert({ id, adapter }); } -void HdMayaSceneDelegate::NodeAdded(const MObject& obj) { - _addedNodes.push_back(obj); -} +void HdMayaSceneDelegate::NodeAdded(const MObject& obj) { _addedNodes.push_back(obj); } -void HdMayaSceneDelegate::UpdateLightVisibility(const MDagPath& dag) { +void HdMayaSceneDelegate::UpdateLightVisibility(const MDagPath& dag) +{ const auto id = GetPrimPath(dag, true); _FindAdapter( id, @@ -548,16 +591,18 @@ void HdMayaSceneDelegate::UpdateLightVisibility(const MDagPath& dag) { _lightAdapters); } -void HdMayaSceneDelegate::AddNewInstance(const MDagPath& dag) { +void HdMayaSceneDelegate::AddNewInstance(const MDagPath& dag) +{ MDagPathArray dags; MDagPath::getAllPathsTo(dag.node(), dags); const auto dagsLength = dags.length(); - if (dagsLength == 0) { return; } - const auto masterDag = dags[0]; - const auto id = GetPrimPath(masterDag, false); + if (dagsLength == 0) { + return; + } + const auto masterDag = dags[0]; + const auto id = GetPrimPath(masterDag, false); std::shared_ptr masterAdapter; - if (!TfMapLookup(_shapeAdapters, id, &masterAdapter) || - masterAdapter == nullptr) { + if (!TfMapLookup(_shapeAdapters, id, &masterAdapter) || masterAdapter == nullptr) { return; } // If dags is 1, we have to recreate the adapter. @@ -568,13 +613,13 @@ void HdMayaSceneDelegate::AddNewInstance(const MDagPath& dag) { // mark dirty. RebuildAdapterOnIdle(id, HdMayaDelegateCtx::RebuildFlagCallbacks); masterAdapter->MarkDirty( - HdChangeTracker::DirtyInstancer | - HdChangeTracker::DirtyInstanceIndex | - HdChangeTracker::DirtyPrimvar); + HdChangeTracker::DirtyInstancer | HdChangeTracker::DirtyInstanceIndex + | HdChangeTracker::DirtyPrimvar); } } -void HdMayaSceneDelegate::SetParams(const HdMayaParams& params) { +void HdMayaSceneDelegate::SetParams(const HdMayaParams& params) +{ const auto& oldParams = GetParams(); if (oldParams.displaySmoothMeshes != params.displaySmoothMeshes) { // I couldn't find any other way to turn this on / off. @@ -596,9 +641,7 @@ void HdMayaSceneDelegate::SetParams(const HdMayaParams& params) { [](HdMayaDagAdapter* a) { if (a->HasType(HdPrimTypeTokens->mesh)) { a->InvalidateTransform(); - a->MarkDirty( - HdChangeTracker::DirtyPoints | - HdChangeTracker::DirtyTransform); + a->MarkDirty(HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyTransform); } }, _shapeAdapters); @@ -606,27 +649,23 @@ void HdMayaSceneDelegate::SetParams(const HdMayaParams& params) { // We need to trigger rebuilding shaders. if (oldParams.textureMemoryPerTexture != params.textureMemoryPerTexture) { _MapAdapter( - [](HdMayaMaterialAdapter* a) { - a->MarkDirty(HdMaterial::AllDirty); - }, + [](HdMayaMaterialAdapter* a) { a->MarkDirty(HdMaterial::AllDirty); }, _materialAdapters); } - if (oldParams.maximumShadowMapResolution != - params.maximumShadowMapResolution) { + if (oldParams.maximumShadowMapResolution != params.maximumShadowMapResolution) { _MapAdapter( - [](HdMayaLightAdapter* a) { a->MarkDirty(HdLight::AllDirty); }, - _lightAdapters); + [](HdMayaLightAdapter* a) { a->MarkDirty(HdLight::AllDirty); }, _lightAdapters); } HdMayaDelegate::SetParams(params); } void HdMayaSceneDelegate::PopulateSelectedPaths( - const MSelectionList& mayaSelection, SdfPathVector& selectedSdfPaths, - const HdSelectionSharedPtr& selection) { + const MSelectionList& mayaSelection, + SdfPathVector& selectedSdfPaths, + const HdSelectionSharedPtr& selection) +{ TF_DEBUG(HDMAYA_DELEGATE_SELECTION) - .Msg( - "HdMayaSceneDelegate::PopulateSelectedPaths - %s\n", - GetMayaDelegateID().GetText()); + .Msg("HdMayaSceneDelegate::PopulateSelectedPaths - %s\n", GetMayaDelegateID().GetText()); // We need to track selected masters (but not non-instanced prims) // because they may not be unique when we iterate over selected items - @@ -640,13 +679,11 @@ void HdMayaSceneDelegate::PopulateSelectedPaths( std::unordered_set selectedMasters; MapSelectionDescendents( mayaSelection, - [this, &selectedSdfPaths, &selectedMasters, - &selection](const MDagPath& dagPath) { + [this, &selectedSdfPaths, &selectedMasters, &selection](const MDagPath& dagPath) { SdfPath primId; if (dagPath.isInstanced()) { auto masterDag = MDagPath(); - if (!TF_VERIFY( - MDagPath::getAPathTo(dagPath.node(), masterDag))) { + if (!TF_VERIFY(MDagPath::getAPathTo(dagPath.node(), masterDag))) { return; } primId = GetPrimPath(masterDag, false); @@ -654,7 +691,9 @@ void HdMayaSceneDelegate::PopulateSelectedPaths( primId = GetPrimPath(dagPath, false); } auto adapter = _shapeAdapters.find(primId); - if (adapter == _shapeAdapters.end()) { return; } + if (adapter == _shapeAdapters.end()) { + return; + } TF_DEBUG(HDMAYA_DELEGATE_SELECTION) .Msg( @@ -703,130 +742,142 @@ void HdMayaSceneDelegate::PopulateSelectionList( } #endif -HdMeshTopology HdMayaSceneDelegate::GetMeshTopology(const SdfPath& id) { +HdMeshTopology HdMayaSceneDelegate::GetMeshTopology(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_MESH_TOPOLOGY) .Msg("HdMayaSceneDelegate::GetMeshTopology(%s)\n", id.GetText()); return _GetValue( id, - [](HdMayaShapeAdapter* a) -> HdMeshTopology { - return a->GetMeshTopology(); - }, + [](HdMayaShapeAdapter* a) -> HdMeshTopology { return a->GetMeshTopology(); }, _shapeAdapters); } -HdBasisCurvesTopology HdMayaSceneDelegate::GetBasisCurvesTopology( - const SdfPath& id) { +HdBasisCurvesTopology HdMayaSceneDelegate::GetBasisCurvesTopology(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_CURVE_TOPOLOGY) .Msg("HdMayaSceneDelegate::GetBasisCurvesTopology(%s)\n", id.GetText()); return _GetValue( id, - [](HdMayaShapeAdapter* a) -> HdBasisCurvesTopology { - return a->GetBasisCurvesTopology(); - }, + [](HdMayaShapeAdapter* a) -> HdBasisCurvesTopology { return a->GetBasisCurvesTopology(); }, _shapeAdapters); } -PxOsdSubdivTags HdMayaSceneDelegate::GetSubdivTags(const SdfPath& id) { +PxOsdSubdivTags HdMayaSceneDelegate::GetSubdivTags(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_SUBDIV_TAGS) .Msg("HdMayaSceneDelegate::GetSubdivTags(%s)\n", id.GetText()); return _GetValue( id, - [](HdMayaShapeAdapter* a) -> PxOsdSubdivTags { - return a->GetSubdivTags(); - }, + [](HdMayaShapeAdapter* a) -> PxOsdSubdivTags { return a->GetSubdivTags(); }, _shapeAdapters); } -GfRange3d HdMayaSceneDelegate::GetExtent(const SdfPath& id) { - TF_DEBUG(HDMAYA_DELEGATE_GET_EXTENT) - .Msg("HdMayaSceneDelegate::GetExtent(%s)\n", id.GetText()); +GfRange3d HdMayaSceneDelegate::GetExtent(const SdfPath& id) +{ + TF_DEBUG(HDMAYA_DELEGATE_GET_EXTENT).Msg("HdMayaSceneDelegate::GetExtent(%s)\n", id.GetText()); return _GetValue( - id, [](HdMayaShapeAdapter* a) -> GfRange3d { return a->GetExtent(); }, - _shapeAdapters); + id, [](HdMayaShapeAdapter* a) -> GfRange3d { return a->GetExtent(); }, _shapeAdapters); } -GfMatrix4d HdMayaSceneDelegate::GetTransform(const SdfPath& id) { +GfMatrix4d HdMayaSceneDelegate::GetTransform(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_TRANSFORM) .Msg("HdMayaSceneDelegate::GetTransform(%s)\n", id.GetText()); return _GetValue( - id, [](HdMayaDagAdapter* a) -> GfMatrix4d { return a->GetTransform(); }, - _shapeAdapters, _lightAdapters); + id, + [](HdMayaDagAdapter* a) -> GfMatrix4d { return a->GetTransform(); }, + _shapeAdapters, + _lightAdapters); } size_t HdMayaSceneDelegate::SampleTransform( - const SdfPath& id, size_t maxSampleCount, float* times, - GfMatrix4d* samples) { + const SdfPath& id, + size_t maxSampleCount, + float* times, + GfMatrix4d* samples) +{ TF_DEBUG(HDMAYA_DELEGATE_SAMPLE_TRANSFORM) .Msg( - "HdMayaSceneDelegate::SampleTransform(%s, %u)\n", id.GetText(), + "HdMayaSceneDelegate::SampleTransform(%s, %u)\n", + id.GetText(), static_cast(maxSampleCount)); return _GetValue( id, [maxSampleCount, times, samples](HdMayaDagAdapter* a) -> size_t { return a->SampleTransform(maxSampleCount, times, samples); }, - _shapeAdapters, _lightAdapters); + _shapeAdapters, + _lightAdapters); } -bool HdMayaSceneDelegate::IsEnabled(const TfToken& option) const { +bool HdMayaSceneDelegate::IsEnabled(const TfToken& option) const +{ TF_DEBUG(HDMAYA_DELEGATE_IS_ENABLED) .Msg("HdMayaSceneDelegate::IsEnabled(%s)\n", option.GetText()); // Maya scene can't be accessed on multiple threads, // so I don't think this is safe to enable. - if (option == HdOptionTokens->parallelRprimSync) { return false; } + if (option == HdOptionTokens->parallelRprimSync) { + return false; + } - TF_WARN( - "HdMayaSceneDelegate::IsEnabled(%s) -- Unsupported option.\n", - option.GetText()); + TF_WARN("HdMayaSceneDelegate::IsEnabled(%s) -- Unsupported option.\n", option.GetText()); return false; } -VtValue HdMayaSceneDelegate::Get(const SdfPath& id, const TfToken& key) { +VtValue HdMayaSceneDelegate::Get(const SdfPath& id, const TfToken& key) +{ TF_DEBUG(HDMAYA_DELEGATE_GET) .Msg("HdMayaSceneDelegate::Get(%s, %s)\n", id.GetText(), key.GetText()); if (id.IsPropertyPath()) { return _GetValue( id.GetPrimPath(), - [&key](HdMayaDagAdapter* a) -> VtValue { - return a->GetInstancePrimvar(key); - }, + [&key](HdMayaDagAdapter* a) -> VtValue { return a->GetInstancePrimvar(key); }, _shapeAdapters); } else { return _GetValue( - id, [&key](HdMayaAdapter* a) -> VtValue { return a->Get(key); }, - _shapeAdapters, _lightAdapters, _materialAdapters); + id, + [&key](HdMayaAdapter* a) -> VtValue { return a->Get(key); }, + _shapeAdapters, + _lightAdapters, + _materialAdapters); } } size_t HdMayaSceneDelegate::SamplePrimvar( - const SdfPath& id, const TfToken& key, size_t maxSampleCount, float* times, - VtValue* samples) { + const SdfPath& id, + const TfToken& key, + size_t maxSampleCount, + float* times, + VtValue* samples) +{ TF_DEBUG(HDMAYA_DELEGATE_SAMPLE_PRIMVAR) .Msg( - "HdMayaSceneDelegate::SamplePrimvar(%s, %s, %u)\n", id.GetText(), - key.GetText(), static_cast(maxSampleCount)); - if (maxSampleCount < 1) { return 0; } + "HdMayaSceneDelegate::SamplePrimvar(%s, %s, %u)\n", + id.GetText(), + key.GetText(), + static_cast(maxSampleCount)); + if (maxSampleCount < 1) { + return 0; + } if (id.IsPropertyPath()) { times[0] = 0.0f; samples[0] = _GetValue( id.GetPrimPath(), - [&key](HdMayaDagAdapter* a) -> VtValue { - return a->GetInstancePrimvar(key); - }, + [&key](HdMayaDagAdapter* a) -> VtValue { return a->GetInstancePrimvar(key); }, _shapeAdapters); return 1; } else { return _GetValue( id, - [&key, maxSampleCount, times, - samples](HdMayaShapeAdapter* a) -> size_t { + [&key, maxSampleCount, times, samples](HdMayaShapeAdapter* a) -> size_t { return a->SamplePrimvar(key, maxSampleCount, times, samples); }, _shapeAdapters); } } -TfToken HdMayaSceneDelegate::GetRenderTag(const SdfPath& id) { +TfToken HdMayaSceneDelegate::GetRenderTag(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_RENDER_TAG) .Msg("HdMayaSceneDelegate::GetRenderTag(%s)\n", id.GetText()); return _GetValue( @@ -835,12 +886,11 @@ TfToken HdMayaSceneDelegate::GetRenderTag(const SdfPath& id) { _shapeAdapters); } -HdPrimvarDescriptorVector HdMayaSceneDelegate::GetPrimvarDescriptors( - const SdfPath& id, HdInterpolation interpolation) { +HdPrimvarDescriptorVector +HdMayaSceneDelegate::GetPrimvarDescriptors(const SdfPath& id, HdInterpolation interpolation) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_PRIMVAR_DESCRIPTORS) - .Msg( - "HdMayaSceneDelegate::GetPrimvarDescriptors(%s, %i)\n", - id.GetText(), interpolation); + .Msg("HdMayaSceneDelegate::GetPrimvarDescriptors(%s, %i)\n", id.GetText(), interpolation); if (id.IsPropertyPath()) { return _GetValue( id.GetPrimPath(), @@ -851,34 +901,32 @@ HdPrimvarDescriptorVector HdMayaSceneDelegate::GetPrimvarDescriptors( } else { return _GetValue( id, - [&interpolation]( - HdMayaShapeAdapter* a) -> HdPrimvarDescriptorVector { + [&interpolation](HdMayaShapeAdapter* a) -> HdPrimvarDescriptorVector { return a->GetPrimvarDescriptors(interpolation); }, _shapeAdapters); } } -VtValue HdMayaSceneDelegate::GetLightParamValue( - const SdfPath& id, const TfToken& paramName) { +VtValue HdMayaSceneDelegate::GetLightParamValue(const SdfPath& id, const TfToken& paramName) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_LIGHT_PARAM_VALUE) .Msg( - "HdMayaSceneDelegate::GetLightParamValue(%s, %s)\n", id.GetText(), - paramName.GetText()); + "HdMayaSceneDelegate::GetLightParamValue(%s, %s)\n", id.GetText(), paramName.GetText()); return _GetValue( id, - [¶mName](HdMayaLightAdapter* a) -> VtValue { - return a->GetLightParamValue(paramName); - }, + [¶mName](HdMayaLightAdapter* a) -> VtValue { return a->GetLightParamValue(paramName); }, _lightAdapters); } -VtIntArray HdMayaSceneDelegate::GetInstanceIndices( - const SdfPath& instancerId, const SdfPath& prototypeId) { +VtIntArray +HdMayaSceneDelegate::GetInstanceIndices(const SdfPath& instancerId, const SdfPath& prototypeId) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_INSTANCE_INDICES) .Msg( "HdMayaSceneDelegate::GetInstanceIndices(%s, %s)\n", - instancerId.GetText(), prototypeId.GetText()); + instancerId.GetText(), + prototypeId.GetText()); return _GetValue( instancerId.GetPrimPath(), [&prototypeId](HdMayaDagAdapter* a) -> VtIntArray { @@ -887,26 +935,32 @@ VtIntArray HdMayaSceneDelegate::GetInstanceIndices( _shapeAdapters); } -GfMatrix4d HdMayaSceneDelegate::GetInstancerTransform( - SdfPath const& instancerId) { +GfMatrix4d HdMayaSceneDelegate::GetInstancerTransform(SdfPath const& instancerId) +{ return GfMatrix4d(1.0); } #if defined(HD_API_VERSION) && HD_API_VERSION >= 34 SdfPath HdMayaSceneDelegate::GetScenePrimPath( - const SdfPath& rprimPath, int instanceIndex, - HdInstancerContext *instancerContext) { + const SdfPath& rprimPath, + int instanceIndex, + HdInstancerContext* instancerContext) +{ return rprimPath; } #elif defined(HD_API_VERSION) && HD_API_VERSION >= 33 -SdfPath HdMayaSceneDelegate::GetScenePrimPath( - const SdfPath& rprimPath, int instanceIndex) { +SdfPath HdMayaSceneDelegate::GetScenePrimPath(const SdfPath& rprimPath, int instanceIndex) +{ return rprimPath; } #else SdfPath HdMayaSceneDelegate::GetPathForInstanceIndex( - const SdfPath& protoPrimPath, int instanceIndex, int* absoluteInstanceIndex, - SdfPath* rprimPath, SdfPathVector* instanceContext) { + const SdfPath& protoPrimPath, + int instanceIndex, + int* absoluteInstanceIndex, + SdfPath* rprimPath, + SdfPathVector* instanceContext) +{ if (absoluteInstanceIndex != nullptr) { *absoluteInstanceIndex = instanceIndex; } @@ -914,42 +968,46 @@ SdfPath HdMayaSceneDelegate::GetPathForInstanceIndex( } #endif -bool HdMayaSceneDelegate::GetVisible(const SdfPath& id) { +bool HdMayaSceneDelegate::GetVisible(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_VISIBLE) .Msg("HdMayaSceneDelegate::GetVisible(%s)\n", id.GetText()); return _GetValue( - id, [](HdMayaDagAdapter* a) -> bool { return a->GetVisible(); }, - _shapeAdapters, _lightAdapters); + id, + [](HdMayaDagAdapter* a) -> bool { return a->GetVisible(); }, + _shapeAdapters, + _lightAdapters); } -bool HdMayaSceneDelegate::GetDoubleSided(const SdfPath& id) { +bool HdMayaSceneDelegate::GetDoubleSided(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_DOUBLE_SIDED) .Msg("HdMayaSceneDelegate::GetDoubleSided(%s)\n", id.GetText()); return _GetValue( - id, [](HdMayaShapeAdapter* a) -> bool { return a->GetDoubleSided(); }, - _shapeAdapters); + id, [](HdMayaShapeAdapter* a) -> bool { return a->GetDoubleSided(); }, _shapeAdapters); } -HdCullStyle HdMayaSceneDelegate::GetCullStyle(const SdfPath& id) { +HdCullStyle HdMayaSceneDelegate::GetCullStyle(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_CULL_STYLE) .Msg("HdMayaSceneDelegate::GetCullStyle(%s)\n", id.GetText()); return HdCullStyleDontCare; } -HdDisplayStyle HdMayaSceneDelegate::GetDisplayStyle(const SdfPath& id) { +HdDisplayStyle HdMayaSceneDelegate::GetDisplayStyle(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_DISPLAY_STYLE) .Msg("HdMayaSceneDelegate::GetDisplayStyle(%s)\n", id.GetText()); return _GetValue( id, - [](HdMayaShapeAdapter* a) -> HdDisplayStyle { - return a->GetDisplayStyle(); - }, + [](HdMayaShapeAdapter* a) -> HdDisplayStyle { return a->GetDisplayStyle(); }, _shapeAdapters); } #if USD_VERSION_NUM <= 1911 -std::string HdMayaSceneDelegate::GetSurfaceShaderSource(const SdfPath& id) { +std::string HdMayaSceneDelegate::GetSurfaceShaderSource(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_SURFACE_SHADER_SOURCE) .Msg("HdMayaSceneDelegate::GetSurfaceShaderSource(%s)\n", id.GetText()); if (id == _fallbackMaterial) { @@ -957,35 +1015,30 @@ std::string HdMayaSceneDelegate::GetSurfaceShaderSource(const SdfPath& id) { } return _GetValue( id, - [](HdMayaMaterialAdapter* a) -> std::string { - return a->GetSurfaceShaderSource(); - }, + [](HdMayaMaterialAdapter* a) -> std::string { return a->GetSurfaceShaderSource(); }, _materialAdapters); } -std::string HdMayaSceneDelegate::GetDisplacementShaderSource( - const SdfPath& id) { +std::string HdMayaSceneDelegate::GetDisplacementShaderSource(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_DISPLACEMENT_SHADER_SOURCE) - .Msg( - "HdMayaSceneDelegate::GetDisplacementShaderSource(%s)\n", - id.GetText()); + .Msg("HdMayaSceneDelegate::GetDisplacementShaderSource(%s)\n", id.GetText()); if (id == _fallbackMaterial) { return HdMayaMaterialAdapter::GetPreviewDisplacementSource(); } return _GetValue( id, - [](HdMayaMaterialAdapter* a) -> std::string { - return a->GetDisplacementShaderSource(); - }, + [](HdMayaMaterialAdapter* a) -> std::string { return a->GetDisplacementShaderSource(); }, _materialAdapters); } -VtValue HdMayaSceneDelegate::GetMaterialParamValue( - const SdfPath& id, const TfToken& paramName) { +VtValue HdMayaSceneDelegate::GetMaterialParamValue(const SdfPath& id, const TfToken& paramName) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_MATERIAL_PARAM_VALUE) .Msg( "HdMayaSceneDelegate::GetMaterialParamValue(%s, %s)\n", - id.GetText(), paramName.GetText()); + id.GetText(), + paramName.GetText()); if (id == _fallbackMaterial) { return HdMayaMaterialAdapter::GetPreviewMaterialParamValue(paramName); } @@ -997,8 +1050,8 @@ VtValue HdMayaSceneDelegate::GetMaterialParamValue( _materialAdapters); } -HdMaterialParamVector HdMayaSceneDelegate::GetMaterialParams( - const SdfPath& id) { +HdMaterialParamVector HdMayaSceneDelegate::GetMaterialParams(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_MATERIAL_PARAMS) .Msg("HdMayaSceneDelegate::GetMaterialParams(%s)\n", id.GetText()); if (id == _fallbackMaterial) { @@ -1006,47 +1059,46 @@ HdMaterialParamVector HdMayaSceneDelegate::GetMaterialParams( } return _GetValue( id, - [](HdMayaMaterialAdapter* a) -> HdMaterialParamVector { - return a->GetMaterialParams(); - }, + [](HdMayaMaterialAdapter* a) -> HdMaterialParamVector { return a->GetMaterialParams(); }, _materialAdapters); } -VtDictionary HdMayaSceneDelegate::GetMaterialMetadata( - const SdfPath& materialId) { +VtDictionary HdMayaSceneDelegate::GetMaterialMetadata(const SdfPath& materialId) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_MATERIAL_METADATA) - .Msg( - "HdMayaSceneDelegate::GetMaterialMetadata(%s)\n", - materialId.GetText()); + .Msg("HdMayaSceneDelegate::GetMaterialMetadata(%s)\n", materialId.GetText()); return _GetValue( materialId, - [](HdMayaMaterialAdapter* a) -> VtDictionary { - return a->GetMaterialMetadata(); - }, + [](HdMayaMaterialAdapter* a) -> VtDictionary { return a->GetMaterialMetadata(); }, _materialAdapters); } #endif // USD_VERSION_NUM <= 1911 -SdfPath HdMayaSceneDelegate::GetMaterialId(const SdfPath& id) { +SdfPath HdMayaSceneDelegate::GetMaterialId(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_MATERIAL_ID) .Msg("HdMayaSceneDelegate::GetMaterialId(%s)\n", id.GetText()); if (!_enableMaterials) return {}; auto shapeAdapter = TfMapLookupPtr(_shapeAdapters, id); - if (shapeAdapter == nullptr) { return _fallbackMaterial; } + if (shapeAdapter == nullptr) { + return _fallbackMaterial; + } auto material = shapeAdapter->get()->GetMaterial(); - if (material == MObject::kNullObj) { return _fallbackMaterial; } + if (material == MObject::kNullObj) { + return _fallbackMaterial; + } auto materialId = GetMaterialPath(material); if (TfMapLookupPtr(_materialAdapters, materialId) != nullptr) { return materialId; } - return _CreateMaterial(materialId, material) ? materialId - : _fallbackMaterial; + return _CreateMaterial(materialId, material) ? materialId : _fallbackMaterial; } -VtValue HdMayaSceneDelegate::GetMaterialResource(const SdfPath& id) { +VtValue HdMayaSceneDelegate::GetMaterialResource(const SdfPath& id) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_MATERIAL_RESOURCE) .Msg("HdMayaSceneDelegate::GetMaterialResource(%s)\n", id.GetText()); if (id == _fallbackMaterial) { @@ -1054,20 +1106,15 @@ VtValue HdMayaSceneDelegate::GetMaterialResource(const SdfPath& id) { } auto ret = _GetValue( id, - [](HdMayaMaterialAdapter* a) -> VtValue { - return a->GetMaterialResource(); - }, + [](HdMayaMaterialAdapter* a) -> VtValue { return a->GetMaterialResource(); }, _materialAdapters); - return ret.IsEmpty() ? HdMayaMaterialAdapter::GetPreviewMaterialResource(id) - : ret; + return ret.IsEmpty() ? HdMayaMaterialAdapter::GetPreviewMaterialResource(id) : ret; } -HdTextureResource::ID HdMayaSceneDelegate::GetTextureResourceID( - const SdfPath& textureId) { +HdTextureResource::ID HdMayaSceneDelegate::GetTextureResourceID(const SdfPath& textureId) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_TEXTURE_RESOURCE_ID) - .Msg( - "HdMayaSceneDelegate::GetTextureResourceID(%s)\n", - textureId.GetText()); + .Msg("HdMayaSceneDelegate::GetTextureResourceID(%s)\n", textureId.GetText()); return _GetValue( textureId.GetPrimPath(), [&textureId](HdMayaMaterialAdapter* a) -> HdTextureResource::ID { @@ -1076,12 +1123,10 @@ HdTextureResource::ID HdMayaSceneDelegate::GetTextureResourceID( _materialAdapters); } -HdTextureResourceSharedPtr HdMayaSceneDelegate::GetTextureResource( - const SdfPath& textureId) { +HdTextureResourceSharedPtr HdMayaSceneDelegate::GetTextureResource(const SdfPath& textureId) +{ TF_DEBUG(HDMAYA_DELEGATE_GET_TEXTURE_RESOURCE) - .Msg( - "HdMayaSceneDelegate::GetTextureResource(%s)\n", - textureId.GetText()); + .Msg("HdMayaSceneDelegate::GetTextureResource(%s)\n", textureId.GetText()); #if USD_VERSION_NUM <= 1911 @@ -1096,7 +1141,7 @@ HdTextureResourceSharedPtr HdMayaSceneDelegate::GetTextureResource( auto* adapterPtr = TfMapLookupPtr(_materialAdapters, textureId); - if(!adapterPtr) { + if (!adapterPtr) { // For texture nodes we may have only inserted an adapter for the material // not for the texture itself. // @@ -1125,8 +1170,8 @@ HdTextureResourceSharedPtr HdMayaSceneDelegate::GetTextureResource( #endif // USD_VERSION_NUM <= 1911 } -bool HdMayaSceneDelegate::_CreateMaterial( - const SdfPath& id, const MObject& obj) { +bool HdMayaSceneDelegate::_CreateMaterial(const SdfPath& id, const MObject& obj) +{ TF_DEBUG(HDMAYA_ADAPTER_MATERIALS) .Msg("HdMayaSceneDelegate::_CreateMaterial(%s)\n", id.GetText()); diff --git a/lib/usd/hdMaya/delegates/sceneDelegate.h b/lib/usd/hdMaya/delegates/sceneDelegate.h index a50a5cc1b5..b4b1606677 100644 --- a/lib/usd/hdMaya/delegates/sceneDelegate.h +++ b/lib/usd/hdMaya/delegates/sceneDelegate.h @@ -16,21 +16,21 @@ #ifndef HDMAYA_SCENE_DELEGATE_H #define HDMAYA_SCENE_DELEGATE_H -#include - -#include -#include +#include +#include +#include +#include -#include #include #include #include +#include #include -#include -#include -#include -#include +#include +#include + +#include /* * Notes. @@ -49,7 +49,8 @@ PXR_NAMESPACE_OPEN_SCOPE -class HdMayaSceneDelegate : public HdMayaDelegateCtx { +class HdMayaSceneDelegate : public HdMayaDelegateCtx +{ public: HDMAYA_API HdMayaSceneDelegate(const InitData& initData); @@ -111,16 +112,17 @@ class HdMayaSceneDelegate : public HdMayaDelegateCtx { HDMAYA_API void PopulateSelectedPaths( - const MSelectionList& mayaSelection, SdfPathVector& selectedSdfPaths, + const MSelectionList& mayaSelection, + SdfPathVector& selectedSdfPaths, const HdSelectionSharedPtr& selection) override; #if MAYA_API_VERSION >= 20210000 HDMAYA_API void PopulateSelectionList( - const HdxPickHitVector& hits, + const HdxPickHitVector& hits, const MHWRender::MSelectionInfo& selectInfo, - MSelectionList& selectionList, - MPointArray& worldSpaceHitPts) override; + MSelectionList& selectionList, + MPointArray& worldSpaceHitPts) override; #endif protected: @@ -140,9 +142,9 @@ class HdMayaSceneDelegate : public HdMayaDelegateCtx { GfMatrix4d GetTransform(const SdfPath& id) override; HDMAYA_API - size_t SampleTransform( - const SdfPath& id, size_t maxSampleCount, float* times, - GfMatrix4d* samples) override; + size_t + SampleTransform(const SdfPath& id, size_t maxSampleCount, float* times, GfMatrix4d* samples) + override; HDMAYA_API bool GetVisible(const SdfPath& id) override; @@ -166,23 +168,24 @@ class HdMayaSceneDelegate : public HdMayaDelegateCtx { HDMAYA_API size_t SamplePrimvar( - const SdfPath& id, const TfToken& key, size_t maxSampleCount, - float* times, VtValue* samples) override; + const SdfPath& id, + const TfToken& key, + size_t maxSampleCount, + float* times, + VtValue* samples) override; HDMAYA_API TfToken GetRenderTag(SdfPath const& id) override; HDMAYA_API - HdPrimvarDescriptorVector GetPrimvarDescriptors( - const SdfPath& id, HdInterpolation interpolation) override; + HdPrimvarDescriptorVector + GetPrimvarDescriptors(const SdfPath& id, HdInterpolation interpolation) override; HDMAYA_API - VtValue GetLightParamValue( - const SdfPath& id, const TfToken& paramName) override; + VtValue GetLightParamValue(const SdfPath& id, const TfToken& paramName) override; HDMAYA_API - VtIntArray GetInstanceIndices( - const SdfPath& instancerId, const SdfPath& prototypeId) override; + VtIntArray GetInstanceIndices(const SdfPath& instancerId, const SdfPath& prototypeId) override; HDMAYA_API GfMatrix4d GetInstancerTransform(SdfPath const& instancerId) override; @@ -190,15 +193,17 @@ class HdMayaSceneDelegate : public HdMayaDelegateCtx { HDMAYA_API #if defined(HD_API_VERSION) && HD_API_VERSION >= 34 SdfPath GetScenePrimPath( - const SdfPath& rprimPath, int instanceIndex, - HdInstancerContext *instancerContext) override; + const SdfPath& rprimPath, + int instanceIndex, + HdInstancerContext* instancerContext) override; #elif defined(HD_API_VERSION) && HD_API_VERSION >= 33 - SdfPath GetScenePrimPath( - const SdfPath& rprimPath, int instanceIndex) override; + SdfPath GetScenePrimPath(const SdfPath& rprimPath, int instanceIndex) override; #else SdfPath GetPathForInstanceIndex( - const SdfPath& protoPrimPath, int instanceIndex, - int* absoluteInstanceIndex, SdfPath* rprimPath, + const SdfPath& protoPrimPath, + int instanceIndex, + int* absoluteInstanceIndex, + SdfPath* rprimPath, SdfPathVector* instanceContext) override; #endif @@ -211,8 +216,7 @@ class HdMayaSceneDelegate : public HdMayaDelegateCtx { std::string GetDisplacementShaderSource(const SdfPath& id) override; HDMAYA_API - VtValue GetMaterialParamValue( - const SdfPath& id, const TfToken& paramName) override; + VtValue GetMaterialParamValue(const SdfPath& id, const TfToken& paramName) override; HDMAYA_API HdMaterialParamVector GetMaterialParams(const SdfPath& id) override; @@ -235,32 +239,29 @@ class HdMayaSceneDelegate : public HdMayaDelegateCtx { VtValue GetMaterialResource(const SdfPath& id) override; HDMAYA_API - HdTextureResource::ID GetTextureResourceID( - const SdfPath& textureId) override; + HdTextureResource::ID GetTextureResourceID(const SdfPath& textureId) override; HDMAYA_API - HdTextureResourceSharedPtr GetTextureResource( - const SdfPath& textureId) override; + HdTextureResourceSharedPtr GetTextureResource(const SdfPath& textureId) override; private: bool _CreateMaterial(const SdfPath& id, const MObject& obj); - template - using AdapterMap = std::unordered_map; + template using AdapterMap = std::unordered_map; /// \brief Unordered Map storing the shape adapters. AdapterMap _shapeAdapters; /// \brief Unordered Map storing the light adapters. AdapterMap _lightAdapters; /// \brief Unordered Map storing the material adapters. - AdapterMap _materialAdapters; - std::vector _callbacks; - std::vector> _adaptersToRecreate; + AdapterMap _materialAdapters; + std::vector _callbacks; + std::vector> _adaptersToRecreate; std::vector> _adaptersToRebuild; - std::vector _addedNodes; - std::vector _materialTagsChanged; + std::vector _addedNodes; + std::vector _materialTagsChanged; SdfPath _fallbackMaterial; - bool _enableMaterials = false; + bool _enableMaterials = false; }; typedef std::shared_ptr MayaSceneDelegateSharedPtr; diff --git a/lib/usd/hdMaya/delegates/testDelegate.cpp b/lib/usd/hdMaya/delegates/testDelegate.cpp index 4138b1b784..e8874de228 100644 --- a/lib/usd/hdMaya/delegates/testDelegate.cpp +++ b/lib/usd/hdMaya/delegates/testDelegate.cpp @@ -15,18 +15,18 @@ // #include "testDelegate.h" -#include - #include +#include + PXR_NAMESPACE_OPEN_SCOPE -TF_DEFINE_ENV_SETTING( - HDMAYA_TEST_DELEGATE_FILE, "", "Path for HdMayaTestDelegate to load"); +TF_DEFINE_ENV_SETTING(HDMAYA_TEST_DELEGATE_FILE, "", "Path for HdMayaTestDelegate to load"); TF_DEFINE_PRIVATE_TOKENS(_tokens, (HdMayaTestDelegate)); -TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaDelegateRegistry, HdMayaTestDelegate) { +TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaDelegateRegistry, HdMayaTestDelegate) +{ if (!TfGetEnvSetting(HDMAYA_TEST_DELEGATE_FILE).empty()) { HdMayaDelegateRegistry::RegisterDelegate( _tokens->HdMayaTestDelegate, @@ -38,12 +38,13 @@ TF_REGISTRY_FUNCTION_WITH_TAG(HdMayaDelegateRegistry, HdMayaTestDelegate) { } HdMayaTestDelegate::HdMayaTestDelegate(const InitData& initData) - : HdMayaDelegate(initData) { - _delegate.reset( - new UsdImagingDelegate(initData.renderIndex, initData.delegateID)); + : HdMayaDelegate(initData) +{ + _delegate.reset(new UsdImagingDelegate(initData.renderIndex, initData.delegateID)); } -void HdMayaTestDelegate::Populate() { +void HdMayaTestDelegate::Populate() +{ _stage = UsdStage::Open(TfGetEnvSetting(HDMAYA_TEST_DELEGATE_FILE)); _delegate->Populate(_stage->GetPseudoRoot()); } diff --git a/lib/usd/hdMaya/delegates/testDelegate.h b/lib/usd/hdMaya/delegates/testDelegate.h index e6b56d2602..c17a614d33 100644 --- a/lib/usd/hdMaya/delegates/testDelegate.h +++ b/lib/usd/hdMaya/delegates/testDelegate.h @@ -16,19 +16,20 @@ #ifndef HDMAYA_TEST_DELEGATE_H #define HDMAYA_TEST_DELEGATE_H -#include +#include -#include #include +#include #include #include #include -#include +#include PXR_NAMESPACE_OPEN_SCOPE -class HdMayaTestDelegate : public HdMayaDelegate { +class HdMayaTestDelegate : public HdMayaDelegate +{ public: HdMayaTestDelegate(const InitData& initData); @@ -36,7 +37,7 @@ class HdMayaTestDelegate : public HdMayaDelegate { private: std::unique_ptr _delegate; - UsdStageRefPtr _stage; + UsdStageRefPtr _stage; }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/hdMaya/utils.cpp b/lib/usd/hdMaya/utils.cpp index 37610050a8..010046d3e0 100644 --- a/lib/usd/hdMaya/utils.cpp +++ b/lib/usd/hdMaya/utils.cpp @@ -15,8 +15,6 @@ // #include "utils.h" -#include - #include #include #include @@ -26,83 +24,88 @@ #include #include +#include + PXR_NAMESPACE_OPEN_SCOPE namespace { -class UdimTextureFactory : public GlfTextureFactoryBase { +class UdimTextureFactory : public GlfTextureFactoryBase +{ public: - virtual GlfTextureRefPtr New( - TfToken const& texturePath, - GlfImage::ImageOriginLocation originLocation = - GlfImage::OriginLowerLeft) const override { + virtual GlfTextureRefPtr + New(TfToken const& texturePath, + GlfImage::ImageOriginLocation originLocation = GlfImage::OriginLowerLeft) const override + { const GlfContextCaps& caps = GlfContextCaps::GetInstance(); return GlfUdimTexture::New( - texturePath, originLocation, + texturePath, + originLocation, UsdImaging_GetUdimTiles(texturePath, caps.maxArrayTextureLayers)); } - virtual GlfTextureRefPtr New( - TfTokenVector const& texturePaths, - GlfImage::ImageOriginLocation originLocation = - GlfImage::OriginLowerLeft) const override { + virtual GlfTextureRefPtr + New(TfTokenVector const& texturePaths, + GlfImage::ImageOriginLocation originLocation = GlfImage::OriginLowerLeft) const override + { return nullptr; } }; } // namespace -MObject GetConnectedFileNode(const MObject& obj, const TfToken& paramName) { - MStatus status; +MObject GetConnectedFileNode(const MObject& obj, const TfToken& paramName) +{ + MStatus status; MFnDependencyNode node(obj, &status); - if (ARCH_UNLIKELY(!status)) { return MObject::kNullObj; } + if (ARCH_UNLIKELY(!status)) { + return MObject::kNullObj; + } return GetConnectedFileNode(node, paramName); } -MObject GetConnectedFileNode( - const MFnDependencyNode& node, const TfToken& paramName) { +MObject GetConnectedFileNode(const MFnDependencyNode& node, const TfToken& paramName) +{ MPlugArray conns; node.findPlug(paramName.GetText(), true).connectedTo(conns, true, false); - if (conns.length() == 0) { return MObject::kNullObj; } + if (conns.length() == 0) { + return MObject::kNullObj; + } const auto ret = conns[0].node(); - if (ret.apiType() == MFn::kFileTexture) { return ret; } + if (ret.apiType() == MFn::kFileTexture) { + return ret; + } return MObject::kNullObj; } -TfToken GetFileTexturePath(const MFnDependencyNode& fileNode) { +TfToken GetFileTexturePath(const MFnDependencyNode& fileNode) +{ if (fileNode.findPlug(MayaAttrs::file::uvTilingMode, true).asShort() != 0) { - const TfToken ret{ - fileNode.findPlug(MayaAttrs::file::fileTextureNamePattern, true) - .asString() - .asChar()}; + const TfToken ret { + fileNode.findPlug(MayaAttrs::file::fileTextureNamePattern, true).asString().asChar() + }; return ret.IsEmpty() - ? TfToken{fileNode - .findPlug( - MayaAttrs::file:: - computedFileTextureNamePattern, - true) - .asString() - .asChar()} - : ret; + ? TfToken { fileNode.findPlug(MayaAttrs::file::computedFileTextureNamePattern, true) + .asString() + .asChar() } + : ret; } else { - const TfToken ret{ - MRenderUtil::exactFileTextureName(fileNode.object()).asChar()}; - return ret.IsEmpty() - ? TfToken{fileNode - .findPlug( - MayaAttrs::file::fileTextureName, true) - .asString() - .asChar()} - : ret; + const TfToken ret { MRenderUtil::exactFileTextureName(fileNode.object()).asChar() }; + return ret.IsEmpty() ? TfToken { fileNode.findPlug(MayaAttrs::file::fileTextureName, true) + .asString() + .asChar() } + : ret; } } -std::tuple GetFileTextureWrappingParams( - const MObject& fileObj) { - const std::tuple def{HdWrapClamp, HdWrapClamp}; - MStatus status; - MFnDependencyNode fileNode(fileObj, &status); - if (!status) { return def; } +std::tuple GetFileTextureWrappingParams(const MObject& fileObj) +{ + const std::tuple def { HdWrapClamp, HdWrapClamp }; + MStatus status; + MFnDependencyNode fileNode(fileObj, &status); + if (!status) { + return def; + } auto getWrap = [&fileNode](MObject& wrapAttr, MObject& mirrorAttr) { if (fileNode.findPlug(wrapAttr, true).asBool()) { @@ -115,14 +118,16 @@ std::tuple GetFileTextureWrappingParams( return HdWrapClamp; } }; - return std::tuple{ - getWrap(MayaAttrs::file::wrapU, MayaAttrs::file::mirrorU), - getWrap(MayaAttrs::file::wrapV, MayaAttrs::file::mirrorV)}; + return std::tuple { getWrap(MayaAttrs::file::wrapU, MayaAttrs::file::mirrorU), + getWrap(MayaAttrs::file::wrapV, MayaAttrs::file::mirrorV) }; } -HdTextureResourceSharedPtr GetFileTextureResource( - const MObject& fileObj, const TfToken& filePath, int maxTextureMemory) { - if (filePath.IsEmpty()) { return {}; } +HdTextureResourceSharedPtr +GetFileTextureResource(const MObject& fileObj, const TfToken& filePath, int maxTextureMemory) +{ + if (filePath.IsEmpty()) { + return {}; + } auto textureType = HdTextureType::Uv; if (GlfIsSupportedUdimTexture(filePath)) { textureType = HdTextureType::Udim; @@ -131,15 +136,13 @@ HdTextureResourceSharedPtr GetFileTextureResource( return {}; } // TODO: handle origin - const auto origin = GlfImage::OriginLowerLeft; + const auto origin = GlfImage::OriginLowerLeft; GlfTextureHandleRefPtr texture = nullptr; if (textureType == HdTextureType::Udim) { UdimTextureFactory factory; - texture = GlfTextureRegistry::GetInstance().GetTextureHandle( - filePath, origin, &factory); + texture = GlfTextureRegistry::GetInstance().GetTextureHandle(filePath, origin, &factory); } else { - texture = GlfTextureRegistry::GetInstance().GetTextureHandle( - filePath, origin); + texture = GlfTextureRegistry::GetInstance().GetTextureHandle(filePath, origin); } const auto wrapping = GetFileTextureWrappingParams(fileObj); @@ -149,11 +152,14 @@ HdTextureResourceSharedPtr GetFileTextureResource( return HdTextureResourceSharedPtr(new HdStSimpleTextureResource( texture, textureType, - std::get<0>(wrapping), std::get<1>(wrapping), + std::get<0>(wrapping), + std::get<1>(wrapping), #if USD_VERSION_NUM >= 1910 HdWrapClamp, #endif - HdMinFilterLinearMipmapLinear, HdMagFilterLinear, maxTextureMemory)); + HdMinFilterLinearMipmapLinear, + HdMagFilterLinear, + maxTextureMemory)); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/hdMaya/utils.h b/lib/usd/hdMaya/utils.h index ed9bffc6d9..36e2ac4b14 100644 --- a/lib/usd/hdMaya/utils.h +++ b/lib/usd/hdMaya/utils.h @@ -19,8 +19,14 @@ #ifndef HDMAYA_UTILS_H #define HDMAYA_UTILS_H -#include -#include +#include +#include + +#include +#include +#include +#include +#include #include #include @@ -32,21 +38,16 @@ #include #include -#include -#include -#include -#include -#include - -#include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE /// \brief Converts a Maya matrix to a double precision GfMatrix. /// \param mayaMat Maya `MMatrix` to be converted. /// \return `GfMatrix4d` equal to \p mayaMat. -inline GfMatrix4d GetGfMatrixFromMaya(const MMatrix& mayaMat) { +inline GfMatrix4d GetGfMatrixFromMaya(const MMatrix& mayaMat) +{ GfMatrix4d mat; memcpy(mat.GetArray(), mayaMat[0], sizeof(double) * 16); return mat; @@ -70,8 +71,7 @@ MObject GetConnectedFileNode(const MObject& obj, const TfToken& paramName); /// \return Maya object to a "file" shader node, `MObject::kNullObj` if there is /// no valid connection. HDMAYA_API -MObject GetConnectedFileNode( - const MFnDependencyNode& node, const TfToken& paramName); +MObject GetConnectedFileNode(const MFnDependencyNode& node, const TfToken& paramName); /// \brief Returns the texture file path from a "file" shader node. /// \param fileNode "file" shader node. @@ -90,8 +90,9 @@ TfToken GetFileTexturePath(const MFnDependencyNode& fileNode); /// \return Pointer to the Hydra Texture resource. HDMAYA_API HdTextureResourceSharedPtr GetFileTextureResource( - const MObject& fileObj, const TfToken& filePath, - int maxTextureMemory = 4 * 1024 * 1024); + const MObject& fileObj, + const TfToken& filePath, + int maxTextureMemory = 4 * 1024 * 1024); /// \brief Returns the texture wrapping parameters from a "file" shader node. /// \param fileObj "file" shader object. @@ -104,11 +105,11 @@ std::tuple GetFileTextureWrappingParams(const MObject& fileObj); /// May optionally filter by node type. The items in the list are also included /// in the set of items that are iterated over (assuming they pass the filter). template -inline void MapSelectionDescendents( - const MSelectionList& sel, FUNC func, - MFn::Type filterType = MFn::kInvalid) { - MStatus status; - MItDag itDag; +inline void +MapSelectionDescendents(const MSelectionList& sel, FUNC func, MFn::Type filterType = MFn::kInvalid) +{ + MStatus status; + MItDag itDag; MDagPath currentSelDag; MDagPath currentDescendentDag; for (MItSelectionList itSel(sel); !itSel.isDone(); itSel.next()) { @@ -125,7 +126,7 @@ inline void MapSelectionDescendents( // We make sure that no parent of the selected item is // also selected - otherwise, we would end up re-traversing the // same subtree - bool parentSelected = false; + bool parentSelected = false; MDagPath parentDag = currentSelDag; parentDag.pop(); for (; parentDag.length() > 0; parentDag.pop()) { @@ -134,7 +135,9 @@ inline void MapSelectionDescendents( break; } } - if (parentSelected) { continue; } + if (parentSelected) { + continue; + } // Now we iterate through all dag descendents of the current // selected item diff --git a/lib/usd/pxrUsdPreviewSurface/api.h b/lib/usd/pxrUsdPreviewSurface/api.h index 38b595751f..bc508950d9 100644 --- a/lib/usd/pxrUsdPreviewSurface/api.h +++ b/lib/usd/pxrUsdPreviewSurface/api.h @@ -19,21 +19,21 @@ #include #if defined(PXR_STATIC) -# define PXRUSDPREVIEWSURFACE_API -# define PXRUSDPREVIEWSURFACE_API_TEMPLATE_CLASS(...) -# define PXRUSDPREVIEWSURFACE_API_TEMPLATE_STRUCT(...) -# define PXRUSDPREVIEWSURFACE_LOCAL +#define PXRUSDPREVIEWSURFACE_API +#define PXRUSDPREVIEWSURFACE_API_TEMPLATE_CLASS(...) +#define PXRUSDPREVIEWSURFACE_API_TEMPLATE_STRUCT(...) +#define PXRUSDPREVIEWSURFACE_LOCAL #else -# if defined(PXRUSDPREVIEWSURFACE_EXPORTS) -# define PXRUSDPREVIEWSURFACE_API ARCH_EXPORT -# define PXRUSDPREVIEWSURFACE_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__) -# define PXRUSDPREVIEWSURFACE_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__) -# else -# define PXRUSDPREVIEWSURFACE_API ARCH_IMPORT -# define PXRUSDPREVIEWSURFACE_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__) -# define PXRUSDPREVIEWSURFACE_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__) -# endif -# define PXRUSDPREVIEWSURFACE_LOCAL ARCH_HIDDEN +#if defined(PXRUSDPREVIEWSURFACE_EXPORTS) +#define PXRUSDPREVIEWSURFACE_API ARCH_EXPORT +#define PXRUSDPREVIEWSURFACE_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__) +#define PXRUSDPREVIEWSURFACE_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__) +#else +#define PXRUSDPREVIEWSURFACE_API ARCH_IMPORT +#define PXRUSDPREVIEWSURFACE_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__) +#define PXRUSDPREVIEWSURFACE_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__) +#endif +#define PXRUSDPREVIEWSURFACE_LOCAL ARCH_HIDDEN #endif #endif diff --git a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurface.cpp b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurface.cpp index 6dbf2d8d59..9db97376ed 100644 --- a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurface.cpp +++ b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurface.cpp @@ -15,10 +15,9 @@ // #include "usdPreviewSurface.h" -#include - #include #include +#include #include #include @@ -35,24 +34,17 @@ #include #include - PXR_NAMESPACE_OPEN_SCOPE - TF_DEFINE_PUBLIC_TOKENS( PxrMayaUsdPreviewSurfaceTokens, PXRUSDPREVIEWSURFACE_USD_PREVIEW_SURFACE_TOKENS); /* static */ -void* -PxrMayaUsdPreviewSurface::creator() -{ - return new PxrMayaUsdPreviewSurface(); -} +void* PxrMayaUsdPreviewSurface::creator() { return new PxrMayaUsdPreviewSurface(); } /* static */ -MStatus -PxrMayaUsdPreviewSurface::initialize() +MStatus PxrMayaUsdPreviewSurface::initialize() { MStatus status; @@ -113,9 +105,7 @@ PxrMayaUsdPreviewSurface::initialize() CHECK_MSTATUS_AND_RETURN_IT(status); diffuseColorAttr = numericAttrFn.createColor( - PxrMayaUsdPreviewSurfaceTokens->DiffuseColorAttrName.GetText(), - "dc", - &status); + PxrMayaUsdPreviewSurfaceTokens->DiffuseColorAttrName.GetText(), "dc", &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = numericAttrFn.setDefault(0.18f, 0.18f, 0.18f); CHECK_MSTATUS_AND_RETURN_IT(status); @@ -141,9 +131,7 @@ PxrMayaUsdPreviewSurface::initialize() CHECK_MSTATUS_AND_RETURN_IT(status); emissiveColorAttr = numericAttrFn.createColor( - PxrMayaUsdPreviewSurfaceTokens->EmissiveColorAttrName.GetText(), - "ec", - &status); + PxrMayaUsdPreviewSurfaceTokens->EmissiveColorAttrName.GetText(), "ec", &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = numericAttrFn.setKeyable(true); CHECK_MSTATUS_AND_RETURN_IT(status); @@ -259,9 +247,7 @@ PxrMayaUsdPreviewSurface::initialize() CHECK_MSTATUS_AND_RETURN_IT(status); specularColorAttr = numericAttrFn.createColor( - PxrMayaUsdPreviewSurfaceTokens->SpecularColorAttrName.GetText(), - "spc", - &status); + PxrMayaUsdPreviewSurfaceTokens->SpecularColorAttrName.GetText(), "spc", &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = numericAttrFn.setKeyable(true); CHECK_MSTATUS_AND_RETURN_IT(status); @@ -285,9 +271,7 @@ PxrMayaUsdPreviewSurface::initialize() CHECK_MSTATUS_AND_RETURN_IT(status); outColorAttr = numericAttrFn.createColor( - PxrMayaUsdPreviewSurfaceTokens->OutColorAttrName.GetText(), - "oc", - &status); + PxrMayaUsdPreviewSurfaceTokens->OutColorAttrName.GetText(), "oc", &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = numericAttrFn.setWritable(false); CHECK_MSTATUS_AND_RETURN_IT(status); @@ -299,9 +283,7 @@ PxrMayaUsdPreviewSurface::initialize() CHECK_MSTATUS_AND_RETURN_IT(status); outTransparencyAttr = numericAttrFn.createColor( - PxrMayaUsdPreviewSurfaceTokens->OutTransparencyAttrName.GetText(), - "ot", - &status); + PxrMayaUsdPreviewSurfaceTokens->OutTransparencyAttrName.GetText(), "ot", &status); CHECK_MSTATUS_AND_RETURN_IT(status); status = numericAttrFn.setWritable(false); CHECK_MSTATUS_AND_RETURN_IT(status); @@ -318,7 +300,7 @@ PxrMayaUsdPreviewSurface::initialize() // (e.g. "surfaceShader"). The iterator will not traverse plugs that it // does not know affect connections downstream. For example, if this shader // has connections for both "diffuseColor" and "roughness", but we only - // declared the attribute affects relationship for "diffuseColor", then + // declared the attribute affects relationship for "diffuseColor", then // only "diffuseColor" would be visited and "roughness" would be skipped // during the traversal, since the plug upstream of the shading engine's // "surfaceShader" plug is this shader's "outColor" attribute, which Maya @@ -357,15 +339,10 @@ PxrMayaUsdPreviewSurface::initialize() } /* virtual */ -void -PxrMayaUsdPreviewSurface::postConstructor() -{ - setMPSafe(true); -} +void PxrMayaUsdPreviewSurface::postConstructor() { setMPSafe(true); } /* virtual */ -MStatus -PxrMayaUsdPreviewSurface::compute(const MPlug& plug, MDataBlock& dataBlock) +MStatus PxrMayaUsdPreviewSurface::compute(const MPlug& plug, MDataBlock& dataBlock) { MStatus status = MS::kUnknownParameter; @@ -383,8 +360,7 @@ PxrMayaUsdPreviewSurface::compute(const MPlug& plug, MDataBlock& dataBlock) CHECK_MSTATUS(status); const MFloatVector diffuseColor = diffuseColorData.asFloatVector(); - MDataHandle outColorHandle = - dataBlock.outputValue(outColorAttr, &status); + MDataHandle outColorHandle = dataBlock.outputValue(outColorAttr, &status); CHECK_MSTATUS(status); outColorHandle.asFloatVector() = diffuseColor; status = dataBlock.setClean(outColorAttr); @@ -396,13 +372,9 @@ PxrMayaUsdPreviewSurface::compute(const MPlug& plug, MDataBlock& dataBlock) CHECK_MSTATUS(status); const float opacity = opacityData.asFloat(); - const float transparency = 1.0f - opacity; - const MFloatVector transparencyColor( - transparency, - transparency, - transparency); - MDataHandle outTransparencyHandle = - dataBlock.outputValue(outTransparencyAttr, &status); + const float transparency = 1.0f - opacity; + const MFloatVector transparencyColor(transparency, transparency, transparency); + MDataHandle outTransparencyHandle = dataBlock.outputValue(outTransparencyAttr, &status); CHECK_MSTATUS(status); outTransparencyHandle.asFloatVector() = transparencyColor; status = dataBlock.setClean(outTransparencyAttr); @@ -412,14 +384,12 @@ PxrMayaUsdPreviewSurface::compute(const MPlug& plug, MDataBlock& dataBlock) return status; } -PxrMayaUsdPreviewSurface::PxrMayaUsdPreviewSurface() : MPxNode() +PxrMayaUsdPreviewSurface::PxrMayaUsdPreviewSurface() + : MPxNode() { } /* virtual */ -PxrMayaUsdPreviewSurface::~PxrMayaUsdPreviewSurface() -{ -} - +PxrMayaUsdPreviewSurface::~PxrMayaUsdPreviewSurface() { } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurface.h b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurface.h index 90bbcc5bae..ab0bc823e1 100644 --- a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurface.h +++ b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurface.h @@ -20,9 +20,8 @@ #include "api.h" -#include - #include +#include #include #include @@ -32,63 +31,49 @@ #include #include - PXR_NAMESPACE_OPEN_SCOPE - -#define PXRUSDPREVIEWSURFACE_USD_PREVIEW_SURFACE_TOKENS \ - ((ClearcoatAttrName, "clearcoat")) \ - ((ClearcoatRoughnessAttrName, "clearcoatRoughness")) \ - ((DiffuseColorAttrName, "diffuseColor")) \ - ((DisplacementAttrName, "displacement")) \ - ((EmissiveColorAttrName, "emissiveColor")) \ - ((IorAttrName, "ior")) \ - ((MetallicAttrName, "metallic")) \ - ((NormalAttrName, "normal")) \ - ((OcclusionAttrName, "occlusion")) \ - ((OpacityAttrName, "opacity")) \ - ((RoughnessAttrName, "roughness")) \ - ((SpecularColorAttrName, "specularColor")) \ - ((UseSpecularWorkflowAttrName, "useSpecularWorkflow")) \ - ((OutColorAttrName, "outColor")) \ - ((OutTransparencyAttrName, "outTransparency")) \ - ((niceName, "USD Preview Surface")) \ - ((exportDescription, "Exports the bound shader as a USD preview surface UsdShade network.")) \ - ((importDescription, "Search for a USD preview surface UsdShade network to import.")) - +#define PXRUSDPREVIEWSURFACE_USD_PREVIEW_SURFACE_TOKENS \ + ((ClearcoatAttrName, "clearcoat"))((ClearcoatRoughnessAttrName, "clearcoatRoughness"))( \ + (DiffuseColorAttrName, "diffuseColor"))((DisplacementAttrName, "displacement"))( \ + (EmissiveColorAttrName, "emissiveColor"))((IorAttrName, "ior"))( \ + (MetallicAttrName, "metallic"))((NormalAttrName, "normal"))( \ + (OcclusionAttrName, "occlusion"))((OpacityAttrName, "opacity"))( \ + (RoughnessAttrName, "roughness"))((SpecularColorAttrName, "specularColor"))( \ + (UseSpecularWorkflowAttrName, "useSpecularWorkflow"))((OutColorAttrName, "outColor"))( \ + (OutTransparencyAttrName, "outTransparency"))((niceName, "USD Preview Surface"))( \ + (exportDescription, \ + "Exports the bound shader as a USD preview surface UsdShade network."))( \ + (importDescription, "Search for a USD preview surface UsdShade network to import.")) TF_DECLARE_PUBLIC_TOKENS( PxrMayaUsdPreviewSurfaceTokens, PXRUSDPREVIEWSURFACE_API, PXRUSDPREVIEWSURFACE_USD_PREVIEW_SURFACE_TOKENS); - class PxrMayaUsdPreviewSurface : public MPxNode { - public: - PXRUSDPREVIEWSURFACE_API - static void* creator(); +public: + PXRUSDPREVIEWSURFACE_API + static void* creator(); - PXRUSDPREVIEWSURFACE_API - static MStatus initialize(); + PXRUSDPREVIEWSURFACE_API + static MStatus initialize(); - PXRUSDPREVIEWSURFACE_API - void postConstructor() override; + PXRUSDPREVIEWSURFACE_API + void postConstructor() override; - PXRUSDPREVIEWSURFACE_API - MStatus compute(const MPlug& plug, MDataBlock& dataBlock) override; + PXRUSDPREVIEWSURFACE_API + MStatus compute(const MPlug& plug, MDataBlock& dataBlock) override; - private: - PxrMayaUsdPreviewSurface(); - ~PxrMayaUsdPreviewSurface() override; +private: + PxrMayaUsdPreviewSurface(); + ~PxrMayaUsdPreviewSurface() override; - PxrMayaUsdPreviewSurface(const PxrMayaUsdPreviewSurface&) = delete; - PxrMayaUsdPreviewSurface& operator=( - const PxrMayaUsdPreviewSurface&) = delete; + PxrMayaUsdPreviewSurface(const PxrMayaUsdPreviewSurface&) = delete; + PxrMayaUsdPreviewSurface& operator=(const PxrMayaUsdPreviewSurface&) = delete; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfacePlugin.cpp b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfacePlugin.cpp index 542b41f6b9..ebd1a77646 100644 --- a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfacePlugin.cpp +++ b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfacePlugin.cpp @@ -24,15 +24,15 @@ #include #include -#include -#include -#include -#include - #include #include #include +#include +#include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE namespace { @@ -104,12 +104,12 @@ MStatus PxrMayaUsdPreviewSurfacePlugin::finalize( } namespace { - bool _registered = false; +bool _registered = false; } /* static */ -MStatus -PxrMayaUsdPreviewSurfacePlugin::registerFragments() { +MStatus PxrMayaUsdPreviewSurfacePlugin::registerFragments() +{ if (_registered) { return MS::kSuccess; } @@ -120,8 +120,8 @@ PxrMayaUsdPreviewSurfacePlugin::registerFragments() { } /* static */ -MStatus -PxrMayaUsdPreviewSurfacePlugin::deregisterFragments() { +MStatus PxrMayaUsdPreviewSurfacePlugin::deregisterFragments() +{ if (!_registered) { return MS::kSuccess; } @@ -132,8 +132,8 @@ PxrMayaUsdPreviewSurfacePlugin::deregisterFragments() { } /* static */ -void -PxrMayaUsdPreviewSurfacePlugin::RegisterPreviewSurfaceReader(const MString& typeName) { +void PxrMayaUsdPreviewSurfacePlugin::RegisterPreviewSurfaceReader(const MString& typeName) +{ TfToken typeNameToken(typeName.asChar()); // There is obvious ambiguity here as soon as two plugins register a UsdPreviewSurface node. @@ -144,20 +144,19 @@ PxrMayaUsdPreviewSurfacePlugin::RegisterPreviewSurfaceReader(const MString& type [typeNameToken](const UsdMayaPrimReaderArgs& readerArgs) { return std::make_shared(readerArgs, typeNameToken); }); - } /* static */ -void -PxrMayaUsdPreviewSurfacePlugin::RegisterPreviewSurfaceWriter(const MString& typeName) { +void PxrMayaUsdPreviewSurfacePlugin::RegisterPreviewSurfaceWriter(const MString& typeName) +{ TfToken typeNameToken(typeName.asChar()); UsdMayaShaderWriterRegistry::Register( typeNameToken, &PxrMayaUsdPreviewSurface_Writer::CanExport, [](const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) { + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) { return std::make_shared(depNodeFn, usdPath, jobCtx); }); } diff --git a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfacePlugin.h b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfacePlugin.h index 4a86df5bf5..e8eded1229 100644 --- a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfacePlugin.h +++ b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfacePlugin.h @@ -18,8 +18,8 @@ #include "api.h" -#include #include +#include #include @@ -31,7 +31,8 @@ PXR_NAMESPACE_OPEN_SCOPE /// Preview surface support requires plugin registration of node classes, node /// data, and draw support. This class provides this service. Each client is expected /// to provide a separate typeName and typeId to ensure proper plugin registration. -class PxrMayaUsdPreviewSurfacePlugin { +class PxrMayaUsdPreviewSurfacePlugin +{ public: /// Initialize a UsdPreviewSurface dependency node named \p typeName with a unique \p typeId for /// the \p plugin using the registrant id \p registrantId for the render overrides. diff --git a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceReader.cpp b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceReader.cpp index c8d98996d9..0019aa2139 100644 --- a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceReader.cpp +++ b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceReader.cpp @@ -20,11 +20,11 @@ #include #include -#include #include #include #include #include +#include #include #include #include @@ -50,7 +50,8 @@ REGISTER_SHADING_MODE_IMPORT_MATERIAL_CONVERSION( PxrMayaUsdPreviewSurfaceTokens->importDescription); PxrMayaUsdPreviewSurface_Reader::PxrMayaUsdPreviewSurface_Reader( - const UsdMayaPrimReaderArgs& readArgs, const TfToken& mayaTypeName) + const UsdMayaPrimReaderArgs& readArgs, + const TfToken& mayaTypeName) : UsdMayaShaderReader(readArgs) , _mayaTypeName(mayaTypeName) { @@ -59,7 +60,7 @@ PxrMayaUsdPreviewSurface_Reader::PxrMayaUsdPreviewSurface_Reader( /* virtual */ bool PxrMayaUsdPreviewSurface_Reader::Read(UsdMayaPrimReaderContext* context) { - const UsdPrim& prim = _GetArgs().GetUsdPrim(); + const UsdPrim& prim = _GetArgs().GetUsdPrim(); UsdShadeShader shaderSchema = UsdShadeShader(prim); if (!shaderSchema) { return false; @@ -102,20 +103,16 @@ bool PxrMayaUsdPreviewSurface_Reader::Read(UsdMayaPrimReaderContext* context) } // "useSpecularWorkflow" is an int in USD, but a boolean in Maya. - if (baseName == PxrMayaUsdPreviewSurfaceTokens->UseSpecularWorkflowAttrName && - inputVal.IsHolding()) { - inputVal = (inputVal.UncheckedGet() == 0) ? - false : - true; + if (baseName == PxrMayaUsdPreviewSurfaceTokens->UseSpecularWorkflowAttrName + && inputVal.IsHolding()) { + inputVal = (inputVal.UncheckedGet() == 0) ? false : true; } if (UsdMayaReadUtil::SetMayaAttr( mayaAttr, inputVal, /* unlinearizeColors = */ false)) { - UsdMayaReadUtil::SetMayaAttrKeyableState( - mayaAttr, - input.GetAttr().GetVariability()); + UsdMayaReadUtil::SetMayaAttrKeyableState(mayaAttr, input.GetAttr().GetVariability()); } } @@ -125,7 +122,7 @@ bool PxrMayaUsdPreviewSurface_Reader::Read(UsdMayaPrimReaderContext* context) /* virtual */ TfToken PxrMayaUsdPreviewSurface_Reader::GetMayaNameForUsdAttrName(const TfToken& usdAttrName) const { - TfToken baseName; + TfToken baseName; UsdShadeAttributeType attrType; std::tie(baseName, attrType) = UsdShadeUtils::GetBaseNameAndType(usdAttrName); diff --git a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceReader.h b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceReader.h index 1000266486..111b0cd11b 100644 --- a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceReader.h +++ b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceReader.h @@ -21,13 +21,15 @@ #include #include -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE -class PxrMayaUsdPreviewSurface_Reader : public UsdMayaShaderReader { +class PxrMayaUsdPreviewSurface_Reader : public UsdMayaShaderReader +{ TfToken _mayaTypeName; + public: PxrMayaUsdPreviewSurface_Reader(const UsdMayaPrimReaderArgs&, const TfToken& mayaTypeName); @@ -38,5 +40,4 @@ class PxrMayaUsdPreviewSurface_Reader : public UsdMayaShaderReader { PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceShadingNodeOverride.cpp b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceShadingNodeOverride.cpp index a51c8ee97c..d94e5b7b2a 100644 --- a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceShadingNodeOverride.cpp +++ b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceShadingNodeOverride.cpp @@ -15,19 +15,17 @@ // #include "usdPreviewSurfaceShadingNodeOverride.h" -#include - -#include - #include -#include +#include +#include #include #include #include #include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -44,47 +42,37 @@ PxrMayaUsdPreviewSurfaceShadingNodeOverride::creator(const MObject& obj) } PxrMayaUsdPreviewSurfaceShadingNodeOverride::PxrMayaUsdPreviewSurfaceShadingNodeOverride( - const MObject& obj) : - MPxSurfaceShadingNodeOverride(obj) + const MObject& obj) + : MPxSurfaceShadingNodeOverride(obj) { } /* virtual */ -PxrMayaUsdPreviewSurfaceShadingNodeOverride::~PxrMayaUsdPreviewSurfaceShadingNodeOverride() -{ -} +PxrMayaUsdPreviewSurfaceShadingNodeOverride::~PxrMayaUsdPreviewSurfaceShadingNodeOverride() { } /* virtual */ -MString -PxrMayaUsdPreviewSurfaceShadingNodeOverride::primaryColorParameter() const +MString PxrMayaUsdPreviewSurfaceShadingNodeOverride::primaryColorParameter() const { return "diffuseColor"; } /* virtual */ -MString -PxrMayaUsdPreviewSurfaceShadingNodeOverride::transparencyParameter() const +MString PxrMayaUsdPreviewSurfaceShadingNodeOverride::transparencyParameter() const { return "transparency"; } /* virtual */ -MString -PxrMayaUsdPreviewSurfaceShadingNodeOverride::bumpAttribute() const -{ - return "normal"; -} +MString PxrMayaUsdPreviewSurfaceShadingNodeOverride::bumpAttribute() const { return "normal"; } /* virtual */ -MHWRender::DrawAPI -PxrMayaUsdPreviewSurfaceShadingNodeOverride::supportedDrawAPIs() const +MHWRender::DrawAPI PxrMayaUsdPreviewSurfaceShadingNodeOverride::supportedDrawAPIs() const { return MHWRender::kAllDevices; } /* virtual */ -MString -PxrMayaUsdPreviewSurfaceShadingNodeOverride::fragmentName() const +MString PxrMayaUsdPreviewSurfaceShadingNodeOverride::fragmentName() const { // This override uses the "Core" directly since the shading node does its // own conversion from "opacity" to "transparency". @@ -92,9 +80,8 @@ PxrMayaUsdPreviewSurfaceShadingNodeOverride::fragmentName() const } /* virtual */ -void -PxrMayaUsdPreviewSurfaceShadingNodeOverride::getCustomMappings( - MHWRender::MAttributeParameterMappingList& mappings) +void PxrMayaUsdPreviewSurfaceShadingNodeOverride::getCustomMappings( + MHWRender::MAttributeParameterMappingList& mappings) { // The control on the Maya shader is 'opacity' (1.0 is opaque), but Maya // prefers to work in terms of transparency (0.0 is opaque). We want Maya @@ -108,5 +95,4 @@ PxrMayaUsdPreviewSurfaceShadingNodeOverride::getCustomMappings( mappings.append(transparencyMapping); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceShadingNodeOverride.h b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceShadingNodeOverride.h index af9dd68e53..ce310d69ad 100644 --- a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceShadingNodeOverride.h +++ b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceShadingNodeOverride.h @@ -26,50 +26,42 @@ #include #include - PXR_NAMESPACE_OPEN_SCOPE -class PxrMayaUsdPreviewSurfaceShadingNodeOverride : - public MHWRender::MPxSurfaceShadingNodeOverride +class PxrMayaUsdPreviewSurfaceShadingNodeOverride : public MHWRender::MPxSurfaceShadingNodeOverride { - public: - - PXRUSDPREVIEWSURFACE_API - static MHWRender::MPxSurfaceShadingNodeOverride* creator( - const MObject& obj); - - PXRUSDPREVIEWSURFACE_API - PxrMayaUsdPreviewSurfaceShadingNodeOverride(const MObject& obj); - PXRUSDPREVIEWSURFACE_API - ~PxrMayaUsdPreviewSurfaceShadingNodeOverride() override; +public: + PXRUSDPREVIEWSURFACE_API + static MHWRender::MPxSurfaceShadingNodeOverride* creator(const MObject& obj); - // MPxSurfaceShadingNodeOverride Overrides. + PXRUSDPREVIEWSURFACE_API + PxrMayaUsdPreviewSurfaceShadingNodeOverride(const MObject& obj); + PXRUSDPREVIEWSURFACE_API + ~PxrMayaUsdPreviewSurfaceShadingNodeOverride() override; - PXRUSDPREVIEWSURFACE_API - MString primaryColorParameter() const override; + // MPxSurfaceShadingNodeOverride Overrides. - PXRUSDPREVIEWSURFACE_API - MString transparencyParameter() const override; + PXRUSDPREVIEWSURFACE_API + MString primaryColorParameter() const override; - PXRUSDPREVIEWSURFACE_API - MString bumpAttribute() const override; + PXRUSDPREVIEWSURFACE_API + MString transparencyParameter() const override; + PXRUSDPREVIEWSURFACE_API + MString bumpAttribute() const override; - // MPxShadingNodeOverride Overrides. + // MPxShadingNodeOverride Overrides. - PXRUSDPREVIEWSURFACE_API - MHWRender::DrawAPI supportedDrawAPIs() const override; + PXRUSDPREVIEWSURFACE_API + MHWRender::DrawAPI supportedDrawAPIs() const override; - PXRUSDPREVIEWSURFACE_API - MString fragmentName() const override; + PXRUSDPREVIEWSURFACE_API + MString fragmentName() const override; - PXRUSDPREVIEWSURFACE_API - void getCustomMappings( - MHWRender::MAttributeParameterMappingList& mappings) override; + PXRUSDPREVIEWSURFACE_API + void getCustomMappings(MHWRender::MAttributeParameterMappingList& mappings) override; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceWriter.cpp b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceWriter.cpp index 6f57898270..ec4bab7ce5 100644 --- a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceWriter.cpp +++ b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceWriter.cpp @@ -15,18 +15,18 @@ // #include "usdPreviewSurfaceWriter.h" -#include #include +#include #include #include #include #include -#include #include #include #include #include +#include #include #include #include @@ -60,13 +60,12 @@ PxrMayaUsdPreviewSurface_Writer::CanExport(const UsdMayaJobExportArgs& exportArg } PxrMayaUsdPreviewSurface_Writer::PxrMayaUsdPreviewSurface_Writer( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaShaderWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaShaderWriter(depNodeFn, usdPath, jobCtx) { - UsdShadeShader shaderSchema = - UsdShadeShader::Define(GetUsdStage(), GetUsdPath()); + UsdShadeShader shaderSchema = UsdShadeShader::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( shaderSchema, "Could not define UsdShadeShader at path '%s'\n", @@ -85,38 +84,31 @@ PxrMayaUsdPreviewSurface_Writer::PxrMayaUsdPreviewSurface_Writer( } // Surface Output - shaderSchema.CreateOutput( - UsdShadeTokens->surface, - SdfValueTypeNames->Token); + shaderSchema.CreateOutput(UsdShadeTokens->surface, SdfValueTypeNames->Token); // Displacement Output - shaderSchema.CreateOutput( - UsdShadeTokens->displacement, - SdfValueTypeNames->Token); + shaderSchema.CreateOutput(UsdShadeTokens->displacement, SdfValueTypeNames->Token); } -static -bool -_AuthorShaderInputFromShadingNodeAttr( - const MFnDependencyNode& depNodeFn, - UsdShadeShader& shaderSchema, - const TfToken& shaderInputName, - const SdfValueTypeName& shaderInputTypeName, - const UsdTimeCode usdTime, - const bool mayaBoolAsUsdInt = false) +static bool _AuthorShaderInputFromShadingNodeAttr( + const MFnDependencyNode& depNodeFn, + UsdShadeShader& shaderSchema, + const TfToken& shaderInputName, + const SdfValueTypeName& shaderInputTypeName, + const UsdTimeCode usdTime, + const bool mayaBoolAsUsdInt = false) { MStatus status; // If the USD shader input type is int but the Maya attribute type is bool, // we do a conversion (e.g. for "useSpecularWorkflow"). - const bool convertBoolToInt = (mayaBoolAsUsdInt && - (shaderInputTypeName == SdfValueTypeNames->Int)); - - MPlug shadingNodePlug = - depNodeFn.findPlug( - shaderInputName.GetText(), - /* wantNetworkedPlug = */ true, - &status); + const bool convertBoolToInt + = (mayaBoolAsUsdInt && (shaderInputTypeName == SdfValueTypeNames->Int)); + + MPlug shadingNodePlug = depNodeFn.findPlug( + shaderInputName.GetText(), + /* wantNetworkedPlug = */ true, + &status); if (status != MS::kSuccess) { return false; } @@ -129,20 +121,16 @@ _AuthorShaderInputFromShadingNodeAttr( if (UsdMayaUtil::IsAuthored(shadingNodePlug)) { // Color values are all linear on the shader, so do not re-linearize // them. - VtValue value = - UsdMayaWriteUtil::GetVtValue( - shadingNodePlug, - convertBoolToInt ? - SdfValueTypeNames->Bool : - shaderInputTypeName, - /* linearizeColors = */ false); + VtValue value = UsdMayaWriteUtil::GetVtValue( + shadingNodePlug, + convertBoolToInt ? SdfValueTypeNames->Bool : shaderInputTypeName, + /* linearizeColors = */ false); if (value.IsEmpty()) { return false; } - UsdShadeInput shaderInput = - shaderSchema.CreateInput(shaderInputName, shaderInputTypeName); + UsdShadeInput shaderInput = shaderSchema.CreateInput(shaderInputName, shaderInputTypeName); // For attributes that are the destination of a connection, we create // the input on the shader but we do *not* author a value for it. We @@ -166,8 +154,7 @@ _AuthorShaderInputFromShadingNodeAttr( } /* virtual */ -void -PxrMayaUsdPreviewSurface_Writer::Write(const UsdTimeCode& usdTime) +void PxrMayaUsdPreviewSurface_Writer::Write(const UsdTimeCode& usdTime) { UsdMayaShaderWriter::Write(usdTime); @@ -295,8 +282,7 @@ PxrMayaUsdPreviewSurface_Writer::Write(const UsdTimeCode& usdTime) /* virtual */ TfToken -PxrMayaUsdPreviewSurface_Writer::GetShadingAttributeNameForMayaAttrName( - const TfToken& mayaAttrName) +PxrMayaUsdPreviewSurface_Writer::GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) { if (!_usdPrim) { return TfToken(); @@ -305,36 +291,30 @@ PxrMayaUsdPreviewSurface_Writer::GetShadingAttributeNameForMayaAttrName( TfToken usdAttrName; if (mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->OutColorAttrName) { - usdAttrName = - TfToken( - TfStringPrintf( - "%s%s", - UsdShadeTokens->outputs.GetText(), - UsdShadeTokens->surface.GetText()).c_str()); - } - else if (mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->ClearcoatAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->ClearcoatRoughnessAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->DiffuseColorAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->DisplacementAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->EmissiveColorAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->IorAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->MetallicAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->NormalAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->OcclusionAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->OpacityAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->RoughnessAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->SpecularColorAttrName || - mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->UseSpecularWorkflowAttrName) { - usdAttrName = - TfToken( - TfStringPrintf( - "%s%s", - UsdShadeTokens->inputs.GetText(), - mayaAttrName.GetText()).c_str()); + usdAttrName = TfToken( + TfStringPrintf( + "%s%s", UsdShadeTokens->outputs.GetText(), UsdShadeTokens->surface.GetText()) + .c_str()); + } else if ( + mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->ClearcoatAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->ClearcoatRoughnessAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->DiffuseColorAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->DisplacementAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->EmissiveColorAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->IorAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->MetallicAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->NormalAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->OcclusionAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->OpacityAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->RoughnessAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->SpecularColorAttrName + || mayaAttrName == PxrMayaUsdPreviewSurfaceTokens->UseSpecularWorkflowAttrName) { + usdAttrName = TfToken( + TfStringPrintf("%s%s", UsdShadeTokens->inputs.GetText(), mayaAttrName.GetText()) + .c_str()); } return usdAttrName; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceWriter.h b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceWriter.h index 4d360e5a4e..aca10064b9 100644 --- a/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceWriter.h +++ b/lib/usd/pxrUsdPreviewSurface/usdPreviewSurfaceWriter.h @@ -21,35 +21,30 @@ #include #include -#include #include +#include #include #include #include - PXR_NAMESPACE_OPEN_SCOPE - class PxrMayaUsdPreviewSurface_Writer : public UsdMayaShaderWriter { - public: - PxrMayaUsdPreviewSurface_Writer( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); +public: + PxrMayaUsdPreviewSurface_Writer( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); - static ContextSupport CanExport(const UsdMayaJobExportArgs&); + static ContextSupport CanExport(const UsdMayaJobExportArgs&); - void Write(const UsdTimeCode& usdTime) override; + void Write(const UsdTimeCode& usdTime) override; - TfToken GetShadingAttributeNameForMayaAttrName( - const TfToken& mayaAttrName) override; + TfToken GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) override; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/schemas/ALMayaReference.cpp b/lib/usd/schemas/ALMayaReference.cpp index 4fff7dac0c..bf56598c5f 100644 --- a/lib/usd/schemas/ALMayaReference.cpp +++ b/lib/usd/schemas/ALMayaReference.cpp @@ -25,9 +25,8 @@ PXR_NAMESPACE_OPEN_SCOPE // Register the schema with the TfType system. TF_REGISTRY_FUNCTION(TfType) { - TfType::Define >(); - + TfType::Define>(); + // Register the usd prim typename as an alias under UsdSchemaBase. This // enables one to call // TfType::Find().FindDerivedByName("ALMayaReference") @@ -37,13 +36,11 @@ TF_REGISTRY_FUNCTION(TfType) } /* virtual */ -MayaUsd_SchemasALMayaReference::~MayaUsd_SchemasALMayaReference() -{ -} +MayaUsd_SchemasALMayaReference::~MayaUsd_SchemasALMayaReference() { } /* static */ MayaUsd_SchemasALMayaReference -MayaUsd_SchemasALMayaReference::Get(const UsdStagePtr &stage, const SdfPath &path) +MayaUsd_SchemasALMayaReference::Get(const UsdStagePtr& stage, const SdfPath& path) { if (!stage) { TF_CODING_ERROR("Invalid stage"); @@ -54,53 +51,44 @@ MayaUsd_SchemasALMayaReference::Get(const UsdStagePtr &stage, const SdfPath &pat /* static */ MayaUsd_SchemasALMayaReference -MayaUsd_SchemasALMayaReference::Define( - const UsdStagePtr &stage, const SdfPath &path) +MayaUsd_SchemasALMayaReference::Define(const UsdStagePtr& stage, const SdfPath& path) { static TfToken usdPrimTypeName("ALMayaReference"); if (!stage) { TF_CODING_ERROR("Invalid stage"); return MayaUsd_SchemasALMayaReference(); } - return MayaUsd_SchemasALMayaReference( - stage->DefinePrim(path, usdPrimTypeName)); + return MayaUsd_SchemasALMayaReference(stage->DefinePrim(path, usdPrimTypeName)); } /* virtual */ -UsdSchemaType MayaUsd_SchemasALMayaReference::_GetSchemaType() const { +UsdSchemaType MayaUsd_SchemasALMayaReference::_GetSchemaType() const +{ return MayaUsd_SchemasALMayaReference::schemaType; } /* static */ -const TfType & -MayaUsd_SchemasALMayaReference::_GetStaticTfType() +const TfType& MayaUsd_SchemasALMayaReference::_GetStaticTfType() { static TfType tfType = TfType::Find(); return tfType; } /* static */ -bool -MayaUsd_SchemasALMayaReference::_IsTypedSchema() +bool MayaUsd_SchemasALMayaReference::_IsTypedSchema() { static bool isTyped = _GetStaticTfType().IsA(); return isTyped; } /* virtual */ -const TfType & -MayaUsd_SchemasALMayaReference::_GetTfType() const -{ - return _GetStaticTfType(); -} +const TfType& MayaUsd_SchemasALMayaReference::_GetTfType() const { return _GetStaticTfType(); } /*static*/ -const TfTokenVector& -MayaUsd_SchemasALMayaReference::GetSchemaAttributeNames(bool includeInherited) +const TfTokenVector& MayaUsd_SchemasALMayaReference::GetSchemaAttributeNames(bool includeInherited) { static TfTokenVector localNames; - static TfTokenVector allNames = - MayaUsd_SchemasMayaReference::GetSchemaAttributeNames(true); + static TfTokenVector allNames = MayaUsd_SchemasMayaReference::GetSchemaAttributeNames(true); if (includeInherited) return allNames; diff --git a/lib/usd/schemas/ALMayaReference.h b/lib/usd/schemas/ALMayaReference.h index 7e5248930c..c7a132e9ce 100644 --- a/lib/usd/schemas/ALMayaReference.h +++ b/lib/usd/schemas/ALMayaReference.h @@ -18,18 +18,18 @@ /// \file mayaUsd_Schemas/ALMayaReference.h -#include #include #include #include #include #include #include +#include #include #include -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -55,7 +55,7 @@ class MayaUsd_SchemasALMayaReference : public MayaUsd_SchemasMayaReference /// Equivalent to MayaUsd_SchemasALMayaReference::Get(prim.GetStage(), prim.GetPath()) /// for a \em valid \p prim, but will not immediately throw an error for /// an invalid \p prim - explicit MayaUsd_SchemasALMayaReference(const UsdPrim& prim=UsdPrim()) + explicit MayaUsd_SchemasALMayaReference(const UsdPrim& prim = UsdPrim()) : MayaUsd_SchemasMayaReference(prim) { } @@ -76,8 +76,7 @@ class MayaUsd_SchemasALMayaReference : public MayaUsd_SchemasMayaReference /// class and all its ancestor classes. Does not include attributes that /// may be authored by custom/extended methods of the schemas involved. MAYAUSD_SCHEMAS_API - static const TfTokenVector & - GetSchemaAttributeNames(bool includeInherited=true); + static const TfTokenVector& GetSchemaAttributeNames(bool includeInherited = true); /// Return a MayaUsd_SchemasALMayaReference holding the prim adhering to this /// schema at \p path on \p stage. If no prim exists at \p path on @@ -89,8 +88,7 @@ class MayaUsd_SchemasALMayaReference : public MayaUsd_SchemasMayaReference /// \endcode /// MAYAUSD_SCHEMAS_API - static MayaUsd_SchemasALMayaReference - Get(const UsdStagePtr &stage, const SdfPath &path); + static MayaUsd_SchemasALMayaReference Get(const UsdStagePtr& stage, const SdfPath& path); /// Attempt to ensure a \a UsdPrim adhering to this schema at \p path /// is defined (according to UsdPrim::IsDefined()) on this stage. @@ -115,8 +113,7 @@ class MayaUsd_SchemasALMayaReference : public MayaUsd_SchemasMayaReference /// the opinion at the current EditTarget. /// MAYAUSD_SCHEMAS_API - static MayaUsd_SchemasALMayaReference - Define(const UsdStagePtr &stage, const SdfPath &path); + static MayaUsd_SchemasALMayaReference Define(const UsdStagePtr& stage, const SdfPath& path); protected: /// Returns the type of schema this class belongs to. @@ -129,21 +126,21 @@ class MayaUsd_SchemasALMayaReference : public MayaUsd_SchemasMayaReference // needs to invoke _GetStaticTfType. friend class UsdSchemaRegistry; MAYAUSD_SCHEMAS_API - static const TfType &_GetStaticTfType(); + static const TfType& _GetStaticTfType(); static bool _IsTypedSchema(); // override SchemaBase virtuals. MAYAUSD_SCHEMAS_API - const TfType &_GetTfType() const override; + const TfType& _GetTfType() const override; public: // ===================================================================== // - // Feel free to add custom code below this line, it will be preserved by - // the code generator. + // Feel free to add custom code below this line, it will be preserved by + // the code generator. // - // Just remember to: - // - Close the class declaration with }; + // Just remember to: + // - Close the class declaration with }; // - Close the namespace with PXR_NAMESPACE_CLOSE_SCOPE // - Close the include guard with #endif // ===================================================================== // diff --git a/lib/usd/schemas/MayaReference.cpp b/lib/usd/schemas/MayaReference.cpp index 06a0f78574..919ff3d174 100644 --- a/lib/usd/schemas/MayaReference.cpp +++ b/lib/usd/schemas/MayaReference.cpp @@ -25,9 +25,8 @@ PXR_NAMESPACE_OPEN_SCOPE // Register the schema with the TfType system. TF_REGISTRY_FUNCTION(TfType) { - TfType::Define >(); - + TfType::Define>(); + // Register the usd prim typename as an alias under UsdSchemaBase. This // enables one to call // TfType::Find().FindDerivedByName("MayaReference") @@ -37,13 +36,11 @@ TF_REGISTRY_FUNCTION(TfType) } /* virtual */ -MayaUsd_SchemasMayaReference::~MayaUsd_SchemasMayaReference() -{ -} +MayaUsd_SchemasMayaReference::~MayaUsd_SchemasMayaReference() { } /* static */ MayaUsd_SchemasMayaReference -MayaUsd_SchemasMayaReference::Get(const UsdStagePtr &stage, const SdfPath &path) +MayaUsd_SchemasMayaReference::Get(const UsdStagePtr& stage, const SdfPath& path) { if (!stage) { TF_CODING_ERROR("Invalid stage"); @@ -54,83 +51,78 @@ MayaUsd_SchemasMayaReference::Get(const UsdStagePtr &stage, const SdfPath &path) /* static */ MayaUsd_SchemasMayaReference -MayaUsd_SchemasMayaReference::Define( - const UsdStagePtr &stage, const SdfPath &path) +MayaUsd_SchemasMayaReference::Define(const UsdStagePtr& stage, const SdfPath& path) { static TfToken usdPrimTypeName("MayaReference"); if (!stage) { TF_CODING_ERROR("Invalid stage"); return MayaUsd_SchemasMayaReference(); } - return MayaUsd_SchemasMayaReference( - stage->DefinePrim(path, usdPrimTypeName)); + return MayaUsd_SchemasMayaReference(stage->DefinePrim(path, usdPrimTypeName)); } /* virtual */ -UsdSchemaType MayaUsd_SchemasMayaReference::_GetSchemaType() const { +UsdSchemaType MayaUsd_SchemasMayaReference::_GetSchemaType() const +{ return MayaUsd_SchemasMayaReference::schemaType; } /* static */ -const TfType & -MayaUsd_SchemasMayaReference::_GetStaticTfType() +const TfType& MayaUsd_SchemasMayaReference::_GetStaticTfType() { static TfType tfType = TfType::Find(); return tfType; } /* static */ -bool -MayaUsd_SchemasMayaReference::_IsTypedSchema() +bool MayaUsd_SchemasMayaReference::_IsTypedSchema() { static bool isTyped = _GetStaticTfType().IsA(); return isTyped; } /* virtual */ -const TfType & -MayaUsd_SchemasMayaReference::_GetTfType() const -{ - return _GetStaticTfType(); -} +const TfType& MayaUsd_SchemasMayaReference::_GetTfType() const { return _GetStaticTfType(); } -UsdAttribute -MayaUsd_SchemasMayaReference::GetMayaReferenceAttr() const +UsdAttribute MayaUsd_SchemasMayaReference::GetMayaReferenceAttr() const { return GetPrim().GetAttribute(MayaUsd_SchemasTokens->mayaReference); } -UsdAttribute -MayaUsd_SchemasMayaReference::CreateMayaReferenceAttr(VtValue const &defaultValue, bool writeSparsely) const +UsdAttribute MayaUsd_SchemasMayaReference::CreateMayaReferenceAttr( + VtValue const& defaultValue, + bool writeSparsely) const { - return UsdSchemaBase::_CreateAttr(MayaUsd_SchemasTokens->mayaReference, - SdfValueTypeNames->Asset, - /* custom = */ false, - SdfVariabilityVarying, - defaultValue, - writeSparsely); + return UsdSchemaBase::_CreateAttr( + MayaUsd_SchemasTokens->mayaReference, + SdfValueTypeNames->Asset, + /* custom = */ false, + SdfVariabilityVarying, + defaultValue, + writeSparsely); } -UsdAttribute -MayaUsd_SchemasMayaReference::GetMayaNamespaceAttr() const +UsdAttribute MayaUsd_SchemasMayaReference::GetMayaNamespaceAttr() const { return GetPrim().GetAttribute(MayaUsd_SchemasTokens->mayaNamespace); } -UsdAttribute -MayaUsd_SchemasMayaReference::CreateMayaNamespaceAttr(VtValue const &defaultValue, bool writeSparsely) const +UsdAttribute MayaUsd_SchemasMayaReference::CreateMayaNamespaceAttr( + VtValue const& defaultValue, + bool writeSparsely) const { - return UsdSchemaBase::_CreateAttr(MayaUsd_SchemasTokens->mayaNamespace, - SdfValueTypeNames->String, - /* custom = */ false, - SdfVariabilityVarying, - defaultValue, - writeSparsely); + return UsdSchemaBase::_CreateAttr( + MayaUsd_SchemasTokens->mayaNamespace, + SdfValueTypeNames->String, + /* custom = */ false, + SdfVariabilityVarying, + defaultValue, + writeSparsely); } namespace { static inline TfTokenVector -_ConcatenateAttributeNames(const TfTokenVector& left,const TfTokenVector& right) +_ConcatenateAttributeNames(const TfTokenVector& left, const TfTokenVector& right) { TfTokenVector result; result.reserve(left.size() + right.size()); @@ -138,20 +130,17 @@ _ConcatenateAttributeNames(const TfTokenVector& left,const TfTokenVector& right) result.insert(result.end(), right.begin(), right.end()); return result; } -} +} // namespace /*static*/ -const TfTokenVector& -MayaUsd_SchemasMayaReference::GetSchemaAttributeNames(bool includeInherited) +const TfTokenVector& MayaUsd_SchemasMayaReference::GetSchemaAttributeNames(bool includeInherited) { static TfTokenVector localNames = { MayaUsd_SchemasTokens->mayaReference, MayaUsd_SchemasTokens->mayaNamespace, }; - static TfTokenVector allNames = - _ConcatenateAttributeNames( - UsdGeomXformable::GetSchemaAttributeNames(true), - localNames); + static TfTokenVector allNames + = _ConcatenateAttributeNames(UsdGeomXformable::GetSchemaAttributeNames(true), localNames); if (includeInherited) return allNames; diff --git a/lib/usd/schemas/MayaReference.h b/lib/usd/schemas/MayaReference.h index 4637a09d30..dfb10577fc 100644 --- a/lib/usd/schemas/MayaReference.h +++ b/lib/usd/schemas/MayaReference.h @@ -18,13 +18,13 @@ /// \file mayaUsd_Schemas/MayaReference.h -#include #include #include #include #include #include #include +#include #include #include #include @@ -56,7 +56,7 @@ class MayaUsd_SchemasMayaReference : public UsdGeomXformable /// Equivalent to MayaUsd_SchemasMayaReference::Get(prim.GetStage(), prim.GetPath()) /// for a \em valid \p prim, but will not immediately throw an error for /// an invalid \p prim - explicit MayaUsd_SchemasMayaReference(const UsdPrim& prim=UsdPrim()) + explicit MayaUsd_SchemasMayaReference(const UsdPrim& prim = UsdPrim()) : UsdGeomXformable(prim) { } @@ -77,8 +77,7 @@ class MayaUsd_SchemasMayaReference : public UsdGeomXformable /// class and all its ancestor classes. Does not include attributes that /// may be authored by custom/extended methods of the schemas involved. MAYAUSD_SCHEMAS_API - static const TfTokenVector & - GetSchemaAttributeNames(bool includeInherited=true); + static const TfTokenVector& GetSchemaAttributeNames(bool includeInherited = true); /// Return a MayaUsd_SchemasMayaReference holding the prim adhering to this /// schema at \p path on \p stage. If no prim exists at \p path on @@ -90,8 +89,7 @@ class MayaUsd_SchemasMayaReference : public UsdGeomXformable /// \endcode /// MAYAUSD_SCHEMAS_API - static MayaUsd_SchemasMayaReference - Get(const UsdStagePtr &stage, const SdfPath &path); + static MayaUsd_SchemasMayaReference Get(const UsdStagePtr& stage, const SdfPath& path); /// Attempt to ensure a \a UsdPrim adhering to this schema at \p path /// is defined (according to UsdPrim::IsDefined()) on this stage. @@ -116,8 +114,7 @@ class MayaUsd_SchemasMayaReference : public UsdGeomXformable /// the opinion at the current EditTarget. /// MAYAUSD_SCHEMAS_API - static MayaUsd_SchemasMayaReference - Define(const UsdStagePtr &stage, const SdfPath &path); + static MayaUsd_SchemasMayaReference Define(const UsdStagePtr& stage, const SdfPath& path); protected: /// Returns the type of schema this class belongs to. @@ -130,17 +127,17 @@ class MayaUsd_SchemasMayaReference : public UsdGeomXformable // needs to invoke _GetStaticTfType. friend class UsdSchemaRegistry; MAYAUSD_SCHEMAS_API - static const TfType &_GetStaticTfType(); + static const TfType& _GetStaticTfType(); static bool _IsTypedSchema(); // override SchemaBase virtuals. MAYAUSD_SCHEMAS_API - const TfType &_GetTfType() const override; + const TfType& _GetTfType() const override; public: // --------------------------------------------------------------------- // - // MAYAREFERENCE + // MAYAREFERENCE // --------------------------------------------------------------------- // /// Path to the maya reference. /// @@ -152,17 +149,19 @@ class MayaUsd_SchemasMayaReference : public UsdGeomXformable MAYAUSD_SCHEMAS_API UsdAttribute GetMayaReferenceAttr() const; - /// See GetMayaReferenceAttr(), and also + /// See GetMayaReferenceAttr(), and also /// \ref Usd_Create_Or_Get_Property for when to use Get vs Create. /// If specified, author \p defaultValue as the attribute's default, /// sparsely (when it makes sense to do so) if \p writeSparsely is \c true - /// the default for \p writeSparsely is \c false. MAYAUSD_SCHEMAS_API - UsdAttribute CreateMayaReferenceAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const; + UsdAttribute CreateMayaReferenceAttr( + VtValue const& defaultValue = VtValue(), + bool writeSparsely = false) const; public: // --------------------------------------------------------------------- // - // MAYANAMESPACE + // MAYANAMESPACE // --------------------------------------------------------------------- // /// Namespace which the maya reference will be imported under. /// @@ -174,21 +173,23 @@ class MayaUsd_SchemasMayaReference : public UsdGeomXformable MAYAUSD_SCHEMAS_API UsdAttribute GetMayaNamespaceAttr() const; - /// See GetMayaNamespaceAttr(), and also + /// See GetMayaNamespaceAttr(), and also /// \ref Usd_Create_Or_Get_Property for when to use Get vs Create. /// If specified, author \p defaultValue as the attribute's default, /// sparsely (when it makes sense to do so) if \p writeSparsely is \c true - /// the default for \p writeSparsely is \c false. MAYAUSD_SCHEMAS_API - UsdAttribute CreateMayaNamespaceAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const; + UsdAttribute CreateMayaNamespaceAttr( + VtValue const& defaultValue = VtValue(), + bool writeSparsely = false) const; public: // ===================================================================== // - // Feel free to add custom code below this line, it will be preserved by - // the code generator. + // Feel free to add custom code below this line, it will be preserved by + // the code generator. // - // Just remember to: - // - Close the class declaration with }; + // Just remember to: + // - Close the class declaration with }; // - Close the namespace with PXR_NAMESPACE_CLOSE_SCOPE // - Close the include guard with #endif // ===================================================================== // diff --git a/lib/usd/schemas/ModuleDeps.cpp b/lib/usd/schemas/ModuleDeps.cpp index f116a98e73..eb01bdf7e8 100644 --- a/lib/usd/schemas/ModuleDeps.cpp +++ b/lib/usd/schemas/ModuleDeps.cpp @@ -13,20 +13,19 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - #include #include #include +#include + PXR_NAMESPACE_OPEN_SCOPE -TF_REGISTRY_FUNCTION(TfScriptModuleLoader) { - const std::vector reqs = { - TfToken("usd"), TfToken("usdGeom") - }; - TfScriptModuleLoader::GetInstance(). - RegisterLibrary(TfToken("schemas"), TfToken("mayaUsd.schemas"), reqs); +TF_REGISTRY_FUNCTION(TfScriptModuleLoader) +{ + const std::vector reqs = { TfToken("usd"), TfToken("usdGeom") }; + TfScriptModuleLoader::GetInstance().RegisterLibrary( + TfToken("schemas"), TfToken("mayaUsd.schemas"), reqs); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/schemas/api.h b/lib/usd/schemas/api.h index 828b777418..91b8f040e4 100644 --- a/lib/usd/schemas/api.h +++ b/lib/usd/schemas/api.h @@ -19,21 +19,21 @@ #include #if defined(PXR_STATIC) -# define MAYAUSD_SCHEMAS_API -# define MAYAUSD_SCHEMAS_API_TEMPLATE_CLASS(...) -# define MAYAUSD_SCHEMAS_API_TEMPLATE_STRUCT(...) -# define MAYAUSD_SCHEMAS_LOCAL +#define MAYAUSD_SCHEMAS_API +#define MAYAUSD_SCHEMAS_API_TEMPLATE_CLASS(...) +#define MAYAUSD_SCHEMAS_API_TEMPLATE_STRUCT(...) +#define MAYAUSD_SCHEMAS_LOCAL #else -# if defined(MAYAUSD_SCHEMAS_EXPORTS) -# define MAYAUSD_SCHEMAS_API ARCH_EXPORT -# define MAYAUSD_SCHEMAS_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__) -# define MAYAUSD_SCHEMAS_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__) -# else -# define MAYAUSD_SCHEMAS_API ARCH_IMPORT -# define MAYAUSD_SCHEMAS_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__) -# define MAYAUSD_SCHEMAS_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__) -# endif -# define MAYAUSD_SCHEMAS_LOCAL ARCH_HIDDEN +#if defined(MAYAUSD_SCHEMAS_EXPORTS) +#define MAYAUSD_SCHEMAS_API ARCH_EXPORT +#define MAYAUSD_SCHEMAS_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__) +#define MAYAUSD_SCHEMAS_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__) +#else +#define MAYAUSD_SCHEMAS_API ARCH_IMPORT +#define MAYAUSD_SCHEMAS_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__) +#define MAYAUSD_SCHEMAS_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__) +#endif +#define MAYAUSD_SCHEMAS_LOCAL ARCH_HIDDEN #endif #endif diff --git a/lib/usd/schemas/tokens.cpp b/lib/usd/schemas/tokens.cpp index b260802c3f..870bb9a861 100644 --- a/lib/usd/schemas/tokens.cpp +++ b/lib/usd/schemas/tokens.cpp @@ -17,13 +17,10 @@ PXR_NAMESPACE_OPEN_SCOPE -MayaUsd_SchemasTokensType::MayaUsd_SchemasTokensType() : - mayaNamespace("mayaNamespace", TfToken::Immortal), - mayaReference("mayaReference", TfToken::Immortal), - allTokens({ - mayaNamespace, - mayaReference - }) +MayaUsd_SchemasTokensType::MayaUsd_SchemasTokensType() + : mayaNamespace("mayaNamespace", TfToken::Immortal) + , mayaReference("mayaReference", TfToken::Immortal) + , allTokens({ mayaNamespace, mayaReference }) { } diff --git a/lib/usd/schemas/tokens.h b/lib/usd/schemas/tokens.h index 2a731aeeea..4557f9b41e 100644 --- a/lib/usd/schemas/tokens.h +++ b/lib/usd/schemas/tokens.h @@ -19,22 +19,21 @@ /// \file mayaUsd_Schemas/tokens.h // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX -// +// // This is an automatically generated file (by usdGenSchema.py). // Do not hand-edit! -// +// // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX -#include - #include #include #include #include -PXR_NAMESPACE_OPEN_SCOPE +#include +PXR_NAMESPACE_OPEN_SCOPE /// \class MayaUsd_SchemasTokensType /// @@ -54,14 +53,15 @@ PXR_NAMESPACE_OPEN_SCOPE /// \code /// gprim.GetMyTokenValuedAttr().Set(MayaUsd_SchemasTokens->mayaNamespace); /// \endcode -struct MayaUsd_SchemasTokensType { +struct MayaUsd_SchemasTokensType +{ MAYAUSD_SCHEMAS_API MayaUsd_SchemasTokensType(); /// \brief "mayaNamespace" - /// + /// /// MayaUsd_SchemasMayaReference const TfToken mayaNamespace; /// \brief "mayaReference" - /// + /// /// MayaUsd_SchemasMayaReference const TfToken mayaReference; /// A vector of all of the tokens listed above. diff --git a/lib/usd/schemas/wrapALMayaReference.cpp b/lib/usd/schemas/wrapALMayaReference.cpp index dcde28ec00..50cd8f88ac 100644 --- a/lib/usd/schemas/wrapALMayaReference.cpp +++ b/lib/usd/schemas/wrapALMayaReference.cpp @@ -13,10 +13,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include - #include #include #include @@ -25,32 +21,31 @@ #include #include +#include #include +#include + using namespace boost::python; PXR_NAMESPACE_USING_DIRECTIVE namespace { -#define WRAP_CUSTOM \ - template static void _CustomWrapCode(Cls &_class) +#define WRAP_CUSTOM template static void _CustomWrapCode(Cls& _class) // fwd decl. WRAP_CUSTOM; - } // anonymous namespace void wrapMayaUsd_SchemasALMayaReference() { typedef MayaUsd_SchemasALMayaReference This; - class_ > - cls("ALMayaReference"); + class_> cls("ALMayaReference"); - cls - .def(init(arg("prim"))) + cls.def(init(arg("prim"))) .def(init(arg("schemaObj"))) .def(TfTypePythonClass()) @@ -60,26 +55,28 @@ void wrapMayaUsd_SchemasALMayaReference() .def("Define", &This::Define, (arg("stage"), arg("path"))) .staticmethod("Define") - .def("GetSchemaAttributeNames", - &This::GetSchemaAttributeNames, - arg("includeInherited")=true, - return_value_policy()) + .def( + "GetSchemaAttributeNames", + &This::GetSchemaAttributeNames, + arg("includeInherited") = true, + return_value_policy()) .staticmethod("GetSchemaAttributeNames") - .def("_GetStaticTfType", (TfType const &(*)()) TfType::Find, - return_value_policy()) + .def( + "_GetStaticTfType", + (TfType const& (*)())TfType::Find, + return_value_policy()) .staticmethod("_GetStaticTfType") .def(!self) - - ; + ; _CustomWrapCode(cls); } // ===================================================================== // -// Feel free to add custom code below this line, it will be preserved by +// Feel free to add custom code below this line, it will be preserved by // the code generator. The entry point for your custom code should look // minimally like the following: // @@ -90,7 +87,7 @@ void wrapMayaUsd_SchemasALMayaReference() // } // // Of course any other ancillary or support code may be provided. -// +// // Just remember to wrap code in the appropriate delimiters: // 'namespace {', '}'. // @@ -99,7 +96,6 @@ void wrapMayaUsd_SchemasALMayaReference() namespace { -WRAP_CUSTOM { -} +WRAP_CUSTOM { } -} +} // namespace diff --git a/lib/usd/schemas/wrapMayaReference.cpp b/lib/usd/schemas/wrapMayaReference.cpp index c16e4a66ac..cad2c3468e 100644 --- a/lib/usd/schemas/wrapMayaReference.cpp +++ b/lib/usd/schemas/wrapMayaReference.cpp @@ -13,10 +13,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - -#include - #include #include #include @@ -25,31 +21,32 @@ #include #include +#include #include +#include + using namespace boost::python; PXR_NAMESPACE_USING_DIRECTIVE namespace { -#define WRAP_CUSTOM \ - template static void _CustomWrapCode(Cls &_class) +#define WRAP_CUSTOM template static void _CustomWrapCode(Cls& _class) // fwd decl. WRAP_CUSTOM; - static UsdAttribute -_CreateMayaReferenceAttr(MayaUsd_SchemasMayaReference &self, - object defaultVal, bool writeSparsely) { +_CreateMayaReferenceAttr(MayaUsd_SchemasMayaReference& self, object defaultVal, bool writeSparsely) +{ return self.CreateMayaReferenceAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Asset), writeSparsely); } - + static UsdAttribute -_CreateMayaNamespaceAttr(MayaUsd_SchemasMayaReference &self, - object defaultVal, bool writeSparsely) { +_CreateMayaNamespaceAttr(MayaUsd_SchemasMayaReference& self, object defaultVal, bool writeSparsely) +{ return self.CreateMayaNamespaceAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->String), writeSparsely); } @@ -60,11 +57,9 @@ void wrapMayaUsd_SchemasMayaReference() { typedef MayaUsd_SchemasMayaReference This; - class_ > - cls("MayaReference"); + class_> cls("MayaReference"); - cls - .def(init(arg("prim"))) + cls.def(init(arg("prim"))) .def(init(arg("schemaObj"))) .def(TfTypePythonClass()) @@ -74,40 +69,40 @@ void wrapMayaUsd_SchemasMayaReference() .def("Define", &This::Define, (arg("stage"), arg("path"))) .staticmethod("Define") - .def("GetSchemaAttributeNames", - &This::GetSchemaAttributeNames, - arg("includeInherited")=true, - return_value_policy()) + .def( + "GetSchemaAttributeNames", + &This::GetSchemaAttributeNames, + arg("includeInherited") = true, + return_value_policy()) .staticmethod("GetSchemaAttributeNames") - .def("_GetStaticTfType", (TfType const &(*)()) TfType::Find, - return_value_policy()) + .def( + "_GetStaticTfType", + (TfType const& (*)())TfType::Find, + return_value_policy()) .staticmethod("_GetStaticTfType") .def(!self) - - .def("GetMayaReferenceAttr", - &This::GetMayaReferenceAttr) - .def("CreateMayaReferenceAttr", - &_CreateMayaReferenceAttr, - (arg("defaultValue")=object(), - arg("writeSparsely")=false)) - - .def("GetMayaNamespaceAttr", - &This::GetMayaNamespaceAttr) - .def("CreateMayaNamespaceAttr", - &_CreateMayaNamespaceAttr, - (arg("defaultValue")=object(), - arg("writeSparsely")=false)) - - ; + .def("GetMayaReferenceAttr", &This::GetMayaReferenceAttr) + .def( + "CreateMayaReferenceAttr", + &_CreateMayaReferenceAttr, + (arg("defaultValue") = object(), arg("writeSparsely") = false)) + + .def("GetMayaNamespaceAttr", &This::GetMayaNamespaceAttr) + .def( + "CreateMayaNamespaceAttr", + &_CreateMayaNamespaceAttr, + (arg("defaultValue") = object(), arg("writeSparsely") = false)) + + ; _CustomWrapCode(cls); } // ===================================================================== // -// Feel free to add custom code below this line, it will be preserved by +// Feel free to add custom code below this line, it will be preserved by // the code generator. The entry point for your custom code should look // minimally like the following: // @@ -118,7 +113,7 @@ void wrapMayaUsd_SchemasMayaReference() // } // // Of course any other ancillary or support code may be provided. -// +// // Just remember to wrap code in the appropriate delimiters: // 'namespace {', '}'. // @@ -127,7 +122,6 @@ void wrapMayaUsd_SchemasMayaReference() namespace { -WRAP_CUSTOM { -} +WRAP_CUSTOM { } -} +} // namespace diff --git a/lib/usd/schemas/wrapTokens.cpp b/lib/usd/schemas/wrapTokens.cpp index f06b6532e9..38ef54f69f 100644 --- a/lib/usd/schemas/wrapTokens.cpp +++ b/lib/usd/schemas/wrapTokens.cpp @@ -15,7 +15,6 @@ // // GENERATED FILE. DO NOT EDIT. #include - #include PXR_NAMESPACE_USING_DIRECTIVE @@ -26,37 +25,36 @@ namespace { // strings and for some reason simply wrapping the token using def_readonly // bypasses to-Python conversion, leading to the error that there's no // Python type for the C++ TfToken type. So we wrap this functor instead. -class _WrapStaticToken { +class _WrapStaticToken +{ public: - _WrapStaticToken(const TfToken* token) : _token(token) { } - - std::string operator()() const + _WrapStaticToken(const TfToken* token) + : _token(token) { - return _token->GetString(); } + std::string operator()() const { return _token->GetString(); } + private: const TfToken* _token; }; -template -void -_AddToken(T& cls, const char* name, const TfToken& token) +template void _AddToken(T& cls, const char* name, const TfToken& token) { - cls.add_static_property(name, - boost::python::make_function( - _WrapStaticToken(&token), - boost::python::return_value_policy< - boost::python::return_by_value>(), - boost::mpl::vector1())); + cls.add_static_property( + name, + boost::python::make_function( + _WrapStaticToken(&token), + boost::python::return_value_policy(), + boost::mpl::vector1())); } -} // anonymous +} // namespace void wrapMayaUsd_SchemasTokens() { - boost::python::class_ - cls("Tokens", boost::python::no_init); + boost::python::class_ cls( + "Tokens", boost::python::no_init); _AddToken(cls, "mayaNamespace", MayaUsd_SchemasTokens->mayaNamespace); _AddToken(cls, "mayaReference", MayaUsd_SchemasTokens->mayaReference); } diff --git a/lib/usd/translators/api.h b/lib/usd/translators/api.h index 390a7a6a01..aacf8ee7e4 100644 --- a/lib/usd/translators/api.h +++ b/lib/usd/translators/api.h @@ -19,21 +19,21 @@ #include #if defined(PXR_STATIC) -# define PXRUSDTRANSLATORS_API -# define PXRUSDTRANSLATORS_API_TEMPLATE_CLASS(...) -# define PXRUSDTRANSLATORS_API_TEMPLATE_STRUCT(...) -# define PXRUSDTRANSLATORS_LOCAL +#define PXRUSDTRANSLATORS_API +#define PXRUSDTRANSLATORS_API_TEMPLATE_CLASS(...) +#define PXRUSDTRANSLATORS_API_TEMPLATE_STRUCT(...) +#define PXRUSDTRANSLATORS_LOCAL #else -# if defined(PXRUSDTRANSLATORS_EXPORTS) -# define PXRUSDTRANSLATORS_API ARCH_EXPORT -# define PXRUSDTRANSLATORS_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__) -# define PXRUSDTRANSLATORS_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__) -# else -# define PXRUSDTRANSLATORS_API ARCH_IMPORT -# define PXRUSDTRANSLATORS_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__) -# define PXRUSDTRANSLATORS_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__) -# endif -# define PXRUSDTRANSLATORS_LOCAL ARCH_HIDDEN +#if defined(PXRUSDTRANSLATORS_EXPORTS) +#define PXRUSDTRANSLATORS_API ARCH_EXPORT +#define PXRUSDTRANSLATORS_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__) +#define PXRUSDTRANSLATORS_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__) +#else +#define PXRUSDTRANSLATORS_API ARCH_IMPORT +#define PXRUSDTRANSLATORS_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__) +#define PXRUSDTRANSLATORS_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__) +#endif +#define PXRUSDTRANSLATORS_LOCAL ARCH_HIDDEN #endif #endif diff --git a/lib/usd/translators/cameraReader.cpp b/lib/usd/translators/cameraReader.cpp index 9710842564..c4fe3d298a 100644 --- a/lib/usd/translators/cameraReader.cpp +++ b/lib/usd/translators/cameraReader.cpp @@ -13,27 +13,22 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include +#include #include #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_DEFINE_READER(UsdGeomCamera, args, context) { const UsdPrim& usdPrim = args.GetUsdPrim(); - MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); - return UsdMayaTranslatorCamera::Read( - UsdGeomCamera(usdPrim), - parentNode, - args, - context); + MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); + return UsdMayaTranslatorCamera::Read(UsdGeomCamera(usdPrim), parentNode, args, context); } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/usd/translators/cameraWriter.cpp b/lib/usd/translators/cameraWriter.cpp index 786df6c0b7..64cc05daf1 100644 --- a/lib/usd/translators/cameraWriter.cpp +++ b/lib/usd/translators/cameraWriter.cpp @@ -15,24 +15,24 @@ // #include "cameraWriter.h" -#include -#include +#include +#include +#include +#include +#include +#include -#include #include #include +#include #include #include #include #include #include -#include -#include -#include -#include -#include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -40,21 +40,18 @@ PXRUSDMAYA_REGISTER_WRITER(camera, PxrUsdTranslators_CameraWriter); PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(camera, UsdGeomCamera); PxrUsdTranslators_CameraWriter::PxrUsdTranslators_CameraWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) { if (!TF_VERIFY(GetDagPath().isValid())) { return; } - UsdGeomCamera primSchema = - UsdGeomCamera::Define(GetUsdStage(), GetUsdPath()); + UsdGeomCamera primSchema = UsdGeomCamera::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( - primSchema, - "Could not define UsdGeomCamera at path '%s'\n", - GetUsdPath().GetText())) { + primSchema, "Could not define UsdGeomCamera at path '%s'\n", GetUsdPath().GetText())) { return; } _usdPrim = primSchema.GetPrim(); @@ -67,8 +64,7 @@ PxrUsdTranslators_CameraWriter::PxrUsdTranslators_CameraWriter( } /* virtual */ -void -PxrUsdTranslators_CameraWriter::Write(const UsdTimeCode& usdTime) +void PxrUsdTranslators_CameraWriter::Write(const UsdTimeCode& usdTime) { UsdMayaPrimWriter::Write(usdTime); @@ -76,10 +72,9 @@ PxrUsdTranslators_CameraWriter::Write(const UsdTimeCode& usdTime) writeCameraAttrs(usdTime, primSchema); } -bool -PxrUsdTranslators_CameraWriter::writeCameraAttrs( - const UsdTimeCode& usdTime, - UsdGeomCamera& primSchema) +bool PxrUsdTranslators_CameraWriter::writeCameraAttrs( + const UsdTimeCode& usdTime, + UsdGeomCamera& primSchema) { // Since write() above will take care of any animation on the camera's // transform, we only want to proceed here if: @@ -100,9 +95,11 @@ PxrUsdTranslators_CameraWriter::writeCameraAttrs( // Using SetFromCamera() would stomp them with a single "transform" xformOp. if (camFn.isOrtho()) { - UsdMayaWriteUtil::SetAttribute(primSchema.GetProjectionAttr(), - UsdGeomTokens->orthographic, - usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetProjectionAttr(), + UsdGeomTokens->orthographic, + usdTime, + _GetSparseValueWriter()); // Contrary to the documentation, Maya actually stores the orthographic // width in centimeters (Maya's internal unit system), not inches. @@ -111,62 +108,91 @@ PxrUsdTranslators_CameraWriter::writeCameraAttrs( // It doesn't seem to be possible to specify a non-square orthographic // camera in Maya, and aspect ratio, lens squeeze ratio, and film // offset have no effect. - UsdMayaWriteUtil::SetAttribute(primSchema.GetHorizontalApertureAttr(), - static_cast(orthoWidth), usdTime, _GetSparseValueWriter()); - - UsdMayaWriteUtil::SetAttribute(primSchema.GetVerticalApertureAttr(), - static_cast(orthoWidth), - usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetHorizontalApertureAttr(), + static_cast(orthoWidth), + usdTime, + _GetSparseValueWriter()); + + UsdMayaWriteUtil::SetAttribute( + primSchema.GetVerticalApertureAttr(), + static_cast(orthoWidth), + usdTime, + _GetSparseValueWriter()); } else { - UsdMayaWriteUtil::SetAttribute(primSchema.GetProjectionAttr(), - UsdGeomTokens->perspective, usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetProjectionAttr(), + UsdGeomTokens->perspective, + usdTime, + _GetSparseValueWriter()); // Lens squeeze ratio applies horizontally only. const double horizontalAperture = UsdMayaUtil::ConvertInchesToMM( camFn.horizontalFilmAperture() * camFn.lensSqueezeRatio()); - const double verticalAperture = UsdMayaUtil::ConvertInchesToMM( - camFn.verticalFilmAperture()); + const double verticalAperture + = UsdMayaUtil::ConvertInchesToMM(camFn.verticalFilmAperture()); // Film offset and shake (when enabled) have the same effect on film back const double horizontalApertureOffset = UsdMayaUtil::ConvertInchesToMM( - (camFn.shakeEnabled() ? - camFn.horizontalFilmOffset() + camFn.horizontalShake() : camFn.horizontalFilmOffset())); + (camFn.shakeEnabled() ? camFn.horizontalFilmOffset() + camFn.horizontalShake() + : camFn.horizontalFilmOffset())); const double verticalApertureOffset = UsdMayaUtil::ConvertInchesToMM( - (camFn.shakeEnabled() ? camFn.verticalFilmOffset() + camFn.verticalShake() : camFn.verticalFilmOffset())); - - UsdMayaWriteUtil::SetAttribute(primSchema.GetHorizontalApertureAttr(), - static_cast(horizontalAperture), usdTime, _GetSparseValueWriter()); - - UsdMayaWriteUtil::SetAttribute(primSchema.GetVerticalApertureAttr(), - static_cast(verticalAperture), usdTime, _GetSparseValueWriter()); - - UsdMayaWriteUtil::SetAttribute(primSchema.GetHorizontalApertureOffsetAttr(), - static_cast(horizontalApertureOffset), usdTime, _GetSparseValueWriter()); - - UsdMayaWriteUtil::SetAttribute(primSchema.GetVerticalApertureOffsetAttr(), - static_cast(verticalApertureOffset), usdTime, _GetSparseValueWriter()); + (camFn.shakeEnabled() ? camFn.verticalFilmOffset() + camFn.verticalShake() + : camFn.verticalFilmOffset())); + + UsdMayaWriteUtil::SetAttribute( + primSchema.GetHorizontalApertureAttr(), + static_cast(horizontalAperture), + usdTime, + _GetSparseValueWriter()); + + UsdMayaWriteUtil::SetAttribute( + primSchema.GetVerticalApertureAttr(), + static_cast(verticalAperture), + usdTime, + _GetSparseValueWriter()); + + UsdMayaWriteUtil::SetAttribute( + primSchema.GetHorizontalApertureOffsetAttr(), + static_cast(horizontalApertureOffset), + usdTime, + _GetSparseValueWriter()); + + UsdMayaWriteUtil::SetAttribute( + primSchema.GetVerticalApertureOffsetAttr(), + static_cast(verticalApertureOffset), + usdTime, + _GetSparseValueWriter()); } // Set the lens parameters. - UsdMayaWriteUtil::SetAttribute(primSchema.GetFocalLengthAttr(), - static_cast(camFn.focalLength()), usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetFocalLengthAttr(), + static_cast(camFn.focalLength()), + usdTime, + _GetSparseValueWriter()); // Always export focus distance and fStop regardless of what // camFn.isDepthOfField() says. Downstream tools can choose to ignore or // override them. - UsdMayaWriteUtil::SetAttribute(primSchema.GetFocusDistanceAttr(), - static_cast(camFn.focusDistance()), usdTime, _GetSparseValueWriter()); - - UsdMayaWriteUtil::SetAttribute(primSchema.GetFStopAttr(), - static_cast(camFn.fStop()), usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetFocusDistanceAttr(), + static_cast(camFn.focusDistance()), + usdTime, + _GetSparseValueWriter()); + + UsdMayaWriteUtil::SetAttribute( + primSchema.GetFStopAttr(), + static_cast(camFn.fStop()), + usdTime, + _GetSparseValueWriter()); // Set the clipping planes. GfVec2f clippingRange(camFn.nearClippingPlane(), camFn.farClippingPlane()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetClippingRangeAttr(), clippingRange, - usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetClippingRangeAttr(), clippingRange, usdTime, _GetSparseValueWriter()); return true; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/cameraWriter.h b/lib/usd/translators/cameraWriter.h index 76528454e0..ebce59ba43 100644 --- a/lib/usd/translators/cameraWriter.h +++ b/lib/usd/translators/cameraWriter.h @@ -18,37 +18,33 @@ /// \file -#include +#include +#include #include #include #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE /// Exports Maya cameras to UsdGeomCamera. class PxrUsdTranslators_CameraWriter : public UsdMayaPrimWriter { - public: - PxrUsdTranslators_CameraWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); - - void Write(const UsdTimeCode& usdTime) override; - - protected: - bool writeCameraAttrs( - const UsdTimeCode& usdTime, - UsdGeomCamera& primSchema); -}; +public: + PxrUsdTranslators_CameraWriter( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); + void Write(const UsdTimeCode& usdTime) override; -PXR_NAMESPACE_CLOSE_SCOPE +protected: + bool writeCameraAttrs(const UsdTimeCode& usdTime, UsdGeomCamera& primSchema); +}; +PXR_NAMESPACE_CLOSE_SCOPE #endif diff --git a/lib/usd/translators/instancerWriter.cpp b/lib/usd/translators/instancerWriter.cpp index a20d28cc39..ff2f71a165 100644 --- a/lib/usd/translators/instancerWriter.cpp +++ b/lib/usd/translators/instancerWriter.cpp @@ -15,14 +15,11 @@ // #include "instancerWriter.h" -#include - -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include @@ -35,23 +32,21 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_REGISTER_WRITER(instancer, PxrUsdTranslators_InstancerWriter); PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(instancer, UsdGeomPointInstancer); -TF_DEFINE_PRIVATE_TOKENS( - _tokens, - (Prototypes) - (instancerTranslate) -); - +TF_DEFINE_PRIVATE_TOKENS(_tokens, (Prototypes)(instancerTranslate)); namespace { @@ -59,11 +54,7 @@ static constexpr double _EPSILON = 1e-3; /// Determines if the second translate op encodes the exact negation of the /// first op, across default values and time samples. -static -bool -_AreTranslateOpsOpposites( - const UsdGeomXformOp& first, - const UsdGeomXformOp& second) +static bool _AreTranslateOpsOpposites(const UsdGeomXformOp& first, const UsdGeomXformOp& second) { if (first.GetPrecision() != second.GetPrecision()) { return false; @@ -99,18 +90,15 @@ _AreTranslateOpsOpposites( /// Edits the xform ops and xformOpOrder on xformable to remove subsequent pairs /// of instancerTranslate and translate ops that cancel each other out. -static -void -_CleanUpRedundantTranslateOps(UsdGeomXformable& xformable) +static void _CleanUpRedundantTranslateOps(UsdGeomXformable& xformable) { - static const TfToken plainTranslateName = UsdGeomXformOp::GetOpName( - UsdGeomXformOp::TypeTranslate); - static const TfToken instancerTranslateName = UsdGeomXformOp::GetOpName( - UsdGeomXformOp::TypeTranslate, _tokens->instancerTranslate); - - bool resetsXformStack; - std::vector ops = xformable.GetOrderedXformOps( - &resetsXformStack); + static const TfToken plainTranslateName + = UsdGeomXformOp::GetOpName(UsdGeomXformOp::TypeTranslate); + static const TfToken instancerTranslateName + = UsdGeomXformOp::GetOpName(UsdGeomXformOp::TypeTranslate, _tokens->instancerTranslate); + + bool resetsXformStack; + std::vector ops = xformable.GetOrderedXformOps(&resetsXformStack); if (ops.size() < 2) { return; } @@ -119,8 +107,8 @@ _CleanUpRedundantTranslateOps(UsdGeomXformable& xformable) for (auto iter = ops.begin(); iter != ops.end() - 1; ++iter) { const UsdGeomXformOp& thisOp = *iter; const UsdGeomXformOp& nextOp = *(iter + 1); - if (thisOp.GetOpName() == instancerTranslateName && - nextOp.GetOpName() == plainTranslateName) { + if (thisOp.GetOpName() == instancerTranslateName + && nextOp.GetOpName() == plainTranslateName) { if (_AreTranslateOpsOpposites(thisOp, nextOp)) { UsdPrim prim = xformable.GetPrim(); @@ -133,10 +121,8 @@ _CleanUpRedundantTranslateOps(UsdGeomXformable& xformable) // scene description completely. // Otherwise, just edit the xformOpOrder to remove these ops. if (ops.size() == 2 && !resetsXformStack) { - prim.RemoveProperty( - xformable.GetXformOpOrderAttr().GetName()); - } - else { + prim.RemoveProperty(xformable.GetXformOpOrderAttr().GetName()); + } else { ops.erase(iter, iter + 2); xformable.SetXformOpOrder(ops, resetsXformStack); } @@ -148,16 +134,13 @@ _CleanUpRedundantTranslateOps(UsdGeomXformable& xformable) /// Gets the transformed position of (0, 0, 0) using the transform's /// local transformation matrix. -static -bool -_GetTransformedOriginInLocalSpace( - const MDagPath& transformDagPath, - GfVec3d* transformedOrigin) +static bool +_GetTransformedOriginInLocalSpace(const MDagPath& transformDagPath, GfVec3d* transformedOrigin) { if (transformDagPath.hasFn(MFn::kTransform)) { MFnTransform fnXform(transformDagPath); - MMatrix xformMat = fnXform.transformationMatrix(); - MPoint origin = MPoint::origin * xformMat; + MMatrix xformMat = fnXform.transformationMatrix(); + MPoint origin = MPoint::origin * xformMat; *transformedOrigin = GfVec3d(origin.x, origin.y, origin.z); return true; } @@ -167,18 +150,17 @@ _GetTransformedOriginInLocalSpace( } // anonymous namespace PxrUsdTranslators_InstancerWriter::PxrUsdTranslators_InstancerWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaTransformWriter(depNodeFn, usdPath, jobCtx), - _numPrototypes(0) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaTransformWriter(depNodeFn, usdPath, jobCtx) + , _numPrototypes(0) { if (!TF_VERIFY(GetDagPath().isValid())) { return; } - UsdGeomPointInstancer primSchema = - UsdGeomPointInstancer::Define(GetUsdStage(), GetUsdPath()); + UsdGeomPointInstancer primSchema = UsdGeomPointInstancer::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( primSchema, "Could not define UsdGeomPointInstancer at path '%s'\n", @@ -200,8 +182,7 @@ PxrUsdTranslators_InstancerWriter::PxrUsdTranslators_InstancerWriter( } /* virtual */ -void -PxrUsdTranslators_InstancerWriter::Write(const UsdTimeCode& usdTime) +void PxrUsdTranslators_InstancerWriter::Write(const UsdTimeCode& usdTime) { UsdMayaTransformWriter::Write(usdTime); @@ -214,24 +195,22 @@ PxrUsdTranslators_InstancerWriter::Write(const UsdTimeCode& usdTime) /// (This function may return false positives, which are OK but will simply /// contribute extra data. It should never return false negatives, which /// would cause correctness problems.) -bool -PxrUsdTranslators_InstancerWriter::_NeedsExtraInstancerTranslate( - const MDagPath& prototypeDagPath, - bool* instancerTranslateAnimated) const +bool PxrUsdTranslators_InstancerWriter::_NeedsExtraInstancerTranslate( + const MDagPath& prototypeDagPath, + bool* instancerTranslateAnimated) const { // XXX: Maybe we could be smarter here and figure out if the animation // affects instancerTranslate? - bool animated = !_GetExportArgs().timeSamples.empty() && - MAnimUtil::isAnimated(prototypeDagPath.node(), false); + bool animated = !_GetExportArgs().timeSamples.empty() + && MAnimUtil::isAnimated(prototypeDagPath.node(), false); if (animated) { *instancerTranslateAnimated = true; return true; } GfVec3d origin; - bool translated = - _GetTransformedOriginInLocalSpace(prototypeDagPath, &origin) && - !GfIsClose(origin, GfVec3d(0.0), _EPSILON); + bool translated = _GetTransformedOriginInLocalSpace(prototypeDagPath, &origin) + && !GfIsClose(origin, GfVec3d(0.0), _EPSILON); if (translated) { *instancerTranslateAnimated = false; return true; @@ -240,12 +219,11 @@ PxrUsdTranslators_InstancerWriter::_NeedsExtraInstancerTranslate( return false; } -bool -PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( - const UsdTimeCode& usdTime, - const UsdGeomPointInstancer& instancer) +bool PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( + const UsdTimeCode& usdTime, + const UsdGeomPointInstancer& instancer) { - MStatus status = MS::kSuccess; + MStatus status = MS::kSuccess; MFnDagNode dagNode(GetDagPath(), &status); CHECK_MSTATUS_AND_RETURN(status, false); @@ -255,19 +233,17 @@ PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( // they came from. Another reason is that it only provides computed matrices // and not separate position, rotation, scale attrs. - const SdfPath prototypesGroupPath = - instancer.GetPrim().GetPath().AppendChild(_tokens->Prototypes); + const SdfPath prototypesGroupPath + = instancer.GetPrim().GetPath().AppendChild(_tokens->Prototypes); // At the default time, setup all the prototype instances. if (usdTime.IsDefault()) { - const MPlug inputHierarchy = dagNode.findPlug("inputHierarchy", true, - &status); + const MPlug inputHierarchy = dagNode.findPlug("inputHierarchy", true, &status); CHECK_MSTATUS_AND_RETURN(status, false); // Note that the "Prototypes" prim needs to be a model group to ensure // contiguous model hierarchy. - const UsdPrim prototypesGroupPrim = GetUsdStage()->DefinePrim( - prototypesGroupPath); + const UsdPrim prototypesGroupPrim = GetUsdStage()->DefinePrim(prototypesGroupPath); UsdModelAPI(prototypesGroupPrim).SetKind(KindTokens->group); _modelPaths.push_back(prototypesGroupPath); @@ -278,8 +254,7 @@ PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( const MPlug plug = inputHierarchy[i]; const MPlug source(UsdMayaUtil::GetConnected(plug)); if (source.isNull()) { - TF_WARN("Cannot read prototype: the source plug %s was null", - plug.name().asChar()); + TF_WARN("Cannot read prototype: the source plug %s was null", plug.name().asChar()); return false; } @@ -293,16 +268,14 @@ PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( // unique numerical suffix _# indicating the prototype index. std::string sourceName(sourceNode.name().asChar()); - if (_writeJobCtx.GetArgs().stripNamespaces){ + if (_writeJobCtx.GetArgs().stripNamespaces) { sourceName = UsdMayaUtil::stripNamespaces(sourceName); } sourceName = TfMakeValidIdentifier(sourceName); - const TfToken prototypeName( - TfStringPrintf("%s_%d", sourceName.c_str(), i)); - const SdfPath prototypeUsdPath = prototypesGroupPrim.GetPath() - .AppendChild(prototypeName); - UsdPrim prototypePrim = GetUsdStage()->DefinePrim( - prototypeUsdPath); + const TfToken prototypeName(TfStringPrintf("%s_%d", sourceName.c_str(), i)); + const SdfPath prototypeUsdPath + = prototypesGroupPrim.GetPath().AppendChild(prototypeName); + UsdPrim prototypePrim = GetUsdStage()->DefinePrim(prototypeUsdPath); _modelPaths.push_back(prototypeUsdPath); // Try to be conservative and only create an intermediary xformOp @@ -316,14 +289,12 @@ PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( // behavior there, we need to make sure that this is also // fixed to match. bool instancerTranslateAnimated = false; - if (_NeedsExtraInstancerTranslate( - prototypeDagPath, &instancerTranslateAnimated)) { + if (_NeedsExtraInstancerTranslate(prototypeDagPath, &instancerTranslateAnimated)) { UsdGeomXformable xformable(prototypePrim); - UsdGeomXformOp newOp = xformable.AddTranslateOp( - UsdGeomXformOp::PrecisionDouble, - _tokens->instancerTranslate); + UsdGeomXformOp newOp = xformable.AddTranslateOp( + UsdGeomXformOp::PrecisionDouble, _tokens->instancerTranslate); _instancerTranslateOps.push_back( - {prototypeDagPath, newOp, instancerTranslateAnimated}); + { prototypeDagPath, newOp, instancerTranslateAnimated }); } // Two notes: @@ -334,11 +305,11 @@ PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( // which always vis'es the prototype root, even if it is marked // hidden. _writeJobCtx.CreatePrimWriterHierarchy( - prototypeDagPath, - prototypeUsdPath, - /*forceUninstance*/ false, - /*exportRootVisibility*/ false, - &_prototypeWriters); + prototypeDagPath, + prototypeUsdPath, + /*forceUninstance*/ false, + /*exportRootVisibility*/ false, + &_prototypeWriters); prototypesRel.AddTarget(prototypeUsdPath); } @@ -363,7 +334,7 @@ PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( if (writer->GetUsdPath().GetParentPath() == prototypesGroupPath) { if (const UsdPrim writerPrim = writer->GetUsdPrim()) { UsdModelAPI primModelAPI(writerPrim); - TfToken kind; + TfToken kind; primModelAPI.GetKind(&kind); if (!KindRegistry::IsA(kind, KindTokens->component)) { primModelAPI.SetKind(KindTokens->component); @@ -381,7 +352,8 @@ PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( GfVec3d origin; if (_GetTransformedOriginInLocalSpace(opData.mayaPath, &origin)) { UsdGeomXformOp translateOp = opData.op; - UsdMayaWriteUtil::SetAttribute(translateOp.GetAttr(), -origin, usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + translateOp.GetAttr(), -origin, usdTime, _GetSparseValueWriter()); } } } @@ -395,25 +367,24 @@ PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( MPlug inputPointsSrc = UsdMayaUtil::GetConnected(inputPointsDest); if (inputPointsSrc.isNull()) { - TF_WARN("inputPoints not connected on instancer '%s'", - GetDagPath().fullPathName().asChar()); + TF_WARN( + "inputPoints not connected on instancer '%s'", GetDagPath().fullPathName().asChar()); return false; } auto holder = UsdMayaUtil::GetPlugDataHandle(inputPointsSrc); if (!holder) { - TF_WARN("Unable to read inputPoints data handle for instancer '%s'", - GetDagPath().fullPathName().asChar()); + TF_WARN( + "Unable to read inputPoints data handle for instancer '%s'", + GetDagPath().fullPathName().asChar()); return false; } - MFnArrayAttrsData inputPointsData(holder->GetDataHandle().data(), - &status); + MFnArrayAttrsData inputPointsData(holder->GetDataHandle().data(), &status); CHECK_MSTATUS_AND_RETURN(status, false); if (!UsdMayaWriteUtil::WriteArrayAttrsToInstancer( - inputPointsData, instancer, _numPrototypes, usdTime, - _GetSparseValueWriter())) { + inputPointsData, instancer, _numPrototypes, usdTime, _GetSparseValueWriter())) { return false; } @@ -421,15 +392,15 @@ PxrUsdTranslators_InstancerWriter::writeInstancerAttrs( instancer.GetPrim().GetStage()->Load(instancer.GetPath()); VtArray extent(2); if (instancer.ComputeExtentAtTime(&extent, usdTime, usdTime)) { - UsdMayaWriteUtil::SetAttribute(instancer.CreateExtentAttr(), &extent, usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + instancer.CreateExtentAttr(), &extent, usdTime, _GetSparseValueWriter()); } return true; } /* virtual */ -void -PxrUsdTranslators_InstancerWriter::PostExport() +void PxrUsdTranslators_InstancerWriter::PostExport() { for (UsdMayaPrimWriterSharedPtr& writer : _prototypeWriters) { writer->PostExport(); @@ -446,18 +417,12 @@ PxrUsdTranslators_InstancerWriter::PostExport() } /* virtual */ -bool -PxrUsdTranslators_InstancerWriter::ShouldPruneChildren() const -{ - return true; -} +bool PxrUsdTranslators_InstancerWriter::ShouldPruneChildren() const { return true; } /* virtual */ -const SdfPathVector& -PxrUsdTranslators_InstancerWriter::GetModelPaths() const +const SdfPathVector& PxrUsdTranslators_InstancerWriter::GetModelPaths() const { return _modelPaths; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/instancerWriter.h b/lib/usd/translators/instancerWriter.h index 6405de11a0..4554680e38 100644 --- a/lib/usd/translators/instancerWriter.h +++ b/lib/usd/translators/instancerWriter.h @@ -18,10 +18,9 @@ /// \file -#include - -#include -#include +#include +#include +#include #include #include @@ -29,9 +28,10 @@ #include #include -#include -#include -#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE @@ -51,32 +51,31 @@ class PxrUsdTranslators_InstancerWriter : public UsdMayaTransformWriter { public: PxrUsdTranslators_InstancerWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); - void Write(const UsdTimeCode& usdTime) override; - void PostExport() override; - bool ShouldPruneChildren() const override; + void Write(const UsdTimeCode& usdTime) override; + void PostExport() override; + bool ShouldPruneChildren() const override; const SdfPathVector& GetModelPaths() const override; protected: - bool writeInstancerAttrs( - const UsdTimeCode& usdTime, - const UsdGeomPointInstancer& instancer); + bool writeInstancerAttrs(const UsdTimeCode& usdTime, const UsdGeomPointInstancer& instancer); private: bool _NeedsExtraInstancerTranslate( - const MDagPath& prototypeDagPath, - bool* instancerTranslateAnimated) const; + const MDagPath& prototypeDagPath, + bool* instancerTranslateAnimated) const; /// Used internally by PxrUsdTranslators_InstancerWriter to keep track of the /// instancerTranslate xformOp for compensating Maya's instancer position /// behavior. - struct _TranslateOpData { - MDagPath mayaPath; + struct _TranslateOpData + { + MDagPath mayaPath; UsdGeomXformOp op; - bool isAnimated; + bool isAnimated; }; /// Number of prototypes that have been set up so far. @@ -91,8 +90,6 @@ class PxrUsdTranslators_InstancerWriter : public UsdMayaTransformWriter SdfPathVector _modelPaths; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/translators/jointWriter.cpp b/lib/usd/translators/jointWriter.cpp index deb07236d6..e0e7e43140 100644 --- a/lib/usd/translators/jointWriter.cpp +++ b/lib/usd/translators/jointWriter.cpp @@ -15,21 +15,19 @@ // #include "jointWriter.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -#include #include #include +#include #include #include #include @@ -40,15 +38,17 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE @@ -56,24 +56,24 @@ PXRUSDMAYA_REGISTER_WRITER(joint, PxrUsdTranslators_JointWriter); PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(joint, UsdSkelSkeleton); PxrUsdTranslators_JointWriter::PxrUsdTranslators_JointWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx), - _valid(false) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) + , _valid(false) { if (!TF_VERIFY(GetDagPath().isValid())) { return; } const TfToken& exportSkels = _GetExportArgs().exportSkels; - if (exportSkels != UsdMayaJobExportArgsTokens->auto_ && - exportSkels != UsdMayaJobExportArgsTokens->explicit_) { + if (exportSkels != UsdMayaJobExportArgsTokens->auto_ + && exportSkels != UsdMayaJobExportArgsTokens->explicit_) { return; } - SdfPath skelPath = - UsdMayaJointUtil::getSkeletonPath(GetDagPath(), _GetExportArgs().stripNamespaces); + SdfPath skelPath + = UsdMayaJointUtil::getSkeletonPath(GetDagPath(), _GetExportArgs().stripNamespaces); _skel = UsdSkelSkeleton::Define(GetUsdStage(), skelPath); if (!TF_VERIFY(_skel)) { @@ -84,31 +84,26 @@ PxrUsdTranslators_JointWriter::PxrUsdTranslators_JointWriter( } /// Whether the transform plugs on a transform node are animated. -static -bool -_IsTransformNodeAnimated(const MDagPath& dagPath) +static bool _IsTransformNodeAnimated(const MDagPath& dagPath) { MFnDependencyNode node(dagPath.node()); - return UsdMayaUtil::isPlugAnimated(node.findPlug("translateX")) || - UsdMayaUtil::isPlugAnimated(node.findPlug("translateY")) || - UsdMayaUtil::isPlugAnimated(node.findPlug("translateZ")) || - UsdMayaUtil::isPlugAnimated(node.findPlug("rotateX")) || - UsdMayaUtil::isPlugAnimated(node.findPlug("rotateY")) || - UsdMayaUtil::isPlugAnimated(node.findPlug("rotateZ")) || - UsdMayaUtil::isPlugAnimated(node.findPlug("scaleX")) || - UsdMayaUtil::isPlugAnimated(node.findPlug("scaleY")) || - UsdMayaUtil::isPlugAnimated(node.findPlug("scaleZ")); + return UsdMayaUtil::isPlugAnimated(node.findPlug("translateX")) + || UsdMayaUtil::isPlugAnimated(node.findPlug("translateY")) + || UsdMayaUtil::isPlugAnimated(node.findPlug("translateZ")) + || UsdMayaUtil::isPlugAnimated(node.findPlug("rotateX")) + || UsdMayaUtil::isPlugAnimated(node.findPlug("rotateY")) + || UsdMayaUtil::isPlugAnimated(node.findPlug("rotateZ")) + || UsdMayaUtil::isPlugAnimated(node.findPlug("scaleX")) + || UsdMayaUtil::isPlugAnimated(node.findPlug("scaleY")) + || UsdMayaUtil::isPlugAnimated(node.findPlug("scaleZ")); } /// Gets the world-space rest transform for a single dag path. -static -GfMatrix4d -_GetJointWorldBindTransform(const MDagPath& dagPath) +static GfMatrix4d _GetJointWorldBindTransform(const MDagPath& dagPath) { MFnDagNode dagNode(dagPath); - MMatrix restTransformWorld; - if (UsdMayaUtil::getPlugMatrix( - dagNode, "bindPose", &restTransformWorld)) { + MMatrix restTransformWorld; + if (UsdMayaUtil::getPlugMatrix(dagNode, "bindPose", &restTransformWorld)) { return GfMatrix4d(restTransformWorld.matrix); } // No bindPose. Assume it's identity. @@ -116,13 +111,11 @@ _GetJointWorldBindTransform(const MDagPath& dagPath) } /// Gets world-space bind transforms for all specified dag paths. -static -VtMatrix4dArray -_GetJointWorldBindTransforms( - const UsdSkelTopology& topology, - const std::vector& jointDagPaths) +static VtMatrix4dArray _GetJointWorldBindTransforms( + const UsdSkelTopology& topology, + const std::vector& jointDagPaths) { - size_t numJoints = jointDagPaths.size(); + size_t numJoints = jointDagPaths.size(); VtMatrix4dArray worldXforms(numJoints); for (size_t i = 0; i < jointDagPaths.size(); ++i) { worldXforms[i] = _GetJointWorldBindTransform(jointDagPaths[i]); @@ -131,9 +124,7 @@ _GetJointWorldBindTransforms( } /// Find a dagPose that holds a bind pose for \p dagPath. -static -MObject -_FindBindPose(const MDagPath& dagPath) +static MObject _FindBindPose(const MDagPath& dagPath) { MStatus status; @@ -154,7 +145,7 @@ _FindBindPose(const MDagPath& dagPath) // or not they represent a bind pose. MFnDependencyNode poseDep(outputNode, &status); - MPlug bindPosePlug = poseDep.findPlug("bindPose", &status); + MPlug bindPosePlug = poseDep.findPlug("bindPose", &status); if (status) { if (bindPosePlug.asBool()) { return outputNode; @@ -170,26 +161,23 @@ _FindBindPose(const MDagPath& dagPath) /// Get the member indices of all objects in \p dagPaths within the /// members array plug of a dagPose. /// Returns true only if all \p dagPaths can be mapped to a dagPose member. -static -bool -_FindDagPoseMembers( - const MFnDependencyNode& dagPoseDep, - const std::vector& dagPaths, - std::vector* indices) +static bool _FindDagPoseMembers( + const MFnDependencyNode& dagPoseDep, + const std::vector& dagPaths, + std::vector* indices) { MStatus status; - MPlug membersPlug = dagPoseDep.findPlug("members", &status); + MPlug membersPlug = dagPoseDep.findPlug("members", &status); CHECK_MSTATUS_AND_RETURN(status, false); // Build a map of dagPath->index. - struct _HashObjectHandle { - std::size_t operator()(const MObjectHandle& o) const { - return o.hashCode(); - } + struct _HashObjectHandle + { + std::size_t operator()(const MObjectHandle& o) const { return o.hashCode(); } }; - std::unordered_map pathIndexMap; + std::unordered_map pathIndexMap; for (size_t i = 0; i < dagPaths.size(); ++i) { pathIndexMap[MObjectHandle(dagPaths[i].node())] = i; } @@ -197,8 +185,8 @@ _FindDagPoseMembers( MPlugArray inputs; indices->clear(); - indices->resize(std::min(membersPlug.numElements(), - static_cast(dagPaths.size())), -1); + indices->resize( + std::min(membersPlug.numElements(), static_cast(dagPaths.size())), -1); for (unsigned int i = 0; i < membersPlug.numElements(); ++i) { @@ -207,7 +195,7 @@ _FindDagPoseMembers( for (unsigned int j = 0; j < inputs.length(); ++j) { MObjectHandle connNode(inputs[j].node()); - auto it = pathIndexMap.find(connNode); + auto it = pathIndexMap.find(connNode); if (it != pathIndexMap.end()) { (*indices)[it->second] = i; } @@ -218,20 +206,20 @@ _FindDagPoseMembers( for (size_t i = 0; i < indices->size(); ++i) { int index = (*indices)[i]; if (index < 0) { - TF_WARN("Node '%s' is not a member of dagPose '%s'.", - MFnDependencyNode(dagPaths[i].node()).name().asChar(), - dagPoseDep.name().asChar()); + TF_WARN( + "Node '%s' is not a member of dagPose '%s'.", + MFnDependencyNode(dagPaths[i].node()).name().asChar(), + dagPoseDep.name().asChar()); return false; } } return true; } -bool -_GetLocalTransformForDagPoseMember( - const MFnDependencyNode& dagPoseDep, - unsigned int index, - GfMatrix4d* xform) +bool _GetLocalTransformForDagPoseMember( + const MFnDependencyNode& dagPoseDep, + unsigned int index, + GfMatrix4d* xform) { MStatus status; @@ -253,24 +241,24 @@ _GetLocalTransformForDagPoseMember( /// Get local-space bind transforms to use as rest transforms. /// The dagPose is expected to hold the local transforms. -static -bool -_GetJointLocalRestTransformsFromDagPose( - const SdfPath& skelPath, - const MDagPath& rootJoint, - const std::vector& jointDagPaths, - VtMatrix4dArray* xforms) +static bool _GetJointLocalRestTransformsFromDagPose( + const SdfPath& skelPath, + const MDagPath& rootJoint, + const std::vector& jointDagPaths, + VtMatrix4dArray* xforms) { // Use whatever bindPose the root joint is a member of. MObject bindPose = _FindBindPose(rootJoint); if (bindPose.isNull()) { - TF_WARN("%s -- Could not find a dagPose node holding a bind pose: " - "The Skeleton's 'restTransforms' property will not be " - "authored.", skelPath.GetText()); + TF_WARN( + "%s -- Could not find a dagPose node holding a bind pose: " + "The Skeleton's 'restTransforms' property will not be " + "authored.", + skelPath.GetText()); return false; } - MStatus status; + MStatus status; MFnDependencyNode bindPoseDep(bindPose, &status); CHECK_MSTATUS_AND_RETURN(status, false); @@ -282,12 +270,14 @@ _GetJointLocalRestTransformsFromDagPose( xforms->resize(jointDagPaths.size()); for (size_t i = 0; i < xforms->size(); ++i) { if (!_GetLocalTransformForDagPoseMember( - bindPoseDep, memberIndices[i], xforms->data()+i)) { - TF_WARN("%s -- Failed retrieving the local transform of joint '%s' " - "from dagPose '%s': The Skeleton's 'restTransforms' " - "property will not be authored.", skelPath.GetText(), - jointDagPaths[i].fullPathName().asChar(), - bindPoseDep.name().asChar()); + bindPoseDep, memberIndices[i], xforms->data() + i)) { + TF_WARN( + "%s -- Failed retrieving the local transform of joint '%s' " + "from dagPose '%s': The Skeleton's 'restTransforms' " + "property will not be authored.", + skelPath.GetText(), + jointDagPaths[i].fullPathName().asChar(), + bindPoseDep.name().asChar()); return false; } } @@ -295,9 +285,7 @@ _GetJointLocalRestTransformsFromDagPose( } /// Gets the world-space transform of \p dagPath at the current time. -static -GfMatrix4d -_GetJointWorldTransform(const MDagPath& dagPath) +static GfMatrix4d _GetJointWorldTransform(const MDagPath& dagPath) { // Don't use Maya's built-in getTranslation(), etc. when extracting the // transform because: @@ -319,11 +307,9 @@ _GetJointWorldTransform(const MDagPath& dagPath) } /// Gets the world-space transform of \p dagPath at the current time. -static -GfMatrix4d -_GetJointLocalTransform(const MDagPath& dagPath) +static GfMatrix4d _GetJointLocalTransform(const MDagPath& dagPath) { - MStatus status; + MStatus status; MFnTransform xform(dagPath, &status); if (status) { MTransformationMatrix mx = xform.transformation(&status); @@ -336,11 +322,7 @@ _GetJointLocalTransform(const MDagPath& dagPath) /// Computes world-space joint transforms for all specified dag paths /// at the current time. -static -bool -_GetJointWorldTransforms( - const std::vector& dagPaths, - VtMatrix4dArray* xforms) +static bool _GetJointWorldTransforms(const std::vector& dagPaths, VtMatrix4dArray* xforms) { xforms->resize(dagPaths.size()); GfMatrix4d* xformsData = xforms->data(); @@ -352,13 +334,11 @@ _GetJointWorldTransforms( /// Computes joint-local transforms for all specified dag paths /// at the current time. -static -bool -_GetJointLocalTransforms( - const UsdSkelTopology& topology, - const std::vector& dagPaths, - const GfMatrix4d& rootXf, - VtMatrix4dArray* localXforms) +static bool _GetJointLocalTransforms( + const UsdSkelTopology& topology, + const std::vector& dagPaths, + const GfMatrix4d& rootXf, + VtMatrix4dArray* localXforms) { VtMatrix4dArray worldXforms; if (_GetJointWorldTransforms(dagPaths, &worldXforms)) { @@ -369,23 +349,20 @@ _GetJointLocalTransforms( for (auto& xf : worldInvXforms) xf = xf.GetInverse(); - return UsdSkelComputeJointLocalTransforms(topology, worldXforms, - worldInvXforms, - localXforms, &rootInvXf); + return UsdSkelComputeJointLocalTransforms( + topology, worldXforms, worldInvXforms, localXforms, &rootInvXf); } return true; } /// Returns true if the joint's transform definitely matches its rest transform /// over all exported frames. -static -bool -_JointMatchesRestPose( - size_t jointIdx, - const MDagPath& dagPath, - const VtMatrix4dArray& xforms, - const VtMatrix4dArray& restXforms, - bool exportingAnimation) +static bool _JointMatchesRestPose( + size_t jointIdx, + const MDagPath& dagPath, + const VtMatrix4dArray& xforms, + const VtMatrix4dArray& restXforms, + bool exportingAnimation) { if (exportingAnimation && _IsTransformNodeAnimated(dagPath)) return false; @@ -397,17 +374,15 @@ _JointMatchesRestPose( /// Given the list of USD joint names and dag paths, returns the joints that /// (1) are moved from their rest poses or (2) have animation, if we are going /// to export animation. -static -void -_GetAnimatedJoints( - const UsdSkelTopology& topology, - const VtTokenArray& usdJointNames, - const MDagPath& rootDagPath, - const std::vector& jointDagPaths, - const VtMatrix4dArray& restXforms, - VtTokenArray* animatedJointNames, - std::vector* animatedJointPaths, - bool exportingAnimation) +static void _GetAnimatedJoints( + const UsdSkelTopology& topology, + const VtTokenArray& usdJointNames, + const MDagPath& rootDagPath, + const std::vector& jointDagPaths, + const VtMatrix4dArray& restXforms, + VtTokenArray* animatedJointNames, + std::vector* animatedJointPaths, + bool exportingAnimation) { if (!TF_VERIFY(usdJointNames.size() == jointDagPaths.size())) { return; @@ -427,32 +402,29 @@ _GetAnimatedJoints( // Compute the current local xforms of all joints so we can decide // whether or not they need to have a value encoded on the anim prim. GfMatrix4d rootXform = _GetJointWorldTransform(rootDagPath); - _GetJointLocalTransforms(topology, jointDagPaths, - rootXform, &localXforms); + _GetJointLocalTransforms(topology, jointDagPaths, rootXform, &localXforms); } // The resulting vector contains only animated joints or joints not // in their rest pose. The order is *not* guaranteed to be the Skeleton // order, because UsdSkel allows arbitrary order on SkelAnimation. for (size_t i = 0; i < jointDagPaths.size(); ++i) { - const TfToken& jointName = usdJointNames[i]; + const TfToken& jointName = usdJointNames[i]; const MDagPath& dagPath = jointDagPaths[i]; - if (!_JointMatchesRestPose(i, jointDagPaths[i], localXforms, - restXforms, exportingAnimation)) { + if (!_JointMatchesRestPose( + i, jointDagPaths[i], localXforms, restXforms, exportingAnimation)) { animatedJointNames->push_back(jointName); animatedJointPaths->push_back(dagPath); } } } -bool -PxrUsdTranslators_JointWriter::_WriteRestState() +bool PxrUsdTranslators_JointWriter::_WriteRestState() { // Check if the root joint is the special root joint created // for round-tripping UsdSkel data. - bool haveUsdSkelXform = - UsdMayaTranslatorSkel::IsUsdSkeleton(GetDagPath()); + bool haveUsdSkelXform = UsdMayaTranslatorSkel::IsUsdSkeleton(GetDagPath()); if (!haveUsdSkelXform) { // We don't have a joint that represents the Skeleton. @@ -462,51 +434,55 @@ PxrUsdTranslators_JointWriter::_WriteRestState() UsdMayaTranslatorSkel::MarkSkelAsMayaGenerated(_skel); } - UsdMayaJointUtil::getJointHierarchyComponents(GetDagPath(), - &_skelXformPath, - &_jointHierarchyRootPath, - &_joints); + UsdMayaJointUtil::getJointHierarchyComponents( + GetDagPath(), &_skelXformPath, &_jointHierarchyRootPath, &_joints); - VtTokenArray skelJointNames = - UsdMayaJointUtil::getJointNames(_joints, GetDagPath(), - _GetExportArgs().stripNamespaces); + VtTokenArray skelJointNames + = UsdMayaJointUtil::getJointNames(_joints, GetDagPath(), _GetExportArgs().stripNamespaces); _topology = UsdSkelTopology(skelJointNames); std::string whyNotValid; if (!_topology.Validate(&whyNotValid)) { - TF_CODING_ERROR("Joint topology is invalid: %s", - whyNotValid.c_str()); + TF_CODING_ERROR("Joint topology is invalid: %s", whyNotValid.c_str()); return false; } // Setup binding relationships on the instance prim, // so that the root xform establishes a skeleton instance // with the right transform. - const UsdSkelBindingAPI binding = UsdMayaTranslatorUtil - ::GetAPISchemaForAuthoring(_skel.GetPrim()); + const UsdSkelBindingAPI binding + = UsdMayaTranslatorUtil ::GetAPISchemaForAuthoring(_skel.GetPrim()); // Mark the bindings for post processing. - UsdMayaWriteUtil::SetAttribute(_skel.GetJointsAttr(), skelJointNames, UsdTimeCode::Default(), _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + _skel.GetJointsAttr(), skelJointNames, UsdTimeCode::Default(), _GetSparseValueWriter()); SdfPath skelPath = _skel.GetPrim().GetPath(); - _writeJobCtx.MarkSkelBindings( - skelPath, skelPath, _GetExportArgs().exportSkels); + _writeJobCtx.MarkSkelBindings(skelPath, skelPath, _GetExportArgs().exportSkels); - VtMatrix4dArray bindXforms = - _GetJointWorldBindTransforms(_topology, _joints); - UsdMayaWriteUtil::SetAttribute(_skel.GetBindTransformsAttr(), bindXforms, UsdTimeCode::Default(), _GetSparseValueWriter()); + VtMatrix4dArray bindXforms = _GetJointWorldBindTransforms(_topology, _joints); + UsdMayaWriteUtil::SetAttribute( + _skel.GetBindTransformsAttr(), bindXforms, UsdTimeCode::Default(), _GetSparseValueWriter()); VtMatrix4dArray restXforms; - if (_GetJointLocalRestTransformsFromDagPose( - skelPath, GetDagPath(), _joints, &restXforms)) { - UsdMayaWriteUtil::SetAttribute(_skel.GetRestTransformsAttr(), restXforms, UsdTimeCode::Default(), _GetSparseValueWriter()); + if (_GetJointLocalRestTransformsFromDagPose(skelPath, GetDagPath(), _joints, &restXforms)) { + UsdMayaWriteUtil::SetAttribute( + _skel.GetRestTransformsAttr(), + restXforms, + UsdTimeCode::Default(), + _GetSparseValueWriter()); } VtTokenArray animJointNames; - _GetAnimatedJoints(_topology, skelJointNames, GetDagPath(), - _joints, restXforms, - &animJointNames, &_animatedJoints, - !_GetExportArgs().timeSamples.empty()); + _GetAnimatedJoints( + _topology, + skelJointNames, + GetDagPath(), + _joints, + restXforms, + &animJointNames, + &_animatedJoints, + !_GetExportArgs().timeSamples.empty()); if (haveUsdSkelXform) { _skelXformAttr = _skel.MakeMatrixXform(); @@ -524,12 +500,15 @@ PxrUsdTranslators_JointWriter::_WriteRestState() _skelAnim = UsdSkelAnimation::Define(GetUsdStage(), animPath); if (TF_VERIFY(_skelAnim)) { - _skelToAnimMapper = - UsdSkelAnimMapper(skelJointNames, animJointNames); + _skelToAnimMapper = UsdSkelAnimMapper(skelJointNames, animJointNames); - UsdMayaWriteUtil::SetAttribute(_skelAnim.GetJointsAttr(), animJointNames, UsdTimeCode::Default(), _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + _skelAnim.GetJointsAttr(), + animJointNames, + UsdTimeCode::Default(), + _GetSparseValueWriter()); - binding.CreateAnimationSourceRel().SetTargets({animPath}); + binding.CreateAnimationSourceRel().SetTargets({ animPath }); } else { return false; } @@ -538,8 +517,7 @@ PxrUsdTranslators_JointWriter::_WriteRestState() } /* virtual */ -void -PxrUsdTranslators_JointWriter::Write(const UsdTimeCode& usdTime) +void PxrUsdTranslators_JointWriter::Write(const UsdTimeCode& usdTime) { if (usdTime.IsDefault()) { _valid = _WriteRestState(); @@ -577,8 +555,7 @@ PxrUsdTranslators_JointWriter::Write(const UsdTimeCode& usdTime) GfMatrix4d rootXf = _GetJointWorldTransform(_jointHierarchyRootPath); VtMatrix4dArray localXforms; - if (_GetJointLocalTransforms(_topology, _joints, - rootXf, &localXforms)) { + if (_GetJointLocalTransforms(_topology, _joints, rootXf, &localXforms)) { // Remap local xforms into the (possibly sparse) anim order. VtMatrix4dArray animLocalXforms; @@ -587,20 +564,23 @@ PxrUsdTranslators_JointWriter::Write(const UsdTimeCode& usdTime) VtVec3fArray translations; VtQuatfArray rotations; VtVec3hArray scales; - if (UsdSkelDecomposeTransforms(animLocalXforms, &translations, - &rotations, &scales)) { + if (UsdSkelDecomposeTransforms( + animLocalXforms, &translations, &rotations, &scales)) { // XXX It is difficult for us to tell which components are // actually animated since we rely on decomposition to get // separate anim components. // In the future, we may want to RLE-compress the data in // PostExport to remove redundant time samples. - UsdMayaWriteUtil::SetAttribute(_skelAnim.GetTranslationsAttr(), - &translations, usdTime, _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(_skelAnim.GetRotationsAttr(), - &rotations, usdTime, _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(_skelAnim.GetScalesAttr(), - &scales, usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + _skelAnim.GetTranslationsAttr(), + &translations, + usdTime, + _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + _skelAnim.GetRotationsAttr(), &rotations, usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + _skelAnim.GetScalesAttr(), &scales, usdTime, _GetSparseValueWriter()); } } } @@ -608,19 +588,13 @@ PxrUsdTranslators_JointWriter::Write(const UsdTimeCode& usdTime) } /* virtual */ -bool -PxrUsdTranslators_JointWriter::ExportsGprims() const +bool PxrUsdTranslators_JointWriter::ExportsGprims() const { // Nether the Skeleton nor its animation sources are gprims. return false; } /* virtual */ -bool -PxrUsdTranslators_JointWriter::ShouldPruneChildren() const -{ - return true; -} - +bool PxrUsdTranslators_JointWriter::ShouldPruneChildren() const { return true; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/jointWriter.h b/lib/usd/translators/jointWriter.h index 7d9562f968..92cbbae719 100644 --- a/lib/usd/translators/jointWriter.h +++ b/lib/usd/translators/jointWriter.h @@ -18,19 +18,19 @@ /// \file -#include +#include +#include #include #include #include #include -#include #include +#include #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -50,9 +50,9 @@ class PxrUsdTranslators_JointWriter : public UsdMayaPrimWriter { public: PxrUsdTranslators_JointWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); void Write(const UsdTimeCode& usdTime) override; bool ExportsGprims() const override; @@ -61,8 +61,8 @@ class PxrUsdTranslators_JointWriter : public UsdMayaPrimWriter private: bool _WriteRestState(); - bool _valid; - UsdSkelSkeleton _skel; + bool _valid; + UsdSkelSkeleton _skel; UsdSkelAnimation _skelAnim; /// The dag path defining the root transform of the Skeleton. @@ -71,15 +71,13 @@ class PxrUsdTranslators_JointWriter : public UsdMayaPrimWriter /// The common parent path of all proper joints. MDagPath _jointHierarchyRootPath; - UsdSkelTopology _topology; - UsdSkelAnimMapper _skelToAnimMapper; + UsdSkelTopology _topology; + UsdSkelAnimMapper _skelToAnimMapper; std::vector _joints, _animatedJoints; - UsdAttribute _skelXformAttr; - bool _skelXformIsAnimated; + UsdAttribute _skelXformAttr; + bool _skelXformIsAnimated; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/translators/lightReader.cpp b/lib/usd/translators/lightReader.cpp index c1f873ce5e..8875c24e5b 100644 --- a/lib/usd/translators/lightReader.cpp +++ b/lib/usd/translators/lightReader.cpp @@ -13,6 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // +#include +#include + #include #include #include @@ -23,9 +26,6 @@ #include #include -#include -#include - PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_DEFINE_READER(UsdLuxCylinderLight, args, context) @@ -73,5 +73,4 @@ PXRUSDMAYA_DEFINE_READER(UsdRiPxrEnvDayLight, args, context) return UsdMayaTranslatorRfMLight::Read(args, context); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/lightWriter.cpp b/lib/usd/translators/lightWriter.cpp index 674a1f6ed1..528a438f17 100644 --- a/lib/usd/translators/lightWriter.cpp +++ b/lib/usd/translators/lightWriter.cpp @@ -63,5 +63,4 @@ PXRUSDMAYA_DEFINE_WRITER(PxrSphereLight, args, context) return UsdMayaTranslatorRfMLight::Write(args, context); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/locatorWriter.cpp b/lib/usd/translators/locatorWriter.cpp index a9dbf39a17..3081738281 100644 --- a/lib/usd/translators/locatorWriter.cpp +++ b/lib/usd/translators/locatorWriter.cpp @@ -15,15 +15,15 @@ // #include "locatorWriter.h" -#include +#include +#include +#include #include #include #include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -31,21 +31,18 @@ PXRUSDMAYA_REGISTER_WRITER(locator, PxrUsdTranslators_LocatorWriter); PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(locator, UsdGeomXform); PxrUsdTranslators_LocatorWriter::PxrUsdTranslators_LocatorWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) { if (!TF_VERIFY(GetDagPath().isValid())) { return; } - UsdGeomXform xformSchema = - UsdGeomXform::Define(GetUsdStage(), GetUsdPath()); + UsdGeomXform xformSchema = UsdGeomXform::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( - xformSchema, - "Could not define UsdGeomXform at path '%s'\n", - GetUsdPath().GetText())) { + xformSchema, "Could not define UsdGeomXform at path '%s'\n", GetUsdPath().GetText())) { return; } @@ -58,5 +55,4 @@ PxrUsdTranslators_LocatorWriter::PxrUsdTranslators_LocatorWriter( } } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/locatorWriter.h b/lib/usd/translators/locatorWriter.h index c01aba3f0c..a3cd1e9e21 100644 --- a/lib/usd/translators/locatorWriter.h +++ b/lib/usd/translators/locatorWriter.h @@ -18,13 +18,13 @@ /// \file -#include +#include +#include #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -43,13 +43,11 @@ class PxrUsdTranslators_LocatorWriter : public UsdMayaPrimWriter { public: PxrUsdTranslators_LocatorWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/translators/materialReader.cpp b/lib/usd/translators/materialReader.cpp index e290dc5464..0222a44ae8 100644 --- a/lib/usd/translators/materialReader.cpp +++ b/lib/usd/translators/materialReader.cpp @@ -13,12 +13,12 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include - #include #include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_DEFINE_READER(UsdShadeMaterial, args, context) @@ -26,10 +26,8 @@ PXRUSDMAYA_DEFINE_READER(UsdShadeMaterial, args, context) bool importUnboundShaders = args.ShouldImportUnboundShaders(); if (importUnboundShaders) { const UsdPrim& usdPrim = args.GetUsdPrim(); - UsdMayaTranslatorMaterial::Read(args.GetJobArguments(), - UsdShadeMaterial(usdPrim), - UsdGeomGprim(), - context); + UsdMayaTranslatorMaterial::Read( + args.GetJobArguments(), UsdShadeMaterial(usdPrim), UsdGeomGprim(), context); } // Always prune materials' namespace descendants - assume that it's just // part of the material's shading network. @@ -37,7 +35,4 @@ PXRUSDMAYA_DEFINE_READER(UsdShadeMaterial, args, context) return true; } - - PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/usd/translators/mayaReferenceReader.cpp b/lib/usd/translators/mayaReferenceReader.cpp index 594a2a86a3..baec34028b 100644 --- a/lib/usd/translators/mayaReferenceReader.cpp +++ b/lib/usd/translators/mayaReferenceReader.cpp @@ -29,14 +29,15 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include +#include #include #include #include -#include -#include +#include + #include #include @@ -45,20 +46,15 @@ PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_DEFINE_READER(MayaUsd_SchemasMayaReference, args, context) { const UsdPrim& usdPrim = args.GetUsdPrim(); - MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); - return UsdMayaTranslatorMayaReference::update( - usdPrim, - parentNode); + MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); + return UsdMayaTranslatorMayaReference::update(usdPrim, parentNode); } PXRUSDMAYA_DEFINE_READER(MayaUsd_SchemasALMayaReference, args, context) { const UsdPrim& usdPrim = args.GetUsdPrim(); - MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); - return UsdMayaTranslatorMayaReference::update( - usdPrim, - parentNode); + MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); + return UsdMayaTranslatorMayaReference::update(usdPrim, parentNode); } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/usd/translators/mayaReferenceUpdater.cpp b/lib/usd/translators/mayaReferenceUpdater.cpp index 80df3bf8c9..505481ccbb 100644 --- a/lib/usd/translators/mayaReferenceUpdater.cpp +++ b/lib/usd/translators/mayaReferenceUpdater.cpp @@ -15,50 +15,53 @@ // #include "mayaReferenceUpdater.h" -#include +#include +#include +#include +#include + #include #include +#include #include #include #include #include -#include -#include -#include -#include #include #include PXR_NAMESPACE_OPEN_SCOPE -PXRUSDMAYA_REGISTER_UPDATER(MayaUsd_SchemasMayaReference, PxrUsdTranslators_MayaReferenceUpdater, (UsdMayaPrimUpdater::Supports::Push | UsdMayaPrimUpdater::Supports::Clear)); -PXRUSDMAYA_REGISTER_UPDATER(MayaUsd_SchemasALMayaReference, PxrUsdTranslators_MayaReferenceUpdater, (UsdMayaPrimUpdater::Supports::Push | UsdMayaPrimUpdater::Supports::Clear)); +PXRUSDMAYA_REGISTER_UPDATER( + MayaUsd_SchemasMayaReference, + PxrUsdTranslators_MayaReferenceUpdater, + (UsdMayaPrimUpdater::Supports::Push | UsdMayaPrimUpdater::Supports::Clear)); +PXRUSDMAYA_REGISTER_UPDATER( + MayaUsd_SchemasALMayaReference, + PxrUsdTranslators_MayaReferenceUpdater, + (UsdMayaPrimUpdater::Supports::Push | UsdMayaPrimUpdater::Supports::Clear)); PxrUsdTranslators_MayaReferenceUpdater::PxrUsdTranslators_MayaReferenceUpdater( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath) : - UsdMayaPrimUpdater(depNodeFn, usdPath) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath) + : UsdMayaPrimUpdater(depNodeFn, usdPath) { } /* virtual */ -bool -PxrUsdTranslators_MayaReferenceUpdater::Pull(UsdMayaPrimUpdaterContext* context) +bool PxrUsdTranslators_MayaReferenceUpdater::Pull(UsdMayaPrimUpdaterContext* context) { const UsdPrim& usdPrim = GetUsdPrim(*context); const MObject& parentNode = GetMayaObject(); - - UsdMayaTranslatorMayaReference::update( - usdPrim, - parentNode); + + UsdMayaTranslatorMayaReference::update(usdPrim, parentNode); return true; } /* virtual */ -void -PxrUsdTranslators_MayaReferenceUpdater::Clear(UsdMayaPrimUpdaterContext* context) +void PxrUsdTranslators_MayaReferenceUpdater::Clear(UsdMayaPrimUpdaterContext* context) { const MObject& parentNode = GetMayaObject(); diff --git a/lib/usd/translators/mayaReferenceUpdater.h b/lib/usd/translators/mayaReferenceUpdater.h index 553eef263d..d6f1352553 100644 --- a/lib/usd/translators/mayaReferenceUpdater.h +++ b/lib/usd/translators/mayaReferenceUpdater.h @@ -16,33 +16,30 @@ #ifndef PXRUSDTRANSLATORS_MAYAREFERENCE_UPDATER_H #define PXRUSDTRANSLATORS_MAYAREFERENCE_UPDATER_H -#include +#include #include -#include +#include PXR_NAMESPACE_OPEN_SCOPE class SdfPath; - /// Exports Maya cameras to UsdGeomCamera. class PxrUsdTranslators_MayaReferenceUpdater : public UsdMayaPrimUpdater { - public: - PxrUsdTranslators_MayaReferenceUpdater( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath); +public: + PxrUsdTranslators_MayaReferenceUpdater( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath); - bool Pull(UsdMayaPrimUpdaterContext* context) override; - void Clear(UsdMayaPrimUpdaterContext* context) override; + bool Pull(UsdMayaPrimUpdaterContext* context) override; + void Clear(UsdMayaPrimUpdaterContext* context) override; - protected: +protected: }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/translators/meshReader.cpp b/lib/usd/translators/meshReader.cpp index 39c7b735f4..7547a0cbcf 100644 --- a/lib/usd/translators/meshReader.cpp +++ b/lib/usd/translators/meshReader.cpp @@ -15,11 +15,6 @@ // // Modifications copyright (C) 2020 Autodesk // -#include - -#include -#include - #include #include #include @@ -30,86 +25,85 @@ #include #include +#include +#include + +#include + PXR_NAMESPACE_OPEN_SCOPE -namespace +namespace { +bool assignMaterial( + const UsdGeomMesh& mesh, + const UsdMayaPrimReaderArgs& args, + const MObject& meshObj, + UsdMayaPrimReaderContext* context) { - bool - assignMaterial(const UsdGeomMesh& mesh, - const UsdMayaPrimReaderArgs& args, - const MObject& meshObj, - UsdMayaPrimReaderContext* context) - { - // If a material is bound, create (or reuse if already present) and assign it - // If no binding is present, assign the mesh to the default shader - const UsdMayaJobImportArgs& jobArguments = args.GetJobArguments(); - return UsdMayaTranslatorMaterial::AssignMaterial(jobArguments, - mesh, - meshObj, - context); - } + // If a material is bound, create (or reuse if already present) and assign it + // If no binding is present, assign the mesh to the default shader + const UsdMayaJobImportArgs& jobArguments = args.GetJobArguments(); + return UsdMayaTranslatorMaterial::AssignMaterial(jobArguments, mesh, meshObj, context); } +} // namespace // prim reader for mesh class MayaUsdPrimReaderMesh final : public UsdMayaPrimReader { public: - MayaUsdPrimReaderMesh(const UsdMayaPrimReaderArgs& args) - : UsdMayaPrimReader(args) {} + MayaUsdPrimReaderMesh(const UsdMayaPrimReaderArgs& args) + : UsdMayaPrimReader(args) + { + } - ~MayaUsdPrimReaderMesh() override {} + ~MayaUsdPrimReaderMesh() override { } bool Read(UsdMayaPrimReaderContext* context) override; }; -TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaPrimReaderRegistry, UsdGeomMesh) +TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaPrimReaderRegistry, UsdGeomMesh) { - UsdMayaPrimReaderRegistry::Register( - [](const UsdMayaPrimReaderArgs& args) { - return std::make_shared(args); - }); + UsdMayaPrimReaderRegistry::Register([](const UsdMayaPrimReaderArgs& args) { + return std::make_shared(args); + }); } -bool -MayaUsdPrimReaderMesh::Read(UsdMayaPrimReaderContext* context) +bool MayaUsdPrimReaderMesh::Read(UsdMayaPrimReaderContext* context) { - if(!context){ + if (!context) { return false; } - MStatus status{MS::kSuccess}; + MStatus status { MS::kSuccess }; const auto& prim = _GetArgs().GetUsdPrim(); - auto mesh = UsdGeomMesh(prim); + auto mesh = UsdGeomMesh(prim); if (!mesh) { return false; } - auto parentNode = context->GetMayaNode(prim.GetPath().GetParentPath(), true); + auto parentNode = context->GetMayaNode(prim.GetPath().GetParentPath(), true); MObject transformObj; - bool retStatus = UsdMayaTranslatorUtil::CreateTransformNode(prim, - parentNode, - _GetArgs(), - context, - &status, - &transformObj); - if(!retStatus){ + bool retStatus = UsdMayaTranslatorUtil::CreateTransformNode( + prim, parentNode, _GetArgs(), context, &status, &transformObj); + if (!retStatus) { return false; } // get the USD stage node from the context's registry MObject stageNode; - if (_GetArgs().GetUseAsAnimationCache()){ - stageNode = context->GetMayaNode(SdfPath(UsdMayaStageNodeTokens->MayaTypeName.GetString()),false); + if (_GetArgs().GetUseAsAnimationCache()) { + stageNode = context->GetMayaNode( + SdfPath(UsdMayaStageNodeTokens->MayaTypeName.GetString()), false); } - MayaUsd::TranslatorMeshRead meshRead(mesh, - prim, - transformObj, - stageNode, - _GetArgs().GetTimeInterval(), - _GetArgs().GetUseAsAnimationCache(), - &status); + MayaUsd::TranslatorMeshRead meshRead( + mesh, + prim, + transformObj, + stageNode, + _GetArgs().GetTimeInterval(), + _GetArgs().GetUseAsAnimationCache(), + &status); CHECK_MSTATUS_AND_RETURN(status, false); // mesh is a shape, so read Gprim properties @@ -120,18 +114,16 @@ MayaUsdPrimReaderMesh::Read(UsdMayaPrimReaderContext* context) // undo/redo deformable mesh (blenshape, PointBasedDeformer) if (meshRead.pointsNumTimeSamples() > 0) { - if (_GetArgs().GetUseAsAnimationCache()){ - context->RegisterNewMayaNode(meshRead.pointBasedDeformerName().asChar(), - meshRead.pointBasedDeformerNode()); - } - else { - if(meshRead.blendObject().apiType() == MFn::kBlend){ + if (_GetArgs().GetUseAsAnimationCache()) { + context->RegisterNewMayaNode( + meshRead.pointBasedDeformerName().asChar(), meshRead.pointBasedDeformerNode()); + } else { + if (meshRead.blendObject().apiType() == MFn::kBlend) { return false; } MFnBlendShapeDeformer blendFnSet(meshRead.blendObject()); - context->RegisterNewMayaNode(blendFnSet.name().asChar(), - meshRead.blendObject()); + context->RegisterNewMayaNode(blendFnSet.name().asChar(), meshRead.blendObject()); } } @@ -139,9 +131,8 @@ MayaUsdPrimReaderMesh::Read(UsdMayaPrimReaderContext* context) assignMaterial(mesh, _GetArgs(), meshRead.meshObject(), context); // assign primvars to mesh - UsdMayaMeshReadUtils::assignPrimvarsToMesh( mesh, - meshRead.meshObject(), - _GetArgs().GetExcludePrimvarNames()); + UsdMayaMeshReadUtils::assignPrimvarsToMesh( + mesh, meshRead.meshObject(), _GetArgs().GetExcludePrimvarNames()); // assign invisible faces UsdMayaMeshReadUtils::assignInvisibleFaces(mesh, meshRead.meshObject()); diff --git a/lib/usd/translators/meshWriter.cpp b/lib/usd/translators/meshWriter.cpp index d41d1e8664..77cfddb2b6 100644 --- a/lib/usd/translators/meshWriter.cpp +++ b/lib/usd/translators/meshWriter.cpp @@ -15,25 +15,23 @@ // #include "meshWriter.h" -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -#include #include #include #include #include #include +#include #include #include #include @@ -43,16 +41,18 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -61,21 +61,16 @@ PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(mesh, UsdGeomMesh); TF_DEFINE_PRIVATE_TOKENS( _tokens, - ((skelJointIndices, "skel:jointIndices")) - ((skelJointWeights, "skel:jointWeights")) - ((skelGeomBindTransform, "skel:geomBindTransform")) -); + ((skelJointIndices, "skel:jointIndices"))((skelJointWeights, "skel:jointWeights"))( + (skelGeomBindTransform, "skel:geomBindTransform"))); PxrUsdTranslators_MeshWriter::PxrUsdTranslators_MeshWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) { - MayaUsd::TranslatorMeshWrite meshWriter( depNodeFn, - GetUsdStage(), - GetUsdPath(), - GetDagPath()); + MayaUsd::TranslatorMeshWrite meshWriter(depNodeFn, GetUsdStage(), GetUsdPath(), GetDagPath()); _usdPrim = meshWriter.usdMesh().GetPrim(); if (!TF_VERIFY( _usdPrim, @@ -85,14 +80,9 @@ PxrUsdTranslators_MeshWriter::PxrUsdTranslators_MeshWriter( } } -void -PxrUsdTranslators_MeshWriter::PostExport() -{ - cleanupPrimvars(); -} +void PxrUsdTranslators_MeshWriter::PostExport() { cleanupPrimvars(); } -void -PxrUsdTranslators_MeshWriter::Write(const UsdTimeCode& usdTime) +void PxrUsdTranslators_MeshWriter::Write(const UsdTimeCode& usdTime) { UsdMayaPrimWriter::Write(usdTime); @@ -100,11 +90,11 @@ PxrUsdTranslators_MeshWriter::Write(const UsdTimeCode& usdTime) writeMeshAttrs(usdTime, primSchema); } -bool -PxrUsdTranslators_MeshWriter::writeMeshAttrs(const UsdTimeCode& usdTime, - UsdGeomMesh& primSchema) +bool PxrUsdTranslators_MeshWriter::writeMeshAttrs( + const UsdTimeCode& usdTime, + UsdGeomMesh& primSchema) { - MStatus status{MS::kSuccess}; + MStatus status { MS::kSuccess }; // Exporting reference object only once if (usdTime.IsDefault() && _GetExportArgs().exportReferenceObjects) { @@ -116,32 +106,34 @@ PxrUsdTranslators_MeshWriter::writeMeshAttrs(const UsdTimeCode& usdTime, // mesh geometry. This should only be run once at default time. if (usdTime.IsDefault()) { const TfToken& exportSkin = _GetExportArgs().exportSkin; - if (exportSkin != UsdMayaJobExportArgsTokens->auto_ && - exportSkin != UsdMayaJobExportArgsTokens->explicit_) { + if (exportSkin != UsdMayaJobExportArgsTokens->auto_ + && exportSkin != UsdMayaJobExportArgsTokens->explicit_) { _skelInputMesh = MObject(); - }else if (exportSkin == UsdMayaJobExportArgsTokens->explicit_ && - !UsdSkelRoot::Find(primSchema.GetPrim())) { + } else if ( + exportSkin == UsdMayaJobExportArgsTokens->explicit_ + && !UsdSkelRoot::Find(primSchema.GetPrim())) { _skelInputMesh = MObject(); - }else { + } else { SdfPath skelPath; - _skelInputMesh = UsdMayaJointUtil::writeSkinningData(primSchema, - GetUsdPath(), - GetDagPath(), - skelPath, - _GetExportArgs().stripNamespaces, - _GetSparseValueWriter()); - - if(!_skelInputMesh.isNull()) { + _skelInputMesh = UsdMayaJointUtil::writeSkinningData( + primSchema, + GetUsdPath(), + GetDagPath(), + skelPath, + _GetExportArgs().stripNamespaces, + _GetSparseValueWriter()); + + if (!_skelInputMesh.isNull()) { // Add all skel primvars to the exclude set. // We don't want later processing to stomp on any of our data. - _excludeColorSets.insert({_tokens->skelJointIndices, - _tokens->skelJointWeights, - _tokens->skelGeomBindTransform}); + _excludeColorSets.insert({ _tokens->skelJointIndices, + _tokens->skelJointWeights, + _tokens->skelGeomBindTransform }); // Mark the bindings for post processing. _writeJobCtx.MarkSkelBindings(primSchema.GetPrim().GetPath(), skelPath, exportSkin); @@ -155,8 +147,7 @@ PxrUsdTranslators_MeshWriter::writeMeshAttrs(const UsdTimeCode& usdTime, MFnMesh finalMesh(GetDagPath(), &status); if (!status) { TF_RUNTIME_ERROR( - "Failed to get final mesh at DAG path: %s", - GetDagPath().fullPathName().asChar()); + "Failed to get final mesh at DAG path: %s", GetDagPath().fullPathName().asChar()); return false; } @@ -164,15 +155,13 @@ PxrUsdTranslators_MeshWriter::writeMeshAttrs(const UsdTimeCode& usdTime, // meshes. The general rule is to use geomMesh only for geometric data such // as vertices, faces, normals, but use finalMesh for UVs, color sets, // and user-defined tagging (e.g. subdiv tags). - MObject geomMeshObj = _skelInputMesh.isNull() ? - finalMesh.object() : _skelInputMesh; + MObject geomMeshObj = _skelInputMesh.isNull() ? finalMesh.object() : _skelInputMesh; // do not pass these to functions that need access to geomMeshObj! // geomMesh.object() returns nil for meshes of type kMeshData. - MFnMesh geomMesh(geomMeshObj, &status); + MFnMesh geomMesh(geomMeshObj, &status); if (!status) { TF_RUNTIME_ERROR( - "Failed to get geom mesh at DAG path: %s", - GetDagPath().fullPathName().asChar()); + "Failed to get geom mesh at DAG path: %s", GetDagPath().fullPathName().asChar()); return false; } @@ -189,7 +178,8 @@ PxrUsdTranslators_MeshWriter::writeMeshAttrs(const UsdTimeCode& usdTime, UsdMayaMeshWriteUtils::writePointsData(geomMesh, primSchema, usdTime, _GetSparseValueWriter()); // Write faceVertexIndices - UsdMayaMeshWriteUtils::writeFaceVertexIndicesData(geomMesh, primSchema, usdTime, _GetSparseValueWriter()); + UsdMayaMeshWriteUtils::writeFaceVertexIndicesData( + geomMesh, primSchema, usdTime, _GetSparseValueWriter()); // Read subdiv scheme tagging. If not set, we default to defaultMeshScheme // flag (this is specified by the job args but defaults to catmullClark). @@ -204,15 +194,19 @@ PxrUsdTranslators_MeshWriter::writeMeshAttrs(const UsdTimeCode& usdTime, bool emitNormals = true; // Default to emitting normals if no tagging. UsdMayaMeshReadUtils::getEmitNormalsTag(finalMesh, &emitNormals); if (emitNormals) { - UsdMayaMeshWriteUtils::writeNormalsData(geomMesh, primSchema, usdTime, _GetSparseValueWriter()); + UsdMayaMeshWriteUtils::writeNormalsData( + geomMesh, primSchema, usdTime, _GetSparseValueWriter()); } } else { // Subdivision surface - export subdiv-specific attributes. - UsdMayaMeshWriteUtils::writeSubdivInterpBound(finalMesh, primSchema, _GetSparseValueWriter()); + UsdMayaMeshWriteUtils::writeSubdivInterpBound( + finalMesh, primSchema, _GetSparseValueWriter()); - UsdMayaMeshWriteUtils::writeSubdivFVLinearInterpolation(finalMesh, primSchema, _GetSparseValueWriter()); + UsdMayaMeshWriteUtils::writeSubdivFVLinearInterpolation( + finalMesh, primSchema, _GetSparseValueWriter()); - UsdMayaMeshWriteUtils::assignSubDivTagsToUSDPrim(finalMesh, primSchema, _GetSparseValueWriter()); + UsdMayaMeshWriteUtils::assignSubDivTagsToUSDPrim( + finalMesh, primSchema, _GetSparseValueWriter()); } // Holes - we treat InvisibleFaces as holes @@ -220,7 +214,8 @@ PxrUsdTranslators_MeshWriter::writeMeshAttrs(const UsdTimeCode& usdTime, // == Write UVSets as Vec2f Primvars if (_GetExportArgs().exportMeshUVs) { - UsdMayaMeshWriteUtils::writeUVSetsAsVec2fPrimvars(finalMesh, primSchema, usdTime, _GetSparseValueWriter()); + UsdMayaMeshWriteUtils::writeUVSetsAsVec2fPrimvars( + finalMesh, primSchema, usdTime, _GetSparseValueWriter()); } // == Gather ColorSets @@ -237,23 +232,24 @@ PxrUsdTranslators_MeshWriter::writeMeshAttrs(const UsdTimeCode& usdTime, std::set colorSetNamesSet(colorSetNames.begin(), colorSetNames.end()); VtArray shadersRGBData; - VtArray shadersAlphaData; - TfToken shadersInterpolation; - VtArray shadersAssignmentIndices; + VtArray shadersAlphaData; + TfToken shadersInterpolation; + VtArray shadersAssignmentIndices; // If we're exporting displayColor or we have color sets, gather colors and // opacities from the shaders assigned to the mesh and/or its faces. // If we find a displayColor color set, the shader colors and opacities // will be used to fill in unauthored/unpainted faces in the color set. if (_GetExportArgs().exportDisplayColor || !colorSetNames.empty()) { - UsdMayaUtil::GetLinearShaderColor(finalMesh, - &shadersRGBData, - &shadersAlphaData, - &shadersInterpolation, - &shadersAssignmentIndices); + UsdMayaUtil::GetLinearShaderColor( + finalMesh, + &shadersRGBData, + &shadersAlphaData, + &shadersInterpolation, + &shadersAssignmentIndices); } - for (const std::string& colorSetName: colorSetNames) { + for (const std::string& colorSetName : colorSetNames) { if (_excludeColorSets.count(colorSetName) > 0) continue; @@ -264,98 +260,106 @@ PxrUsdTranslators_MeshWriter::writeMeshAttrs(const UsdTimeCode& usdTime, if (!_GetExportArgs().exportDisplayColor) { continue; } - isDisplayColor=true; + isDisplayColor = true; } if (colorSetName == UsdMayaMeshPrimvarTokens->DisplayOpacityColorSetName.GetString()) { - TF_WARN("Mesh \"%s\" has a color set named \"%s\", " + TF_WARN( + "Mesh \"%s\" has a color set named \"%s\", " "which is a reserved Primvar name in USD. Skipping...", finalMesh.fullPathName().asChar(), - UsdMayaMeshPrimvarTokens->DisplayOpacityColorSetName - .GetText()); + UsdMayaMeshPrimvarTokens->DisplayOpacityColorSetName.GetText()); continue; } - VtArray RGBData; - VtArray AlphaData; - TfToken interpolation; - VtArray assignmentIndices; + VtArray RGBData; + VtArray AlphaData; + TfToken interpolation; + VtArray assignmentIndices; MFnMesh::MColorRepresentation colorSetRep; - bool clamped = false; - - if (!UsdMayaMeshWriteUtils::getMeshColorSetData(finalMesh, - MString(colorSetName.c_str()), - isDisplayColor, - shadersRGBData, - shadersAlphaData, - shadersAssignmentIndices, - &RGBData, - &AlphaData, - &interpolation, - &assignmentIndices, - &colorSetRep, - &clamped)) { - TF_WARN("Unable to retrieve colorSet data: %s on mesh: %s. " - "Skipping...", - colorSetName.c_str(), finalMesh.fullPathName().asChar()); + bool clamped = false; + + if (!UsdMayaMeshWriteUtils::getMeshColorSetData( + finalMesh, + MString(colorSetName.c_str()), + isDisplayColor, + shadersRGBData, + shadersAlphaData, + shadersAssignmentIndices, + &RGBData, + &AlphaData, + &interpolation, + &assignmentIndices, + &colorSetRep, + &clamped)) { + TF_WARN( + "Unable to retrieve colorSet data: %s on mesh: %s. " + "Skipping...", + colorSetName.c_str(), + finalMesh.fullPathName().asChar()); continue; } if (isDisplayColor) { // We tag the resulting displayColor/displayOpacity primvar as // authored to make sure we reconstruct the color set on import. - UsdMayaMeshWriteUtils::addDisplayPrimvars(primSchema, - usdTime, - colorSetRep, - RGBData, - AlphaData, - interpolation, - assignmentIndices, - clamped, - true, - _GetSparseValueWriter()); + UsdMayaMeshWriteUtils::addDisplayPrimvars( + primSchema, + usdTime, + colorSetRep, + RGBData, + AlphaData, + interpolation, + assignmentIndices, + clamped, + true, + _GetSparseValueWriter()); } else { const std::string sanitizedName = UsdMayaUtil::SanitizeColorSetName(colorSetName); // if our sanitized name is different than our current one and the // sanitized name already exists, it means 2 things are trying to // write to the same primvar. warn and continue. - if (colorSetName != sanitizedName && - colorSetNamesSet.count(sanitizedName) > 0) { - TF_WARN("Skipping colorSet '%s' as the colorSet '%s' exists as " - "well.", - colorSetName.c_str(), sanitizedName.c_str()); + if (colorSetName != sanitizedName && colorSetNamesSet.count(sanitizedName) > 0) { + TF_WARN( + "Skipping colorSet '%s' as the colorSet '%s' exists as " + "well.", + colorSetName.c_str(), + sanitizedName.c_str()); continue; } TfToken colorSetNameToken = TfToken(sanitizedName); if (colorSetRep == MFnMesh::kAlpha) { - UsdMayaMeshWriteUtils::createAlphaPrimVar(primSchema, - colorSetNameToken, - usdTime, - AlphaData, - interpolation, - assignmentIndices, - clamped, - _GetSparseValueWriter()); + UsdMayaMeshWriteUtils::createAlphaPrimVar( + primSchema, + colorSetNameToken, + usdTime, + AlphaData, + interpolation, + assignmentIndices, + clamped, + _GetSparseValueWriter()); } else if (colorSetRep == MFnMesh::kRGB) { - UsdMayaMeshWriteUtils::createRGBPrimVar(primSchema, - colorSetNameToken, - usdTime, - RGBData, - interpolation, - assignmentIndices, - clamped, - _GetSparseValueWriter()); + UsdMayaMeshWriteUtils::createRGBPrimVar( + primSchema, + colorSetNameToken, + usdTime, + RGBData, + interpolation, + assignmentIndices, + clamped, + _GetSparseValueWriter()); } else if (colorSetRep == MFnMesh::kRGBA) { - UsdMayaMeshWriteUtils::createRGBAPrimVar(primSchema, - colorSetNameToken, - usdTime, - RGBData, - AlphaData, - interpolation, - assignmentIndices, - clamped, - _GetSparseValueWriter()); + UsdMayaMeshWriteUtils::createRGBAPrimVar( + primSchema, + colorSetNameToken, + usdTime, + RGBData, + AlphaData, + interpolation, + assignmentIndices, + clamped, + _GetSparseValueWriter()); } } } @@ -372,37 +376,32 @@ PxrUsdTranslators_MeshWriter::writeMeshAttrs(const UsdTimeCode& usdTime, // not adding the clamp attribute as custom data. We also don't need to // reconstruct a color set from them on import since they originated // from the bound shader(s), so the authored flag is set to false. - UsdMayaMeshWriteUtils::addDisplayPrimvars(primSchema, - usdTime, - MFnMesh::kRGBA, - shadersRGBData, - shadersAlphaData, - shadersInterpolation, - shadersAssignmentIndices, - false, - false, - _GetSparseValueWriter()); + UsdMayaMeshWriteUtils::addDisplayPrimvars( + primSchema, + usdTime, + MFnMesh::kRGBA, + shadersRGBData, + shadersAlphaData, + shadersInterpolation, + shadersAssignmentIndices, + false, + false, + _GetSparseValueWriter()); } return true; } -bool -PxrUsdTranslators_MeshWriter::ExportsGprims() const -{ - return true; -} +bool PxrUsdTranslators_MeshWriter::ExportsGprims() const { return true; } -bool -PxrUsdTranslators_MeshWriter::isMeshAnimated() const +bool PxrUsdTranslators_MeshWriter::isMeshAnimated() const { // Note that _HasAnimCurves() as computed by UsdMayaTransformWriter is // whether the finalMesh is animated. return _skelInputMesh.isNull() ? _HasAnimCurves() : false; } -void -PxrUsdTranslators_MeshWriter::cleanupPrimvars() +void PxrUsdTranslators_MeshWriter::cleanupPrimvars() { if (!isMeshAnimated()) { // Based on how setPrimvar() works, the cleanup phase doesn't apply to @@ -416,7 +415,7 @@ PxrUsdTranslators_MeshWriter::cleanupPrimvars() // of the indices are assigned), then we can remove the unassigned value // and shift all the indices down. const UsdGeomMesh primSchema(GetUsdPrim()); - for (const UsdGeomPrimvar& primvar: primSchema.GetPrimvars()) { + for (const UsdGeomPrimvar& primvar : primSchema.GetPrimvars()) { if (!primvar) { continue; } diff --git a/lib/usd/translators/meshWriter.h b/lib/usd/translators/meshWriter.h index 3057e5316f..ad288472d4 100644 --- a/lib/usd/translators/meshWriter.h +++ b/lib/usd/translators/meshWriter.h @@ -18,27 +18,27 @@ /// \file -#include -#include - -#include -#include -#include +#include +#include -#include #include #include #include #include #include +#include #include #include #include #include #include -#include -#include +#include +#include +#include + +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -47,9 +47,10 @@ PXR_NAMESPACE_OPEN_SCOPE class PxrUsdTranslators_MeshWriter : public UsdMayaPrimWriter { public: - PxrUsdTranslators_MeshWriter(const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); + PxrUsdTranslators_MeshWriter( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); void Write(const UsdTimeCode& usdTime) override; bool ExportsGprims() const override; @@ -75,8 +76,6 @@ class PxrUsdTranslators_MeshWriter : public UsdMayaPrimWriter std::set _excludeColorSets; }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/translators/nurbsCurveWriter.cpp b/lib/usd/translators/nurbsCurveWriter.cpp index 98990cba65..99d4b60f90 100644 --- a/lib/usd/translators/nurbsCurveWriter.cpp +++ b/lib/usd/translators/nurbsCurveWriter.cpp @@ -15,45 +15,43 @@ // #include "nurbsCurveWriter.h" -#include - -#include -#include -#include -#include +#include +#include +#include +#include +#include -#include #include #include +#include #include #include #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include + +#include PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_REGISTER_WRITER(nurbsCurve, PxrUsdTranslators_NurbsCurveWriter); PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(nurbsCurve, UsdGeomNurbsCurves); - PxrUsdTranslators_NurbsCurveWriter::PxrUsdTranslators_NurbsCurveWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) { if (!TF_VERIFY(GetDagPath().isValid())) { return; } - UsdGeomNurbsCurves primSchema = - UsdGeomNurbsCurves::Define(GetUsdStage(), GetUsdPath()); + UsdGeomNurbsCurves primSchema = UsdGeomNurbsCurves::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( primSchema, "Could not define UsdGeomNurbsCurves at path '%s'\n", @@ -70,8 +68,7 @@ PxrUsdTranslators_NurbsCurveWriter::PxrUsdTranslators_NurbsCurveWriter( } /* virtual */ -void -PxrUsdTranslators_NurbsCurveWriter::Write(const UsdTimeCode& usdTime) +void PxrUsdTranslators_NurbsCurveWriter::Write(const UsdTimeCode& usdTime) { UsdMayaPrimWriter::Write(usdTime); @@ -79,46 +76,44 @@ PxrUsdTranslators_NurbsCurveWriter::Write(const UsdTimeCode& usdTime) writeNurbsCurveAttrs(usdTime, primSchema); } -bool -PxrUsdTranslators_NurbsCurveWriter::writeNurbsCurveAttrs( - const UsdTimeCode& usdTime, - UsdGeomNurbsCurves& primSchema) +bool PxrUsdTranslators_NurbsCurveWriter::writeNurbsCurveAttrs( + const UsdTimeCode& usdTime, + UsdGeomNurbsCurves& primSchema) { MStatus status = MS::kSuccess; // Return if usdTime does not match if shape is animated - if (usdTime.IsDefault() == _HasAnimCurves() ) { + if (usdTime.IsDefault() == _HasAnimCurves()) { // skip shape as the usdTime does not match if shape isAnimated value return true; } MFnDependencyNode fnDepNode(GetDagPath().node(), &status); - MString name = fnDepNode.name(); + MString name = fnDepNode.name(); MFnNurbsCurve curveFn(GetDagPath(), &status); if (!status) { TF_RUNTIME_ERROR( - "MFnNurbsCurve() failed for curve at DAG path: %s", - GetDagPath().fullPathName().asChar()); + "MFnNurbsCurve() failed for curve at DAG path: %s", + GetDagPath().fullPathName().asChar()); return false; } // How to repeat the end knots. - bool wrap = false; + bool wrap = false; MFnNurbsCurve::Form form(curveFn.form()); - if (form == MFnNurbsCurve::kClosed || - form == MFnNurbsCurve::kPeriodic){ + if (form == MFnNurbsCurve::kClosed || form == MFnNurbsCurve::kPeriodic) { wrap = true; } // Get curve attrs ====== unsigned int numCurves = 1; // Assuming only 1 curve for now - VtIntArray curveOrder(numCurves); - VtIntArray curveVertexCounts(numCurves); + VtIntArray curveOrder(numCurves); + VtIntArray curveVertexCounts(numCurves); VtFloatArray curveWidths(numCurves); VtVec2dArray ranges(numCurves); - curveOrder[0] = curveFn.degree()+1; + curveOrder[0] = curveFn.degree() + 1; curveVertexCounts[0] = curveFn.numCVs(); if (!TF_VERIFY(curveOrder[0] <= curveVertexCounts[0])) { return false; @@ -136,7 +131,7 @@ PxrUsdTranslators_NurbsCurveWriter::writeNurbsCurveAttrs( status = curveFn.getCVs(mayaCurveCVs, MSpace::kObject); CHECK_MSTATUS_AND_RETURN(status, false); VtVec3fArray points(mayaCurveCVs.length()); // all CVs batched together - for (unsigned int i=0; i < mayaCurveCVs.length(); i++) { + for (unsigned int i = 0; i < mayaCurveCVs.length(); i++) { points[i].Set(mayaCurveCVs[i].x, mayaCurveCVs[i].y, mayaCurveCVs[i].z); } @@ -148,10 +143,10 @@ PxrUsdTranslators_NurbsCurveWriter::writeNurbsCurveAttrs( curveKnots[i + 1] = mayaCurveKnots[i]; } if (wrap) { - curveKnots[0] = curveKnots[1] - (curveKnots[curveKnots.size() - 2] - - curveKnots[curveKnots.size() - 3]); - curveKnots[curveKnots.size() - 1] = - curveKnots[curveKnots.size() - 2] + (curveKnots[2] - curveKnots[1]); + curveKnots[0] = curveKnots[1] + - (curveKnots[curveKnots.size() - 2] - curveKnots[curveKnots.size() - 3]); + curveKnots[curveKnots.size() - 1] + = curveKnots[curveKnots.size() - 2] + (curveKnots[2] - curveKnots[1]); } else { curveKnots[0] = curveKnots[1]; curveKnots[curveKnots.size() - 1] = curveKnots[curveKnots.size() - 2]; @@ -160,18 +155,17 @@ PxrUsdTranslators_NurbsCurveWriter::writeNurbsCurveAttrs( // Gprim VtVec3fArray extent(2); UsdGeomCurves::ComputeExtent(points, curveWidths, &extent); - UsdMayaWriteUtil::SetAttribute(primSchema.CreateExtentAttr(), &extent, usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.CreateExtentAttr(), &extent, usdTime, _GetSparseValueWriter()); // find the number of segments: (vertexCount - order + 1) per curve // varying interpolation is number of segments + number of curves - size_t accumulatedVertexCount = - std::accumulate(curveVertexCounts.begin(), curveVertexCounts.end(), 0); - size_t accumulatedOrder = - std::accumulate(curveOrder.begin(), curveOrder.end(), 0); - size_t expectedSegmentCount = - accumulatedVertexCount - accumulatedOrder + curveVertexCounts.size(); - size_t expectedVaryingSize = - expectedSegmentCount + curveVertexCounts.size(); + size_t accumulatedVertexCount + = std::accumulate(curveVertexCounts.begin(), curveVertexCounts.end(), 0); + size_t accumulatedOrder = std::accumulate(curveOrder.begin(), curveOrder.end(), 0); + size_t expectedSegmentCount + = accumulatedVertexCount - accumulatedOrder + curveVertexCounts.size(); + size_t expectedVaryingSize = expectedSegmentCount + curveVertexCounts.size(); if (curveWidths.size() == 1) primSchema.SetWidthsInterpolation(UsdGeomTokens->constant); @@ -190,13 +184,28 @@ PxrUsdTranslators_NurbsCurveWriter::writeNurbsCurveAttrs( // Curve // not animatable - UsdMayaWriteUtil::SetAttribute(primSchema.GetOrderAttr(), curveOrder, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetCurveVertexCountsAttr(), &curveVertexCounts, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetWidthsAttr(), &curveWidths, UsdTimeCode::Default(), _GetSparseValueWriter()); - - UsdMayaWriteUtil::SetAttribute(primSchema.GetKnotsAttr(), &curveKnots, UsdTimeCode::Default(), _GetSparseValueWriter()); // not animatable - UsdMayaWriteUtil::SetAttribute(primSchema.GetRangesAttr(), &ranges, UsdTimeCode::Default(), _GetSparseValueWriter()); // not animatable - UsdMayaWriteUtil::SetAttribute(primSchema.GetPointsAttr(), &points, usdTime, _GetSparseValueWriter()); // CVs + UsdMayaWriteUtil::SetAttribute( + primSchema.GetOrderAttr(), curveOrder, UsdTimeCode::Default(), _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetCurveVertexCountsAttr(), + &curveVertexCounts, + UsdTimeCode::Default(), + _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetWidthsAttr(), &curveWidths, UsdTimeCode::Default(), _GetSparseValueWriter()); + + UsdMayaWriteUtil::SetAttribute( + primSchema.GetKnotsAttr(), + &curveKnots, + UsdTimeCode::Default(), + _GetSparseValueWriter()); // not animatable + UsdMayaWriteUtil::SetAttribute( + primSchema.GetRangesAttr(), + &ranges, + UsdTimeCode::Default(), + _GetSparseValueWriter()); // not animatable + UsdMayaWriteUtil::SetAttribute( + primSchema.GetPointsAttr(), &points, usdTime, _GetSparseValueWriter()); // CVs // TODO: Handle periodic and non-periodic cases @@ -204,11 +213,6 @@ PxrUsdTranslators_NurbsCurveWriter::writeNurbsCurveAttrs( } /* virtual */ -bool -PxrUsdTranslators_NurbsCurveWriter::ExportsGprims() const -{ - return true; -} - +bool PxrUsdTranslators_NurbsCurveWriter::ExportsGprims() const { return true; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/nurbsCurveWriter.h b/lib/usd/translators/nurbsCurveWriter.h index 4282370cb3..2844e42c86 100644 --- a/lib/usd/translators/nurbsCurveWriter.h +++ b/lib/usd/translators/nurbsCurveWriter.h @@ -18,39 +18,35 @@ /// \file -#include +#include +#include #include #include #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE /// Exports Maya nurbsCurve objects (MFnNurbsCurve) as UsdGeomNurbsCurves. class PxrUsdTranslators_NurbsCurveWriter : public UsdMayaPrimWriter { - public: - PxrUsdTranslators_NurbsCurveWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); +public: + PxrUsdTranslators_NurbsCurveWriter( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); - void Write(const UsdTimeCode& usdTime) override; + void Write(const UsdTimeCode& usdTime) override; - bool ExportsGprims() const override; + bool ExportsGprims() const override; - protected: - bool writeNurbsCurveAttrs( - const UsdTimeCode& usdTime, - UsdGeomNurbsCurves& primSchema); +protected: + bool writeNurbsCurveAttrs(const UsdTimeCode& usdTime, UsdGeomNurbsCurves& primSchema); }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/translators/nurbsCurvesReader.cpp b/lib/usd/translators/nurbsCurvesReader.cpp index 5370412907..c89101950c 100644 --- a/lib/usd/translators/nurbsCurvesReader.cpp +++ b/lib/usd/translators/nurbsCurvesReader.cpp @@ -13,24 +13,19 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include - #include #include +#include +#include + PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_DEFINE_READER(UsdGeomNurbsCurves, args, context) { const UsdPrim& usdPrim = args.GetUsdPrim(); - MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); - return UsdMayaTranslatorCurves::Create( - UsdGeomCurves(usdPrim), - parentNode, - args, - context); + MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); + return UsdMayaTranslatorCurves::Create(UsdGeomCurves(usdPrim), parentNode, args, context); } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/usd/translators/nurbsPatchReader.cpp b/lib/usd/translators/nurbsPatchReader.cpp index a793f5036c..607e2fd808 100644 --- a/lib/usd/translators/nurbsPatchReader.cpp +++ b/lib/usd/translators/nurbsPatchReader.cpp @@ -13,27 +13,22 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include +#include #include #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_DEFINE_READER(UsdGeomNurbsPatch, args, context) { const UsdPrim& usdPrim = args.GetUsdPrim(); - MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); - return UsdMayaTranslatorNurbsPatch::Read( - UsdGeomNurbsPatch(usdPrim), - parentNode, - args, - context); + MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); + return UsdMayaTranslatorNurbsPatch::Read(UsdGeomNurbsPatch(usdPrim), parentNode, args, context); } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/usd/translators/nurbsSurfaceWriter.cpp b/lib/usd/translators/nurbsSurfaceWriter.cpp index badf6e1663..52d411449c 100644 --- a/lib/usd/translators/nurbsSurfaceWriter.cpp +++ b/lib/usd/translators/nurbsSurfaceWriter.cpp @@ -15,20 +15,19 @@ // #include "nurbsSurfaceWriter.h" -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include -#include #include #include #include #include #include #include +#include #include #include #include @@ -36,30 +35,29 @@ #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_REGISTER_WRITER(nurbsSurface, PxrUsdTranslators_NurbsSurfaceWriter); PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(nurbsSurface, UsdGeomNurbsPatch); - PxrUsdTranslators_NurbsSurfaceWriter::PxrUsdTranslators_NurbsSurfaceWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) { if (!TF_VERIFY(GetDagPath().isValid())) { return; } - UsdGeomNurbsPatch primSchema = - UsdGeomNurbsPatch::Define(GetUsdStage(), GetUsdPath()); + UsdGeomNurbsPatch primSchema = UsdGeomNurbsPatch::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( primSchema, "Could not define UsdGeomNurbsPatch at path '%s'\n", @@ -75,14 +73,12 @@ PxrUsdTranslators_NurbsSurfaceWriter::PxrUsdTranslators_NurbsSurfaceWriter( } } -static -void -_FixNormalizedKnotRange( - VtArray& knots, - const unsigned int numKnots, - const unsigned int degree, - const double startVal, - const double endVal) +static void _FixNormalizedKnotRange( + VtArray& knots, + const unsigned int numKnots, + const unsigned int degree, + const double startVal, + const double endVal) { // ensure we've produced valid knot ranges; the data coming // from Maya is fine but sometimes rounding errors in the normalization @@ -109,8 +105,7 @@ _FixNormalizedKnotRange( } /* virtual */ -void -PxrUsdTranslators_NurbsSurfaceWriter::Write(const UsdTimeCode& usdTimeCode) +void PxrUsdTranslators_NurbsSurfaceWriter::Write(const UsdTimeCode& usdTimeCode) { UsdMayaPrimWriter::Write(usdTimeCode); @@ -118,15 +113,14 @@ PxrUsdTranslators_NurbsSurfaceWriter::Write(const UsdTimeCode& usdTimeCode) writeNurbsSurfaceAttrs(usdTimeCode, primSchema); } -bool -PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( - const UsdTimeCode& usdTimeCode, - UsdGeomNurbsPatch& primSchema) +bool PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( + const UsdTimeCode& usdTimeCode, + UsdGeomNurbsPatch& primSchema) { MStatus status = MS::kSuccess; // Return if usdTimeCode does not match if shape is animated - if (usdTimeCode.IsDefault() == _HasAnimCurves() ) { + if (usdTimeCode.IsDefault() == _HasAnimCurves()) { // skip shape as the usdTimeCode does not match if shape isAnimated value return true; } @@ -134,8 +128,8 @@ PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( MFnNurbsSurface nurbs(GetDagPath(), &status); if (!status) { TF_RUNTIME_ERROR( - "MFnNurbsSurface() failed for surface at DAG path: %s", - GetDagPath().fullPathName().asChar()); + "MFnNurbsSurface() failed for surface at DAG path: %s", + GetDagPath().fullPathName().asChar()); return false; } @@ -145,31 +139,29 @@ PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( // shader assignment possible. if (_GetExportArgs().exportDisplayColor) { VtArray RGBData; - VtArray AlphaData; - TfToken interpolation; - VtArray assignmentIndices; - if (UsdMayaUtil::GetLinearShaderColor(nurbs, - &RGBData, - &AlphaData, - &interpolation, - &assignmentIndices)) { - if (RGBData.size()>0) { + VtArray AlphaData; + TfToken interpolation; + VtArray assignmentIndices; + if (UsdMayaUtil::GetLinearShaderColor( + nurbs, &RGBData, &AlphaData, &interpolation, &assignmentIndices)) { + if (RGBData.size() > 0) { UsdGeomPrimvar dispColor = primSchema.CreateDisplayColorPrimvar(); if (interpolation != dispColor.GetInterpolation()) { dispColor.SetInterpolation(interpolation); } - UsdMayaWriteUtil::SetAttribute(dispColor.GetAttr(), RGBData, UsdTimeCode::Default(), _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + dispColor.GetAttr(), RGBData, UsdTimeCode::Default(), _GetSparseValueWriter()); if (!assignmentIndices.empty()) { dispColor.SetIndices(assignmentIndices); } } - if (AlphaData.size() > 0 && - !GfIsClose(AlphaData[0], 1.0, 1e-9)) { + if (AlphaData.size() > 0 && !GfIsClose(AlphaData[0], 1.0, 1e-9)) { UsdGeomPrimvar dispOpacity = primSchema.CreateDisplayOpacityPrimvar(); if (interpolation != dispOpacity.GetInterpolation()) { dispOpacity.SetInterpolation(interpolation); } - UsdMayaWriteUtil::SetAttribute(dispOpacity, AlphaData, UsdTimeCode::Default(), _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + dispOpacity, AlphaData, UsdTimeCode::Default(), _GetSparseValueWriter()); if (!assignmentIndices.empty()) { dispOpacity.SetIndices(assignmentIndices); } @@ -181,9 +173,9 @@ PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( unsigned int numKnotsInV = nurbs.numKnotsInV(); if (numKnotsInU < 2 || numKnotsInV < 2) { TF_RUNTIME_ERROR( - "MFnNurbsSurface '%s' has degenerate knot vectors. " - "Skipping...", - GetDagPath().fullPathName().asChar()); + "MFnNurbsSurface '%s' has degenerate knot vectors. " + "Skipping...", + GetDagPath().fullPathName().asChar()); return false; } @@ -197,72 +189,75 @@ PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( nurbs.getKnotDomain(startU, endU, startV, endV); // Offset and scale to normalize knots from 0 to 1 - double uOffset=0.0; - double vOffset=0.0; + double uOffset = 0.0; + double vOffset = 0.0; double uScale = 1.0; double vScale = 1.0; if (_GetExportArgs().normalizeNurbs) { - if (endU>startU && endV>startV) { + if (endU > startU && endV > startV) { uOffset = startU; vOffset = startV; uScale = 1.0 / (endU - startU); vScale = 1.0 / (endV - startV); - startU = 0; startV = 0; - endU = 1; endV = 1; + startU = 0; + startV = 0; + endU = 1; + endV = 1; } } GfVec2d uRange, vRange; - uRange[0]=startU; uRange[1]=endU; - vRange[0]=startV; vRange[1]=endV; + uRange[0] = startU; + uRange[1] = endU; + vRange[0] = startV; + vRange[1] = endV; // pad the start and end with a knot on each side, since thats what // most apps, like Houdini and Renderman want these two extra knots - VtArray sampKnotsInU(numKnotsInU+2); - VtArray sampKnotsInV(numKnotsInV+2); + VtArray sampKnotsInU(numKnotsInU + 2); + VtArray sampKnotsInV(numKnotsInV + 2); for (unsigned int i = 0; i < numKnotsInU; i++) { - sampKnotsInU[i+1]=(double)((knotsInU[i]-uOffset)*uScale); + sampKnotsInU[i + 1] = (double)((knotsInU[i] - uOffset) * uScale); } for (unsigned int i = 0; i < numKnotsInV; i++) { - sampKnotsInV[i+1]=(double)((knotsInV[i]-vOffset)*vScale); + sampKnotsInV[i + 1] = (double)((knotsInV[i] - vOffset) * vScale); } if (_GetExportArgs().normalizeNurbs) { - _FixNormalizedKnotRange(sampKnotsInU, numKnotsInU+2, nurbs.degreeU(), startU, endU); - _FixNormalizedKnotRange(sampKnotsInV, numKnotsInV+2, nurbs.degreeV(), startV, endV); + _FixNormalizedKnotRange(sampKnotsInU, numKnotsInU + 2, nurbs.degreeU(), startU, endU); + _FixNormalizedKnotRange(sampKnotsInV, numKnotsInV + 2, nurbs.degreeV(), startV, endV); } - sampKnotsInU[0] = (2.0 * sampKnotsInU[1] - sampKnotsInU[2]); - sampKnotsInU[numKnotsInU+1] = (2.0 * sampKnotsInU[numKnotsInU] - - sampKnotsInU[numKnotsInU-1]); + sampKnotsInU[numKnotsInU + 1] + = (2.0 * sampKnotsInU[numKnotsInU] - sampKnotsInU[numKnotsInU - 1]); sampKnotsInV[0] = (2.0 * sampKnotsInV[1] - sampKnotsInV[2]); - sampKnotsInV[numKnotsInV+1] = (2.0 * sampKnotsInV[numKnotsInV] - - sampKnotsInV[numKnotsInV-1]); + sampKnotsInV[numKnotsInV + 1] + = (2.0 * sampKnotsInV[numKnotsInV] - sampKnotsInV[numKnotsInV - 1]); MPointArray cvArray; nurbs.getCVs(cvArray, MSpace::kObject); unsigned int numCVs = cvArray.length(); - int numCVsInU = nurbs.numCVsInU(); - int numCVsInV = nurbs.numCVsInV(); + int numCVsInU = nurbs.numCVsInU(); + int numCVsInV = nurbs.numCVsInV(); VtArray sampPos(numCVs); - VtArray sampPosWeights(numCVs); - bool setWeights = false; + VtArray sampPosWeights(numCVs); + bool setWeights = false; // Create st vec2f vertex primvar VtArray stValues; if (_GetExportArgs().exportNurbsExplicitUV) { - stValues.resize(numCVsInU*numCVsInV); + stValues.resize(numCVsInU * numCVsInV); } // Maya stores the data where v varies the fastest (v,u order) // so we need to pack the data differently u,v order // WE DIFFER FROM ALEMBIC WRITER, WE DON'T FLIP V - int cvIndex=0; + int cvIndex = 0; for (int v = 0; v < numCVsInV; v++) { for (int u = 0; u < numCVsInU; u++) { int index = u * numCVsInV + v; @@ -278,8 +273,8 @@ PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( // No need to check for nurbsTexCoordParam yet since we only // support uniform in the code if (stValues.size() > static_cast(cvIndex)) { - float sValue = static_cast(u)/static_cast(numCVsInU-1); - float tValue = static_cast(v)/static_cast(numCVsInV-1); + float sValue = static_cast(u) / static_cast(numCVsInU - 1); + float tValue = static_cast(v) / static_cast(numCVsInV - 1); stValues[cvIndex] = GfVec2f(sValue, tValue); } @@ -291,54 +286,103 @@ PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( // Compute the extent using the CVs. VtArray extent(2); UsdGeomPointBased::ComputeExtent(sampPos, &extent); - UsdMayaWriteUtil::SetAttribute(primSchema.CreateExtentAttr(), extent, usdTimeCode, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.CreateExtentAttr(), extent, usdTimeCode, _GetSparseValueWriter()); // Set NurbsPatch attributes - UsdMayaWriteUtil::SetAttribute(primSchema.GetUVertexCountAttr(), numCVsInU, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetVVertexCountAttr(), numCVsInV, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetUOrderAttr(), nurbs.degreeU() + 1, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetVOrderAttr(), nurbs.degreeV() + 1, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetUKnotsAttr(), sampKnotsInU, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetVKnotsAttr(), sampKnotsInV, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetURangeAttr(), uRange, UsdTimeCode::Default(),_GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetVRangeAttr(), vRange, UsdTimeCode::Default(),_GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetPointsAttr(), sampPos, usdTimeCode, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetUVertexCountAttr(), + numCVsInU, + UsdTimeCode::Default(), + _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetVVertexCountAttr(), + numCVsInV, + UsdTimeCode::Default(), + _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetUOrderAttr(), + nurbs.degreeU() + 1, + UsdTimeCode::Default(), + _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetVOrderAttr(), + nurbs.degreeV() + 1, + UsdTimeCode::Default(), + _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetUKnotsAttr(), sampKnotsInU, UsdTimeCode::Default(), _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetVKnotsAttr(), sampKnotsInV, UsdTimeCode::Default(), _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetURangeAttr(), uRange, UsdTimeCode::Default(), _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetVRangeAttr(), vRange, UsdTimeCode::Default(), _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetPointsAttr(), sampPos, usdTimeCode, _GetSparseValueWriter()); if (setWeights) { - UsdMayaWriteUtil::SetAttribute(primSchema.GetPointWeightsAttr(), - sampPosWeights, UsdTimeCode::Default(), _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetPointWeightsAttr(), + sampPosWeights, + UsdTimeCode::Default(), + _GetSparseValueWriter()); } // If stValues vector has vertex data, create and assign st if (stValues.size() == static_cast(numCVsInU * numCVsInV)) { - SdfValueTypeName uvValueType = (UsdMayaWriteUtil::WriteUVAsFloat2())? - (SdfValueTypeNames->Float2Array) : (SdfValueTypeNames->TexCoord2fArray); - UsdGeomPrimvar uvSet = - primSchema.CreatePrimvar(UsdUtilsGetPrimaryUVSetName(), - uvValueType, - UsdGeomTokens->vertex); - UsdMayaWriteUtil::SetAttribute(uvSet.GetAttr(), &stValues, UsdTimeCode::Default(), _GetSparseValueWriter()); + SdfValueTypeName uvValueType = (UsdMayaWriteUtil::WriteUVAsFloat2()) + ? (SdfValueTypeNames->Float2Array) + : (SdfValueTypeNames->TexCoord2fArray); + UsdGeomPrimvar uvSet = primSchema.CreatePrimvar( + UsdUtilsGetPrimaryUVSetName(), uvValueType, UsdGeomTokens->vertex); + UsdMayaWriteUtil::SetAttribute( + uvSet.GetAttr(), &stValues, UsdTimeCode::Default(), _GetSparseValueWriter()); } // Set Form switch (nurbs.formInU()) { - case MFnNurbsSurface::kClosed: - UsdMayaWriteUtil::SetAttribute(primSchema.GetUFormAttr(), UsdGeomTokens->closed, UsdTimeCode::Default(), _GetSparseValueWriter()); + case MFnNurbsSurface::kClosed: + UsdMayaWriteUtil::SetAttribute( + primSchema.GetUFormAttr(), + UsdGeomTokens->closed, + UsdTimeCode::Default(), + _GetSparseValueWriter()); break; - case MFnNurbsSurface::kPeriodic: - UsdMayaWriteUtil::SetAttribute(primSchema.GetUFormAttr(), UsdGeomTokens->periodic, UsdTimeCode::Default(), _GetSparseValueWriter()); + case MFnNurbsSurface::kPeriodic: + UsdMayaWriteUtil::SetAttribute( + primSchema.GetUFormAttr(), + UsdGeomTokens->periodic, + UsdTimeCode::Default(), + _GetSparseValueWriter()); break; - default: - UsdMayaWriteUtil::SetAttribute(primSchema.GetUFormAttr(), UsdGeomTokens->open, UsdTimeCode::Default(), _GetSparseValueWriter()); + default: + UsdMayaWriteUtil::SetAttribute( + primSchema.GetUFormAttr(), + UsdGeomTokens->open, + UsdTimeCode::Default(), + _GetSparseValueWriter()); } switch (nurbs.formInV()) { - case MFnNurbsSurface::kClosed: - UsdMayaWriteUtil::SetAttribute(primSchema.GetVFormAttr(), UsdGeomTokens->closed, UsdTimeCode::Default(), _GetSparseValueWriter()); + case MFnNurbsSurface::kClosed: + UsdMayaWriteUtil::SetAttribute( + primSchema.GetVFormAttr(), + UsdGeomTokens->closed, + UsdTimeCode::Default(), + _GetSparseValueWriter()); break; - case MFnNurbsSurface::kPeriodic: - UsdMayaWriteUtil::SetAttribute(primSchema.GetVFormAttr(), UsdGeomTokens->periodic, UsdTimeCode::Default(), _GetSparseValueWriter()); + case MFnNurbsSurface::kPeriodic: + UsdMayaWriteUtil::SetAttribute( + primSchema.GetVFormAttr(), + UsdGeomTokens->periodic, + UsdTimeCode::Default(), + _GetSparseValueWriter()); break; - default: - UsdMayaWriteUtil::SetAttribute(primSchema.GetVFormAttr(), UsdGeomTokens->open, UsdTimeCode::Default(), _GetSparseValueWriter()); + default: + UsdMayaWriteUtil::SetAttribute( + primSchema.GetVFormAttr(), + UsdGeomTokens->open, + UsdTimeCode::Default(), + _GetSparseValueWriter()); } // If not trimmed surface, you are done @@ -362,24 +406,22 @@ PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( // in head-to-tail fashion and must be explicitly closed. " // A Maya boundary is equivalent to an USD/RenderMan loop - VtArray trimNumCurves; - VtArray trimNumPos; - VtArray trimOrder; - VtArray trimKnot; + VtArray trimNumCurves; + VtArray trimNumPos; + VtArray trimOrder; + VtArray trimKnot; VtArray trimRange; VtArray trimPoint; int numLoops = 0; - for (unsigned int i = 0; i < numRegions; i++) - { + for (unsigned int i = 0; i < numRegions; i++) { MTrimBoundaryArray result; // if the 3rd argument is set to be true, return the 2D curve nurbs.getTrimBoundaries(result, i, true); unsigned int numBoundaries = result.length(); - for (unsigned int j = 0; j < numBoundaries; j++) - { + for (unsigned int j = 0; j < numBoundaries; j++) { /* WE DON'T NEED THIS BUT IT'S HERE FOR POSSIBLE FUTURE USE switch(fn.boundaryType(i,j)) { @@ -395,34 +437,31 @@ PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( unsigned int numTrimCurve = boundary.length(); trimNumCurves.push_back(numTrimCurve); numLoops++; - for (unsigned int k = 0; k < numTrimCurve; k++) - { + for (unsigned int k = 0; k < numTrimCurve; k++) { MObject curveObj = boundary[k]; - if (curveObj.hasFn(MFn::kNurbsCurve)) - { + if (curveObj.hasFn(MFn::kNurbsCurve)) { MFnNurbsCurve mFnCurve(curveObj); int numCVs = mFnCurve.numCVs(); trimNumPos.push_back(numCVs); - trimOrder.push_back(mFnCurve.degree()+1); + trimOrder.push_back(mFnCurve.degree() + 1); double start, end; mFnCurve.getKnotDomain(start, end); GfVec2d range; - range[0]=start; - range[1]=end; + range[0] = start; + range[1] = end; trimRange.push_back(range); MPointArray cvArray; mFnCurve.getCVs(cvArray); // WE DIFFER FROM ALEMBIC WRITER, WE DON'T FLIP V - for (int l = 0; l < numCVs; l++) - { + for (int l = 0; l < numCVs; l++) { GfVec3d point; - point[0]=(double)((cvArray[l].x-uOffset)*uScale); - point[1]=(double)((cvArray[l].y-vOffset)*vScale); - point[2]=cvArray[l].w; + point[0] = (double)((cvArray[l].x - uOffset) * uScale); + point[1] = (double)((cvArray[l].y - vOffset) * vScale); + point[2] = cvArray[l].w; trimPoint.push_back(point); } @@ -433,8 +472,7 @@ PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( // push_back a dummy value, we will set it below std::size_t totalNumKnots = trimKnot.size(); trimKnot.push_back(0.0); - for (unsigned int l = 0; l < numKnots; l++) - { + for (unsigned int l = 0; l < numKnots; l++) { trimKnot.push_back(knot[l]); } @@ -443,34 +481,53 @@ PxrUsdTranslators_NurbsSurfaceWriter::writeNurbsSurfaceAttrs( // for a knot sequence with uniform end knots, create their // the new knots offset at an interval equal to the existing // first and last knot intervals - double k1 = trimKnot[totalNumKnots+1]; - double k2 = trimKnot[totalNumKnots+2]; - double klast_1 = trimKnot[trimKnot.size()-1]; - double klast_2 = trimKnot[trimKnot.size()-2]; + double k1 = trimKnot[totalNumKnots + 1]; + double k2 = trimKnot[totalNumKnots + 2]; + double klast_1 = trimKnot[trimKnot.size() - 1]; + double klast_2 = trimKnot[trimKnot.size() - 2]; trimKnot[totalNumKnots] = 2.0 * k1 - k2; trimKnot.push_back(2.0 * klast_1 - klast_2); } } // for k - } // for j - } // for i - - UsdMayaWriteUtil::SetAttribute(primSchema.GetTrimCurveCountsAttr(), &trimNumCurves, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetTrimCurveOrdersAttr(), &trimOrder, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetTrimCurveVertexCountsAttr(), &trimNumPos, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetTrimCurveKnotsAttr(), &trimKnot, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetTrimCurveRangesAttr(), &trimRange, UsdTimeCode::Default(), _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(primSchema.GetTrimCurvePointsAttr(), &trimPoint, UsdTimeCode::Default(), _GetSparseValueWriter()); + } // for j + } // for i + + UsdMayaWriteUtil::SetAttribute( + primSchema.GetTrimCurveCountsAttr(), + &trimNumCurves, + UsdTimeCode::Default(), + _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetTrimCurveOrdersAttr(), + &trimOrder, + UsdTimeCode::Default(), + _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetTrimCurveVertexCountsAttr(), + &trimNumPos, + UsdTimeCode::Default(), + _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetTrimCurveKnotsAttr(), + &trimKnot, + UsdTimeCode::Default(), + _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetTrimCurveRangesAttr(), + &trimRange, + UsdTimeCode::Default(), + _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + primSchema.GetTrimCurvePointsAttr(), + &trimPoint, + UsdTimeCode::Default(), + _GetSparseValueWriter()); // NO NON TRIM CODE HERE SINCE WE RETURN EARLIER IF NOT TRIMMED return true; } /* virtual */ -bool -PxrUsdTranslators_NurbsSurfaceWriter::ExportsGprims() const -{ - return true; -} - +bool PxrUsdTranslators_NurbsSurfaceWriter::ExportsGprims() const { return true; } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/nurbsSurfaceWriter.h b/lib/usd/translators/nurbsSurfaceWriter.h index 51c48f612a..6bd4cd7885 100644 --- a/lib/usd/translators/nurbsSurfaceWriter.h +++ b/lib/usd/translators/nurbsSurfaceWriter.h @@ -18,39 +18,35 @@ /// \file -#include +#include +#include #include #include #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE /// Exports Maya nurbsSurface objects (MFnNurbsSurface) as UsdGeomNurbsPatch. class PxrUsdTranslators_NurbsSurfaceWriter : public UsdMayaPrimWriter { - public: - PxrUsdTranslators_NurbsSurfaceWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); +public: + PxrUsdTranslators_NurbsSurfaceWriter( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); - void Write(const UsdTimeCode& usdTime) override; + void Write(const UsdTimeCode& usdTime) override; - bool ExportsGprims() const override; + bool ExportsGprims() const override; - protected: - bool writeNurbsSurfaceAttrs( - const UsdTimeCode& usdTime, - UsdGeomNurbsPatch& primSchema); +protected: + bool writeNurbsSurfaceAttrs(const UsdTimeCode& usdTime, UsdGeomNurbsPatch& primSchema); }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/translators/particleWriter.cpp b/lib/usd/translators/particleWriter.cpp index d579fb630f..8f8c104b3d 100644 --- a/lib/usd/translators/particleWriter.cpp +++ b/lib/usd/translators/particleWriter.cpp @@ -15,12 +15,20 @@ // #include "particleWriter.h" -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -32,20 +40,12 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -55,150 +55,176 @@ PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(particle, UsdGeomPoints); PXRUSDMAYA_REGISTER_WRITER(nParticle, PxrUsdTranslators_ParticleWriter); PXRUSDMAYA_REGISTER_ADAPTOR_SCHEMA(nParticle, UsdGeomPoints); - namespace { - template - inline void _convertVector(T& t, const MVector& v) { - // I wish we had concepts - // We are guaranteed to have arithmetic types - using _t = decltype(+t[0]); - t[0] = static_cast<_t>(v.x); - t[1] = static_cast<_t>(v.y); - t[2] = static_cast<_t>(v.z); - } +template inline void _convertVector(T& t, const MVector& v) +{ + // I wish we had concepts + // We are guaranteed to have arithmetic types + using _t = decltype(+t[0]); + t[0] = static_cast<_t>(v.x); + t[1] = static_cast<_t>(v.y); + t[2] = static_cast<_t>(v.z); +} - template - using _sharedVtArray = std::shared_ptr>; +template using _sharedVtArray = std::shared_ptr>; - template - _sharedVtArray _convertVectorArray(const MVectorArray& a) { - const auto count = a.length(); - auto* ret = new VtArray(count); - for (auto i = decltype(count){0}; i < count; ++i) { - _convertVector(ret->operator[](i), a[i]); - } - return _sharedVtArray(ret); +template _sharedVtArray _convertVectorArray(const MVectorArray& a) +{ + const auto count = a.length(); + auto* ret = new VtArray(count); + for (auto i = decltype(count) { 0 }; i < count; ++i) { + _convertVector(ret->operator[](i), a[i]); } + return _sharedVtArray(ret); +} - template - _sharedVtArray _convertArray(const MDoubleArray& a) { - const auto count = a.length(); - auto* ret = new VtArray(count); - for (auto i = decltype(count){0}; i < count; ++i) { - ret->operator[](i) = static_cast(a[i]); - } - return _sharedVtArray(ret); +template _sharedVtArray _convertArray(const MDoubleArray& a) +{ + const auto count = a.length(); + auto* ret = new VtArray(count); + for (auto i = decltype(count) { 0 }; i < count; ++i) { + ret->operator[](i) = static_cast(a[i]); } + return _sharedVtArray(ret); +} - template - _sharedVtArray _convertArray(const MIntArray& a) { - const auto count = a.length(); - auto* ret = new VtArray(count); - for (auto i = decltype(count){0}; i < count; ++i) { - ret->operator[](i) = static_cast(a[i]); - } - return _sharedVtArray(ret); +template _sharedVtArray _convertArray(const MIntArray& a) +{ + const auto count = a.length(); + auto* ret = new VtArray(count); + for (auto i = decltype(count) { 0 }; i < count; ++i) { + ret->operator[](i) = static_cast(a[i]); } + return _sharedVtArray(ret); +} - template - using _strVecPair = std::pair>; - - template - using _strVecPairVec = std::vector<_strVecPair>; +template using _strVecPair = std::pair>; - template - size_t _minCount(const _strVecPairVec& a) { - auto mn = std::numeric_limits::max(); - for (const auto& v : a) { - mn = std::min(mn, v.second->size()); - } +template using _strVecPairVec = std::vector<_strVecPair>; - return mn; +template size_t _minCount(const _strVecPairVec& a) +{ + auto mn = std::numeric_limits::max(); + for (const auto& v : a) { + mn = std::min(mn, v.second->size()); } - template - void _resizeVectors(_strVecPairVec& a, size_t size) { - for (const auto& v : a) { - v.second->resize(size); - } - } + return mn; +} - template - inline void _addAttr(UsdGeomPoints& points, const TfToken& name, - const SdfValueTypeName& typeName, - const VtArray& a, const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter *valueWriter) { - auto attr = points.GetPrim().CreateAttribute(name, typeName, false, SdfVariabilityVarying); - VtValue val(a); - valueWriter->SetAttribute(attr, &val, usdTime); +template void _resizeVectors(_strVecPairVec& a, size_t size) +{ + for (const auto& v : a) { + v.second->resize(size); } +} - const TfToken _rgbName("rgb"); - const TfToken _emissionName("emission"); - const TfToken _opacityName("opacity"); - const TfToken _lifespanName("lifespan"); - const TfToken _massName("mass"); - - template - void _addAttrVec(UsdGeomPoints& points, const SdfValueTypeName& typeName, - const _strVecPairVec& a, - const UsdTimeCode& usdTime, - UsdUtilsSparseValueWriter *valueWriter) { - for (const auto& v : a) { - _addAttr(points, v.first, typeName, *v.second, usdTime, - valueWriter); - } - } +template +inline void _addAttr( + UsdGeomPoints& points, + const TfToken& name, + const SdfValueTypeName& typeName, + const VtArray& a, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) +{ + auto attr = points.GetPrim().CreateAttribute(name, typeName, false, SdfVariabilityVarying); + VtValue val(a); + valueWriter->SetAttribute(attr, &val, usdTime); +} - // The logic of filtering the user attributes is based on partio4Maya/PartioExport. - // https://github.com/redpawfx/partio/blob/redpawfx-rez/contrib/partio4Maya/scripts/partioExportGui.mel - // We either don't want these or already export them using one of the builtin functions. - const std::set _supressedAttrs = { - "emitterDataPosition", "emitterDataVelocity", "fieldDataMass", - "fieldDataPosition", "fieldDataVelocity", "inputGeometryPoints", - "lastCachedPosition", "lastPosition", "lastVelocity", - "lastWorldPosition", "lastWorldVelocity", "worldVelocityInObjectSpace", - "position", "velocity", "acceleration", "rgb", "rgbPP", "incandescencePP", - "radius", "radiusPP", "age", "opacity", "opacityPP", "lifespan", "lifespanPP", - "id", "particleId", "mass", - }; - - // All the initial state attributes end with 0 - bool _isInitialAttribute(const std::string& attrName) { - return attrName.back() == '0'; +const TfToken _rgbName("rgb"); +const TfToken _emissionName("emission"); +const TfToken _opacityName("opacity"); +const TfToken _lifespanName("lifespan"); +const TfToken _massName("mass"); + +template +void _addAttrVec( + UsdGeomPoints& points, + const SdfValueTypeName& typeName, + const _strVecPairVec& a, + const UsdTimeCode& usdTime, + UsdUtilsSparseValueWriter* valueWriter) +{ + for (const auto& v : a) { + _addAttr(points, v.first, typeName, *v.second, usdTime, valueWriter); } +} - bool _isCachedAttribute(const std::string& attrName) { - constexpr auto _cached = "cached"; - constexpr auto _Cache = "Cache"; - return TfStringEndsWith(attrName, _Cache) || TfStringStartsWith(attrName, _cached); - } +// The logic of filtering the user attributes is based on partio4Maya/PartioExport. +// https://github.com/redpawfx/partio/blob/redpawfx-rez/contrib/partio4Maya/scripts/partioExportGui.mel +// We either don't want these or already export them using one of the builtin functions. +const std::set _supressedAttrs = { + "emitterDataPosition", + "emitterDataVelocity", + "fieldDataMass", + "fieldDataPosition", + "fieldDataVelocity", + "inputGeometryPoints", + "lastCachedPosition", + "lastPosition", + "lastVelocity", + "lastWorldPosition", + "lastWorldVelocity", + "worldVelocityInObjectSpace", + "position", + "velocity", + "acceleration", + "rgb", + "rgbPP", + "incandescencePP", + "radius", + "radiusPP", + "age", + "opacity", + "opacityPP", + "lifespan", + "lifespanPP", + "id", + "particleId", + "mass", +}; + +// All the initial state attributes end with 0 +bool _isInitialAttribute(const std::string& attrName) { return attrName.back() == '0'; } + +bool _isCachedAttribute(const std::string& attrName) +{ + constexpr auto _cached = "cached"; + constexpr auto _Cache = "Cache"; + return TfStringEndsWith(attrName, _Cache) || TfStringStartsWith(attrName, _cached); +} - bool _isValidAttr(const std::string& attrName) { - if (attrName.empty()) { return false; } - if (_isInitialAttribute(attrName)) { return false; } - if (_isCachedAttribute(attrName)) { return false; } - return _supressedAttrs.find(attrName) == _supressedAttrs.end(); +bool _isValidAttr(const std::string& attrName) +{ + if (attrName.empty()) { + return false; + } + if (_isInitialAttribute(attrName)) { + return false; } + if (_isCachedAttribute(attrName)) { + return false; + } + return _supressedAttrs.find(attrName) == _supressedAttrs.end(); } +} // namespace PxrUsdTranslators_ParticleWriter::PxrUsdTranslators_ParticleWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaTransformWriter(depNodeFn, usdPath, jobCtx), - mInitialFrameDone(false) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaTransformWriter(depNodeFn, usdPath, jobCtx) + , mInitialFrameDone(false) { if (!TF_VERIFY(GetDagPath().isValid())) { return; } - UsdGeomPoints primSchema = - UsdGeomPoints::Define(GetUsdStage(), GetUsdPath()); + UsdGeomPoints primSchema = UsdGeomPoints::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( - primSchema, - "Could not define UsdGeomPoints at path '%s'\n", - GetUsdPath().GetText())) { + primSchema, "Could not define UsdGeomPoints at path '%s'\n", GetUsdPath().GetText())) { return; } _usdPrim = primSchema.GetPrim(); @@ -213,8 +239,7 @@ PxrUsdTranslators_ParticleWriter::PxrUsdTranslators_ParticleWriter( } /* virtual */ -void -PxrUsdTranslators_ParticleWriter::Write(const UsdTimeCode& usdTime) +void PxrUsdTranslators_ParticleWriter::Write(const UsdTimeCode& usdTime) { UsdMayaTransformWriter::Write(usdTime); @@ -222,10 +247,9 @@ PxrUsdTranslators_ParticleWriter::Write(const UsdTimeCode& usdTime) writeParams(usdTime, primSchema); } -void -PxrUsdTranslators_ParticleWriter::writeParams( - const UsdTimeCode& usdTime, - UsdGeomPoints& points) +void PxrUsdTranslators_ParticleWriter::writeParams( + const UsdTimeCode& usdTime, + UsdGeomPoints& points) { // XXX: Check this properly, static particles are uncommon, but used. if (usdTime.IsDefault()) { @@ -269,12 +293,12 @@ PxrUsdTranslators_ParticleWriter::writeParams( } _strVecPairVec vectors; - _strVecPairVec floats; - _strVecPairVec ints; + _strVecPairVec floats; + _strVecPairVec ints; MVectorArray mayaVectors; MDoubleArray mayaDoubles; - MIntArray mayaInts; + MIntArray mayaInts; deformedParticleSys.position(mayaVectors); auto positions = _convertVectorArray(mayaVectors); @@ -331,12 +355,14 @@ PxrUsdTranslators_ParticleWriter::writeParams( } } - const auto minSize = std::min( - { - _minCount(vectors), _minCount(floats), _minCount(ints), - positions->size(), velocities->size(), ids->size(), radii->size(), masses->size() - } - ); + const auto minSize = std::min({ _minCount(vectors), + _minCount(floats), + _minCount(ints), + positions->size(), + velocities->size(), + ids->size(), + radii->size(), + masses->size() }); if (minSize == 0) { return; @@ -351,35 +377,43 @@ PxrUsdTranslators_ParticleWriter::writeParams( radii->resize(minSize); masses->resize(minSize); - UsdMayaWriteUtil::SetAttribute(points.GetPointsAttr(), positions.get(), usdTime, _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(points.GetVelocitiesAttr(), velocities.get(), usdTime, _GetSparseValueWriter()); - UsdMayaWriteUtil::SetAttribute(points.GetIdsAttr(), ids.get(), usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + points.GetPointsAttr(), positions.get(), usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + points.GetVelocitiesAttr(), velocities.get(), usdTime, _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + points.GetIdsAttr(), ids.get(), usdTime, _GetSparseValueWriter()); // radius -> width conversion - for (auto& r : *radii) { r = r * 2.0f; } - - UsdMayaWriteUtil::SetAttribute(points.GetWidthsAttr(), radii.get(), usdTime, _GetSparseValueWriter()); + for (auto& r : *radii) { + r = r * 2.0f; + } - _addAttr(points, _massName, SdfValueTypeNames->FloatArray, *masses, usdTime, - _GetSparseValueWriter()); + UsdMayaWriteUtil::SetAttribute( + points.GetWidthsAttr(), radii.get(), usdTime, _GetSparseValueWriter()); + + _addAttr( + points, + _massName, + SdfValueTypeNames->FloatArray, + *masses, + usdTime, + _GetSparseValueWriter()); // TODO: check if we need the array suffix!! - _addAttrVec(points, SdfValueTypeNames->Vector3fArray, vectors, usdTime, - _GetSparseValueWriter()); - _addAttrVec(points, SdfValueTypeNames->FloatArray, floats, usdTime, - _GetSparseValueWriter()); - _addAttrVec(points, SdfValueTypeNames->IntArray, ints, usdTime, - _GetSparseValueWriter()); + _addAttrVec( + points, SdfValueTypeNames->Vector3fArray, vectors, usdTime, _GetSparseValueWriter()); + _addAttrVec(points, SdfValueTypeNames->FloatArray, floats, usdTime, _GetSparseValueWriter()); + _addAttrVec(points, SdfValueTypeNames->IntArray, ints, usdTime, _GetSparseValueWriter()); } -void -PxrUsdTranslators_ParticleWriter::initializeUserAttributes() +void PxrUsdTranslators_ParticleWriter::initializeUserAttributes() { - const auto particleNode = GetMayaObject(); + const auto particleNode = GetMayaObject(); MFnParticleSystem particleSys(GetDagPath()); const auto attributeCount = particleSys.attributeCount(); - for (auto i = decltype(attributeCount){0}; i < attributeCount; ++i) { + for (auto i = decltype(attributeCount) { 0 }; i < attributeCount; ++i) { MObject attrObj = particleSys.attribute(i); // we need custom attributes if (particleSys.attributeClass(attrObj) == MFnDependencyNode::kNormalAttr) { @@ -387,13 +421,17 @@ PxrUsdTranslators_ParticleWriter::initializeUserAttributes() } // only checking for parent attrs MPlug attrPlug(particleNode, attrObj); - if (!attrPlug.parent().isNull()) { continue; } + if (!attrPlug.parent().isNull()) { + continue; + } MFnAttribute attr(attrObj); - const auto mayaAttrName = attr.name(); + const auto mayaAttrName = attr.name(); const std::string attrName = mayaAttrName.asChar(); - if (!_isValidAttr(attrName)) { continue; } + if (!_isValidAttr(attrName)) { + continue; + } if (particleSys.isPerParticleIntAttribute(mayaAttrName)) { mUserAttributes.emplace_back(TfToken(attrName), mayaAttrName, PER_PARTICLE_INT); } else if (particleSys.isPerParticleDoubleAttribute(mayaAttrName)) { @@ -404,5 +442,4 @@ PxrUsdTranslators_ParticleWriter::initializeUserAttributes() } } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/particleWriter.h b/lib/usd/translators/particleWriter.h index 79dd3c0cd3..6a6b15dce6 100644 --- a/lib/usd/translators/particleWriter.h +++ b/lib/usd/translators/particleWriter.h @@ -21,47 +21,46 @@ #include #include -#include -#include - -#include -#include - -#include #include +#include #include #include #include +#include +#include + +#include +#include + PXR_NAMESPACE_OPEN_SCOPE class PxrUsdTranslators_ParticleWriter : public UsdMayaTransformWriter { public: PxrUsdTranslators_ParticleWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); void Write(const UsdTimeCode& usdTime) override; private: void writeParams(const UsdTimeCode& usdTime, UsdGeomPoints& points); - enum ParticleType { + enum ParticleType + { PER_PARTICLE_INT, PER_PARTICLE_DOUBLE, PER_PARTICLE_VECTOR }; std::vector> mUserAttributes; - bool mInitialFrameDone; + bool mInitialFrameDone; void initializeUserAttributes(); }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/translators/plugin.cpp b/lib/usd/translators/plugin.cpp index 904e000658..d9e3950584 100644 --- a/lib/usd/translators/plugin.cpp +++ b/lib/usd/translators/plugin.cpp @@ -13,26 +13,21 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include +#include "api.h" #include -#include "api.h" +#include +#include PXR_NAMESPACE_USING_DIRECTIVE PXRUSDTRANSLATORS_API -MStatus -initializePlugin(MObject obj) +MStatus initializePlugin(MObject obj) { MFnPlugin plugin(obj, "Pixar", "1.0", "Any"); return MStatus::kSuccess; } PXRUSDTRANSLATORS_API -MStatus -uninitializePlugin(MObject /*obj*/) -{ - return MStatus::kSuccess; -} +MStatus uninitializePlugin(MObject /*obj*/) { return MStatus::kSuccess; } diff --git a/lib/usd/translators/scopeReader.cpp b/lib/usd/translators/scopeReader.cpp index 4d8ead67cb..26b13c28c0 100644 --- a/lib/usd/translators/scopeReader.cpp +++ b/lib/usd/translators/scopeReader.cpp @@ -13,34 +13,32 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include +#include #include #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_DEFINE_READER(UsdGeomScope, args, context) { const UsdPrim& usdPrim = args.GetUsdPrim(); - MObject parentNode = context->GetMayaNode( - usdPrim.GetPath().GetParentPath(), true); + MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); MStatus status; MObject mayaNode; return UsdMayaTranslatorUtil::CreateDummyTransformNode( - usdPrim, - parentNode, - /*importTypeName*/ true, - args, - context, - &status, - &mayaNode); + usdPrim, + parentNode, + /*importTypeName*/ true, + args, + context, + &status, + &mayaNode); } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/usd/translators/shading/rfmShaderTranslation.cpp b/lib/usd/translators/shading/rfmShaderTranslation.cpp index 0e2027e7cd..e78f9cef94 100644 --- a/lib/usd/translators/shading/rfmShaderTranslation.cpp +++ b/lib/usd/translators/shading/rfmShaderTranslation.cpp @@ -20,25 +20,19 @@ #include #include -#include #include #include #include - +#include PXR_NAMESPACE_OPEN_SCOPE - TF_DEFINE_PRIVATE_TOKENS( _tokens, - ((conversionName, "rendermanForMaya")) - ((renderContext, "ri")) - ((niceName, "RenderMan for Maya")) - ((exportDescription, "Exports bound shaders as a RenderMan for Maya UsdShade network.")) - ((importDescription, "Imports a RenderMan UsdShade network.")) -); - + ((conversionName, "rendermanForMaya"))((renderContext, "ri"))((niceName, "RenderMan for Maya"))( + (exportDescription, "Exports bound shaders as a RenderMan for Maya UsdShade network."))( + (importDescription, "Imports a RenderMan UsdShade network."))); REGISTER_SHADING_MODE_EXPORT_MATERIAL_CONVERSION( _tokens->conversionName, @@ -58,10 +52,7 @@ REGISTER_SHADING_MODE_IMPORT_MATERIAL_CONVERSION( TF_REGISTRY_FUNCTION(UsdMayaShaderWriterRegistry) { for (const auto& i : RfmNodesToShaderIds) { - UsdMayaSymmetricShaderWriter::RegisterWriter( - i.first, - i.second, - _tokens->conversionName); + UsdMayaSymmetricShaderWriter::RegisterWriter(i.first, i.second, _tokens->conversionName); } }; @@ -71,12 +62,8 @@ TF_REGISTRY_FUNCTION(UsdMayaShaderWriterRegistry) TF_REGISTRY_FUNCTION(UsdMayaShaderReaderRegistry) { for (const auto& i : RfmNodesToShaderIds) { - UsdMayaSymmetricShaderReader::RegisterReader( - i.second, - i.first, - _tokens->conversionName); + UsdMayaSymmetricShaderReader::RegisterReader(i.second, i.first, _tokens->conversionName); } }; - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/shading/usdBlinnReader.cpp b/lib/usd/translators/shading/usdBlinnReader.cpp index 45887b8816..ce79f5a343 100644 --- a/lib/usd/translators/shading/usdBlinnReader.cpp +++ b/lib/usd/translators/shading/usdBlinnReader.cpp @@ -46,7 +46,8 @@ PXR_NAMESPACE_OPEN_SCOPE /// Shader reader for importing UsdPreviewSurface to Maya's blinn material nodes -class PxrUsdTranslators_BlinnReader : public PxrUsdTranslators_LambertReader { +class PxrUsdTranslators_BlinnReader : public PxrUsdTranslators_LambertReader +{ using _BaseClass = PxrUsdTranslators_LambertReader; public: diff --git a/lib/usd/translators/shading/usdBlinnWriter.cpp b/lib/usd/translators/shading/usdBlinnWriter.cpp index 0d557cbc97..09bb55a51b 100644 --- a/lib/usd/translators/shading/usdBlinnWriter.cpp +++ b/lib/usd/translators/shading/usdBlinnWriter.cpp @@ -15,14 +15,14 @@ // #include "usdReflectWriter.h" -#include #include +#include #include -#include #include #include #include +#include #include #include @@ -35,7 +35,8 @@ PXR_NAMESPACE_OPEN_SCOPE -class PxrUsdTranslators_BlinnWriter : public PxrUsdTranslators_ReflectWriter { +class PxrUsdTranslators_BlinnWriter : public PxrUsdTranslators_ReflectWriter +{ typedef PxrUsdTranslators_ReflectWriter BaseClass; public: @@ -58,10 +59,7 @@ TF_DEFINE_PRIVATE_TOKENS( _tokens, // Maya material nodes attribute names - (eccentricity) - (specularColor) - (specularRollOff) -); + (eccentricity)(specularColor)(specularRollOff)); PxrUsdTranslators_BlinnWriter::PxrUsdTranslators_BlinnWriter( const MFnDependencyNode& depNodeFn, @@ -134,7 +132,7 @@ PxrUsdTranslators_BlinnWriter::GetShadingAttributeNameForMayaAttrName(const TfTo return UsdShadeUtils::GetFullName( PxrMayaUsdPreviewSurfaceTokens->RoughnessAttrName, UsdShadeAttributeType::Input); } - + return BaseClass::GetShadingAttributeNameForMayaAttrName(mayaAttrName); } diff --git a/lib/usd/translators/shading/usdDisplacementShaderWriter.cpp b/lib/usd/translators/shading/usdDisplacementShaderWriter.cpp index 725ebe9e41..a117db9cab 100644 --- a/lib/usd/translators/shading/usdDisplacementShaderWriter.cpp +++ b/lib/usd/translators/shading/usdDisplacementShaderWriter.cpp @@ -86,8 +86,7 @@ PxrUsdTranslators_DisplacementShaderWriter::PxrUsdTranslators_DisplacementShader } // Existing UsdPreviewSurface not found. Create one. - UsdShadeShader shaderSchema = - UsdShadeShader::Define(GetUsdStage(), GetUsdPath()); + UsdShadeShader shaderSchema = UsdShadeShader::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( shaderSchema, "Could not define UsdShadeShader at path '%s'\n", @@ -95,8 +94,7 @@ PxrUsdTranslators_DisplacementShaderWriter::PxrUsdTranslators_DisplacementShader return; } - UsdAttribute idAttr = - shaderSchema.CreateIdAttr(VtValue(UsdImagingTokens->UsdPreviewSurface)); + UsdAttribute idAttr = shaderSchema.CreateIdAttr(VtValue(UsdImagingTokens->UsdPreviewSurface)); _usdPrim = shaderSchema.GetPrim(); if (!TF_VERIFY( @@ -107,14 +105,10 @@ PxrUsdTranslators_DisplacementShaderWriter::PxrUsdTranslators_DisplacementShader } // Surface Output - shaderSchema.CreateOutput( - UsdShadeTokens->surface, - SdfValueTypeNames->Token); + shaderSchema.CreateOutput(UsdShadeTokens->surface, SdfValueTypeNames->Token); // Displacement Output - shaderSchema.CreateOutput( - UsdShadeTokens->displacement, - SdfValueTypeNames->Token); + shaderSchema.CreateOutput(UsdShadeTokens->displacement, SdfValueTypeNames->Token); } /* virtual */ diff --git a/lib/usd/translators/shading/usdFileTextureWriter.cpp b/lib/usd/translators/shading/usdFileTextureWriter.cpp index b4a6b7c5ef..98a0d9e12b 100644 --- a/lib/usd/translators/shading/usdFileTextureWriter.cpp +++ b/lib/usd/translators/shading/usdFileTextureWriter.cpp @@ -32,8 +32,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -46,24 +46,24 @@ #include #include + #include PXR_NAMESPACE_OPEN_SCOPE class PxrUsdTranslators_FileTextureWriter : public UsdMayaShaderWriter { - public: - PxrUsdTranslators_FileTextureWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); +public: + PxrUsdTranslators_FileTextureWriter( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); - static ContextSupport CanExport(const UsdMayaJobExportArgs&); + static ContextSupport CanExport(const UsdMayaJobExportArgs&); - void Write(const UsdTimeCode& usdTime) override; + void Write(const UsdTimeCode& usdTime) override; - TfToken GetShadingAttributeNameForMayaAttrName( - const TfToken& mayaAttrName) override; + TfToken GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) override; }; PXRUSDMAYA_REGISTER_SHADER_WRITER(file, PxrUsdTranslators_FileTextureWriter); @@ -72,35 +72,18 @@ TF_DEFINE_PRIVATE_TOKENS( _tokens, // Maya "file" node attribute names - (alphaGain) - (alphaOffset) - (colorGain) - (colorOffset) - (colorSpace) - (defaultColor) - (fileTextureName) - (outAlpha) - (outColor) - (outColorR) - (outColorG) - (outColorB) - (outTransparency) - (outTransparencyR) - (outTransparencyG) - (outTransparencyB) - (wrapU) - (wrapV) + (alphaGain)(alphaOffset)(colorGain)(colorOffset)(colorSpace)(defaultColor)(fileTextureName)( + outAlpha)(outColor)(outColorR)(outColorG)(outColorB)(outTransparency)(outTransparencyR)( + outTransparencyG)(outTransparencyB)(wrapU)(wrapV) // UDIM handling: - (uvTilingMode) - ((UDIMTag, "")) + (uvTilingMode)((UDIMTag, "")) // XXX: We duplicate these tokens here rather than create a dependency on // usdImaging in case the plugin is being built with imaging disabled. // If/when they move out of usdImaging to a place that is always available, // they should be pulled from there instead. - (UsdUVTexture) - (UsdPrimvarReader_float2) + (UsdUVTexture)(UsdPrimvarReader_float2) // UsdPrimvarReader_float2 Prim Name ((PrimvarReaderShaderName, "TexCoordReader")) @@ -112,25 +95,14 @@ TF_DEFINE_PRIVATE_TOKENS( (result) // UsdUVTexture Input Names - (bias) - (fallback) - (file) - (scale) - (st) - (wrapS) - (wrapT) + (bias)(fallback)(file)(scale)(st)(wrapS)(wrapT) // Values for wrapS and wrapT - (black) - (repeat) + (black)(repeat) // UsdUVTexture Output Names - ((RGBOutputName, "rgb")) - ((RedOutputName, "r")) - ((GreenOutputName, "g")) - ((BlueOutputName, "b")) - ((AlphaOutputName, "a")) -); + ((RGBOutputName, "rgb"))((RedOutputName, "r"))((GreenOutputName, "g"))((BlueOutputName, "b"))( + (AlphaOutputName, "a"))); UsdMayaShaderWriter::ContextSupport PxrUsdTranslators_FileTextureWriter::CanExport(const UsdMayaJobExportArgs& exportArgs) @@ -141,14 +113,13 @@ PxrUsdTranslators_FileTextureWriter::CanExport(const UsdMayaJobExportArgs& expor } PxrUsdTranslators_FileTextureWriter::PxrUsdTranslators_FileTextureWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaShaderWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaShaderWriter(depNodeFn, usdPath, jobCtx) { // Create a UsdUVTexture shader as the "primary" shader for this writer. - UsdShadeShader texShaderSchema = - UsdShadeShader::Define(GetUsdStage(), GetUsdPath()); + UsdShadeShader texShaderSchema = UsdShadeShader::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( texShaderSchema, "Could not define UsdShadeShader at path '%s'\n", @@ -168,17 +139,15 @@ PxrUsdTranslators_FileTextureWriter::PxrUsdTranslators_FileTextureWriter( // Now create a UsdPrimvarReader shader that the UsdUvTexture shader will // use. - const SdfPath primvarReaderShaderPath = - texShaderSchema.GetPath().AppendChild(_tokens->PrimvarReaderShaderName); - UsdShadeShader primvarReaderShaderSchema = - UsdShadeShader::Define(GetUsdStage(), primvarReaderShaderPath); + const SdfPath primvarReaderShaderPath + = texShaderSchema.GetPath().AppendChild(_tokens->PrimvarReaderShaderName); + UsdShadeShader primvarReaderShaderSchema + = UsdShadeShader::Define(GetUsdStage(), primvarReaderShaderPath); - primvarReaderShaderSchema.CreateIdAttr( - VtValue(_tokens->UsdPrimvarReader_float2)); + primvarReaderShaderSchema.CreateIdAttr(VtValue(_tokens->UsdPrimvarReader_float2)); - UsdShadeInput varnameInput = primvarReaderShaderSchema.CreateInput( - _tokens->varname, - SdfValueTypeNames->Token); + UsdShadeInput varnameInput + = primvarReaderShaderSchema.CreateInput(_tokens->varname, SdfValueTypeNames->Token); // We expose the primvar reader varname attribute to the material to allow // easy specialization based on UV mappings to geometries: @@ -206,27 +175,23 @@ PxrUsdTranslators_FileTextureWriter::PxrUsdTranslators_FileTextureWriter( varnameInput.Set(UsdUtilsGetPrimaryUVSetName()); } - UsdShadeOutput primvarReaderOutput = - primvarReaderShaderSchema.CreateOutput( - _tokens->result, - SdfValueTypeNames->Float2); + UsdShadeOutput primvarReaderOutput + = primvarReaderShaderSchema.CreateOutput(_tokens->result, SdfValueTypeNames->Float2); // Connect the output of the primvar reader to the texture coordinate // input of the UV texture. - texShaderSchema.CreateInput( - _tokens->st, - SdfValueTypeNames->Float2).ConnectToSource(primvarReaderOutput); + texShaderSchema.CreateInput(_tokens->st, SdfValueTypeNames->Float2) + .ConnectToSource(primvarReaderOutput); } namespace { // Match UDIM pattern, from 1001 to 1999 const std::regex _udimRegex(".*[^\\d](1(?:[0-9][0-9][1-9]|[1-9][1-9]0|0[1-9]0|[1-9]00))(?:[^\\d].*|$)"); -} +} // namespace /* virtual */ -void -PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) +void PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) { UsdMayaShaderWriter::Write(usdTime); @@ -246,11 +211,10 @@ PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) } // File - const MPlug fileTextureNamePlug = - depNodeFn.findPlug( - _tokens->fileTextureName.GetText(), - /* wantNetworkedPlug = */ true, - &status); + const MPlug fileTextureNamePlug = depNodeFn.findPlug( + _tokens->fileTextureName.GetText(), + /* wantNetworkedPlug = */ true, + &status); if (status != MS::kSuccess) { return; } @@ -266,12 +230,13 @@ PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) // USD asset resolvers. For package files, the exporter needs full // paths. const std::string& fileName = GetUsdStage()->GetRootLayer()->GetRealPath(); - TfToken fileExt(TfGetExtension(fileName)); + TfToken fileExt(TfGetExtension(fileName)); if (fileExt != UsdMayaTranslatorTokens->UsdFileExtensionPackage) { boost::filesystem::path usdDir(fileName); usdDir = usdDir.parent_path(); boost::system::error_code ec; - boost::filesystem::path relativePath = boost::filesystem::relative(fileTextureName, usdDir, ec); + boost::filesystem::path relativePath + = boost::filesystem::relative(fileTextureName, usdDir, ec); if (!ec && !relativePath.empty()) { fileTextureName = relativePath.generic_string(); } @@ -304,15 +269,14 @@ PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) // The Maya file node's 'colorGain' and 'alphaGain' attributes map to the // UsdUVTexture's scale input. - bool isScaleAuthored = false; + bool isScaleAuthored = false; GfVec4f scale(1.0f, 1.0f, 1.0f, 1.0f); // Color Gain - const MPlug colorGainPlug = - depNodeFn.findPlug( - _tokens->colorGain.GetText(), - /* wantNetworkedPlug = */ true, - &status); + const MPlug colorGainPlug = depNodeFn.findPlug( + _tokens->colorGain.GetText(), + /* wantNetworkedPlug = */ true, + &status); if (status != MS::kSuccess) { return; } @@ -329,11 +293,10 @@ PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) } // Alpha Gain - const MPlug alphaGainPlug = - depNodeFn.findPlug( - _tokens->alphaGain.GetText(), - /* wantNetworkedPlug = */ true, - &status); + const MPlug alphaGainPlug = depNodeFn.findPlug( + _tokens->alphaGain.GetText(), + /* wantNetworkedPlug = */ true, + &status); if (status != MS::kSuccess) { return; } @@ -348,22 +311,19 @@ PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) } if (isScaleAuthored) { - shaderSchema.CreateInput( - _tokens->scale, - SdfValueTypeNames->Float4).Set(scale, usdTime); + shaderSchema.CreateInput(_tokens->scale, SdfValueTypeNames->Float4).Set(scale, usdTime); } // The Maya file node's 'colorOffset' and 'alphaOffset' attributes map to // the UsdUVTexture's bias input. - bool isBiasAuthored = false; + bool isBiasAuthored = false; GfVec4f bias(0.0f, 0.0f, 0.0f, 0.0f); // Color Offset - const MPlug colorOffsetPlug = - depNodeFn.findPlug( - _tokens->colorOffset.GetText(), - /* wantNetworkedPlug = */ true, - &status); + const MPlug colorOffsetPlug = depNodeFn.findPlug( + _tokens->colorOffset.GetText(), + /* wantNetworkedPlug = */ true, + &status); if (status != MS::kSuccess) { return; } @@ -380,11 +340,10 @@ PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) } // Alpha Offset - const MPlug alphaOffsetPlug = - depNodeFn.findPlug( - _tokens->alphaOffset.GetText(), - /* wantNetworkedPlug = */ true, - &status); + const MPlug alphaOffsetPlug = depNodeFn.findPlug( + _tokens->alphaOffset.GetText(), + /* wantNetworkedPlug = */ true, + &status); if (status != MS::kSuccess) { return; } @@ -399,17 +358,14 @@ PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) } if (isBiasAuthored) { - shaderSchema.CreateInput( - _tokens->bias, - SdfValueTypeNames->Float4).Set(bias, usdTime); + shaderSchema.CreateInput(_tokens->bias, SdfValueTypeNames->Float4).Set(bias, usdTime); } // Default Color - const MPlug defaultColorPlug = - depNodeFn.findPlug( - _tokens->defaultColor.GetText(), - /* wantNetworkedPlug = */ true, - &status); + const MPlug defaultColorPlug = depNodeFn.findPlug( + _tokens->defaultColor.GetText(), + /* wantNetworkedPlug = */ true, + &status); if (status != MS::kSuccess) { return; } @@ -427,16 +383,13 @@ PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) } } - shaderSchema.CreateInput( - _tokens->fallback, - SdfValueTypeNames->Float4).Set(fallback, usdTime); + shaderSchema.CreateInput(_tokens->fallback, SdfValueTypeNames->Float4).Set(fallback, usdTime); // Wrap U - const MPlug wrapUPlug = - depNodeFn.findPlug( - _tokens->wrapU.GetText(), - /* wantNetworkedPlug = */ true, - &status); + const MPlug wrapUPlug = depNodeFn.findPlug( + _tokens->wrapU.GetText(), + /* wantNetworkedPlug = */ true, + &status); if (status != MS::kSuccess) { return; } @@ -448,17 +401,14 @@ PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) } const TfToken wrapS = wrapU ? _tokens->repeat : _tokens->black; - shaderSchema.CreateInput( - _tokens->wrapS, - SdfValueTypeNames->Token).Set(wrapS, usdTime); + shaderSchema.CreateInput(_tokens->wrapS, SdfValueTypeNames->Token).Set(wrapS, usdTime); } // Wrap V - const MPlug wrapVPlug = - depNodeFn.findPlug( - _tokens->wrapV.GetText(), - /* wantNetworkedPlug = */ true, - &status); + const MPlug wrapVPlug = depNodeFn.findPlug( + _tokens->wrapV.GetText(), + /* wantNetworkedPlug = */ true, + &status); if (status != MS::kSuccess) { return; } @@ -470,18 +420,15 @@ PxrUsdTranslators_FileTextureWriter::Write(const UsdTimeCode& usdTime) } const TfToken wrapT = wrapV ? _tokens->repeat : _tokens->black; - shaderSchema.CreateInput( - _tokens->wrapT, - SdfValueTypeNames->Token).Set(wrapT, usdTime); + shaderSchema.CreateInput(_tokens->wrapT, SdfValueTypeNames->Token).Set(wrapT, usdTime); } } /* virtual */ -TfToken -PxrUsdTranslators_FileTextureWriter::GetShadingAttributeNameForMayaAttrName( - const TfToken& mayaAttrName) +TfToken PxrUsdTranslators_FileTextureWriter::GetShadingAttributeNameForMayaAttrName( + const TfToken& mayaAttrName) { - TfToken usdAttrName; + TfToken usdAttrName; SdfValueTypeName usdTypeName = SdfValueTypeNames->Float; if (mayaAttrName == _tokens->outColor) { @@ -493,11 +440,10 @@ PxrUsdTranslators_FileTextureWriter::GetShadingAttributeNameForMayaAttrName( usdAttrName = _tokens->GreenOutputName; } else if (mayaAttrName == _tokens->outColorB) { usdAttrName = _tokens->BlueOutputName; - } else if (mayaAttrName == _tokens->outAlpha || - mayaAttrName == _tokens->outTransparency || - mayaAttrName == _tokens->outTransparencyR || - mayaAttrName == _tokens->outTransparencyG || - mayaAttrName == _tokens->outTransparencyB) { + } else if ( + mayaAttrName == _tokens->outAlpha || mayaAttrName == _tokens->outTransparency + || mayaAttrName == _tokens->outTransparencyR || mayaAttrName == _tokens->outTransparencyG + || mayaAttrName == _tokens->outTransparencyB) { usdAttrName = _tokens->AlphaOutputName; } @@ -515,5 +461,4 @@ PxrUsdTranslators_FileTextureWriter::GetShadingAttributeNameForMayaAttrName( return usdAttrName; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/shading/usdLambertReader.cpp b/lib/usd/translators/shading/usdLambertReader.cpp index 92b68d83ab..c7636ef301 100644 --- a/lib/usd/translators/shading/usdLambertReader.cpp +++ b/lib/usd/translators/shading/usdLambertReader.cpp @@ -98,10 +98,8 @@ void PxrUsdTranslators_LambertReader::_OnBeforeReadAttribute( } /* override */ -void -PxrUsdTranslators_LambertReader::_ConvertToMaya( - const TfToken& mayaAttrName, - VtValue& usdValue) const +void PxrUsdTranslators_LambertReader::_ConvertToMaya(const TfToken& mayaAttrName, VtValue& usdValue) + const { if (mayaAttrName == _tokens->transparency && usdValue.IsHolding()) { const float opacity = usdValue.UncheckedGet(); diff --git a/lib/usd/translators/shading/usdLambertReader.h b/lib/usd/translators/shading/usdLambertReader.h index f2fa99cee8..d1f07b8b1d 100644 --- a/lib/usd/translators/shading/usdLambertReader.h +++ b/lib/usd/translators/shading/usdLambertReader.h @@ -29,7 +29,8 @@ PXR_NAMESPACE_OPEN_SCOPE /// Shader reader for importing UsdPreviewSurface to Maya's lambert material nodes -class PxrUsdTranslators_LambertReader : public PxrUsdTranslators_MaterialReader { +class PxrUsdTranslators_LambertReader : public PxrUsdTranslators_MaterialReader +{ using _BaseClass = PxrUsdTranslators_MaterialReader; public: diff --git a/lib/usd/translators/shading/usdLambertWriter.cpp b/lib/usd/translators/shading/usdLambertWriter.cpp index bb894b77ec..d5553f2c7a 100644 --- a/lib/usd/translators/shading/usdLambertWriter.cpp +++ b/lib/usd/translators/shading/usdLambertWriter.cpp @@ -15,14 +15,14 @@ // #include "usdLambertWriter.h" -#include #include +#include #include -#include #include #include #include +#include #include #include #include @@ -43,12 +43,7 @@ TF_DEFINE_PRIVATE_TOKENS( _tokens, // Maya material nodes attribute names - (color) - (transparency) - (diffuse) - (incandescence) - (normalCamera) -); + (color)(transparency)(diffuse)(incandescence)(normalCamera)); PxrUsdTranslators_LambertWriter::PxrUsdTranslators_LambertWriter( const MFnDependencyNode& depNodeFn, @@ -86,16 +81,13 @@ void PxrUsdTranslators_LambertWriter::Write(const UsdTimeCode& usdTime) usdTime, _tokens->diffuse); - const MPlug transparencyPlug = - depNodeFn.findPlug( - depNodeFn.attribute(_tokens->transparency.GetText()), - /* wantNetworkedPlug = */ true, - &status); + const MPlug transparencyPlug = depNodeFn.findPlug( + depNodeFn.attribute(_tokens->transparency.GetText()), + /* wantNetworkedPlug = */ true, + &status); if (status == MS::kSuccess && UsdMayaUtil::IsAuthored(transparencyPlug)) { - UsdShadeInput opacityInput = - shaderSchema.CreateInput( - PxrMayaUsdPreviewSurfaceTokens->OpacityAttrName, - SdfValueTypeNames->Float); + UsdShadeInput opacityInput = shaderSchema.CreateInput( + PxrMayaUsdPreviewSurfaceTokens->OpacityAttrName, SdfValueTypeNames->Float); // For attributes that are the destination of a connection, we create // the input on the shader but we do *not* author a value for it. We @@ -103,10 +95,10 @@ void PxrUsdTranslators_LambertWriter::Write(const UsdTimeCode& usdTime) // We'll leave it to the shading export to handle creating the // connections in USD. if (!transparencyPlug.isDestination(&status)) { - const float transparencyAvg = - (transparencyPlug.child(0u).asFloat() + - transparencyPlug.child(1u).asFloat() + - transparencyPlug.child(2u).asFloat()) / 3.0f; + const float transparencyAvg + = (transparencyPlug.child(0u).asFloat() + transparencyPlug.child(1u).asFloat() + + transparencyPlug.child(2u).asFloat()) + / 3.0f; opacityInput.Set(1.0f - transparencyAvg, usdTime); } diff --git a/lib/usd/translators/shading/usdLambertWriter.h b/lib/usd/translators/shading/usdLambertWriter.h index c0abe307cd..4aced44998 100644 --- a/lib/usd/translators/shading/usdLambertWriter.h +++ b/lib/usd/translators/shading/usdLambertWriter.h @@ -18,10 +18,10 @@ /// \file -#include - #include "usdMaterialWriter.h" +#include + PXR_NAMESPACE_OPEN_SCOPE /// Shader writer for exporting the Lambert part of a Maya shading node to USD. @@ -30,19 +30,18 @@ class PxrUsdTranslators_LambertWriter : public PxrUsdTranslators_MaterialWriter { typedef PxrUsdTranslators_MaterialWriter BaseClass; - public: - PxrUsdTranslators_LambertWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); +public: + PxrUsdTranslators_LambertWriter( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); - void Write(const UsdTimeCode& usdTime) override; + void Write(const UsdTimeCode& usdTime) override; - TfToken GetShadingAttributeNameForMayaAttrName( - const TfToken& mayaAttrName) override; + TfToken GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) override; - protected: - virtual void WriteSpecular(const UsdTimeCode& usdTime); +protected: + virtual void WriteSpecular(const UsdTimeCode& usdTime); }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/shading/usdMaterialReader.h b/lib/usd/translators/shading/usdMaterialReader.h index 20238843e4..528719a9c2 100644 --- a/lib/usd/translators/shading/usdMaterialReader.h +++ b/lib/usd/translators/shading/usdMaterialReader.h @@ -32,7 +32,8 @@ struct UsdMayaJobImportArgs; class UsdShadeShader; /// Shader reader for importing UsdPreviewSurface to Maya's native material nodes -class PxrUsdTranslators_MaterialReader : public UsdMayaShaderReader { +class PxrUsdTranslators_MaterialReader : public UsdMayaShaderReader +{ public: PxrUsdTranslators_MaterialReader(const UsdMayaPrimReaderArgs&); diff --git a/lib/usd/translators/shading/usdMaterialWriter.cpp b/lib/usd/translators/shading/usdMaterialWriter.cpp index 68a2eaafdb..397137587e 100644 --- a/lib/usd/translators/shading/usdMaterialWriter.cpp +++ b/lib/usd/translators/shading/usdMaterialWriter.cpp @@ -15,18 +15,19 @@ // #include "usdMaterialWriter.h" -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include -#include #include #include #include #include +#include #include #include #include @@ -37,13 +38,12 @@ #include #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include @@ -55,8 +55,7 @@ TF_DEFINE_PRIVATE_TOKENS( _tokens, // Maya material nodes attribute names - (outColor) -); + (outColor)); UsdMayaShaderWriter::ContextSupport PxrUsdTranslators_MaterialWriter::CanExport(const UsdMayaJobExportArgs& exportArgs) @@ -67,13 +66,12 @@ PxrUsdTranslators_MaterialWriter::CanExport(const UsdMayaJobExportArgs& exportAr } PxrUsdTranslators_MaterialWriter::PxrUsdTranslators_MaterialWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaShaderWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaShaderWriter(depNodeFn, usdPath, jobCtx) { - UsdShadeShader shaderSchema = - UsdShadeShader::Define(GetUsdStage(), GetUsdPath()); + UsdShadeShader shaderSchema = UsdShadeShader::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( shaderSchema, "Could not define UsdShadeShader at path '%s'\n", @@ -81,8 +79,7 @@ PxrUsdTranslators_MaterialWriter::PxrUsdTranslators_MaterialWriter( return; } - UsdAttribute idAttr = - shaderSchema.CreateIdAttr(VtValue(UsdImagingTokens->UsdPreviewSurface)); + UsdAttribute idAttr = shaderSchema.CreateIdAttr(VtValue(UsdImagingTokens->UsdPreviewSurface)); _usdPrim = shaderSchema.GetPrim(); if (!TF_VERIFY( @@ -93,25 +90,20 @@ PxrUsdTranslators_MaterialWriter::PxrUsdTranslators_MaterialWriter( } // Surface Output - shaderSchema.CreateOutput( - UsdShadeTokens->surface, - SdfValueTypeNames->Token); + shaderSchema.CreateOutput(UsdShadeTokens->surface, SdfValueTypeNames->Token); // Displacement Output - shaderSchema.CreateOutput( - UsdShadeTokens->displacement, - SdfValueTypeNames->Token); + shaderSchema.CreateOutput(UsdShadeTokens->displacement, SdfValueTypeNames->Token); } -bool -PxrUsdTranslators_MaterialWriter::AuthorShaderInputFromShadingNodeAttr( - const MFnDependencyNode& depNodeFn, - const TfToken& shadingNodeAttrName, - UsdShadeShader& shaderSchema, - const TfToken& shaderInputName, - const UsdTimeCode usdTime, - bool ignoreIfUnauthored, - const SdfValueTypeName& inputTypeName) +bool PxrUsdTranslators_MaterialWriter::AuthorShaderInputFromShadingNodeAttr( + const MFnDependencyNode& depNodeFn, + const TfToken& shadingNodeAttrName, + UsdShadeShader& shaderSchema, + const TfToken& shaderInputName, + const UsdTimeCode usdTime, + bool ignoreIfUnauthored, + const SdfValueTypeName& inputTypeName) { return AuthorShaderInputFromScaledShadingNodeAttr( depNodeFn, @@ -124,24 +116,22 @@ PxrUsdTranslators_MaterialWriter::AuthorShaderInputFromShadingNodeAttr( inputTypeName); } -bool -PxrUsdTranslators_MaterialWriter::AuthorShaderInputFromScaledShadingNodeAttr( - const MFnDependencyNode& depNodeFn, - const TfToken& shadingNodeAttrName, - UsdShadeShader& shaderSchema, - const TfToken& shaderInputName, - const UsdTimeCode usdTime, - const TfToken& scalingAttrName, - bool ignoreIfUnauthored, - const SdfValueTypeName& inputTypeName) +bool PxrUsdTranslators_MaterialWriter::AuthorShaderInputFromScaledShadingNodeAttr( + const MFnDependencyNode& depNodeFn, + const TfToken& shadingNodeAttrName, + UsdShadeShader& shaderSchema, + const TfToken& shaderInputName, + const UsdTimeCode usdTime, + const TfToken& scalingAttrName, + bool ignoreIfUnauthored, + const SdfValueTypeName& inputTypeName) { MStatus status; - MPlug shadingNodePlug = - depNodeFn.findPlug( - depNodeFn.attribute(shadingNodeAttrName.GetText()), - /* wantNetworkedPlug = */ true, - &status); + MPlug shadingNodePlug = depNodeFn.findPlug( + depNodeFn.attribute(shadingNodeAttrName.GetText()), + /* wantNetworkedPlug = */ true, + &status); if (status != MS::kSuccess) { return false; } @@ -156,25 +146,21 @@ PxrUsdTranslators_MaterialWriter::AuthorShaderInputFromScaledShadingNodeAttr( return false; } - const SdfValueTypeName shaderInputTypeName = - bool(inputTypeName) ? - inputTypeName : - Converter::getUsdTypeName(shadingNodePlug); + const SdfValueTypeName shaderInputTypeName + = bool(inputTypeName) ? inputTypeName : Converter::getUsdTypeName(shadingNodePlug); // Are color values are all linear on the shader? // Do we need to re-linearize them? - VtValue value = - UsdMayaWriteUtil::GetVtValue( - shadingNodePlug, - shaderInputTypeName, - /* linearizeColors = */ false); + VtValue value = UsdMayaWriteUtil::GetVtValue( + shadingNodePlug, + shaderInputTypeName, + /* linearizeColors = */ false); if (value.IsEmpty()) { return false; } - UsdShadeInput shaderInput = - shaderSchema.CreateInput(shaderInputName, shaderInputTypeName); + UsdShadeInput shaderInput = shaderSchema.CreateInput(shaderInputName, shaderInputTypeName); // For attributes that are the destination of a connection, we create // the input on the shader but we do *not* author a value for it. We @@ -185,11 +171,10 @@ PxrUsdTranslators_MaterialWriter::AuthorShaderInputFromScaledShadingNodeAttr( if (scalingAttrName != TfToken() && value.IsHolding()) { float colorScale = 1.0f; - MPlug scalingPlug = - depNodeFn.findPlug( - depNodeFn.attribute(scalingAttrName.GetText()), - /* wantNetworkedPlug = */ true, - &status); + MPlug scalingPlug = depNodeFn.findPlug( + depNodeFn.attribute(scalingAttrName.GetText()), + /* wantNetworkedPlug = */ true, + &status); if (status == MS::kSuccess) { colorScale = scalingPlug.asFloat(); } @@ -204,9 +189,8 @@ PxrUsdTranslators_MaterialWriter::AuthorShaderInputFromScaledShadingNodeAttr( } /* virtual */ -TfToken -PxrUsdTranslators_MaterialWriter::GetShadingAttributeNameForMayaAttrName( - const TfToken& mayaAttrName) +TfToken PxrUsdTranslators_MaterialWriter::GetShadingAttributeNameForMayaAttrName( + const TfToken& mayaAttrName) { if (mayaAttrName == _tokens->outColor) { return UsdShadeUtils::GetFullName(UsdShadeTokens->surface, UsdShadeAttributeType::Output); diff --git a/lib/usd/translators/shading/usdMaterialWriter.h b/lib/usd/translators/shading/usdMaterialWriter.h index 15146b5496..3adb87ce89 100644 --- a/lib/usd/translators/shading/usdMaterialWriter.h +++ b/lib/usd/translators/shading/usdMaterialWriter.h @@ -36,62 +36,60 @@ class UsdTimeCode; /// Shader writer for exporting Maya's material shading nodes to USD. class PxrUsdTranslators_MaterialWriter : public UsdMayaShaderWriter { - public: - PxrUsdTranslators_MaterialWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); +public: + PxrUsdTranslators_MaterialWriter( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); - static ContextSupport CanExport(const UsdMayaJobExportArgs&); + static ContextSupport CanExport(const UsdMayaJobExportArgs&); - TfToken GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) override; + TfToken GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) override; - protected: - /// Adds the schema attribute \p shaderInputName to the schema \p shaderSchema if the - /// Maya attribute \p shadingNodeAttrName in dependency node \p depNodeFn has been modified - /// or has an incoming connection at \p usdTime. - /// - /// By default, the shader input will be created and authored - /// regardless of whether the Maya attribute is authored or connected. - /// If instead the shader input should only be authored if the Maya - /// attribute is authored, the optional \p ignoreIfUnauthored parameter - /// can be set to true. This may be appropriate for cases where the - /// Maya attribute and the shader input share the same default value - /// (for example, "incandescence" in Maya and "emissiveColor" in - /// UsdPreviewSurface are both black by default). - /// - /// If a specific SdfValueTypeName is desired for the created - /// UsdShadeInput, it can be provided with the optional - /// \p inputTypeName parameter. This is useful in cases where the role - /// of the value type name may not be discoverable strictly from - /// inspecting the Maya attribute plug (for example, determining that - /// the "normalCamera" attributes of Maya shaders should be exported as - /// Normal3f rather than just Float3). - bool AuthorShaderInputFromShadingNodeAttr( - const MFnDependencyNode& depNodeFn, - const TfToken& shadingNodeAttrName, - UsdShadeShader& shaderSchema, - const TfToken& shaderInputName, - const UsdTimeCode usdTime, - bool ignoreIfUnauthored = false, - const SdfValueTypeName& inputTypeName = SdfValueTypeName()); - - /// Same as AuthorShaderInputFromShadingNodeAttr, but allows scaling the value using a float - /// value found in the attribute \p scalingAttrName of the dependency node \p depNodeFn. - /// - bool AuthorShaderInputFromScaledShadingNodeAttr( - const MFnDependencyNode& depNodeFn, - const TfToken& shadingNodeAttrName, - UsdShadeShader& shaderSchema, - const TfToken& shaderInputName, - const UsdTimeCode usdTime, - const TfToken& scalingAttrName, - bool ignoreIfUnauthored = false, - const SdfValueTypeName& inputTypeName = SdfValueTypeName()); +protected: + /// Adds the schema attribute \p shaderInputName to the schema \p shaderSchema if the + /// Maya attribute \p shadingNodeAttrName in dependency node \p depNodeFn has been modified + /// or has an incoming connection at \p usdTime. + /// + /// By default, the shader input will be created and authored + /// regardless of whether the Maya attribute is authored or connected. + /// If instead the shader input should only be authored if the Maya + /// attribute is authored, the optional \p ignoreIfUnauthored parameter + /// can be set to true. This may be appropriate for cases where the + /// Maya attribute and the shader input share the same default value + /// (for example, "incandescence" in Maya and "emissiveColor" in + /// UsdPreviewSurface are both black by default). + /// + /// If a specific SdfValueTypeName is desired for the created + /// UsdShadeInput, it can be provided with the optional + /// \p inputTypeName parameter. This is useful in cases where the role + /// of the value type name may not be discoverable strictly from + /// inspecting the Maya attribute plug (for example, determining that + /// the "normalCamera" attributes of Maya shaders should be exported as + /// Normal3f rather than just Float3). + bool AuthorShaderInputFromShadingNodeAttr( + const MFnDependencyNode& depNodeFn, + const TfToken& shadingNodeAttrName, + UsdShadeShader& shaderSchema, + const TfToken& shaderInputName, + const UsdTimeCode usdTime, + bool ignoreIfUnauthored = false, + const SdfValueTypeName& inputTypeName = SdfValueTypeName()); + /// Same as AuthorShaderInputFromShadingNodeAttr, but allows scaling the value using a float + /// value found in the attribute \p scalingAttrName of the dependency node \p depNodeFn. + /// + bool AuthorShaderInputFromScaledShadingNodeAttr( + const MFnDependencyNode& depNodeFn, + const TfToken& shadingNodeAttrName, + UsdShadeShader& shaderSchema, + const TfToken& shaderInputName, + const UsdTimeCode usdTime, + const TfToken& scalingAttrName, + bool ignoreIfUnauthored = false, + const SdfValueTypeName& inputTypeName = SdfValueTypeName()); }; PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/translators/shading/usdPhongEWriter.cpp b/lib/usd/translators/shading/usdPhongEWriter.cpp index 704c4fdf3a..41731aa1c3 100644 --- a/lib/usd/translators/shading/usdPhongEWriter.cpp +++ b/lib/usd/translators/shading/usdPhongEWriter.cpp @@ -15,14 +15,14 @@ // #include "usdReflectWriter.h" -#include #include +#include #include -#include #include #include #include +#include #include #include @@ -35,7 +35,8 @@ PXR_NAMESPACE_OPEN_SCOPE -class PxrUsdTranslators_PhongEWriter : public PxrUsdTranslators_ReflectWriter { +class PxrUsdTranslators_PhongEWriter : public PxrUsdTranslators_ReflectWriter +{ typedef PxrUsdTranslators_ReflectWriter BaseClass; public: @@ -55,8 +56,7 @@ TF_DEFINE_PRIVATE_TOKENS( _tokens, // Maya - (roughness) -); + (roughness)); PxrUsdTranslators_PhongEWriter::PxrUsdTranslators_PhongEWriter( const MFnDependencyNode& depNodeFn, @@ -102,7 +102,7 @@ PxrUsdTranslators_PhongEWriter::GetShadingAttributeNameForMayaAttrName(const TfT return UsdShadeUtils::GetFullName( PxrMayaUsdPreviewSurfaceTokens->RoughnessAttrName, UsdShadeAttributeType::Input); } - + return BaseClass::GetShadingAttributeNameForMayaAttrName(mayaAttrName); } diff --git a/lib/usd/translators/shading/usdPhongReader.cpp b/lib/usd/translators/shading/usdPhongReader.cpp index 3f6cbf1664..735f8ba29b 100644 --- a/lib/usd/translators/shading/usdPhongReader.cpp +++ b/lib/usd/translators/shading/usdPhongReader.cpp @@ -45,7 +45,8 @@ PXR_NAMESPACE_OPEN_SCOPE /// Shader reader for importing UsdPreviewSurface to Maya's phong material nodes -class PxrUsdTranslators_PhongReader : public PxrUsdTranslators_LambertReader { +class PxrUsdTranslators_PhongReader : public PxrUsdTranslators_LambertReader +{ using _BaseClass = PxrUsdTranslators_LambertReader; public: diff --git a/lib/usd/translators/shading/usdPhongWriter.cpp b/lib/usd/translators/shading/usdPhongWriter.cpp index 991e97ad40..084a2982da 100644 --- a/lib/usd/translators/shading/usdPhongWriter.cpp +++ b/lib/usd/translators/shading/usdPhongWriter.cpp @@ -15,16 +15,16 @@ // #include "usdReflectWriter.h" -#include #include +#include #include #include -#include #include #include #include #include +#include #include #include #include @@ -39,7 +39,8 @@ PXR_NAMESPACE_OPEN_SCOPE -class PxrUsdTranslators_PhongWriter : public PxrUsdTranslators_ReflectWriter { +class PxrUsdTranslators_PhongWriter : public PxrUsdTranslators_ReflectWriter +{ typedef PxrUsdTranslators_ReflectWriter BaseClass; public: @@ -57,8 +58,7 @@ TF_DEFINE_PRIVATE_TOKENS( _tokens, // Maya material nodes attribute names - (cosinePower) -); + (cosinePower)); PxrUsdTranslators_PhongWriter::PxrUsdTranslators_PhongWriter( const MFnDependencyNode& depNodeFn, diff --git a/lib/usd/translators/shading/usdReflectWriter.cpp b/lib/usd/translators/shading/usdReflectWriter.cpp index a79b80e16e..81fdfb0780 100644 --- a/lib/usd/translators/shading/usdReflectWriter.cpp +++ b/lib/usd/translators/shading/usdReflectWriter.cpp @@ -15,9 +15,9 @@ // #include "usdReflectWriter.h" -#include #include #include +#include #include #include @@ -32,8 +32,7 @@ TF_DEFINE_PRIVATE_TOKENS( _tokens, // Maya material nodes attribute names - (specularColor) -); + (specularColor)); PxrUsdTranslators_ReflectWriter::PxrUsdTranslators_ReflectWriter( const MFnDependencyNode& depNodeFn, diff --git a/lib/usd/translators/shading/usdReflectWriter.h b/lib/usd/translators/shading/usdReflectWriter.h index 8a22792004..06f1f02945 100644 --- a/lib/usd/translators/shading/usdReflectWriter.h +++ b/lib/usd/translators/shading/usdReflectWriter.h @@ -18,10 +18,10 @@ /// \file -#include - #include "usdLambertWriter.h" +#include + PXR_NAMESPACE_OPEN_SCOPE /// Shader writer for exporting the reflective part of a Maya shading node to USD. @@ -30,17 +30,16 @@ class PxrUsdTranslators_ReflectWriter : public PxrUsdTranslators_LambertWriter { typedef PxrUsdTranslators_LambertWriter BaseClass; - public: - PxrUsdTranslators_ReflectWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); +public: + PxrUsdTranslators_ReflectWriter( + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); - TfToken GetShadingAttributeNameForMayaAttrName( - const TfToken& mayaAttrName) override; + TfToken GetShadingAttributeNameForMayaAttrName(const TfToken& mayaAttrName) override; - protected: - void WriteSpecular(const UsdTimeCode& usdTime) override; +protected: + void WriteSpecular(const UsdTimeCode& usdTime) override; }; PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/shading/usdStandardSurfaceReader.cpp b/lib/usd/translators/shading/usdStandardSurfaceReader.cpp index dcfc97a654..c1f8f8e06c 100644 --- a/lib/usd/translators/shading/usdStandardSurfaceReader.cpp +++ b/lib/usd/translators/shading/usdStandardSurfaceReader.cpp @@ -46,7 +46,8 @@ PXR_NAMESPACE_OPEN_SCOPE /// Shader reader for importing UsdPreviewSurface to Maya's standardSurface material nodes -class PxrUsdTranslators_StandardSurfaceReader : public PxrUsdTranslators_MaterialReader { +class PxrUsdTranslators_StandardSurfaceReader : public PxrUsdTranslators_MaterialReader +{ using _BaseClass = PxrUsdTranslators_MaterialReader; public: diff --git a/lib/usd/translators/shading/usdStandardSurfaceWriter.cpp b/lib/usd/translators/shading/usdStandardSurfaceWriter.cpp index 1e3557f449..42d635f8c7 100644 --- a/lib/usd/translators/shading/usdStandardSurfaceWriter.cpp +++ b/lib/usd/translators/shading/usdStandardSurfaceWriter.cpp @@ -15,16 +15,16 @@ // #include "usdMaterialWriter.h" -#include #include +#include #include #include -#include #include #include #include #include +#include #include #include #include @@ -39,7 +39,8 @@ PXR_NAMESPACE_OPEN_SCOPE -class PxrUsdTranslators_StandardSurfaceWriter : public PxrUsdTranslators_MaterialWriter { +class PxrUsdTranslators_StandardSurfaceWriter : public PxrUsdTranslators_MaterialWriter +{ typedef PxrUsdTranslators_MaterialWriter BaseClass; public: @@ -59,20 +60,8 @@ TF_DEFINE_PRIVATE_TOKENS( _tokens, // Maya material nodes attribute names - (base) - (baseColor) - (emission) - (emissionColor) - (metalness) - (specular) - (specularColor) - (specularIOR) - (specularRoughness) - (coat) - (coatRoughness) - (transmission) - (normalCamera) -); + (base)(baseColor)(emission)(emissionColor)(metalness)(specular)(specularColor)(specularIOR)( + specularRoughness)(coat)(coatRoughness)(transmission)(normalCamera)); PxrUsdTranslators_StandardSurfaceWriter::PxrUsdTranslators_StandardSurfaceWriter( const MFnDependencyNode& depNodeFn, diff --git a/lib/usd/translators/shading/usdUVTextureReader.cpp b/lib/usd/translators/shading/usdUVTextureReader.cpp index 3ea413fce7..50f4a281c9 100644 --- a/lib/usd/translators/shading/usdUVTextureReader.cpp +++ b/lib/usd/translators/shading/usdUVTextureReader.cpp @@ -19,11 +19,11 @@ #include #include -#include #include #include #include #include +#include #include #include #include @@ -43,7 +43,8 @@ PXR_NAMESPACE_OPEN_SCOPE -class PxrMayaUsdUVTexture_Reader : public UsdMayaShaderReader { +class PxrMayaUsdUVTexture_Reader : public UsdMayaShaderReader +{ public: PxrMayaUsdUVTexture_Reader(const UsdMayaPrimReaderArgs&); @@ -58,59 +59,23 @@ TF_DEFINE_PRIVATE_TOKENS( _tokens, // Maya "file" node attribute names - (file) - (alphaGain) - (alphaOffset) - (colorGain) - (colorOffset) - (colorSpace) - (defaultColor) - (fileTextureName) - (outAlpha) - (outColor) - (outColorR) - (outColorG) - (outColorB) - (place2dTexture) - (coverage) - (translateFrame) - (rotateFrame) - (mirrorU) - (mirrorV) - (stagger) - (wrapU) - (wrapV) - (repeatUV) - (offset) - (rotateUV) - (noiseUV) - (vertexUvOne) - (vertexUvTwo) - (vertexUvThree) - (vertexCameraOne) + (file)(alphaGain)(alphaOffset)(colorGain)(colorOffset)(colorSpace)(defaultColor)( + fileTextureName)(outAlpha)(outColor)(outColorR)(outColorG)(outColorB)(place2dTexture)( + coverage)(translateFrame)(rotateFrame)(mirrorU)(mirrorV)(stagger)(wrapU)(wrapV)(repeatUV)( + offset)(rotateUV)(noiseUV)(vertexUvOne)(vertexUvTwo)(vertexUvThree)(vertexCameraOne) // UsdUVTexture Input Names - (bias) - (fallback) - (scale) - (wrapS) - (wrapT) + (bias)(fallback)(scale)(wrapS)(wrapT) // Values for wrapS and wrapT - (black) - (repeat) + (black)(repeat) // UsdUVTexture Output Names - ((RGBOutputName, "rgb")) - ((RedOutputName, "r")) - ((GreenOutputName, "g")) - ((BlueOutputName, "b")) - ((AlphaOutputName, "a")) + ((RGBOutputName, "rgb"))((RedOutputName, "r"))((GreenOutputName, "g"))((BlueOutputName, "b"))( + (AlphaOutputName, "a")) // UDIM detection - ((UDIMTag, "")) - (uvTilingMode) -); + ((UDIMTag, ""))(uvTilingMode)); static const TfTokenVector _Place2dTextureConnections = { _tokens->coverage, _tokens->translateFrame, _tokens->rotateFrame, _tokens->mirrorU, @@ -320,7 +285,7 @@ bool PxrMayaUsdUVTexture_Reader::Read(UsdMayaPrimReaderContext* context) /* virtual */ TfToken PxrMayaUsdUVTexture_Reader::GetMayaNameForUsdAttrName(const TfToken& usdAttrName) const { - TfToken usdOutputName; + TfToken usdOutputName; UsdShadeAttributeType attrType; std::tie(usdOutputName, attrType) = UsdShadeUtils::GetBaseNameAndType(usdAttrName); diff --git a/lib/usd/translators/skelReader.cpp b/lib/usd/translators/skelReader.cpp index 2be7e238ec..98bc6a6acf 100644 --- a/lib/usd/translators/skelReader.cpp +++ b/lib/usd/translators/skelReader.cpp @@ -13,7 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include +#include +#include #include #include @@ -24,9 +26,7 @@ #include #include -#include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -37,9 +37,11 @@ class UsdMayaPrimReaderSkeleton : public UsdMayaPrimReader { public: UsdMayaPrimReaderSkeleton(const UsdMayaPrimReaderArgs& args) - : UsdMayaPrimReader(args) {} + : UsdMayaPrimReader(args) + { + } - ~UsdMayaPrimReaderSkeleton() override {} + ~UsdMayaPrimReaderSkeleton() override { } bool Read(UsdMayaPrimReaderContext* context) override; @@ -49,17 +51,13 @@ class UsdMayaPrimReaderSkeleton : public UsdMayaPrimReader UsdSkelCache _cache; }; - -TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaPrimReaderRegistry, UsdSkelSkeleton) { - UsdMayaPrimReaderRegistry::Register( - [](const UsdMayaPrimReaderArgs& args) - { - return UsdMayaPrimReaderSharedPtr( - new UsdMayaPrimReaderSkeleton(args)); - }); +TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaPrimReaderRegistry, UsdSkelSkeleton) +{ + UsdMayaPrimReaderRegistry::Register([](const UsdMayaPrimReaderArgs& args) { + return UsdMayaPrimReaderSharedPtr(new UsdMayaPrimReaderSkeleton(args)); + }); } - /// Prim reader for a UsdSkelRoot. /// This post-processes the skinnable prims beneath a UsdSkelRoot /// to define skin clusters, etc. for bound skeletons. @@ -67,9 +65,11 @@ class UsdMayaPrimReaderSkelRoot : public UsdMayaPrimReader { public: UsdMayaPrimReaderSkelRoot(const UsdMayaPrimReaderArgs& args) - : UsdMayaPrimReader(args) {} + : UsdMayaPrimReader(args) + { + } - ~UsdMayaPrimReaderSkelRoot() override {} + ~UsdMayaPrimReaderSkelRoot() override { } bool Read(UsdMayaPrimReaderContext* context) override; @@ -83,20 +83,14 @@ class UsdMayaPrimReaderSkelRoot : public UsdMayaPrimReader UsdSkelCache _cache; }; - - -TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaPrimReaderRegistry, UsdSkelRoot) { - UsdMayaPrimReaderRegistry::Register( - [](const UsdMayaPrimReaderArgs& args) - { - return UsdMayaPrimReaderSharedPtr( - new UsdMayaPrimReaderSkelRoot(args)); - }); +TF_REGISTRY_FUNCTION_WITH_TAG(UsdMayaPrimReaderRegistry, UsdSkelRoot) +{ + UsdMayaPrimReaderRegistry::Register([](const UsdMayaPrimReaderArgs& args) { + return UsdMayaPrimReaderSharedPtr(new UsdMayaPrimReaderSkelRoot(args)); + }); } - -bool -UsdMayaPrimReaderSkeleton::Read(UsdMayaPrimReaderContext* context) +bool UsdMayaPrimReaderSkeleton::Read(UsdMayaPrimReaderContext* context) { UsdSkelSkeleton skel(_GetArgs().GetUsdPrim()); if (!TF_VERIFY(skel)) @@ -104,8 +98,7 @@ UsdMayaPrimReaderSkeleton::Read(UsdMayaPrimReaderContext* context) if (UsdSkelSkeletonQuery skelQuery = _cache.GetSkelQuery(skel)) { - MObject parentNode = context->GetMayaNode( - skel.GetPrim().GetPath().GetParentPath(), true); + MObject parentNode = context->GetMayaNode(skel.GetPrim().GetPath().GetParentPath(), true); // Build out a joint hierarchy. VtArray joints; @@ -116,10 +109,9 @@ UsdMayaPrimReaderSkeleton::Read(UsdMayaPrimReaderContext* context) // This is not necessary for skinning to function i Maya, but is not // necessary in order to properly round-trip the Skeleton's // restTransforms, and is a requirement of some exporters. - // The dagPose command also will not work without this. + // The dagPose command also will not work without this. MObject bindPose; - if (UsdMayaTranslatorSkel::CreateBindPose( - skelQuery, joints, context, &bindPose)) { + if (UsdMayaTranslatorSkel::CreateBindPose(skelQuery, joints, context, &bindPose)) { return true; } } @@ -127,9 +119,7 @@ UsdMayaPrimReaderSkeleton::Read(UsdMayaPrimReaderContext* context) return false; } - -bool -UsdMayaPrimReaderSkelRoot::Read(UsdMayaPrimReaderContext* context) +bool UsdMayaPrimReaderSkelRoot::Read(UsdMayaPrimReaderContext* context) { UsdSkelRoot skelRoot(_GetArgs().GetUsdPrim()); if (!TF_VERIFY(skelRoot)) @@ -138,9 +128,9 @@ UsdMayaPrimReaderSkelRoot::Read(UsdMayaPrimReaderContext* context) // First pass through: // The skel root itself is a transform, so produce a transform. // Skeletal bindings will be handled as a post sub-tree process. - MObject parentNode = - context->GetMayaNode(skelRoot.GetPrim().GetPath().GetParentPath(), - /*findAncestors*/ true); + MObject parentNode = context->GetMayaNode( + skelRoot.GetPrim().GetPath().GetParentPath(), + /*findAncestors*/ true); MStatus status; MObject obj; @@ -148,15 +138,12 @@ UsdMayaPrimReaderSkelRoot::Read(UsdMayaPrimReaderContext* context) skelRoot.GetPrim(), parentNode, _GetArgs(), context, &status, &obj); } - -void -UsdMayaPrimReaderSkelRoot::PostReadSubtree( - UsdMayaPrimReaderContext* context) +void UsdMayaPrimReaderSkelRoot::PostReadSubtree(UsdMayaPrimReaderContext* context) { UsdSkelRoot skelRoot(_GetArgs().GetUsdPrim()); if (!TF_VERIFY(skelRoot)) return; - + // Compute skel bindings and create skin clusters for bound skels // We do this in a post-subtree stage to ensure that any skinnable // prims we produce skin clusters for have been processed first. @@ -166,10 +153,7 @@ UsdMayaPrimReaderSkelRoot::PostReadSubtree( #if USD_VERSION_NUM > 2008 _cache.Populate(skelRoot, UsdTraverseInstanceProxies()); - if (!_cache.ComputeSkelBindings( - skelRoot, - &bindings, - UsdTraverseInstanceProxies())) { + if (!_cache.ComputeSkelBindings(skelRoot, &bindings, UsdTraverseInstanceProxies())) { return; } #else @@ -184,15 +168,13 @@ UsdMayaPrimReaderSkelRoot::PostReadSubtree( if (binding.GetSkinningTargets().empty()) continue; - if (const UsdSkelSkeletonQuery& skelQuery = - _cache.GetSkelQuery(binding.GetSkeleton())) { - + if (const UsdSkelSkeletonQuery& skelQuery = _cache.GetSkelQuery(binding.GetSkeleton())) { + VtArray joints; - if (!UsdMayaTranslatorSkel::GetJoints( - skelQuery, context, &joints)) { + if (!UsdMayaTranslatorSkel::GetJoints(skelQuery, context, &joints)) { continue; } - + for (const auto& skinningQuery : binding.GetSkinningTargets()) { const UsdPrim& skinnedPrim = skinningQuery.GetPrim(); @@ -211,13 +193,12 @@ UsdMayaPrimReaderSkelRoot::PostReadSubtree( VtIntArray indices(joints.size()); for (size_t i = 0; i < joints.size(); ++i) indices[i] = i; - + VtIntArray remappedIndices; - if (!skinningQuery.GetMapper()->Remap( - indices, &remappedIndices)) { + if (!skinningQuery.GetMapper()->Remap(indices, &remappedIndices)) { continue; } - + skinningJoints.resize(remappedIndices.size()); for (size_t i = 0; i < remappedIndices.size(); ++i) { int index = remappedIndices[i]; @@ -227,17 +208,20 @@ UsdMayaPrimReaderSkelRoot::PostReadSubtree( } } - MObject bindPose - = UsdMayaTranslatorSkel::GetBindPose(skelQuery, context); + MObject bindPose = UsdMayaTranslatorSkel::GetBindPose(skelQuery, context); // Add a skin cluster to skin this prim. UsdMayaTranslatorSkel::CreateSkinCluster( - skelQuery, skinningQuery, skinningJoints, - skinnedPrim, _GetArgs(), context, bindPose); + skelQuery, + skinningQuery, + skinningJoints, + skinnedPrim, + _GetArgs(), + context, + bindPose); } } } } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/strokeWriter.cpp b/lib/usd/translators/strokeWriter.cpp index 2c53156b3e..1b2f5b0b85 100644 --- a/lib/usd/translators/strokeWriter.cpp +++ b/lib/usd/translators/strokeWriter.cpp @@ -15,19 +15,13 @@ // #include "strokeWriter.h" -#include -#include -#include -#include -#include -#include -#include +#include -#include #include #include #include #include +#include #include #include #include @@ -35,24 +29,29 @@ #include #include -#include +#include +#include +#include +#include +#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_REGISTER_WRITER(stroke, PxrUsdTranslators_StrokeWriter); PxrUsdTranslators_StrokeWriter::PxrUsdTranslators_StrokeWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx) : - UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx) + : UsdMayaPrimWriter(depNodeFn, usdPath, jobCtx) { if (!TF_VERIFY(GetDagPath().isValid())) { return; } - UsdGeomBasisCurves primSchema = - UsdGeomBasisCurves::Define(GetUsdStage(), GetUsdPath()); + UsdGeomBasisCurves primSchema = UsdGeomBasisCurves::Define(GetUsdStage(), GetUsdPath()); if (!TF_VERIFY( primSchema, "Could not define UsdGeomBasisCurves at path <%s>\n", @@ -69,31 +68,25 @@ PxrUsdTranslators_StrokeWriter::PxrUsdTranslators_StrokeWriter( } } -static -void -_CollectCurveVertexData( - const MRenderLineArray& renderLineArray, - VtIntArray& curveVertexCounts, - VtVec3fArray& curvePoints, - VtFloatArray& curveWidths, - VtVec3fArray& curveDisplayColors, - VtFloatArray& curveDisplayOpacities) +static void _CollectCurveVertexData( + const MRenderLineArray& renderLineArray, + VtIntArray& curveVertexCounts, + VtVec3fArray& curvePoints, + VtFloatArray& curveWidths, + VtVec3fArray& curveDisplayColors, + VtFloatArray& curveDisplayOpacities) { const int renderLineArrayLength = renderLineArray.length(); if (renderLineArrayLength < 0) { return; } - const unsigned int numRenderLines = - static_cast(renderLineArrayLength); + const unsigned int numRenderLines = static_cast(renderLineArrayLength); MStatus status; - for (unsigned int lineIndex = 0u; - lineIndex < numRenderLines; - ++lineIndex) { - const MRenderLine renderLine = - renderLineArray.renderLine(lineIndex, &status); + for (unsigned int lineIndex = 0u; lineIndex < numRenderLines; ++lineIndex) { + const MRenderLine renderLine = renderLineArray.renderLine(lineIndex, &status); if (status != MS::kSuccess) { // Render line arrays can be sparse, so some lines may be invalid // and should just be skipped. @@ -137,14 +130,12 @@ _CollectCurveVertexData( for (unsigned int vertIndex = 0u; vertIndex < numPoints; ++vertIndex) { const MVector& vertPoint = linePoints[vertIndex]; - curvePoints.push_back( - GfVec3f(vertPoint[0], vertPoint[1], vertPoint[2])); + curvePoints.push_back(GfVec3f(vertPoint[0], vertPoint[1], vertPoint[2])); curveWidths.push_back(static_cast(lineWidths[vertIndex])); const MVector& vertColor = lineColors[vertIndex]; - curveDisplayColors.push_back( - GfVec3f(vertColor[0], vertColor[1], vertColor[2])); + curveDisplayColors.push_back(GfVec3f(vertColor[0], vertColor[1], vertColor[2])); // Convert transparency in Maya (a vector with zero as fully opaque // and one as fully transparent) into a single float opacity for @@ -152,18 +143,15 @@ _CollectCurveVertexData( // do this by averaging together the individual components of the // Maya transparency. const MVector& vertTransparency = lineTransparencies[vertIndex]; - const float vertOpacity = static_cast( - 1.0 - ((vertTransparency[0] + - vertTransparency[1] + - vertTransparency[2]) / 3.0)); + const float vertOpacity = static_cast( + 1.0 - ((vertTransparency[0] + vertTransparency[1] + vertTransparency[2]) / 3.0)); curveDisplayOpacities.push_back(vertOpacity); } } } /* virtual */ -void -PxrUsdTranslators_StrokeWriter::Write(const UsdTimeCode& usdTime) +void PxrUsdTranslators_StrokeWriter::Write(const UsdTimeCode& usdTime) { UsdMayaPrimWriter::Write(usdTime); @@ -171,7 +159,7 @@ PxrUsdTranslators_StrokeWriter::Write(const UsdTimeCode& usdTime) return; } - MStatus status; + MStatus status; MFnPfxGeometry pfxGeomFn(GetDagPath(), &status); if (status != MS::kSuccess) { TF_RUNTIME_ERROR( @@ -239,8 +227,7 @@ PxrUsdTranslators_StrokeWriter::Write(const UsdTimeCode& usdTime) curvesSchema.CreateTypeAttr(VtValue(UsdGeomTokens->linear)); - UsdAttribute curveVertexCountsAttr = - curvesSchema.CreateCurveVertexCountsAttr(); + UsdAttribute curveVertexCountsAttr = curvesSchema.CreateCurveVertexCountsAttr(); curveVertexCountsAttr.Set(curveVertexCounts, usdTime); UsdAttribute curvePointsAttr = curvesSchema.CreatePointsAttr(); @@ -249,12 +236,12 @@ PxrUsdTranslators_StrokeWriter::Write(const UsdTimeCode& usdTime) UsdAttribute curveWidthsAttr = curvesSchema.CreateWidthsAttr(); curveWidthsAttr.Set(curveWidths, usdTime); - UsdGeomPrimvar displayColorPrimvar = - curvesSchema.CreateDisplayColorPrimvar(UsdGeomTokens->vertex); + UsdGeomPrimvar displayColorPrimvar + = curvesSchema.CreateDisplayColorPrimvar(UsdGeomTokens->vertex); displayColorPrimvar.Set(curveDisplayColors, usdTime); - UsdGeomPrimvar displayOpacityPrimvar = - curvesSchema.CreateDisplayOpacityPrimvar(UsdGeomTokens->vertex); + UsdGeomPrimvar displayOpacityPrimvar + = curvesSchema.CreateDisplayOpacityPrimvar(UsdGeomTokens->vertex); displayOpacityPrimvar.Set(curveDisplayOpacities, usdTime); mainLines.deleteArray(); @@ -262,5 +249,4 @@ PxrUsdTranslators_StrokeWriter::Write(const UsdTimeCode& usdTime) flowerLines.deleteArray(); } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/translators/strokeWriter.h b/lib/usd/translators/strokeWriter.h index 490155c4da..a62c27e8ca 100644 --- a/lib/usd/translators/strokeWriter.h +++ b/lib/usd/translators/strokeWriter.h @@ -18,14 +18,14 @@ /// \file -#include +#include +#include #include #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -34,19 +34,15 @@ class PxrUsdTranslators_StrokeWriter : public UsdMayaPrimWriter { public: PxrUsdTranslators_StrokeWriter( - const MFnDependencyNode& depNodeFn, - const SdfPath& usdPath, - UsdMayaWriteJobContext& jobCtx); + const MFnDependencyNode& depNodeFn, + const SdfPath& usdPath, + UsdMayaWriteJobContext& jobCtx); void Write(const UsdTimeCode& usdTime) override; - bool ExportsGprims() const override { - return true; - } + bool ExportsGprims() const override { return true; } }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/lib/usd/translators/xformReader.cpp b/lib/usd/translators/xformReader.cpp index decb52d9a2..0dc66176e1 100644 --- a/lib/usd/translators/xformReader.cpp +++ b/lib/usd/translators/xformReader.cpp @@ -13,31 +13,26 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include +#include #include #include #include -#include -#include +#include PXR_NAMESPACE_OPEN_SCOPE PXRUSDMAYA_DEFINE_READER(UsdGeomXform, args, context) { const UsdPrim& usdPrim = args.GetUsdPrim(); - MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); + MObject parentNode = context->GetMayaNode(usdPrim.GetPath().GetParentPath(), true); MStatus status; MObject mayaNode; - return UsdMayaTranslatorUtil::CreateTransformNode(usdPrim, - parentNode, - args, - context, - &status, - &mayaNode); + return UsdMayaTranslatorUtil::CreateTransformNode( + usdPrim, parentNode, args, context, &status, &mayaNode); } PXR_NAMESPACE_CLOSE_SCOPE - diff --git a/lib/usd/ui/IMayaMQtUtil.h b/lib/usd/ui/IMayaMQtUtil.h index e59489d833..a6c7674b68 100644 --- a/lib/usd/ui/IMayaMQtUtil.h +++ b/lib/usd/ui/IMayaMQtUtil.h @@ -17,13 +17,12 @@ #ifndef MAYAUSDUI_I_MAYA_MQT_UTIL_H #define MAYAUSDUI_I_MAYA_MQT_UTIL_H - -#include - #include #include +#include + class QPixmap; namespace MAYAUSD_NS_DEF { @@ -35,17 +34,16 @@ namespace MAYAUSD_NS_DEF { class MAYAUSD_UI_PUBLIC IMayaMQtUtil { public: - virtual ~IMayaMQtUtil() {} + virtual ~IMayaMQtUtil() { } - //! Get the scaled size for Maya interface scaling. - virtual int dpiScale(int size) const = 0; - virtual float dpiScale(float size) const = 0; + //! Get the scaled size for Maya interface scaling. + virtual int dpiScale(int size) const = 0; + virtual float dpiScale(float size) const = 0; - //! Loads the a pixmap for the given resource name. - virtual QPixmap* createPixmap(const std::string& imageName) const = 0; + //! Loads the a pixmap for the given resource name. + virtual QPixmap* createPixmap(const std::string& imageName) const = 0; }; -} // namespace MayaUsd - +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/usd/ui/IUSDImportView.h b/lib/usd/ui/IUSDImportView.h index 5148663dac..7b56c9625f 100644 --- a/lib/usd/ui/IUSDImportView.h +++ b/lib/usd/ui/IUSDImportView.h @@ -17,12 +17,11 @@ #ifndef MAYAUSDUI_I_USD_IMPORT_VIEW_H #define MAYAUSDUI_I_USD_IMPORT_VIEW_H - -#include - #include #include +#include + #include PXR_NAMESPACE_USING_DIRECTIVE @@ -35,34 +34,33 @@ namespace MAYAUSD_NS_DEF { class MAYAUSD_UI_PUBLIC IUSDImportView { public: - /** - * \brief Destructor. - */ - virtual ~IUSDImportView() = 0; + /** + * \brief Destructor. + */ + virtual ~IUSDImportView() = 0; - //! \return The filename associated with this import view. - virtual const std::string& filename() const = 0; + //! \return The filename associated with this import view. + virtual const std::string& filename() const = 0; - //! \return The root prim of the stage to use for import. - virtual const std::string& rootPrimPath() const = 0; + //! \return The root prim of the stage to use for import. + virtual const std::string& rootPrimPath() const = 0; - //! \return The USD population mask of the stage to use for import. - virtual UsdStagePopulationMask stagePopulationMask() const = 0; + //! \return The USD population mask of the stage to use for import. + virtual UsdStagePopulationMask stagePopulationMask() const = 0; - //! \return The USD initial load set of the stage to use for import. - virtual UsdStage::InitialLoadSet stageInitialLoadSet() const = 0; + //! \return The USD initial load set of the stage to use for import. + virtual UsdStage::InitialLoadSet stageInitialLoadSet() const = 0; - //! \return The USD variant selections (that were modified) to use for import. - virtual ImportData::PrimVariantSelections primVariantSelections() const = 0; + //! \return The USD variant selections (that were modified) to use for import. + virtual ImportData::PrimVariantSelections primVariantSelections() const = 0; - /** - * \brief Display the view. - * \return True if the user applied the changes, false if they canceled. - */ - virtual bool execute() = 0; + /** + * \brief Display the view. + * \return True if the user applied the changes, false if they canceled. + */ + virtual bool execute() = 0; }; -} // namespace MayaUsd - +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/usd/ui/ItemDelegate.cpp b/lib/usd/ui/ItemDelegate.cpp index 6947c9714f..f4317f16aa 100644 --- a/lib/usd/ui/ItemDelegate.cpp +++ b/lib/usd/ui/ItemDelegate.cpp @@ -15,7 +15,10 @@ // #include "ItemDelegate.h" -#include +#include + +#include +#include #include #include @@ -24,291 +27,292 @@ #include #include #include - -#include -#include - -#include - #include #include +#include + namespace MAYAUSD_NS_DEF { -QWidget* ItemDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const +QWidget* ItemDelegate::createEditor( + QWidget* parent, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { - // Check out special type role (instead of column) since it is only set then this - // prim has a variant set and variant selection. - int type = index.data(kTypeRole).toInt(); - if (type == kVariants) - { - TreeItem* treeItem = getTreeItemForIndex(index); - assert(treeItem != nullptr); - if (nullptr != treeItem) - { - // Look in the import data (from the tree model) to see if it has a prim variant selection - // matching the prim from this item. If found we send that variant selection to the editor - // so that it will set that value rather (in the combobox) rather than the one from prim. - SdfVariantSelectionMap varSelMap; - TreeModel* treeModel = qobject_cast(treeItem->model()); - if ((treeModel != nullptr) && (treeModel->importData() != nullptr)) - { - const ImportData::PrimVariantSelections& primVarSel = treeModel->importData()->primVariantSelections(); - ImportData::PrimVariantSelections::const_iterator iter = primVarSel.find(treeItem->prim().GetPath()); - if (iter != std::end(primVarSel)) - { - varSelMap = iter->second; - } - } - - VariantsEditorWidget* editor = new VariantsEditorWidget(parent, this, treeItem->prim(), varSelMap); - if (!varSelMap.empty()) - { - setModelData(editor, treeItem->model(), treeItem->model()->indexFromItem(treeItem)); - } - return editor; - } - } - - return ParentClass::createEditor(parent, option, index); + // Check out special type role (instead of column) since it is only set then this + // prim has a variant set and variant selection. + int type = index.data(kTypeRole).toInt(); + if (type == kVariants) { + TreeItem* treeItem = getTreeItemForIndex(index); + assert(treeItem != nullptr); + if (nullptr != treeItem) { + // Look in the import data (from the tree model) to see if it has a prim variant + // selection matching the prim from this item. If found we send that variant selection + // to the editor so that it will set that value rather (in the combobox) rather than the + // one from prim. + SdfVariantSelectionMap varSelMap; + TreeModel* treeModel = qobject_cast(treeItem->model()); + if ((treeModel != nullptr) && (treeModel->importData() != nullptr)) { + const ImportData::PrimVariantSelections& primVarSel + = treeModel->importData()->primVariantSelections(); + ImportData::PrimVariantSelections::const_iterator iter + = primVarSel.find(treeItem->prim().GetPath()); + if (iter != std::end(primVarSel)) { + varSelMap = iter->second; + } + } + + VariantsEditorWidget* editor + = new VariantsEditorWidget(parent, this, treeItem->prim(), varSelMap); + if (!varSelMap.empty()) { + setModelData(editor, treeItem->model(), treeItem->model()->indexFromItem(treeItem)); + } + return editor; + } + } + + return ParentClass::createEditor(parent, option, index); } -void ItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const +void ItemDelegate::paint( + QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { - // Draw gridlines - doesn't work correctly as it sometimes draws lines in the middle of cells! -// painter->save(); -// painter->setPen(QColor(60, 60, 60)/*option.palette.color(QPalette::Base)*/); -// painter->drawRect(QRect(0, option.rect.y(), option.rect.right(), option.rect.bottom())); -// painter->restore(); + // Draw gridlines - doesn't work correctly as it sometimes draws lines in the middle of cells! + // painter->save(); + // painter->setPen(QColor(60, 60, 60)/*option.palette.color(QPalette::Base)*/); + // painter->drawRect(QRect(0, option.rect.y(), option.rect.right(), option.rect.bottom())); + // painter->restore(); - ParentClass::paint(painter, option, index); + ParentClass::paint(painter, option, index); } void ItemDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { - int type = index.data(kTypeRole).toInt(); - if (type == kVariants) - { - VariantsEditorWidget* widget = static_cast(editor); - widget->blockSignals(true); - // We don't bother getting the kVariantNameRole and setting it in the widget - // as it will never change once initially set. - QVariant varSel = index.data(kVariantSelectionRole); - if (varSel.isValid() && varSel.canConvert()) - { - widget->setVariantSelections(varSel.toStringList()); - } - widget->blockSignals(false); - } - ParentClass::setEditorData(editor, index); + int type = index.data(kTypeRole).toInt(); + if (type == kVariants) { + VariantsEditorWidget* widget = static_cast(editor); + widget->blockSignals(true); + // We don't bother getting the kVariantNameRole and setting it in the widget + // as it will never change once initially set. + QVariant varSel = index.data(kVariantSelectionRole); + if (varSel.isValid() && varSel.canConvert()) { + widget->setVariantSelections(varSel.toStringList()); + } + widget->blockSignals(false); + } + ParentClass::setEditorData(editor, index); } -void ItemDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const +void ItemDelegate::setModelData( + QWidget* editor, + QAbstractItemModel* model, + const QModelIndex& index) const { - int type = index.data(kTypeRole).toInt(); - if (type == kVariants) - { - VariantsEditorWidget* widget = static_cast(editor); - model->setData(index, widget->sizeHint(), Qt::SizeHintRole); - model->setData(index, widget->variantNames(), kVariantNameRole); - model->setData(index, widget->variantSelections(), kVariantSelectionRole); - - TreeItem* treeItem = getTreeItemForIndex(index); - assert(treeItem != nullptr); - if (nullptr != treeItem) - { - treeItem->setVariantSelectionModified(); - Q_EMIT variantModified(); - } - } - - ParentClass::setModelData(editor, model, index); + int type = index.data(kTypeRole).toInt(); + if (type == kVariants) { + VariantsEditorWidget* widget = static_cast(editor); + model->setData(index, widget->sizeHint(), Qt::SizeHintRole); + model->setData(index, widget->variantNames(), kVariantNameRole); + model->setData(index, widget->variantSelections(), kVariantSelectionRole); + + TreeItem* treeItem = getTreeItemForIndex(index); + assert(treeItem != nullptr); + if (nullptr != treeItem) { + treeItem->setVariantSelectionModified(); + Q_EMIT variantModified(); + } + } + + ParentClass::setModelData(editor, model, index); } QSize ItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { - int type = index.data(kTypeRole).toInt(); - if (type == kVariants) - { - QSize s = index.data(Qt::SizeHintRole).toSize(); - return s.isValid() ? s : ParentClass::sizeHint(option, index); - } - - return ParentClass::sizeHint(option, index); + int type = index.data(kTypeRole).toInt(); + if (type == kVariants) { + QSize s = index.data(Qt::SizeHintRole).toSize(); + return s.isValid() ? s : ParentClass::sizeHint(option, index); + } + + return ParentClass::sizeHint(option, index); } -void ItemDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& index) const +void ItemDelegate::updateEditorGeometry( + QWidget* editor, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { - int type = index.data(kTypeRole).toInt(); - if (type == kVariants) - { - editor->setGeometry(option.rect); - } - else - { - ParentClass::updateEditorGeometry(editor, option, index); - } + int type = index.data(kTypeRole).toInt(); + if (type == kVariants) { + editor->setGeometry(option.rect); + } else { + ParentClass::updateEditorGeometry(editor, option, index); + } } TreeItem* ItemDelegate::getTreeItemForIndex(const QModelIndex& index) const { - // Do we have an item directly from our tree model? - const TreeModel* treeModel = qobject_cast(index.model()); - if (nullptr != treeModel) - { - TreeItem* item = static_cast(treeModel->itemFromIndex(index)); - return item; - } - - // If the item is not directly from the tree model, then it should be from - // the proxy model. - const QSortFilterProxyModel* proxyModel = qobject_cast(index.model()); - if (proxyModel != nullptr) - { - treeModel = qobject_cast(proxyModel->sourceModel()); - if (treeModel != nullptr) - { - TreeItem* item = static_cast(treeModel->itemFromIndex(proxyModel->mapToSource(index))); - return item; - } - } - - return nullptr; + // Do we have an item directly from our tree model? + const TreeModel* treeModel = qobject_cast(index.model()); + if (nullptr != treeModel) { + TreeItem* item = static_cast(treeModel->itemFromIndex(index)); + return item; + } + + // If the item is not directly from the tree model, then it should be from + // the proxy model. + const QSortFilterProxyModel* proxyModel + = qobject_cast(index.model()); + if (proxyModel != nullptr) { + treeModel = qobject_cast(proxyModel->sourceModel()); + if (treeModel != nullptr) { + TreeItem* item + = static_cast(treeModel->itemFromIndex(proxyModel->mapToSource(index))); + return item; + } + } + + return nullptr; } void ItemDelegate::commitVariantSelection(VariantsEditorWidget* editor) { - Q_EMIT commitData(editor); + Q_EMIT commitData(editor); } //------------------------------------------------------------------------------ // VariantsEditorWidget //------------------------------------------------------------------------------ -VariantsEditorWidget::VariantsEditorWidget(QWidget* parent, const ItemDelegate* itemDelegate, const UsdPrim& prim, const SdfVariantSelectionMap& varSelMap) - : QWidget(parent) +VariantsEditorWidget::VariantsEditorWidget( + QWidget* parent, + const ItemDelegate* itemDelegate, + const UsdPrim& prim, + const SdfVariantSelectionMap& varSelMap) + : QWidget(parent) { - assert(prim.HasVariantSets()); - UsdVariantSets varSets = prim.GetVariantSets(); - - // We can have multiple variant selections (meaning multiple combo boxes). - // So we need a vertical layout for them. - QVBoxLayout* layout = new QVBoxLayout; - layout->setContentsMargins(0,1,0,1); - layout->setSpacing(2); - - // Note: the variant set names are returned in reverse order. - std::vector usdVarSetNames; - varSets.GetNames(&usdVarSetNames); - for (auto it=usdVarSetNames.crbegin(); it != usdVarSetNames.crend(); it++) - { - UsdVariantSet varSet1 = varSets.GetVariantSet(*it); - - // The names list will contain the variant selection, followed by all - // the variant names. - QStringList qtVarNames; - - // Check to see if the input variant selection map contains this variant. - // If yes, then we use the selection from the map, rather than the prim. - SdfVariantSelectionMap::const_iterator iter = varSelMap.find(varSet1.GetName()); - if (iter != std::end(varSelMap)) - { - qtVarNames.push_back(QString::fromStdString(iter->second)); - } - else - { - qtVarNames.push_back(QString::fromStdString(varSet1.GetVariantSelection())); - } - - // Set the tree item with the data needed to fill the combo box. - const auto usdVarNames = varSet1.GetVariantNames(); - for (const auto& vn : usdVarNames) - { - qtVarNames.push_back(vn.c_str()); - } - - QString qtVarName = QString::fromStdString(varSet1.GetName()); - QLayout* varSetLayout = createVariantSet(itemDelegate, qtVarName, qtVarNames); - layout->addLayout(varSetLayout); - } - - setLayout(layout); + assert(prim.HasVariantSets()); + UsdVariantSets varSets = prim.GetVariantSets(); + + // We can have multiple variant selections (meaning multiple combo boxes). + // So we need a vertical layout for them. + QVBoxLayout* layout = new QVBoxLayout; + layout->setContentsMargins(0, 1, 0, 1); + layout->setSpacing(2); + + // Note: the variant set names are returned in reverse order. + std::vector usdVarSetNames; + varSets.GetNames(&usdVarSetNames); + for (auto it = usdVarSetNames.crbegin(); it != usdVarSetNames.crend(); it++) { + UsdVariantSet varSet1 = varSets.GetVariantSet(*it); + + // The names list will contain the variant selection, followed by all + // the variant names. + QStringList qtVarNames; + + // Check to see if the input variant selection map contains this variant. + // If yes, then we use the selection from the map, rather than the prim. + SdfVariantSelectionMap::const_iterator iter = varSelMap.find(varSet1.GetName()); + if (iter != std::end(varSelMap)) { + qtVarNames.push_back(QString::fromStdString(iter->second)); + } else { + qtVarNames.push_back(QString::fromStdString(varSet1.GetVariantSelection())); + } + + // Set the tree item with the data needed to fill the combo box. + const auto usdVarNames = varSet1.GetVariantNames(); + for (const auto& vn : usdVarNames) { + qtVarNames.push_back(vn.c_str()); + } + + QString qtVarName = QString::fromStdString(varSet1.GetName()); + QLayout* varSetLayout = createVariantSet(itemDelegate, qtVarName, qtVarNames); + layout->addLayout(varSetLayout); + } + + setLayout(layout); } -QLayout* VariantsEditorWidget::createVariantSet(const ItemDelegate* itemDelegate, const QString& varName, QStringList& varNames) +QLayout* VariantsEditorWidget::createVariantSet( + const ItemDelegate* itemDelegate, + const QString& varName, + QStringList& varNames) { - // We'll display the variant set and variant selection on a single row. - QHBoxLayout* layout = new QHBoxLayout; - layout->setContentsMargins(0,0,0,0); + // We'll display the variant set and variant selection on a single row. + QHBoxLayout* layout = new QHBoxLayout; + layout->setContentsMargins(0, 0, 0, 0); - QLabel* lbl = new QLabel(varName); - layout->addWidget(lbl); - fVariantLabels.append(lbl); + QLabel* lbl = new QLabel(varName); + layout->addWidget(lbl); + fVariantLabels.append(lbl); - QString varSel = varNames.takeFirst(); - QComboBox* cb = new QComboBox; + QString varSel = varNames.takeFirst(); + QComboBox* cb = new QComboBox; - ItemDelegate* id = const_cast(itemDelegate); + ItemDelegate* id = const_cast(itemDelegate); #if QT_VERSION >= QT_VERSION_CHECK(5, 7, 0) - connect(cb, QOverload::of(&QComboBox::activated), - id, [this, id]{ id->commitVariantSelection(this); } ); + connect(cb, QOverload::of(&QComboBox::activated), id, [this, id] { + id->commitVariantSelection(this); + }); #else - connect(cb, static_cast(&QComboBox::activated), - id, [this, id]{ id->commitVariantSelection(this); } ); + connect( + cb, + static_cast(&QComboBox::activated), + id, + [this, id] { id->commitVariantSelection(this); }); #endif - cb->addItems(varNames); - cb->setCurrentText(varSel); - cb->setFocusPolicy( Qt::StrongFocus ); - cb->installEventFilter(this); + cb->addItems(varNames); + cb->setCurrentText(varSel); + cb->setFocusPolicy(Qt::StrongFocus); + cb->installEventFilter(this); - layout->addWidget(cb); - fVariantCombos.append(cb); + layout->addWidget(cb); + fVariantCombos.append(cb); - return layout; + return layout; } QStringList VariantsEditorWidget::variantNames() const { - QStringList names; - for (auto lbl : fVariantLabels) - { - names.append(lbl->text()); - } - return names; + QStringList names; + for (auto lbl : fVariantLabels) { + names.append(lbl->text()); + } + return names; } QStringList VariantsEditorWidget::variantSelections() const { - QStringList sels; - for (auto cb : fVariantCombos) - { - sels.append(cb->currentText()); - } - return sels; + QStringList sels; + for (auto cb : fVariantCombos) { + sels.append(cb->currentText()); + } + return sels; } void VariantsEditorWidget::setVariantSelections(const QStringList& varSel) { - assert(varSel.count() == fVariantCombos.count()); - if (varSel.count() != fVariantCombos.count()) return; + assert(varSel.count() == fVariantCombos.count()); + if (varSel.count() != fVariantCombos.count()) + return; - for (int i=0; isetCurrentText(varSel.at(i)); - } + for (int i = 0; i < varSel.count(); ++i) { + fVariantCombos.at(i)->setCurrentText(varSel.at(i)); + } } -bool VariantsEditorWidget::eventFilter( QObject * o, QEvent * e ) +bool VariantsEditorWidget::eventFilter(QObject* o, QEvent* e) { - // Block wheel event scrolling when just hovering over the variants - if ( e->type() == QEvent::Wheel && qobject_cast( o ) ) - { - e->ignore(); - return true; - } - - return QWidget::eventFilter( o, e ); + // Block wheel event scrolling when just hovering over the variants + if (e->type() == QEvent::Wheel && qobject_cast(o)) { + e->ignore(); + return true; + } + + return QWidget::eventFilter(o, e); } -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/usd/ui/ItemDelegate.h b/lib/usd/ui/ItemDelegate.h index 8d9c44a6ec..05e61d494e 100644 --- a/lib/usd/ui/ItemDelegate.h +++ b/lib/usd/ui/ItemDelegate.h @@ -17,16 +17,14 @@ #ifndef MAYAUSDUI_ITEM_DELEGATE_H #define MAYAUSDUI_ITEM_DELEGATE_H - -#include -#include -#include +#include #include #include -#include - +#include +#include +#include #include class QLabel; @@ -44,82 +42,90 @@ class VariantsEditorWidget; */ class MAYAUSD_UI_PUBLIC ItemDelegate : public QStyledItemDelegate { - Q_OBJECT + Q_OBJECT public: - using ParentClass = QStyledItemDelegate; - - using QStyledItemDelegate::QStyledItemDelegate; - - enum DELEGATE_TYPE - { - kNone, - kVariants, - }; - - enum Roles { - // The type role is used to distinguish what type of delegate item we are dealing - // with. It should be set with one of the DELEGATE_TYPE from above. - kTypeRole = Qt::UserRole + 1, - - // The variant name role is used to hold the current variant names (from the - // qt labels in the editor widget). - // Data = QStringList of variant names. - kVariantNameRole = Qt::UserRole + 2, - - // The variant selection role is used to hold the current variant selections - // (from the qt comboboxes in the editor widget). - // Data = QStringList of variant selections. - kVariantSelectionRole = Qt::UserRole + 3 - }; - - // QStyledItemDelegate overrides - QWidget* createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const override; - void paint(QPainter*, const QStyleOptionViewItem&, const QModelIndex&) const override; - void setEditorData(QWidget*, const QModelIndex&) const override; - void setModelData(QWidget*, QAbstractItemModel*, const QModelIndex&) const override; - QSize sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const override; - void updateEditorGeometry(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const override; + using ParentClass = QStyledItemDelegate; + + using QStyledItemDelegate::QStyledItemDelegate; + + enum DELEGATE_TYPE + { + kNone, + kVariants, + }; + + enum Roles + { + // The type role is used to distinguish what type of delegate item we are dealing + // with. It should be set with one of the DELEGATE_TYPE from above. + kTypeRole = Qt::UserRole + 1, + + // The variant name role is used to hold the current variant names (from the + // qt labels in the editor widget). + // Data = QStringList of variant names. + kVariantNameRole = Qt::UserRole + 2, + + // The variant selection role is used to hold the current variant selections + // (from the qt comboboxes in the editor widget). + // Data = QStringList of variant selections. + kVariantSelectionRole = Qt::UserRole + 3 + }; + + // QStyledItemDelegate overrides + QWidget* createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const override; + void paint(QPainter*, const QStyleOptionViewItem&, const QModelIndex&) const override; + void setEditorData(QWidget*, const QModelIndex&) const override; + void setModelData(QWidget*, QAbstractItemModel*, const QModelIndex&) const override; + QSize sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const override; + void + updateEditorGeometry(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const override; Q_SIGNALS: - void variantModified() const; + void variantModified() const; public Q_SLOTS: - void commitVariantSelection(VariantsEditorWidget* editor); + void commitVariantSelection(VariantsEditorWidget* editor); private: - TreeItem* getTreeItemForIndex(const QModelIndex& index) const; + TreeItem* getTreeItemForIndex(const QModelIndex& index) const; }; // ItemDelegate /** * \brief Widget that will contain all the variants for a prim. */ -class VariantsEditorWidget: public QWidget +class VariantsEditorWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - VariantsEditorWidget(QWidget* parent, const ItemDelegate* itemDelegate, const UsdPrim& prim, const SdfVariantSelectionMap& varSelMap); + VariantsEditorWidget( + QWidget* parent, + const ItemDelegate* itemDelegate, + const UsdPrim& prim, + const SdfVariantSelectionMap& varSelMap); - QStringList variantNames() const; + QStringList variantNames() const; - QStringList variantSelections() const; - void setVariantSelections(const QStringList& varSel); + QStringList variantSelections() const; + void setVariantSelections(const QStringList& varSel); protected: - bool eventFilter(QObject *obj, QEvent *ev) override; + bool eventFilter(QObject* obj, QEvent* ev) override; private: - QLayout* createVariantSet(const ItemDelegate* itemDelegate, const QString& varName, QStringList& varNames); + QLayout* createVariantSet( + const ItemDelegate* itemDelegate, + const QString& varName, + QStringList& varNames); private: - QList fVariantLabels; - QList fVariantCombos; + QList fVariantLabels; + QList fVariantCombos; }; // VariantsEditorWidget -} // namespace MayaUsd - +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/usd/ui/TreeItem.cpp b/lib/usd/ui/TreeItem.cpp index 78a5aa1747..ee09c911cd 100644 --- a/lib/usd/ui/TreeItem.cpp +++ b/lib/usd/ui/TreeItem.cpp @@ -15,13 +15,13 @@ // #include "TreeItem.h" -#include - #include -#include -#include #include +#include +#include + +#include namespace MAYAUSD_NS_DEF { @@ -31,107 +31,82 @@ QPixmap* TreeItem::fsCheckBoxOff = nullptr; QPixmap* TreeItem::fsCheckBoxOffDisabled = nullptr; TreeItem::TreeItem(const UsdPrim& prim, Type t) noexcept - : ParentClass() - , fPrim(prim) - , fType(t) - , fCheckState(CheckState::kChecked_Disabled) - , fVariantSelectionModified(false) + : ParentClass() + , fPrim(prim) + , fType(t) + , fCheckState(CheckState::kChecked_Disabled) + , fVariantSelectionModified(false) { - initializeItem(); + initializeItem(); } -UsdPrim TreeItem::prim() const -{ - return fPrim; -} +UsdPrim TreeItem::prim() const { return fPrim; } -int TreeItem::type() const -{ - return ParentClass::ItemType::UserType; -} +int TreeItem::type() const { return ParentClass::ItemType::UserType; } const QPixmap& TreeItem::checkImage() const { - if (fsCheckBoxOn == nullptr) - { - const TreeModel* treeModel = qobject_cast(model()); - if (treeModel != nullptr) - { - fsCheckBoxOn = treeModel->mayaQtUtil().createPixmap("checkboxOn.png"); - fsCheckBoxOnDisabled = treeModel->mayaQtUtil().createPixmap("checkboxOnDisabled.png"); - fsCheckBoxOff = treeModel->mayaQtUtil().createPixmap("checkboxOff.png"); - fsCheckBoxOffDisabled = treeModel->mayaQtUtil().createPixmap("checkboxOffDisabled.png"); - } - else - { - // The tree model should never be null, but we can recover here if it is. - TF_RUNTIME_ERROR("Unexpected null tree model"); - fsCheckBoxOn = new QPixmap(":/checkboxOn.png"); - fsCheckBoxOnDisabled = new QPixmap(":/checkboxOnDisabled.png"); - fsCheckBoxOff = new QPixmap(":/checkboxOff.png"); - fsCheckBoxOffDisabled = new QPixmap(":/checkboxOffDisabled.png"); - } - } + if (fsCheckBoxOn == nullptr) { + const TreeModel* treeModel = qobject_cast(model()); + if (treeModel != nullptr) { + fsCheckBoxOn = treeModel->mayaQtUtil().createPixmap("checkboxOn.png"); + fsCheckBoxOnDisabled = treeModel->mayaQtUtil().createPixmap("checkboxOnDisabled.png"); + fsCheckBoxOff = treeModel->mayaQtUtil().createPixmap("checkboxOff.png"); + fsCheckBoxOffDisabled = treeModel->mayaQtUtil().createPixmap("checkboxOffDisabled.png"); + } else { + // The tree model should never be null, but we can recover here if it is. + TF_RUNTIME_ERROR("Unexpected null tree model"); + fsCheckBoxOn = new QPixmap(":/checkboxOn.png"); + fsCheckBoxOnDisabled = new QPixmap(":/checkboxOnDisabled.png"); + fsCheckBoxOff = new QPixmap(":/checkboxOff.png"); + fsCheckBoxOffDisabled = new QPixmap(":/checkboxOffDisabled.png"); + } + } - switch (fCheckState) - { - case CheckState::kChecked: - return *fsCheckBoxOn; - case CheckState::kChecked_Disabled: - return *fsCheckBoxOnDisabled; - case CheckState::kUnchecked: - return *fsCheckBoxOff; - case CheckState::kUnchecked_Disabled: - return *fsCheckBoxOffDisabled; - default: - return *fsCheckBoxOffDisabled; - } + switch (fCheckState) { + case CheckState::kChecked: return *fsCheckBoxOn; + case CheckState::kChecked_Disabled: return *fsCheckBoxOnDisabled; + case CheckState::kUnchecked: return *fsCheckBoxOff; + case CheckState::kUnchecked_Disabled: return *fsCheckBoxOffDisabled; + default: return *fsCheckBoxOffDisabled; + } } void TreeItem::setCheckState(TreeItem::CheckState st) { - assert(fType == Type::kLoad); - if (fType == Type::kLoad) - fCheckState = st; + assert(fType == Type::kLoad); + if (fType == Type::kLoad) + fCheckState = st; } void TreeItem::setVariantSelectionModified() { - assert(fType == Type::kVariants); - if (fType == Type::kVariants) - fVariantSelectionModified = true; + assert(fType == Type::kVariants); + if (fType == Type::kVariants) + fVariantSelectionModified = true; } void TreeItem::initializeItem() { - switch (fType) - { - case Type::kLoad: - fCheckState = CheckState::kChecked_Disabled; - break; - case Type::kName: - if (fPrim.IsPseudoRoot()) - setText("Root"); - else - setText(QString::fromStdString(fPrim.GetName().GetString())); - break; - case Type::kType: - setText(QString::fromStdString(fPrim.GetTypeName().GetString())); - break; - case Type::kVariants: - { - if (fPrim.HasVariantSets()) - { - // We set a special role flag when this prim has variant sets. - // So we know when to create the label and combo box(es) for the variant - // sets and to override the drawing in the styled item delegate. - setData(ItemDelegate::kVariants, ItemDelegate::kTypeRole); - } - } - break; - default: - break; - } + switch (fType) { + case Type::kLoad: fCheckState = CheckState::kChecked_Disabled; break; + case Type::kName: + if (fPrim.IsPseudoRoot()) + setText("Root"); + else + setText(QString::fromStdString(fPrim.GetName().GetString())); + break; + case Type::kType: setText(QString::fromStdString(fPrim.GetTypeName().GetString())); break; + case Type::kVariants: { + if (fPrim.HasVariantSets()) { + // We set a special role flag when this prim has variant sets. + // So we know when to create the label and combo box(es) for the variant + // sets and to override the drawing in the styled item delegate. + setData(ItemDelegate::kVariants, ItemDelegate::kTypeRole); + } + } break; + default: break; + } } -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/usd/ui/TreeItem.h b/lib/usd/ui/TreeItem.h index 0780331861..fb1fd6a768 100644 --- a/lib/usd/ui/TreeItem.h +++ b/lib/usd/ui/TreeItem.h @@ -17,14 +17,12 @@ #ifndef MAYAUSDUI_TREE_ITEM_H #define MAYAUSDUI_TREE_ITEM_H - -#include -#include +#include #include -#include - +#include +#include #include PXR_NAMESPACE_USING_DIRECTIVE @@ -33,99 +31,98 @@ namespace MAYAUSD_NS_DEF { /** * \brief Item representing a node used to build a Qt TreeModel. - * \remarks This item is intended to hold references to USD Prims in the future, so additional information can be - * displayed to the User when interacting with Tree content. + * \remarks This item is intended to hold references to USD Prims in the future, so additional + * information can be displayed to the User when interacting with Tree content. */ class MAYAUSD_UI_PUBLIC TreeItem : public QStandardItem { public: - using ParentClass = QStandardItem; - - enum class Type - { - kLoad, - kName, - kType, - kVariants - }; - - enum class CheckState - { - kChecked, - kChecked_Disabled, - kUnchecked, - kUnchecked_Disabled - }; - - /** - * \brief Constructor. - * \param prim The USD Prim to represent with this item. - * \param text Column text to display on the View of the the Qt TreeModel. - */ - explicit TreeItem(const UsdPrim& prim, Type t) noexcept; - - /** - * \brief Destructor. - */ - virtual ~TreeItem() = default; - - /** - * \brief Return the USD Prim that is represented by the item. - * \return The USD Prim that is represented by the item. - */ - UsdPrim prim() const; - - /** - * \brief Return a flag indicating the type of the item. - * \remarks This is used by Qt to distinguish custom items from the base class. - * \return A flag indicating that the type is a custom item, different from the base class. - */ - int type() const override; - - //! Returns the check state of this tree item. - //! Only valid for kLoad type. - TreeItem::CheckState checkState() const { return fCheckState; } - const QPixmap& checkImage() const; - - //! Sets the checkstate of this tree item. - //! Only valid for kLoad type. - void setCheckState(TreeItem::CheckState st); - - //! Returns true if the variant selection for this item was modified. - //! Only valid for kVariants type. - bool variantSelectionModified() const { return fVariantSelectionModified; } - - //! Special flag set when the variant selection (of this item) is modified. - //! Only valid for kVariants type. - void setVariantSelectionModified(); - - //! Reset the flag that is set to track if the variant selection has been modified. - //! Only valid for kVariants type. - void resetVariantSelectionModified() { fVariantSelectionModified = false; } + using ParentClass = QStandardItem; + + enum class Type + { + kLoad, + kName, + kType, + kVariants + }; + + enum class CheckState + { + kChecked, + kChecked_Disabled, + kUnchecked, + kUnchecked_Disabled + }; + + /** + * \brief Constructor. + * \param prim The USD Prim to represent with this item. + * \param text Column text to display on the View of the the Qt TreeModel. + */ + explicit TreeItem(const UsdPrim& prim, Type t) noexcept; + + /** + * \brief Destructor. + */ + virtual ~TreeItem() = default; + + /** + * \brief Return the USD Prim that is represented by the item. + * \return The USD Prim that is represented by the item. + */ + UsdPrim prim() const; + + /** + * \brief Return a flag indicating the type of the item. + * \remarks This is used by Qt to distinguish custom items from the base class. + * \return A flag indicating that the type is a custom item, different from the base class. + */ + int type() const override; + + //! Returns the check state of this tree item. + //! Only valid for kLoad type. + TreeItem::CheckState checkState() const { return fCheckState; } + const QPixmap& checkImage() const; + + //! Sets the checkstate of this tree item. + //! Only valid for kLoad type. + void setCheckState(TreeItem::CheckState st); + + //! Returns true if the variant selection for this item was modified. + //! Only valid for kVariants type. + bool variantSelectionModified() const { return fVariantSelectionModified; } + + //! Special flag set when the variant selection (of this item) is modified. + //! Only valid for kVariants type. + void setVariantSelectionModified(); + + //! Reset the flag that is set to track if the variant selection has been modified. + //! Only valid for kVariants type. + void resetVariantSelectionModified() { fVariantSelectionModified = false; } private: - void initializeItem(); + void initializeItem(); protected: - // The USD Prim that the item represents in the TreeModel. - UsdPrim fPrim; + // The USD Prim that the item represents in the TreeModel. + UsdPrim fPrim; - // The type of this item. - Type fType; + // The type of this item. + Type fType; - // For the LOAD column, the check state. - CheckState fCheckState; + // For the LOAD column, the check state. + CheckState fCheckState; - // Special flag set when the variant selection was modified. - bool fVariantSelectionModified; + // Special flag set when the variant selection was modified. + bool fVariantSelectionModified; - static QPixmap* fsCheckBoxOn; - static QPixmap* fsCheckBoxOnDisabled; - static QPixmap* fsCheckBoxOff; - static QPixmap* fsCheckBoxOffDisabled; + static QPixmap* fsCheckBoxOn; + static QPixmap* fsCheckBoxOnDisabled; + static QPixmap* fsCheckBoxOff; + static QPixmap* fsCheckBoxOffDisabled; }; -} // namespace MayaUsd - +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/usd/ui/TreeModel.cpp b/lib/usd/ui/TreeModel.cpp index c2951bb089..416c87c650 100644 --- a/lib/usd/ui/TreeModel.cpp +++ b/lib/usd/ui/TreeModel.cpp @@ -15,386 +15,360 @@ // #include "TreeModel.h" -#include - -#include -#include - #include -#include -#include +#include +#include #include +#include +#include + +#include namespace MAYAUSD_NS_DEF { namespace { -TreeItem* findTreeItem(TreeModel* treeModel, const QModelIndex& parent, std::functionfn) +TreeItem* +findTreeItem(TreeModel* treeModel, const QModelIndex& parent, std::function fn) { - for (int r=0; rrowCount(parent); ++r) - { - // Note: only the load column (0) has children, so we use it when looking for children. - QModelIndex childIndex = treeModel->index(r, TreeModel::kTreeColumn_Load, parent); - TreeItem* item = static_cast(treeModel->itemFromIndex(childIndex)); - if (fn(item)) - { - return item; - } - // If this item is check-enabled, we don't need to check it's children because - // we know they will be check-disabled. - else if (treeModel->hasChildren(childIndex)) - { - TreeItem* tempItem = findTreeItem(treeModel, childIndex, fn); - if (tempItem != nullptr) - return tempItem; - } - } - return nullptr; + for (int r = 0; r < treeModel->rowCount(parent); ++r) { + // Note: only the load column (0) has children, so we use it when looking for children. + QModelIndex childIndex = treeModel->index(r, TreeModel::kTreeColumn_Load, parent); + TreeItem* item = static_cast(treeModel->itemFromIndex(childIndex)); + if (fn(item)) { + return item; + } + // If this item is check-enabled, we don't need to check it's children because + // we know they will be check-disabled. + else if (treeModel->hasChildren(childIndex)) { + TreeItem* tempItem = findTreeItem(treeModel, childIndex, fn); + if (tempItem != nullptr) + return tempItem; + } + } + return nullptr; } void resetVariantToPrimSelection(TreeItem* variantItem) { - assert(variantItem); + assert(variantItem); - UsdPrim prim = variantItem->prim(); - assert(prim.IsValid() && prim.HasVariantSets()); + UsdPrim prim = variantItem->prim(); + assert(prim.IsValid() && prim.HasVariantSets()); - UsdVariantSets varSets = prim.GetVariantSets(); + UsdVariantSets varSets = prim.GetVariantSets(); - std::vector usdVarSetNames; - varSets.GetNames(&usdVarSetNames); + std::vector usdVarSetNames; + varSets.GetNames(&usdVarSetNames); - QStringList qtVarNames; - for (auto it=usdVarSetNames.crbegin(); it != usdVarSetNames.crend(); it++) - { - UsdVariantSet varSet1 = varSets.GetVariantSet(*it); - qtVarNames.push_back(QString::fromStdString(varSet1.GetVariantSelection())); - } + QStringList qtVarNames; + for (auto it = usdVarSetNames.crbegin(); it != usdVarSetNames.crend(); it++) { + UsdVariantSet varSet1 = varSets.GetVariantSet(*it); + qtVarNames.push_back(QString::fromStdString(varSet1.GetVariantSelection())); + } - variantItem->setData(qtVarNames, ItemDelegate::kVariantSelectionRole); - variantItem->resetVariantSelectionModified(); + variantItem->setData(qtVarNames, ItemDelegate::kVariantSelectionRole); + variantItem->resetVariantSelectionModified(); } void resetAllVariants(TreeModel* treeModel, const QModelIndex& parent) { - for (int r=0; rrowCount(parent); ++r) - { - QModelIndex variantIndex = treeModel->index(r, TreeModel::kTreeColumn_Variants, parent); - TreeItem* variantItem = static_cast(treeModel->itemFromIndex(variantIndex)); - - if (nullptr != variantItem && variantItem->variantSelectionModified()) - { - resetVariantToPrimSelection(variantItem); - } - - QModelIndex childIndex = treeModel->index(r, TreeModel::kTreeColumn_Load, parent); - if (treeModel->hasChildren(childIndex)) - { - resetAllVariants(treeModel, childIndex); - } - } + for (int r = 0; r < treeModel->rowCount(parent); ++r) { + QModelIndex variantIndex = treeModel->index(r, TreeModel::kTreeColumn_Variants, parent); + TreeItem* variantItem = static_cast(treeModel->itemFromIndex(variantIndex)); + + if (nullptr != variantItem && variantItem->variantSelectionModified()) { + resetVariantToPrimSelection(variantItem); + } + + QModelIndex childIndex = treeModel->index(r, TreeModel::kTreeColumn_Load, parent); + if (treeModel->hasChildren(childIndex)) { + resetAllVariants(treeModel, childIndex); + } + } } -} +} // namespace -TreeModel::TreeModel(const IMayaMQtUtil& mayaQtUtil, const ImportData* importData /*= nullptr*/, QObject* parent /*= nullptr*/) noexcept - : ParentClass{ parent } - , fImportData{ importData } - , fMayaQtUtil{ mayaQtUtil } +TreeModel::TreeModel( + const IMayaMQtUtil& mayaQtUtil, + const ImportData* importData /*= nullptr*/, + QObject* parent /*= nullptr*/) noexcept + : ParentClass { parent } + , fImportData { importData } + , fMayaQtUtil { mayaQtUtil } { } -QVariant TreeModel::data(const QModelIndex &index, int role /*= Qt::DisplayRole*/) const +QVariant TreeModel::data(const QModelIndex& index, int role /*= Qt::DisplayRole*/) const { - if (!index.isValid()) - return QVariant(); + if (!index.isValid()) + return QVariant(); - TreeItem* item = static_cast(itemFromIndex(index)); + TreeItem* item = static_cast(itemFromIndex(index)); - if ((role == Qt::DecorationRole) && (index.column() == kTreeColumn_Load)) - return item->checkImage(); + if ((role == Qt::DecorationRole) && (index.column() == kTreeColumn_Load)) + return item->checkImage(); - return ParentClass::data(index, role); + return ParentClass::data(index, role); } -Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const +Qt::ItemFlags TreeModel::flags(const QModelIndex& index) const { - if (!index.isValid()) - return 0; + if (!index.isValid()) + return 0; - // The base class implementation returns a combination of flags that enables - // the item (ItemIsEnabled) and allows it to be selected (ItemIsSelectable). - Qt::ItemFlags flags = ParentClass::flags(index); - if (index.column() == kTreeColumn_Load) - flags &= ~Qt::ItemIsSelectable; + // The base class implementation returns a combination of flags that enables + // the item (ItemIsEnabled) and allows it to be selected (ItemIsSelectable). + Qt::ItemFlags flags = ParentClass::flags(index); + if (index.column() == kTreeColumn_Load) + flags &= ~Qt::ItemIsSelectable; - return flags; + return flags; } -void TreeModel::setParentsCheckState(const QModelIndex &child, TreeItem::CheckState state) +void TreeModel::setParentsCheckState(const QModelIndex& child, TreeItem::CheckState state) { - QModelIndex parentIndex = this->parent(child); - if (parentIndex.isValid()) - { - TreeItem* item = static_cast(itemFromIndex(parentIndex)); - - // If the parent item state matches the input, no need to recurse. - const TreeItem::CheckState currState = item->checkState(); - if(currState != state) - { - item->setCheckState(state); - QVector roles; - roles << Qt::DecorationRole; - Q_EMIT dataChanged(parentIndex, parentIndex, roles); - setParentsCheckState(parentIndex, state); - } - } + QModelIndex parentIndex = this->parent(child); + if (parentIndex.isValid()) { + TreeItem* item = static_cast(itemFromIndex(parentIndex)); + + // If the parent item state matches the input, no need to recurse. + const TreeItem::CheckState currState = item->checkState(); + if (currState != state) { + item->setCheckState(state); + QVector roles; + roles << Qt::DecorationRole; + Q_EMIT dataChanged(parentIndex, parentIndex, roles); + setParentsCheckState(parentIndex, state); + } + } } -void TreeModel::setChildCheckState(const QModelIndex &parent, TreeItem::CheckState state) +void TreeModel::setChildCheckState(const QModelIndex& parent, TreeItem::CheckState state) { - int rMin = -1, rMax = -1; - for (int r=0; rindex(r, kTreeColumn_Load, parent); - TreeItem* item = static_cast(itemFromIndex(childIndex)); - - // If child item state matches the input, no need to recurse. - const TreeItem::CheckState currState = item->checkState(); - if (currState != state) - { - if (rMin == -1) rMin = r; - if (r > rMax) rMax = r; - item->setCheckState(state); - if (hasChildren(childIndex)) - setChildCheckState(childIndex, state); - } - } - QModelIndex rMinIndex = this->index(rMin, kTreeColumn_Load, parent); - QModelIndex rMaxIndex = this->index(rMax, kTreeColumn_Load, parent); - QVector roles; - roles << Qt::DecorationRole; - Q_EMIT dataChanged(rMinIndex, rMaxIndex, roles); + int rMin = -1, rMax = -1; + for (int r = 0; r < rowCount(parent); ++r) { + // Note: only the load column (0) has children, so we use it when looking for children. + QModelIndex childIndex = this->index(r, kTreeColumn_Load, parent); + TreeItem* item = static_cast(itemFromIndex(childIndex)); + + // If child item state matches the input, no need to recurse. + const TreeItem::CheckState currState = item->checkState(); + if (currState != state) { + if (rMin == -1) + rMin = r; + if (r > rMax) + rMax = r; + item->setCheckState(state); + if (hasChildren(childIndex)) + setChildCheckState(childIndex, state); + } + } + QModelIndex rMinIndex = this->index(rMin, kTreeColumn_Load, parent); + QModelIndex rMaxIndex = this->index(rMax, kTreeColumn_Load, parent); + QVector roles; + roles << Qt::DecorationRole; + Q_EMIT dataChanged(rMinIndex, rMaxIndex, roles); } void TreeModel::getRootPrimPath(std::string& rootPrimPath, const QModelIndex& parent) { - // We simply need to find the single item that is "check-enabled" as there can - // only be one. - auto fn = [](TreeItem* item) -> bool - { - if (item->checkState() == TreeItem::CheckState::kChecked) - return true; - return false; - }; - TreeItem* item = findTreeItem(this, QModelIndex(), fn); - if (item != nullptr) - rootPrimPath = item->prim().GetPath().GetString(); + // We simply need to find the single item that is "check-enabled" as there can + // only be one. + auto fn = [](TreeItem* item) -> bool { + if (item->checkState() == TreeItem::CheckState::kChecked) + return true; + return false; + }; + TreeItem* item = findTreeItem(this, QModelIndex(), fn); + if (item != nullptr) + rootPrimPath = item->prim().GetPath().GetString(); } void TreeModel::fillStagePopulationMask(UsdStagePopulationMask& popMask, const QModelIndex& parent) { - for (int r=0; rindex(r, kTreeColumn_Load, parent); - TreeItem* item = static_cast(itemFromIndex(childIndex)); - if (item->checkState() == TreeItem::CheckState::kChecked) - { - auto primPath = item->prim().GetPath(); - if (!popMask.Includes(primPath)) - popMask.Add(primPath); - return; - } - // If this item is check-enabled, we don't need to check it's children because - // we know they will be check-disabled. - else if (hasChildren(childIndex)) - { - fillStagePopulationMask(popMask, childIndex); - } - } + for (int r = 0; r < rowCount(parent); ++r) { + // Note: only the load column (0) has children, so we use it when looking for children. + QModelIndex childIndex = this->index(r, kTreeColumn_Load, parent); + TreeItem* item = static_cast(itemFromIndex(childIndex)); + if (item->checkState() == TreeItem::CheckState::kChecked) { + auto primPath = item->prim().GetPath(); + if (!popMask.Includes(primPath)) + popMask.Add(primPath); + return; + } + // If this item is check-enabled, we don't need to check it's children because + // we know they will be check-disabled. + else if (hasChildren(childIndex)) { + fillStagePopulationMask(popMask, childIndex); + } + } } -void TreeModel::fillPrimVariantSelections(ImportData::PrimVariantSelections& primVariantSelections, const QModelIndex& parent) +void TreeModel::fillPrimVariantSelections( + ImportData::PrimVariantSelections& primVariantSelections, + const QModelIndex& parent) { - for (int r=0; rindex(r, kTreeColumn_Variants, parent); - TreeItem* item = static_cast(itemFromIndex(variantIndex)); - if (item->variantSelectionModified()) - { - // Note: both the variant name and variant selection roles contain a - // QStringList for data. - QVariant varSel = variantIndex.data(ItemDelegate::kVariantSelectionRole); - if (varSel.isValid() && varSel.canConvert()) - { - // The name role must be valid if the selection role was. - QStringList varSelections = varSel.toStringList(); - QStringList varNames = variantIndex.data(ItemDelegate::kVariantNameRole).toStringList(); - assert(varSelections.count() == varNames.count()); - if (varSelections.count() == varNames.count()) - { - SdfVariantSelectionMap varSels; - for (int i=0; iprim().GetPath()] = varSels; - } - } - } - - // Note: only the load column (0) has children, so we use it when looking for children. - QModelIndex childIndex = this->index(r, kTreeColumn_Load, parent); - if (hasChildren(childIndex)) - { - fillPrimVariantSelections(primVariantSelections, childIndex); - } - } + for (int r = 0; r < rowCount(parent); ++r) { + QModelIndex variantIndex = this->index(r, kTreeColumn_Variants, parent); + TreeItem* item = static_cast(itemFromIndex(variantIndex)); + if (item->variantSelectionModified()) { + // Note: both the variant name and variant selection roles contain a + // QStringList for data. + QVariant varSel = variantIndex.data(ItemDelegate::kVariantSelectionRole); + if (varSel.isValid() && varSel.canConvert()) { + // The name role must be valid if the selection role was. + QStringList varSelections = varSel.toStringList(); + QStringList varNames + = variantIndex.data(ItemDelegate::kVariantNameRole).toStringList(); + assert(varSelections.count() == varNames.count()); + if (varSelections.count() == varNames.count()) { + SdfVariantSelectionMap varSels; + for (int i = 0; i < varNames.count(); ++i) { + varSels[varNames.at(i).toStdString()] = varSelections.at(i).toStdString(); + } + primVariantSelections[item->prim().GetPath()] = varSels; + } + } + } + + // Note: only the load column (0) has children, so we use it when looking for children. + QModelIndex childIndex = this->index(r, kTreeColumn_Load, parent); + if (hasChildren(childIndex)) { + fillPrimVariantSelections(primVariantSelections, childIndex); + } + } } void TreeModel::openPersistentEditors(QTreeView* tv, const QModelIndex& parent) { - for (int r=0; rindex(r, kTreeColumn_Variants, parent); - int type = varSelIndex.data(ItemDelegate::kTypeRole).toInt(); - if (type == ItemDelegate::kVariants) - { - QSortFilterProxyModel* proxyModel = qobject_cast(tv->model()); - tv->openPersistentEditor(proxyModel->mapFromSource(varSelIndex)); - } - - // Note: only the load column (0) has children, so we use it when looking for children. - QModelIndex childIndex = this->index(r, kTreeColumn_Load, parent); - if (hasChildren(childIndex)) - { - openPersistentEditors(tv, childIndex); - } - } + for (int r = 0; r < rowCount(parent); ++r) { + QModelIndex varSelIndex = this->index(r, kTreeColumn_Variants, parent); + int type = varSelIndex.data(ItemDelegate::kTypeRole).toInt(); + if (type == ItemDelegate::kVariants) { + QSortFilterProxyModel* proxyModel = qobject_cast(tv->model()); + tv->openPersistentEditor(proxyModel->mapFromSource(varSelIndex)); + } + + // Note: only the load column (0) has children, so we use it when looking for children. + QModelIndex childIndex = this->index(r, kTreeColumn_Load, parent); + if (hasChildren(childIndex)) { + openPersistentEditors(tv, childIndex); + } + } } void TreeModel::setRootPrimPath(const std::string& path) { - // Find the prim matching the root prim path from the import data and - // check-enable it. - SdfPath rootPrimPath(path); - auto fnFindRoot = [rootPrimPath](TreeItem* item) -> bool - { - if (item->prim().GetPath() == rootPrimPath) - return true; - return false; - }; - TreeItem* item = findTreeItem(this, QModelIndex(), fnFindRoot); - if (item != nullptr) - { - checkEnableItem(item); - } + // Find the prim matching the root prim path from the import data and + // check-enable it. + SdfPath rootPrimPath(path); + auto fnFindRoot = [rootPrimPath](TreeItem* item) -> bool { + if (item->prim().GetPath() == rootPrimPath) + return true; + return false; + }; + TreeItem* item = findTreeItem(this, QModelIndex(), fnFindRoot); + if (item != nullptr) { + checkEnableItem(item); + } } void TreeModel::uncheckEnableTree() { - // When unchecking any item we uncheck-enable the entire tree. - setChildCheckState(QModelIndex(), TreeItem::CheckState::kUnchecked); + // When unchecking any item we uncheck-enable the entire tree. + setChildCheckState(QModelIndex(), TreeItem::CheckState::kUnchecked); - updateCheckedItemCount(); + updateCheckedItemCount(); } void TreeModel::checkEnableItem(TreeItem* item) { - if (item != nullptr) - { - // All ancestors [and their descendants] become unchecked-disabled, and all descendants - // become checked-disabled. - - // First run-thru entire tree and uncheck-disable everything. - setChildCheckState(QModelIndex(), TreeItem::CheckState::kUnchecked_Disabled); - - // Then check the item that was clicked. - item->setCheckState(TreeItem::CheckState::kChecked); - QModelIndex modelIndex = indexFromItem(item); - QVector roles; - roles << Qt::DecorationRole; - Q_EMIT dataChanged(modelIndex, modelIndex, roles); - - // Then check-disable all the children of the clicked item. - setChildCheckState(modelIndex, TreeItem::CheckState::kChecked_Disabled); - - updateCheckedItemCount(); - } + if (item != nullptr) { + // All ancestors [and their descendants] become unchecked-disabled, and all descendants + // become checked-disabled. + + // First run-thru entire tree and uncheck-disable everything. + setChildCheckState(QModelIndex(), TreeItem::CheckState::kUnchecked_Disabled); + + // Then check the item that was clicked. + item->setCheckState(TreeItem::CheckState::kChecked); + QModelIndex modelIndex = indexFromItem(item); + QVector roles; + roles << Qt::DecorationRole; + Q_EMIT dataChanged(modelIndex, modelIndex, roles); + + // Then check-disable all the children of the clicked item. + setChildCheckState(modelIndex, TreeItem::CheckState::kChecked_Disabled); + + updateCheckedItemCount(); + } } void TreeModel::updateCheckedItemCount() const { - int nbChecked = 0, nbVariantsModified = 0; - countCheckedItems(QModelIndex(), nbChecked, nbVariantsModified); + int nbChecked = 0, nbVariantsModified = 0; + countCheckedItems(QModelIndex(), nbChecked, nbVariantsModified); - // When the checked items change we will count, and emit signals for, the number of - // checked items as well as the number of in-scope modified variants. - Q_EMIT checkedStateChanged(nbChecked); - Q_EMIT modifiedVariantCountChanged(nbVariantsModified); + // When the checked items change we will count, and emit signals for, the number of + // checked items as well as the number of in-scope modified variants. + Q_EMIT checkedStateChanged(nbChecked); + Q_EMIT modifiedVariantCountChanged(nbVariantsModified); } -void TreeModel::countCheckedItems(const QModelIndex &parent, int& nbChecked, int& nbVariantsModified) const +void TreeModel::countCheckedItems( + const QModelIndex& parent, + int& nbChecked, + int& nbVariantsModified) const { - for (int r=0; rindex(r, kTreeColumn_Load, parent); - item = static_cast(itemFromIndex(checkedChildIndex)); - - const TreeItem::CheckState state = item->checkState(); - if (TreeItem::CheckState::kChecked == state || - TreeItem::CheckState::kChecked_Disabled == state) - { - nbChecked++; - - // We are only counting modified variants of in-scope prims - QModelIndex variantChildIndex = this->index(r, kTreeColumn_Variants, parent); - item = static_cast(itemFromIndex(variantChildIndex)); - - if (item->variantSelectionModified()) - { - nbVariantsModified++; - } - } - - if (hasChildren(checkedChildIndex)) - countCheckedItems(checkedChildIndex, nbChecked, nbVariantsModified); - } + for (int r = 0; r < rowCount(parent); ++r) { + TreeItem* item; + + QModelIndex checkedChildIndex = this->index(r, kTreeColumn_Load, parent); + item = static_cast(itemFromIndex(checkedChildIndex)); + + const TreeItem::CheckState state = item->checkState(); + if (TreeItem::CheckState::kChecked == state + || TreeItem::CheckState::kChecked_Disabled == state) { + nbChecked++; + + // We are only counting modified variants of in-scope prims + QModelIndex variantChildIndex = this->index(r, kTreeColumn_Variants, parent); + item = static_cast(itemFromIndex(variantChildIndex)); + + if (item->variantSelectionModified()) { + nbVariantsModified++; + } + } + + if (hasChildren(checkedChildIndex)) + countCheckedItems(checkedChildIndex, nbChecked, nbVariantsModified); + } } void TreeModel::updateModifiedVariantCount() const { - int nbChecked = 0, nbVariantsModified = 0; - countCheckedItems(QModelIndex(), nbChecked, nbVariantsModified); + int nbChecked = 0, nbVariantsModified = 0; + countCheckedItems(QModelIndex(), nbChecked, nbVariantsModified); - Q_EMIT modifiedVariantCountChanged(nbVariantsModified); + Q_EMIT modifiedVariantCountChanged(nbVariantsModified); } void TreeModel::onItemClicked(TreeItem* item) { - if (item->index().column() == kTreeColumn_Load) - { - // We only allow toggling an enabled checked or unchecked item. - TreeItem::CheckState st = item->checkState(); - if (st == TreeItem::CheckState::kChecked) - { - uncheckEnableTree(); - } - else if (st == TreeItem::CheckState::kUnchecked) - { - checkEnableItem(item); - } - } + if (item->index().column() == kTreeColumn_Load) { + // We only allow toggling an enabled checked or unchecked item. + TreeItem::CheckState st = item->checkState(); + if (st == TreeItem::CheckState::kChecked) { + uncheckEnableTree(); + } else if (st == TreeItem::CheckState::kUnchecked) { + checkEnableItem(item); + } + } } -void TreeModel::resetVariants() -{ - resetAllVariants(this, QModelIndex()); -} +void TreeModel::resetVariants() { resetAllVariants(this, QModelIndex()); } -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/usd/ui/TreeModel.h b/lib/usd/ui/TreeModel.h index 8f6d9a3cb6..8358e2445a 100644 --- a/lib/usd/ui/TreeModel.h +++ b/lib/usd/ui/TreeModel.h @@ -17,16 +17,14 @@ #ifndef MAYAUSDUI_TREE_MODEL_H #define MAYAUSDUI_TREE_MODEL_H - -#include - -#include - #include #include -#include +#include + +#include #include +#include class QTreeView; @@ -43,73 +41,78 @@ class IMayaMQtUtil; */ class MAYAUSD_UI_PUBLIC TreeModel : public QStandardItemModel { - Q_OBJECT + Q_OBJECT public: - using ParentClass = QStandardItemModel; - - /** - * \brief Constructor. - * \param parent A reference to the parent of the TreeModel. - */ - explicit TreeModel(const IMayaMQtUtil& mayaQtUtil, const ImportData* importData = nullptr, QObject* parent = nullptr) noexcept; - - // QStandardItemModel overrides - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - Qt::ItemFlags flags(const QModelIndex &index) const override; - - /** - * \brief Order of the columns as they appear in the Tree. - * \remarks The order of the enumeration is important. - */ - enum TREE_COLUMNS - { - kTreeColumn_Load, // Should we load this prim? - kTreeColumn_Name, // Name of the item as it appears in the TreeView. - kTreeColumn_Type, // Type of the primitive. - kTreeColumn_Variants, // Variant Set(s) and Variant Selection of the primitive. - kTreeColumn_Last // Last element of the enum. - }; - - void setRootPrimPath(const std::string& path); - void getRootPrimPath(std::string&, const QModelIndex& parent); - void fillStagePopulationMask(UsdStagePopulationMask& popMask, const QModelIndex& parent); - void fillPrimVariantSelections(ImportData::PrimVariantSelections& primVariantSelections, const QModelIndex& parent); - void openPersistentEditors(QTreeView* tv, const QModelIndex& parent); - - const ImportData* importData() const { return fImportData; } - const IMayaMQtUtil& mayaQtUtil() const { return fMayaQtUtil; } - - void onItemClicked(TreeItem* item); - - void resetVariants(); - + using ParentClass = QStandardItemModel; + + /** + * \brief Constructor. + * \param parent A reference to the parent of the TreeModel. + */ + explicit TreeModel( + const IMayaMQtUtil& mayaQtUtil, + const ImportData* importData = nullptr, + QObject* parent = nullptr) noexcept; + + // QStandardItemModel overrides + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + + /** + * \brief Order of the columns as they appear in the Tree. + * \remarks The order of the enumeration is important. + */ + enum TREE_COLUMNS + { + kTreeColumn_Load, // Should we load this prim? + kTreeColumn_Name, // Name of the item as it appears in the TreeView. + kTreeColumn_Type, // Type of the primitive. + kTreeColumn_Variants, // Variant Set(s) and Variant Selection of the primitive. + kTreeColumn_Last // Last element of the enum. + }; + + void setRootPrimPath(const std::string& path); + void getRootPrimPath(std::string&, const QModelIndex& parent); + void fillStagePopulationMask(UsdStagePopulationMask& popMask, const QModelIndex& parent); + void fillPrimVariantSelections( + ImportData::PrimVariantSelections& primVariantSelections, + const QModelIndex& parent); + void openPersistentEditors(QTreeView* tv, const QModelIndex& parent); + + const ImportData* importData() const { return fImportData; } + const IMayaMQtUtil& mayaQtUtil() const { return fMayaQtUtil; } + + void onItemClicked(TreeItem* item); + + void resetVariants(); + private: - void uncheckEnableTree(); - void checkEnableItem(TreeItem* item); + void uncheckEnableTree(); + void checkEnableItem(TreeItem* item); - void updateCheckedItemCount() const; - void countCheckedItems(const QModelIndex &parent, int& nbChecked, int& nbVariantsModified) const; + void updateCheckedItemCount() const; + void + countCheckedItems(const QModelIndex& parent, int& nbChecked, int& nbVariantsModified) const; - void setParentsCheckState(const QModelIndex &child, TreeItem::CheckState state); - void setChildCheckState(const QModelIndex &parent, TreeItem::CheckState state); + void setParentsCheckState(const QModelIndex& child, TreeItem::CheckState state); + void setChildCheckState(const QModelIndex& parent, TreeItem::CheckState state); Q_SIGNALS: - void checkedStateChanged(int nbChecked) const; - void modifiedVariantCountChanged(int nbModified) const; + void checkedStateChanged(int nbChecked) const; + void modifiedVariantCountChanged(int nbModified) const; public Q_SLOTS: - void updateModifiedVariantCount() const; + void updateModifiedVariantCount() const; private: - // Extra import data, if any to set the initial state of dialog from. - const ImportData* fImportData; + // Extra import data, if any to set the initial state of dialog from. + const ImportData* fImportData; - // Special interface we can use to perform Maya Qt utilities (such as Pixmap loading). - const IMayaMQtUtil& fMayaQtUtil; + // Special interface we can use to perform Maya Qt utilities (such as Pixmap loading). + const IMayaMQtUtil& fMayaQtUtil; }; -} // namespace MayaUsd - +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/usd/ui/TreeModelFactory.cpp b/lib/usd/ui/TreeModelFactory.cpp index ad4b8ddd77..40258526e7 100644 --- a/lib/usd/ui/TreeModelFactory.cpp +++ b/lib/usd/ui/TreeModelFactory.cpp @@ -15,105 +15,109 @@ // #include "TreeModelFactory.h" -#include -#include -#include - #include #include - #include #include #include +#include +#include +#include + namespace MAYAUSD_NS_DEF { -// Ensure the TreeModelFactory is not constructible, as it is intended to be used only through static factory methods. +// Ensure the TreeModelFactory is not constructible, as it is intended to be used only through +// static factory methods. // -// While additional traits like std::is_copy_constructible or std::is_move_constructible could also be used, the fact -// that the Factory cannot be (traditionally) instantiated prevents other constructors and assignments operators from -// being useful. -static_assert(!std::is_constructible::value, "TreeModelFactory should not be constructible."); - +// While additional traits like std::is_copy_constructible or std::is_move_constructible could also +// be used, the fact that the Factory cannot be (traditionally) instantiated prevents other +// constructors and assignments operators from being useful. +static_assert( + !std::is_constructible::value, + "TreeModelFactory should not be constructible."); /*static*/ -std::unique_ptr TreeModelFactory::createEmptyTreeModel(const IMayaMQtUtil& mayaQtUtil, const ImportData* importData /*= nullptr*/, QObject* parent /*= nullptr*/) +std::unique_ptr TreeModelFactory::createEmptyTreeModel( + const IMayaMQtUtil& mayaQtUtil, + const ImportData* importData /*= nullptr*/, + QObject* parent /*= nullptr*/) { - std::unique_ptr treeModel(new TreeModel(mayaQtUtil, importData, parent)); - treeModel->setHorizontalHeaderLabels({ QObject::tr(""), - QObject::tr("Prim Name"), - QObject::tr("Prim Type"), - QObject::tr("Variant Set and Variant") }); - return treeModel; + std::unique_ptr treeModel(new TreeModel(mayaQtUtil, importData, parent)); + treeModel->setHorizontalHeaderLabels({ QObject::tr(""), + QObject::tr("Prim Name"), + QObject::tr("Prim Type"), + QObject::tr("Variant Set and Variant") }); + return treeModel; } /*static*/ -std::unique_ptr TreeModelFactory::createFromStage -( - const UsdStageRefPtr& stage, - const IMayaMQtUtil& mayaQtUtil, - const ImportData* importData /*= nullptr*/, - QObject* parent, int* nbItems /*= nullptr*/ +std::unique_ptr TreeModelFactory::createFromStage( + const UsdStageRefPtr& stage, + const IMayaMQtUtil& mayaQtUtil, + const ImportData* importData /*= nullptr*/, + QObject* parent, + int* nbItems /*= nullptr*/ ) { - std::unique_ptr treeModel = createEmptyTreeModel(mayaQtUtil, importData, parent); - int cnt = buildTreeHierarchy(stage->GetPseudoRoot(), treeModel->invisibleRootItem()); - if (nbItems != nullptr) - *nbItems = cnt; - return treeModel; + std::unique_ptr treeModel = createEmptyTreeModel(mayaQtUtil, importData, parent); + int cnt = buildTreeHierarchy(stage->GetPseudoRoot(), treeModel->invisibleRootItem()); + if (nbItems != nullptr) + *nbItems = cnt; + return treeModel; } /*static*/ QList TreeModelFactory::createPrimRow(const UsdPrim& prim) { - // Cache the values to be displayed, in order to avoid querying the USD Prim too frequently (despite it being - // cached and optimized for frequent access). Avoiding frequent conversions from USD Strings to Qt Strings helps - // in keeping memory allocations low. - QList ret = { - new TreeItem(prim, TreeItem::Type::kLoad), - new TreeItem(prim, TreeItem::Type::kName), - new TreeItem(prim, TreeItem::Type::kType), - new TreeItem(prim, TreeItem::Type::kVariants) - }; - return ret; + // Cache the values to be displayed, in order to avoid querying the USD Prim too frequently + // (despite it being cached and optimized for frequent access). Avoiding frequent conversions + // from USD Strings to Qt Strings helps in keeping memory allocations low. + QList ret = { new TreeItem(prim, TreeItem::Type::kLoad), + new TreeItem(prim, TreeItem::Type::kName), + new TreeItem(prim, TreeItem::Type::kType), + new TreeItem(prim, TreeItem::Type::kVariants) }; + return ret; } /*static*/ int TreeModelFactory::buildTreeHierarchy(const UsdPrim& prim, QStandardItem* parentItem) { - QList primDataCells = createPrimRow(prim); - parentItem->appendRow(primDataCells); - int cnt = 1; + QList primDataCells = createPrimRow(prim); + parentItem->appendRow(primDataCells); + int cnt = 1; - for (const auto& childPrim : prim.GetAllChildren()) - { - cnt += buildTreeHierarchy(childPrim, primDataCells.front()); - } - return cnt; + for (const auto& childPrim : prim.GetAllChildren()) { + cnt += buildTreeHierarchy(childPrim, primDataCells.front()); + } + return cnt; } /*static*/ -int TreeModelFactory::buildTreeHierarchy(const UsdPrim& prim, QStandardItem* parentItem, - const unordered_sdfpath_set& primsToIncludeInTree, size_t& insertionsRemaining) +int TreeModelFactory::buildTreeHierarchy( + const UsdPrim& prim, + QStandardItem* parentItem, + const unordered_sdfpath_set& primsToIncludeInTree, + size_t& insertionsRemaining) { - int cnt = 0; - bool primShouldBeIncluded = primsToIncludeInTree.find(prim.GetPath()) != primsToIncludeInTree.end(); - if (primShouldBeIncluded) - { - QList primDataCells = createPrimRow(prim); - parentItem->appendRow(primDataCells); - ++cnt; + int cnt = 0; + bool primShouldBeIncluded + = primsToIncludeInTree.find(prim.GetPath()) != primsToIncludeInTree.end(); + if (primShouldBeIncluded) { + QList primDataCells = createPrimRow(prim); + parentItem->appendRow(primDataCells); + ++cnt; - // Only continue processing additional USD Prims if all expected results have not already been found: - if (--insertionsRemaining > 0) - { - for (const auto& childPrim : prim.GetAllChildren()) - { - cnt += buildTreeHierarchy(childPrim, primDataCells.front(), primsToIncludeInTree, insertionsRemaining); - } - } - } - return cnt; + // Only continue processing additional USD Prims if all expected results have not already + // been found: + if (--insertionsRemaining > 0) { + for (const auto& childPrim : prim.GetAllChildren()) { + cnt += buildTreeHierarchy( + childPrim, primDataCells.front(), primsToIncludeInTree, insertionsRemaining); + } + } + } + return cnt; } -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/usd/ui/TreeModelFactory.h b/lib/usd/ui/TreeModelFactory.h index a0c116e5a1..8d4b3ee8fc 100644 --- a/lib/usd/ui/TreeModelFactory.h +++ b/lib/usd/ui/TreeModelFactory.h @@ -17,19 +17,17 @@ #ifndef MAYAUSDUI_TREE_MODEL_FACTORY_H #define MAYAUSDUI_TREE_MODEL_FACTORY_H - -#include -#include - -#include +#include #include #include -#include - +#include #include +#include +#include + class QObject; class QStandardItem; @@ -42,68 +40,75 @@ class TreeModel; class ImportData; /** - * \brief Factory to create a tree-like structure of USD content suitable to be displayed in a TreeView. + * \brief Factory to create a tree-like structure of USD content suitable to be displayed in a + * TreeView. */ class MAYAUSD_UI_PUBLIC TreeModelFactory { private: - /** - * \brief Default Constructor (deleted). - */ - TreeModelFactory() = delete; + /** + * \brief Default Constructor (deleted). + */ + TreeModelFactory() = delete; public: - /** - * \brief Create an empty TreeModel. - * \param parent A reference to the parent of the TreeModel. - * \return An empty TreeModel. - */ - static std::unique_ptr createEmptyTreeModel(const IMayaMQtUtil& mayaQtUtil, const ImportData* importData = nullptr, QObject* parent = nullptr); - - /** - * \brief Create a TreeModel from the given USD Stage. - * \param stage A reference to the USD Stage from which to create a TreeModel. - * \param parent A reference to the parent of the TreeModel. - * \param nbItems Number of items added to the TreeModel. - * \return A TreeModel created from the given USD Stage. - */ - static std::unique_ptr createFromStage(const UsdStageRefPtr& stage, - const IMayaMQtUtil& mayaQtUtil, - const ImportData* importData = nullptr, - QObject* parent = nullptr, - int* nbItems = nullptr); + /** + * \brief Create an empty TreeModel. + * \param parent A reference to the parent of the TreeModel. + * \return An empty TreeModel. + */ + static std::unique_ptr createEmptyTreeModel( + const IMayaMQtUtil& mayaQtUtil, + const ImportData* importData = nullptr, + QObject* parent = nullptr); + + /** + * \brief Create a TreeModel from the given USD Stage. + * \param stage A reference to the USD Stage from which to create a TreeModel. + * \param parent A reference to the parent of the TreeModel. + * \param nbItems Number of items added to the TreeModel. + * \return A TreeModel created from the given USD Stage. + */ + static std::unique_ptr createFromStage( + const UsdStageRefPtr& stage, + const IMayaMQtUtil& mayaQtUtil, + const ImportData* importData = nullptr, + QObject* parent = nullptr, + int* nbItems = nullptr); protected: - // Type definition for an STL unordered set of SDF Paths: - using unordered_sdfpath_set = std::unordered_set; - - /** - * \brief Create the list of data cells used to represent the given USD Prim's data in the tree. - * \param prim The USD Prim for which to create the list of data cells. - * \return The List of data cells used to represent the given USD Prim's data in the tree. - */ - static QList createPrimRow(const UsdPrim& prim); - - /** - * \brief Build the tree hierarchy starting at the given USD Prim. - * \param prim The USD Prim from which to start building the tree hierarchy. - * \param parentItem The parent into which to attach the tree hierarchy. - * \return The number of items added. - */ - static int buildTreeHierarchy(const UsdPrim& prim, QStandardItem* parentItem); - /** - * \brief Build the tree hierarchy starting at the given USD Prim. - * \param prim The USD Prim from which to start building the tree hierarchy. - * \param parentItem The parent into which to attach the tree hierarchy. - * \param primsToIncludeInTree The list of USD Prim paths to include when building the tree. - * \param insertionsRemaining The number of items yet to be inserted. - * \return The number of items added. - */ - static int buildTreeHierarchy(const UsdPrim& prim, QStandardItem* parentItem, - const unordered_sdfpath_set& primsToIncludeInTree, size_t& insertionsRemaining); + // Type definition for an STL unordered set of SDF Paths: + using unordered_sdfpath_set = std::unordered_set; + + /** + * \brief Create the list of data cells used to represent the given USD Prim's data in the tree. + * \param prim The USD Prim for which to create the list of data cells. + * \return The List of data cells used to represent the given USD Prim's data in the tree. + */ + static QList createPrimRow(const UsdPrim& prim); + + /** + * \brief Build the tree hierarchy starting at the given USD Prim. + * \param prim The USD Prim from which to start building the tree hierarchy. + * \param parentItem The parent into which to attach the tree hierarchy. + * \return The number of items added. + */ + static int buildTreeHierarchy(const UsdPrim& prim, QStandardItem* parentItem); + /** + * \brief Build the tree hierarchy starting at the given USD Prim. + * \param prim The USD Prim from which to start building the tree hierarchy. + * \param parentItem The parent into which to attach the tree hierarchy. + * \param primsToIncludeInTree The list of USD Prim paths to include when building the tree. + * \param insertionsRemaining The number of items yet to be inserted. + * \return The number of items added. + */ + static int buildTreeHierarchy( + const UsdPrim& prim, + QStandardItem* parentItem, + const unordered_sdfpath_set& primsToIncludeInTree, + size_t& insertionsRemaining); }; -} // namespace MayaUsd - +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/usd/ui/USDImportDialog.cpp b/lib/usd/ui/USDImportDialog.cpp index 10eb925e64..5577486f19 100644 --- a/lib/usd/ui/USDImportDialog.cpp +++ b/lib/usd/ui/USDImportDialog.cpp @@ -15,14 +15,14 @@ // #include "USDImportDialog.h" -#include +#include "ui_USDImportDialog.h" #include #include #include -#include "ui_USDImportDialog.h" +#include namespace MAYAUSD_NS_DEF { @@ -30,198 +30,211 @@ namespace MAYAUSD_NS_DEF { // and without it we have an undefined symbol. IUSDImportView::~IUSDImportView() { } -USDImportDialog::USDImportDialog(const std::string& filename, const ImportData* importData,const IMayaMQtUtil& mayaQtUtil, QWidget* parent /*= nullptr*/) - : QDialog{ parent } - , fUI{ new Ui::ImportDialog() } - , fStage{ UsdStage::Open(filename, UsdStage::InitialLoadSet::LoadNone) } - , fFilename{ filename } - , fRootPrimPath("/") +USDImportDialog::USDImportDialog( + const std::string& filename, + const ImportData* importData, + const IMayaMQtUtil& mayaQtUtil, + QWidget* parent /*= nullptr*/) + : QDialog { parent } + , fUI { new Ui::ImportDialog() } + , fStage { UsdStage::Open(filename, UsdStage::InitialLoadSet::LoadNone) } + , fFilename { filename } + , fRootPrimPath("/") { - if (!fStage) - throw std::invalid_argument("Invalid filename passed to USD Import Dialog"); - - fUI->setupUi(this); - - // If we were given some import data we will only use it if it matches our - // input filename. In the case where the user opened dialog, clicked Apply and - // then reopens the dialog we want to reset the dialog to the previous state. - const ImportData* matchingImportData = nullptr; - if ((importData != nullptr) && (fFilename == importData->filename())) - { - fRootPrimPath = importData->rootPrimPath(); - matchingImportData = importData; - } - - int minW = fUI->nbPrimsInScopeLabel->fontMetrics().width("12345"); - fUI->nbPrimsInScopeLabel->setMinimumWidth(minW); - fUI->nbVariantsChangedLabel->setMinimumWidth(minW); - - // These calls must come after the UI is initialized via "setupUi()": - int nbItems = 0; - fTreeModel = TreeModelFactory::createFromStage(fStage, mayaQtUtil, matchingImportData, this, &nbItems); - fProxyModel = std::unique_ptr(new QSortFilterProxyModel(this)); - QObject::connect(fTreeModel.get(), SIGNAL(checkedStateChanged(int)), this, SLOT(onCheckedStateChanged(int))); - QObject::connect(fTreeModel.get(), SIGNAL(modifiedVariantCountChanged(int)), this, SLOT(onModifiedVariantsChanged(int))); - - // Set the root prim path in the tree model. This will set the default check states. - fTreeModel->setRootPrimPath(fRootPrimPath); - - // Configure the TreeView of the dialog: - fProxyModel->setSourceModel(fTreeModel.get()); + if (!fStage) + throw std::invalid_argument("Invalid filename passed to USD Import Dialog"); + + fUI->setupUi(this); + + // If we were given some import data we will only use it if it matches our + // input filename. In the case where the user opened dialog, clicked Apply and + // then reopens the dialog we want to reset the dialog to the previous state. + const ImportData* matchingImportData = nullptr; + if ((importData != nullptr) && (fFilename == importData->filename())) { + fRootPrimPath = importData->rootPrimPath(); + matchingImportData = importData; + } + + int minW = fUI->nbPrimsInScopeLabel->fontMetrics().width("12345"); + fUI->nbPrimsInScopeLabel->setMinimumWidth(minW); + fUI->nbVariantsChangedLabel->setMinimumWidth(minW); + + // These calls must come after the UI is initialized via "setupUi()": + int nbItems = 0; + fTreeModel + = TreeModelFactory::createFromStage(fStage, mayaQtUtil, matchingImportData, this, &nbItems); + fProxyModel = std::unique_ptr(new QSortFilterProxyModel(this)); + QObject::connect( + fTreeModel.get(), SIGNAL(checkedStateChanged(int)), this, SLOT(onCheckedStateChanged(int))); + QObject::connect( + fTreeModel.get(), + SIGNAL(modifiedVariantCountChanged(int)), + this, + SLOT(onModifiedVariantsChanged(int))); + + // Set the root prim path in the tree model. This will set the default check states. + fTreeModel->setRootPrimPath(fRootPrimPath); + + // Configure the TreeView of the dialog: + fProxyModel->setSourceModel(fTreeModel.get()); #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) - fProxyModel->setRecursiveFilteringEnabled(true); + fProxyModel->setRecursiveFilteringEnabled(true); #endif - fProxyModel->setDynamicSortFilter(false); - fProxyModel->setFilterCaseSensitivity(Qt::CaseSensitivity::CaseInsensitive); - fUI->treeView->setModel(fProxyModel.get()); - fUI->treeView->setTreePosition(TreeModel::kTreeColumn_Name); - fUI->treeView->setAlternatingRowColors(true); - fUI->treeView->setSelectionMode(QAbstractItemView::SingleSelection); - QObject::connect(fUI->treeView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(onItemClicked(const QModelIndex&))); - QObject::connect(fUI->actionReset_File, SIGNAL(triggered(bool)), this, SLOT(onResetFileTriggered())); - QObject::connect(fUI->actionHelp_on_Hierarchy_View, SIGNAL(triggered(bool)), this, SLOT(onHierarchyViewHelpTriggered())); - - QHeaderView* header = fUI->treeView->header(); - - header->setStretchLastSection(true); - header->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter); - - fItemDelegate = std::unique_ptr(new ItemDelegate(fUI->treeView)); - QObject::connect(fItemDelegate.get(), SIGNAL(variantModified()), - fTreeModel.get(), SLOT(updateModifiedVariantCount())); - - // Set our item delegate on the treeview so we can customize the drawing of - // the variant sets. - fUI->treeView->setItemDelegate(fItemDelegate.get()); - - // Must be done AFTER we set our item delegate - fTreeModel->openPersistentEditors(fUI->treeView, QModelIndex()); - - // This request to expand the tree to a default depth of 3 should come after the creation - // of the editors since it can trigger calls to things like sizeHint before we've put any of - // the variant set UI in place. - fUI->treeView->expandToDepth(3); - - // Set some initial widths for the tree view columns. - const int kLoadWidth = mayaQtUtil.dpiScale(25); - constexpr int kTypeWidth = 120; - constexpr int kNameWidth = 500; - header->setMinimumSectionSize(kLoadWidth); - header->resizeSection(TreeModel::kTreeColumn_Load, kLoadWidth); - header->resizeSection(TreeModel::kTreeColumn_Name, kNameWidth); - header->resizeSection(TreeModel::kTreeColumn_Type, kTypeWidth); - header->setSectionResizeMode(0, QHeaderView::Fixed); - - // Display the full path of the file to import: - fUI->usdFilePath->setText(QString::fromStdString(fFilename)); - - // Make sure the "Import" button is enabled. - fUI->applyButton->setEnabled(true); + fProxyModel->setDynamicSortFilter(false); + fProxyModel->setFilterCaseSensitivity(Qt::CaseSensitivity::CaseInsensitive); + fUI->treeView->setModel(fProxyModel.get()); + fUI->treeView->setTreePosition(TreeModel::kTreeColumn_Name); + fUI->treeView->setAlternatingRowColors(true); + fUI->treeView->setSelectionMode(QAbstractItemView::SingleSelection); + QObject::connect( + fUI->treeView, + SIGNAL(clicked(const QModelIndex&)), + this, + SLOT(onItemClicked(const QModelIndex&))); + QObject::connect( + fUI->actionReset_File, SIGNAL(triggered(bool)), this, SLOT(onResetFileTriggered())); + QObject::connect( + fUI->actionHelp_on_Hierarchy_View, + SIGNAL(triggered(bool)), + this, + SLOT(onHierarchyViewHelpTriggered())); + + QHeaderView* header = fUI->treeView->header(); + + header->setStretchLastSection(true); + header->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter); + + fItemDelegate = std::unique_ptr(new ItemDelegate(fUI->treeView)); + QObject::connect( + fItemDelegate.get(), + SIGNAL(variantModified()), + fTreeModel.get(), + SLOT(updateModifiedVariantCount())); + + // Set our item delegate on the treeview so we can customize the drawing of + // the variant sets. + fUI->treeView->setItemDelegate(fItemDelegate.get()); + + // Must be done AFTER we set our item delegate + fTreeModel->openPersistentEditors(fUI->treeView, QModelIndex()); + + // This request to expand the tree to a default depth of 3 should come after the creation + // of the editors since it can trigger calls to things like sizeHint before we've put any of + // the variant set UI in place. + fUI->treeView->expandToDepth(3); + + // Set some initial widths for the tree view columns. + const int kLoadWidth = mayaQtUtil.dpiScale(25); + constexpr int kTypeWidth = 120; + constexpr int kNameWidth = 500; + header->setMinimumSectionSize(kLoadWidth); + header->resizeSection(TreeModel::kTreeColumn_Load, kLoadWidth); + header->resizeSection(TreeModel::kTreeColumn_Name, kNameWidth); + header->resizeSection(TreeModel::kTreeColumn_Type, kTypeWidth); + header->setSectionResizeMode(0, QHeaderView::Fixed); + + // Display the full path of the file to import: + fUI->usdFilePath->setText(QString::fromStdString(fFilename)); + + // Make sure the "Import" button is enabled. + fUI->applyButton->setEnabled(true); } USDImportDialog::~USDImportDialog() { - // Note: the destructor is needed here so we can forward declare the Ui::ImportDialog - // and only include "ui_USDImportDialog.h" here in the .cpp (instead of .h). + // Note: the destructor is needed here so we can forward declare the Ui::ImportDialog + // and only include "ui_USDImportDialog.h" here in the .cpp (instead of .h). } bool USDImportDialog::execute() { - // Fixup the palette by changing the alternate base color which is used for - // painting the tree alternate rows. - // TODO - there is a small problem here in that this works, but not until you - // force the tree to redraw by clicking in it. -// QPalette treePal = fUI->treeView->palette(); -// treePal.setBrush(QPalette::Active, QPalette::AlternateBase, treePal.color(QPalette::Active, QPalette::Base).lighter(130)); -// fUI->treeView->setPalette(treePal); - return exec() == QDialog::Accepted; + // Fixup the palette by changing the alternate base color which is used for + // painting the tree alternate rows. + // TODO - there is a small problem here in that this works, but not until you + // force the tree to redraw by clicking in it. + // QPalette treePal = fUI->treeView->palette(); + // treePal.setBrush(QPalette::Active, QPalette::AlternateBase, treePal.color(QPalette::Active, + // QPalette::Base).lighter(130)); fUI->treeView->setPalette(treePal); + return exec() == QDialog::Accepted; } -const std::string& USDImportDialog::filename() const -{ - return fFilename; -} +const std::string& USDImportDialog::filename() const { return fFilename; } const std::string& USDImportDialog::rootPrimPath() const { - std::string rootPrimPath; - fTreeModel->getRootPrimPath(rootPrimPath, QModelIndex()); - if (!rootPrimPath.empty()) - fRootPrimPath = rootPrimPath; - return fRootPrimPath; + std::string rootPrimPath; + fTreeModel->getRootPrimPath(rootPrimPath, QModelIndex()); + if (!rootPrimPath.empty()) + fRootPrimPath = rootPrimPath; + return fRootPrimPath; } UsdStagePopulationMask USDImportDialog::stagePopulationMask() const { - UsdStagePopulationMask stagePopulationMask; - fTreeModel->fillStagePopulationMask(stagePopulationMask, QModelIndex()); - return stagePopulationMask; + UsdStagePopulationMask stagePopulationMask; + fTreeModel->fillStagePopulationMask(stagePopulationMask, QModelIndex()); + return stagePopulationMask; } ImportData::PrimVariantSelections USDImportDialog::primVariantSelections() const { - ImportData::PrimVariantSelections varSels; - fTreeModel->fillPrimVariantSelections(varSels, QModelIndex()); - return varSels; + ImportData::PrimVariantSelections varSels; + fTreeModel->fillPrimVariantSelections(varSels, QModelIndex()); + return varSels; } UsdStage::InitialLoadSet USDImportDialog::stageInitialLoadSet() const { - return UsdStage::InitialLoadSet::LoadAll; + return UsdStage::InitialLoadSet::LoadAll; } void USDImportDialog::onItemClicked(const QModelIndex& index) { - TreeItem* item = static_cast(fTreeModel->itemFromIndex(fProxyModel->mapToSource(index))); - if (item != nullptr) - { - // When user checks a prim that is in a collapsed state, then that prim - // gets checked-enabled and it expands to show its immediate children. - fTreeModel->onItemClicked(item); - if (!fUI->treeView->isExpanded(index)) - { - if (item->checkState() == TreeItem::CheckState::kChecked) - fUI->treeView->expand(index); - } - } + TreeItem* item + = static_cast(fTreeModel->itemFromIndex(fProxyModel->mapToSource(index))); + if (item != nullptr) { + // When user checks a prim that is in a collapsed state, then that prim + // gets checked-enabled and it expands to show its immediate children. + fTreeModel->onItemClicked(item); + if (!fUI->treeView->isExpanded(index)) { + if (item->checkState() == TreeItem::CheckState::kChecked) + fUI->treeView->expand(index); + } + } } void USDImportDialog::onResetFileTriggered() { - if (nullptr != fTreeModel) - { - fTreeModel->resetVariants(); - fTreeModel->setRootPrimPath("/"); - } + if (nullptr != fTreeModel) { + fTreeModel->resetVariants(); + fTreeModel->setRootPrimPath("/"); + } } void USDImportDialog::onHierarchyViewHelpTriggered() { - MGlobal::executeCommand("showHelp \"UsdHierarchyView\""); + MGlobal::executeCommand("showHelp \"UsdHierarchyView\""); } void USDImportDialog::onCheckedStateChanged(int nbChecked) { - QString nbLabel; - nbLabel.setNum(nbChecked); - fUI->nbPrimsInScopeLabel->setText(nbLabel); + QString nbLabel; + nbLabel.setNum(nbChecked); + fUI->nbPrimsInScopeLabel->setText(nbLabel); } void USDImportDialog::onModifiedVariantsChanged(int nbModified) { - QString nbLabel; - nbLabel.setNum(nbModified); - fUI->nbVariantsChangedLabel->setText(nbLabel); + QString nbLabel; + nbLabel.setNum(nbModified); + fUI->nbVariantsChangedLabel->setText(nbLabel); } -int USDImportDialog::primsInScopeCount() const -{ - return fUI->nbPrimsInScopeLabel->text().toInt(); -} +int USDImportDialog::primsInScopeCount() const { return fUI->nbPrimsInScopeLabel->text().toInt(); } int USDImportDialog::switchedVariantCount() const { - return fUI->nbVariantsChangedLabel->text().toInt(); + return fUI->nbVariantsChangedLabel->text().toInt(); } -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/usd/ui/USDImportDialog.h b/lib/usd/ui/USDImportDialog.h index 3ad5f3594f..a7a763b19c 100644 --- a/lib/usd/ui/USDImportDialog.h +++ b/lib/usd/ui/USDImportDialog.h @@ -17,23 +17,21 @@ #ifndef MAYAUSDUI_USD_IMPORT_DIALOG_H #define MAYAUSDUI_USD_IMPORT_DIALOG_H - -#include - -#include -#include +#include #include -#include - -#include +#include +#include #include -#include #include +#include +#include + +#include namespace Ui { - class ImportDialog; +class ImportDialog; } PXR_NAMESPACE_USING_DIRECTIVE @@ -46,62 +44,65 @@ class IMayaMQtUtil; * \brief USD file import dialog. */ class MAYAUSD_UI_PUBLIC USDImportDialog - : public QDialog - , public IUSDImportView + : public QDialog + , public IUSDImportView { - Q_OBJECT + Q_OBJECT public: - /** - * \brief Constructor. - * \param filename Absolute file path of a USD file to import. - * \param parent A reference to the parent widget of the dialog. - */ - explicit USDImportDialog(const std::string& filename, const ImportData* importData, const IMayaMQtUtil& mayaQtUtil, QWidget* parent = nullptr); - - //! Destructor. - ~USDImportDialog(); - - // IUSDImportView overrides - const std::string& filename() const override; - const std::string& rootPrimPath() const override; - UsdStagePopulationMask stagePopulationMask() const override; - UsdStage::InitialLoadSet stageInitialLoadSet() const override; - ImportData::PrimVariantSelections primVariantSelections() const override; - bool execute() override; - - int primsInScopeCount() const; - int switchedVariantCount() const; + /** + * \brief Constructor. + * \param filename Absolute file path of a USD file to import. + * \param parent A reference to the parent widget of the dialog. + */ + explicit USDImportDialog( + const std::string& filename, + const ImportData* importData, + const IMayaMQtUtil& mayaQtUtil, + QWidget* parent = nullptr); + + //! Destructor. + ~USDImportDialog(); + + // IUSDImportView overrides + const std::string& filename() const override; + const std::string& rootPrimPath() const override; + UsdStagePopulationMask stagePopulationMask() const override; + UsdStage::InitialLoadSet stageInitialLoadSet() const override; + ImportData::PrimVariantSelections primVariantSelections() const override; + bool execute() override; + + int primsInScopeCount() const; + int switchedVariantCount() const; private Q_SLOTS: - void onItemClicked(const QModelIndex&); - void onResetFileTriggered(); - void onHierarchyViewHelpTriggered(); - void onCheckedStateChanged(int); - void onModifiedVariantsChanged(int); + void onItemClicked(const QModelIndex&); + void onResetFileTriggered(); + void onHierarchyViewHelpTriggered(); + void onCheckedStateChanged(int); + void onModifiedVariantsChanged(int); protected: - // Reference to the Qt UI View of the dialog: - std::unique_ptr fUI; + // Reference to the Qt UI View of the dialog: + std::unique_ptr fUI; - // Reference to the Model holding the structure of the USD file hierarchy: - std::unique_ptr fTreeModel; - // Reference to the Proxy Model used to sort and filter the USD file hierarchy: - std::unique_ptr fProxyModel; - // Reference to the delegate we set on the tree view: - std::unique_ptr fItemDelegate; + // Reference to the Model holding the structure of the USD file hierarchy: + std::unique_ptr fTreeModel; + // Reference to the Proxy Model used to sort and filter the USD file hierarchy: + std::unique_ptr fProxyModel; + // Reference to the delegate we set on the tree view: + std::unique_ptr fItemDelegate; - // Reference to the USD Stage holding the list of Prims which could be imported: - UsdStageRefPtr fStage; + // Reference to the USD Stage holding the list of Prims which could be imported: + UsdStageRefPtr fStage; - // The filename for the USD stage we opened. - std::string fFilename; + // The filename for the USD stage we opened. + std::string fFilename; - // The root prim path. - mutable std::string fRootPrimPath; + // The root prim path. + mutable std::string fRootPrimPath; }; -} // namespace MayaUsd - +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/usd/ui/USDImportDialogCmd.cpp b/lib/usd/ui/USDImportDialogCmd.cpp index ba3f702425..6572900166 100644 --- a/lib/usd/ui/USDImportDialogCmd.cpp +++ b/lib/usd/ui/USDImportDialogCmd.cpp @@ -19,30 +19,29 @@ #include #include +#include #include +#include +#include #include +#include #include #include #include #include -#include -#include -#include -#include // This is added to prevent multiple definitions of the MApiVersion string. #define MNoVersionString -#include - #include #include #include -#include -#include +#include #include #include +#include +#include namespace MAYAUSD_NS_DEF { @@ -62,205 +61,192 @@ constexpr auto kPrimCountFlagLong = "-primCount"; constexpr auto kSwitchedVariantCountFlag = "-swc"; constexpr auto kSwitchedVariantCountFlagLong = "-switchedVariantCount"; -} +} // namespace /*static*/ MStatus USDImportDialogCmd::initialize(MFnPlugin& plugin) { - return plugin.registerCommand( - fsName, - USDImportDialogCmd::creator, - USDImportDialogCmd::createSyntax); + return plugin.registerCommand( + fsName, USDImportDialogCmd::creator, USDImportDialogCmd::createSyntax); } /*static*/ -MStatus USDImportDialogCmd::finalize(MFnPlugin& plugin) -{ - return plugin.deregisterCommand(fsName); -} +MStatus USDImportDialogCmd::finalize(MFnPlugin& plugin) { return plugin.deregisterCommand(fsName); } /*static*/ -void* USDImportDialogCmd::creator() -{ - return new USDImportDialogCmd(); -} +void* USDImportDialogCmd::creator() { return new USDImportDialogCmd(); } MStatus USDImportDialogCmd::applyToProxy(const MString& proxyPath) { - MDagPath proxyShapeDagPath; - MSelectionList selection; - selection.add(proxyPath); - MStatus status = selection.getDagPath(0, proxyShapeDagPath); - if (status.error()) - return status; + MDagPath proxyShapeDagPath; + MSelectionList selection; + selection.add(proxyPath); + MStatus status = selection.getDagPath(0, proxyShapeDagPath); + if (status.error()) + return status; - MObject proxyShapeObj = proxyShapeDagPath.node(&status); - CHECK_MSTATUS_AND_RETURN_IT(status); + MObject proxyShapeObj = proxyShapeDagPath.node(&status); + CHECK_MSTATUS_AND_RETURN_IT(status); MFnDependencyNode fn(proxyShapeObj, &status); - CHECK_MSTATUS_AND_RETURN_IT(status); + CHECK_MSTATUS_AND_RETURN_IT(status); - if (fn.typeName() != MString("mayaUsdProxyShape")) - return MS::kInvalidParameter; + if (fn.typeName() != MString("mayaUsdProxyShape")) + return MS::kInvalidParameter; MayaUsdProxyShapeBase* proxyShape = dynamic_cast(fn.userNode()); - if (!proxyShape) - return MS::kInvalidParameter; + if (!proxyShape) + return MS::kInvalidParameter; - MPlug primPath = fn.findPlug("primPath", &status); - CHECK_MSTATUS_AND_RETURN_IT(status); + MPlug primPath = fn.findPlug("primPath", &status); + CHECK_MSTATUS_AND_RETURN_IT(status); - MPlug filePath = fn.findPlug("filePath", &status); - CHECK_MSTATUS_AND_RETURN_IT(status); + MPlug filePath = fn.findPlug("filePath", &status); + CHECK_MSTATUS_AND_RETURN_IT(status); - ImportData& importData = ImportData::instance(); - primPath.setValue(MString(importData.rootPrimPath().c_str())); - CHECK_MSTATUS_AND_RETURN_IT(status); + ImportData& importData = ImportData::instance(); + primPath.setValue(MString(importData.rootPrimPath().c_str())); + CHECK_MSTATUS_AND_RETURN_IT(status); - filePath.setValue(MString(importData.filename().c_str())); - CHECK_MSTATUS_AND_RETURN_IT(status); + filePath.setValue(MString(importData.filename().c_str())); + CHECK_MSTATUS_AND_RETURN_IT(status); - auto rootPrim = proxyShape->usdPrim(); - if (!rootPrim) - return MS::kNotFound; + auto rootPrim = proxyShape->usdPrim(); + if (!rootPrim) + return MS::kNotFound; - auto stage = rootPrim.GetStage(); - if (!stage) - return MS::kNotFound; + auto stage = rootPrim.GetStage(); + if (!stage) + return MS::kNotFound; - for (auto& primVariant : importData.primVariantSelections()) { - auto prim = stage->GetPrimAtPath(primVariant.first); - if (!prim || !prim.HasVariantSets()) - return MS::kNotFound; + for (auto& primVariant : importData.primVariantSelections()) { + auto prim = stage->GetPrimAtPath(primVariant.first); + if (!prim || !prim.HasVariantSets()) + return MS::kNotFound; - for (auto& variant : primVariant.second) { - auto variantSet = prim.GetVariantSet(variant.first); - if (variantSet) - variantSet.SetVariantSelection(variant.second); - } - } + for (auto& variant : primVariant.second) { + auto variantSet = prim.GetVariantSet(variant.first); + if (variantSet) + variantSet.SetVariantSelection(variant.second); + } + } return MS::kSuccess; } MStatus USDImportDialogCmd::doIt(const MArgList& args) { - MStatus st; - MArgParser argData(syntax(), args, &st); - if (!st) return st; - - if (argData.isQuery()) - { - if (argData.isFlagSet(kPrimPathFlag)) - { - const ImportData& importData = ImportData::cinstance(); - std::string rootPrimPath = importData.rootPrimPath(); - setResult(rootPrimPath.c_str()); - return MS::kSuccess; - } - - if (argData.isFlagSet(kPrimCountFlag)) - { - const ImportData& importData = ImportData::cinstance(); - setResult(importData.primsInScopeCount()); - return MS::kSuccess; - } - - if (argData.isFlagSet(kSwitchedVariantCountFlag)) - { - const ImportData& importData = ImportData::cinstance(); - setResult(importData.switchedVariantCount()); - return MS::kSuccess; - } - - return MS::kInvalidParameter; - } - - // Edit flags below: - if(argData.isFlagSet(kClearDataFlag)) - { - ImportData& importData = ImportData::instance(); - importData.clearData(); - return MS::kSuccess; - } - - // No command object is expected - if(argData.isFlagSet(kApplyToProxyFlag)) - { - MStringArray proxyArray; - st = argData.getObjects(proxyArray); - if (!st || proxyArray.length() != 1) - return MS::kInvalidParameter; - - return applyToProxy(proxyArray[0]); - } - - MStringArray filenameArray; - st = argData.getObjects(filenameArray); - if (st && (filenameArray.length() > 0)) - { - // We only use the first one. - MFileObject fo; - MString assetPath; - fo.setRawFullName(filenameArray[0]); - bool validTarget = fo.exists(); - if (!validTarget) { - // Give the default usd-asset-resolver a chance - if (const char* cStr = filenameArray[0].asChar()) { - validTarget = !ArGetResolver().Resolve(cStr).empty(); - if (validTarget) - assetPath = filenameArray[0]; - } - } else - assetPath = fo.resolvedFullName(); - - if (validTarget) - { - USDQtUtil usdQtUtil; - ImportData& importData = ImportData::instance(); - - // Creating the View can pause Maya, usually only briefly but it's noticable, so we'll toggle the wait cursor to show that it's working. - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - - std::unique_ptr usdImportDialog(new USDImportDialog(assetPath.asChar(), &importData, usdQtUtil, MQtUtil::mainWindow())); - - QApplication::restoreOverrideCursor(); - - if (usdImportDialog->execute()) - { - // The user clicked 'Apply' so copy the info from the dialog to the import data instance. - importData.setFilename(usdImportDialog->filename()); - importData.setStageInitialLoadSet(usdImportDialog->stageInitialLoadSet()); - importData.setRootPrimPath(usdImportDialog->rootPrimPath()); - // Don't set the stage pop mask until we solve how to use it together with - // the root prim path. - //importData.setStagePopulationMask(usdImportDialog->stagePopulationMask()); - importData.setPrimVariantSelections(usdImportDialog->primVariantSelections()); - - importData.setPrimsInScopeCount(usdImportDialog->primsInScopeCount()); - importData.setSwitchedVariantCount(usdImportDialog->switchedVariantCount()); - - setResult(assetPath); - } - return MS::kSuccess; - } - } - - return MS::kInvalidParameter; + MStatus st; + MArgParser argData(syntax(), args, &st); + if (!st) + return st; + + if (argData.isQuery()) { + if (argData.isFlagSet(kPrimPathFlag)) { + const ImportData& importData = ImportData::cinstance(); + std::string rootPrimPath = importData.rootPrimPath(); + setResult(rootPrimPath.c_str()); + return MS::kSuccess; + } + + if (argData.isFlagSet(kPrimCountFlag)) { + const ImportData& importData = ImportData::cinstance(); + setResult(importData.primsInScopeCount()); + return MS::kSuccess; + } + + if (argData.isFlagSet(kSwitchedVariantCountFlag)) { + const ImportData& importData = ImportData::cinstance(); + setResult(importData.switchedVariantCount()); + return MS::kSuccess; + } + + return MS::kInvalidParameter; + } + + // Edit flags below: + if (argData.isFlagSet(kClearDataFlag)) { + ImportData& importData = ImportData::instance(); + importData.clearData(); + return MS::kSuccess; + } + + // No command object is expected + if (argData.isFlagSet(kApplyToProxyFlag)) { + MStringArray proxyArray; + st = argData.getObjects(proxyArray); + if (!st || proxyArray.length() != 1) + return MS::kInvalidParameter; + + return applyToProxy(proxyArray[0]); + } + + MStringArray filenameArray; + st = argData.getObjects(filenameArray); + if (st && (filenameArray.length() > 0)) { + // We only use the first one. + MFileObject fo; + MString assetPath; + fo.setRawFullName(filenameArray[0]); + bool validTarget = fo.exists(); + if (!validTarget) { + // Give the default usd-asset-resolver a chance + if (const char* cStr = filenameArray[0].asChar()) { + validTarget = !ArGetResolver().Resolve(cStr).empty(); + if (validTarget) + assetPath = filenameArray[0]; + } + } else + assetPath = fo.resolvedFullName(); + + if (validTarget) { + USDQtUtil usdQtUtil; + ImportData& importData = ImportData::instance(); + + // Creating the View can pause Maya, usually only briefly but it's noticable, so we'll + // toggle the wait cursor to show that it's working. + QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); + + std::unique_ptr usdImportDialog(new USDImportDialog( + assetPath.asChar(), &importData, usdQtUtil, MQtUtil::mainWindow())); + + QApplication::restoreOverrideCursor(); + + if (usdImportDialog->execute()) { + // The user clicked 'Apply' so copy the info from the dialog to the import data + // instance. + importData.setFilename(usdImportDialog->filename()); + importData.setStageInitialLoadSet(usdImportDialog->stageInitialLoadSet()); + importData.setRootPrimPath(usdImportDialog->rootPrimPath()); + // Don't set the stage pop mask until we solve how to use it together with + // the root prim path. + // importData.setStagePopulationMask(usdImportDialog->stagePopulationMask()); + importData.setPrimVariantSelections(usdImportDialog->primVariantSelections()); + + importData.setPrimsInScopeCount(usdImportDialog->primsInScopeCount()); + importData.setSwitchedVariantCount(usdImportDialog->switchedVariantCount()); + + setResult(assetPath); + } + return MS::kSuccess; + } + } + + return MS::kInvalidParameter; } MSyntax USDImportDialogCmd::createSyntax() { - MSyntax syntax; - syntax.enableQuery(true); - syntax.enableEdit(false); - syntax.addFlag(kPrimPathFlag, kPrimPathFlagLong); - syntax.addFlag(kClearDataFlag, kClearDataFlagLong); - syntax.addFlag(kApplyToProxyFlag, kApplyToProxyFlagLong); - syntax.addFlag(kPrimCountFlag, kPrimCountFlagLong); - syntax.addFlag(kSwitchedVariantCountFlag, kSwitchedVariantCountFlagLong); - - syntax.setObjectType(MSyntax::kStringObjects, 0, 1); - return syntax; + MSyntax syntax; + syntax.enableQuery(true); + syntax.enableEdit(false); + syntax.addFlag(kPrimPathFlag, kPrimPathFlagLong); + syntax.addFlag(kClearDataFlag, kClearDataFlagLong); + syntax.addFlag(kApplyToProxyFlag, kApplyToProxyFlagLong); + syntax.addFlag(kPrimCountFlag, kPrimCountFlagLong); + syntax.addFlag(kSwitchedVariantCountFlag, kSwitchedVariantCountFlagLong); + + syntax.setObjectType(MSyntax::kStringObjects, 0, 1); + return syntax; } -} // namespace MayaUsd \ No newline at end of file +} // namespace MAYAUSD_NS_DEF \ No newline at end of file diff --git a/lib/usd/ui/USDImportDialogCmd.h b/lib/usd/ui/USDImportDialogCmd.h index afecafb9d8..8d0f34645b 100644 --- a/lib/usd/ui/USDImportDialogCmd.h +++ b/lib/usd/ui/USDImportDialogCmd.h @@ -17,35 +17,34 @@ #ifndef MAYAUSDUI_USD_IMPORT_DIALOG_CMD_H #define MAYAUSDUI_USD_IMPORT_DIALOG_CMD_H +#include #include -#include - #include namespace MAYAUSD_NS_DEF { -class MAYAUSD_UI_PUBLIC USDImportDialogCmd : public MPxCommand { +class MAYAUSD_UI_PUBLIC USDImportDialogCmd : public MPxCommand +{ public: - USDImportDialogCmd() = default; - ~USDImportDialogCmd() override = default; + USDImportDialogCmd() = default; + ~USDImportDialogCmd() override = default; - static MStatus initialize(MFnPlugin&); - static MStatus finalize(MFnPlugin&); + static MStatus initialize(MFnPlugin&); + static MStatus finalize(MFnPlugin&); - static const MString fsName; + static const MString fsName; - static void* creator(); - static MSyntax createSyntax(); + static void* creator(); + static MSyntax createSyntax(); - MStatus doIt(const MArgList& args) override; + MStatus doIt(const MArgList& args) override; private: MStatus applyToProxy(const MString& proxyPath); }; -} // namespace MayaUsd - +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/usd/ui/USDQtUtil.cpp b/lib/usd/ui/USDQtUtil.cpp index 79bdf24a03..1726065c27 100644 --- a/lib/usd/ui/USDQtUtil.cpp +++ b/lib/usd/ui/USDQtUtil.cpp @@ -21,19 +21,13 @@ namespace MAYAUSD_NS_DEF { -int USDQtUtil::dpiScale(int size) const -{ - return MQtUtil::dpiScale(size); -} +int USDQtUtil::dpiScale(int size) const { return MQtUtil::dpiScale(size); } -float USDQtUtil::dpiScale(float size) const -{ - return MQtUtil::dpiScale(size); -} +float USDQtUtil::dpiScale(float size) const { return MQtUtil::dpiScale(size); } QPixmap* USDQtUtil::createPixmap(const std::string& imageName) const { - return MQtUtil::createPixmap(imageName.c_str()); + return MQtUtil::createPixmap(imageName.c_str()); } -} // namespace MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/lib/usd/ui/USDQtUtil.h b/lib/usd/ui/USDQtUtil.h index c5cecac10f..d7fb843758 100644 --- a/lib/usd/ui/USDQtUtil.h +++ b/lib/usd/ui/USDQtUtil.h @@ -17,25 +17,23 @@ #ifndef MAYAUSDUI_USD_QT_UTIL_H #define MAYAUSDUI_USD_QT_UTIL_H - #include -#include #include +#include namespace MAYAUSD_NS_DEF { class MAYAUSD_UI_PUBLIC USDQtUtil : public IMayaMQtUtil { public: - ~USDQtUtil() override = default; + ~USDQtUtil() override = default; - int dpiScale(int size) const override; - float dpiScale(float size) const override; - QPixmap* createPixmap(const std::string& imageName) const override; + int dpiScale(int size) const override; + float dpiScale(float size) const override; + QPixmap* createPixmap(const std::string& imageName) const override; }; -} // namespace MayaUsd - +} // namespace MAYAUSD_NS_DEF #endif diff --git a/lib/usd/ui/api.h b/lib/usd/ui/api.h index 86e4a8fc65..c849193524 100644 --- a/lib/usd/ui/api.h +++ b/lib/usd/ui/api.h @@ -16,29 +16,28 @@ #if defined _WIN32 || defined __CYGWIN__ - // The main export symbol used for the UI library. - #ifdef MAYAUSD_UI_EXPORT - #ifdef __GNUC__ - #define MAYAUSD_UI_PUBLIC __attribute__ ((dllexport)) - #else - #define MAYAUSD_UI_PUBLIC __declspec(dllexport) - #endif - #else - #ifdef __GNUC__ - #define MAYAUSD_UI_PUBLIC __attribute__ ((dllimport)) - #else - #define MAYAUSD_UI_PUBLIC __declspec(dllimport) - #endif - #endif - #define MAYAUSD_UI_LOCAL - +// The main export symbol used for the UI library. +#ifdef MAYAUSD_UI_EXPORT +#ifdef __GNUC__ +#define MAYAUSD_UI_PUBLIC __attribute__((dllexport)) +#else +#define MAYAUSD_UI_PUBLIC __declspec(dllexport) +#endif #else - #if __GNUC__ >= 4 - #define MAYAUSD_UI_PUBLIC __attribute__ ((visibility ("default"))) - #define MAYAUSD_UI_LOCAL __attribute__ ((visibility ("hidden"))) +#ifdef __GNUC__ +#define MAYAUSD_UI_PUBLIC __attribute__((dllimport)) #else - #define MAYAUSD_UI_PUBLIC - #define MAYAUSD_UI_LOCAL +#define MAYAUSD_UI_PUBLIC __declspec(dllimport) #endif #endif +#define MAYAUSD_UI_LOCAL +#else +#if __GNUC__ >= 4 +#define MAYAUSD_UI_PUBLIC __attribute__((visibility("default"))) +#define MAYAUSD_UI_LOCAL __attribute__((visibility("hidden"))) +#else +#define MAYAUSD_UI_PUBLIC +#define MAYAUSD_UI_LOCAL +#endif +#endif diff --git a/lib/usd/ui/demo/testMayaUsdUI.cpp b/lib/usd/ui/demo/testMayaUsdUI.cpp index 519a05d7f4..8d2a730269 100644 --- a/lib/usd/ui/demo/testMayaUsdUI.cpp +++ b/lib/usd/ui/demo/testMayaUsdUI.cpp @@ -13,39 +13,32 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include -#include +#include + +#include #include #include #include - -#include - -#include - #include #include +#include +#include + class TestUIQtUtil : public MayaUsd::IMayaMQtUtil { public: - ~TestUIQtUtil() override = default; + ~TestUIQtUtil() override = default; - int dpiScale(int size) const override; - float dpiScale(float size) const override; - QPixmap* createPixmap(const std::string& imageName) const override; + int dpiScale(int size) const override; + float dpiScale(float size) const override; + QPixmap* createPixmap(const std::string& imageName) const override; }; -int TestUIQtUtil::dpiScale(int size) const -{ - return size; -} +int TestUIQtUtil::dpiScale(int size) const { return size; } -float TestUIQtUtil::dpiScale(float size) const -{ - return size; -} +float TestUIQtUtil::dpiScale(float size) const { return size; } QPixmap* TestUIQtUtil::createPixmap(const std::string& imageName) const { @@ -54,18 +47,21 @@ QPixmap* TestUIQtUtil::createPixmap(const std::string& imageName) const return new QPixmap(resName); } -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - if (argc < 2) - { - std::cout << "Usage: " << argv[0] << " " << std::endl; + if (argc < 2) { + std::cout << "Usage: " << argv[0] << " " + << std::endl; std::cout << std::endl; - std::cout << " Ex: " << argv[0] << "\"/Kitchen_set/Props_grp/DiningTable_grp/ChairB_2\" \"/Kitchen_set/Props_grp/North_grp/NorthWall_grp/NailA_1:modelingVariant=NailB\"" << std::endl; + std::cout + << " Ex: " << argv[0] + << "\"/Kitchen_set/Props_grp/DiningTable_grp/ChairB_2\" " + "\"/Kitchen_set/Props_grp/North_grp/NorthWall_grp/NailA_1:modelingVariant=NailB\"" + << std::endl; exit(EXIT_FAILURE); } - if (QProcessEnvironment::systemEnvironment().contains("MAYA_LOCATION")) - { + if (QProcessEnvironment::systemEnvironment().contains("MAYA_LOCATION")) { QString mayaLoc = QProcessEnvironment::systemEnvironment().value("MAYA_LOCATION"); QCoreApplication::addLibraryPath(mayaLoc + "\\plugins"); } @@ -80,27 +76,23 @@ int main(int argc, char *argv[]) // Set some import data for testing. MayaUsd::ImportData importData(usdFile); - if (argc >= 3) - { + if (argc >= 3) { std::string strRootPrimPath = argv[2]; importData.setRootPrimPath(strRootPrimPath); } - if (argc >= 4) - { - std::string strPrimVarSel = argv[3]; + if (argc >= 4) { + std::string strPrimVarSel = argv[3]; std::string::size_type pos1 = strPrimVarSel.find(':'); - if (pos1 != std::string::npos) - { - std::string strPrimPath = strPrimVarSel.substr(0, pos1); + if (pos1 != std::string::npos) { + std::string strPrimPath = strPrimVarSel.substr(0, pos1); std::string::size_type pos2 = strPrimVarSel.find('=', pos1); - if (pos2 != std::string::npos) - { - std::string strVarName = strPrimVarSel.substr(pos1+1, pos2-pos1-1); - std::string strVarSel = strPrimVarSel.substr(pos2+1); + if (pos2 != std::string::npos) { + std::string strVarName = strPrimVarSel.substr(pos1 + 1, pos2 - pos1 - 1); + std::string strVarSel = strPrimVarSel.substr(pos2 + 1); MayaUsd::ImportData::PrimVariantSelections primVarSels; - SdfVariantSelectionMap varSel; + SdfVariantSelectionMap varSel; varSel[strVarName] = strVarSel; primVarSels[SdfPath(strPrimPath)] = varSel; importData.setPrimVariantSelections(primVarSels); @@ -109,20 +101,23 @@ int main(int argc, char *argv[]) } // Create and show the ImportUI - TestUIQtUtil uiQtUtil; + TestUIQtUtil uiQtUtil; MayaUsd::USDImportDialog usdImportDialog(usdFile, &importData, uiQtUtil); // Give the dialog the Maya dark style. QStyle* adsk = app.style(); usdImportDialog.setStyle(adsk); QPalette newPal(adsk->standardPalette()); - newPal.setBrush(QPalette::Active, QPalette::AlternateBase, newPal.color(QPalette::Active, QPalette::Base).lighter(130)); + newPal.setBrush( + QPalette::Active, + QPalette::AlternateBase, + newPal.color(QPalette::Active, QPalette::Base).lighter(130)); usdImportDialog.setPalette(newPal); usdImportDialog.show(); - auto ret = app.exec(); - std::string rootPrimPath = usdImportDialog.rootPrimPath(); - UsdStagePopulationMask popMask = usdImportDialog.stagePopulationMask(); + auto ret = app.exec(); + std::string rootPrimPath = usdImportDialog.rootPrimPath(); + UsdStagePopulationMask popMask = usdImportDialog.stagePopulationMask(); MayaUsd::ImportData::PrimVariantSelections varSel = usdImportDialog.primVariantSelections(); return ret; diff --git a/lib/usd/utils/ALHalf.h b/lib/usd/utils/ALHalf.h index a26fa6562c..b549824ea7 100644 --- a/lib/usd/utils/ALHalf.h +++ b/lib/usd/utils/ALHalf.h @@ -15,12 +15,14 @@ // //---------------------------------------------------------------------------------------------------------------------- /// \file ALHalf.h -/// \brief The half <-> float conversions included within USD make use of a somewhat inefficient LUT to perform -/// conversion from half to float, and the float to half conversion requires quite a bit shifting and masking. -/// The Intel Ivy Bridge CPUs actually implemented float <-> conversions in hardware via the vcvtps2ph and -/// vcvtph2ps instructions (which convert 8 floats at a time with a latency of 4 or 5 cycles). This header file -/// provides some methods to convert between half/float and half/double using the F16C conversion intrinsics. -/// To enable HW conversions, pass the compiler flag -mf16c to clang or gcc. +/// \brief The half <-> float conversions included within USD make use of a somewhat inefficient +/// LUT to perform +/// conversion from half to float, and the float to half conversion requires quite a bit +/// shifting and masking. The Intel Ivy Bridge CPUs actually implemented float <-> +/// conversions in hardware via the vcvtps2ph and vcvtph2ps instructions (which convert 8 +/// floats at a time with a latency of 4 or 5 cycles). This header file provides some +/// methods to convert between half/float and half/double using the F16C conversion +/// intrinsics. To enable HW conversions, pass the compiler flag -mf16c to clang or gcc. //---------------------------------------------------------------------------------------------------------------------- #pragma once @@ -40,220 +42,205 @@ namespace MayaUsdUtils { /// converts 8xhalf to 8xfloat inline void half2float_8f(const GfHalf input[8], float out[8]) { - const __m128i a = _mm_loadu_si128((const __m128i*)input); - _mm256_storeu_ps(out, _mm256_cvtph_ps(a)); + const __m128i a = _mm_loadu_si128((const __m128i*)input); + _mm256_storeu_ps(out, _mm256_cvtph_ps(a)); } /// converts 4xhalf to 4xfloat inline void half2float_4f(const GfHalf input[4], float out[4]) { - const __m128i a = _mm_castpd_si128(_mm_load_sd((const double*)input)); - _mm_storeu_ps(out, _mm_cvtph_ps(a)); + const __m128i a = _mm_castpd_si128(_mm_load_sd((const double*)input)); + _mm_storeu_ps(out, _mm_cvtph_ps(a)); } /// converts a half to a float inline float half2float_1f(const GfHalf h) { - const __m128i a = _mm_set1_epi32(uint32_t(h.bits()) << 16 | h.bits()); - const __m128 f = _mm_cvtph_ps(a); - float r; - _mm_store_ss(&r, f); - return r; + const __m128i a = _mm_set1_epi32(uint32_t(h.bits()) << 16 | h.bits()); + const __m128 f = _mm_cvtph_ps(a); + float r; + _mm_store_ss(&r, f); + return r; } /// converts 8xhalf to 8xfloat inline void half2double_8f(const GfHalf input[8], double out[8]) { - const __m128i a = _mm_loadu_si128((const __m128i*)input); - const __m256 f = _mm256_cvtph_ps(a); - const __m256d flo = _mm256_cvtps_pd(_mm256_extractf128_ps(f, 0)); - const __m256d fhi = _mm256_cvtps_pd(_mm256_extractf128_ps(f, 1)); - _mm256_storeu_pd(out, flo); - _mm256_storeu_pd(out + 4, fhi); + const __m128i a = _mm_loadu_si128((const __m128i*)input); + const __m256 f = _mm256_cvtph_ps(a); + const __m256d flo = _mm256_cvtps_pd(_mm256_extractf128_ps(f, 0)); + const __m256d fhi = _mm256_cvtps_pd(_mm256_extractf128_ps(f, 1)); + _mm256_storeu_pd(out, flo); + _mm256_storeu_pd(out + 4, fhi); } /// converts 4xhalf to 4xfloat inline void half2double_4f(const GfHalf input[4], double out[4]) { - const __m128i a = _mm_castpd_si128(_mm_load_sd((const double*)input)); - _mm256_storeu_pd(out, _mm256_cvtps_pd(_mm_cvtph_ps(a))); + const __m128i a = _mm_castpd_si128(_mm_load_sd((const double*)input)); + _mm256_storeu_pd(out, _mm256_cvtps_pd(_mm_cvtph_ps(a))); } /// converts a half to a float inline double half2double_1f(const GfHalf h) { - const __m128i a = _mm_set1_epi32(uint32_t(h.bits()) << 16 | h.bits()); - const __m128 f = _mm_cvtph_ps(a); - float r; - _mm_store_ss(&r, f); - return double(r); + const __m128i a = _mm_set1_epi32(uint32_t(h.bits()) << 16 | h.bits()); + const __m128 f = _mm_cvtph_ps(a); + float r; + _mm_store_ss(&r, f); + return double(r); } /// converts 8xfloat to 8xhalf inline void float2half_8f(const float input[8], GfHalf out[8]) { - const __m256 a = _mm256_loadu_ps(input); - _mm_storeu_si128((__m128i*)out, _mm256_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION)); + const __m256 a = _mm256_loadu_ps(input); + _mm_storeu_si128((__m128i*)out, _mm256_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION)); } /// converts 4xfloat to 4xhalf inline void float2half_4f(const float input[4], GfHalf out[4]) { - const __m128 a = _mm_loadu_ps(input); - _mm_store_sd((double*)out, _mm_castsi128_pd(_mm_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION))); + const __m128 a = _mm_loadu_ps(input); + _mm_store_sd((double*)out, _mm_castsi128_pd(_mm_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION))); } /// converts a float to a half inline GfHalf float2half_1f(const float f) { - const __m128 a = _mm_load_ss(&f); - const __m128i b = _mm_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION); - const uint16_t i = _mm_extract_epi16(b, 0); - return *(const GfHalf*)(&i); + const __m128 a = _mm_load_ss(&f); + const __m128i b = _mm_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION); + const uint16_t i = _mm_extract_epi16(b, 0); + return *(const GfHalf*)(&i); } /// converts 8xdouble to 8xhalf inline void double2half_8f(const double input[8], GfHalf out[8]) { - const __m256d alo = _mm256_loadu_pd(input); - const __m256d ahi = _mm256_loadu_pd(input + 4); - const __m256 a = _mm256_insertf128_ps( - _mm256_castps128_ps256(_mm256_cvtpd_ps(alo)), - _mm256_cvtpd_ps(ahi), - 1); - _mm_storeu_si128((__m128i*)out, _mm256_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION)); + const __m256d alo = _mm256_loadu_pd(input); + const __m256d ahi = _mm256_loadu_pd(input + 4); + const __m256 a = _mm256_insertf128_ps( + _mm256_castps128_ps256(_mm256_cvtpd_ps(alo)), _mm256_cvtpd_ps(ahi), 1); + _mm_storeu_si128((__m128i*)out, _mm256_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION)); } /// converts 4xdouble to 4xhalf inline void double2half_4f(const double input[4], GfHalf out[4]) { - const __m128 a = _mm256_cvtpd_ps(_mm256_loadu_pd(input)); - _mm_store_sd((double*)out, _mm_castsi128_pd(_mm_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION))); + const __m128 a = _mm256_cvtpd_ps(_mm256_loadu_pd(input)); + _mm_store_sd((double*)out, _mm_castsi128_pd(_mm_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION))); } /// converts a double to a half inline GfHalf double2half_1f(const double f) { - const __m128d d = _mm_load_sd(&f); - const __m128 a = _mm_cvtpd_ps(d); - const __m128i b = _mm_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION); - const uint16_t i = _mm_extract_epi16(b, 0); - return *(const GfHalf*)(&i); + const __m128d d = _mm_load_sd(&f); + const __m128 a = _mm_cvtpd_ps(d); + const __m128i b = _mm_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION); + const uint16_t i = _mm_extract_epi16(b, 0); + return *(const GfHalf*)(&i); } #else /// converts 8xhalf to 8xfloat inline void half2float_8f(const GfHalf input[8], float out[8]) { - out[0] = float(input[0]); - out[1] = float(input[1]); - out[2] = float(input[2]); - out[3] = float(input[3]); - out[4] = float(input[4]); - out[5] = float(input[5]); - out[6] = float(input[6]); - out[7] = float(input[7]); + out[0] = float(input[0]); + out[1] = float(input[1]); + out[2] = float(input[2]); + out[3] = float(input[3]); + out[4] = float(input[4]); + out[5] = float(input[5]); + out[6] = float(input[6]); + out[7] = float(input[7]); } /// converts 4xhalf to 4xfloat inline void half2float_4f(const GfHalf input[4], float out[4]) { - out[0] = float(input[0]); - out[1] = float(input[1]); - out[2] = float(input[2]); - out[3] = float(input[3]); + out[0] = float(input[0]); + out[1] = float(input[1]); + out[2] = float(input[2]); + out[3] = float(input[3]); } /// convert half to float -inline float half2float_1f(const GfHalf h) -{ - return float(h); -} +inline float half2float_1f(const GfHalf h) { return float(h); } /// converts 8xhalf to 8xfloat inline void half2double_8f(const GfHalf input[8], double out[8]) { - out[0] = double(float(input[0])); - out[1] = double(float(input[1])); - out[2] = double(float(input[2])); - out[3] = double(float(input[3])); - out[4] = double(float(input[4])); - out[5] = double(float(input[5])); - out[6] = double(float(input[6])); - out[7] = double(float(input[7])); + out[0] = double(float(input[0])); + out[1] = double(float(input[1])); + out[2] = double(float(input[2])); + out[3] = double(float(input[3])); + out[4] = double(float(input[4])); + out[5] = double(float(input[5])); + out[6] = double(float(input[6])); + out[7] = double(float(input[7])); } /// converts 4xhalf to 4xfloat inline void half2double_4f(const GfHalf input[4], double out[4]) { - out[0] = double(float(input[0])); - out[1] = double(float(input[1])); - out[2] = double(float(input[2])); - out[3] = double(float(input[3])); + out[0] = double(float(input[0])); + out[1] = double(float(input[1])); + out[2] = double(float(input[2])); + out[3] = double(float(input[3])); } /// convert half to float -inline double half2fdouble_1f(const GfHalf h) -{ - return double(float(h)); -} +inline double half2fdouble_1f(const GfHalf h) { return double(float(h)); } /// converts 8xfloat to 8xhalf inline void float2half_8f(const float input[8], GfHalf out[8]) { - out[0] = GfHalf(input[0]); - out[1] = GfHalf(input[1]); - out[2] = GfHalf(input[2]); - out[3] = GfHalf(input[3]); - out[4] = GfHalf(input[4]); - out[5] = GfHalf(input[5]); - out[6] = GfHalf(input[6]); - out[7] = GfHalf(input[7]); + out[0] = GfHalf(input[0]); + out[1] = GfHalf(input[1]); + out[2] = GfHalf(input[2]); + out[3] = GfHalf(input[3]); + out[4] = GfHalf(input[4]); + out[5] = GfHalf(input[5]); + out[6] = GfHalf(input[6]); + out[7] = GfHalf(input[7]); } /// converts 4xfloat to 4xhalf inline void float2half_4f(const float input[4], GfHalf out[4]) { - out[0] = GfHalf(input[0]); - out[1] = GfHalf(input[1]); - out[2] = GfHalf(input[2]); - out[3] = GfHalf(input[3]); + out[0] = GfHalf(input[0]); + out[1] = GfHalf(input[1]); + out[2] = GfHalf(input[2]); + out[3] = GfHalf(input[3]); } /// converts a float to a half -inline GfHalf float2half_1f(const float f) -{ - return GfHalf(f); -} +inline GfHalf float2half_1f(const float f) { return GfHalf(f); } /// converts 8xdouble to 8xhalf inline void double2half_8f(const double input[8], GfHalf out[8]) { - out[0] = GfHalf(float(input[0])); - out[1] = GfHalf(float(input[1])); - out[2] = GfHalf(float(input[2])); - out[3] = GfHalf(float(input[3])); - out[4] = GfHalf(float(input[4])); - out[5] = GfHalf(float(input[5])); - out[6] = GfHalf(float(input[6])); - out[7] = GfHalf(float(input[7])); + out[0] = GfHalf(float(input[0])); + out[1] = GfHalf(float(input[1])); + out[2] = GfHalf(float(input[2])); + out[3] = GfHalf(float(input[3])); + out[4] = GfHalf(float(input[4])); + out[5] = GfHalf(float(input[5])); + out[6] = GfHalf(float(input[6])); + out[7] = GfHalf(float(input[7])); } /// converts 4xdouble to 4xhalf inline void double2half_4f(const double input[4], GfHalf out[4]) { - out[0] = GfHalf(float(input[0])); - out[1] = GfHalf(float(input[1])); - out[2] = GfHalf(float(input[2])); - out[3] = GfHalf(float(input[3])); + out[0] = GfHalf(float(input[0])); + out[1] = GfHalf(float(input[1])); + out[2] = GfHalf(float(input[2])); + out[3] = GfHalf(float(input[3])); } /// converts a double to a half -inline GfHalf double2half_1f(const double f) -{ - return GfHalf(float(f)); -} +inline GfHalf double2half_1f(const double f) { return GfHalf(float(f)); } #endif -} // MayaUsdUtils - +} // namespace MayaUsdUtils diff --git a/lib/usd/utils/Api.h b/lib/usd/utils/Api.h index 90393aa6e3..0b938af262 100644 --- a/lib/usd/utils/Api.h +++ b/lib/usd/utils/Api.h @@ -15,26 +15,26 @@ // #if defined _WIN32 || defined __CYGWIN__ - #ifdef MAYA_USD_UTILS_EXPORT - #ifdef __GNUC__ - #define MAYA_USD_UTILS_PUBLIC __attribute__ ((dllexport)) - #else - #define MAYA_USD_UTILS_PUBLIC __declspec(dllexport) - #endif - #else - #ifdef __GNUC__ - #define MAYA_USD_UTILS_PUBLIC __attribute__ ((dllimport)) - #else - #define MAYA_USD_UTILS_PUBLIC __declspec(dllimport) - #endif - #endif - #define MAYA_USD_UTILS_LOCAL +#ifdef MAYA_USD_UTILS_EXPORT +#ifdef __GNUC__ +#define MAYA_USD_UTILS_PUBLIC __attribute__((dllexport)) #else - #if __GNUC__ >= 4 - #define MAYA_USD_UTILS_PUBLIC __attribute__ ((visibility ("default"))) - #define MAYA_USD_UTILS_LOCAL __attribute__ ((visibility ("hidden"))) - #else - #define MAYA_USD_UTILS_PUBLIC - #define MAYA_USD_UTILS_LOCAL - #endif +#define MAYA_USD_UTILS_PUBLIC __declspec(dllexport) +#endif +#else +#ifdef __GNUC__ +#define MAYA_USD_UTILS_PUBLIC __attribute__((dllimport)) +#else +#define MAYA_USD_UTILS_PUBLIC __declspec(dllimport) +#endif +#endif +#define MAYA_USD_UTILS_LOCAL +#else +#if __GNUC__ >= 4 +#define MAYA_USD_UTILS_PUBLIC __attribute__((visibility("default"))) +#define MAYA_USD_UTILS_LOCAL __attribute__((visibility("hidden"))) +#else +#define MAYA_USD_UTILS_PUBLIC +#define MAYA_USD_UTILS_LOCAL +#endif #endif \ No newline at end of file diff --git a/lib/usd/utils/DebugCodes.cpp b/lib/usd/utils/DebugCodes.cpp index 68c2c67f5c..d050cbd146 100644 --- a/lib/usd/utils/DebugCodes.cpp +++ b/lib/usd/utils/DebugCodes.cpp @@ -15,14 +15,14 @@ // #include "DebugCodes.h" -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE TF_REGISTRY_FUNCTION(TfDebug) { - TF_DEBUG_ENVIRONMENT_SYMBOL(MAYAUSDUTILS_INFO, "MAYAUSDUTILS' General debug messages"); + TF_DEBUG_ENVIRONMENT_SYMBOL(MAYAUSDUTILS_INFO, "MAYAUSDUTILS' General debug messages"); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/lib/usd/utils/DebugCodes.h b/lib/usd/utils/DebugCodes.h index 600eb5922d..e2d81d06a7 100644 --- a/lib/usd/utils/DebugCodes.h +++ b/lib/usd/utils/DebugCodes.h @@ -15,8 +15,8 @@ // #pragma once -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE TF_DEBUG_CODES(MAYAUSDUTILS_INFO); diff --git a/lib/usd/utils/DiffCore.cpp b/lib/usd/utils/DiffCore.cpp index 04532055df..5f6e0ede31 100644 --- a/lib/usd/utils/DiffCore.cpp +++ b/lib/usd/utils/DiffCore.cpp @@ -15,356 +15,305 @@ // #include "DiffCore.h" -#include -#include - #include +#include +#include + namespace MayaUsdUtils { //---------------------------------------------------------------------------------------------------------------------- bool vec2AreAllTheSame(const float* u, const float* v, size_t count) { - // if already at the end of the array, we're done - if(count <= 1) - { - return true; - } + // if already at the end of the array, we're done + if (count <= 1) { + return true; + } #ifdef __AVX2__ - const f256 u8 = splat8f(u[0]); - const f256 v8 = splat8f(v[0]); - - const size_t count8 = count & ~7ULL; - for(size_t i = 0; i < count8; i += 8) - { - const f256 uu = loadu8f(u + i); - const f256 vv = loadu8f(v + i); - const f256 cmpu = cmpne8f(uu, u8); - const f256 cmpv = cmpne8f(vv, v8); - if(movemask8f(or8f(cmpu, cmpv))) - return false; - } - - for(size_t i = count8; i < count; ++i) - { - if(u[i] != u[0] || v[i] != v[0]) - return false; - } - return true; + const f256 u8 = splat8f(u[0]); + const f256 v8 = splat8f(v[0]); + + const size_t count8 = count & ~7ULL; + for (size_t i = 0; i < count8; i += 8) { + const f256 uu = loadu8f(u + i); + const f256 vv = loadu8f(v + i); + const f256 cmpu = cmpne8f(uu, u8); + const f256 cmpv = cmpne8f(vv, v8); + if (movemask8f(or8f(cmpu, cmpv))) + return false; + } + + for (size_t i = count8; i < count; ++i) { + if (u[i] != u[0] || v[i] != v[0]) + return false; + } + return true; #elif defined(__SSE__) - const f128 u4 = splat4f(u[0]); - const f128 v4 = splat4f(v[0]); - - const size_t count4 = count & ~3ULL; - for(size_t i = 0; i < count4; i += 4) - { - const f128 uu = loadu4f(u + i); - const f128 vv = loadu4f(v + i); - const f128 cmpu = cmpne4f(uu, u4); - const f128 cmpv = cmpne4f(vv, v4); - if(movemask4f(or4f(cmpu, cmpv))) - return false; - } - - for(size_t i = count4; i < count; ++i) - { - if(u[i] != u[0] || v[i] != v[0]) - return false; - } - return true; + const f128 u4 = splat4f(u[0]); + const f128 v4 = splat4f(v[0]); + + const size_t count4 = count & ~3ULL; + for (size_t i = 0; i < count4; i += 4) { + const f128 uu = loadu4f(u + i); + const f128 vv = loadu4f(v + i); + const f128 cmpu = cmpne4f(uu, u4); + const f128 cmpv = cmpne4f(vv, v4); + if (movemask4f(or4f(cmpu, cmpv))) + return false; + } + + for (size_t i = count4; i < count; ++i) { + if (u[i] != u[0] || v[i] != v[0]) + return false; + } + return true; #else - for(size_t i = 1; i < count; ++i) - { - if(u[0] != u[i] || v[0] != v[i]) - return false; - } - return true; + for (size_t i = 1; i < count; ++i) { + if (u[0] != u[i] || v[0] != v[i]) + return false; + } + return true; #endif - } //---------------------------------------------------------------------------------------------------------------------- bool vec2AreAllTheSame(const float* array, size_t count) { - // if already at the end of the array, we're done - if(count <= 1) - { - return true; - } + // if already at the end of the array, we're done + if (count <= 1) { + return true; + } #ifdef __AVX2__ - const float x = array[0]; - const float y = array[1]; - const f256 xy = set8f(x, y, x, y, x, y, x, y); - size_t count4 = count & ~3ULL; - for(size_t i = 0, n = count4 * 2; i < n; i += 8) - { - const f256 temp = loadu8f(array + i); - const f256 cmp = cmpne8f(temp, xy); - if(movemask8f(cmp)) - return false; - } - if(count & 2) - { - const f128 temp = loadu4f(array + count4 * 2); - const f128 cmp = cmpne4f(temp, cast4f(xy)); - if(movemask4f(cmp)) - return false; - count4 += 2; - } - if(count & 1) - { - const float nx = array[count4 * 2]; - const float ny = array[count4 * 2 + 1]; - if(nx != x || ny != y) - return false; - } - return true; + const float x = array[0]; + const float y = array[1]; + const f256 xy = set8f(x, y, x, y, x, y, x, y); + size_t count4 = count & ~3ULL; + for (size_t i = 0, n = count4 * 2; i < n; i += 8) { + const f256 temp = loadu8f(array + i); + const f256 cmp = cmpne8f(temp, xy); + if (movemask8f(cmp)) + return false; + } + if (count & 2) { + const f128 temp = loadu4f(array + count4 * 2); + const f128 cmp = cmpne4f(temp, cast4f(xy)); + if (movemask4f(cmp)) + return false; + count4 += 2; + } + if (count & 1) { + const float nx = array[count4 * 2]; + const float ny = array[count4 * 2 + 1]; + if (nx != x || ny != y) + return false; + } + return true; #elif defined(__SSE__) - const float x = array[0]; - const float y = array[1]; - const f128 xy = set4f(x, y, x, y); - const size_t count2 = count & ~1ULL; - for(size_t i = 0, n = count2 * 2; i < n; i += 4) - { - const f128 temp = loadu4f(array + i); - const f128 cmp = cmpne4f(temp, xy); - if(movemask4f(cmp)) - return false; - } - if(count & 1) - { - const float nx = array[count2 * 2]; - const float ny = array[count2 * 2 + 1]; - if(nx != x || ny != y) - return false; - } - return true; + const float x = array[0]; + const float y = array[1]; + const f128 xy = set4f(x, y, x, y); + const size_t count2 = count & ~1ULL; + for (size_t i = 0, n = count2 * 2; i < n; i += 4) { + const f128 temp = loadu4f(array + i); + const f128 cmp = cmpne4f(temp, xy); + if (movemask4f(cmp)) + return false; + } + if (count & 1) { + const float nx = array[count2 * 2]; + const float ny = array[count2 * 2 + 1]; + if (nx != x || ny != y) + return false; + } + return true; #else - const float x = array[0]; - const float y = array[1]; - for(size_t i = 2, n = count * 2; i < n; i += 2) - { - if(x != array[i] || y != array[i + 1]) - { - return false; - } - } - return true; + const float x = array[0]; + const float y = array[1]; + for (size_t i = 2, n = count * 2; i < n; i += 2) { + if (x != array[i] || y != array[i + 1]) { + return false; + } + } + return true; #endif } //---------------------------------------------------------------------------------------------------------------------- bool vec3AreAllTheSame(const float* array, size_t count) { - // if already at the end of the array, we're done - if(count <= 1) - { - return true; - } + // if already at the end of the array, we're done + if (count <= 1) { + return true; + } #ifdef __AVX2__ - const float x = array[0]; - const float y = array[1]; - const float z = array[2]; - - // test the first 8 in the array - for(int32_t i = 3, n = 3 * std::min(size_t(8), count); i < n; i += 3) - { - if(x != array[i] || - y != array[i + 1] || - z != array[i + 2]) - return false; - } - // if already at the end of the array, we're done - if(count <= 8) - { - return true; - } - - // load 8 vec3s - const f256 first8[3] = { - loadu8f(array + 0), - loadu8f(array + 8), - loadu8f(array + 16) - }; - - // now test groups of 8 x 3D vectors - size_t count8 = count & ~7ULL; - for(int32_t i = 3 * 8, n = 3 * count8; i < n; i += 3 * 8) - { - const f256 a = loadu8f(array + i + 0); - const f256 b = loadu8f(array + i + 8); - const f256 c = loadu8f(array + i + 16); - const f256 cmpa = cmpne8f(first8[0], a); - const f256 cmpb = cmpne8f(first8[1], b); - const f256 cmpc = cmpne8f(first8[2], c); - const f256 cmp = or8f(or8f(cmpa, cmpb), cmpc); - if(movemask8f(cmp)) - return false; - } - - // now test a final group of 4 x 3D vectors - if(count & 4) - { - const f128 a = loadu4f(array + 3 * count8 + 0); - const f128 b = loadu4f(array + 3 * count8 + 4); - const f128 c = loadu4f(array + 3 * count8 + 8); - const f128 cmpa = cmpne4f(extract4f(first8[0], 0), a); - const f128 cmpb = cmpne4f(extract4f(first8[0], 1), b); - const f128 cmpc = cmpne4f(extract4f(first8[1], 0), c); - const f128 cmp = or4f(or4f(cmpa, cmpb), cmpc); - if(movemask4f(cmp)) - return false; - count8 += 4; - } - - // and now the remaining three - if(count & 3) - { - for(int i = 3 * count8, n = 3 * count; i < n; i += 3) - { - if(x != array[i] || - y != array[i + 1] || - z != array[i + 2]) - { - return false; - } + const float x = array[0]; + const float y = array[1]; + const float z = array[2]; + + // test the first 8 in the array + for (int32_t i = 3, n = 3 * std::min(size_t(8), count); i < n; i += 3) { + if (x != array[i] || y != array[i + 1] || z != array[i + 2]) + return false; + } + // if already at the end of the array, we're done + if (count <= 8) { + return true; } - } - return true; -#elif defined(__SSE__) + // load 8 vec3s + const f256 first8[3] = { loadu8f(array + 0), loadu8f(array + 8), loadu8f(array + 16) }; + + // now test groups of 8 x 3D vectors + size_t count8 = count & ~7ULL; + for (int32_t i = 3 * 8, n = 3 * count8; i < n; i += 3 * 8) { + const f256 a = loadu8f(array + i + 0); + const f256 b = loadu8f(array + i + 8); + const f256 c = loadu8f(array + i + 16); + const f256 cmpa = cmpne8f(first8[0], a); + const f256 cmpb = cmpne8f(first8[1], b); + const f256 cmpc = cmpne8f(first8[2], c); + const f256 cmp = or8f(or8f(cmpa, cmpb), cmpc); + if (movemask8f(cmp)) + return false; + } - const float x = array[0]; - const float y = array[1]; - const float z = array[2]; - - // test the first 8 in the array - for(int32_t i = 3, n = 3 * std::min(size_t(4), count); i < n; i += 3) - { - if(x != array[i] || - y != array[i + 1] || - z != array[i + 2]) - return false; - } - // if already at the end of the array, we're done - if(count <= 4) - { + // now test a final group of 4 x 3D vectors + if (count & 4) { + const f128 a = loadu4f(array + 3 * count8 + 0); + const f128 b = loadu4f(array + 3 * count8 + 4); + const f128 c = loadu4f(array + 3 * count8 + 8); + const f128 cmpa = cmpne4f(extract4f(first8[0], 0), a); + const f128 cmpb = cmpne4f(extract4f(first8[0], 1), b); + const f128 cmpc = cmpne4f(extract4f(first8[1], 0), c); + const f128 cmp = or4f(or4f(cmpa, cmpb), cmpc); + if (movemask4f(cmp)) + return false; + count8 += 4; + } + + // and now the remaining three + if (count & 3) { + for (int i = 3 * count8, n = 3 * count; i < n; i += 3) { + if (x != array[i] || y != array[i + 1] || z != array[i + 2]) { + return false; + } + } + } return true; - } - - // load 8 vec3s - const f128 first4[3] = { - loadu4f(array + 0), - loadu4f(array + 4), - loadu4f(array + 8) - }; - - // now test groups of 8 x 3D vectors - const size_t count4 = count & ~3ULL; - for(int32_t i = 3 * 4, n = 3 * count4; i < n; i += 3 * 4) - { - const f128 a = loadu4f(array + i + 0); - const f128 b = loadu4f(array + i + 4); - const f128 c = loadu4f(array + i + 8); - const f128 cmpa = cmpne4f(first4[0], a); - const f128 cmpb = cmpne4f(first4[1], b); - const f128 cmpc = cmpne4f(first4[2], c); - const f128 cmp = or4f(or4f(cmpa, cmpb), cmpc); - if(movemask4f(cmp)) - return false; - } - - // and now the remaining three - if(count & 3) - { - for(int i = 3 * count4, n = 3 * count; i < n; i += 3) - { - if(x != array[i] || y != array[i + 1] || z != array[i + 2]) - { - return false; - } + +#elif defined(__SSE__) + + const float x = array[0]; + const float y = array[1]; + const float z = array[2]; + + // test the first 8 in the array + for (int32_t i = 3, n = 3 * std::min(size_t(4), count); i < n; i += 3) { + if (x != array[i] || y != array[i + 1] || z != array[i + 2]) + return false; + } + // if already at the end of the array, we're done + if (count <= 4) { + return true; + } + + // load 8 vec3s + const f128 first4[3] = { loadu4f(array + 0), loadu4f(array + 4), loadu4f(array + 8) }; + + // now test groups of 8 x 3D vectors + const size_t count4 = count & ~3ULL; + for (int32_t i = 3 * 4, n = 3 * count4; i < n; i += 3 * 4) { + const f128 a = loadu4f(array + i + 0); + const f128 b = loadu4f(array + i + 4); + const f128 c = loadu4f(array + i + 8); + const f128 cmpa = cmpne4f(first4[0], a); + const f128 cmpb = cmpne4f(first4[1], b); + const f128 cmpc = cmpne4f(first4[2], c); + const f128 cmp = or4f(or4f(cmpa, cmpb), cmpc); + if (movemask4f(cmp)) + return false; } - } - return true; + + // and now the remaining three + if (count & 3) { + for (int i = 3 * count4, n = 3 * count; i < n; i += 3) { + if (x != array[i] || y != array[i + 1] || z != array[i + 2]) { + return false; + } + } + } + return true; #else - const float x = array[0]; - const float y = array[1]; - const float z = array[2]; - for(size_t i = 3, n = count * 3; i < n; i += 3) - { - if(x != array[i] || y != array[i + 1] || z != array[i + 2]) - { - return false; - } - } - return true; + const float x = array[0]; + const float y = array[1]; + const float z = array[2]; + for (size_t i = 3, n = count * 3; i < n; i += 3) { + if (x != array[i] || y != array[i + 1] || z != array[i + 2]) { + return false; + } + } + return true; #endif } //---------------------------------------------------------------------------------------------------------------------- bool vec4AreAllTheSame(const float* array, size_t count) { - // if already at the end of the array, we're done - if(count <= 1) - { - return true; - } + // if already at the end of the array, we're done + if (count <= 1) { + return true; + } #ifdef __AVX2__ - const f128 first = load4f(array + 0); - const f256 pair = set8f(first, first); - - const size_t count2 = count & ~1ULL; - for(size_t i = 0, n = count2 * 4; i < n; i += 8) - { - const f256 temp = loadu8f(array + i); - const f256 cmp = cmpne8f(temp, pair); - if(movemask8f(cmp)) - return false; - } - if(count & 1) - { - const f128 temp = loadu4f(array + (count2 << 2)); - const f128 cmp = cmpne4f(temp, cast4f(pair)); - if(movemask4f(cmp)) - return false; - } - return true; + const f128 first = load4f(array + 0); + const f256 pair = set8f(first, first); + + const size_t count2 = count & ~1ULL; + for (size_t i = 0, n = count2 * 4; i < n; i += 8) { + const f256 temp = loadu8f(array + i); + const f256 cmp = cmpne8f(temp, pair); + if (movemask8f(cmp)) + return false; + } + if (count & 1) { + const f128 temp = loadu4f(array + (count2 << 2)); + const f128 cmp = cmpne4f(temp, cast4f(pair)); + if (movemask4f(cmp)) + return false; + } + return true; #elif defined(__SSE__) - const f128 first = load4f(array + 0); - for(size_t i = 4, n = count * 4; i < n; i += 4) - { - const f128 temp = loadu4f(array + i); - const f128 cmp = cmpne4f(temp, first); - if(movemask4f(cmp)) - return false; - } - return true; + const f128 first = load4f(array + 0); + for (size_t i = 4, n = count * 4; i < n; i += 4) { + const f128 temp = loadu4f(array + i); + const f128 cmp = cmpne4f(temp, first); + if (movemask4f(cmp)) + return false; + } + return true; #else - const float x = array[0]; - const float y = array[1]; - const float z = array[2]; - const float w = array[3]; - for(size_t i = 4, n = count * 4; i < n; i += 4) - { - if(x != array[i] || y != array[i + 1] || z != array[i + 2] || w != array[i + 3]) - { - return false; - } - } - return true; + const float x = array[0]; + const float y = array[1]; + const float z = array[2]; + const float w = array[3]; + for (size_t i = 4, n = count * 4; i < n; i += 4) { + if (x != array[i] || y != array[i + 1] || z != array[i + 2] || w != array[i + 3]) { + return false; + } + } + return true; #endif } @@ -372,55 +321,49 @@ bool vec4AreAllTheSame(const float* array, size_t count) bool vec2AreAllTheSame(const double* array, size_t count) { - // if already at the end of the array, we're done - if(count <= 1) - { - return true; - } + // if already at the end of the array, we're done + if (count <= 1) { + return true; + } #ifdef __AVX2__ - const d128 xy = loadu2d(array); - const d256 xyxy = set4d(xy, xy); - const size_t count2 = count & ~1ULL; - for(size_t i = 0, n = count2 * 2; i < n; i += 4) - { - const d256 temp = loadu4d(array + i); - const d256 cmp = cmpne4d(temp, xyxy); - if(movemask4d(cmp)) - return false; - } - if(count & 1) - { - const d128 temp = loadu2d(array + count2 * 2); - const d128 cmp = cmpne2d(temp, xy); - if(movemask2d(cmp)) - return false; - } - return true; + const d128 xy = loadu2d(array); + const d256 xyxy = set4d(xy, xy); + const size_t count2 = count & ~1ULL; + for (size_t i = 0, n = count2 * 2; i < n; i += 4) { + const d256 temp = loadu4d(array + i); + const d256 cmp = cmpne4d(temp, xyxy); + if (movemask4d(cmp)) + return false; + } + if (count & 1) { + const d128 temp = loadu2d(array + count2 * 2); + const d128 cmp = cmpne2d(temp, xy); + if (movemask2d(cmp)) + return false; + } + return true; #elif defined(__SSE__) - const d128 xy = loadu2d(array); - for(size_t i = 2, n = count * 2; i < n; i += 2) - { - const d128 temp = loadu2d(array + i); - const d128 cmp = cmpne2d(temp, xy); - if(movemask2d(cmp)) - return false; - } - return true; + const d128 xy = loadu2d(array); + for (size_t i = 2, n = count * 2; i < n; i += 2) { + const d128 temp = loadu2d(array + i); + const d128 cmp = cmpne2d(temp, xy); + if (movemask2d(cmp)) + return false; + } + return true; #else - const double x = array[0]; - const double y = array[1]; - for(size_t i = 2, n = count * 2; i < n; i += 2) - { - if(x != array[i] || y != array[i + 1]) - { - return false; - } - } - return true; + const double x = array[0]; + const double y = array[1]; + for (size_t i = 2, n = count * 2; i < n; i += 2) { + if (x != array[i] || y != array[i + 1]) { + return false; + } + } + return true; #endif } @@ -428,259 +371,222 @@ bool vec2AreAllTheSame(const double* array, size_t count) bool vec3AreAllTheSame(const double* array, size_t count) { - // if already at the end of the array, we're done - if(count <= 1) - { - return true; - } + // if already at the end of the array, we're done + if (count <= 1) { + return true; + } #ifdef __AVX2__ - const double x = array[0]; - const double y = array[1]; - const double z = array[2]; - - // test the first 4 in the array - for(int32_t i = 3, n = 3 * std::min(size_t(4), count); i < n; i += 3) - { - if(x != array[i] || - y != array[i + 1] || - z != array[i + 2]) - return false; - } - // if already at the end of the array, we're done - if(count <= 4) - { - return true; - } - - // load 8 vec3s - const d256 first4[3] = { - loadu4d(array + 0), - loadu4d(array + 4), - loadu4d(array + 8) - }; - - // now test groups of 8 x 3D vectors - const size_t count4 = count & ~3ULL; - for(int32_t i = 3 * 4, n = 3 * count4; i < n; i += 3 * 4) - { - const d256 a = loadu4d(array + i + 0); - const d256 b = loadu4d(array + i + 4); - const d256 c = loadu4d(array + i + 8); - const d256 cmpa = cmpne4d(first4[0], a); - const d256 cmpb = cmpne4d(first4[1], b); - const d256 cmpc = cmpne4d(first4[2], c); - const d256 cmp = or4d(or4d(cmpa, cmpb), cmpc); - if(movemask4d(cmp)) - return false; - } - - // and now the remaining three - if(count & 3) - { - for(int i = 3 * count4, n = 3 * count; i < n; i += 3) - { - if(x != array[i] || y != array[i + 1] || z != array[i + 2]) - { - return false; - } + const double x = array[0]; + const double y = array[1]; + const double z = array[2]; + + // test the first 4 in the array + for (int32_t i = 3, n = 3 * std::min(size_t(4), count); i < n; i += 3) { + if (x != array[i] || y != array[i + 1] || z != array[i + 2]) + return false; } - } - return true; + // if already at the end of the array, we're done + if (count <= 4) { + return true; + } + + // load 8 vec3s + const d256 first4[3] = { loadu4d(array + 0), loadu4d(array + 4), loadu4d(array + 8) }; + + // now test groups of 8 x 3D vectors + const size_t count4 = count & ~3ULL; + for (int32_t i = 3 * 4, n = 3 * count4; i < n; i += 3 * 4) { + const d256 a = loadu4d(array + i + 0); + const d256 b = loadu4d(array + i + 4); + const d256 c = loadu4d(array + i + 8); + const d256 cmpa = cmpne4d(first4[0], a); + const d256 cmpb = cmpne4d(first4[1], b); + const d256 cmpc = cmpne4d(first4[2], c); + const d256 cmp = or4d(or4d(cmpa, cmpb), cmpc); + if (movemask4d(cmp)) + return false; + } + + // and now the remaining three + if (count & 3) { + for (int i = 3 * count4, n = 3 * count; i < n; i += 3) { + if (x != array[i] || y != array[i + 1] || z != array[i + 2]) { + return false; + } + } + } + return true; #elif defined(__SSE__) - const double x = array[0]; - const double y = array[1]; - const double z = array[2]; + const double x = array[0]; + const double y = array[1]; + const double z = array[2]; + + // test the first 2 in the array + if (x != array[3] || y != array[4] || z != array[5]) + return false; - // test the first 2 in the array - if(x != array[3] || - y != array[4] || - z != array[5]) - return false; + // if already at the end of the array, we're done + if (count <= 2) { + return true; + } + + // load 8 vec3s + const d128 first4[3] = { loadu2d(array + 0), loadu2d(array + 2), loadu2d(array + 4) }; + + // now test groups of 8 x 3D vectors + const size_t count2 = count & ~1ULL; + for (int32_t i = 3 * 2, n = 3 * count2; i < n; i += 3 * 2) { + const d128 a = loadu2d(array + i + 0); + const d128 b = loadu2d(array + i + 2); + const d128 c = loadu2d(array + i + 4); + const d128 cmpa = cmpne2d(first4[0], a); + const d128 cmpb = cmpne2d(first4[1], b); + const d128 cmpc = cmpne2d(first4[2], c); + const d128 cmp = or2d(or2d(cmpa, cmpb), cmpc); + if (movemask2d(cmp)) + return false; + } - // if already at the end of the array, we're done - if(count <= 2) - { + // and now the remaining three + if (count & 1) { + if (x != array[count2 * 3] || y != array[count2 * 3 + 1] || z != array[count2 * 3 + 2]) { + return false; + } + } return true; - } - - // load 8 vec3s - const d128 first4[3] = { - loadu2d(array + 0), - loadu2d(array + 2), - loadu2d(array + 4) - }; - - // now test groups of 8 x 3D vectors - const size_t count2 = count & ~1ULL; - for(int32_t i = 3 * 2, n = 3 * count2; i < n; i += 3 * 2) - { - const d128 a = loadu2d(array + i + 0); - const d128 b = loadu2d(array + i + 2); - const d128 c = loadu2d(array + i + 4); - const d128 cmpa = cmpne2d(first4[0], a); - const d128 cmpb = cmpne2d(first4[1], b); - const d128 cmpc = cmpne2d(first4[2], c); - const d128 cmp = or2d(or2d(cmpa, cmpb), cmpc); - if(movemask2d(cmp)) - return false; - } - - // and now the remaining three - if(count & 1) - { - if(x != array[count2*3] || y != array[count2*3 + 1] || z != array[count2*3 + 2]) - { - return false; - } - } - return true; #else - const double x = array[0]; - const double y = array[1]; - const double z = array[2]; - for(size_t i = 3, n = count * 3; i < n; i += 3) - { - if(x != array[i] || y != array[i + 1] || z != array[i + 2]) - { - return false; - } - } - return true; + const double x = array[0]; + const double y = array[1]; + const double z = array[2]; + for (size_t i = 3, n = count * 3; i < n; i += 3) { + if (x != array[i] || y != array[i + 1] || z != array[i + 2]) { + return false; + } + } + return true; #endif } //---------------------------------------------------------------------------------------------------------------------- bool vec4AreAllTheSame(const double* array, size_t count) { - // if already at the end of the array, we're done - if(count <= 1) - { - return true; - } + // if already at the end of the array, we're done + if (count <= 1) { + return true; + } #ifdef __AVX2__ - const d256 first = loadu4d(array + 0); - for(size_t i = 4, n = count * 4; i < n; i += 4) - { - const d256 temp = loadu4d(array + i); - const d256 cmp = cmpne4d(temp, first); - if(movemask4d(cmp)) - return false; - } - return true; + const d256 first = loadu4d(array + 0); + for (size_t i = 4, n = count * 4; i < n; i += 4) { + const d256 temp = loadu4d(array + i); + const d256 cmp = cmpne4d(temp, first); + if (movemask4d(cmp)) + return false; + } + return true; #elif defined(__SSE__) - const d128 xy = loadu2d(array + 0); - const d128 zw = loadu2d(array + 2); - for(size_t i = 4, n = count * 4; i < n; i += 4) - { - const d128 tempxy = loadu2d(array + i); - const d128 tempzw = loadu2d(array + i + 2); - const d128 cmpxy = cmpne2d(tempxy, xy); - const d128 cmpzw = cmpne2d(tempzw, zw); - if(movemask2d(or2d(cmpxy, cmpzw))) - return false; - } - return true; + const d128 xy = loadu2d(array + 0); + const d128 zw = loadu2d(array + 2); + for (size_t i = 4, n = count * 4; i < n; i += 4) { + const d128 tempxy = loadu2d(array + i); + const d128 tempzw = loadu2d(array + i + 2); + const d128 cmpxy = cmpne2d(tempxy, xy); + const d128 cmpzw = cmpne2d(tempzw, zw); + if (movemask2d(or2d(cmpxy, cmpzw))) + return false; + } + return true; #else - const double x = array[0]; - const double y = array[1]; - const double z = array[2]; - const double w = array[3]; - for(size_t i = 4, n = count * 4; i < n; i += 4) - { - if(x != array[i] || y != array[i + 1] || z != array[i + 2] || w != array[i + 3]) - { - return false; - } - } - return true; + const double x = array[0]; + const double y = array[1]; + const double z = array[2]; + const double w = array[3]; + for (size_t i = 4, n = count * 4; i < n; i += 4) { + if (x != array[i] || y != array[i + 1] || z != array[i + 2] || w != array[i + 3]) { + return false; + } + } + return true; #endif } //---------------------------------------------------------------------------------------------------------------------- bool compareArray( const GfHalf* const input0, - const float* const input1, - const size_t count0, - const size_t count1, - const float eps) + const float* const input1, + const size_t count0, + const size_t count1, + const float eps) { - if(count0 != count1) - { - return false; - } + if (count0 != count1) { + return false; + } #ifdef __AVX2__ - const f256 eps8 = splat8f(eps); - const size_t count8 = count0 & ~0x7ULL; - size_t i = 0; - - // check all values that can be processed in blocks of 8 - for(; i < count8; i += 8) - { - const i128 in0 = loadu4i(input0 + i); - const f256 in1 = loadu8f(input1 + i); - const f256 diff = abs8f(sub8f(cvtph8(in0), in1)); + const f256 eps8 = splat8f(eps); + const size_t count8 = count0 & ~0x7ULL; + size_t i = 0; + + // check all values that can be processed in blocks of 8 + for (; i < count8; i += 8) { + const i128 in0 = loadu4i(input0 + i); + const f256 in1 = loadu8f(input1 + i); + const f256 diff = abs8f(sub8f(cvtph8(in0), in1)); + const f256 cmp = cmpgt8f(diff, eps8); + if (movemask8f(cmp)) + return false; + } + + // use a masked load to load the last 0 -> 7 elements in each array. The unused + // elements will be set to zero, so the if(diff > eps) test should return 0 + // in the movemask for those elements. + const f256 in1 = loadmask7f(input1 + i, count0); + alignas(16) GfHalf values[8] = { 0 }; + for (uint16_t j = 0, n = (count0 & 0x7); j < n; ++i, ++j) + values[j] = input0[i]; + const f256 in0 = cvtph8(load4i(values)); + const f256 diff = abs8f(sub8f(in0, in1)); const f256 cmp = cmpgt8f(diff, eps8); - if(movemask8f(cmp)) - return false; - } - - // use a masked load to load the last 0 -> 7 elements in each array. The unused - // elements will be set to zero, so the if(diff > eps) test should return 0 - // in the movemask for those elements. - const f256 in1 = loadmask7f(input1 + i, count0); - alignas(16) GfHalf values[8] = {0}; - for(uint16_t j = 0, n = (count0 & 0x7); j < n; ++i, ++j) - values[j] = input0[i]; - const f256 in0 = cvtph8(load4i(values)); - const f256 diff = abs8f(sub8f(in0, in1)); - const f256 cmp = cmpgt8f(diff, eps8); - return movemask8f(cmp) == 0; + return movemask8f(cmp) == 0; #elif defined(__SSE__) - const f128 eps4 = splat4f(eps); - const size_t count4 = count0 & ~0x3ULL; - size_t i = 0; - for(; i < count4; i += 4) - { - const f128 in1 = loadu4f(input1 + i); - // if HW float16 support available - #ifdef __F16C__ - const i128 in0 = load2i(input0 + i); - const f128 diff = abs4f(sub4f(cvtph4(in0), in1)); - #else - const f128 temp = set4f(input0[i], input0[i + 1], input0[i + 2], input0[i + 3]); - const f128 diff = abs4f(sub4f(temp, in1)); - #endif - const f128 cmp = cmpgt4f(diff, eps4); - if(movemask4f(cmp)) - return false; - } - - // check the final 3 elements (deliberate fallthrough in switch cases) - // using switch to make sure the compiler isn't *clever* and inserts an - // optimised loop (clang 5.0 can't optimise the loop in this case). - bool result = true; - switch(count0 & 0x3) - { - case 3: result = result & (std::abs(input0[i + 2] - input1[i + 2]) <= eps); - case 2: result = result & (std::abs(input0[i + 1] - input1[i + 1]) <= eps); - case 1: result = result & (std::abs(input0[i + 0] - input1[i + 0]) <= eps); - default: - break; - } - return result; + const f128 eps4 = splat4f(eps); + const size_t count4 = count0 & ~0x3ULL; + size_t i = 0; + for (; i < count4; i += 4) { + const f128 in1 = loadu4f(input1 + i); +// if HW float16 support available +#ifdef __F16C__ + const i128 in0 = load2i(input0 + i); + const f128 diff = abs4f(sub4f(cvtph4(in0), in1)); +#else + const f128 temp = set4f(input0[i], input0[i + 1], input0[i + 2], input0[i + 3]); + const f128 diff = abs4f(sub4f(temp, in1)); +#endif + const f128 cmp = cmpgt4f(diff, eps4); + if (movemask4f(cmp)) + return false; + } + + // check the final 3 elements (deliberate fallthrough in switch cases) + // using switch to make sure the compiler isn't *clever* and inserts an + // optimised loop (clang 5.0 can't optimise the loop in this case). + bool result = true; + switch (count0 & 0x3) { + case 3: result = result & (std::abs(input0[i + 2] - input1[i + 2]) <= eps); + case 2: result = result & (std::abs(input0[i + 1] - input1[i + 1]) <= eps); + case 1: result = result & (std::abs(input0[i + 0] - input1[i + 0]) <= eps); + default: break; + } + return result; #else - for(size_t i = 0; i < count0; ++i) - { - if(std::abs(float(input0[i]) - float(input1[i])) > eps) - { - return false; - } - } - return true; + for (size_t i = 0; i < count0; ++i) { + if (std::abs(float(input0[i]) - float(input1[i])) > eps) { + return false; + } + } + return true; #endif } @@ -688,192 +594,173 @@ bool compareArray( bool compareArray( const GfHalf* const input0, const double* const input1, - const size_t count0, - const size_t count1, - const double eps) + const size_t count0, + const size_t count1, + const double eps) { - if(count0 != count1) - { - return false; - } + if (count0 != count1) { + return false; + } #ifdef __AVX2__ - const f256 eps8 = splat8f(eps); - const size_t count8 = count0 & ~0x7ULL; - size_t i = 0; - - // check all values that can be processed in blocks of 8 - for(; i < count8; i += 8) - { - const i128 in0 = loadu4i(input0 + i); - const f128 in1a = cvt4d_to_4f(loadu4d(input1 + i)); - const f128 in1b = cvt4d_to_4f(loadu4d(input1 + i + 4)); - const f256 in1 = set2f128(in1a, in1b); - const f256 diff = abs8f(sub8f(cvtph8(in0), in1)); + const f256 eps8 = splat8f(eps); + const size_t count8 = count0 & ~0x7ULL; + size_t i = 0; + + // check all values that can be processed in blocks of 8 + for (; i < count8; i += 8) { + const i128 in0 = loadu4i(input0 + i); + const f128 in1a = cvt4d_to_4f(loadu4d(input1 + i)); + const f128 in1b = cvt4d_to_4f(loadu4d(input1 + i + 4)); + const f256 in1 = set2f128(in1a, in1b); + const f256 diff = abs8f(sub8f(cvtph8(in0), in1)); + const f256 cmp = cmpgt8f(diff, eps8); + if (movemask8f(cmp)) { + return false; + } + } + alignas(16) GfHalf a[8] = { 0 }; + for (int j = 0, k = i, n = count0 % 8; j < n; ++k, ++j) { + a[j] = input0[k]; + } + + const f256 in0 = cvtph8(loadu4i(a)); + f256 in1; + if (count0 & 0x4) { + const f128 in1a = cvt4d_to_4f(loadu4d(input1 + i)); + const f128 in1b = cvt4d_to_4f(loadmask3d(input1 + i + 4, count0)); + in1 = set2f128(in1a, in1b); + } else { + const f128 in1a = cvt4d_to_4f(loadmask3d(input1 + i, count0)); + in1 = set2f128(in1a, zero4f()); + } + const f256 diff = abs8f(sub8f(in0, in1)); const f256 cmp = cmpgt8f(diff, eps8); - if(movemask8f(cmp)) - { - return false; - } - } - alignas(16) GfHalf a[8] = {0}; - for(int j = 0, k = i, n = count0 % 8; j < n; ++k, ++j) - { - a[j] = input0[k]; - } - - const f256 in0 = cvtph8(loadu4i(a)); - f256 in1; - if(count0 & 0x4) - { - const f128 in1a = cvt4d_to_4f(loadu4d(input1 + i)); - const f128 in1b = cvt4d_to_4f(loadmask3d(input1 + i + 4, count0)); - in1 = set2f128(in1a, in1b); - } - else - { - const f128 in1a = cvt4d_to_4f(loadmask3d(input1 + i, count0)); - in1 = set2f128(in1a, zero4f()); - } - const f256 diff = abs8f(sub8f(in0, in1)); - const f256 cmp = cmpgt8f(diff, eps8); - if(movemask8f(cmp)) - return false; - - return true; + if (movemask8f(cmp)) + return false; + + return true; #elif defined(__SSE__) - const f128 eps4 = splat4f(eps); - const size_t count4 = count0 & ~0x3ULL; - size_t i = 0; - for(; i < count4; i += 4) - { - const f128 in1a = cvt2d_to_2f(loadu2d(input1 + i)); - const f128 in1b = cvt2d_to_2f(loadu2d(input1 + i + 2)); - const f128 in1 = movelh4f(in1a, in1b); - - // if HW float16 support available - #ifdef __F16C__ - const i128 in0 = load2i(input0 + i); - const f128 diff = abs4f(sub4f(cvtph4(in0), in1)); - #else - const f128 temp = set4f(input0[i], input0[i + 1], input0[i + 2], input0[i + 3]); - const f128 diff = abs4f(sub4f(temp, in1)); - #endif - - const f128 cmp = cmpgt4f(diff, eps4); - if(movemask4f(cmp)) - return false; - } - - // check the final 3 elements (deliberate fallthrough in switch cases) - // using switch to make sure the compiler isn't *clever* and inserts an - // optimised loop (clang 5.0 can't optimise the loop in this case). - bool result = true; - switch(count0 & 0x3) - { - case 3: result = result & (float(std::abs(input0[i + 2]) - float(input1[i + 2])) <= eps); - case 2: result = result & (float(std::abs(input0[i + 1]) - float(input1[i + 1])) <= eps); - case 1: result = result & (float(std::abs(input0[i + 0]) - float(input1[i + 0])) <= eps); - default: - break; - } - return result; + const f128 eps4 = splat4f(eps); + const size_t count4 = count0 & ~0x3ULL; + size_t i = 0; + for (; i < count4; i += 4) { + const f128 in1a = cvt2d_to_2f(loadu2d(input1 + i)); + const f128 in1b = cvt2d_to_2f(loadu2d(input1 + i + 2)); + const f128 in1 = movelh4f(in1a, in1b); + +// if HW float16 support available +#ifdef __F16C__ + const i128 in0 = load2i(input0 + i); + const f128 diff = abs4f(sub4f(cvtph4(in0), in1)); +#else + const f128 temp = set4f(input0[i], input0[i + 1], input0[i + 2], input0[i + 3]); + const f128 diff = abs4f(sub4f(temp, in1)); +#endif + + const f128 cmp = cmpgt4f(diff, eps4); + if (movemask4f(cmp)) + return false; + } + + // check the final 3 elements (deliberate fallthrough in switch cases) + // using switch to make sure the compiler isn't *clever* and inserts an + // optimised loop (clang 5.0 can't optimise the loop in this case). + bool result = true; + switch (count0 & 0x3) { + case 3: result = result & (float(std::abs(input0[i + 2]) - float(input1[i + 2])) <= eps); + case 2: result = result & (float(std::abs(input0[i + 1]) - float(input1[i + 1])) <= eps); + case 1: result = result & (float(std::abs(input0[i + 0]) - float(input1[i + 0])) <= eps); + default: break; + } + return result; #else - for(size_t i = 0; i < count0; ++i) - { - if(std::abs(float(input0[i]) - float(input1[i])) > eps) - return false; - } - return true; + for (size_t i = 0; i < count0; ++i) { + if (std::abs(float(input0[i]) - float(input1[i])) > eps) + return false; + } + return true; #endif } //---------------------------------------------------------------------------------------------------------------------- bool compareArray( const double* const input0, - const float* const input1, - const size_t count0, - const size_t count1, - const float eps) + const float* const input1, + const size_t count0, + const size_t count1, + const float eps) { - if(count0 != count1) - { - return false; - } - for(size_t i = 0; i < count0; ++i) - { - if(std::abs(input0[i] - input1[i]) > eps) - return false; - } - return true; + if (count0 != count1) { + return false; + } + for (size_t i = 0; i < count0; ++i) { + if (std::abs(input0[i] - input1[i]) > eps) + return false; + } + return true; } - //---------------------------------------------------------------------------------------------------------------------- bool compareArray( const double* const input0, const double* const input1, - const size_t count0, - const size_t count1, - const double eps) + const size_t count0, + const size_t count1, + const double eps) { - if(count0 != count1) - { - return false; - } + if (count0 != count1) { + return false; + } #ifdef __AVX2__ - const d256 eps4 = splat4d(eps); - const size_t count4 = count0 & ~0x3ULL; - size_t i = 0; - - // check all values that can be processed in blocks of 8 - for(; i < count4; i += 4) - { - const d256 in0 = loadu4d(input0 + i); - const d256 in1 = loadu4d(input1 + i); + const d256 eps4 = splat4d(eps); + const size_t count4 = count0 & ~0x3ULL; + size_t i = 0; + + // check all values that can be processed in blocks of 8 + for (; i < count4; i += 4) { + const d256 in0 = loadu4d(input0 + i); + const d256 in1 = loadu4d(input1 + i); + const d256 diff = abs4d(sub4d(in0, in1)); + const d256 cmp = cmpgt4d(diff, eps4); + if (movemask4d(cmp)) + return false; + } + + // use a masked load to load the last 0 -> 7 elements in each array. The unused + // elements will be set to zero, so the if(diff > eps) test should return 0 + // in the movemask for those elements. + const d256 in0 = loadmask3d(input0 + i, count0); + const d256 in1 = loadmask3d(input1 + i, count0); const d256 diff = abs4d(sub4d(in0, in1)); const d256 cmp = cmpgt4d(diff, eps4); - if(movemask4d(cmp)) - return false; - } - - // use a masked load to load the last 0 -> 7 elements in each array. The unused - // elements will be set to zero, so the if(diff > eps) test should return 0 - // in the movemask for those elements. - const d256 in0 = loadmask3d(input0 + i, count0); - const d256 in1 = loadmask3d(input1 + i, count0); - const d256 diff = abs4d(sub4d(in0, in1)); - const d256 cmp = cmpgt4d(diff, eps4); - return movemask4d(cmp) == 0; + return movemask4d(cmp) == 0; #elif defined(__SSE__) - const d128 eps2 = splat2d(eps); - const size_t count2 = count0 & ~0x1ULL; - size_t i = 0; - for(; i < count2; i += 2) - { - const d128 in0 = loadu2d(input0 + i); - const d128 in1 = loadu2d(input1 + i); - const d128 diff = abs2d(sub2d(in0, in1)); - const d128 cmp = cmpgt2d(diff, eps2); - if(movemask2d(cmp)) - return false; - } - - // check the final element (If it's there) - bool result = true; - if(count0 & 0x1) - { - result = std::abs(input0[i] - input1[i]) <= eps; - } - return result; + const d128 eps2 = splat2d(eps); + const size_t count2 = count0 & ~0x1ULL; + size_t i = 0; + for (; i < count2; i += 2) { + const d128 in0 = loadu2d(input0 + i); + const d128 in1 = loadu2d(input1 + i); + const d128 diff = abs2d(sub2d(in0, in1)); + const d128 cmp = cmpgt2d(diff, eps2); + if (movemask2d(cmp)) + return false; + } + + // check the final element (If it's there) + bool result = true; + if (count0 & 0x1) { + result = std::abs(input0[i] - input1[i]) <= eps; + } + return result; #else - for(size_t i = 0; i < count0; ++i) - { - if(std::abs(input0[i] - input1[i]) > eps) - return false; - } - return true; + for (size_t i = 0; i < count0; ++i) { + if (std::abs(input0[i] - input1[i]) > eps) + return false; + } + return true; #endif } @@ -881,80 +768,71 @@ bool compareArray( bool compareArray( const float* const input0, const float* const input1, - const size_t count0, - const size_t count1, - const float eps) + const size_t count0, + const size_t count1, + const float eps) { - if(count0 != count1) - { - return false; - } + if (count0 != count1) { + return false; + } #ifdef __AVX2__ - const f256 eps8 = splat8f(eps); - const size_t count8 = count0 & ~0x7ULL; - size_t i = 0; - - // check all values that can be processed in blocks of 8 - for(; i < count8; i += 8) - { - const f256 in0 = loadu8f(input0 + i); - const f256 in1 = loadu8f(input1 + i); - const f256 diff = abs8f(sub8f(in0, in1)); - const f256 cmp = cmpgt8f(diff, eps8); - if(movemask8f(cmp)) - { - return false; + const f256 eps8 = splat8f(eps); + const size_t count8 = count0 & ~0x7ULL; + size_t i = 0; + + // check all values that can be processed in blocks of 8 + for (; i < count8; i += 8) { + const f256 in0 = loadu8f(input0 + i); + const f256 in1 = loadu8f(input1 + i); + const f256 diff = abs8f(sub8f(in0, in1)); + const f256 cmp = cmpgt8f(diff, eps8); + if (movemask8f(cmp)) { + return false; + } } - } - // use a masked load to load the last 0 -> 7 elements in each array. The unused - // elements will be set to zero, so the if(diff > eps) test should return 0 - // in the movemask for those elements. - const f256 in0 = loadmask7f(input0 + i, count0); - const f256 in1 = loadmask7f(input1 + i, count0); - const f256 diff = abs8f(sub8f(in0, in1)); - const f256 cmp = cmpgt8f(diff, eps8); - return movemask8f(cmp) == 0; + // use a masked load to load the last 0 -> 7 elements in each array. The unused + // elements will be set to zero, so the if(diff > eps) test should return 0 + // in the movemask for those elements. + const f256 in0 = loadmask7f(input0 + i, count0); + const f256 in1 = loadmask7f(input1 + i, count0); + const f256 diff = abs8f(sub8f(in0, in1)); + const f256 cmp = cmpgt8f(diff, eps8); + return movemask8f(cmp) == 0; #elif defined(__SSE__) - const f128 eps4 = splat4f(eps); - const size_t count4 = count0 & ~0x3ULL; - size_t i = 0; - for(; i < count4; i += 4) - { - const f128 in0 = loadu4f(input0 + i); - const f128 in1 = loadu4f(input1 + i); - const f128 diff = abs4f(sub4f(in0, in1)); - const f128 cmp = cmpgt4f(diff, eps4); - - if(movemask4f(cmp)) - { - return false; - } - } - - // check the final 3 elements (deliberate fallthrough in switch cases) - // using switch to make sure the compiler isn't *clever* and inserts an - // optimised loop (clang 5.0 can't optimise the loop in this case). - bool result = true; - switch(count0 & 0x3) - { - case 3: result = result & (std::abs(input0[i + 2] - input1[i + 2]) <= eps); - case 2: result = result & (std::abs(input0[i + 1] - input1[i + 1]) <= eps); - case 1: result = result & (std::abs(input0[i + 0] - input1[i + 0]) <= eps); - default: - break; - } - return result; + const f128 eps4 = splat4f(eps); + const size_t count4 = count0 & ~0x3ULL; + size_t i = 0; + for (; i < count4; i += 4) { + const f128 in0 = loadu4f(input0 + i); + const f128 in1 = loadu4f(input1 + i); + const f128 diff = abs4f(sub4f(in0, in1)); + const f128 cmp = cmpgt4f(diff, eps4); + + if (movemask4f(cmp)) { + return false; + } + } + + // check the final 3 elements (deliberate fallthrough in switch cases) + // using switch to make sure the compiler isn't *clever* and inserts an + // optimised loop (clang 5.0 can't optimise the loop in this case). + bool result = true; + switch (count0 & 0x3) { + case 3: result = result & (std::abs(input0[i + 2] - input1[i + 2]) <= eps); + case 2: result = result & (std::abs(input0[i + 1] - input1[i + 1]) <= eps); + case 1: result = result & (std::abs(input0[i + 0] - input1[i + 0]) <= eps); + default: break; + } + return result; #else - for(size_t i = 0; i < count0; ++i) - { - if(std::abs(input0[i] - input1[i]) > eps) - { - return false; - } - } - return true; + for (size_t i = 0; i < count0; ++i) { + if (std::abs(input0[i] - input1[i]) > eps) { + return false; + } + } + return true; #endif } @@ -962,79 +840,72 @@ bool compareArray( bool compareArray( const int8_t* const input0, const int8_t* const input1, - const size_t count0, - const size_t count1) + const size_t count0, + const size_t count1) { - if(count0 != count1) - { - return false; - } + if (count0 != count1) { + return false; + } #ifdef __AVX2__ - const size_t count32 = count0 & ~0x1FULL; - size_t i = 0; - - // check all values that can be processed in blocks of 8 - for(; i < count32; i += 32) - { - const i256 in0 = loadu8i(input0 + i); - const i256 in1 = loadu8i(input1 + i); + const size_t count32 = count0 & ~0x1FULL; + size_t i = 0; + + // check all values that can be processed in blocks of 8 + for (; i < count32; i += 32) { + const i256 in0 = loadu8i(input0 + i); + const i256 in1 = loadu8i(input1 + i); + const i256 cmp = cmpeq32i8(in0, in1); + if (~movemask32i8(cmp)) + return false; + } + + alignas(32) uint8_t a[32] = { 0 }; + alignas(32) uint8_t b[32] = { 0 }; + for (int j = 0, n = count0 % 32; j < n; ++i, ++j) { + a[j] = input0[i]; + b[j] = input1[i]; + } + + // use a masked load to load the last 0 -> 7 elements in each array. The unused + // elements will be set to zero, so the if(diff > eps) test should return 0 + // in the movemask for those elements. + const i256 in0 = load8i(a); + const i256 in1 = load8i(b); const i256 cmp = cmpeq32i8(in0, in1); - if(~movemask32i8(cmp)) - return false; - } - - alignas(32) uint8_t a[32] = {0}; - alignas(32) uint8_t b[32] = {0}; - for(int j = 0, n = count0 % 32; j < n; ++i, ++j) - { - a[j] = input0[i]; - b[j] = input1[i]; - } - - // use a masked load to load the last 0 -> 7 elements in each array. The unused - // elements will be set to zero, so the if(diff > eps) test should return 0 - // in the movemask for those elements. - const i256 in0 = load8i(a); - const i256 in1 = load8i(b); - const i256 cmp = cmpeq32i8(in0, in1); - return movemask32i8(cmp) == -1; + return movemask32i8(cmp) == -1; #elif defined(__SSE__) - const size_t count16 = count0 & ~0xFULL; - size_t i = 0; - for(; i < count16; i += 16) - { - const i128 in0 = loadu4i(input0 + i); - const i128 in1 = loadu4i(input1 + i); + const size_t count16 = count0 & ~0xFULL; + size_t i = 0; + for (; i < count16; i += 16) { + const i128 in0 = loadu4i(input0 + i); + const i128 in1 = loadu4i(input1 + i); + const i128 cmp = cmpeq16i8(in0, in1); + if (0xFFFF & (~movemask16i8(cmp))) { + return false; + } + } + + alignas(16) uint8_t a[16] = { 0 }; + alignas(16) uint8_t b[16] = { 0 }; + for (int j = 0; i < count0; ++i, ++j) { + a[j] = input0[i]; + b[j] = input1[i]; + } + + // use a masked load to load the last 0 -> 7 elements in each array. The unused + // elements will be set to zero, so the if(diff > eps) test should return 0 + // in the movemask for those elements. + const i128 in0 = load4i(a); + const i128 in1 = load4i(b); const i128 cmp = cmpeq16i8(in0, in1); - if(0xFFFF & (~movemask16i8(cmp))) - { - return false; - } - } - - alignas(16) uint8_t a[16] = {0}; - alignas(16) uint8_t b[16] = {0}; - for(int j = 0; i < count0; ++i, ++j) - { - a[j] = input0[i]; - b[j] = input1[i]; - } - - // use a masked load to load the last 0 -> 7 elements in each array. The unused - // elements will be set to zero, so the if(diff > eps) test should return 0 - // in the movemask for those elements. - const i128 in0 = load4i(a); - const i128 in1 = load4i(b); - const i128 cmp = cmpeq16i8(in0, in1); - return 0xFFFF == movemask16i8(cmp); - #else - for(size_t i = 0; i < count0; ++i) - { - if(input0[i] != input1[i]) - return false; - } - return true; + return 0xFFFF == movemask16i8(cmp); +#else + for (size_t i = 0; i < count0; ++i) { + if (input0[i] != input1[i]) + return false; + } + return true; #endif } @@ -1042,67 +913,61 @@ bool compareArray( bool compareArray( const int32_t* const input0, const int32_t* const input1, - const size_t count0, - const size_t count1) + const size_t count0, + const size_t count1) { - if(count0 != count1) - { - return false; - } + if (count0 != count1) { + return false; + } #ifdef __AVX2__ - const size_t count8 = count0 & ~0x7ULL; - size_t i = 0; - - // check all values that can be processed in blocks of 8 - for(; i < count8; i += 8) - { - const i256 in0 = loadu8i(input0 + i); - const i256 in1 = loadu8i(input1 + i); + const size_t count8 = count0 & ~0x7ULL; + size_t i = 0; + + // check all values that can be processed in blocks of 8 + for (; i < count8; i += 8) { + const i256 in0 = loadu8i(input0 + i); + const i256 in1 = loadu8i(input1 + i); + const i256 cmp = cmpeq8i(in0, in1); + if (0xFF & (~movemask8i(cmp))) + return false; + } + + // use a masked load to load the last 0 -> 7 elements in each array. The unused + // elements will be set to zero, so the if(diff > eps) test should return 0 + // in the movemask for those elements. + const i256 in0 = loadmask7i(input0 + i, count0); + const i256 in1 = loadmask7i(input1 + i, count0); const i256 cmp = cmpeq8i(in0, in1); - if(0xFF & (~movemask8i(cmp))) - return false; - } - - // use a masked load to load the last 0 -> 7 elements in each array. The unused - // elements will be set to zero, so the if(diff > eps) test should return 0 - // in the movemask for those elements. - const i256 in0 = loadmask7i(input0 + i, count0); - const i256 in1 = loadmask7i(input1 + i, count0); - const i256 cmp = cmpeq8i(in0, in1); - return (0xFF & (~movemask8i(cmp))) == 0; + return (0xFF & (~movemask8i(cmp))) == 0; #elif defined(__SSE__) - const size_t count4 = count0 & ~0x3ULL; - size_t i = 0; - for(; i < count4; i += 4) - { - const i128 in0 = loadu4i(input0 + i); - const i128 in1 = loadu4i(input1 + i); - const i128 cmp = cmpeq4i(in0, in1); - if(0xF & (~movemask4i(cmp))) - return false; - } - - // check the final 3 elements (deliberate fallthrough in switch cases) - // using switch to make sure the compiler isn't *clever* and inserts an - // optimised loop (clang 5.0 can't optimise the loop in this case). - bool result = true; - switch(count0 & 0x3) - { - case 3: result = result & (input0[i + 2] == input1[i + 2]); - case 2: result = result & (input0[i + 1] == input1[i + 1]); - case 1: result = result & (input0[i + 0] == input1[i + 0]); - default: - break; - } - return result; + const size_t count4 = count0 & ~0x3ULL; + size_t i = 0; + for (; i < count4; i += 4) { + const i128 in0 = loadu4i(input0 + i); + const i128 in1 = loadu4i(input1 + i); + const i128 cmp = cmpeq4i(in0, in1); + if (0xF & (~movemask4i(cmp))) + return false; + } + + // check the final 3 elements (deliberate fallthrough in switch cases) + // using switch to make sure the compiler isn't *clever* and inserts an + // optimised loop (clang 5.0 can't optimise the loop in this case). + bool result = true; + switch (count0 & 0x3) { + case 3: result = result & (input0[i + 2] == input1[i + 2]); + case 2: result = result & (input0[i + 1] == input1[i + 1]); + case 1: result = result & (input0[i + 0] == input1[i + 0]); + default: break; + } + return result; #else - for(size_t i = 0; i < count0; ++i) - { - if(input0[i] != input1[i]) - return false; - } - return true; + for (size_t i = 0; i < count0; ++i) { + if (input0[i] != input1[i]) + return false; + } + return true; #endif } @@ -1111,251 +976,225 @@ bool compareUvArray( const float* const u0, const float* const v0, const float* const uv1, - const size_t count0, - const size_t count1, - const float eps) + const size_t count0, + const size_t count1, + const float eps) { - if(count0 != count1) - { - return false; - } + if (count0 != count1) { + return false; + } #ifdef __AVX2__ - const f256 eps8 = splat8f(eps); - const size_t count8 = count0 & ~0x7ULL; - size_t i = 0, j = 0; - - // check all values that can be processed in blocks of 8 - for(; i < count8; i += 8, j += 16) - { - const f256 inu0 = loadu8f(u0 + i); - const f256 inv0 = loadu8f(v0 + i); - const f256 inuv1a = loadu8f(uv1 + j); - const f256 inuv1b = loadu8f(uv1 + j + 8); - - // zip U and V arrays together - const f256 xy0 = unpacklo8f(inu0, inv0); - const f256 xy1 = unpackhi8f(inu0, inv0); - const f256 inuv0a = permute128f<0, 2>(xy0, xy1); - const f256 inuv0b = permute128f<1, 3>(xy0, xy1); - - const f256 diff0 = abs8f(sub8f(inuv0a, inuv1a)); - const f256 diff1 = abs8f(sub8f(inuv0b, inuv1b)); - const f256 cmp0 = cmpgt8f(diff0, eps8); - const f256 cmp1 = cmpgt8f(diff1, eps8); - if(movemask8f(cmp0) | movemask8f(cmp1)) - return false; - } - - if(count0 != count8) - { - f256 inu0, inv0, inuv1a, inuv1b; - if(count0 & 0x4) - { - inu0 = loadmask7f(u0 + i, count0); - inv0 = loadmask7f(v0 + i, count0); - inuv1a = loadu8f(uv1 + j); - inuv1b = loadmask7f(uv1 + j + 8, count0 << 1); - } - else - { - inu0 = loadmask7f(u0 + i, count0); - inv0 = loadmask7f(v0 + i, count0); - inuv1a = loadmask7f(uv1 + j, count0 << 1); - inuv1b = zero8f(); - } - - // zip U and V arrays together - const f256 xy0 = unpacklo8f(inu0, inv0); - const f256 xy1 = unpackhi8f(inu0, inv0); - const f256 inuv0a = permute128f<0, 2>(xy0, xy1); - const f256 inuv0b = permute128f<1, 3>(xy0, xy1); - - const f256 diff0 = abs8f(sub8f(inuv0a, inuv1a)); - const f256 diff1 = abs8f(sub8f(inuv0b, inuv1b)); - const f256 cmp0 = cmpgt8f(diff0, eps8); - const f256 cmp1 = cmpgt8f(diff1, eps8); - if(movemask8f(cmp0) | movemask8f(cmp1)) - return false; - } - - return true; + const f256 eps8 = splat8f(eps); + const size_t count8 = count0 & ~0x7ULL; + size_t i = 0, j = 0; + + // check all values that can be processed in blocks of 8 + for (; i < count8; i += 8, j += 16) { + const f256 inu0 = loadu8f(u0 + i); + const f256 inv0 = loadu8f(v0 + i); + const f256 inuv1a = loadu8f(uv1 + j); + const f256 inuv1b = loadu8f(uv1 + j + 8); + + // zip U and V arrays together + const f256 xy0 = unpacklo8f(inu0, inv0); + const f256 xy1 = unpackhi8f(inu0, inv0); + const f256 inuv0a = permute128f<0, 2>(xy0, xy1); + const f256 inuv0b = permute128f<1, 3>(xy0, xy1); + + const f256 diff0 = abs8f(sub8f(inuv0a, inuv1a)); + const f256 diff1 = abs8f(sub8f(inuv0b, inuv1b)); + const f256 cmp0 = cmpgt8f(diff0, eps8); + const f256 cmp1 = cmpgt8f(diff1, eps8); + if (movemask8f(cmp0) | movemask8f(cmp1)) + return false; + } + + if (count0 != count8) { + f256 inu0, inv0, inuv1a, inuv1b; + if (count0 & 0x4) { + inu0 = loadmask7f(u0 + i, count0); + inv0 = loadmask7f(v0 + i, count0); + inuv1a = loadu8f(uv1 + j); + inuv1b = loadmask7f(uv1 + j + 8, count0 << 1); + } else { + inu0 = loadmask7f(u0 + i, count0); + inv0 = loadmask7f(v0 + i, count0); + inuv1a = loadmask7f(uv1 + j, count0 << 1); + inuv1b = zero8f(); + } + + // zip U and V arrays together + const f256 xy0 = unpacklo8f(inu0, inv0); + const f256 xy1 = unpackhi8f(inu0, inv0); + const f256 inuv0a = permute128f<0, 2>(xy0, xy1); + const f256 inuv0b = permute128f<1, 3>(xy0, xy1); + + const f256 diff0 = abs8f(sub8f(inuv0a, inuv1a)); + const f256 diff1 = abs8f(sub8f(inuv0b, inuv1b)); + const f256 cmp0 = cmpgt8f(diff0, eps8); + const f256 cmp1 = cmpgt8f(diff1, eps8); + if (movemask8f(cmp0) | movemask8f(cmp1)) + return false; + } + + return true; #elif defined(__SSE__) - const f128 eps4 = splat4f(eps); - const size_t count4 = count0 & ~0x3ULL; - size_t i = 0, j = 0; - - // check all values that can be processed in blocks of 8 - for(; i < count4; i += 4, j += 8) - { - const f128 inu0 = loadu4f(u0 + i); - const f128 inv0 = loadu4f(v0 + i); - const f128 inuv1a = loadu4f(uv1 + j); - const f128 inuv1b = loadu4f(uv1 + j + 4); - - // zip U and V arrays together - const f128 inuv0a = unpacklo4f(inu0, inv0); - const f128 inuv0b = unpackhi4f(inu0, inv0); - - const f128 diff0 = abs4f(sub4f(inuv0a, inuv1a)); - const f128 diff1 = abs4f(sub4f(inuv0b, inuv1b)); - const f128 cmp0 = cmpgt4f(diff0, eps4); - const f128 cmp1 = cmpgt4f(diff1, eps4); - if(movemask4f(cmp0) | movemask4f(cmp1)) - return false; - } - - if(count0 != count4) - { - f128 inuv0a, inuv0b, inu1, inv1; - if(count0 & 0x2) - { - inuv0a = loadu4f(uv1 + j); - inuv0b = loadmask3f(uv1 + j + 4, count0 << 1); - inu1 = loadmask3f(u0 + i, count0); - inv1 = loadmask3f(v0 + i, count0); - } - else - { - inuv0a = loadmask3f(uv1 + j, count0 << 1); - inuv0b = zero4f(); - inu1 = loadmask3f(u0 + i, count0); - inv1 = loadmask3f(v0 + i, count0); - } - - // zip U and V arrays together - const f128 inuv1a = unpacklo4f(inu1, inv1); - const f128 inuv1b = unpackhi4f(inu1, inv1); - const f128 diff0 = abs4f(sub4f(inuv0a, inuv1a)); - const f128 diff1 = abs4f(sub4f(inuv0b, inuv1b)); - const f128 cmp0 = cmpgt4f(diff0, eps4); - const f128 cmp1 = cmpgt4f(diff1, eps4); - if(movemask4f(cmp0) | movemask4f(cmp1)) - return false; - } - - return true; + const f128 eps4 = splat4f(eps); + const size_t count4 = count0 & ~0x3ULL; + size_t i = 0, j = 0; + + // check all values that can be processed in blocks of 8 + for (; i < count4; i += 4, j += 8) { + const f128 inu0 = loadu4f(u0 + i); + const f128 inv0 = loadu4f(v0 + i); + const f128 inuv1a = loadu4f(uv1 + j); + const f128 inuv1b = loadu4f(uv1 + j + 4); + + // zip U and V arrays together + const f128 inuv0a = unpacklo4f(inu0, inv0); + const f128 inuv0b = unpackhi4f(inu0, inv0); + + const f128 diff0 = abs4f(sub4f(inuv0a, inuv1a)); + const f128 diff1 = abs4f(sub4f(inuv0b, inuv1b)); + const f128 cmp0 = cmpgt4f(diff0, eps4); + const f128 cmp1 = cmpgt4f(diff1, eps4); + if (movemask4f(cmp0) | movemask4f(cmp1)) + return false; + } + + if (count0 != count4) { + f128 inuv0a, inuv0b, inu1, inv1; + if (count0 & 0x2) { + inuv0a = loadu4f(uv1 + j); + inuv0b = loadmask3f(uv1 + j + 4, count0 << 1); + inu1 = loadmask3f(u0 + i, count0); + inv1 = loadmask3f(v0 + i, count0); + } else { + inuv0a = loadmask3f(uv1 + j, count0 << 1); + inuv0b = zero4f(); + inu1 = loadmask3f(u0 + i, count0); + inv1 = loadmask3f(v0 + i, count0); + } + + // zip U and V arrays together + const f128 inuv1a = unpacklo4f(inu1, inv1); + const f128 inuv1b = unpackhi4f(inu1, inv1); + const f128 diff0 = abs4f(sub4f(inuv0a, inuv1a)); + const f128 diff1 = abs4f(sub4f(inuv0b, inuv1b)); + const f128 cmp0 = cmpgt4f(diff0, eps4); + const f128 cmp1 = cmpgt4f(diff1, eps4); + if (movemask4f(cmp0) | movemask4f(cmp1)) + return false; + } + + return true; #else - for(size_t i = 0, j = 0; i < count0; ++i, j += 2) - { - if(std::abs(u0[i] - uv1[j + 0]) > eps || std::abs(v0[i] - uv1[j + 1]) > eps) - return false; - } - return true; + for (size_t i = 0, j = 0; i < count0; ++i, j += 2) { + if (std::abs(u0[i] - uv1[j + 0]) > eps || std::abs(v0[i] - uv1[j + 1]) > eps) + return false; + } + return true; #endif } //---------------------------------------------------------------------------------------------------------------------- bool compareUvArray( - const float u0, - const float v0, + const float u0, + const float v0, const float* const u1, const float* const v1, - const size_t count, - const float eps) + const size_t count, + const float eps) { #ifdef __AVX2__ - const f256 U = splat8f(u0); - const f256 V = splat8f(v0); - - const f256 eps8 = splat8f(eps); - const size_t count8 = count & ~0x7ULL; - size_t i = 0; - - // check all values that can be processed in blocks of 4 - for(; i < count8; i += 8) - { - const f256 au1 = loadu8f(u1 + i); - const f256 av1 = loadu8f(v1 + i); - - const f256 diffu = abs8f(sub8f(au1, U)); - const f256 diffv = abs8f(sub8f(av1, V)); - const f256 cmpu = cmpgt8f(diffu, eps8); - const f256 cmpv = cmpgt8f(diffv, eps8); - if(movemask8f(cmpu) || movemask8f(cmpv)) - return false; - } - - if(count8 != count) - { - alignas(32) float utemp[8]; - alignas(32) float vtemp[8]; - storeu8f(utemp, U); - storeu8f(vtemp, V); - f256 inu0, inv0, inu1, inv1; - inu0 = loadmask7f(utemp, count); - inv0 = loadmask7f(utemp, count); - inu1 = loadmask7f(u1 + i, count); - inv1 = loadmask7f(v1 + i, count); - - const f256 diffu = abs8f(sub8f(inu0, inu1)); - const f256 diffv = abs8f(sub8f(inv0, inv1)); - const f256 cmpu = cmpgt8f(diffu, eps8); - const f256 cmpv = cmpgt8f(diffv, eps8); - if(movemask8f(cmpu) || movemask8f(cmpv)) - return false; - } - - return true; + const f256 U = splat8f(u0); + const f256 V = splat8f(v0); + + const f256 eps8 = splat8f(eps); + const size_t count8 = count & ~0x7ULL; + size_t i = 0; + + // check all values that can be processed in blocks of 4 + for (; i < count8; i += 8) { + const f256 au1 = loadu8f(u1 + i); + const f256 av1 = loadu8f(v1 + i); + + const f256 diffu = abs8f(sub8f(au1, U)); + const f256 diffv = abs8f(sub8f(av1, V)); + const f256 cmpu = cmpgt8f(diffu, eps8); + const f256 cmpv = cmpgt8f(diffv, eps8); + if (movemask8f(cmpu) || movemask8f(cmpv)) + return false; + } + + if (count8 != count) { + alignas(32) float utemp[8]; + alignas(32) float vtemp[8]; + storeu8f(utemp, U); + storeu8f(vtemp, V); + f256 inu0, inv0, inu1, inv1; + inu0 = loadmask7f(utemp, count); + inv0 = loadmask7f(utemp, count); + inu1 = loadmask7f(u1 + i, count); + inv1 = loadmask7f(v1 + i, count); + + const f256 diffu = abs8f(sub8f(inu0, inu1)); + const f256 diffv = abs8f(sub8f(inv0, inv1)); + const f256 cmpu = cmpgt8f(diffu, eps8); + const f256 cmpv = cmpgt8f(diffv, eps8); + if (movemask8f(cmpu) || movemask8f(cmpv)) + return false; + } + + return true; #elif defined(__SSE__) - const f128 U = splat4f(u0); - const f128 V = splat4f(v0); - - const f128 eps4 = splat4f(eps); - const size_t count4 = count & ~0x3ULL; - size_t i = 0; - - // check all values that can be processed in blocks of 4 - for(; i < count4; i += 4) - { - const f128 au1 = loadu4f(u1 + i); - const f128 av1 = loadu4f(v1 + i); - - const f128 diffu = abs4f(sub4f(au1, U)); - const f128 diffv = abs4f(sub4f(av1, V)); - const f128 cmpu = cmpgt4f(diffu, eps4); - const f128 cmpv = cmpgt4f(diffv, eps4); - if(movemask4f(cmpu) || movemask4f(cmpv)) - return false; - } - - if(count4 != count) - { - bool result = true; - switch(count & 0x3) - { - case 3: - result = (std::abs(u0 - u1[i + 2]) <= eps && - std::abs(v0 - v1[i + 2]) <= eps); - case 2: - result = result && - (std::abs(u0 - u1[i + 1]) <= eps && - std::abs(v0 - v1[i + 1]) <= eps); - case 1: - result = result && - (std::abs(u0 - u1[i + 0]) <= eps && - std::abs(v0 - v1[i + 0]) <= eps); - default: - break; + const f128 U = splat4f(u0); + const f128 V = splat4f(v0); + + const f128 eps4 = splat4f(eps); + const size_t count4 = count & ~0x3ULL; + size_t i = 0; + + // check all values that can be processed in blocks of 4 + for (; i < count4; i += 4) { + const f128 au1 = loadu4f(u1 + i); + const f128 av1 = loadu4f(v1 + i); + + const f128 diffu = abs4f(sub4f(au1, U)); + const f128 diffv = abs4f(sub4f(av1, V)); + const f128 cmpu = cmpgt4f(diffu, eps4); + const f128 cmpv = cmpgt4f(diffv, eps4); + if (movemask4f(cmpu) || movemask4f(cmpv)) + return false; } - return result; - } - return true; + if (count4 != count) { + bool result = true; + switch (count & 0x3) { + case 3: result = (std::abs(u0 - u1[i + 2]) <= eps && std::abs(v0 - v1[i + 2]) <= eps); + case 2: + result = result && (std::abs(u0 - u1[i + 1]) <= eps && std::abs(v0 - v1[i + 1]) <= eps); + case 1: + result = result && (std::abs(u0 - u1[i + 0]) <= eps && std::abs(v0 - v1[i + 0]) <= eps); + default: break; + } + return result; + } + + return true; #else - for(size_t i = 0; i < count; ++i) - { - if(std::abs(u0 - u1[i]) > eps || - std::abs(v0 - v1[i]) > eps) - return false; - } - return true; + for (size_t i = 0; i < count; ++i) { + if (std::abs(u0 - u1[i]) > eps || std::abs(v0 - v1[i]) > eps) + return false; + } + return true; #endif } @@ -1363,120 +1202,109 @@ bool compareUvArray( bool compareArray3Dto4D( const float* const input3d, const float* const input4d, - const size_t count3d, - const size_t count4d, - const float eps) + const size_t count3d, + const size_t count4d, + const float eps) { - if(count3d != count4d) - { - return false; - } - - for(size_t i = 0, j = 0, n = count3d * 3; i < n; i += 3, j += 4) - { - if(std::abs(input3d[i + 0] - input4d[j + 0]) > eps || - std::abs(input3d[i + 1] - input4d[j + 1]) > eps || - std::abs(input3d[i + 2] - input4d[j + 2]) > eps) - return false; - } - return true; + if (count3d != count4d) { + return false; + } + + for (size_t i = 0, j = 0, n = count3d * 3; i < n; i += 3, j += 4) { + if (std::abs(input3d[i + 0] - input4d[j + 0]) > eps + || std::abs(input3d[i + 1] - input4d[j + 1]) > eps + || std::abs(input3d[i + 2] - input4d[j + 2]) > eps) + return false; + } + return true; } //---------------------------------------------------------------------------------------------------------------------- bool compareArrayFloat3DtoDouble4D( - const float* const input3d, + const float* const input3d, const double* const input4d, - const size_t count3d, - const size_t count4d, - const float eps) + const size_t count3d, + const size_t count4d, + const float eps) { - if (count3d != count4d) - { - return false; - } + if (count3d != count4d) { + return false; + } #ifdef __AVX2__ - const f128 eps4 = splatf4f(eps); - for (size_t i = 0; i < count3d; ++i) - { - const f128 float3d = loadmask3f(input3d + i * 3, 3); - const d256 double4d = loadmask3d(input4d + i * 4, 3); - const f128 float4d = cvt4d_to_4f(double4d); - const f128 diff = abs4f(sub4f(float3d, float4d)); - const f128 cmp = cmpgt4f(diff, eps4); - if(movemask4f(cmp)) - return false; - } + const f128 eps4 = splatf4f(eps); + for (size_t i = 0; i < count3d; ++i) { + const f128 float3d = loadmask3f(input3d + i * 3, 3); + const d256 double4d = loadmask3d(input4d + i * 4, 3); + const f128 float4d = cvt4d_to_4f(double4d); + const f128 diff = abs4f(sub4f(float3d, float4d)); + const f128 cmp = cmpgt4f(diff, eps4); + if (movemask4f(cmp)) + return false; + } #else - for (size_t i = 0, j = 0, n = count3d * 3; i < n; i +=3, j += 4) - { - if (std::abs(input3d[i + 0] - input4d[j + 0]) > eps || - std::abs(input3d[i + 1] - input4d[j + 1]) > eps || - std::abs(input3d[i + 2] - input4d[j + 2]) > eps) - return false; - } - return true; + for (size_t i = 0, j = 0, n = count3d * 3; i < n; i += 3, j += 4) { + if (std::abs(input3d[i + 0] - input4d[j + 0]) > eps + || std::abs(input3d[i + 1] - input4d[j + 1]) > eps + || std::abs(input3d[i + 2] - input4d[j + 2]) > eps) + return false; + } + return true; #endif } //---------------------------------------------------------------------------------------------------------------------- bool compareRGBAArray( - const float r, - const float g, - const float b, - const float a, + const float r, + const float g, + const float b, + const float a, const float* const rgba, - const size_t count, - const float eps) + const size_t count, + const float eps) { #ifdef __AVX2__ - const f256 colour = set8f(r, g, b, a, r, g, b, a); - const f256 eps8 = splat8f(eps); - const size_t count2 = count & ~0x1ULL; - size_t i = 0; - - // check all values that can be processed in blocks of 4 - for(; i < count2 * 4; i += 8) - { - const f256 in = loadu8f(rgba + i); - const f256 diff = abs8f(sub8f(in, colour)); - const f256 cmp = cmpgt8f(diff, eps8); - if(movemask8f(cmp)) - return false; - } - - if(count & 1) - { - const f128 in = loadu4f(rgba + i); - const f128 diff = abs4f(sub4f(in, cast4f(colour))); - const f128 cmp = cmpgt4f(diff, cast4f(eps8)); - if(movemask4f(cmp)) - return false; - } + const f256 colour = set8f(r, g, b, a, r, g, b, a); + const f256 eps8 = splat8f(eps); + const size_t count2 = count & ~0x1ULL; + size_t i = 0; + + // check all values that can be processed in blocks of 4 + for (; i < count2 * 4; i += 8) { + const f256 in = loadu8f(rgba + i); + const f256 diff = abs8f(sub8f(in, colour)); + const f256 cmp = cmpgt8f(diff, eps8); + if (movemask8f(cmp)) + return false; + } + + if (count & 1) { + const f128 in = loadu4f(rgba + i); + const f128 diff = abs4f(sub4f(in, cast4f(colour))); + const f128 cmp = cmpgt4f(diff, cast4f(eps8)); + if (movemask4f(cmp)) + return false; + } #elif defined(__SSE__) - const f128 colour = set4f(r, g, b, a); - const f128 eps4 = splat4f(eps); - - // check all values that can be processed in blocks of 4 - for(size_t i = 0; i < count * 4; i += 4) - { - const f128 in = loadu4f(rgba + i); - const f128 diff = abs4f(sub4f(in, colour)); - const f128 cmp = cmpgt4f(diff, eps4); - if(movemask4f(cmp)) - return false; - } + const f128 colour = set4f(r, g, b, a); + const f128 eps4 = splat4f(eps); + + // check all values that can be processed in blocks of 4 + for (size_t i = 0; i < count * 4; i += 4) { + const f128 in = loadu4f(rgba + i); + const f128 diff = abs4f(sub4f(in, colour)); + const f128 cmp = cmpgt4f(diff, eps4); + if (movemask4f(cmp)) + return false; + } #else - for(size_t i = 0; i < count * 4; i += 4) - { - if(std::abs(rgba[i + 0] - r) > eps || - std::abs(rgba[i + 1] - g) > eps || - std::abs(rgba[i + 2] - b) > eps || - std::abs(rgba[i + 3] - a) > eps) - return false; - } + for (size_t i = 0; i < count * 4; i += 4) { + if (std::abs(rgba[i + 0] - r) > eps || std::abs(rgba[i + 1] - g) > eps + || std::abs(rgba[i + 2] - b) > eps || std::abs(rgba[i + 3] - a) > eps) + return false; + } #endif - return true; + return true; } -} // MayaUsdUtils +} // namespace MayaUsdUtils diff --git a/lib/usd/utils/DiffCore.h b/lib/usd/utils/DiffCore.h index eefdff6839..89c4c84e05 100644 --- a/lib/usd/utils/DiffCore.h +++ b/lib/usd/utils/DiffCore.h @@ -15,11 +15,11 @@ // #pragma once -#include - #include #include +#include + namespace MayaUsdUtils { //---------------------------------------------------------------------------------------------------------------------- @@ -99,10 +99,10 @@ bool vec4AreAllTheSame(const double* array, size_t count); MAYA_USD_UTILS_PUBLIC bool compareArray( const GfHalf* const input0, - const float* const input1, - const size_t count0, - const size_t count1, - const float eps = 1e-3f); + const float* const input1, + const size_t count0, + const size_t count1, + const float eps = 1e-3f); //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -115,11 +115,14 @@ bool compareArray( /// or the contents of the arrays differ //---------------------------------------------------------------------------------------------------------------------- inline bool compareArray( - const float* const input0, + const float* const input0, const GfHalf* const input1, - const size_t count0, - const size_t count1, - const float eps = 1e-3f) { return compareArray(input1, input0, count1, count0, eps); } + const size_t count0, + const size_t count1, + const float eps = 1e-3f) +{ + return compareArray(input1, input0, count1, count0, eps); +} //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -135,9 +138,9 @@ MAYA_USD_UTILS_PUBLIC bool compareArray( const GfHalf* const input0, const double* const input1, - const size_t count0, - const size_t count1, - const double eps = 1e-5f); + const size_t count0, + const size_t count1, + const double eps = 1e-5f); //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -152,9 +155,12 @@ bool compareArray( inline bool compareArray( const double* const input0, const GfHalf* const input1, - const size_t count0, - const size_t count1, - const float eps = 1e-3f) { return compareArray(input1, input0, count1, count0, eps); } + const size_t count0, + const size_t count1, + const float eps = 1e-3f) +{ + return compareArray(input1, input0, count1, count0, eps); +} //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -170,12 +176,13 @@ MAYA_USD_UTILS_PUBLIC bool compareArray( const float* const input0, const float* const input1, - const size_t count0, - const size_t count1, - const float eps = 1e-5f); + const size_t count0, + const size_t count1, + const float eps = 1e-5f); //---------------------------------------------------------------------------------------------------------------------- -/// \brief Compares a vector 3 array against a vector 4D array, ignoring the 4d component, and checking for equality +/// \brief Compares a vector 3 array against a vector 4D array, ignoring the 4d component, and +/// checking for equality /// in all of the remaining 3d components. /// \param input3d the first input array to test /// \param input4d the second input array to test @@ -189,18 +196,18 @@ MAYA_USD_UTILS_PUBLIC bool compareArray3Dto4D( const float* const input3d, const float* const input4d, - const size_t count3d, - const size_t count4d, - const float eps = 1e-5f); + const size_t count3d, + const size_t count4d, + const float eps = 1e-5f); //---------------------------------------------------------------------------------------------------------------------- MAYA_USD_UTILS_PUBLIC bool compareArrayFloat3DtoDouble4D( - const float* const input3d, + const float* const input3d, const double* const input4d, - const size_t count3d, - const size_t count4d, - const float eps = 1e-5f); + const size_t count3d, + const size_t count4d, + const float eps = 1e-5f); //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -216,9 +223,9 @@ MAYA_USD_UTILS_PUBLIC bool compareArray( const double* const input0, const double* const input1, - const size_t count0, - const size_t count1, - const double eps = 1e-5); + const size_t count0, + const size_t count1, + const double eps = 1e-5); //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -233,10 +240,10 @@ bool compareArray( MAYA_USD_UTILS_PUBLIC bool compareArray( const double* const input0, - const float* const input1, - const size_t count0, - const size_t count1, - const float eps = 1e-5f); + const float* const input1, + const size_t count0, + const size_t count1, + const float eps = 1e-5f); //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -249,11 +256,14 @@ bool compareArray( /// or the contents of the arrays differ //---------------------------------------------------------------------------------------------------------------------- inline bool compareArray( - const float* const input0, + const float* const input0, const double* const input1, - const size_t count0, - const size_t count1, - const float eps = 1e-5f) { return compareArray(input1, input0, count1, count0, eps); } + const size_t count0, + const size_t count1, + const float eps = 1e-5f) +{ + return compareArray(input1, input0, count1, count0, eps); +} //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -269,8 +279,8 @@ MAYA_USD_UTILS_PUBLIC bool compareArray( const int8_t* const input0, const int8_t* const input1, - const size_t count0, - const size_t count1); + const size_t count0, + const size_t count1); //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -285,8 +295,11 @@ bool compareArray( inline bool compareArray( const uint8_t* const input0, const uint8_t* const input1, - const size_t count0, - const size_t count1) { return compareArray((const int8_t*)input0, (const int8_t*)input1, count0, count1); } + const size_t count0, + const size_t count1) +{ + return compareArray((const int8_t*)input0, (const int8_t*)input1, count0, count1); +} //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -301,8 +314,11 @@ inline bool compareArray( inline bool compareArray( const int16_t* const input0, const int16_t* const input1, - const size_t count0, - const size_t count1) { return compareArray((const int8_t*)input0, (const int8_t*)input1, count0 << 1, count1 << 1); } + const size_t count0, + const size_t count1) +{ + return compareArray((const int8_t*)input0, (const int8_t*)input1, count0 << 1, count1 << 1); +} //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -317,8 +333,11 @@ inline bool compareArray( inline bool compareArray( const uint16_t* const input0, const uint16_t* const input1, - const size_t count0, - const size_t count1) { return compareArray((const int8_t*)input0, (const int8_t*)input1, count0 << 1, count1 << 1); } + const size_t count0, + const size_t count1) +{ + return compareArray((const int8_t*)input0, (const int8_t*)input1, count0 << 1, count1 << 1); +} //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -334,8 +353,8 @@ MAYA_USD_UTILS_PUBLIC bool compareArray( const int32_t* const input0, const int32_t* const input1, - const size_t count0, - const size_t count1); + const size_t count0, + const size_t count1); //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -350,8 +369,11 @@ bool compareArray( inline bool compareArray( const uint32_t* const input0, const uint32_t* const input1, - const size_t count0, - const size_t count1) { return compareArray((const int32_t*)input0, (const int32_t*)input1, count0, count1); } + const size_t count0, + const size_t count1) +{ + return compareArray((const int32_t*)input0, (const int32_t*)input1, count0, count1); +} //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -366,8 +388,11 @@ inline bool compareArray( inline bool compareArray( const int64_t* const input0, const int64_t* const input1, - const size_t count0, - const size_t count1) { return compareArray((const int32_t*)input0, (const int32_t*)input1, count0 << 1, count1 << 1); } + const size_t count0, + const size_t count1) +{ + return compareArray((const int32_t*)input0, (const int32_t*)input1, count0 << 1, count1 << 1); +} //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -382,8 +407,11 @@ inline bool compareArray( inline bool compareArray( const uint64_t* const input0, const uint64_t* const input1, - const size_t count0, - const size_t count1) { return compareArray((const int32_t*)input0, (const int32_t*)input1, count0 << 1, count1 << 1); } + const size_t count0, + const size_t count1) +{ + return compareArray((const int32_t*)input0, (const int32_t*)input1, count0 << 1, count1 << 1); +} //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -400,9 +428,9 @@ bool compareUvArray( const float* const u0, const float* const v0, const float* const uv1, - const size_t count0, - const size_t count1, - const float eps = 1e-5f); + const size_t count0, + const size_t count1, + const float eps = 1e-5f); //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -416,12 +444,12 @@ bool compareUvArray( //---------------------------------------------------------------------------------------------------------------------- MAYA_USD_UTILS_PUBLIC bool compareUvArray( - const float u0, - const float v0, + const float u0, + const float v0, const float* const u1, const float* const v1, - const size_t count, - const float eps = 1e-5f); + const size_t count, + const float eps = 1e-5f); //---------------------------------------------------------------------------------------------------------------------- /// \brief a simple method to check for differences between a pair of arrays. @@ -435,13 +463,13 @@ bool compareUvArray( //---------------------------------------------------------------------------------------------------------------------- MAYA_USD_UTILS_PUBLIC bool compareRGBAArray( - const float r, - const float g, - const float b, - const float a, + const float r, + const float g, + const float b, + const float a, const float* const rgba, - const size_t count, - const float eps = 1e-5f); + const size_t count, + const float eps = 1e-5f); //---------------------------------------------------------------------------------------------------------------------- -} // MayaUsdUtils +} // namespace MayaUsdUtils diff --git a/lib/usd/utils/ForwardDeclares.h b/lib/usd/utils/ForwardDeclares.h index e73e40e41a..c8689f6ac2 100644 --- a/lib/usd/utils/ForwardDeclares.h +++ b/lib/usd/utils/ForwardDeclares.h @@ -37,5 +37,5 @@ class UsdReferences; PXR_NAMESPACE_CLOSE_SCOPE namespace MayaUsdUtils { - typedef std::vector UsdPrimVector; -} // MayaUsdUtils +typedef std::vector UsdPrimVector; +} // namespace MayaUsdUtils diff --git a/lib/usd/utils/SIMD.h b/lib/usd/utils/SIMD.h index 8df5acb1c2..622bc6c9c6 100644 --- a/lib/usd/utils/SIMD.h +++ b/lib/usd/utils/SIMD.h @@ -16,61 +16,61 @@ #pragma once #ifdef _WIN32 -# define ALIGN16(X) __declspec(align(16)) X -# define ALIGN32(X) __declspec(align(32)) X +#define ALIGN16(X) __declspec(align(16)) X +#define ALIGN32(X) __declspec(align(32)) X #else -# define ALIGN16(X) X __attribute__((aligned(16))) -# define ALIGN32(X) X __attribute__((aligned(32))) +#define ALIGN16(X) X __attribute__((aligned(16))) +#define ALIGN32(X) X __attribute__((aligned(32))) #endif #include #ifdef __AVX2__ -# include +#include #endif #ifdef __SSE__ -# include +#include #endif #ifdef __SSE2__ -# include +#include #endif #ifdef __SSE3__ -# include +#include #endif #ifdef __SSE4_1__ -# include +#include #endif #if (__GNUC__ >= 4) -# define AL_DLL_HIDDEN __attribute__ ((visibility ("hidden"))) +#define AL_DLL_HIDDEN __attribute__((visibility("hidden"))) #else -# define AL_DLL_HIDDEN +#define AL_DLL_HIDDEN #endif // For reasons unknown, GCC 4.8 fails to correctly assemble certain AVX2 instructions. // This is a known issue that was fixed in gcc 4.9. #if (__GNUC__ <= 4) && (__GNUC_MINOR__ <= 8) -# define ENABLE_SOME_AVX_ROUTINES 0 +#define ENABLE_SOME_AVX_ROUTINES 0 #else -# define ENABLE_SOME_AVX_ROUTINES 1 +#define ENABLE_SOME_AVX_ROUTINES 1 #endif namespace MayaUsdUtils { #if defined(__SSE__) -typedef __m128 f128; +typedef __m128 f128; typedef __m128i i128; typedef __m128d d128; -# define shiftBytesLeft(reg, count) _mm_slli_si128(reg, count) -# define shiftBytesRight(reg, count) _mm_srli_si128(reg, count) -# define shuffle4f(a, b, W, Z, Y, X) _mm_shuffle_ps(a, b, _MM_SHUFFLE(W, Z, Y, X)) +#define shiftBytesLeft(reg, count) _mm_slli_si128(reg, count) +#define shiftBytesRight(reg, count) _mm_srli_si128(reg, count) +#define shuffle4f(a, b, W, Z, Y, X) _mm_shuffle_ps(a, b, _MM_SHUFFLE(W, Z, Y, X)) -# define lshift64(X, N) _mm_slli_epi64(X, N) +#define lshift64(X, N) _mm_slli_epi64(X, N) AL_DLL_HIDDEN inline f128 zero4f() { return _mm_setzero_ps(); } AL_DLL_HIDDEN inline i128 zero4i() { return _mm_setzero_si128(); } @@ -84,8 +84,14 @@ AL_DLL_HIDDEN inline d128 cast2d(const f128 reg) { return _mm_castps_pd(reg); } AL_DLL_HIDDEN inline d128 cast2d(const i128 reg) { return _mm_castsi128_pd(reg); } AL_DLL_HIDDEN inline f128 load1f(const void* const ptr) { return _mm_load_ss((const float*)ptr); } -AL_DLL_HIDDEN inline f128 load2f(const void* const ptr) { return cast4f(_mm_load_sd((const double*)ptr)); } -AL_DLL_HIDDEN inline i128 load2i(const void* const ptr) { return cast4i(_mm_load_sd((const double*)ptr)); } +AL_DLL_HIDDEN inline f128 load2f(const void* const ptr) +{ + return cast4f(_mm_load_sd((const double*)ptr)); +} +AL_DLL_HIDDEN inline i128 load2i(const void* const ptr) +{ + return cast4i(_mm_load_sd((const double*)ptr)); +} AL_DLL_HIDDEN inline int32_t movemask16i8(const i128 reg) { return _mm_movemask_epi8(reg); } AL_DLL_HIDDEN inline int32_t movemask4i(const i128 reg) { return _mm_movemask_ps(cast4f(reg)); } @@ -104,40 +110,90 @@ AL_DLL_HIDDEN inline f128 cmpne4f(const f128 a, const f128 b) { return _mm_cmpne AL_DLL_HIDDEN inline d128 cmpne2d(const d128 a, const d128 b) { return _mm_cmpneq_pd(a, b); } AL_DLL_HIDDEN inline i128 cmpeq8i16(const i128 a, const i128 b) { return _mm_cmpeq_epi16(a, b); } -AL_DLL_HIDDEN inline f128 set4f(const float a, const float b, const float c, const float d) {return _mm_setr_ps(a, b, c, d); } -AL_DLL_HIDDEN inline i128 set4i(const int32_t a, const int32_t b, const int32_t c, const int32_t d) {return _mm_setr_epi32(a, b, c, d); } -AL_DLL_HIDDEN inline d128 set2d(const double a, const double b) {return _mm_setr_pd(a, b); } +AL_DLL_HIDDEN inline f128 set4f(const float a, const float b, const float c, const float d) +{ + return _mm_setr_ps(a, b, c, d); +} +AL_DLL_HIDDEN inline i128 set4i(const int32_t a, const int32_t b, const int32_t c, const int32_t d) +{ + return _mm_setr_epi32(a, b, c, d); +} +AL_DLL_HIDDEN inline d128 set2d(const double a, const double b) { return _mm_setr_pd(a, b); } AL_DLL_HIDDEN inline i128 set16i8( - const int8_t a0, const int8_t b0, const int8_t c0, const int8_t d0, - const int8_t a1, const int8_t b1, const int8_t c1, const int8_t d1, - const int8_t a2, const int8_t b2, const int8_t c2, const int8_t d2, - const int8_t a3, const int8_t b3, const int8_t c3, const int8_t d3) -{return _mm_setr_epi8(a0, b0, c0, d0, a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3); } + const int8_t a0, + const int8_t b0, + const int8_t c0, + const int8_t d0, + const int8_t a1, + const int8_t b1, + const int8_t c1, + const int8_t d1, + const int8_t a2, + const int8_t b2, + const int8_t c2, + const int8_t d2, + const int8_t a3, + const int8_t b3, + const int8_t c3, + const int8_t d3) +{ + return _mm_setr_epi8(a0, b0, c0, d0, a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3); +} AL_DLL_HIDDEN inline f128 loadu4f(const void* const ptr) { return _mm_loadu_ps((const float*)ptr); } -AL_DLL_HIDDEN inline i128 loadu4i(const void* const ptr) { return _mm_loadu_si128((const i128*)ptr); } -AL_DLL_HIDDEN inline d128 loadu2d(const void* const ptr) { return _mm_loadu_pd((const double*)ptr); } +AL_DLL_HIDDEN inline i128 loadu4i(const void* const ptr) +{ + return _mm_loadu_si128((const i128*)ptr); +} +AL_DLL_HIDDEN inline d128 loadu2d(const void* const ptr) +{ + return _mm_loadu_pd((const double*)ptr); +} AL_DLL_HIDDEN inline f128 load4f(const void* const ptr) { return _mm_load_ps((const float*)ptr); } AL_DLL_HIDDEN inline i128 load4i(const void* const ptr) { return _mm_load_si128((const i128*)ptr); } AL_DLL_HIDDEN inline d128 load2d(const void* const ptr) { return _mm_load_pd((const double*)ptr); } -AL_DLL_HIDDEN inline void storeu4f(void* const ptr, const f128 reg) { _mm_storeu_ps((float*)ptr, reg); } -AL_DLL_HIDDEN inline void storeu4i(void* const ptr, const i128 reg) { _mm_storeu_si128((i128*)ptr, reg); } -AL_DLL_HIDDEN inline void storeu2d(void* const ptr, const d128 reg) { _mm_storeu_pd((double*)ptr, reg); } +AL_DLL_HIDDEN inline void storeu4f(void* const ptr, const f128 reg) +{ + _mm_storeu_ps((float*)ptr, reg); +} +AL_DLL_HIDDEN inline void storeu4i(void* const ptr, const i128 reg) +{ + _mm_storeu_si128((i128*)ptr, reg); +} +AL_DLL_HIDDEN inline void storeu2d(void* const ptr, const d128 reg) +{ + _mm_storeu_pd((double*)ptr, reg); +} -AL_DLL_HIDDEN inline void store4f(void* const ptr, const f128 reg) { _mm_store_ps((float*)ptr, reg); } -AL_DLL_HIDDEN inline void store4i(void* const ptr, const i128 reg) { _mm_store_si128((i128*)ptr, reg); } -AL_DLL_HIDDEN inline void store2d(void* const ptr, const d128 reg) { _mm_store_pd((double*)ptr, reg); } +AL_DLL_HIDDEN inline void store4f(void* const ptr, const f128 reg) +{ + _mm_store_ps((float*)ptr, reg); +} +AL_DLL_HIDDEN inline void store4i(void* const ptr, const i128 reg) +{ + _mm_store_si128((i128*)ptr, reg); +} +AL_DLL_HIDDEN inline void store2d(void* const ptr, const d128 reg) +{ + _mm_store_pd((double*)ptr, reg); +} AL_DLL_HIDDEN inline d128 cvt2f_to_2d(const f128 reg) { return _mm_cvtps_pd(reg); } AL_DLL_HIDDEN inline f128 cvt2d_to_2f(const d128 reg) { return _mm_cvtpd_ps(reg); } AL_DLL_HIDDEN inline f128 movehl4f(const f128 a, const f128 b) { return _mm_movehl_ps(a, b); } AL_DLL_HIDDEN inline f128 movelh4f(const f128 a, const f128 b) { return _mm_movelh_ps(a, b); } -AL_DLL_HIDDEN inline i128 movehl4i(const i128 a, const i128 b) { return cast4i(_mm_movehl_ps(cast4f(a), cast4f(b))); } -AL_DLL_HIDDEN inline i128 movelh4i(const i128 a, const i128 b) { return cast4i(_mm_movelh_ps(cast4f(a), cast4f(b))); } +AL_DLL_HIDDEN inline i128 movehl4i(const i128 a, const i128 b) +{ + return cast4i(_mm_movehl_ps(cast4f(a), cast4f(b))); +} +AL_DLL_HIDDEN inline i128 movelh4i(const i128 a, const i128 b) +{ + return cast4i(_mm_movelh_ps(cast4f(a), cast4f(b))); +} AL_DLL_HIDDEN inline d128 or2d(const d128 a, const d128 b) { return _mm_or_pd(a, b); } AL_DLL_HIDDEN inline f128 or4f(const f128 a, const f128 b) { return _mm_or_ps(a, b); } @@ -169,43 +225,45 @@ AL_DLL_HIDDEN inline i128 splat2i64(const int64_t f) { return _mm_set1_epi64x(f) AL_DLL_HIDDEN inline f128 unpacklo4f(const f128 a, const f128 b) { return _mm_unpacklo_ps(a, b); } AL_DLL_HIDDEN inline f128 unpackhi4f(const f128 a, const f128 b) { return _mm_unpackhi_ps(a, b); } -# if !defined(__SSE4__) && !defined(__SSE4_1__) && !defined(__SSE4_2__) && !defined(__AVX__) && !defined(__AVX2__) +#if !defined(__SSE4__) && !defined(__SSE4_1__) && !defined(__SSE4_2__) && !defined(__AVX__) \ + && !defined(__AVX2__) AL_DLL_HIDDEN inline __m128 _mm_blendv_ps(__m128 a, __m128 b, __m128 c) { - return _mm_or_ps(_mm_and_ps(c, b), _mm_andnot_ps(c, a)); + return _mm_or_ps(_mm_and_ps(c, b), _mm_andnot_ps(c, a)); } -# else +#else AL_DLL_HIDDEN inline i128 cvt2i32_to_2i64(const i128 reg) { return _mm_cvtepi32_epi64(reg); } -# endif +#endif -AL_DLL_HIDDEN inline f128 select4f(const f128 falseResult, const f128 trueResult, const f128 cmp) { return _mm_blendv_ps(falseResult, trueResult, cmp); } +AL_DLL_HIDDEN inline f128 select4f(const f128 falseResult, const f128 trueResult, const f128 cmp) +{ + return _mm_blendv_ps(falseResult, trueResult, cmp); +} -# define shiftBytesLeft128(reg, count) _mm_slli_si128(reg, count) -# define shiftBytesRight128(reg, count) _mm_srli_si128(reg, count) -# define shiftBitsLeft4i32(reg, count) _mm_slli_epi32(reg, count) -# define shiftBitsRight4i32(reg, count) _mm_srli_epi32(reg, count) -# define shiftBitsLeft2i64(reg, count) _mm_slli_epi64(reg, count) -# define shiftBitsRight2i64(reg, count) _mm_srli_epi64(reg, count) +#define shiftBytesLeft128(reg, count) _mm_slli_si128(reg, count) +#define shiftBytesRight128(reg, count) _mm_srli_si128(reg, count) +#define shiftBitsLeft4i32(reg, count) _mm_slli_epi32(reg, count) +#define shiftBitsRight4i32(reg, count) _mm_srli_epi32(reg, count) +#define shiftBitsLeft2i64(reg, count) _mm_slli_epi64(reg, count) +#define shiftBitsRight2i64(reg, count) _mm_srli_epi64(reg, count) -# if defined(__SSE4_1__) +#if defined(__SSE4_1__) AL_DLL_HIDDEN inline i128 cmpeq2i64(const i128 a, const i128 b) { return _mm_cmpeq_epi64(a, b); } -# endif +#endif -# define extract128i64(reg, index) _mm_extract_epi64(reg, index) +#define extract128i64(reg, index) _mm_extract_epi64(reg, index) inline f128 abs4f(const f128 v) { return _mm_andnot_ps(splat4f(-0.0f), v); } inline d128 abs2d(const d128 v) { return _mm_andnot_pd(splat2d(-0.0), v); } #endif - #if defined(__AVX2__) -typedef __m256 f256; +typedef __m256 f256; typedef __m256i i256; typedef __m256d d256; - -# define shuffle8f(a, b, W, Z, Y, X) _mm256_shuffle_ps(a, b, _MM_SHUFFLE(W, Z, Y, X)) +#define shuffle8f(a, b, W, Z, Y, X) _mm256_shuffle_ps(a, b, _MM_SHUFFLE(W, Z, Y, X)) AL_DLL_HIDDEN inline f256 zero8f() { return _mm256_setzero_ps(); } AL_DLL_HIDDEN inline i256 zero8i() { return _mm256_setzero_si256(); } @@ -226,40 +284,110 @@ AL_DLL_HIDDEN inline int32_t movemask4d(const d256 reg) { return _mm256_movemask AL_DLL_HIDDEN inline i256 cmpeq8i(const i256 a, const i256 b) { return _mm256_cmpeq_epi32(a, b); } -# define permute2f128(a, b, mask) _mm256_permute2f128_ps(a, b, mask) +#define permute2f128(a, b, mask) _mm256_permute2f128_ps(a, b, mask) -template -AL_DLL_HIDDEN inline f256 permute128f(const f256 a, const f256 b) { return _mm256_permute2f128_ps(a, b, X | (Y << 4)); } +template AL_DLL_HIDDEN inline f256 permute128f(const f256 a, const f256 b) +{ + return _mm256_permute2f128_ps(a, b, X | (Y << 4)); +} -AL_DLL_HIDDEN inline d256 set4d(const d128 a, const d128 b) { return _mm256_insertf128_pd(_mm256_castpd128_pd256(a), b, 1); } -AL_DLL_HIDDEN inline f256 set8f(const f128 a, const f128 b) { return _mm256_insertf128_ps(_mm256_castps128_ps256(a), b, 1); } -AL_DLL_HIDDEN inline i256 set8i(const i128 a, const i128 b) { return _mm256_inserti128_si256(_mm256_castsi128_si256(a), b, 1); } +AL_DLL_HIDDEN inline d256 set4d(const d128 a, const d128 b) +{ + return _mm256_insertf128_pd(_mm256_castpd128_pd256(a), b, 1); +} +AL_DLL_HIDDEN inline f256 set8f(const f128 a, const f128 b) +{ + return _mm256_insertf128_ps(_mm256_castps128_ps256(a), b, 1); +} +AL_DLL_HIDDEN inline i256 set8i(const i128 a, const i128 b) +{ + return _mm256_inserti128_si256(_mm256_castsi128_si256(a), b, 1); +} -AL_DLL_HIDDEN inline d256 set4d(const double a, const double b, const double c, const double d) { return _mm256_setr_pd(a, b, c, d); } -AL_DLL_HIDDEN inline f256 set8f(const float a, const float b, const float c, const float d, - const float e, const float f, const float g, const float h) - {return _mm256_setr_ps(a,b,c,d,e,f,g,h); } -AL_DLL_HIDDEN inline i256 set8i(const int32_t a, const int32_t b, const int32_t c, const int32_t d, - const int32_t e, const int32_t f, const int32_t g, const int32_t h) - {return _mm256_setr_epi32(a,b,c,d,e,f,g,h); } +AL_DLL_HIDDEN inline d256 set4d(const double a, const double b, const double c, const double d) +{ + return _mm256_setr_pd(a, b, c, d); +} +AL_DLL_HIDDEN inline f256 set8f( + const float a, + const float b, + const float c, + const float d, + const float e, + const float f, + const float g, + const float h) +{ + return _mm256_setr_ps(a, b, c, d, e, f, g, h); +} +AL_DLL_HIDDEN inline i256 set8i( + const int32_t a, + const int32_t b, + const int32_t c, + const int32_t d, + const int32_t e, + const int32_t f, + const int32_t g, + const int32_t h) +{ + return _mm256_setr_epi32(a, b, c, d, e, f, g, h); +} AL_DLL_HIDDEN inline d256 set4f(const double a, const double b, const double c, const double d) - {return _mm256_setr_pd(a, b, c, d); } +{ + return _mm256_setr_pd(a, b, c, d); +} -AL_DLL_HIDDEN inline f256 loadu8f(const void* const ptr) { return _mm256_loadu_ps((const float*)ptr); } -AL_DLL_HIDDEN inline i256 loadu8i(const void* const ptr) { return _mm256_loadu_si256((const i256*)ptr); } -AL_DLL_HIDDEN inline d256 loadu4d(const void* const ptr) { return _mm256_loadu_pd((const double*)ptr); } +AL_DLL_HIDDEN inline f256 loadu8f(const void* const ptr) +{ + return _mm256_loadu_ps((const float*)ptr); +} +AL_DLL_HIDDEN inline i256 loadu8i(const void* const ptr) +{ + return _mm256_loadu_si256((const i256*)ptr); +} +AL_DLL_HIDDEN inline d256 loadu4d(const void* const ptr) +{ + return _mm256_loadu_pd((const double*)ptr); +} -AL_DLL_HIDDEN inline f256 load8f(const void* const ptr) { return _mm256_load_ps((const float*)ptr); } -AL_DLL_HIDDEN inline i256 load8i(const void* const ptr) { return _mm256_load_si256((const i256*)ptr); } -AL_DLL_HIDDEN inline d256 load4d(const void* const ptr) { return _mm256_load_pd((const double*)ptr); } +AL_DLL_HIDDEN inline f256 load8f(const void* const ptr) +{ + return _mm256_load_ps((const float*)ptr); +} +AL_DLL_HIDDEN inline i256 load8i(const void* const ptr) +{ + return _mm256_load_si256((const i256*)ptr); +} +AL_DLL_HIDDEN inline d256 load4d(const void* const ptr) +{ + return _mm256_load_pd((const double*)ptr); +} -AL_DLL_HIDDEN inline void storeu8f(void* const ptr, const f256 reg) { _mm256_storeu_ps((float*)ptr, reg); } -AL_DLL_HIDDEN inline void storeu8i(void* const ptr, const i256 reg) { _mm256_storeu_si256((i256*)ptr, reg); } -AL_DLL_HIDDEN inline void storeu4d(void* const ptr, const d256 reg) { _mm256_storeu_pd((double*)ptr, reg); } +AL_DLL_HIDDEN inline void storeu8f(void* const ptr, const f256 reg) +{ + _mm256_storeu_ps((float*)ptr, reg); +} +AL_DLL_HIDDEN inline void storeu8i(void* const ptr, const i256 reg) +{ + _mm256_storeu_si256((i256*)ptr, reg); +} +AL_DLL_HIDDEN inline void storeu4d(void* const ptr, const d256 reg) +{ + _mm256_storeu_pd((double*)ptr, reg); +} -AL_DLL_HIDDEN inline void store8f(void* const ptr, const f256 reg) { _mm256_store_ps((float*)ptr, reg); } -AL_DLL_HIDDEN inline void store8i(void* const ptr, const i256 reg) { _mm256_store_si256((i256*)ptr, reg); } -AL_DLL_HIDDEN inline void store4d(void* const ptr, const d256 reg) { _mm256_store_pd((double*)ptr, reg); } +AL_DLL_HIDDEN inline void store8f(void* const ptr, const f256 reg) +{ + _mm256_store_ps((float*)ptr, reg); +} +AL_DLL_HIDDEN inline void store8i(void* const ptr, const i256 reg) +{ + _mm256_store_si256((i256*)ptr, reg); +} +AL_DLL_HIDDEN inline void store4d(void* const ptr, const d256 reg) +{ + _mm256_store_pd((double*)ptr, reg); +} AL_DLL_HIDDEN inline d256 cvt4f_to_4d(const f128 reg) { return _mm256_cvtps_pd(reg); } AL_DLL_HIDDEN inline f128 cvt4d_to_4f(const d256 reg) { return _mm256_cvtpd_ps(reg); } @@ -287,34 +415,61 @@ AL_DLL_HIDDEN inline i256 sub8i(const i256 a, const i256 b) { return _mm256_sub_ AL_DLL_HIDDEN inline d256 sub4d(const d256 a, const d256 b) { return _mm256_sub_pd(a, b); } AL_DLL_HIDDEN inline i256 sub4i64(const i256 a, const i256 b) { return _mm256_sub_epi64(a, b); } -AL_DLL_HIDDEN inline f256 select8f(const f256 falseResult, const f256 trueResult, const f256 cmp) { return _mm256_blendv_ps(falseResult, trueResult, cmp); } +AL_DLL_HIDDEN inline f256 select8f(const f256 falseResult, const f256 trueResult, const f256 cmp) +{ + return _mm256_blendv_ps(falseResult, trueResult, cmp); +} -AL_DLL_HIDDEN inline f256 permutevar8x32f(const f256 a, const i256 b) { return _mm256_permutevar8x32_ps(a, b); } +AL_DLL_HIDDEN inline f256 permutevar8x32f(const f256 a, const i256 b) +{ + return _mm256_permutevar8x32_ps(a, b); +} -AL_DLL_HIDDEN inline f256 unpacklo8f(const f256 a, const f256 b) { return _mm256_unpacklo_ps(a, b); } -AL_DLL_HIDDEN inline f256 unpackhi8f(const f256 a, const f256 b) { return _mm256_unpackhi_ps(a, b); } +AL_DLL_HIDDEN inline f256 unpacklo8f(const f256 a, const f256 b) +{ + return _mm256_unpacklo_ps(a, b); +} +AL_DLL_HIDDEN inline f256 unpackhi8f(const f256 a, const f256 b) +{ + return _mm256_unpackhi_ps(a, b); +} -# define extract4f(reg, index) _mm256_extractf128_ps(reg, index) -# define extract256i64(reg, index) _mm256_extract_epi64(reg, index) +#define extract4f(reg, index) _mm256_extractf128_ps(reg, index) +#define extract256i64(reg, index) _mm256_extract_epi64(reg, index) AL_DLL_HIDDEN inline f256 splat8f(const float f) { return _mm256_set1_ps(f); } AL_DLL_HIDDEN inline d256 splat4d(const double f) { return _mm256_set1_pd(f); } AL_DLL_HIDDEN inline i256 splat8i(const int32_t f) { return _mm256_set1_epi32(f); } AL_DLL_HIDDEN inline i256 splat4i64(const int64_t f) { return _mm256_set1_epi64x(f); } -AL_DLL_HIDDEN inline f128 i32gather4f(const float* const ptr, const i128 indices) { return _mm_i32gather_ps(ptr, indices, 4); } -AL_DLL_HIDDEN inline f256 i32gather8f(const float* const ptr, const i256 indices) { return _mm256_i32gather_ps(ptr, indices, 4); } -AL_DLL_HIDDEN inline i128 i32gather4i(const int32_t* const ptr, const i128 indices) { return _mm_i32gather_epi32(ptr, indices, 4); } -AL_DLL_HIDDEN inline i256 i32gather8i(const int32_t* const ptr, const i256 indices) { return _mm256_i32gather_epi32(ptr, indices, 4); } +AL_DLL_HIDDEN inline f128 i32gather4f(const float* const ptr, const i128 indices) +{ + return _mm_i32gather_ps(ptr, indices, 4); +} +AL_DLL_HIDDEN inline f256 i32gather8f(const float* const ptr, const i256 indices) +{ + return _mm256_i32gather_ps(ptr, indices, 4); +} +AL_DLL_HIDDEN inline i128 i32gather4i(const int32_t* const ptr, const i128 indices) +{ + return _mm_i32gather_epi32(ptr, indices, 4); +} +AL_DLL_HIDDEN inline i256 i32gather8i(const int32_t* const ptr, const i256 indices) +{ + return _mm256_i32gather_epi32(ptr, indices, 4); +} -AL_DLL_HIDDEN inline f256 set2f128(const f128 lo, const f128 hi) { return _mm256_insertf128_ps(_mm256_castps128_ps256(lo), hi, 1); } +AL_DLL_HIDDEN inline f256 set2f128(const f128 lo, const f128 hi) +{ + return _mm256_insertf128_ps(_mm256_castps128_ps256(lo), hi, 1); +} -# define shiftBytesLeft256(reg, count) _mm256_slli_si256(reg, count) -# define shiftBytesRight256(reg, count) _mm256_srli_si256(reg, count) -# define shiftBitsLeft8i32(reg, count) _mm256_slli_epi32(reg, count) -# define shiftBitsRight8i32(reg, count) _mm256_srli_epi32(reg, count) -# define shiftBitsLeft4i64(reg, count) _mm256_slli_epi64(reg, count) -# define shiftBitsRight4i64(reg, count) _mm256_srli_epi64(reg, count) +#define shiftBytesLeft256(reg, count) _mm256_slli_si256(reg, count) +#define shiftBytesRight256(reg, count) _mm256_srli_si256(reg, count) +#define shiftBitsLeft8i32(reg, count) _mm256_slli_epi32(reg, count) +#define shiftBitsRight8i32(reg, count) _mm256_srli_epi32(reg, count) +#define shiftBitsLeft4i64(reg, count) _mm256_slli_epi64(reg, count) +#define shiftBitsRight4i64(reg, count) _mm256_srli_epi64(reg, count) inline f256 cmpgt8f(const f256 a, const f256 b) { return _mm256_cmp_ps(a, b, _CMP_GT_OQ); } inline d256 cmpgt4d(const d256 a, const d256 b) { return _mm256_cmp_pd(a, b, _CMP_GT_OQ); } @@ -330,19 +485,14 @@ inline d256 abs4d(const d256 v) { return _mm256_andnot_pd(splat4d(-0.0), v); } /// \brief loads up to 7 floating point values from ptr, and sets the other elements to zero. inline f256 loadmask7f(const void* const ptr, const size_t count) { - // mask_offset = 7 - (count % 8) - // - // This gives us an index into the array of masks which we can pass into - // _mm256_maskload_ps later on. - const size_t mask_offset = (~count) & 0x7; - const int32_t masks[] = { - -1, -1, -1, -1, - -1, -1, -1, 0, - 0, 0, 0, 0, - 0, 0, 0, 0 - }; - const i256 loadmask = loadu8i(masks + mask_offset); - return _mm256_maskload_ps((const float*)ptr, loadmask); + // mask_offset = 7 - (count % 8) + // + // This gives us an index into the array of masks which we can pass into + // _mm256_maskload_ps later on. + const size_t mask_offset = (~count) & 0x7; + const int32_t masks[] = { -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + const i256 loadmask = loadu8i(masks + mask_offset); + return _mm256_maskload_ps((const float*)ptr, loadmask); } /// \brief loads up to 7 integer values from ptr, and sets the other elements to zero. @@ -353,67 +503,58 @@ inline i256 loadmask7i(const void* const ptr, const size_t count) inline d256 loadmask3d(const void* const ptr, const size_t count) { - // mask_offset = 3 - (count % 3) - // - // This gives us an index into the array of masks which we can pass into - // _mm256_maskload_ps later on. - const size_t mask_offset = (~count) & 0x3; - const int64_t masks[] = { - -1, -1, -1, 0, - 0, 0, 0, 0 - }; - const i256 loadmask = loadu8i(masks + mask_offset); - return _mm256_maskload_pd((const double*)ptr, loadmask); + // mask_offset = 3 - (count % 3) + // + // This gives us an index into the array of masks which we can pass into + // _mm256_maskload_ps later on. + const size_t mask_offset = (~count) & 0x3; + const int64_t masks[] = { -1, -1, -1, 0, 0, 0, 0, 0 }; + const i256 loadmask = loadu8i(masks + mask_offset); + return _mm256_maskload_pd((const double*)ptr, loadmask); } inline i256 loadmask3i64(const void* const ptr, const size_t count) { - return cast8i(loadmask3d(ptr, count)); + return cast8i(loadmask3d(ptr, count)); } #endif #ifdef __F16C__ -# ifdef __AVX__ +#ifdef __AVX__ inline f256 cvtph8(const i128 a) { return _mm256_cvtph_ps(a); } inline i128 cvtph8(const f256 a) { return _mm256_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION); } -# else -inline f128 cvtph4(const i128 a) { return _mm_cvtph_ps(a); } -inline i128 cvtph4(const f128 a) { return _mm_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION); } -# endif +#else +inline f128 cvtph4(const i128 a) { return _mm_cvtph_ps(a); } +inline i128 cvtph4(const f128 a) { return _mm_cvtps_ph(a, _MM_FROUND_CUR_DIRECTION); } +#endif #endif - #ifdef __AVX__ /// \brief loads up to 3 floating point values from ptr, and sets the other elements to zero. inline f128 loadmask3f(const void* const ptr, const size_t count) { - // mask_offset = 3 - (count % 3) - // - // This gives us an index into the array of masks which we can pass into - // _mm256_maskload_ps later on. - const size_t mask_offset = (~count) & 0x3; - const int32_t masks[] = { - -1, -1, -1, 0, - 0, 0, 0, 0 - }; - const i128 loadmask = loadu4i(masks + mask_offset); - return _mm_maskload_ps((const float*)ptr, loadmask); + // mask_offset = 3 - (count % 3) + // + // This gives us an index into the array of masks which we can pass into + // _mm256_maskload_ps later on. + const size_t mask_offset = (~count) & 0x3; + const int32_t masks[] = { -1, -1, -1, 0, 0, 0, 0, 0 }; + const i128 loadmask = loadu4i(masks + mask_offset); + return _mm_maskload_ps((const float*)ptr, loadmask); } #elif defined(__SSE__) /// \brief loads up to 3 floating point values from ptr, and sets the other elements to zero. inline f128 loadmask3f(const void* const ptr, size_t count) { - alignas(16) float p[4] = {0}; - const float* const fp = (const float*)ptr; - switch(count & 3) - { - case 3: p[2] = fp[2]; /* break; */ - case 2: p[1] = fp[1]; /* break; */ - case 1: p[0] = fp[0]; /* break; */ - default: break; - } - return _mm_load_ps((const float*)p); + alignas(16) float p[4] = { 0 }; + const float* const fp = (const float*)ptr; + switch (count & 3) { + case 3: p[2] = fp[2]; /* break; */ + case 2: p[1] = fp[1]; /* break; */ + case 1: p[0] = fp[0]; /* break; */ + default: break; + } + return _mm_load_ps((const float*)p); } #endif -} // MayaUsdUtils - +} // namespace MayaUsdUtils diff --git a/lib/usd/utils/util.cpp b/lib/usd/utils/util.cpp index 2903ff3631..9d45a23b6c 100644 --- a/lib/usd/utils/util.cpp +++ b/lib/usd/utils/util.cpp @@ -20,113 +20,100 @@ #include #include #include -#include #include #include +#include PXR_NAMESPACE_USING_DIRECTIVE -namespace +namespace { +std::map getDict(const UsdPrimCompositionQueryArc& arc) { - std::map - getDict(const UsdPrimCompositionQueryArc& arc) { - std::string arcType; - switch (arc.GetArcType()) { - case PcpArcTypeRoot: - arcType = "PcpArcTypeRoot"; - break; - case PcpArcTypeReference: - arcType = "PcpArcTypeReference"; - break; - case PcpArcTypePayload: - arcType = "PcpArcTypePayload"; - break; - case PcpArcTypeInherit: - arcType = "PcpArcTypeInherit"; - break; - case PcpArcTypeSpecialize: - arcType = "PcpArcTypeSpecialize"; - break; - case PcpArcTypeVariant: - arcType = "PcpArcTypeVariant"; - break; - default: - break; - } + std::string arcType; + switch (arc.GetArcType()) { + case PcpArcTypeRoot: arcType = "PcpArcTypeRoot"; break; + case PcpArcTypeReference: arcType = "PcpArcTypeReference"; break; + case PcpArcTypePayload: arcType = "PcpArcTypePayload"; break; + case PcpArcTypeInherit: arcType = "PcpArcTypeInherit"; break; + case PcpArcTypeSpecialize: arcType = "PcpArcTypeSpecialize"; break; + case PcpArcTypeVariant: arcType = "PcpArcTypeVariant"; break; + default: break; + } + + auto introducingLayer = arc.GetIntroducingLayer(); + auto introducingNode = arc.GetIntroducingNode(); + + return { + { "arcType", arcType }, + { "hasSpecs", arc.HasSpecs() ? "True" : "False" }, + { "introLayer", introducingLayer ? introducingLayer->GetRealPath() : "" }, + { "introLayerStack", + introducingNode + ? introducingNode.GetLayerStack()->GetIdentifier().rootLayer->GetRealPath() + : "" }, + { "introPath", arc.GetIntroducingPrimPath().GetString() }, + { "isAncestral", arc.IsAncestral() ? "True" : "False" }, + { "isImplicit", arc.IsImplicit() ? "True" : "False" }, + { "isIntroRootLayer", arc.IsIntroducedInRootLayerStack() ? "True" : "False" }, + { "isIntroRootLayerPrim", arc.IsIntroducedInRootLayerPrimSpec() ? "True" : "False" }, + { "nodeLayerStack", + arc.GetTargetNode().GetLayerStack()->GetIdentifier().rootLayer->GetRealPath() }, + { "nodePath", arc.GetTargetNode().GetPath().GetString() }, + }; +} - auto introducingLayer = arc.GetIntroducingLayer(); - auto introducingNode = arc.GetIntroducingNode(); - - return { - {"arcType" , arcType}, - {"hasSpecs", arc.HasSpecs() ? "True" : "False"}, - {"introLayer", introducingLayer ? introducingLayer->GetRealPath() : ""}, - {"introLayerStack", introducingNode ? introducingNode.GetLayerStack()->GetIdentifier().rootLayer->GetRealPath() : ""}, - {"introPath", arc.GetIntroducingPrimPath().GetString()}, - {"isAncestral", arc.IsAncestral() ? "True" : "False"}, - {"isImplicit", arc.IsImplicit() ? "True" : "False"}, - {"isIntroRootLayer", arc.IsIntroducedInRootLayerStack() ? "True" : "False"}, - {"isIntroRootLayerPrim", arc.IsIntroducedInRootLayerPrimSpec() ? "True" : "False" }, - {"nodeLayerStack", arc.GetTargetNode().GetLayerStack()->GetIdentifier().rootLayer->GetRealPath()}, - {"nodePath", arc.GetTargetNode().GetPath().GetString()}, - }; +void replaceReferenceItems( + const UsdPrim& oldPrim, + const SdfPath& newPath, + const SdfReferencesProxy& referencesList, + SdfListOpType op) +{ + // set the listProxy based on the SdfListOpType + SdfReferencesProxy::ListProxy listProxy = referencesList.GetAppendedItems(); + if (op == SdfListOpTypePrepended) { + listProxy = referencesList.GetPrependedItems(); + } else if (op == SdfListOpTypeOrdered) { + listProxy = referencesList.GetOrderedItems(); + } else if (op == SdfListOpTypeAdded) { + listProxy = referencesList.GetAddedItems(); + } else if (op == SdfListOpTypeDeleted) { + listProxy = referencesList.GetDeletedItems(); } - void replaceReferenceItems(const UsdPrim& oldPrim, - const SdfPath& newPath, - const SdfReferencesProxy& referencesList, - SdfListOpType op) - { - // set the listProxy based on the SdfListOpType - SdfReferencesProxy::ListProxy listProxy = referencesList.GetAppendedItems(); - if (op == SdfListOpTypePrepended) { - listProxy = referencesList.GetPrependedItems(); - } else if (op == SdfListOpTypeOrdered) { - listProxy = referencesList.GetOrderedItems(); - } else if (op == SdfListOpTypeAdded) { - listProxy = referencesList.GetAddedItems(); - } else if (op == SdfListOpTypeDeleted) { - listProxy = referencesList.GetDeletedItems(); - } + // fetching the existing SdfReference items and using + // the Replace() method to replace them with updated SdfReference items. + for (const SdfReference& ref : listProxy) { + if (MayaUsdUtils::isInternalReference(ref)) { + SdfPath finalPath; + if (oldPrim.GetPath() == ref.GetPrimPath()) { + finalPath = newPath; + } else if (ref.GetPrimPath().HasPrefix(oldPrim.GetPath())) { + finalPath = ref.GetPrimPath().ReplacePrefix(oldPrim.GetPath(), newPath); + } - // fetching the existing SdfReference items and using - // the Replace() method to replace them with updated SdfReference items. - for (const SdfReference &ref : listProxy) - { - if (MayaUsdUtils::isInternalReference(ref)) - { - SdfPath finalPath; - if(oldPrim.GetPath() == ref.GetPrimPath()) { - finalPath = newPath; - } - else if(ref.GetPrimPath().HasPrefix(oldPrim.GetPath())) { - finalPath = ref.GetPrimPath().ReplacePrefix(oldPrim.GetPath(), newPath); - } - - if(finalPath.IsEmpty()) { - continue; - } - - // replace the old reference with new one - SdfReference newRef; - newRef.SetPrimPath(finalPath); - listProxy.Replace(ref, newRef); + if (finalPath.IsEmpty()) { + continue; } + + // replace the old reference with new one + SdfReference newRef; + newRef.SetPrimPath(finalPath); + listProxy.Replace(ref, newRef); } } } +} // namespace namespace MayaUsdUtils { -SdfLayerHandle -defPrimSpecLayer(const UsdPrim& prim) +SdfLayerHandle defPrimSpecLayer(const UsdPrim& prim) { // Iterate over the layer stack, starting at the highest-priority layer. // The source layer is the one in which there exists a def primSpec, not // an over. SdfLayerHandle defLayer; - auto layerStack = prim.GetStage()->GetLayerStack(); + auto layerStack = prim.GetStage()->GetLayerStack(); for (auto layer : layerStack) { auto primSpec = layer->GetPrimAtPath(prim.GetPath()); @@ -138,26 +125,24 @@ defPrimSpecLayer(const UsdPrim& prim) return defLayer; } -SdfPrimSpecHandle -getPrimSpecAtEditTarget(const UsdPrim& prim) +SdfPrimSpecHandle getPrimSpecAtEditTarget(const UsdPrim& prim) { auto stage = prim.GetStage(); return stage->GetEditTarget().GetPrimSpecForScenePath(prim.GetPath()); } -void -printCompositionQuery(const UsdPrim& prim, std::ostream& os) +void printCompositionQuery(const UsdPrim& prim, std::ostream& os) { UsdPrimCompositionQuery query(prim); os << "[\n"; - // the composition arcs are always returned in order from strongest + // the composition arcs are always returned in order from strongest // to weakest regardless of the filter. for (const auto& arc : query.GetCompositionArcs()) { const auto& arcDic = getDict(arc); os << "{\n"; - std::for_each(arcDic.begin(),arcDic.end(), [&](const auto& it) { + std::for_each(arcDic.begin(), arcDic.end(), [&](const auto& it) { os << it.first << ": " << it.second << '\n'; }); os << "}\n"; @@ -166,20 +151,16 @@ printCompositionQuery(const UsdPrim& prim, std::ostream& os) os << "]\n\n"; } -bool -updateInternalReferencesPath(const UsdPrim& oldPrim, const SdfPath& newPath) +bool updateInternalReferencesPath(const UsdPrim& oldPrim, const SdfPath& newPath) { SdfChangeBlock changeBlock; - for (const auto& p : oldPrim.GetStage()->Traverse()) - { - if(p.HasAuthoredReferences()) - { + for (const auto& p : oldPrim.GetStage()->Traverse()) { + if (p.HasAuthoredReferences()) { auto primSpec = getPrimSpecAtEditTarget(p); - if (primSpec) - { + if (primSpec) { SdfReferencesProxy referencesList = primSpec->GetReferenceList(); - // update append/prepend lists individually + // update append/prepend lists individually replaceReferenceItems(oldPrim, newPath, referencesList, SdfListOpTypeAppended); replaceReferenceItems(oldPrim, newPath, referencesList, SdfListOpTypePrepended); } @@ -189,14 +170,13 @@ updateInternalReferencesPath(const UsdPrim& oldPrim, const SdfPath& newPath) return true; } -bool -isInternalReference(const SdfReference& ref) +bool isInternalReference(const SdfReference& ref) { - #if USD_VERSION_NUM >= 2008 +#if USD_VERSION_NUM >= 2008 return ref.IsInternal(); - #else +#else return ref.GetAssetPath().empty(); - #endif +#endif } -} // MayaUsdUtils +} // namespace MayaUsdUtils diff --git a/lib/usd/utils/util.h b/lib/usd/utils/util.h index 1ba946a96e..74594e6706 100644 --- a/lib/usd/utils/util.h +++ b/lib/usd/utils/util.h @@ -18,35 +18,33 @@ #define MAYAUSDUTILS_UTIL_H #include - #include PXR_NAMESPACE_USING_DIRECTIVE namespace MayaUsdUtils { - //! Return the highest-priority layer where the prim has a def primSpec. - MAYA_USD_UTILS_PUBLIC - SdfLayerHandle defPrimSpecLayer(const UsdPrim& prim); +//! Return the highest-priority layer where the prim has a def primSpec. +MAYA_USD_UTILS_PUBLIC +SdfLayerHandle defPrimSpecLayer(const UsdPrim& prim); - //! Return a PrimSpec for the argument prim in the layer containing the stage's current edit target. - MAYA_USD_UTILS_PUBLIC - SdfPrimSpecHandle getPrimSpecAtEditTarget(const UsdPrim& prim); +//! Return a PrimSpec for the argument prim in the layer containing the stage's current edit target. +MAYA_USD_UTILS_PUBLIC +SdfPrimSpecHandle getPrimSpecAtEditTarget(const UsdPrim& prim); - //! Convenience function for printing the list of queried composition arcs in order. - MAYA_USD_UTILS_PUBLIC - void printCompositionQuery(const UsdPrim& prim, std::ostream& os); +//! Convenience function for printing the list of queried composition arcs in order. +MAYA_USD_UTILS_PUBLIC +void printCompositionQuery(const UsdPrim& prim, std::ostream& os); - //! This function automatically updates the internal refrences path if - // the path that it has referenced is changed. - MAYA_USD_UTILS_PUBLIC - bool updateInternalReferencesPath(const UsdPrim& oldPrim, const SdfPath& newPath); +//! This function automatically updates the internal refrences path if +// the path that it has referenced is changed. +MAYA_USD_UTILS_PUBLIC +bool updateInternalReferencesPath(const UsdPrim& oldPrim, const SdfPath& newPath); - //! Returns true if reference is internal. - MAYA_USD_UTILS_PUBLIC - bool isInternalReference(const SdfReference&); +//! Returns true if reference is internal. +MAYA_USD_UTILS_PUBLIC +bool isInternalReference(const SdfReference&); } // namespace MayaUsdUtils #endif // MAYAUSDUTILS_UTIL_H - diff --git a/plugin/adsk/plugin/ProxyShape.cpp b/plugin/adsk/plugin/ProxyShape.cpp index 97ed9239ac..aef8af25f1 100644 --- a/plugin/adsk/plugin/ProxyShape.cpp +++ b/plugin/adsk/plugin/ProxyShape.cpp @@ -22,21 +22,16 @@ namespace MAYAUSD_NS_DEF { // ======================================================== -const MTypeId MAYAUSD_PROXYSHAPE_ID (0x58000095); +const MTypeId MAYAUSD_PROXYSHAPE_ID(0x58000095); const MTypeId ProxyShape::typeId(MayaUsd::MAYAUSD_PROXYSHAPE_ID); const MString ProxyShape::typeName("mayaUsdProxyShape"); /* static */ -void* -ProxyShape::creator() -{ - return new ProxyShape(); -} +void* ProxyShape::creator() { return new ProxyShape(); } /* static */ -MStatus -ProxyShape::initialize() +MStatus ProxyShape::initialize() { MStatus retValue = inheritAttributesFrom(MayaUsdProxyShapeBase::typeName); CHECK_MSTATUS_AND_RETURN_IT(retValue); @@ -44,7 +39,8 @@ ProxyShape::initialize() return retValue; } -ProxyShape::ProxyShape() : MayaUsdProxyShapeBase() +ProxyShape::ProxyShape() + : MayaUsdProxyShapeBase() { TfRegistryManager::GetInstance().SubscribeTo(); } @@ -61,17 +57,16 @@ void ProxyShape::postConstructor() { ParentClass::postConstructor(); - if (!MayaUsdProxyShapePlugin::useVP2_NativeUSD_Rendering()) - { + if (!MayaUsdProxyShapePlugin::useVP2_NativeUSD_Rendering()) { // This shape uses Hydra for imaging, so make sure that the // pxrHdImagingShape is setup. PXR_NS::PxrMayaHdImagingShape::GetOrCreateInstance(); } - + // Enable proxy accessor features for this proxy #if MAYA_API_VERSION >= 20210000 enableProxyAccessor(); #endif } -} // MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/plugin/adsk/plugin/ProxyShape.h b/plugin/adsk/plugin/ProxyShape.h index 16ee00e01a..a21525ae2d 100644 --- a/plugin/adsk/plugin/ProxyShape.h +++ b/plugin/adsk/plugin/ProxyShape.h @@ -15,12 +15,12 @@ // #pragma once -#include +#include "base/api.h" #include #include -#include "base/api.h" +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -28,28 +28,28 @@ namespace MAYAUSD_NS_DEF { class ProxyShape : public MayaUsdProxyShapeBase { - public: - typedef MayaUsdProxyShapeBase ParentClass; +public: + typedef MayaUsdProxyShapeBase ParentClass; - MAYAUSD_PLUGIN_PUBLIC - static const MTypeId typeId; - MAYAUSD_PLUGIN_PUBLIC - static const MString typeName; + MAYAUSD_PLUGIN_PUBLIC + static const MTypeId typeId; + MAYAUSD_PLUGIN_PUBLIC + static const MString typeName; - MAYAUSD_PLUGIN_PUBLIC - static void* creator(); + MAYAUSD_PLUGIN_PUBLIC + static void* creator(); - MAYAUSD_PLUGIN_PUBLIC - static MStatus initialize(); + MAYAUSD_PLUGIN_PUBLIC + static MStatus initialize(); - void postConstructor() override; + void postConstructor() override; - private: - ProxyShape(); +private: + ProxyShape(); - ProxyShape(const ProxyShape&); - ~ProxyShape() override; - ProxyShape& operator=(const ProxyShape&); + ProxyShape(const ProxyShape&); + ~ProxyShape() override; + ProxyShape& operator=(const ProxyShape&); }; -} // MayaUsd +} // namespace MAYAUSD_NS_DEF diff --git a/plugin/adsk/plugin/adskExportCommand.cpp b/plugin/adsk/plugin/adskExportCommand.cpp index dfb1eff305..66bf2103bd 100644 --- a/plugin/adsk/plugin/adskExportCommand.cpp +++ b/plugin/adsk/plugin/adskExportCommand.cpp @@ -19,9 +19,6 @@ namespace MAYAUSD_NS_DEF { const MString ADSKMayaUSDExportCommand::commandName("mayaUSDExport"); -void* ADSKMayaUSDExportCommand::creator() -{ - return new ADSKMayaUSDExportCommand(); -} +void* ADSKMayaUSDExportCommand::creator() { return new ADSKMayaUSDExportCommand(); } -} +} // namespace MAYAUSD_NS_DEF diff --git a/plugin/adsk/plugin/adskExportCommand.h b/plugin/adsk/plugin/adskExportCommand.h index c7cddbe9fa..ae8df9eb29 100644 --- a/plugin/adsk/plugin/adskExportCommand.h +++ b/plugin/adsk/plugin/adskExportCommand.h @@ -24,13 +24,12 @@ namespace MAYAUSD_NS_DEF { class MAYAUSD_PLUGIN_PUBLIC ADSKMayaUSDExportCommand : public MayaUsd::MayaUSDExportCommand { - public: - +public: static const MString commandName; static void* creator(); }; -} +} // namespace MAYAUSD_NS_DEF #endif diff --git a/plugin/adsk/plugin/adskImportCommand.cpp b/plugin/adsk/plugin/adskImportCommand.cpp index 94bde55162..1f2f46eb1e 100644 --- a/plugin/adsk/plugin/adskImportCommand.cpp +++ b/plugin/adsk/plugin/adskImportCommand.cpp @@ -19,9 +19,6 @@ namespace MAYAUSD_NS_DEF { const MString ADSKMayaUSDImportCommand::commandName("mayaUSDImport"); -void* ADSKMayaUSDImportCommand::creator() -{ - return new ADSKMayaUSDImportCommand(); -} +void* ADSKMayaUSDImportCommand::creator() { return new ADSKMayaUSDImportCommand(); } -} +} // namespace MAYAUSD_NS_DEF diff --git a/plugin/adsk/plugin/adskImportCommand.h b/plugin/adsk/plugin/adskImportCommand.h index 0fc9d6017a..9e9861704f 100644 --- a/plugin/adsk/plugin/adskImportCommand.h +++ b/plugin/adsk/plugin/adskImportCommand.h @@ -24,13 +24,12 @@ namespace MAYAUSD_NS_DEF { class MAYAUSD_PLUGIN_PUBLIC ADSKMayaUSDImportCommand : public MayaUsd::MayaUSDImportCommand { - public: - +public: static const MString commandName; static void* creator(); }; -} +} // namespace MAYAUSD_NS_DEF #endif diff --git a/plugin/adsk/plugin/adskListShadingModesCommand.cpp b/plugin/adsk/plugin/adskListShadingModesCommand.cpp index 4d0ac4a3a7..9d2bc577db 100644 --- a/plugin/adsk/plugin/adskListShadingModesCommand.cpp +++ b/plugin/adsk/plugin/adskListShadingModesCommand.cpp @@ -24,4 +24,4 @@ void* ADSKMayaUSDListShadingModesCommand::creator() return new ADSKMayaUSDListShadingModesCommand(); } -} +} // namespace MAYAUSD_NS_DEF diff --git a/plugin/adsk/plugin/adskListShadingModesCommand.h b/plugin/adsk/plugin/adskListShadingModesCommand.h index a2d1b72339..cfed9ef74f 100644 --- a/plugin/adsk/plugin/adskListShadingModesCommand.h +++ b/plugin/adsk/plugin/adskListShadingModesCommand.h @@ -22,15 +22,15 @@ namespace MAYAUSD_NS_DEF { -class MAYAUSD_PLUGIN_PUBLIC ADSKMayaUSDListShadingModesCommand : public MayaUsd::MayaUSDListShadingModesCommand +class MAYAUSD_PLUGIN_PUBLIC ADSKMayaUSDListShadingModesCommand + : public MayaUsd::MayaUSDListShadingModesCommand { - public: - +public: static const MString commandName; static void* creator(); }; -} +} // namespace MAYAUSD_NS_DEF #endif diff --git a/plugin/adsk/plugin/base/api.h b/plugin/adsk/plugin/base/api.h index 388849245e..3d71b43265 100644 --- a/plugin/adsk/plugin/base/api.h +++ b/plugin/adsk/plugin/base/api.h @@ -16,29 +16,29 @@ #if defined _WIN32 || defined __CYGWIN__ - // We need a different export symbol for the plugin because when we are building - // the actual Maya plugin we must 'export' the two functions for plugin load/unload. - // And then we won't set the core export because we need to 'import' the symbols. - #ifdef MAYAUSD_PLUGIN_EXPORT - #ifdef __GNUC__ - #define MAYAUSD_PLUGIN_PUBLIC __attribute__ ((dllexport)) - #else - #define MAYAUSD_PLUGIN_PUBLIC __declspec(dllexport) - #endif - #else - #ifdef __GNUC__ - #define MAYAUSD_PLUGIN_PUBLIC __attribute__ ((dllimport)) - #else - #define MAYAUSD_PLUGIN_PUBLIC __declspec(dllimport) - #endif - #endif - #define MAYAUSD_PLUGIN_LOCAL +// We need a different export symbol for the plugin because when we are building +// the actual Maya plugin we must 'export' the two functions for plugin load/unload. +// And then we won't set the core export because we need to 'import' the symbols. +#ifdef MAYAUSD_PLUGIN_EXPORT +#ifdef __GNUC__ +#define MAYAUSD_PLUGIN_PUBLIC __attribute__((dllexport)) #else - #if __GNUC__ >= 4 - #define MAYAUSD_PLUGIN_PUBLIC __attribute__ ((visibility ("default"))) - #define MAYAUSD_PLUGIN_LOCAL __attribute__ ((visibility ("hidden"))) +#define MAYAUSD_PLUGIN_PUBLIC __declspec(dllexport) +#endif +#else +#ifdef __GNUC__ +#define MAYAUSD_PLUGIN_PUBLIC __attribute__((dllimport)) +#else +#define MAYAUSD_PLUGIN_PUBLIC __declspec(dllimport) +#endif +#endif +#define MAYAUSD_PLUGIN_LOCAL +#else +#if __GNUC__ >= 4 +#define MAYAUSD_PLUGIN_PUBLIC __attribute__((visibility("default"))) +#define MAYAUSD_PLUGIN_LOCAL __attribute__((visibility("hidden"))) #else - #define MAYAUSD_PLUGIN_PUBLIC - #define MAYAUSD_PLUGIN_LOCAL +#define MAYAUSD_PLUGIN_PUBLIC +#define MAYAUSD_PLUGIN_LOCAL #endif #endif diff --git a/plugin/adsk/plugin/exportTranslator.cpp b/plugin/adsk/plugin/exportTranslator.cpp index b70fd16514..45a8d39f7a 100644 --- a/plugin/adsk/plugin/exportTranslator.cpp +++ b/plugin/adsk/plugin/exportTranslator.cpp @@ -16,19 +16,19 @@ // #include "exportTranslator.h" -#include -#include -#include +#include +#include +#include +#include #include #include #include #include -#include -#include -#include -#include +#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -36,44 +36,43 @@ namespace MAYAUSD_NS_DEF { const MString UsdMayaExportTranslator::translatorName("USD Export"); -void* UsdMayaExportTranslator::creator() { - return new UsdMayaExportTranslator(); -} +void* UsdMayaExportTranslator::creator() { return new UsdMayaExportTranslator(); } -UsdMayaExportTranslator::UsdMayaExportTranslator() : - MPxFileTranslator() { +UsdMayaExportTranslator::UsdMayaExportTranslator() + : MPxFileTranslator() +{ } -UsdMayaExportTranslator::~UsdMayaExportTranslator() { -} +UsdMayaExportTranslator::~UsdMayaExportTranslator() { } -MStatus -UsdMayaExportTranslator::writer(const MFileObject &file, - const MString &optionsString, - MPxFileTranslator::FileAccessMode mode ) { +MStatus UsdMayaExportTranslator::writer( + const MFileObject& file, + const MString& optionsString, + MPxFileTranslator::FileAccessMode mode) +{ // If we are in neither of these modes then there won't be anything to do - if (mode != MPxFileTranslator::kExportActiveAccessMode && - mode != MPxFileTranslator::kExportAccessMode) { + if (mode != MPxFileTranslator::kExportActiveAccessMode + && mode != MPxFileTranslator::kExportAccessMode) { return MS::kSuccess; } - std::string fileName(file.fullName().asChar(), file.fullName().length()); + std::string fileName(file.fullName().asChar(), file.fullName().length()); VtDictionary userArgs; - bool exportAnimation = false; - GfInterval timeInterval(1.0, 1.0); - double frameStride = 1.0; - bool append=false; - + bool exportAnimation = false; + GfInterval timeInterval(1.0, 1.0); + double frameStride = 1.0; + bool append = false; + std::set frameSamples; MStringArray filteredTypes; - // Get the options + // Get the options if (optionsString.length() > 0) { MStringArray optionList; MStringArray theOption; optionsString.split(';', optionList); - for(int i=0; i<(int)optionList.length(); ++i) { + for (int i = 0; i < (int)optionList.length(); ++i) { theOption.clear(); optionList[i].split('=', theOption); if (theOption.length() != 2) { @@ -83,33 +82,28 @@ UsdMayaExportTranslator::writer(const MFileObject &file, std::string argName(theOption[0].asChar()); if (argName == "animation") { exportAnimation = (theOption[1].asInt() != 0); - } - else if (argName == "startTime") { + } else if (argName == "startTime") { timeInterval.SetMin(theOption[1].asDouble()); - } - else if (argName == "endTime") { + } else if (argName == "endTime") { timeInterval.SetMax(theOption[1].asDouble()); - } - else if (argName == "frameStride") { + } else if (argName == "frameStride") { frameStride = theOption[1].asDouble(); - } - else if (argName == "filterTypes") { + } else if (argName == "filterTypes") { theOption[1].split(',', filteredTypes); - } - else if (argName == "frameSample") { + } else if (argName == "frameSample") { frameSamples.clear(); MStringArray samplesStrings; theOption[1].split(' ', samplesStrings); unsigned int nbSams = samplesStrings.length(); - for(unsigned int sam=0; sam timeSamples = UsdMayaWriteUtil::GetTimeSamples( - timeInterval, frameSamples, frameStride); - PXR_NS::UsdMayaJobExportArgs jobArgs = PXR_NS::UsdMayaJobExportArgs::CreateFromDictionary( - userArgs, dagPaths, timeSamples); - + const std::vector timeSamples + = UsdMayaWriteUtil::GetTimeSamples(timeInterval, frameSamples, frameStride); + PXR_NS::UsdMayaJobExportArgs jobArgs + = PXR_NS::UsdMayaJobExportArgs::CreateFromDictionary(userArgs, dagPaths, timeSamples); + unsigned int len = filteredTypes.length(); - for (unsigned int i=0; i < len; ++i) { + for (unsigned int i = 0; i < len; ++i) { jobArgs.AddFilteredTypeName(filteredTypes[i].asChar()); } @@ -151,19 +145,18 @@ UsdMayaExportTranslator::writer(const MFileObject &file, if (!writeJob.Write(fileName, append)) { return MS::kFailure; } - + return MS::kSuccess; } -MPxFileTranslator::MFileKind -UsdMayaExportTranslator::identifyFile( - const MFileObject& file, - const char* /*buffer*/, - short /*size*/) const +MPxFileTranslator::MFileKind UsdMayaExportTranslator::identifyFile( + const MFileObject& file, + const char* /*buffer*/, + short /*size*/) const { - MFileKind retValue = kNotMyFileType; + MFileKind retValue = kNotMyFileType; const MString fileName = file.fullName(); - const int lastIndex = fileName.length() - 1; + const int lastIndex = fileName.length() - 1; const int periodIndex = fileName.rindex('.'); if (periodIndex < 0 || periodIndex >= lastIndex) { @@ -172,14 +165,10 @@ UsdMayaExportTranslator::identifyFile( const MString fileExtension = fileName.substring(periodIndex + 1, lastIndex); - if (fileExtension == - UsdMayaTranslatorTokens->UsdFileExtensionDefault.GetText() || - fileExtension == - UsdMayaTranslatorTokens->UsdFileExtensionASCII.GetText() || - fileExtension == - UsdMayaTranslatorTokens->UsdFileExtensionCrate.GetText() || - fileExtension == - UsdMayaTranslatorTokens->UsdFileExtensionPackage.GetText()) { + if (fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionDefault.GetText() + || fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionASCII.GetText() + || fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionCrate.GetText() + || fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionPackage.GetText()) { retValue = kIsMyFileType; } @@ -187,16 +176,15 @@ UsdMayaExportTranslator::identifyFile( } /* static */ -const std::string& -UsdMayaExportTranslator::GetDefaultOptions() +const std::string& UsdMayaExportTranslator::GetDefaultOptions() { - static std::string defaultOptions; + static std::string defaultOptions; static std::once_flag once; std::call_once(once, []() { std::ostringstream optionsStream; for (const std::pair keyValue : - PXR_NS::UsdMayaJobExportArgs::GetDefaultDictionary()) { - bool canConvert; + PXR_NS::UsdMayaJobExportArgs::GetDefaultDictionary()) { + bool canConvert; std::string valueStr; std::tie(canConvert, valueStr) = UsdMayaUtil::ValueToArgument(keyValue.second); if (canConvert) { @@ -215,4 +203,4 @@ UsdMayaExportTranslator::GetDefaultOptions() return defaultOptions; } -} +} // namespace MAYAUSD_NS_DEF diff --git a/plugin/adsk/plugin/exportTranslator.h b/plugin/adsk/plugin/exportTranslator.h index 1e8e4d7d96..dabbc1d9e3 100644 --- a/plugin/adsk/plugin/exportTranslator.h +++ b/plugin/adsk/plugin/exportTranslator.h @@ -16,64 +16,61 @@ // #pragma once +#include "base/api.h" + +#include + +#include + #include #include #include #include -#include - -#include - -#include "base/api.h" - namespace MAYAUSD_NS_DEF { /// File translator for USD files. Handles the USD option in the Export window. class UsdMayaExportTranslator : public MPxFileTranslator { - public: - MAYAUSD_PLUGIN_PUBLIC - static const MString translatorName; - - /** - * method to create UsdMayaExportTranslator file translator - */ - MAYAUSD_PLUGIN_PUBLIC - static void* creator(); - - MAYAUSD_PLUGIN_PUBLIC - MStatus writer( - const MFileObject& file, - const MString& optionsString, - MPxFileTranslator::FileAccessMode mode) override; - - bool haveReadMethod() const override { return false; } - bool haveWriteMethod() const override { return true; } - - MAYAUSD_PLUGIN_PUBLIC - MFileKind identifyFile( - const MFileObject& file, - const char* buffer, - short size) const override; - - MString defaultExtension() const override { - return PXR_NS::UsdMayaTranslatorTokens->UsdFileExtensionDefault.GetText(); - } - MString filter() const override { - return PXR_NS::UsdMayaTranslatorTokens->UsdWritableFileFilter.GetText(); - } - - MAYAUSD_PLUGIN_PUBLIC - static const std::string& GetDefaultOptions(); - - private: - - UsdMayaExportTranslator(); - UsdMayaExportTranslator(const UsdMayaExportTranslator&); - ~UsdMayaExportTranslator() override; - UsdMayaExportTranslator& operator=(const UsdMayaExportTranslator&); +public: + MAYAUSD_PLUGIN_PUBLIC + static const MString translatorName; + + /** + * method to create UsdMayaExportTranslator file translator + */ + MAYAUSD_PLUGIN_PUBLIC + static void* creator(); + + MAYAUSD_PLUGIN_PUBLIC + MStatus writer( + const MFileObject& file, + const MString& optionsString, + MPxFileTranslator::FileAccessMode mode) override; + + bool haveReadMethod() const override { return false; } + bool haveWriteMethod() const override { return true; } + + MAYAUSD_PLUGIN_PUBLIC + MFileKind identifyFile(const MFileObject& file, const char* buffer, short size) const override; + + MString defaultExtension() const override + { + return PXR_NS::UsdMayaTranslatorTokens->UsdFileExtensionDefault.GetText(); + } + MString filter() const override + { + return PXR_NS::UsdMayaTranslatorTokens->UsdWritableFileFilter.GetText(); + } + + MAYAUSD_PLUGIN_PUBLIC + static const std::string& GetDefaultOptions(); + +private: + UsdMayaExportTranslator(); + UsdMayaExportTranslator(const UsdMayaExportTranslator&); + ~UsdMayaExportTranslator() override; + UsdMayaExportTranslator& operator=(const UsdMayaExportTranslator&); }; -} - +} // namespace MAYAUSD_NS_DEF diff --git a/plugin/adsk/plugin/importTranslator.cpp b/plugin/adsk/plugin/importTranslator.cpp index d35426fa3d..18abc24973 100644 --- a/plugin/adsk/plugin/importTranslator.cpp +++ b/plugin/adsk/plugin/importTranslator.cpp @@ -16,46 +16,40 @@ // #include "importTranslator.h" -#include -#include - #include #include #include #include +#include +#include + #include #include #include #include -#include -#include +#include +#include PXR_NAMESPACE_OPEN_SCOPE /* static */ -void* -UsdMayaImportTranslator::creator() -{ - return new UsdMayaImportTranslator(); -} +void* UsdMayaImportTranslator::creator() { return new UsdMayaImportTranslator(); } -UsdMayaImportTranslator::UsdMayaImportTranslator() : MPxFileTranslator() +UsdMayaImportTranslator::UsdMayaImportTranslator() + : MPxFileTranslator() { } /* virtual */ -UsdMayaImportTranslator::~UsdMayaImportTranslator() -{ -} +UsdMayaImportTranslator::~UsdMayaImportTranslator() { } /* virtual */ -MStatus -UsdMayaImportTranslator::reader( - const MFileObject& file, - const MString& optionsString, - MPxFileTranslator::FileAccessMode /*mode*/) +MStatus UsdMayaImportTranslator::reader( + const MFileObject& file, + const MString& optionsString, + MPxFileTranslator::FileAccessMode /*mode*/) { std::string fileName(file.fullName().asChar(), file.fullName().length()); @@ -63,14 +57,13 @@ UsdMayaImportTranslator::reader( // the import data. This would happen if the user performed an import with // the dialog and then manually with a different file name. MayaUsd::ImportData& importData = MayaUsd::ImportData::instance(); - if (fileName != importData.filename()) - { + if (fileName != importData.filename()) { importData.clearData(); importData.setFilename(fileName); } - bool readAnimData = true; - bool useCustomFrameRange = false; + bool readAnimData = true; + bool useCustomFrameRange = false; GfInterval timeInterval(1.0, 1.0); VtDictionary userArgs; @@ -79,7 +72,7 @@ UsdMayaImportTranslator::reader( MStringArray optionList; MStringArray theOption; optionsString.split(';', optionList); - for(int i=0, n=optionList.length(); i= lastIndex) { @@ -152,10 +139,10 @@ UsdMayaImportTranslator::identifyFile( const MString fileExtension = fileName.substring(periodIndex + 1, lastIndex); - if (fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionDefault.GetText() || - fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionASCII.GetText() || - fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionCrate.GetText() || - fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionPackage.GetText()) { + if (fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionDefault.GetText() + || fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionASCII.GetText() + || fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionCrate.GetText() + || fileExtension == UsdMayaTranslatorTokens->UsdFileExtensionPackage.GetText()) { retValue = kIsMyFileType; } @@ -163,22 +150,20 @@ UsdMayaImportTranslator::identifyFile( } /* static */ -const std::string& -UsdMayaImportTranslator::GetDefaultOptions() +const std::string& UsdMayaImportTranslator::GetDefaultOptions() { - static std::string defaultOptions; + static std::string defaultOptions; static std::once_flag once; std::call_once(once, []() { std::vector entries; for (const std::pair keyValue : - UsdMayaJobImportArgs::GetDefaultDictionary()) { - bool canConvert; + UsdMayaJobImportArgs::GetDefaultDictionary()) { + bool canConvert; std::string valueStr; std::tie(canConvert, valueStr) = UsdMayaUtil::ValueToArgument(keyValue.second); if (canConvert) { - entries.push_back(TfStringPrintf("%s=%s", - keyValue.first.c_str(), - valueStr.c_str())); + entries.push_back( + TfStringPrintf("%s=%s", keyValue.first.c_str(), valueStr.c_str())); } } entries.push_back("readAnimData=0"); @@ -189,5 +174,4 @@ UsdMayaImportTranslator::GetDefaultOptions() return defaultOptions; } - PXR_NAMESPACE_CLOSE_SCOPE diff --git a/plugin/adsk/plugin/importTranslator.h b/plugin/adsk/plugin/importTranslator.h index ff8f5513fc..cf2cc3e4a2 100644 --- a/plugin/adsk/plugin/importTranslator.h +++ b/plugin/adsk/plugin/importTranslator.h @@ -17,66 +17,60 @@ #ifndef PXRUSDMAYA_IMPORT_TRANSLATOR_H #define PXRUSDMAYA_IMPORT_TRANSLATOR_H -#include +#include "base/api.h" + +#include +#include + +#include #include #include #include #include -#include - -#include -#include - -#include "base/api.h" +#include PXR_NAMESPACE_OPEN_SCOPE - /// File translator for USD files. Handles the USD option in the Import window. class UsdMayaImportTranslator : public MPxFileTranslator { - public: - - MAYAUSD_PLUGIN_PUBLIC - static void* creator(); - - MAYAUSD_PLUGIN_PUBLIC - MStatus reader( - const MFileObject& file, - const MString& optionsString, - MPxFileTranslator::FileAccessMode mode) override; - - bool haveReadMethod() const override { return true; } - bool haveWriteMethod() const override { return false; } - - MAYAUSD_PLUGIN_PUBLIC - MFileKind identifyFile( - const MFileObject& file, - const char* buffer, - short size) const override; - - MString defaultExtension() const override { - return UsdMayaTranslatorTokens->UsdFileExtensionDefault.GetText(); - } - MString filter() const override { - return UsdMayaTranslatorTokens->UsdReadableFileFilter.GetText(); - } - - MAYAUSD_PLUGIN_PUBLIC - static const std::string& GetDefaultOptions(); - - private: - - UsdMayaImportTranslator(); - UsdMayaImportTranslator(const UsdMayaImportTranslator&); - ~UsdMayaImportTranslator() override; - UsdMayaImportTranslator& operator=(const UsdMayaImportTranslator&); +public: + MAYAUSD_PLUGIN_PUBLIC + static void* creator(); + + MAYAUSD_PLUGIN_PUBLIC + MStatus reader( + const MFileObject& file, + const MString& optionsString, + MPxFileTranslator::FileAccessMode mode) override; + + bool haveReadMethod() const override { return true; } + bool haveWriteMethod() const override { return false; } + + MAYAUSD_PLUGIN_PUBLIC + MFileKind identifyFile(const MFileObject& file, const char* buffer, short size) const override; + + MString defaultExtension() const override + { + return UsdMayaTranslatorTokens->UsdFileExtensionDefault.GetText(); + } + MString filter() const override + { + return UsdMayaTranslatorTokens->UsdReadableFileFilter.GetText(); + } + + MAYAUSD_PLUGIN_PUBLIC + static const std::string& GetDefaultOptions(); + +private: + UsdMayaImportTranslator(); + UsdMayaImportTranslator(const UsdMayaImportTranslator&); + ~UsdMayaImportTranslator() override; + UsdMayaImportTranslator& operator=(const UsdMayaImportTranslator&); }; - PXR_NAMESPACE_CLOSE_SCOPE - #endif diff --git a/plugin/adsk/plugin/plugin.cpp b/plugin/adsk/plugin/plugin.cpp index f0658bcd6a..e654e0fd29 100644 --- a/plugin/adsk/plugin/plugin.cpp +++ b/plugin/adsk/plugin/plugin.cpp @@ -13,40 +13,38 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - +#include "ProxyShape.h" #include "adskExportCommand.h" #include "adskImportCommand.h" #include "adskListShadingModesCommand.h" +#include "base/api.h" +#include "exportTranslator.h" +#include "importTranslator.h" -#include -#include -#include - -#include -#include -#include - -#include #include #include #include #include #include +#include #include #include #include #include #include +#include -#include +#include +#include +#include -#include "base/api.h" -#include "exportTranslator.h" -#include "importTranslator.h" -#include "ProxyShape.h" +#include +#include +#include -#include +#include + +#include #if defined(WANT_QT_BUILD) #include #endif @@ -57,7 +55,7 @@ #if defined(MAYAUSD_VERSION) #define STRINGIFY(x) #x -#define TOSTRING(x) STRINGIFY(x) +#define TOSTRING(x) STRINGIFY(x) #else #error "MAYAUSD_VERSION is not defined" #endif @@ -88,14 +86,18 @@ template void deregisterCommandCheck(MFnPlugin& plugin) } // namespace TF_REGISTRY_FUNCTION(UsdMayaShaderReaderRegistry) -{ PxrMayaUsdPreviewSurfacePlugin::RegisterPreviewSurfaceReader(MayaUsdPreviewSurface_typeName); }; +{ + PxrMayaUsdPreviewSurfacePlugin::RegisterPreviewSurfaceReader(MayaUsdPreviewSurface_typeName); +}; TF_REGISTRY_FUNCTION(UsdMayaShaderWriterRegistry) -{ PxrMayaUsdPreviewSurfacePlugin::RegisterPreviewSurfaceWriter(MayaUsdPreviewSurface_typeName); }; +{ + PxrMayaUsdPreviewSurfacePlugin::RegisterPreviewSurfaceWriter(MayaUsdPreviewSurface_typeName); +}; MAYAUSD_PLUGIN_PUBLIC MStatus initializePlugin(MObject obj) { - MStatus status; + MStatus status; MFnPlugin plugin(obj, "Autodesk", TOSTRING(MAYAUSD_VERSION), "Any"); status = plugin.registerFileTranslator( @@ -148,14 +150,15 @@ MStatus initializePlugin(MObject obj) status = UsdMayaUndoHelperCommand::initialize(plugin); if (!status) { - status.perror(std::string("registerCommand ").append( - UsdMayaUndoHelperCommand::name()).c_str()); + status.perror( + std::string("registerCommand ").append(UsdMayaUndoHelperCommand::name()).c_str()); } #if defined(WANT_QT_BUILD) status = MayaUsd::USDImportDialogCmd::initialize(plugin); if (!status) { - MString err("registerCommand" ); err += MayaUsd::USDImportDialogCmd::fsName; + MString err("registerCommand"); + err += MayaUsd::USDImportDialogCmd::fsName; status.perror(err); } #endif @@ -167,24 +170,26 @@ MStatus initializePlugin(MObject obj) MayaUsdPreviewSurface_registrantId); CHECK_MSTATUS(status); - plugin.registerUI("mayaUsd_pluginUICreation", "mayaUsd_pluginUIDeletion", - "mayaUsd_pluginBatchLoad", "mayaUsd_pluginBatchUnload"); + plugin.registerUI( + "mayaUsd_pluginUICreation", + "mayaUsd_pluginUIDeletion", + "mayaUsd_pluginBatchLoad", + "mayaUsd_pluginBatchUnload"); // As of 2-Aug-2019, these PlugPlugin translators are not loaded // automatically. To be investigated. A duplicate of this code is in the // Pixar plugin.cpp. - const std::vector translatorPluginNames{ - "mayaUsd_Schemas", "mayaUsd_Translators"}; - const auto& plugRegistry = PlugRegistry::GetInstance(); - std::stringstream msg("mayaUsdPlugin: "); + const std::vector translatorPluginNames { "mayaUsd_Schemas", + "mayaUsd_Translators" }; + const auto& plugRegistry = PlugRegistry::GetInstance(); + std::stringstream msg("mayaUsdPlugin: "); for (const auto& pluginName : translatorPluginNames) { auto plugin = plugRegistry.GetPluginWithName(pluginName); if (!plugin) { status = MStatus::kFailure; msg << "translator " << pluginName << " not found."; status.perror(msg.str().c_str()); - } - else { + } else { // Load is a no-op if already loaded. if (!plugin->Load()) { status = MStatus::kFailure; @@ -203,7 +208,7 @@ MAYAUSD_PLUGIN_PUBLIC MStatus uninitializePlugin(MObject obj) { MFnPlugin plugin(obj); - MStatus status; + MStatus status; status = PxrMayaUsdPreviewSurfacePlugin::finalize( plugin, @@ -214,8 +219,8 @@ MStatus uninitializePlugin(MObject obj) status = UsdMayaUndoHelperCommand::finalize(plugin); if (!status) { - status.perror(std::string("deregisterCommand ").append( - UsdMayaUndoHelperCommand::name()).c_str()); + status.perror( + std::string("deregisterCommand ").append(UsdMayaUndoHelperCommand::name()).c_str()); } deregisterCommandCheck(plugin); @@ -223,7 +228,8 @@ MStatus uninitializePlugin(MObject obj) #if defined(WANT_QT_BUILD) status = MayaUsd::USDImportDialogCmd::finalize(plugin); if (!status) { - MString err("deregisterCommand" ); err += MayaUsd::USDImportDialogCmd::fsName; + MString err("deregisterCommand"); + err += MayaUsd::USDImportDialogCmd::fsName; status.perror(err); } #endif @@ -252,6 +258,6 @@ MStatus uninitializePlugin(MObject obj) #endif UsdMayaSceneResetNotice::RemoveListener(); - + return status; } diff --git a/plugin/al/lib/AL_USDMaya/AL/docpages/docs_codegroups.h b/plugin/al/lib/AL_USDMaya/AL/docpages/docs_codegroups.h index 703cc13161..6d7a5b6e7c 100644 --- a/plugin/al/lib/AL_USDMaya/AL/docpages/docs_codegroups.h +++ b/plugin/al/lib/AL_USDMaya/AL/docpages/docs_codegroups.h @@ -3,22 +3,24 @@ /// \defgroup mayautils Maya Helpers //---------------------------------------------------------------------------------------------------------------------- - //---------------------------------------------------------------------------------------------------------------------- /// \defgroup profiler Profiler /// \ingroup mayautils -/// \brief A series of classes and macros that provide a very simple in-code profiler to get some high level timings +/// \brief A series of classes and macros that provide a very simple in-code profiler to get some +/// high level timings /// of the various processes during import / export operations. //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- /// \defgroup mayagui Maya GUI /// \ingroup mayautils -/// \brief These are a series of classes and functions to help automate a lot of the boiler plate GUI code that is +/// \brief These are a series of classes and functions to help automate a lot of the boiler +/// plate GUI code that is /// often needed for a Maya plug-in. The classes fall into two main categories -/// -# code generators that automate the construction of MEL script UI (e.g. AETemplates, menus, file export -/// dialogs, etc). -/// -# wrappers around core Maya MPx functionality to enforce error checking, and minimize potential errors. +/// -# code generators that automate the construction of MEL script UI (e.g. AETemplates, +/// menus, file export dialogs, etc). +/// -# wrappers around core Maya MPx functionality to enforce error checking, and +/// minimize potential errors. /// -# SIMD optimized methods for extracting data from core Maya API classes. //---------------------------------------------------------------------------------------------------------------------- @@ -49,15 +51,3 @@ /// \ingroup fileio /// \brief Classes that deal with the import/export of USD data into maya //---------------------------------------------------------------------------------------------------------------------- - - - - - - - - - - - - diff --git a/plugin/al/lib/AL_USDMaya/AL/docpages/docs_events.h b/plugin/al/lib/AL_USDMaya/AL/docpages/docs_events.h index 4b7deba696..97d923240d 100644 --- a/plugin/al/lib/AL_USDMaya/AL/docpages/docs_events.h +++ b/plugin/al/lib/AL_USDMaya/AL/docpages/docs_events.h @@ -3,17 +3,19 @@ \defgroup events Core Event System \ingroup mayautils \brief -The AL_USDMaya event system attempts to provide a more robust event system for Maya that works around some of the -short comings of the MMessage/scriptJob approach. This system is employed within AL_USDMaya to expose programming hooks -that can be used to execute your own code during the internal processes of AL_USDMaya (e.g. before/after a variant switch) +The AL_USDMaya event system attempts to provide a more robust event system for Maya that works +around some of the short comings of the MMessage/scriptJob approach. This system is employed within +AL_USDMaya to expose programming hooks that can be used to execute your own code during the internal +processes of AL_USDMaya (e.g. before/after a variant switch) \section events_Motivation Events Motivation \subsection MMessage Why not use scriptJob / MMessage? -Maya already has its own event management system, which are exposed via the MMessage (and derived classes) in the API, -and scriptJob within MEL/python. These systems work, but they have a number of drawbacks when deployed in a medium to large -sized studio with multiple shows in flight. As an example of some of the problems that can arise, consider this scenario: +Maya already has its own event management system, which are exposed via the MMessage (and derived +classes) in the API, and scriptJob within MEL/python. These systems work, but they have a number +of drawbacks when deployed in a medium to large sized studio with multiple shows in flight. As an +example of some of the problems that can arise, consider this scenario: \code // A callback that will create a node we will store some shot settings on @@ -33,38 +35,42 @@ global proc onFileNew_createDefaultSetOfNodes() global int $scriptJob2 = `scriptJob -e "NewSceneOpened" "onFileNew_createDefaultSetOfNodes"`; \endcode -Now in this case, since we are registering those script jobs in a specific order, when a 'file new' occurs, our custom -shot node will be created, and it will be added to the set of nodes to ignore at export time. All well and good! +Now in this case, since we are registering those script jobs in a specific order, when a 'file new' +occurs, our custom shot node will be created, and it will be added to the set of nodes to ignore at +export time. All well and good! -If however we registered scriptJob2 first, we'd end up with the set being created first, and then we'd create our shot -settings node (which would not be part of the set). Now who knows which is the right way around in this context -(it is after all an illustrative example!), but the important take home message here, is that there can be -behavioural changes when scriptJobs and MMessages are registered in differing orders. +If however we registered scriptJob2 first, we'd end up with the set being created first, and then +we'd create our shot settings node (which would not be part of the set). Now who knows which +is the right way around in this context (it is after all an illustrative example!), but the +important take home message here, is that there can be behavioural changes when scriptJobs and +MMessages are registered in differing orders. -This is often a problem in most studios, since it's likely that those two scriptJobs (or MMessage events) are -actually located in different plug-ins, and therefore small bugs can be introduced if the events are accidentally -registered in an incorrect order. +This is often a problem in most studios, since it's likely that those two scriptJobs (or MMessage +events) are actually located in different plug-ins, and therefore small bugs can be introduced +if the events are accidentally registered in an incorrect order. -In cases where small bugs are introduced, it is often extremely hard to track down what has caused the offending -bug, since the maya event system doesn't really give you an adequate way to track down which events triggered which -callbacks, and more importantly any ideas in how to track down the code that contained the events. +In cases where small bugs are introduced, it is often extremely hard to track down what has caused +the offending bug, since the maya event system doesn't really give you an adequate way to track down +which events triggered which callbacks, and more importantly any ideas in how to track down the code +that contained the events. \subsection terminology Some Terminology \li \b Event : An event is a point in code that can trigger multiple callbacks -\li \b Callback : This is a small bit of code that the user can bind to a specific event, to be executed when it is triggered -\li \b Node \b Event : an event that is bound to a specific maya node +\li \b Callback : This is a small bit of code that the user can bind to a specific event, to be +executed when it is triggered \li \b Node \b Event : an event that is bound to a specific maya node \li \b Global \b Event : an event that is not bound to any particular node \section events_CoreSystem Core Event API \subsection event_specialisation Implementing the System Backend -The event system itself is defined in such as a way as to allow you to provide a custom backend when initialising the -event system. The primary reason for this is to allow a repurposing of the event system into different DCC contexts -(e.g. Maya, Houdini, etc). Within the usdmaya plugin, this backend binding is provided in the class MayaEventSystemBinding -defined within AL/usdmaya/Global.cpp. The main purpose of this binding is to connect the event system to the underlying -logging and scripting capability of the DCC app. +The event system itself is defined in such as a way as to allow you to provide a custom backend when +initialising the event system. The primary reason for this is to allow a repurposing of the event +system into different DCC contexts (e.g. Maya, Houdini, etc). Within the usdmaya plugin, this +backend binding is provided in the class MayaEventSystemBinding defined within +AL/usdmaya/Global.cpp. The main purpose of this binding is to connect the event system to the +underlying logging and scripting capability of the DCC app. \code #include "AL/event/EventHandler.h" @@ -166,8 +172,9 @@ MStatus initializePlugin(MObject obj) // to access the global scheduler auto& scheduler = AL::event::EventScheduler::getScheduler(); - // lets register a simple event named "OnSomethingHappened" that is of the type kUserSpecifiedEventType - g_mySimpleEvent = scheduler.registerEvent("OnSomethingHappened", kUserSpecifiedEventType); + // lets register a simple event named "OnSomethingHappened" that is of the type +kUserSpecifiedEventType g_mySimpleEvent = scheduler.registerEvent("OnSomethingHappened", +kUserSpecifiedEventType); // make sure the event registered correctly if(g_mySimpleEvent == 0) @@ -178,10 +185,10 @@ MStatus initializePlugin(MObject obj) // Simply as an example, we may wish to register a C callback on the event! g_myCallbackId = scheduler.registerCallback( g_mySimpleEvent, ///< the event Id we wish to have our callback triggered on - "myToolName_myCallbackFunction", ///< a unique tag to identify the who owns the callback, and its purpose - myCallbackFunction, ///< the C function we wish to execute - 10000, ///< a weight value for the callback. Smaller values are executed first, larger last - nullptr); ///< an optional userData pointer + "myToolName_myCallbackFunction", ///< a unique tag to identify the who owns the callback, and +its purpose myCallbackFunction, ///< the C function we wish to execute 10000, ///< a +weight value for the callback. Smaller values are executed first, larger last nullptr); ///< an +optional userData pointer // make sure the callback registered correctly if(g_myCallbackId == 0) @@ -212,8 +219,9 @@ MStatus uninitializePlugin(MObject obj) } \endcode -It should be noted that once this plugin have been loaded, there are a number of MEL commands exposed that allow you -to interact with that event in MEL/python script. Firstly we can get a list of the global events registered: +It should be noted that once this plugin have been loaded, there are a number of MEL commands +exposed that allow you to interact with that event in MEL/python script. Firstly we can get a list +of the global events registered: \code print `AL_usdmaya_ListEvents`; @@ -233,7 +241,8 @@ AL_usdmaya_TriggerEvent "OnSomethingHappened"; // I am a callback! \endcode -Via the MEL command AL_usdmaya_Callback it is possible to assign a callback from a MEL or python script. +Via the MEL command AL_usdmaya_Callback it is possible to assign a callback from a MEL or python +script. \code // simple callback @@ -246,12 +255,13 @@ string $melCodeToExecute = "print \"mel callback!\n\""; // * The integer weight for the callback // * The MEL script to execute // -global int $callbackId[] = `AL_usdmaya_Callback -me "OnSomethingHappened" "MyMelScript_operation" 10001 $melCodeToExecute`; -\endcode +global int $callbackId[] = `AL_usdmaya_Callback -me "OnSomethingHappened" "MyMelScript_operation" +10001 $melCodeToExecute`; \endcode -You will notice that the callback id's are returned as an array. This is simply because the C++ Callback ID's are 64bit, -however sadly MEL does not support 64bit integer values, so the callbacks are returned as a pair of 32bit integers. -These pair of callback values can be used to query some information about the callback using the command AL_usdmaya_CallbackQuery +You will notice that the callback id's are returned as an array. This is simply because the C++ +Callback ID's are 64bit, however sadly MEL does not support 64bit integer values, so the callbacks +are returned as a pair of 32bit integers. These pair of callback values can be used to query some +information about the callback using the command AL_usdmaya_CallbackQuery \code // print the tag for the callback @@ -270,7 +280,8 @@ print ("weight: " + `AL_usdmaya_CallbackQuery -w $callbackId[0] $callbackId[1]` print ("code: " + `AL_usdmaya_CallbackQuery -c $callbackId[0] $callbackId[1]` + "\n"); \endcode -If you wish to see which callbacks are registered against a specific event, you can use the AL_usdmaya_ListCallbacks command, e.g. +If you wish to see which callbacks are registered against a specific event, you can use the +AL_usdmaya_ListCallbacks command, e.g. \code proc printCallbackInfo(string $eventName) @@ -279,19 +290,24 @@ proc printCallbackInfo(string $eventName) print ("EventBreakdown: " + $eventName + "\n"); for(int $i = 0; $i < size($callbackIds); $i += 2) { - print ("callback " + ($i / 2 + 1) + " : [" + $callbackIds[$i] + ", " + $callbackIds[$i + 1] + "]\n"); + print ("callback " + ($i / 2 + 1) + " : [" + $callbackIds[$i] + ", " + $callbackIds[$i + 1] + +"]\n"); // print the tag for the callback - print (" tag: " + `AL_usdmaya_CallbackQuery -tag $callbackIds[$i] $callbackIds[$i + 1]` + "\n"); + print (" tag: " + `AL_usdmaya_CallbackQuery -tag $callbackIds[$i] $callbackIds[$i + 1]` + +"\n"); // print the eventId for the callback - print (" eventId: " + `AL_usdmaya_CallbackQuery -e $callbackIds[$i] $callbackIds[$i + 1]` + "\n"); + print (" eventId: " + `AL_usdmaya_CallbackQuery -e $callbackIds[$i] $callbackIds[$i + 1]` + +"\n"); // print the type of the callback (returns "Python", "MEL", or "C") - print (" type: " + `AL_usdmaya_CallbackQuery -ty $callbackIds[$i] $callbackIds[$i + 1]` + "\n"); + print (" type: " + `AL_usdmaya_CallbackQuery -ty $callbackIds[$i] $callbackIds[$i + 1]` + +"\n"); // print the callback weight - print (" weight: " + `AL_usdmaya_CallbackQuery -w $callbackIds[$i] $callbackIds[$i + 1]` + "\n"); + print (" weight: " + `AL_usdmaya_CallbackQuery -w $callbackIds[$i] $callbackIds[$i + 1]` + +"\n"); // print the callback code print (" code: \n----------------------------------------------------------------\n" + @@ -333,8 +349,9 @@ AL_usdmaya_Event -d "AnEventDefinedInMEL"; \subsection nodeEventsC Node Events in C++ -To make use of the maya node events, your node should derive from the AL::usdmaya::nodes::MayaNodeEvents class. -A simple example of setting a node up with the events system would look like so: +To make use of the maya node events, your node should derive from the +AL::usdmaya::nodes::MayaNodeEvents class. A simple example of setting a node up with the events +system would look like so: \code @@ -356,7 +373,8 @@ class MyMayaNode ~MyMayaNode() { - // you don't need to unregister events (events are automatically unregistered in the MayaNodeEvents dtor). + // you don't need to unregister events (events are automatically unregistered in the +MayaNodeEvents dtor). // This is only here for example purposes unregisterEvent("PreThingHappened"); unregisterEvent("PostThingHappened"); @@ -380,8 +398,9 @@ class MyMayaNode }; \endcode -That's basically the only setup you need to perform in order to make a custom plugin node compatible with -the events system. We can now use AL_usdmaya_ListEvents to get a list of the events that the node supports +That's basically the only setup you need to perform in order to make a custom plugin node compatible +with the events system. We can now use AL_usdmaya_ListEvents to get a list of the events that the +node supports \code // create a node that supports events @@ -396,21 +415,23 @@ print `AL_usdmaya_ListEvents $node`; // PostThingHappened \endcode -Via the MEL command AL_usdmaya_Callback it is possible to assign a callback from a MEL or python script to that node. +Via the MEL command AL_usdmaya_Callback it is possible to assign a callback from a MEL or python +script to that node. \code // simple callback string $melCodeToExecute = "print \"mel callback!\n\""; -// -mne/-melNodeEvent flag arguments: (note: -pne/-pythonNodeEvent will treat the callback code as python) +// -mne/-melNodeEvent flag arguments: (note: -pne/-pythonNodeEvent will treat the callback code as +python) // * The node name // * The event name // * A unique tag to identify the callback // * The integer weight for the callback // * The MEL script to execute // -global int $callbackId[] = `AL_usdmaya_Callback -mne $node "PreThingHappened" "MyMelScript_operation" 10001 $melCodeToExecute`; -\endcode +global int $callbackId[] = `AL_usdmaya_Callback -mne $node "PreThingHappened" +"MyMelScript_operation" 10001 $melCodeToExecute`; \endcode We can also trigger the event from MEL/python if we wish: @@ -423,8 +444,8 @@ AL_usdmaya_TriggerEvent "PreThingHappened" $node; \endcode -As with the Global Events, these pair of callback values can be used to query some information about the callback using the -command AL_usdmaya_CallbackQuery +As with the Global Events, these pair of callback values can be used to query some information about +the callback using the command AL_usdmaya_CallbackQuery \code // print the tag for the callback @@ -443,7 +464,8 @@ print ("weight: " + `AL_usdmaya_CallbackQuery -w $callbackId[0] $callbackId[1]` print ("code: " + `AL_usdmaya_CallbackQuery -c $callbackId[0] $callbackId[1]` + "\n"); \endcode -If you wish to see which callbacks are registered against a specific event, you can use the AL_usdmaya_ListCallbacks command, e.g. +If you wish to see which callbacks are registered against a specific event, you can use the +AL_usdmaya_ListCallbacks command, e.g. \code proc printNodeCallbackInfo(string $eventName, string $node) @@ -452,19 +474,24 @@ proc printNodeCallbackInfo(string $eventName, string $node) print ("EventBreakdown for node: " + $node + " and event: " + $eventName + "\n"); for(int $i = 0; $i < size($callbackIds); $i += 2) { - print ("callback " + ($i / 2 + 1) + " : [" + $callbackIds[$i] + ", " + $callbackIds[$i + 1] + "]\n"); + print ("callback " + ($i / 2 + 1) + " : [" + $callbackIds[$i] + ", " + $callbackIds[$i + 1] + +"]\n"); // print the tag for the callback - print (" tag: " + `AL_usdmaya_CallbackQuery -tag $callbackIds[$i] $callbackIds[$i + 1]` + "\n"); + print (" tag: " + `AL_usdmaya_CallbackQuery -tag $callbackIds[$i] $callbackIds[$i + 1]` + +"\n"); // print the eventId for the callback - print (" eventId: " + `AL_usdmaya_CallbackQuery -e $callbackIds[$i] $callbackIds[$i + 1]` + "\n"); + print (" eventId: " + `AL_usdmaya_CallbackQuery -e $callbackIds[$i] $callbackIds[$i + 1]` + +"\n"); // print the type of the callback (returns "Python", "MEL", or "C") - print (" type: " + `AL_usdmaya_CallbackQuery -ty $callbackIds[$i] $callbackIds[$i + 1]` + "\n"); + print (" type: " + `AL_usdmaya_CallbackQuery -ty $callbackIds[$i] $callbackIds[$i + 1]` + +"\n"); // print the callback weight - print (" weight: " + `AL_usdmaya_CallbackQuery -w $callbackIds[$i] $callbackIds[$i + 1]` + "\n"); + print (" weight: " + `AL_usdmaya_CallbackQuery -w $callbackIds[$i] $callbackIds[$i + 1]` + +"\n"); // print the callback code print (" code: \n----------------------------------------------------------------\n" + @@ -487,7 +514,8 @@ AL_usdmaya_Callback -d $callbackId[0] $callbackId[1]; AL_usdmaya_DeleteCallbacks $callbackId[0]; \endcode -It is also possible to define entirely new events on the node in your own MEL or python scripts, e.g. +It is also possible to define entirely new events on the node in your own MEL or python scripts, +e.g. \code @@ -504,9 +532,10 @@ AL_usdmaya_Event -d "AnEventDefinedInMEL" $node; \subsection parentEventsC Parent / Child events in C++ -As an optional part of the events system, it is possible to provide additional information to an event that describes -a parent/child relationship between callbacks and events. Child events themselves are not triggered automatically (that -task is something that needs to be done manually), and child events can only be parented to a callback. +As an optional part of the events system, it is possible to provide additional information to an +event that describes a parent/child relationship between callbacks and events. Child events +themselves are not triggered automatically (that task is something that needs to be done manually), +and child events can only be parented to a callback. \code @@ -567,10 +596,10 @@ MStatus initializePlugin(MObject obj) // Simply as an example, we may wish to register a C callback on the event! g_myCallbackId1 = scheduler.registerCallback( g_mySimpleEvent1, ///< the event Id we wish to have our callback triggered on - "myToolName_myCallbackFunction1", ///< a unique tag to identify the who owns the callback, and its purpose - myCallbackFunction1, ///< the C function we wish to execute - 10000, ///< a weight value for the callback. Smaller values are executed first, larger last - nullptr); ///< an optional userData pointer + "myToolName_myCallbackFunction1", ///< a unique tag to identify the who owns the callback, and +its purpose myCallbackFunction1, ///< the C function we wish to execute 10000, ///< a +weight value for the callback. Smaller values are executed first, larger last nullptr); ///< an +optional userData pointer // make sure the callback registered correctly if(g_myCallbackId1 == 0) @@ -579,7 +608,8 @@ MStatus initializePlugin(MObject obj) } // lets register a simple event - g_mySimpleEvent2 = scheduler.registerEvent("OnChildThingHappened", kUserSpecifiedEventType, g_myCallbackId1); + g_mySimpleEvent2 = scheduler.registerEvent("OnChildThingHappened", kUserSpecifiedEventType, +g_myCallbackId1); // make sure the event registered correctly if(g_mySimpleEvent2 == 0) @@ -590,10 +620,10 @@ MStatus initializePlugin(MObject obj) // Simply as an example, we may wish to register a C callback on the event! g_myCallbackId2 = scheduler.registerCallback( g_mySimpleEvent2, ///< the event Id we wish to have our callback triggered on - "myToolName_myCallbackFunction2", ///< a unique tag to identify the who owns the callback, and its purpose - myCallbackFunction2, ///< the C function we wish to execute - 10000, ///< a weight value for the callback. Smaller values are executed first, larger last - nullptr); ///< an optional userData pointer + "myToolName_myCallbackFunction2", ///< a unique tag to identify the who owns the callback, and +its purpose myCallbackFunction2, ///< the C function we wish to execute 10000, ///< a +weight value for the callback. Smaller values are executed first, larger last nullptr); ///< an +optional userData pointer // make sure the callback registered correctly if(g_myCallbackId2 == 0) @@ -669,7 +699,8 @@ int $parentCallback[] = `AL_usdmaya_EventQuery -p $childEventName`; // quickly check to see whether the event has a callback or not if(size($parentCallback)) { - print ("parent callback of " + $childEventName + " has ID [" + $parentCallback[0] + ", " + $parentCallback[1] + "]\n"); + print ("parent callback of " + $childEventName + " has ID [" + $parentCallback[0] + ", " + +$parentCallback[1] + "]\n"); } else { @@ -677,33 +708,36 @@ else } \endcode -similarly, given a callback you can determine the child event ID's via the AL_usdmaya_CallbackQuery command and the --ce / -childEvents flag: +similarly, given a callback you can determine the child event ID's via the AL_usdmaya_CallbackQuery +command and the -ce / -childEvents flag: \code // query the parent callback to the child event -int $childEventIds[] = `AL_usdmaya_CallbackQuery -ce $mainEventName $parentCallback[0] $parentCallback[1]`; +int $childEventIds[] = `AL_usdmaya_CallbackQuery -ce $mainEventName $parentCallback[0] +$parentCallback[1]`; // quickly check to see whether the event has a callback or not for($event in $childEventIds) { - print ("eventID " + $event + " is a child of callback " + $parentCallback[0] + " " + $parentCallback[1] + "\n"); + print ("eventID " + $event + " is a child of callback " + $parentCallback[0] + " " + +$parentCallback[1] + "\n"); } \endcode -If you wish to convert the event ID back into the text name (and possibly get the associated node) you the -AL_usdmaya_EventLookup command +If you wish to convert the event ID back into the text name (and possibly get the associated node) +you the AL_usdmaya_EventLookup command \code // query the parent callback to the child event -int $childEventIds[] = `AL_usdmaya_CallbackQuery -ce $mainEventName $parentCallback[0] $parentCallback[1]`; +int $childEventIds[] = `AL_usdmaya_CallbackQuery -ce $mainEventName $parentCallback[0] +$parentCallback[1]`; // quickly check to see whether the event has a callback or not for($event in $childEventIds) { - print ("eventID " + $event + " is a child of callback " + $parentCallback[0] + " " + $parentCallback[1] + "\n"); - print (" - eventName " + `AL_usdmaya_EventLookup -name $event` + "\n"); - print (" - owningNode " + `AL_usdmaya_EventLookup -node $event` + "\n"); + print ("eventID " + $event + " is a child of callback " + $parentCallback[0] + " " + +$parentCallback[1] + "\n"); print (" - eventName " + `AL_usdmaya_EventLookup -name $event` + +"\n"); print (" - owningNode " + `AL_usdmaya_EventLookup -node $event` + "\n"); } \endcode diff --git a/plugin/al/lib/AL_USDMaya/AL/docpages/docs_mayaevents.h b/plugin/al/lib/AL_USDMaya/AL/docpages/docs_mayaevents.h index 8af04647c8..4cc5a0905f 100644 --- a/plugin/al/lib/AL_USDMaya/AL/docpages/docs_mayaevents.h +++ b/plugin/al/lib/AL_USDMaya/AL/docpages/docs_mayaevents.h @@ -5,15 +5,15 @@ \section events_MayaEvents Maya Event System -As a direct replacement to MMessage (and related classes) the class AL::maya::MayaEventManager provides an interface -to register your own C++ callback functions. All of the static methods AL::maya::MayaEventManager::registerCallback take -the following arguments: +As a direct replacement to MMessage (and related classes) the class AL::maya::MayaEventManager +provides an interface to register your own C++ callback functions. All of the static methods +AL::maya::MayaEventManager::registerCallback take the following arguments: \li func - the C++ function pointer \li eventName - the name of the the event (see list below) \li tag - a unique a tag string to identify the creator of the callback -\li weight - the event weight (lowest weights are executed first, highest last, all usdmaya weights are 0x1000) -\li userData - an optional user data pointer +\li weight - the event weight (lowest weights are executed first, highest last, all usdmaya weights +are 0x1000) \li userData - an optional user data pointer The list of registered event names can be queried by running the mel command: @@ -21,7 +21,8 @@ The list of registered event names can be queried by running the mel command: print `AL_usdmaya_ListEvents`; \endcode -The following table lists the registered event name, and the type of callback function required to handle that callback. +The following table lists the registered event name, and the type of callback function required to +handle that callback. \li \b "AnimCurveEdited" - AL::maya::event::MayaCallbackType::kObjArrayFunction \li \b "AnimKeyFrameEdited" - AL::maya::event::MayaCallbackType::kObjArrayFunction @@ -113,8 +114,10 @@ A quick example of replacing a MSceneMessage::kAfterNew message with the events \code -#include #include "AL/maya/event/MayaEventManager.h" + +#include + #include void onFileNewCallback() diff --git a/plugin/al/lib/AL_USDMaya/AL/docpages/docs_mayahelpers.h b/plugin/al/lib/AL_USDMaya/AL/docpages/docs_mayahelpers.h index 60b565d21f..c3710cef77 100644 --- a/plugin/al/lib/AL_USDMaya/AL/docpages/docs_mayahelpers.h +++ b/plugin/al/lib/AL_USDMaya/AL/docpages/docs_mayahelpers.h @@ -3,8 +3,8 @@ \page mayahelpers Maya API Helper Classes -Most of the custom nodes and commands that form part of the AL_usdmaya plug-in utilize helper classes to automate some of the -boiler plate aspects of the Maya API. These include: +Most of the custom nodes and commands that form part of the AL_usdmaya plug-in utilize helper +classes to automate some of the boiler plate aspects of the Maya API. These include: \li \b MPxCommand : creation of option box GUI's, option vars, and menu items \li \b MPxNode : automatic generation of attribute editor templates @@ -13,12 +13,14 @@ boiler plate aspects of the Maya API. These include: \section almaya_commandgui AL::maya::utils::CommandGuiHelper -Typically within Maya most MEL commands end up being exposed to the user via a fairly standard pattern, where by you have a menu item -on a menu somewhere, along with an option box that allows you to configure some preferences that are stored between Maya sessions. -The MEL code needed to implement this is not overly complicated, but it can be rather tedious, and occasionally prone to errors. +Typically within Maya most MEL commands end up being exposed to the user via a fairly standard +pattern, where by you have a menu item on a menu somewhere, along with an option box that allows you +to configure some preferences that are stored between Maya sessions. The MEL code needed to +implement this is not overly complicated, but it can be rather tedious, and occasionally prone to +errors. -As a way to minimize the possibility of bugs, most MEL commands within the USD maya bridge have an auto generated GUI to go along with -them. +As a way to minimize the possibility of bugs, most MEL commands within the USD maya bridge have an +auto generated GUI to go along with them. \code // initialise a new GUI for the AL_usdmaya_ProxyShapeImport command with: @@ -27,18 +29,22 @@ them. // * "Import" as a text label on the OK button // * A menu item called "Import" found under the USD/Proxy Shape/ menu // - AL::maya::utils::CommandGuiHelper commandGui("AL_usdmaya_ProxyShapeImport", "Proxy Shape Import", "Import", "USD/Proxy Shape/Import", true); + AL::maya::utils::CommandGuiHelper commandGui("AL_usdmaya_ProxyShapeImport", "Proxy Shape +Import", "Import", "USD/Proxy Shape/Import", true); // and now we need to add GUI items for each of the flags to the actual command - commandGui.addFilePathOption("file", "File Path", AL::maya::utils::CommandGuiHelper::kLoad, "USD Ascii (*.usd) (*.usd)", AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); - commandGui.addStringOption("primPath", "USD Prim Path", "", false, AL::maya::utils::CommandGuiHelper::kStringOptional); - commandGui.addStringOption("excludePrimPath", "Exclude Prim Path", "", false, AL::maya::utils::CommandGuiHelper::kStringOptional); - commandGui.addStringOption("name", "Proxy Shape Node Name", "", false, AL::maya::utils::CommandGuiHelper::kStringOptional); - commandGui.addBoolOption("connectToTime", "Connect to Time", true, true); - commandGui.addBoolOption("unloaded", "Opens the layer with payloads unloaded.", false, true); -\endcode - -All of that auto generates a series of MEL functions that in total make our GUI. Below is an annotated version of the generated MEL script. + commandGui.addFilePathOption("file", "File Path", AL::maya::utils::CommandGuiHelper::kLoad, "USD +Ascii (*.usd) (*.usd)", AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); + commandGui.addStringOption("primPath", "USD Prim Path", "", false, +AL::maya::utils::CommandGuiHelper::kStringOptional); commandGui.addStringOption("excludePrimPath", +"Exclude Prim Path", "", false, AL::maya::utils::CommandGuiHelper::kStringOptional); + commandGui.addStringOption("name", "Proxy Shape Node Name", "", false, +AL::maya::utils::CommandGuiHelper::kStringOptional); commandGui.addBoolOption("connectToTime", +"Connect to Time", true, true); commandGui.addBoolOption("unloaded", "Opens the layer with payloads +unloaded.", false, true); \endcode + +All of that auto generates a series of MEL functions that in total make our GUI. Below is an +annotated version of the generated MEL script. \code // This method is called when clicking on an option box menu item, or (as in this case) when you @@ -47,7 +53,8 @@ global proc build_AL_usdmaya_ProxyShapeImport_optionGUI() { // only allow one option box to be visible if(`window -q -ex "AL_usdmaya_ProxyShapeImport_optionGUI"`) return; - $window = `window -title "Proxy Shape Import" -w 550 -h 350 "AL_usdmaya_ProxyShapeImport_optionGUI"`; + $window = `window -title "Proxy Shape Import" -w 550 -h 350 +"AL_usdmaya_ProxyShapeImport_optionGUI"`; // Add the edit menu, with reset & save settings options $menuBarLayout = `menuBarLayout`; @@ -72,12 +79,14 @@ global proc build_AL_usdmaya_ProxyShapeImport_optionGUI() setParent ..; // Now add the OK, Save, and Close buttons - // * OK : First save all of the control settings, then execute the command (using saved settings), and finally destroy the option box window. + // * OK : First save all of the control settings, then execute the command (using saved +settings), and finally destroy the option box window. // * Save: Just save the options // * Close: destroy the window $rowLayout = `paneLayout -cn "vertical3"`; - $doit = `button -label "Import" -c ("save_AL_usdmaya_ProxyShapeImport_optionGUI;execute_AL_usdmaya_ProxyShapeImport_optionGUI;deleteUI " + $window)`; - $saveit = `button -label "Apply" -c "save_AL_usdmaya_ProxyShapeImport_optionGUI"`; + $doit = `button -label "Import" -c +("save_AL_usdmaya_ProxyShapeImport_optionGUI;execute_AL_usdmaya_ProxyShapeImport_optionGUI;deleteUI +" + $window)`; $saveit = `button -label "Apply" -c "save_AL_usdmaya_ProxyShapeImport_optionGUI"`; $close = `button -label "Close" -c ("deleteUI " + $window)`;o setParent ..; formLayout -e @@ -113,8 +122,9 @@ global proc init_AL_usdmaya_ProxyShapeImport_optionGUI() // It retrieves the current values from the GUI, and then updates the option var values. global proc save_AL_usdmaya_ProxyShapeImport_optionGUI() { - optionVar -iv "AL_usdmaya_ProxyShapeImport_connectToTime" `checkBox -q -v AL_usdmaya_ProxyShapeImport_connectToTime`; - optionVar -iv "AL_usdmaya_ProxyShapeImport_unloaded" `checkBox -q -v AL_usdmaya_ProxyShapeImport_unloaded`; + optionVar -iv "AL_usdmaya_ProxyShapeImport_connectToTime" `checkBox -q -v +AL_usdmaya_ProxyShapeImport_connectToTime`; optionVar -iv "AL_usdmaya_ProxyShapeImport_unloaded" +`checkBox -q -v AL_usdmaya_ProxyShapeImport_unloaded`; }; // After the dialog is created, this method reads the current option var values, @@ -124,8 +134,9 @@ global proc load_AL_usdmaya_ProxyShapeImport_optionGUI() textField -e -tx "" AL_usdmaya_ProxyShapeImport_primPath; textField -e -tx "" AL_usdmaya_ProxyShapeImport_excludePrimPath; textField -e -tx "" AL_usdmaya_ProxyShapeImport_name; - checkBox -e -v `optionVar -q "AL_usdmaya_ProxyShapeImport_connectToTime"` AL_usdmaya_ProxyShapeImport_connectToTime; - checkBox -e -v `optionVar -q "AL_usdmaya_ProxyShapeImport_unloaded"` AL_usdmaya_ProxyShapeImport_unloaded; + checkBox -e -v `optionVar -q "AL_usdmaya_ProxyShapeImport_connectToTime"` +AL_usdmaya_ProxyShapeImport_connectToTime; checkBox -e -v `optionVar -q +"AL_usdmaya_ProxyShapeImport_unloaded"` AL_usdmaya_ProxyShapeImport_unloaded; }; // If you select the 'Reset' menu item, this method will be called. @@ -161,7 +172,8 @@ global proc execute_AL_usdmaya_ProxyShapeImport_optionGUI() if(`textField -ex AL_usdmaya_ProxyShapeImport_excludePrimPath`) if(size(`textField -q -tx AL_usdmaya_ProxyShapeImport_excludePrimPath`)) - $str += " -excludePrimPath \"" + `textField -q -tx AL_usdmaya_ProxyShapeImport_excludePrimPath` + "\""; + $str += " -excludePrimPath \"" + `textField -q -tx +AL_usdmaya_ProxyShapeImport_excludePrimPath` + "\""; if(`textField -ex AL_usdmaya_ProxyShapeImport_name`) if(size(`textField -q -tx AL_usdmaya_ProxyShapeImport_name`)) @@ -190,9 +202,9 @@ global proc build_AL_usdmaya_ProxyShapeImport_labels() // construct each control global proc build_AL_usdmaya_ProxyShapeImport_controls() { - textFieldButtonGrp -h 20 -bl "..." -bc "alFileDialogHandler(\"USD Ascii (*.usd) (*.usd)\", \"AL_usdmaya_ProxyShapeImport_file\", 1)" AL_usdmaya_ProxyShapeImport_file; - textField -h 20 AL_usdmaya_ProxyShapeImport_primPath; - textField -h 20 AL_usdmaya_ProxyShapeImport_excludePrimPath; + textFieldButtonGrp -h 20 -bl "..." -bc "alFileDialogHandler(\"USD Ascii (*.usd) (*.usd)\", +\"AL_usdmaya_ProxyShapeImport_file\", 1)" AL_usdmaya_ProxyShapeImport_file; textField -h 20 +AL_usdmaya_ProxyShapeImport_primPath; textField -h 20 AL_usdmaya_ProxyShapeImport_excludePrimPath; textField -h 20 AL_usdmaya_ProxyShapeImport_name; checkBox -l "" -h 20 AL_usdmaya_ProxyShapeImport_connectToTime; checkBox -l "" -h 20 AL_usdmaya_ProxyShapeImport_unloaded; @@ -203,4 +215,3 @@ global proc build_AL_usdmaya_ProxyShapeImport_controls() */ - diff --git a/plugin/al/lib/AL_USDMaya/AL/docpages/docs_translator_plugins.h b/plugin/al/lib/AL_USDMaya/AL/docpages/docs_translator_plugins.h index 479b831e5d..e0cce77e50 100644 --- a/plugin/al/lib/AL_USDMaya/AL/docpages/docs_translator_plugins.h +++ b/plugin/al/lib/AL_USDMaya/AL/docpages/docs_translator_plugins.h @@ -3,20 +3,22 @@ \page translator_plugins Custom Plugin Translators -The plug-in translator system that is the core of AL_USDMaya provides a number of ways to integrate USD with existing -maya nodes (including custom Maya plug-ins). Any particular type can be integrated in one (or all) of these ways: +The plug-in translator system that is the core of AL_USDMaya provides a number of ways to integrate +USD with existing maya nodes (including custom Maya plug-ins). Any particular type can be integrated +in one (or all) of these ways: * File Import * File Export * Importing as part of an AL_usdmaya_ProxyShape * Handling the changes to a AL_usdmaya_ProxyShape as a result of a variant switch -The API for defining your own plug-in translator may at first seems a little convoluted (especially if you were expecting -to override a pair of import/export methods), however this API has evolved over time to ensure it works correctly with -live variant switches, prim activation/de-activation, and a number of other live changes to the underlying USD scene. +The API for defining your own plug-in translator may at first seems a little convoluted (especially +if you were expecting to override a pair of import/export methods), however this API has evolved +over time to ensure it works correctly with live variant switches, prim activation/de-activation, +and a number of other live changes to the underlying USD scene. -To try to explain how this all works, let's start of with an extremely silly plug-in example that will create a custom -translator plugin to represent a polygon cube node in Maya. +To try to explain how this all works, let's start of with an extremely silly plug-in example that +will create a custom translator plugin to represent a polygon cube node in Maya. *PolyCubeNodeTranslator.h* \code @@ -45,7 +47,8 @@ class PolyCubeNodeTranslator // new to AL_USDMaya 0.29.0 ExportFlag canExport(const MObject& obj) override; - UsdPrim exportObject(UsdStageRefPtr stage, MDagPath dagPath, const SdfPath& usdPath, const ExporterParams& params) override; + UsdPrim exportObject(UsdStageRefPtr stage, MDagPath dagPath, const SdfPath& usdPath, const +ExporterParams& params) override; private: @@ -63,16 +66,16 @@ class PolyCubeNodeTranslator }; \endcode -As an absolute minimum, you'll need to implement the update and tearDown methods. The following is an explanation of what those -methods do, and how to implement them correctly. +As an absolute minimum, you'll need to implement the update and tearDown methods. The following is +an explanation of what those methods do, and how to implement them correctly. \b General \b Setup *PolyCubeNodeTranslator.cpp* \code -#include "PolyCubeNodeTranslator.h" #include "AL/usd/schemas/maya/PolyCube.h" //< this is the custom schema you have created +#include "PolyCubeNodeTranslator.h" // Some macro magic that generates some boiler plate code. AL_USDMAYA_DEFINE_TRANSLATOR(PolyCubeNodeTranslator, AL_usd_PolyCube); @@ -81,9 +84,10 @@ AL_USDMAYA_DEFINE_TRANSLATOR(PolyCubeNodeTranslator, AL_usd_PolyCube); \b initialize -The initialize method is a one time initialisation step for your translator plug-in. Now we all want to ensure our plug-ins -operate as quickly as possible right? So the initialize step is really to help improve the performance when accessing data -via MPlugs (i.e. Ideally we don't want to be accessing MPlugs by constantly calling findPlug("someString")) +The initialize method is a one time initialisation step for your translator plug-in. Now we all want +to ensure our plug-ins operate as quickly as possible right? So the initialize step is really to +help improve the performance when accessing data via MPlugs (i.e. Ideally we don't want to be +accessing MPlugs by constantly calling findPlug("someString")) \code MStatus PolyCubeNodeTranslator::initialize() @@ -95,7 +99,8 @@ MStatus PolyCubeNodeTranslator::initialize() // assign a node class to the polyCube MNodeClass polyCube("polyCube"); - // now do a one time look up of the attributes. This now means we can access the attributes directly + // now do a one time look up of the attributes. This now means we can access the attributes +directly // without needing to call MFnDependencyNode::findPlug() (and the string compares that implies!) m_width = polyCube.attribute("width"); m_height = polyCube.attribute("height"); @@ -110,9 +115,10 @@ MStatus PolyCubeNodeTranslator::initialize() m_inputMesh = mesh.attribute("input"); - // Now obviously you're a careful developer, and have been checking all MStatus values in the code above right??? - // Just returning success isn't something we're advocating here, it's just a silly tutorial after all! - return MS::kSuccess; + // Now obviously you're a careful developer, and have been checking all MStatus values in the code +above right??? + // Just returning success isn't something we're advocating here, it's just a silly tutorial after +all! return MS::kSuccess; } \endcode @@ -128,23 +134,25 @@ bool PolyCubeNodeTranslator::needsTransformParent() const } \endcode -If your node is a DAG node (i.e. a shape or custom transform), it will need to have a transform created for it, -so return true in this case. If however you node is a simple DG node (e.g. surface shader, texture etc), -then you should return false from this method. +If your node is a DAG node (i.e. a shape or custom transform), it will need to have a transform +created for it, so return true in this case. If however you node is a simple DG node (e.g. surface +shader, texture etc), then you should return false from this method. -If you return true, a new transform will be generated within Maya to which you can parent your shape on creation. -If you return false, no transform will be generated. +If you return true, a new transform will be generated within Maya to which you can parent your shape +on creation. If you return false, no transform will be generated. \b import -The Import method should only *really* be used to create the Maya nodes that will represent your custom prim. -Now there is a small caveat to this. If the contents of your prim does not have any relationships to other -prims in the stage, then you may as well do all of the setup you need within Import. +The Import method should only *really* be used to create the Maya nodes that will represent your +custom prim. Now there is a small caveat to this. If the contents of your prim does not have any +relationships to other prims in the stage, then you may as well do all of the setup you need within +Import. -This example will create a simple polyCubeCreator node, a mesh, and connect them together. To do this will not require -information from any other prim (for example, if there was another prim that contained a surface material, or a mesh -deformation, then there would be a second step involved here to make those relationships in the Maya DG). +This example will create a simple polyCubeCreator node, a mesh, and connect them together. To do +this will not require information from any other prim (for example, if there was another prim that +contained a surface material, or a mesh deformation, then there would be a second step involved here +to make those relationships in the Maya DG). \code MStatus PolyCubeNodeTranslator::import(const UsdPrim& prim, MObject& parent) @@ -152,9 +160,9 @@ MStatus PolyCubeNodeTranslator::import(const UsdPrim& prim, MObject& parent) MFnDependencyNode fnDep; MFnDagNode fnDag; - // create the two maya nodes we need (parent the shape under the transform node that's been created for us) - MObject oPolyCube = fnDep.createNode(); - MObject oMesh = fnDag.createNode("mesh", parent); + // create the two maya nodes we need (parent the shape under the transform node that's been +created for us) MObject oPolyCube = fnDep.createNode(); MObject oMesh = fnDag.createNode("mesh", +parent); // we need to register the nodes we create with the context()->insertItem(prim.GetPath(), oPolyCube); @@ -191,24 +199,27 @@ MStatus PolyCubeNodeTranslator::import(const UsdPrim& prim, MObject& parent) \b Post \b Import -Having generated all of the nodes you need to, you might end up needing to hook those nodes to other prims. -This is admittedly a bit of a bad example (because in this case the node connections could have all been made -within import itself). +Having generated all of the nodes you need to, you might end up needing to hook those nodes to other +prims. This is admittedly a bit of a bad example (because in this case the node connections could +have all been made within import itself). -However, in cases where the scene involves relationships between prims (e.g. one prim is a material, the other -is the shape), it won't be possible to make those connections within import (because the other Maya node may not -have been created yet). In those cases, you will need to make use of the postImport method to perform the connection -of the maya nodes to other prims. +However, in cases where the scene involves relationships between prims (e.g. one prim is a material, +the other is the shape), it won't be possible to make those connections within import (because the +other Maya node may not have been created yet). In those cases, you will need to make use of the +postImport method to perform the connection of the maya nodes to other prims. \code MStatus PolyCubeNodeTranslator::postImport(const UsdPrim& inputPrim, MObject& parent) { // Previously we created two Maya nodes for our inputPrim (the mesh and the polycube). - // Whenever you need to retrieve those Maya nodes, you can retrieve them from the translator context + // Whenever you need to retrieve those Maya nodes, you can retrieve them from the translator +context // by passing the prim, and the type of node you are searching for, into the getMObject function. // - // If you have a situation where your inputPrim has a relationship to another prim (e.g. the other prim - // may be a surface material, geometry deformer, etc), and you wish to extract the MObject for that related + // If you have a situation where your inputPrim has a relationship to another prim (e.g. the other +prim + // may be a surface material, geometry deformer, etc), and you wish to extract the MObject for +that related // prim, then just pass the related prim in as the first argument, and it will be returned to you. MObjectHandle handleToMesh; @@ -227,8 +238,8 @@ MStatus PolyCubeNodeTranslator::postImport(const UsdPrim& inputPrim, MObject& pa // now connect the output of the polycube to the input of the mesh. MDGModifier mod; - mod.connect(MPlug(handleToPolyCube.object(), m_outputMesh), MPlug(handleToMesh.object(), m_inputMesh)); - mod.doIt(); + mod.connect(MPlug(handleToPolyCube.object(), m_outputMesh), MPlug(handleToMesh.object(), +m_inputMesh)); mod.doIt(); // please check and log any errors rather than simply returning success! return MS::kSuccess; @@ -238,16 +249,16 @@ MStatus PolyCubeNodeTranslator::postImport(const UsdPrim& inputPrim, MObject& pa \b Variant \b Switching -If you've only supported the methods previously discussed, then your custom prim type should now be imported when -you load a usd scene with the proxy shape. +If you've only supported the methods previously discussed, then your custom prim type should now be +imported when you load a usd scene with the proxy shape. -If however you want to be able to respond to variant switches, and swap in or out nodes as a result, there is a -little bit more work to do. +If however you want to be able to respond to variant switches, and swap in or out nodes as a result, +there is a little bit more work to do. -When a variant is switched, the proxy shape intercepts an event generated by USD that indicates that a variant is -about to switch on a specific prim. At this point, the AL maya plugin will traverse the hierarchy under the -prim on which the variant switched, and call a preTearDown() method. This method can be used to copy any values -from your maya nodes into a layer within the usd stage. +When a variant is switched, the proxy shape intercepts an event generated by USD that indicates that +a variant is about to switch on a specific prim. At this point, the AL maya plugin will traverse the +hierarchy under the prim on which the variant switched, and call a preTearDown() method. This method +can be used to copy any values from your maya nodes into a layer within the usd stage. \code // This is just a helper method (to avoid some code duplication later on) @@ -300,14 +311,15 @@ MStatus PolyCubeNodeTranslator::preTearDown(UsdPrim& prim) After the variant switch has occurred, the AL USD plugin will do a quick sanity check comparing the prims that were there previously, and the ones that are there now. -For each prim, if a corresponding prim still exists after the variant switch, AND the prim type is the same, -then it call an update() method on your translator. Adding this method is optional, however it can improve -the speed of a variant switch, so it is recommended! +For each prim, if a corresponding prim still exists after the variant switch, AND the prim type is +the same, then it call an update() method on your translator. Adding this method is optional, +however it can improve the speed of a variant switch, so it is recommended! -If you wish to provide an update method to your translator, you will first need to opt in to this mechanism. -By returning true from supportsUpdate (by default it returns false), you will now be able to provide a -slightly quicker way for handling prims that do not change as a result of the switch. If however you return -false here, your node will always be destroyed (via tear down), before being re-imported. +If you wish to provide an update method to your translator, you will first need to opt in to this +mechanism. By returning true from supportsUpdate (by default it returns false), you will now be able +to provide a slightly quicker way for handling prims that do not change as a result of the switch. +If however you return false here, your node will always be destroyed (via tear down), before being +re-imported. \code bool PolyCubeNodeTranslator::supportsUpdate() const @@ -316,8 +328,9 @@ bool PolyCubeNodeTranslator::supportsUpdate() const } \endcode -Once you have notified AL usd maya that your translator can update, simply provide your update function -(which should simply copy the values from the prim and onto the maya nodes you previously created) +Once you have notified AL usd maya that your translator can update, simply provide your update +function (which should simply copy the values from the prim and onto the maya nodes you previously +created) \code MStatus PolyCubeNodeTranslator::update(const UsdPrim& prim) @@ -360,8 +373,9 @@ MStatus PolyCubeNodeTranslator::update(const UsdPrim& prim) } \endcode -Now the eagle eyed reader may notice that the above function looks very similar to the import() function we initially -wrote. To save yourself from a boiler plate code explosion, one option would be to simply call update from import: +Now the eagle eyed reader may notice that the above function looks very similar to the import() +function we initially wrote. To save yourself from a boiler plate code explosion, one option would +be to simply call update from import: \code MStatus PolyCubeNodeTranslator::import(const UsdPrim& prim, MObject& parent) @@ -369,9 +383,9 @@ MStatus PolyCubeNodeTranslator::import(const UsdPrim& prim, MObject& parent) MFnDependencyNode fnDep; MFnDagNode fnDag; - // create the two maya nodes we need (parent the shape under the transform node that's been created for us) - MObject oPolyCube = fnDep.createNode(); - MObject oMesh = fnDag.createNode("mesh", parent); + // create the two maya nodes we need (parent the shape under the transform node that's been +created for us) MObject oPolyCube = fnDep.createNode(); MObject oMesh = fnDag.createNode("mesh", +parent); // we need to register the nodes we create with the context()->insertItem(prim.GetPath(), oPolyCube); @@ -382,8 +396,9 @@ MStatus PolyCubeNodeTranslator::import(const UsdPrim& prim, MObject& parent) } \endcode -Now, if the variant switch results in the prim type changing, or the prim being removed, then a final method will -be called, which is tearDown. The simplest implementation of this method is the following: +Now, if the variant switch results in the prim type changing, or the prim being removed, then a +final method will be called, which is tearDown. The simplest implementation of this method is the +following: \code MStatus PolyCubeNodeTranslator::tearDown(const SdfPath& primPath) @@ -394,24 +409,27 @@ MStatus PolyCubeNodeTranslator::tearDown(const SdfPath& primPath) } \endcode -In most cases that is probably enough. In some cases however, there may be times when you need to ensure the nodes -are deleted in a specific order, or you have some other book keeping exercise to perform. Feel free to do so here! +In most cases that is probably enough. In some cases however, there may be times when you need to +ensure the nodes are deleted in a specific order, or you have some other book keeping exercise to +perform. Feel free to do so here! -It should be noted that whilst preTearDown and update are optional, tearDown is NOT. You must implement this method -in order to support variant switching! +It should be noted that whilst preTearDown and update are optional, tearDown is NOT. You must +implement this method in order to support variant switching! \b Importable \b by \b Default -When a USD file is imported into a proxy shape node, if you \a always want that node to be imported immediately, -then you should return true from the importableByDefault method (which is the default). This will cause the -translator to be run as soon as the matching prim type has been encountered. In some cases, you might not want -those prims to be immediately imported. One example of this is with mesh data. +When a USD file is imported into a proxy shape node, if you \a always want that node to be imported +immediately, then you should return true from the importableByDefault method (which is the default). +This will cause the translator to be run as soon as the matching prim type has been encountered. In +some cases, you might not want those prims to be immediately imported. One example of this is with +mesh data. -If you are importing a very geometry heavy scene with a large number of dense meshes, you would want to keep -those meshes within USD/Hydra for as long as possible for performance reasons. If you return false from -importableByDefault, then that particular node type can only be manually imported by calling the AL_usdmaya_TranslatePrim -command. This means that importing and displaying the data will be quick by default, however if you need to make -modifications to that particular prim, you'll be able to selectively import the data when needed. +If you are importing a very geometry heavy scene with a large number of dense meshes, you would want +to keep those meshes within USD/Hydra for as long as possible for performance reasons. If you return +false from importableByDefault, then that particular node type can only be manually imported by +calling the AL_usdmaya_TranslatePrim command. This means that importing and displaying the data will +be quick by default, however if you need to make modifications to that particular prim, you'll be +able to selectively import the data when needed. \code bool PolyCubeNodeTranslator::importableByDefault() const @@ -422,9 +440,10 @@ bool PolyCubeNodeTranslator::importableByDefault() const \b canExport -If you wish to provide support for the standard file export operations (e.g. export some Maya data as a USD file), -then there is a two step process you need to adhere to. The first step is to determine whether this translator -can handle the export of a given Maya node, and the second step is to implement the actual export of that data. +If you wish to provide support for the standard file export operations (e.g. export some Maya data +as a USD file), then there is a two step process you need to adhere to. The first step is to +determine whether this translator can handle the export of a given Maya node, and the second step is +to implement the actual export of that data. \code ExportFlag PolyCubeNodeTranslator::canExport(const MObject& obj) @@ -451,10 +470,10 @@ ExportFlag PolyCubeNodeTranslator::canExport(const MObject& obj) \b exportObject -Finally, if the object can be exported by your translator, and it is the best translator available, then -AL_USDMaya will call the exportObject method to export the data into USD. It's worth noting that the -preTearDown and exportObject methods are likely to share a significant amount of code, hence the reason -for utilising a common 'writeEdits' method. +Finally, if the object can be exported by your translator, and it is the best translator available, +then AL_USDMaya will call the exportObject method to export the data into USD. It's worth noting +that the preTearDown and exportObject methods are likely to share a significant amount of code, +hence the reason for utilising a common 'writeEdits' method. \code UsdPrim PolyCubeNodeTranslator::exportObject( diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Api.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Api.h index a68ac4975f..51d1698fef 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Api.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Api.h @@ -15,26 +15,26 @@ // #if defined _WIN32 || defined __CYGWIN__ - #ifdef AL_USDMAYA_EXPORT - #ifdef __GNUC__ - #define AL_USDMAYA_PUBLIC __attribute__ ((dllexport)) - #else - #define AL_USDMAYA_PUBLIC __declspec(dllexport) - #endif - #else - #ifdef __GNUC__ - #define AL_USDMAYA_PUBLIC __attribute__ ((dllimport)) - #else - #define AL_USDMAYA_PUBLIC __declspec(dllimport) - #endif - #endif - #define AL_USDMAYA_LOCAL +#ifdef AL_USDMAYA_EXPORT +#ifdef __GNUC__ +#define AL_USDMAYA_PUBLIC __attribute__((dllexport)) #else - #if __GNUC__ >= 4 - #define AL_USDMAYA_PUBLIC __attribute__ ((visibility ("default"))) - #define AL_USDMAYA_LOCAL __attribute__ ((visibility ("hidden"))) - #else - #define AL_USDMAYA_PUBLIC - #define AL_USDMAYA_LOCAL - #endif +#define AL_USDMAYA_PUBLIC __declspec(dllexport) +#endif +#else +#ifdef __GNUC__ +#define AL_USDMAYA_PUBLIC __attribute__((dllimport)) +#else +#define AL_USDMAYA_PUBLIC __declspec(dllimport) +#endif +#endif +#define AL_USDMAYA_LOCAL +#else +#if __GNUC__ >= 4 +#define AL_USDMAYA_PUBLIC __attribute__((visibility("default"))) +#define AL_USDMAYA_LOCAL __attribute__((visibility("hidden"))) +#else +#define AL_USDMAYA_PUBLIC +#define AL_USDMAYA_LOCAL +#endif #endif diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/CodeTimings.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/CodeTimings.cpp index 5057213e4f..fe159797bb 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/CodeTimings.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/CodeTimings.cpp @@ -14,8 +14,9 @@ // limitations under the License. // #include "AL/usdmaya/CodeTimings.h" -#include + #include +#include #ifdef OSMac_ // For clock_gettime() @@ -27,88 +28,90 @@ namespace usdmaya { //---------------------------------------------------------------------------------------------------------------------- Profiler::ProfilerSectionStackNode Profiler::m_timeStack[MAX_TIMESTAMP_STACK_SIZE]; -uint32_t Profiler::m_stackPos = 0; -Profiler::ProfilerSectionPathLUT Profiler::m_map; +uint32_t Profiler::m_stackPos = 0; +Profiler::ProfilerSectionPathLUT Profiler::m_map; //---------------------------------------------------------------------------------------------------------------------- inline bool Profiler::compareTimeStamps(const iter_t a, const iter_t b) { - if(a->second.tv_sec > b->second.tv_sec) return true; - if(a->second.tv_sec < b->second.tv_sec) return false; - return a->second.tv_nsec > b->second.tv_nsec; + if (a->second.tv_sec > b->second.tv_sec) + return true; + if (a->second.tv_sec < b->second.tv_sec) + return false; + return a->second.tv_nsec > b->second.tv_nsec; } -#define INDENT for(uint32_t i = 0; i < indent; ++i) os << " "; +#define INDENT \ + for (uint32_t i = 0; i < indent; ++i) \ + os << " "; //---------------------------------------------------------------------------------------------------------------------- -void Profiler::print(std::ostream& os, iter_t it, const ProfilerSectionPathLUT& lut, uint32_t indent, double total) +void Profiler::print( + std::ostream& os, + iter_t it, + const ProfilerSectionPathLUT& lut, + uint32_t indent, + double total) { - const ProfilerSectionPath& hp = it->first; - const AL::usdmaya::ProfilerSectionTag& he = *hp.m_top; - - double timeTaken = (it->second.tv_sec * 1000.0f + it->second.tv_nsec * 0.000001f); - double percentage = timeTaken / total; - percentage = int(10000.0 * percentage) * 0.01; - - INDENT; - if(timeTaken > 20000.0) - { - os << "[" << percentage << "%](" << (timeTaken * 0.001) << "S) " << he.m_sectionName << std::endl; - } - else - { - os << "[" << percentage << "%](" << timeTaken << "ms) " << he.m_sectionName << std::endl; - } - - std::vector sorted; - for(auto a = lut.begin(), e = lut.end(); a != e; ++a) - { - if(a->first.m_parent == &hp) - { - sorted.push_back(a); + const ProfilerSectionPath& hp = it->first; + const AL::usdmaya::ProfilerSectionTag& he = *hp.m_top; + + double timeTaken = (it->second.tv_sec * 1000.0f + it->second.tv_nsec * 0.000001f); + double percentage = timeTaken / total; + percentage = int(10000.0 * percentage) * 0.01; + + INDENT; + if (timeTaken > 20000.0) { + os << "[" << percentage << "%](" << (timeTaken * 0.001) << "S) " << he.m_sectionName + << std::endl; + } else { + os << "[" << percentage << "%](" << timeTaken << "ms) " << he.m_sectionName << std::endl; + } + + std::vector sorted; + for (auto a = lut.begin(), e = lut.end(); a != e; ++a) { + if (a->first.m_parent == &hp) { + sorted.push_back(a); + } } - } - std::sort(sorted.begin(), sorted.end(), compareTimeStamps); + std::sort(sorted.begin(), sorted.end(), compareTimeStamps); - for(auto a = sorted.begin(), e = sorted.end(); a != e; ++a) - { - print(os, *a, lut, indent + 1, total); - } + for (auto a = sorted.begin(), e = sorted.end(); a != e; ++a) { + print(os, *a, lut, indent + 1, total); + } } //---------------------------------------------------------------------------------------------------------------------- void Profiler::printReport(std::ostream& os) { - double total = 0; - std::vector sorted; - for(auto a = m_map.begin(), e = m_map.end(); a != e; ++a) - { - if(!a->first.m_parent) - { - total += (a->second.tv_sec * 1000.0f + a->second.tv_nsec * 0.000001f); - sorted.push_back(a); + double total = 0; + std::vector sorted; + for (auto a = m_map.begin(), e = m_map.end(); a != e; ++a) { + if (!a->first.m_parent) { + total += (a->second.tv_sec * 1000.0f + a->second.tv_nsec * 0.000001f); + sorted.push_back(a); + } } - } - std::sort(sorted.begin(), sorted.end(), compareTimeStamps); + std::sort(sorted.begin(), sorted.end(), compareTimeStamps); - for(auto a = sorted.begin(), e = sorted.end(); a != e; ++a) - { - print(os, *a, m_map, 0, total); - } + for (auto a = sorted.begin(), e = sorted.end(); a != e; ++a) { + print(os, *a, m_map, 0, total); + } - clearAll(); + clearAll(); } #ifdef _WIN32 #include -int clock_gettime(int, struct timespec *spec) //C-file part +int clock_gettime(int, struct timespec* spec) // C-file part { - __int64 wintime; GetSystemTimeAsFileTime((FILETIME*)&wintime); - wintime -= 116444736000000000i64; //1jan1601 to 1jan1970 - spec->tv_sec = wintime / 10000000i64; //seconds - spec->tv_nsec = wintime % 10000000i64 * 100; //nano-seconds - return 0; + __int64 wintime; + GetSystemTimeAsFileTime((FILETIME*)&wintime); + wintime -= 116444736000000000i64; // 1jan1601 to 1jan1970 + spec->tv_sec = wintime / 10000000i64; // seconds + spec->tv_nsec = wintime % 10000000i64 * 100; // nano-seconds + return 0; } #define CLOCK_REALTIME_COARSE 0 @@ -117,67 +120,61 @@ int clock_gettime(int, struct timespec *spec) //C-file part //---------------------------------------------------------------------------------------------------------------------- void Profiler::pushTime(const AL::usdmaya::ProfilerSectionTag* entry) { - assert(MAX_TIMESTAMP_STACK_SIZE > m_stackPos); - m_timeStack[m_stackPos].m_entry = entry; - #ifdef _WIN32 - while(clock_gettime(CLOCK_REALTIME_COARSE, &m_timeStack[m_stackPos].m_time) != 0) /* deliberately empty */; - #endif - - const timespec null_ts = {0, 0}; - if(m_stackPos) - { - auto parent = m_timeStack[m_stackPos - 1].m_path; - ProfilerSectionPath path(entry, &parent->first); - auto it = m_map.find(path); - if(it != m_map.end()) - { - m_timeStack[m_stackPos].m_path = it; - } - else - { - m_map.insert(std::make_pair(path, null_ts)); - m_timeStack[m_stackPos].m_path = m_map.find(path); - } - } - else - { - ProfilerSectionPath path(entry, 0); - auto it = m_map.find(path); - if(it != m_map.end()) - { - m_timeStack[m_stackPos].m_path = it; - } - else - { - m_map.insert(std::make_pair(path, null_ts)); - m_timeStack[m_stackPos].m_path = m_map.find(path); + assert(MAX_TIMESTAMP_STACK_SIZE > m_stackPos); + m_timeStack[m_stackPos].m_entry = entry; +#ifdef _WIN32 + while (clock_gettime(CLOCK_REALTIME_COARSE, &m_timeStack[m_stackPos].m_time) + != 0) /* deliberately empty */ + ; +#endif + + const timespec null_ts = { 0, 0 }; + if (m_stackPos) { + auto parent = m_timeStack[m_stackPos - 1].m_path; + ProfilerSectionPath path(entry, &parent->first); + auto it = m_map.find(path); + if (it != m_map.end()) { + m_timeStack[m_stackPos].m_path = it; + } else { + m_map.insert(std::make_pair(path, null_ts)); + m_timeStack[m_stackPos].m_path = m_map.find(path); + } + } else { + ProfilerSectionPath path(entry, 0); + auto it = m_map.find(path); + if (it != m_map.end()) { + m_timeStack[m_stackPos].m_path = it; + } else { + m_map.insert(std::make_pair(path, null_ts)); + m_timeStack[m_stackPos].m_path = m_map.find(path); + } } - } - ++m_stackPos; + ++m_stackPos; } //---------------------------------------------------------------------------------------------------------------------- void Profiler::popTime() { - assert(m_stackPos > 0); - --m_stackPos; - timespec endtime{}; - #ifdef _WIN32 - while(clock_gettime(CLOCK_REALTIME_COARSE, &endtime) != 0) /* deliberately empty */; - #elif OSMac_ - // clock_gettime() is only present on OSX 10.12 and above. - clock_gettime(CLOCK_REALTIME, &endtime); - #else - timespec_get(&endtime, TIME_UTC); - #endif - - // compute time difference - timespec diff = timeDiff(m_timeStack[m_stackPos].m_time, endtime); - m_timeStack[m_stackPos].m_path->second = timeAdd(diff, m_timeStack[m_stackPos].m_path->second); + assert(m_stackPos > 0); + --m_stackPos; + timespec endtime {}; +#ifdef _WIN32 + while (clock_gettime(CLOCK_REALTIME_COARSE, &endtime) != 0) /* deliberately empty */ + ; +#elif OSMac_ + // clock_gettime() is only present on OSX 10.12 and above. + clock_gettime(CLOCK_REALTIME, &endtime); +#else + timespec_get(&endtime, TIME_UTC); +#endif + + // compute time difference + timespec diff = timeDiff(m_timeStack[m_stackPos].m_time, endtime); + m_timeStack[m_stackPos].m_path->second = timeAdd(diff, m_timeStack[m_stackPos].m_path->second); } //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/CodeTimings.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/CodeTimings.h index 4eddc1b7d5..aa0e9cb63f 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/CodeTimings.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/CodeTimings.h @@ -14,13 +14,12 @@ // limitations under the License. // #pragma once -#include -#include -#include -#include #include #include #include +#include +#include +#include namespace AL { namespace usdmaya { @@ -33,51 +32,55 @@ const uint32_t MAX_TIMESTAMP_STACK_SIZE = 16; //---------------------------------------------------------------------------------------------------------------------- /// \ingroup profilerprofiler -/// \brief This class provides a static hash that should be unique for a line within a specific function. +/// \brief This class provides a static hash that should be unique for a line within a specific +/// function. //---------------------------------------------------------------------------------------------------------------------- class ProfilerSectionTag { - friend class Profiler; -public: + friend class Profiler; - /// \brief ctor - /// \param sectionName a human readable name for the profiling section - /// \param filePath the file that contains this code section - /// \param lineNumber the line number in the file where this section starts - inline ProfilerSectionTag( - const std::string sectionName, - const std::string filePath, - const size_t lineNumber) - : m_sectionName(sectionName), m_filePath(filePath), m_lineNumber(lineNumber), - m_hash(((std::hash()(filePath) << 1) ^ (std::hash()(lineNumber) << 1)) ^ std::hash()(sectionName)) - {} +public: + /// \brief ctor + /// \param sectionName a human readable name for the profiling section + /// \param filePath the file that contains this code section + /// \param lineNumber the line number in the file where this section starts + inline ProfilerSectionTag( + const std::string sectionName, + const std::string filePath, + const size_t lineNumber) + : m_sectionName(sectionName) + , m_filePath(filePath) + , m_lineNumber(lineNumber) + , m_hash( + ((std::hash()(filePath) << 1) ^ (std::hash()(lineNumber) << 1)) + ^ std::hash()(sectionName)) + { + } - /// \brief equality operator - /// \param rhs right hand side to test for equality - /// \return true if equal, false otherwise - inline bool operator == (const ProfilerSectionTag& rhs) const + /// \brief equality operator + /// \param rhs right hand side to test for equality + /// \return true if equal, false otherwise + inline bool operator==(const ProfilerSectionTag& rhs) const { - return m_hash == rhs.m_hash && - m_sectionName == rhs.m_sectionName && - m_filePath == rhs.m_filePath && - m_lineNumber == rhs.m_lineNumber; + return m_hash == rhs.m_hash && m_sectionName == rhs.m_sectionName + && m_filePath == rhs.m_filePath && m_lineNumber == rhs.m_lineNumber; } - /// \brief return the hash of this class - /// \return the hash of this class - inline size_t hash() const - { return m_hash;} + /// \brief return the hash of this class + /// \return the hash of this class + inline size_t hash() const { return m_hash; } private: - const std::string m_sectionName; ///< the human readable identifier for this section - const std::string m_filePath; ///< the file that contains this code section - const size_t m_lineNumber; ///< the line number within the file - const size_t m_hash; ///< unique hash to identify this section + const std::string m_sectionName; ///< the human readable identifier for this section + const std::string m_filePath; ///< the file that contains this code section + const size_t m_lineNumber; ///< the line number within the file + const size_t m_hash; ///< unique hash to identify this section }; //---------------------------------------------------------------------------------------------------------------------- /// \ingroup profiler -/// \brief This class represents a path made up of AL::usdmaya::ProfilerSectionTag's. It is used so that we can distinguish between +/// \brief This class represents a path made up of AL::usdmaya::ProfilerSectionTag's. It is used so +/// that we can distinguish between /// identical code sections, accessed from alternative paths, e.g. /// \code /// void func1() { @@ -99,49 +102,53 @@ class ProfilerSectionTag //---------------------------------------------------------------------------------------------------------------------- class ProfilerSectionPath { - friend class Profiler; -public: + friend class Profiler; - /// \brief ctor - /// \param top the top node on the profiling stack - /// \param parent the parent path - inline ProfilerSectionPath(const AL::usdmaya::ProfilerSectionTag* const top, const ProfilerSectionPath* const parent = 0) - : m_top(top), m_parent(parent), m_hash(m_top->hash() ^ (m_parent ? m_parent->hash() : 0)) - {} +public: + /// \brief ctor + /// \param top the top node on the profiling stack + /// \param parent the parent path + inline ProfilerSectionPath( + const AL::usdmaya::ProfilerSectionTag* const top, + const ProfilerSectionPath* const parent = 0) + : m_top(top) + , m_parent(parent) + , m_hash(m_top->hash() ^ (m_parent ? m_parent->hash() : 0)) + { + } - /// \brief equality operator - /// \param rhs the right hand side of the comparison - /// \return true if the paths are the same - inline bool operator == (const ProfilerSectionPath& rhs) const - { return (m_hash == rhs.m_hash && m_top == rhs.m_top && m_parent == rhs.m_parent); } + /// \brief equality operator + /// \param rhs the right hand side of the comparison + /// \return true if the paths are the same + inline bool operator==(const ProfilerSectionPath& rhs) const + { + return (m_hash == rhs.m_hash && m_top == rhs.m_top && m_parent == rhs.m_parent); + } - /// \brief return the hash of this class - /// \return the hash of this class - inline size_t hash() const - { return m_hash;} + /// \brief return the hash of this class + /// \return the hash of this class + inline size_t hash() const { return m_hash; } private: - const ProfilerSectionTag* const m_top; - const ProfilerSectionPath* const m_parent; - const size_t m_hash; + const ProfilerSectionTag* const m_top; + const ProfilerSectionPath* const m_parent; + const size_t m_hash; }; -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- #ifndef AL_GENERATING_DOCS namespace std { -template<> struct hash { - inline size_t operator()(const AL::usdmaya::ProfilerSectionTag& k) const { - return k.hash(); - } +template <> struct hash +{ + inline size_t operator()(const AL::usdmaya::ProfilerSectionTag& k) const { return k.hash(); } }; -template<> struct hash { - inline size_t operator()(const AL::usdmaya::ProfilerSectionPath& k) const { - return k.hash(); - } +template <> struct hash +{ + inline size_t operator()(const AL::usdmaya::ProfilerSectionPath& k) const { return k.hash(); } }; -} // std +} // namespace std #endif //---------------------------------------------------------------------------------------------------------------------- @@ -149,9 +156,10 @@ namespace AL { namespace usdmaya { //---------------------------------------------------------------------------------------------------------------------- /// \ingroup profiler -/// \brief This class implements a very simple incode profiler. This profiler is NOT thread safe. It is mainly used to -/// get some basic stats on the where the bottlenecks are during a file import/export operation. A simple example -/// of usage: +/// \brief This class implements a very simple incode profiler. This profiler is NOT thread safe. +/// It is mainly used to +/// get some basic stats on the where the bottlenecks are during a file import/export +/// operation. A simple example of usage: /// \code /// void func1() { /// AL_BEGIN_PROFILE_SECTION(func1); @@ -184,90 +192,84 @@ namespace usdmaya { class Profiler { public: + /// \brief call to output the report + /// \param os the stream to write the report to + static void printReport(std::ostream& os); - /// \brief call to output the report - /// \param os the stream to write the report to - static void printReport(std::ostream& os); - - /// \brief call to clear internal timers - static inline void clearAll() + /// \brief call to clear internal timers + static inline void clearAll() { - assert(m_stackPos == 0); - m_map.clear(); + assert(m_stackPos == 0); + m_map.clear(); } - /// \brief do not call directly. Use the AL_BEGIN_PROFILE_SECTION macro - /// \param entry a unique tag for this code section. - static void pushTime(const ProfilerSectionTag* entry); + /// \brief do not call directly. Use the AL_BEGIN_PROFILE_SECTION macro + /// \param entry a unique tag for this code section. + static void pushTime(const ProfilerSectionTag* entry); - /// \brief do not call directly. Use the AL_END_PROFILE_SECTION macro - static void popTime(); + /// \brief do not call directly. Use the AL_END_PROFILE_SECTION macro + static void popTime(); private: + typedef std::unordered_map ProfilerSectionPathLUT; + typedef ProfilerSectionPathLUT::const_iterator iter_t; + static inline bool compareTimeStamps(const iter_t, const iter_t); + static void print(std::ostream& os, iter_t, const ProfilerSectionPathLUT&, uint32_t, double); - typedef std::unordered_map ProfilerSectionPathLUT; - typedef ProfilerSectionPathLUT::const_iterator iter_t; - static inline bool compareTimeStamps(const iter_t, const iter_t); - static void print(std::ostream& os, iter_t, const ProfilerSectionPathLUT&, uint32_t, double); - - struct ProfilerSectionStackNode - { - timespec m_time; - const ProfilerSectionTag* m_entry; - ProfilerSectionPathLUT::iterator m_path; - }; - - static inline timespec timeDiff(const timespec startTime, const timespec endTime) - { - timespec ts; - if (endTime.tv_nsec < startTime.tv_nsec) + struct ProfilerSectionStackNode { - ts.tv_sec = endTime.tv_sec - 1 - startTime.tv_sec; - ts.tv_nsec = 1000000000 + endTime.tv_nsec - startTime.tv_nsec; - } - else + timespec m_time; + const ProfilerSectionTag* m_entry; + ProfilerSectionPathLUT::iterator m_path; + }; + + static inline timespec timeDiff(const timespec startTime, const timespec endTime) { - ts.tv_sec = endTime.tv_sec - startTime.tv_sec; - ts.tv_nsec = endTime.tv_nsec - startTime.tv_nsec; + timespec ts; + if (endTime.tv_nsec < startTime.tv_nsec) { + ts.tv_sec = endTime.tv_sec - 1 - startTime.tv_sec; + ts.tv_nsec = 1000000000 + endTime.tv_nsec - startTime.tv_nsec; + } else { + ts.tv_sec = endTime.tv_sec - startTime.tv_sec; + ts.tv_nsec = endTime.tv_nsec - startTime.tv_nsec; + } + return ts; } - return ts; - } - static inline timespec timeAdd(timespec t1, timespec t2) - { - timespec ts; - int32_t sec = t2.tv_sec + t1.tv_sec; - int32_t nsec = t2.tv_nsec + t1.tv_nsec; - if (nsec >= 1000000000) + static inline timespec timeAdd(timespec t1, timespec t2) { - nsec -= 1000000000; - sec++; + timespec ts; + int32_t sec = t2.tv_sec + t1.tv_sec; + int32_t nsec = t2.tv_nsec + t1.tv_nsec; + if (nsec >= 1000000000) { + nsec -= 1000000000; + sec++; + } + ts.tv_sec = sec; + ts.tv_nsec = nsec; + return ts; } - ts.tv_sec = sec; - ts.tv_nsec = nsec; - return ts; - } - static ProfilerSectionStackNode m_timeStack[MAX_TIMESTAMP_STACK_SIZE]; - static uint32_t m_stackPos; - static ProfilerSectionPathLUT m_map; + static ProfilerSectionStackNode m_timeStack[MAX_TIMESTAMP_STACK_SIZE]; + static uint32_t m_stackPos; + static ProfilerSectionPathLUT m_map; }; //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- /// \ingroup profiler /// Put this macro at the start of a timed section of code -#define AL_BEGIN_PROFILE_SECTION(TimedSection) \ - { \ - static const AL::usdmaya::ProfilerSectionTag __entry(#TimedSection, __FILE__, __LINE__); \ - AL::usdmaya::Profiler::pushTime(&__entry); \ - } +#define AL_BEGIN_PROFILE_SECTION(TimedSection) \ + { \ + static const AL::usdmaya::ProfilerSectionTag __entry(#TimedSection, __FILE__, __LINE__); \ + AL::usdmaya::Profiler::pushTime(&__entry); \ + } /// \ingroup profiler /// Put this macro after a timed section of code. -#define AL_END_PROFILE_SECTION() \ - { AL::usdmaya::Profiler::popTime(); } - - +#define AL_END_PROFILE_SECTION() \ + { \ + AL::usdmaya::Profiler::popTime(); \ + } diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/DebugCodes.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/DebugCodes.cpp index bb8f0b6581..659697e789 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/DebugCodes.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/DebugCodes.cpp @@ -15,24 +15,24 @@ // #include "AL/usdmaya/DebugCodes.h" -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE TF_REGISTRY_FUNCTION(TfDebug) { - TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_TRANSLATORS, "UsdMaya translators"); - TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_EVENTS, "UsdMaya events"); - TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_EVALUATION, "UsdMaya evaluation"); - TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_COMMANDS, "UsdMaya commands"); - TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_LAYERS, "UsdMaya layers"); - TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_DRAW, "UsdMaya draw"); - TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_SELECTION, "UsdMaya selection"); - TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_GUIHELPER, "UsdMaya CommandGuiHelper"); - TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_RENDERER, "UsdMaya renderer"); - TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_GEOMETRY_DEFORMER, "UsdMaya geometry animation deformer"); - TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_TRANSFORM_MATRIX, "UsdMaya transform matrix"); + TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_TRANSLATORS, "UsdMaya translators"); + TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_EVENTS, "UsdMaya events"); + TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_EVALUATION, "UsdMaya evaluation"); + TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_COMMANDS, "UsdMaya commands"); + TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_LAYERS, "UsdMaya layers"); + TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_DRAW, "UsdMaya draw"); + TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_SELECTION, "UsdMaya selection"); + TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_GUIHELPER, "UsdMaya CommandGuiHelper"); + TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_RENDERER, "UsdMaya renderer"); + TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_GEOMETRY_DEFORMER, "UsdMaya geometry animation deformer"); + TF_DEBUG_ENVIRONMENT_SYMBOL(ALUSDMAYA_TRANSFORM_MATRIX, "UsdMaya transform matrix"); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/DebugCodes.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/DebugCodes.h index 73750cd792..f8d5c81c7a 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/DebugCodes.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/DebugCodes.h @@ -15,8 +15,8 @@ // #pragma once -#include #include +#include PXR_NAMESPACE_OPEN_SCOPE @@ -43,6 +43,5 @@ namespace maya { using PXR_NS::TfDebug; -} // maya -} // AL - +} // namespace maya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/ForwardDeclares.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/ForwardDeclares.h index 2c18a41e8c..1cd2085478 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/ForwardDeclares.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/ForwardDeclares.h @@ -14,9 +14,10 @@ // limitations under the License. // #pragma once -#include #include "AL/usdmaya/utils/ForwardDeclares.h" +#include + // forward declare usd types namespace AL { @@ -45,7 +46,7 @@ class ProxyShapePostLoadProcess; class ProxyShapePrintRefCountState; class ProxyShapeRemoveAllTransforms; class TransformationMatrixToggleTimeSource; -} // cmds +} // namespace cmds namespace fileio { class AnimationTranslator; @@ -61,11 +62,11 @@ struct NativeTranslatorRegistry; struct NodeFactory; class TransformIterator; namespace translators { - class DagNodeTranslator; - class DgNodeTranslator; - class TransformTranslator; -} // translators -} // fileio +class DagNodeTranslator; +class DgNodeTranslator; +class TransformTranslator; +} // namespace translators +} // namespace fileio namespace nodes { class Layer; @@ -77,7 +78,7 @@ class Transform; class Scope; class TransformationMatrix; class BasicTransformationMatrix; -} // nodes +} // namespace nodes -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Global.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Global.cpp index 968ee363d2..91ead3acc5 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Global.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Global.cpp @@ -14,12 +14,13 @@ // limitations under the License. // #include "AL/usdmaya/Global.h" + #include "AL/usdmaya/DebugCodes.h" #include "AL/usdmaya/StageCache.h" #include "AL/usdmaya/nodes/LayerManager.h" #include "AL/usdmaya/nodes/ProxyShape.h" -#include "AL/usdmaya/nodes/Transform.h" #include "AL/usdmaya/nodes/Scope.h" +#include "AL/usdmaya/nodes/Transform.h" #include "AL/usdmaya/nodes/TransformationMatrix.h" #include @@ -30,8 +31,8 @@ #if defined(WANT_UFE_BUILD) #include "AL/usdmaya/TypeIDs.h" #include "ufe/globalSelection.h" -#include "ufe/observer.h" #include "ufe/observableSelection.h" +#include "ufe/observer.h" #include "ufe/path.h" #include "ufe/sceneItemList.h" #include "ufe/selectionNotification.h" @@ -45,163 +46,143 @@ #include #ifndef AL_USDMAYA_LOCATION_NAME - #define AL_USDMAYA_LOCATION_NAME "AL_USDMAYA_LOCATION" +#define AL_USDMAYA_LOCATION_NAME "AL_USDMAYA_LOCATION" #endif namespace { - // Keep track of how many levels "deep" in file reads we are - because - // a file open can can trigger a reference load, which can trigger a - // a sub-reference load, etc... we only want to run postFileRead after - // once per top-level file read operation (ie, once per open, or once - // per import, or once per reference). - std::atomic readDepth; +// Keep track of how many levels "deep" in file reads we are - because +// a file open can can trigger a reference load, which can trigger a +// a sub-reference load, etc... we only want to run postFileRead after +// once per top-level file read operation (ie, once per open, or once +// per import, or once per reference). +std::atomic readDepth; #if defined(WANT_UFE_BUILD) - // The proxy shape has an internal cache which needs to update when any of - // its UFE scene items are selected and transformed. - class UfeTransformObserver : public Ufe::Observer - { - public: - UfeTransformObserver() : Ufe::Observer() +// The proxy shape has an internal cache which needs to update when any of +// its UFE scene items are selected and transformed. +class UfeTransformObserver : public Ufe::Observer +{ +public: + UfeTransformObserver() + : Ufe::Observer() { } - ~UfeTransformObserver() override - { - } + ~UfeTransformObserver() override { } void operator()(const Ufe::Notification& notification) override { - auto xformChanged = dynamic_cast(¬ification); - if (xformChanged == nullptr) return; - - // Action for USD scene items only. - Ufe::SceneItem::Ptr sceneItem = xformChanged->item(); - if (!sceneItem || (sceneItem->runTimeId() != AL::usdmaya::USD_UFE_RUNTIME_ID)) return; - - std::string mayaPath = sceneItem->path().popSegment().popHead().string(); - - MSelectionList sl; - sl.add(MString(mayaPath.c_str(), mayaPath.length())); - - MObject object; - MStatus status = sl.getDependNode(0, object); - if (!status) return; - - MFnDependencyNode dependNode(object, &status); - if (!status) return; - - if (dependNode.typeId() == AL::usdmaya::nodes::ProxyShape::kTypeId) - { - auto proxyShape = - static_cast(dependNode.userNode()); - if (proxyShape) - { - proxyShape->clearBoundingBoxCache(); + auto xformChanged = dynamic_cast(¬ification); + if (xformChanged == nullptr) + return; + + // Action for USD scene items only. + Ufe::SceneItem::Ptr sceneItem = xformChanged->item(); + if (!sceneItem || (sceneItem->runTimeId() != AL::usdmaya::USD_UFE_RUNTIME_ID)) + return; + + std::string mayaPath = sceneItem->path().popSegment().popHead().string(); + + MSelectionList sl; + sl.add(MString(mayaPath.c_str(), mayaPath.length())); + + MObject object; + MStatus status = sl.getDependNode(0, object); + if (!status) + return; + + MFnDependencyNode dependNode(object, &status); + if (!status) + return; + + if (dependNode.typeId() == AL::usdmaya::nodes::ProxyShape::kTypeId) { + auto proxyShape = static_cast(dependNode.userNode()); + if (proxyShape) { + proxyShape->clearBoundingBoxCache(); + } } - } } - }; +}; #endif -} +} // namespace namespace AL { namespace usdmaya { - //---------------------------------------------------------------------------------------------------------------------- #if defined(WANT_UFE_BUILD) - // Observe UFE scene items for transformation changed only when they are selected. - class Global::UfeSelectionObserver : public Ufe::Observer - { - public: +// Observe UFE scene items for transformation changed only when they are selected. +class Global::UfeSelectionObserver : public Ufe::Observer +{ +public: UfeSelectionObserver() - : Ufe::Observer() - , m_ufeTransformObserver(std::make_shared()) - , m_openingFile(false) + : Ufe::Observer() + , m_ufeTransformObserver(std::make_shared()) + , m_openingFile(false) { } - ~UfeSelectionObserver() override - { - clear(); - } + ~UfeSelectionObserver() override { clear(); } void clear() { - for (auto si : m_observedSceneItems) - { - Ufe::Transform3d::removeObserver(si, m_ufeTransformObserver); - } + for (auto si : m_observedSceneItems) { + Ufe::Transform3d::removeObserver(si, m_ufeTransformObserver); + } - m_observedSceneItems.clear(); + m_observedSceneItems.clear(); } void observe(const Ufe::SceneItem::Ptr& si) { - if (si && - (si->runTimeId() == USD_UFE_RUNTIME_ID) && - Ufe::Transform3d::addObserver(si, m_ufeTransformObserver)) - { - m_observedSceneItems.push_back(si); - } + if (si && (si->runTimeId() == USD_UFE_RUNTIME_ID) + && Ufe::Transform3d::addObserver(si, m_ufeTransformObserver)) { + m_observedSceneItems.push_back(si); + } } - void openingFile(bool val) - { - m_openingFile = val; - } + void openingFile(bool val) { m_openingFile = val; } void operator()(const Ufe::Notification& notification) override { - // During Maya file read, each node will be selected in turn, so we get - // notified for each node in the scene. Prune this out. - if (m_openingFile) - { - return; - } + // During Maya file read, each node will be selected in turn, so we get + // notified for each node in the scene. Prune this out. + if (m_openingFile) { + return; + } - auto selectionChanged = dynamic_cast(¬ification); - if (selectionChanged == nullptr) - { - return; - } - - if (dynamic_cast(selectionChanged)) - { - clear(); - } - else if (dynamic_cast(selectionChanged) || - dynamic_cast(selectionChanged)) - { - clear(); - - const Ufe::GlobalSelection::Ptr& ufeSelection = Ufe::GlobalSelection::get(); - if (ufeSelection) - { - for (auto it = ufeSelection->cbegin(); it != ufeSelection->cend(); it++) - { - observe(*it); - } + auto selectionChanged = dynamic_cast(¬ification); + if (selectionChanged == nullptr) { + return; } - } - else if (auto appended = dynamic_cast(selectionChanged)) - { - observe(appended->item()); - } - else if (auto removed = dynamic_cast(selectionChanged)) - { - Ufe::SceneItem::Ptr si = removed->item(); - if (si && - (si->runTimeId() == USD_UFE_RUNTIME_ID) && - Ufe::Transform3d::removeObserver(si, m_ufeTransformObserver)) - { - m_observedSceneItems.remove(si); + + if (dynamic_cast(selectionChanged)) { + clear(); + } else if ( + dynamic_cast(selectionChanged) + || dynamic_cast(selectionChanged)) { + clear(); + + const Ufe::GlobalSelection::Ptr& ufeSelection = Ufe::GlobalSelection::get(); + if (ufeSelection) { + for (auto it = ufeSelection->cbegin(); it != ufeSelection->cend(); it++) { + observe(*it); + } + } + } else if ( + auto appended = dynamic_cast(selectionChanged)) { + observe(appended->item()); + } else if ( + auto removed = dynamic_cast(selectionChanged)) { + Ufe::SceneItem::Ptr si = removed->item(); + if (si && (si->runTimeId() == USD_UFE_RUNTIME_ID) + && Ufe::Transform3d::removeObserver(si, m_ufeTransformObserver)) { + m_observedSceneItems.remove(si); + } } - } } - private: +private: // Scene items being observed for transformation matrix change. Ufe::SceneItemList m_observedSceneItems; @@ -209,9 +190,9 @@ namespace usdmaya { std::shared_ptr m_ufeTransformObserver; bool m_openingFile; - }; +}; - std::shared_ptr Global::m_ufeSelectionObserver; +std::shared_ptr Global::m_ufeSelectionObserver; #endif //---------------------------------------------------------------------------------------------------------------------- @@ -225,322 +206,307 @@ AL::event::CallbackId Global::m_postExport; //---------------------------------------------------------------------------------------------------------------------- -//class of MObjects +// class of MObjects static MSelectionList g_selected; -//Store the current selection list, but dont store AL_USD proxies +// Store the current selection list, but dont store AL_USD proxies static void storeSelection() { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("storeSelection\n"); - MGlobal::getActiveSelectionList(g_selected); - - // some utils that test for AL types, but which only initialise function sets when it's possible - // that the type may be a plugin shape or transform. Avoids a tonne of function set initialisations - // and string compares on the types. - auto isProxyShape = [] (MDagPath p) { - if(p.node().hasFn(MFn::kPluginShape)) { - return MFnDagNode(p).typeName() == "AL_usdmaya_ProxyShape"; - } - return false; - }; - auto isTransform = [] (MDagPath p) { - if(p.node().hasFn(MFn::kPluginTransformNode)) { - MTypeId nodeId = MFnDagNode(p).typeId(); - return nodeId == AL::usdmaya::nodes::Transform::kTypeId || nodeId == AL::usdmaya::nodes::Scope::kTypeId; - } - return false; - }; - - for(unsigned int i = 0; i < g_selected.length(); /* empty */ ) - { - // grab item as a dag path (skip over materials/textures/etc) - MDagPath selectedPath; - if(!g_selected.getDagPath(i, selectedPath)) - { - ++i; - continue; - } + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("storeSelection\n"); + MGlobal::getActiveSelectionList(g_selected); + + // some utils that test for AL types, but which only initialise function sets when it's possible + // that the type may be a plugin shape or transform. Avoids a tonne of function set + // initialisations and string compares on the types. + auto isProxyShape = [](MDagPath p) { + if (p.node().hasFn(MFn::kPluginShape)) { + return MFnDagNode(p).typeName() == "AL_usdmaya_ProxyShape"; + } + return false; + }; + auto isTransform = [](MDagPath p) { + if (p.node().hasFn(MFn::kPluginTransformNode)) { + MTypeId nodeId = MFnDagNode(p).typeId(); + return nodeId == AL::usdmaya::nodes::Transform::kTypeId + || nodeId == AL::usdmaya::nodes::Scope::kTypeId; + } + return false; + }; + + for (unsigned int i = 0; i < g_selected.length(); /* empty */) { + // grab item as a dag path (skip over materials/textures/etc) + MDagPath selectedPath; + if (!g_selected.getDagPath(i, selectedPath)) { + ++i; + continue; + } - // test for any selected proxy shapes or transform nodes - if(isProxyShape(selectedPath) || isTransform(selectedPath)) - { - // remove node from selection list - g_selected.remove(i); - continue; - } + // test for any selected proxy shapes or transform nodes + if (isProxyShape(selectedPath) || isTransform(selectedPath)) { + // remove node from selection list + g_selected.remove(i); + continue; + } - // test for any parents of proxy shapes selected (don't iterate over all children, just the shape nodes below) - uint32_t num = 0, j; - selectedPath.numberOfShapesDirectlyBelow(num); - for(j = 0; j < num; ++j) - { - MDagPath child = selectedPath; - child.extendToShapeDirectlyBelow(j); //< only care about shape nodes (rather than ALL children!) - if(isProxyShape(child)) - { - g_selected.remove(i); - break; - } - } + // test for any parents of proxy shapes selected (don't iterate over all children, just the + // shape nodes below) + uint32_t num = 0, j; + selectedPath.numberOfShapesDirectlyBelow(num); + for (j = 0; j < num; ++j) { + MDagPath child = selectedPath; + child.extendToShapeDirectlyBelow( + j); //< only care about shape nodes (rather than ALL children!) + if (isProxyShape(child)) { + g_selected.remove(i); + break; + } + } - // if none found, increment count - if(j == num) - { - ++i; + // if none found, increment count + if (j == num) { + ++i; + } } - } - } -//Reselect the selection stored in storeSelection() +// Reselect the selection stored in storeSelection() static void restoreSelection() { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("restoreSelection\n"); - MGlobal::setActiveSelectionList(g_selected); + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("restoreSelection\n"); + MGlobal::setActiveSelectionList(g_selected); } //---------------------------------------------------------------------------------------------------------------------- static void onFileNew(void*) { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("onFileNew\n"); - // These should both clear the caches, however they don't actually do anything of the sort. Puzzled. - UsdUtilsStageCache::Get().Clear(); - StageCache::Clear(); + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("onFileNew\n"); + // These should both clear the caches, however they don't actually do anything of the sort. + // Puzzled. + UsdUtilsStageCache::Get().Clear(); + StageCache::Clear(); } //---------------------------------------------------------------------------------------------------------------------- static void preFileRead(void*) { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("preFileRead\n"); + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("preFileRead\n"); - if(!readDepth) - { - Global::openingFile(true); - } - ++readDepth; + if (!readDepth) { + Global::openingFile(true); + } + ++readDepth; } //---------------------------------------------------------------------------------------------------------------------- static void postFileRead(void*) { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("postFileRead\n"); - - // If the plugin is loaded as the result of a "requires" statment when opening a scene, - // it's possible for postFileRead to be called without preFileRead having been... so, - // make sure we don't decrement past 0! - size_t oldReadDepth = readDepth.fetch_sub(1); - if (ARCH_UNLIKELY(oldReadDepth == 0)) - { - // Assume we got here because we didn't call preFileRead - do the increment that it - // missed - readDepth++; - oldReadDepth++; - } - - // oldReadDepth is the value BEFORE we decremented (with fetch_sub), so should be 1 - // if we're now "done" - if (oldReadDepth != 1) - { - return; - } - - nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); - if (layerManager) - { - layerManager->loadAllLayers(); - AL_MAYA_CHECK_ERROR2(layerManager->clearSerialisationAttributes(), "postFileRead"); - } - - MFnDependencyNode fn; - { - std::vector& unloadedProxies = nodes::ProxyShape::GetUnloadedProxyShapes(); - unsigned int numUnloadedProxies = unloadedProxies.size(); - for(unsigned int i = 0; i < numUnloadedProxies; ++i) + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("postFileRead\n"); + + // If the plugin is loaded as the result of a "requires" statment when opening a scene, + // it's possible for postFileRead to be called without preFileRead having been... so, + // make sure we don't decrement past 0! + size_t oldReadDepth = readDepth.fetch_sub(1); + if (ARCH_UNLIKELY(oldReadDepth == 0)) { + // Assume we got here because we didn't call preFileRead - do the increment that it + // missed + readDepth++; + oldReadDepth++; + } + + // oldReadDepth is the value BEFORE we decremented (with fetch_sub), so should be 1 + // if we're now "done" + if (oldReadDepth != 1) { + return; + } + + nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); + if (layerManager) { + layerManager->loadAllLayers(); + AL_MAYA_CHECK_ERROR2(layerManager->clearSerialisationAttributes(), "postFileRead"); + } + + MFnDependencyNode fn; { - if(!(unloadedProxies[i].isValid() && unloadedProxies[i].isAlive())) - { - continue; - } - fn.setObject(unloadedProxies[i].object()); - if(fn.typeId() != nodes::ProxyShape::kTypeId) - { - TF_CODING_ERROR("ProxyShape::m_unloadedProxyShapes had a non-Proxy-Shape mobject"); - continue; - } - - // execute a pull on each proxy shape to ensure that each one has a valid USD stage! - nodes::ProxyShape* proxy = (nodes::ProxyShape*)fn.userNode(); - proxy->loadStage(); - auto stage = proxy->getUsdStage(); - proxy->deserialiseTranslatorContext(); - proxy->translatorManufacture().preparePythonTranslators(proxy->context()); - proxy->findPrimsWithMetaData(); - proxy->deserialiseTransformRefs(); + std::vector& unloadedProxies = nodes::ProxyShape::GetUnloadedProxyShapes(); + unsigned int numUnloadedProxies = unloadedProxies.size(); + for (unsigned int i = 0; i < numUnloadedProxies; ++i) { + if (!(unloadedProxies[i].isValid() && unloadedProxies[i].isAlive())) { + continue; + } + fn.setObject(unloadedProxies[i].object()); + if (fn.typeId() != nodes::ProxyShape::kTypeId) { + TF_CODING_ERROR("ProxyShape::m_unloadedProxyShapes had a non-Proxy-Shape mobject"); + continue; + } + + // execute a pull on each proxy shape to ensure that each one has a valid USD stage! + nodes::ProxyShape* proxy = (nodes::ProxyShape*)fn.userNode(); + proxy->loadStage(); + auto stage = proxy->getUsdStage(); + proxy->deserialiseTranslatorContext(); + proxy->translatorManufacture().preparePythonTranslators(proxy->context()); + proxy->findPrimsWithMetaData(); + proxy->deserialiseTransformRefs(); + } + unloadedProxies.clear(); } - unloadedProxies.clear(); - } - { - MItDependencyNodes iter(MFn::kPluginTransformNode); - for(; !iter.isDone(); iter.next()) { - fn.setObject(iter.item()); - if(fn.typeId() == nodes::Transform::kTypeId || fn.typeId() == nodes::Scope::kTypeId) - { - // ensure all of the transforms are referring to the correct prim - nodes::Scope* tmPtr = (nodes::Scope*)fn.userNode(); - tmPtr->transform()->initialiseToPrim(true, tmPtr); - } + MItDependencyNodes iter(MFn::kPluginTransformNode); + for (; !iter.isDone(); iter.next()) { + fn.setObject(iter.item()); + if (fn.typeId() == nodes::Transform::kTypeId || fn.typeId() == nodes::Scope::kTypeId) { + // ensure all of the transforms are referring to the correct prim + nodes::Scope* tmPtr = (nodes::Scope*)fn.userNode(); + tmPtr->transform()->initialiseToPrim(true, tmPtr); + } + } } - } - Global::openingFile(false); + Global::openingFile(false); } //---------------------------------------------------------------------------------------------------------------------- static void _preFileSave() { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("preFileSave\n"); + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("preFileSave\n"); - // currently, if we have selected a shape in the usd proxy shape, a series of transforms will have been created. - // Ideally we don't want these transient nodes to be stored in the Maya file, so make sure we unselect prior to a file - // save (which should call another set of callbacks and delete those transient nodes. This should leave us with just - // those AL::usdmaya::nodes::Transform nodes that are created because they are required, or have been requested). + // currently, if we have selected a shape in the usd proxy shape, a series of transforms will + // have been created. Ideally we don't want these transient nodes to be stored in the Maya file, + // so make sure we unselect prior to a file save (which should call another set of callbacks and + // delete those transient nodes. This should leave us with just those + // AL::usdmaya::nodes::Transform nodes that are created because they are required, or have been + // requested). - // Selection will be restored to the selection prior to the clearing in the post save. + // Selection will be restored to the selection prior to the clearing in the post save. - storeSelection(); + storeSelection(); - MGlobal::clearSelectionList(); + MGlobal::clearSelectionList(); - nodes::ProxyShape::serializeAll(); + nodes::ProxyShape::serializeAll(); } //---------------------------------------------------------------------------------------------------------------------- static void preFileSave(void*) { - // This is a file-save callback, so we want to be EXTRA careful not to crash out, and - // lose their work right when they need it most! - // ...except if we're in a debug build, in which case just crash the mofo, so we - // notice! + // This is a file-save callback, so we want to be EXTRA careful not to crash out, and + // lose their work right when they need it most! + // ...except if we're in a debug build, in which case just crash the mofo, so we + // notice! #ifndef DEBUG - try - { + try { #endif - _preFileSave(); + _preFileSave(); #ifndef DEBUG - } - catch (const std::exception& e) - { - MString msg("Caught unhandled exception inside of al_usdmaya save callback: "); - msg += e.what(); - MGlobal::displayError(msg); - std::cerr << msg.asChar(); - TfPrintStackTrace(std::cerr, "Unhandled error in al_usdmaya save callback:"); - } - catch (...) - { - MGlobal::displayError("Caught unknown exception inside of al_usdmaya save callback"); - TfPrintStackTrace(std::cerr, "Unknown error in al_usdmaya save callback:"); - } + } catch (const std::exception& e) { + MString msg("Caught unhandled exception inside of al_usdmaya save callback: "); + msg += e.what(); + MGlobal::displayError(msg); + std::cerr << msg.asChar(); + TfPrintStackTrace(std::cerr, "Unhandled error in al_usdmaya save callback:"); + } catch (...) { + MGlobal::displayError("Caught unknown exception inside of al_usdmaya save callback"); + TfPrintStackTrace(std::cerr, "Unknown error in al_usdmaya save callback:"); + } #endif } //---------------------------------------------------------------------------------------------------------------------- static void postFileSave(void*) { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("postFileSave\n"); - - nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); - if (layerManager) - { - AL_MAYA_CHECK_ERROR2(layerManager->clearSerialisationAttributes(), "postFileSave"); - } - // Restore selection cleared by _preFileSave() - restoreSelection(); + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("postFileSave\n"); + + nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); + if (layerManager) { + AL_MAYA_CHECK_ERROR2(layerManager->clearSerialisationAttributes(), "postFileSave"); + } + // Restore selection cleared by _preFileSave() + restoreSelection(); } //---------------------------------------------------------------------------------------------------------------------- static void preFileExport(void* p) { - storeSelection(); - nodes::ProxyShape::serializeAll(); + storeSelection(); + nodes::ProxyShape::serializeAll(); } //---------------------------------------------------------------------------------------------------------------------- -static void postFileExport(void* p) -{ - postFileSave(p); -} +static void postFileExport(void* p) { postFileSave(p); } //---------------------------------------------------------------------------------------------------------------------- void Global::onPluginLoad() { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("Registering callbacks\n"); - - auto& manager = AL::maya::event::MayaEventManager::instance(); - m_fileNew = manager.registerCallback(onFileNew, "AfterNew", "usdmaya_onFileNew", 0x1000); - m_preSave = manager.registerCallback(preFileSave, "BeforeSave", "usdmaya_preFileSave", 0x1000); - m_postSave = manager.registerCallback(postFileSave, "AfterSave", "usdmaya_postFileSave", 0x1000); - m_preRead = manager.registerCallback(preFileRead, "BeforeFileRead", "usdmaya_preFileRead", 0x1000); - m_postRead = manager.registerCallback(postFileRead, "AfterFileRead", "usdmaya_postFileRead", 0x1000); - m_preExport = manager.registerCallback(preFileExport, "BeforeExport", "usdmaya_preFileExport", 0x1000); - m_postExport = manager.registerCallback(postFileExport, "AfterExport", "usdmaya_postFileExport", 0x1000); - - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("Registering USD plugins\n"); - // Let USD know about the additional plugins - std::string pluginLocation(TfStringCatPaths(TfGetenv(AL_USDMAYA_LOCATION_NAME), "share/usd/plugins")); - PlugRegistry::GetInstance().RegisterPlugins(pluginLocation); + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("Registering callbacks\n"); + + auto& manager = AL::maya::event::MayaEventManager::instance(); + m_fileNew = manager.registerCallback(onFileNew, "AfterNew", "usdmaya_onFileNew", 0x1000); + m_preSave = manager.registerCallback(preFileSave, "BeforeSave", "usdmaya_preFileSave", 0x1000); + m_postSave + = manager.registerCallback(postFileSave, "AfterSave", "usdmaya_postFileSave", 0x1000); + m_preRead + = manager.registerCallback(preFileRead, "BeforeFileRead", "usdmaya_preFileRead", 0x1000); + m_postRead + = manager.registerCallback(postFileRead, "AfterFileRead", "usdmaya_postFileRead", 0x1000); + m_preExport + = manager.registerCallback(preFileExport, "BeforeExport", "usdmaya_preFileExport", 0x1000); + m_postExport + = manager.registerCallback(postFileExport, "AfterExport", "usdmaya_postFileExport", 0x1000); + + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("Registering USD plugins\n"); + // Let USD know about the additional plugins + std::string pluginLocation( + TfStringCatPaths(TfGetenv(AL_USDMAYA_LOCATION_NAME), "share/usd/plugins")); + PlugRegistry::GetInstance().RegisterPlugins(pluginLocation); #if defined(WANT_UFE_BUILD) - const Ufe::GlobalSelection::Ptr& ufeSelection = Ufe::GlobalSelection::get(); - if (ufeSelection) - { - m_ufeSelectionObserver = std::make_shared(); - ufeSelection->addObserver(m_ufeSelectionObserver); - } + const Ufe::GlobalSelection::Ptr& ufeSelection = Ufe::GlobalSelection::get(); + if (ufeSelection) { + m_ufeSelectionObserver = std::make_shared(); + ufeSelection->addObserver(m_ufeSelectionObserver); + } #endif - // For callback initialization for stage cache callback, it will be done via proxy node attribute change. + // For callback initialization for stage cache callback, it will be done via proxy node + // attribute change. } //---------------------------------------------------------------------------------------------------------------------- void Global::onPluginUnload() { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("Removing callbacks\n"); - auto& manager = AL::maya::event::MayaEventManager::instance(); - manager.unregisterCallback(m_fileNew); - manager.unregisterCallback(m_preSave); - manager.unregisterCallback(m_postSave); - manager.unregisterCallback(m_preRead); - manager.unregisterCallback(m_postRead); - manager.unregisterCallback(m_preExport); - manager.unregisterCallback(m_postExport); - StageCache::removeCallbacks(); - - AL::maya::event::MayaEventManager::freeInstance(); - AL::event::EventScheduler::freeScheduler(); + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("Removing callbacks\n"); + auto& manager = AL::maya::event::MayaEventManager::instance(); + manager.unregisterCallback(m_fileNew); + manager.unregisterCallback(m_preSave); + manager.unregisterCallback(m_postSave); + manager.unregisterCallback(m_preRead); + manager.unregisterCallback(m_postRead); + manager.unregisterCallback(m_preExport); + manager.unregisterCallback(m_postExport); + StageCache::removeCallbacks(); + + AL::maya::event::MayaEventManager::freeInstance(); + AL::event::EventScheduler::freeScheduler(); #if defined(WANT_UFE_BUILD) - const Ufe::GlobalSelection::Ptr& ufeSelection = Ufe::GlobalSelection::get(); - if (ufeSelection) - { - ufeSelection->removeObserver(m_ufeSelectionObserver); - m_ufeSelectionObserver = nullptr; - } + const Ufe::GlobalSelection::Ptr& ufeSelection = Ufe::GlobalSelection::get(); + if (ufeSelection) { + ufeSelection->removeObserver(m_ufeSelectionObserver); + m_ufeSelectionObserver = nullptr; + } #endif } void Global::openingFile(bool val) { #if defined(WANT_UFE_BUILD) - if (m_ufeSelectionObserver) - { - m_ufeSelectionObserver->openingFile(val); - } + if (m_ufeSelectionObserver) { + m_ufeSelectionObserver->openingFile(val); + } #endif } //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // al +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Global.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Global.h index 01d4afe26a..595846b76f 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Global.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Global.h @@ -15,8 +15,8 @@ // #pragma once -#include "AL/usdmaya/Api.h" #include "AL/event/EventHandler.h" +#include "AL/usdmaya/Api.h" #include @@ -31,54 +31,51 @@ namespace usdmaya { class Global { public: + /// \brief initialise the global state + AL_USDMAYA_PUBLIC + static void onPluginLoad(); - /// \brief initialise the global state - AL_USDMAYA_PUBLIC - static void onPluginLoad(); + /// \brief uninitialise the global state + AL_USDMAYA_PUBLIC + static void onPluginUnload(); - /// \brief uninitialise the global state - AL_USDMAYA_PUBLIC - static void onPluginUnload(); + /// pre save callback + static AL::event::CallbackId preSave() { return m_preSave; } - /// pre save callback - static AL::event::CallbackId preSave() - { return m_preSave; } + /// post save callback + static AL::event::CallbackId postSave() { return m_postSave; } - /// post save callback - static AL::event::CallbackId postSave() - { return m_postSave; } + /// pre open callback + static AL::event::CallbackId preRead() { return m_preRead; } - /// pre open callback - static AL::event::CallbackId preRead() - { return m_preRead; } + /// post open callback + static AL::event::CallbackId postRead() { return m_postRead; } - /// post open callback - static AL::event::CallbackId postRead() - { return m_postRead; } + /// callback used to flush the USD caches after a file new + static AL::event::CallbackId fileNew() { return m_fileNew; } - /// callback used to flush the USD caches after a file new - static AL::event::CallbackId fileNew() - { return m_fileNew; } - - static void openingFile(bool val); + static void openingFile(bool val); private: - static AL::event::CallbackId m_preSave; ///< callback prior to saving the scene (so we can store the session layer) - static AL::event::CallbackId m_postSave; ///< callback after saving - static AL::event::CallbackId m_preRead; ///< callback executed before opening a maya file - static AL::event::CallbackId m_postRead; ///< callback executed after opening a maya file - needed to re-hook up the UsdPrims - static AL::event::CallbackId m_fileNew; ///< callback used to flush the USD caches after a file new - static AL::event::CallbackId m_preExport; ///< callback prior to exporting the scene (so we can store the session layer) - static AL::event::CallbackId m_postExport; ///< callback after exporting + static AL::event::CallbackId + m_preSave; ///< callback prior to saving the scene (so we can store the session layer) + static AL::event::CallbackId m_postSave; ///< callback after saving + static AL::event::CallbackId m_preRead; ///< callback executed before opening a maya file + static AL::event::CallbackId m_postRead; ///< callback executed after opening a maya file - + ///< needed to re-hook up the UsdPrims + static AL::event::CallbackId + m_fileNew; ///< callback used to flush the USD caches after a file new + static AL::event::CallbackId + m_preExport; ///< callback prior to exporting the scene (so we can store the session layer) + static AL::event::CallbackId m_postExport; ///< callback after exporting #if defined(WANT_UFE_BUILD) - class UfeSelectionObserver; - static std::shared_ptr m_ufeSelectionObserver; + class UfeSelectionObserver; + static std::shared_ptr m_ufeSelectionObserver; #endif }; //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // al +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Metadata.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Metadata.cpp index a329a9a104..e3a93fe7a5 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Metadata.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Metadata.cpp @@ -36,6 +36,6 @@ const TfToken Metadata::lockUnlocked("unlocked"); const TfToken Metadata::assetType("assettype"); //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Metadata.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Metadata.h index c8acfb7a39..1bef8d339f 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Metadata.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Metadata.h @@ -31,58 +31,62 @@ namespace usdmaya { /// \brief The MetaData tokens we attach to various prims struct Metadata { - /// MetaData token that allows the overriding of the transform type from the default AL_usdmaya_Transform on import. - AL_USDMAYA_PUBLIC - static const TfToken transformType; - - /// MetaData token that can be applied to a prim which will add it to the UsdImaging ignore list (so that it will not - /// be rendered in Hydra). - AL_USDMAYA_PUBLIC - static const TfToken excludeFromProxyShape; - - /// MetaData token that controls whether a prim will be imported as Maya geometry - AL_USDMAYA_PUBLIC - static const TfToken importAsNative; - - /// Name of the property that determines if the prim is selectable or not - AL_USDMAYA_PUBLIC - static const TfToken selectability; - - /// Value used in the selectibility property that tags the prim as selectable - AL_USDMAYA_PUBLIC - static const TfToken selectable; - - /// Value used in the selectibility property that tags the prim as unselectable - AL_USDMAYA_PUBLIC - static const TfToken unselectable; - - AL_USDMAYA_PUBLIC - static const TfToken mergedTransform; - AL_USDMAYA_PUBLIC - static const TfToken unmerged; - - /// Name of the property that determines if attributes on corresponding Maya object of the prim are locked or not. - AL_USDMAYA_PUBLIC - static const TfToken locked; - - /// Value used in the lock property that tags transform (including children) attributes are locked - AL_USDMAYA_PUBLIC - static const TfToken lockTransform; - - /// Value used in the lock property that tags prim inherits its parent state - AL_USDMAYA_PUBLIC - static const TfToken lockInherited; - - /// Value used in the lock property that tags prim unlocked regardless of its parent state - AL_USDMAYA_PUBLIC - static const TfToken lockUnlocked; - - /// This represents the medata key that plugins can be registered against as an alternative to typed schemas - AL_USDMAYA_PUBLIC - static const TfToken assetType; + /// MetaData token that allows the overriding of the transform type from the default + /// AL_usdmaya_Transform on import. + AL_USDMAYA_PUBLIC + static const TfToken transformType; + + /// MetaData token that can be applied to a prim which will add it to the UsdImaging ignore list + /// (so that it will not be rendered in Hydra). + AL_USDMAYA_PUBLIC + static const TfToken excludeFromProxyShape; + + /// MetaData token that controls whether a prim will be imported as Maya geometry + AL_USDMAYA_PUBLIC + static const TfToken importAsNative; + + /// Name of the property that determines if the prim is selectable or not + AL_USDMAYA_PUBLIC + static const TfToken selectability; + + /// Value used in the selectibility property that tags the prim as selectable + AL_USDMAYA_PUBLIC + static const TfToken selectable; + + /// Value used in the selectibility property that tags the prim as unselectable + AL_USDMAYA_PUBLIC + static const TfToken unselectable; + + AL_USDMAYA_PUBLIC + static const TfToken mergedTransform; + AL_USDMAYA_PUBLIC + static const TfToken unmerged; + + /// Name of the property that determines if attributes on corresponding Maya object of the prim + /// are locked or not. + AL_USDMAYA_PUBLIC + static const TfToken locked; + + /// Value used in the lock property that tags transform (including children) attributes are + /// locked + AL_USDMAYA_PUBLIC + static const TfToken lockTransform; + + /// Value used in the lock property that tags prim inherits its parent state + AL_USDMAYA_PUBLIC + static const TfToken lockInherited; + + /// Value used in the lock property that tags prim unlocked regardless of its parent state + AL_USDMAYA_PUBLIC + static const TfToken lockUnlocked; + + /// This represents the medata key that plugins can be registered against as an alternative to + /// typed schemas + AL_USDMAYA_PUBLIC + static const TfToken assetType; }; //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/PluginRegister.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/PluginRegister.h index 61822c73cd..5e1ba24413 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/PluginRegister.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/PluginRegister.h @@ -14,8 +14,8 @@ // limitations under the License. // #pragma once -#include #include + #include "AL/maya/utils/CommandGuiHelper.h" #include "AL/maya/utils/MenuBuilder.h" #include "AL/usdmaya/Global.h" @@ -36,26 +36,27 @@ #include "AL/usdmaya/nodes/LayerManager.h" #include "AL/usdmaya/nodes/MeshAnimCreator.h" #include "AL/usdmaya/nodes/MeshAnimDeformer.h" -#include "AL/usdmaya/nodes/ProxyUsdGeomCamera.h" #include "AL/usdmaya/nodes/ProxyDrawOverride.h" #include "AL/usdmaya/nodes/ProxyShape.h" #include "AL/usdmaya/nodes/ProxyShapeUI.h" +#include "AL/usdmaya/nodes/ProxyUsdGeomCamera.h" #include "AL/usdmaya/nodes/RendererManager.h" +#include "AL/usdmaya/nodes/Scope.h" #include "AL/usdmaya/nodes/Transform.h" #include "AL/usdmaya/nodes/TransformationMatrix.h" -#include "AL/usdmaya/nodes/Scope.h" + +#include #include #include #include #include +#include #include #include #include -#include - #if defined(WANT_UFE_BUILD) #include #endif @@ -66,8 +67,9 @@ namespace AL { namespace usdmaya { //---------------------------------------------------------------------------------------------------------------------- -/// \brief Short term fix to enable meshes to connect directly to USD prims. This will be removed once the plugin -/// translator API has been updated to allow custom import/export options. +/// \brief Short term fix to enable meshes to connect directly to USD prims. This will be removed +/// once the plugin +/// translator API has been updated to allow custom import/export options. //---------------------------------------------------------------------------------------------------------------------- static const char* const g_geom_deformer_code = R"( global proc AL_usdmaya_meshStaticImport() @@ -160,318 +162,333 @@ global proc AL_usdmaya_meshAnimImport() )"; //---------------------------------------------------------------------------------------------------------------------- -/// \brief This method is basically the main initializePlugin routine. The reason for it being a template is simply +/// \brief This method is basically the main initializePlugin routine. The reason for it being a +/// template is simply /// a historical artifact. /// \param plugin the MFnPlugin /// \todo Move this code into initializePlugin /// \ingroup usdmaya //---------------------------------------------------------------------------------------------------------------------- -template -MStatus registerPlugin(AFnPlugin& plugin) +template MStatus registerPlugin(AFnPlugin& plugin) { - GlfGlewInit(); + GlfGlewInit(); - // We may be in a non-gui maya... if so, - // GlfContextCaps::InitInstance() will error - if (GlfGLContext::GetCurrentGLContext()->IsValid()) { - GlfContextCaps::InitInstance(); - } - - if(!MGlobal::optionVarExists("AL_usdmaya_selectMode")) - { - MGlobal::setOptionVarValue("AL_usdmaya_selectMode", 0); - } - - if(!MGlobal::optionVarExists("AL_usdmaya_selectResolution")) - { - MGlobal::setOptionVarValue("AL_usdmaya_selectResolution", 10); - } - - if(!MGlobal::optionVarExists("AL_usdmaya_pickMode")) - { - MGlobal::setOptionVarValue("AL_usdmaya_pickMode", static_cast(nodes::ProxyShape::PickMode::kPrims)); - } + // We may be in a non-gui maya... if so, + // GlfContextCaps::InitInstance() will error + if (GlfGLContext::GetCurrentGLContext()->IsValid()) { + GlfContextCaps::InitInstance(); + } - if(!MGlobal::optionVarExists("AL_usdmaya_readAnimatedValues")) - { - MGlobal::setOptionVarValue("AL_usdmaya_readAnimatedValues", false); - } + if (!MGlobal::optionVarExists("AL_usdmaya_selectMode")) { + MGlobal::setOptionVarValue("AL_usdmaya_selectMode", 0); + } - if(!MGlobal::optionVarExists("AL_usdmaya_selectionEnabled")) - { - MGlobal::setOptionVarValue("AL_usdmaya_selectionEnabled", true); - } + if (!MGlobal::optionVarExists("AL_usdmaya_selectResolution")) { + MGlobal::setOptionVarValue("AL_usdmaya_selectResolution", 10); + } - if(!MGlobal::optionVarExists("AL_usdmaya_pushToPrim")) - { - MGlobal::setOptionVarValue("AL_usdmaya_pushToPrim", true); - } + if (!MGlobal::optionVarExists("AL_usdmaya_pickMode")) { + MGlobal::setOptionVarValue( + "AL_usdmaya_pickMode", static_cast(nodes::ProxyShape::PickMode::kPrims)); + } - if(!MGlobal::optionVarExists("AL_usdmaya_ignoreLockPrims")) - { - MGlobal::setOptionVarValue("AL_usdmaya_ignoreLockPrims", false); - } + if (!MGlobal::optionVarExists("AL_usdmaya_readAnimatedValues")) { + MGlobal::setOptionVarValue("AL_usdmaya_readAnimatedValues", false); + } - MStatus status; + if (!MGlobal::optionVarExists("AL_usdmaya_selectionEnabled")) { + MGlobal::setOptionVarValue("AL_usdmaya_selectionEnabled", true); + } - // gpuCachePluginMain used as an example. - if (MGlobal::kInteractive == MGlobal::mayaState()) { - const auto otherPriority = MSelectionMask::getSelectionTypePriority("polymesh"); - if (!MSelectionMask::registerSelectionType(AL::usdmaya::nodes::ProxyShape::s_selectionMaskName, otherPriority)) { - status.perror("Error registering selection mask!"); - return MS::kFailure; + if (!MGlobal::optionVarExists("AL_usdmaya_pushToPrim")) { + MGlobal::setOptionVarValue("AL_usdmaya_pushToPrim", true); } - MString cmd = "addSelectTypeItem(\"Surface\",\""; - cmd += AL::usdmaya::nodes::ProxyShape::s_selectionMaskName; - cmd += "\",\""; - cmd += "AL Proxy Shape"; - cmd += "\")"; + if (!MGlobal::optionVarExists("AL_usdmaya_ignoreLockPrims")) { + MGlobal::setOptionVarValue("AL_usdmaya_ignoreLockPrims", false); + } - status = MGlobal::executeCommand(cmd); - if (!status) { - status.perror("Error adding al_ProxyShape selection type!"); - return status; + MStatus status; + + // gpuCachePluginMain used as an example. + if (MGlobal::kInteractive == MGlobal::mayaState()) { + const auto otherPriority = MSelectionMask::getSelectionTypePriority("polymesh"); + if (!MSelectionMask::registerSelectionType( + AL::usdmaya::nodes::ProxyShape::s_selectionMaskName, otherPriority)) { + status.perror("Error registering selection mask!"); + return MS::kFailure; + } + + MString cmd = "addSelectTypeItem(\"Surface\",\""; + cmd += AL::usdmaya::nodes::ProxyShape::s_selectionMaskName; + cmd += "\",\""; + cmd += "AL Proxy Shape"; + cmd += "\")"; + + status = MGlobal::executeCommand(cmd); + if (!status) { + status.perror("Error adding al_ProxyShape selection type!"); + return status; + } } - } - AL_REGISTER_COMMAND(plugin, AL::maya::utils::CommandGuiListGen); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::CreateUsdPrim); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerCreateLayer); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerGetLayers); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerCurrentEditTarget); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerSave); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerSetMuted); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ManageRenderer); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImport); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeFindLoadable); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImportAllTransforms); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeRemoveAllTransforms); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeResync); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImportPrimPathAsMaya); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapePrintRefCountState); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ChangeVariant); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ActivatePrim); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeSelect); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapePostSelect); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::InternalProxyShapeSelect); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::UsdDebugCommand); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListEvents); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListCallbacks); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListTranslators); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::Callback); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::TriggerEvent); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::DeleteCallbacks); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::CallbackQuery); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::Event); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::EventQuery); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::EventLookup); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::TranslatePrim); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerManager); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::SyncFileIOGui); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::fileio::ImportCommand); - AL_REGISTER_COMMAND(plugin, AL::usdmaya::fileio::ExportCommand); - AL_REGISTER_TRANSLATOR(plugin, AL::usdmaya::fileio::ImportTranslator); - AL_REGISTER_TRANSLATOR(plugin, AL::usdmaya::fileio::ExportTranslator); - AL_REGISTER_DRAW_OVERRIDE(plugin, AL::usdmaya::nodes::ProxyDrawOverride); - - status = MayaUsdProxyShapePlugin::initialize(plugin); - CHECK_MSTATUS(status); - - if (MayaUsdProxyShapePlugin::useVP2_NativeUSD_Rendering()) { - status = plugin.registerShape( - AL::usdmaya::nodes::ProxyShape::kTypeName, - AL::usdmaya::nodes::ProxyShape::kTypeId, - AL::usdmaya::nodes::ProxyShape::creator, - AL::usdmaya::nodes::ProxyShape::initialise, - AL::usdmaya::nodes::ProxyShapeUI::creator, - MayaUsdProxyShapePlugin::getProxyShapeClassification() - ); - CHECK_MSTATUS(status); - } - else { - AL_REGISTER_SHAPE_NODE(plugin, AL::usdmaya::nodes::ProxyShape, AL::usdmaya::nodes::ProxyShapeUI, AL::usdmaya::nodes::ProxyDrawOverride); - } + AL_REGISTER_COMMAND(plugin, AL::maya::utils::CommandGuiListGen); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::CreateUsdPrim); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerCreateLayer); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerGetLayers); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerCurrentEditTarget); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerSave); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerSetMuted); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ManageRenderer); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImport); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeFindLoadable); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImportAllTransforms); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeRemoveAllTransforms); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeResync); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImportPrimPathAsMaya); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapePrintRefCountState); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ChangeVariant); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ActivatePrim); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeSelect); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapePostSelect); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::InternalProxyShapeSelect); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::UsdDebugCommand); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListEvents); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListCallbacks); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListTranslators); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::Callback); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::TriggerEvent); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::DeleteCallbacks); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::CallbackQuery); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::Event); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::EventQuery); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::EventLookup); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::TranslatePrim); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerManager); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::cmds::SyncFileIOGui); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::fileio::ImportCommand); + AL_REGISTER_COMMAND(plugin, AL::usdmaya::fileio::ExportCommand); + AL_REGISTER_TRANSLATOR(plugin, AL::usdmaya::fileio::ImportTranslator); + AL_REGISTER_TRANSLATOR(plugin, AL::usdmaya::fileio::ExportTranslator); + AL_REGISTER_DRAW_OVERRIDE(plugin, AL::usdmaya::nodes::ProxyDrawOverride); + + status = MayaUsdProxyShapePlugin::initialize(plugin); + CHECK_MSTATUS(status); + + if (MayaUsdProxyShapePlugin::useVP2_NativeUSD_Rendering()) { + status = plugin.registerShape( + AL::usdmaya::nodes::ProxyShape::kTypeName, + AL::usdmaya::nodes::ProxyShape::kTypeId, + AL::usdmaya::nodes::ProxyShape::creator, + AL::usdmaya::nodes::ProxyShape::initialise, + AL::usdmaya::nodes::ProxyShapeUI::creator, + MayaUsdProxyShapePlugin::getProxyShapeClassification()); + CHECK_MSTATUS(status); + } else { + AL_REGISTER_SHAPE_NODE( + plugin, + AL::usdmaya::nodes::ProxyShape, + AL::usdmaya::nodes::ProxyShapeUI, + AL::usdmaya::nodes::ProxyDrawOverride); + } #if defined(WANT_UFE_BUILD) - status = MayaUsd::ufe::initialize(); - if (!status) { - status.perror("Unable to initialize ufe."); - } + status = MayaUsd::ufe::initialize(); + if (!status) { + status.perror("Unable to initialize ufe."); + } #endif - AL_REGISTER_TRANSFORM_NODE(plugin, AL::usdmaya::nodes::Scope, AL::usdmaya::nodes::BasicTransformationMatrix); - AL_REGISTER_TRANSFORM_NODE(plugin, AL::usdmaya::nodes::Transform, AL::usdmaya::nodes::TransformationMatrix); - AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::RendererManager); - AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::Layer); - AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::MeshAnimCreator); - AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::MeshAnimDeformer); - AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::ProxyUsdGeomCamera); - - // Since AL_MAYA_DECLARE_NODE / AL_MAYA_DEFINE_NODE declare/define "creator" - // method, and AL_REGISTER_DEPEND_NODE registers "creator", in order to - // define custom creator, need to either 'override' one of those... chose to - // replace AL_REGISTER_DEPEND_NODE - //AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::LayerManager); - { - MStatus status = plugin.registerNode( - AL::usdmaya::nodes::LayerManager::kTypeName, - AL::usdmaya::nodes::LayerManager::kTypeId, - AL::usdmaya::nodes::LayerManager::conditionalCreator, - AL::usdmaya::nodes::LayerManager::initialise); - if(!status) { - status.perror("unable to register depend node LayerManager"); - return status; + AL_REGISTER_TRANSFORM_NODE( + plugin, AL::usdmaya::nodes::Scope, AL::usdmaya::nodes::BasicTransformationMatrix); + AL_REGISTER_TRANSFORM_NODE( + plugin, AL::usdmaya::nodes::Transform, AL::usdmaya::nodes::TransformationMatrix); + AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::RendererManager); + AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::Layer); + AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::MeshAnimCreator); + AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::MeshAnimDeformer); + AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::ProxyUsdGeomCamera); + + // Since AL_MAYA_DECLARE_NODE / AL_MAYA_DEFINE_NODE declare/define "creator" + // method, and AL_REGISTER_DEPEND_NODE registers "creator", in order to + // define custom creator, need to either 'override' one of those... chose to + // replace AL_REGISTER_DEPEND_NODE + // AL_REGISTER_DEPEND_NODE(plugin, AL::usdmaya::nodes::LayerManager); + { + MStatus status = plugin.registerNode( + AL::usdmaya::nodes::LayerManager::kTypeName, + AL::usdmaya::nodes::LayerManager::kTypeId, + AL::usdmaya::nodes::LayerManager::conditionalCreator, + AL::usdmaya::nodes::LayerManager::initialise); + if (!status) { + status.perror("unable to register depend node LayerManager"); + return status; + } } - } - // generate the menu GUI + option boxes - AL::usdmaya::cmds::constructLayerCommandGuis(); - AL::usdmaya::cmds::constructProxyShapeCommandGuis(); - AL::usdmaya::cmds::constructDebugCommandGuis(); - AL::usdmaya::cmds::constructRendererCommandGuis(); - AL::usdmaya::cmds::constructPickModeCommandGuis(); - - MGlobal::executeCommand(g_geom_deformer_code); - AL::maya::utils::MenuBuilder::addEntry("USD/Animated Geometry/Connect selected meshes to USD (static)", "AL_usdmaya_meshStaticImport"); - AL::maya::utils::MenuBuilder::addEntry("USD/Animated Geometry/Connect selected meshes to USD (animated)", "AL_usdmaya_meshAnimImport"); - AL::maya::utils::MenuBuilder::addEntry("USD/Selection Enabled", "optionVar -iv \\\"AL_usdmaya_selectionEnabled\\\" #1", true, MGlobal::optionVarIntValue("AL_usdmaya_selectionEnabled")); - AL::maya::utils::MenuBuilder::addEntry("USD/Enable pushToPrim", "optionVar -iv \\\"AL_usdmaya_pushToPrim\\\" #1", true, MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim")); - AL::maya::utils::MenuBuilder::addEntry("USD/Selection Ignore Lock Prims Enabled", "optionVar -iv \\\"AL_usdmaya_ignoreLockPrims\\\" #1", true, MGlobal::optionVarIntValue("AL_usdmaya_ignoreLockPrims")); - CHECK_MSTATUS(AL::maya::utils::MenuBuilder::generatePluginUI(plugin, "AL_usdmaya")); - AL::usdmaya::Global::onPluginLoad(); - - // As of 2-Aug-2019, these PlugPlugin translators are not loaded - // automatically. To be investigated. A duplicate of this code is in the - // Autodesk plugin.cpp. - const std::vector translatorPluginNames{ - "mayaUsd_Schemas", "mayaUsd_Translators" }; - const auto& plugRegistry = PlugRegistry::GetInstance(); - std::stringstream msg("mayaUsdPlugin: "); - for (const auto& pluginName : translatorPluginNames) { - auto plugin = plugRegistry.GetPluginWithName(pluginName); - if (!plugin) { - status = MStatus::kFailure; - msg << "translator " << pluginName << " not found."; - status.perror(msg.str().c_str()); - } - else { - // Load is a no-op if already loaded. - if (!plugin->Load()) { - status = MStatus::kFailure; - msg << pluginName << " translator load failed."; - status.perror(msg.str().c_str()); - } - } - } + // generate the menu GUI + option boxes + AL::usdmaya::cmds::constructLayerCommandGuis(); + AL::usdmaya::cmds::constructProxyShapeCommandGuis(); + AL::usdmaya::cmds::constructDebugCommandGuis(); + AL::usdmaya::cmds::constructRendererCommandGuis(); + AL::usdmaya::cmds::constructPickModeCommandGuis(); + + MGlobal::executeCommand(g_geom_deformer_code); + AL::maya::utils::MenuBuilder::addEntry( + "USD/Animated Geometry/Connect selected meshes to USD (static)", + "AL_usdmaya_meshStaticImport"); + AL::maya::utils::MenuBuilder::addEntry( + "USD/Animated Geometry/Connect selected meshes to USD (animated)", + "AL_usdmaya_meshAnimImport"); + AL::maya::utils::MenuBuilder::addEntry( + "USD/Selection Enabled", + "optionVar -iv \\\"AL_usdmaya_selectionEnabled\\\" #1", + true, + MGlobal::optionVarIntValue("AL_usdmaya_selectionEnabled")); + AL::maya::utils::MenuBuilder::addEntry( + "USD/Enable pushToPrim", + "optionVar -iv \\\"AL_usdmaya_pushToPrim\\\" #1", + true, + MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim")); + AL::maya::utils::MenuBuilder::addEntry( + "USD/Selection Ignore Lock Prims Enabled", + "optionVar -iv \\\"AL_usdmaya_ignoreLockPrims\\\" #1", + true, + MGlobal::optionVarIntValue("AL_usdmaya_ignoreLockPrims")); + CHECK_MSTATUS(AL::maya::utils::MenuBuilder::generatePluginUI(plugin, "AL_usdmaya")); + AL::usdmaya::Global::onPluginLoad(); + + // As of 2-Aug-2019, these PlugPlugin translators are not loaded + // automatically. To be investigated. A duplicate of this code is in the + // Autodesk plugin.cpp. + const std::vector translatorPluginNames { "mayaUsd_Schemas", + "mayaUsd_Translators" }; + const auto& plugRegistry = PlugRegistry::GetInstance(); + std::stringstream msg("mayaUsdPlugin: "); + for (const auto& pluginName : translatorPluginNames) { + auto plugin = plugRegistry.GetPluginWithName(pluginName); + if (!plugin) { + status = MStatus::kFailure; + msg << "translator " << pluginName << " not found."; + status.perror(msg.str().c_str()); + } else { + // Load is a no-op if already loaded. + if (!plugin->Load()) { + status = MStatus::kFailure; + msg << pluginName << " translator load failed."; + status.perror(msg.str().c_str()); + } + } + } - // Force all plugins to be loaded at startup time. Unless we load plugins upfront - // options will not be registered until the start of import or export, and won't be available in the GUI - const TfType& translatorType = TfType::Find(); - PlugPluginPtrVector plugins = PlugRegistry::GetInstance().GetAllPlugins(); - for(auto& plugin : plugins) - { - if(!plugin->IsLoaded() && plugin->DeclaresType(translatorType, true)) - plugin->Load(); - } + // Force all plugins to be loaded at startup time. Unless we load plugins upfront + // options will not be registered until the start of import or export, and won't be available in + // the GUI + const TfType& translatorType = TfType::Find(); + PlugPluginPtrVector plugins = PlugRegistry::GetInstance().GetAllPlugins(); + for (auto& plugin : plugins) { + if (!plugin->IsLoaded() && plugin->DeclaresType(translatorType, true)) + plugin->Load(); + } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- -/// \brief This method is basically the main uninitializePlugin routine. The reason for it being a template is simply +/// \brief This method is basically the main uninitializePlugin routine. The reason for it being a +/// template is simply /// a historical artifact. /// \param plugin the MFnPlugin /// \todo Move this code into uninitializePlugin /// \ingroup usdmaya //---------------------------------------------------------------------------------------------------------------------- -template -MStatus unregisterPlugin(AFnPlugin& plugin) +template MStatus unregisterPlugin(AFnPlugin& plugin) { - MStatus status; + MStatus status; #if defined(WANT_UFE_BUILD) - status = MayaUsd::ufe::finalize(); - CHECK_MSTATUS(status); + status = MayaUsd::ufe::finalize(); + CHECK_MSTATUS(status); #endif - // gpuCachePluginMain used as an example. - if (MGlobal::kInteractive == MGlobal::mayaState()) { - MString cmd = "deleteSelectTypeItem(\"Surface\",\""; - cmd += AL::usdmaya::nodes::ProxyShape::s_selectionMaskName; - cmd += "\")"; - - status = MGlobal::executeCommand(cmd); - if (!status) { - status.perror("Error removing al_ProxyShape selection type!"); - return status; + // gpuCachePluginMain used as an example. + if (MGlobal::kInteractive == MGlobal::mayaState()) { + MString cmd = "deleteSelectTypeItem(\"Surface\",\""; + cmd += AL::usdmaya::nodes::ProxyShape::s_selectionMaskName; + cmd += "\")"; + + status = MGlobal::executeCommand(cmd); + if (!status) { + status.perror("Error removing al_ProxyShape selection type!"); + return status; + } + + if (!MSelectionMask::deregisterSelectionType( + AL::usdmaya::nodes::ProxyShape::s_selectionMaskName)) { + status.perror("Error deregistering selection mask!"); + return MS::kFailure; + } } - if (!MSelectionMask::deregisterSelectionType(AL::usdmaya::nodes::ProxyShape::s_selectionMaskName)) { - status.perror("Error deregistering selection mask!"); - return MS::kFailure; - } - } - - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::SyncFileIOGui); - AL_UNREGISTER_COMMAND(plugin, AL::maya::utils::CommandGuiListGen); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::InternalProxyShapeSelect); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapePostSelect); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeSelect); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ActivatePrim); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ChangeVariant); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerCreateLayer); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerCurrentEditTarget); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerGetLayers); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerSave); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerSetMuted); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ManageRenderer); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImport); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeFindLoadable); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImportAllTransforms); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeRemoveAllTransforms); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeResync); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImportPrimPathAsMaya); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapePrintRefCountState); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::Callback); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListCallbacks); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListEvents); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListTranslators); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::TriggerEvent); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::DeleteCallbacks); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::CallbackQuery); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::Event); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::EventQuery); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::EventLookup); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::UsdDebugCommand); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::fileio::ImportCommand); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::fileio::ExportCommand); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::TranslatePrim); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerManager); - AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::CreateUsdPrim); - AL_UNREGISTER_TRANSLATOR(plugin, AL::usdmaya::fileio::ImportTranslator); - AL_UNREGISTER_TRANSLATOR(plugin, AL::usdmaya::fileio::ExportTranslator); - AL_UNREGISTER_DRAW_OVERRIDE(plugin, AL::usdmaya::nodes::ProxyDrawOverride); - AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::MeshAnimDeformer); - AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::MeshAnimCreator); - AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::ProxyShape); - - status = MayaUsdProxyShapePlugin::finalize(plugin); - CHECK_MSTATUS(status); - - AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::Transform); - AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::Scope); - AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::RendererManager); - AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::Layer); - AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::LayerManager); - - AL::usdmaya::Global::onPluginUnload(); - return status; + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::SyncFileIOGui); + AL_UNREGISTER_COMMAND(plugin, AL::maya::utils::CommandGuiListGen); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::InternalProxyShapeSelect); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapePostSelect); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeSelect); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ActivatePrim); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ChangeVariant); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerCreateLayer); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerCurrentEditTarget); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerGetLayers); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerSave); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerSetMuted); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ManageRenderer); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImport); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeFindLoadable); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImportAllTransforms); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeRemoveAllTransforms); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeResync); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapeImportPrimPathAsMaya); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ProxyShapePrintRefCountState); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::Callback); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListCallbacks); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListEvents); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::ListTranslators); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::TriggerEvent); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::DeleteCallbacks); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::CallbackQuery); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::Event); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::EventQuery); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::EventLookup); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::UsdDebugCommand); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::fileio::ImportCommand); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::fileio::ExportCommand); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::TranslatePrim); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::LayerManager); + AL_UNREGISTER_COMMAND(plugin, AL::usdmaya::cmds::CreateUsdPrim); + AL_UNREGISTER_TRANSLATOR(plugin, AL::usdmaya::fileio::ImportTranslator); + AL_UNREGISTER_TRANSLATOR(plugin, AL::usdmaya::fileio::ExportTranslator); + AL_UNREGISTER_DRAW_OVERRIDE(plugin, AL::usdmaya::nodes::ProxyDrawOverride); + AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::MeshAnimDeformer); + AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::MeshAnimCreator); + AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::ProxyShape); + + status = MayaUsdProxyShapePlugin::finalize(plugin); + CHECK_MSTATUS(status); + + AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::Transform); + AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::Scope); + AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::RendererManager); + AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::Layer); + AL_UNREGISTER_NODE(plugin, AL::usdmaya::nodes::LayerManager); + + AL::usdmaya::Global::onPluginUnload(); + return status; } #undef AL_RUN_TESTS //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/SelectabilityDB.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/SelectabilityDB.cpp index 215f51b474..154e26ae09 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/SelectabilityDB.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/SelectabilityDB.cpp @@ -21,118 +21,101 @@ namespace usdmaya { //---------------------------------------------------------------------------------------------------------------------- bool SelectabilityDB::isPathUnselectable(const SdfPath& path) const { - auto begin = m_unselectablePaths.begin(); - auto end = m_unselectablePaths.end(); - auto foundPathEntry = end; - auto root = SdfPath::AbsoluteRootPath(); - auto temp(path); + auto begin = m_unselectablePaths.begin(); + auto end = m_unselectablePaths.end(); + auto foundPathEntry = end; + auto root = SdfPath::AbsoluteRootPath(); + auto temp(path); - while(temp != root) - { - foundPathEntry = std::lower_bound(begin, foundPathEntry, temp); - if(foundPathEntry != end && temp == *foundPathEntry) - { - return true; + while (temp != root) { + foundPathEntry = std::lower_bound(begin, foundPathEntry, temp); + if (foundPathEntry != end && temp == *foundPathEntry) { + return true; + } + temp = temp.GetParentPath(); } - temp = temp.GetParentPath(); - } - return false; + return false; } //---------------------------------------------------------------------------------------------------------------------- void SelectabilityDB::removePathsAsUnselectable(const SdfPathVector& paths) { - for(SdfPath path : paths) - { - removeUnselectablePath(path); - } + for (SdfPath path : paths) { + removeUnselectablePath(path); + } - auto end = m_unselectablePaths.end(); - auto start = m_unselectablePaths.begin(); - for(SdfPath path : paths) - { - auto temp = std::lower_bound(start, end, path); - if(temp != end) - { - if(*temp == path) - { - temp = m_unselectablePaths.erase(temp); - } - start = temp; + auto end = m_unselectablePaths.end(); + auto start = m_unselectablePaths.begin(); + for (SdfPath path : paths) { + auto temp = std::lower_bound(start, end, path); + if (temp != end) { + if (*temp == path) { + temp = m_unselectablePaths.erase(temp); + } + start = temp; + } } - } } //---------------------------------------------------------------------------------------------------------------------- void SelectabilityDB::removePathAsUnselectable(const SdfPath& path) { - removeUnselectablePath(path); + removeUnselectablePath(path); } //---------------------------------------------------------------------------------------------------------------------- void SelectabilityDB::addPathsAsUnselectable(const SdfPathVector& paths) { - auto end = m_unselectablePaths.end(); - auto start = m_unselectablePaths.begin(); - for(auto iter = paths.begin(), last = paths.end(); iter != last; ++iter) - { - start = std::lower_bound(start, end, *iter); + auto end = m_unselectablePaths.end(); + auto start = m_unselectablePaths.begin(); + for (auto iter = paths.begin(), last = paths.end(); iter != last; ++iter) { + start = std::lower_bound(start, end, *iter); - // If we've hit the end, we can simply append the remaining elements in one go. - if(start == end) - { - m_unselectablePaths.insert(end, iter, last); - return; - } + // If we've hit the end, we can simply append the remaining elements in one go. + if (start == end) { + m_unselectablePaths.insert(end, iter, last); + return; + } - if(*start != *iter) - { - m_unselectablePaths.insert(start, *iter); + if (*start != *iter) { + m_unselectablePaths.insert(start, *iter); + } } - } } //---------------------------------------------------------------------------------------------------------------------- -void SelectabilityDB::addPathAsUnselectable(const SdfPath& path) -{ - addUnselectablePath(path); -} +void SelectabilityDB::addPathAsUnselectable(const SdfPath& path) { addUnselectablePath(path); } //---------------------------------------------------------------------------------------------------------------------- bool SelectabilityDB::removeUnselectablePath(const SdfPath& path) { - auto end = m_unselectablePaths.end(); - auto foundPathEntry = std::lower_bound(m_unselectablePaths.begin(), end, path); - if(foundPathEntry != end && *foundPathEntry == path) - { - m_unselectablePaths.erase(foundPathEntry); - return true; - } - return false; + auto end = m_unselectablePaths.end(); + auto foundPathEntry = std::lower_bound(m_unselectablePaths.begin(), end, path); + if (foundPathEntry != end && *foundPathEntry == path) { + m_unselectablePaths.erase(foundPathEntry); + return true; + } + return false; } //---------------------------------------------------------------------------------------------------------------------- bool SelectabilityDB::addUnselectablePath(const SdfPath& path) { - auto end = m_unselectablePaths.end(); - auto iter = std::lower_bound(m_unselectablePaths.begin(), end, path); - if(iter != end) - { - if(*iter != path) - { - m_unselectablePaths.insert(iter, path); - return true; + auto end = m_unselectablePaths.end(); + auto iter = std::lower_bound(m_unselectablePaths.begin(), end, path); + if (iter != end) { + if (*iter != path) { + m_unselectablePaths.insert(iter, path); + return true; + } + } else { + m_unselectablePaths.push_back(path); + return true; } - } - else - { - m_unselectablePaths.push_back(path); - return true; - } - return false; + return false; } //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- \ No newline at end of file diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/SelectabilityDB.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/SelectabilityDB.h index 807c610d41..471690fc43 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/SelectabilityDB.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/SelectabilityDB.h @@ -27,98 +27,103 @@ namespace AL { namespace usdmaya { ///--------------------------------------------------------------------------------------------------------------------- -/// \brief Logic that stores a sorted list of paths which represent Selectable points in the USD hierarchy +/// \brief Logic that stores a sorted list of paths which represent Selectable points in the USD +/// hierarchy ///--------------------------------------------------------------------------------------------------------------------- class SelectabilityDB { - // at little unpleasant design wise, however it means the proxy shape can directly modify the internal - // list of unselectable paths. I have looked at moving some of that logic into this class, however that would - // incur a performance penalty (lock & excluded prim processing can be done at the same time). - friend class nodes::ProxyShape; + // at little unpleasant design wise, however it means the proxy shape can directly modify the + // internal list of unselectable paths. I have looked at moving some of that logic into this + // class, however that would incur a performance penalty (lock & excluded prim processing can be + // done at the same time). + friend class nodes::ProxyShape; + public: + SelectabilityDB() + : m_unselectablePaths() + { + m_unselectablePaths.reserve(128); + } - SelectabilityDB() - : m_unselectablePaths() - { - m_unselectablePaths.reserve(128); - } - - //-------------------------------------------------------------------------------------------------------------------- - /// \brief Determines this path is unselectable - /// \param path that you want to determine if it's unselectable - //-------------------------------------------------------------------------------------------------------------------- - AL_USDMAYA_PUBLIC - bool isPathUnselectable(const SdfPath& path) const; - - //-------------------------------------------------------------------------------------------------------------------- - /// \brief Determines whether there is an internal entry for the path specified (and only this path!). If you wish - /// to determine selectability, call isPathUnselectable instead. - /// \param path the path to check to see if exists - /// \return true if the path is contained, false if not. - //-------------------------------------------------------------------------------------------------------------------- - bool containsPath(const SdfPath& path) const - { - auto foundPathEntry = std::lower_bound(m_unselectablePaths.begin(), m_unselectablePaths.end(), path); - if(foundPathEntry != m_unselectablePaths.end() && path == *foundPathEntry) + //-------------------------------------------------------------------------------------------------------------------- + /// \brief Determines this path is unselectable + /// \param path that you want to determine if it's unselectable + //-------------------------------------------------------------------------------------------------------------------- + AL_USDMAYA_PUBLIC + bool isPathUnselectable(const SdfPath& path) const; + + //-------------------------------------------------------------------------------------------------------------------- + /// \brief Determines whether there is an internal entry for the path specified (and only this + /// path!). If you wish + /// to determine selectability, call isPathUnselectable instead. + /// \param path the path to check to see if exists + /// \return true if the path is contained, false if not. + //-------------------------------------------------------------------------------------------------------------------- + bool containsPath(const SdfPath& path) const { - return true; + auto foundPathEntry + = std::lower_bound(m_unselectablePaths.begin(), m_unselectablePaths.end(), path); + if (foundPathEntry != m_unselectablePaths.end() && path == *foundPathEntry) { + return true; + } + return false; } - return false; - } - - //-------------------------------------------------------------------------------------------------------------------- - /// \brief Adds a list of paths to the selectable list - /// \param paths which will be added as selectable. All children paths will be also unselectable - //-------------------------------------------------------------------------------------------------------------------- - AL_USDMAYA_PUBLIC - void addPathsAsUnselectable(const SdfPathVector& paths); - - //-------------------------------------------------------------------------------------------------------------------- - /// \brief Sets a list of paths to the selectable list - /// \param paths which will be added as selectable. All children paths will be also unselectable - //-------------------------------------------------------------------------------------------------------------------- - void setPathsAsUnselectable(const SdfPathVector& paths) - { - m_unselectablePaths = paths; - std::sort(m_unselectablePaths.begin(), m_unselectablePaths.end()); - } - - //-------------------------------------------------------------------------------------------------------------------- - /// \brief Adds a path to the unselectable list - /// \param path which will be added as unselectable. All children paths will be also unselectable - //-------------------------------------------------------------------------------------------------------------------- - AL_USDMAYA_PUBLIC - void addPathAsUnselectable(const SdfPath& path); - - //-------------------------------------------------------------------------------------------------------------------- - /// \brief Gets the currently explictly tracked unseletable paths - //-------------------------------------------------------------------------------------------------------------------- - inline const SdfPathVector& getUnselectablePaths() const - { return m_unselectablePaths; } - - ///------------------------------------------------------------------------------------------------------------------- - /// \brief Removes a list of paths from the selectable list if the exist. - /// \param paths the paths to remove from the selectable list - ///------------------------------------------------------------------------------------------------------------------- - AL_USDMAYA_PUBLIC - void removePathsAsUnselectable(const SdfPathVector& paths); - - //-------------------------------------------------------------------------------------------------------------------- - /// \brief Remove a path from the selectable list if the exist. - /// \param path the path to remove from the selectable list - //-------------------------------------------------------------------------------------------------------------------- - AL_USDMAYA_PUBLIC - void removePathAsUnselectable(const SdfPath& path); + + //-------------------------------------------------------------------------------------------------------------------- + /// \brief Adds a list of paths to the selectable list + /// \param paths which will be added as selectable. All children paths will be also + /// unselectable + //-------------------------------------------------------------------------------------------------------------------- + AL_USDMAYA_PUBLIC + void addPathsAsUnselectable(const SdfPathVector& paths); + + //-------------------------------------------------------------------------------------------------------------------- + /// \brief Sets a list of paths to the selectable list + /// \param paths which will be added as selectable. All children paths will be also + /// unselectable + //-------------------------------------------------------------------------------------------------------------------- + void setPathsAsUnselectable(const SdfPathVector& paths) + { + m_unselectablePaths = paths; + std::sort(m_unselectablePaths.begin(), m_unselectablePaths.end()); + } + + //-------------------------------------------------------------------------------------------------------------------- + /// \brief Adds a path to the unselectable list + /// \param path which will be added as unselectable. All children paths will be also + /// unselectable + //-------------------------------------------------------------------------------------------------------------------- + AL_USDMAYA_PUBLIC + void addPathAsUnselectable(const SdfPath& path); + + //-------------------------------------------------------------------------------------------------------------------- + /// \brief Gets the currently explictly tracked unseletable paths + //-------------------------------------------------------------------------------------------------------------------- + inline const SdfPathVector& getUnselectablePaths() const { return m_unselectablePaths; } + + ///------------------------------------------------------------------------------------------------------------------- + /// \brief Removes a list of paths from the selectable list if the exist. + /// \param paths the paths to remove from the selectable list + ///------------------------------------------------------------------------------------------------------------------- + AL_USDMAYA_PUBLIC + void removePathsAsUnselectable(const SdfPathVector& paths); + + //-------------------------------------------------------------------------------------------------------------------- + /// \brief Remove a path from the selectable list if the exist. + /// \param path the path to remove from the selectable list + //-------------------------------------------------------------------------------------------------------------------- + AL_USDMAYA_PUBLIC + void removePathAsUnselectable(const SdfPath& path); private: - bool addUnselectablePath(const SdfPath& path); - bool removeUnselectablePath(const SdfPath& path); + bool addUnselectablePath(const SdfPath& path); + bool removeUnselectablePath(const SdfPath& path); private: - SdfPathVector m_unselectablePaths; + SdfPathVector m_unselectablePaths; }; //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- \ No newline at end of file diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/StageCache.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/StageCache.cpp index eead18632d..a5960850e9 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/StageCache.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/StageCache.cpp @@ -14,76 +14,67 @@ // limitations under the License. // #include "AL/usdmaya/StageCache.h" + +#include "AL/maya/event/MayaEventManager.h" #include "AL/usdmaya/DebugCodes.h" #include -#include "AL/maya/event/MayaEventManager.h" namespace AL { namespace usdmaya { -AL::event::CallbackId StageCache::g_beforeNewCallbackId = 0; -AL::event::CallbackId StageCache::g_beforeLoadCallbackId = 0; +AL::event::CallbackId StageCache::g_beforeNewCallbackId = 0; +AL::event::CallbackId StageCache::g_beforeLoadCallbackId = 0; static AL::event::EventId g_stageCacheCleared = 0; //---------------------------------------------------------------------------------------------------------------------- static void onMayaSceneUpdateCallback(void* clientData) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("Clean the usdMaya cache on maya scene update.\n"); - StageCache::Clear(); + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("Clean the usdMaya cache on maya scene update.\n"); + StageCache::Clear(); } //---------------------------------------------------------------------------------------------------------------------- UsdStageCache& StageCache::Get() { - // IMPORTANT: At every NEW scene in Maya we clear the USD stage cache. - if (g_beforeNewCallbackId == 0) - { - g_beforeNewCallbackId = AL::maya::event::MayaEventManager::instance().registerCallback( - onMayaSceneUpdateCallback, - "BeforeNew", - "ClearStageCacheOnFileNew", - 0x10000); - g_beforeLoadCallbackId = AL::maya::event::MayaEventManager::instance().registerCallback( - onMayaSceneUpdateCallback, - "BeforeOpen", - "ClearStageCacheOnFileOpen", - 0x10000); + // IMPORTANT: At every NEW scene in Maya we clear the USD stage cache. + if (g_beforeNewCallbackId == 0) { + g_beforeNewCallbackId = AL::maya::event::MayaEventManager::instance().registerCallback( + onMayaSceneUpdateCallback, "BeforeNew", "ClearStageCacheOnFileNew", 0x10000); + g_beforeLoadCallbackId = AL::maya::event::MayaEventManager::instance().registerCallback( + onMayaSceneUpdateCallback, "BeforeOpen", "ClearStageCacheOnFileOpen", 0x10000); - g_stageCacheCleared = AL::event::EventScheduler::getScheduler().registerEvent("OnUsdStageCacheCleared", AL::event::kUSDMayaEventType); - } - return UsdUtilsStageCache::Get(); + g_stageCacheCleared = AL::event::EventScheduler::getScheduler().registerEvent( + "OnUsdStageCacheCleared", AL::event::kUSDMayaEventType); + } + return UsdUtilsStageCache::Get(); } //---------------------------------------------------------------------------------------------------------------------- void StageCache::Clear() { - UsdUtilsStageCache::Get().Clear(); - AL::event::EventScheduler::getScheduler().triggerEvent(g_stageCacheCleared); + UsdUtilsStageCache::Get().Clear(); + AL::event::EventScheduler::getScheduler().triggerEvent(g_stageCacheCleared); } //---------------------------------------------------------------------------------------------------------------------- void StageCache::removeCallbacks() { - if (g_stageCacheCleared) - { - AL::event::EventScheduler::getScheduler().unregisterEvent(g_stageCacheCleared); - g_stageCacheCleared = 0; - } - if (g_beforeNewCallbackId) - { - AL::maya::event::MayaEventManager::instance().unregisterCallback(g_beforeNewCallbackId); - g_beforeNewCallbackId = 0; - } - if (g_beforeLoadCallbackId) - { - AL::maya::event::MayaEventManager::instance().unregisterCallback(g_beforeLoadCallbackId); - g_beforeLoadCallbackId = 0; - } + if (g_stageCacheCleared) { + AL::event::EventScheduler::getScheduler().unregisterEvent(g_stageCacheCleared); + g_stageCacheCleared = 0; + } + if (g_beforeNewCallbackId) { + AL::maya::event::MayaEventManager::instance().unregisterCallback(g_beforeNewCallbackId); + g_beforeNewCallbackId = 0; + } + if (g_beforeLoadCallbackId) { + AL::maya::event::MayaEventManager::instance().unregisterCallback(g_beforeLoadCallbackId); + g_beforeLoadCallbackId = 0; + } } //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/StageCache.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/StageCache.h index f4f0672e23..8ec2177154 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/StageCache.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/StageCache.h @@ -15,11 +15,11 @@ // #pragma once +#include "AL/event/EventHandler.h" #include "AL/usdmaya/Api.h" #include #include -#include "AL/event/EventHandler.h" PXR_NAMESPACE_USING_DIRECTIVE @@ -32,24 +32,24 @@ namespace usdmaya { class StageCache { public: + /// \brief Return the singleton stage cache for use by all USD clients within Maya. + /// \return the cache requested + /// \todo we need to offer a way of mapping from a specific ProxyShape to a specific stage + AL_USDMAYA_PUBLIC + static UsdStageCache& Get(); - /// \brief Return the singleton stage cache for use by all USD clients within Maya. - /// \return the cache requested - /// \todo we need to offer a way of mapping from a specific ProxyShape to a specific stage - AL_USDMAYA_PUBLIC - static UsdStageCache& Get(); + /// \brief Clear the cache + AL_USDMAYA_PUBLIC + static void Clear(); - /// \brief Clear the cache - AL_USDMAYA_PUBLIC - static void Clear(); + /// \brief deletes the callbacks constructed to manage the stage cache + AL_USDMAYA_PUBLIC + static void removeCallbacks(); - /// \brief deletes the callbacks constructed to manage the stage cache - AL_USDMAYA_PUBLIC - static void removeCallbacks(); private: - static AL::event::CallbackId g_beforeNewCallbackId; - static AL::event::CallbackId g_beforeLoadCallbackId; + static AL::event::CallbackId g_beforeNewCallbackId; + static AL::event::CallbackId g_beforeLoadCallbackId; }; -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/TransformOperation.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/TransformOperation.cpp index 0ecfa7f577..e0fd500bb4 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/TransformOperation.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/TransformOperation.cpp @@ -24,122 +24,107 @@ namespace AL { namespace usdmaya { //---------------------------------------------------------------------------------------------------------------------- -// usd transform components (e.g. rotate, scale, etc) are all stringly typed. There is no 'simple' way of determining -// how these transforms should be interpreted (e.g. should we use a maya transform, a joint, etc). The original maya -// USD bridge performs an O(n^2) comparison between two string arrays. If all the strings in one array, are found in -// the second array, then the transform is interpreted as a maya type. String compares seems to be the only way to -// do this, so this code attempts to improve on the original bridge by being a little bit more cautious in how those +// usd transform components (e.g. rotate, scale, etc) are all stringly typed. There is no 'simple' +// way of determining how these transforms should be interpreted (e.g. should we use a maya +// transform, a joint, etc). The original maya USD bridge performs an O(n^2) comparison between two +// string arrays. If all the strings in one array, are found in the second array, then the transform +// is interpreted as a maya type. String compares seems to be the only way to do this, so this code +// attempts to improve on the original bridge by being a little bit more cautious in how those // strcmps are performed. //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- -static const std::string g_opNames[] = -{ - std::string("translate"), - std::string("pivot"), - std::string("rotatePivotTranslate"), - std::string("rotatePivot"), - std::string("rotate"), - std::string("rotateAxis"), - std::string("rotatePivotINV"), - std::string("scalePivotTranslate"), - std::string("scalePivot"), - std::string("shear"), - std::string("scale"), - std::string("scalePivotINV"), - std::string("pivotINV"), - std::string("transform"), - std::string("unknown") -}; +static const std::string g_opNames[] = { std::string("translate"), + std::string("pivot"), + std::string("rotatePivotTranslate"), + std::string("rotatePivot"), + std::string("rotate"), + std::string("rotateAxis"), + std::string("rotatePivotINV"), + std::string("scalePivotTranslate"), + std::string("scalePivot"), + std::string("shear"), + std::string("scale"), + std::string("scalePivotINV"), + std::string("pivotINV"), + std::string("transform"), + std::string("unknown") }; //---------------------------------------------------------------------------------------------------------------------- TransformOperation xformOpToEnum(const std::string& opName) { #define TestType(X) ((opName == g_opNames[X]) ? X : kUnknownOp) - switch(opName[0]) - { - case 'p': - { - switch(opName.size()) - { + switch (opName[0]) { + case 'p': { + switch (opName.size()) { case 5: return TestType(kPivot); case 8: return TestType(kPivotInv); - } - } - break; + } + } break; - case 'r': - { - switch(opName.size()) - { + case 'r': { + switch (opName.size()) { case 6: return TestType(kRotate); case 7: - case 9: - { - if(opName.compare(0, 6, "rotate") == 0) - { - return kRotate; - } + case 9: { + if (opName.compare(0, 6, "rotate") == 0) { + return kRotate; + } } case 10: return TestType(kRotateAxis); case 11: return TestType(kRotatePivot); case 14: return TestType(kRotatePivotInv); case 20: return TestType(kRotatePivotTranslate); - } - } - break; + } + } break; - case 's': - { - switch(opName.size()) - { - case 5: - { - if(opName[1] == 'c') return TestType(kScale); - return TestType(kShear); + case 's': { + switch (opName.size()) { + case 5: { + if (opName[1] == 'c') + return TestType(kScale); + return TestType(kShear); } case 10: return TestType(kScalePivot); case 13: return TestType(kScalePivotInv); case 19: return TestType(kScalePivotTranslate); - } - } - break; + } + } break; - case 't': - { - if(opName == g_opNames[kTransform]) return kTransform; - return TestType(kTranslate); + case 't': { + if (opName == g_opNames[kTransform]) + return kTransform; + return TestType(kTranslate); + } } - } #undef TestType - return kUnknownOp; + return kUnknownOp; } //---------------------------------------------------------------------------------------------------------------------- bool matchesMayaProfile( std::vector::const_iterator it, std::vector::const_iterator end, - std::vector::iterator output) + std::vector::iterator output) { - bool matchesMaya = true; + bool matchesMaya = true; - int32_t last = -1; - for(; it != end; ++it, ++output) - { - std::string attrName = it->GetBaseName(); - if(it->IsInverseOp()) - attrName += "INV"; - const TransformOperation thisOp = xformOpToEnum(attrName); - if(thisOp == kPivot || thisOp == kPivotInv || thisOp == kTransform) - matchesMaya = false; - if(last >= thisOp) - matchesMaya = false; - *output = thisOp; - } - return matchesMaya; + int32_t last = -1; + for (; it != end; ++it, ++output) { + std::string attrName = it->GetBaseName(); + if (it->IsInverseOp()) + attrName += "INV"; + const TransformOperation thisOp = xformOpToEnum(attrName); + if (thisOp == kPivot || thisOp == kPivotInv || thisOp == kTransform) + matchesMaya = false; + if (last >= thisOp) + matchesMaya = false; + *output = thisOp; + } + return matchesMaya; } //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/TransformOperation.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/TransformOperation.h index 344bcce2f5..4657957e67 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/TransformOperation.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/TransformOperation.h @@ -35,48 +35,46 @@ namespace usdmaya { //---------------------------------------------------------------------------------------------------------------------- enum TransformOperation : uint8_t { - kTranslate = 0, - kPivot, - kRotatePivotTranslate, - kRotatePivot, - kRotate, - kRotateAxis, - kRotatePivotInv, - kScalePivotTranslate, - kScalePivot, - kShear, - kScale, - kScalePivotInv, - kPivotInv, - kTransform, - kUnknownOp + kTranslate = 0, + kPivot, + kRotatePivotTranslate, + kRotatePivot, + kRotate, + kRotateAxis, + kRotatePivotInv, + kScalePivotTranslate, + kScalePivot, + kShear, + kScale, + kScalePivotInv, + kPivotInv, + kTransform, + kUnknownOp }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief Convert the textual name of a transformation operation into an easier to handle enum value -/// \param opName -/// \return the transform op enum -/// \ingroup usdmaya +/// \brief Convert the textual name of a transformation operation into an easier to handle enum +/// value \param opName \return the transform op enum \ingroup usdmaya //---------------------------------------------------------------------------------------------------------------------- AL_USDMAYA_PUBLIC TransformOperation xformOpToEnum(const std::string& opName); //---------------------------------------------------------------------------------------------------------------------- -/// \brief a function to check to see if the incoming transform operations are compatible with the maya transform +/// \brief a function to check to see if the incoming transform operations are compatible with the +/// maya transform /// types. /// \param it the start of the transform operations /// \param end the end of the transform operations -/// \param output a simpler set of sorted enums, which are used later as a quicker way to index the transform ops. -/// \return true if the type is compatible with maya -/// \ingroup usdmaya +/// \param output a simpler set of sorted enums, which are used later as a quicker way to index the +/// transform ops. \return true if the type is compatible with maya \ingroup usdmaya //---------------------------------------------------------------------------------------------------------------------- AL_USDMAYA_PUBLIC bool matchesMayaProfile( std::vector::const_iterator it, std::vector::const_iterator end, - std::vector::iterator output); + std::vector::iterator output); //---------------------------------------------------------------------------------------------------------------------- -} // usdmaya -} // AL +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/TypeIDs.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/TypeIDs.h index d7c6089bfb..2bb6e9bb76 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/TypeIDs.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/TypeIDs.h @@ -20,23 +20,23 @@ namespace AL { namespace usdmaya { // The type id's for the maya nodes -const MTypeId AL_USDMAYA_PROXYSHAPE (0x00112A20); -const MTypeId AL_USDMAYA_TRANSFORM (0x00112A21); -const MTypeId AL_USDMAYA_TRANSFORMATION_MATRIX (0x00112A22); -const MTypeId AL_USDMAYA_LAYER (0x00112A23); -const MTypeId AL_USDMAYA_STAGEDATA (0x00112A24); -const MTypeId AL_USDMAYA_LAYERMANAGER (0x00112A27); -const MTypeId AL_USDMAYA_RENDERERMANAGER (0x00112A28); -const MTypeId AL_USDMAYA_USDGEOMCAMERAPROXY (0x00112A2B); -const MTypeId AL_USDMAYA_SCOPE (0x00112A31); -const MTypeId AL_USDMAYA_IDENTITY_MATRIX (0x00112A32); +const MTypeId AL_USDMAYA_PROXYSHAPE(0x00112A20); +const MTypeId AL_USDMAYA_TRANSFORM(0x00112A21); +const MTypeId AL_USDMAYA_TRANSFORMATION_MATRIX(0x00112A22); +const MTypeId AL_USDMAYA_LAYER(0x00112A23); +const MTypeId AL_USDMAYA_STAGEDATA(0x00112A24); +const MTypeId AL_USDMAYA_LAYERMANAGER(0x00112A27); +const MTypeId AL_USDMAYA_RENDERERMANAGER(0x00112A28); +const MTypeId AL_USDMAYA_USDGEOMCAMERAPROXY(0x00112A2B); +const MTypeId AL_USDMAYA_SCOPE(0x00112A31); +const MTypeId AL_USDMAYA_IDENTITY_MATRIX(0x00112A32); #if defined(WANT_UFE_BUILD) -const int MAYA_UFE_RUNTIME_ID(1); +const int MAYA_UFE_RUNTIME_ID(1); const char MAYA_UFE_SEPARATOR('|'); -const int USD_UFE_RUNTIME_ID(2); +const int USD_UFE_RUNTIME_ID(2); const char USD_UFE_SEPARATOR('/'); #endif -} // namespace usdmaya -} // namespace AL +} // namespace usdmaya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Version.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Version.h index 40c3ae68e5..95032653c7 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/Version.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/Version.h @@ -17,24 +17,21 @@ #include -#define xstr(a) stringify(a) +#define xstr(a) stringify(a) #define stringify(a) #a #define AL_USDMAYA_VERSION_MAJOR 1 #define AL_USDMAYA_VERSION_MINOR 0 #define AL_USDMAYA_VERSION_PATCH 0 -#define AL_USDMAYA_VERSION_STR xstr(AL_USDMAYA_VERSION_MAJOR) "." \ - xstr(AL_USDMAYA_VERSION_MINOR) "." \ - xstr(AL_USDMAYA_VERSION_PATCH) +#define AL_USDMAYA_VERSION_STR \ + xstr(AL_USDMAYA_VERSION_MAJOR) "." xstr(AL_USDMAYA_VERSION_MINOR) "." xstr( \ + AL_USDMAYA_VERSION_PATCH) namespace AL { namespace usdmaya { -inline const char* getVersion() -{ - return AL_USDMAYA_VERSION_STR; -} +inline const char* getVersion() { return AL_USDMAYA_VERSION_STR; } -} // namespace AL } // namespace usdmaya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/CreateUsdPrim.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/CreateUsdPrim.cpp index 908ae9bd24..3703bb4dc9 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/CreateUsdPrim.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/CreateUsdPrim.cpp @@ -14,14 +14,15 @@ // limitations under the License. // #include "AL/usdmaya/cmds/CreateUsdPrim.h" + #include "AL/usdmaya/nodes/ProxyShape.h" +#include + #include #include #include -#include - namespace AL { namespace usdmaya { namespace cmds { @@ -29,38 +30,30 @@ namespace cmds { //---------------------------------------------------------------------------------------------------------------------- nodes::ProxyShape* getShapeNode(const MArgDatabase& args) { - MSelectionList sl; - args.getObjects(sl); - MDagPath path; - MStatus status = sl.getDagPath(0, path); - if(!status) - { - MGlobal::displayError("Argument is not a proxy shape"); - throw status; - } - - if(path.node().hasFn(MFn::kTransform)) - { - path.extendToShape(); - } - - if(path.node().hasFn(MFn::kPluginShape)) - { - MFnDagNode fn(path); - if(fn.typeId() == nodes::ProxyShape::kTypeId) - { - return (nodes::ProxyShape*)fn.userNode(); + MSelectionList sl; + args.getObjects(sl); + MDagPath path; + MStatus status = sl.getDagPath(0, path); + if (!status) { + MGlobal::displayError("Argument is not a proxy shape"); + throw status; } - else - { - MGlobal::displayError("No usd proxy shape selected"); + + if (path.node().hasFn(MFn::kTransform)) { + path.extendToShape(); + } + + if (path.node().hasFn(MFn::kPluginShape)) { + MFnDagNode fn(path); + if (fn.typeId() == nodes::ProxyShape::kTypeId) { + return (nodes::ProxyShape*)fn.userNode(); + } else { + MGlobal::displayError("No usd proxy shape selected"); + } + } else { + MGlobal::displayError("No usd proxy shape selected"); } - } - else - { - MGlobal::displayError("No usd proxy shape selected"); - } - return 0; + return 0; } //---------------------------------------------------------------------------------------------------------------------- @@ -69,71 +62,63 @@ AL_MAYA_DEFINE_COMMAND(CreateUsdPrim, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax CreateUsdPrim::createSyntax() { - MSyntax syn; - syn.addFlag("-k", "-kind", MSyntax::kString); - syn.addFlag("-h", "-help"); - syn.addArg(MSyntax::kString); - syn.addArg(MSyntax::kString); - syn.useSelectionAsDefault(false); - syn.setObjectType(MSyntax::kSelectionList, 0, 1); - return syn; + MSyntax syn; + syn.addFlag("-k", "-kind", MSyntax::kString); + syn.addFlag("-h", "-help"); + syn.addArg(MSyntax::kString); + syn.addArg(MSyntax::kString); + syn.useSelectionAsDefault(false); + syn.setObjectType(MSyntax::kSelectionList, 0, 1); + return syn; } //---------------------------------------------------------------------------------------------------------------------- MStatus CreateUsdPrim::doIt(const MArgList& args) { - try - { - MStatus status; - MArgDatabase db(syntax(), args, &status); - if(!status) - throw status; - AL_MAYA_COMMAND_HELP(db, g_helpText); - - nodes::ProxyShape* node = getShapeNode(db); - if(!node) - throw MS::kFailure; - - MString primPath, primType, kind; - db.getCommandArgument(0, primPath); - db.getCommandArgument(1, primType); - - if(db.isFlagSet("-k")) - { - db.getFlagArgument("-k", 0, kind); - } - - auto stage = node->usdStage(); - - SdfPath path(primPath.asChar()); - TfToken type(primType.asChar()); - - UsdPrim prim = stage->DefinePrim(path, type); - if(prim) - { - if(kind.length()) - { - UsdModelAPI modelAPI(prim); - modelAPI.SetKind(TfToken(kind.asChar())); - } - setResult(true); + try { + MStatus status; + MArgDatabase db(syntax(), args, &status); + if (!status) + throw status; + AL_MAYA_COMMAND_HELP(db, g_helpText); + + nodes::ProxyShape* node = getShapeNode(db); + if (!node) + throw MS::kFailure; + + MString primPath, primType, kind; + db.getCommandArgument(0, primPath); + db.getCommandArgument(1, primType); + + if (db.isFlagSet("-k")) { + db.getFlagArgument("-k", 0, kind); + } + + auto stage = node->usdStage(); + + SdfPath path(primPath.asChar()); + TfToken type(primType.asChar()); + + UsdPrim prim = stage->DefinePrim(path, type); + if (prim) { + if (kind.length()) { + UsdModelAPI modelAPI(prim); + modelAPI.SetKind(TfToken(kind.asChar())); + } + setResult(true); + } else { + setResult(false); + } + + return MS::kSuccess; + } catch (MStatus status) { + return status; } - else - { - setResult(false); - } - - return MS::kSuccess; - } - catch(MStatus status) - { - return status; - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- -const char* const CreateUsdPrim::g_helpText = R"( +const char* const CreateUsdPrim::g_helpText = R"( AL_usdmaya_CreateUsdPrim Overview: This command allows you to create a new prim of a specific point at a path within the stage represented by a proxy @@ -148,8 +133,7 @@ const char* const CreateUsdPrim::g_helpText = R"( )"; //---------------------------------------------------------------------------------------------------------------------- -} -} -} +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/CreateUsdPrim.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/CreateUsdPrim.h index b272ffbdfa..093ec8c284 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/CreateUsdPrim.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/CreateUsdPrim.h @@ -15,9 +15,10 @@ // #pragma once -#include #include "AL/maya/utils/MayaHelperMacros.h" +#include + namespace AL { namespace usdmaya { namespace cmds { @@ -26,15 +27,15 @@ namespace cmds { /// \brief A command that allows you to register and unregister new Event types from script. /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class CreateUsdPrim - : public MPxCommand +class CreateUsdPrim : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - MStatus doIt(const MArgList& args) override; + MStatus doIt(const MArgList& args) override; }; -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/DebugCommands.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/DebugCommands.cpp index c35fa628b7..46ab3f8ea2 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/DebugCommands.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/DebugCommands.cpp @@ -14,15 +14,16 @@ // limitations under the License. // #include "AL/usdmaya/cmds/DebugCommands.h" -#include "AL/usdmaya/DebugCodes.h" + #include "AL/maya/utils/MenuBuilder.h" +#include "AL/usdmaya/DebugCodes.h" #include -#include -#include #include +#include #include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -35,73 +36,55 @@ AL_MAYA_DEFINE_COMMAND(UsdDebugCommand, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax UsdDebugCommand::createSyntax() { - MSyntax syn; - syn.addFlag("-h", "-help", MSyntax::kNoArg); - syn.addFlag("-ls", "-listSymbols", MSyntax::kNoArg); - syn.addFlag("-en", "-enable", MSyntax::kString); - syn.addFlag("-ds", "-disable", MSyntax::kString); - syn.addFlag("-st", "-state", MSyntax::kString); - return syn; + MSyntax syn; + syn.addFlag("-h", "-help", MSyntax::kNoArg); + syn.addFlag("-ls", "-listSymbols", MSyntax::kNoArg); + syn.addFlag("-en", "-enable", MSyntax::kString); + syn.addFlag("-ds", "-disable", MSyntax::kString); + syn.addFlag("-st", "-state", MSyntax::kString); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -bool UsdDebugCommand::isUndoable() const -{ - return false; -} +bool UsdDebugCommand::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MStatus UsdDebugCommand::doIt(const MArgList& argList) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("AL_usdmaya_UsdDebugCommand::doIt\n"); - try - { - MStatus status; - MArgDatabase args(syntax(), argList, &status); - if(!status) - return status; - - AL_MAYA_COMMAND_HELP(args, g_helpText); - - const bool listSymbols = args.isFlagSet("-ls"); - if(listSymbols) - { - MStringArray returned; - auto symbols = TfDebug::GetDebugSymbolNames(); - for(auto symbol : symbols) - { - returned.append(MString(symbol.c_str(), symbol.size())); - } - setResult(returned); - } - else - if(args.isFlagSet("-en")) - { - MString arg; - args.getFlagArgument("-en", 0, arg); - TfDebug::SetDebugSymbolsByName(arg.asChar(), true); - } - else - if(args.isFlagSet("-ds")) - { - MString arg; - args.getFlagArgument("-ds", 0, arg); - TfDebug::SetDebugSymbolsByName(arg.asChar(), false); - } - else - if(args.isFlagSet("-st")) - { - MString arg; - args.getFlagArgument("-st", 0, arg); - bool state = TfDebug::IsDebugSymbolNameEnabled(arg.asChar()); - setResult(state); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("AL_usdmaya_UsdDebugCommand::doIt\n"); + try { + MStatus status; + MArgDatabase args(syntax(), argList, &status); + if (!status) + return status; + + AL_MAYA_COMMAND_HELP(args, g_helpText); + + const bool listSymbols = args.isFlagSet("-ls"); + if (listSymbols) { + MStringArray returned; + auto symbols = TfDebug::GetDebugSymbolNames(); + for (auto symbol : symbols) { + returned.append(MString(symbol.c_str(), symbol.size())); + } + setResult(returned); + } else if (args.isFlagSet("-en")) { + MString arg; + args.getFlagArgument("-en", 0, arg); + TfDebug::SetDebugSymbolsByName(arg.asChar(), true); + } else if (args.isFlagSet("-ds")) { + MString arg; + args.getFlagArgument("-ds", 0, arg); + TfDebug::SetDebugSymbolsByName(arg.asChar(), false); + } else if (args.isFlagSet("-st")) { + MString arg; + args.getFlagArgument("-st", 0, arg); + bool state = TfDebug::IsDebugSymbolNameEnabled(arg.asChar()); + setResult(state); + } + } catch (const MStatus&) { } - } - catch(const MStatus&) - { - - } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- @@ -193,11 +176,11 @@ global proc AL_usdmaya_debug_gui() //---------------------------------------------------------------------------------------------------------------------- void constructDebugCommandGuis() { - MGlobal::executeCommand(g_usdmaya_debug_gui); - AL::maya::utils::MenuBuilder::addEntry("USD/Debug/TfDebug Options", "AL_usdmaya_debug_gui"); + MGlobal::executeCommand(g_usdmaya_debug_gui); + AL::maya::utils::MenuBuilder::addEntry("USD/Debug/TfDebug Options", "AL_usdmaya_debug_gui"); } -const char* const UsdDebugCommand::g_helpText = R"( +const char* const UsdDebugCommand::g_helpText = R"( AL_usdmaya_UsdDebugCommand Overview: This command allows you to modify the enabled/disabled state of the various TfDebug notifications. To retrieve a @@ -220,7 +203,7 @@ const char* const UsdDebugCommand::g_helpText = R"( )"; //---------------------------------------------------------------------------------------------------------------------- -} -} -} +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/DebugCommands.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/DebugCommands.h index 009cf24bec..378f91e9fc 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/DebugCommands.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/DebugCommands.h @@ -21,7 +21,6 @@ #include - namespace AL { namespace usdmaya { namespace cmds { @@ -30,23 +29,20 @@ namespace cmds { /// \brief A command that allows you to query and modify the current status of the TfDebug symbols. /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class UsdDebugCommand - : public MPxCommand +class UsdDebugCommand : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; /// builds the GUI for the TfDebug notices AL_USDMAYA_PUBLIC void constructDebugCommandGuis(); -} // cmds -} // usdmaya -} // AL - - - +} // namespace cmds +} // namespace usdmaya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/EventCommand.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/EventCommand.cpp index 45b7e80b73..c93bef394f 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/EventCommand.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/EventCommand.cpp @@ -14,7 +14,9 @@ // limitations under the License. // #include "AL/usdmaya/cmds/EventCommand.h" + #include "AL/usdmaya/DebugCodes.h" + #include #include @@ -37,172 +39,161 @@ AL_MAYA_DEFINE_COMMAND(Event, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax Event::createSyntax() { - MSyntax syn; - syn.addFlag("-h", "-help", MSyntax::kString); - syn.addFlag("-d", "-delete"); - syn.addFlag("-p", "-parent", MSyntax::kLong, MSyntax::kLong); - syn.addArg(MSyntax::kString); - syn.useSelectionAsDefault(false); - syn.setObjectType(MSyntax::kSelectionList, 0, 1); - return syn; + MSyntax syn; + syn.addFlag("-h", "-help", MSyntax::kString); + syn.addFlag("-d", "-delete"); + syn.addFlag("-p", "-parent", MSyntax::kLong, MSyntax::kLong); + syn.addArg(MSyntax::kString); + syn.useSelectionAsDefault(false); + syn.setObjectType(MSyntax::kSelectionList, 0, 1); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -bool Event::isUndoable() const -{ - return true; -} +bool Event::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- MStatus Event::doIt(const MArgList& argList) { - try - { - MStatus status; - MArgDatabase db(syntax(), argList, &status); - if(!status) - throw status; - AL_MAYA_COMMAND_HELP(db, g_helpText); - - db.getCommandArgument(0, m_eventName); - - if(db.isFlagSet("-p")) - { - union { - int asInt[2]; - AL::event::CallbackId asId; - }; - db.getFlagArgument("-p", 0, asInt[0]); - db.getFlagArgument("-p", 1, asInt[1]); - m_parentEvent = asId; - } + try { + MStatus status; + MArgDatabase db(syntax(), argList, &status); + if (!status) + throw status; + AL_MAYA_COMMAND_HELP(db, g_helpText); - m_deleting = db.isFlagSet("-d"); - - MSelectionList items; - status = db.getObjects(items); - if(status && items.length()) - { - MObject object; - if(items.getDependNode(0, object)) - { - MFnDependencyNode fn(object); - m_associatedData = dynamic_cast(fn.userNode()); - if(!m_associatedData) - { - MGlobal::displayError(MString("AL_usdmaya_Event, specified node does not support the NodeEvents interface: ") + fn.name()); - return MS::kFailure; - } - AL::event::EventId id = m_associatedData->getId(m_eventName.asChar()); - if(m_deleting && !id) - { - MGlobal::displayError(MString("AL_usdmaya_Event, cannot delete an event that doesn't exist: ") + fn.name()); - return MS::kFailure; + db.getCommandArgument(0, m_eventName); + + if (db.isFlagSet("-p")) { + union + { + int asInt[2]; + AL::event::CallbackId asId; + }; + db.getFlagArgument("-p", 0, asInt[0]); + db.getFlagArgument("-p", 1, asInt[1]); + m_parentEvent = asId; } - if(!m_deleting && id) - { - MGlobal::displayError(MString("AL_usdmaya_Event, specified event already exists on node: ") + fn.name()); - return MS::kFailure; + + m_deleting = db.isFlagSet("-d"); + + MSelectionList items; + status = db.getObjects(items); + if (status && items.length()) { + MObject object; + if (items.getDependNode(0, object)) { + MFnDependencyNode fn(object); + m_associatedData = dynamic_cast(fn.userNode()); + if (!m_associatedData) { + MGlobal::displayError( + MString("AL_usdmaya_Event, specified node does not support the NodeEvents " + "interface: ") + + fn.name()); + return MS::kFailure; + } + AL::event::EventId id = m_associatedData->getId(m_eventName.asChar()); + if (m_deleting && !id) { + MGlobal::displayError( + MString("AL_usdmaya_Event, cannot delete an event that doesn't exist: ") + + fn.name()); + return MS::kFailure; + } + if (!m_deleting && id) { + MGlobal::displayError( + MString("AL_usdmaya_Event, specified event already exists on node: ") + + fn.name()); + return MS::kFailure; + } + } else { + MGlobal::displayError( + "AL_usdmaya_Event, specified node could not be retrieved from selection list."); + return MS::kFailure; + } + } else { + auto event = AL::event::EventScheduler::getScheduler().event(m_eventName.asChar()); + if (m_deleting && !event) { + MGlobal::displayError( + MString("AL_usdmaya_Event, cannot delete an event that doesn't exist: ") + + m_eventName); + return MS::kFailure; + } + if (!m_deleting && event) { + MGlobal::displayError( + MString("AL_usdmaya_Event, specified event already exists on node: ") + + m_eventName); + return MS::kFailure; + } } - } - else - { - MGlobal::displayError("AL_usdmaya_Event, specified node could not be retrieved from selection list."); - return MS::kFailure; - } - } - else - { - auto event = AL::event::EventScheduler::getScheduler().event(m_eventName.asChar()); - if(m_deleting && !event) - { - MGlobal::displayError(MString("AL_usdmaya_Event, cannot delete an event that doesn't exist: ") + m_eventName); - return MS::kFailure; - } - if(!m_deleting && event) - { - MGlobal::displayError(MString("AL_usdmaya_Event, specified event already exists on node: ") + m_eventName); - return MS::kFailure; - } + } catch (MStatus status) { + return status; } - } - catch(MStatus status) - { - return status; - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- MStatus Event::redoIt() { - if(m_associatedData) - { - if(m_deleting) - { - m_associatedData->unregisterEvent(m_eventName.asChar()); - } - else - { - m_associatedData->registerEvent(m_eventName.asChar(), AL::event::kUserSpecifiedEventType, m_parentEvent); - } - } - else - { - if(m_deleting) - { - AL::event::EventScheduler::getScheduler().unregisterEvent(m_eventName.asChar()); - } - else - { - AL::event::EventScheduler::getScheduler().registerEvent(m_eventName.asChar(), AL::event::kUserSpecifiedEventType, m_associatedData, m_parentEvent); + if (m_associatedData) { + if (m_deleting) { + m_associatedData->unregisterEvent(m_eventName.asChar()); + } else { + m_associatedData->registerEvent( + m_eventName.asChar(), AL::event::kUserSpecifiedEventType, m_parentEvent); + } + } else { + if (m_deleting) { + AL::event::EventScheduler::getScheduler().unregisterEvent(m_eventName.asChar()); + } else { + AL::event::EventScheduler::getScheduler().registerEvent( + m_eventName.asChar(), + AL::event::kUserSpecifiedEventType, + m_associatedData, + m_parentEvent); + } } - } - m_deleting = !m_deleting; - return MS::kSuccess; + m_deleting = !m_deleting; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -MStatus Event::undoIt() -{ - return redoIt(); -} +MStatus Event::undoIt() { return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- MStatus BaseCallbackCommand::redoItImplementation() { - AL::event::CallbackIds callbacksToDelete(m_callbacksToInsert.size()); - AL::event::Callbacks callbacksToInsert(m_callbacksToDelete.size()); - - for(size_t i = 0, n = m_callbacksToDelete.size(); i < n; ++i) - { - if(!AL::event::EventScheduler::getScheduler().unregisterCallback(m_callbacksToDelete[i], callbacksToInsert[i])) - { - union { - int32_t asInt[2]; - AL::event::CallbackId asCb; - }; - asCb = m_callbacksToDelete[i]; - MString errorString = "failed to unregister callback with ID: "; - errorString += asInt[0]; - errorString += ' '; - errorString += asInt[1]; - MGlobal::displayError(errorString); + AL::event::CallbackIds callbacksToDelete(m_callbacksToInsert.size()); + AL::event::Callbacks callbacksToInsert(m_callbacksToDelete.size()); + + for (size_t i = 0, n = m_callbacksToDelete.size(); i < n; ++i) { + if (!AL::event::EventScheduler::getScheduler().unregisterCallback( + m_callbacksToDelete[i], callbacksToInsert[i])) { + union + { + int32_t asInt[2]; + AL::event::CallbackId asCb; + }; + asCb = m_callbacksToDelete[i]; + MString errorString = "failed to unregister callback with ID: "; + errorString += asInt[0]; + errorString += ' '; + errorString += asInt[1]; + MGlobal::displayError(errorString); + } } - } - - for(size_t i = 0, n = m_callbacksToInsert.size(); i < n; ++i) - { - callbacksToDelete[i] = AL::event::EventScheduler::getScheduler().registerCallback(m_callbacksToInsert[i]); - if(!callbacksToDelete[i]) - { - MGlobal::displayError(MString("failed to register callback with tag: ") + m_callbacksToInsert[i].tag().c_str()); + + for (size_t i = 0, n = m_callbacksToInsert.size(); i < n; ++i) { + callbacksToDelete[i] + = AL::event::EventScheduler::getScheduler().registerCallback(m_callbacksToInsert[i]); + if (!callbacksToDelete[i]) { + MGlobal::displayError( + MString("failed to register callback with tag: ") + + m_callbacksToInsert[i].tag().c_str()); + } } - } - std::swap(callbacksToDelete, m_callbacksToDelete); - std::swap(callbacksToInsert, m_callbacksToInsert); - return MS::kSuccess; + std::swap(callbacksToDelete, m_callbacksToDelete); + std::swap(callbacksToInsert, m_callbacksToInsert); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- @@ -211,552 +202,477 @@ AL_MAYA_DEFINE_COMMAND(Callback, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax Callback::createSyntax() { - MSyntax syn; - syn.addFlag("-h", "-help", MSyntax::kString); - syn.addFlag("-pe", "-pythonEvent", MSyntax::kString, MSyntax::kString, MSyntax::kUnsigned, MSyntax::kString); - syn.addFlag("-pne", "-pythonNodeEvent", MSyntax::kString, MSyntax::kString, MSyntax::kString, MSyntax::kUnsigned, MSyntax::kString); - syn.addFlag("-me", "-melEvent", MSyntax::kString, MSyntax::kString, MSyntax::kUnsigned, MSyntax::kString); - syn.addFlag("-mne", "-melNodeEvent", MSyntax::kString, MSyntax::kString, MSyntax::kString, MSyntax::kUnsigned, MSyntax::kString); - syn.addFlag("-se", "-supportsEvent", MSyntax::kString); - syn.addFlag("-de", "-deleteEvent", MSyntax::kLong, MSyntax::kLong); - syn.makeFlagMultiUse("-pe"); - syn.makeFlagMultiUse("-pne"); - syn.makeFlagMultiUse("-me"); - syn.makeFlagMultiUse("-mne"); - syn.makeFlagMultiUse("-de"); - return syn; + MSyntax syn; + syn.addFlag("-h", "-help", MSyntax::kString); + syn.addFlag( + "-pe", + "-pythonEvent", + MSyntax::kString, + MSyntax::kString, + MSyntax::kUnsigned, + MSyntax::kString); + syn.addFlag( + "-pne", + "-pythonNodeEvent", + MSyntax::kString, + MSyntax::kString, + MSyntax::kString, + MSyntax::kUnsigned, + MSyntax::kString); + syn.addFlag( + "-me", + "-melEvent", + MSyntax::kString, + MSyntax::kString, + MSyntax::kUnsigned, + MSyntax::kString); + syn.addFlag( + "-mne", + "-melNodeEvent", + MSyntax::kString, + MSyntax::kString, + MSyntax::kString, + MSyntax::kUnsigned, + MSyntax::kString); + syn.addFlag("-se", "-supportsEvent", MSyntax::kString); + syn.addFlag("-de", "-deleteEvent", MSyntax::kLong, MSyntax::kLong); + syn.makeFlagMultiUse("-pe"); + syn.makeFlagMultiUse("-pne"); + syn.makeFlagMultiUse("-me"); + syn.makeFlagMultiUse("-mne"); + syn.makeFlagMultiUse("-de"); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -bool Callback::isUndoable() const -{ - return true; -} +bool Callback::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- MStatus Callback::doIt(const MArgList& argList) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("Callback::doIt\n"); - try - { - MStatus status; - MArgDatabase db(syntax(), argList, &status); - if(!status) - throw status; - AL_MAYA_COMMAND_HELP(db, g_helpText); - - if(db.isFlagSet("se")) - { - MString nodeName; - if(db.getFlagArgument("se", 0, nodeName)) - { - MSelectionList sl; - if(sl.add(nodeName)) - { - MObject node; - sl.getDependNode(0, node); - MFnDependencyNode fn(node, &status); - if(status) - { - if(dynamic_cast(fn.userNode())) - { - setResult(true); - } - else - { - setResult(false); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("Callback::doIt\n"); + try { + MStatus status; + MArgDatabase db(syntax(), argList, &status); + if (!status) + throw status; + AL_MAYA_COMMAND_HELP(db, g_helpText); + + if (db.isFlagSet("se")) { + MString nodeName; + if (db.getFlagArgument("se", 0, nodeName)) { + MSelectionList sl; + if (sl.add(nodeName)) { + MObject node; + sl.getDependNode(0, node); + MFnDependencyNode fn(node, &status); + if (status) { + if (dynamic_cast(fn.userNode())) { + setResult(true); + } else { + setResult(false); + } + } else { + setResult(false); + } + } else { + MGlobal::displayError( + MString("AL_usdmaya_Event, unknown node specified: ") + nodeName); + return MS::kFailure; + } } - } - else - { - setResult(false); - } - } - else - { - MGlobal::displayError(MString("AL_usdmaya_Event, unknown node specified: ") + nodeName); - return MS::kFailure; } - } - } - - MIntArray returnedIds; - auto storeId = [&returnedIds] (const AL::event::CallbackId id) - { - const int* const ptr = (const int*)&id; - returnedIds.append(ptr[0]); - returnedIds.append(ptr[1]); - }; - - for(uint32_t i = 0, n = db.numberOfFlagUses("-pe"); i < n; ++i) - { - MArgList args; - db.getFlagArgumentList("pe", i, args); - MString eventName = args.asString(0); - MString tag = args.asString(1); - unsigned weight = args.asInt(2); - MString commandText = args.asString(3); - - auto cb = AL::event::EventScheduler::getScheduler().buildCallback(eventName.asChar(), tag.asChar(), commandText.asChar(), weight, true); - if(cb.callbackId()) - { - m_callbacksToInsert.push_back(std::move(cb)); - } - storeId(cb.callbackId()); - } - - for(uint32_t i = 0, n = db.numberOfFlagUses("-me"); i < n; ++i) - { - MArgList args; - db.getFlagArgumentList("me", i, args); - MString eventName = args.asString(0); - MString tag = args.asString(1); - unsigned weight = args.asInt(2); - MString commandText = args.asString(3); - - auto cb = AL::event::EventScheduler::getScheduler().buildCallback(eventName.asChar(), tag.asChar(), commandText.asChar(), weight, false); - if(cb.callbackId()) - { - m_callbacksToInsert.push_back(std::move(cb)); - } - storeId(cb.callbackId()); - } + MIntArray returnedIds; + auto storeId = [&returnedIds](const AL::event::CallbackId id) { + const int* const ptr = (const int*)&id; + returnedIds.append(ptr[0]); + returnedIds.append(ptr[1]); + }; - for(uint32_t i = 0, n = db.numberOfFlagUses("-pne"); i < n; ++i) - { - MArgList args; - db.getFlagArgumentList("pne", i, args); - MString nodeName = args.asString(0); - MString eventName = args.asString(1); - MString tag = args.asString(2); - unsigned weight = args.asInt(3); - MString commandText = args.asString(4); - - MSelectionList sl; - if(sl.add(nodeName)) - { - MObject nodeHandle; - sl.getDependNode(0, nodeHandle); - MFnDependencyNode fn(nodeHandle); - - AL::event::NodeEvents* event = dynamic_cast(fn.userNode()); - if(!event) - { - MGlobal::displayError(MString("specified node does not support the NodeEvents interface: ") + nodeName); + for (uint32_t i = 0, n = db.numberOfFlagUses("-pe"); i < n; ++i) { + MArgList args; + db.getFlagArgumentList("pe", i, args); + MString eventName = args.asString(0); + MString tag = args.asString(1); + unsigned weight = args.asInt(2); + MString commandText = args.asString(3); + + auto cb = AL::event::EventScheduler::getScheduler().buildCallback( + eventName.asChar(), tag.asChar(), commandText.asChar(), weight, true); + if (cb.callbackId()) { + m_callbacksToInsert.push_back(std::move(cb)); + } + storeId(cb.callbackId()); } - else - { - AL::event::EventId eventId = event->getId(eventName.asChar()); - if(eventId) - { - auto* scheduler = event->scheduler(); - auto cb = scheduler->buildCallback(eventId, tag.asChar(), commandText.asChar(), weight, true); - if(cb.callbackId()) - { - m_callbacksToInsert.push_back(std::move(cb)); + + for (uint32_t i = 0, n = db.numberOfFlagUses("-me"); i < n; ++i) { + MArgList args; + db.getFlagArgumentList("me", i, args); + MString eventName = args.asString(0); + MString tag = args.asString(1); + unsigned weight = args.asInt(2); + MString commandText = args.asString(3); + + auto cb = AL::event::EventScheduler::getScheduler().buildCallback( + eventName.asChar(), tag.asChar(), commandText.asChar(), weight, false); + if (cb.callbackId()) { + m_callbacksToInsert.push_back(std::move(cb)); } storeId(cb.callbackId()); - continue; - } } - } - storeId(0); - } - for(uint32_t i = 0, n = db.numberOfFlagUses("-mne"); i < n; ++i) - { - MArgList args; - db.getFlagArgumentList("mne", i, args); - MString nodeName = args.asString(0); - MString eventName = args.asString(1); - MString tag = args.asString(2); - unsigned weight = args.asInt(3); - MString commandText = args.asString(4); - - MSelectionList sl; - if(sl.add(nodeName)) - { - MObject nodeHandle; - sl.getDependNode(0, nodeHandle); - MFnDependencyNode fn(nodeHandle); - - AL::event::NodeEvents* event = dynamic_cast(fn.userNode()); - if(!event) - { - MGlobal::displayError(MString("specified node does not support the NodeEvents interface: ") + nodeName); + for (uint32_t i = 0, n = db.numberOfFlagUses("-pne"); i < n; ++i) { + MArgList args; + db.getFlagArgumentList("pne", i, args); + MString nodeName = args.asString(0); + MString eventName = args.asString(1); + MString tag = args.asString(2); + unsigned weight = args.asInt(3); + MString commandText = args.asString(4); + + MSelectionList sl; + if (sl.add(nodeName)) { + MObject nodeHandle; + sl.getDependNode(0, nodeHandle); + MFnDependencyNode fn(nodeHandle); + + AL::event::NodeEvents* event = dynamic_cast(fn.userNode()); + if (!event) { + MGlobal::displayError( + MString("specified node does not support the NodeEvents interface: ") + + nodeName); + } else { + AL::event::EventId eventId = event->getId(eventName.asChar()); + if (eventId) { + auto* scheduler = event->scheduler(); + auto cb = scheduler->buildCallback( + eventId, tag.asChar(), commandText.asChar(), weight, true); + if (cb.callbackId()) { + m_callbacksToInsert.push_back(std::move(cb)); + } + storeId(cb.callbackId()); + continue; + } + } + } + storeId(0); } - else - { - AL::event::EventId eventId = event->getId(eventName.asChar()); - if(eventId) - { - auto* scheduler = event->scheduler(); - auto cb = scheduler->buildCallback(eventId, tag.asChar(), commandText.asChar(), weight, false); - if(cb.callbackId()) - { - m_callbacksToInsert.push_back(std::move(cb)); + + for (uint32_t i = 0, n = db.numberOfFlagUses("-mne"); i < n; ++i) { + MArgList args; + db.getFlagArgumentList("mne", i, args); + MString nodeName = args.asString(0); + MString eventName = args.asString(1); + MString tag = args.asString(2); + unsigned weight = args.asInt(3); + MString commandText = args.asString(4); + + MSelectionList sl; + if (sl.add(nodeName)) { + MObject nodeHandle; + sl.getDependNode(0, nodeHandle); + MFnDependencyNode fn(nodeHandle); + + AL::event::NodeEvents* event = dynamic_cast(fn.userNode()); + if (!event) { + MGlobal::displayError( + MString("specified node does not support the NodeEvents interface: ") + + nodeName); + } else { + AL::event::EventId eventId = event->getId(eventName.asChar()); + if (eventId) { + auto* scheduler = event->scheduler(); + auto cb = scheduler->buildCallback( + eventId, tag.asChar(), commandText.asChar(), weight, false); + if (cb.callbackId()) { + m_callbacksToInsert.push_back(std::move(cb)); + } + storeId(cb.callbackId()); + continue; + } + } } - storeId(cb.callbackId()); - continue; - } + storeId(0); } - } - storeId(0); - } - for(uint32_t i = 0, n = db.numberOfFlagUses("-de"); i < n; ++i) - { - MArgList args; - db.getFlagArgumentList("de", i, args); - union { - int asInt[2]; - AL::event::CallbackId asId; - }; - asInt[0] = args.asInt(0); - asInt[1] = args.asInt(1); - m_callbacksToDelete.push_back(asId); - } + for (uint32_t i = 0, n = db.numberOfFlagUses("-de"); i < n; ++i) { + MArgList args; + db.getFlagArgumentList("de", i, args); + union + { + int asInt[2]; + AL::event::CallbackId asId; + }; + asInt[0] = args.asInt(0); + asInt[1] = args.asInt(1); + m_callbacksToDelete.push_back(asId); + } - setResult(returnedIds); - } - catch(MStatus status) - { - return status; - } - return redoItImplementation(); + setResult(returnedIds); + } catch (MStatus status) { + return status; + } + return redoItImplementation(); } //---------------------------------------------------------------------------------------------------------------------- -MStatus Callback::redoIt() -{ - return redoItImplementation(); -} +MStatus Callback::redoIt() { return redoItImplementation(); } //---------------------------------------------------------------------------------------------------------------------- -MStatus Callback::undoIt() -{ - return redoItImplementation(); -} - +MStatus Callback::undoIt() { return redoItImplementation(); } //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- AL_MAYA_DEFINE_COMMAND(ListEvents, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- -bool ListEvents::isUndoable() const -{ - return false; -} +bool ListEvents::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MSyntax ListEvents::createSyntax() { - MSyntax syntax; - syntax.useSelectionAsDefault(false); - syntax.setObjectType(MSyntax::kSelectionList, 0, 1); - return syntax; + MSyntax syntax; + syntax.useSelectionAsDefault(false); + syntax.setObjectType(MSyntax::kSelectionList, 0, 1); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- MStatus ListEvents::doIt(const MArgList& args) { - MStatus status = MS::kSuccess; - MStringArray eventNames; - try - { - MArgDatabase database(syntax(), args, &status); - if(database.isFlagSet("-h")) - { - return MGlobal::executeCommand("AL_usdmaya_Event -h"); - } + MStatus status = MS::kSuccess; + MStringArray eventNames; + try { + MArgDatabase database(syntax(), args, &status); + if (database.isFlagSet("-h")) { + return MGlobal::executeCommand("AL_usdmaya_Event -h"); + } - if(!status) - { - return status; - } + if (!status) { + return status; + } - MSelectionList items; - status = database.getObjects(items); - if(status && items.length()) - { - MObject objectHandle; - items.getDependNode(0, objectHandle); - - MFnDependencyNode fn(objectHandle, &status); - if(status) - { - MPxNode* ptr = fn.userNode(); - if(ptr) - { - AL::event::NodeEvents* event = dynamic_cast(ptr); - if(event) - { - for(const auto& eventInfo : event->events()) - { - eventNames.append(eventInfo.first.c_str()); + MSelectionList items; + status = database.getObjects(items); + if (status && items.length()) { + MObject objectHandle; + items.getDependNode(0, objectHandle); + + MFnDependencyNode fn(objectHandle, &status); + if (status) { + MPxNode* ptr = fn.userNode(); + if (ptr) { + AL::event::NodeEvents* event = dynamic_cast(ptr); + if (event) { + for (const auto& eventInfo : event->events()) { + eventNames.append(eventInfo.first.c_str()); + } + } + } + } + } else { + for (auto& it : AL::event::EventScheduler::getScheduler().registeredEvents()) { + if (!it.associatedData()) { + eventNames.append(it.name().c_str()); + } } - } - } - } - } - else - { - for(auto& it : AL::event::EventScheduler::getScheduler().registeredEvents()) - { - if(!it.associatedData()) - { - eventNames.append(it.name().c_str()); } - } + } catch (const MStatus&) { } - } - catch(const MStatus&) - { - } - setResult(eventNames); - return status; + setResult(eventNames); + return status; } - //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- AL_MAYA_DEFINE_COMMAND(TriggerEvent, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- -bool TriggerEvent::isUndoable() const -{ - return false; -} +bool TriggerEvent::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MSyntax TriggerEvent::createSyntax() { - MSyntax syntax; - syntax.addFlag("-n", "-node", MSyntax::kString); - syntax.addArg(MSyntax::kString); - return syntax; + MSyntax syntax; + syntax.addFlag("-n", "-node", MSyntax::kString); + syntax.addArg(MSyntax::kString); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- MStatus TriggerEvent::doIt(const MArgList& args) { - MStatus status = MS::kSuccess; - MStringArray eventNames; - try - { - MArgDatabase database(syntax(), args, &status); - if(!status) - return status; - - MString nodeName, eventName; - database.getCommandArgument(0, eventName); - - bool nodeSpecified = database.isFlagSet("-n"); - if(nodeSpecified) - { - database.getFlagArgument("-n", 0, nodeName); - - MSelectionList items; - items.add(nodeName); - MObject objectHandle; - items.getDependNode(0, objectHandle); - - MFnDependencyNode fn(objectHandle, &status); - if(status) - { - MPxNode* ptr = fn.userNode(); - if(ptr) - { - AL::event::NodeEvents* event = dynamic_cast(ptr); - if(event) - { - setResult(event->triggerEvent(eventName.asChar())); - } - else - { - MGlobal::displayError(MString("specified node does not support events: ") + nodeName); + MStatus status = MS::kSuccess; + MStringArray eventNames; + try { + MArgDatabase database(syntax(), args, &status); + if (!status) return status; - } - } - else - { - MGlobal::displayError(MString("specified node does not support events: ") + nodeName); - return status; + + MString nodeName, eventName; + database.getCommandArgument(0, eventName); + + bool nodeSpecified = database.isFlagSet("-n"); + if (nodeSpecified) { + database.getFlagArgument("-n", 0, nodeName); + + MSelectionList items; + items.add(nodeName); + MObject objectHandle; + items.getDependNode(0, objectHandle); + + MFnDependencyNode fn(objectHandle, &status); + if (status) { + MPxNode* ptr = fn.userNode(); + if (ptr) { + AL::event::NodeEvents* event = dynamic_cast(ptr); + if (event) { + setResult(event->triggerEvent(eventName.asChar())); + } else { + MGlobal::displayError( + MString("specified node does not support events: ") + nodeName); + return status; + } + } else { + MGlobal::displayError( + MString("specified node does not support events: ") + nodeName); + return status; + } + } else { + MGlobal::displayError( + MString("failed to attach function set to node: ") + nodeName); + return status; + } + } else { + setResult(AL::event::EventScheduler::getScheduler().triggerEvent(eventName.asChar())); } - } - else - { - MGlobal::displayError(MString("failed to attach function set to node: ") + nodeName); - return status; - } - } - else - { - setResult(AL::event::EventScheduler::getScheduler().triggerEvent(eventName.asChar())); + } catch (const MStatus&) { } - } - catch(const MStatus&) - { - } - setResult(eventNames); - return status; + setResult(eventNames); + return status; } - //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- AL_MAYA_DEFINE_COMMAND(DeleteCallbacks, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- -bool DeleteCallbacks::isUndoable() const -{ - return true; -} +bool DeleteCallbacks::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- -MSyntax DeleteCallbacks::createSyntax() -{ - return MSyntax(); -} +MSyntax DeleteCallbacks::createSyntax() { return MSyntax(); } //---------------------------------------------------------------------------------------------------------------------- MStatus DeleteCallbacks::doIt(const MArgList& args) { - for(uint32_t i = 0, n = args.length(); i < n; ++i) - { - MStatus status; - MIntArray items = args.asIntArray(i, &status); - if(status && (items.length() & 1) == 0) - { - union - { - int asint[2]; - AL::event::CallbackId asid; - }; - for(uint32_t j = 0, m = items.length(); j < m; j += 2) - { - asint[0] = items[j]; - asint[1] = items[j + 1]; - m_callbacksToDelete.push_back(asid); - } - } - else - { - MGlobal::displayError("AL_usdmaya_DeleteEvents: failed to parse input callback IDs"); - return MS::kFailure; + for (uint32_t i = 0, n = args.length(); i < n; ++i) { + MStatus status; + MIntArray items = args.asIntArray(i, &status); + if (status && (items.length() & 1) == 0) { + union + { + int asint[2]; + AL::event::CallbackId asid; + }; + for (uint32_t j = 0, m = items.length(); j < m; j += 2) { + asint[0] = items[j]; + asint[1] = items[j + 1]; + m_callbacksToDelete.push_back(asid); + } + } else { + MGlobal::displayError("AL_usdmaya_DeleteEvents: failed to parse input callback IDs"); + return MS::kFailure; + } } - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- -MStatus DeleteCallbacks::undoIt() -{ - return redoItImplementation(); -} +MStatus DeleteCallbacks::undoIt() { return redoItImplementation(); } //---------------------------------------------------------------------------------------------------------------------- -MStatus DeleteCallbacks::redoIt() -{ - return redoItImplementation(); -} +MStatus DeleteCallbacks::redoIt() { return redoItImplementation(); } //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- AL_MAYA_DEFINE_COMMAND(ListCallbacks, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- -bool ListCallbacks::isUndoable() const -{ - return false; -} +bool ListCallbacks::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MSyntax ListCallbacks::createSyntax() { - MSyntax syntax; - syntax.addArg(MSyntax::kString); - syntax.useSelectionAsDefault(false); - syntax.setObjectType(MSyntax::kSelectionList, 0, 1); - return syntax; + MSyntax syntax; + syntax.addArg(MSyntax::kString); + syntax.useSelectionAsDefault(false); + syntax.setObjectType(MSyntax::kSelectionList, 0, 1); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- MStatus ListCallbacks::doIt(const MArgList& args) { - MStatus status = MS::kSuccess; - try - { - MArgDatabase database(syntax(), args, &status); - if(!status) - { - return status; - } - MString eventName; - database.getCommandArgument(0, eventName); - - MSelectionList items; - status = database.getObjects(items); - if(status && items.length()) - { - MObject objectHandle; - items.getDependNode(0, objectHandle); - - MIntArray callbacks; - MFnDependencyNode fn(objectHandle, &status); - if(status) - { - MPxNode* ptr = fn.userNode(); - if(ptr) - { - AL::event::NodeEvents* event = dynamic_cast(ptr); - if(event) - { - const auto it = event->scheduler()->event(eventName.asChar()); - if(it) - { - for(const auto& eventInfo : it->callbacks()) - { - union { - int ii[2]; - AL::event::CallbackId id; - }; - id = eventInfo.callbackId(); - callbacks.append(ii[0]); - callbacks.append(ii[1]); - } - } - } + MStatus status = MS::kSuccess; + try { + MArgDatabase database(syntax(), args, &status); + if (!status) { + return status; } - } - setResult(callbacks); - } - else - { - MIntArray callbacks; - auto eventHandler = AL::event::EventScheduler::getScheduler().event(eventName.asChar()); - if(eventHandler) - { - for(const auto& eventInfo : eventHandler->callbacks()) - { - union { - int ii[2]; - AL::event::CallbackId id; - }; - id = eventInfo.callbackId(); - callbacks.append(ii[0]); - callbacks.append(ii[1]); + MString eventName; + database.getCommandArgument(0, eventName); + + MSelectionList items; + status = database.getObjects(items); + if (status && items.length()) { + MObject objectHandle; + items.getDependNode(0, objectHandle); + + MIntArray callbacks; + MFnDependencyNode fn(objectHandle, &status); + if (status) { + MPxNode* ptr = fn.userNode(); + if (ptr) { + AL::event::NodeEvents* event = dynamic_cast(ptr); + if (event) { + const auto it = event->scheduler()->event(eventName.asChar()); + if (it) { + for (const auto& eventInfo : it->callbacks()) { + union + { + int ii[2]; + AL::event::CallbackId id; + }; + id = eventInfo.callbackId(); + callbacks.append(ii[0]); + callbacks.append(ii[1]); + } + } + } + } + } + setResult(callbacks); + } else { + MIntArray callbacks; + auto eventHandler = AL::event::EventScheduler::getScheduler().event(eventName.asChar()); + if (eventHandler) { + for (const auto& eventInfo : eventHandler->callbacks()) { + union + { + int ii[2]; + AL::event::CallbackId id; + }; + id = eventInfo.callbackId(); + callbacks.append(ii[0]); + callbacks.append(ii[1]); + } + } + setResult(callbacks); } - } - setResult(callbacks); + } catch (const MStatus&) { } - } - catch(const MStatus&) - { - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- @@ -766,75 +682,60 @@ AL_MAYA_DEFINE_COMMAND(EventLookup, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax EventLookup::createSyntax() { - MSyntax syntax; - syntax.addFlag("-h", "-help"); - syntax.addFlag("-n", "-name"); - syntax.addFlag("-nd", "-node"); - syntax.addArg(MSyntax::kLong); - return syntax; + MSyntax syntax; + syntax.addFlag("-h", "-help"); + syntax.addFlag("-n", "-name"); + syntax.addFlag("-nd", "-node"); + syntax.addArg(MSyntax::kLong); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- MStatus EventLookup::doIt(const MArgList& args) { - MStatus status = MS::kSuccess; - MStringArray eventNames; - try - { - MArgDatabase database(syntax(), args, &status); - if(!status) - return status; - AL_MAYA_COMMAND_HELP(database, g_helpText); - - int eventId = 0; - if(!database.getCommandArgument(0, eventId)) - { - return MS::kFailure; - } + MStatus status = MS::kSuccess; + MStringArray eventNames; + try { + MArgDatabase database(syntax(), args, &status); + if (!status) + return status; + AL_MAYA_COMMAND_HELP(database, g_helpText); - AL::event::EventDispatcher* dispatcher = AL::event::EventScheduler::getScheduler().event(eventId); - if(dispatcher) - { - if(database.isFlagSet("-n")) - { - setResult(dispatcher->name().c_str()); - } - else - if(database.isFlagSet("-nd")) - { - MString nodeName = ""; - AL::event::NodeEvents* node = (AL::event::NodeEvents*)dispatcher->associatedData(); - if(node) - { - MPxNode* mpxNode = dynamic_cast(node); - if(mpxNode) - { - MFnDependencyNode fn(mpxNode->thisMObject()); - nodeName = fn.name(); - } + int eventId = 0; + if (!database.getCommandArgument(0, eventId)) { + return MS::kFailure; + } + + AL::event::EventDispatcher* dispatcher + = AL::event::EventScheduler::getScheduler().event(eventId); + if (dispatcher) { + if (database.isFlagSet("-n")) { + setResult(dispatcher->name().c_str()); + } else if (database.isFlagSet("-nd")) { + MString nodeName = ""; + AL::event::NodeEvents* node = (AL::event::NodeEvents*)dispatcher->associatedData(); + if (node) { + MPxNode* mpxNode = dynamic_cast(node); + if (mpxNode) { + MFnDependencyNode fn(mpxNode->thisMObject()); + nodeName = fn.name(); + } + } + setResult(nodeName); + } else { + MGlobal::displayError("AL_usdmaya_EventLookup: no flag specified"); + return MS::kFailure; + } + } else { + MGlobal::displayError("AL_usdmaya_EventLookup: invalid event specified"); + return MS::kFailure; } - setResult(nodeName); - } - else - { - MGlobal::displayError("AL_usdmaya_EventLookup: no flag specified"); + } catch (...) { return MS::kFailure; - } - } - else - { - MGlobal::displayError("AL_usdmaya_EventLookup: invalid event specified"); - return MS::kFailure; } - } - catch(...) - { - return MS::kFailure; - } - return MS::kSuccess; + return MS::kSuccess; } - //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- AL_MAYA_DEFINE_COMMAND(EventQuery, AL_usdmaya); @@ -842,90 +743,74 @@ AL_MAYA_DEFINE_COMMAND(EventQuery, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax EventQuery::createSyntax() { - MSyntax syntax; - syntax.addFlag("-h", "-help"); - syntax.addFlag("-e", "-eventId"); - syntax.addFlag("-p", "-parentId"); - syntax.addArg(MSyntax::kString); - syntax.useSelectionAsDefault(false); - syntax.setObjectType(MSyntax::kSelectionList, 0, 1); - return syntax; + MSyntax syntax; + syntax.addFlag("-h", "-help"); + syntax.addFlag("-e", "-eventId"); + syntax.addFlag("-p", "-parentId"); + syntax.addArg(MSyntax::kString); + syntax.useSelectionAsDefault(false); + syntax.setObjectType(MSyntax::kSelectionList, 0, 1); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- MStatus EventQuery::doIt(const MArgList& args) { - MStatus status = MS::kSuccess; - MStringArray eventNames; - try - { - MArgDatabase database(syntax(), args, &status); - if(!status) - return status; - AL_MAYA_COMMAND_HELP(database, g_helpText); - - MString eventName; - if(!database.getCommandArgument(0, eventName)) - { - return MS::kFailure; - } + MStatus status = MS::kSuccess; + MStringArray eventNames; + try { + MArgDatabase database(syntax(), args, &status); + if (!status) + return status; + AL_MAYA_COMMAND_HELP(database, g_helpText); - AL::event::EventDispatcher* dispatcher = 0; - - MSelectionList items; - status = database.getObjects(items); - if(status && items.length()) - { - MObject obj; - items.getDependNode(0, obj); - AL::event::NodeEvents* handler = dynamic_cast(MFnDependencyNode(obj).userNode()); - if(handler) - { - AL::event::EventId eventId = handler->getId(eventName.asChar()); - dispatcher = handler->scheduler()->event(eventId); - } - } - else - { - dispatcher = AL::event::EventScheduler::getScheduler().event(eventName.asChar()); - } + MString eventName; + if (!database.getCommandArgument(0, eventName)) { + return MS::kFailure; + } - if(dispatcher) - { - if(database.isFlagSet("-p")) - { - union - { - AL::event::CallbackId id; - int asInt[2]; - }; - id = dispatcher->parentCallbackId(); - appendToResult(asInt[0]); - appendToResult(asInt[1]); - } - else - if(database.isFlagSet("-e")) - { - AL::event::EventId eventId = dispatcher->eventId(); - setResult(eventId); - } - else - { - MGlobal::displayError("AL_usdmaya_EventQuery: no flag specified"); + AL::event::EventDispatcher* dispatcher = 0; + + MSelectionList items; + status = database.getObjects(items); + if (status && items.length()) { + MObject obj; + items.getDependNode(0, obj); + AL::event::NodeEvents* handler + = dynamic_cast(MFnDependencyNode(obj).userNode()); + if (handler) { + AL::event::EventId eventId = handler->getId(eventName.asChar()); + dispatcher = handler->scheduler()->event(eventId); + } + } else { + dispatcher = AL::event::EventScheduler::getScheduler().event(eventName.asChar()); + } + + if (dispatcher) { + if (database.isFlagSet("-p")) { + union + { + AL::event::CallbackId id; + int asInt[2]; + }; + id = dispatcher->parentCallbackId(); + appendToResult(asInt[0]); + appendToResult(asInt[1]); + } else if (database.isFlagSet("-e")) { + AL::event::EventId eventId = dispatcher->eventId(); + setResult(eventId); + } else { + MGlobal::displayError("AL_usdmaya_EventQuery: no flag specified"); + return MS::kFailure; + } + } else { + MGlobal::displayError("AL_usdmaya_EventQuery: invalid event specified"); + return MS::kFailure; + } + } catch (...) { return MS::kFailure; - } - } - else - { - MGlobal::displayError("AL_usdmaya_EventQuery: invalid event specified"); - return MS::kFailure; } - } - catch(...) - { - return MS::kFailure; - } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- @@ -933,144 +818,113 @@ MStatus EventQuery::doIt(const MArgList& args) AL_MAYA_DEFINE_COMMAND(CallbackQuery, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- -bool CallbackQuery::isUndoable() const -{ - return false; -} +bool CallbackQuery::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MSyntax CallbackQuery::createSyntax() { - MSyntax syntax; - syntax.addFlag("-h", "-help"); - syntax.addFlag("-e", "-eventId"); - syntax.addFlag("-u", "-userData"); - syntax.addFlag("-et", "-eventTag"); - syntax.addFlag("-ty", "-type"); - syntax.addFlag("-w", "-weight"); - syntax.addFlag("-c", "-command"); - syntax.addFlag("-fp", "-functionPointer"); - syntax.addFlag("-ce", "-childEvents"); - syntax.addArg(MSyntax::kLong); - syntax.addArg(MSyntax::kLong); - return syntax; + MSyntax syntax; + syntax.addFlag("-h", "-help"); + syntax.addFlag("-e", "-eventId"); + syntax.addFlag("-u", "-userData"); + syntax.addFlag("-et", "-eventTag"); + syntax.addFlag("-ty", "-type"); + syntax.addFlag("-w", "-weight"); + syntax.addFlag("-c", "-command"); + syntax.addFlag("-fp", "-functionPointer"); + syntax.addFlag("-ce", "-childEvents"); + syntax.addArg(MSyntax::kLong); + syntax.addArg(MSyntax::kLong); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- MStatus CallbackQuery::doIt(const MArgList& args) { - MStatus status = MS::kSuccess; - MStringArray eventNames; - try - { - MArgDatabase database(syntax(), args, &status); - if(!status) - return status; - AL_MAYA_COMMAND_HELP(database, g_helpText); - - union { - int asint[2]; - AL::event::CallbackId asCb; - }; - - if(!database.getCommandArgument(0, asint[0]) || - !database.getCommandArgument(1, asint[1])) - { - return MS::kFailure; - } + MStatus status = MS::kSuccess; + MStringArray eventNames; + try { + MArgDatabase database(syntax(), args, &status); + if (!status) + return status; + AL_MAYA_COMMAND_HELP(database, g_helpText); - auto event = AL::event::EventScheduler::getScheduler().findCallback(asCb); - if(event) - { - auto writeHex = [](const uint8_t b[8]) - { - MString text = "0x"; - const char* const hex = "0123456789ABCDEF"; - for(int i = 0; i < 8; ++i) + union { - const uint8_t c = b[i]; - text += hex[(c >> 4) & 0xF]; - text += hex[c & 0xF]; + int asint[2]; + AL::event::CallbackId asCb; + }; + + if (!database.getCommandArgument(0, asint[0]) + || !database.getCommandArgument(1, asint[1])) { + return MS::kFailure; } - return text; - }; - - if(database.isFlagSet("-ce")) - { - MIntArray events; - const AL::event::EventScheduler& scheduler = AL::event::EventScheduler::getScheduler(); - for(auto& e : scheduler.registeredEvents()) - { - if(e.parentCallbackId() == asCb) - { - events.append(e.eventId()); - } + + auto event = AL::event::EventScheduler::getScheduler().findCallback(asCb); + if (event) { + auto writeHex = [](const uint8_t b[8]) { + MString text = "0x"; + const char* const hex = "0123456789ABCDEF"; + for (int i = 0; i < 8; ++i) { + const uint8_t c = b[i]; + text += hex[(c >> 4) & 0xF]; + text += hex[c & 0xF]; + } + return text; + }; + + if (database.isFlagSet("-ce")) { + MIntArray events; + const AL::event::EventScheduler& scheduler + = AL::event::EventScheduler::getScheduler(); + for (auto& e : scheduler.registeredEvents()) { + if (e.parentCallbackId() == asCb) { + events.append(e.eventId()); + } + } + setResult(events); + } else if (database.isFlagSet("-e")) { + AL::event::EventId id = event->eventId(); + setResult(int(id)); + } else if (database.isFlagSet("-et")) { + setResult(event->tag().c_str()); + } else if (database.isFlagSet("-ty")) { + if (event->isPythonCallback()) + setResult("Python"); + else if (event->isPythonCallback()) + setResult("MEL"); + else + setResult("C"); + } else if (database.isFlagSet("-w")) { + setResult(int(event->weight())); + } else if (database.isFlagSet("-c")) { + setResult(event->callbackText()); + } else if (database.isFlagSet("-fp")) { + union + { + uint8_t b[8]; + const void* p; + }; + p = event->callback(); + setResult(writeHex(b)); + } else if (database.isFlagSet("-u")) { + union + { + uint8_t b[8]; + const void* p; + }; + p = event->userData(); + setResult(writeHex(b)); + } } - setResult(events); - } - else - if(database.isFlagSet("-e")) - { - AL::event::EventId id = event->eventId(); - setResult(int(id)); - } - else - if(database.isFlagSet("-et")) - { - setResult(event->tag().c_str()); - } - else - if(database.isFlagSet("-ty")) - { - if(event->isPythonCallback()) - setResult("Python"); - else - if(event->isPythonCallback()) - setResult("MEL"); - else - setResult("C"); - } - else - if(database.isFlagSet("-w")) - { - setResult(int(event->weight())); - } - else - if(database.isFlagSet("-c")) - { - setResult(event->callbackText()); - } - else - if(database.isFlagSet("-fp")) - { - union { - uint8_t b[8]; - const void* p; - }; - p = event->callback(); - setResult(writeHex(b)); - } - else - if(database.isFlagSet("-u")) - { - union { - uint8_t b[8]; - const void* p; - }; - p = event->userData(); - setResult(writeHex(b)); - } + } catch (...) { + return MS::kFailure; } - } - catch(...) - { - return MS::kFailure; - } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -const char* const Event::g_helpText = R"( +const char* const Event::g_helpText = R"( AL_usdmaya_Event Overview: This command allows the ability to register / unregister new events. @@ -1135,19 +989,19 @@ Parent Events )"; //---------------------------------------------------------------------------------------------------------------------- -const char* const EventQuery::g_helpText = R"( +const char* const EventQuery::g_helpText = R"( AL_usdmaya_EventQuery Overview: )"; //---------------------------------------------------------------------------------------------------------------------- -const char* const EventLookup::g_helpText = R"( +const char* const EventLookup::g_helpText = R"( AL_usdmaya_EventLookup Overview: )"; //---------------------------------------------------------------------------------------------------------------------- -const char* const CallbackQuery::g_helpText = R"( +const char* const CallbackQuery::g_helpText = R"( AL_usdmaya_CallbackQuery Overview: Given the 2 integer identifier for a callback, this command can return some information about that callback. e.g. @@ -1170,7 +1024,7 @@ const char* const CallbackQuery::g_helpText = R"( )"; //---------------------------------------------------------------------------------------------------------------------- -const char* const Callback::g_helpText = R"( +const char* const Callback::g_helpText = R"( AL_usdmaya_Callback Overview: This command allows the user the ability to create and destroy callbacks that will be triggered during certain @@ -1285,10 +1139,8 @@ multi use for all these flags is to allow you to do a one hit creation of all ev )"; - //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/EventCommand.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/EventCommand.h index d009d56e42..aa27b4e98d 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/EventCommand.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/EventCommand.h @@ -15,123 +15,127 @@ // #pragma once - -#include #include "AL/event/EventHandler.h" #include "AL/maya/utils/MayaHelperMacros.h" +#include + namespace AL { namespace usdmaya { namespace cmds { //---------------------------------------------------------------------------------------------------------------------- -/// \brief The base class for all commands that need to create/delete callbacks in some way. Fill m_callbacksToDelete -/// with the CallbackIds you want to delete, and fill the m_callbacksToInsert array with the callbacks returned -/// from AL::AL::event::EventScheduler::buildCallback. Within the undo/redo implementation of a mel command, simply -/// call redoItImplementation. This method will destroy the callbacks requested, and insert the created callbacks. -/// Once called, the values of the m_callbacksToDelete and m_callbacksToInsert will be swapped, therefore calling -/// redoItImplementation again will undo the previous action. +/// \brief The base class for all commands that need to create/delete callbacks in some way. Fill +/// m_callbacksToDelete +/// with the CallbackIds you want to delete, and fill the m_callbacksToInsert array with the +/// callbacks returned from AL::AL::event::EventScheduler::buildCallback. Within the +/// undo/redo implementation of a mel command, simply call redoItImplementation. This method +/// will destroy the callbacks requested, and insert the created callbacks. Once called, the +/// values of the m_callbacksToDelete and m_callbacksToInsert will be swapped, therefore +/// calling redoItImplementation again will undo the previous action. /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- struct BaseCallbackCommand { - /// call within both the undo and redo methods - MStatus redoItImplementation(); - /// the callback ids that need to be deleted - std::vector m_callbacksToDelete; - /// the callback structures generated from EventScheduler::buildCallback - AL::event::Callbacks m_callbacksToInsert; + /// call within both the undo and redo methods + MStatus redoItImplementation(); + /// the callback ids that need to be deleted + std::vector m_callbacksToDelete; + /// the callback structures generated from EventScheduler::buildCallback + AL::event::Callbacks m_callbacksToInsert; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief A command that allows you to register and unregister new Event types from script. /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class Event - : public MPxCommand +class Event : public MPxCommand { - MString m_eventName; - AL::event::NodeEvents* m_associatedData = 0; - AL::event::CallbackId m_parentEvent = 0; - bool m_deleting = false; + MString m_eventName; + AL::event::NodeEvents* m_associatedData = 0; + AL::event::CallbackId m_parentEvent = 0; + bool m_deleting = false; + public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; - MStatus redoIt() override; - MStatus undoIt() override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; + MStatus redoIt() override; + MStatus undoIt() override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief A command that allows you to query information about a specific event /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class EventQuery - : public MPxCommand +class EventQuery : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - MStatus doIt(const MArgList& args) override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief A command that allows you to query information about an event /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class EventLookup - : public MPxCommand +class EventLookup : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - MStatus doIt(const MArgList& args) override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief A command that allows you to create / delete callbacks assigned to a specific event within AL_usdmaya -/// \ingroup commands +/// \brief A command that allows you to create / delete callbacks assigned to a specific event +/// within AL_usdmaya \ingroup commands //---------------------------------------------------------------------------------------------------------------------- class Callback - : public MPxCommand, - public BaseCallbackCommand + : public MPxCommand + , public BaseCallbackCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; - MStatus redoIt() override; - MStatus undoIt() override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; + MStatus redoIt() override; + MStatus undoIt() override; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief A command that lists the events available on either a particular node, or the global set of events -/// \ingroup commands +/// \brief A command that lists the events available on either a particular node, or the global set +/// of events \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ListEvents - : public MPxCommand +class ListEvents : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief A command that will trigger all callbacks on an event /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class TriggerEvent - : public MPxCommand +class TriggerEvent : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- @@ -139,54 +143,52 @@ class TriggerEvent /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- class DeleteCallbacks - : public MPxCommand, - public BaseCallbackCommand + : public MPxCommand + , public BaseCallbackCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; - MStatus redoIt() override; - MStatus undoIt() override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; + MStatus redoIt() override; + MStatus undoIt() override; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief A command that lists the events available on either a particular node, or the global set of events -/// \ingroup commands +/// \brief A command that lists the events available on either a particular node, or the global set +/// of events \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ListCallbacks - : public MPxCommand +class ListCallbacks : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief A command that lists the events available on either a particular node, or the global set of events -/// \ingroup commands +/// \brief A command that lists the events available on either a particular node, or the global set +/// of events \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class CallbackQuery - : public MPxCommand +class CallbackQuery : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; /// builds the GUI for the TfDebug notices extern void constructEventCommandGuis(); //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - - - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/LayerCommands.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/LayerCommands.cpp index 50f32dea14..5a2ecb83c0 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/LayerCommands.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/LayerCommands.cpp @@ -14,9 +14,10 @@ // limitations under the License. // #include "AL/usdmaya/cmds/LayerCommands.h" -#include "AL/usdmaya/DebugCodes.h" -#include "AL/maya/utils/Utils.h" + #include "AL/maya/utils/CommandGuiHelper.h" +#include "AL/maya/utils/Utils.h" +#include "AL/usdmaya/DebugCodes.h" #include "AL/usdmaya/nodes/LayerManager.h" #include "AL/usdmaya/nodes/ProxyShape.h" #include "AL/usdmaya/nodes/Transform.h" @@ -30,81 +31,72 @@ #include #include #include -#include namespace { - AL::usdmaya::nodes::ProxyShape* getProxyShapeFromSel(const MSelectionList& sl) - { - auto getShapePtr = [](const MObject& mobj, MFnDagNode& fnDag) - ->AL::usdmaya::nodes::ProxyShape* - { - if(mobj.hasFn(MFn::kPluginShape)) - { - fnDag.setObject(mobj); - if(fnDag.typeId() == AL::usdmaya::nodes::ProxyShape::kTypeId) - { - return (AL::usdmaya::nodes::ProxyShape*)fnDag.userNode(); +AL::usdmaya::nodes::ProxyShape* getProxyShapeFromSel(const MSelectionList& sl) +{ + auto getShapePtr + = [](const MObject& mobj, MFnDagNode& fnDag) -> AL::usdmaya::nodes::ProxyShape* { + if (mobj.hasFn(MFn::kPluginShape)) { + fnDag.setObject(mobj); + if (fnDag.typeId() == AL::usdmaya::nodes::ProxyShape::kTypeId) { + return (AL::usdmaya::nodes::ProxyShape*)fnDag.userNode(); + } } - } - return nullptr; + return nullptr; }; AL::usdmaya::nodes::ProxyShape* foundShape = nullptr; - MDagPath path; + MDagPath path; const uint32_t selLength = sl.length(); - for(uint32_t i = 0; i < selLength ; ++i) - { - MStatus status = sl.getDagPath(i, path); - if(status != MS::kSuccess) continue; - - MFnDagNode fn(path); - - if(path.node().hasFn(MFn::kTransform)) - { - if(fn.typeId() == AL::usdmaya::nodes::Transform::kTypeId || - fn.typeId() == AL::usdmaya::nodes::Scope::kTypeId) - { - auto transform = (AL::usdmaya::nodes::Scope*)fn.userNode(); - if(transform) - { - MPlug sourcePlug = transform->inStageDataPlug().source(); - foundShape = getShapePtr(sourcePlug.node(), fn); - if (foundShape) return foundShape; - } - else - { - MGlobal::displayError(MString("Error getting Transform pointer for ") - + fn.partialPathName()); - return nullptr; - } - // If we have an AL_usdmaya_ProxyShapeTransform, but it wasn't hooked - // up to a ProxyShape, just continue to the next selection item - continue; - } - else - { - // If it's a "normal" xform, search all shapes directly below - unsigned int numShapes; - AL_MAYA_CHECK_ERROR_RETURN_VAL(path.numberOfShapesDirectlyBelow(numShapes), - nullptr, "Error getting number of shapes beneath " + path.partialPathName()); - for(unsigned int i = 0; i < numShapes; path.pop(), ++i) - { - path.extendToShapeDirectlyBelow(i); + for (uint32_t i = 0; i < selLength; ++i) { + MStatus status = sl.getDagPath(i, path); + if (status != MS::kSuccess) + continue; + + MFnDagNode fn(path); + + if (path.node().hasFn(MFn::kTransform)) { + if (fn.typeId() == AL::usdmaya::nodes::Transform::kTypeId + || fn.typeId() == AL::usdmaya::nodes::Scope::kTypeId) { + auto transform = (AL::usdmaya::nodes::Scope*)fn.userNode(); + if (transform) { + MPlug sourcePlug = transform->inStageDataPlug().source(); + foundShape = getShapePtr(sourcePlug.node(), fn); + if (foundShape) + return foundShape; + } else { + MGlobal::displayError( + MString("Error getting Transform pointer for ") + fn.partialPathName()); + return nullptr; + } + // If we have an AL_usdmaya_ProxyShapeTransform, but it wasn't hooked + // up to a ProxyShape, just continue to the next selection item + continue; + } else { + // If it's a "normal" xform, search all shapes directly below + unsigned int numShapes; + AL_MAYA_CHECK_ERROR_RETURN_VAL( + path.numberOfShapesDirectlyBelow(numShapes), + nullptr, + "Error getting number of shapes beneath " + path.partialPathName()); + for (unsigned int i = 0; i < numShapes; path.pop(), ++i) { + path.extendToShapeDirectlyBelow(i); + foundShape = getShapePtr(path.node(), fn); + if (foundShape) + return foundShape; + } + } + } else { foundShape = getShapePtr(path.node(), fn); - if(foundShape) return foundShape; - } + if (foundShape) + return foundShape; } - } - else - { - foundShape = getShapePtr(path.node(), fn); - if(foundShape) return foundShape; - } } return nullptr; - } } +} // namespace namespace AL { namespace usdmaya { @@ -112,85 +104,74 @@ namespace cmds { //---------------------------------------------------------------------------------------------------------------------- MSyntax LayerCommandBase::setUpCommonSyntax() { - MSyntax syntax; - syntax.addFlag("-p", "-proxy", MSyntax::kString); - return syntax; + MSyntax syntax; + syntax.addFlag("-p", "-proxy", MSyntax::kString); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- nodes::ProxyShape* LayerCommandBase::getShapeNode(const MArgDatabase& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCommandBase::getShapeNode\n"); - MDagPath path; - MSelectionList sl; - args.getObjects(sl); - - const uint32_t selLength = sl.length(); - for(uint32_t i = 0; i < selLength; ++i) - { - MStatus status = sl.getDagPath(i, path); - if(status != MS::kSuccess) continue; - - if(path.node().hasFn(MFn::kTransform)) - { - path.extendToShape(); - } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCommandBase::getShapeNode\n"); + MDagPath path; + MSelectionList sl; + args.getObjects(sl); - if(path.node().hasFn(MFn::kPluginShape)) - { - MFnDagNode fn(path); - if(fn.typeId() == nodes::ProxyShape::kTypeId) - { - return (nodes::ProxyShape*)fn.userNode(); - } - } - } - - sl.clear(); + const uint32_t selLength = sl.length(); + for (uint32_t i = 0; i < selLength; ++i) { + MStatus status = sl.getDagPath(i, path); + if (status != MS::kSuccess) + continue; - { - if(args.isFlagSet("-p")) - { - MString proxyName; - if(args.getFlagArgument("-p", 0, proxyName)) - { - sl.add(proxyName); - if(sl.length()) - { - MStatus status = sl.getDagPath(0, path); - if(status == MS::kSuccess) - { - if(path.node().hasFn(MFn::kTransform)) - { - path.extendToShape(); - } + if (path.node().hasFn(MFn::kTransform)) { + path.extendToShape(); + } - if(path.node().hasFn(MFn::kPluginShape)) - { - MFnDagNode fn(path); - if(fn.typeId() == nodes::ProxyShape::kTypeId) - { + if (path.node().hasFn(MFn::kPluginShape)) { + MFnDagNode fn(path); + if (fn.typeId() == nodes::ProxyShape::kTypeId) { return (nodes::ProxyShape*)fn.userNode(); - } } - } } - } - MGlobal::displayError("Invalid ProxyShape specified/selected with -p flag"); } - else - MGlobal::displayError("No ProxyShape specified/selected"); - } - throw MS::kFailure; - return 0; + sl.clear(); + + { + if (args.isFlagSet("-p")) { + MString proxyName; + if (args.getFlagArgument("-p", 0, proxyName)) { + sl.add(proxyName); + if (sl.length()) { + MStatus status = sl.getDagPath(0, path); + if (status == MS::kSuccess) { + if (path.node().hasFn(MFn::kTransform)) { + path.extendToShape(); + } + + if (path.node().hasFn(MFn::kPluginShape)) { + MFnDagNode fn(path); + if (fn.typeId() == nodes::ProxyShape::kTypeId) { + return (nodes::ProxyShape*)fn.userNode(); + } + } + } + } + } + MGlobal::displayError("Invalid ProxyShape specified/selected with -p flag"); + } else + MGlobal::displayError("No ProxyShape specified/selected"); + } + + throw MS::kFailure; + return 0; } //---------------------------------------------------------------------------------------------------------------------- UsdStageRefPtr LayerCommandBase::getShapeNodeStage(const MArgDatabase& args) { - nodes::ProxyShape* node = getShapeNode(args); - return node ? node->getUsdStage() : UsdStageRefPtr(); + nodes::ProxyShape* node = getShapeNode(args); + return node ? node->getUsdStage() : UsdStageRefPtr(); } //---------------------------------------------------------------------------------------------------------------------- @@ -202,144 +183,107 @@ AL_MAYA_DEFINE_COMMAND(LayerGetLayers, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax LayerGetLayers::createSyntax() { - MSyntax syn = setUpCommonSyntax(); - syn.useSelectionAsDefault(true); - syn.setObjectType(MSyntax::kSelectionList, 0, 1); - syn.addFlag("-h", "-help", MSyntax::kNoArg); - syn.addFlag("-u", "-used", MSyntax::kNoArg); - syn.addFlag("-m", "-muted", MSyntax::kNoArg); - syn.addFlag("-s", "-stack", MSyntax::kNoArg); - syn.addFlag("-sl", "-sessionLayer", MSyntax::kNoArg); - syn.addFlag("-rl", "-rootLayer", MSyntax::kNoArg); - syn.addFlag("-id", "-identifiers", MSyntax::kNoArg); - return syn; + MSyntax syn = setUpCommonSyntax(); + syn.useSelectionAsDefault(true); + syn.setObjectType(MSyntax::kSelectionList, 0, 1); + syn.addFlag("-h", "-help", MSyntax::kNoArg); + syn.addFlag("-u", "-used", MSyntax::kNoArg); + syn.addFlag("-m", "-muted", MSyntax::kNoArg); + syn.addFlag("-s", "-stack", MSyntax::kNoArg); + syn.addFlag("-sl", "-sessionLayer", MSyntax::kNoArg); + syn.addFlag("-rl", "-rootLayer", MSyntax::kNoArg); + syn.addFlag("-id", "-identifiers", MSyntax::kNoArg); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -bool LayerGetLayers::isUndoable() const -{ - return false; -} +bool LayerGetLayers::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerGetLayers::doIt(const MArgList& argList) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerGetLayers::doIt\n"); - try - { - MStatus status; - MArgDatabase args(syntax(), argList, &status); - if(!status) - return status; - AL_MAYA_COMMAND_HELP(args, g_helpText); - - nodes::ProxyShape* proxyShape = getShapeNode(args); - UsdStageRefPtr stage = proxyShape->usdStage(); - MStringArray results; - - const bool useIdentifiers = args.isFlagSet("-id"); - if(args.isFlagSet("-rl")) - { - - SdfLayerHandle rootLayer = stage->GetRootLayer(); - if(useIdentifiers) - { - setResult(AL::maya::utils::convert(rootLayer->GetIdentifier())); - } - else - { - setResult(AL::maya::utils::convert(rootLayer->GetDisplayName())); - } - return MS::kSuccess; - } - else - if(args.isFlagSet("-m")) - { - const std::vector& layers = stage->GetMutedLayers(); - for(auto it = layers.begin(); it != layers.end(); ++it) - { - if(useIdentifiers) - { - results.append(AL::maya::utils::convert(*it)); - } - else - { - // Need to convert from identifier to display name... - auto layer = SdfLayer::Find(*it); - if (!layer) - { - // If we failed to grab the layer from it's identifier, something went wrong... - MGlobal::displayError(MString("Could not find muted layer from identifier: ") + AL::maya::utils::convert(*it)); - return MS::kFailure; - } - results.append(AL::maya::utils::convert(layer->GetDisplayName())); - } - } - } - else - if(args.isFlagSet("-s")) - { - const bool includeSessionLayer = args.isFlagSet("-sl"); - SdfLayerHandleVector layerStack = stage->GetLayerStack(includeSessionLayer); - for(auto it = layerStack.begin(); it != layerStack.end(); ++it) - { - if(useIdentifiers) - { - results.append(AL::maya::utils::convert((*it)->GetIdentifier())); - } - else - { - results.append(AL::maya::utils::convert((*it)->GetDisplayName())); - } - } - } - else - if(args.isFlagSet("-u")) - { - const bool includeSessionLayer = args.isFlagSet("-sl"); - SdfLayerHandle sessionLayer = stage->GetSessionLayer(); - SdfLayerHandleVector layerStack = stage->GetUsedLayers(); - for(auto it = layerStack.begin(); it != layerStack.end(); ++it) - { - if(!includeSessionLayer) - { - if(sessionLayer == *it) - continue; - } - if(useIdentifiers) - { - results.append(AL::maya::utils::convert((*it)->GetIdentifier())); - } - else - { - results.append(AL::maya::utils::convert((*it)->GetDisplayName())); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerGetLayers::doIt\n"); + try { + MStatus status; + MArgDatabase args(syntax(), argList, &status); + if (!status) + return status; + AL_MAYA_COMMAND_HELP(args, g_helpText); + + nodes::ProxyShape* proxyShape = getShapeNode(args); + UsdStageRefPtr stage = proxyShape->usdStage(); + MStringArray results; + + const bool useIdentifiers = args.isFlagSet("-id"); + if (args.isFlagSet("-rl")) { + + SdfLayerHandle rootLayer = stage->GetRootLayer(); + if (useIdentifiers) { + setResult(AL::maya::utils::convert(rootLayer->GetIdentifier())); + } else { + setResult(AL::maya::utils::convert(rootLayer->GetDisplayName())); + } + return MS::kSuccess; + } else if (args.isFlagSet("-m")) { + const std::vector& layers = stage->GetMutedLayers(); + for (auto it = layers.begin(); it != layers.end(); ++it) { + if (useIdentifiers) { + results.append(AL::maya::utils::convert(*it)); + } else { + // Need to convert from identifier to display name... + auto layer = SdfLayer::Find(*it); + if (!layer) { + // If we failed to grab the layer from it's identifier, something went + // wrong... + MGlobal::displayError( + MString("Could not find muted layer from identifier: ") + + AL::maya::utils::convert(*it)); + return MS::kFailure; + } + results.append(AL::maya::utils::convert(layer->GetDisplayName())); + } + } + } else if (args.isFlagSet("-s")) { + const bool includeSessionLayer = args.isFlagSet("-sl"); + SdfLayerHandleVector layerStack = stage->GetLayerStack(includeSessionLayer); + for (auto it = layerStack.begin(); it != layerStack.end(); ++it) { + if (useIdentifiers) { + results.append(AL::maya::utils::convert((*it)->GetIdentifier())); + } else { + results.append(AL::maya::utils::convert((*it)->GetDisplayName())); + } + } + } else if (args.isFlagSet("-u")) { + const bool includeSessionLayer = args.isFlagSet("-sl"); + SdfLayerHandle sessionLayer = stage->GetSessionLayer(); + SdfLayerHandleVector layerStack = stage->GetUsedLayers(); + for (auto it = layerStack.begin(); it != layerStack.end(); ++it) { + if (!includeSessionLayer) { + if (sessionLayer == *it) + continue; + } + if (useIdentifiers) { + results.append(AL::maya::utils::convert((*it)->GetIdentifier())); + } else { + results.append(AL::maya::utils::convert((*it)->GetDisplayName())); + } + } + } else if (args.isFlagSet("-sl")) { + SdfLayerHandle sessionLayer = stage->GetSessionLayer(); + if (useIdentifiers) { + setResult(AL::maya::utils::convert(sessionLayer->GetIdentifier())); + } else { + setResult(AL::maya::utils::convert(sessionLayer->GetDisplayName())); + } + return MS::kSuccess; } - } + setResult(results); + } catch (const MStatus& status) { + return status; } - else - if(args.isFlagSet("-sl")) - { - SdfLayerHandle sessionLayer = stage->GetSessionLayer(); - if(useIdentifiers) - { - setResult(AL::maya::utils::convert(sessionLayer->GetIdentifier())); - } - else - { - setResult(AL::maya::utils::convert(sessionLayer->GetDisplayName())); - } - return MS::kSuccess; - } - setResult(results); - } - catch(const MStatus& status) - { - return status; - } - return MS::kSuccess; + return MS::kSuccess; } - //---------------------------------------------------------------------------------------------------------------------- // LayerCreateLayer //---------------------------------------------------------------------------------------------------------------------- @@ -347,138 +291,126 @@ AL_MAYA_DEFINE_COMMAND(LayerCreateLayer, AL_usdmaya); MSyntax LayerCreateLayer::createSyntax() { - MSyntax syn = setUpCommonSyntax(); - syn.useSelectionAsDefault(true); - syn.setObjectType(MSyntax::kSelectionList, 0, 1); - syn.addFlag("-o", "-open", MSyntax::kString); - syn.addFlag("-s", "-sublayer", MSyntax::kNoArg); - syn.addFlag("-h", "-help", MSyntax::kNoArg); - return syn; + MSyntax syn = setUpCommonSyntax(); + syn.useSelectionAsDefault(true); + syn.setObjectType(MSyntax::kSelectionList, 0, 1); + syn.addFlag("-o", "-open", MSyntax::kString); + syn.addFlag("-s", "-sublayer", MSyntax::kNoArg); + syn.addFlag("-h", "-help", MSyntax::kNoArg); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -bool LayerCreateLayer::isUndoable() const -{ - return true; -} +bool LayerCreateLayer::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerCreateLayer::doIt(const MArgList& argList) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCreateLayer::doIt\n"); - try - { - MStatus status; - MArgDatabase args(syntax(), argList, &status); - if(!status) - return status; - - AL_MAYA_COMMAND_HELP(args, g_helpText); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCreateLayer::doIt\n"); + try { + MStatus status; + MArgDatabase args(syntax(), argList, &status); + if (!status) + return status; + + AL_MAYA_COMMAND_HELP(args, g_helpText); + + if (args.isFlagSet("-o")) { + // extract remaining args + args.getFlagArgument("-o", 0, m_filePath); + } - if(args.isFlagSet("-o")) - { - // extract remaining args - args.getFlagArgument("-o", 0, m_filePath); - } + if (args.isFlagSet("-s")) { + m_addSublayer = true; + } - if(args.isFlagSet("-s")) - { - m_addSublayer = true; - } + m_shape = getShapeNode(args); - m_shape = getShapeNode(args); + if (!m_shape) { + throw MS::kFailure; + } - if(!m_shape) - { - throw MS::kFailure; + m_stage = m_shape->getUsdStage(); + if (!m_stage) { + MGlobal::displayError("no valid stage found on the proxy shape"); + throw MS::kFailure; + } + m_rootLayer = m_stage->GetRootLayer(); + } catch (const MStatus& status) { + return status; } - m_stage = m_shape->getUsdStage(); - if(!m_stage) - { - MGlobal::displayError("no valid stage found on the proxy shape"); - throw MS::kFailure; + if (!m_shape) { + MGlobal::displayError(MString("LayerCreateLayer: Invalid shape during Layer creation")); + return MS::kFailure; } - m_rootLayer = m_stage->GetRootLayer(); - } - catch(const MStatus& status) - { - return status; - } - - if(!m_shape) - { - MGlobal::displayError(MString("LayerCreateLayer: Invalid shape during Layer creation")); - return MS::kFailure; - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerCreateLayer::undoIt() { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCreateLayer::undoIt\n"); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCreateLayer::undoIt\n"); - // first let's go remove the newly created layer handle from the root layer we added it to - LAYER_HANDLE_CHECK(m_newLayer); + // first let's go remove the newly created layer handle from the root layer we added it to + LAYER_HANDLE_CHECK(m_newLayer); - if(m_layerWasInserted) - { - auto manager = AL::usdmaya::nodes::LayerManager::findOrCreateManager(); - manager->removeLayer(m_newLayer); - } - - if(m_addSublayer) - { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCreateLayer::Undo'ing '%s', removing from sublayers \n", m_newLayer->GetIdentifier().c_str()); - SdfSubLayerProxy paths = m_stage->GetRootLayer()->GetSubLayerPaths(); - paths.Remove(m_newLayer->GetIdentifier()); - } - - // lots more to do here! - return MS::kSuccess; + if (m_layerWasInserted) { + auto manager = AL::usdmaya::nodes::LayerManager::findOrCreateManager(); + manager->removeLayer(m_newLayer); + } + + if (m_addSublayer) { + TF_DEBUG(ALUSDMAYA_COMMANDS) + .Msg( + "LayerCreateLayer::Undo'ing '%s', removing from sublayers \n", + m_newLayer->GetIdentifier().c_str()); + SdfSubLayerProxy paths = m_stage->GetRootLayer()->GetSubLayerPaths(); + paths.Remove(m_newLayer->GetIdentifier()); + } + + // lots more to do here! + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerCreateLayer::redoIt() { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCreateLayer::redoIt\n"); - UsdStageRefPtr childStage; - - if(m_filePath.length() > 0) - { - std::string filePath = AL::maya::utils::convert(m_filePath); - m_newLayer = SdfLayer::FindOrOpen(filePath); - if(!m_newLayer) - { - MGlobal::displayError(MString("LayerCreateLayer:unable to open layer \"") + m_filePath + "\""); - return MS::kFailure; - } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCreateLayer::redoIt\n"); + UsdStageRefPtr childStage; + + if (m_filePath.length() > 0) { + std::string filePath = AL::maya::utils::convert(m_filePath); + m_newLayer = SdfLayer::FindOrOpen(filePath); + if (!m_newLayer) { + MGlobal::displayError( + MString("LayerCreateLayer:unable to open layer \"") + m_filePath + "\""); + return MS::kFailure; + } - } - else - { - m_newLayer = SdfLayer::CreateAnonymous(); - if(!m_newLayer) - { - MGlobal::displayError("LayerCreateLayer:unable to create anonymous layer"); - return MS::kFailure; + } else { + m_newLayer = SdfLayer::CreateAnonymous(); + if (!m_newLayer) { + MGlobal::displayError("LayerCreateLayer:unable to create anonymous layer"); + return MS::kFailure; + } } - } - auto manager = AL::usdmaya::nodes::LayerManager::findOrCreateManager(); - m_layerWasInserted = manager->addLayer(m_newLayer); - - if(m_addSublayer) - { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCreateLayer::Adding '%s' to sublayers\n", m_newLayer->GetIdentifier().c_str()); - SdfSubLayerProxy paths = m_stage->GetRootLayer()->GetSubLayerPaths(); - paths.push_back(m_newLayer->GetIdentifier()); - } + auto manager = AL::usdmaya::nodes::LayerManager::findOrCreateManager(); + m_layerWasInserted = manager->addLayer(m_newLayer); + + if (m_addSublayer) { + TF_DEBUG(ALUSDMAYA_COMMANDS) + .Msg( + "LayerCreateLayer::Adding '%s' to sublayers\n", + m_newLayer->GetIdentifier().c_str()); + SdfSubLayerProxy paths = m_stage->GetRootLayer()->GetSubLayerPaths(); + paths.push_back(m_newLayer->GetIdentifier()); + } - std::stringstream ss("LayerCreateLayer:", std::ios_base::app | std::ios_base::out); - MGlobal::displayInfo(ss.str().c_str()); - return MS::kSuccess; + std::stringstream ss("LayerCreateLayer:", std::ios_base::app | std::ios_base::out); + MGlobal::displayInfo(ss.str().c_str()); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- @@ -490,262 +422,232 @@ AL_MAYA_DEFINE_COMMAND(LayerCurrentEditTarget, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax LayerCurrentEditTarget::createSyntax() { - MSyntax syn = setUpCommonSyntax(); - syn.useSelectionAsDefault(true); - syn.setObjectType(MSyntax::kSelectionList, 0, 1); - syn.enableQuery(true); - syn.addFlag("-l", "-layer", MSyntax::kString); - syn.addFlag("-sp", "-sourcePath", MSyntax::kString); - syn.addFlag("-tp", "-targetPath", MSyntax::kString); - syn.addFlag("-h", "-help", MSyntax::kNoArg); - syn.addFlag("-fdn", "-findByDisplayName", MSyntax::kNoArg); - syn.addFlag("-fid", "-findByIdentifier", MSyntax::kNoArg); - return syn; + MSyntax syn = setUpCommonSyntax(); + syn.useSelectionAsDefault(true); + syn.setObjectType(MSyntax::kSelectionList, 0, 1); + syn.enableQuery(true); + syn.addFlag("-l", "-layer", MSyntax::kString); + syn.addFlag("-sp", "-sourcePath", MSyntax::kString); + syn.addFlag("-tp", "-targetPath", MSyntax::kString); + syn.addFlag("-h", "-help", MSyntax::kNoArg); + syn.addFlag("-fdn", "-findByDisplayName", MSyntax::kNoArg); + syn.addFlag("-fid", "-findByIdentifier", MSyntax::kNoArg); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -bool LayerCurrentEditTarget::isUndoable() const -{ - return true; -} +bool LayerCurrentEditTarget::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- -PcpNodeRef LayerCurrentEditTarget::determineEditTargetMapping(UsdStageRefPtr stage, - const MArgDatabase& args, - SdfLayerHandle editTargetLayer) const +PcpNodeRef LayerCurrentEditTarget::determineEditTargetMapping( + UsdStageRefPtr stage, + const MArgDatabase& args, + SdfLayerHandle editTargetLayer) const { - if(editTargetLayer.IsInvalid()) - { - return PcpNodeRef(); - } - - if(args.isFlagSet("-sp") && args.isFlagSet("-tp")) - { - MString targetPath; - MString sourcePath; - args.getFlagArgument("-tp", 0, targetPath); - args.getFlagArgument("-sp", 0, sourcePath); - - UsdPrim parentPrim = stage->GetPrimAtPath(SdfPath(targetPath.asChar())); - if( ! parentPrim.IsValid() ) - { - std::stringstream ss("LayerCurrentEditTarget:", std::ios_base::app | std::ios_base::out); - ss << "Couldn't find the parent prim at path '" << targetPath.asChar() << "'" << std::endl; - MGlobal::displayWarning(ss.str().c_str()); - return PcpNodeRef(); + if (editTargetLayer.IsInvalid()) { + return PcpNodeRef(); } - SdfReferenceListOp referenceListOp; - if(parentPrim.GetMetadata(TfToken("references"), &referenceListOp)) - { - // TODO: I doubt this is the correct way to get current references. The API for UsdPrim.GetReferences() isn't sufficient! - // TODO: Spiff recommends getting the references a different way, - // TODO: as mentioned here https://groups.google.com/forum/#!topic/usd-interest/o6jK0tVw2eU - const SdfListOp::ItemVector& addedItems = referenceListOp.GetAddedItems(); - - size_t referenceListSize = addedItems.size(); - for(size_t i = 0; i < referenceListSize; ++i) - { - SdfLayerHandle referencedLayer = SdfLayer::Find(addedItems[i].GetAssetPath()); - - // Is the referenced layer referring to the layer we selected? - if(referencedLayer == editTargetLayer) - { - PcpNodeRef::child_const_range childRange = parentPrim.GetPrimIndex().GetRootNode().GetChildrenRange(); - PcpNodeRef::child_const_iterator currentChildSpec = childRange.first; - PcpNodeRef::child_const_iterator end = childRange.second; - while(currentChildSpec != end) - { - if(currentChildSpec->GetParentNode().GetPath() == SdfPath(targetPath.asChar()) - && currentChildSpec->GetPath() == SdfPath(sourcePath.asChar())) - { - return *currentChildSpec; - } - ++currentChildSpec; - } + if (args.isFlagSet("-sp") && args.isFlagSet("-tp")) { + MString targetPath; + MString sourcePath; + args.getFlagArgument("-tp", 0, targetPath); + args.getFlagArgument("-sp", 0, sourcePath); + + UsdPrim parentPrim = stage->GetPrimAtPath(SdfPath(targetPath.asChar())); + if (!parentPrim.IsValid()) { + std::stringstream ss( + "LayerCurrentEditTarget:", std::ios_base::app | std::ios_base::out); + ss << "Couldn't find the parent prim at path '" << targetPath.asChar() << "'" + << std::endl; + MGlobal::displayWarning(ss.str().c_str()); + return PcpNodeRef(); } - } - MGlobal::displayWarning("LayerCurrentEditTarget: Couldn't find the PcpNodeRef to initialise the MappingFunction for the EditTarget"); + SdfReferenceListOp referenceListOp; + if (parentPrim.GetMetadata(TfToken("references"), &referenceListOp)) { + // TODO: I doubt this is the correct way to get current references. The API for + // UsdPrim.GetReferences() isn't sufficient! + // TODO: Spiff recommends getting the references a different way, + // TODO: as mentioned here + // https://groups.google.com/forum/#!topic/usd-interest/o6jK0tVw2eU + const SdfListOp::ItemVector& addedItems = referenceListOp.GetAddedItems(); + + size_t referenceListSize = addedItems.size(); + for (size_t i = 0; i < referenceListSize; ++i) { + SdfLayerHandle referencedLayer = SdfLayer::Find(addedItems[i].GetAssetPath()); + + // Is the referenced layer referring to the layer we selected? + if (referencedLayer == editTargetLayer) { + PcpNodeRef::child_const_range childRange + = parentPrim.GetPrimIndex().GetRootNode().GetChildrenRange(); + PcpNodeRef::child_const_iterator currentChildSpec = childRange.first; + PcpNodeRef::child_const_iterator end = childRange.second; + while (currentChildSpec != end) { + if (currentChildSpec->GetParentNode().GetPath() + == SdfPath(targetPath.asChar()) + && currentChildSpec->GetPath() == SdfPath(sourcePath.asChar())) { + return *currentChildSpec; + } + ++currentChildSpec; + } + } + } + + MGlobal::displayWarning("LayerCurrentEditTarget: Couldn't find the PcpNodeRef to " + "initialise the MappingFunction for the EditTarget"); + } + } else { + MGlobal::displayInfo( + "LayerCurrentEditTarget: Default MappingFunction for EditTarget will be used since " + "sp(Source Prim) and tp(Target Prim) flags were not set"); } - } - else - { - MGlobal::displayInfo("LayerCurrentEditTarget: Default MappingFunction for EditTarget will be used since sp(Source Prim) and tp(Target Prim) flags were not set"); - } - return PcpNodeRef(); + return PcpNodeRef(); } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerCurrentEditTarget::doIt(const MArgList& argList) { - try - { - MStatus status; - MArgDatabase args(syntax(), argList, &status); - if(!status) - return status; - - AL_MAYA_COMMAND_HELP(args, g_helpText); - if(args.isQuery()) - { - isQuery = true; - stage = getShapeNodeStage(args); - if(stage) - { - const UsdEditTarget& editTarget = stage->GetEditTarget(); - previous = editTarget; - } - else - { - MGlobal::displayError("LayerCurrentEditTarget: no loaded stage found on proxy node"); - return MS::kFailure; - } - } - else - { - // Setup the function pointers which will be used to find the wanted layer - if(args.isFlagSet("-fid")) - { - // Use the Identifier when looking for the correct layer. Used for anonymous layers - getLayerId = [](SdfLayerHandle layer) { return layer->GetIdentifier(); }; - } - else if(args.isFlagSet("-fdn")) - { - // Use the DisplayName when looking for the correct layer - getLayerId = [](SdfLayerHandle layer) { return layer->GetDisplayName(); }; - } - else - { - // Default to DisplayName if not specified for backwards compatibility - getLayerId = [](SdfLayerHandle layer) { return layer->GetDisplayName(); }; - } - - isQuery = false; - - stage = getShapeNodeStage(args); - if(stage) - { - // if the layer has been manually specified - MString layerName; - SdfLayerHandle foundLayer = nullptr; - if(args.isFlagSet("-l") && args.getFlagArgument("-l", 0, layerName)) - { - nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); - if(layerManager) - { - foundLayer = layerManager->findLayer(layerName.asChar()); - } - } - - previous = stage->GetEditTarget(); - isQuery = false; - std::string layerName2; - if(foundLayer) - { - - PcpNodeRef mappingNode = determineEditTargetMapping(stage, args, foundLayer); - if(mappingNode) - { - next = UsdEditTarget(foundLayer, mappingNode); - } - else - { - next = UsdEditTarget(foundLayer); - } - layerName2 = getLayerId(next.GetLayer()); - } - else - if(layerName.length() > 0) - { - layerName2 = AL::maya::utils::convert(layerName); - SdfLayerHandleVector layers = stage->GetUsedLayers(); - for(auto it = layers.begin(); it != layers.end(); ++it) - { - - SdfLayerHandle handle = *it; - - if(layerName2 == getLayerId(handle)) - { - PcpNodeRef mappingNode = determineEditTargetMapping(stage, args, handle); - if(mappingNode) - { - next = UsdEditTarget(handle, mappingNode); - } - else - { - next = UsdEditTarget(handle); - } - break; + try { + MStatus status; + MArgDatabase args(syntax(), argList, &status); + if (!status) + return status; + + AL_MAYA_COMMAND_HELP(args, g_helpText); + if (args.isQuery()) { + isQuery = true; + stage = getShapeNodeStage(args); + if (stage) { + const UsdEditTarget& editTarget = stage->GetEditTarget(); + previous = editTarget; + } else { + MGlobal::displayError( + "LayerCurrentEditTarget: no loaded stage found on proxy node"); + return MS::kFailure; + } + } else { + // Setup the function pointers which will be used to find the wanted layer + if (args.isFlagSet("-fid")) { + // Use the Identifier when looking for the correct layer. Used for anonymous layers + getLayerId = [](SdfLayerHandle layer) { return layer->GetIdentifier(); }; + } else if (args.isFlagSet("-fdn")) { + // Use the DisplayName when looking for the correct layer + getLayerId = [](SdfLayerHandle layer) { return layer->GetDisplayName(); }; + } else { + // Default to DisplayName if not specified for backwards compatibility + getLayerId = [](SdfLayerHandle layer) { return layer->GetDisplayName(); }; } - } - } - else - { - MGlobal::displayError("No layer specified"); - return MS::kFailure; - } - if(!next.IsValid()) - { - // if we failed to find the layer in the list of used layers, just check to see whether we are actually able to - // edit said layer. - SdfLayerHandleVector layers = stage->GetUsedLayers(); - for(auto it = layers.begin(); it != layers.end(); ++it) - { - SdfLayerHandle handle = *it; - if(layerName2 == getLayerId(handle)) - { - MGlobal::displayError("LayerCurrentEditTarget: Unable to set the edit target, the specified layer cannot be edited"); - return MS::kFailure; + isQuery = false; + + stage = getShapeNodeStage(args); + if (stage) { + // if the layer has been manually specified + MString layerName; + SdfLayerHandle foundLayer = nullptr; + if (args.isFlagSet("-l") && args.getFlagArgument("-l", 0, layerName)) { + nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); + if (layerManager) { + foundLayer = layerManager->findLayer(layerName.asChar()); + } + } + + previous = stage->GetEditTarget(); + isQuery = false; + std::string layerName2; + if (foundLayer) { + + PcpNodeRef mappingNode = determineEditTargetMapping(stage, args, foundLayer); + if (mappingNode) { + next = UsdEditTarget(foundLayer, mappingNode); + } else { + next = UsdEditTarget(foundLayer); + } + layerName2 = getLayerId(next.GetLayer()); + } else if (layerName.length() > 0) { + layerName2 = AL::maya::utils::convert(layerName); + SdfLayerHandleVector layers = stage->GetUsedLayers(); + for (auto it = layers.begin(); it != layers.end(); ++it) { + + SdfLayerHandle handle = *it; + + if (layerName2 == getLayerId(handle)) { + PcpNodeRef mappingNode + = determineEditTargetMapping(stage, args, handle); + if (mappingNode) { + next = UsdEditTarget(handle, mappingNode); + } else { + next = UsdEditTarget(handle); + } + break; + } + } + } else { + MGlobal::displayError("No layer specified"); + return MS::kFailure; + } + + if (!next.IsValid()) { + // if we failed to find the layer in the list of used layers, just check to see + // whether we are actually able to edit said layer. + SdfLayerHandleVector layers = stage->GetUsedLayers(); + for (auto it = layers.begin(); it != layers.end(); ++it) { + SdfLayerHandle handle = *it; + if (layerName2 == getLayerId(handle)) { + MGlobal::displayError("LayerCurrentEditTarget: Unable to set the edit " + "target, the specified layer cannot be edited"); + return MS::kFailure; + } + } + MGlobal::displayError( + MString("LayerCurrentEditTarget: no layer found on proxy node that matches " + "the name \"") + + AL::maya::utils::convert(layerName2) + "\""); + return MS::kFailure; + } + } else { + MGlobal::displayError( + "LayerCurrentEditTarget: no loaded stage found on proxy node"); + return MS::kFailure; } - } - MGlobal::displayError(MString("LayerCurrentEditTarget: no layer found on proxy node that matches the name \"") + AL::maya::utils::convert(layerName2) + "\""); - return MS::kFailure; } - } - else - { - MGlobal::displayError("LayerCurrentEditTarget: no loaded stage found on proxy node"); - return MS::kFailure; - } + } catch (const MStatus& status) { + MGlobal::displayError("LayerCurrentEditTarget: no proxy node found"); + return status; } - } - catch(const MStatus& status) - { - MGlobal::displayError("LayerCurrentEditTarget: no proxy node found"); - return status; - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerCurrentEditTarget::redoIt() { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCurrentEditTarget::redoIt\n"); - if(!isQuery) - { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCurrentEditTarget::redoIt setting target: %s\n", next.GetLayer()->GetDisplayName().c_str()); - stage->SetEditTarget(next); - } - else - { - setResult(AL::maya::utils::convert(previous.GetLayer()->GetDisplayName())); - } - return MS::kSuccess; + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCurrentEditTarget::redoIt\n"); + if (!isQuery) { + TF_DEBUG(ALUSDMAYA_COMMANDS) + .Msg( + "LayerCurrentEditTarget::redoIt setting target: %s\n", + next.GetLayer()->GetDisplayName().c_str()); + stage->SetEditTarget(next); + } else { + setResult(AL::maya::utils::convert(previous.GetLayer()->GetDisplayName())); + } + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerCurrentEditTarget::undoIt() { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCurrentEditTarget::undoIt\n"); - if(!isQuery) - { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCurrentEditTarget::undoIt setting target: %s\n", previous.GetLayer()->GetDisplayName().c_str()); - stage->SetEditTarget(previous); - } - return MS::kSuccess; + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("LayerCurrentEditTarget::undoIt\n"); + if (!isQuery) { + TF_DEBUG(ALUSDMAYA_COMMANDS) + .Msg( + "LayerCurrentEditTarget::undoIt setting target: %s\n", + previous.GetLayer()->GetDisplayName().c_str()); + stage->SetEditTarget(previous); + } + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- @@ -756,126 +658,106 @@ AL_MAYA_DEFINE_COMMAND(LayerSave, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax LayerSave::createSyntax() { - MSyntax syn = setUpCommonSyntax(); - syn.addArg(MSyntax::kString); // Layer name - syn.addFlag("-f", "-filename", MSyntax::kString); - syn.addFlag("-s", "-string", MSyntax::kNoArg); - syn.addFlag("-h", "-help", MSyntax::kNoArg); - return syn; + MSyntax syn = setUpCommonSyntax(); + syn.addArg(MSyntax::kString); // Layer name + syn.addFlag("-f", "-filename", MSyntax::kString); + syn.addFlag("-s", "-string", MSyntax::kNoArg); + syn.addFlag("-h", "-help", MSyntax::kNoArg); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -bool LayerSave::isUndoable() const -{ - return false; -} +bool LayerSave::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerSave::doIt(const MArgList& argList) { - try - { - MStatus status; - MArgDatabase args(syntax(), argList, &status); - if(!status) - return status; - - AL_MAYA_COMMAND_HELP(args, g_helpText); - - MString layerName = args.commandArgumentString(0); - if(layerName.length() == 0) - { - MGlobal::displayError("LayerSave: you need to specify a layer name that you wish to save"); - throw MS::kFailure; - } - - SdfLayerHandle handle; - nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); - if(layerManager) - { - handle = layerManager->findLayer(layerName.asChar()); - } - else - { - MGlobal::displayError("LayerSave: no layer manager in scene (so no layers)"); - throw MS::kFailure; - } - - LAYER_HANDLE_CHECK(handle); - if(handle) - { - bool flatten = args.isFlagSet("-fl"); - if(flatten) - { - if(!args.isFlagSet("-f") && !args.isFlagSet("-s")) - { - MGlobal::displayError("LayerSave: when using -flatten/-fl, you must specify the filename"); - throw MS::kFailure; + try { + MStatus status; + MArgDatabase args(syntax(), argList, &status); + if (!status) + return status; + + AL_MAYA_COMMAND_HELP(args, g_helpText); + + MString layerName = args.commandArgumentString(0); + if (layerName.length() == 0) { + MGlobal::displayError( + "LayerSave: you need to specify a layer name that you wish to save"); + throw MS::kFailure; } - // grab the path to the layer. - const std::string filename = handle->GetRealPath(); - std::string outfilepath; - if(args.isFlagSet("-f")) - { - MString temp; - args.getFlagArgument("-f", 0, temp); - outfilepath = AL::maya::utils::convert(temp); + SdfLayerHandle handle; + nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); + if (layerManager) { + handle = layerManager->findLayer(layerName.asChar()); + } else { + MGlobal::displayError("LayerSave: no layer manager in scene (so no layers)"); + throw MS::kFailure; } - // make sure the user is not going to annihilate their own work. - // I should probably put more checks in here? Or just remove this check and - // assume user error is not a thing? - if(outfilepath == filename) - { - MGlobal::displayError("LayerSave: nice try, but no, I'm not going to let you overwrite the layer with a flattened version." - "\nthat would seem like a very bad idea to me."); - throw MS::kFailure; - } - } - else - { - bool exportingToString = args.isFlagSet("-s"); - if(exportingToString) - { - // just set the text string as the result of the command - std::string temp; - handle->ExportToString(&temp); - setResult(AL::maya::utils::convert(temp)); - } - else - { - // if exporting to a file - if(args.isFlagSet("-f")) - { - MString temp; - args.getFlagArgument("-f", 0, temp); - const std::string filename = AL::maya::utils::convert(temp); - bool result = handle->Export(filename); - setResult(result); - if(!result) MGlobal::displayError("LayerSave: could not export layer"); - } - else - { - bool result = handle->Save(); - setResult(result); - if(!result) MGlobal::displayError("LayerSave: could not save layer"); - } + LAYER_HANDLE_CHECK(handle); + if (handle) { + bool flatten = args.isFlagSet("-fl"); + if (flatten) { + if (!args.isFlagSet("-f") && !args.isFlagSet("-s")) { + MGlobal::displayError( + "LayerSave: when using -flatten/-fl, you must specify the filename"); + throw MS::kFailure; + } + + // grab the path to the layer. + const std::string filename = handle->GetRealPath(); + std::string outfilepath; + if (args.isFlagSet("-f")) { + MString temp; + args.getFlagArgument("-f", 0, temp); + outfilepath = AL::maya::utils::convert(temp); + } + + // make sure the user is not going to annihilate their own work. + // I should probably put more checks in here? Or just remove this check and + // assume user error is not a thing? + if (outfilepath == filename) { + MGlobal::displayError("LayerSave: nice try, but no, I'm not going to let you " + "overwrite the layer with a flattened version." + "\nthat would seem like a very bad idea to me."); + throw MS::kFailure; + } + } else { + bool exportingToString = args.isFlagSet("-s"); + if (exportingToString) { + // just set the text string as the result of the command + std::string temp; + handle->ExportToString(&temp); + setResult(AL::maya::utils::convert(temp)); + } else { + // if exporting to a file + if (args.isFlagSet("-f")) { + MString temp; + args.getFlagArgument("-f", 0, temp); + const std::string filename = AL::maya::utils::convert(temp); + bool result = handle->Export(filename); + setResult(result); + if (!result) + MGlobal::displayError("LayerSave: could not export layer"); + } else { + bool result = handle->Save(); + setResult(result); + if (!result) + MGlobal::displayError("LayerSave: could not save layer"); + } + } + } + } else { + MGlobal::displayError( + MString("LayerSave: Could not find layer named '") + layerName + "'"); + throw MS::kFailure; } - } + } catch (const MStatus& status) { + return status; } - else - { - MGlobal::displayError(MString("LayerSave: Could not find layer named '") - + layerName + "'"); - throw MS::kFailure; - } - } - catch(const MStatus& status) - { - return status; - } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- @@ -886,251 +768,248 @@ AL_MAYA_DEFINE_COMMAND(LayerSetMuted, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax LayerSetMuted::createSyntax() { - MSyntax syn = setUpCommonSyntax(); - syn.addArg(MSyntax::kString); // Layer name - syn.addFlag("-h", "-help", MSyntax::kNoArg); - syn.addFlag("-m", "-muted", MSyntax::kBoolean); - return syn; + MSyntax syn = setUpCommonSyntax(); + syn.addArg(MSyntax::kString); // Layer name + syn.addFlag("-h", "-help", MSyntax::kNoArg); + syn.addFlag("-m", "-muted", MSyntax::kBoolean); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -bool LayerSetMuted::isUndoable() const -{ - return true; -} +bool LayerSetMuted::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerSetMuted::doIt(const MArgList& argList) { - try - { - MStatus status; - MArgDatabase args(syntax(), argList, &status); - if(!status) - return status; - - AL_MAYA_COMMAND_HELP(args, g_helpText); + try { + MStatus status; + MArgDatabase args(syntax(), argList, &status); + if (!status) + return status; + + AL_MAYA_COMMAND_HELP(args, g_helpText); + + MString layerName = args.commandArgumentString(0); + if (layerName.length() == 0) { + MGlobal::displayError( + "LayerSetMuted: you need to specify a layer name that you wish to set muted"); + throw MS::kFailure; + } - MString layerName = args.commandArgumentString(0); - if(layerName.length() == 0) - { - MGlobal::displayError("LayerSetMuted: you need to specify a layer name that you wish to set muted"); - throw MS::kFailure; - } + if (!args.isFlagSet("-m")) { + MGlobal::displayError("LayerSetMuted: please tell me whether you want to mute or " + "unmute via the -m flag"); + throw MS::kFailure; + } - if(!args.isFlagSet("-m")) - { - MGlobal::displayError("LayerSetMuted: please tell me whether you want to mute or unmute via the -m flag"); - throw MS::kFailure; - } + nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); + if (layerManager) { + m_layer = layerManager->findLayer(layerName.asChar()); + } else { + MGlobal::displayError("LayerSetMuted: no layer manager in scene (so no layers)"); + throw MS::kFailure; + } + LAYER_HANDLE_CHECK(m_layer); + if (!m_layer) { + MGlobal::displayError("LayerSetMuted: no valid USD layer found on the node"); + throw MS::kFailure; + } - nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); - if(layerManager) - { - m_layer = layerManager->findLayer(layerName.asChar()); - } - else - { - MGlobal::displayError("LayerSetMuted: no layer manager in scene (so no layers)"); - throw MS::kFailure; - } - LAYER_HANDLE_CHECK(m_layer); - if(!m_layer) - { - MGlobal::displayError("LayerSetMuted: no valid USD layer found on the node"); - throw MS::kFailure; + args.getFlagArgument("-m", 0, m_muted); + } catch (const MStatus& status) { + return status; } - - args.getFlagArgument("-m", 0, m_muted); - } - catch(const MStatus& status) - { - return status; - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerSetMuted::undoIt() { - if(m_layer) - m_layer->SetMuted(m_muted); - return MS::kSuccess; + if (m_layer) + m_layer->SetMuted(m_muted); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerSetMuted::redoIt() { - if(m_layer) - m_layer->SetMuted(m_muted); - return MS::kSuccess; + if (m_layer) + m_layer->SetMuted(m_muted); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -/// \brief Retrieves all the layers that have been set as the EditTarget from any Stage during this session. +/// \brief Retrieves all the layers that have been set as the EditTarget from any Stage during this +/// session. //---------------------------------------------------------------------------------------------------------------------- AL_MAYA_DEFINE_COMMAND(LayerManager, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- -bool LayerManager::isUndoable() const -{ - return false; -} +bool LayerManager::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MSyntax LayerManager::createSyntax() { - MSyntax syn = setUpCommonSyntax(); - syn.useSelectionAsDefault(true); - syn.setObjectType(MSyntax::kSelectionList, 0); - syn.addFlag("-dal", "-dirtyallLayers", MSyntax::kNoArg); - syn.addFlag("-dso", "-dirtysessiononly", MSyntax::kNoArg); - syn.addFlag("-dlo", "-dirtyedittargetlayersonly", MSyntax::kNoArg); - return syn; + MSyntax syn = setUpCommonSyntax(); + syn.useSelectionAsDefault(true); + syn.setObjectType(MSyntax::kSelectionList, 0); + syn.addFlag("-dal", "-dirtyallLayers", MSyntax::kNoArg); + syn.addFlag("-dso", "-dirtysessiononly", MSyntax::kNoArg); + syn.addFlag("-dlo", "-dirtyedittargetlayersonly", MSyntax::kNoArg); + return syn; } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerManager::doIt(const MArgList& argList) { - try - { - MStatus status; - MArgDatabase args(syntax(), argList, &status); - if(!status) - return status; - - AL_MAYA_COMMAND_HELP(args, g_helpText); - - nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); - - auto shouldRecord = [&](const MString& currId) - { - if(args.isFlagSet("-dso")) - { - UsdStageRefPtr stage = getShapeNodeStage(args); - std::string shapesSessionId = stage->GetSessionLayer()->GetIdentifier(); - if(std::strcmp(currId.asChar(), shapesSessionId.c_str()) != 0) - { - // only return the dirty session layer for the selected stage - return false; - } - } - else if(args.isFlagSet("-dlo")) - { - std::string displayName = SdfLayer::GetDisplayNameFromIdentifier(currId.asChar()); - std::size_t found = displayName.find("session"); - if(found != std::string::npos) - { - return false; - } - } - return true; - }; - - MStringArray results; - if(layerManager) - { - MStringArray identifiers; - layerManager->getLayerIdentifiers(identifiers); - - for(uint32_t x = 0, n = identifiers.length(); x < n; ++x) - { - MString currId = identifiers[x]; - - if(!shouldRecord(currId)) - { - continue; - } - - SdfLayerHandle l = layerManager->findLayer(currId.asChar()); - if(l) - { - std::string str; - l->ExportToString(&str); - - // Write the results in adjacent pairs(id,contents, id,contents) - results.append(currId); - results.append(AL::maya::utils::convert(str)); + try { + MStatus status; + MArgDatabase args(syntax(), argList, &status); + if (!status) + return status; + + AL_MAYA_COMMAND_HELP(args, g_helpText); + + nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); + + auto shouldRecord = [&](const MString& currId) { + if (args.isFlagSet("-dso")) { + UsdStageRefPtr stage = getShapeNodeStage(args); + std::string shapesSessionId = stage->GetSessionLayer()->GetIdentifier(); + if (std::strcmp(currId.asChar(), shapesSessionId.c_str()) != 0) { + // only return the dirty session layer for the selected stage + return false; + } + } else if (args.isFlagSet("-dlo")) { + std::string displayName = SdfLayer::GetDisplayNameFromIdentifier(currId.asChar()); + std::size_t found = displayName.find("session"); + if (found != std::string::npos) { + return false; + } + } + return true; + }; + + MStringArray results; + if (layerManager) { + MStringArray identifiers; + layerManager->getLayerIdentifiers(identifiers); + + for (uint32_t x = 0, n = identifiers.length(); x < n; ++x) { + MString currId = identifiers[x]; + + if (!shouldRecord(currId)) { + continue; + } + + SdfLayerHandle l = layerManager->findLayer(currId.asChar()); + if (l) { + std::string str; + l->ExportToString(&str); + + // Write the results in adjacent pairs(id,contents, id,contents) + results.append(currId); + results.append(AL::maya::utils::convert(str)); + } + } } - } + setResult(results); + } catch (const MStatus& status) { + return status; } - setResult(results); - } - catch(const MStatus& status) - { - return status; - } - - return MS::kSuccess; + + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStringArray buildEditedLayersList(const MString&) { - MStringArray result; - nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); - if(layerManager) - { - layerManager->getLayerIdentifiers(result); - } - return result; + MStringArray result; + nodes::LayerManager* layerManager = nodes::LayerManager::findManager(); + if (layerManager) { + layerManager->getLayerIdentifiers(result); + } + return result; } //---------------------------------------------------------------------------------------------------------------------- MStringArray buildProxyLayersList(const MString&) { - MStringArray result; - MSelectionList sl; - AL_MAYA_CHECK_ERROR_RETURN_VAL(MGlobal::getActiveSelectionList(sl), result, - "Error building layer list"); - - nodes::ProxyShape* foundShape = getProxyShapeFromSel(sl); - if (!foundShape) - { - MGlobal::displayError("No proxy shape selected"); - return result; - } + MStringArray result; + MSelectionList sl; + AL_MAYA_CHECK_ERROR_RETURN_VAL( + MGlobal::getActiveSelectionList(sl), result, "Error building layer list"); + + nodes::ProxyShape* foundShape = getProxyShapeFromSel(sl); + if (!foundShape) { + MGlobal::displayError("No proxy shape selected"); + return result; + } - auto stage = foundShape->getUsdStage(); - if (!stage) - { - MGlobal::displayError(MString("Proxy shape '") + foundShape->name() + "' had no usd stage"); - return result; - } + auto stage = foundShape->getUsdStage(); + if (!stage) { + MGlobal::displayError(MString("Proxy shape '") + foundShape->name() + "' had no usd stage"); + return result; + } - auto usedLayers = stage->GetUsedLayers(); + auto usedLayers = stage->GetUsedLayers(); - for(auto& layer : usedLayers) - { - result.append(layer->GetIdentifier().c_str()); - } - return result; + for (auto& layer : usedLayers) { + result.append(layer->GetIdentifier().c_str()); + } + return result; } //---------------------------------------------------------------------------------------------------------------------- void constructLayerCommandGuis() { - { - AL::maya::utils::CommandGuiHelper saveLayer("AL_usdmaya_LayerSave", "Save Layer", "Save Layer", "USD/Layers/Save Layer", false); - saveLayer.addListOption("l", "Layer to Save", (AL::maya::utils::GenerateListFn)buildEditedLayersList, /*isMandatory=*/true); - saveLayer.addFilePathOption("f", "USD File Path", AL::maya::utils::CommandGuiHelper::kSave, "USDA files (*.usda) (*.usda);;USDC files (*.usdc) (*.usdc);;Alembic Files (*.abc) (*.abc);;All Files (*) (*)", AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); - } - - { - AL::maya::utils::CommandGuiHelper createLayer("AL_usdmaya_LayerCreateLayer", "Create Layer on current layer", "Create", "USD/Layers/Create Sub Layer", false); - createLayer.addExecuteText(" -s "); - createLayer.addFilePathOption("open", "Find or Open Existing Layer", AL::maya::utils::CommandGuiHelper::kLoad, "USD files (*.usd*) (*.usd*);; Alembic Files (*.abc) (*.abc);;All Files (*) (*)", AL::maya::utils::CommandGuiHelper::kStringOptional); - } - - { - AL::maya::utils::CommandGuiHelper setEditTarget("AL_usdmaya_LayerCurrentEditTarget", "Set Current Edit Target", "Set", "USD/Layers/Set Current Edit Target", false); - // we build our layer list using identifiers, so make sure the command is told to expect identifiers - setEditTarget.addExecuteText(" -fid "); - setEditTarget.addListOption("l", "USD Layer", (AL::maya::utils::GenerateListFn)buildProxyLayersList); - } -} + { + AL::maya::utils::CommandGuiHelper saveLayer( + "AL_usdmaya_LayerSave", "Save Layer", "Save Layer", "USD/Layers/Save Layer", false); + saveLayer.addListOption( + "l", + "Layer to Save", + (AL::maya::utils::GenerateListFn)buildEditedLayersList, + /*isMandatory=*/true); + saveLayer.addFilePathOption( + "f", + "USD File Path", + AL::maya::utils::CommandGuiHelper::kSave, + "USDA files (*.usda) (*.usda);;USDC files (*.usdc) (*.usdc);;Alembic Files (*.abc) " + "(*.abc);;All Files (*) (*)", + AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); + } + { + AL::maya::utils::CommandGuiHelper createLayer( + "AL_usdmaya_LayerCreateLayer", + "Create Layer on current layer", + "Create", + "USD/Layers/Create Sub Layer", + false); + createLayer.addExecuteText(" -s "); + createLayer.addFilePathOption( + "open", + "Find or Open Existing Layer", + AL::maya::utils::CommandGuiHelper::kLoad, + "USD files (*.usd*) (*.usd*);; Alembic Files (*.abc) (*.abc);;All Files (*) (*)", + AL::maya::utils::CommandGuiHelper::kStringOptional); + } + { + AL::maya::utils::CommandGuiHelper setEditTarget( + "AL_usdmaya_LayerCurrentEditTarget", + "Set Current Edit Target", + "Set", + "USD/Layers/Set Current Edit Target", + false); + // we build our layer list using identifiers, so make sure the command is told to expect + // identifiers + setEditTarget.addExecuteText(" -fid "); + setEditTarget.addListOption( + "l", "USD Layer", (AL::maya::utils::GenerateListFn)buildProxyLayersList); + } +} //---------------------------------------------------------------------------------------------------------------------- // Documentation strings. @@ -1315,7 +1194,7 @@ LayerManager Command Overview: )"; //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/LayerCommands.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/LayerCommands.h index 6858bea02b..3ea4602220 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/LayerCommands.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/LayerCommands.h @@ -35,167 +35,171 @@ namespace cmds { /// \brief Helper class /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class LayerCommandBase - : public MPxCommand +class LayerCommandBase : public MPxCommand { public: - - /// \brief sets up some core/common command params for all the layer commands. Just specifies that selection can be - /// used as an argument. - /// \return the syntax object with the command command flags specified - static MSyntax setUpCommonSyntax(); - - /// \brief find the proxy shape node from a valid pre-parsed arg database - /// \param args the argument database to get the proxy shape from - /// \return the proxy shape node (if found in the args) - nodes::ProxyShape* getShapeNode(const MArgDatabase& args); - - /// \brief get the USD stage - /// \param args the argument database to get the stage from - /// \return the stage from a proxy shape node (if found in the args) - UsdStageRefPtr getShapeNodeStage(const MArgDatabase& args); - -// /// \brief hunt for the first node of the specified type found in the selection list object args -// /// \param args the pre-parsed argument data base -// /// \param typeId the typeId of the object type that may appear as one of the selected objects -// /// \return the MObject of the node if found -// MObject getSelectedNode(const MArgDatabase& args, const MTypeId typeId); + /// \brief sets up some core/common command params for all the layer commands. Just specifies + /// that selection can be + /// used as an argument. + /// \return the syntax object with the command command flags specified + static MSyntax setUpCommonSyntax(); + + /// \brief find the proxy shape node from a valid pre-parsed arg database + /// \param args the argument database to get the proxy shape from + /// \return the proxy shape node (if found in the args) + nodes::ProxyShape* getShapeNode(const MArgDatabase& args); + + /// \brief get the USD stage + /// \param args the argument database to get the stage from + /// \return the stage from a proxy shape node (if found in the args) + UsdStageRefPtr getShapeNodeStage(const MArgDatabase& args); + + // /// \brief hunt for the first node of the specified type found in the selection list object + // args + // /// \param args the pre-parsed argument data base + // /// \param typeId the typeId of the object type that may appear as one of the selected + // objects + // /// \return the MObject of the node if found + // MObject getSelectedNode(const MArgDatabase& args, const MTypeId typeId); }; //---------------------------------------------------------------------------------------------------------------------- /// \brief Given some selected proxy shape node, return the layer names /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class LayerGetLayers - : public LayerCommandBase +class LayerGetLayers : public LayerCommandBase { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief Given some selected or passed in proxy shape node, create a layer in maya parented to the layer +/// \brief Given some selected or passed in proxy shape node, create a layer in maya parented to +/// the layer /// matching the identifier passed in, else parents to the rootlayer. /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class LayerCreateLayer - : public LayerCommandBase +class LayerCreateLayer : public LayerCommandBase { - UsdStageRefPtr m_stage; - SdfLayerHandle m_rootLayer; - SdfLayerRefPtr m_newLayer; - MString m_filePath; - nodes::ProxyShape* m_shape; - bool m_addSublayer = false; - bool m_layerWasInserted; + UsdStageRefPtr m_stage; + SdfLayerHandle m_rootLayer; + SdfLayerRefPtr m_newLayer; + MString m_filePath; + nodes::ProxyShape* m_shape; + bool m_addSublayer = false; + bool m_layerWasInserted; public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus undoIt() override; - MStatus redoIt() override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus undoIt() override; + MStatus redoIt() override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief Save the specified layer /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class LayerSave - : public LayerCommandBase +class LayerSave : public LayerCommandBase { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief Export a layer to the given filename /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class LayerExport - : public LayerCommandBase +class LayerExport : public LayerCommandBase { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief Get / Set the current edit target for the stage /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class LayerCurrentEditTarget - : public LayerCommandBase +class LayerCurrentEditTarget : public LayerCommandBase { - LayerCurrentEditTarget() {} - UsdEditTarget previous; - UsdEditTarget next; - UsdStageRefPtr stage; - bool isQuery; - std::function getLayerId; + LayerCurrentEditTarget() { } + UsdEditTarget previous; + UsdEditTarget next; + UsdStageRefPtr stage; + bool isQuery; + std::function getLayerId; public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; - MStatus undoIt() override; - MStatus redoIt() override; - PcpNodeRef determineEditTargetMapping(UsdStageRefPtr stage, const MArgDatabase& args, SdfLayerHandle editTargetLayer) const; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; + MStatus undoIt() override; + MStatus redoIt() override; + PcpNodeRef determineEditTargetMapping( + UsdStageRefPtr stage, + const MArgDatabase& args, + SdfLayerHandle editTargetLayer) const; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief Get / Set whether the layer is currently muted /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class LayerSetMuted - : public LayerCommandBase +class LayerSetMuted : public LayerCommandBase { - SdfLayerHandle m_layer; - bool m_muted; + SdfLayerHandle m_layer; + bool m_muted; + public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; - MStatus undoIt() override; - MStatus redoIt() override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; + MStatus undoIt() override; + MStatus redoIt() override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief Command to introspect and pull out data from the layer manager /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class LayerManager - : public LayerCommandBase +class LayerManager : public LayerCommandBase { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; - MStatus captureLayerContents(const MString& id, MStringArray& results); + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; + MStatus captureLayerContents(const MString& id, MStringArray& results); }; - - /// \brief function called on startup to generate the menu & option boxes for the layer commands /// \ingroup commands AL_USDMAYA_PUBLIC void constructLayerCommandGuis(); //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ListTranslators.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ListTranslators.cpp index 63e9dc2141..3f52232ddd 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ListTranslators.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ListTranslators.cpp @@ -15,16 +15,16 @@ // #include "AL/usdmaya/cmds/ListTranslators.h" -#include -#include +#include "AL/usdmaya/fileio/translators/TranslatorBase.h" + #include +#include +#include #include #include -#include #include - -#include "AL/usdmaya/fileio/translators/TranslatorBase.h" +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -37,58 +37,47 @@ AL_MAYA_DEFINE_COMMAND(ListTranslators, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax ListTranslators::createSyntax() { - MSyntax syn; - syn.addFlag("-h", "-help", MSyntax::kNoArg); - return syn; + MSyntax syn; + syn.addFlag("-h", "-help", MSyntax::kNoArg); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -bool ListTranslators::isUndoable() const -{ - return false; -} +bool ListTranslators::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MStatus ListTranslators::doIt(const MArgList& argList) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("AL_usdmaya_ListTranslators::doIt\n"); - try - { - MStatus status; - MArgDatabase args(syntax(), argList, &status); - if(!status) - return status; - - AL_MAYA_COMMAND_HELP(args, g_helpText); - - - auto contextPtr = fileio::translators::TranslatorContext::create(0); - - std::set derivedTypes; - PlugRegistry::GetAllDerivedTypes(&derivedTypes); - - MStringArray strings; - for (const TfType& t : derivedTypes) - { - if (auto* factory = t.GetFactory()) - { - if (fileio::translators::TranslatorRefPtr ptr = factory->create(contextPtr)) - { - strings.append(ptr->getTranslatedType().GetTypeName().c_str()); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("AL_usdmaya_ListTranslators::doIt\n"); + try { + MStatus status; + MArgDatabase args(syntax(), argList, &status); + if (!status) + return status; + + AL_MAYA_COMMAND_HELP(args, g_helpText); + + auto contextPtr = fileio::translators::TranslatorContext::create(0); + + std::set derivedTypes; + PlugRegistry::GetAllDerivedTypes(&derivedTypes); + + MStringArray strings; + for (const TfType& t : derivedTypes) { + if (auto* factory = t.GetFactory()) { + if (fileio::translators::TranslatorRefPtr ptr = factory->create(contextPtr)) { + strings.append(ptr->getTranslatedType().GetTypeName().c_str()); + } + } } - } - } - - setResult(strings); - } - catch(const MStatus&) - { - } - return MS::kSuccess; + setResult(strings); + } catch (const MStatus&) { + } + return MS::kSuccess; } -const char* const ListTranslators::g_helpText = R"( +const char* const ListTranslators::g_helpText = R"( AL_usdmaya_ListTranslators Overview: This command returns an array of strings which correspond to the translator plugins registered @@ -98,7 +87,7 @@ const char* const ListTranslators::g_helpText = R"( )"; //---------------------------------------------------------------------------------------------------------------------- -} -} -} +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ListTranslators.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ListTranslators.h index 71ed6f3a6c..b539f3603d 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ListTranslators.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ListTranslators.h @@ -25,22 +25,19 @@ namespace usdmaya { namespace cmds { //---------------------------------------------------------------------------------------------------------------------- -/// \brief A command that allows you to query all of the translator plugins that are currently registered with AL_usdmaya -/// \ingroup commands +/// \brief A command that allows you to query all of the translator plugins that are currently +/// registered with AL_usdmaya \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ListTranslators - : public MPxCommand +class ListTranslators : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; -} // cmds -} // usdmaya -} // AL - - - +} // namespace cmds +} // namespace usdmaya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapeCommands.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapeCommands.cpp index 22c47bfbf8..ddcb3649f9 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapeCommands.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapeCommands.cpp @@ -14,11 +14,11 @@ // limitations under the License. // #include "AL/usdmaya/cmds/ProxyShapeCommands.h" -#include "AL/usdmaya/nodes/LayerManager.h" #include "AL/maya/utils/CommandGuiHelper.h" #include "AL/maya/utils/MenuBuilder.h" #include "AL/maya/utils/Utils.h" +#include "AL/usdmaya/nodes/LayerManager.h" #include #include @@ -27,7 +27,7 @@ #include namespace { - typedef void (AL::usdmaya::nodes::SelectionList::*SelectionListModifierFunc)(SdfPath); +typedef void (AL::usdmaya::nodes::SelectionList::*SelectionListModifierFunc)(SdfPath); } namespace AL { @@ -36,129 +36,107 @@ namespace cmds { //---------------------------------------------------------------------------------------------------------------------- MSyntax ProxyShapeCommandBase::setUpCommonSyntax() { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeCommandBase::setUpCommonSyntax\n"); - MSyntax syntax; - syntax.useSelectionAsDefault(true); - syntax.setObjectType(MSyntax::kSelectionList, 0, 1); - syntax.addFlag("-p", "-proxy", MSyntax::kString); - return syntax; + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeCommandBase::setUpCommonSyntax\n"); + MSyntax syntax; + syntax.useSelectionAsDefault(true); + syntax.setObjectType(MSyntax::kSelectionList, 0, 1); + syntax.addFlag("-p", "-proxy", MSyntax::kString); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- MDagPath ProxyShapeCommandBase::getShapePath(const MArgDatabase& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeCommandBase::getShapePath\n"); - MSelectionList sl; - args.getObjects(sl); - MDagPath path; - MStatus status = sl.getDagPath(0, path); - if(!status) - { - MGlobal::displayError("Argument is not a proxy shape"); - throw status; - } - - if(path.node().hasFn(MFn::kTransform)) - { - path.extendToShape(); - } - - if(path.node().hasFn(MFn::kPluginShape)) - { - MFnDagNode fn(path); - if(fn.typeId() == nodes::ProxyShape::kTypeId) - { - return path; - } - else - { - MGlobal::displayError("No usd proxy shape selected"); - throw MS::kFailure; + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeCommandBase::getShapePath\n"); + MSelectionList sl; + args.getObjects(sl); + MDagPath path; + MStatus status = sl.getDagPath(0, path); + if (!status) { + MGlobal::displayError("Argument is not a proxy shape"); + throw status; } - } - else - { - MGlobal::displayError("No usd proxy shape selected"); - throw MS::kFailure; - } - return MDagPath(); -} - -//---------------------------------------------------------------------------------------------------------------------- -nodes::ProxyShape* ProxyShapeCommandBase::getShapeNode(const MArgDatabase& args) -{ - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeCommandBase::getShapeNode\n"); - MDagPath path; - MSelectionList sl; - args.getObjects(sl); - - for(uint32_t i = 0; i < sl.length(); ++i) - { - MStatus status = sl.getDagPath(i, path); - if(status) - { - if(path.node().hasFn(MFn::kTransform)) - { + if (path.node().hasFn(MFn::kTransform)) { path.extendToShape(); - } + } - if(path.node().hasFn(MFn::kPluginShape)) - { + if (path.node().hasFn(MFn::kPluginShape)) { MFnDagNode fn(path); - if(fn.typeId() == nodes::ProxyShape::kTypeId) - { - return (nodes::ProxyShape*)fn.userNode(); + if (fn.typeId() == nodes::ProxyShape::kTypeId) { + return path; + } else { + MGlobal::displayError("No usd proxy shape selected"); + throw MS::kFailure; } - } + } else { + MGlobal::displayError("No usd proxy shape selected"); + throw MS::kFailure; } - } - sl.clear(); + return MDagPath(); +} - { - if(args.isFlagSet("-p")) - { - MString proxyName; - if(args.getFlagArgument("-p", 0, proxyName)) - { - sl.add(proxyName); - if(sl.length()) - { - MStatus status = sl.getDagPath(0, path); - if(status) - { - if(path.node().hasFn(MFn::kTransform)) - { - path.extendToShape(); +//---------------------------------------------------------------------------------------------------------------------- +nodes::ProxyShape* ProxyShapeCommandBase::getShapeNode(const MArgDatabase& args) +{ + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeCommandBase::getShapeNode\n"); + MDagPath path; + MSelectionList sl; + args.getObjects(sl); + + for (uint32_t i = 0; i < sl.length(); ++i) { + MStatus status = sl.getDagPath(i, path); + if (status) { + if (path.node().hasFn(MFn::kTransform)) { + path.extendToShape(); } - if(path.node().hasFn(MFn::kPluginShape)) - { - MFnDagNode fn(path); - if(fn.typeId() == nodes::ProxyShape::kTypeId) - { - return (nodes::ProxyShape*)fn.userNode(); - } + if (path.node().hasFn(MFn::kPluginShape)) { + MFnDagNode fn(path); + if (fn.typeId() == nodes::ProxyShape::kTypeId) { + return (nodes::ProxyShape*)fn.userNode(); + } } - } } - } - MGlobal::displayError("Invalid ProxyShape specified/selected with -p flag"); } - else - MGlobal::displayError("No ProxyShape specified/selected"); - } + sl.clear(); + + { + if (args.isFlagSet("-p")) { + MString proxyName; + if (args.getFlagArgument("-p", 0, proxyName)) { + sl.add(proxyName); + if (sl.length()) { + MStatus status = sl.getDagPath(0, path); + if (status) { + if (path.node().hasFn(MFn::kTransform)) { + path.extendToShape(); + } + + if (path.node().hasFn(MFn::kPluginShape)) { + MFnDagNode fn(path); + if (fn.typeId() == nodes::ProxyShape::kTypeId) { + return (nodes::ProxyShape*)fn.userNode(); + } + } + } + } + } + MGlobal::displayError("Invalid ProxyShape specified/selected with -p flag"); + } else + MGlobal::displayError("No ProxyShape specified/selected"); + } - throw MS::kFailure; - return 0; + throw MS::kFailure; + return 0; } //---------------------------------------------------------------------------------------------------------------------- UsdStageRefPtr ProxyShapeCommandBase::getShapeNodeStage(const MArgDatabase& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeCommandBase::getShapeNodeStage\n"); - nodes::ProxyShape* node = getShapeNode(args); - return node ? node->usdStage() : UsdStageRefPtr(); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeCommandBase::getShapeNodeStage\n"); + nodes::ProxyShape* node = getShapeNode(args); + return node ? node->usdStage() : UsdStageRefPtr(); } //---------------------------------------------------------------------------------------------------------------------- @@ -168,278 +146,251 @@ AL_MAYA_DEFINE_COMMAND(ProxyShapeImport, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax ProxyShapeImport::createSyntax() { - MSyntax syntax; - syntax.useSelectionAsDefault(true); - syntax.setObjectType(MSyntax::kSelectionList, 0); - syntax.addFlag("-f", "-file", MSyntax::kString); - syntax.addFlag("-sid", "-stageId", MSyntax::kLong); - syntax.addFlag("-s", "-session", MSyntax::kString); - syntax.addFlag("-n", "-name", MSyntax::kString); - syntax.addFlag("-pp", "-primPath", MSyntax::kString); - syntax.addFlag("-epp", "-excludePrimPath", MSyntax::kString); - syntax.addFlag("-ctt", "-connectToTime", MSyntax::kBoolean); - syntax.addFlag("-ul", "-unloaded", MSyntax::kBoolean); - syntax.addFlag("-fp", "-fullpaths", MSyntax::kBoolean); - syntax.makeFlagMultiUse("-arp"); - - syntax.addFlag("-pmi", "-populationMaskInclude", MSyntax::kString); - - syntax.addFlag("-h", "-help", MSyntax::kNoArg); - return syntax; + MSyntax syntax; + syntax.useSelectionAsDefault(true); + syntax.setObjectType(MSyntax::kSelectionList, 0); + syntax.addFlag("-f", "-file", MSyntax::kString); + syntax.addFlag("-sid", "-stageId", MSyntax::kLong); + syntax.addFlag("-s", "-session", MSyntax::kString); + syntax.addFlag("-n", "-name", MSyntax::kString); + syntax.addFlag("-pp", "-primPath", MSyntax::kString); + syntax.addFlag("-epp", "-excludePrimPath", MSyntax::kString); + syntax.addFlag("-ctt", "-connectToTime", MSyntax::kBoolean); + syntax.addFlag("-ul", "-unloaded", MSyntax::kBoolean); + syntax.addFlag("-fp", "-fullpaths", MSyntax::kBoolean); + syntax.makeFlagMultiUse("-arp"); + + syntax.addFlag("-pmi", "-populationMaskInclude", MSyntax::kString); + + syntax.addFlag("-h", "-help", MSyntax::kNoArg); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- -bool ProxyShapeImport::isUndoable() const -{ - return true; -} +bool ProxyShapeImport::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeImport::undoIt() { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeImport::undoIt\n"); - // undo parenting - MFnDagNode fn; - for(uint32_t i = 0; i < m_parentTransforms.length(); ++i) - { - fn.setObject(m_parentTransforms[i]); - fn.removeChild(m_shape); - } - - return m_modifier.undoIt(); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeImport::undoIt\n"); + // undo parenting + MFnDagNode fn; + for (uint32_t i = 0; i < m_parentTransforms.length(); ++i) { + fn.setObject(m_parentTransforms[i]); + fn.removeChild(m_shape); + } + + return m_modifier.undoIt(); } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeImport::redoIt() { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeImport::redoIt\n"); - MStatus status = m_modifier.doIt(); - if(status) - { - // set the name of the node - MFnDagNode fnShape(m_shape); - - if(m_createdParent) - { - // if lots of TM's have been specified as parents, just name the shape explicitly - if(m_parentTransforms.length()) - { - if(m_proxy_name.length()) - { - fnShape.setName(m_proxy_name + "Shape"); - } - } - else - { - MFnDependencyNode fnTransform(fnShape.parent(0)); - fnShape.setName(fnTransform.name() + "Shape"); - if(m_proxy_name.length()) - { - fnTransform.setName(m_proxy_name); - } - else - { - fnTransform.setName("AL_usdmaya_Proxy"); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeImport::redoIt\n"); + MStatus status = m_modifier.doIt(); + if (status) { + // set the name of the node + MFnDagNode fnShape(m_shape); + + if (m_createdParent) { + // if lots of TM's have been specified as parents, just name the shape explicitly + if (m_parentTransforms.length()) { + if (m_proxy_name.length()) { + fnShape.setName(m_proxy_name + "Shape"); + } + } else { + MFnDependencyNode fnTransform(fnShape.parent(0)); + fnShape.setName(fnTransform.name() + "Shape"); + if (m_proxy_name.length()) { + fnTransform.setName(m_proxy_name); + } else { + fnTransform.setName("AL_usdmaya_Proxy"); + } + } } - } - } - status = m_modifier2.doIt(); - if(status) - { - // parent under instances - MFnDagNode fn; - for(uint32_t i = 0; i < m_parentTransforms.length(); ++i) - { - fn.setObject(m_parentTransforms[i]); - fn.addChild(m_shape, MFnDagNode::kNextPos, true); - } + status = m_modifier2.doIt(); + if (status) { + // parent under instances + MFnDagNode fn; + for (uint32_t i = 0; i < m_parentTransforms.length(); ++i) { + fn.setObject(m_parentTransforms[i]); + fn.addChild(m_shape, MFnDagNode::kNextPos, true); + } + } } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeImport::doIt(const MArgList& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeImport::doIt\n"); - MStatus status; - MArgDatabase database(syntax(), args, &status); - AL_MAYA_COMMAND_HELP(database, g_helpText); - if(!status) - return status; + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeImport::doIt\n"); + MStatus status; + MArgDatabase database(syntax(), args, &status); + AL_MAYA_COMMAND_HELP(database, g_helpText); + if (!status) + return status; + + // extract any parent transforms for the command. + { + MSelectionList items; + if (database.getObjects(items)) { + for (uint32_t i = 0; i < items.length(); ++i) { + MObject node; + items.getDependNode(i, node); + if (node.hasFn(MFn::kTransform)) { + m_createdParent = false; + m_parentTransforms.append(node); + } + } + } + } - // extract any parent transforms for the command. - { - MSelectionList items; - if(database.getObjects(items)) - { - for(uint32_t i = 0; i < items.length(); ++i) - { - MObject node; - items.getDependNode(i, node); - if(node.hasFn(MFn::kTransform)) - { - m_createdParent = false; - m_parentTransforms.append(node); + MString filePath; + int stageId; + MString sessionLayerSerialized; + MString primPath; + MString excludePrimPath; + + MString populationMaskIncludePath; + bool connectToTime = true; + + // extract command args + bool hasFilePath = database.isFlagSet("-f") && database.getFlagArgument("-f", 0, filePath); + bool hasStageCacheId = database.isFlagSet("-sid") + && database.getFlagArgument("-sid", 0, stageId) && (stageId != -1); + if (!hasFilePath && !hasStageCacheId) { + MGlobal::displayError("Neither file path nor stage Id specified."); + return MS::kFailure; + } else if (hasFilePath && hasStageCacheId) { + MGlobal::displayError("Cannot specify both file path and stage cache Id."); + return MS::kFailure; + } + + if (hasStageCacheId) { + UsdStageCache::Id stageCacheId = UsdStageCache::Id().FromLongInt(stageId); + if (!StageCache::Get().Contains(stageCacheId)) { + MGlobal::displayError( + MString("Cannot find stage with Id ") + stageId + " in stage cache."); + return MS::kFailure; } - } } - } - - MString filePath; - int stageId; - MString sessionLayerSerialized; - MString primPath; - MString excludePrimPath; - - MString populationMaskIncludePath; - bool connectToTime = true; - - // extract command args - bool hasFilePath = database.isFlagSet("-f") && database.getFlagArgument("-f", 0, filePath); - bool hasStageCacheId = database.isFlagSet("-sid") && database.getFlagArgument("-sid", 0, stageId) && (stageId != -1); - if(!hasFilePath && !hasStageCacheId) - { - MGlobal::displayError("Neither file path nor stage Id specified."); - return MS::kFailure; - } - else - if (hasFilePath && hasStageCacheId) - { - MGlobal::displayError("Cannot specify both file path and stage cache Id."); - return MS::kFailure; - } - if (hasStageCacheId) - { - UsdStageCache::Id stageCacheId = UsdStageCache::Id().FromLongInt(stageId); - if (!StageCache::Get().Contains(stageCacheId)) - { - MGlobal::displayError(MString("Cannot find stage with Id ") + stageId + " in stage cache."); - return MS::kFailure; + bool hasName = database.isFlagSet("-n"); + bool hasPrimPath = database.isFlagSet("-pp"); + bool hasExclPrimPath = database.isFlagSet("-epp"); + bool hasSession = database.isFlagSet("-s"); + bool hasStagePopulationMaskInclude = database.isFlagSet("-pmi"); + + if (hasName) { + database.getFlagArgument("-n", 0, m_proxy_name); } - } - - bool hasName = database.isFlagSet("-n"); - bool hasPrimPath = database.isFlagSet("-pp"); - bool hasExclPrimPath = database.isFlagSet("-epp"); - bool hasSession = database.isFlagSet("-s"); - bool hasStagePopulationMaskInclude = database.isFlagSet("-pmi"); - - if(hasName) { - database.getFlagArgument("-n", 0, m_proxy_name); - } - if(hasPrimPath) { - database.getFlagArgument("-pp", 0, primPath); - if (!SdfPath(primPath.asChar()).IsPrimPath()) { - MGlobal::displayError(MString("Invalid primPath: ") + primPath); - return MS::kFailure; + if (hasPrimPath) { + database.getFlagArgument("-pp", 0, primPath); + if (!SdfPath(primPath.asChar()).IsPrimPath()) { + MGlobal::displayError(MString("Invalid primPath: ") + primPath); + return MS::kFailure; + } } - } - if(hasExclPrimPath) { - database.getFlagArgument("-epp", 0, excludePrimPath); - if (!SdfPath(excludePrimPath.asChar()).IsPrimPath()) { - MGlobal::displayError(MString("Invalid excludePrimPath: ") + excludePrimPath); - return MS::kFailure; + if (hasExclPrimPath) { + database.getFlagArgument("-epp", 0, excludePrimPath); + if (!SdfPath(excludePrimPath.asChar()).IsPrimPath()) { + MGlobal::displayError(MString("Invalid excludePrimPath: ") + excludePrimPath); + return MS::kFailure; + } } - } - if(database.isFlagSet("-ctt")) { - database.getFlagArgument("-ctt", 0, connectToTime); - } - if(hasSession){ - database.getFlagArgument("-s", 0, sessionLayerSerialized); - } - if(hasStagePopulationMaskInclude) - { - database.getFlagArgument("-pmi", 0, populationMaskIncludePath); - } - - // what are we parenting this node to? - MObject firstParent; - if(m_parentTransforms.length()) - { - firstParent = m_parentTransforms[0]; - m_parentTransforms.remove(0); - } - else - { - // if no TM specified, create one - firstParent = m_modifier.createNode("transform"); - } - - // create the shape node - m_shape = m_modifier.createNode(nodes::ProxyShape::kTypeId, firstParent); - - // initialize the session layer, if given - if(hasSession) - { - auto sessionLayer = SdfLayer::CreateAnonymous(); - - sessionLayer->ImportFromString(AL::maya::utils::convert(sessionLayerSerialized)); - auto layerManager = nodes::LayerManager::findOrCreateManager(&m_modifier); - if (!layerManager) - { - MGlobal::displayError(MString("Unknown error getting/creating LayerManager node")); - return MS::kFailure; + if (database.isFlagSet("-ctt")) { + database.getFlagArgument("-ctt", 0, connectToTime); } - layerManager->addLayer(sessionLayer); - m_modifier.newPlugValueString(MPlug(m_shape, nodes::ProxyShape::sessionLayerName()), - AL::maya::utils::convert(sessionLayer->GetIdentifier())); - } - - // intialise the params - if(hasPrimPath) m_modifier.newPlugValueString(MPlug(m_shape, nodes::ProxyShape::primPath()), primPath); - if(hasExclPrimPath) m_modifier.newPlugValueString(MPlug(m_shape, nodes::ProxyShape::excludePrimPaths()), excludePrimPath); - if(database.isFlagSet("-ul")) - { - bool unloaded; - database.getFlagArgument("-ul", 0, unloaded); - m_modifier.newPlugValueBool(MPlug(m_shape, nodes::ProxyShape::unloaded()), unloaded); - } - - - if(hasStagePopulationMaskInclude) m_modifier.newPlugValueString(MPlug(m_shape, nodes::ProxyShape::populationMaskIncludePaths()), populationMaskIncludePath); - - // Prefer stage cache Id over file path. - if (hasStageCacheId) - { - m_modifier2.newPlugValueInt(MPlug(m_shape, nodes::ProxyShape::stageCacheId()), stageId); - } - else - { - m_modifier2.newPlugValueString(MPlug(m_shape, nodes::ProxyShape::filePath()), filePath); - } - - if(connectToTime) - { - MSelectionList sl; - sl.add("time1"); - MObject time1; - sl.getDependNode(0, time1); - MFnDependencyNode fnTime(time1); - MPlug outTime = fnTime.findPlug("outTime"); - m_modifier2.connect(outTime, MPlug(m_shape, nodes::ProxyShape::time())); - } - status = redoIt(); - CHECK_MSTATUS_AND_RETURN_IT(status); - MFnDagNode dagNode(m_shape, &status); - CHECK_MSTATUS_AND_RETURN_IT(status); - MDagPathArray dagPaths; - MStringArray stringNames; - CHECK_MSTATUS_AND_RETURN_IT(dagNode.getAllPaths(dagPaths)); - std::function getFullPath = - [&](const MDagPath& dagPath) { return dagPath.fullPathName(); }; - std::function getPartialPath = - [&](const MDagPath& dagPath) { return dagPath.partialPathName(); }; - auto getPath = database.isFlagSet("-fp") ? getFullPath : getPartialPath; - for(size_t i = 0; i< dagPaths.length(); i++) { - stringNames.append(getPath(dagPaths[i])); - } - clearResult(); - setResult(stringNames); - return status; + if (hasSession) { + database.getFlagArgument("-s", 0, sessionLayerSerialized); + } + if (hasStagePopulationMaskInclude) { + database.getFlagArgument("-pmi", 0, populationMaskIncludePath); + } + + // what are we parenting this node to? + MObject firstParent; + if (m_parentTransforms.length()) { + firstParent = m_parentTransforms[0]; + m_parentTransforms.remove(0); + } else { + // if no TM specified, create one + firstParent = m_modifier.createNode("transform"); + } + + // create the shape node + m_shape = m_modifier.createNode(nodes::ProxyShape::kTypeId, firstParent); + + // initialize the session layer, if given + if (hasSession) { + auto sessionLayer = SdfLayer::CreateAnonymous(); + + sessionLayer->ImportFromString(AL::maya::utils::convert(sessionLayerSerialized)); + auto layerManager = nodes::LayerManager::findOrCreateManager(&m_modifier); + if (!layerManager) { + MGlobal::displayError(MString("Unknown error getting/creating LayerManager node")); + return MS::kFailure; + } + layerManager->addLayer(sessionLayer); + m_modifier.newPlugValueString( + MPlug(m_shape, nodes::ProxyShape::sessionLayerName()), + AL::maya::utils::convert(sessionLayer->GetIdentifier())); + } + + // intialise the params + if (hasPrimPath) + m_modifier.newPlugValueString(MPlug(m_shape, nodes::ProxyShape::primPath()), primPath); + if (hasExclPrimPath) + m_modifier.newPlugValueString( + MPlug(m_shape, nodes::ProxyShape::excludePrimPaths()), excludePrimPath); + if (database.isFlagSet("-ul")) { + bool unloaded; + database.getFlagArgument("-ul", 0, unloaded); + m_modifier.newPlugValueBool(MPlug(m_shape, nodes::ProxyShape::unloaded()), unloaded); + } + + if (hasStagePopulationMaskInclude) + m_modifier.newPlugValueString( + MPlug(m_shape, nodes::ProxyShape::populationMaskIncludePaths()), + populationMaskIncludePath); + + // Prefer stage cache Id over file path. + if (hasStageCacheId) { + m_modifier2.newPlugValueInt(MPlug(m_shape, nodes::ProxyShape::stageCacheId()), stageId); + } else { + m_modifier2.newPlugValueString(MPlug(m_shape, nodes::ProxyShape::filePath()), filePath); + } + + if (connectToTime) { + MSelectionList sl; + sl.add("time1"); + MObject time1; + sl.getDependNode(0, time1); + MFnDependencyNode fnTime(time1); + MPlug outTime = fnTime.findPlug("outTime"); + m_modifier2.connect(outTime, MPlug(m_shape, nodes::ProxyShape::time())); + } + status = redoIt(); + CHECK_MSTATUS_AND_RETURN_IT(status); + MFnDagNode dagNode(m_shape, &status); + CHECK_MSTATUS_AND_RETURN_IT(status); + MDagPathArray dagPaths; + MStringArray stringNames; + CHECK_MSTATUS_AND_RETURN_IT(dagNode.getAllPaths(dagPaths)); + std::function getFullPath + = [&](const MDagPath& dagPath) { return dagPath.fullPathName(); }; + std::function getPartialPath + = [&](const MDagPath& dagPath) { return dagPath.partialPathName(); }; + auto getPath = database.isFlagSet("-fp") ? getFullPath : getPartialPath; + for (size_t i = 0; i < dagPaths.length(); i++) { + stringNames.append(getPath(dagPaths[i])); + } + clearResult(); + setResult(stringNames); + return status; } //---------------------------------------------------------------------------------------------------------------------- @@ -449,162 +400,141 @@ AL_MAYA_DEFINE_COMMAND(ProxyShapeFindLoadable, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax ProxyShapeFindLoadable::createSyntax() { - MSyntax syntax = setUpCommonSyntax(); - syntax.addFlag("-l", "-loaded"); - syntax.addFlag("-ul", "-unloaded"); - syntax.addFlag("-pp", "-primPath", MSyntax::kString); - return syntax; + MSyntax syntax = setUpCommonSyntax(); + syntax.addFlag("-l", "-loaded"); + syntax.addFlag("-ul", "-unloaded"); + syntax.addFlag("-pp", "-primPath", MSyntax::kString); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- -bool ProxyShapeFindLoadable::isUndoable() const -{ - return false; -} +bool ProxyShapeFindLoadable::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeFindLoadable::doIt(const MArgList& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeFindLoadable::doIt\n"); - try - { - MStatus status; - MArgDatabase db(syntax(), args, &status); - if(!status) - { - std::cout << status.errorString() << std::endl; - return status; - } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeFindLoadable::doIt\n"); + try { + MStatus status; + MArgDatabase db(syntax(), args, &status); + if (!status) { + std::cout << status.errorString() << std::endl; + return status; + } - AL_MAYA_COMMAND_HELP(db, g_helpText); - bool loaded = db.isFlagSet("-l"); - bool unloaded = db.isFlagSet("-ul"); - if(unloaded && loaded) - { - MGlobal::displayError("-loaded or -unloaded, there can be only one."); - return MS::kFailure; - } + AL_MAYA_COMMAND_HELP(db, g_helpText); + bool loaded = db.isFlagSet("-l"); + bool unloaded = db.isFlagSet("-ul"); + if (unloaded && loaded) { + MGlobal::displayError("-loaded or -unloaded, there can be only one."); + return MS::kFailure; + } - SdfPath path; - if(db.isFlagSet("-pp")) - { - MString pathString; - db.getFlagArgument("-pp", 0, pathString); - path = SdfPath(AL::maya::utils::convert(pathString)); - if (!path.IsPrimPath()) { - MGlobal::displayError(MString("Invalid primPath: ") + path.GetText()); - return MS::kFailure; - } - } - else - { - path = SdfPath::AbsoluteRootPath(); - } + SdfPath path; + if (db.isFlagSet("-pp")) { + MString pathString; + db.getFlagArgument("-pp", 0, pathString); + path = SdfPath(AL::maya::utils::convert(pathString)); + if (!path.IsPrimPath()) { + MGlobal::displayError(MString("Invalid primPath: ") + path.GetText()); + return MS::kFailure; + } + } else { + path = SdfPath::AbsoluteRootPath(); + } - MStringArray result; - UsdStageRefPtr stage = getShapeNodeStage(db); - if(!unloaded && !loaded) - { - SdfPathSet all = stage->FindLoadable(path); - result.setLength(all.size()); - uint32_t i = 0; - for(auto it = all.begin(); it != all.end(); ++it, ++i) - { - result[i] = AL::maya::utils::convert(it->GetString()); - } - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("all %zu\n", all.size()); - } - else - if(loaded && db.isFlagSet("-pp")) - { - SdfPathSet loadableSet = stage->FindLoadable(path); - SdfPathSet loadedSet = stage->GetLoadSet(); - SdfPathSet intersected; - - std::set_intersection( - loadedSet.begin(), loadedSet.end(), - loadableSet.begin(), loadableSet.end(), - std::inserter(intersected, intersected.end())); - - result.setLength(intersected.size()); - uint32_t i = 0; - for(auto it = intersected.begin(); it != intersected.end(); ++it, ++i) - { - result[i] = AL::maya::utils::convert(it->GetString()); - } - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadableSet %zu\n", loadableSet.size()); - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadedSet %zu\n", loadedSet.size()); - } - else - if(loaded) - { - SdfPathSet all = stage->GetLoadSet(); - result.setLength(all.size()); - uint32_t i = 0; - for(auto it = all.begin(); it != all.end(); ++it, ++i) - { - result[i] = AL::maya::utils::convert(it->GetString()); - } - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loaded %zu\n", all.size()); - } - else - if(unloaded && db.isFlagSet("-pp")) - { - SdfPathSet all = stage->FindLoadable(); - SdfPathSet loadableSet = stage->FindLoadable(path); - SdfPathSet loadedSet = stage->GetLoadSet(); - SdfPathSet diffed; - SdfPathSet intersected; - - std::set_difference( - loadedSet.begin(), loadedSet.end(), - all.begin(), all.end(), - std::inserter(diffed, diffed.end())); - - std::set_intersection( - diffed.begin(), diffed.end(), - loadableSet.begin(), loadableSet.end(), - std::inserter(intersected, intersected.end())); - - result.setLength(intersected.size()); - uint32_t i = 0; - for(auto it = intersected.begin(); it != intersected.end(); ++it, ++i) - { - result[i] = AL::maya::utils::convert(it->GetString()); - } - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("all %zu\n", all.size()); - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadableSet %zu\n", loadableSet.size()); - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadedSet %zu\n", loadedSet.size()); - } - else - if(unloaded) - { - SdfPathSet loadableSet = stage->FindLoadable(path); - SdfPathSet loadedSet = stage->GetLoadSet(); - SdfPathSet diffed; - - std::set_difference( - loadedSet.begin(), loadedSet.end(), - loadableSet.begin(), loadableSet.end(), - std::inserter(diffed, diffed.end())); - - result.setLength(diffed.size()); - uint32_t i = 0; - for(auto it = diffed.begin(); it != diffed.end(); ++it, ++i) - { - result[i] = AL::maya::utils::convert(it->GetString()); - } - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadedSet %zu\n", loadedSet.size()); - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadableSet %zu\n", loadableSet.size()); - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("diffed %zu\n", diffed.size()); + MStringArray result; + UsdStageRefPtr stage = getShapeNodeStage(db); + if (!unloaded && !loaded) { + SdfPathSet all = stage->FindLoadable(path); + result.setLength(all.size()); + uint32_t i = 0; + for (auto it = all.begin(); it != all.end(); ++it, ++i) { + result[i] = AL::maya::utils::convert(it->GetString()); + } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("all %zu\n", all.size()); + } else if (loaded && db.isFlagSet("-pp")) { + SdfPathSet loadableSet = stage->FindLoadable(path); + SdfPathSet loadedSet = stage->GetLoadSet(); + SdfPathSet intersected; + + std::set_intersection( + loadedSet.begin(), + loadedSet.end(), + loadableSet.begin(), + loadableSet.end(), + std::inserter(intersected, intersected.end())); + + result.setLength(intersected.size()); + uint32_t i = 0; + for (auto it = intersected.begin(); it != intersected.end(); ++it, ++i) { + result[i] = AL::maya::utils::convert(it->GetString()); + } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadableSet %zu\n", loadableSet.size()); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadedSet %zu\n", loadedSet.size()); + } else if (loaded) { + SdfPathSet all = stage->GetLoadSet(); + result.setLength(all.size()); + uint32_t i = 0; + for (auto it = all.begin(); it != all.end(); ++it, ++i) { + result[i] = AL::maya::utils::convert(it->GetString()); + } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loaded %zu\n", all.size()); + } else if (unloaded && db.isFlagSet("-pp")) { + SdfPathSet all = stage->FindLoadable(); + SdfPathSet loadableSet = stage->FindLoadable(path); + SdfPathSet loadedSet = stage->GetLoadSet(); + SdfPathSet diffed; + SdfPathSet intersected; + + std::set_difference( + loadedSet.begin(), + loadedSet.end(), + all.begin(), + all.end(), + std::inserter(diffed, diffed.end())); + + std::set_intersection( + diffed.begin(), + diffed.end(), + loadableSet.begin(), + loadableSet.end(), + std::inserter(intersected, intersected.end())); + + result.setLength(intersected.size()); + uint32_t i = 0; + for (auto it = intersected.begin(); it != intersected.end(); ++it, ++i) { + result[i] = AL::maya::utils::convert(it->GetString()); + } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("all %zu\n", all.size()); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadableSet %zu\n", loadableSet.size()); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadedSet %zu\n", loadedSet.size()); + } else if (unloaded) { + SdfPathSet loadableSet = stage->FindLoadable(path); + SdfPathSet loadedSet = stage->GetLoadSet(); + SdfPathSet diffed; + + std::set_difference( + loadedSet.begin(), + loadedSet.end(), + loadableSet.begin(), + loadableSet.end(), + std::inserter(diffed, diffed.end())); + + result.setLength(diffed.size()); + uint32_t i = 0; + for (auto it = diffed.begin(); it != diffed.end(); ++it, ++i) { + result[i] = AL::maya::utils::convert(it->GetString()); + } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadedSet %zu\n", loadedSet.size()); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("loadableSet %zu\n", loadableSet.size()); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("diffed %zu\n", diffed.size()); + } + setResult(result); + } catch (const MStatus& status) { + return status; } - setResult(result); - } - catch(const MStatus& status) - { - return status; - } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- @@ -614,125 +544,106 @@ AL_MAYA_DEFINE_COMMAND(ProxyShapeImportAllTransforms, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax ProxyShapeImportAllTransforms::createSyntax() { - MSyntax syntax = setUpCommonSyntax(); - syntax.addFlag("-p2p", "-pushToPrim", MSyntax::kBoolean); - syntax.addFlag("-pp", "-primPath", MSyntax::kString); - syntax.addFlag("-s", "-selected", MSyntax::kNoArg); - return syntax; + MSyntax syntax = setUpCommonSyntax(); + syntax.addFlag("-p2p", "-pushToPrim", MSyntax::kBoolean); + syntax.addFlag("-pp", "-primPath", MSyntax::kString); + syntax.addFlag("-s", "-selected", MSyntax::kNoArg); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- -bool ProxyShapeImportAllTransforms::isUndoable() const -{ - return true; -} +bool ProxyShapeImportAllTransforms::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeImportAllTransforms::undoIt() { - if(m_modifier2.doIt()) - { - return m_modifier.doIt(); - } - return MS::kFailure; + if (m_modifier2.doIt()) { + return m_modifier.doIt(); + } + return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeImportAllTransforms::redoIt() { - if(m_modifier.doIt()) - { - return m_modifier2.doIt(); - } - return MS::kFailure; + if (m_modifier.doIt()) { + return m_modifier2.doIt(); + } + return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeImportAllTransforms::doIt(const MArgList& args) { - try - { - MStatus status; - MArgDatabase db(syntax(), args, &status); - if(!status) - { - std::cout << status.errorString() << std::endl; - return status; - } + try { + MStatus status; + MArgDatabase db(syntax(), args, &status); + if (!status) { + std::cout << status.errorString() << std::endl; + return status; + } - AL_MAYA_COMMAND_HELP(db, g_helpText); - bool pushToPrim = false; - if(db.isFlagSet("-p2p")) - { - db.getFlagArgument("-p2p", 0, pushToPrim); - } + AL_MAYA_COMMAND_HELP(db, g_helpText); + bool pushToPrim = false; + if (db.isFlagSet("-p2p")) { + db.getFlagArgument("-p2p", 0, pushToPrim); + } - MString primPath; - if(db.isFlagSet("-pp")) - { - db.getFlagArgument("-pp", 0, primPath); - } + MString primPath; + if (db.isFlagSet("-pp")) { + db.getFlagArgument("-pp", 0, primPath); + } - // This command should pretty much always just - nodes::ProxyShape::TransformReason reason = nodes::ProxyShape::kRequested; - if(db.isFlagSet("-s")) - { - reason = nodes::ProxyShape::kSelection; - } + // This command should pretty much always just + nodes::ProxyShape::TransformReason reason = nodes::ProxyShape::kRequested; + if (db.isFlagSet("-s")) { + reason = nodes::ProxyShape::kSelection; + } - MDagPath shapePath = getShapePath(db); - MObject shapeObject = shapePath.node(); - MDagPath transformPath = shapePath; - transformPath.pop(); + MDagPath shapePath = getShapePath(db); + MObject shapeObject = shapePath.node(); + MDagPath transformPath = shapePath; + transformPath.pop(); - nodes::ProxyShape* shapeNode = getShapeNode(db); - if(!shapeNode) - { - throw MS::kFailure; - } + nodes::ProxyShape* shapeNode = getShapeNode(db); + if (!shapeNode) { + throw MS::kFailure; + } - UsdStageRefPtr stage = shapeNode->usdStage(); - if(!stage) - { - throw MS::kFailure; - } + UsdStageRefPtr stage = shapeNode->usdStage(); + if (!stage) { + throw MS::kFailure; + } - MDGModifier* modifier = 0; - if(pushToPrim) - { - modifier = &m_modifier2; - } + MDGModifier* modifier = 0; + if (pushToPrim) { + modifier = &m_modifier2; + } - if(primPath.length()) - { - SdfPath usdPath(AL::maya::utils::convert(primPath)); - UsdPrim prim = stage->GetPrimAtPath(usdPath); - if(!prim) - { - MGlobal::displayError(MString("The prim path specified could not be found in the USD stage: ") + primPath); - throw MS::kFailure; - } - else - { - shapeNode->makeUsdTransforms(prim, m_modifier, reason, modifier); - } - } - else - { - UsdPrim root = stage->GetPseudoRoot(); - for(auto it = root.GetChildren().begin(), end = root.GetChildren().end(); it != end; ++it) - { - SdfPath usdPath = it->GetPath(); - UsdPrim prim = stage->GetPrimAtPath(usdPath); - shapeNode->makeUsdTransforms(prim, m_modifier, reason, modifier); - } + if (primPath.length()) { + SdfPath usdPath(AL::maya::utils::convert(primPath)); + UsdPrim prim = stage->GetPrimAtPath(usdPath); + if (!prim) { + MGlobal::displayError( + MString("The prim path specified could not be found in the USD stage: ") + + primPath); + throw MS::kFailure; + } else { + shapeNode->makeUsdTransforms(prim, m_modifier, reason, modifier); + } + } else { + UsdPrim root = stage->GetPseudoRoot(); + for (auto it = root.GetChildren().begin(), end = root.GetChildren().end(); it != end; + ++it) { + SdfPath usdPath = it->GetPath(); + UsdPrim prim = stage->GetPrimAtPath(usdPath); + shapeNode->makeUsdTransforms(prim, m_modifier, reason, modifier); + } + } + } catch (const MStatus&) { + return MS::kFailure; } - } - catch(const MStatus&) - { - return MS::kFailure; - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- @@ -742,101 +653,81 @@ AL_MAYA_DEFINE_COMMAND(ProxyShapeRemoveAllTransforms, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax ProxyShapeRemoveAllTransforms::createSyntax() { - MSyntax syntax = setUpCommonSyntax(); - syntax.addFlag("-h", "-help", MSyntax::kNoArg); - syntax.addFlag("-pp", "-primPath", MSyntax::kString); - - // This flag is not to be used. I'm just using it for testing purposes. - syntax.addFlag("-s", "-selection", MSyntax::kNoArg); - syntax.addFlag("-f", "-force", MSyntax::kNoArg); - return syntax; + MSyntax syntax = setUpCommonSyntax(); + syntax.addFlag("-h", "-help", MSyntax::kNoArg); + syntax.addFlag("-pp", "-primPath", MSyntax::kString); + + // This flag is not to be used. I'm just using it for testing purposes. + syntax.addFlag("-s", "-selection", MSyntax::kNoArg); + syntax.addFlag("-f", "-force", MSyntax::kNoArg); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- -bool ProxyShapeRemoveAllTransforms::isUndoable() const -{ - return true; -} +bool ProxyShapeRemoveAllTransforms::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- -MStatus ProxyShapeRemoveAllTransforms::undoIt() -{ - return m_modifier.undoIt(); -} +MStatus ProxyShapeRemoveAllTransforms::undoIt() { return m_modifier.undoIt(); } //---------------------------------------------------------------------------------------------------------------------- -MStatus ProxyShapeRemoveAllTransforms::redoIt() -{ - return m_modifier.doIt(); -} +MStatus ProxyShapeRemoveAllTransforms::redoIt() { return m_modifier.doIt(); } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeRemoveAllTransforms::doIt(const MArgList& args) { - try - { - MStatus status; - MArgDatabase db(syntax(), args, &status); - if(!status) - { - std::cout << status.errorString() << std::endl; - return status; - } - - AL_MAYA_COMMAND_HELP(db, g_helpText); - nodes::ProxyShape* shapeNode = getShapeNode(db); - MDagPath shapePath = getShapePath(db); - MObject shapeObject = shapePath.node(); - MDagPath transformPath = shapePath; - transformPath.pop(); + try { + MStatus status; + MArgDatabase db(syntax(), args, &status); + if (!status) { + std::cout << status.errorString() << std::endl; + return status; + } - // This command should pretty much always just - nodes::ProxyShape::TransformReason reason = nodes::ProxyShape::kRequested; - if(db.isFlagSet("-s")) - { - reason = nodes::ProxyShape::kSelection; - } + AL_MAYA_COMMAND_HELP(db, g_helpText); + nodes::ProxyShape* shapeNode = getShapeNode(db); + MDagPath shapePath = getShapePath(db); + MObject shapeObject = shapePath.node(); + MDagPath transformPath = shapePath; + transformPath.pop(); + + // This command should pretty much always just + nodes::ProxyShape::TransformReason reason = nodes::ProxyShape::kRequested; + if (db.isFlagSet("-s")) { + reason = nodes::ProxyShape::kSelection; + } - MString primPath; - if(db.isFlagSet("-pp")) - { - db.getFlagArgument("-pp", 0, primPath); - } + MString primPath; + if (db.isFlagSet("-pp")) { + db.getFlagArgument("-pp", 0, primPath); + } - UsdStageRefPtr stage = shapeNode->usdStage(); - if(!stage) - { - throw MS::kFailure; - } + UsdStageRefPtr stage = shapeNode->usdStage(); + if (!stage) { + throw MS::kFailure; + } - if(primPath.length()) - { - SdfPath usdPath(AL::maya::utils::convert(primPath)); - UsdPrim prim = stage->GetPrimAtPath(usdPath); - if(!prim) - { - MGlobal::displayError(MString("The prim path specified could not be found in the USD stage: ") + primPath); - throw MS::kFailure; - } - else - { - shapeNode->removeUsdTransforms(prim, m_modifier, reason); - } - } - else - { - UsdPrim root = stage->GetPseudoRoot(); - for(auto it = root.GetChildren().begin(), end = root.GetChildren().end(); it != end; ++it) - { - shapeNode->removeUsdTransforms(*it, m_modifier, reason); - } + if (primPath.length()) { + SdfPath usdPath(AL::maya::utils::convert(primPath)); + UsdPrim prim = stage->GetPrimAtPath(usdPath); + if (!prim) { + MGlobal::displayError( + MString("The prim path specified could not be found in the USD stage: ") + + primPath); + throw MS::kFailure; + } else { + shapeNode->removeUsdTransforms(prim, m_modifier, reason); + } + } else { + UsdPrim root = stage->GetPseudoRoot(); + for (auto it = root.GetChildren().begin(), end = root.GetChildren().end(); it != end; + ++it) { + shapeNode->removeUsdTransforms(*it, m_modifier, reason); + } + } + } catch (const MStatus&) { + return MS::kFailure; } - } - catch(const MStatus&) - { - return MS::kFailure; - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- @@ -846,71 +737,61 @@ AL_MAYA_DEFINE_COMMAND(ProxyShapeResync, AL_usdmaya); MSyntax ProxyShapeResync::createSyntax() { - MSyntax syntax = setUpCommonSyntax(); - syntax.addFlag("-pp", "-primPath", MSyntax::kString); - return syntax; + MSyntax syntax = setUpCommonSyntax(); + syntax.addFlag("-pp", "-primPath", MSyntax::kString); + return syntax; } -bool ProxyShapeResync::isUndoable() const -{ - return false; -} +bool ProxyShapeResync::isUndoable() const { return false; } MStatus ProxyShapeResync::doIt(const MArgList& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeResync::doIt\n"); - try - { - MStatus status; - MArgDatabase db(syntax(), args, &status); - if(!status) - { - std::cout << status.errorString() << std::endl; - return status; - } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeResync::doIt\n"); + try { + MStatus status; + MArgDatabase db(syntax(), args, &status); + if (!status) { + std::cout << status.errorString() << std::endl; + return status; + } - AL_MAYA_COMMAND_HELP(db, g_helpText); - m_shapeNode = getShapeNode(db); + AL_MAYA_COMMAND_HELP(db, g_helpText); + m_shapeNode = getShapeNode(db); - if(db.isFlagSet("-pp")) - { - MString pathString; - db.getFlagArgument("-pp", 0, pathString); - SdfPath primPath = SdfPath(AL::maya::utils::convert(pathString)); - if (!primPath.IsPrimPath()) { - MGlobal::displayError(MString("Invalid primPath: ") + pathString); - return MS::kFailure; - } + if (db.isFlagSet("-pp")) { + MString pathString; + db.getFlagArgument("-pp", 0, pathString); + SdfPath primPath = SdfPath(AL::maya::utils::convert(pathString)); + if (!primPath.IsPrimPath()) { + MGlobal::displayError(MString("Invalid primPath: ") + pathString); + return MS::kFailure; + } - UsdStageRefPtr stage = m_shapeNode->getUsdStage(); - UsdPrim prim = stage->GetPrimAtPath(primPath); + UsdStageRefPtr stage = m_shapeNode->getUsdStage(); + UsdPrim prim = stage->GetPrimAtPath(primPath); - if(prim.IsValid()) - { - m_resyncPrimPath = primPath; - } + if (prim.IsValid()) { + m_resyncPrimPath = primPath; + } + } + } catch (const MStatus& status) { + return status; } - } - catch(const MStatus& status) - { - return status; - } - return redoIt(); + return redoIt(); } MStatus ProxyShapeResync::redoIt() { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeResync::redoIt\n"); - if(m_resyncPrimPath == SdfPath::EmptyPath()) - { - MGlobal::displayError("ProxyShapeResync: PrimPath is empty. "); - return MStatus::kFailure; - } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeResync::redoIt\n"); + if (m_resyncPrimPath == SdfPath::EmptyPath()) { + MGlobal::displayError("ProxyShapeResync: PrimPath is empty. "); + return MStatus::kFailure; + } - m_shapeNode->primChangedAtPath(m_resyncPrimPath); + m_shapeNode->primChangedAtPath(m_resyncPrimPath); - return MStatus::kSuccess; + return MStatus::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- @@ -920,112 +801,93 @@ AL_MAYA_DEFINE_COMMAND(InternalProxyShapeSelect, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax InternalProxyShapeSelect::createSyntax() { - MSyntax syntax = setUpCommonSyntax(); - syntax.useSelectionAsDefault(false); - syntax.addFlag("-pp", "-primPath", MSyntax::kString); - syntax.addFlag("-h", "-help", MSyntax::kNoArg); - syntax.addFlag("-cl", "-clear", MSyntax::kNoArg); - syntax.addFlag("-a", "-append", MSyntax::kNoArg); - syntax.addFlag("-tgl", "-toggle", MSyntax::kNoArg); - syntax.addFlag("-r", "-replace", MSyntax::kNoArg); - syntax.addFlag("-d", "-deselect", MSyntax::kNoArg); - syntax.makeFlagMultiUse("-pp"); - return syntax; + MSyntax syntax = setUpCommonSyntax(); + syntax.useSelectionAsDefault(false); + syntax.addFlag("-pp", "-primPath", MSyntax::kString); + syntax.addFlag("-h", "-help", MSyntax::kNoArg); + syntax.addFlag("-cl", "-clear", MSyntax::kNoArg); + syntax.addFlag("-a", "-append", MSyntax::kNoArg); + syntax.addFlag("-tgl", "-toggle", MSyntax::kNoArg); + syntax.addFlag("-r", "-replace", MSyntax::kNoArg); + syntax.addFlag("-d", "-deselect", MSyntax::kNoArg); + syntax.makeFlagMultiUse("-pp"); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- -bool InternalProxyShapeSelect::isUndoable() const -{ - return true; -} +bool InternalProxyShapeSelect::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- MStatus InternalProxyShapeSelect::doIt(const MArgList& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("InternalProxyShapeSelect::doIt\n"); - try - { - MStatus status; - MArgDatabase db(syntax(), args, &status); - if(!status) - { - std::cout << status.errorString() << std::endl; - return status; - } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("InternalProxyShapeSelect::doIt\n"); + try { + MStatus status; + MArgDatabase db(syntax(), args, &status); + if (!status) { + std::cout << status.errorString() << std::endl; + return status; + } - AL_MAYA_COMMAND_HELP(db, g_helpText); - m_proxy = getShapeNode(db); - if(!m_proxy) - { - throw MS::kFailure; - } - m_previous = m_proxy->selectionList(); - if(db.isFlagSet("-cl")) - { - } - else - { - SelectionListModifierFunc selListModiferFunc; - if(db.isFlagSet("-d")) - { - m_new = m_previous; - selListModiferFunc = &nodes::SelectionList::remove; - } - else - if(db.isFlagSet("-tgl")) - { - m_new = m_previous; - selListModiferFunc = &nodes::SelectionList::toggle; - } - else - { - if(!db.isFlagSet("-r")) - { - m_new = m_previous; + AL_MAYA_COMMAND_HELP(db, g_helpText); + m_proxy = getShapeNode(db); + if (!m_proxy) { + throw MS::kFailure; } + m_previous = m_proxy->selectionList(); + if (db.isFlagSet("-cl")) { + } else { + SelectionListModifierFunc selListModiferFunc; + if (db.isFlagSet("-d")) { + m_new = m_previous; + selListModiferFunc = &nodes::SelectionList::remove; + } else if (db.isFlagSet("-tgl")) { + m_new = m_previous; + selListModiferFunc = &nodes::SelectionList::toggle; + } else { + if (!db.isFlagSet("-r")) { + m_new = m_previous; + } + + selListModiferFunc = &nodes::SelectionList::add; + } - selListModiferFunc = &nodes::SelectionList::add; - } - - for(uint32_t i = 0, n = db.numberOfFlagUses("-pp"); i < n; ++i) - { - MArgList args; - db.getFlagArgumentList("-pp", i, args); - MString pathString = args.asString(0); - SdfPath path(AL::maya::utils::convert(pathString)); - if (!path.IsPrimPath()) { - MGlobal::displayError(MString("Invalid primPath: ") + pathString); - return MS::kFailure; + for (uint32_t i = 0, n = db.numberOfFlagUses("-pp"); i < n; ++i) { + MArgList args; + db.getFlagArgumentList("-pp", i, args); + MString pathString = args.asString(0); + SdfPath path(AL::maya::utils::convert(pathString)); + if (!path.IsPrimPath()) { + MGlobal::displayError(MString("Invalid primPath: ") + pathString); + return MS::kFailure; + } + (m_new.*selListModiferFunc)(path); + } } - (m_new.*selListModiferFunc)(path); - } + } catch (const MStatus& status) { + return status; } - } - catch(const MStatus& status) - { - return status; - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- MStatus InternalProxyShapeSelect::undoIt() { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("InternalProxyShapeSelect::undoIt\n"); - m_proxy->selectionList() = m_previous; - if(MGlobal::kInteractive == MGlobal::mayaState()) - MGlobal::executeCommand("refresh", false, false); - return MS::kSuccess; + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("InternalProxyShapeSelect::undoIt\n"); + m_proxy->selectionList() = m_previous; + if (MGlobal::kInteractive == MGlobal::mayaState()) + MGlobal::executeCommand("refresh", false, false); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus InternalProxyShapeSelect::redoIt() { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("InternalProxyShapeSelect::redoIt\n"); - m_proxy->selectionList() = m_new; - if(MGlobal::kInteractive == MGlobal::mayaState()) - MGlobal::executeCommand("refresh", false, false); - return MS::kSuccess; + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("InternalProxyShapeSelect::redoIt\n"); + m_proxy->selectionList() = m_new; + if (MGlobal::kInteractive == MGlobal::mayaState()) + MGlobal::executeCommand("refresh", false, false); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- @@ -1035,139 +897,112 @@ AL_MAYA_DEFINE_COMMAND(ProxyShapeSelect, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax ProxyShapeSelect::createSyntax() { - MSyntax syntax = setUpCommonSyntax(); - syntax.addFlag("-pp", "-primPath", MSyntax::kString); - syntax.addFlag("-h", "-help", MSyntax::kNoArg); - syntax.addFlag("-cl", "-clear", MSyntax::kNoArg); - syntax.addFlag("-a", "-append", MSyntax::kNoArg); - syntax.addFlag("-tgl", "-toggle", MSyntax::kNoArg); - syntax.addFlag("-r", "-replace", MSyntax::kNoArg); - syntax.addFlag("-d", "-deselect", MSyntax::kNoArg); - syntax.addFlag("-i", "-internal", MSyntax::kNoArg); - syntax.makeFlagMultiUse("-pp"); - return syntax; + MSyntax syntax = setUpCommonSyntax(); + syntax.addFlag("-pp", "-primPath", MSyntax::kString); + syntax.addFlag("-h", "-help", MSyntax::kNoArg); + syntax.addFlag("-cl", "-clear", MSyntax::kNoArg); + syntax.addFlag("-a", "-append", MSyntax::kNoArg); + syntax.addFlag("-tgl", "-toggle", MSyntax::kNoArg); + syntax.addFlag("-r", "-replace", MSyntax::kNoArg); + syntax.addFlag("-d", "-deselect", MSyntax::kNoArg); + syntax.addFlag("-i", "-internal", MSyntax::kNoArg); + syntax.makeFlagMultiUse("-pp"); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- -bool ProxyShapeSelect::isUndoable() const -{ - return true; -} +bool ProxyShapeSelect::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeSelect::doIt(const MArgList& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeSelect::doIt\n"); - try - { - MStatus status; - MArgDatabase db(syntax(), args, &status); - if(!status) - { - std::cout << status.errorString() << std::endl; - return status; - } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeSelect::doIt\n"); + try { + MStatus status; + MArgDatabase db(syntax(), args, &status); + if (!status) { + std::cout << status.errorString() << std::endl; + return status; + } - AL_MAYA_COMMAND_HELP(db, g_helpText); - nodes::ProxyShape* proxy = getShapeNode(db); - if(!proxy) - { - throw MS::kFailure; - } - SdfPathVector orderedPaths; - nodes::SelectionUndoHelper::SdfPathHashSet unorderedPaths; + AL_MAYA_COMMAND_HELP(db, g_helpText); + nodes::ProxyShape* proxy = getShapeNode(db); + if (!proxy) { + throw MS::kFailure; + } + SdfPathVector orderedPaths; + nodes::SelectionUndoHelper::SdfPathHashSet unorderedPaths; + + MGlobal::ListAdjustment mode = MGlobal::kAddToList; + if (db.isFlagSet("-cl")) { + mode = MGlobal::kReplaceList; + } else { + for (uint32_t i = 0, n = db.numberOfFlagUses("-pp"); i < n; ++i) { + MArgList args; + db.getFlagArgumentList("-pp", i, args); + MString pathString = args.asString(0); + + SdfPath path(AL::maya::utils::convert(pathString)); + + if (!proxy->selectabilityDB().isPathUnselectable(path) && path.IsAbsolutePath()) { + auto insertResult = unorderedPaths.insert(path); + if (insertResult.second) { + orderedPaths.push_back(path); + } + } + } - MGlobal::ListAdjustment mode = MGlobal::kAddToList; - if(db.isFlagSet("-cl")) - { - mode = MGlobal::kReplaceList; - } - else - { - for(uint32_t i = 0, n = db.numberOfFlagUses("-pp"); i < n; ++i) - { - MArgList args; - db.getFlagArgumentList("-pp", i, args); - MString pathString = args.asString(0); - - SdfPath path(AL::maya::utils::convert(pathString)); - - if(!proxy->selectabilityDB().isPathUnselectable(path) && path.IsAbsolutePath()) - { - auto insertResult = unorderedPaths.insert(path); - if (insertResult.second) { - orderedPaths.push_back(path); - } + if (db.isFlagSet("-tgl")) { + mode = MGlobal::kXORWithList; + } else if (db.isFlagSet("-a")) { + mode = MGlobal::kAddToList; + } else if (db.isFlagSet("-r")) { + mode = MGlobal::kReplaceList; + } else if (db.isFlagSet("-d")) { + mode = MGlobal::kRemoveFromList; + } } - } - - if(db.isFlagSet("-tgl")) - { - mode = MGlobal::kXORWithList; - } - else - if(db.isFlagSet("-a")) - { - mode = MGlobal::kAddToList; - } - else - if(db.isFlagSet("-r")) - { - mode = MGlobal::kReplaceList; - } - else - if(db.isFlagSet("-d")) - { - mode = MGlobal::kRemoveFromList; - } - } - const bool isInternal = db.isFlagSet("-i"); + const bool isInternal = db.isFlagSet("-i"); - m_helper = new nodes::SelectionUndoHelper(proxy, unorderedPaths, mode, isInternal); - if(!proxy->doSelect(*m_helper, orderedPaths)) - { - delete m_helper; - m_helper = 0; + m_helper = new nodes::SelectionUndoHelper(proxy, unorderedPaths, mode, isInternal); + if (!proxy->doSelect(*m_helper, orderedPaths)) { + delete m_helper; + m_helper = 0; + } + return _redoIt(isInternal); + } catch (const MStatus& status) { + return status; + } catch (...) { + MStatus status = MS::kFailure; + status.perror("(ProxyShapeSelect::doIt) Unknown internal failure!"); + return status; } - return _redoIt(isInternal); - } - catch(const MStatus& status) - { - return status; - } - catch(...) - { - MStatus status = MS::kFailure; - status.perror("(ProxyShapeSelect::doIt) Unknown internal failure!"); - return status; - } } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeSelect::undoIt() { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeSelect::undoIt\n"); - if(m_helper) m_helper->undoIt(); - if(MGlobal::kInteractive == MGlobal::mayaState()) - MGlobal::executeCommand("refresh", false, false); - return MS::kSuccess; + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeSelect::undoIt\n"); + if (m_helper) + m_helper->undoIt(); + if (MGlobal::kInteractive == MGlobal::mayaState()) + MGlobal::executeCommand("refresh", false, false); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -MStatus ProxyShapeSelect::redoIt() -{ - return _redoIt(false); -} +MStatus ProxyShapeSelect::redoIt() { return _redoIt(false); } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeSelect::_redoIt(bool isInternal) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeSelect::redoIt\n"); - if(m_helper) m_helper->doIt(); - if(MGlobal::kInteractive == MGlobal::mayaState() && !isInternal) - MGlobal::executeCommandOnIdle("refresh", false); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeSelect::redoIt\n"); + if (m_helper) + m_helper->doIt(); + if (MGlobal::kInteractive == MGlobal::mayaState() && !isInternal) + MGlobal::executeCommandOnIdle("refresh", false); - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- @@ -1177,79 +1012,70 @@ AL_MAYA_DEFINE_COMMAND(ProxyShapePostSelect, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax ProxyShapePostSelect::createSyntax() { - MSyntax syntax = setUpCommonSyntax(); - return syntax; + MSyntax syntax = setUpCommonSyntax(); + return syntax; } - //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapePostSelect::redoIt() { - m_proxy->setChangedSelectionState(false); - MSelectionList sl; - MGlobal::getActiveSelectionList(sl); - MString command; - MFnDagNode fn(m_proxy->thisMObject()); - for (const auto& path : m_proxy->selectedPaths()) { - auto obj = m_proxy->findRequiredPath(path); - if (obj != MObject::kNullObj) { - MFnDagNode dagNode(obj); - MDagPath dg; - dagNode.getPath(dg); - if (!sl.hasItem(dg)) { - command += "AL_usdmaya_ProxyShapeSelect -i -d -pp \""; - command += path.GetText(); - command += "\" \""; - command += fn.fullPathName(); - command += "\";"; - } + m_proxy->setChangedSelectionState(false); + MSelectionList sl; + MGlobal::getActiveSelectionList(sl); + MString command; + MFnDagNode fn(m_proxy->thisMObject()); + for (const auto& path : m_proxy->selectedPaths()) { + auto obj = m_proxy->findRequiredPath(path); + if (obj != MObject::kNullObj) { + MFnDagNode dagNode(obj); + MDagPath dg; + dagNode.getPath(dg); + if (!sl.hasItem(dg)) { + command += "AL_usdmaya_ProxyShapeSelect -i -d -pp \""; + command += path.GetText(); + command += "\" \""; + command += fn.fullPathName(); + command += "\";"; + } + } + } + if (command.length() > 0) { + MGlobal::executeCommand(command, false, false); } - } - if (command.length() > 0) { - MGlobal::executeCommand(command, false, false); - } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapePostSelect::undoIt() { - m_proxy->setChangedSelectionState(true); - return MS::kSuccess; + m_proxy->setChangedSelectionState(true); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -bool ProxyShapePostSelect::isUndoable() const -{ - return true; -} +bool ProxyShapePostSelect::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapePostSelect::doIt(const MArgList& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapePostSelect::doIt\n"); - try - { - MStatus status; - MArgDatabase db(syntax(), args, &status); - if(!status) - { - std::cout << status.errorString() << std::endl; - return status; - } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapePostSelect::doIt\n"); + try { + MStatus status; + MArgDatabase db(syntax(), args, &status); + if (!status) { + std::cout << status.errorString() << std::endl; + return status; + } - AL_MAYA_COMMAND_HELP(db, g_helpText); - m_proxy = getShapeNode(db); - if(!m_proxy) - { - throw MS::kFailure; + AL_MAYA_COMMAND_HELP(db, g_helpText); + m_proxy = getShapeNode(db); + if (!m_proxy) { + throw MS::kFailure; + } + } catch (const MStatus& status) { + return status; } - } - catch(const MStatus& status) - { - return status; - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- @@ -1257,107 +1083,86 @@ MStatus ProxyShapePostSelect::doIt(const MArgList& args) AL_MAYA_DEFINE_COMMAND(ProxyShapeImportPrimPathAsMaya, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- -MObject ProxyShapeImportPrimPathAsMaya::makePrimTansforms( - nodes::ProxyShape* shapeNode, - UsdPrim usdPrim) +MObject +ProxyShapeImportPrimPathAsMaya::makePrimTansforms(nodes::ProxyShape* shapeNode, UsdPrim usdPrim) { - return shapeNode->makeUsdTransformChain(usdPrim, m_modifier, nodes::ProxyShape::kRequired); + return shapeNode->makeUsdTransformChain(usdPrim, m_modifier, nodes::ProxyShape::kRequired); } //---------------------------------------------------------------------------------------------------------------------- MSyntax ProxyShapeImportPrimPathAsMaya::createSyntax() { - MSyntax syntax = setUpCommonSyntax(); - syntax.addFlag("-pp", "-primPath", MSyntax::kString); - syntax.addFlag("-ap", "-asProxy", MSyntax::kNoArg); - syntax.addFlag("-h", "-help", MSyntax::kNoArg); - return syntax; + MSyntax syntax = setUpCommonSyntax(); + syntax.addFlag("-pp", "-primPath", MSyntax::kString); + syntax.addFlag("-ap", "-asProxy", MSyntax::kNoArg); + syntax.addFlag("-h", "-help", MSyntax::kNoArg); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- -bool ProxyShapeImportPrimPathAsMaya::isUndoable() const -{ - return true; -} +bool ProxyShapeImportPrimPathAsMaya::isUndoable() const { return true; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapeImportPrimPathAsMaya::doIt(const MArgList& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeImportPrimPathAsMaya::doIt\n"); - try - { - MStatus status; - MArgDatabase db(syntax(), args, &status); - if(!status) - { - std::cout << status.errorString() << std::endl; - return status; - } - - AL_MAYA_COMMAND_HELP(db, g_helpText); - MDagPath shapePath = getShapePath(db); - m_transformPath = shapePath; - m_transformPath.pop(); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapeImportPrimPathAsMaya::doIt\n"); + try { + MStatus status; + MArgDatabase db(syntax(), args, &status); + if (!status) { + std::cout << status.errorString() << std::endl; + return status; + } - if(db.isFlagSet("-pp")) - { - MString pathString; - db.getFlagArgument("-pp", 0, pathString); - m_path = SdfPath(AL::maya::utils::convert(pathString)); - if (!m_path.IsPrimPath()) { - MGlobal::displayError(MString("Invalid primPath: ") + pathString); - return MS::kFailure; - } - } + AL_MAYA_COMMAND_HELP(db, g_helpText); + MDagPath shapePath = getShapePath(db); + m_transformPath = shapePath; + m_transformPath.pop(); + + if (db.isFlagSet("-pp")) { + MString pathString; + db.getFlagArgument("-pp", 0, pathString); + m_path = SdfPath(AL::maya::utils::convert(pathString)); + if (!m_path.IsPrimPath()) { + MGlobal::displayError(MString("Invalid primPath: ") + pathString); + return MS::kFailure; + } + } - m_asProxyShape = false; - if(db.isFlagSet("-ap")) { - m_asProxyShape = true; - } + m_asProxyShape = false; + if (db.isFlagSet("-ap")) { + m_asProxyShape = true; + } - nodes::ProxyShape* shapeNode = getShapeNode(db); - if(!shapeNode) - { - throw MS::kFailure; - } + nodes::ProxyShape* shapeNode = getShapeNode(db); + if (!shapeNode) { + throw MS::kFailure; + } - UsdPrim usdPrim = shapeNode->usdStage()->GetPrimAtPath(m_path); - if(!usdPrim) - { - throw MS::kFailure; - } + UsdPrim usdPrim = shapeNode->usdStage()->GetPrimAtPath(m_path); + if (!usdPrim) { + throw MS::kFailure; + } - MObject parentTransform = makePrimTansforms(shapeNode, usdPrim); - if(m_asProxyShape) - { - MFnDagNode fn; - MObject node = m_modifier.createNode(nodes::ProxyShape::kTypeId, parentTransform); - fn.setObject(node); - fn.setName(usdPrim.GetName().GetText()); - } - else - { + MObject parentTransform = makePrimTansforms(shapeNode, usdPrim); + if (m_asProxyShape) { + MFnDagNode fn; + MObject node = m_modifier.createNode(nodes::ProxyShape::kTypeId, parentTransform); + fn.setObject(node); + fn.setName(usdPrim.GetName().GetText()); + } else { + } + } catch (const MStatus& status) { + return status; } - } - catch(const MStatus& status) - { - return status; - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- -MStatus ProxyShapeImportPrimPathAsMaya::redoIt() -{ - return m_modifier.doIt(); -} +MStatus ProxyShapeImportPrimPathAsMaya::redoIt() { return m_modifier.doIt(); } //---------------------------------------------------------------------------------------------------------------------- -MStatus ProxyShapeImportPrimPathAsMaya::undoIt() -{ - return m_modifier.undoIt(); -} - +MStatus ProxyShapeImportPrimPathAsMaya::undoIt() { return m_modifier.undoIt(); } //---------------------------------------------------------------------------------------------------------------------- @@ -1367,293 +1172,334 @@ AL_MAYA_DEFINE_COMMAND(TranslatePrim, AL_usdmaya); MSyntax TranslatePrim::createSyntax() { - MSyntax syntax = setUpCommonSyntax(); - syntax.addFlag("-ip", "-importPaths", MSyntax::kString); - syntax.addFlag("-tp", "-teardownPaths", MSyntax::kString); - syntax.addFlag("-up", "-updatePaths", MSyntax::kString); - syntax.addFlag("-fi", "-forceImport", MSyntax::kNoArg); - syntax.addFlag("-fd", "-forceDefault", MSyntax::kNoArg); - syntax.addFlag("-ptp", "-pushToPrim", MSyntax::kBoolean); - syntax.addFlag("-rav", "-readAnimatedValues", MSyntax::kBoolean); - syntax.addFlag("-r", "-recursive"); - return syntax; + MSyntax syntax = setUpCommonSyntax(); + syntax.addFlag("-ip", "-importPaths", MSyntax::kString); + syntax.addFlag("-tp", "-teardownPaths", MSyntax::kString); + syntax.addFlag("-up", "-updatePaths", MSyntax::kString); + syntax.addFlag("-fi", "-forceImport", MSyntax::kNoArg); + syntax.addFlag("-fd", "-forceDefault", MSyntax::kNoArg); + syntax.addFlag("-ptp", "-pushToPrim", MSyntax::kBoolean); + syntax.addFlag("-rav", "-readAnimatedValues", MSyntax::kBoolean); + syntax.addFlag("-r", "-recursive"); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- MStatus TranslatePrim::doIt(const MArgList& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("TranslatePrim::doIt\n"); - try - { - MStatus status; - MArgDatabase db(syntax(), args, &status); - if(!status) - { - std::cout << status.errorString() << std::endl; - return status; - } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("TranslatePrim::doIt\n"); + try { + MStatus status; + MArgDatabase db(syntax(), args, &status); + if (!status) { + std::cout << status.errorString() << std::endl; + return status; + } - AL_MAYA_COMMAND_HELP(db, g_helpText); - m_proxy = getShapeNode(db); + AL_MAYA_COMMAND_HELP(db, g_helpText); + m_proxy = getShapeNode(db); - m_recursive = db.isFlagSet("-r"); + m_recursive = db.isFlagSet("-r"); - if(db.isFlagSet("-ip")) - { - MString pathsCsv; - db.getFlagArgument("-ip", 0, pathsCsv); - m_importPaths = m_proxy->getPrimPathsFromCommaJoinedString(pathsCsv); - } + if (db.isFlagSet("-ip")) { + MString pathsCsv; + db.getFlagArgument("-ip", 0, pathsCsv); + m_importPaths = m_proxy->getPrimPathsFromCommaJoinedString(pathsCsv); + } - if(db.isFlagSet("-tp")) - { - MString pathsCsv; - db.getFlagArgument("-tp", 0, pathsCsv); - m_teardownPaths = m_proxy->getPrimPathsFromCommaJoinedString(pathsCsv); - } + if (db.isFlagSet("-tp")) { + MString pathsCsv; + db.getFlagArgument("-tp", 0, pathsCsv); + m_teardownPaths = m_proxy->getPrimPathsFromCommaJoinedString(pathsCsv); + } - if(db.isFlagSet("-up")) - { - MString pathsCsv; - db.getFlagArgument("-up", 0, pathsCsv); - m_updatePaths = m_proxy->getPrimPathsFromCommaJoinedString(pathsCsv); - } + if (db.isFlagSet("-up")) { + MString pathsCsv; + db.getFlagArgument("-up", 0, pathsCsv); + m_updatePaths = m_proxy->getPrimPathsFromCommaJoinedString(pathsCsv); + } - // change the translator context to force import - if(db.isFlagSet("-fi")) - { - tp.setForcePrimImport(true); - } + // change the translator context to force import + if (db.isFlagSet("-fi")) { + tp.setForcePrimImport(true); + } - // should pushToPrim be enabled on transforms when translating? - if(db.isFlagSet("-ptp")) - { - bool value = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"); - db.getFlagArgument("-ptp", 0, value); - tp.setPushToPrim(value); - } + // should pushToPrim be enabled on transforms when translating? + if (db.isFlagSet("-ptp")) { + bool value = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"); + db.getFlagArgument("-ptp", 0, value); + tp.setPushToPrim(value); + } - // should pushToPrim be enabled on transforms when translating? - if(db.isFlagSet("-rav")) - { - bool value = true; - db.getFlagArgument("-rav", 0, value); - tp.setReadAnimatedValues(value); - } + // should pushToPrim be enabled on transforms when translating? + if (db.isFlagSet("-rav")) { + bool value = true; + db.getFlagArgument("-rav", 0, value); + tp.setReadAnimatedValues(value); + } - // change the translator context to read default value - if(db.isFlagSet("-fd")) - { - m_proxy->context()->setForceDefaultRead(true); - } + // change the translator context to read default value + if (db.isFlagSet("-fd")) { + m_proxy->context()->setForceDefaultRead(true); + } - if(m_recursive) - { - const bool forceImport = db.isFlagSet("-fi"); - MFnDagNode fn(m_proxy->thisMObject()); - MDagPath proxyTransformPath; - fn.getPath(proxyTransformPath); - proxyTransformPath.pop(); - - auto& manufacture = m_proxy->translatorManufacture(); - - auto stage = m_proxy->usdStage(); - SdfPathVector newImportPaths; - for(auto importPath : m_importPaths) - { - { - auto prim = stage->GetPrimAtPath(importPath); - if(prim) - { - if(manufacture.get(prim)) - { - newImportPaths.push_back(importPath); + if (m_recursive) { + const bool forceImport = db.isFlagSet("-fi"); + MFnDagNode fn(m_proxy->thisMObject()); + MDagPath proxyTransformPath; + fn.getPath(proxyTransformPath); + proxyTransformPath.pop(); + + auto& manufacture = m_proxy->translatorManufacture(); + + auto stage = m_proxy->usdStage(); + SdfPathVector newImportPaths; + for (auto importPath : m_importPaths) { + { + auto prim = stage->GetPrimAtPath(importPath); + if (prim) { + if (manufacture.get(prim)) { + newImportPaths.push_back(importPath); + } + } + } + auto newPrimSet = m_proxy->huntForNativeNodesUnderPrim( + proxyTransformPath, importPath, manufacture, forceImport); + for (auto it : newPrimSet) { + newImportPaths.push_back(it.GetPath()); + } } - } - } - auto newPrimSet = m_proxy->huntForNativeNodesUnderPrim(proxyTransformPath, importPath, manufacture, forceImport); - for(auto it : newPrimSet) - { - newImportPaths.push_back(it.GetPath()); - } - } - std::swap(m_importPaths, newImportPaths); - - SdfPathVector newTeardownPaths; - for(auto teardownPath : m_teardownPaths) - { - { - auto prim = stage->GetPrimAtPath(teardownPath); - if(prim) - { - if(manufacture.get(prim)) - { - newTeardownPaths.push_back(teardownPath); + std::swap(m_importPaths, newImportPaths); + + SdfPathVector newTeardownPaths; + for (auto teardownPath : m_teardownPaths) { + { + auto prim = stage->GetPrimAtPath(teardownPath); + if (prim) { + if (manufacture.get(prim)) { + newTeardownPaths.push_back(teardownPath); + } + } + } + auto newPrimSet = m_proxy->huntForNativeNodesUnderPrim( + proxyTransformPath, teardownPath, manufacture, true); + for (auto it : newPrimSet) { + newTeardownPaths.push_back(it.GetPath()); + } } - } - } - auto newPrimSet = m_proxy->huntForNativeNodesUnderPrim(proxyTransformPath, teardownPath, manufacture, true); - for(auto it : newPrimSet) - { - newTeardownPaths.push_back(it.GetPath()); - } - } - std::swap(m_teardownPaths, newTeardownPaths); - - SdfPathVector newUpdatePaths; - for(auto updatePath : m_updatePaths) - { - { - auto prim = stage->GetPrimAtPath(updatePath); - if(prim) - { - if(manufacture.get(prim)) - { - newUpdatePaths.push_back(updatePath); + std::swap(m_teardownPaths, newTeardownPaths); + + SdfPathVector newUpdatePaths; + for (auto updatePath : m_updatePaths) { + { + auto prim = stage->GetPrimAtPath(updatePath); + if (prim) { + if (manufacture.get(prim)) { + newUpdatePaths.push_back(updatePath); + } + } + } + auto newPrimSet = m_proxy->huntForNativeNodesUnderPrim( + proxyTransformPath, updatePath, manufacture, true); + for (auto it : newPrimSet) { + // We only want to list the prims that are actually updateable. + auto translator = manufacture.get(it); + if (translator && translator->supportsUpdate()) { + newUpdatePaths.push_back(it.GetPath()); + } + } } - } - } - auto newPrimSet = m_proxy->huntForNativeNodesUnderPrim(proxyTransformPath, updatePath, manufacture, true); - for(auto it : newPrimSet) - { - // We only want to list the prims that are actually updateable. - auto translator = manufacture.get(it); - if(translator && translator->supportsUpdate()) - { - newUpdatePaths.push_back(it.GetPath()); - } + std::swap(m_updatePaths, newUpdatePaths); } - } - std::swap(m_updatePaths, newUpdatePaths); + } catch (const MStatus& status) { + return status; } - } - catch(const MStatus& status) - { - return status; - } - return redoIt(); + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- -bool TranslatePrim::isUndoable() const -{ - return false; -} +bool TranslatePrim::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MStatus TranslatePrim::redoIt() { - MDagPath parentTransform = m_proxy->parentTransform(); - - // This makes sure we cannot run import twice. - SdfPathVector newImportPaths; - for(auto importPath : m_importPaths) - { - uint32_t selected = 0; - uint32_t required = 0; - uint32_t refCount = 0; - m_proxy->getCounts(importPath, selected, required, refCount); - if(!required && !refCount) - { - newImportPaths.push_back(importPath); + MDagPath parentTransform = m_proxy->parentTransform(); + + // This makes sure we cannot run import twice. + SdfPathVector newImportPaths; + for (auto importPath : m_importPaths) { + uint32_t selected = 0; + uint32_t required = 0; + uint32_t refCount = 0; + m_proxy->getCounts(importPath, selected, required, refCount); + if (!required && !refCount) { + newImportPaths.push_back(importPath); + } } - } - - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("TranslatePrim::redoIt\n"); - m_proxy->translatePrimPathsIntoMaya(newImportPaths, m_teardownPaths, tp); - - // construct locks and selectability for imported prims - if(m_proxy->isLockPrimFeatureActive()) - { - m_proxy->removeMetaData(m_teardownPaths); - m_proxy->processChangedMetaData(SdfPathVector(), newImportPaths); - } - - auto stage = m_proxy->usdStage(); - auto manufacture = m_proxy->translatorManufacture(); - for(auto it : m_updatePaths) - { - auto prim = stage->GetPrimAtPath(it); - if(prim) - { - auto translator = manufacture.get(prim); - if(translator && translator->supportsUpdate()) - { - translator->update(prim); - } - else - { - MString err = "Update requested on prim that does not support update: "; - err += it.GetText(); - MGlobal::displayWarning(err); - } + + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("TranslatePrim::redoIt\n"); + m_proxy->translatePrimPathsIntoMaya(newImportPaths, m_teardownPaths, tp); + + // construct locks and selectability for imported prims + if (m_proxy->isLockPrimFeatureActive()) { + m_proxy->removeMetaData(m_teardownPaths); + m_proxy->processChangedMetaData(SdfPathVector(), newImportPaths); } - } - return MStatus::kSuccess; -} + auto stage = m_proxy->usdStage(); + auto manufacture = m_proxy->translatorManufacture(); + for (auto it : m_updatePaths) { + auto prim = stage->GetPrimAtPath(it); + if (prim) { + auto translator = manufacture.get(prim); + if (translator && translator->supportsUpdate()) { + translator->update(prim); + } else { + MString err = "Update requested on prim that does not support update: "; + err += it.GetText(); + MGlobal::displayWarning(err); + } + } + } + return MStatus::kSuccess; +} //---------------------------------------------------------------------------------------------------------------------- void constructProxyShapeCommandGuis() { - { - AL::maya::utils::CommandGuiHelper commandGui("AL_usdmaya_ProxyShapeImport", "Proxy Shape Import", "Import", "USD/Proxy Shape/Import", false); - commandGui.addFilePathOption("file", "File Path", AL::maya::utils::CommandGuiHelper::kLoad, "USD all (*.usdc *.usda *.usd);;USD crate (*.usdc) (*.usdc);;USD Ascii (*.usda) (*.usda);;USD (*.usd) (*.usd)", AL::maya::utils::CommandGuiHelper::kStringOptional); - commandGui.addIntOption("stageId", "Stage cache Id", -1, false); - commandGui.addStringOption("primPath", "USD Prim Path", "", false, AL::maya::utils::CommandGuiHelper::kStringOptional); - commandGui.addStringOption("excludePrimPath", "Exclude Prim Path", "", false, AL::maya::utils::CommandGuiHelper::kStringOptional); - commandGui.addStringOption("name", "Proxy Shape Node Name", "", false, AL::maya::utils::CommandGuiHelper::kStringOptional); - commandGui.addBoolOption("connectToTime", "Connect to Time", true, true); - commandGui.addBoolOption("unloaded", "Opens the layer with payloads unloaded.", false, true); - } - - { - AL::maya::utils::CommandGuiHelper commandGui("AL_usdmaya_ProxyShapeImportPrimPathAsMaya", "Import Prim Path as Maya xforms", "Import", "USD/Proxy Shape/Import Prim Path as Maya", true); - commandGui.addStringOption("primPath", "USD Prim Path", "", false, AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); - commandGui.addFlagOption("asProxy", "Import Subsection as a Proxy Node", false, true); - } - - { - AL::maya::utils::CommandGuiHelper commandGui("AL_usdmaya_ProxyShapeImportAllTransforms", "Import All Transforms", "Import", "USD/Proxy Shape/Import Transforms as Transforms", true); - commandGui.addBoolOption("pushToPrim", "Push to Prim", false, true); - } - - { - AL::maya::utils::CommandGuiHelper commandGui("AL_usdmaya_ProxyShapeRemoveAllTransforms", "Remove All Transforms", "Remove", "USD/Proxy Shape/Remove all Transforms", true); - } - - { - AL::maya::utils::CommandGuiHelper commandGui("AL_usdmaya_ProxyShapeResync", "Resync at Prim path", "", "Resync and reload prim at passed in primpath", false); - commandGui.addStringOption("primPath", "USD Prim Path", "", false, AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); - } - - { - AL::maya::utils::CommandGuiHelper commandGui("AL_usdmaya_TranslatePrim", "Translate a Prim at path", "", "Run the translator to either import or teardown the Prims at the paths", false); - commandGui.addStringOption("importPath", "USD Prim Path", "", false, AL::maya::utils::CommandGuiHelper::kStringOptional); - commandGui.addStringOption("teardownPath", "USD Prim Path", "", false, AL::maya::utils::CommandGuiHelper::kStringOptional); - } + { + AL::maya::utils::CommandGuiHelper commandGui( + "AL_usdmaya_ProxyShapeImport", + "Proxy Shape Import", + "Import", + "USD/Proxy Shape/Import", + false); + commandGui.addFilePathOption( + "file", + "File Path", + AL::maya::utils::CommandGuiHelper::kLoad, + "USD all (*.usdc *.usda *.usd);;USD crate (*.usdc) (*.usdc);;USD Ascii (*.usda) " + "(*.usda);;USD (*.usd) (*.usd)", + AL::maya::utils::CommandGuiHelper::kStringOptional); + commandGui.addIntOption("stageId", "Stage cache Id", -1, false); + commandGui.addStringOption( + "primPath", + "USD Prim Path", + "", + false, + AL::maya::utils::CommandGuiHelper::kStringOptional); + commandGui.addStringOption( + "excludePrimPath", + "Exclude Prim Path", + "", + false, + AL::maya::utils::CommandGuiHelper::kStringOptional); + commandGui.addStringOption( + "name", + "Proxy Shape Node Name", + "", + false, + AL::maya::utils::CommandGuiHelper::kStringOptional); + commandGui.addBoolOption("connectToTime", "Connect to Time", true, true); + commandGui.addBoolOption( + "unloaded", "Opens the layer with payloads unloaded.", false, true); + } + + { + AL::maya::utils::CommandGuiHelper commandGui( + "AL_usdmaya_ProxyShapeImportPrimPathAsMaya", + "Import Prim Path as Maya xforms", + "Import", + "USD/Proxy Shape/Import Prim Path as Maya", + true); + commandGui.addStringOption( + "primPath", + "USD Prim Path", + "", + false, + AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); + commandGui.addFlagOption("asProxy", "Import Subsection as a Proxy Node", false, true); + } + + { + AL::maya::utils::CommandGuiHelper commandGui( + "AL_usdmaya_ProxyShapeImportAllTransforms", + "Import All Transforms", + "Import", + "USD/Proxy Shape/Import Transforms as Transforms", + true); + commandGui.addBoolOption("pushToPrim", "Push to Prim", false, true); + } + + { + AL::maya::utils::CommandGuiHelper commandGui( + "AL_usdmaya_ProxyShapeRemoveAllTransforms", + "Remove All Transforms", + "Remove", + "USD/Proxy Shape/Remove all Transforms", + true); + } + + { + AL::maya::utils::CommandGuiHelper commandGui( + "AL_usdmaya_ProxyShapeResync", + "Resync at Prim path", + "", + "Resync and reload prim at passed in primpath", + false); + commandGui.addStringOption( + "primPath", + "USD Prim Path", + "", + false, + AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); + } + + { + AL::maya::utils::CommandGuiHelper commandGui( + "AL_usdmaya_TranslatePrim", + "Translate a Prim at path", + "", + "Run the translator to either import or teardown the Prims at the paths", + false); + commandGui.addStringOption( + "importPath", + "USD Prim Path", + "", + false, + AL::maya::utils::CommandGuiHelper::kStringOptional); + commandGui.addStringOption( + "teardownPath", + "USD Prim Path", + "", + false, + AL::maya::utils::CommandGuiHelper::kStringOptional); + } } //---------------------------------------------------------------------------------------------------------------------- void constructPickModeCommandGuis() { - const nodes::ProxyShape::PickMode pickMode = MGlobal::optionVarExists("AL_usdmaya_pickMode") - ? nodes::ProxyShape::PickMode(MGlobal::optionVarIntValue("AL_usdmaya_pickMode")) // Restore from prefs - : nodes::ProxyShape::PickMode::kPrims; // Fall back to default - AL::maya::utils::MenuBuilder::addEntry("USD/Pick Mode/Prims", - "optionVar -iv \\\"AL_usdmaya_pickMode\\\" 0", - false, // Checkbox - false, // Checkbox state - true, // Radio button - pickMode == nodes::ProxyShape::PickMode::kPrims); // Radio button state - AL::maya::utils::MenuBuilder::addEntry("USD/Pick Mode/Models", - "optionVar -iv \\\"AL_usdmaya_pickMode\\\" 1", - false, // Checkbox - false, // Checkbox state - true, // Radio button - pickMode == nodes::ProxyShape::PickMode::kModels); // Radio button state + const nodes::ProxyShape::PickMode pickMode = MGlobal::optionVarExists("AL_usdmaya_pickMode") + ? nodes::ProxyShape::PickMode( + MGlobal::optionVarIntValue("AL_usdmaya_pickMode")) // Restore from prefs + : nodes::ProxyShape::PickMode::kPrims; // Fall back to default + AL::maya::utils::MenuBuilder::addEntry( + "USD/Pick Mode/Prims", + "optionVar -iv \\\"AL_usdmaya_pickMode\\\" 0", + false, // Checkbox + false, // Checkbox state + true, // Radio button + pickMode == nodes::ProxyShape::PickMode::kPrims); // Radio button state + AL::maya::utils::MenuBuilder::addEntry( + "USD/Pick Mode/Models", + "optionVar -iv \\\"AL_usdmaya_pickMode\\\" 1", + false, // Checkbox + false, // Checkbox state + true, // Radio button + pickMode == nodes::ProxyShape::PickMode::kModels); // Radio button state } //---------------------------------------------------------------------------------------------------------------------- @@ -1662,48 +1508,39 @@ AL_MAYA_DEFINE_COMMAND(ProxyShapePrintRefCountState, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax ProxyShapePrintRefCountState::createSyntax() { - MSyntax syntax = setUpCommonSyntax(); - syntax.addFlag("-h", "-help", MSyntax::kNoArg); - return syntax; + MSyntax syntax = setUpCommonSyntax(); + syntax.addFlag("-h", "-help", MSyntax::kNoArg); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- -bool ProxyShapePrintRefCountState::isUndoable() const -{ - return false; -} +bool ProxyShapePrintRefCountState::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapePrintRefCountState::doIt(const MArgList& args) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapePrintRefCountState::doIt\n"); - try - { - MStatus status; - MArgDatabase db(syntax(), args, &status); - if(!status) - { - std::cout << status.errorString() << std::endl; - return status; - } + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ProxyShapePrintRefCountState::doIt\n"); + try { + MStatus status; + MArgDatabase db(syntax(), args, &status); + if (!status) { + std::cout << status.errorString() << std::endl; + return status; + } - AL_MAYA_COMMAND_HELP(db, g_helpText); + AL_MAYA_COMMAND_HELP(db, g_helpText); - /// find the proxy shape node - nodes::ProxyShape* shapeNode = getShapeNode(db); - if(shapeNode) - { - shapeNode->printRefCounts(); + /// find the proxy shape node + nodes::ProxyShape* shapeNode = getShapeNode(db); + if (shapeNode) { + shapeNode->printRefCounts(); + } + } catch (const MStatus& status) { + return status; } - } - catch(const MStatus& status) - { - return status; - } - return MS::kSuccess; + return MS::kSuccess; } - //---------------------------------------------------------------------------------------------------------------------- // Documentation strings. //---------------------------------------------------------------------------------------------------------------------- @@ -1853,7 +1690,6 @@ AL_usdmaya_ProxyShapePrintRefCountState Overview: AL_usdmaya_ProxyShapePrintRefCountState -p "ProxyShapeName"; )"; - //---------------------------------------------------------------------------------------------------------------------- const char* const ProxyShapeSelect::g_helpText = R"( AL_usdmaya_ProxyShapeSelect Overview: @@ -1930,7 +1766,6 @@ AL_usdmaya_InternalProxyShapeSelect Overview: )"; - //---------------------------------------------------------------------------------------------------------------------- const char* const ProxyShapeResync::g_helpText = R"( AL_usdmaya_ProxyShapeResync Overview: @@ -1966,7 +1801,7 @@ TranslatePrim Overview: their corresponding prim type is brought into the scene. )"; //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapeCommands.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapeCommands.h index d500af9e18..6274164503 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapeCommands.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapeCommands.h @@ -33,107 +33,111 @@ namespace usdmaya { namespace cmds { //---------------------------------------------------------------------------------------------------------------------- -/// \brief Base class for all proxy shape commands. Sets up some common command syntax, along with a few handy utility +/// \brief Base class for all proxy shape commands. Sets up some common command syntax, along with +/// a few handy utility /// methods. /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ProxyShapeCommandBase - : public MPxCommand +class ProxyShapeCommandBase : public MPxCommand { public: + /// \brief sets up some core/common command params - enables specification of selectin list as + /// a command argument \return the syntax object that contains the common command arguments + static MSyntax setUpCommonSyntax(); - /// \brief sets up some core/common command params - enables specification of selectin list as a command argument - /// \return the syntax object that contains the common command arguments - static MSyntax setUpCommonSyntax(); + /// \brief find the proxy shape node + /// \param args the valid argument data base + /// \return the dag path to the proxy shape (extracted from the selected nodes used as the + /// command args) + MDagPath getShapePath(const MArgDatabase& args); - /// \brief find the proxy shape node - /// \param args the valid argument data base - /// \return the dag path to the proxy shape (extracted from the selected nodes used as the command args) - MDagPath getShapePath(const MArgDatabase& args); - - /// \brief find the proxy shape nodeata base - /// \param args the valid argument data base - /// \return the proxy shape specified in the selected command arguments - nodes::ProxyShape* getShapeNode(const MArgDatabase& args); - - /// \brief get the USD stage - /// \param args the valid argument data base - /// \return the stage from the proxy shape specified in the selected command arguments - UsdStageRefPtr getShapeNodeStage(const MArgDatabase& args); + /// \brief find the proxy shape nodeata base + /// \param args the valid argument data base + /// \return the proxy shape specified in the selected command arguments + nodes::ProxyShape* getShapeNode(const MArgDatabase& args); + /// \brief get the USD stage + /// \param args the valid argument data base + /// \return the stage from the proxy shape specified in the selected command arguments + UsdStageRefPtr getShapeNodeStage(const MArgDatabase& args); }; //---------------------------------------------------------------------------------------------------------------------- /// \brief Imports a proxy shape into maya /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ProxyShapeImport - : public MPxCommand +class ProxyShapeImport : public MPxCommand { - MDagModifier m_modifier; - MDagModifier m_modifier2; - MObjectArray m_parentTransforms; - MObject m_shape; - MString m_proxy_name; - bool m_createdParent = true; + MDagModifier m_modifier; + MDagModifier m_modifier2; + MObjectArray m_parentTransforms; + MObject m_shape; + MString m_proxy_name; + bool m_createdParent = true; + public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus undoIt() override; - MStatus redoIt() override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus undoIt() override; + MStatus redoIt() override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief ProxyShapeFindLoadable /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ProxyShapeFindLoadable - : public ProxyShapeCommandBase +class ProxyShapeFindLoadable : public ProxyShapeCommandBase { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief ProxyShapeImportAllTransforms -/// From a proxy shape, this will import all usdPrims in the stage as AL_usdmaya_Transform nodes. +/// From a proxy shape, this will import all usdPrims in the stage as AL_usdmaya_Transform +/// nodes. /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ProxyShapeImportAllTransforms - : public ProxyShapeCommandBase +class ProxyShapeImportAllTransforms : public ProxyShapeCommandBase { - MDagModifier m_modifier; - MDagModifier m_modifier2; + MDagModifier m_modifier; + MDagModifier m_modifier2; + public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus undoIt() override; - MStatus redoIt() override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus undoIt() override; + MStatus redoIt() override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief ProxyShapeRemoveAllTransforms -/// A command that will remove all AL::usdmaya::nodes::Transform nodes from a given AL_usd_ProxyShape +/// A command that will remove all AL::usdmaya::nodes::Transform nodes from a given +/// AL_usd_ProxyShape /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ProxyShapeRemoveAllTransforms - : public ProxyShapeCommandBase +class ProxyShapeRemoveAllTransforms : public ProxyShapeCommandBase { - MDagModifier m_modifier; + MDagModifier m_modifier; + public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus undoIt() override; - MStatus redoIt() override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus undoIt() override; + MStatus redoIt() override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- @@ -141,150 +145,155 @@ class ProxyShapeRemoveAllTransforms /// A command that will import a portion of a proxyNode as Maya geometry/transforms /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ProxyShapeImportPrimPathAsMaya - : public ProxyShapeCommandBase +class ProxyShapeImportPrimPathAsMaya : public ProxyShapeCommandBase { - MDagModifier m_modifier; - SdfPath m_path; - MDagPath m_transformPath; - fileio::ImporterParams m_importParams; - MObjectArray m_nodesToKill; - bool m_asProxyShape; - - MObject makePrimTansforms( - nodes::ProxyShape* shapeNode, - UsdPrim usdPrim); - - MObject makeUsdTransformChain( - std::map& mapped, - const UsdPrim& usdPrim, - const MPlug& outStage, - const MPlug& outTime, - const MObject& parentXForm); + MDagModifier m_modifier; + SdfPath m_path; + MDagPath m_transformPath; + fileio::ImporterParams m_importParams; + MObjectArray m_nodesToKill; + bool m_asProxyShape; + + MObject makePrimTansforms(nodes::ProxyShape* shapeNode, UsdPrim usdPrim); + + MObject makeUsdTransformChain( + std::map& mapped, + const UsdPrim& usdPrim, + const MPlug& outStage, + const MPlug& outTime, + const MObject& parentXForm); + public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus undoIt() override; - MStatus redoIt() override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus undoIt() override; + MStatus redoIt() override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief ProxyShapePrintRefCountState /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ProxyShapePrintRefCountState - : public ProxyShapeCommandBase +class ProxyShapePrintRefCountState : public ProxyShapeCommandBase { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief ProxyShapeResync /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ProxyShapeResync - : public ProxyShapeCommandBase +class ProxyShapeResync : public ProxyShapeCommandBase { - SdfPath m_resyncPrimPath; - UsdPrim m_resyncPrim; - nodes::ProxyShape* m_shapeNode; + SdfPath m_resyncPrimPath; + UsdPrim m_resyncPrim; + nodes::ProxyShape* m_shapeNode; + public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; - MStatus redoIt() override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; + MStatus redoIt() override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief ProxyShapeSelect /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ProxyShapeSelect - : public ProxyShapeCommandBase +class ProxyShapeSelect : public ProxyShapeCommandBase { - nodes::SelectionUndoHelper* m_helper; + nodes::SelectionUndoHelper* m_helper; + public: - ProxyShapeSelect () : m_helper(0) {} - ~ProxyShapeSelect() { delete m_helper; } - AL_MAYA_DECLARE_COMMAND(); + ProxyShapeSelect() + : m_helper(0) + { + } + ~ProxyShapeSelect() { delete m_helper; } + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; - MStatus undoIt() override; - MStatus redoIt() override; - MStatus _redoIt(bool isInternal); + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; + MStatus undoIt() override; + MStatus redoIt() override; + MStatus _redoIt(bool isInternal); }; //---------------------------------------------------------------------------------------------------------------------- /// \brief ProxyShapeSelect /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ProxyShapePostSelect - : public ProxyShapeCommandBase +class ProxyShapePostSelect : public ProxyShapeCommandBase { - nodes::ProxyShape* m_proxy; + nodes::ProxyShape* m_proxy; + public: - ~ProxyShapePostSelect() {} - AL_MAYA_DECLARE_COMMAND(); + ~ProxyShapePostSelect() { } + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; - MStatus undoIt() override; - MStatus redoIt() override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; + MStatus undoIt() override; + MStatus redoIt() override; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief InternalProxyShapeSelect /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class InternalProxyShapeSelect - : public ProxyShapeCommandBase +class InternalProxyShapeSelect : public ProxyShapeCommandBase { - nodes::ProxyShape* m_proxy; - nodes::SelectionList m_previous; - nodes::SelectionList m_new; + nodes::ProxyShape* m_proxy; + nodes::SelectionList m_previous; + nodes::SelectionList m_new; + public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; - MStatus undoIt() override; - MStatus redoIt() override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; + MStatus undoIt() override; + MStatus redoIt() override; }; - //---------------------------------------------------------------------------------------------------------------------- /// \brief TranslatePrim /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class TranslatePrim - : public ProxyShapeCommandBase +class TranslatePrim : public ProxyShapeCommandBase { - fileio::translators::TranslatorParameters tp; + fileio::translators::TranslatorParameters tp; - nodes::ProxyShape* m_proxy; - SdfPathVector m_importPaths; - SdfPathVector m_teardownPaths; - SdfPathVector m_updatePaths; - bool m_recursive; + nodes::ProxyShape* m_proxy; + SdfPathVector m_importPaths; + SdfPathVector m_teardownPaths; + SdfPathVector m_updatePaths; + bool m_recursive; public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; - MStatus redoIt() override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; + MStatus redoIt() override; }; - -/// \brief This function will generate all of the MEL script menus, and the option boxes, for all of the proxy shape +/// \brief This function will generate all of the MEL script menus, and the option boxes, for all +/// of the proxy shape /// commands. /// \ingroup commands AL_USDMAYA_PUBLIC @@ -296,7 +305,7 @@ AL_USDMAYA_PUBLIC void constructPickModeCommandGuis(); //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapePostLoadProcess.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapePostLoadProcess.cpp index e3176b4649..6350d229ce 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapePostLoadProcess.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapePostLoadProcess.cpp @@ -32,104 +32,105 @@ namespace { struct CompareLayerHandle { - bool operator () (const SdfLayerHandle& a, const SdfLayerHandle& b) const - { - return a->GetDisplayName() < b->GetDisplayName(); - } + bool operator()(const SdfLayerHandle& a, const SdfLayerHandle& b) const + { + return a->GetDisplayName() < b->GetDisplayName(); + } }; -typedef std::set LayerSet; -typedef std::map LayerMap; -typedef std::map LayerToObjectMap; +typedef std::set LayerSet; +typedef std::map LayerMap; +typedef std::map LayerToObjectMap; //---------------------------------------------------------------------------------------------------------------------- struct ImportCallback { - enum ScriptType : uint32_t - { - kMel, - kPython - }; - - void setCallbackType(TfToken scriptType) - { - if(scriptType == "mel") + enum ScriptType : uint32_t { - type = kMel; - } - else - if(scriptType == "py") + kMel, + kPython + }; + + void setCallbackType(TfToken scriptType) { - type = kPython; + if (scriptType == "mel") { + type = kMel; + } else if (scriptType == "py") { + type = kPython; + } } - } - std::string name; - VtDictionary params; - ScriptType type; + std::string name; + VtDictionary params; + ScriptType type; }; //---------------------------------------------------------------------------------------------------------------------- void huntForNativeNodes( - const MDagPath& proxyTransformPath, - std::vector& schemaPrims, + const MDagPath& proxyTransformPath, + std::vector& schemaPrims, std::vector& postCallBacks, - nodes::ProxyShape& proxy) + nodes::ProxyShape& proxy) { - UsdStageRefPtr stage = proxy.getUsdStage(); - fileio::translators::TranslatorManufacture& manufacture = proxy.translatorManufacture(); - - fileio::SchemaPrimsUtils utils(manufacture); - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("huntForNativeNodes::huntForNativeNodes\n"); - fileio::TransformIterator it(stage, proxyTransformPath); - for(; !it.done(); it.next()) - { - UsdPrim prim = it.prim(); - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("huntForNativeNodes: PrimName %s\n", prim.GetName().GetText()); - - // If the prim isn't importable by default then don't add it to the list - fileio::translators::TranslatorRefPtr t = utils.isSchemaPrim(prim); - if(t && t->importableByDefault()) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::huntForNativeNodes found matching schema %s\n", prim.GetPath().GetText()); - schemaPrims.push_back(prim); - } + UsdStageRefPtr stage = proxy.getUsdStage(); + fileio::translators::TranslatorManufacture& manufacture = proxy.translatorManufacture(); + + fileio::SchemaPrimsUtils utils(manufacture); + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("huntForNativeNodes::huntForNativeNodes\n"); + fileio::TransformIterator it(stage, proxyTransformPath); + for (; !it.done(); it.next()) { + UsdPrim prim = it.prim(); + TF_DEBUG(ALUSDMAYA_COMMANDS) + .Msg("huntForNativeNodes: PrimName %s\n", prim.GetName().GetText()); + + // If the prim isn't importable by default then don't add it to the list + fileio::translators::TranslatorRefPtr t = utils.isSchemaPrim(prim); + if (t && t->importableByDefault()) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShapePostLoadProcess::huntForNativeNodes found matching schema %s\n", + prim.GetPath().GetText()); + schemaPrims.push_back(prim); + } - VtDictionary customData = prim.GetCustomData(); - VtDictionary::const_iterator postCallBacksEntry = customData.find("callbacks"); - if(postCallBacksEntry != customData.end()) - { - //Get the list of post callbacks - VtDictionary melCallbacks = postCallBacksEntry->second.Get(); - - for(VtDictionary::const_iterator melCommand = melCallbacks.begin(), end = melCallbacks.end(); - melCommand != end; - ++melCommand) - { - ImportCallback importCallback; - importCallback.name = melCommand->first; - importCallback.type = ImportCallback::kMel; - importCallback.params = melCommand->second.Get(); - - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::huntForNativeNodes adding post callback from %s\n", prim.GetPath().GetText()); - postCallBacks.push_back(importCallback); - } + VtDictionary customData = prim.GetCustomData(); + VtDictionary::const_iterator postCallBacksEntry = customData.find("callbacks"); + if (postCallBacksEntry != customData.end()) { + // Get the list of post callbacks + VtDictionary melCallbacks = postCallBacksEntry->second.Get(); + + for (VtDictionary::const_iterator melCommand = melCallbacks.begin(), + end = melCallbacks.end(); + melCommand != end; + ++melCommand) { + ImportCallback importCallback; + importCallback.name = melCommand->first; + importCallback.type = ImportCallback::kMel; + importCallback.params = melCommand->second.Get(); + + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShapePostLoadProcess::huntForNativeNodes adding post callback from " + "%s\n", + prim.GetPath().GetText()); + postCallBacks.push_back(importCallback); + } + } } - } } -} // anon +} // namespace //---------------------------------------------------------------------------------------------------------------------- -static bool parentNodeIsUnmerged(const UsdPrim & prim) +static bool parentNodeIsUnmerged(const UsdPrim& prim) { - bool parentUnmerged = false; - TfToken val; - if(prim.GetParent().IsValid() && prim.GetParent().GetMetadata(AL::usdmaya::Metadata::mergedTransform, &val)) - { - parentUnmerged = (val == AL::usdmaya::Metadata::unmerged); - } - return parentUnmerged; + bool parentUnmerged = false; + TfToken val; + if (prim.GetParent().IsValid() + && prim.GetParent().GetMetadata(AL::usdmaya::Metadata::mergedTransform, &val)) { + parentUnmerged = (val == AL::usdmaya::Metadata::unmerged); + } + return parentUnmerged; } //---------------------------------------------------------------------------------------------------------------------- @@ -137,308 +138,316 @@ fileio::ImporterParams ProxyShapePostLoadProcess::m_params; //---------------------------------------------------------------------------------------------------------------------- void ProxyShapePostLoadProcess::createTranformChainsForSchemaPrims( - nodes::ProxyShape* ptrNode, - const std::vector& schemaPrims, - const MDagPath& proxyTransformPath, + nodes::ProxyShape* ptrNode, + const std::vector& schemaPrims, + const MDagPath& proxyTransformPath, ProxyShapePostLoadProcess::MObjectToPrim& objsToCreate, - bool pushToPrim, - bool readAnimatedValues) + bool pushToPrim, + bool readAnimatedValues) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::createTranformChainsForSchemaPrims\n"); - AL_BEGIN_PROFILE_SECTION(CreateTransformChains); - { - objsToCreate.reserve(schemaPrims.size()); - MDagModifier modifier; - MDGModifier modifier2; - - MPlug outStage = ptrNode->outStageDataPlug(); - MPlug outTime = ptrNode->outTimePlug(); - MFnTransform fnx(proxyTransformPath); - fileio::SchemaPrimsUtils schemaPrimUtils(ptrNode->translatorManufacture()); - for(auto it = schemaPrims.begin(); it != schemaPrims.end(); ++it) + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("ProxyShapePostLoadProcess::createTranformChainsForSchemaPrims\n"); + AL_BEGIN_PROFILE_SECTION(CreateTransformChains); { - const UsdPrim& usdPrim = *it; - if(usdPrim.IsValid()) - { - SdfPath path = usdPrim.GetPath(); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::createTranformChainsForSchemaPrims checking %s\n", path.GetText()); - MObject newpath = MObject::kNullObj; - bool parentUnmerged = parentNodeIsUnmerged(usdPrim); - - if(schemaPrimUtils.needsTransformParent(usdPrim)) - { - if(!parentUnmerged) - { - newpath = ptrNode->makeUsdTransformChain(usdPrim, modifier, nodes::ProxyShape::kRequired, &modifier2, 0, pushToPrim, readAnimatedValues); - } - else - { - newpath = ptrNode->makeUsdTransformChain(usdPrim.GetParent(), modifier, nodes::ProxyShape::kRequired, &modifier2, 0, pushToPrim, readAnimatedValues); - } + objsToCreate.reserve(schemaPrims.size()); + MDagModifier modifier; + MDGModifier modifier2; + + MPlug outStage = ptrNode->outStageDataPlug(); + MPlug outTime = ptrNode->outTimePlug(); + MFnTransform fnx(proxyTransformPath); + fileio::SchemaPrimsUtils schemaPrimUtils(ptrNode->translatorManufacture()); + for (auto it = schemaPrims.begin(); it != schemaPrims.end(); ++it) { + const UsdPrim& usdPrim = *it; + if (usdPrim.IsValid()) { + SdfPath path = usdPrim.GetPath(); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShapePostLoadProcess::createTranformChainsForSchemaPrims checking " + "%s\n", + path.GetText()); + MObject newpath = MObject::kNullObj; + bool parentUnmerged = parentNodeIsUnmerged(usdPrim); + + if (schemaPrimUtils.needsTransformParent(usdPrim)) { + if (!parentUnmerged) { + newpath = ptrNode->makeUsdTransformChain( + usdPrim, + modifier, + nodes::ProxyShape::kRequired, + &modifier2, + 0, + pushToPrim, + readAnimatedValues); + } else { + newpath = ptrNode->makeUsdTransformChain( + usdPrim.GetParent(), + modifier, + nodes::ProxyShape::kRequired, + &modifier2, + 0, + pushToPrim, + readAnimatedValues); + } + } + objsToCreate.emplace_back(newpath, usdPrim); + } else { + std::cout << "prim is invalid" << std::endl; + } } - objsToCreate.emplace_back(newpath, usdPrim); - } - else - { - std::cout << "prim is invalid" << std::endl; - } - } - if(!modifier.doIt()) - { - std::cerr << "Failed to connect up attributes" << std::endl; - } - else - if(!modifier2.doIt()) - { - std::cerr << "Failed to enable pushToPrim attributes" << std::endl; + if (!modifier.doIt()) { + std::cerr << "Failed to connect up attributes" << std::endl; + } else if (!modifier2.doIt()) { + std::cerr << "Failed to enable pushToPrim attributes" << std::endl; + } } - } - AL_END_PROFILE_SECTION(); + AL_END_PROFILE_SECTION(); } //---------------------------------------------------------------------------------------------------------------------- void ProxyShapePostLoadProcess::createSchemaPrims( - nodes::ProxyShape* proxy, - const std::vector& objsToCreate, + nodes::ProxyShape* proxy, + const std::vector& objsToCreate, const fileio::translators::TranslatorParameters& param) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::createSchemaPrims\n"); - AL_BEGIN_PROFILE_SECTION(CreatePrims); - { - fileio::translators::TranslatorContextPtr context = proxy->context(); - fileio::translators::TranslatorManufacture& translatorManufacture = proxy->translatorManufacture(); - - if(context->getForceDefaultRead()) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::createSchemaPrims," - " will read default values\n"); - } - - auto it = objsToCreate.begin(); - const auto end = objsToCreate.end(); - for(; it != end; ++it) + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::createSchemaPrims\n"); + AL_BEGIN_PROFILE_SECTION(CreatePrims); { - UsdPrim prim = *it; - bool parentUnmerged = parentNodeIsUnmerged(prim); - MObject object; - if (parentUnmerged) - { - object = proxy->findRequiredPath(prim.GetParent().GetPath()); - } - else - { - object = proxy->findRequiredPath(prim.GetPath()); - } - - fileio::translators::TranslatorRefPtr translator = translatorManufacture.get(prim); - - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::createSchemaPrims prim=%s\n", prim.GetPath().GetText()); - - //if(!context->hasEntry(prim.GetPath(), prim.GetTypeName())) - { - AL_BEGIN_PROFILE_SECTION(SchemaPrims); - MObject created; - if(!fileio::importSchemaPrim(prim, object, created, context, translator, param)) - { - std::cerr << "Error: unable to load schema prim node: '" << prim.GetName().GetString() << "' that has type: '" << prim.GetTypeName() << "'" << std::endl; + fileio::translators::TranslatorContextPtr context = proxy->context(); + fileio::translators::TranslatorManufacture& translatorManufacture + = proxy->translatorManufacture(); + + if (context->getForceDefaultRead()) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("ProxyShapePostLoadProcess::createSchemaPrims," + " will read default values\n"); } - AL_END_PROFILE_SECTION(); - auto dataPlugins = translatorManufacture.getExtraDataPlugins(created); - for(auto dataPlugin : dataPlugins) - { - dataPlugin->import(prim, created); + auto it = objsToCreate.begin(); + const auto end = objsToCreate.end(); + for (; it != end; ++it) { + UsdPrim prim = *it; + bool parentUnmerged = parentNodeIsUnmerged(prim); + MObject object; + if (parentUnmerged) { + object = proxy->findRequiredPath(prim.GetParent().GetPath()); + } else { + object = proxy->findRequiredPath(prim.GetPath()); + } + + fileio::translators::TranslatorRefPtr translator = translatorManufacture.get(prim); + + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShapePostLoadProcess::createSchemaPrims prim=%s\n", + prim.GetPath().GetText()); + + // if(!context->hasEntry(prim.GetPath(), prim.GetTypeName())) + { + AL_BEGIN_PROFILE_SECTION(SchemaPrims); + MObject created; + if (!fileio::importSchemaPrim(prim, object, created, context, translator, param)) { + std::cerr << "Error: unable to load schema prim node: '" + << prim.GetName().GetString() << "' that has type: '" + << prim.GetTypeName() << "'" << std::endl; + } + AL_END_PROFILE_SECTION(); + + auto dataPlugins = translatorManufacture.getExtraDataPlugins(created); + for (auto dataPlugin : dataPlugins) { + dataPlugin->import(prim, created); + } + } } - } } - } - AL_END_PROFILE_SECTION(); + AL_END_PROFILE_SECTION(); } //---------------------------------------------------------------------------------------------------------------------- void ProxyShapePostLoadProcess::updateSchemaPrims( - nodes::ProxyShape* proxy, + nodes::ProxyShape* proxy, const std::vector& objsToCreate) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::updateSchemaPrims\n"); - AL_BEGIN_PROFILE_SECTION(CreatePrims); - { - fileio::translators::TranslatorContextPtr context = proxy->context(); - fileio::translators::TranslatorManufacture& translatorManufacture = proxy->translatorManufacture(); - - auto it = objsToCreate.begin(); - const auto end = objsToCreate.end(); - for(; it != end; ++it) + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::updateSchemaPrims\n"); + AL_BEGIN_PROFILE_SECTION(CreatePrims); { - UsdPrim prim = *it; - - fileio::translators::TranslatorRefPtr translator = translatorManufacture.get(prim); - std::string translatorId = translatorManufacture.generateTranslatorId(prim); - bool hasMatchingEntry = context->hasEntry(prim.GetPath(), translatorId); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::updateSchemaPrims: hasEntry(%s, %s)=%d\n", prim.GetPath().GetText(), translatorId.c_str(), hasMatchingEntry); - - - if(!hasMatchingEntry) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::createSchemaPrims prim=%s hasEntry=false\n", prim.GetPath().GetText()); - AL_BEGIN_PROFILE_SECTION(SchemaPrims); - MObject created; - MObject object = proxy->findRequiredPath(prim.GetPath()); - fileio::importSchemaPrim(prim, object, created, context, translator); - AL_END_PROFILE_SECTION(); - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::createSchemaPrims [update] prim=%s\n", prim.GetPath().GetText()); - if(translator) - { - if(translator->update(prim).statusCode() == MStatus::kNotImplemented) - { - MGlobal::displayError( - MString("Prim type has claimed that it supports variant switching via update, but it does not! ") + - prim.GetPath().GetText()); - } - else - { - std::vector returned; - if(context->getMObjects(prim, returned) && !returned.empty()) - { - auto dataPlugins = translatorManufacture.getExtraDataPlugins(returned[0].object()); - for(auto dataPlugin : dataPlugins) - { - dataPlugin->update(prim); - } + fileio::translators::TranslatorContextPtr context = proxy->context(); + fileio::translators::TranslatorManufacture& translatorManufacture + = proxy->translatorManufacture(); + + auto it = objsToCreate.begin(); + const auto end = objsToCreate.end(); + for (; it != end; ++it) { + UsdPrim prim = *it; + + fileio::translators::TranslatorRefPtr translator = translatorManufacture.get(prim); + std::string translatorId = translatorManufacture.generateTranslatorId(prim); + bool hasMatchingEntry = context->hasEntry(prim.GetPath(), translatorId); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShapePostLoadProcess::updateSchemaPrims: hasEntry(%s, %s)=%d\n", + prim.GetPath().GetText(), + translatorId.c_str(), + hasMatchingEntry); + + if (!hasMatchingEntry) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShapePostLoadProcess::createSchemaPrims prim=%s hasEntry=false\n", + prim.GetPath().GetText()); + AL_BEGIN_PROFILE_SECTION(SchemaPrims); + MObject created; + MObject object = proxy->findRequiredPath(prim.GetPath()); + fileio::importSchemaPrim(prim, object, created, context, translator); + AL_END_PROFILE_SECTION(); + } else { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShapePostLoadProcess::createSchemaPrims [update] prim=%s\n", + prim.GetPath().GetText()); + if (translator) { + if (translator->update(prim).statusCode() == MStatus::kNotImplemented) { + MGlobal::displayError( + MString("Prim type has claimed that it supports variant switching via " + "update, but it does not! ") + + prim.GetPath().GetText()); + } else { + std::vector returned; + if (context->getMObjects(prim, returned) && !returned.empty()) { + auto dataPlugins + = translatorManufacture.getExtraDataPlugins(returned[0].object()); + for (auto dataPlugin : dataPlugins) { + dataPlugin->update(prim); + } + } + } + } } - } } - } } - } - AL_END_PROFILE_SECTION(); + AL_END_PROFILE_SECTION(); } - //---------------------------------------------------------------------------------------------------------------------- void ProxyShapePostLoadProcess::connectSchemaPrims( - nodes::ProxyShape* proxy, + nodes::ProxyShape* proxy, const std::vector& objsToCreate) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::connectSchemaPrims\n"); - AL_BEGIN_PROFILE_SECTION(PostImportLogic); - - fileio::translators::TranslatorContextPtr context = proxy->context(); - fileio::translators::TranslatorManufacture& translatorManufacture = proxy->translatorManufacture(); - - // iterate over the prims we created, and call any post-import logic to make any attribute connections etc - auto it = objsToCreate.begin(); - const auto end = objsToCreate.end(); - for(; it != end; ++it) - { - UsdPrim prim = *it; - fileio::translators::TranslatorRefPtr torBase = translatorManufacture.get(prim); - if(torBase) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::connectSchemaPrims [postImport] prim=%s\n", prim.GetPath().GetText()); - AL_BEGIN_PROFILE_SECTION(TranslatorBasePostImport); - torBase->postImport(prim); - std::vector returned; - if(context->getMObjects(prim, returned) && !returned.empty()) - { - auto dataPlugins = translatorManufacture.getExtraDataPlugins(returned[0].object()); - for(auto dataPlugin : dataPlugins) - { - dataPlugin->postImport(prim); - } - } + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::connectSchemaPrims\n"); + AL_BEGIN_PROFILE_SECTION(PostImportLogic); + + fileio::translators::TranslatorContextPtr context = proxy->context(); + fileio::translators::TranslatorManufacture& translatorManufacture + = proxy->translatorManufacture(); + + // iterate over the prims we created, and call any post-import logic to make any attribute + // connections etc + auto it = objsToCreate.begin(); + const auto end = objsToCreate.end(); + for (; it != end; ++it) { + UsdPrim prim = *it; + fileio::translators::TranslatorRefPtr torBase = translatorManufacture.get(prim); + if (torBase) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShapePostLoadProcess::connectSchemaPrims [postImport] prim=%s\n", + prim.GetPath().GetText()); + AL_BEGIN_PROFILE_SECTION(TranslatorBasePostImport); + torBase->postImport(prim); + std::vector returned; + if (context->getMObjects(prim, returned) && !returned.empty()) { + auto dataPlugins = translatorManufacture.getExtraDataPlugins(returned[0].object()); + for (auto dataPlugin : dataPlugins) { + dataPlugin->postImport(prim); + } + } - context->updateUniqueKey(prim); + context->updateUniqueKey(prim); - AL_END_PROFILE_SECTION(); + AL_END_PROFILE_SECTION(); + } } - } - AL_END_PROFILE_SECTION(); + AL_END_PROFILE_SECTION(); } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShapePostLoadProcess::initialise(nodes::ProxyShape* ptrNode) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::initialise called\n"); - - if(!ptrNode) - { - std::cerr << "ProxyShapePostLoadProcess::initialise Unable to initialise the PostLoadProcess since the ProxyShape ptr is null" << std::endl; - return MStatus::kFailure; - } - - MFnDagNode fn(ptrNode->thisMObject()); - MDagPath proxyTransformPath; - fn.getPath(proxyTransformPath); - - // make sure we unload all references prior to reloading them again - ptrNode->unloadMayaReferences(); - ptrNode->destroyTransformReferences(); - fileio::translators::TranslatorManufacture::preparePythonTranslators(ptrNode->context()); - - // Now go and delete any child Transforms found directly underneath the shapes parent. - // These nodes are likely to be driven by the output stage data of the shape. - { - MDagModifier modifier; - MFnDagNode fnDag(fn.parent(0)); - for(uint32_t i = 0; i < fnDag.childCount(); ++i) + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShapePostLoadProcess::initialise called\n"); + + if (!ptrNode) { + std::cerr << "ProxyShapePostLoadProcess::initialise Unable to initialise the " + "PostLoadProcess since the ProxyShape ptr is null" + << std::endl; + return MStatus::kFailure; + } + + MFnDagNode fn(ptrNode->thisMObject()); + MDagPath proxyTransformPath; + fn.getPath(proxyTransformPath); + + // make sure we unload all references prior to reloading them again + ptrNode->unloadMayaReferences(); + ptrNode->destroyTransformReferences(); + fileio::translators::TranslatorManufacture::preparePythonTranslators(ptrNode->context()); + + // Now go and delete any child Transforms found directly underneath the shapes parent. + // These nodes are likely to be driven by the output stage data of the shape. { - MObject obj = fnDag.child(i); - if(obj.hasFn(MFn::kPluginTransformNode)) - { - MFnDagNode fnChild(obj); - if(fnChild.typeId() == nodes::Transform::kTypeId || - fnChild.typeId() == nodes::Scope::kTypeId) - { - modifier.deleteNode(obj); + MDagModifier modifier; + MFnDagNode fnDag(fn.parent(0)); + for (uint32_t i = 0; i < fnDag.childCount(); ++i) { + MObject obj = fnDag.child(i); + if (obj.hasFn(MFn::kPluginTransformNode)) { + MFnDagNode fnChild(obj); + if (fnChild.typeId() == nodes::Transform::kTypeId + || fnChild.typeId() == nodes::Scope::kTypeId) { + modifier.deleteNode(obj); + } + } } - } + + if (!modifier.doIt()) { } } - if(!modifier.doIt()) - { + AL_BEGIN_PROFILE_SECTION(HuntForNativePrims); + proxyTransformPath.pop(); + + // iterate over the stage and find all custom schema nodes that have registered translator + // plugins + std::vector schemaPrims; + std::vector callBacks; + UsdStageRefPtr stage = ptrNode->usdStage(); + if (stage) { + huntForNativeNodes( + proxyTransformPath, + schemaPrims, + callBacks, + *ptrNode /* stage, ptrNode->translatorManufacture()*/); + } else { + AL_END_PROFILE_SECTION(); + return MS::kFailure; } - } - - AL_BEGIN_PROFILE_SECTION(HuntForNativePrims); - proxyTransformPath.pop(); - - // iterate over the stage and find all custom schema nodes that have registered translator plugins - std::vector schemaPrims; - std::vector callBacks; - UsdStageRefPtr stage = ptrNode->usdStage(); - if(stage) - { - huntForNativeNodes(proxyTransformPath, schemaPrims, callBacks, *ptrNode/* stage, ptrNode->translatorManufacture()*/); - } - else - { - AL_END_PROFILE_SECTION(); - return MS::kFailure; - } - AL_END_PROFILE_SECTION(); + AL_END_PROFILE_SECTION(); - // generate the transform chains - MObjectToPrim objsToCreate; - createTranformChainsForSchemaPrims(ptrNode, schemaPrims, proxyTransformPath, objsToCreate); + // generate the transform chains + MObjectToPrim objsToCreate; + createTranformChainsForSchemaPrims(ptrNode, schemaPrims, proxyTransformPath, objsToCreate); - // create prims that need to be imported - createSchemaPrims(ptrNode, schemaPrims); + // create prims that need to be imported + createSchemaPrims(ptrNode, schemaPrims); - // now perform any post-creation fix up - connectSchemaPrims(ptrNode, schemaPrims); + // now perform any post-creation fix up + connectSchemaPrims(ptrNode, schemaPrims); - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapePostLoadProcess.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapePostLoadProcess.h index 6b3be8022e..6234bc5470 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapePostLoadProcess.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/ProxyShapePostLoadProcess.h @@ -26,16 +26,21 @@ namespace usdmaya { namespace cmds { //---------------------------------------------------------------------------------------------------------------------- -/// \brief When importing a new usd stage into an AL::usdmaya::nodes::ProxyShape, there are a selection of post import +/// \brief When importing a new usd stage into an AL::usdmaya::nodes::ProxyShape, there are a +/// selection of post import /// processes that need to take place in order to import any custom usd plugins found. /// -/// \li If any custom plugin prims are found, that represent DAG nodes (e.g. they are shapes or transforms), -/// then a hierarchy of AL::usdmaya::nodes::Transform nodes will be generated so that the USD transform -/// values found on the prims, will have a direct mapping to a maya transform. This allows use of the -/// standard Maya scale/translate/rotate manipulators to control maya nodes directly. -/// \li For every custom plugin prim found, that node will need to be translated into Maya, and then connected +/// \li If any custom plugin prims are found, that represent DAG nodes (e.g. they are shapes +/// or transforms), +/// then a hierarchy of AL::usdmaya::nodes::Transform nodes will be generated so that +/// the USD transform values found on the prims, will have a direct mapping to a maya +/// transform. This allows use of the standard Maya scale/translate/rotate manipulators +/// to control maya nodes directly. +/// \li For every custom plugin prim found, that node will need to be translated into Maya, +/// and then connected /// up with the other imported prims. -/// \li A certain amount of book keeping information will need to be generated, so that variant switching can +/// \li A certain amount of book keeping information will need to be generated, so that +/// variant switching can /// be used to modify or remove those nodes at a later date. /// /// This helper class manages those processes. @@ -45,64 +50,68 @@ namespace cmds { class ProxyShapePostLoadProcess { public: + /// a mapping from an MObject to a UsdPrim + typedef std::vector> MObjectToPrim; - /// a mapping from an MObject to a UsdPrim - typedef std::vector > MObjectToPrim; + /// \brief called after a proxy shape has been created. Traverses the prim hierarchy and looks + /// to see whether + /// any custom plugin translators need to be called, and performs additional + /// book-keeping. + /// \param shape the proxy shape node that has just been created + /// \return MS::kSuccess if ok + static MStatus initialise(nodes::ProxyShape* shape); - /// \brief called after a proxy shape has been created. Traverses the prim hierarchy and looks to see whether - /// any custom plugin translators need to be called, and performs additional book-keeping. - /// \param shape the proxy shape node that has just been created - /// \return MS::kSuccess if ok - static MStatus initialise(nodes::ProxyShape* shape); + /// \brief given a specific proxy shape, and a collection of UsdPrims that represent custom + /// DagNode types, this + /// will generate a transform hierarchy that will allow you to map the UsdPrims to + /// equivalent maya transforms + /// \param shape the proxy shape these transforms are being pulled in from + /// \param schemaPrims an array of prims for which transforms should be created + /// \param proxyTransformPath a path to the transform node that resides above the proxy shape + /// \param objsToCreate a mapping from the MObjects created (for the transform nodes), to the + /// UsdPrim that is represented \param pushToPrim specifies the value of the pushToPrim + /// attribute on the created transform nodes \param readAnimatedValues specifies the value of + /// the readAnimatedValues attribute on the created transform nodes + static void createTranformChainsForSchemaPrims( + nodes::ProxyShape* shape, + const std::vector& schemaPrims, + const MDagPath& proxyTransformPath, + MObjectToPrim& objsToCreate, + bool pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"), + bool readAnimatedValues = MGlobal::optionVarIntValue("AL_usdmaya_readAnimatedValues")); - /// \brief given a specific proxy shape, and a collection of UsdPrims that represent custom DagNode types, this - /// will generate a transform hierarchy that will allow you to map the UsdPrims to equivalent maya transforms - /// \param shape the proxy shape these transforms are being pulled in from - /// \param schemaPrims an array of prims for which transforms should be created - /// \param proxyTransformPath a path to the transform node that resides above the proxy shape - /// \param objsToCreate a mapping from the MObjects created (for the transform nodes), to the UsdPrim that is represented - /// \param pushToPrim specifies the value of the pushToPrim attribute on the created transform nodes - /// \param readAnimatedValues specifies the value of the readAnimatedValues attribute on the created transform nodes - static void createTranformChainsForSchemaPrims( - nodes::ProxyShape* shape, - const std::vector& schemaPrims, - const MDagPath& proxyTransformPath, - MObjectToPrim& objsToCreate, - bool pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"), - bool readAnimatedValues = MGlobal::optionVarIntValue("AL_usdmaya_readAnimatedValues")); + /// \brief After transforms exist to parent the custom plugin-prim types (i.e. after a call to + /// createTranformChainsForSchemaPrims), this method should be called to call the plugin + /// translators for all those nodes that should be imported into the Maya Scene. + /// \param proxy the proxy shape to create the schema prims on + /// \param objsToCreate the mapping returned from createTranformChainsForSchemaPrims + /// \param param the translator plugin options + static void createSchemaPrims( + nodes::ProxyShape* proxy, + const std::vector& objsToCreate, + const fileio::translators::TranslatorParameters& param + = fileio::translators::TranslatorParameters()); - /// \brief After transforms exist to parent the custom plugin-prim types (i.e. after a call to - /// createTranformChainsForSchemaPrims), this method should be called to call the plugin translators for all - /// those nodes that should be imported into the Maya Scene. - /// \param proxy the proxy shape to create the schema prims on - /// \param objsToCreate the mapping returned from createTranformChainsForSchemaPrims - /// \param param the translator plugin options - static void createSchemaPrims( - nodes::ProxyShape* proxy, - const std::vector& objsToCreate, - const fileio::translators::TranslatorParameters& param = fileio::translators::TranslatorParameters()); + /// \brief called once all plugin nodes have been created, and will request that each plugin + /// translator performs + /// the postImport fixup to safely make any connections between Maya nodes + /// \param proxy the proxy shape to connect the schema prims + /// \param objsToCreate the mapping returned from createTranformChainsForSchemaPrims + static void + connectSchemaPrims(nodes::ProxyShape* proxy, const std::vector& objsToCreate); - /// \brief called once all plugin nodes have been created, and will request that each plugin translator performs - /// the postImport fixup to safely make any connections between Maya nodes - /// \param proxy the proxy shape to connect the schema prims - /// \param objsToCreate the mapping returned from createTranformChainsForSchemaPrims - static void connectSchemaPrims( - nodes::ProxyShape* proxy, - const std::vector& objsToCreate); - - /// \brief updates the list of UsdPrims after a variant switch (but when the nodes have not changed) - /// \param proxy the proxy shape to update - /// \param objsToUpdate the list of prims to be updated - static void updateSchemaPrims( - nodes::ProxyShape* proxy, - const std::vector& objsToUpdate); + /// \brief updates the list of UsdPrims after a variant switch (but when the nodes have not + /// changed) \param proxy the proxy shape to update \param objsToUpdate the list of prims to + /// be updated + static void + updateSchemaPrims(nodes::ProxyShape* proxy, const std::vector& objsToUpdate); private: - static fileio::ImporterParams m_params; + static fileio::ImporterParams m_params; }; //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/RendererCommands.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/RendererCommands.cpp index 1f817a3567..0130143dde 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/RendererCommands.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/RendererCommands.cpp @@ -14,8 +14,9 @@ // limitations under the License. // #include "AL/usdmaya/cmds/RendererCommands.h" -#include "AL/usdmaya/nodes/RendererManager.h" + #include "AL/maya/utils/CommandGuiHelper.h" +#include "AL/usdmaya/nodes/RendererManager.h" #include #include @@ -33,79 +34,70 @@ AL_MAYA_DEFINE_COMMAND(ManageRenderer, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax ManageRenderer::createSyntax() { - MSyntax syn; - syn.addFlag("-h", "-help", MSyntax::kNoArg); - syn.addFlag("-sp", "-setPlugin", MSyntax::kString); - return syn; + MSyntax syn; + syn.addFlag("-h", "-help", MSyntax::kNoArg); + syn.addFlag("-sp", "-setPlugin", MSyntax::kString); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -bool ManageRenderer::isUndoable() const -{ - return false; -} +bool ManageRenderer::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MStatus ManageRenderer::doIt(const MArgList& argList) { - try - { - MStatus status; - MArgDatabase args(syntax(), argList, &status); - if(!status) - return status; - - AL_MAYA_COMMAND_HELP(args, g_helpText); - - if(args.isFlagSet("-sp")) - { - MString name; - args.getFlagArgument("-sp", 0, name); - bool result = nodes::RendererManager::findOrCreateManager()->setRendererPlugin(name); - setResult(result); + try { + MStatus status; + MArgDatabase args(syntax(), argList, &status); + if (!status) + return status; + + AL_MAYA_COMMAND_HELP(args, g_helpText); + + if (args.isFlagSet("-sp")) { + MString name; + args.getFlagArgument("-sp", 0, name); + bool result = nodes::RendererManager::findOrCreateManager()->setRendererPlugin(name); + setResult(result); + } + } catch (const MStatus& status) { + return status; } - } - catch(const MStatus& status) - { - return status; - } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStringArray buildRendererPluginsList(const MString&) { - nodes::RendererManager* RendererManager = nodes::RendererManager::findManager(); - if(RendererManager) - { - int index = RendererManager->getRendererPluginIndex(); - if (index > 0) - { - // swap items so current plugin is first and active in the list - MStringArray result = AL::usdmaya::nodes::RendererManager::getRendererPluginList(); - MString temp = result[0]; - result[0] = result[index]; - result[index] = temp; - return result; + nodes::RendererManager* RendererManager = nodes::RendererManager::findManager(); + if (RendererManager) { + int index = RendererManager->getRendererPluginIndex(); + if (index > 0) { + // swap items so current plugin is first and active in the list + MStringArray result = AL::usdmaya::nodes::RendererManager::getRendererPluginList(); + MString temp = result[0]; + result[0] = result[index]; + result[index] = temp; + return result; + } } - } - return AL::usdmaya::nodes::RendererManager::getRendererPluginList(); + return AL::usdmaya::nodes::RendererManager::getRendererPluginList(); } //---------------------------------------------------------------------------------------------------------------------- void constructRendererCommandGuis() { - /// It makes little sense to add this menu when there's just one option - if (AL::usdmaya::nodes::RendererManager::getRendererPluginList().length() > 1) - { - { - AL::maya::utils::CommandGuiHelper manageRenderer("AL_usdmaya_ManageRenderer", "Hydra Renderer Plugin", "Set", "USD/Renderer", false); - manageRenderer.addListOption("sp", "Plugin Name", (AL::maya::utils::GenerateListFn)buildRendererPluginsList); + /// It makes little sense to add this menu when there's just one option + if (AL::usdmaya::nodes::RendererManager::getRendererPluginList().length() > 1) { + { + AL::maya::utils::CommandGuiHelper manageRenderer( + "AL_usdmaya_ManageRenderer", "Hydra Renderer Plugin", "Set", "USD/Renderer", false); + manageRenderer.addListOption( + "sp", "Plugin Name", (AL::maya::utils::GenerateListFn)buildRendererPluginsList); + } } - } } - //---------------------------------------------------------------------------------------------------------------------- // Documentation strings. //---------------------------------------------------------------------------------------------------------------------- @@ -121,7 +113,7 @@ ManageRenderer Overview: )"; //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/RendererCommands.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/RendererCommands.h index e358bf5a66..759c3929d5 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/RendererCommands.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/RendererCommands.h @@ -28,14 +28,14 @@ namespace cmds { /// \brief Get / Set renderer plugin settings /// \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ManageRenderer - : public MPxCommand +class ManageRenderer : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; /// \brief function called on startup to generate the menu & option boxes for the layer commands @@ -44,7 +44,7 @@ AL_USDMAYA_PUBLIC void constructRendererCommandGuis(); //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/SyncFileIOGui.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/SyncFileIOGui.cpp index e3d595c449..e57a6e5a45 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/SyncFileIOGui.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/SyncFileIOGui.cpp @@ -14,12 +14,13 @@ // limitations under the License. // #include "AL/usdmaya/cmds/SyncFileIOGui.h" + +#include "AL/maya/utils/MenuBuilder.h" #include "AL/maya/utils/PluginTranslatorOptions.h" #include "AL/usdmaya/DebugCodes.h" -#include "AL/maya/utils/MenuBuilder.h" -#include #include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -32,45 +33,39 @@ AL_MAYA_DEFINE_COMMAND(SyncFileIOGui, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax SyncFileIOGui::createSyntax() { - MSyntax syn; - syn.addFlag("-h", "-help", MSyntax::kNoArg); - syn.addArg(MSyntax::kString); - return syn; + MSyntax syn; + syn.addFlag("-h", "-help", MSyntax::kNoArg); + syn.addArg(MSyntax::kString); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -bool SyncFileIOGui::isUndoable() const -{ - return false; -} +bool SyncFileIOGui::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MStatus SyncFileIOGui::doIt(const MArgList& argList) { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("AL_usdmaya_SyncFileIOGui::doIt\n"); - try - { - MStatus status; - MArgDatabase args(syntax(), argList, &status); - if(!status) - return status; - - AL_MAYA_COMMAND_HELP(args, g_helpText); - - MString translatorName; - status = args.getCommandArgument(0, translatorName); - if(!status) - return status; - - maya::utils::PluginTranslatorOptionsContextManager::resyncGUI(translatorName.asChar()); - } - catch(const MStatus&) - { - } - return MS::kSuccess; + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("AL_usdmaya_SyncFileIOGui::doIt\n"); + try { + MStatus status; + MArgDatabase args(syntax(), argList, &status); + if (!status) + return status; + + AL_MAYA_COMMAND_HELP(args, g_helpText); + + MString translatorName; + status = args.getCommandArgument(0, translatorName); + if (!status) + return status; + + maya::utils::PluginTranslatorOptionsContextManager::resyncGUI(translatorName.asChar()); + } catch (const MStatus&) { + } + return MS::kSuccess; } -const char* const SyncFileIOGui::g_helpText = R"( +const char* const SyncFileIOGui::g_helpText = R"( AL_usdmaya_SyncFileIOGui Overview: This command is for internal use. @@ -87,7 +82,7 @@ const char* const SyncFileIOGui::g_helpText = R"( )"; //---------------------------------------------------------------------------------------------------------------------- -} -} -} +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/SyncFileIOGui.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/SyncFileIOGui.h index 068480374a..3878465c71 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/SyncFileIOGui.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/SyncFileIOGui.h @@ -25,22 +25,19 @@ namespace usdmaya { namespace cmds { //---------------------------------------------------------------------------------------------------------------------- -/// \brief A command that is used to pre-sync the auto generated GUI for the plugin options to a translator. -/// \ingroup commands +/// \brief A command that is used to pre-sync the auto generated GUI for the plugin options to a +/// translator. \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class SyncFileIOGui - : public MPxCommand +class SyncFileIOGui : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; -} // cmds -} // usdmaya -} // AL - - - +} // namespace cmds +} // namespace usdmaya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/UnloadPrim.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/UnloadPrim.cpp index d234b094c7..495036372c 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/UnloadPrim.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/UnloadPrim.cpp @@ -13,111 +13,96 @@ // See the License for the specific language governing permissions and // limitations under the License. // +#include "AL/usdmaya/cmds/UnloadPrim.h" + #include "AL/maya/utils/CommandGuiHelper.h" #include "AL/maya/utils/Utils.h" #include "AL/usdmaya/DebugCodes.h" -#include "AL/usdmaya/cmds/UnloadPrim.h" #include "AL/usdmaya/fileio/TransformIterator.h" #include "AL/usdmaya/nodes/ProxyShape.h" #include "AL/usdmaya/nodes/Transform.h" -#include -#include -#include -#include -#include -#include -#include -#include - #include #include #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include namespace AL { namespace usdmaya { namespace cmds { - AL_MAYA_DEFINE_COMMAND(ChangeVariant, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax ChangeVariant::createSyntax() { - MSyntax syntax; - syntax.useSelectionAsDefault(true); - syntax.setObjectType(MSyntax::kSelectionList, 0); - syntax.addFlag("-pp", "-primPath", MSyntax::kString); - syntax.addFlag("-vs", "-variantSet", MSyntax::kString); - syntax.addFlag("-v", "-variant", MSyntax::kString); - return syntax; + MSyntax syntax; + syntax.useSelectionAsDefault(true); + syntax.setObjectType(MSyntax::kSelectionList, 0); + syntax.addFlag("-pp", "-primPath", MSyntax::kString); + syntax.addFlag("-vs", "-variantSet", MSyntax::kString); + syntax.addFlag("-v", "-variant", MSyntax::kString); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- -bool ChangeVariant::isUndoable() const -{ - return false; -} +bool ChangeVariant::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MStatus ChangeVariant::doIt(const MArgList& args) { - try - { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ChangeVariant::doIt\n"); - MStatus status; - MArgDatabase database(syntax(), args, &status); - if(!status) - return status; - - MString pp; - MString vset; - MString variant; - - if(!database.isFlagSet("-pp") || !database.isFlagSet("-vs") || !database.isFlagSet("-v")) - { - MGlobal::displayError("Not enough information to set variant"); - return MS::kFailure; - } + try { + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ChangeVariant::doIt\n"); + MStatus status; + MArgDatabase database(syntax(), args, &status); + if (!status) + return status; + + MString pp; + MString vset; + MString variant; + + if (!database.isFlagSet("-pp") || !database.isFlagSet("-vs") || !database.isFlagSet("-v")) { + MGlobal::displayError("Not enough information to set variant"); + return MS::kFailure; + } - if(!database.getFlagArgument("-pp", 0, pp) || - !database.getFlagArgument("-vs", 0, vset) || - !database.getFlagArgument("-v", 0, variant)) - { - MGlobal::displayError("Not enough information to set variant"); - return MS::kFailure; - } + if (!database.getFlagArgument("-pp", 0, pp) || !database.getFlagArgument("-vs", 0, vset) + || !database.getFlagArgument("-v", 0, variant)) { + MGlobal::displayError("Not enough information to set variant"); + return MS::kFailure; + } - /// find the proxy shape node - nodes::ProxyShape* proxy = getShapeNode(database); - if(proxy) - { - auto stage = proxy->usdStage(); - if(stage) - { - UsdPrim prim = stage->GetPrimAtPath(SdfPath(AL::maya::utils::convert(pp))); - if(prim) - { - UsdVariantSet actualSet = prim.GetVariantSet(AL::maya::utils::convert(vset)); - if(actualSet) - { - if(!actualSet.SetVariantSelection(AL::maya::utils::convert(variant))) - { - MGlobal::displayError("could not switch variant"); + /// find the proxy shape node + nodes::ProxyShape* proxy = getShapeNode(database); + if (proxy) { + auto stage = proxy->usdStage(); + if (stage) { + UsdPrim prim = stage->GetPrimAtPath(SdfPath(AL::maya::utils::convert(pp))); + if (prim) { + UsdVariantSet actualSet = prim.GetVariantSet(AL::maya::utils::convert(vset)); + if (actualSet) { + if (!actualSet.SetVariantSelection(AL::maya::utils::convert(variant))) { + MGlobal::displayError("could not switch variant"); + } + } + } } - } } - } + } catch (MStatus&) { + std::cout << "Error" << std::endl; } - } - catch(MStatus&) - { - std::cout << "Error" << std::endl; - } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- @@ -126,75 +111,61 @@ AL_MAYA_DEFINE_COMMAND(ActivatePrim, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- MSyntax ActivatePrim::createSyntax() { - MSyntax syntax; - syntax.useSelectionAsDefault(true); - syntax.setObjectType(MSyntax::kSelectionList, 0); - syntax.addFlag("-pp", "-primPath", MSyntax::kString); - syntax.addFlag("-a", "-activate", MSyntax::kBoolean); - return syntax; + MSyntax syntax; + syntax.useSelectionAsDefault(true); + syntax.setObjectType(MSyntax::kSelectionList, 0); + syntax.addFlag("-pp", "-primPath", MSyntax::kString); + syntax.addFlag("-a", "-activate", MSyntax::kBoolean); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- -bool ActivatePrim::isUndoable() const -{ - return false; -} +bool ActivatePrim::isUndoable() const { return false; } //---------------------------------------------------------------------------------------------------------------------- MStatus ActivatePrim::doIt(const MArgList& args) { - try - { - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ActivatePrim::doIt\n"); - MStatus status; - MArgDatabase database(syntax(), args, &status); - if(!status) - return status; - - MString pp; - bool active = false; - - if(!database.isFlagSet("-pp") || !database.isFlagSet("-a")) - { - MGlobal::displayError("Not enough information to activate prim"); - return MS::kFailure; - } - - if(!database.getFlagArgument("-pp", 0, pp) || - !database.getFlagArgument("-a", 0, active)) - { - MGlobal::displayError("Not enough information to activate prim"); - return MS::kFailure; - } + try { + TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("ActivatePrim::doIt\n"); + MStatus status; + MArgDatabase database(syntax(), args, &status); + if (!status) + return status; + + MString pp; + bool active = false; + + if (!database.isFlagSet("-pp") || !database.isFlagSet("-a")) { + MGlobal::displayError("Not enough information to activate prim"); + return MS::kFailure; + } - /// find the proxy shape node - nodes::ProxyShape* proxy = getShapeNode(database); - if(proxy) - { - auto stage = proxy->usdStage(); - if(stage) - { - UsdPrim prim = stage->GetPrimAtPath(SdfPath(AL::maya::utils::convert(pp))); - if(prim) - { - prim.SetActive(active); + if (!database.getFlagArgument("-pp", 0, pp) || !database.getFlagArgument("-a", 0, active)) { + MGlobal::displayError("Not enough information to activate prim"); + return MS::kFailure; } - else - { - std::cout << "prim not found" << std::endl; + + /// find the proxy shape node + nodes::ProxyShape* proxy = getShapeNode(database); + if (proxy) { + auto stage = proxy->usdStage(); + if (stage) { + UsdPrim prim = stage->GetPrimAtPath(SdfPath(AL::maya::utils::convert(pp))); + if (prim) { + prim.SetActive(active); + } else { + std::cout << "prim not found" << std::endl; + } + } } - } + } catch (MStatus) { + std::cout << "Error" << std::endl; } - } - catch(MStatus) - { - std::cout << "Error" << std::endl; - } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/UnloadPrim.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/UnloadPrim.h index f1733a60ee..82768d63cc 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/UnloadPrim.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/cmds/UnloadPrim.h @@ -20,13 +20,14 @@ /* #include "AL/usdmaya/fileio/ImportParams.h" -#include -#include -#include -#include #include #include + +#include +#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE */ @@ -36,36 +37,35 @@ namespace usdmaya { namespace cmds { //---------------------------------------------------------------------------------------------------------------------- -/// \brief A command to force a variant switch - just a maya convenience wrapper around USD functionality -/// \ingroup commands +/// \brief A command to force a variant switch - just a maya convenience wrapper around USD +/// functionality \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ChangeVariant - : public ProxyShapeCommandBase +class ChangeVariant : public ProxyShapeCommandBase { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief A command to activate / deactivate a prim - just a maya convenience wrapper around USD functionality -/// \ingroup commands +/// \brief A command to activate / deactivate a prim - just a maya convenience wrapper around USD +/// functionality \ingroup commands //---------------------------------------------------------------------------------------------------------------------- -class ActivatePrim - : public ProxyShapeCommandBase +class ActivatePrim : public ProxyShapeCommandBase { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); + private: - bool isUndoable() const override; - MStatus doIt(const MArgList& args) override; + bool isUndoable() const override; + MStatus doIt(const MArgList& args) override; }; - //---------------------------------------------------------------------------------------------------------------------- -} // cmds -} // usdmaya -} // AL +} // namespace cmds +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/AnimationTranslator.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/AnimationTranslator.cpp index 97b3cf3002..66ce00bc39 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/AnimationTranslator.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/AnimationTranslator.cpp @@ -15,6 +15,7 @@ // #include "AL/usdmaya/fileio/AnimationTranslator.h" + #include "AL/usdmaya/fileio/translators/DgNodeTranslator.h" #include "AL/usdmaya/fileio/translators/TransformTranslator.h" #include "AL/usdmaya/utils/MeshUtils.h" @@ -34,99 +35,88 @@ namespace fileio { //---------------------------------------------------------------------------------------------------------------------- void AnimationTranslator::exportAnimation(const ExporterParams& params) { - auto const startAttrib = m_animatedPlugs.begin(); - auto const endAttrib = m_animatedPlugs.end(); - auto const startAttribScaled = m_scaledAnimatedPlugs.begin(); - auto const endAttribScaled = m_scaledAnimatedPlugs.end(); - auto const startTransformAttrib = m_animatedTransformPlugs.begin(); - auto const endTransformAttrib = m_animatedTransformPlugs.end(); - auto const startMultiAttrib = m_animatedMultiPlugs.begin(); - auto const endMultiAttrib = m_animatedMultiPlugs.end(); - auto const startMesh = m_animatedMeshes.begin(); - auto const endMesh = m_animatedMeshes.end(); - auto const startWSM = m_worldSpaceOutputs.begin(); - auto const endWSM = m_worldSpaceOutputs.end(); + auto const startAttrib = m_animatedPlugs.begin(); + auto const endAttrib = m_animatedPlugs.end(); + auto const startAttribScaled = m_scaledAnimatedPlugs.begin(); + auto const endAttribScaled = m_scaledAnimatedPlugs.end(); + auto const startTransformAttrib = m_animatedTransformPlugs.begin(); + auto const endTransformAttrib = m_animatedTransformPlugs.end(); + auto const startMultiAttrib = m_animatedMultiPlugs.begin(); + auto const endMultiAttrib = m_animatedMultiPlugs.end(); + auto const startMesh = m_animatedMeshes.begin(); + auto const endMesh = m_animatedMeshes.end(); + auto const startWSM = m_worldSpaceOutputs.begin(); + auto const endWSM = m_worldSpaceOutputs.end(); - if((startAttrib != endAttrib) || - (startAttribScaled != endAttribScaled) || - (startTransformAttrib != endTransformAttrib) || - (startMultiAttrib != endMultiAttrib) || - (startMesh != endMesh) || - (startWSM != endWSM) || - (!m_animatedNodes.empty())) - { - double increment = 1.0 / std::max(1U, params.m_subSamples); - for(double t = params.m_minFrame, e = params.m_maxFrame + 1e-3f; t < e; t += increment) - { - MAnimControl::setCurrentTime(t); - UsdTimeCode timeCode(t); - for(auto it = startAttrib; it != endAttrib; ++it) - { - /// \todo This feels wrong. Split the DgNodeTranslator class into 3 ... - /// maya::Dg - /// usdmaya::Dg - /// usdmaya::fileio::translator::Dg - translators::DgNodeTranslator::copyAttributeValue(it->first, it->second, timeCode); - } - for(auto it = startAttribScaled; it != endAttribScaled; ++it) - { - /// \todo This feels wrong. Split the DgNodeTranslator class into 3 ... - /// maya::Dg - /// usdmaya::Dg - /// usdmaya::fileio::translator::Dg - translators::DgNodeTranslator::copyAttributeValue(it->first, it->second.attr, it->second.scale, timeCode); - } - for (auto it = startTransformAttrib; it != endTransformAttrib; ++it) - { - translators::TransformTranslator::copyAttributeValue(it->first, it->second, timeCode); - } - for (auto it = startMultiAttrib; it != endMultiAttrib; ++it) - { - // Note: so far there is only one attribute need to be treated specially - // we do this special handling for this particular attribute atm, - // will see if we need to generalize once have more requests - if (it->first.GetName() == UsdGeomTokens->clippingRange && it->second.size() == 2) - { - const auto& plugs(it->second); - MDistance nearDistance; - MDistance farDistance; - if (plugs[0].getValue(nearDistance) == MStatus::kSuccess && plugs[1].getValue(farDistance) == MStatus::kSuccess) - { - GfVec2f clippingRange{ - static_cast(nearDistance.as(MDistance::kCentimeters)), - static_cast(farDistance.as(MDistance::kCentimeters))}; - it->first.Set(clippingRange,timeCode); - } - } - } - for(auto it = startMesh; it != endMesh; ++it) - { - UsdGeomMesh mesh(it->second.GetPrim()); - AL::usdmaya::utils::MeshExportContext context(it->first, mesh, timeCode); - context.copyVertexData(timeCode); - } - for(auto nodeAnim : m_animatedNodes) - { - nodeAnim.m_translator->exportCustomAnim(nodeAnim.m_path, nodeAnim.m_prim, timeCode); - } - for(auto it = startWSM; it != endWSM; ++it) - { - MMatrix mat = it->first.inclusiveMatrix(); + if ((startAttrib != endAttrib) || (startAttribScaled != endAttribScaled) + || (startTransformAttrib != endTransformAttrib) || (startMultiAttrib != endMultiAttrib) + || (startMesh != endMesh) || (startWSM != endWSM) || (!m_animatedNodes.empty())) { + double increment = 1.0 / std::max(1U, params.m_subSamples); + for (double t = params.m_minFrame, e = params.m_maxFrame + 1e-3f; t < e; t += increment) { + MAnimControl::setCurrentTime(t); + UsdTimeCode timeCode(t); + for (auto it = startAttrib; it != endAttrib; ++it) { + /// \todo This feels wrong. Split the DgNodeTranslator class into 3 ... + /// maya::Dg + /// usdmaya::Dg + /// usdmaya::fileio::translator::Dg + translators::DgNodeTranslator::copyAttributeValue(it->first, it->second, timeCode); + } + for (auto it = startAttribScaled; it != endAttribScaled; ++it) { + /// \todo This feels wrong. Split the DgNodeTranslator class into 3 ... + /// maya::Dg + /// usdmaya::Dg + /// usdmaya::fileio::translator::Dg + translators::DgNodeTranslator::copyAttributeValue( + it->first, it->second.attr, it->second.scale, timeCode); + } + for (auto it = startTransformAttrib; it != endTransformAttrib; ++it) { + translators::TransformTranslator::copyAttributeValue( + it->first, it->second, timeCode); + } + for (auto it = startMultiAttrib; it != endMultiAttrib; ++it) { + // Note: so far there is only one attribute need to be treated specially + // we do this special handling for this particular attribute atm, + // will see if we need to generalize once have more requests + if (it->first.GetName() == UsdGeomTokens->clippingRange && it->second.size() == 2) { + const auto& plugs(it->second); + MDistance nearDistance; + MDistance farDistance; + if (plugs[0].getValue(nearDistance) == MStatus::kSuccess + && plugs[1].getValue(farDistance) == MStatus::kSuccess) { + GfVec2f clippingRange { + static_cast(nearDistance.as(MDistance::kCentimeters)), + static_cast(farDistance.as(MDistance::kCentimeters)) + }; + it->first.Set(clippingRange, timeCode); + } + } + } + for (auto it = startMesh; it != endMesh; ++it) { + UsdGeomMesh mesh(it->second.GetPrim()); + AL::usdmaya::utils::MeshExportContext context(it->first, mesh, timeCode); + context.copyVertexData(timeCode); + } + for (auto nodeAnim : m_animatedNodes) { + nodeAnim.m_translator->exportCustomAnim(nodeAnim.m_path, nodeAnim.m_prim, timeCode); + } + for (auto it = startWSM; it != endWSM; ++it) { + MMatrix mat = it->first.inclusiveMatrix(); #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif - it->second.Set(*(const GfMatrix4d*)&mat, timeCode); + it->second.Set(*(const GfMatrix4d*)&mat, timeCode); #ifdef __GNUC__ #pragma GCC diagnostic pop #endif - } + } + } } - } } //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/AnimationTranslator.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/AnimationTranslator.h index fc9792345d..4ef4ba2ccb 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/AnimationTranslator.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/AnimationTranslator.h @@ -28,12 +28,12 @@ namespace AL { namespace usdmaya { namespace fileio { -using usdmaya::utils::ScaledPair; -using usdmaya::utils::PlugAttrVector; +using usdmaya::utils::AnimationCheckTransformAttributes; using usdmaya::utils::MeshAttrVector; using usdmaya::utils::PlugAttrScaledVector; +using usdmaya::utils::PlugAttrVector; +using usdmaya::utils::ScaledPair; using usdmaya::utils::WorldSpaceAttrVector; -using usdmaya::utils::AnimationCheckTransformAttributes; //---------------------------------------------------------------------------------------------------------------------- /// \brief A utility class to help with exporting animated plugs from maya @@ -42,31 +42,33 @@ using usdmaya::utils::AnimationCheckTransformAttributes; class AnimationTranslator : public usdmaya::utils::AnimationTranslator { public: + /// \brief After the scene has been exported, call this method to export the animation data on + /// various attributes \param params the export options + AL_USDMAYA_PUBLIC + void exportAnimation(const ExporterParams& params); - /// \brief After the scene has been exported, call this method to export the animation data on various attributes - /// \param params the export options - AL_USDMAYA_PUBLIC - void exportAnimation(const ExporterParams& params); - - /// \brief insert a prim into the anim translator for custom anim export. - /// \param translator the plugin translator to handle the export of anim data for the node - /// \param dagPath the maya dag path for the maya object to export - /// \param usdPrim the prim to write the data into - inline void addCustomAnimNode(translators::TranslatorBase* translator, MDagPath dagPath, UsdPrim usdPrim) - { m_animatedNodes.push_back({translator, dagPath, usdPrim}); } + /// \brief insert a prim into the anim translator for custom anim export. + /// \param translator the plugin translator to handle the export of anim data for the node + /// \param dagPath the maya dag path for the maya object to export + /// \param usdPrim the prim to write the data into + inline void + addCustomAnimNode(translators::TranslatorBase* translator, MDagPath dagPath, UsdPrim usdPrim) + { + m_animatedNodes.push_back({ translator, dagPath, usdPrim }); + } private: - struct NodeExportInfo - { - translators::TranslatorBase* m_translator; - MDagPath m_path; - UsdPrim m_prim; - }; - std::vector m_animatedNodes; + struct NodeExportInfo + { + translators::TranslatorBase* m_translator; + MDagPath m_path; + UsdPrim m_prim; + }; + std::vector m_animatedNodes; }; //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Export.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Export.cpp index aa86bc6b45..6c5948a8fa 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Export.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Export.cpp @@ -13,17 +13,23 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/fileio/AnimationTranslator.h" #include "AL/usdmaya/fileio/Export.h" + +#include "AL/maya/utils/MObjectMap.h" +#include "AL/maya/utils/Utils.h" +#include "AL/usdmaya/Metadata.h" +#include "AL/usdmaya/TransformOperation.h" +#include "AL/usdmaya/fileio/AnimationTranslator.h" #include "AL/usdmaya/fileio/ExportTranslator.h" #include "AL/usdmaya/fileio/NodeFactory.h" #include "AL/usdmaya/fileio/translators/TransformTranslator.h" -#include "AL/usdmaya/Metadata.h" -#include "AL/usdmaya/TransformOperation.h" #include "AL/usdmaya/utils/MeshUtils.h" #include "AL/usdmaya/utils/Utils.h" -#include "AL/maya/utils/Utils.h" -#include "AL/maya/utils/MObjectMap.h" + +#include +#include +#include +#include #include #include @@ -34,11 +40,6 @@ #include #include -#include -#include -#include -#include - namespace AL { namespace usdmaya { namespace fileio { @@ -48,80 +49,75 @@ AL_MAYA_DEFINE_COMMAND(ExportCommand, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- static unsigned int mayaDagPathToSdfPath(char* dagPathBuffer, unsigned int dagPathSize) { - char* writer = dagPathBuffer; - char* backTrack = writer; - - for (const char *reader = dagPathBuffer, *end = reader + dagPathSize; reader != end; ++reader) - { - const char c = *reader; - switch (c) - { - case ':': - writer = backTrack; - break; - - case '|': - *writer = '/'; - ++writer; - backTrack = writer; - break; - - default: - if (reader != writer) - *writer = c; - - ++writer; - break; + char* writer = dagPathBuffer; + char* backTrack = writer; + + for (const char *reader = dagPathBuffer, *end = reader + dagPathSize; reader != end; ++reader) { + const char c = *reader; + switch (c) { + case ':': writer = backTrack; break; + + case '|': + *writer = '/'; + ++writer; + backTrack = writer; + break; + + default: + if (reader != writer) + *writer = c; + + ++writer; + break; + } } - } - return writer - dagPathBuffer; + return writer - dagPathBuffer; } //---------------------------------------------------------------------------------------------------------------------- static inline SdfPath makeUsdPath(const MDagPath& rootPath, const MDagPath& path) { - // if the rootPath is empty, we can just use the entire path - const uint32_t rootPathLength = rootPath.length(); - if(!rootPathLength) - { - std::string fpn = AL::maya::utils::convert(path.fullPathName()); - fpn.resize(mayaDagPathToSdfPath(&fpn[0], fpn.size())); - return SdfPath(fpn); - } + // if the rootPath is empty, we can just use the entire path + const uint32_t rootPathLength = rootPath.length(); + if (!rootPathLength) { + std::string fpn = AL::maya::utils::convert(path.fullPathName()); + fpn.resize(mayaDagPathToSdfPath(&fpn[0], fpn.size())); + return SdfPath(fpn); + } - // otherwise we need to do a little fiddling. - MString rootPathString, pathString, newPathString; - rootPathString = rootPath.fullPathName(); - pathString = path.fullPathName(); + // otherwise we need to do a little fiddling. + MString rootPathString, pathString, newPathString; + rootPathString = rootPath.fullPathName(); + pathString = path.fullPathName(); - // trim off the root path from the object we are exporting - newPathString = pathString.substring(rootPathString.length(), pathString.length()); + // trim off the root path from the object we are exporting + newPathString = pathString.substring(rootPathString.length(), pathString.length()); - std::string fpn = AL::maya::utils::convert(newPathString); - fpn.resize(mayaDagPathToSdfPath(&fpn[0], fpn.size())); - return SdfPath(fpn); + std::string fpn = AL::maya::utils::convert(newPathString); + fpn.resize(mayaDagPathToSdfPath(&fpn[0], fpn.size())); + return SdfPath(fpn); } //---------------------------------------------------------------------------------------------------------------------- static inline MDagPath getParentPath(const MDagPath& dagPath) { - MFnDagNode dagNode(dagPath); - MFnDagNode parentNode(dagNode.parent(0)); - MDagPath parentPath; - parentNode.getPath(parentPath); - return parentPath; + MFnDagNode dagNode(dagPath); + MFnDagNode parentNode(dagNode.parent(0)); + MDagPath parentPath; + parentNode.getPath(parentPath); + return parentPath; } //---------------------------------------------------------------------------------------------------------------------- static inline SdfPath makeMasterPath(UsdPrim instancesPrim, const MDagPath& dagPath) { - MString fullPathName = dagPath.fullPathName(); - std::string fullPath(fullPathName.asChar() + 1, fullPathName.length() - 1); - std::string usdPath = instancesPrim.GetPath().GetString() + '/' + fullPath; - std::replace(usdPath.begin(), usdPath.end(), '|', '_'); - std::replace(usdPath.begin(), usdPath.end(), ':', '_'); - return SdfPath(usdPath); + MString fullPathName = dagPath.fullPathName(); + std::string fullPath(fullPathName.asChar() + 1, fullPathName.length() - 1); + std::string usdPath = instancesPrim.GetPath().GetString() + '/' + fullPath; + std::replace(usdPath.begin(), usdPath.end(), '|', '_'); + std::replace(usdPath.begin(), usdPath.end(), ':', '_'); + return SdfPath(usdPath); } //---------------------------------------------------------------------------------------------------------------------- @@ -129,197 +125,173 @@ static inline SdfPath makeMasterPath(UsdPrim instancesPrim, const MDagPath& dagP //---------------------------------------------------------------------------------------------------------------------- struct Export::Impl { - inline bool contains(const MFnDependencyNode& fn) - { - #if AL_UTILS_ENABLE_SIMD - union - { - __m128i sse; - AL::maya::utils::guid uuid; - }; - fn.uuid().get(uuid.uuid); - bool contains = m_nodeMap.find(sse) != m_nodeMap.end(); - if(!contains) - m_nodeMap.insert(std::make_pair(sse, fn.object())); - #else - AL::maya::utils::guid uuid; - fn.uuid().get(uuid.uuid); - bool contains = m_nodeMap.find(uuid) != m_nodeMap.end(); - if(!contains) - m_nodeMap.insert(std::make_pair(uuid, fn.object())); - #endif - return contains; - } - - inline bool contains(const MObject& obj) - { - MFnDependencyNode fn(obj); - return contains(fn); - } - - inline SdfPath getMasterPath(const MFnDagNode& fn) - { - #if AL_UTILS_ENABLE_SIMD - union + inline bool contains(const MFnDependencyNode& fn) { - __m128i sse; - AL::maya::utils::guid uuid; - }; - fn.uuid().get(uuid.uuid); - auto iterInst = m_instanceMap.find(sse); - if (iterInst == m_instanceMap.end()) +#if AL_UTILS_ENABLE_SIMD + union + { + __m128i sse; + AL::maya::utils::guid uuid; + }; + fn.uuid().get(uuid.uuid); + bool contains = m_nodeMap.find(sse) != m_nodeMap.end(); + if (!contains) + m_nodeMap.insert(std::make_pair(sse, fn.object())); +#else + AL::maya::utils::guid uuid; + fn.uuid().get(uuid.uuid); + bool contains = m_nodeMap.find(uuid) != m_nodeMap.end(); + if (!contains) + m_nodeMap.insert(std::make_pair(uuid, fn.object())); +#endif + return contains; + } + + inline bool contains(const MObject& obj) { - MDagPath dagPath; - fn.getPath(dagPath); - SdfPath instancePath = makeMasterPath(m_instancesPrim, dagPath); - m_instanceMap.emplace(sse, instancePath); - return instancePath; + MFnDependencyNode fn(obj); + return contains(fn); } - #else - AL::maya::utils::guid uuid; - fn.uuid().get(uuid.uuid); - auto iterInst = m_instanceMap.find(uuid); - if (iterInst == m_instanceMap.end()) + + inline SdfPath getMasterPath(const MFnDagNode& fn) { - MDagPath dagPath; - fn.getPath(dagPath); - SdfPath instancePath = makeMasterPath(m_instancesPrim, dagPath); - m_instanceMap.emplace(uuid, instancePath); - return instancePath; +#if AL_UTILS_ENABLE_SIMD + union + { + __m128i sse; + AL::maya::utils::guid uuid; + }; + fn.uuid().get(uuid.uuid); + auto iterInst = m_instanceMap.find(sse); + if (iterInst == m_instanceMap.end()) { + MDagPath dagPath; + fn.getPath(dagPath); + SdfPath instancePath = makeMasterPath(m_instancesPrim, dagPath); + m_instanceMap.emplace(sse, instancePath); + return instancePath; + } +#else + AL::maya::utils::guid uuid; + fn.uuid().get(uuid.uuid); + auto iterInst = m_instanceMap.find(uuid); + if (iterInst == m_instanceMap.end()) { + MDagPath dagPath; + fn.getPath(dagPath); + SdfPath instancePath = makeMasterPath(m_instancesPrim, dagPath); + m_instanceMap.emplace(uuid, instancePath); + return instancePath; + } +#endif + return iterInst->second; } - #endif - return iterInst->second; - } - - - inline bool setStage(UsdStageRefPtr ptr) - { - m_stage = ptr; - return m_stage; - } - - inline UsdStageRefPtr stage() - { - return m_stage; - } - - void setAnimationFrame(double minFrame, double maxFrame) - { - m_stage->SetStartTimeCode(minFrame); - m_stage->SetEndTimeCode(maxFrame); - } - - void setDefaultPrimIfOnlyOneRoot(SdfPath defaultPrim) - { - UsdPrim psuedo = m_stage->GetPseudoRoot(); - auto children = psuedo.GetChildren(); - auto first = children.begin(); - if(first != children.end()) + + inline bool setStage(UsdStageRefPtr ptr) { - auto next = first; - ++next; - if(next == children.end()) - { - // if we get here, there is only one prim at the root level. - // set that prim as the default prim. - m_stage->SetDefaultPrim(*first); - } + m_stage = ptr; + return m_stage; } - if (!m_stage->HasDefaultPrim() && !defaultPrim.IsEmpty()) + + inline UsdStageRefPtr stage() { return m_stage; } + + void setAnimationFrame(double minFrame, double maxFrame) { - m_stage->SetDefaultPrim(m_stage->GetPrimAtPath(defaultPrim)); + m_stage->SetStartTimeCode(minFrame); + m_stage->SetEndTimeCode(maxFrame); } - } - void filterSample() - { - std::vector timeSamples; - std::vector dupSamples; - for (auto prim : m_stage->Traverse()) + void setDefaultPrimIfOnlyOneRoot(SdfPath defaultPrim) { - std::vector attributes = prim.GetAuthoredAttributes(); - for (auto attr : attributes) - { - timeSamples.clear(); - dupSamples.clear(); - attr.GetTimeSamples(&timeSamples); - VtValue prevSampleBlob; - for (auto sample : timeSamples) - { - VtValue currSampleBlob; - attr.Get(&currSampleBlob, sample); - if (prevSampleBlob == currSampleBlob) - { - dupSamples.emplace_back(sample); - } - else - { - prevSampleBlob = currSampleBlob; - // only clear samples between constant segment - if (dupSamples.size() > 1) - { - dupSamples.pop_back(); - for (auto dup : dupSamples) - { - attr.ClearAtTime(dup); - } + UsdPrim psuedo = m_stage->GetPseudoRoot(); + auto children = psuedo.GetChildren(); + auto first = children.begin(); + if (first != children.end()) { + auto next = first; + ++next; + if (next == children.end()) { + // if we get here, there is only one prim at the root level. + // set that prim as the default prim. + m_stage->SetDefaultPrim(*first); } - dupSamples.clear(); - } } - for (auto dup : dupSamples) - { - attr.ClearAtTime(dup); + if (!m_stage->HasDefaultPrim() && !defaultPrim.IsEmpty()) { + m_stage->SetDefaultPrim(m_stage->GetPrimAtPath(defaultPrim)); + } + } + + void filterSample() + { + std::vector timeSamples; + std::vector dupSamples; + for (auto prim : m_stage->Traverse()) { + std::vector attributes = prim.GetAuthoredAttributes(); + for (auto attr : attributes) { + timeSamples.clear(); + dupSamples.clear(); + attr.GetTimeSamples(&timeSamples); + VtValue prevSampleBlob; + for (auto sample : timeSamples) { + VtValue currSampleBlob; + attr.Get(&currSampleBlob, sample); + if (prevSampleBlob == currSampleBlob) { + dupSamples.emplace_back(sample); + } else { + prevSampleBlob = currSampleBlob; + // only clear samples between constant segment + if (dupSamples.size() > 1) { + dupSamples.pop_back(); + for (auto dup : dupSamples) { + attr.ClearAtTime(dup); + } + } + dupSamples.clear(); + } + } + for (auto dup : dupSamples) { + attr.ClearAtTime(dup); + } + } } - } } - } - void doExport(const char* const filename, bool toFilter = false, SdfPath defaultPrim = SdfPath()) - { - setDefaultPrimIfOnlyOneRoot(defaultPrim); - if (toFilter) + void + doExport(const char* const filename, bool toFilter = false, SdfPath defaultPrim = SdfPath()) { - filterSample(); + setDefaultPrimIfOnlyOneRoot(defaultPrim); + if (toFilter) { + filterSample(); + } + m_stage->GetRootLayer()->Save(); + m_nodeMap.clear(); } - m_stage->GetRootLayer()->Save(); - m_nodeMap.clear(); - } - - inline UsdPrim instancesPrim() - { - return m_instancesPrim; - } - - void createInstancesPrim() - { - m_instancesPrim = m_stage->OverridePrim(SdfPath("/MayaExportedInstanceSources")); - } - - void processInstances() - { - if (!m_instancesPrim) - return; - if (!m_instancesPrim.GetAllChildren()) + + inline UsdPrim instancesPrim() { return m_instancesPrim; } + + void createInstancesPrim() { - m_stage->RemovePrim(m_instancesPrim.GetPrimPath()); + m_instancesPrim = m_stage->OverridePrim(SdfPath("/MayaExportedInstanceSources")); } - else + + void processInstances() { - m_instancesPrim.SetSpecifier(SdfSpecifierOver); + if (!m_instancesPrim) + return; + if (!m_instancesPrim.GetAllChildren()) { + m_stage->RemovePrim(m_instancesPrim.GetPrimPath()); + } else { + m_instancesPrim.SetSpecifier(SdfSpecifierOver); + } } - } private: - #if AL_UTILS_ENABLE_SIMD - std::map m_nodeMap; - std::map m_instanceMap; - #else - std::map m_nodeMap; - std::map m_instanceMap; - #endif - UsdStageRefPtr m_stage; - UsdPrim m_instancesPrim; +#if AL_UTILS_ENABLE_SIMD + std::map m_nodeMap; + std::map m_instanceMap; +#else + std::map m_nodeMap; + std::map m_instanceMap; +#endif + UsdStageRefPtr m_stage; + UsdPrim m_instancesPrim; }; static MObject g_transform_rotateAttr = MObject::kNullObj; @@ -330,953 +302,879 @@ static MObject g_geomConstraint_targetAttr = MObject::kNullObj; //---------------------------------------------------------------------------------------------------------------------- Export::Export(const ExporterParams& params) - : m_params(params), - m_impl(new Export::Impl), - m_translatorManufacture(nullptr) + : m_params(params) + , m_impl(new Export::Impl) + , m_translatorManufacture(nullptr) { - if(g_transform_rotateAttr == MObject::kNullObj) - { - MNodeClass nct("transform"); - MNodeClass nch("ikHandle"); - MNodeClass nce("ikEffector"); - MNodeClass ngc("geometryConstraint"); - g_transform_rotateAttr = nct.attribute("r"); - g_transform_translateAttr = nct.attribute("t"); - g_handle_startJointAttr = nch.attribute("hsj"); - g_effector_handleAttr = nce.attribute("hp"); - g_geomConstraint_targetAttr = ngc.attribute("tg"); - } - - if(params.m_activateAllTranslators) - { - m_translatorManufacture.activateAll(); - } - else - { - m_translatorManufacture.deactivateAll(); - } - - if(!params.m_activePluginTranslators.empty()) - { - m_translatorManufacture.activate(params.m_activePluginTranslators); - } - if(!params.m_inactivePluginTranslators.empty()) - { - m_translatorManufacture.deactivate(params.m_inactivePluginTranslators); - } - - if(m_impl->setStage(UsdStage::CreateNew(m_params.m_fileName.asChar()))) - { - doExport(); - } + if (g_transform_rotateAttr == MObject::kNullObj) { + MNodeClass nct("transform"); + MNodeClass nch("ikHandle"); + MNodeClass nce("ikEffector"); + MNodeClass ngc("geometryConstraint"); + g_transform_rotateAttr = nct.attribute("r"); + g_transform_translateAttr = nct.attribute("t"); + g_handle_startJointAttr = nch.attribute("hsj"); + g_effector_handleAttr = nce.attribute("hp"); + g_geomConstraint_targetAttr = ngc.attribute("tg"); + } + + if (params.m_activateAllTranslators) { + m_translatorManufacture.activateAll(); + } else { + m_translatorManufacture.deactivateAll(); + } + + if (!params.m_activePluginTranslators.empty()) { + m_translatorManufacture.activate(params.m_activePluginTranslators); + } + if (!params.m_inactivePluginTranslators.empty()) { + m_translatorManufacture.deactivate(params.m_inactivePluginTranslators); + } + + if (m_impl->setStage(UsdStage::CreateNew(m_params.m_fileName.asChar()))) { + doExport(); + } } //---------------------------------------------------------------------------------------------------------------------- -Export::~Export() -{ - delete m_impl; -} +Export::~Export() { delete m_impl; } //---------------------------------------------------------------------------------------------------------------------- UsdPrim Export::exportMeshUV(MDagPath path, const SdfPath& usdPath) { - UsdPrim overPrim = m_impl->stage()->OverridePrim(usdPath); - MStatus status; - MFnMesh fnMesh(path, &status); - AL_MAYA_CHECK_ERROR2(status, MString("unable to attach function set to mesh") + path.fullPathName()); - if (status == MStatus::kSuccess) - { - UsdGeomMesh mesh(overPrim); - AL::usdmaya::utils::MeshExportContext context(path, mesh, UsdTimeCode::Default(), false); - context.copyUvSetData(); - } - return overPrim; + UsdPrim overPrim = m_impl->stage()->OverridePrim(usdPath); + MStatus status; + MFnMesh fnMesh(path, &status); + AL_MAYA_CHECK_ERROR2( + status, MString("unable to attach function set to mesh") + path.fullPathName()); + if (status == MStatus::kSuccess) { + UsdGeomMesh mesh(overPrim); + AL::usdmaya::utils::MeshExportContext context(path, mesh, UsdTimeCode::Default(), false); + context.copyUvSetData(); + } + return overPrim; } //---------------------------------------------------------------------------------------------------------------------- UsdPrim Export::exportAssembly(MDagPath path, const SdfPath& usdPath) { - UsdGeomXform mesh = UsdGeomXform::Define(m_impl->stage(), usdPath); - if(!m_params.m_mergeTransforms) - mesh.GetPrim().SetMetadata(AL::usdmaya::Metadata::mergedTransform, AL::usdmaya::Metadata::unmerged); - return mesh.GetPrim(); + UsdGeomXform mesh = UsdGeomXform::Define(m_impl->stage(), usdPath); + if (!m_params.m_mergeTransforms) + mesh.GetPrim().SetMetadata( + AL::usdmaya::Metadata::mergedTransform, AL::usdmaya::Metadata::unmerged); + return mesh.GetPrim(); } //---------------------------------------------------------------------------------------------------------------------- UsdPrim Export::exportPluginLocatorNode(MDagPath path, const SdfPath& usdPath) { - UsdGeomXform mesh = UsdGeomXform::Define(m_impl->stage(), usdPath); - if(!m_params.m_mergeTransforms) - mesh.GetPrim().SetMetadata(AL::usdmaya::Metadata::mergedTransform, AL::usdmaya::Metadata::unmerged); - return mesh.GetPrim(); + UsdGeomXform mesh = UsdGeomXform::Define(m_impl->stage(), usdPath); + if (!m_params.m_mergeTransforms) + mesh.GetPrim().SetMetadata( + AL::usdmaya::Metadata::mergedTransform, AL::usdmaya::Metadata::unmerged); + return mesh.GetPrim(); } //---------------------------------------------------------------------------------------------------------------------- UsdPrim Export::exportPluginShape(MDagPath path, const SdfPath& usdPath) { - UsdGeomXform mesh = UsdGeomXform::Define(m_impl->stage(), usdPath); - if(!m_params.m_mergeTransforms) - mesh.GetPrim().SetMetadata(AL::usdmaya::Metadata::mergedTransform, AL::usdmaya::Metadata::unmerged); - return mesh.GetPrim(); + UsdGeomXform mesh = UsdGeomXform::Define(m_impl->stage(), usdPath); + if (!m_params.m_mergeTransforms) + mesh.GetPrim().SetMetadata( + AL::usdmaya::Metadata::mergedTransform, AL::usdmaya::Metadata::unmerged); + return mesh.GetPrim(); } //---------------------------------------------------------------------------------------------------------------------- void Export::exportGeometryConstraint(MDagPath constraintPath, const SdfPath& usdPath) { - auto animTranslator = m_params.m_animTranslator; - if(!animTranslator) - { - return; - } - - MPlug plug(constraintPath.node(), g_geomConstraint_targetAttr); - for(uint32_t i = 0, n = plug.numElements(); i < n; ++i) - { - MPlug geom = plug.elementByLogicalIndex(i).child(0); - MPlugArray connected; - geom.connectedTo(connected, true, true); - if(connected.length()) - { - MPlug inputGeom = connected[0]; - MFnDagNode fn(inputGeom.node()); - MDagPath geomPath; - fn.getPath(geomPath); - if(AnimationTranslator::isAnimatedMesh(geomPath)) - { - auto stage = m_impl->stage(); - - // move to the constrained node - constraintPath.pop(); - - SdfPath newPath = usdPath.GetParentPath(); + auto animTranslator = m_params.m_animTranslator; + if (!animTranslator) { + return; + } - UsdPrim prim = stage->GetPrimAtPath(newPath); - if(prim) - { - UsdGeomXform xform(prim); - bool reset; - std::vector ops = xform.GetOrderedXformOps(&reset); - for(auto op : ops) - { - const TransformOperation thisOp = xformOpToEnum(op.GetBaseName()); - if(thisOp == kTranslate) - { - animTranslator->forceAddPlug(MPlug(constraintPath.node(), g_transform_translateAttr), op.GetAttr()); - break; + MPlug plug(constraintPath.node(), g_geomConstraint_targetAttr); + for (uint32_t i = 0, n = plug.numElements(); i < n; ++i) { + MPlug geom = plug.elementByLogicalIndex(i).child(0); + MPlugArray connected; + geom.connectedTo(connected, true, true); + if (connected.length()) { + MPlug inputGeom = connected[0]; + MFnDagNode fn(inputGeom.node()); + MDagPath geomPath; + fn.getPath(geomPath); + if (AnimationTranslator::isAnimatedMesh(geomPath)) { + auto stage = m_impl->stage(); + + // move to the constrained node + constraintPath.pop(); + + SdfPath newPath = usdPath.GetParentPath(); + + UsdPrim prim = stage->GetPrimAtPath(newPath); + if (prim) { + UsdGeomXform xform(prim); + bool reset; + std::vector ops = xform.GetOrderedXformOps(&reset); + for (auto op : ops) { + const TransformOperation thisOp = xformOpToEnum(op.GetBaseName()); + if (thisOp == kTranslate) { + animTranslator->forceAddPlug( + MPlug(constraintPath.node(), g_transform_translateAttr), + op.GetAttr()); + break; + } + } + return; + } else { + std::cout << "prim not valid " << newPath.GetText() << std::endl; + } } - } - return; } - else - { - std::cout << "prim not valid " << newPath.GetText() << std::endl; - } - } } - } } //---------------------------------------------------------------------------------------------------------------------- void Export::exportIkChain(MDagPath effectorPath, const SdfPath& usdPath) { - auto animTranslator = m_params.m_animTranslator; - if(!animTranslator) - { - return; - } - - MPlug hp(effectorPath.node(), g_effector_handleAttr); - hp = hp.elementByLogicalIndex(0); - MPlugArray connected; - hp.connectedTo(connected, true, true); - if(connected.length()) - { - // grab the handle node - MObject handleObj = connected[0].node(); - - MPlug translatePlug(handleObj, g_transform_translateAttr); - - // if the translation values on the ikHandle is animated, then we can assume the rotation values on the - // joint chain between the effector and the start joint will also be animated - bool handleIsAnimated = AnimationTranslator::isAnimated(translatePlug, true); - if(handleIsAnimated) - { - // locate the start joint in the chain - MPlug startJoint(handleObj, g_handle_startJointAttr); - MPlugArray connected; - startJoint.connectedTo(connected, true, true); - if(connected.length()) - { - // this will be the top chain in the system - MObject startNode = connected[0].node(); - - auto stage = m_impl->stage(); - SdfPath newPath = usdPath; - - UsdPrim prim; - // now step up from the effector to the start joint and output the rotations - do - { - // no point handling the effector - effectorPath.pop(); - newPath = newPath.GetParentPath(); - - prim = stage->GetPrimAtPath(newPath); - if(prim) - { - UsdGeomXform xform(prim); - MPlug rotatePlug(effectorPath.node(), g_transform_rotateAttr); - bool reset; - std::vector ops = xform.GetOrderedXformOps(&reset); - for(auto op : ops) - { - const float radToDeg = 180.0f / 3.141592654f; - bool added = false; - switch(op.GetOpType()) - { - case UsdGeomXformOp::TypeRotateXYZ: - case UsdGeomXformOp::TypeRotateXZY: - case UsdGeomXformOp::TypeRotateYXZ: - case UsdGeomXformOp::TypeRotateYZX: - case UsdGeomXformOp::TypeRotateZXY: - case UsdGeomXformOp::TypeRotateZYX: - added = true; - animTranslator->forceAddPlug(rotatePlug, op.GetAttr(), radToDeg); - break; - default: - break; - } - if(added) break; + auto animTranslator = m_params.m_animTranslator; + if (!animTranslator) { + return; + } + + MPlug hp(effectorPath.node(), g_effector_handleAttr); + hp = hp.elementByLogicalIndex(0); + MPlugArray connected; + hp.connectedTo(connected, true, true); + if (connected.length()) { + // grab the handle node + MObject handleObj = connected[0].node(); + + MPlug translatePlug(handleObj, g_transform_translateAttr); + + // if the translation values on the ikHandle is animated, then we can assume the rotation + // values on the joint chain between the effector and the start joint will also be animated + bool handleIsAnimated = AnimationTranslator::isAnimated(translatePlug, true); + if (handleIsAnimated) { + // locate the start joint in the chain + MPlug startJoint(handleObj, g_handle_startJointAttr); + MPlugArray connected; + startJoint.connectedTo(connected, true, true); + if (connected.length()) { + // this will be the top chain in the system + MObject startNode = connected[0].node(); + + auto stage = m_impl->stage(); + SdfPath newPath = usdPath; + + UsdPrim prim; + // now step up from the effector to the start joint and output the rotations + do { + // no point handling the effector + effectorPath.pop(); + newPath = newPath.GetParentPath(); + + prim = stage->GetPrimAtPath(newPath); + if (prim) { + UsdGeomXform xform(prim); + MPlug rotatePlug(effectorPath.node(), g_transform_rotateAttr); + bool reset; + std::vector ops = xform.GetOrderedXformOps(&reset); + for (auto op : ops) { + const float radToDeg = 180.0f / 3.141592654f; + bool added = false; + switch (op.GetOpType()) { + case UsdGeomXformOp::TypeRotateXYZ: + case UsdGeomXformOp::TypeRotateXZY: + case UsdGeomXformOp::TypeRotateYXZ: + case UsdGeomXformOp::TypeRotateYZX: + case UsdGeomXformOp::TypeRotateZXY: + case UsdGeomXformOp::TypeRotateZYX: + added = true; + animTranslator->forceAddPlug(rotatePlug, op.GetAttr(), radToDeg); + break; + default: break; + } + if (added) + break; + } + } else { + std::cout << "prim not valid" << std::endl; + } + } while (effectorPath.node() != startNode); } - } - else - { - std::cout << "prim not valid" << std::endl; - } } - while(effectorPath.node() != startNode); - } } - } - return; + return; } //---------------------------------------------------------------------------------------------------------------------- void Export::copyTransformParams(UsdPrim prim, MFnTransform& fnTransform) { - translators::TransformTranslator::copyAttributes(fnTransform.object(), prim, m_params, fnTransform.dagPath()); - if(m_params.m_dynamicAttributes) - { - translators::DgNodeTranslator::copyDynamicAttributes(fnTransform.object(), prim, m_params.m_animTranslator); - } + translators::TransformTranslator::copyAttributes( + fnTransform.object(), prim, m_params, fnTransform.dagPath()); + if (m_params.m_dynamicAttributes) { + translators::DgNodeTranslator::copyDynamicAttributes( + fnTransform.object(), prim, m_params.m_animTranslator); + } - // handle the special case of exporting - { - auto dataPlugins = m_translatorManufacture.getExtraDataPlugins(fnTransform.object()); - for(auto dataPlugin : dataPlugins) + // handle the special case of exporting { - if(dataPlugin->getFnType() == MFn::kTransform) - { - dataPlugin->exportObject(prim, fnTransform.object(), ExporterParams()); - } + auto dataPlugins = m_translatorManufacture.getExtraDataPlugins(fnTransform.object()); + for (auto dataPlugin : dataPlugins) { + if (dataPlugin->getFnType() == MFn::kTransform) { + dataPlugin->exportObject(prim, fnTransform.object(), ExporterParams()); + } + } } - } } //---------------------------------------------------------------------------------------------------------------------- SdfPath Export::determineUsdPath(MDagPath path, const SdfPath& usdPath, ReferenceType refType) { - switch (refType) - { - case kNoReference: - { - return usdPath; - } - break; - - case kShapeReference: - { - return makeMasterPath(m_impl->instancesPrim(), path); - } - break; - - case kTransformReference: - { - UsdStageRefPtr stage = m_impl->stage(); - SdfPath masterTransformPath = makeMasterPath(m_impl->instancesPrim(), getParentPath(path)); - if (!stage->GetPrimAtPath(masterTransformPath)) - { - auto parentPrim = UsdGeomXform::Define(stage, masterTransformPath); - if(!m_params.m_mergeTransforms) - parentPrim.GetPrim().SetMetadata(AL::usdmaya::Metadata::mergedTransform, AL::usdmaya::Metadata::unmerged); - } - TfToken shapeName(MFnDagNode(path).name().asChar()); - return masterTransformPath.AppendChild(shapeName); + switch (refType) { + case kNoReference: { + return usdPath; + } break; + + case kShapeReference: { + return makeMasterPath(m_impl->instancesPrim(), path); + } break; + + case kTransformReference: { + UsdStageRefPtr stage = m_impl->stage(); + SdfPath masterTransformPath = makeMasterPath(m_impl->instancesPrim(), getParentPath(path)); + if (!stage->GetPrimAtPath(masterTransformPath)) { + auto parentPrim = UsdGeomXform::Define(stage, masterTransformPath); + if (!m_params.m_mergeTransforms) + parentPrim.GetPrim().SetMetadata( + AL::usdmaya::Metadata::mergedTransform, AL::usdmaya::Metadata::unmerged); + } + TfToken shapeName(MFnDagNode(path).name().asChar()); + return masterTransformPath.AppendChild(shapeName); + } break; } - break; - } - return SdfPath(); + return SdfPath(); } //---------------------------------------------------------------------------------------------------------------------- -void Export::addReferences(MDagPath shapePath, MFnTransform& fnTransform, SdfPath& usdPath, - const SdfPath& instancePath, ReferenceType refType) +void Export::addReferences( + MDagPath shapePath, + MFnTransform& fnTransform, + SdfPath& usdPath, + const SdfPath& instancePath, + ReferenceType refType) { - UsdStageRefPtr stage = m_impl->stage(); - if (refType == kShapeReference) - { - if (shapePath.node().hasFn(MFn::kMesh)) - { - UsdGeomMesh::Define(stage, usdPath); - } - else if (shapePath.node().hasFn(MFn::kNurbsCurve)) - { - UsdGeomNurbsCurves::Define(stage, usdPath); + UsdStageRefPtr stage = m_impl->stage(); + if (refType == kShapeReference) { + if (shapePath.node().hasFn(MFn::kMesh)) { + UsdGeomMesh::Define(stage, usdPath); + } else if (shapePath.node().hasFn(MFn::kNurbsCurve)) { + UsdGeomNurbsCurves::Define(stage, usdPath); + } } - } - UsdPrim usdPrim = stage->GetPrimAtPath(usdPath); - if (usdPrim) - { - // usd only allows instanceable on transform prim - switch (refType) - { - case kTransformReference: - { - usdPrim.SetInstanceable(true); - } - break; - - case kShapeReference: - { - copyTransformParams(usdPrim, fnTransform); - } - break; - - default: - break; + UsdPrim usdPrim = stage->GetPrimAtPath(usdPath); + if (usdPrim) { + // usd only allows instanceable on transform prim + switch (refType) { + case kTransformReference: { + usdPrim.SetInstanceable(true); + } break; + + case kShapeReference: { + copyTransformParams(usdPrim, fnTransform); + } break; + + default: break; + } + usdPrim.GetReferences().AddReference(SdfReference("", instancePath)); } - usdPrim.GetReferences().AddReference(SdfReference("", instancePath)); - } } //---------------------------------------------------------------------------------------------------------------------- bool Export::isPrimDefined(SdfPath& usdPath) { - UsdPrim transformPrim = m_impl->stage()->GetPrimAtPath(usdPath); - return (transformPrim && transformPrim.IsDefined()); + UsdPrim transformPrim = m_impl->stage()->GetPrimAtPath(usdPath); + return (transformPrim && transformPrim.IsDefined()); } //---------------------------------------------------------------------------------------------------------------------- -void Export::exportShapesCommonProc(MDagPath shapePath, MFnTransform& fnTransform, SdfPath& usdPath, - const ReferenceType refType) +void Export::exportShapesCommonProc( + MDagPath shapePath, + MFnTransform& fnTransform, + SdfPath& usdPath, + const ReferenceType refType) { - UsdPrim transformPrim; - - bool copyTransform = true; - MFnDagNode dgNode(shapePath); - translators::TranslatorManufacture::RefPtr translatorPtr = m_translatorManufacture.get(shapePath.node()); - if (translatorPtr) - { - SdfPath shapeUsdPath = determineUsdPath(shapePath, usdPath, refType); - - // If the prim is valid and has already been defined, we skip the leftover shapes. - // Since that is probably the case a transform has multiple shapes and we chose to merge transform. - // In that case, once a shape get exported we will skip the rest of shapes. - if(isPrimDefined(shapeUsdPath)) - { - TF_WARN("The usd prim: %s has already been defined, will skip exporting the shape: %s", - shapeUsdPath.GetText(), shapePath.partialPathName().asChar()); - return; - } + UsdPrim transformPrim; + + bool copyTransform = true; + MFnDagNode dgNode(shapePath); + translators::TranslatorManufacture::RefPtr translatorPtr + = m_translatorManufacture.get(shapePath.node()); + if (translatorPtr) { + SdfPath shapeUsdPath = determineUsdPath(shapePath, usdPath, refType); + + // If the prim is valid and has already been defined, we skip the leftover shapes. + // Since that is probably the case a transform has multiple shapes and we chose to merge + // transform. In that case, once a shape get exported we will skip the rest of shapes. + if (isPrimDefined(shapeUsdPath)) { + TF_WARN( + "The usd prim: %s has already been defined, will skip exporting the shape: %s", + shapeUsdPath.GetText(), + shapePath.partialPathName().asChar()); + return; + } - transformPrim = translatorPtr->exportObject(m_impl->stage(), shapePath, shapeUsdPath, m_params); - auto dataPlugins = m_translatorManufacture.getExtraDataPlugins(shapePath.node()); - for(auto dataPlugin : dataPlugins) - { - dataPlugin->exportObject(transformPrim, shapePath.node(), m_params); - } + transformPrim + = translatorPtr->exportObject(m_impl->stage(), shapePath, shapeUsdPath, m_params); + auto dataPlugins = m_translatorManufacture.getExtraDataPlugins(shapePath.node()); + for (auto dataPlugin : dataPlugins) { + dataPlugin->exportObject(transformPrim, shapePath.node(), m_params); + } - copyTransform = (refType == kNoReference); - } - else // no translator register for this Maya type - { - // As same reason above, for multiple shapes transform, once there's a shape exported, we ignore the leftovers: - if(isPrimDefined(usdPath)) + copyTransform = (refType == kNoReference); + } else // no translator register for this Maya type { - TF_WARN("The usd prim: %s has already been defined, will skip exporting the shape: %s", - usdPath.GetText(), shapePath.partialPathName().asChar()); - return; - } + // As same reason above, for multiple shapes transform, once there's a shape exported, we + // ignore the leftovers: + if (isPrimDefined(usdPath)) { + TF_WARN( + "The usd prim: %s has already been defined, will skip exporting the shape: %s", + usdPath.GetText(), + shapePath.partialPathName().asChar()); + return; + } - if (shapePath.node().hasFn(MFn::kAssembly)) - { - transformPrim = exportAssembly(shapePath, usdPath); + if (shapePath.node().hasFn(MFn::kAssembly)) { + transformPrim = exportAssembly(shapePath, usdPath); + } else if (shapePath.node().hasFn(MFn::kPluginLocatorNode)) { + transformPrim = exportPluginLocatorNode(shapePath, usdPath); + } else if (shapePath.node().hasFn(MFn::kPluginShape)) { + transformPrim = exportPluginShape(shapePath, usdPath); + } } - else - if (shapePath.node().hasFn(MFn::kPluginLocatorNode)) - { - transformPrim = exportPluginLocatorNode(shapePath, usdPath); + + // if we haven't created a transform for this shape (possible if we chose not to export it) + // create a transform shape for the prim. + if (!transformPrim) { + UsdGeomXform xform = UsdGeomXform::Define(m_impl->stage(), usdPath); + transformPrim = xform.GetPrim(); } - else - if (shapePath.node().hasFn(MFn::kPluginShape)) - { - transformPrim = exportPluginShape(shapePath, usdPath); + + if (m_params.m_mergeTransforms && copyTransform) { + copyTransformParams(transformPrim, fnTransform); } - } - - // if we haven't created a transform for this shape (possible if we chose not to export it) - // create a transform shape for the prim. - if (!transformPrim) - { - UsdGeomXform xform = UsdGeomXform::Define(m_impl->stage(), usdPath); - transformPrim = xform.GetPrim(); - } - - if(m_params.m_mergeTransforms && copyTransform) - { - copyTransformParams(transformPrim, fnTransform); - } } //---------------------------------------------------------------------------------------------------------------------- void Export::exportShapesOnlyUVProc(MDagPath shapePath, MFnTransform& fnTransform, SdfPath& usdPath) { - if(shapePath.node().hasFn(MFn::kMesh)) - { - exportMeshUV(shapePath, usdPath); - } - else - { - m_impl->stage()->OverridePrim(usdPath); - } + if (shapePath.node().hasFn(MFn::kMesh)) { + exportMeshUV(shapePath, usdPath); + } else { + m_impl->stage()->OverridePrim(usdPath); + } } //---------------------------------------------------------------------------------------------------------------------- void Export::exportSceneHierarchy(MDagPath rootPath, SdfPath& defaultPrim) { - MDagPath parentPath = rootPath; - parentPath.pop(); - static const TfToken xformToken("Xform"); - - MItDag it(MItDag::kDepthFirst); - it.reset(rootPath, MItDag::kDepthFirst, MFn::kTransform); - - std::function exportShapeProc = - [this] (MDagPath shapePath, MFnTransform& fnTransform, SdfPath& usdPath, ReferenceType refType) - { - this->exportShapesCommonProc(shapePath, fnTransform, usdPath, refType); - }; - - std::function exportTransformFunc = - [this] (MDagPath transformPath, MFnTransform& fnTransform, SdfPath& usdPath, bool inWorldSpace) - { - SdfPath path; - if(inWorldSpace) - { - const std::string& pathName = usdPath.GetString(); - size_t s = pathName.find_last_of('/'); - path = SdfPath(pathName.data() + s); - } - else - { - path = usdPath; - } - - bool exportKids = true; - translators::TranslatorManufacture::RefPtr translatorPtr = m_translatorManufacture.get(transformPath.node()); - if (translatorPtr) - { - UsdPrim transformPrim = translatorPtr->exportObject(m_impl->stage(), transformPath, path, m_params); - this->copyTransformParams(transformPrim, fnTransform); - exportKids = translatorPtr->exportDescendants(); - } - else - { + MDagPath parentPath = rootPath; + parentPath.pop(); + static const TfToken xformToken("Xform"); + + MItDag it(MItDag::kDepthFirst); + it.reset(rootPath, MItDag::kDepthFirst, MFn::kTransform); + + std::function exportShapeProc + = [this]( + MDagPath shapePath, + MFnTransform& fnTransform, + SdfPath& usdPath, + ReferenceType refType) { + this->exportShapesCommonProc(shapePath, fnTransform, usdPath, refType); + }; + + std::function exportTransformFunc + = [this]( + MDagPath transformPath, + MFnTransform& fnTransform, + SdfPath& usdPath, + bool inWorldSpace) { + SdfPath path; + if (inWorldSpace) { + const std::string& pathName = usdPath.GetString(); + size_t s = pathName.find_last_of('/'); + path = SdfPath(pathName.data() + s); + } else { + path = usdPath; + } - UsdGeomXform xform = UsdGeomXform::Define(m_impl->stage(), path); - UsdPrim transformPrim = xform.GetPrim(); - this->copyTransformParams(transformPrim, fnTransform); - } - return exportKids; - }; - - // choose right proc required by meshUV option; - if (m_params.getBool("Mesh UV Only")) - { - exportShapeProc = - [this] (MDagPath shapePath, MFnTransform& fnTransform, SdfPath& usdPath, ReferenceType refType) - { - this->exportShapesOnlyUVProc(shapePath, fnTransform, usdPath); - }; - exportTransformFunc = - [this] (MDagPath transformPath, MFnTransform& fnTransform, SdfPath& usdPath, bool inWorldSpace) - { - const std::string& pathName = usdPath.GetString(); - size_t s = pathName.find_last_of('/'); - SdfPath path(pathName.data() + s); - m_impl->stage()->OverridePrim(path); - return true; - }; - } - - MFnTransform fnTransform; - // loop through transforms only - while(!it.isDone()) - { - // assign transform function set - MDagPath transformPath; - it.getPath(transformPath); - - fnTransform.setObject(transformPath); - - // Make sure we haven't seen this transform before. - bool transformHasBeenExported = m_impl->contains(fnTransform); - if(transformHasBeenExported) - { - // We have an instanced shape! - std::cout << "encountered transform instance " << fnTransform.fullPathName().asChar() << std::endl; + bool exportKids = true; + translators::TranslatorManufacture::RefPtr translatorPtr + = m_translatorManufacture.get(transformPath.node()); + if (translatorPtr) { + UsdPrim transformPrim + = translatorPtr->exportObject(m_impl->stage(), transformPath, path, m_params); + this->copyTransformParams(transformPrim, fnTransform); + exportKids = translatorPtr->exportDescendants(); + } else { + + UsdGeomXform xform = UsdGeomXform::Define(m_impl->stage(), path); + UsdPrim transformPrim = xform.GetPrim(); + this->copyTransformParams(transformPrim, fnTransform); + } + return exportKids; + }; + + // choose right proc required by meshUV option; + if (m_params.getBool("Mesh UV Only")) { + exportShapeProc = [this]( + MDagPath shapePath, + MFnTransform& fnTransform, + SdfPath& usdPath, + ReferenceType refType) { + this->exportShapesOnlyUVProc(shapePath, fnTransform, usdPath); + }; + exportTransformFunc = [this]( + MDagPath transformPath, + MFnTransform& fnTransform, + SdfPath& usdPath, + bool inWorldSpace) { + const std::string& pathName = usdPath.GetString(); + size_t s = pathName.find_last_of('/'); + SdfPath path(pathName.data() + s); + m_impl->stage()->OverridePrim(path); + return true; + }; } - if(!transformHasBeenExported || m_params.m_duplicateInstances) - { - // generate a USD path from the current path - SdfPath usdPath; - - // we should take a look to see whether the name was changed on import. - // If it did change, make sure we save it using the original name, and not the new one. - MStatus status; - MPlug originalNamePlug = fnTransform.findPlug("alusd_originalPath", &status); - if(!status) - { - usdPath = makeUsdPath(parentPath, transformPath); - } - - // for UV only exporting, record first prim as default - if (m_params.getBool("Mesh UV Only") && defaultPrim.IsEmpty()) - { - defaultPrim = usdPath; - } - - if(transformPath.node().hasFn(MFn::kIkEffector)) - { - exportIkChain(transformPath, usdPath); - } - else - if(transformPath.node().hasFn(MFn::kGeometryConstraint)) - { - exportGeometryConstraint(transformPath, usdPath); - } - - // how many shapes are directly under this transform path? - uint32_t numShapes; - transformPath.numberOfShapesDirectlyBelow(numShapes); - - if(!m_params.m_mergeTransforms && !m_params.m_exportInWorldSpace) - { - bool exportKids = exportTransformFunc(transformPath, fnTransform, usdPath, m_params.m_exportInWorldSpace); - UsdPrim prim = m_impl->stage()->GetPrimAtPath(usdPath); - prim.SetMetadata(AL::usdmaya::Metadata::mergedTransform, AL::usdmaya::Metadata::unmerged); - if (!exportKids) - { - it.prune(); + MFnTransform fnTransform; + // loop through transforms only + while (!it.isDone()) { + // assign transform function set + MDagPath transformPath; + it.getPath(transformPath); + + fnTransform.setObject(transformPath); + + // Make sure we haven't seen this transform before. + bool transformHasBeenExported = m_impl->contains(fnTransform); + if (transformHasBeenExported) { + // We have an instanced shape! + std::cout << "encountered transform instance " << fnTransform.fullPathName().asChar() + << std::endl; } - } - if(numShapes) - { - // This is a slight annoyance about the way that USD has no concept of - // shapes (it merges shapes into transforms usually). This means if we have - // 1 transform, with 4 shapes parented underneath, it means we'll end up with - // the transform data duplicated four times. + if (!transformHasBeenExported || m_params.m_duplicateInstances) { + // generate a USD path from the current path + SdfPath usdPath; - ReferenceType refType = kNoReference; + // we should take a look to see whether the name was changed on import. + // If it did change, make sure we save it using the original name, and not the new one. + MStatus status; + MPlug originalNamePlug = fnTransform.findPlug("alusd_originalPath", &status); + if (!status) { + usdPath = makeUsdPath(parentPath, transformPath); + } - for(uint32_t j = 0; j < numShapes; ++j) - { - MDagPath shapePath = transformPath; - shapePath.extendToShapeDirectlyBelow(j); - MFnDagNode shapeDag(shapePath); - SdfPath shapeUsdPath = usdPath; - - if(!m_params.m_mergeTransforms) - { - fnTransform.setObject(shapePath); - shapeUsdPath = makeUsdPath(parentPath, shapePath); - } - - bool shapeNotYetExported = !m_impl->contains(shapePath.node()); - bool shapeInstanced = shapePath.isInstanced(); - if(shapeNotYetExported || m_params.m_duplicateInstances) - { - // if the path has a child shape, process the shape now - if (!m_params.m_duplicateInstances && shapeInstanced) - { - refType = m_params.m_mergeTransforms ? kShapeReference : kTransformReference; + // for UV only exporting, record first prim as default + if (m_params.getBool("Mesh UV Only") && defaultPrim.IsEmpty()) { + defaultPrim = usdPath; } - exportShapeProc(shapePath, fnTransform, shapeUsdPath, refType); - } - else - { - refType = m_params.m_mergeTransforms ? kShapeReference : kTransformReference; - } - - if (refType == kShapeReference) - { - SdfPath instancePath = m_impl->getMasterPath(shapeDag); - addReferences(shapePath, fnTransform, shapeUsdPath, instancePath, refType); - } - else if (refType == kTransformReference) - { - SdfPath instancePath = m_impl->getMasterPath(MFnDagNode(shapeDag.parent(0))); - addReferences(shapePath, fnTransform, usdPath, instancePath, refType); - } - } - } - else - { - if(m_params.m_mergeTransforms) - { - if (!exportTransformFunc(transformPath, fnTransform, usdPath, m_params.m_exportInWorldSpace)) - { - it.prune(); - } + + if (transformPath.node().hasFn(MFn::kIkEffector)) { + exportIkChain(transformPath, usdPath); + } else if (transformPath.node().hasFn(MFn::kGeometryConstraint)) { + exportGeometryConstraint(transformPath, usdPath); + } + + // how many shapes are directly under this transform path? + uint32_t numShapes; + transformPath.numberOfShapesDirectlyBelow(numShapes); + + if (!m_params.m_mergeTransforms && !m_params.m_exportInWorldSpace) { + bool exportKids = exportTransformFunc( + transformPath, fnTransform, usdPath, m_params.m_exportInWorldSpace); + UsdPrim prim = m_impl->stage()->GetPrimAtPath(usdPath); + prim.SetMetadata( + AL::usdmaya::Metadata::mergedTransform, AL::usdmaya::Metadata::unmerged); + if (!exportKids) { + it.prune(); + } + } + + if (numShapes) { + // This is a slight annoyance about the way that USD has no concept of + // shapes (it merges shapes into transforms usually). This means if we have + // 1 transform, with 4 shapes parented underneath, it means we'll end up with + // the transform data duplicated four times. + + ReferenceType refType = kNoReference; + + for (uint32_t j = 0; j < numShapes; ++j) { + MDagPath shapePath = transformPath; + shapePath.extendToShapeDirectlyBelow(j); + MFnDagNode shapeDag(shapePath); + SdfPath shapeUsdPath = usdPath; + + if (!m_params.m_mergeTransforms) { + fnTransform.setObject(shapePath); + shapeUsdPath = makeUsdPath(parentPath, shapePath); + } + + bool shapeNotYetExported = !m_impl->contains(shapePath.node()); + bool shapeInstanced = shapePath.isInstanced(); + if (shapeNotYetExported || m_params.m_duplicateInstances) { + // if the path has a child shape, process the shape now + if (!m_params.m_duplicateInstances && shapeInstanced) { + refType = m_params.m_mergeTransforms ? kShapeReference + : kTransformReference; + } + exportShapeProc(shapePath, fnTransform, shapeUsdPath, refType); + } else { + refType + = m_params.m_mergeTransforms ? kShapeReference : kTransformReference; + } + + if (refType == kShapeReference) { + SdfPath instancePath = m_impl->getMasterPath(shapeDag); + addReferences(shapePath, fnTransform, shapeUsdPath, instancePath, refType); + } else if (refType == kTransformReference) { + SdfPath instancePath + = m_impl->getMasterPath(MFnDagNode(shapeDag.parent(0))); + addReferences(shapePath, fnTransform, usdPath, instancePath, refType); + } + } + } else { + if (m_params.m_mergeTransforms) { + if (!exportTransformFunc( + transformPath, fnTransform, usdPath, m_params.m_exportInWorldSpace)) { + it.prune(); + } + } + } + } else { + // We have an instanced transform + // How do we reference that here? } - } - } - else - { - // We have an instanced transform - // How do we reference that here? - } - it.next(); - } + it.next(); + } } //---------------------------------------------------------------------------------------------------------------------- void Export::doExport() { - auto context = translators::TranslatorContext::create(nullptr); - translators::TranslatorManufacture::preparePythonTranslators(context); - - // make sure the node factory has been initialised as least once prior to use - getNodeFactory(); - - const MTime oldCurTime = MAnimControl::currentTime(); - if(m_params.m_animTranslator) - { - // try to ensure that we have some sort of consistent output for each run by forcing the export to the first frame - MAnimControl::setCurrentTime(m_params.m_minFrame); - } - - if(!m_params.m_duplicateInstances) - { - m_impl->createInstancesPrim(); - } - - MObjectArray objects; - const MSelectionList& sl = m_params.m_nodes; - SdfPath defaultPrim; - - for(uint32_t i = 0, n = sl.length(); i < n; ++i) - { - MDagPath path; - if(sl.getDagPath(i, path)) - { - if(path.node().hasFn(MFn::kTransform)) - { - exportSceneHierarchy(path, defaultPrim); - } - else - if(path.node().hasFn(MFn::kShape)) - { - path.pop(); - exportSceneHierarchy(path, defaultPrim); - } + auto context = translators::TranslatorContext::create(nullptr); + translators::TranslatorManufacture::preparePythonTranslators(context); + + // make sure the node factory has been initialised as least once prior to use + getNodeFactory(); + + const MTime oldCurTime = MAnimControl::currentTime(); + if (m_params.m_animTranslator) { + // try to ensure that we have some sort of consistent output for each run by forcing the + // export to the first frame + MAnimControl::setCurrentTime(m_params.m_minFrame); } - else - { - MObject obj; - sl.getDependNode(i, obj); - objects.append(obj); + + if (!m_params.m_duplicateInstances) { + m_impl->createInstancesPrim(); + } + + MObjectArray objects; + const MSelectionList& sl = m_params.m_nodes; + SdfPath defaultPrim; + + for (uint32_t i = 0, n = sl.length(); i < n; ++i) { + MDagPath path; + if (sl.getDagPath(i, path)) { + if (path.node().hasFn(MFn::kTransform)) { + exportSceneHierarchy(path, defaultPrim); + } else if (path.node().hasFn(MFn::kShape)) { + path.pop(); + exportSceneHierarchy(path, defaultPrim); + } + } else { + MObject obj; + sl.getDependNode(i, obj); + objects.append(obj); + } } - } - if(m_params.m_animTranslator) - { - m_params.m_animTranslator->exportAnimation(m_params); - m_impl->setAnimationFrame(m_params.m_minFrame, m_params.m_maxFrame); + if (m_params.m_animTranslator) { + m_params.m_animTranslator->exportAnimation(m_params); + m_impl->setAnimationFrame(m_params.m_minFrame, m_params.m_maxFrame); - // return user to their original frame - MAnimControl::setCurrentTime(oldCurTime); - } + // return user to their original frame + MAnimControl::setCurrentTime(oldCurTime); + } - m_impl->processInstances(); - m_impl->doExport(m_params.m_fileName.asChar(), m_params.m_filterSample, defaultPrim); + m_impl->processInstances(); + m_impl->doExport(m_params.m_fileName.asChar(), m_params.m_filterSample, defaultPrim); } //---------------------------------------------------------------------------------------------------------------------- ExportCommand::ExportCommand() - : m_params() + : m_params() { } //---------------------------------------------------------------------------------------------------------------------- -ExportCommand::~ExportCommand() -{ -} +ExportCommand::~ExportCommand() { } //---------------------------------------------------------------------------------------------------------------------- MStatus ExportCommand::doIt(const MArgList& args) { - maya::utils::OptionsParser parser; - ExportTranslator::options().initParser(parser); - m_params.m_parser = &parser; - PluginTranslatorOptionsInstance pluginInstance(ExportTranslator::pluginContext()); - parser.setPluginOptionsContext(&pluginInstance); - - MStatus status; - MArgDatabase argData(syntax(), args, &status); - AL_MAYA_CHECK_ERROR(status, "ALUSDExport: failed to match arguments"); - AL_MAYA_COMMAND_HELP(argData, g_helpText); - - // fetch filename and ensure it's valid - if(!argData.isFlagSet("f", &status)) - { - MGlobal::displayError("ALUSDExport: \"file\" argument must be set"); - return MS::kFailure; - } - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("f", 0, m_params.m_fileName), "ALUSDExport: Unable to fetch \"file\" argument"); - if(argData.isFlagSet("sl", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("sl", 0, m_params.m_selected), "ALUSDExport: Unable to fetch \"selected\" argument"); - } - if(argData.isFlagSet("da", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("da", 0, m_params.m_dynamicAttributes), "ALUSDExport: Unable to fetch \"dynamic\" argument"); - } - if(argData.isFlagSet("di", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("di", 0, m_params.m_duplicateInstances), "ALUSDExport: Unable to fetch \"duplicateInstances\" argument"); - } - if(argData.isFlagSet("m", &status)) - { - bool option; - argData.getFlagArgument("m", 0, option); - m_params.setBool("Meshes", option); - } - if(argData.isFlagSet("uvs", &status)) - { - bool option; - argData.getFlagArgument("uvs", 0, option); - m_params.setBool("Mesh UVs", option); - } - if(argData.isFlagSet("uvo", &status)) - { - bool option; - argData.getFlagArgument("uvo", 0, option); - m_params.setBool("Mesh UV Only", option); - } - if(argData.isFlagSet("pr", &status)) - { - bool option; - argData.getFlagArgument("pr", 0, option); - m_params.setBool("Mesh Points as PRef", option); - } - - if(argData.isFlagSet("luv", &status)) - { - MGlobal::displayWarning("-luv flag is deprecated in AL_usdmaya_ExportCommand\n"); - } - if(argData.isFlagSet("mt", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("mt", 0, m_params.m_mergeTransforms), "ALUSDExport: Unable to fetch \"merge transforms\" argument"); - } - if(argData.isFlagSet("nc", &status)) - { - bool option; - argData.getFlagArgument("nc", 0, option); - m_params.setBool("Nurbs Curves", option); - } - - if(argData.isFlagSet("fr", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("fr", 0, m_params.m_minFrame), "ALUSDExport: Unable to fetch \"frame range\" argument"); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("fr", 1, m_params.m_maxFrame), "ALUSDExport: Unable to fetch \"frame range\" argument"); - m_params.m_animation = true; - } - else if(argData.isFlagSet("ani", &status)) - { - m_params.m_animation = true; - m_params.m_minFrame = MAnimControl::minTime().value(); - m_params.m_maxFrame = MAnimControl::maxTime().value(); - } - - if(argData.isFlagSet("ss", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("ss", 0, m_params.m_subSamples), "ALUSDExport: Unable to fetch \"sub samples\" argument"); - } - - if (argData.isFlagSet("fs", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("fs", 0, m_params.m_filterSample), "ALUSDExport: Unable to fetch \"filter sample\" argument"); - } - if(argData.isFlagSet("eac", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("eac", 0, m_params.m_extensiveAnimationCheck), "ALUSDExport: Unable to fetch \"extensive animation check\" argument"); - } - if(argData.isFlagSet("ws", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("ws", 0, m_params.m_exportInWorldSpace), "ALUSDExport: Unable to fetch \"world space\" argument"); - } - if(argData.isFlagSet("opt", &status)) - { - MString optionString; - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("opt", 0, optionString), "ALUSDExport: Unable to fetch \"options\" argument"); - parser.parse(optionString); - } - if(m_params.m_animation) - { - m_params.m_animTranslator = new AnimationTranslator; - } - - m_params.m_activateAllTranslators = true; - bool eat = argData.isFlagSet("eat", &status); - bool dat = argData.isFlagSet("dat", &status); - if(eat && dat) - { - MGlobal::displayError("ALUSDExport: cannot enable all translators, AND disable all translators, at the same time"); - } - else - if(dat) - { - m_params.m_activateAllTranslators = false; - } - - if(argData.isFlagSet("ept", &status)) - { - MString arg; - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("ept", 0, arg), "ALUSDExport: Unable to fetch \"enablePluginTranslators\" argument"); - MStringArray strings; - arg.split(',', strings); - for(uint32_t i = 0, n = strings.length(); i < n; ++i) - { - m_params.m_activePluginTranslators.emplace_back(strings[i].asChar()); + maya::utils::OptionsParser parser; + ExportTranslator::options().initParser(parser); + m_params.m_parser = &parser; + PluginTranslatorOptionsInstance pluginInstance(ExportTranslator::pluginContext()); + parser.setPluginOptionsContext(&pluginInstance); + + MStatus status; + MArgDatabase argData(syntax(), args, &status); + AL_MAYA_CHECK_ERROR(status, "ALUSDExport: failed to match arguments"); + AL_MAYA_COMMAND_HELP(argData, g_helpText); + + // fetch filename and ensure it's valid + if (!argData.isFlagSet("f", &status)) { + MGlobal::displayError("ALUSDExport: \"file\" argument must be set"); + return MS::kFailure; } - } - - if(argData.isFlagSet("dpt", &status)) - { - MString arg; - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("dpt", 0, arg), "ALUSDExport: Unable to fetch \"disablePluginTranslators\" argument"); - MStringArray strings; - arg.split(',', strings); - for(uint32_t i = 0, n = strings.length(); i < n; ++i) - { - m_params.m_inactivePluginTranslators.emplace_back(strings[i].asChar()); + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("f", 0, m_params.m_fileName), + "ALUSDExport: Unable to fetch \"file\" argument"); + if (argData.isFlagSet("sl", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("sl", 0, m_params.m_selected), + "ALUSDExport: Unable to fetch \"selected\" argument"); + } + if (argData.isFlagSet("da", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("da", 0, m_params.m_dynamicAttributes), + "ALUSDExport: Unable to fetch \"dynamic\" argument"); + } + if (argData.isFlagSet("di", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("di", 0, m_params.m_duplicateInstances), + "ALUSDExport: Unable to fetch \"duplicateInstances\" argument"); + } + if (argData.isFlagSet("m", &status)) { + bool option; + argData.getFlagArgument("m", 0, option); + m_params.setBool("Meshes", option); + } + if (argData.isFlagSet("uvs", &status)) { + bool option; + argData.getFlagArgument("uvs", 0, option); + m_params.setBool("Mesh UVs", option); + } + if (argData.isFlagSet("uvo", &status)) { + bool option; + argData.getFlagArgument("uvo", 0, option); + m_params.setBool("Mesh UV Only", option); + } + if (argData.isFlagSet("pr", &status)) { + bool option; + argData.getFlagArgument("pr", 0, option); + m_params.setBool("Mesh Points as PRef", option); + } + + if (argData.isFlagSet("luv", &status)) { + MGlobal::displayWarning("-luv flag is deprecated in AL_usdmaya_ExportCommand\n"); + } + if (argData.isFlagSet("mt", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("mt", 0, m_params.m_mergeTransforms), + "ALUSDExport: Unable to fetch \"merge transforms\" argument"); + } + if (argData.isFlagSet("nc", &status)) { + bool option; + argData.getFlagArgument("nc", 0, option); + m_params.setBool("Nurbs Curves", option); } - } - return redoIt(); + if (argData.isFlagSet("fr", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("fr", 0, m_params.m_minFrame), + "ALUSDExport: Unable to fetch \"frame range\" argument"); + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("fr", 1, m_params.m_maxFrame), + "ALUSDExport: Unable to fetch \"frame range\" argument"); + m_params.m_animation = true; + } else if (argData.isFlagSet("ani", &status)) { + m_params.m_animation = true; + m_params.m_minFrame = MAnimControl::minTime().value(); + m_params.m_maxFrame = MAnimControl::maxTime().value(); + } + + if (argData.isFlagSet("ss", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("ss", 0, m_params.m_subSamples), + "ALUSDExport: Unable to fetch \"sub samples\" argument"); + } + + if (argData.isFlagSet("fs", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("fs", 0, m_params.m_filterSample), + "ALUSDExport: Unable to fetch \"filter sample\" argument"); + } + if (argData.isFlagSet("eac", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("eac", 0, m_params.m_extensiveAnimationCheck), + "ALUSDExport: Unable to fetch \"extensive animation check\" argument"); + } + if (argData.isFlagSet("ws", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("ws", 0, m_params.m_exportInWorldSpace), + "ALUSDExport: Unable to fetch \"world space\" argument"); + } + if (argData.isFlagSet("opt", &status)) { + MString optionString; + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("opt", 0, optionString), + "ALUSDExport: Unable to fetch \"options\" argument"); + parser.parse(optionString); + } + if (m_params.m_animation) { + m_params.m_animTranslator = new AnimationTranslator; + } + + m_params.m_activateAllTranslators = true; + bool eat = argData.isFlagSet("eat", &status); + bool dat = argData.isFlagSet("dat", &status); + if (eat && dat) { + MGlobal::displayError("ALUSDExport: cannot enable all translators, AND disable all " + "translators, at the same time"); + } else if (dat) { + m_params.m_activateAllTranslators = false; + } + + if (argData.isFlagSet("ept", &status)) { + MString arg; + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("ept", 0, arg), + "ALUSDExport: Unable to fetch \"enablePluginTranslators\" argument"); + MStringArray strings; + arg.split(',', strings); + for (uint32_t i = 0, n = strings.length(); i < n; ++i) { + m_params.m_activePluginTranslators.emplace_back(strings[i].asChar()); + } + } + + if (argData.isFlagSet("dpt", &status)) { + MString arg; + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("dpt", 0, arg), + "ALUSDExport: Unable to fetch \"disablePluginTranslators\" argument"); + MStringArray strings; + arg.split(',', strings); + for (uint32_t i = 0, n = strings.length(); i < n; ++i) { + m_params.m_inactivePluginTranslators.emplace_back(strings[i].asChar()); + } + } + + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- MStatus ExportCommand::redoIt() { - static const std::unordered_set ignoredNodes - { - "persp", - "front", - "top", - "side" - }; - - if(m_params.m_selected) - { - MGlobal::getActiveSelectionList(m_params.m_nodes); - } - else - { - MDagPath path; - MItDag it(MItDag::kDepthFirst, MFn::kTransform); - while(!it.isDone()) - { - it.getPath(path); - const MString name = path.partialPathName(); - const std::string s(name.asChar(), name.length()); - if(ignoredNodes.find(s) == ignoredNodes.end()) - { - m_params.m_nodes.add(path); - } - it.prune(); - it.next(); + static const std::unordered_set ignoredNodes { "persp", "front", "top", "side" }; + + if (m_params.m_selected) { + MGlobal::getActiveSelectionList(m_params.m_nodes); + } else { + MDagPath path; + MItDag it(MItDag::kDepthFirst, MFn::kTransform); + while (!it.isDone()) { + it.getPath(path); + const MString name = path.partialPathName(); + const std::string s(name.asChar(), name.length()); + if (ignoredNodes.find(s) == ignoredNodes.end()) { + m_params.m_nodes.add(path); + } + it.prune(); + it.next(); + } } - } - Export exporter(m_params); - delete m_params.m_animTranslator; + Export exporter(m_params); + delete m_params.m_animTranslator; - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -MStatus ExportCommand::undoIt() -{ - return MS::kSuccess; -} +MStatus ExportCommand::undoIt() { return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MSyntax ExportCommand::createSyntax() { - const char* const errorString = "ALUSDExport: failed to create syntax"; - - MStatus status; - MSyntax syntax; - status = syntax.addFlag("-f" , "-file", MSyntax::kString); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-sl" , "-selected", MSyntax::kBoolean); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-da" , "-dynamic", MSyntax::kBoolean); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-m" , "-meshes", MSyntax::kBoolean); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-uvs" , "-meshUVS", MSyntax::kBoolean); // If this is on, we export UV data beside normal data. - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-uvo" , "-meshUVOnly", MSyntax::kBoolean); // when this is on, only overs contains UV are exported. - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-pr" , "-meshPointsPref", MSyntax::kBoolean); // when this is on, only overs contains UV are exported. - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-luv" , "-leftHandedUV", MSyntax::kBoolean); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-nc" , "-nurbsCurves", MSyntax::kBoolean); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-di" , "-duplicateInstances", MSyntax::kBoolean); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-mt", "-mergeTransforms", MSyntax::kBoolean); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-ani", "-animation", MSyntax::kNoArg); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-fr", "-frameRange", MSyntax::kDouble, MSyntax::kDouble); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-fs", "-filterSample", MSyntax::kBoolean); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-eac", "-extensiveAnimationCheck", MSyntax::kBoolean); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-ss", "-subSamples", MSyntax::kUnsigned); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-ws", "-worldSpace", MSyntax::kBoolean); - AL_MAYA_CHECK_ERROR2(status, errorString); - status = syntax.addFlag("-opt", "-options", MSyntax::kString); - AL_MAYA_CHECK_ERROR2(status, errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-eat", "-enableAllTranslators", MSyntax::kNoArg), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-dat", "-disableAllTranslators", MSyntax::kNoArg), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-ept", "-enablePluginTranslators", MSyntax::kString), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-dpt", "-disablePluginTranslators", MSyntax::kString), errorString); - syntax.enableQuery(false); - syntax.enableEdit(false); - - return syntax; + const char* const errorString = "ALUSDExport: failed to create syntax"; + + MStatus status; + MSyntax syntax; + status = syntax.addFlag("-f", "-file", MSyntax::kString); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-sl", "-selected", MSyntax::kBoolean); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-da", "-dynamic", MSyntax::kBoolean); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-m", "-meshes", MSyntax::kBoolean); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag( + "-uvs", + "-meshUVS", + MSyntax::kBoolean); // If this is on, we export UV data beside normal data. + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag( + "-uvo", + "-meshUVOnly", + MSyntax::kBoolean); // when this is on, only overs contains UV are exported. + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag( + "-pr", + "-meshPointsPref", + MSyntax::kBoolean); // when this is on, only overs contains UV are exported. + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-luv", "-leftHandedUV", MSyntax::kBoolean); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-nc", "-nurbsCurves", MSyntax::kBoolean); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-di", "-duplicateInstances", MSyntax::kBoolean); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-mt", "-mergeTransforms", MSyntax::kBoolean); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-ani", "-animation", MSyntax::kNoArg); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-fr", "-frameRange", MSyntax::kDouble, MSyntax::kDouble); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-fs", "-filterSample", MSyntax::kBoolean); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-eac", "-extensiveAnimationCheck", MSyntax::kBoolean); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-ss", "-subSamples", MSyntax::kUnsigned); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-ws", "-worldSpace", MSyntax::kBoolean); + AL_MAYA_CHECK_ERROR2(status, errorString); + status = syntax.addFlag("-opt", "-options", MSyntax::kString); + AL_MAYA_CHECK_ERROR2(status, errorString); + AL_MAYA_CHECK_ERROR2( + syntax.addFlag("-eat", "-enableAllTranslators", MSyntax::kNoArg), errorString); + AL_MAYA_CHECK_ERROR2( + syntax.addFlag("-dat", "-disableAllTranslators", MSyntax::kNoArg), errorString); + AL_MAYA_CHECK_ERROR2( + syntax.addFlag("-ept", "-enablePluginTranslators", MSyntax::kString), errorString); + AL_MAYA_CHECK_ERROR2( + syntax.addFlag("-dpt", "-disablePluginTranslators", MSyntax::kString), errorString); + syntax.enableQuery(false); + syntax.enableEdit(false); + + return syntax; } //---------------------------------------------------------------------------------------------------------------------- @@ -1305,7 +1203,7 @@ ExportCommand Overview: )"; //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Export.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Export.h index a30657094c..27b39acfdd 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Export.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Export.h @@ -14,18 +14,17 @@ // limitations under the License. // #pragma once +#include "AL/maya/utils/Api.h" +#include "AL/maya/utils/MayaHelperMacros.h" #include "AL/usdmaya/fileio/ExportParams.h" #include "AL/usdmaya/fileio/translators/TranslatorBase.h" - -#include +#include "AL/usdmaya/utils/ForwardDeclares.h" #include -#include "AL/usdmaya/utils/ForwardDeclares.h" -#include "AL/maya/utils/Api.h" -#include "AL/maya/utils/MayaHelperMacros.h" -PXR_NAMESPACE_USING_DIRECTIVE +#include +PXR_NAMESPACE_USING_DIRECTIVE namespace AL { namespace usdmaya { @@ -34,87 +33,92 @@ namespace fileio { //---------------------------------------------------------------------------------------------------------------------- /// \brief A class that wraps up the entire export process /// -/// This command will export the maya hierarchy at the specified prim path or selection, into the USD format. During -/// traversal of the maya DAG hierarchy, the USD schema type is exported on the prim if it can be determined from the -/// maya node type, if the schema type couldn't be determined a Xform type prim is exported to represent it. If a known -/// type is found, then it is exported via the the corresponding export translator which is configured based -/// on the input parameters of the command. +/// This command will export the maya hierarchy at the specified prim path or selection, into the +/// USD format. During traversal of the maya DAG hierarchy, the USD schema type is exported on the +/// prim if it can be determined from the maya node type, if the schema type couldn't be determined +/// a Xform type prim is exported to represent it. If a known type is found, then it is exported via +/// the the corresponding export translator which is configured based on the input parameters of the +/// command. /// -/// Each exporter has an explicit list of plugs that will get exported if certain input parameters are passed in then -/// they can be exported over a frame range +/// Each exporter has an explicit list of plugs that will get exported if certain input parameters +/// are passed in then they can be exported over a frame range /// -/// Instances are currently not fully supported. If instances are encountered and the duplicateInstances flag is ON, -/// then the hierarchy is deduplicated. If duplicateInstances is off then only the first instance found is exported. -/// \ingroup fileio +/// Instances are currently not fully supported. If instances are encountered and the +/// duplicateInstances flag is ON, then the hierarchy is deduplicated. If duplicateInstances is off +/// then only the first instance found is exported. \ingroup fileio //---------------------------------------------------------------------------------------------------------------------- class Export { public: + /// \brief The constructor performs the export from Maya to USD based on the input parameters. + /// \param params the export parameters that describe what will be exported from Maya + Export(const ExporterParams& params); - /// \brief The constructor performs the export from Maya to USD based on the input parameters. - /// \param params the export parameters that describe what will be exported from Maya - Export(const ExporterParams& params); - - /// \brief dtor - ~Export(); + /// \brief dtor + ~Export(); private: - - enum ReferenceType - { - kNoReference, - kShapeReference, - kTransformReference, - }; - - void exportSceneHierarchy(MDagPath path, SdfPath& defaultPrim); - void exportShapesCommonProc(MDagPath shapePath, MFnTransform& fnTransform, SdfPath& usdPath, ReferenceType refType); - void exportShapesOnlyUVProc(MDagPath shapePath, MFnTransform& fnTransform, SdfPath& usdPath); - UsdPrim exportMeshUV(MDagPath path, const SdfPath& usdPath); - UsdPrim exportAssembly(MDagPath path, const SdfPath& usdPath); - UsdPrim exportPluginLocatorNode(MDagPath path, const SdfPath& usdPath); - UsdPrim exportPluginShape(MDagPath path, const SdfPath& usdPath); - void exportIkChain(MDagPath effectorPath, const SdfPath& usdPath); - void exportGeometryConstraint(MDagPath effectorPath, const SdfPath& usdPath); - void copyTransformParams(UsdPrim prim, MFnTransform& fnTransform); - SdfPath determineUsdPath(MDagPath path, const SdfPath& usdPath, ReferenceType refType); - void addReferences(MDagPath shapePath, MFnTransform& fnTransform, SdfPath& usdPath, - const SdfPath& instancePath, ReferenceType refType); - inline bool isPrimDefined(SdfPath &usdPath); - struct Impl; - void doExport(); - const ExporterParams& m_params; - Impl* m_impl; - translators::TranslatorManufacture m_translatorManufacture; - + enum ReferenceType + { + kNoReference, + kShapeReference, + kTransformReference, + }; + + void exportSceneHierarchy(MDagPath path, SdfPath& defaultPrim); + void exportShapesCommonProc( + MDagPath shapePath, + MFnTransform& fnTransform, + SdfPath& usdPath, + ReferenceType refType); + void exportShapesOnlyUVProc(MDagPath shapePath, MFnTransform& fnTransform, SdfPath& usdPath); + UsdPrim exportMeshUV(MDagPath path, const SdfPath& usdPath); + UsdPrim exportAssembly(MDagPath path, const SdfPath& usdPath); + UsdPrim exportPluginLocatorNode(MDagPath path, const SdfPath& usdPath); + UsdPrim exportPluginShape(MDagPath path, const SdfPath& usdPath); + void exportIkChain(MDagPath effectorPath, const SdfPath& usdPath); + void exportGeometryConstraint(MDagPath effectorPath, const SdfPath& usdPath); + void copyTransformParams(UsdPrim prim, MFnTransform& fnTransform); + SdfPath determineUsdPath(MDagPath path, const SdfPath& usdPath, ReferenceType refType); + void addReferences( + MDagPath shapePath, + MFnTransform& fnTransform, + SdfPath& usdPath, + const SdfPath& instancePath, + ReferenceType refType); + inline bool isPrimDefined(SdfPath& usdPath); + struct Impl; + void doExport(); + const ExporterParams& m_params; + Impl* m_impl; + translators::TranslatorManufacture m_translatorManufacture; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief A thin MEL command layer that just wraps the AL::usdmaya::fileio::Export process. /// \ingroup fileio //---------------------------------------------------------------------------------------------------------------------- -class ExportCommand - : public MPxCommand +class ExportCommand : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); - /// \brief ctor - ExportCommand(); + /// \brief ctor + ExportCommand(); - /// \brief dtor - ~ExportCommand(); + /// \brief dtor + ~ExportCommand(); private: - MStatus doIt(const MArgList& args); - MStatus redoIt(); - MStatus undoIt(); - bool isUndoable() const { return true; }; - ExporterParams m_params; + MStatus doIt(const MArgList& args); + MStatus redoIt(); + MStatus undoIt(); + bool isUndoable() const { return true; }; + ExporterParams m_params; }; //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportParams.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportParams.h index 70b358f19c..b8a0ce4846 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportParams.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportParams.h @@ -14,14 +14,16 @@ // limitations under the License. // #pragma once +#include "AL/maya/utils/FileTranslatorOptions.h" + #include -#include +#include #include #include -#include "AL/maya/utils/FileTranslatorOptions.h" -#include + +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -30,88 +32,98 @@ namespace usdmaya { namespace fileio { //---------------------------------------------------------------------------------------------------------------------- -/// \brief parameters for the exporter. These parameters are constructed by any command or file translator that wishes -/// to export data from maya, which are then passed to the AL::usdmaya::fileio::Export class to perform the -/// actual export work. +/// \brief parameters for the exporter. These parameters are constructed by any command or file +/// translator that wishes +/// to export data from maya, which are then passed to the AL::usdmaya::fileio::Export class +/// to perform the actual export work. /// \ingroup fileio //---------------------------------------------------------------------------------------------------------------------- struct ExporterParams { - maya::utils::OptionsParser* m_parser = 0; - MSelectionList m_nodes; ///< the selected node to be exported - MString m_fileName; ///< the filename of the file we will be exporting - double m_minFrame=0.0; ///< the start frame for the animation export - double m_maxFrame=1.0; ///< the end frame of the animation export - uint32_t m_subSamples = 1; ///< the number of subsample steps to export - bool m_selected = false; ///< are we exporting selected objects (true) or all objects (false) - bool m_dynamicAttributes = true; ///< if true export any dynamic attributes found on the nodes we are exporting - bool m_duplicateInstances = true; ///< if true, instances will be exported as duplicates. As of 23/01/17, nothing will be exported if set to false. - bool m_mergeTransforms = true; ///< if true, shapes will be merged into their parent transforms in the exported data. If false, the transform and shape will be exported seperately - bool m_animation = false; ///< if true, animation will be exported. - bool m_useTimelineRange = false; ///< if true, then the export uses Maya's timeline range. - bool m_filterSample = false; ///< if true, duplicate sample of attribute will be filtered out - bool m_exportInWorldSpace = false; ///< if true, transform hierarchies will be flattened to a single WS transform PRIM (and no parents will be written out) - AnimationTranslator* m_animTranslator = 0; ///< the animation translator to help exporting the animation data - bool m_extensiveAnimationCheck = true; ///< if true, extensive animation check will be performed on transform nodes. - int m_exportAtWhichTime = 0; ///< controls where the data will be written to: 0 = default time, 1 = earliest time, 2 = current time - UsdTimeCode m_timeCode = UsdTimeCode::Default(); + maya::utils::OptionsParser* m_parser = 0; + MSelectionList m_nodes; ///< the selected node to be exported + MString m_fileName; ///< the filename of the file we will be exporting + double m_minFrame = 0.0; ///< the start frame for the animation export + double m_maxFrame = 1.0; ///< the end frame of the animation export + uint32_t m_subSamples = 1; ///< the number of subsample steps to export + bool m_selected = false; ///< are we exporting selected objects (true) or all objects (false) + bool m_dynamicAttributes + = true; ///< if true export any dynamic attributes found on the nodes we are exporting + bool m_duplicateInstances = true; ///< if true, instances will be exported as duplicates. As of + ///< 23/01/17, nothing will be exported if set to false. + bool m_mergeTransforms + = true; ///< if true, shapes will be merged into their parent transforms in the exported + ///< data. If false, the transform and shape will be exported seperately + bool m_animation = false; ///< if true, animation will be exported. + bool m_useTimelineRange = false; ///< if true, then the export uses Maya's timeline range. + bool m_filterSample = false; ///< if true, duplicate sample of attribute will be filtered out + bool m_exportInWorldSpace + = false; ///< if true, transform hierarchies will be flattened to a single WS transform PRIM + ///< (and no parents will be written out) + AnimationTranslator* m_animTranslator + = 0; ///< the animation translator to help exporting the animation data + bool m_extensiveAnimationCheck + = true; ///< if true, extensive animation check will be performed on transform nodes. + int m_exportAtWhichTime = 0; ///< controls where the data will be written to: 0 = default time, + ///< 1 = earliest time, 2 = current time + UsdTimeCode m_timeCode = UsdTimeCode::Default(); - bool m_activateAllTranslators = true; - TfTokenVector m_activePluginTranslators; - TfTokenVector m_inactivePluginTranslators; + bool m_activateAllTranslators = true; + TfTokenVector m_activePluginTranslators; + TfTokenVector m_inactivePluginTranslators; - /// \brief Given the text name of an option, returns the boolean value for that option. - /// \param str the name of the option - /// \return the option value - bool getBool(const char* const str) const - { - if(m_parser) - return m_parser->getBool(str); - return false; - } + /// \brief Given the text name of an option, returns the boolean value for that option. + /// \param str the name of the option + /// \return the option value + bool getBool(const char* const str) const + { + if (m_parser) + return m_parser->getBool(str); + return false; + } - /// \brief Given the text name of an option, returns the integer value for that option. - /// \param str the name of the option - /// \return the option value - int getInt(const char* const str) const - { - if(m_parser) - return m_parser->getInt(str); - return 0; - } + /// \brief Given the text name of an option, returns the integer value for that option. + /// \param str the name of the option + /// \return the option value + int getInt(const char* const str) const + { + if (m_parser) + return m_parser->getInt(str); + return 0; + } - /// \brief Given the text name of an option, returns the floating point value for that option. - /// \param str the name of the option - /// \return the option value - float getFloat(const char* const str) const - { - if(m_parser) - return m_parser->getFloat(str); - return 0.0f; - } + /// \brief Given the text name of an option, returns the floating point value for that option. + /// \param str the name of the option + /// \return the option value + float getFloat(const char* const str) const + { + if (m_parser) + return m_parser->getFloat(str); + return 0.0f; + } - /// \brief Given the text name of an option, returns the string value for that option. - /// \param str the name of the option - /// \return the option value - MString getString(const char* const str) const - { - if(m_parser) - return m_parser->getString(str); - return MString(); - } + /// \brief Given the text name of an option, returns the string value for that option. + /// \param str the name of the option + /// \return the option value + MString getString(const char* const str) const + { + if (m_parser) + return m_parser->getString(str); + return MString(); + } - /// \brief Sets the value of the specified option, to the specified value - /// \param str the name of the option to set - /// \param value the option value - void setBool(const char* const str, bool value) - { - if(m_parser) - m_parser->setBool(str, value); - } + /// \brief Sets the value of the specified option, to the specified value + /// \param str the name of the option to set + /// \param value the option value + void setBool(const char* const str, bool value) + { + if (m_parser) + m_parser->setBool(str, value); + } }; //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportTranslator.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportTranslator.cpp index a30e9f8e89..2a73d8a12c 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportTranslator.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportTranslator.cpp @@ -13,9 +13,10 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/fileio/Export.h" #include "AL/usdmaya/fileio/ExportTranslator.h" + #include "AL/usdmaya/fileio/AnimationTranslator.h" +#include "AL/usdmaya/fileio/Export.h" #include #include @@ -29,137 +30,101 @@ namespace AL { namespace usdmaya { namespace fileio { -PluginTranslatorOptionsContext ExportTranslator::m_pluginContext; -PluginTranslatorOptions* ExportTranslator::m_compatPluginOptions; +PluginTranslatorOptionsContext ExportTranslator::m_pluginContext; +PluginTranslatorOptions* ExportTranslator::m_compatPluginOptions; PluginTranslatorOptionsInstance* ExportTranslator::m_pluginInstance; //---------------------------------------------------------------------------------------------------------------------- -const char* const ExportTranslator::compactionLevels[] = { - "None", - "Basic", - "Medium", - "Extensive", - 0 -}; +const char* const ExportTranslator::compactionLevels[] + = { "None", "Basic", "Medium", "Extensive", 0 }; //---------------------------------------------------------------------------------------------------------------------- -const char* const ExportTranslator::timelineLevel[] = { - "Default Time", - "Earliest Time", - "Current Time", - "Min Timeline Range", - 0 -}; - +const char* const ExportTranslator::timelineLevel[] + = { "Default Time", "Earliest Time", "Current Time", "Min Timeline Range", 0 }; //---------------------------------------------------------------------------------------------------------------------- -MStatus ExportTranslator::writer(const MFileObject& file, const AL::maya::utils::OptionsParser& options, FileAccessMode mode) +MStatus ExportTranslator::writer( + const MFileObject& file, + const AL::maya::utils::OptionsParser& options, + FileAccessMode mode) { - static const std::unordered_set ignoredNodes - { - "persp", - "front", - "top", - "side" - }; - - ExporterParams params; - params.m_dynamicAttributes = options.getBool(kDynamicAttributes); - params.m_duplicateInstances = options.getBool(kDuplicateInstances); - params.m_mergeTransforms = options.getBool(kMergeTransforms); - params.m_fileName = file.fullName(); - params.m_selected = mode == MPxFileTranslator::kExportActiveAccessMode; - params.m_animation = options.getBool(kAnimation); - params.m_exportAtWhichTime = options.getBool(kExportAtWhichTime); - params.m_exportInWorldSpace = options.getBool(kExportInWorldSpace); - params.m_subSamples = options.getInt(kSubSamples); - params.m_parser = (maya::utils::OptionsParser*)&options; - params.m_activateAllTranslators = options.getBool(kActivateAllTranslators); - MStringArray strings; - options.getString(kActiveTranslatorList).split(',', strings); - for(uint32_t i = 0, n = strings.length(); i < n; ++i) - { - params.m_activePluginTranslators.emplace_back(strings[i].asChar()); - } - strings.setLength(0); - options.getString(kInactiveTranslatorList).split(',', strings); - for(uint32_t i = 0, n = strings.length(); i < n; ++i) - { - params.m_inactivePluginTranslators.emplace_back(strings[i].asChar()); - } - - if(m_pluginInstance) - { - m_pluginInstance->toOptionVars("ExportTranslator"); - } - - if(params.m_animation) - { - if(options.getBool(kUseTimelineRange)) - { - params.m_minFrame = MAnimControl::minTime().value(); - params.m_maxFrame = MAnimControl::maxTime().value(); + static const std::unordered_set ignoredNodes { "persp", "front", "top", "side" }; + + ExporterParams params; + params.m_dynamicAttributes = options.getBool(kDynamicAttributes); + params.m_duplicateInstances = options.getBool(kDuplicateInstances); + params.m_mergeTransforms = options.getBool(kMergeTransforms); + params.m_fileName = file.fullName(); + params.m_selected = mode == MPxFileTranslator::kExportActiveAccessMode; + params.m_animation = options.getBool(kAnimation); + params.m_exportAtWhichTime = options.getBool(kExportAtWhichTime); + params.m_exportInWorldSpace = options.getBool(kExportInWorldSpace); + params.m_subSamples = options.getInt(kSubSamples); + params.m_parser = (maya::utils::OptionsParser*)&options; + params.m_activateAllTranslators = options.getBool(kActivateAllTranslators); + MStringArray strings; + options.getString(kActiveTranslatorList).split(',', strings); + for (uint32_t i = 0, n = strings.length(); i < n; ++i) { + params.m_activePluginTranslators.emplace_back(strings[i].asChar()); } - else - { - params.m_minFrame = options.getFloat(kFrameMin); - params.m_maxFrame = options.getFloat(kFrameMax); + strings.setLength(0); + options.getString(kInactiveTranslatorList).split(',', strings); + for (uint32_t i = 0, n = strings.length(); i < n; ++i) { + params.m_inactivePluginTranslators.emplace_back(strings[i].asChar()); + } + + if (m_pluginInstance) { + m_pluginInstance->toOptionVars("ExportTranslator"); + } + + if (params.m_animation) { + if (options.getBool(kUseTimelineRange)) { + params.m_minFrame = MAnimControl::minTime().value(); + params.m_maxFrame = MAnimControl::maxTime().value(); + } else { + params.m_minFrame = options.getFloat(kFrameMin); + params.m_maxFrame = options.getFloat(kFrameMax); + } + params.m_animTranslator = new AnimationTranslator; } - params.m_animTranslator = new AnimationTranslator; - } - params.m_filterSample = options.getBool(kFilterSample); - if(params.m_selected) - { - MGlobal::getActiveSelectionList(params.m_nodes); - } - else - { - MDagPath path; - MItDag it(MItDag::kDepthFirst, MFn::kTransform); - while(!it.isDone()) - { - it.getPath(path); - const MString name = path.partialPathName(); - const std::string s(name.asChar(), name.length()); - if(ignoredNodes.find(s) == ignoredNodes.end()) - { - params.m_nodes.add(path); - } - it.prune(); - it.next(); + params.m_filterSample = options.getBool(kFilterSample); + if (params.m_selected) { + MGlobal::getActiveSelectionList(params.m_nodes); + } else { + MDagPath path; + MItDag it(MItDag::kDepthFirst, MFn::kTransform); + while (!it.isDone()) { + it.getPath(path); + const MString name = path.partialPathName(); + const std::string s(name.asChar(), name.length()); + if (ignoredNodes.find(s) == ignoredNodes.end()) { + params.m_nodes.add(path); + } + it.prune(); + it.next(); + } } - } - - switch(params.m_exportAtWhichTime) - { - case 0: - params.m_timeCode = UsdTimeCode::Default(); - break; - case 1: - params.m_timeCode = UsdTimeCode::EarliestTime(); - break; - case 2: - params.m_timeCode = UsdTimeCode(MAnimControl::currentTime().value()); - break; - case 3: - params.m_timeCode = UsdTimeCode(params.m_minFrame); - break; - } - - Export exporter(params); - - if(params.m_animTranslator) - { - delete params.m_animTranslator; - } - - // import your data - - return MS::kSuccess; // done! + + switch (params.m_exportAtWhichTime) { + case 0: params.m_timeCode = UsdTimeCode::Default(); break; + case 1: params.m_timeCode = UsdTimeCode::EarliestTime(); break; + case 2: params.m_timeCode = UsdTimeCode(MAnimControl::currentTime().value()); break; + case 3: params.m_timeCode = UsdTimeCode(params.m_minFrame); break; + } + + Export exporter(params); + + if (params.m_animTranslator) { + delete params.m_animTranslator; + } + + // import your data + + return MS::kSuccess; // done! } //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportTranslator.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportTranslator.h index d501c8cdfc..91f9ea499e 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportTranslator.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ExportTranslator.h @@ -24,117 +24,156 @@ namespace AL { namespace usdmaya { namespace fileio { -using AL::maya::utils::PluginTranslatorOptionsContext; -using AL::maya::utils::PluginTranslatorOptionsInstance; using AL::maya::utils::PluginTranslatorOptions; +using AL::maya::utils::PluginTranslatorOptionsContext; using AL::maya::utils::PluginTranslatorOptionsContextManager; +using AL::maya::utils::PluginTranslatorOptionsInstance; //---------------------------------------------------------------------------------------------------------------------- -/// \brief A Maya export plugin that writes out USD files from Maya (this is largely optimised for the needs of the +/// \brief A Maya export plugin that writes out USD files from Maya (this is largely optimised for +/// the needs of the /// AnimalLogic pipeline). /// \ingroup fileio //---------------------------------------------------------------------------------------------------------------------- -AL_MAYA_TRANSLATOR_BEGIN(ExportTranslator, "AL usdmaya export", false, true, "usda", "*.usdc;*.usda;*.usd;*.usdt"); - - /// \fn void* creator() - /// \brief creates an instance of the file translator - /// \return a new file translator instance - - /// \var const char* const kTranslatorName - /// \brief the name of the file translator - - /// \var const char* const kClassName - /// \brief the name of the C++ file translator class - - // specify the option names (These will uniquely identify the exporter options) - static constexpr const char* const kDynamicAttributes = "Dynamic Attributes"; ///< export dynamic attributes option name - static constexpr const char* const kDuplicateInstances = "Duplicate Instances"; ///< export instances option name - static constexpr const char* const kMergeTransforms = "Merge Transforms"; ///< export by merging transforms and shapes option name - static constexpr const char* const kAnimation = "Animation"; ///< export animation data option name - static constexpr const char* const kUseTimelineRange = "Use Timeline Range"; ///< export using the timeline range option name - static constexpr const char* const kFrameMin = "Frame Min"; ///< specify min time frame option name - static constexpr const char* const kFrameMax = "Frame Max"; ///< specify max time frame option name - static constexpr const char* const kSubSamples = "Sub Samples"; ///< specify the number of sub samples to export - static constexpr const char* const kFilterSample = "Filter Sample"; ///< export filter sample option name - static constexpr const char* const kExportAtWhichTime = "Export At Which Time"; ///< which time code should be used for default values? - static constexpr const char* const kExportInWorldSpace = "Export In World Space"; ///< should selected transforms be output in world space? - static constexpr const char* const kActivateAllTranslators = "Activate all Plugin Translators"; ///< if true, all translator plugins will be enabled by default - static constexpr const char* const kActiveTranslatorList = "Active Translator List"; ///< A comma seperated list of translator plugins that should be activated for export - static constexpr const char* const kInactiveTranslatorList = "Inactive Translator List"; ///< A comma seperated list of translator plugins that should be inactive for export - - AL_USDMAYA_PUBLIC - static const char* const compactionLevels[]; - - AL_USDMAYA_PUBLIC - static const char* const timelineLevel[]; - - /// \brief provide a method to specify the export options - /// \param options a set of options that are constructed and later used for option parsing - /// \return MS::kSuccess if ok - static MStatus specifyOptions(AL::maya::utils::FileTranslatorOptions& options) - { +AL_MAYA_TRANSLATOR_BEGIN( + ExportTranslator, + "AL usdmaya export", + false, + true, + "usda", + "*.usdc;*.usda;*.usd;*.usdt"); + +/// \fn void* creator() +/// \brief creates an instance of the file translator +/// \return a new file translator instance + +/// \var const char* const kTranslatorName +/// \brief the name of the file translator + +/// \var const char* const kClassName +/// \brief the name of the C++ file translator class + +// specify the option names (These will uniquely identify the exporter options) +static constexpr const char* const kDynamicAttributes + = "Dynamic Attributes"; ///< export dynamic attributes option name +static constexpr const char* const kDuplicateInstances + = "Duplicate Instances"; ///< export instances option name +static constexpr const char* const kMergeTransforms + = "Merge Transforms"; ///< export by merging transforms and shapes option name +static constexpr const char* const kAnimation = "Animation"; ///< export animation data option name +static constexpr const char* const kUseTimelineRange + = "Use Timeline Range"; ///< export using the timeline range option name +static constexpr const char* const kFrameMin = "Frame Min"; ///< specify min time frame option name +static constexpr const char* const kFrameMax = "Frame Max"; ///< specify max time frame option name +static constexpr const char* const kSubSamples + = "Sub Samples"; ///< specify the number of sub samples to export +static constexpr const char* const kFilterSample + = "Filter Sample"; ///< export filter sample option name +static constexpr const char* const kExportAtWhichTime + = "Export At Which Time"; ///< which time code should be used for default values? +static constexpr const char* const kExportInWorldSpace + = "Export In World Space"; ///< should selected transforms be output in world space? +static constexpr const char* const kActivateAllTranslators + = "Activate all Plugin Translators"; ///< if true, all translator plugins will be enabled by + ///< default +static constexpr const char* const kActiveTranslatorList + = "Active Translator List"; ///< A comma seperated list of translator plugins that should be + ///< activated for export +static constexpr const char* const kInactiveTranslatorList + = "Inactive Translator List"; ///< A comma seperated list of translator plugins that should be + ///< inactive for export + +AL_USDMAYA_PUBLIC +static const char* const compactionLevels[]; + +AL_USDMAYA_PUBLIC +static const char* const timelineLevel[]; + +/// \brief provide a method to specify the export options +/// \param options a set of options that are constructed and later used for option parsing +/// \return MS::kSuccess if ok +static MStatus specifyOptions(AL::maya::utils::FileTranslatorOptions& options) +{ ExporterParams defaultValues; - if(!options.addFrame("AL USD Exporter Options")) return MS::kFailure; - if(!options.addBool(kDynamicAttributes, defaultValues.m_dynamicAttributes)) return MS::kFailure; - if(!options.addBool(kDuplicateInstances, defaultValues.m_duplicateInstances)) return MS::kFailure; - if(!options.addBool(kMergeTransforms, defaultValues.m_mergeTransforms)) return MS::kFailure; - if(!options.addBool(kAnimation, defaultValues.m_animation)) return MS::kFailure; - if(!options.addBool(kUseTimelineRange, defaultValues.m_useTimelineRange)) return MS::kFailure; - if(!options.addFloat(kFrameMin, defaultValues.m_minFrame)) return MS::kFailure; - if(!options.addFloat(kFrameMax, defaultValues.m_maxFrame)) return MS::kFailure; - if(!options.addInt(kSubSamples, defaultValues.m_subSamples)) return MS::kFailure; - if(!options.addBool(kFilterSample, defaultValues.m_filterSample)) return MS::kFailure; - if(!options.addEnum(kExportAtWhichTime, timelineLevel, defaultValues.m_exportAtWhichTime)) return MS::kFailure; - if(!options.addBool(kExportInWorldSpace, defaultValues.m_exportInWorldSpace)) return MS::kFailure; - if(!options.addBool(kActivateAllTranslators, true)) return MS::kFailure; - if(!options.addString(kActiveTranslatorList, "")) return MS::kFailure; - if(!options.addString(kInactiveTranslatorList, "")) return MS::kFailure; - + if (!options.addFrame("AL USD Exporter Options")) + return MS::kFailure; + if (!options.addBool(kDynamicAttributes, defaultValues.m_dynamicAttributes)) + return MS::kFailure; + if (!options.addBool(kDuplicateInstances, defaultValues.m_duplicateInstances)) + return MS::kFailure; + if (!options.addBool(kMergeTransforms, defaultValues.m_mergeTransforms)) + return MS::kFailure; + if (!options.addBool(kAnimation, defaultValues.m_animation)) + return MS::kFailure; + if (!options.addBool(kUseTimelineRange, defaultValues.m_useTimelineRange)) + return MS::kFailure; + if (!options.addFloat(kFrameMin, defaultValues.m_minFrame)) + return MS::kFailure; + if (!options.addFloat(kFrameMax, defaultValues.m_maxFrame)) + return MS::kFailure; + if (!options.addInt(kSubSamples, defaultValues.m_subSamples)) + return MS::kFailure; + if (!options.addBool(kFilterSample, defaultValues.m_filterSample)) + return MS::kFailure; + if (!options.addEnum(kExportAtWhichTime, timelineLevel, defaultValues.m_exportAtWhichTime)) + return MS::kFailure; + if (!options.addBool(kExportInWorldSpace, defaultValues.m_exportInWorldSpace)) + return MS::kFailure; + if (!options.addBool(kActivateAllTranslators, true)) + return MS::kFailure; + if (!options.addString(kActiveTranslatorList, "")) + return MS::kFailure; + if (!options.addString(kInactiveTranslatorList, "")) + return MS::kFailure; + // register the export translator context PluginTranslatorOptionsContextManager::registerContext("ExportTranslator", &m_pluginContext); - + return MS::kSuccess; - } +} - /// \brief clean up the options registered for this translator - /// \param options a set of options that are constructed and later used for option parsing - /// \return MS::kSuccess if ok - static MStatus cleanupOptions(AL::maya::utils::FileTranslatorOptions& options) - { - if(!options.removeFrame("AL USD Exporter Options")) return MS::kFailure; +/// \brief clean up the options registered for this translator +/// \param options a set of options that are constructed and later used for option parsing +/// \return MS::kSuccess if ok +static MStatus cleanupOptions(AL::maya::utils::FileTranslatorOptions& options) +{ + if (!options.removeFrame("AL USD Exporter Options")) + return MS::kFailure; // unregister the export translator context PluginTranslatorOptionsContextManager::unregisterContext("ExportTranslator"); return MS::kSuccess; - } - - void prepPluginOptions() override - { - // I need to possibly recreate this when dirty (i.e. when new optins have been registered/unregistered) - if(m_pluginContext.dirty()) - { - delete m_pluginInstance; - m_pluginInstance = new PluginTranslatorOptionsInstance(m_pluginContext); - setPluginOptionsContext(m_pluginInstance); +} + +void prepPluginOptions() override +{ + // I need to possibly recreate this when dirty (i.e. when new optins have been + // registered/unregistered) + if (m_pluginContext.dirty()) { + delete m_pluginInstance; + m_pluginInstance = new PluginTranslatorOptionsInstance(m_pluginContext); + setPluginOptionsContext(m_pluginInstance); } - } +} - static PluginTranslatorOptionsContext& pluginContext() - { return m_pluginContext; } +static PluginTranslatorOptionsContext& pluginContext() { return m_pluginContext; } private: - AL_USDMAYA_PUBLIC - static PluginTranslatorOptionsContext m_pluginContext; - static PluginTranslatorOptions* m_compatPluginOptions; - AL_USDMAYA_PUBLIC - static PluginTranslatorOptionsInstance* m_pluginInstance; - AL_USDMAYA_PUBLIC - MStatus writer(const MFileObject& file, const AL::maya::utils::OptionsParser& options, FileAccessMode mode) override; +AL_USDMAYA_PUBLIC +static PluginTranslatorOptionsContext m_pluginContext; +static PluginTranslatorOptions* m_compatPluginOptions; +AL_USDMAYA_PUBLIC +static PluginTranslatorOptionsInstance* m_pluginInstance; +AL_USDMAYA_PUBLIC +MStatus writer( + const MFileObject& file, + const AL::maya::utils::OptionsParser& options, + FileAccessMode mode) override; AL_MAYA_TRANSLATOR_END(); //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Import.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Import.cpp index 76075c3f1e..b1ae98d40f 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Import.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Import.cpp @@ -14,14 +14,16 @@ // limitations under the License. // #include "AL/usdmaya/fileio/Import.h" + +#include "AL/maya/utils/Utils.h" +#include "AL/usdmaya/CodeTimings.h" +#include "AL/usdmaya/Metadata.h" #include "AL/usdmaya/fileio/ImportTranslator.h" #include "AL/usdmaya/fileio/SchemaPrims.h" #include "AL/usdmaya/fileio/TransformIterator.h" -#include "AL/usdmaya/Metadata.h" #include "AL/usdmaya/utils/Utils.h" -#include "AL/maya/utils/Utils.h" -#include "AL/usdmaya/CodeTimings.h" +#include #include #include @@ -29,436 +31,410 @@ #include #include -#include - namespace AL { namespace usdmaya { namespace fileio { -using AL::maya::utils::PluginTranslatorOptionsContext; -using AL::maya::utils::PluginTranslatorOptionsInstance; using AL::maya::utils::PluginTranslatorOptions; +using AL::maya::utils::PluginTranslatorOptionsContext; using AL::maya::utils::PluginTranslatorOptionsContextManager; +using AL::maya::utils::PluginTranslatorOptionsInstance; AL_MAYA_DEFINE_COMMAND(ImportCommand, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- Import::Import(const ImporterParams& params) - : m_params(params), m_success(false) + : m_params(params) + , m_success(false) { - doImport(); + doImport(); } //---------------------------------------------------------------------------------------------------------------------- -Import::~Import() -{ -} +Import::~Import() { } //---------------------------------------------------------------------------------------------------------------------- MObject Import::createParentTransform( - const UsdPrim& prim, - TransformIterator& it, - translators::TranslatorManufacture manufacture) + const UsdPrim& prim, + TransformIterator& it, + translators::TranslatorManufacture manufacture) { - NodeFactory& factory = getNodeFactory(); + NodeFactory& factory = getNodeFactory(); fileio::SchemaPrimsUtils utils(manufacture); - MObject parent = it.parent(); - const char * transformType = "transform"; - std::string ttype; - prim.GetMetadata(Metadata::transformType, &ttype); - if(!ttype.empty()){ - transformType = ttype.c_str(); - } - TF_DEBUG(ALUSDMAYA_COMMANDS).Msg("Import::doImport::createParentTransform prim=%s transformType=%s\n", prim.GetPath().GetText(), transformType); - MObject obj = factory.createNode(prim, transformType, parent); - - // handle the special case of importing custom transform params - { - auto dataPlugins = manufacture.getExtraDataPlugins(obj); - for(auto dataPlugin : dataPlugins) + MObject parent = it.parent(); + const char* transformType = "transform"; + std::string ttype; + prim.GetMetadata(Metadata::transformType, &ttype); + if (!ttype.empty()) { + transformType = ttype.c_str(); + } + TF_DEBUG(ALUSDMAYA_COMMANDS) + .Msg( + "Import::doImport::createParentTransform prim=%s transformType=%s\n", + prim.GetPath().GetText(), + transformType); + MObject obj = factory.createNode(prim, transformType, parent); + + // handle the special case of importing custom transform params { - // special case - if(dataPlugin->getFnType() == MFn::kTransform) - { - dataPlugin->import(prim, obj); - } + auto dataPlugins = manufacture.getExtraDataPlugins(obj); + for (auto dataPlugin : dataPlugins) { + // special case + if (dataPlugin->getFnType() == MFn::kTransform) { + dataPlugin->import(prim, obj); + } + } } - } - it.append(obj); - return obj; + it.append(obj); + return obj; }; //---------------------------------------------------------------------------------------------------------------------- void Import::doImport() { - AL::usdmaya::Profiler::clearAll(); - AL_BEGIN_PROFILE_SECTION(doImport); - - translators::TranslatorContextPtr context = translators::TranslatorContext::create(nullptr); - translators::TranslatorManufacture manufacture(context); - if(m_params.m_activateAllTranslators) - { - manufacture.activateAll(); - } - else - { - manufacture.deactivateAll(); - } - - if(!m_params.m_activePluginTranslators.empty()) - { - manufacture.activate(m_params.m_activePluginTranslators); - } - if(!m_params.m_inactivePluginTranslators.empty()) - { - manufacture.deactivate(m_params.m_inactivePluginTranslators); - } - - - UsdStageRefPtr stage; - if(m_params.m_rootLayer) - { - //stage = UsdStage::Open(m_params.m_rootLayer, m_params.m_sessionLayer); - } - else - { - AL_BEGIN_PROFILE_SECTION(OpenStage); - stage = UsdStage::Open(m_params.m_fileName.asChar(), m_params.m_stageUnloaded ? UsdStage::LoadNone : UsdStage::LoadAll); - AL_END_PROFILE_SECTION(); - } + AL::usdmaya::Profiler::clearAll(); + AL_BEGIN_PROFILE_SECTION(doImport); + + translators::TranslatorContextPtr context = translators::TranslatorContext::create(nullptr); + translators::TranslatorManufacture manufacture(context); + if (m_params.m_activateAllTranslators) { + manufacture.activateAll(); + } else { + manufacture.deactivateAll(); + } - if(stage != UsdStageRefPtr()) - { - // set timeline range if animation is enabled - if(m_params.m_animations) - { - const char* const timeError = "ALUSDImport: error setting time range"; - const MTime startTimeCode = stage->GetStartTimeCode(); - const MTime endTimeCode = stage->GetEndTimeCode(); - AL_MAYA_CHECK_ERROR2(MAnimControl::setMinTime(startTimeCode), timeError); - AL_MAYA_CHECK_ERROR2(MAnimControl::setMaxTime(endTimeCode), timeError); + if (!m_params.m_activePluginTranslators.empty()) { + manufacture.activate(m_params.m_activePluginTranslators); + } + if (!m_params.m_inactivePluginTranslators.empty()) { + manufacture.deactivate(m_params.m_inactivePluginTranslators); } - NodeFactory& factory = getNodeFactory(); - factory.setImportParams(&m_params); + UsdStageRefPtr stage; + if (m_params.m_rootLayer) { + // stage = UsdStage::Open(m_params.m_rootLayer, m_params.m_sessionLayer); + } else { + AL_BEGIN_PROFILE_SECTION(OpenStage); + stage = UsdStage::Open( + m_params.m_fileName.asChar(), + m_params.m_stageUnloaded ? UsdStage::LoadNone : UsdStage::LoadAll); + AL_END_PROFILE_SECTION(); + } - MFnDependencyNode fn; + if (stage != UsdStageRefPtr()) { + // set timeline range if animation is enabled + if (m_params.m_animations) { + const char* const timeError = "ALUSDImport: error setting time range"; + const MTime startTimeCode = stage->GetStartTimeCode(); + const MTime endTimeCode = stage->GetEndTimeCode(); + AL_MAYA_CHECK_ERROR2(MAnimControl::setMinTime(startTimeCode), timeError); + AL_MAYA_CHECK_ERROR2(MAnimControl::setMaxTime(endTimeCode), timeError); + } - fileio::SchemaPrimsUtils utils(manufacture); + NodeFactory& factory = getNodeFactory(); + factory.setImportParams(&m_params); + MFnDependencyNode fn; - m_nonImportablePrims.clear(); - if(!m_params.getBool("Import Meshes")) - { - m_nonImportablePrims.insert(TfToken("Mesh")); - } - if(!m_params.getBool("Import Curves")) - { - m_nonImportablePrims.insert(TfToken("NurbsCurves")); - } + fileio::SchemaPrimsUtils utils(manufacture); - std::map masterMap; - TransformIterator it(stage, m_params.m_parentPath); - // start from the assigned prim - const std::string importPrimPath = AL::maya::utils::convert(m_params.m_primPath); - if(!importPrimPath.empty()) - { - UsdPrim importPrim = stage->GetPrimAtPath(SdfPath(importPrimPath)); - if(importPrim) - { - it = TransformIterator(importPrim, m_params.m_parentPath); - } - } - - for(; !it.done(); it.next()) - { - const UsdPrim& prim = it.prim(); - if(prim.IsInstance()) - { - UsdPrim masterPrim = prim.GetMaster(); - auto iter = masterMap.find(masterPrim.GetPath()); - if(iter == masterMap.end()) - { - MObject mayaObject = createParentTransform(prim, it, manufacture); - MFnDagNode fnInstance(mayaObject); - fnInstance.setInstanceable(true); - masterMap.emplace(masterPrim.GetPath(), mayaObject); + m_nonImportablePrims.clear(); + if (!m_params.getBool("Import Meshes")) { + m_nonImportablePrims.insert(TfToken("Mesh")); } - else - { - MStatus status; - MObject instanceParent = iter->second; - MObject mayaObject = createParentTransform(prim, it, manufacture); - - MFnDagNode fnParent(mayaObject, &status); - MFnDagNode fnInstance(instanceParent, &status); - if(!status) status.perror("Failed to access instance parent"); - - // add each child from the instance transform, to the new transform - for(int i = 0; unsigned(i) < fnInstance.childCount(); ++i) - { - MObject child = fnInstance.child(i); - status = fnParent.addChild(child, MFnDagNode::kNextPos, true); - if(!status) status.perror("Failed to parent instance"); - } - - it.prune(); + if (!m_params.getBool("Import Curves")) { + m_nonImportablePrims.insert(TfToken("NurbsCurves")); } - } - else - { - translators::TranslatorRefPtr schemaTranslator = utils.isSchemaPrim(prim); - if(schemaTranslator != nullptr) - { - if (m_nonImportablePrims.find(prim.GetTypeName()) == m_nonImportablePrims.end()) - { - // check merge status on parent transform (we must use the parent from the iterator!) - bool parentUnmerged = false; - TfToken val; - if(it.parentPrim().GetMetadata(AL::usdmaya::Metadata::mergedTransform, &val)) - { - parentUnmerged = (val == AL::usdmaya::Metadata::unmerged); - } - MObject obj; - if(!parentUnmerged) - { - obj = createParentTransform(prim, it, manufacture); - } - else - { - obj = it.parent(); + std::map masterMap; + TransformIterator it(stage, m_params.m_parentPath); + // start from the assigned prim + const std::string importPrimPath = AL::maya::utils::convert(m_params.m_primPath); + if (!importPrimPath.empty()) { + UsdPrim importPrim = stage->GetPrimAtPath(SdfPath(importPrimPath)); + if (importPrim) { + it = TransformIterator(importPrim, m_params.m_parentPath); } - MObject shape = createShape(schemaTranslator, manufacture, prim, obj, parentUnmerged); - - MFnTransform fnP(obj); - fnP.addChild(shape, MFnTransform::kNextPos, true); - } } - else - { - AL_BEGIN_PROFILE_SECTION(ImportingTransform); - createParentTransform(prim, it, manufacture); - AL_END_PROFILE_SECTION(); + + for (; !it.done(); it.next()) { + const UsdPrim& prim = it.prim(); + if (prim.IsInstance()) { + UsdPrim masterPrim = prim.GetMaster(); + auto iter = masterMap.find(masterPrim.GetPath()); + if (iter == masterMap.end()) { + MObject mayaObject = createParentTransform(prim, it, manufacture); + MFnDagNode fnInstance(mayaObject); + fnInstance.setInstanceable(true); + masterMap.emplace(masterPrim.GetPath(), mayaObject); + } else { + MStatus status; + MObject instanceParent = iter->second; + MObject mayaObject = createParentTransform(prim, it, manufacture); + + MFnDagNode fnParent(mayaObject, &status); + MFnDagNode fnInstance(instanceParent, &status); + if (!status) + status.perror("Failed to access instance parent"); + + // add each child from the instance transform, to the new transform + for (int i = 0; unsigned(i) < fnInstance.childCount(); ++i) { + MObject child = fnInstance.child(i); + status = fnParent.addChild(child, MFnDagNode::kNextPos, true); + if (!status) + status.perror("Failed to parent instance"); + } + + it.prune(); + } + } else { + translators::TranslatorRefPtr schemaTranslator = utils.isSchemaPrim(prim); + if (schemaTranslator != nullptr) { + if (m_nonImportablePrims.find(prim.GetTypeName()) + == m_nonImportablePrims.end()) { + // check merge status on parent transform (we must use the parent from the + // iterator!) + bool parentUnmerged = false; + TfToken val; + if (it.parentPrim().GetMetadata( + AL::usdmaya::Metadata::mergedTransform, &val)) { + parentUnmerged = (val == AL::usdmaya::Metadata::unmerged); + } + + MObject obj; + if (!parentUnmerged) { + obj = createParentTransform(prim, it, manufacture); + } else { + obj = it.parent(); + } + MObject shape + = createShape(schemaTranslator, manufacture, prim, obj, parentUnmerged); + + MFnTransform fnP(obj); + fnP.addChild(shape, MFnTransform::kNextPos, true); + } + } else { + AL_BEGIN_PROFILE_SECTION(ImportingTransform); + createParentTransform(prim, it, manufacture); + AL_END_PROFILE_SECTION(); + } + } } - } } - } - m_success = true; + m_success = true; - AL_END_PROFILE_SECTION(); + AL_END_PROFILE_SECTION(); - std::stringstream strstr; - strstr << "Breakdown for file: " << m_params.m_fileName << std::endl; - AL::usdmaya::Profiler::printReport(strstr); - MGlobal::displayInfo(AL::maya::utils::convert(strstr.str())); + std::stringstream strstr; + strstr << "Breakdown for file: " << m_params.m_fileName << std::endl; + AL::usdmaya::Profiler::printReport(strstr); + MGlobal::displayInfo(AL::maya::utils::convert(strstr.str())); } //---------------------------------------------------------------------------------------------------------------------- MObject Import::createShape( - translators::TranslatorRefPtr translator, - translators::TranslatorManufacture& manufacture, - const UsdPrim& prim, - MObject parent, - bool parentUnmerged) + translators::TranslatorRefPtr translator, + translators::TranslatorManufacture& manufacture, + const UsdPrim& prim, + MObject parent, + bool parentUnmerged) { - MObject shapeObj; - if (prim.IsInMaster()) - { - const SdfPath& primPath = prim.GetPrimPath(); - if (m_instanceObjects.find(primPath) != m_instanceObjects.end()) - { - shapeObj = m_instanceObjects[primPath]; + MObject shapeObj; + if (prim.IsInMaster()) { + const SdfPath& primPath = prim.GetPrimPath(); + if (m_instanceObjects.find(primPath) != m_instanceObjects.end()) { + shapeObj = m_instanceObjects[primPath]; + } else { + translator->import(prim, parent, shapeObj); + NodeFactory::setupNode(prim, shapeObj, parent, true); + m_instanceObjects[primPath] = shapeObj; + } + } else { + translator->import(prim, parent, shapeObj); + NodeFactory::setupNode(prim, shapeObj, parent, parentUnmerged); } - else - { - translator->import(prim, parent, shapeObj); - NodeFactory::setupNode(prim, shapeObj, parent, true); - m_instanceObjects[primPath] = shapeObj; + + auto dataPlugins = manufacture.getExtraDataPlugins(shapeObj); + for (auto dataPlugin : dataPlugins) { + // special case + dataPlugin->import(prim, parent); } - } - else - { - translator->import(prim, parent, shapeObj); - NodeFactory::setupNode(prim, shapeObj, parent, parentUnmerged); - } - - auto dataPlugins = manufacture.getExtraDataPlugins(shapeObj); - for(auto dataPlugin : dataPlugins) - { - // special case - dataPlugin->import(prim, parent); - } - - return shapeObj; + + return shapeObj; } //---------------------------------------------------------------------------------------------------------------------- MStatus ImportCommand::doIt(const MArgList& args) { - maya::utils::OptionsParser parser; - ImportTranslator::options().initParser(parser); - m_params.m_parser = &parser; - PluginTranslatorOptionsInstance pluginInstance(ImportTranslator::pluginContext()); - parser.setPluginOptionsContext(&pluginInstance); - - MStatus status; - MArgDatabase argData(syntax(), args, &status); - AL_MAYA_CHECK_ERROR(status, "ImportCommand: failed to match arguments"); - - // fetch filename and ensure it's valid - if(!argData.isFlagSet("-f", &status)) - { - MGlobal::displayError("ImportCommand: \"file\" argument must be set"); - return MS::kFailure; - } - - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("-f", 0, m_params.m_fileName), "ImportCommand: Unable to fetch \"file\" argument"); - - // check for parent path flag. Convert to MDagPath if found. - if(argData.isFlagSet("-p", &status)) - { - MString parent; - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("-p", 0, parent), "ImportCommand: Unable to fetch \"parent\" argument"); - - MSelectionList sl, sl2; - MGlobal::getActiveSelectionList(sl); - MGlobal::selectByName(parent, MGlobal::kReplaceList); - MGlobal::getActiveSelectionList(sl2); - MGlobal::setActiveSelectionList(sl); - if(sl2.length()) - { - sl2.getDagPath(0, m_params.m_parentPath); + maya::utils::OptionsParser parser; + ImportTranslator::options().initParser(parser); + m_params.m_parser = &parser; + PluginTranslatorOptionsInstance pluginInstance(ImportTranslator::pluginContext()); + parser.setPluginOptionsContext(&pluginInstance); + + MStatus status; + MArgDatabase argData(syntax(), args, &status); + AL_MAYA_CHECK_ERROR(status, "ImportCommand: failed to match arguments"); + + // fetch filename and ensure it's valid + if (!argData.isFlagSet("-f", &status)) { + MGlobal::displayError("ImportCommand: \"file\" argument must be set"); + return MS::kFailure; } - } - - if (argData.isFlagSet("-pp", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("-pp", 0, m_params.m_primPath), "ImportCommand, Unable to fetch \"primPath\" argument"); - } - - if(argData.isFlagSet("-un", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("-un", 0, m_params.m_stageUnloaded), "ImportCommand: Unable to fetch \"unloaded\" argument") - } - - if(argData.isFlagSet("-a", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("-a", 0, m_params.m_animations), "ImportCommand: Unable to fetch \"animation\" argument"); - } - - if(argData.isFlagSet("-da", &status)) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("-da", 0, m_params.m_dynamicAttributes), "ImportCommand: Unable to fetch \"dynamicAttributes\" argument"); - } - - if(argData.isFlagSet("-m", &status)) - { - bool value = true; - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("-m", 0, value), "ImportCommand: Unable to fetch \"meshes\" argument"); - m_params.setBool("Import Meshes", value); - } - - if(argData.isFlagSet("-nc", &status)) - { - bool value = true; - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("-nc", 0, value), "ImportCommand: Unable to fetch \"nurbs curves\" argument"); - m_params.setBool("Import Curves", value); - } - - if(argData.isFlagSet("opt", &status)) - { - MString optionString; - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("opt", 0, optionString), "ImportCommand: Unable to fetch \"options\" argument"); - parser.parse(optionString); - } - - if(argData.isFlagSet("-fd", &status)) - { - m_params.m_forceDefaultRead = true; - } - - m_params.m_activateAllTranslators = true; - bool eat = argData.isFlagSet("eat", &status); - bool dat = argData.isFlagSet("dat", &status); - if(eat && dat) - { - MGlobal::displayError("ImportCommand: cannot enable all translators, AND disable all translators, at the same time"); - } - else - if(dat) - { - m_params.m_activateAllTranslators = false; - } - - if(argData.isFlagSet("ept", &status)) - { - MString arg; - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("ept", 0, arg), "ALUSDExport: Unable to fetch \"enablePluginTranslators\" argument"); - MStringArray strings; - arg.split(',', strings); - for(uint32_t i = 0, n = strings.length(); i < n; ++i) - { - m_params.m_activePluginTranslators.emplace_back(strings[i].asChar()); + + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("-f", 0, m_params.m_fileName), + "ImportCommand: Unable to fetch \"file\" argument"); + + // check for parent path flag. Convert to MDagPath if found. + if (argData.isFlagSet("-p", &status)) { + MString parent; + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("-p", 0, parent), + "ImportCommand: Unable to fetch \"parent\" argument"); + + MSelectionList sl, sl2; + MGlobal::getActiveSelectionList(sl); + MGlobal::selectByName(parent, MGlobal::kReplaceList); + MGlobal::getActiveSelectionList(sl2); + MGlobal::setActiveSelectionList(sl); + if (sl2.length()) { + sl2.getDagPath(0, m_params.m_parentPath); + } } - } - - if(argData.isFlagSet("dpt", &status)) - { - MString arg; - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("dpt", 0, arg), "ALUSDExport: Unable to fetch \"disablePluginTranslators\" argument"); - MStringArray strings; - arg.split(',', strings); - for(uint32_t i = 0, n = strings.length(); i < n; ++i) - { - m_params.m_inactivePluginTranslators.emplace_back(strings[i].asChar()); + + if (argData.isFlagSet("-pp", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("-pp", 0, m_params.m_primPath), + "ImportCommand, Unable to fetch \"primPath\" argument"); + } + + if (argData.isFlagSet("-un", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("-un", 0, m_params.m_stageUnloaded), + "ImportCommand: Unable to fetch \"unloaded\" argument") + } + + if (argData.isFlagSet("-a", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("-a", 0, m_params.m_animations), + "ImportCommand: Unable to fetch \"animation\" argument"); + } + + if (argData.isFlagSet("-da", &status)) { + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("-da", 0, m_params.m_dynamicAttributes), + "ImportCommand: Unable to fetch \"dynamicAttributes\" argument"); } - } - return redoIt(); + if (argData.isFlagSet("-m", &status)) { + bool value = true; + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("-m", 0, value), + "ImportCommand: Unable to fetch \"meshes\" argument"); + m_params.setBool("Import Meshes", value); + } + + if (argData.isFlagSet("-nc", &status)) { + bool value = true; + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("-nc", 0, value), + "ImportCommand: Unable to fetch \"nurbs curves\" argument"); + m_params.setBool("Import Curves", value); + } + + if (argData.isFlagSet("opt", &status)) { + MString optionString; + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("opt", 0, optionString), + "ImportCommand: Unable to fetch \"options\" argument"); + parser.parse(optionString); + } + + if (argData.isFlagSet("-fd", &status)) { + m_params.m_forceDefaultRead = true; + } + + m_params.m_activateAllTranslators = true; + bool eat = argData.isFlagSet("eat", &status); + bool dat = argData.isFlagSet("dat", &status); + if (eat && dat) { + MGlobal::displayError("ImportCommand: cannot enable all translators, AND disable all " + "translators, at the same time"); + } else if (dat) { + m_params.m_activateAllTranslators = false; + } + + if (argData.isFlagSet("ept", &status)) { + MString arg; + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("ept", 0, arg), + "ALUSDExport: Unable to fetch \"enablePluginTranslators\" argument"); + MStringArray strings; + arg.split(',', strings); + for (uint32_t i = 0, n = strings.length(); i < n; ++i) { + m_params.m_activePluginTranslators.emplace_back(strings[i].asChar()); + } + } + + if (argData.isFlagSet("dpt", &status)) { + MString arg; + AL_MAYA_CHECK_ERROR( + argData.getFlagArgument("dpt", 0, arg), + "ALUSDExport: Unable to fetch \"disablePluginTranslators\" argument"); + MStringArray strings; + arg.split(',', strings); + for (uint32_t i = 0, n = strings.length(); i < n; ++i) { + m_params.m_inactivePluginTranslators.emplace_back(strings[i].asChar()); + } + } + + return redoIt(); } //---------------------------------------------------------------------------------------------------------------------- MStatus ImportCommand::redoIt() { - Import importer(m_params); - return importer ? MS::kSuccess : MS::kFailure; + Import importer(m_params); + return importer ? MS::kSuccess : MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- -MStatus ImportCommand::undoIt() -{ - return MS::kSuccess; -} +MStatus ImportCommand::undoIt() { return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MSyntax ImportCommand::createSyntax() { - const char* const errorString = "ImportCommand: failed to create syntax"; - - MSyntax syntax; - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-a", "-anim"), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-f", "-file", MSyntax::kString), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-un", "-unloaded", MSyntax::kBoolean), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-p", "-parent", MSyntax::kString), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-pp", "-primPath", MSyntax::kString), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-da", "-dynamicAttribute", MSyntax::kBoolean), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-m", "-meshes", MSyntax::kBoolean), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-nc", "-nurbsCurves", MSyntax::kBoolean), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-fd", "-forceDefaultRead", MSyntax::kNoArg), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-eat", "-enableAllTranslators", MSyntax::kNoArg), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-dat", "-disableAllTranslators", MSyntax::kNoArg), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-ept", "-enablePluginTranslators", MSyntax::kString), errorString); - AL_MAYA_CHECK_ERROR2(syntax.addFlag("-dpt", "-disablePluginTranslators", MSyntax::kString), errorString); - syntax.makeFlagMultiUse("-arp"); - syntax.enableQuery(false); - syntax.enableEdit(false); - return syntax; + const char* const errorString = "ImportCommand: failed to create syntax"; + + MSyntax syntax; + AL_MAYA_CHECK_ERROR2(syntax.addFlag("-a", "-anim"), errorString); + AL_MAYA_CHECK_ERROR2(syntax.addFlag("-f", "-file", MSyntax::kString), errorString); + AL_MAYA_CHECK_ERROR2(syntax.addFlag("-un", "-unloaded", MSyntax::kBoolean), errorString); + AL_MAYA_CHECK_ERROR2(syntax.addFlag("-p", "-parent", MSyntax::kString), errorString); + AL_MAYA_CHECK_ERROR2(syntax.addFlag("-pp", "-primPath", MSyntax::kString), errorString); + AL_MAYA_CHECK_ERROR2( + syntax.addFlag("-da", "-dynamicAttribute", MSyntax::kBoolean), errorString); + AL_MAYA_CHECK_ERROR2(syntax.addFlag("-m", "-meshes", MSyntax::kBoolean), errorString); + AL_MAYA_CHECK_ERROR2(syntax.addFlag("-nc", "-nurbsCurves", MSyntax::kBoolean), errorString); + AL_MAYA_CHECK_ERROR2(syntax.addFlag("-fd", "-forceDefaultRead", MSyntax::kNoArg), errorString); + AL_MAYA_CHECK_ERROR2( + syntax.addFlag("-eat", "-enableAllTranslators", MSyntax::kNoArg), errorString); + AL_MAYA_CHECK_ERROR2( + syntax.addFlag("-dat", "-disableAllTranslators", MSyntax::kNoArg), errorString); + AL_MAYA_CHECK_ERROR2( + syntax.addFlag("-ept", "-enablePluginTranslators", MSyntax::kString), errorString); + AL_MAYA_CHECK_ERROR2( + syntax.addFlag("-dpt", "-disablePluginTranslators", MSyntax::kString), errorString); + syntax.makeFlagMultiUse("-arp"); + syntax.enableQuery(false); + syntax.enableEdit(false); + return syntax; } //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Import.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Import.h index ad7b24abfb..5cc78c2ec6 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Import.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/Import.h @@ -14,18 +14,16 @@ // limitations under the License. // #pragma once +#include "AL/maya/utils/MayaHelperMacros.h" #include "AL/usdmaya/fileio/ImportParams.h" #include "AL/usdmaya/fileio/NodeFactory.h" #include "AL/usdmaya/fileio/translators/TranslatorBase.h" -#include "AL/maya/utils/MayaHelperMacros.h" +#include #include - -#include PXR_NAMESPACE_USING_DIRECTIVE - namespace AL { namespace usdmaya { namespace fileio { @@ -37,67 +35,65 @@ namespace fileio { class Import { public: + /// \brief the ctor runs the main import process. Simply pass in a set of parameters that will + /// determine what maya + /// should import into the scene + /// \param params the import params + Import(const ImporterParams& params); - /// \brief the ctor runs the main import process. Simply pass in a set of parameters that will determine what maya - /// should import into the scene - /// \param params the import params - Import(const ImporterParams& params); - - /// \brief dtor - ~Import(); + /// \brief dtor + ~Import(); - /// \brief returns true if the import succeeded, false otherwise - inline operator bool () const - { return m_success; } + /// \brief returns true if the import succeeded, false otherwise + inline operator bool() const { return m_success; } private: - void doImport(); - MObject createShape( - translators::TranslatorRefPtr translator, - translators::TranslatorManufacture& manufacture, - const UsdPrim& prim, - MObject parent, - bool parentUnmerged); -MObject createParentTransform( - const UsdPrim& prim, - TransformIterator& it, - translators::TranslatorManufacture manufacture); - - const ImporterParams& m_params; - TfHashMap m_instanceObjects; - TfToken::HashSet m_nonImportablePrims; - bool m_success; + void doImport(); + MObject createShape( + translators::TranslatorRefPtr translator, + translators::TranslatorManufacture& manufacture, + const UsdPrim& prim, + MObject parent, + bool parentUnmerged); + MObject createParentTransform( + const UsdPrim& prim, + TransformIterator& it, + translators::TranslatorManufacture manufacture); + + const ImporterParams& m_params; + TfHashMap m_instanceObjects; + TfToken::HashSet m_nonImportablePrims; + bool m_success; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief A command to import a USD file into Maya (partially supporting Animal Logic specific things) -/// \ingroup fileio +/// \brief A command to import a USD file into Maya (partially supporting Animal Logic specific +/// things) \ingroup fileio //---------------------------------------------------------------------------------------------------------------------- -class ImportCommand - : public MPxCommand +class ImportCommand : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); + AL_MAYA_DECLARE_COMMAND(); - /// ctor - inline ImportCommand() - : m_params() {} + /// ctor + inline ImportCommand() + : m_params() + { + } - /// dtor - inline ~ImportCommand() - {} + /// dtor + inline ~ImportCommand() { } private: - MStatus doIt(const MArgList& args); - MStatus redoIt(); - MStatus undoIt(); - bool isUndoable() const { return true; }; - ImporterParams m_params; + MStatus doIt(const MArgList& args); + MStatus redoIt(); + MStatus undoIt(); + bool isUndoable() const { return true; }; + ImporterParams m_params; }; //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportParams.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportParams.h index 369a2e0efa..8f94136905 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportParams.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportParams.h @@ -14,12 +14,13 @@ // limitations under the License. // #pragma once -#include -#include -#include +#include "AL/maya/utils/FileTranslatorOptions.h" #include -#include "AL/maya/utils/FileTranslatorOptions.h" + +#include +#include +#include #include @@ -35,77 +36,81 @@ namespace fileio { //---------------------------------------------------------------------------------------------------------------------- struct ImporterParams { - AL::maya::utils::OptionsParser* m_parser = 0; - MDagPath m_parentPath; ///< the parent transform under which the USD file will be imported - MString m_primPath; ///< the prim path which importing will start from - MString m_fileName; ///< the name of the file to import - bool m_animations = true; ///< true to import animation data, false to ignore animation data import - bool m_dynamicAttributes = true; ///< if true, attributes in the USD file marked as 'custom' will be imported as dynamic attributes. - bool m_stageUnloaded = true; ///< if true, the USD stage will be opened with the UsdStage::LoadNone flag. If false the stage will be loaded with the UsdStage::LoadAll flag - bool m_forceDefaultRead = false; ///< true to explicit read default values - SdfLayerRefPtr m_rootLayer; ///< \todo Remove? - SdfLayerRefPtr m_sessionLayer; ///< \todo Remove? + AL::maya::utils::OptionsParser* m_parser = 0; + MDagPath m_parentPath; ///< the parent transform under which the USD file will be imported + MString m_primPath; ///< the prim path which importing will start from + MString m_fileName; ///< the name of the file to import + bool m_animations + = true; ///< true to import animation data, false to ignore animation data import + bool m_dynamicAttributes = true; ///< if true, attributes in the USD file marked as 'custom' + ///< will be imported as dynamic attributes. + bool m_stageUnloaded + = true; ///< if true, the USD stage will be opened with the UsdStage::LoadNone flag. If + ///< false the stage will be loaded with the UsdStage::LoadAll flag + bool m_forceDefaultRead = false; ///< true to explicit read default values + SdfLayerRefPtr m_rootLayer; ///< \todo Remove? + SdfLayerRefPtr m_sessionLayer; ///< \todo Remove? - bool m_activateAllTranslators = true; - TfTokenVector m_activePluginTranslators; - TfTokenVector m_inactivePluginTranslators; - - mutable MObjectArray m_newAnimCurves; ///< to contain the possible created new animCurves for future management. + bool m_activateAllTranslators = true; + TfTokenVector m_activePluginTranslators; + TfTokenVector m_inactivePluginTranslators; - /// \brief Given the text name of an option, returns the boolean value for that option. - /// \param str the name of the option - /// \return the option value - bool getBool(const char* const str) const - { - if(m_parser) + mutable MObjectArray + m_newAnimCurves; ///< to contain the possible created new animCurves for future management. + + /// \brief Given the text name of an option, returns the boolean value for that option. + /// \param str the name of the option + /// \return the option value + bool getBool(const char* const str) const { - return m_parser->getBool(str); + if (m_parser) { + return m_parser->getBool(str); + } + return false; } - return false; - } - /// \brief Given the text name of an option, returns the integer value for that option. - /// \param str the name of the option - /// \return the option value - int getInt(const char* const str) const - { - if(m_parser) - return m_parser->getInt(str); - return 0; - } + /// \brief Given the text name of an option, returns the integer value for that option. + /// \param str the name of the option + /// \return the option value + int getInt(const char* const str) const + { + if (m_parser) + return m_parser->getInt(str); + return 0; + } - /// \brief Given the text name of an option, returns the floating point value for that option. - /// \param str the name of the option - /// \return the option value - float getFloat(const char* const str) const - { - if(m_parser) - return m_parser->getFloat(str); - return 0.0f; - } + /// \brief Given the text name of an option, returns the floating point value for that option. + /// \param str the name of the option + /// \return the option value + float getFloat(const char* const str) const + { + if (m_parser) + return m_parser->getFloat(str); + return 0.0f; + } - /// \brief Given the text name of an option, returns the string value for that option. - /// \param str the name of the option - /// \return the option value - MString getString(const char* const str) const - { - if(m_parser) - return m_parser->getString(str); - return MString(); - } + /// \brief Given the text name of an option, returns the string value for that option. + /// \param str the name of the option + /// \return the option value + MString getString(const char* const str) const + { + if (m_parser) + return m_parser->getString(str); + return MString(); + } - /// \brief Sets the value of a boolean option - /// \param str the name of the option to set - /// \param value the new value for the option - void setBool(const char* const str, bool value) - { - if(m_parser) - m_parser->setBool(str, value); - } + /// \brief Sets the value of a boolean option + /// \param str the name of the option to set + /// \param value the new value for the option + void setBool(const char* const str, bool value) + { + if (m_parser) + m_parser->setBool(str, value); + } }; //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportTranslator.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportTranslator.cpp index 66931f790d..95c30fd945 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportTranslator.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportTranslator.cpp @@ -13,72 +13,71 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/fileio/Import.h" #include "AL/usdmaya/fileio/ImportTranslator.h" -#include +#include "AL/usdmaya/fileio/Import.h" + #include +#include namespace AL { namespace usdmaya { namespace fileio { -PluginTranslatorOptionsContext ImportTranslator::m_pluginContext; -PluginTranslatorOptions* ImportTranslator::m_compatPluginOptions; +PluginTranslatorOptionsContext ImportTranslator::m_pluginContext; +PluginTranslatorOptions* ImportTranslator::m_compatPluginOptions; PluginTranslatorOptionsInstance* ImportTranslator::m_pluginInstance; //---------------------------------------------------------------------------------------------------------------------- -MStatus ImportTranslator::reader(const MFileObject& file, const AL::maya::utils::OptionsParser& options, FileAccessMode mode) +MStatus ImportTranslator::reader( + const MFileObject& file, + const AL::maya::utils::OptionsParser& options, + FileAccessMode mode) { - m_params.m_parser = (maya::utils::OptionsParser*)&options; - MString parentPath = options.getString(kParentPath); - m_params.m_parentPath = MDagPath(); - if(parentPath.length()) - { - MSelectionList sl, sl2; - MGlobal::getActiveSelectionList(sl); - MGlobal::selectByName(parentPath, MGlobal::kReplaceList); - MGlobal::getActiveSelectionList(sl2); - MGlobal::setActiveSelectionList(sl); - if(sl2.length()) - { - sl2.getDagPath(0, m_params.m_parentPath); + m_params.m_parser = (maya::utils::OptionsParser*)&options; + MString parentPath = options.getString(kParentPath); + m_params.m_parentPath = MDagPath(); + if (parentPath.length()) { + MSelectionList sl, sl2; + MGlobal::getActiveSelectionList(sl); + MGlobal::selectByName(parentPath, MGlobal::kReplaceList); + MGlobal::getActiveSelectionList(sl2); + MGlobal::setActiveSelectionList(sl); + if (sl2.length()) { + sl2.getDagPath(0, m_params.m_parentPath); + } } - } - m_params.m_primPath = options.getString(kPrimPath); + m_params.m_primPath = options.getString(kPrimPath); - m_params.m_activateAllTranslators = options.getBool(kActivateAllTranslators); - MStringArray strings; - options.getString(kActiveTranslatorList).split(',', strings); - for(uint32_t i = 0, n = strings.length(); i < n; ++i) - { - m_params.m_activePluginTranslators.emplace_back(strings[i].asChar()); - } - strings.setLength(0); - options.getString(kInactiveTranslatorList).split(',', strings); - for(uint32_t i = 0, n = strings.length(); i < n; ++i) - { - m_params.m_inactivePluginTranslators.emplace_back(strings[i].asChar()); - } + m_params.m_activateAllTranslators = options.getBool(kActivateAllTranslators); + MStringArray strings; + options.getString(kActiveTranslatorList).split(',', strings); + for (uint32_t i = 0, n = strings.length(); i < n; ++i) { + m_params.m_activePluginTranslators.emplace_back(strings[i].asChar()); + } + strings.setLength(0); + options.getString(kInactiveTranslatorList).split(',', strings); + for (uint32_t i = 0, n = strings.length(); i < n; ++i) { + m_params.m_inactivePluginTranslators.emplace_back(strings[i].asChar()); + } - m_params.m_fileName = file.fullName(); - m_params.m_animations = options.getBool(kAnimations); - m_params.m_stageUnloaded = options.getBool(kStageUnload); - m_params.m_forceDefaultRead = options.getBool(kReadDefaultValues); + m_params.m_fileName = file.fullName(); + m_params.m_animations = options.getBool(kAnimations); + m_params.m_stageUnloaded = options.getBool(kStageUnload); + m_params.m_forceDefaultRead = options.getBool(kReadDefaultValues); + + if (m_pluginInstance) { + m_pluginInstance->toOptionVars("ImportTranslator"); + } - if(m_pluginInstance) - { - m_pluginInstance->toOptionVars("ImportTranslator"); - } - - Import importer(m_params); + Import importer(m_params); - return importer ? MS::kSuccess : MS::kFailure; // done! + return importer ? MS::kSuccess : MS::kFailure; // done! } //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportTranslator.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportTranslator.h index 04c5779b05..614d55dd9f 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportTranslator.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/ImportTranslator.h @@ -24,99 +24,120 @@ namespace AL { namespace usdmaya { namespace fileio { -using AL::maya::utils::PluginTranslatorOptionsContext; -using AL::maya::utils::PluginTranslatorOptionsInstance; using AL::maya::utils::PluginTranslatorOptions; +using AL::maya::utils::PluginTranslatorOptionsContext; using AL::maya::utils::PluginTranslatorOptionsContextManager; +using AL::maya::utils::PluginTranslatorOptionsInstance; //---------------------------------------------------------------------------------------------------------------------- /// \brief A USD importer into Maya (partially supporting Animal Logic specific things) /// \ingroup fileio //---------------------------------------------------------------------------------------------------------------------- -AL_MAYA_TRANSLATOR_BEGIN(ImportTranslator, "AL usdmaya import", true, false, "*.usda", "*.usdc;*.usda;*.usd;*.usdt"); - - /// \fn void* creator() - /// \brief creates an instance of the file translator - /// \return a new file translator instance - - /// \var const char* const kTranslatorName - /// \brief the name of the file translator - - /// \var const char* const kClassName - /// \brief the name of the C++ file translator class - - // specify the option names (These will uniquely identify the exporter options) - static constexpr const char* const kParentPath = "Parent Path"; ///< the parent path option name - static constexpr const char* const kPrimPath = "Prim Path"; ///< the prim path option name - static constexpr const char* const kAnimations = "Import Animations"; ///< the import animation option name - static constexpr const char* const kDynamicAttributes = "Import Dynamic Attributes"; ///< the import dynamic attributes option name - static constexpr const char* const kStageUnload = "Load None"; ///< the import animation option name - static constexpr const char* const kReadDefaultValues = "Read Default Values"; ///< the import animation option name - static constexpr const char* const kActivateAllTranslators = "Activate all Plugin Translators"; - static constexpr const char* const kActiveTranslatorList = "Active Translator List"; - static constexpr const char* const kInactiveTranslatorList = "Inactive Translator List"; - - /// \brief provide a method to specify the import options - /// \param options a set of options that are constructed and later used for option parsing - /// \return MS::kSuccess if ok - static MStatus specifyOptions(AL::maya::utils::FileTranslatorOptions& options) - { - if(!options.addFrame("AL USD Importer Options")) return MS::kFailure; - if(!options.addString(kParentPath, "")) return MS::kFailure; - if(!options.addString(kPrimPath, "")) return MS::kFailure; - if(!options.addBool(kAnimations, true)) return MS::kFailure; - if(!options.addBool(kDynamicAttributes, true)) return MS::kFailure; - if(!options.addBool(kStageUnload, false)) return MS::kFailure; - if(!options.addBool(kReadDefaultValues, true)) return MS::kFailure; - if(!options.addBool(kActivateAllTranslators, true)) return MS::kFailure; - if(!options.addString(kActiveTranslatorList, "")) return MS::kFailure; - if(!options.addString(kInactiveTranslatorList, "")) return MS::kFailure; +AL_MAYA_TRANSLATOR_BEGIN( + ImportTranslator, + "AL usdmaya import", + true, + false, + "*.usda", + "*.usdc;*.usda;*.usd;*.usdt"); + +/// \fn void* creator() +/// \brief creates an instance of the file translator +/// \return a new file translator instance + +/// \var const char* const kTranslatorName +/// \brief the name of the file translator + +/// \var const char* const kClassName +/// \brief the name of the C++ file translator class + +// specify the option names (These will uniquely identify the exporter options) +static constexpr const char* const kParentPath = "Parent Path"; ///< the parent path option name +static constexpr const char* const kPrimPath = "Prim Path"; ///< the prim path option name +static constexpr const char* const kAnimations + = "Import Animations"; ///< the import animation option name +static constexpr const char* const kDynamicAttributes + = "Import Dynamic Attributes"; ///< the import dynamic attributes option name +static constexpr const char* const kStageUnload = "Load None"; ///< the import animation option name +static constexpr const char* const kReadDefaultValues + = "Read Default Values"; ///< the import animation option name +static constexpr const char* const kActivateAllTranslators = "Activate all Plugin Translators"; +static constexpr const char* const kActiveTranslatorList = "Active Translator List"; +static constexpr const char* const kInactiveTranslatorList = "Inactive Translator List"; + +/// \brief provide a method to specify the import options +/// \param options a set of options that are constructed and later used for option parsing +/// \return MS::kSuccess if ok +static MStatus specifyOptions(AL::maya::utils::FileTranslatorOptions& options) +{ + if (!options.addFrame("AL USD Importer Options")) + return MS::kFailure; + if (!options.addString(kParentPath, "")) + return MS::kFailure; + if (!options.addString(kPrimPath, "")) + return MS::kFailure; + if (!options.addBool(kAnimations, true)) + return MS::kFailure; + if (!options.addBool(kDynamicAttributes, true)) + return MS::kFailure; + if (!options.addBool(kStageUnload, false)) + return MS::kFailure; + if (!options.addBool(kReadDefaultValues, true)) + return MS::kFailure; + if (!options.addBool(kActivateAllTranslators, true)) + return MS::kFailure; + if (!options.addString(kActiveTranslatorList, "")) + return MS::kFailure; + if (!options.addString(kInactiveTranslatorList, "")) + return MS::kFailure; // register the export translator context PluginTranslatorOptionsContextManager::registerContext("ImportTranslator", &m_pluginContext); return MS::kSuccess; - } +} - /// \brief clean up the options registered for this translator - /// \param options a set of options that are constructed and later used for option parsing - /// \return MS::kSuccess if ok - static MStatus cleanupOptions(AL::maya::utils::FileTranslatorOptions& options) - { - if(!options.removeFrame("AL USD Importer Options")) return MS::kFailure; +/// \brief clean up the options registered for this translator +/// \param options a set of options that are constructed and later used for option parsing +/// \return MS::kSuccess if ok +static MStatus cleanupOptions(AL::maya::utils::FileTranslatorOptions& options) +{ + if (!options.removeFrame("AL USD Importer Options")) + return MS::kFailure; // unregister the export translator context PluginTranslatorOptionsContextManager::unregisterContext("ImportTranslator"); return MS::kSuccess; - } - - void prepPluginOptions() override - { - if(m_pluginContext.dirty()) - { - delete m_pluginInstance; - m_pluginInstance = new PluginTranslatorOptionsInstance(m_pluginContext); - setPluginOptionsContext(m_pluginInstance); +} + +void prepPluginOptions() override +{ + if (m_pluginContext.dirty()) { + delete m_pluginInstance; + m_pluginInstance = new PluginTranslatorOptionsInstance(m_pluginContext); + setPluginOptionsContext(m_pluginInstance); } - } +} - static PluginTranslatorOptionsContext& pluginContext() - { return m_pluginContext; } +static PluginTranslatorOptionsContext& pluginContext() { return m_pluginContext; } private: - AL_USDMAYA_PUBLIC - static PluginTranslatorOptionsContext m_pluginContext; - AL_USDMAYA_PUBLIC - static PluginTranslatorOptions* m_compatPluginOptions; - AL_USDMAYA_PUBLIC - static PluginTranslatorOptionsInstance* m_pluginInstance; - AL_USDMAYA_PUBLIC - MStatus reader(const MFileObject& file, const AL::maya::utils::OptionsParser& options, FileAccessMode mode) override; - ImporterParams m_params; +AL_USDMAYA_PUBLIC +static PluginTranslatorOptionsContext m_pluginContext; +AL_USDMAYA_PUBLIC +static PluginTranslatorOptions* m_compatPluginOptions; +AL_USDMAYA_PUBLIC +static PluginTranslatorOptionsInstance* m_pluginInstance; +AL_USDMAYA_PUBLIC +MStatus reader( + const MFileObject& file, + const AL::maya::utils::OptionsParser& options, + FileAccessMode mode) override; +ImporterParams m_params; AL_MAYA_TRANSLATOR_END(); //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/NodeFactory.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/NodeFactory.cpp index a6b693224a..2e7c288d5a 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/NodeFactory.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/NodeFactory.cpp @@ -13,18 +13,19 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/utils/AttributeType.h" +#include "AL/usdmaya/fileio/NodeFactory.h" + #include "AL/usdmaya/fileio/Import.h" #include "AL/usdmaya/fileio/ImportParams.h" -#include "AL/usdmaya/fileio/NodeFactory.h" -#include "AL/usdmaya/fileio/translators/DgNodeTranslator.h" #include "AL/usdmaya/fileio/translators/DagNodeTranslator.h" +#include "AL/usdmaya/fileio/translators/DgNodeTranslator.h" #include "AL/usdmaya/fileio/translators/TransformTranslator.h" +#include "AL/usdmaya/utils/AttributeType.h" +#include "AL/usdmaya/utils/Utils.h" +#include #include #include -#include -#include "AL/usdmaya/utils/Utils.h" namespace AL { namespace usdmaya { @@ -35,96 +36,96 @@ NodeFactory* g_nodeFactory = 0; //---------------------------------------------------------------------------------------------------------------------- void freeNodeFactory() { - delete g_nodeFactory; - g_nodeFactory = 0; + delete g_nodeFactory; + g_nodeFactory = 0; } //---------------------------------------------------------------------------------------------------------------------- NodeFactory& getNodeFactory() { - if(!g_nodeFactory) - { - g_nodeFactory = new NodeFactory; - } - return *g_nodeFactory; + if (!g_nodeFactory) { + g_nodeFactory = new NodeFactory; + } + return *g_nodeFactory; } //---------------------------------------------------------------------------------------------------------------------- NodeFactory::NodeFactory() -: m_builders(), m_params(0) + : m_builders() + , m_params(0) { - translators::DgNodeTranslator::registerType(); - translators::DagNodeTranslator::registerType(); - translators::TransformTranslator::registerType(); - m_builders.insert(std::make_pair("node", new translators::DgNodeTranslator)); - m_builders.insert(std::make_pair("dagNode", new translators::DagNodeTranslator)); - m_builders.insert(std::make_pair("transform", new translators::TransformTranslator)); + translators::DgNodeTranslator::registerType(); + translators::DagNodeTranslator::registerType(); + translators::TransformTranslator::registerType(); + m_builders.insert(std::make_pair("node", new translators::DgNodeTranslator)); + m_builders.insert(std::make_pair("dagNode", new translators::DagNodeTranslator)); + m_builders.insert(std::make_pair("transform", new translators::TransformTranslator)); } //---------------------------------------------------------------------------------------------------------------------- NodeFactory::~NodeFactory() { - auto it = m_builders.begin(); - auto e = m_builders.end(); - for(; it != e; ++it) - { - delete it->second; - } + auto it = m_builders.begin(); + auto e = m_builders.end(); + for (; it != e; ++it) { + delete it->second; + } } //---------------------------------------------------------------------------------------------------------------------- -MObject NodeFactory::createNode(const UsdPrim& from, const char* const nodeType, MObject parent, bool parentUnmerged) +MObject NodeFactory::createNode( + const UsdPrim& from, + const char* const nodeType, + MObject parent, + bool parentUnmerged) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg(" NodeFactory::createNode: %s of type %s\n", from.GetPrimPath().GetText(), nodeType); - std::unordered_map::iterator it = m_builders.find(nodeType); - if(it == m_builders.end()) - { - //If we can't find a specific translator, use the DagNodeTranslator - it = m_builders.find("dagNode"); - } - MObject obj = it->second->createNode(from, parent, nodeType, *m_params); - setupNode(from, obj, parent, parentUnmerged); - return obj; + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg(" NodeFactory::createNode: %s of type %s\n", from.GetPrimPath().GetText(), nodeType); + std::unordered_map::iterator it + = m_builders.find(nodeType); + if (it == m_builders.end()) { + // If we can't find a specific translator, use the DagNodeTranslator + it = m_builders.find("dagNode"); + } + MObject obj = it->second->createNode(from, parent, nodeType, *m_params); + setupNode(from, obj, parent, parentUnmerged); + return obj; } //---------------------------------------------------------------------------------------------------------------------- void NodeFactory::setupNode(const UsdPrim& from, MObject obj, MObject parent, bool parentUnmerged) { - if(obj != MObject::kNullObj) - { - MFnDependencyNode fn(obj); + if (obj != MObject::kNullObj) { + MFnDependencyNode fn(obj); - MString nodeName = AL::usdmaya::utils::convert(from.GetName()); - MString newNodeName; + MString nodeName = AL::usdmaya::utils::convert(from.GetName()); + MString newNodeName; - if(obj.hasFn(MFn::kShape)) - { - if(!parentUnmerged) - { - nodeName += "Shape"; - } - // FIXME: calling mapUsdPrimToMayaNode no longer has any effect since it doesn't write to the session layer. Remove this? - // Write in the shapes parent transform node's path instead of the shape. - // This was done because we want the xform to be selected when chosen through the outliner instead of the shape. - AL::usdmaya::utils::mapUsdPrimToMayaNode(from, parent); - } - else - { - AL::usdmaya::utils::mapUsdPrimToMayaNode(from, obj); - } - newNodeName = fn.setName(nodeName); + if (obj.hasFn(MFn::kShape)) { + if (!parentUnmerged) { + nodeName += "Shape"; + } + // FIXME: calling mapUsdPrimToMayaNode no longer has any effect since it doesn't write + // to the session layer. Remove this? Write in the shapes parent transform node's path + // instead of the shape. This was done because we want the xform to be selected when + // chosen through the outliner instead of the shape. + AL::usdmaya::utils::mapUsdPrimToMayaNode(from, parent); + } else { + AL::usdmaya::utils::mapUsdPrimToMayaNode(from, obj); + } + newNodeName = fn.setName(nodeName); - // if the name has changed on import, add the original name to the node so we can keep track of this. - if(nodeName != newNodeName) - { - fileio::translators::DgNodeTranslator::addStringValue(obj, "alusd_originalName", newNodeName.asChar()); + // if the name has changed on import, add the original name to the node so we can keep track + // of this. + if (nodeName != newNodeName) { + fileio::translators::DgNodeTranslator::addStringValue( + obj, "alusd_originalName", newNodeName.asChar()); + } } - } } //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/NodeFactory.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/NodeFactory.h index 67267fcb5d..674910fe14 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/NodeFactory.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/NodeFactory.h @@ -14,9 +14,10 @@ // limitations under the License. // #pragma once +#include "AL/usdmaya/ForwardDeclares.h" + #include #include -#include "AL/usdmaya/ForwardDeclares.h" PXR_NAMESPACE_USING_DIRECTIVE @@ -31,31 +32,36 @@ namespace fileio { //---------------------------------------------------------------------------------------------------------------------- struct NodeFactory { - /// \brief ctor. Currently initialises the inbuilt translators. - NodeFactory(); + /// \brief ctor. Currently initialises the inbuilt translators. + NodeFactory(); - /// \brief dtor - ~NodeFactory(); + /// \brief dtor + ~NodeFactory(); - /// \brief create a node - /// \param from the prim we are copying the data from - /// \param nodeType can be one of "transform", "mesh", "nurbsCurve", or "camera". - /// \param parent the parent transform for the Maya data - /// \param parentUnmerged if false, the parent transform will be merged with a shape. If true, the nodes will remain - /// separate - MObject createNode(const UsdPrim& from, const char* const nodeType, MObject parent, bool parentUnmerged = false); + /// \brief create a node + /// \param from the prim we are copying the data from + /// \param nodeType can be one of "transform", "mesh", "nurbsCurve", or "camera". + /// \param parent the parent transform for the Maya data + /// \param parentUnmerged if false, the parent transform will be merged with a shape. If true, + /// the nodes will remain + /// separate + MObject createNode( + const UsdPrim& from, + const char* const nodeType, + MObject parent, + bool parentUnmerged = false); - static void setupNode(const UsdPrim& from, MObject obj, MObject parent, bool parentUnmerged); + static void setupNode(const UsdPrim& from, MObject obj, MObject parent, bool parentUnmerged); - /// \brief Some of the translators rely on import settings specified in the import params. Prior to use of this factory, - /// you should set the import params for it to use. - /// \param params the import params - void setImportParams(const ImporterParams* params) - { m_params = params; } + /// \brief Some of the translators rely on import settings specified in the import params. + /// Prior to use of this factory, + /// you should set the import params for it to use. + /// \param params the import params + void setImportParams(const ImporterParams* params) { m_params = params; } private: - std::unordered_map m_builders; - const ImporterParams* m_params; + std::unordered_map m_builders; + const ImporterParams* m_params; }; //---------------------------------------------------------------------------------------------------------------------- @@ -70,7 +76,7 @@ NodeFactory& getNodeFactory(); void freeNodeFactory(); //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/SchemaPrims.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/SchemaPrims.cpp index 41675e7b92..5e8da89dfb 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/SchemaPrims.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/SchemaPrims.cpp @@ -15,15 +15,14 @@ // #include "AL/usdmaya/fileio/SchemaPrims.h" -#include - #include +#include + namespace AL { namespace usdmaya { namespace fileio { - /// the prim typename tokens const TfToken ALSchemaType("ALType"); const TfToken ALExcludedPrimSchema("ALExcludedPrim"); @@ -33,79 +32,79 @@ const TfToken ALExcludedPrimSchema("ALExcludedPrim"); /// \param cameraNode the returned camera /// \param dagPath path to the cameras transform node //---------------------------------------------------------------------------------------------------------------------- -void huntForParentCamera(MObject& cameraNode, const MDagPath &dagPath) +void huntForParentCamera(MObject& cameraNode, const MDagPath& dagPath) { - MDagPath cameraPath = dagPath; - cameraPath.pop(); - MFnDagNode cameraXform(cameraPath); - for(uint32_t i = 0; i < cameraXform.childCount(); ++i) - { - if(cameraXform.child(i).hasFn(MFn::kCamera)) - { - cameraNode = cameraXform.child(i); - break; + MDagPath cameraPath = dagPath; + cameraPath.pop(); + MFnDagNode cameraXform(cameraPath); + for (uint32_t i = 0; i < cameraXform.childCount(); ++i) { + if (cameraXform.child(i).hasFn(MFn::kCamera)) { + cameraNode = cameraXform.child(i); + break; + } } - } } //---------------------------------------------------------------------------------------------------------------------- bool importSchemaPrim( - const UsdPrim& prim, - MObject& parent, - MObject& created, - translators::TranslatorContextPtr context, - const translators::TranslatorRefPtr torBase, + const UsdPrim& prim, + MObject& parent, + MObject& created, + translators::TranslatorContextPtr context, + const translators::TranslatorRefPtr torBase, const fileio::translators::TranslatorParameters& param) { - if(torBase) - { - if(param.forceTranslatorImport() || torBase->importableByDefault()) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("SchemaPrims::importSchemaPrim import %s\n", prim.GetPath().GetText()); - if(torBase->import(prim, parent, created) != MS::kSuccess) - { - std::cerr << "Failed to import schema prim \"" << prim.GetPath().GetText() << "\"\n"; + if (torBase) { + if (param.forceTranslatorImport() || torBase->importableByDefault()) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("SchemaPrims::importSchemaPrim import %s\n", prim.GetPath().GetText()); + if (torBase->import(prim, parent, created) != MS::kSuccess) { + std::cerr << "Failed to import schema prim \"" << prim.GetPath().GetText() + << "\"\n"; + return false; + } + } else { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "SchemaPrims::Skipping import of '%s' since it is not importable by default \n", + prim.GetPath().GetText()); + return false; + } + } else { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "SchemaPrims::importSchemaPrim Failed to find a translator for %s[%s]\n", + prim.GetPath().GetText(), + prim.GetTypeName().GetText()); return false; - } - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("SchemaPrims::Skipping import of '%s' since it is not importable by default \n", prim.GetPath().GetText()); - return false; } - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("SchemaPrims::importSchemaPrim Failed to find a translator for %s[%s]\n", prim.GetPath().GetText(), prim.GetTypeName().GetText()); - return false; - } - if(context) - context->registerItem(prim, created == MObject::kNullObj ? parent : created); - return true; + if (context) + context->registerItem(prim, created == MObject::kNullObj ? parent : created); + return true; } //---------------------------------------------------------------------------------------------------------------------- SchemaPrimsUtils::SchemaPrimsUtils(fileio::translators::TranslatorManufacture& manufacture) - : m_manufacture(manufacture) + : m_manufacture(manufacture) { } //---------------------------------------------------------------------------------------------------------------------- bool SchemaPrimsUtils::needsTransformParent(const UsdPrim& prim) { - auto translator = m_manufacture.get(prim); - return translator->needsTransformParent(); + auto translator = m_manufacture.get(prim); + return translator->needsTransformParent(); } //---------------------------------------------------------------------------------------------------------------------- fileio::translators::TranslatorRefPtr SchemaPrimsUtils::isSchemaPrim(const UsdPrim& prim) { - return m_manufacture.get(prim); + return m_manufacture.get(prim); } //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/SchemaPrims.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/SchemaPrims.h index 8958b7467d..2e2680bf43 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/SchemaPrims.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/SchemaPrims.h @@ -15,14 +15,14 @@ // #pragma once -#include - +#include "AL/maya/utils/ForwardDeclares.h" #include "AL/usdmaya/fileio/translators/TranslatorBase.h" #include "AL/usdmaya/fileio/translators/TranslatorContext.h" -#include "AL/maya/utils/ForwardDeclares.h" -#include #include +#include + +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -47,12 +47,13 @@ extern const TfToken assetType; /// \ingroup fileio //---------------------------------------------------------------------------------------------------------------------- bool importSchemaPrim( - const UsdPrim& usdPrim, - MObject& parent, - MObject& created, - translators::TranslatorContextPtr context = TfNullPtr, - const translators::TranslatorRefPtr translator = TfNullPtr, - const fileio::translators::TranslatorParameters& param = fileio::translators::TranslatorParameters()); + const UsdPrim& usdPrim, + MObject& parent, + MObject& created, + translators::TranslatorContextPtr context = TfNullPtr, + const translators::TranslatorRefPtr translator = TfNullPtr, + const fileio::translators::TranslatorParameters& param + = fileio::translators::TranslatorParameters()); //---------------------------------------------------------------------------------------------------------------------- /// \brief utility class to determine whether a usd transform chain should be created @@ -61,28 +62,26 @@ bool importSchemaPrim( class SchemaPrimsUtils { public: + /// \brief ctor + /// \param manufacture the translator registry + SchemaPrimsUtils(fileio::translators::TranslatorManufacture& manufacture); - /// \brief ctor - /// \param manufacture the translator registry - SchemaPrimsUtils(fileio::translators::TranslatorManufacture& manufacture); + /// \brief utility function to determine if a prim is one of our custom schema prims + /// \param prim the USD prim to test + /// \return the corresponding translator of the schema prim + fileio::translators::TranslatorRefPtr isSchemaPrim(const UsdPrim& prim); - /// \brief utility function to determine if a prim is one of our custom schema prims - /// \param prim the USD prim to test - /// \return the corresponding translator of the schema prim - fileio::translators::TranslatorRefPtr isSchemaPrim(const UsdPrim& prim); + /// \brief returns true if the prim specified requires a transform when importing custom nodes + /// into the maya scene \param prim the USD prim to check \return true if the prim requires a + /// parent transform on import, false otherwise + bool needsTransformParent(const UsdPrim& prim); - /// \brief returns true if the prim specified requires a transform when importing custom nodes into the maya scene - /// \param prim the USD prim to check - /// \return true if the prim requires a parent transform on import, false otherwise - bool needsTransformParent(const UsdPrim& prim); - private: - fileio::translators::TranslatorManufacture& m_manufacture; + fileio::translators::TranslatorManufacture& m_manufacture; }; - //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/TransformIterator.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/TransformIterator.cpp index 8d4cc2ba7d..beed304cca 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/TransformIterator.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/TransformIterator.cpp @@ -14,198 +14,182 @@ // limitations under the License. // #include "AL/usdmaya/fileio/TransformIterator.h" -#include "AL/usdmaya/DebugCodes.h" -#include +#include "AL/usdmaya/DebugCodes.h" #include +#include + #include namespace AL { namespace usdmaya { namespace fileio { - //---------------------------------------------------------------------------------------------------------------------- -TransformIterator::TransformIterator(UsdStageRefPtr stage, const MDagPath& parentPath, bool stopOnInstance) - : m_primStack(), - m_stage(stage), - m_stopOnInstance(stopOnInstance) +TransformIterator::TransformIterator( + UsdStageRefPtr stage, + const MDagPath& parentPath, + bool stopOnInstance) + : m_primStack() + , m_stage(stage) + , m_stopOnInstance(stopOnInstance) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TransformIterator::TransformIterator parent path: %s\n", parentPath.fullPathName().asChar()); - - m_primStack.reserve(128); - UsdPrim psuedoPrim = stage->GetPseudoRoot(); - m_primStack.push_back(StackRef(psuedoPrim)); - if(parentPath.length()) - append(parentPath.node()); - else - append(MObject::kNullObj); - next(); // skip the psuedo root. - if(parentPath.length()) - append(parentPath.node()); - else - append(MObject::kNullObj); - m_parentPath = parentPath; + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TransformIterator::TransformIterator parent path: %s\n", + parentPath.fullPathName().asChar()); + + m_primStack.reserve(128); + UsdPrim psuedoPrim = stage->GetPseudoRoot(); + m_primStack.push_back(StackRef(psuedoPrim)); + if (parentPath.length()) + append(parentPath.node()); + else + append(MObject::kNullObj); + next(); // skip the psuedo root. + if (parentPath.length()) + append(parentPath.node()); + else + append(MObject::kNullObj); + m_parentPath = parentPath; } //---------------------------------------------------------------------------------------------------------------------- -TransformIterator::TransformIterator(const UsdPrim& usdStartPrim, const MDagPath& mayaStartPath, bool stopOnInstance) - : m_primStack(), - m_stage(usdStartPrim.GetStage()), - m_stopOnInstance(stopOnInstance) +TransformIterator::TransformIterator( + const UsdPrim& usdStartPrim, + const MDagPath& mayaStartPath, + bool stopOnInstance) + : m_primStack() + , m_stage(usdStartPrim.GetStage()) + , m_stopOnInstance(stopOnInstance) { - m_primStack.reserve(128); - m_primStack.push_back(StackRef(usdStartPrim)); - append(mayaStartPath.node()); - m_parentPath = mayaStartPath; + m_primStack.reserve(128); + m_primStack.push_back(StackRef(usdStartPrim)); + append(mayaStartPath.node()); + m_parentPath = mayaStartPath; } //---------------------------------------------------------------------------------------------------------------------- MDagPath TransformIterator::currentPath() const { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TransformIterator::currentPath\n"); - MDagPath p = m_parentPath; - for(auto it = m_primStack.begin(); it != m_primStack.end(); ++it) - { - if(it->m_object != MObject::kNullObj) - { - { - MFnDagNode fn(it->m_object); - fn.getPath(p); - } + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TransformIterator::currentPath\n"); + MDagPath p = m_parentPath; + for (auto it = m_primStack.begin(); it != m_primStack.end(); ++it) { + if (it->m_object != MObject::kNullObj) { + { + MFnDagNode fn(it->m_object); + fn.getPath(p); + } + } } - } - return p; + return p; } //---------------------------------------------------------------------------------------------------------------------- -void TransformIterator::prune() -{ - m_primStack.pop_back(); -} +void TransformIterator::prune() { m_primStack.pop_back(); } //---------------------------------------------------------------------------------------------------------------------- bool TransformIterator::next() { - if(done()) - { - return false; - } - do - { - StackRef& r = *(m_primStack.end() - 1); - if(r.m_prim.IsInstance() && !m_stopOnInstance) - { - if(!m_stopOnInstance) - { - UsdPrim master = r.m_prim.GetMaster(); - m_primStack.push_back(StackRef(master)); - m_visitedMasterPrimPaths.insert(master.GetPath()); - StackRef& p = *(m_primStack.end() - 2); - StackRef& c = *(m_primStack.end() - 1); - c.m_object = p.m_object; - next(); - } - return !done(); + if (done()) { + return false; } - else - if(r.m_begin == r.m_end) - { - m_primStack.pop_back(); - if(m_primStack.empty()) - { - break; - } - - { - StackRef& b = *(m_primStack.end() - 1); - if(b.m_prim.IsInstance() && !m_stopOnInstance) - { - m_primStack.pop_back(); + do { + StackRef& r = *(m_primStack.end() - 1); + if (r.m_prim.IsInstance() && !m_stopOnInstance) { + if (!m_stopOnInstance) { + UsdPrim master = r.m_prim.GetMaster(); + m_primStack.push_back(StackRef(master)); + m_visitedMasterPrimPaths.insert(master.GetPath()); + StackRef& p = *(m_primStack.end() - 2); + StackRef& c = *(m_primStack.end() - 1); + c.m_object = p.m_object; + next(); + } + return !done(); + } else if (r.m_begin == r.m_end) { + m_primStack.pop_back(); + if (m_primStack.empty()) { + break; + } + + { + StackRef& b = *(m_primStack.end() - 1); + if (b.m_prim.IsInstance() && !m_stopOnInstance) { + m_primStack.pop_back(); + } + } + } else { + m_primStack.push_back(StackRef(*(r.m_begin++))); + return !done(); } - } - } - else - { - m_primStack.push_back(StackRef(*(r.m_begin++))); - return !done(); - } - } - while(!done()); - return !done(); + } while (!done()); + return !done(); } - //---------------------------------------------------------------------------------------------------------------------- TransformIterator::StackRef::StackRef(const UsdPrim& prim) - : m_prim(prim), - m_object(MObject::kNullObj), - m_begin(), - m_end(), - m_currentChild(-1), - m_numChildren(0) + : m_prim(prim) + , m_object(MObject::kNullObj) + , m_begin() + , m_end() + , m_currentChild(-1) + , m_numChildren(0) { - if(prim) - { - auto begin = prim.GetChildren().begin(); - m_begin = begin; - m_end = prim.GetChildren().end(); - while(begin != m_end) - { - m_numChildren++; - ++begin; + if (prim) { + auto begin = prim.GetChildren().begin(); + m_begin = begin; + m_end = prim.GetChildren().end(); + while (begin != m_end) { + m_numChildren++; + ++begin; + } + } else { + std::cout << "StackRef::StackRef initialized with null prim" << std::endl; } - } - else - { - std::cout << "StackRef::StackRef initialized with null prim" << std::endl; - } } //---------------------------------------------------------------------------------------------------------------------- TransformIterator::StackRef::StackRef(const StackRef& prim) -: m_prim(prim.m_prim), - m_object(prim.m_object), - m_begin(prim.m_begin), - m_end(prim.m_end), - m_currentChild(prim.m_currentChild), - m_numChildren(prim.m_numChildren) + : m_prim(prim.m_prim) + , m_object(prim.m_object) + , m_begin(prim.m_begin) + , m_end(prim.m_end) + , m_currentChild(prim.m_currentChild) + , m_numChildren(prim.m_numChildren) { } //---------------------------------------------------------------------------------------------------------------------- TransformIterator::StackRef::StackRef() - : m_prim(), - m_object(MObject::kNullObj), - m_begin(), - m_end(), - m_currentChild(-1), - m_numChildren(0) + : m_prim() + , m_object(MObject::kNullObj) + , m_begin() + , m_end() + , m_currentChild(-1) + , m_numChildren(0) { } //---------------------------------------------------------------------------------------------------------------------- UsdPrim TransformIterator::parentPrim() const { - UsdPrim parentPrim = m_stage->GetPseudoRoot(); - if(m_primStack.size() > 1) - { - parentPrim = (m_primStack.end() - 2)->m_prim; - if(parentPrim.IsMaster()) - { - if(m_primStack.size() > 2) - { - parentPrim = (m_primStack.end() - 3)->m_prim; - } + UsdPrim parentPrim = m_stage->GetPseudoRoot(); + if (m_primStack.size() > 1) { + parentPrim = (m_primStack.end() - 2)->m_prim; + if (parentPrim.IsMaster()) { + if (m_primStack.size() > 2) { + parentPrim = (m_primStack.end() - 3)->m_prim; + } + } } - } - return parentPrim; + return parentPrim; } //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- \ No newline at end of file diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/TransformIterator.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/TransformIterator.h index 9142c9092c..504ca064fb 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/TransformIterator.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/TransformIterator.h @@ -16,10 +16,11 @@ #pragma once #include "AL/usdmaya/Api.h" -#include #include +#include + PXR_NAMESPACE_USING_DIRECTIVE namespace AL { @@ -33,110 +34,110 @@ namespace fileio { class TransformIterator { public: - - /// \brief ctor. Initialises the iterator to the root of the stage - /// \param stage the stage to iterate over - /// \param parentPath the DAG path of the proxy shape - /// \param stopOnInstance if true, the iterator will not iterate through children of an instance - AL_USDMAYA_PUBLIC - TransformIterator(UsdStageRefPtr stage, const MDagPath& parentPath = MDagPath(), bool stopOnInstance = false); - - /// \brief ctor. Initialises the iterator to the root of the stage - /// \param startPrim a prim in a stage where the iteration should start - /// \param startMayaPath the DAG path of the proxy shape - /// \param stopOnInstance if true, the iterator will not iterate through children of an instance - AL_USDMAYA_PUBLIC - TransformIterator(const UsdPrim& startPrim, const MDagPath& startMayaPath, bool stopOnInstance = false); - - /// \brief return true if the iteration is complete - /// \return true when the iteration is complete - inline bool done() const - { return m_primStack.empty(); } - - /// \brief returns the current iteration depth - /// \return the iteration depth - inline size_t depth() const - { return m_primStack.size(); } - - /// \brief return the current prim - /// \return the current prim - inline const UsdPrim& prim() const - { return (m_primStack.end() - 1)->m_prim; } - - /// \brief return the current prim - /// \return the current prim - AL_USDMAYA_PUBLIC - UsdPrim parentPrim() const; - - /// \brief do not iterate over the children of this node - AL_USDMAYA_PUBLIC - void prune(); - - /// \brief move to the next item in the stage - /// \return true if we managed to move to the next prim, false if we have finished traversal - AL_USDMAYA_PUBLIC - bool next(); - - /// \brief in order to keep the maya path in sync with the USD prim, at each iteration step you - /// should pass in the MObject of the node in maya that mirrors your place in the USD hierarchy. - /// Without this step the current dag path will not be valid. - /// \param newNode the node to append into the stack - inline void append(const MObject newNode) + /// \brief ctor. Initialises the iterator to the root of the stage + /// \param stage the stage to iterate over + /// \param parentPath the DAG path of the proxy shape + /// \param stopOnInstance if true, the iterator will not iterate through children of an + /// instance + AL_USDMAYA_PUBLIC + TransformIterator( + UsdStageRefPtr stage, + const MDagPath& parentPath = MDagPath(), + bool stopOnInstance = false); + + /// \brief ctor. Initialises the iterator to the root of the stage + /// \param startPrim a prim in a stage where the iteration should start + /// \param startMayaPath the DAG path of the proxy shape + /// \param stopOnInstance if true, the iterator will not iterate through children of an + /// instance + AL_USDMAYA_PUBLIC + TransformIterator( + const UsdPrim& startPrim, + const MDagPath& startMayaPath, + bool stopOnInstance = false); + + /// \brief return true if the iteration is complete + /// \return true when the iteration is complete + inline bool done() const { return m_primStack.empty(); } + + /// \brief returns the current iteration depth + /// \return the iteration depth + inline size_t depth() const { return m_primStack.size(); } + + /// \brief return the current prim + /// \return the current prim + inline const UsdPrim& prim() const { return (m_primStack.end() - 1)->m_prim; } + + /// \brief return the current prim + /// \return the current prim + AL_USDMAYA_PUBLIC + UsdPrim parentPrim() const; + + /// \brief do not iterate over the children of this node + AL_USDMAYA_PUBLIC + void prune(); + + /// \brief move to the next item in the stage + /// \return true if we managed to move to the next prim, false if we have finished traversal + AL_USDMAYA_PUBLIC + bool next(); + + /// \brief in order to keep the maya path in sync with the USD prim, at each iteration step you + /// should pass in the MObject of the node in maya that mirrors your place in the USD + /// hierarchy. Without this step the current dag path will not be valid. + /// \param newNode the node to append into the stack + inline void append(const MObject newNode) { - if(!m_primStack.empty()) - m_primStack[m_primStack.size() - 1].m_object = newNode; + if (!m_primStack.empty()) + m_primStack[m_primStack.size() - 1].m_object = newNode; } - /// \brief returns the parent transform of the current node. - /// \return the MObject of the parent node, r MObject::kNullObj if no valid parent - inline MObject parent() const + /// \brief returns the parent transform of the current node. + /// \return the MObject of the parent node, r MObject::kNullObj if no valid parent + inline MObject parent() const { - if(m_primStack.size() > 1) - { - if( (m_primStack.end() - 2)->m_object != MObject::kNullObj) - { - return (m_primStack.end() - 2)->m_object; + if (m_primStack.size() > 1) { + if ((m_primStack.end() - 2)->m_object != MObject::kNullObj) { + return (m_primStack.end() - 2)->m_object; + } + if ((m_primStack.end() - 1)->m_object != MObject::kNullObj) { + return (m_primStack.end() - 1)->m_object; + } } - if( (m_primStack.end() - 1)->m_object != MObject::kNullObj) - { - return (m_primStack.end() - 1)->m_object; + if (m_primStack.size() == 1) { + return (m_primStack.end() - 1)->m_object; } - } - if(m_primStack.size() == 1) - { - return (m_primStack.end() - 1)->m_object; - } - return m_parentPath.node(); + return m_parentPath.node(); } - /// \brief returns the current maya path equivalent of the current USD prim. - /// \return the maya dag path - AL_USDMAYA_PUBLIC - MDagPath currentPath() const; + /// \brief returns the current maya path equivalent of the current USD prim. + /// \return the maya dag path + AL_USDMAYA_PUBLIC + MDagPath currentPath() const; private: - struct StackRef - { - StackRef(const UsdPrim& prim); - StackRef(const StackRef& prim); - StackRef(); - UsdPrim m_prim; - MObject m_object; - UsdPrim::SiblingIterator m_begin; - UsdPrim::SiblingIterator m_end; - int32_t m_currentChild; - int32_t m_numChildren; - }; - - std::vector m_primStack; - UsdStageRefPtr m_stage; - MDagPath m_parentPath; - TfHashSet m_visitedMasterPrimPaths; - bool m_stopOnInstance; + struct StackRef + { + StackRef(const UsdPrim& prim); + StackRef(const StackRef& prim); + StackRef(); + UsdPrim m_prim; + MObject m_object; + UsdPrim::SiblingIterator m_begin; + UsdPrim::SiblingIterator m_end; + int32_t m_currentChild; + int32_t m_numChildren; + }; + + std::vector m_primStack; + UsdStageRefPtr m_stage; + MDagPath m_parentPath; + TfHashSet m_visitedMasterPrimPaths; + bool m_stopOnInstance; }; //---------------------------------------------------------------------------------------------------------------------- -} // fileio -} // usdmaya -} // AL +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DagNodeTranslator.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DagNodeTranslator.cpp index 5c8292e276..fca761db4a 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DagNodeTranslator.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DagNodeTranslator.cpp @@ -15,21 +15,21 @@ // #include "AL/usdmaya/fileio/translators/DagNodeTranslator.h" +#include +#include +#include + #include #include #include #include #include +#include #include #include -#include #include #include -#include -#include -#include - namespace AL { namespace usdmaya { namespace fileio { @@ -41,71 +41,81 @@ MObject DagNodeTranslator::m_initialShadingGroup = MObject::kNullObj; //---------------------------------------------------------------------------------------------------------------------- MStatus DagNodeTranslator::registerType() { - const char* const errorString = "DagNodeTranslator::Unable to extract attribute for DagNodeTranslator"; - MNodeClass fn("transform"); - MStatus status; + const char* const errorString + = "DagNodeTranslator::Unable to extract attribute for DagNodeTranslator"; + MNodeClass fn("transform"); + MStatus status; - m_visible = fn.attribute("v", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_visible = fn.attribute("v", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - DagNodeTranslator::initialiseDefaultShadingGroup(m_initialShadingGroup); + DagNodeTranslator::initialiseDefaultShadingGroup(m_initialShadingGroup); - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- void DagNodeTranslator::initialiseDefaultShadingGroup(MObject& target) { - MSelectionList sl; - MGlobal::selectByName("initialShadingGroup", MGlobal::kReplaceList); - MGlobal::getActiveSelectionList(sl); + MSelectionList sl; + MGlobal::selectByName("initialShadingGroup", MGlobal::kReplaceList); + MGlobal::getActiveSelectionList(sl); - MObject shadingGroup; - sl.getDependNode(0, target); + MObject shadingGroup; + sl.getDependNode(0, target); } //---------------------------------------------------------------------------------------------------------------------- -MObject DagNodeTranslator::createNode(const UsdPrim& from, MObject parent, const char* nodeType, const ImporterParams& params) +MObject DagNodeTranslator::createNode( + const UsdPrim& from, + MObject parent, + const char* nodeType, + const ImporterParams& params) { - std::string xformError = std::string("DagNodeTranslator::createNode error creating node of type ") + nodeType - + ". Create transform instead"; - MStatus status; - MFnDagNode fn; - - MObject to = fn.create(nodeType, parent, &status); - AL_MAYA_CHECK_ERROR2(status, xformError.c_str()); - if (status!= MS::kSuccess) { - to = fn.create("transform", parent, &status); - } - AL_MAYA_CHECK_ERROR2(status, "DagNodeTranslator::createNode error creating node of type transform"); - - status = copyAttributes(from, to, params); - AL_MAYA_CHECK_ERROR_RETURN_NULL_MOBJECT(status, "DagNodeTranslator::createNode unable to copy attributes"); - - return to; + std::string xformError + = std::string("DagNodeTranslator::createNode error creating node of type ") + nodeType + + ". Create transform instead"; + MStatus status; + MFnDagNode fn; + + MObject to = fn.create(nodeType, parent, &status); + AL_MAYA_CHECK_ERROR2(status, xformError.c_str()); + if (status != MS::kSuccess) { + to = fn.create("transform", parent, &status); + } + AL_MAYA_CHECK_ERROR2( + status, "DagNodeTranslator::createNode error creating node of type transform"); + + status = copyAttributes(from, to, params); + AL_MAYA_CHECK_ERROR_RETURN_NULL_MOBJECT( + status, "DagNodeTranslator::createNode unable to copy attributes"); + + return to; } //---------------------------------------------------------------------------------------------------------------------- -MStatus DagNodeTranslator::copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params) +MStatus +DagNodeTranslator::copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params) { - AL_MAYA_CHECK_ERROR2(DgNodeTranslator::copyAttributes(from, to, params), "Errr"); + AL_MAYA_CHECK_ERROR2(DgNodeTranslator::copyAttributes(from, to, params), "Errr"); - const UsdGeomXform xformSchema(from); - return copyBool(to, m_visible, xformSchema.GetVisibilityAttr()); + const UsdGeomXform xformSchema(from); + return copyBool(to, m_visible, xformSchema.GetVisibilityAttr()); } //---------------------------------------------------------------------------------------------------------------------- MStatus DagNodeTranslator::applyDefaultMaterialOnShape(MObject shape) { - MStatus status; - MFnSet fn(m_initialShadingGroup, &status); - AL_MAYA_CHECK_ERROR(status, "DagNodeTranslator::Unable to attach MfnSet to initialShadingGroup"); - return fn.addMember(shape); + MStatus status; + MFnSet fn(m_initialShadingGroup, &status); + AL_MAYA_CHECK_ERROR( + status, "DagNodeTranslator::Unable to attach MfnSet to initialShadingGroup"); + return fn.addMember(shape); } //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DagNodeTranslator.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DagNodeTranslator.h index 16a28e991b..7d9a2e0174 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DagNodeTranslator.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DagNodeTranslator.h @@ -31,64 +31,66 @@ namespace translators { /// \brief A class to transfer dag node data between Usd <--> Maya /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -class DagNodeTranslator - : public DgNodeTranslator +class DagNodeTranslator : public DgNodeTranslator { public: + /// \brief static type registration + /// \return MS::kSuccess if ok + AL_USDMAYA_PUBLIC + static MStatus registerType(); - /// \brief static type registration - /// \return MS::kSuccess if ok - AL_USDMAYA_PUBLIC - static MStatus registerType(); + /// \brief Creates a new maya node of the given type and set attributes based on input prim + /// \param from the UsdPrim to copy the data from + /// \param parent the parent Dag node to parent the newly created object under + /// \param nodeType the maya node type to create + /// \param params the importer params that determines what will be imported + /// \return the newly created node + AL_USDMAYA_PUBLIC + MObject createNode( + const UsdPrim& from, + MObject parent, + const char* nodeType, + const ImporterParams& params) override; - /// \brief Creates a new maya node of the given type and set attributes based on input prim - /// \param from the UsdPrim to copy the data from - /// \param parent the parent Dag node to parent the newly created object under - /// \param nodeType the maya node type to create - /// \param params the importer params that determines what will be imported - /// \return the newly created node - AL_USDMAYA_PUBLIC - MObject createNode(const UsdPrim& from, MObject parent, const char* nodeType, const ImporterParams& params) override; + /// \brief helper method to copy attributes from the UsdPrim to the Maya node + /// \param from the UsdPrim to copy the data from + /// \param to the maya node to copy the data to + /// \param params the importer params to determine what to import + /// \return MS::kSuccess if ok + AL_USDMAYA_PUBLIC + MStatus copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params); - /// \brief helper method to copy attributes from the UsdPrim to the Maya node - /// \param from the UsdPrim to copy the data from - /// \param to the maya node to copy the data to - /// \param params the importer params to determine what to import - /// \return MS::kSuccess if ok - AL_USDMAYA_PUBLIC - MStatus copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params); + /// \brief Copies data from the maya node onto the usd primitive + /// \param from the maya node to copy the data from + /// \param to the USD prim to copy the attributes to + /// \param params the exporter params to determine what should be exported + /// \return MS::kSuccess if ok + static MStatus copyAttributes(const MObject& from, UsdPrim& to, const ExporterParams& params) + { + return MS::kSuccess; + } - /// \brief Copies data from the maya node onto the usd primitive - /// \param from the maya node to copy the data from - /// \param to the USD prim to copy the attributes to - /// \param params the exporter params to determine what should be exported - /// \return MS::kSuccess if ok - static MStatus copyAttributes(const MObject& from, UsdPrim& to, const ExporterParams& params) - { return MS::kSuccess; } + /// \brief assign the default material to the shape specified + /// \param shape the maya shape to assign a material to + /// \return MS::kSuccess if ok + AL_USDMAYA_PUBLIC + MStatus applyDefaultMaterialOnShape(MObject shape); - /// \brief assign the default material to the shape specified - /// \param shape the maya shape to assign a material to - /// \return MS::kSuccess if ok - AL_USDMAYA_PUBLIC - MStatus applyDefaultMaterialOnShape(MObject shape); - - AL_USDMAYA_PUBLIC - static void initialiseDefaultShadingGroup(MObject& target); + AL_USDMAYA_PUBLIC + static void initialiseDefaultShadingGroup(MObject& target); protected: - /// an MObject handle to the initial shading group, which can be assigned to newly imported geometry so that - /// default shading is applied to the shading group - static MObject m_initialShadingGroup; - - /// the visibility attribute common to all dag nodes - static MObject m_visible; - + /// an MObject handle to the initial shading group, which can be assigned to newly imported + /// geometry so that default shading is applied to the shading group + static MObject m_initialShadingGroup; + /// the visibility attribute common to all dag nodes + static MObject m_visible; }; //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DgNodeTranslator.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DgNodeTranslator.cpp index e08f4535ab..3dfcc439ce 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DgNodeTranslator.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DgNodeTranslator.cpp @@ -13,26 +13,28 @@ // See the License for the specific language governing permissions and // limitations under the License. // +#include "AL/usdmaya/fileio/translators/DgNodeTranslator.h" + #include "AL/maya/utils/NodeHelper.h" #include "AL/usdmaya/fileio/ExportParams.h" #include "AL/usdmaya/fileio/ImportParams.h" -#include "AL/usdmaya/fileio/translators/DgNodeTranslator.h" -#include -#include -#include -#include -#include +#include +#include #include -#include -#include #include -#include -#include -#include #include +#include +#include #include -#include +#include +#include +#include +#include +#include +#include + +#include #include @@ -42,56 +44,54 @@ namespace fileio { namespace translators { //---------------------------------------------------------------------------------------------------------------------- -MStatus DgNodeTranslator::registerType() -{ - return MS::kSuccess; -} +MStatus DgNodeTranslator::registerType() { return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -MObject DgNodeTranslator::createNode(const UsdPrim& from, MObject parent, const char* nodeType, const ImporterParams& params) +MObject DgNodeTranslator::createNode( + const UsdPrim& from, + MObject parent, + const char* nodeType, + const ImporterParams& params) { - MFnDependencyNode fn; - MObject to = fn.create(nodeType); + MFnDependencyNode fn; + MObject to = fn.create(nodeType); - MStatus status = copyAttributes(from, to, params); - AL_MAYA_CHECK_ERROR_RETURN_NULL_MOBJECT(status, "Dg node translator: unable to get attributes"); + MStatus status = copyAttributes(from, to, params); + AL_MAYA_CHECK_ERROR_RETURN_NULL_MOBJECT(status, "Dg node translator: unable to get attributes"); - return to; + return to; } //---------------------------------------------------------------------------------------------------------------------- -MStatus DgNodeTranslator::copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params) +MStatus +DgNodeTranslator::copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params) { - if(params.m_dynamicAttributes) - { - const std::vector attributes = from.GetAttributes(); - for(size_t i = 0; i < attributes.size(); ++i) - { - if(attributes[i].IsAuthored() && attributes[i].HasValue() && attributes[i].IsCustom()) - { - if(!attributeHandled(attributes[i])) - addDynamicAttribute(to, attributes[i]); - } + if (params.m_dynamicAttributes) { + const std::vector attributes = from.GetAttributes(); + for (size_t i = 0; i < attributes.size(); ++i) { + if (attributes[i].IsAuthored() && attributes[i].HasValue() + && attributes[i].IsCustom()) { + if (!attributeHandled(attributes[i])) + addDynamicAttribute(to, attributes[i]); + } + } } - } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -MStatus DgNodeTranslator::copyAttributes(const MObject& from, UsdPrim& to, const ExporterParams& params) +MStatus +DgNodeTranslator::copyAttributes(const MObject& from, UsdPrim& to, const ExporterParams& params) { - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -bool DgNodeTranslator::attributeHandled(const UsdAttribute& usdAttr) -{ - return false; -} +bool DgNodeTranslator::attributeHandled(const UsdAttribute& usdAttr) { return false; } //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DgNodeTranslator.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DgNodeTranslator.h index 7d0dc729eb..61f5f511b5 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DgNodeTranslator.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/DgNodeTranslator.h @@ -43,54 +43,57 @@ namespace translators { /// \brief Utility class that transfers DgNodes between Maya and USD. /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -class DgNodeTranslator - : public usdmaya::utils::DgNodeHelper +class DgNodeTranslator : public usdmaya::utils::DgNodeHelper { public: + /// \brief static type registration + /// \return MS::kSuccess if ok + AL_USDMAYA_PUBLIC + static MStatus registerType(); + /// \brief Creates a new maya node of the given type and set attributes based on input prim + /// \param from the UsdPrim to copy the data from + /// \param parent the parent Dag node to parent the newly created object under + /// \param nodeType the maya node type to create + /// \param params the importer params that determines what will be imported + /// \return the newly created node + AL_USDMAYA_PUBLIC + virtual MObject createNode( + const UsdPrim& from, + MObject parent, + const char* nodeType, + const ImporterParams& params); - /// \brief static type registration - /// \return MS::kSuccess if ok - AL_USDMAYA_PUBLIC - static MStatus registerType(); + /// \brief helper method to copy attributes from the UsdPrim to the Maya node + /// \param from the UsdPrim to copy the data from + /// \param to the maya node to copy the data to + /// \param params the importer params to determine what to import + /// \return MS::kSuccess if ok + AL_USDMAYA_PUBLIC + MStatus copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params); - /// \brief Creates a new maya node of the given type and set attributes based on input prim - /// \param from the UsdPrim to copy the data from - /// \param parent the parent Dag node to parent the newly created object under - /// \param nodeType the maya node type to create - /// \param params the importer params that determines what will be imported - /// \return the newly created node - AL_USDMAYA_PUBLIC - virtual MObject createNode(const UsdPrim& from, MObject parent, const char* nodeType, const ImporterParams& params); + /// \brief Copies data from the maya node onto the usd primitive + /// \param from the maya node to copy the data from + /// \param to the USD prim to copy the attributes to + /// \param params the exporter params to determine what should be exported + /// \return MS::kSuccess if ok + AL_USDMAYA_PUBLIC + static MStatus copyAttributes(const MObject& from, UsdPrim& to, const ExporterParams& params); - /// \brief helper method to copy attributes from the UsdPrim to the Maya node - /// \param from the UsdPrim to copy the data from - /// \param to the maya node to copy the data to - /// \param params the importer params to determine what to import - /// \return MS::kSuccess if ok - AL_USDMAYA_PUBLIC - MStatus copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params); - - /// \brief Copies data from the maya node onto the usd primitive - /// \param from the maya node to copy the data from - /// \param to the USD prim to copy the attributes to - /// \param params the exporter params to determine what should be exported - /// \return MS::kSuccess if ok - AL_USDMAYA_PUBLIC - static MStatus copyAttributes(const MObject& from, UsdPrim& to, const ExporterParams& params); - - /// \brief A temporary solution. Given a custom attribute, if a translator handles it somehow (i.e. lazy approach to - /// not creating a schema), then overload this method and return true on the attribute you are handling. - /// This will prevent the attribute from being imported/exported as a dynamic attribute. - /// \param usdAttr the attribute to test - /// \return true if your translator is handling this attr - AL_USDMAYA_PUBLIC - virtual bool attributeHandled(const UsdAttribute& usdAttr); + /// \brief A temporary solution. Given a custom attribute, if a translator handles it somehow + /// (i.e. lazy approach to + /// not creating a schema), then overload this method and return true on the attribute + /// you are handling. This will prevent the attribute from being imported/exported as a + /// dynamic attribute. + /// \param usdAttr the attribute to test + /// \return true if your translator is handling this attr + AL_USDMAYA_PUBLIC + virtual bool attributeHandled(const UsdAttribute& usdAttr); }; //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/ExtraDataPlugin.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/ExtraDataPlugin.cpp index 6488d0b2ba..ce4d783cc8 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/ExtraDataPlugin.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/ExtraDataPlugin.cpp @@ -22,14 +22,11 @@ namespace fileio { namespace translators { //---------------------------------------------------------------------------------------------------------------------- -TF_REGISTRY_FUNCTION(TfType) -{ - TfType::Define(); -} +TF_REGISTRY_FUNCTION(TfType) { TfType::Define(); } //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/ExtraDataPlugin.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/ExtraDataPlugin.h index 02e25b7581..6358c34357 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/ExtraDataPlugin.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/ExtraDataPlugin.h @@ -34,178 +34,176 @@ namespace fileio { namespace translators { //---------------------------------------------------------------------------------------------------------------------- -/// \brief This base class defines an interface to allow you to import/export extra data to/from USD prims. It works -/// alongside the core translator plugin concepts, and allows you to decorate the data of a prim being -/// imported/exported. -/// It works by associating itself with a specific MFn::Type, and if matched at export/import time, the api -/// schema translator will be called to handle its specific attributes. +/// \brief This base class defines an interface to allow you to import/export extra data to/from +/// USD prims. It works +/// alongside the core translator plugin concepts, and allows you to decorate the data of a +/// prim being imported/exported. It works by associating itself with a specific MFn::Type, +/// and if matched at export/import time, the api schema translator will be called to handle +/// its specific attributes. /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- class ExtraDataPluginAbstract - : public TfRefBase, public TfWeakBase + : public TfRefBase + , public TfWeakBase { public: - typedef ExtraDataPluginAbstract This; ///< this type - typedef TfRefPtr RefPtr; ///< the type of a reference this type - typedef TfWeakPtr Ptr; ///< weak pointer to this type - - /// \brief dtor - virtual ~ExtraDataPluginAbstract() = default; - ExtraDataPluginAbstract() = default; - - /// \brief Provides the base filter to remove Maya nodes to test for. If the plugin is intended to apply to a - /// custom maya node, then the MFn::Type returned should be the relevant MFn::kPluginFoo enum, - /// and you will also need to specify the node typename by overloading the getPluginTypeName method. - virtual MFn::Type getFnType() const - { return MFn::kInvalid; }; - - /// \brief If the plugin is to apply to a maya plugin node type, then you'll need to specify the typename - /// by overloading this method. - /// \return the maya plugin typename - virtual const char* getPluginTypeName() const - { return ""; } - - /// \brief Override this to do a one time initialization of your translator. Primarily this is to allow you to - /// extract some MObject attribute handles from an MNodeClass, to avoid the need for calling findPlug at - /// runtime (and the inherent cost of the strcmps/hash lookup that entails) - /// \return MS::kSuccess if all ok - virtual MStatus initialize() - { return MS::kSuccess; } - - /// \brief Override this method to import a prim into your scene. - /// \param prim the usd prim to be imported into maya - /// \param node the node that has been imported, on which you wish to import additionl attributes - /// \return MS::kSuccess if all ok - virtual MStatus import(const UsdPrim& prim, const MObject& node) - { return MS::kSuccess; } - - /// \brief Override this method to export additional parameters on a node already handled by another translator. - /// \param prim the USD prim to export into - /// \param node the maya node being exported. - /// \param params the exporter params - /// \return the prim created - virtual MStatus exportObject(UsdPrim& prim, const MObject& node, const ExporterParams& params) - { return MS::kSuccess; } - - /// \brief If your node needs to set up any relationships after import (for example, adding the node to a set, or - /// making attribute connections), then all of that work should be performed here. - /// \param prim the prim we are importing. - /// \return MS::kSuccess if all ok - virtual MStatus postImport(const UsdPrim& prim) - { return MS::kSuccess; } - - /// \brief This method will be called prior to the tear down process taking place. This is the last chance you have - /// to do any serialisation whilst all of the existing nodes are available to query. - /// \param prim the prim that may be modified or deleted as a result of a variant switch - /// \return MS::kSuccess if all ok - virtual MStatus preTearDown(UsdPrim& prim) - { return MS::kSuccess; } - - /// \brief override this method and return true if the translator supports update - /// \return true if your plugin supports update, false otherwise. - virtual bool supportsUpdate() const - { return true; } - - /// \brief Optionally override this method to copy the attribute values from the prim onto the Maya nodes you have - /// created. - /// \param prim the prim - /// \return MS::kSuccess if all ok - virtual MStatus update(const UsdPrim& prim) - { return MS::kSuccess; } - - /// \brief internal method - set the internal pointer to the translator context - /// \param ctx the context pointer - inline void setContext(TranslatorContextPtr ctx) - { m_context = ctx; } - - /// \brief return a pointer to the translator context - TranslatorContextPtr context() - { return m_context; } + typedef ExtraDataPluginAbstract This; ///< this type + typedef TfRefPtr RefPtr; ///< the type of a reference this type + typedef TfWeakPtr Ptr; ///< weak pointer to this type + + /// \brief dtor + virtual ~ExtraDataPluginAbstract() = default; + ExtraDataPluginAbstract() = default; + + /// \brief Provides the base filter to remove Maya nodes to test for. If the plugin is intended + /// to apply to a + /// custom maya node, then the MFn::Type returned should be the relevant MFn::kPluginFoo + /// enum, and you will also need to specify the node typename by overloading the + /// getPluginTypeName method. + virtual MFn::Type getFnType() const { return MFn::kInvalid; }; + + /// \brief If the plugin is to apply to a maya plugin node type, then you'll need to specify + /// the typename + /// by overloading this method. + /// \return the maya plugin typename + virtual const char* getPluginTypeName() const { return ""; } + + /// \brief Override this to do a one time initialization of your translator. Primarily this is + /// to allow you to + /// extract some MObject attribute handles from an MNodeClass, to avoid the need for + /// calling findPlug at runtime (and the inherent cost of the strcmps/hash lookup that + /// entails) + /// \return MS::kSuccess if all ok + virtual MStatus initialize() { return MS::kSuccess; } + + /// \brief Override this method to import a prim into your scene. + /// \param prim the usd prim to be imported into maya + /// \param node the node that has been imported, on which you wish to import additionl + /// attributes \return MS::kSuccess if all ok + virtual MStatus import(const UsdPrim& prim, const MObject& node) { return MS::kSuccess; } + + /// \brief Override this method to export additional parameters on a node already handled by + /// another translator. \param prim the USD prim to export into \param node the maya node + /// being exported. \param params the exporter params \return the prim created + virtual MStatus exportObject(UsdPrim& prim, const MObject& node, const ExporterParams& params) + { + return MS::kSuccess; + } + + /// \brief If your node needs to set up any relationships after import (for example, adding the + /// node to a set, or + /// making attribute connections), then all of that work should be performed here. + /// \param prim the prim we are importing. + /// \return MS::kSuccess if all ok + virtual MStatus postImport(const UsdPrim& prim) { return MS::kSuccess; } + + /// \brief This method will be called prior to the tear down process taking place. This is the + /// last chance you have + /// to do any serialisation whilst all of the existing nodes are available to query. + /// \param prim the prim that may be modified or deleted as a result of a variant switch + /// \return MS::kSuccess if all ok + virtual MStatus preTearDown(UsdPrim& prim) { return MS::kSuccess; } + + /// \brief override this method and return true if the translator supports update + /// \return true if your plugin supports update, false otherwise. + virtual bool supportsUpdate() const { return true; } + + /// \brief Optionally override this method to copy the attribute values from the prim onto the + /// Maya nodes you have + /// created. + /// \param prim the prim + /// \return MS::kSuccess if all ok + virtual MStatus update(const UsdPrim& prim) { return MS::kSuccess; } + + /// \brief internal method - set the internal pointer to the translator context + /// \param ctx the context pointer + inline void setContext(TranslatorContextPtr ctx) { m_context = ctx; } + + /// \brief return a pointer to the translator context + TranslatorContextPtr context() { return m_context; } private: - TranslatorContextPtr m_context; + TranslatorContextPtr m_context; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief the base class for extra data plugins +/// \brief the base class for extra data plugins /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -class ExtraDataPluginBase - : public ExtraDataPluginAbstract +class ExtraDataPluginBase : public ExtraDataPluginAbstract { public: - typedef ExtraDataPluginBase This; - typedef TfRefPtr RefPtr; + typedef ExtraDataPluginBase This; + typedef TfRefPtr RefPtr; - /// \brief dtor - virtual ~ExtraDataPluginBase() - {} + /// \brief dtor + virtual ~ExtraDataPluginBase() { } }; //---------------------------------------------------------------------------------------------------------------------- /// \brief core factory type to create an extra data plug-in translator /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -class ExtraDataPluginFactoryBase - : public TfType::FactoryBase +class ExtraDataPluginFactoryBase : public TfType::FactoryBase { public: - /// \brief overridden by the TranslatorFactory to create a new translator for a given type - /// \param ctx the current translator context - /// \return the plugin translator - AL_USDMAYA_PUBLIC - virtual TfRefPtr create(TranslatorContextPtr ctx) const = 0; + /// \brief overridden by the TranslatorFactory to create a new translator for a given type + /// \param ctx the current translator context + /// \return the plugin translator + AL_USDMAYA_PUBLIC + virtual TfRefPtr create(TranslatorContextPtr ctx) const = 0; }; - //---------------------------------------------------------------------------------------------------------------------- /// \brief core factory type to create an extra data plug-in translator /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -template -class ExtraDataPluginTranslatorFactory : public ExtraDataPluginFactoryBase +template class ExtraDataPluginTranslatorFactory : public ExtraDataPluginFactoryBase { public: - /// \brief creates a new translator for a given type T - /// \param ctx the current translator context - /// \return the plugin translator associated with type T - TfRefPtr create(TranslatorContextPtr ctx) const override - { return T::create(ctx); } + /// \brief creates a new translator for a given type T + /// \param ctx the current translator context + /// \return the plugin translator associated with type T + TfRefPtr create(TranslatorContextPtr ctx) const override + { + return T::create(ctx); + } }; //---------------------------------------------------------------------------------------------------------------------- /// \brief a macro to declare an extra data plug-in translator /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -#define AL_USDMAYA_DECLARE_EXTRA_DATA_PLUGIN(PlugClass) \ -typedef PlugClass This; \ -typedef TfRefPtr RefPtr; \ -typedef TfWeakPtr Ptr; \ -AL_MAYA_MACROS_PUBLIC \ -static RefPtr create(TranslatorContextPtr context); +#define AL_USDMAYA_DECLARE_EXTRA_DATA_PLUGIN(PlugClass) \ + typedef PlugClass This; \ + typedef TfRefPtr RefPtr; \ + typedef TfWeakPtr Ptr; \ + AL_MAYA_MACROS_PUBLIC \ + static RefPtr create(TranslatorContextPtr context); //---------------------------------------------------------------------------------------------------------------------- /// \brief a macro to define an extra data plug-in translator /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -#define AL_USDMAYA_DEFINE_EXTRA_DATA_PLUGIN(PlugClass) \ -TfRefPtr \ -PlugClass::create(TranslatorContextPtr context) { \ - TfRefPtr plugin = TfCreateRefPtr(new This()); \ - plugin->setContext(context); \ - if(!plugin->initialize()) return TfRefPtr(); \ - return plugin; \ -} \ - \ -TF_REGISTRY_FUNCTION(TfType) \ -{ \ - TfType::Define>() \ - .SetFactory>(); \ -} +#define AL_USDMAYA_DEFINE_EXTRA_DATA_PLUGIN(PlugClass) \ + TfRefPtr PlugClass::create(TranslatorContextPtr context) \ + { \ + TfRefPtr plugin = TfCreateRefPtr(new This()); \ + plugin->setContext(context); \ + if (!plugin->initialize()) \ + return TfRefPtr(); \ + return plugin; \ + } \ + \ + TF_REGISTRY_FUNCTION(TfType) \ + { \ + TfType::Define>() \ + .SetFactory>(); \ + } //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TestExtraDataPlugin.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TestExtraDataPlugin.cpp index 6fa0c71974..492a86f977 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TestExtraDataPlugin.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TestExtraDataPlugin.cpp @@ -1,8 +1,9 @@ #include "AL/usdmaya/fileio/translators/TestExtraDataPlugin.h" + +#include "AL/usdmaya/fileio/ExportParams.h" #include "AL/usdmaya/fileio/translators/TranslatorBase.h" #include "AL/usdmaya/fileio/translators/TranslatorContext.h" -#include "AL/usdmaya/fileio/ExportParams.h" namespace AL { namespace usdmaya { @@ -11,7 +12,7 @@ namespace translators { AL_USDMAYA_DEFINE_EXTRA_DATA_PLUGIN(TestExtraDataPlugin); -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TestExtraDataPlugin.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TestExtraDataPlugin.h index 0bb4bb5a6d..18f51bf1db 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TestExtraDataPlugin.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TestExtraDataPlugin.h @@ -25,8 +25,8 @@ #include #include #include -#include #include +#include #include @@ -35,81 +35,102 @@ namespace usdmaya { namespace fileio { namespace translators { -class TestExtraDataPlugin - : public ExtraDataPluginBase +class TestExtraDataPlugin : public ExtraDataPluginBase { public: - - AL_USDMAYA_DECLARE_EXTRA_DATA_PLUGIN(TestExtraDataPlugin); - - /// \brief dtor - virtual ~TestExtraDataPlugin() = default; - TestExtraDataPlugin() = default; - - /// \brief Provides the base filter to remove Maya nodes to test for the applied schema - /// for this test, just output the distance dimension - virtual MFn::Type getFnType() const - { return MFn::kDistance; } - - /// \brief Override this to do a one time initialization of your translator. Primarily this is to allow you to - /// extract some MObject attribute handles from an MNodeClass, to avoid the need for calling findPlug at - /// runtime (and the inherent cost of the strcmps/hash lookup that entails) - /// \return MS::kSuccess if all ok - MStatus initialize() - { initialiseCalled = true; return MS::kSuccess; } - - /// \brief Override this method to import a prim into your scene. - /// \param prim the usd prim to be imported into maya - /// \param node the maya node to import the data onto - /// \return MS::kSuccess if all ok - MStatus import(const UsdPrim& prim, const MObject& node) - { importCalled = true; UsdPrim(prim).CreateAttribute(TfToken("imported"), SdfValueTypeNames->Float); return MS::kSuccess; } - - /// \brief Override this method to export a Maya object into USD - /// \param prim the USD prim to store the extra data attributes - /// \param node the maya node to read the data from - /// \param params the exporter params - /// \return the prim created - MStatus exportObject(UsdPrim& prim, const MObject& node, const ExporterParams& params) - { exportObjectCalled = true; prim.CreateAttribute(TfToken("exported"), SdfValueTypeNames->Float); return MS::kSuccess; } - - /// \brief If your node needs to set up any relationships after import (for example, adding the node to a set, or - /// making attribute connections), then all of that work should be performed here. - /// \param prim the prim we are importing. - /// \return MS::kSuccess if all ok - MStatus postImport(const UsdPrim& prim) - { postImportCalled = true; return MS::kSuccess; } - - /// \brief This method will be called prior to the tear down process taking place. This is the last chance you have - /// to do any serialisation whilst all of the existing nodes are available to query. - /// \param prim the prim that may be modified or deleted as a result of a variant switch - /// \return MS::kSuccess if all ok - MStatus preTearDown(UsdPrim& prim) - { preTearDownCalled = true; return MS::kSuccess; } - - /// \brief override this method and return true if the translator supports update - /// \return true if your plugin supports update, false otherwise. - bool supportsUpdate() const - { return true; } - - /// \brief Optionally override this method to copy the attribute values from the prim onto the Maya nodes you have - /// created. - /// \param prim the prim - /// \return MS::kSuccess if all ok - MStatus update(const UsdPrim& prim) - { updateCalled = true; return MS::kSuccess; } - - bool initialiseCalled = false; - bool importCalled = false; - bool exportObjectCalled = false; - bool postImportCalled = false; - bool preTearDownCalled = false; - bool updateCalled = false; + AL_USDMAYA_DECLARE_EXTRA_DATA_PLUGIN(TestExtraDataPlugin); + + /// \brief dtor + virtual ~TestExtraDataPlugin() = default; + TestExtraDataPlugin() = default; + + /// \brief Provides the base filter to remove Maya nodes to test for the applied schema + /// for this test, just output the distance dimension + virtual MFn::Type getFnType() const { return MFn::kDistance; } + + /// \brief Override this to do a one time initialization of your translator. Primarily this is + /// to allow you to + /// extract some MObject attribute handles from an MNodeClass, to avoid the need for + /// calling findPlug at runtime (and the inherent cost of the strcmps/hash lookup that + /// entails) + /// \return MS::kSuccess if all ok + MStatus initialize() + { + initialiseCalled = true; + return MS::kSuccess; + } + + /// \brief Override this method to import a prim into your scene. + /// \param prim the usd prim to be imported into maya + /// \param node the maya node to import the data onto + /// \return MS::kSuccess if all ok + MStatus import(const UsdPrim& prim, const MObject& node) + { + importCalled = true; + UsdPrim(prim).CreateAttribute(TfToken("imported"), SdfValueTypeNames->Float); + return MS::kSuccess; + } + + /// \brief Override this method to export a Maya object into USD + /// \param prim the USD prim to store the extra data attributes + /// \param node the maya node to read the data from + /// \param params the exporter params + /// \return the prim created + MStatus exportObject(UsdPrim& prim, const MObject& node, const ExporterParams& params) + { + exportObjectCalled = true; + prim.CreateAttribute(TfToken("exported"), SdfValueTypeNames->Float); + return MS::kSuccess; + } + + /// \brief If your node needs to set up any relationships after import (for example, adding the + /// node to a set, or + /// making attribute connections), then all of that work should be performed here. + /// \param prim the prim we are importing. + /// \return MS::kSuccess if all ok + MStatus postImport(const UsdPrim& prim) + { + postImportCalled = true; + return MS::kSuccess; + } + + /// \brief This method will be called prior to the tear down process taking place. This is the + /// last chance you have + /// to do any serialisation whilst all of the existing nodes are available to query. + /// \param prim the prim that may be modified or deleted as a result of a variant switch + /// \return MS::kSuccess if all ok + MStatus preTearDown(UsdPrim& prim) + { + preTearDownCalled = true; + return MS::kSuccess; + } + + /// \brief override this method and return true if the translator supports update + /// \return true if your plugin supports update, false otherwise. + bool supportsUpdate() const { return true; } + + /// \brief Optionally override this method to copy the attribute values from the prim onto the + /// Maya nodes you have + /// created. + /// \param prim the prim + /// \return MS::kSuccess if all ok + MStatus update(const UsdPrim& prim) + { + updateCalled = true; + return MS::kSuccess; + } + + bool initialiseCalled = false; + bool importCalled = false; + bool exportObjectCalled = false; + bool postImportCalled = false; + bool preTearDownCalled = false; + bool updateCalled = false; }; //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TransformTranslator.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TransformTranslator.cpp index c7ddeff46e..5363fa9878 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TransformTranslator.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TransformTranslator.cpp @@ -14,40 +14,40 @@ // limitations under the License. // #include "AL/usdmaya/fileio/translators/TransformTranslator.h" + +#include "AL/usdmaya/fileio/AnimationTranslator.h" #include "AL/usdmaya/fileio/ExportParams.h" #include "AL/usdmaya/fileio/ImportParams.h" -#include "AL/usdmaya/fileio/AnimationTranslator.h" #include "AL/usdmaya/nodes/Transform.h" +#include "AL/usdmaya/utils/AttributeType.h" +#include "AL/usdmaya/utils/DgNodeHelper.h" +#include "AL/usdmaya/utils/Utils.h" + +#include +#include +#include -#include -#include #include +#include #include #include -#include +#include +#include #include -#include -#include #include +#include #include -#include +#include +#include +#include +#include #include -#include -#include - -#include -#include -#include -#include "AL/usdmaya/utils/AttributeType.h" -#include "AL/usdmaya/utils/DgNodeHelper.h" -#include "AL/usdmaya/utils/Utils.h" namespace AL { namespace usdmaya { namespace fileio { namespace translators { - //---------------------------------------------------------------------------------------------------------------------- MObject TransformTranslator::m_inheritsTransform = MObject::kNullObj; MObject TransformTranslator::m_scale = MObject::kNullObj; @@ -73,746 +73,800 @@ MObject TransformTranslator::m_visibility = MObject::kNullObj; //---------------------------------------------------------------------------------------------------------------------- MStatus TransformTranslator::registerType() { - const char* const errorString = "Unable to extract attribute for TransformTranslator"; - MNodeClass nc("transform"); - MStatus status; - m_rotation = nc.attribute("r", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + const char* const errorString = "Unable to extract attribute for TransformTranslator"; + MNodeClass nc("transform"); + MStatus status; + m_rotation = nc.attribute("r", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_rotationX = nc.attribute("rx", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_rotationX = nc.attribute("rx", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_rotationY = nc.attribute("ry", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_rotationY = nc.attribute("ry", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_rotationZ = nc.attribute("rz", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_rotationZ = nc.attribute("rz", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_rotateOrder = nc.attribute("ro", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_rotateOrder = nc.attribute("ro", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_rotateAxis = nc.attribute("ra", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_rotateAxis = nc.attribute("ra", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_rotateAxisX = nc.attribute("rax", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_rotateAxisX = nc.attribute("rax", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_rotateAxisY = nc.attribute("ray", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_rotateAxisY = nc.attribute("ray", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_rotateAxisZ = nc.attribute("raz", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_rotateAxisZ = nc.attribute("raz", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_rotatePivot = nc.attribute("rp", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_rotatePivot = nc.attribute("rp", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_rotatePivotTranslate = nc.attribute("rpt", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_rotatePivotTranslate = nc.attribute("rpt", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_scale = nc.attribute("s", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_scale = nc.attribute("s", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_scalePivot = nc.attribute("sp", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_scalePivot = nc.attribute("sp", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_scalePivotTranslate = nc.attribute("spt", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_scalePivotTranslate = nc.attribute("spt", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_selectHandle = nc.attribute("hdl", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_selectHandle = nc.attribute("hdl", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_shear = nc.attribute("sh", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_shear = nc.attribute("sh", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_transMinusRotatePivot = nc.attribute("tmrp", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_transMinusRotatePivot = nc.attribute("tmrp", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_translation = nc.attribute("t", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_translation = nc.attribute("t", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - m_inheritsTransform = nc.attribute("it", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + m_inheritsTransform = nc.attribute("it", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - MNodeClass dagNodeClass("dagNode"); - m_visibility = dagNodeClass.attribute("visibility", &status); - AL_MAYA_CHECK_ERROR(status, errorString); + MNodeClass dagNodeClass("dagNode"); + m_visibility = dagNodeClass.attribute("visibility", &status); + AL_MAYA_CHECK_ERROR(status, errorString); - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -MObject TransformTranslator::createNode(const UsdPrim& from, MObject parent, const char* nodeType, const ImporterParams& params) +MObject TransformTranslator::createNode( + const UsdPrim& from, + MObject parent, + const char* nodeType, + const ImporterParams& params) { - const char* const xformError = "ALUSDImport: error creating transform node"; - MStatus status; - MFnTransform fnx; - MObject obj = fnx.create(parent, &status); - AL_MAYA_CHECK_ERROR2(status, xformError); - - status = copyAttributes(from, obj, params); - AL_MAYA_CHECK_ERROR_RETURN_NULL_MOBJECT(status, "ALUSDImport: error getting transform attributes"); - return obj; + const char* const xformError = "ALUSDImport: error creating transform node"; + MStatus status; + MFnTransform fnx; + MObject obj = fnx.create(parent, &status); + AL_MAYA_CHECK_ERROR2(status, xformError); + + status = copyAttributes(from, obj, params); + AL_MAYA_CHECK_ERROR_RETURN_NULL_MOBJECT( + status, "ALUSDImport: error getting transform attributes"); + return obj; } //---------------------------------------------------------------------------------------------------------------------- MEulerRotation::RotationOrder convertRotationOrder(UsdGeomXformOp::Type type) { - switch (type) - { - case UsdGeomXformOp::TypeRotateX: - case UsdGeomXformOp::TypeRotateY: - case UsdGeomXformOp::TypeRotateZ: - case UsdGeomXformOp::TypeRotateXYZ: + switch (type) { + case UsdGeomXformOp::TypeRotateX: + case UsdGeomXformOp::TypeRotateY: + case UsdGeomXformOp::TypeRotateZ: + case UsdGeomXformOp::TypeRotateXYZ: return MEulerRotation::kXYZ; + case UsdGeomXformOp::TypeRotateXZY: return MEulerRotation::kXZY; + case UsdGeomXformOp::TypeRotateYXZ: return MEulerRotation::kYXZ; + case UsdGeomXformOp::TypeRotateYZX: return MEulerRotation::kYZX; + case UsdGeomXformOp::TypeRotateZXY: return MEulerRotation::kZXY; + case UsdGeomXformOp::TypeRotateZYX: return MEulerRotation::kZYX; + default: break; + } return MEulerRotation::kXYZ; - case UsdGeomXformOp::TypeRotateXZY: - return MEulerRotation::kXZY; - case UsdGeomXformOp::TypeRotateYXZ: - return MEulerRotation::kYXZ; - case UsdGeomXformOp::TypeRotateYZX: - return MEulerRotation::kYZX; - case UsdGeomXformOp::TypeRotateZXY: - return MEulerRotation::kZXY; - case UsdGeomXformOp::TypeRotateZYX: - return MEulerRotation::kZYX; - default: - break; - } - return MEulerRotation::kXYZ; } //---------------------------------------------------------------------------------------------------------------------- -bool TransformTranslator::getAnimationVariables(TransformOperation opIt, MObject &obj, double &conversionFactor) +bool TransformTranslator::getAnimationVariables( + TransformOperation opIt, + MObject& obj, + double& conversionFactor) { - switch(opIt) - { - case kTranslate: - { - obj = m_translation; - break; + switch (opIt) { + case kTranslate: { + obj = m_translation; + break; + } + case kRotatePivotTranslate: { + obj = m_rotatePivotTranslate; + break; } - case kRotatePivotTranslate: - { - obj = m_rotatePivotTranslate; - break; + case kRotatePivot: { + obj = m_rotatePivot; + break; } - case kRotatePivot: - { - obj = m_rotatePivot; - break; + case kRotate: { + obj = m_rotation; + MAngle one(1.0, MAngle::kDegrees); + conversionFactor = one.as(MAngle::kRadians); + break; } - case kRotate: - { - obj = m_rotation; - MAngle one(1.0, MAngle::kDegrees); - conversionFactor = one.as(MAngle::kRadians); - break; + case kRotateAxis: { + obj = m_rotateAxis; + MAngle one(1.0, MAngle::kDegrees); + conversionFactor = one.as(MAngle::kRadians); + break; } - case kRotateAxis: - { - obj = m_rotateAxis; - MAngle one(1.0, MAngle::kDegrees); - conversionFactor = one.as(MAngle::kRadians); - break; + case kScalePivotTranslate: { + obj = m_scalePivotTranslate; + break; } - case kScalePivotTranslate: - { - obj = m_scalePivotTranslate; - break; + case kScalePivot: { + obj = m_scalePivot; + break; } - case kScalePivot: - { - obj = m_scalePivot; - break; + case kShear: { + obj = m_shear; + break; } - case kShear: - { - obj = m_shear; - break; + case kScale: { + obj = m_scale; + break; } - case kScale: - { - obj = m_scale; - break; + default: { + std::cerr << "TransformTranslator::copyAnimated - Unknown transform operation" << std::endl; + return 1; } - default: - { - std::cerr << "TransformTranslator::copyAnimated - Unknown transform operation" << std::endl; - return 1; } - } - return 0; + return 0; } //---------------------------------------------------------------------------------------------------------------------- -MStatus TransformTranslator::copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params) +MStatus +TransformTranslator::copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params) { - static const UsdTimeCode usdTime = params.m_forceDefaultRead ? - UsdTimeCode::Default() : UsdTimeCode::EarliestTime(); - const char* const xformError = "ALUSDImport: error creating transform node"; - AL_MAYA_CHECK_ERROR2(DagNodeTranslator::copyAttributes(from, to, params), xformError); - - const UsdGeomXform xformSchema(from); - bool resetsXformStack = false; - std::vector xformops = xformSchema.GetOrderedXformOps(&resetsXformStack); - std::vector orderedOps(xformops.size()); - - if(matchesMayaProfile(xformops.begin(), xformops.end(), orderedOps.begin())) - { - auto opIt = orderedOps.begin(); - for(std::vector::const_iterator it = xformops.begin(), e = xformops.end(); it != e; ++it, ++opIt) - { - const UsdGeomXformOp& op = *it; - const SdfValueTypeName vtn = op.GetTypeName(); - - utils::UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); - - // Import animation (if we have time samples) - if (op.GetNumTimeSamples()) - { - if(attr_type == utils::UsdDataType::kVec3f || attr_type == utils::UsdDataType::kVec3d) - { - MObject obj; - double conversionFactor = 1.0; - getAnimationVariables(*opIt, obj, conversionFactor); - - if (obj.isNull()) - { - continue; - } - - if (*opIt == kRotate) - { - // Set the rotate order - AL_MAYA_CHECK_ERROR2(setInt32(to, m_rotateOrder, uint32_t(convertRotationOrder(op.GetOpType()))), xformError); - } - if (attr_type == utils::UsdDataType::kVec3f) - { - AL_MAYA_CHECK_ERROR2(setVec3Anim(to, obj, op, conversionFactor, ¶ms.m_newAnimCurves), xformError); - } - else - { - AL_MAYA_CHECK_ERROR2(setVec3Anim(to, obj, op, conversionFactor, ¶ms.m_newAnimCurves), xformError); - } - } - else if(attr_type == utils::UsdDataType::kFloat) - { - MObject attr; - switch(*opIt) - { - case kRotate: - { - switch(op.GetOpType()) - { - case UsdGeomXformOp::TypeRotateX: attr = m_rotationX; break; - case UsdGeomXformOp::TypeRotateY: attr = m_rotationY; break; - case UsdGeomXformOp::TypeRotateZ: attr = m_rotationZ; break; - default: break; - } - break; - } - case kRotateAxis: - { - switch(op.GetOpType()) - { - case UsdGeomXformOp::TypeRotateX: attr = m_rotateAxisX; break; - case UsdGeomXformOp::TypeRotateY: attr = m_rotateAxisY; break; - case UsdGeomXformOp::TypeRotateZ: attr = m_rotateAxisZ; break; - default: break; - } - break; + static const UsdTimeCode usdTime + = params.m_forceDefaultRead ? UsdTimeCode::Default() : UsdTimeCode::EarliestTime(); + const char* const xformError = "ALUSDImport: error creating transform node"; + AL_MAYA_CHECK_ERROR2(DagNodeTranslator::copyAttributes(from, to, params), xformError); + + const UsdGeomXform xformSchema(from); + bool resetsXformStack = false; + std::vector xformops = xformSchema.GetOrderedXformOps(&resetsXformStack); + std::vector orderedOps(xformops.size()); + + if (matchesMayaProfile(xformops.begin(), xformops.end(), orderedOps.begin())) { + auto opIt = orderedOps.begin(); + for (std::vector::const_iterator it = xformops.begin(), e = xformops.end(); + it != e; + ++it, ++opIt) { + const UsdGeomXformOp& op = *it; + const SdfValueTypeName vtn = op.GetTypeName(); + + utils::UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); + + // Import animation (if we have time samples) + if (op.GetNumTimeSamples()) { + if (attr_type == utils::UsdDataType::kVec3f + || attr_type == utils::UsdDataType::kVec3d) { + MObject obj; + double conversionFactor = 1.0; + getAnimationVariables(*opIt, obj, conversionFactor); + + if (obj.isNull()) { + continue; + } + + if (*opIt == kRotate) { + // Set the rotate order + AL_MAYA_CHECK_ERROR2( + setInt32( + to, m_rotateOrder, uint32_t(convertRotationOrder(op.GetOpType()))), + xformError); + } + if (attr_type == utils::UsdDataType::kVec3f) { + AL_MAYA_CHECK_ERROR2( + setVec3Anim( + to, obj, op, conversionFactor, ¶ms.m_newAnimCurves), + xformError); + } else { + AL_MAYA_CHECK_ERROR2( + setVec3Anim( + to, obj, op, conversionFactor, ¶ms.m_newAnimCurves), + xformError); + } + } else if (attr_type == utils::UsdDataType::kFloat) { + MObject attr; + switch (*opIt) { + case kRotate: { + switch (op.GetOpType()) { + case UsdGeomXformOp::TypeRotateX: attr = m_rotationX; break; + case UsdGeomXformOp::TypeRotateY: attr = m_rotationY; break; + case UsdGeomXformOp::TypeRotateZ: attr = m_rotationZ; break; + default: break; + } + break; + } + case kRotateAxis: { + switch (op.GetOpType()) { + case UsdGeomXformOp::TypeRotateX: attr = m_rotateAxisX; break; + case UsdGeomXformOp::TypeRotateY: attr = m_rotateAxisY; break; + case UsdGeomXformOp::TypeRotateZ: attr = m_rotateAxisZ; break; + default: break; + } + break; + } + default: break; + } + + if (!attr.isNull()) { + setAngleAnim(to, attr, op, ¶ms.m_newAnimCurves); + } + } else if (attr_type == utils::UsdDataType::kMatrix4d) { + if (*opIt == kShear) { + std::cerr << "[TransformTranslator::copyAttributes] Error: Animated shear " + "not currently supported" + << std::endl; + } + } + + continue; } - default: break; - } - - if (!attr.isNull()) - { - setAngleAnim(to, attr, op, ¶ms.m_newAnimCurves); - } - } - else if(attr_type == utils::UsdDataType::kMatrix4d) - { - if(*opIt == kShear) - { - std::cerr << "[TransformTranslator::copyAttributes] Error: Animated shear not currently supported" << std::endl; - } - } - - continue; - - } - - // Else if static - const float degToRad = 3.141592654f / 180.0f; - if(attr_type == utils::UsdDataType::kVec3f) - { - GfVec3f value(0); + // Else if static + const float degToRad = 3.141592654f / 180.0f; + + if (attr_type == utils::UsdDataType::kVec3f) { + GfVec3f value(0); + + const bool retValue = op.GetAs(&value, usdTime); + if (!retValue) { + continue; + } + + switch (*opIt) { + case kTranslate: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_translation, value[0], value[1], value[2]), xformError); + break; + case kRotatePivotTranslate: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_rotatePivotTranslate, value[0], value[1], value[2]), + xformError); + break; + case kRotatePivot: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_rotatePivot, value[0], value[1], value[2]), xformError); + break; + case kRotate: { + AL_MAYA_CHECK_ERROR2( + setInt32(to, m_rotateOrder, uint32_t(convertRotationOrder(op.GetOpType()))), + xformError); + AL_MAYA_CHECK_ERROR2( + setVec3( + to, + m_rotation, + MAngle(value[0], MAngle::kDegrees), + MAngle(value[1], MAngle::kDegrees), + MAngle(value[2], MAngle::kDegrees)), + xformError); + } break; + case kRotateAxis: + AL_MAYA_CHECK_ERROR2( + setVec3( + to, + m_rotateAxis, + value[0] * degToRad, + value[1] * degToRad, + value[2] * degToRad), + xformError); + break; + case kScalePivotTranslate: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_scalePivotTranslate, value[0], value[1], value[2]), + xformError); + break; + case kScalePivot: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_scalePivot, value[0], value[1], value[2]), xformError); + break; + case kShear: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_shear, value[0], value[1], value[2]), xformError); + break; + case kScale: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_scale, value[0], value[1], value[2]), xformError); + break; - const bool retValue = op.GetAs(&value, usdTime); - if (!retValue) - { - continue; - } + default: break; + } + } else if (attr_type == utils::UsdDataType::kVec3d) { + GfVec3d value(0); + + const bool retValue = op.GetAs(&value, usdTime); + if (!retValue) { + continue; + } + + switch (*opIt) { + case kTranslate: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_translation, value[0], value[1], value[2]), xformError); + break; + case kRotatePivotTranslate: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_rotatePivotTranslate, value[0], value[1], value[2]), + xformError); + break; + case kRotatePivot: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_rotatePivot, value[0], value[1], value[2]), xformError); + break; + case kRotate: { + AL_MAYA_CHECK_ERROR2( + setInt32(to, m_rotateOrder, uint32_t(convertRotationOrder(op.GetOpType()))), + xformError); + AL_MAYA_CHECK_ERROR2( + setVec3( + to, + m_rotation, + MAngle(value[0], MAngle::kDegrees), + MAngle(value[1], MAngle::kDegrees), + MAngle(value[2], MAngle::kDegrees)), + xformError); + } break; + case kRotateAxis: + AL_MAYA_CHECK_ERROR2( + setVec3( + to, + m_rotateAxis, + value[0] * degToRad, + value[1] * degToRad, + value[2] * degToRad), + xformError); + break; + case kScalePivotTranslate: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_scalePivotTranslate, value[0], value[1], value[2]), + xformError); + break; + case kScalePivot: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_scalePivot, value[0], value[1], value[2]), xformError); + break; + case kShear: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_shear, value[0], value[1], value[2]), xformError); + break; + case kScale: + AL_MAYA_CHECK_ERROR2( + setVec3(to, m_scale, value[0], value[1], value[2]), xformError); + break; - switch(*opIt) - { - case kTranslate: AL_MAYA_CHECK_ERROR2(setVec3(to, m_translation, value[0], value[1], value[2]), xformError); break; - case kRotatePivotTranslate: AL_MAYA_CHECK_ERROR2(setVec3(to, m_rotatePivotTranslate, value[0], value[1], value[2]), xformError); break; - case kRotatePivot: AL_MAYA_CHECK_ERROR2(setVec3(to, m_rotatePivot, value[0], value[1], value[2]), xformError); break; - case kRotate: - { - AL_MAYA_CHECK_ERROR2(setInt32(to, m_rotateOrder, uint32_t(convertRotationOrder(op.GetOpType()))), xformError); - AL_MAYA_CHECK_ERROR2(setVec3(to, m_rotation, - MAngle(value[0], MAngle::kDegrees), - MAngle(value[1], MAngle::kDegrees), - MAngle(value[2], MAngle::kDegrees)), xformError); - } - break; - case kRotateAxis: AL_MAYA_CHECK_ERROR2(setVec3(to, m_rotateAxis, value[0] * degToRad, value[1] * degToRad, value[2] * degToRad), xformError); break; - case kScalePivotTranslate: AL_MAYA_CHECK_ERROR2(setVec3(to, m_scalePivotTranslate, value[0], value[1], value[2]), xformError); break; - case kScalePivot: AL_MAYA_CHECK_ERROR2(setVec3(to, m_scalePivot, value[0], value[1], value[2]), xformError); break; - case kShear: AL_MAYA_CHECK_ERROR2(setVec3(to, m_shear, value[0], value[1], value[2]), xformError); break; - case kScale: AL_MAYA_CHECK_ERROR2(setVec3(to, m_scale, value[0], value[1], value[2]), xformError); break; - - default: - break; - } - } - else - if(attr_type == utils::UsdDataType::kVec3d) - { - GfVec3d value(0); - - const bool retValue = op.GetAs(&value, usdTime); - if (!retValue) - { - continue; - } + default: break; + } + } else if (attr_type == utils::UsdDataType::kFloat) { + float value = 0; + + const bool retValue = op.GetAs(&value, usdTime); + if (!retValue) { + continue; + } + + switch (*opIt) { + case kRotate: { + switch (op.GetOpType()) { + case UsdGeomXformOp::TypeRotateX: + AL_MAYA_CHECK_ERROR2( + setAngle(to, m_rotationX, MAngle(value, MAngle::kDegrees)), xformError); + break; + + case UsdGeomXformOp::TypeRotateY: + AL_MAYA_CHECK_ERROR2( + setAngle(to, m_rotationY, MAngle(value, MAngle::kDegrees)), xformError); + break; + + case UsdGeomXformOp::TypeRotateZ: + AL_MAYA_CHECK_ERROR2( + setAngle(to, m_rotationZ, MAngle(value, MAngle::kDegrees)), xformError); + break; + + default: break; + } + } break; + + case kRotateAxis: { + switch (op.GetOpType()) { + case UsdGeomXformOp::TypeRotateX: + AL_MAYA_CHECK_ERROR2( + setAngle(to, m_rotateAxisX, MAngle(value, MAngle::kDegrees)), + xformError); + break; + + case UsdGeomXformOp::TypeRotateY: + AL_MAYA_CHECK_ERROR2( + setAngle(to, m_rotateAxisY, MAngle(value, MAngle::kDegrees)), + xformError); + break; + + case UsdGeomXformOp::TypeRotateZ: + AL_MAYA_CHECK_ERROR2( + setAngle(to, m_rotateAxisZ, MAngle(value, MAngle::kDegrees)), + xformError); + break; + + default: break; + } + } break; - switch(*opIt) - { - case kTranslate: AL_MAYA_CHECK_ERROR2(setVec3(to, m_translation, value[0], value[1], value[2]), xformError); break; - case kRotatePivotTranslate: AL_MAYA_CHECK_ERROR2(setVec3(to, m_rotatePivotTranslate, value[0], value[1], value[2]), xformError); break; - case kRotatePivot: AL_MAYA_CHECK_ERROR2(setVec3(to, m_rotatePivot, value[0], value[1], value[2]), xformError); break; - case kRotate: - { - AL_MAYA_CHECK_ERROR2(setInt32(to, m_rotateOrder, uint32_t(convertRotationOrder(op.GetOpType()))), xformError); - AL_MAYA_CHECK_ERROR2(setVec3(to, m_rotation, - MAngle(value[0], MAngle::kDegrees), - MAngle(value[1], MAngle::kDegrees), - MAngle(value[2], MAngle::kDegrees)), xformError); - } - break; - case kRotateAxis: AL_MAYA_CHECK_ERROR2(setVec3(to, m_rotateAxis, value[0] * degToRad, value[1] * degToRad, value[2] * degToRad), xformError); break; - case kScalePivotTranslate: AL_MAYA_CHECK_ERROR2(setVec3(to, m_scalePivotTranslate, value[0], value[1], value[2]), xformError); break; - case kScalePivot: AL_MAYA_CHECK_ERROR2(setVec3(to, m_scalePivot, value[0], value[1], value[2]), xformError); break; - case kShear: AL_MAYA_CHECK_ERROR2(setVec3(to, m_shear, value[0], value[1], value[2]), xformError); break; - case kScale: AL_MAYA_CHECK_ERROR2(setVec3(to, m_scale, value[0], value[1], value[2]), xformError); break; - - default: - break; - } - } - else - if(attr_type == utils::UsdDataType::kFloat) - { - float value = 0; - - const bool retValue = op.GetAs(&value, usdTime); - if (!retValue) - { - continue; + default: break; + } + } else if (attr_type == utils::UsdDataType::kMatrix4d) { + if (*opIt == kShear) { + GfMatrix4d value; + const bool retValue = op.GetAs(&value, usdTime); + if (!retValue) { + continue; + } + + const float shearX = value[1][0]; + const float shearY = value[2][0]; + const float shearZ = value[2][1]; + AL_MAYA_CHECK_ERROR2(setVec3(to, m_shear, shearX, shearY, shearZ), xformError); + } + } } + } else { + bool resetsXformStack = false; + GfMatrix4d value; + xformSchema.GetLocalTransformation(&value, &resetsXformStack, usdTime); + + double S[3], T[3]; + MEulerRotation R; + AL::usdmaya::utils::matrixToSRT(value, S, R, T); + MVector rotVector = R.asVector(); + AL_MAYA_CHECK_ERROR2( + setAngle(to, m_rotationX, MAngle(rotVector.x, MAngle::kRadians)), xformError); + AL_MAYA_CHECK_ERROR2( + setAngle(to, m_rotationY, MAngle(rotVector.y, MAngle::kRadians)), xformError); + AL_MAYA_CHECK_ERROR2( + setAngle(to, m_rotationZ, MAngle(rotVector.z, MAngle::kRadians)), xformError); + AL_MAYA_CHECK_ERROR2(setVec3(to, m_translation, T[0], T[1], T[2]), xformError); + AL_MAYA_CHECK_ERROR2(setVec3(to, m_scale, S[0], S[1], S[2]), xformError); + } - switch(*opIt) - { - case kRotate: - { - switch(op.GetOpType()) - { - case UsdGeomXformOp::TypeRotateX: - AL_MAYA_CHECK_ERROR2(setAngle(to, m_rotationX, MAngle(value, MAngle::kDegrees)), xformError); - break; - - case UsdGeomXformOp::TypeRotateY: - AL_MAYA_CHECK_ERROR2(setAngle(to, m_rotationY, MAngle(value, MAngle::kDegrees)), xformError); - break; - - case UsdGeomXformOp::TypeRotateZ: - AL_MAYA_CHECK_ERROR2(setAngle(to, m_rotationZ, MAngle(value, MAngle::kDegrees)), xformError); - break; - - default: - break; - } - } - break; - - case kRotateAxis: - { - switch(op.GetOpType()) - { - case UsdGeomXformOp::TypeRotateX: - AL_MAYA_CHECK_ERROR2(setAngle(to, m_rotateAxisX, MAngle(value, MAngle::kDegrees)), xformError); - break; - - case UsdGeomXformOp::TypeRotateY: - AL_MAYA_CHECK_ERROR2(setAngle(to, m_rotateAxisY, MAngle(value, MAngle::kDegrees)), xformError); - break; - - case UsdGeomXformOp::TypeRotateZ: - AL_MAYA_CHECK_ERROR2(setAngle(to, m_rotateAxisZ, MAngle(value, MAngle::kDegrees)), xformError); - break; - - default: - break; - } - } - break; + AL_MAYA_CHECK_ERROR2(setBool(to, m_inheritsTransform, !resetsXformStack), xformError); - default: - break; - } - } - else - if(attr_type == utils::UsdDataType::kMatrix4d) - { - if(*opIt == kShear) - { - GfMatrix4d value; - const bool retValue = op.GetAs(&value, usdTime); - if(!retValue) - { - continue; - } - - const float shearX = value[1][0]; - const float shearY = value[2][0]; - const float shearZ = value[2][1]; - AL_MAYA_CHECK_ERROR2(setVec3(to, m_shear, shearX, shearY, shearZ), xformError); - } - } + processMetaData(from, to, params); + if (UsdAttribute myAttr = from.GetAttribute(UsdGeomTokens->visibility)) { + DgNodeHelper::setVisAttrAnim(to, m_visibility, myAttr, ¶ms.m_newAnimCurves); } - } - else - { - bool resetsXformStack = false; - GfMatrix4d value; - xformSchema.GetLocalTransformation(&value, &resetsXformStack, usdTime); - - double S[3], T[3]; - MEulerRotation R; - AL::usdmaya::utils::matrixToSRT(value, S, R, T); - MVector rotVector = R.asVector(); - AL_MAYA_CHECK_ERROR2(setAngle(to, m_rotationX, MAngle(rotVector.x, MAngle::kRadians)), xformError); - AL_MAYA_CHECK_ERROR2(setAngle(to, m_rotationY, MAngle(rotVector.y, MAngle::kRadians)), xformError); - AL_MAYA_CHECK_ERROR2(setAngle(to, m_rotationZ, MAngle(rotVector.z, MAngle::kRadians)), xformError); - AL_MAYA_CHECK_ERROR2(setVec3(to, m_translation, T[0], T[1], T[2]), xformError); - AL_MAYA_CHECK_ERROR2(setVec3(to, m_scale, S[0], S[1], S[2]), xformError); - } - - AL_MAYA_CHECK_ERROR2(setBool(to, m_inheritsTransform, !resetsXformStack), xformError); - - processMetaData(from, to, params); - if (UsdAttribute myAttr = from.GetAttribute(UsdGeomTokens->visibility)) - { - DgNodeHelper::setVisAttrAnim(to, m_visibility, myAttr, ¶ms.m_newAnimCurves); - } - - return MS::kSuccess; + + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -MStatus TransformTranslator::processMetaData(const UsdPrim& from, MObject& to, const ImporterParams& params) +MStatus +TransformTranslator::processMetaData(const UsdPrim& from, MObject& to, const ImporterParams& params) { - UsdMetadataValueMap map = from.GetAllAuthoredMetadata(); - auto it = map.begin(); - auto end = map.end(); - for(; it != end; ++it) - { - //const TfToken& token = it->first; - //const VtValue& value = it->second; - //const TfType& type = value.GetType(); - } - return MS::kSuccess; + UsdMetadataValueMap map = from.GetAllAuthoredMetadata(); + auto it = map.begin(); + auto end = map.end(); + for (; it != end; ++it) { + // const TfToken& token = it->first; + // const VtValue& value = it->second; + // const TfType& type = value.GetType(); + } + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- bool animationCheck(AnimationTranslator* animTranslator, MPlug plug) { - if(!animTranslator) return false; - return animTranslator->isAnimated(plug, true); + if (!animTranslator) + return false; + return animTranslator->isAnimated(plug, true); } //---------------------------------------------------------------------------------------------------------------------- UsdAttribute addTranslateOp( const UsdGeomXformable& xformSchema, - const char* attrName, - const GfVec3f& currentValue, - const UsdTimeCode& time) + const char* attrName, + const GfVec3f& currentValue, + const UsdTimeCode& time) { - UsdGeomXformOp op = xformSchema.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken(attrName)); - op.Set(currentValue, time); - return op.GetAttr(); + UsdGeomXformOp op + = xformSchema.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken(attrName)); + op.Set(currentValue, time); + return op.GetAttr(); } //---------------------------------------------------------------------------------------------------------------------- -UsdAttribute addInverseTranslateOp( - const UsdGeomXformable& xformSchema, - const char* attrName) +UsdAttribute addInverseTranslateOp(const UsdGeomXformable& xformSchema, const char* attrName) { - UsdGeomXformOp op = xformSchema.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken(attrName), true); - return op.GetAttr(); + UsdGeomXformOp op + = xformSchema.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken(attrName), true); + return op.GetAttr(); } //---------------------------------------------------------------------------------------------------------------------- UsdAttribute addTranslateOp( const UsdGeomXformable& xformSchema, - const char* attrName, - const GfVec3d& currentValue, - const UsdTimeCode& time) + const char* attrName, + const GfVec3d& currentValue, + const UsdTimeCode& time) { - UsdGeomXformOp op = xformSchema.AddTranslateOp(UsdGeomXformOp::PrecisionDouble, TfToken(attrName)); - op.Set(currentValue, time); - return op.GetAttr(); + UsdGeomXformOp op + = xformSchema.AddTranslateOp(UsdGeomXformOp::PrecisionDouble, TfToken(attrName)); + op.Set(currentValue, time); + return op.GetAttr(); } //---------------------------------------------------------------------------------------------------------------------- UsdAttribute addRotateOp( - const UsdGeomXform &xformSchema, - const char *attrName, - const int32_t& rotateOrder, - const GfVec3f& rotation, - const UsdTimeCode& time) + const UsdGeomXform& xformSchema, + const char* attrName, + const int32_t& rotateOrder, + const GfVec3f& rotation, + const UsdTimeCode& time) { - TfToken rotateToken(attrName); - UsdGeomXformOp op; - switch(rotateOrder) - { - case MEulerRotation::kXYZ: - op = xformSchema.AddRotateXYZOp(UsdGeomXformOp::PrecisionFloat, rotateToken); - break; - - case MEulerRotation::kXZY: - op = xformSchema.AddRotateXZYOp(UsdGeomXformOp::PrecisionFloat, rotateToken); - break; - - case MEulerRotation::kYXZ: - op = xformSchema.AddRotateYXZOp(UsdGeomXformOp::PrecisionFloat, rotateToken); - break; - - case MEulerRotation::kYZX: - op = xformSchema.AddRotateYZXOp(UsdGeomXformOp::PrecisionFloat, rotateToken); - break; - - case MEulerRotation::kZXY: - op = xformSchema.AddRotateZXYOp(UsdGeomXformOp::PrecisionFloat, rotateToken); - break; - - case MEulerRotation::kZYX: - op = xformSchema.AddRotateZYXOp(UsdGeomXformOp::PrecisionFloat, rotateToken); - break; - - default: - break; - } - op.Set(rotation, time); - return op.GetAttr(); + TfToken rotateToken(attrName); + UsdGeomXformOp op; + switch (rotateOrder) { + case MEulerRotation::kXYZ: + op = xformSchema.AddRotateXYZOp(UsdGeomXformOp::PrecisionFloat, rotateToken); + break; + + case MEulerRotation::kXZY: + op = xformSchema.AddRotateXZYOp(UsdGeomXformOp::PrecisionFloat, rotateToken); + break; + + case MEulerRotation::kYXZ: + op = xformSchema.AddRotateYXZOp(UsdGeomXformOp::PrecisionFloat, rotateToken); + break; + + case MEulerRotation::kYZX: + op = xformSchema.AddRotateYZXOp(UsdGeomXformOp::PrecisionFloat, rotateToken); + break; + + case MEulerRotation::kZXY: + op = xformSchema.AddRotateZXYOp(UsdGeomXformOp::PrecisionFloat, rotateToken); + break; + + case MEulerRotation::kZYX: + op = xformSchema.AddRotateZYXOp(UsdGeomXformOp::PrecisionFloat, rotateToken); + break; + + default: break; + } + op.Set(rotation, time); + return op.GetAttr(); } //---------------------------------------------------------------------------------------------------------------------- -MStatus TransformTranslator::copyAttributes(const MObject& from, UsdPrim& to, const ExporterParams& params, const MDagPath& path) +MStatus TransformTranslator::copyAttributes( + const MObject& from, + UsdPrim& to, + const ExporterParams& params, + const MDagPath& path) { - UsdGeomXform xformSchema(to); - GfVec3f scale; - GfVec3f shear; - GfVec3f rotation; - int32_t rotateOrder; - GfVec3f rotateAxis; - GfVec3d translation; - GfVec3f scalePivot; - GfVec3f rotatePivot; - GfVec3f scalePivotTranslate; - GfVec3f rotatePivotTranslate; - bool inheritsTransform; - bool visible; - - static const GfVec3f defaultScale(1.0f); - static const GfVec3f defaultShear(0.0f); - static const GfVec3f defaultRotation(0.0f); - static const GfVec3f defaultRotateAxis(0.0f); - static const GfVec3d defaultTranslation(0.0f); - static const GfVec3f defaultScalePivot(0.0f); - static const GfVec3f defaultRotatePivot(0.0f); - static const GfVec3f defaultScalePivotTranslate(0.0f); - static const GfVec3f defaultRotatePivotTranslate(0.0f); - static const bool defaultVisible(true); - - const float radToDeg = 57.295779506f; - AnimationTranslator* animTranslator = params.m_animTranslator; - - // Check if transform attributes are considered animated, - // if true, we consider translation, rotation, rotateOrder and scale attributes are animated: - bool transformAnimated = false; - if(params.m_extensiveAnimationCheck) - { - transformAnimated = animTranslator->isAnimatedTransform(from); - } - - if(!params.m_exportInWorldSpace) - { - getBool(from, m_inheritsTransform, inheritsTransform); - getBool(from, m_visible, visible); - getVec3(from, m_scale, (float*)&scale); - getVec3(from, m_shear, (float*)&shear); - getVec3(from, m_rotation, (float*)&rotation); - getInt32(from, m_rotateOrder, rotateOrder); - getVec3(from, m_rotateAxis, (float*)&rotateAxis); - getVec3(from, m_translation, (double*)&translation); - getVec3(from, m_scalePivot, (float*)&scalePivot); - getVec3(from, m_rotatePivot, (float*)&rotatePivot); - getVec3(from, m_scalePivotTranslate, (float*)&scalePivotTranslate); - getVec3(from, m_rotatePivotTranslate, (float*)&rotatePivotTranslate); - - // For insurance, we will make sure there aren't any ordered ops before we start - xformSchema.ClearXformOpOrder(); - - // This adds an op to the stack so we should do it after ClearXformOpOrder(): - xformSchema.SetResetXformStack(!inheritsTransform); - - bool plugAnimated = animationCheck(animTranslator, MPlug(from, m_visible)); - if (plugAnimated || visible != defaultVisible) - { - UsdAttribute visibleAttr = xformSchema.GetVisibilityAttr(); - - if (plugAnimated && animTranslator) - { - animTranslator->forceAddTransformPlug(MPlug(from, m_visible), visibleAttr); - } - else - { - visibleAttr.Set(visible ? UsdGeomTokens->inherited : UsdGeomTokens->invisible); - } + UsdGeomXform xformSchema(to); + GfVec3f scale; + GfVec3f shear; + GfVec3f rotation; + int32_t rotateOrder; + GfVec3f rotateAxis; + GfVec3d translation; + GfVec3f scalePivot; + GfVec3f rotatePivot; + GfVec3f scalePivotTranslate; + GfVec3f rotatePivotTranslate; + bool inheritsTransform; + bool visible; + + static const GfVec3f defaultScale(1.0f); + static const GfVec3f defaultShear(0.0f); + static const GfVec3f defaultRotation(0.0f); + static const GfVec3f defaultRotateAxis(0.0f); + static const GfVec3d defaultTranslation(0.0f); + static const GfVec3f defaultScalePivot(0.0f); + static const GfVec3f defaultRotatePivot(0.0f); + static const GfVec3f defaultScalePivotTranslate(0.0f); + static const GfVec3f defaultRotatePivotTranslate(0.0f); + static const bool defaultVisible(true); + + const float radToDeg = 57.295779506f; + AnimationTranslator* animTranslator = params.m_animTranslator; + + // Check if transform attributes are considered animated, + // if true, we consider translation, rotation, rotateOrder and scale attributes are animated: + bool transformAnimated = false; + if (params.m_extensiveAnimationCheck) { + transformAnimated = animTranslator->isAnimatedTransform(from); } - plugAnimated = transformAnimated || animationCheck(animTranslator, MPlug(from, m_translation)); - if(plugAnimated || translation != defaultTranslation) - { - UsdAttribute translateAttr = addTranslateOp(xformSchema, "", translation, params.m_timeCode); - if(plugAnimated && animTranslator) animTranslator->forceAddPlug(MPlug(from, m_translation), translateAttr); - } + if (!params.m_exportInWorldSpace) { + getBool(from, m_inheritsTransform, inheritsTransform); + getBool(from, m_visible, visible); + getVec3(from, m_scale, (float*)&scale); + getVec3(from, m_shear, (float*)&shear); + getVec3(from, m_rotation, (float*)&rotation); + getInt32(from, m_rotateOrder, rotateOrder); + getVec3(from, m_rotateAxis, (float*)&rotateAxis); + getVec3(from, m_translation, (double*)&translation); + getVec3(from, m_scalePivot, (float*)&scalePivot); + getVec3(from, m_rotatePivot, (float*)&rotatePivot); + getVec3(from, m_scalePivotTranslate, (float*)&scalePivotTranslate); + getVec3(from, m_rotatePivotTranslate, (float*)&rotatePivotTranslate); + + // For insurance, we will make sure there aren't any ordered ops before we start + xformSchema.ClearXformOpOrder(); + + // This adds an op to the stack so we should do it after ClearXformOpOrder(): + xformSchema.SetResetXformStack(!inheritsTransform); + + bool plugAnimated = animationCheck(animTranslator, MPlug(from, m_visible)); + if (plugAnimated || visible != defaultVisible) { + UsdAttribute visibleAttr = xformSchema.GetVisibilityAttr(); + + if (plugAnimated && animTranslator) { + animTranslator->forceAddTransformPlug(MPlug(from, m_visible), visibleAttr); + } else { + visibleAttr.Set(visible ? UsdGeomTokens->inherited : UsdGeomTokens->invisible); + } + } - plugAnimated = animationCheck(animTranslator, MPlug(from, m_rotatePivotTranslate)); - if(plugAnimated || rotatePivotTranslate != defaultRotatePivotTranslate) - { - UsdAttribute rotatePivotTranslateAttr = addTranslateOp(xformSchema, "rotatePivotTranslate", rotatePivotTranslate, params.m_timeCode); - if(plugAnimated && animTranslator) animTranslator->forceAddPlug(MPlug(from, m_rotatePivotTranslate), rotatePivotTranslateAttr); - } + plugAnimated + = transformAnimated || animationCheck(animTranslator, MPlug(from, m_translation)); + if (plugAnimated || translation != defaultTranslation) { + UsdAttribute translateAttr + = addTranslateOp(xformSchema, "", translation, params.m_timeCode); + if (plugAnimated && animTranslator) + animTranslator->forceAddPlug(MPlug(from, m_translation), translateAttr); + } - plugAnimated = animationCheck(animTranslator, MPlug(from, m_rotatePivot)); - if(plugAnimated || rotatePivot != defaultRotatePivot) - { - UsdAttribute rotatePivotAttr = addTranslateOp(xformSchema, "rotatePivot", rotatePivot, params.m_timeCode); - if(plugAnimated && animTranslator) animTranslator->forceAddPlug(MPlug(from, m_rotatePivot), rotatePivotAttr); - } + plugAnimated = animationCheck(animTranslator, MPlug(from, m_rotatePivotTranslate)); + if (plugAnimated || rotatePivotTranslate != defaultRotatePivotTranslate) { + UsdAttribute rotatePivotTranslateAttr = addTranslateOp( + xformSchema, "rotatePivotTranslate", rotatePivotTranslate, params.m_timeCode); + if (plugAnimated && animTranslator) + animTranslator->forceAddPlug( + MPlug(from, m_rotatePivotTranslate), rotatePivotTranslateAttr); + } - plugAnimated = transformAnimated || animationCheck(animTranslator, MPlug(from, m_rotation)); - if(plugAnimated || rotation != defaultRotation) - { - rotation *= radToDeg; - UsdAttribute rotateAttr = addRotateOp(xformSchema, "", rotateOrder, rotation, params.m_timeCode); - if(plugAnimated && animTranslator) animTranslator->forceAddPlug(MPlug(from, m_rotation), rotateAttr, radToDeg); - } + plugAnimated = animationCheck(animTranslator, MPlug(from, m_rotatePivot)); + if (plugAnimated || rotatePivot != defaultRotatePivot) { + UsdAttribute rotatePivotAttr + = addTranslateOp(xformSchema, "rotatePivot", rotatePivot, params.m_timeCode); + if (plugAnimated && animTranslator) + animTranslator->forceAddPlug(MPlug(from, m_rotatePivot), rotatePivotAttr); + } - plugAnimated = animationCheck(animTranslator, MPlug(from, m_rotateAxis)); - if(plugAnimated || rotateAxis != defaultRotateAxis) - { - rotateAxis *= radToDeg; - UsdAttribute rotateAxisAttr = addRotateOp(xformSchema, "rotateAxis", MEulerRotation::kXYZ, rotateAxis, params.m_timeCode); - if(plugAnimated && animTranslator) animTranslator->forceAddPlug(MPlug(from, m_rotateAxis), rotateAxisAttr, radToDeg); - } + plugAnimated = transformAnimated || animationCheck(animTranslator, MPlug(from, m_rotation)); + if (plugAnimated || rotation != defaultRotation) { + rotation *= radToDeg; + UsdAttribute rotateAttr + = addRotateOp(xformSchema, "", rotateOrder, rotation, params.m_timeCode); + if (plugAnimated && animTranslator) + animTranslator->forceAddPlug(MPlug(from, m_rotation), rotateAttr, radToDeg); + } - plugAnimated = animationCheck(animTranslator, MPlug(from, m_rotatePivot)); - if(plugAnimated || rotatePivot != defaultRotatePivot) - { - addInverseTranslateOp(xformSchema, "rotatePivot"); - } + plugAnimated = animationCheck(animTranslator, MPlug(from, m_rotateAxis)); + if (plugAnimated || rotateAxis != defaultRotateAxis) { + rotateAxis *= radToDeg; + UsdAttribute rotateAxisAttr = addRotateOp( + xformSchema, "rotateAxis", MEulerRotation::kXYZ, rotateAxis, params.m_timeCode); + if (plugAnimated && animTranslator) + animTranslator->forceAddPlug(MPlug(from, m_rotateAxis), rotateAxisAttr, radToDeg); + } - plugAnimated = animationCheck(animTranslator, MPlug(from, m_scalePivotTranslate)); - if(plugAnimated || scalePivotTranslate != defaultScalePivotTranslate) - { - UsdAttribute scalePivotTranslateAttr = addTranslateOp(xformSchema, "scalePivotTranslate", scalePivotTranslate, params.m_timeCode); - if(plugAnimated && animTranslator) animTranslator->forceAddPlug(MPlug(from, m_scalePivotTranslate), scalePivotTranslateAttr); - } + plugAnimated = animationCheck(animTranslator, MPlug(from, m_rotatePivot)); + if (plugAnimated || rotatePivot != defaultRotatePivot) { + addInverseTranslateOp(xformSchema, "rotatePivot"); + } - plugAnimated = animationCheck(animTranslator, MPlug(from, m_scalePivot)); - if(plugAnimated || scalePivot != defaultScalePivot) - { - UsdAttribute scalePivotAttr = addTranslateOp(xformSchema, "scalePivot", scalePivot, params.m_timeCode); - if(plugAnimated && animTranslator) animTranslator->forceAddPlug(MPlug(from, m_scalePivot), scalePivotAttr); - } + plugAnimated = animationCheck(animTranslator, MPlug(from, m_scalePivotTranslate)); + if (plugAnimated || scalePivotTranslate != defaultScalePivotTranslate) { + UsdAttribute scalePivotTranslateAttr = addTranslateOp( + xformSchema, "scalePivotTranslate", scalePivotTranslate, params.m_timeCode); + if (plugAnimated && animTranslator) + animTranslator->forceAddPlug( + MPlug(from, m_scalePivotTranslate), scalePivotTranslateAttr); + } - if(shear != defaultShear) - { - GfMatrix4d shearMatrix( - 1.0f, 0.0f, 0.0f, 0.0f, - shear[0], 1.0f, 0.0f, 0.0f, - shear[1], shear[2], 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f); - UsdGeomXformOp op = xformSchema.AddTransformOp(UsdGeomXformOp::PrecisionDouble, TfToken("shear")); - op.Set(shearMatrix, params.m_timeCode); - } + plugAnimated = animationCheck(animTranslator, MPlug(from, m_scalePivot)); + if (plugAnimated || scalePivot != defaultScalePivot) { + UsdAttribute scalePivotAttr + = addTranslateOp(xformSchema, "scalePivot", scalePivot, params.m_timeCode); + if (plugAnimated && animTranslator) + animTranslator->forceAddPlug(MPlug(from, m_scalePivot), scalePivotAttr); + } - plugAnimated = transformAnimated || animationCheck(animTranslator, MPlug(from, m_scale)); - if(plugAnimated || scale != defaultScale) - { - UsdGeomXformOp op = xformSchema.AddScaleOp(UsdGeomXformOp::PrecisionFloat, TfToken("")); - op.Set(scale, params.m_timeCode); - if(plugAnimated && animTranslator) animTranslator->forceAddPlug(MPlug(from, m_scale), op.GetAttr()); - } + if (shear != defaultShear) { + GfMatrix4d shearMatrix( + 1.0f, + 0.0f, + 0.0f, + 0.0f, + shear[0], + 1.0f, + 0.0f, + 0.0f, + shear[1], + shear[2], + 1.0f, + 0.0f, + 0.0f, + 0.0f, + 0.0f, + 1.0f); + UsdGeomXformOp op + = xformSchema.AddTransformOp(UsdGeomXformOp::PrecisionDouble, TfToken("shear")); + op.Set(shearMatrix, params.m_timeCode); + } - plugAnimated = animationCheck(animTranslator, MPlug(from, m_scalePivot)); - if(plugAnimated || scalePivot != defaultScalePivot) - { - addInverseTranslateOp(xformSchema, "scalePivot"); - } - } - else - { - MMatrix wsm = path.inclusiveMatrix(); - auto op = xformSchema.AddTransformOp(UsdGeomXformOp::PrecisionDouble, TfToken("transform")); + plugAnimated = transformAnimated || animationCheck(animTranslator, MPlug(from, m_scale)); + if (plugAnimated || scale != defaultScale) { + UsdGeomXformOp op = xformSchema.AddScaleOp(UsdGeomXformOp::PrecisionFloat, TfToken("")); + op.Set(scale, params.m_timeCode); + if (plugAnimated && animTranslator) + animTranslator->forceAddPlug(MPlug(from, m_scale), op.GetAttr()); + } + + plugAnimated = animationCheck(animTranslator, MPlug(from, m_scalePivot)); + if (plugAnimated || scalePivot != defaultScalePivot) { + addInverseTranslateOp(xformSchema, "scalePivot"); + } + } else { + MMatrix wsm = path.inclusiveMatrix(); + auto op = xformSchema.AddTransformOp(UsdGeomXformOp::PrecisionDouble, TfToken("transform")); #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif - op.Set(*(const GfMatrix4d*)&wsm, params.m_timeCode); + op.Set(*(const GfMatrix4d*)&wsm, params.m_timeCode); #ifdef __GNUC__ #pragma GCC diagnostic pop #endif - if(animTranslator) animTranslator->addWorldSpace(path, op.GetAttr()); - } + if (animTranslator) + animTranslator->addWorldSpace(path, op.GetAttr()); + } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -void TransformTranslator::copyAttributeValue(const MPlug& plug, UsdAttribute& usdAttr, const UsdTimeCode& timeCode) +void TransformTranslator::copyAttributeValue( + const MPlug& plug, + UsdAttribute& usdAttr, + const UsdTimeCode& timeCode) { - MObject node = plug.node(); - MObject attribute = plug.attribute(); - static const TfToken visToken = UsdGeomTokens->visibility; - if (usdAttr.GetName() == visToken) - { - bool value; - getBool(node, attribute, value); - usdAttr.Set(value ? UsdGeomTokens->inherited : UsdGeomTokens->invisible, timeCode); - } + MObject node = plug.node(); + MObject attribute = plug.attribute(); + static const TfToken visToken = UsdGeomTokens->visibility; + if (usdAttr.GetName() == visToken) { + bool value; + getBool(node, attribute, value); + usdAttr.Set(value ? UsdGeomTokens->inherited : UsdGeomTokens->invisible, timeCode); + } } //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TransformTranslator.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TransformTranslator.h index ce92d7162c..f3b0f06d3e 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TransformTranslator.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TransformTranslator.h @@ -35,86 +35,97 @@ namespace translators { /// \brief A utility class to transfer transform nodes between Maya and USD /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -class TransformTranslator - : public DagNodeTranslator +class TransformTranslator : public DagNodeTranslator { public: + /// \brief static type registration + /// \return MS::kSuccess if ok + AL_USDMAYA_PUBLIC + static MStatus registerType(); - /// \brief static type registration - /// \return MS::kSuccess if ok - AL_USDMAYA_PUBLIC - static MStatus registerType(); + /// \brief Creates a new maya node of the given type and set attributes based on input prim + /// \param from the UsdPrim to copy the data from + /// \param parent the parent Dag node to parent the newly created object under + /// \param nodeType the maya node type to create + /// \param params the importer params that determines what will be imported + /// \return the newly created node + AL_USDMAYA_PUBLIC + MObject createNode( + const UsdPrim& from, + MObject parent, + const char* nodeType, + const ImporterParams& params) override; - /// \brief Creates a new maya node of the given type and set attributes based on input prim - /// \param from the UsdPrim to copy the data from - /// \param parent the parent Dag node to parent the newly created object under - /// \param nodeType the maya node type to create - /// \param params the importer params that determines what will be imported - /// \return the newly created node - AL_USDMAYA_PUBLIC - MObject createNode(const UsdPrim& from, MObject parent, const char* nodeType, const ImporterParams& params) override; + /// \brief helper method to copy attributes from the UsdPrim to the Maya node + /// \param from the UsdPrim to copy the data from + /// \param to the maya node to copy the data to + /// \param params the importer params to determine what to import + /// \return MS::kSuccess if ok + AL_USDMAYA_PUBLIC + MStatus copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params); - /// \brief helper method to copy attributes from the UsdPrim to the Maya node - /// \param from the UsdPrim to copy the data from - /// \param to the maya node to copy the data to - /// \param params the importer params to determine what to import - /// \return MS::kSuccess if ok - AL_USDMAYA_PUBLIC - MStatus copyAttributes(const UsdPrim& from, MObject to, const ImporterParams& params); + /// \brief Copies data from the maya node onto the usd primitive + /// \param from the maya node to copy the data from + /// \param to the USD prim to copy the attributes to + /// \param params the exporter params to determine what should be exported + /// \param path the dag path + /// \return MS::kSuccess if ok + AL_USDMAYA_PUBLIC + static MStatus copyAttributes( + const MObject& from, + UsdPrim& to, + const ExporterParams& params, + const MDagPath& path); - /// \brief Copies data from the maya node onto the usd primitive - /// \param from the maya node to copy the data from - /// \param to the USD prim to copy the attributes to - /// \param params the exporter params to determine what should be exported - /// \param path the dag path - /// \return MS::kSuccess if ok - AL_USDMAYA_PUBLIC - static MStatus copyAttributes(const MObject& from, UsdPrim& to, const ExporterParams& params, const MDagPath& path); + /// \brief copy the attribute value from the plug specified, at the given time, and store the + /// data on the usdAttr. \param attr the attribute to be copied \param usdAttr the attribute + /// to copy the data to \param timeCode the timecode to use when setting the data + AL_USDMAYA_PUBLIC + static void + copyAttributeValue(const MPlug& attr, UsdAttribute& usdAttr, const UsdTimeCode& timeCode); - /// \brief copy the attribute value from the plug specified, at the given time, and store the data on the usdAttr. - /// \param attr the attribute to be copied - /// \param usdAttr the attribute to copy the data to - /// \param timeCode the timecode to use when setting the data - AL_USDMAYA_PUBLIC - static void copyAttributeValue(const MPlug& attr, UsdAttribute& usdAttr, const UsdTimeCode& timeCode); - - /// \brief retrieve the corresponding maya attribute for the transform operation. - /// \param operation the transform operation we want the maya attribute handle for - /// \param attribute the returned attribute handle - /// \param conversionFactor a scaling that should be applied to the maya attributes to put them into the correct - /// units for USD - /// \return true if the attribute is known to be animated, and the attribute/conversionFactor contain valid results - AL_USDMAYA_PUBLIC - static bool getAnimationVariables(TransformOperation operation, MObject& attribute, double& conversionFactor); + /// \brief retrieve the corresponding maya attribute for the transform operation. + /// \param operation the transform operation we want the maya attribute handle for + /// \param attribute the returned attribute handle + /// \param conversionFactor a scaling that should be applied to the maya attributes to put them + /// into the correct + /// units for USD + /// \return true if the attribute is known to be animated, and the attribute/conversionFactor + /// contain valid results + AL_USDMAYA_PUBLIC + static bool getAnimationVariables( + TransformOperation operation, + MObject& attribute, + double& conversionFactor); private: - static MStatus processMetaData(const UsdPrim& from, MObject& to, const ImporterParams& params); + static MStatus processMetaData(const UsdPrim& from, MObject& to, const ImporterParams& params); - static MObject m_inheritsTransform; - static MObject m_scale; - static MObject m_shear; - static MObject m_rotation; - static MObject m_rotationX; - static MObject m_rotationY; - static MObject m_rotationZ; - static MObject m_rotateOrder; - static MObject m_rotateAxis; - static MObject m_rotateAxisX; - static MObject m_rotateAxisY; - static MObject m_rotateAxisZ; - static MObject m_translation; - static MObject m_scalePivot; - static MObject m_rotatePivot; - static MObject m_scalePivotTranslate; - static MObject m_rotatePivotTranslate; - static MObject m_selectHandle; - static MObject m_transMinusRotatePivot; - static MObject m_visibility; + static MObject m_inheritsTransform; + static MObject m_scale; + static MObject m_shear; + static MObject m_rotation; + static MObject m_rotationX; + static MObject m_rotationY; + static MObject m_rotationZ; + static MObject m_rotateOrder; + static MObject m_rotateAxis; + static MObject m_rotateAxisX; + static MObject m_rotateAxisY; + static MObject m_rotateAxisZ; + static MObject m_translation; + static MObject m_scalePivot; + static MObject m_rotatePivot; + static MObject m_scalePivotTranslate; + static MObject m_rotatePivotTranslate; + static MObject m_selectHandle; + static MObject m_transMinusRotatePivot; + static MObject m_visibility; }; //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorBase.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorBase.cpp index 38ec09d7f5..58593b6cad 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorBase.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorBase.cpp @@ -14,21 +14,24 @@ // limitations under the License. // #include "AL/usdmaya/fileio/translators/TranslatorBase.h" + #include "AL/usdmaya/DebugCodes.h" +#include "AL/usdmaya/Metadata.h" + #include #include #include #include #include -#include "AL/usdmaya/Metadata.h" namespace AL { namespace usdmaya { namespace fileio { namespace translators { -std::vector TranslatorManufacture::m_pythonTranslators; -std::unordered_map TranslatorManufacture::m_assetTypeToPythonTranslatorsMap; +std::vector TranslatorManufacture::m_pythonTranslators; +std::unordered_map + TranslatorManufacture::m_assetTypeToPythonTranslatorsMap; TfToken TranslatorManufacture::TranslatorPrefixAssetType("assettype:"); TfToken TranslatorManufacture::TranslatorPrefixSchemaType("schematype:"); @@ -36,438 +39,419 @@ TfToken TranslatorManufacture::TranslatorPrefixSchemaType("schematype:"); //---------------------------------------------------------------------------------------------------------------------- TranslatorManufacture::TranslatorManufacture(TranslatorContextPtr context) { - std::set loadedTypes; - std::set derivedTypes; + std::set loadedTypes; + std::set derivedTypes; + + bool keepGoing = true; + while (keepGoing) { + keepGoing = false; + derivedTypes.clear(); + PlugRegistry::GetAllDerivedTypes(&derivedTypes); + for (const TfType& t : derivedTypes) { + const auto insertResult = loadedTypes.insert(t); + if (insertResult.second) { + // TfType::GetFactory may cause additional plugins to be loaded + // may means potentially more translator types. We need to re-iterate + // over the derived types just to be sure... + keepGoing = true; + if (auto* factory = t.GetFactory()) { + if (TranslatorRefPtr ptr = factory->create(context)) { + auto it = m_translatorsMap.find(ptr->getTranslatedType().GetTypeName()); + if (it == m_translatorsMap.end()) { + m_translatorsMap.emplace(ptr->getTranslatedType().GetTypeName(), ptr); + ptr->setRegistrationType( + TranslatorManufacture::TranslatorPrefixSchemaType); + } else { + // located two translators for the same type + auto& previous = it->second; + if (previous->canBeOverridden() && !ptr->canBeOverridden()) { + m_translatorsMap[ptr->getTranslatedType().GetTypeName()] = ptr; + ptr->setRegistrationType( + TranslatorManufacture::TranslatorPrefixSchemaType); + } + } + } + } + } + } + } - bool keepGoing = true; - while (keepGoing) - { - keepGoing = false; derivedTypes.clear(); - PlugRegistry::GetAllDerivedTypes(&derivedTypes); - for (const TfType& t : derivedTypes) - { - const auto insertResult = loadedTypes.insert(t); - if (insertResult.second) - { + PlugRegistry::GetAllDerivedTypes(&derivedTypes); + for (const TfType& t : derivedTypes) { // TfType::GetFactory may cause additional plugins to be loaded // may means potentially more translator types. We need to re-iterate // over the derived types just to be sure... - keepGoing = true; - if (auto* factory = t.GetFactory()) - { - if (TranslatorRefPtr ptr = factory->create(context)) - { - auto it = m_translatorsMap.find(ptr->getTranslatedType().GetTypeName()); - if(it == m_translatorsMap.end()) - { - m_translatorsMap.emplace(ptr->getTranslatedType().GetTypeName(), ptr); - ptr->setRegistrationType(TranslatorManufacture::TranslatorPrefixSchemaType); + if (auto* factory = t.GetFactory()) { + if (auto ptr = factory->create(context)) { + m_extraDataPlugins.push_back(ptr); } - else - { - // located two translators for the same type - auto& previous = it->second; - if(previous->canBeOverridden() && !ptr->canBeOverridden()) - { - m_translatorsMap[ptr->getTranslatedType().GetTypeName()] = ptr; - ptr->setRegistrationType(TranslatorManufacture::TranslatorPrefixSchemaType); - } - } - } } - } - } - } - - derivedTypes.clear(); - PlugRegistry::GetAllDerivedTypes(&derivedTypes); - for (const TfType& t : derivedTypes) - { - // TfType::GetFactory may cause additional plugins to be loaded - // may means potentially more translator types. We need to re-iterate - // over the derived types just to be sure... - if (auto* factory = t.GetFactory()) - { - if (auto ptr = factory->create(context)) - { - m_extraDataPlugins.push_back(ptr); - } } - } } //---------------------------------------------------------------------------------------------------------------------- -TranslatorRefPtr TranslatorManufacture::get(const UsdPrim &prim) +TranslatorRefPtr TranslatorManufacture::get(const UsdPrim& prim) { - TranslatorRefPtr translator = TfNullPtr; - - //Try metadata first - std::string assetType; - prim.GetMetadata(Metadata::assetType, &assetType); - if (!assetType.empty()) - { - translator = getTranslatorByAssetTypeMetadata(assetType); - } - - //Then try schema - which tries C++ then python - if (!translator) - { - translator = getTranslatorBySchemaType(prim.GetTypeName() ); - } - return translator; + TranslatorRefPtr translator = TfNullPtr; + + // Try metadata first + std::string assetType; + prim.GetMetadata(Metadata::assetType, &assetType); + if (!assetType.empty()) { + translator = getTranslatorByAssetTypeMetadata(assetType); + } + + // Then try schema - which tries C++ then python + if (!translator) { + translator = getTranslatorBySchemaType(prim.GetTypeName()); + } + return translator; } //---------------------------------------------------------------------------------------------------------------------- -TranslatorManufacture::RefPtr TranslatorManufacture::getTranslatorByAssetTypeMetadata(const std::string& assetTypeValue) +TranslatorManufacture::RefPtr +TranslatorManufacture::getTranslatorByAssetTypeMetadata(const std::string& assetTypeValue) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::getTranslatorByAssetTypeMetadata:: looking for type %s\n",assetTypeValue.c_str()); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorManufacture::getTranslatorByAssetTypeMetadata:: looking for type %s\n", + assetTypeValue.c_str()); - //Look it up in our map of translators + // Look it up in our map of translators auto it = m_assetTypeToPythonTranslatorsMap.find(assetTypeValue); - if (it != m_assetTypeToPythonTranslatorsMap.end()) - { - if(it->second->active()) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::getTranslatorByAssetTypeMetadata:: found python translator for type %s\n",assetTypeValue.c_str()); - return it->second; - } + if (it != m_assetTypeToPythonTranslatorsMap.end()) { + if (it->second->active()) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorManufacture::getTranslatorByAssetTypeMetadata:: found python " + "translator for type %s\n", + assetTypeValue.c_str()); + return it->second; + } } - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::getTranslatorByAssetTypeMetadata:: no translator found for %s\n",assetTypeValue.c_str()); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorManufacture::getTranslatorByAssetTypeMetadata:: no translator found for " + "%s\n", + assetTypeValue.c_str()); return TfNullPtr; } //---------------------------------------------------------------------------------------------------------------------- TranslatorRefPtr TranslatorManufacture::getTranslatorBySchemaType(const TfToken type_name) { - if(auto py = getPythonTranslatorBySchemaType(type_name)) - { - return py; - } - - TfType type = TfType::FindDerivedByName(type_name); - std::string typeName(type.GetTypeName()); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::getTranslatorBySchemaType:: found schema %s\n",typeName.c_str()); - - //Look it up in our map of translators - auto it = m_translatorsMap.find(typeName); - if (it != m_translatorsMap.end()) - { - if(it->second->active()) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::getTranslatorBySchemaType:: found active C++ translator for schema %s\n",typeName.c_str()); - return it->second; + if (auto py = getPythonTranslatorBySchemaType(type_name)) { + return py; } - } - return TranslatorRefPtr(); -} + TfType type = TfType::FindDerivedByName(type_name); + std::string typeName(type.GetTypeName()); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorManufacture::getTranslatorBySchemaType:: found schema %s\n", + typeName.c_str()); + + // Look it up in our map of translators + auto it = m_translatorsMap.find(typeName); + if (it != m_translatorsMap.end()) { + if (it->second->active()) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorManufacture::getTranslatorBySchemaType:: found active C++ " + "translator for schema %s\n", + typeName.c_str()); + return it->second; + } + } + return TranslatorRefPtr(); +} //---------------------------------------------------------------------------------------------------------------------- TranslatorRefPtr TranslatorManufacture::get(const MObject& mayaObject) { - TranslatorRefPtr base; - TranslatorManufacture::RefPtr derived; - - if(auto py = TranslatorManufacture::getPythonTranslator(mayaObject)) - { - return py; - } - - for(auto& it : m_translatorsMap) - { - if(it.second->active()) - { - ExportFlag mode = it.second->canExport(mayaObject); - switch(mode) - { - case ExportFlag::kNotSupported: break; - case ExportFlag::kFallbackSupport: base = it.second; break; - case ExportFlag::kSupported: derived = it.second; break; - default: - break; - } + TranslatorRefPtr base; + TranslatorManufacture::RefPtr derived; + + if (auto py = TranslatorManufacture::getPythonTranslator(mayaObject)) { + return py; } - } - if(derived) { - return derived; - } - return base; -} + for (auto& it : m_translatorsMap) { + if (it.second->active()) { + ExportFlag mode = it.second->canExport(mayaObject); + switch (mode) { + case ExportFlag::kNotSupported: break; + case ExportFlag::kFallbackSupport: base = it.second; break; + case ExportFlag::kSupported: derived = it.second; break; + default: break; + } + } + } + if (derived) { + return derived; + } + return base; +} -TranslatorRefPtr TranslatorManufacture::getTranslatorFromId(const std::string& translatorId ) +TranslatorRefPtr TranslatorManufacture::getTranslatorFromId(const std::string& translatorId) { - TranslatorRefPtr translator; - - if (translatorId.find(TranslatorManufacture::TranslatorPrefixAssetType.GetString(), 0) == 0) - { - //cover the assettype use case - translator = getTranslatorByAssetTypeMetadata(translatorId.substr(10)); - } - else if (translatorId.find(TranslatorManufacture::TranslatorPrefixSchemaType.GetString(), 0) == 0) - { - //cover the schema type use case, - translator = getTranslatorBySchemaType(TfToken(translatorId.substr(11))); - } - else - { - // support backward compatibility (where the schema type was stored with no prefix - translator = getTranslatorBySchemaType(TfToken(translatorId)); - } - return translator; + TranslatorRefPtr translator; + + if (translatorId.find(TranslatorManufacture::TranslatorPrefixAssetType.GetString(), 0) == 0) { + // cover the assettype use case + translator = getTranslatorByAssetTypeMetadata(translatorId.substr(10)); + } else if ( + translatorId.find(TranslatorManufacture::TranslatorPrefixSchemaType.GetString(), 0) == 0) { + // cover the schema type use case, + translator = getTranslatorBySchemaType(TfToken(translatorId.substr(11))); + } else { + // support backward compatibility (where the schema type was stored with no prefix + translator = getTranslatorBySchemaType(TfToken(translatorId)); + } + return translator; } -std::string TranslatorManufacture::generateTranslatorId(const UsdPrim& prim ) +std::string TranslatorManufacture::generateTranslatorId(const UsdPrim& prim) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::generateTranslatorId for prim %s\n", prim.GetPath().GetText()); - std::string translatorId; - TranslatorRefPtr translator = TfNullPtr; - - //Try metadata first - std::string assetType; - prim.GetMetadata(Metadata::assetType, &assetType); - if (!assetType.empty()) - { - translator = getTranslatorByAssetTypeMetadata(assetType); - if (translator) - { - translatorId = TranslatorManufacture::TranslatorPrefixAssetType.GetString() + assetType; - } - } - //Then try schema - which tries C++ then python - if (!translator) - { - translator = getTranslatorBySchemaType(prim.GetTypeName()); - if (translator) - { - translatorId = TranslatorManufacture::TranslatorPrefixSchemaType.GetString() + prim.GetTypeName().GetString(); - } - } - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::generateTranslatorId generated ID %s\n", translatorId.c_str()); - return translatorId; + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorManufacture::generateTranslatorId for prim %s\n", prim.GetPath().GetText()); + std::string translatorId; + TranslatorRefPtr translator = TfNullPtr; + + // Try metadata first + std::string assetType; + prim.GetMetadata(Metadata::assetType, &assetType); + if (!assetType.empty()) { + translator = getTranslatorByAssetTypeMetadata(assetType); + if (translator) { + translatorId = TranslatorManufacture::TranslatorPrefixAssetType.GetString() + assetType; + } + } + // Then try schema - which tries C++ then python + if (!translator) { + translator = getTranslatorBySchemaType(prim.GetTypeName()); + if (translator) { + translatorId = TranslatorManufacture::TranslatorPrefixSchemaType.GetString() + + prim.GetTypeName().GetString(); + } + } + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorManufacture::generateTranslatorId generated ID %s\n", translatorId.c_str()); + return translatorId; } //---------------------------------------------------------------------------------------------------------------------- -std::vector TranslatorManufacture::getExtraDataPlugins(const MObject& mayaObject) +std::vector +TranslatorManufacture::getExtraDataPlugins(const MObject& mayaObject) { - std::vector ptrs; - for(auto plugin : m_extraDataPlugins) - { - MFn::Type type = plugin->getFnType(); - if(mayaObject.hasFn(type)) - { - switch(type) - { - case MFn::kPluginMotionPathNode: - case MFn::kPluginDependNode: - case MFn::kPluginLocatorNode: - case MFn::kPluginDeformerNode: - case MFn::kPluginShape: - case MFn::kPluginFieldNode: - case MFn::kPluginEmitterNode: - case MFn::kPluginSpringNode: - case MFn::kPluginIkSolver: - case MFn::kPluginHardwareShader: - case MFn::kPluginHwShaderNode: - case MFn::kPluginTransformNode: - case MFn::kPluginObjectSet: - case MFn::kPluginImagePlaneNode: - case MFn::kPluginConstraintNode: - case MFn::kPluginManipulatorNode: - case MFn::kPluginSkinCluster: - case MFn::kPluginGeometryFilter: - case MFn::kPluginBlendShape: - { - const MString typeName = plugin->getPluginTypeName(); - MFnDependencyNode fn(mayaObject); - if(fn.typeName() != typeName) - { - continue; - } + std::vector ptrs; + for (auto plugin : m_extraDataPlugins) { + MFn::Type type = plugin->getFnType(); + if (mayaObject.hasFn(type)) { + switch (type) { + case MFn::kPluginMotionPathNode: + case MFn::kPluginDependNode: + case MFn::kPluginLocatorNode: + case MFn::kPluginDeformerNode: + case MFn::kPluginShape: + case MFn::kPluginFieldNode: + case MFn::kPluginEmitterNode: + case MFn::kPluginSpringNode: + case MFn::kPluginIkSolver: + case MFn::kPluginHardwareShader: + case MFn::kPluginHwShaderNode: + case MFn::kPluginTransformNode: + case MFn::kPluginObjectSet: + case MFn::kPluginImagePlaneNode: + case MFn::kPluginConstraintNode: + case MFn::kPluginManipulatorNode: + case MFn::kPluginSkinCluster: + case MFn::kPluginGeometryFilter: + case MFn::kPluginBlendShape: { + const MString typeName = plugin->getPluginTypeName(); + MFnDependencyNode fn(mayaObject); + if (fn.typeName() != typeName) { + continue; + } + } break; + default: break; + } + ptrs.push_back(plugin); } - break; - default: - break; - } - ptrs.push_back(plugin); } - } - return ptrs; + return ptrs; } //---------------------------------------------------------------------------------------------------------------------- void TranslatorManufacture::activate(const TfTokenVector& types) { - for(auto& type : types) - { - auto it = m_translatorsMap.find(type.GetString()); - if(it != m_translatorsMap.end()) - it->second->activate(); - } + for (auto& type : types) { + auto it = m_translatorsMap.find(type.GetString()); + if (it != m_translatorsMap.end()) + it->second->activate(); + } } //---------------------------------------------------------------------------------------------------------------------- void TranslatorManufacture::deactivate(const TfTokenVector& types) { - for(auto& type : types) - { - auto it = m_translatorsMap.find(type.GetString()); - if(it != m_translatorsMap.end()) - it->second->deactivate(); - } + for (auto& type : types) { + auto it = m_translatorsMap.find(type.GetString()); + if (it != m_translatorsMap.end()) + it->second->deactivate(); + } } //---------------------------------------------------------------------------------------------------------------------- void TranslatorManufacture::activateAll() { - for(auto& it : m_translatorsMap) - { - it.second->activate(); - } + for (auto& it : m_translatorsMap) { + it.second->activate(); + } } //---------------------------------------------------------------------------------------------------------------------- void TranslatorManufacture::deactivateAll() { - for(auto& it : m_translatorsMap) - { - it.second->deactivate(); - } + for (auto& it : m_translatorsMap) { + it.second->deactivate(); + } } //---------------------------------------------------------------------------------------------------------------------- bool TranslatorManufacture::addPythonTranslator(TranslatorRefPtr tb, const TfToken& assetType) { - if(tb->getTranslatedType().IsUnknown() && assetType.IsEmpty()) - { - return false; - } - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::addPythonTranslator\n"); - tb->initialize(); - m_pythonTranslators.push_back(tb); - if(!assetType.IsEmpty()) - { - m_assetTypeToPythonTranslatorsMap.emplace(assetType.GetString(), tb); - tb->setRegistrationType(TranslatorManufacture::TranslatorPrefixAssetType); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::addPythonTranslator added by asset type %s\n", assetType.GetText()); - } - else - { - tb->setRegistrationType(TranslatorManufacture::TranslatorPrefixSchemaType); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::addPythonTranslator added by schema type %s\n", tb->getTranslatedType().GetTypeName().c_str()); - } - return true; + if (tb->getTranslatedType().IsUnknown() && assetType.IsEmpty()) { + return false; + } + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::addPythonTranslator\n"); + tb->initialize(); + m_pythonTranslators.push_back(tb); + if (!assetType.IsEmpty()) { + m_assetTypeToPythonTranslatorsMap.emplace(assetType.GetString(), tb); + tb->setRegistrationType(TranslatorManufacture::TranslatorPrefixAssetType); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorManufacture::addPythonTranslator added by asset type %s\n", + assetType.GetText()); + } else { + tb->setRegistrationType(TranslatorManufacture::TranslatorPrefixSchemaType); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorManufacture::addPythonTranslator added by schema type %s\n", + tb->getTranslatedType().GetTypeName().c_str()); + } + return true; } //---------------------------------------------------------------------------------------------------------------------- void TranslatorManufacture::clearPythonTranslators() { - m_pythonTranslators.clear(); - m_assetTypeToPythonTranslatorsMap.clear(); + m_pythonTranslators.clear(); + m_assetTypeToPythonTranslatorsMap.clear(); } //---------------------------------------------------------------------------------------------------------------------- TranslatorRefPtr TranslatorManufacture::getPythonTranslatorBySchemaType(const TfToken type_name) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::getPythonTranslatorBySchemaType looking for translator for type %s\n", type_name.GetText()); - TfType type = TfType::FindDerivedByName(type_name); - - for(auto it : TranslatorManufacture::m_pythonTranslators) - { - if((it->getRegistrationType()==TranslatorManufacture::TranslatorPrefixSchemaType) && (type == it->getTranslatedType())) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::getPythonTranslatorBySchemaType:: found a translator for type %s\n", type_name.GetText()); - return it; + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorManufacture::getPythonTranslatorBySchemaType looking for translator for " + "type %s\n", + type_name.GetText()); + TfType type = TfType::FindDerivedByName(type_name); + + for (auto it : TranslatorManufacture::m_pythonTranslators) { + if ((it->getRegistrationType() == TranslatorManufacture::TranslatorPrefixSchemaType) + && (type == it->getTranslatedType())) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorManufacture::getPythonTranslatorBySchemaType:: found a translator " + "for type %s\n", + type_name.GetText()); + return it; + } } - } - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::getPythonTranslatorBySchemaType:: :didn't find any translator::returning nothing"); - return 0; + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorManufacture::getPythonTranslatorBySchemaType:: :didn't find any " + "translator::returning nothing"); + return 0; } //---------------------------------------------------------------------------------------------------------------------- TranslatorRefPtr TranslatorManufacture::getPythonTranslator(const MObject& mayaObject) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::getPythonTranslator %s\n", mayaObject.apiTypeStr()); - TranslatorRefPtr base; - for(auto it : TranslatorManufacture::m_pythonTranslators) - { - auto canExport = it->canExport(mayaObject); - switch(canExport) - { - case ExportFlag::kSupported: - return it; - - case ExportFlag::kFallbackSupport: - base = it; - break; - - default: - break; + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorManufacture::getPythonTranslator %s\n", mayaObject.apiTypeStr()); + TranslatorRefPtr base; + for (auto it : TranslatorManufacture::m_pythonTranslators) { + auto canExport = it->canExport(mayaObject); + switch (canExport) { + case ExportFlag::kSupported: return it; + + case ExportFlag::kFallbackSupport: base = it; break; + + default: break; + } } - } - return base; + return base; } //---------------------------------------------------------------------------------------------------------------------- bool TranslatorManufacture::deletePythonTranslator(const TfType type_name) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::deletePythonTranslator\n"); - for(auto it = TranslatorManufacture::m_pythonTranslators.begin(), end = TranslatorManufacture::m_pythonTranslators.end(); it != end; ++it) - { - auto state_ = PyGILState_Ensure(); - auto thetype = (*it)->getTranslatedType(); - PyGILState_Release(state_); - if(type_name == thetype) - { - TranslatorManufacture::m_pythonTranslators.erase(it); - return true; + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::deletePythonTranslator\n"); + for (auto it = TranslatorManufacture::m_pythonTranslators.begin(), + end = TranslatorManufacture::m_pythonTranslators.end(); + it != end; + ++it) { + auto state_ = PyGILState_Ensure(); + auto thetype = (*it)->getTranslatedType(); + PyGILState_Release(state_); + if (type_name == thetype) { + TranslatorManufacture::m_pythonTranslators.erase(it); + return true; + } } - } - return false; + return false; } //---------------------------------------------------------------------------------------------------------------------- void TranslatorManufacture::preparePythonTranslators(TranslatorContext::RefPtr context) -{ - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::preparePythonTranslators\n"); - for(auto it : TranslatorManufacture::m_pythonTranslators) - { - it->setContext(context); - } - for(auto it : TranslatorManufacture::m_assetTypeToPythonTranslatorsMap) - { - (it.second)->setContext(context); - } +{ + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorManufacture::preparePythonTranslators\n"); + for (auto it : TranslatorManufacture::m_pythonTranslators) { + it->setContext(context); + } + for (auto it : TranslatorManufacture::m_assetTypeToPythonTranslatorsMap) { + (it.second)->setContext(context); + } } //---------------------------------------------------------------------------------------------------------------------- void TranslatorManufacture::updatePythonTranslators(TranslatorContext::RefPtr context) { - m_contextualisedPythonTranslators.clear(); - for(const auto &tr : m_pythonTranslators) - { - m_contextualisedPythonTranslators.push_back(tr); - m_contextualisedPythonTranslators.back()->setContext(context); - } + m_contextualisedPythonTranslators.clear(); + for (const auto& tr : m_pythonTranslators) { + m_contextualisedPythonTranslators.push_back(tr); + m_contextualisedPythonTranslators.back()->setContext(context); + } } //---------------------------------------------------------------------------------------------------------------------- std::vector TranslatorManufacture::getPythonTranslators() { - return m_pythonTranslators; + return m_pythonTranslators; } //---------------------------------------------------------------------------------------------------------------------- -TF_REGISTRY_FUNCTION(TfType) -{ - TfType::Define(); -} +TF_REGISTRY_FUNCTION(TfType) { TfType::Define(); } //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorBase.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorBase.h index 17bf0ca63c..119201716d 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorBase.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorBase.h @@ -41,274 +41,293 @@ namespace translators { /// \brief Enum used to determine whether a given maya node type is supported for export enum class ExportFlag { - kNotSupported, ///< no support available - kFallbackSupport, ///< support provided by the core ALUsdMaya plugin - kSupported ///< support provided by plugin translators + kNotSupported, ///< no support available + kFallbackSupport, ///< support provided by the core ALUsdMaya plugin + kSupported ///< support provided by plugin translators }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief The base class interface of all translator plugins. The absolute minimum a translator plugin must implement +/// \brief The base class interface of all translator plugins. The absolute minimum a translator +/// plugin must implement /// are the following 3 methods: /// -/// \li \b initialize : Each translator has an opportunity to initialize itself. This should be used to -/// perform any internal initialization (for example, using an MNodeClass to extract MObjects for the -/// attributes you intend to translate, rather than using MFnDependencyNode::findPlug()) -/// \li \b import : This should be used to create all node(s) that your translator will generate. -/// \li \b tearDown : If a variant switch occurs that removes/replaces your node type, your translator will -/// be asked to remove the nodes it created from the scene. In this method, delete any nodes you created. +/// \li \b initialize : Each translator has an opportunity to initialize itself. This +/// should be used to +/// perform any internal initialization (for example, using an MNodeClass to extract +/// MObjects for the attributes you intend to translate, rather than using +/// MFnDependencyNode::findPlug()) +/// \li \b import : This should be used to create all node(s) that your translator will +/// generate. \li \b tearDown : If a variant switch occurs that removes/replaces your node +/// type, your translator will +/// be asked to remove the nodes it created from the scene. In this method, delete any +/// nodes you created. /// -/// This will enable your plug-in to work correctly with variant switching. In addition, you may wish to -/// overload the following methods: +/// This will enable your plug-in to work correctly with variant switching. In addition, you +/// may wish to overload the following methods: /// -/// \li \b needsTransformParent : If the maya node you will be creating is a DAG shape or custom transform, -/// then by default this method returns true, which will provide you with a transform node under which -/// you can parent your DAG shape. -/// \li \b postImport : The order in which the usd prims are imported into the scene is undefined, so -/// if you wish to make any connections between Maya nodes, then that should be done here (i.e. when you -/// are sure that all nodes will exist within the scene). -/// \li \b preTearDown : Prior to being notified of a tear down notification (as a result of a variant switch) -/// if your plugin needs to save some state (e.g. layout or animation tweaks), then that data should be -/// serialised in the preTearDown event. This method should not delete any nodes or make changes to the -/// Maya scene. It is your last chance to inspect and serialise data prior to any nodes being deleted -/// as a result of the tearDown. -/// \li \b update : If a variant switch occurs that leaves a prim intact (but may have changed some attribute -/// values), then you can override this method to simply copy the attributes values from the prim onto the -/// existing maya nodes. This is often faster than destroying and recreating the nodes. If you implement -/// this method, you must override \b supportsUpdate to return true. +/// \li \b needsTransformParent : If the maya node you will be creating is a DAG shape or +/// custom transform, +/// then by default this method returns true, which will provide you with a transform +/// node under which you can parent your DAG shape. +/// \li \b postImport : The order in which the usd prims are imported into the scene is +/// undefined, so +/// if you wish to make any connections between Maya nodes, then that should be done +/// here (i.e. when you are sure that all nodes will exist within the scene). +/// \li \b preTearDown : Prior to being notified of a tear down notification (as a result +/// of a variant switch) +/// if your plugin needs to save some state (e.g. layout or animation tweaks), then +/// that data should be serialised in the preTearDown event. This method should not +/// delete any nodes or make changes to the Maya scene. It is your last chance to +/// inspect and serialise data prior to any nodes being deleted as a result of the +/// tearDown. +/// \li \b update : If a variant switch occurs that leaves a prim intact (but may have +/// changed some attribute +/// values), then you can override this method to simply copy the attributes values +/// from the prim onto the existing maya nodes. This is often faster than destroying +/// and recreating the nodes. If you implement this method, you must override \b +/// supportsUpdate to return true. /// /// Do not inherit from this class directly - use the TranslatorBase instead. /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- class TranslatorAbstract - : public TfRefBase, public TfWeakBase + : public TfRefBase + , public TfWeakBase { public: - typedef TranslatorAbstract This; ///< this type - typedef TfRefPtr RefPtr; ///< the type of a reference this type - typedef TfWeakPtr Ptr; ///< weak pointer to this type - - /// \brief dtor - virtual ~TranslatorAbstract() = default; - TranslatorAbstract() = default; - - /// \brief Override to specify the schema type of the prim that this translator plugin is responsible for. - /// \return the custom schema type associated with this prim - virtual TfType getTranslatedType() const = 0; - - /// \brief if the custom node type you are importing requires a parent transform (e.g. you are importing a shape node), - /// then this method should return true. If however you do not need a parent transform (e.g. you are importing - /// a texture!), then you can return false here. - /// \return true if this type of node requires a transform as a parent node (i.e. this is a DAG node), false if the node - /// if a dependency node - virtual bool needsTransformParent() const - { return true; } - - /// \brief Override this to do a one time initialization of your translator. Primarily this is to allow you to - /// extract some MObject attribute handles from an MNodeClass, to avoid the need for calling findPlug at - /// runtime (and the inherent cost of the strcmps/hash lookup that entails) - /// \return MS::kSuccess if all ok - virtual MStatus initialize() - { return MS::kSuccess; } - - /// \brief Override this method to import a prim into your scene. - /// \param prim the usd prim to be imported into maya - /// \param parent a handle to an MObject that represents an AL_usd_Transform node. You should parent your DAG - /// objects under this node. If the prim you are importing is NOT a DAG object (e.g. surface shader, etc), - /// then you can ignore this parameter. - /// \param createdObj a handle to an MObject created in the importing process - /// \return MS::kSuccess if all ok - virtual MStatus import(const UsdPrim& prim, MObject& parent, MObject& createdObj) - { return MS::kSuccess; } - - /// \brief Override this method to export a Maya object into USD - /// \param stage the stage to write the data into - /// \param dagPath the Maya dag path of the object to export - /// \param usdPath the path in the USD stage where the prim should be created - /// \param params the exporter params - /// \return the prim created - virtual UsdPrim exportObject(UsdStageRefPtr stage, MDagPath dagPath, const SdfPath& usdPath, const ExporterParams& params) - { return UsdPrim(); } - - /// \brief If your node needs to set up any relationships after import (for example, adding the node to a set, or - /// making attribute connections), then all of that work should be performed here. - /// \param prim the prim we are importing. - /// \return MS::kSuccess if all ok - virtual MStatus postImport(const UsdPrim& prim) - { return MS::kSuccess; } - - /// \brief If your plugin has its own hashing mechanism, your plugin can override this method to return - /// a *meaningful* value as the unique key for the prim, e.g. a md5 hash or uuid string. - /// This method happens just before updating the prim or removing the prim (e.g. when switching variant), then - /// USDMaya checks this hash value to decide if update() / tearDown() / import() are really necessary to be - /// called. - /// Not implementing this method, returning empty string or a false value would indicate this prim is always - /// needed to be updated (or tearDown() and import(), depends on the return value of supportsUpdate()), this - /// is the backward compatible method (prior 0.35.3); returning a constant value would indicate - /// this prim does not need to be updated (or recreated) at all. - /// \param prim the prim to inspect. - /// \return unique key string. - virtual std::size_t generateUniqueKey(const UsdPrim& prim) const - { return 0; } - - /// \brief This method will be called prior to the tear down process taking place. This is the last chance you have - /// to do any serialisation whilst all of the existing nodes are available to query. - /// \param prim the prim that may be modified or deleted as a result of a variant switch - /// \return MS::kSuccess if all ok - virtual MStatus preTearDown(UsdPrim& prim) - { return MS::kSuccess; } - - /// \brief If your plugin creates any nodes within Maya, then this method should be overridden to remove those - /// nodes. This forms a central role within the variant switching system. - /// \param path the path to the prim that should be removed. \b CRASH_ALERT : It is vitally important that you do - /// not attempt to access the prim from the current usd stage. It is entirely possible that a variant switch - /// has removed the prim from the stage, so any attempts to access the UsdPrim via this path, is more than - /// likely to crash Maya. - /// \return MS::kSuccess if all ok - virtual MStatus tearDown(const SdfPath& path) - { return MStatus::kNotImplemented; } - - /// \brief override this method and return true if the translator supports update - /// \return true if your plugin supports update, false otherwise. - virtual bool supportsUpdate() const - { return false; } - - /// \brief If a translator is importableByDefault=true, it will always be automatically imported on ProxyShape - /// initialisation. - /// \return returns true if the Translator doesn't automatically import the Prim. - virtual bool importableByDefault() const - { return true; } - - /// \brief Optionally override this method to copy the attribute values from the prim onto the Maya nodes you have - /// created. - /// \param prim the prim - /// \return MS::kSuccess if all ok - virtual MStatus update(const UsdPrim& prim) - { return MStatus::kNotImplemented; } - - /// \brief Method used to test a Maya node to see whether it can be exported. - virtual ExportFlag canExport(const MObject& obj) - { return ExportFlag::kNotSupported; } - - /// \brief The translator plugins that ship with AL_USDMaya specify this flag as true so that they can be overridden - virtual bool canBeOverridden() - { return false; } - - /// \brief After exporting the current obj/dagPath, should we proceed to it's children? - virtual bool exportDescendants() const - { return true; } + typedef TranslatorAbstract This; ///< this type + typedef TfRefPtr RefPtr; ///< the type of a reference this type + typedef TfWeakPtr Ptr; ///< weak pointer to this type + + /// \brief dtor + virtual ~TranslatorAbstract() = default; + TranslatorAbstract() = default; + + /// \brief Override to specify the schema type of the prim that this translator plugin is + /// responsible for. \return the custom schema type associated with this prim + virtual TfType getTranslatedType() const = 0; + + /// \brief if the custom node type you are importing requires a parent transform (e.g. you are + /// importing a shape node), + /// then this method should return true. If however you do not need a parent transform + /// (e.g. you are importing a texture!), then you can return false here. + /// \return true if this type of node requires a transform as a parent node (i.e. this is a DAG + /// node), false if the node + /// if a dependency node + virtual bool needsTransformParent() const { return true; } + + /// \brief Override this to do a one time initialization of your translator. Primarily this is + /// to allow you to + /// extract some MObject attribute handles from an MNodeClass, to avoid the need for + /// calling findPlug at runtime (and the inherent cost of the strcmps/hash lookup that + /// entails) + /// \return MS::kSuccess if all ok + virtual MStatus initialize() { return MS::kSuccess; } + + /// \brief Override this method to import a prim into your scene. + /// \param prim the usd prim to be imported into maya + /// \param parent a handle to an MObject that represents an AL_usd_Transform node. You should + /// parent your DAG + /// objects under this node. If the prim you are importing is NOT a DAG object (e.g. + /// surface shader, etc), then you can ignore this parameter. + /// \param createdObj a handle to an MObject created in the importing process + /// \return MS::kSuccess if all ok + virtual MStatus import(const UsdPrim& prim, MObject& parent, MObject& createdObj) + { + return MS::kSuccess; + } + + /// \brief Override this method to export a Maya object into USD + /// \param stage the stage to write the data into + /// \param dagPath the Maya dag path of the object to export + /// \param usdPath the path in the USD stage where the prim should be created + /// \param params the exporter params + /// \return the prim created + virtual UsdPrim exportObject( + UsdStageRefPtr stage, + MDagPath dagPath, + const SdfPath& usdPath, + const ExporterParams& params) + { + return UsdPrim(); + } + /// \brief If your node needs to set up any relationships after import (for example, adding the + /// node to a set, or + /// making attribute connections), then all of that work should be performed here. + /// \param prim the prim we are importing. + /// \return MS::kSuccess if all ok + virtual MStatus postImport(const UsdPrim& prim) { return MS::kSuccess; } + + /// \brief If your plugin has its own hashing mechanism, your plugin can override this method + /// to return + /// a *meaningful* value as the unique key for the prim, e.g. a md5 hash or uuid string. + /// This method happens just before updating the prim or removing the prim (e.g. when + /// switching variant), then USDMaya checks this hash value to decide if update() / + /// tearDown() / import() are really necessary to be called. Not implementing this + /// method, returning empty string or a false value would indicate this prim is always + /// needed to be updated (or tearDown() and import(), depends on the return value of + /// supportsUpdate()), this is the backward compatible method (prior 0.35.3); returning + /// a constant value would indicate this prim does not need to be updated (or recreated) + /// at all. + /// \param prim the prim to inspect. + /// \return unique key string. + virtual std::size_t generateUniqueKey(const UsdPrim& prim) const { return 0; } + + /// \brief This method will be called prior to the tear down process taking place. This is the + /// last chance you have + /// to do any serialisation whilst all of the existing nodes are available to query. + /// \param prim the prim that may be modified or deleted as a result of a variant switch + /// \return MS::kSuccess if all ok + virtual MStatus preTearDown(UsdPrim& prim) { return MS::kSuccess; } + + /// \brief If your plugin creates any nodes within Maya, then this method should be overridden + /// to remove those + /// nodes. This forms a central role within the variant switching system. + /// \param path the path to the prim that should be removed. \b CRASH_ALERT : It is vitally + /// important that you do + /// not attempt to access the prim from the current usd stage. It is entirely possible + /// that a variant switch has removed the prim from the stage, so any attempts to access + /// the UsdPrim via this path, is more than likely to crash Maya. + /// \return MS::kSuccess if all ok + virtual MStatus tearDown(const SdfPath& path) { return MStatus::kNotImplemented; } + + /// \brief override this method and return true if the translator supports update + /// \return true if your plugin supports update, false otherwise. + virtual bool supportsUpdate() const { return false; } + + /// \brief If a translator is importableByDefault=true, it will always be automatically imported + /// on ProxyShape initialisation. \return returns true if the Translator doesn't automatically + /// import the Prim. + virtual bool importableByDefault() const { return true; } + + /// \brief Optionally override this method to copy the attribute values from the prim onto the + /// Maya nodes you have + /// created. + /// \param prim the prim + /// \return MS::kSuccess if all ok + virtual MStatus update(const UsdPrim& prim) { return MStatus::kNotImplemented; } + + /// \brief Method used to test a Maya node to see whether it can be exported. + virtual ExportFlag canExport(const MObject& obj) { return ExportFlag::kNotSupported; } + + /// \brief The translator plugins that ship with AL_USDMaya specify this flag as true so that + /// they can be overridden + virtual bool canBeOverridden() { return false; } + + /// \brief After exporting the current obj/dagPath, should we proceed to it's children? + virtual bool exportDescendants() const { return true; } }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief Base class for maya translator usd plugins. The TfType of these plugins has to be derived from the base +/// \brief Base class for maya translator usd plugins. The TfType of these plugins has to be +/// derived from the base /// TfType, TranslatorBase. - /// \ingroup translators +/// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -class TranslatorBase - : public TranslatorAbstract +class TranslatorBase : public TranslatorAbstract { public: - typedef TranslatorBase This; - typedef TfRefPtr RefPtr; - - /// \brief dtor - virtual ~TranslatorBase() - {} - - /// \brief returns the translated prim type - TfType getTranslatedType() const override - { return m_translatedType; } - - /// \brief returns the context currently being used to translate the USD prims. The context can be used to add - /// references to prims you have created in your translator plugins - TranslatorContextPtr context() const - { return m_context; } - - /// \brief Internal method used to create a new instance of a plugin translator - /// \param primType the type of translator to manufacture - /// \param context the translation context - /// \return a handle to the newly created plugin translator - AL_USDMAYA_PUBLIC - static RefPtr manufacture(const std::string& primType, TranslatorContextPtr context) = delete; - - /// \brief return the usd stage associated with this context - /// \return the usd stage - UsdStageRefPtr getUsdStage() const - { return context()->getUsdStage(); } - - /// \brief override if you have a node that needs to generate animation that cannot be mapped between an MPlug - /// and a UsdAttribute. - /// \param path path to the object being exported - /// \param prim the prim to write the data into - /// \param timeCode the time value to sample the data at - virtual void exportCustomAnim(const MDagPath& path, UsdPrim& prim, const UsdTimeCode& timeCode) + typedef TranslatorBase This; + typedef TfRefPtr RefPtr; + + /// \brief dtor + virtual ~TranslatorBase() { } + + /// \brief returns the translated prim type + TfType getTranslatedType() const override { return m_translatedType; } + + /// \brief returns the context currently being used to translate the USD prims. The context can + /// be used to add + /// references to prims you have created in your translator plugins + TranslatorContextPtr context() const { return m_context; } + + /// \brief Internal method used to create a new instance of a plugin translator + /// \param primType the type of translator to manufacture + /// \param context the translation context + /// \return a handle to the newly created plugin translator + AL_USDMAYA_PUBLIC + static RefPtr manufacture(const std::string& primType, TranslatorContextPtr context) = delete; + + /// \brief return the usd stage associated with this context + /// \return the usd stage + UsdStageRefPtr getUsdStage() const { return context()->getUsdStage(); } + + /// \brief override if you have a node that needs to generate animation that cannot be mapped + /// between an MPlug + /// and a UsdAttribute. + /// \param path path to the object being exported + /// \param prim the prim to write the data into + /// \param timeCode the time value to sample the data at + virtual void exportCustomAnim(const MDagPath& path, UsdPrim& prim, const UsdTimeCode& timeCode) { - (void)path; - (void)prim; - (void)timeCode; + (void)path; + (void)prim; + (void)timeCode; } - /// \brief returns the active status of the translator - bool active() const - { return m_active; } - - /// \brief activate this translator - void activate() - { m_active = true; } - - /// \brief deactivate this translator - void deactivate() - { m_active = false; } - - /// \brief internal method. Used within AL_USDMAYA_DEFINE_TRANSLATOR macro to set the translation context - /// \param context the internal context - virtual void setContext(const TranslatorContextPtr context) - { m_context = context; } - - void setRegistrationType(const TfToken& registrationType) - { - m_registrationType = registrationType; - } - TfToken getRegistrationType() const - { - return m_registrationType; - } + /// \brief returns the active status of the translator + bool active() const { return m_active; } -protected: + /// \brief activate this translator + void activate() { m_active = true; } + + /// \brief deactivate this translator + void deactivate() { m_active = false; } + + /// \brief internal method. Used within AL_USDMAYA_DEFINE_TRANSLATOR macro to set the + /// translation context \param context the internal context + virtual void setContext(const TranslatorContextPtr context) { m_context = context; } - /// \brief internal method. Used within AL_USDMAYA_DEFINE_TRANSLATOR macro to set the schema type of the node we - /// translate. - /// \param translatedType the schema type name - virtual void setTranslatedType(const TfType& translatedType) - { m_translatedType = translatedType; } - - class NewNodesCollector - { - public: - NewNodesCollector(TranslatorContextPtr context, UsdPrim prim):m_context(context), m_prim(prim){} - ~NewNodesCollector() + void setRegistrationType(const TfToken& registrationType) { - if(!m_context)return; - for(unsigned int i=0; iinsertItem(m_prim, m_objectArray[i]); - } + m_registrationType = registrationType; } - MObjectArray *nodeContainerPtr(){return &m_objectArray;} - private: - TranslatorContextPtr m_context; - UsdPrim m_prim; - MObjectArray m_objectArray; - }; + TfToken getRegistrationType() const { return m_registrationType; } + +protected: + /// \brief internal method. Used within AL_USDMAYA_DEFINE_TRANSLATOR macro to set the schema + /// type of the node we + /// translate. + /// \param translatedType the schema type name + virtual void setTranslatedType(const TfType& translatedType) + { + m_translatedType = translatedType; + } + + class NewNodesCollector + { + public: + NewNodesCollector(TranslatorContextPtr context, UsdPrim prim) + : m_context(context) + , m_prim(prim) + { + } + ~NewNodesCollector() + { + if (!m_context) + return; + for (unsigned int i = 0; i < m_objectArray.length(); ++i) { + m_context->insertItem(m_prim, m_objectArray[i]); + } + } + MObjectArray* nodeContainerPtr() { return &m_objectArray; } + + private: + TranslatorContextPtr m_context; + UsdPrim m_prim; + MObjectArray m_objectArray; + }; private: - TfType m_translatedType; - TranslatorContextPtr m_context; - bool m_active = true; - TfToken m_registrationType; /// how was this plugin registered (e.g by schematype or by assettype) + TfType m_translatedType; + TranslatorContextPtr m_context; + bool m_active = true; + TfToken + m_registrationType; /// how was this plugin registered (e.g by schematype or by assettype) }; -typedef TfRefPtr TranslatorRefPtr; +typedef TfRefPtr TranslatorRefPtr; typedef std::vector TranslatorRefPtrVector; //---------------------------------------------------------------------------------------------------------------------- @@ -318,209 +337,209 @@ typedef std::vector TranslatorRefPtrVector; class TranslatorManufacture { public: - typedef TfRefPtr RefPtr; ///< handle to a plug-in transla - typedef TfRefPtr ExtraDataPluginPtr; ///< handle to a plug-in transla - typedef std::vector RefPtrVector; - static TfToken TranslatorPrefixAssetType; - AL_USDMAYA_PUBLIC static TfToken TranslatorPrefixSchemaType; - - - /// \brief constructs a registry of translator plugins that are currently registered within usd maya. This construction - /// should only happen once per-proxy shape. - /// \param context the translator context for this registry - AL_USDMAYA_PUBLIC - TranslatorManufacture(TranslatorContextPtr context); - - /// \brief returns a translator for the specified prim. - /// \param prim - /// \return the requested translator type - AL_USDMAYA_PUBLIC - TranslatorRefPtr get(const UsdPrim &prim); - - /// \brief returns a translator for the specified MObject (used for Import) - /// \param mayaObject the maya object for which you wish to check for a plugin node translator - /// \return returns the requested translator type - AL_USDMAYA_PUBLIC - TranslatorRefPtr get(const MObject& mayaObject); - - /// \brief we have a string encoding scheme like "schematype:Mesh", "assettype:foo" to record which translator was used to translate a specific prim - /// \param translatorId the string encoding defining which translator to use - /// \return returns the requested translator type - AL_USDMAYA_PUBLIC - TranslatorRefPtr getTranslatorFromId(const std::string& translatorId); - - /// \brief generates the string encoding about what translator will be used to import a prim based off what translators are currently registered/loaded - /// \param prim the prim to construct a translator for - /// \return the string encoding - AL_USDMAYA_PUBLIC - std::string generateTranslatorId(const UsdPrim& prim); - - - /// \brief returns a list of extra data plugins that may apply to this node type - /// \param mayaObject - /// \return returns a list of extra data plugins that can be applied to the current node - AL_USDMAYA_PUBLIC - std::vector getExtraDataPlugins(const MObject& mayaObject); - - /// \brief activates the translator of the specified type - /// \param types the type names of the translator(s) to activate - /// \return returns the requested translator type - AL_USDMAYA_PUBLIC - void activate(const TfTokenVector& types); - - /// \brief returns a translator for the specified prim type. - /// \param types the type names of the translator(s) to activate - /// \return returns the requested translator type - AL_USDMAYA_PUBLIC - void deactivate(const TfTokenVector& types); - - /// \brief activates the translator of the specified type - /// \param type_name the name of the translator to activate - /// \return returns the requested translator type - AL_USDMAYA_PUBLIC - void activateAll(); - - /// \brief deactivate all translators - AL_USDMAYA_PUBLIC - void deactivateAll(); - - /// \brief check to see if a python translator has been registered for the specified maya node (used for Export) - /// \param mayaObject the maya object to locate a translator for - /// \return returns the python translator (if one is available) - AL_USDMAYA_PUBLIC - static TranslatorRefPtr getPythonTranslator(const MObject& mayaObject); - - /// \brief If a translator is registered for the specified type, delete it. - /// \param type_name the type of the traslator to query - /// \return returns true if the translator was found and deleted, false otherwise - AL_USDMAYA_PUBLIC - static bool deletePythonTranslator(const TfType type_name); - - /// \brief add a new python translator into the context - /// \param traslatorHandle the translator to register - /// \param assetTypeValue the type of asset you wish to process with this translator - /// \return true if the translator returns a valid TfType - AL_USDMAYA_PUBLIC - static bool addPythonTranslator(TranslatorRefPtr translatorHandle, const TfToken& assetTypeValue=TfToken()); - - /// \brief delete all registered python translators - AL_USDMAYA_PUBLIC - static void clearPythonTranslators(); - - /// \brief prepare python translators for use prior to a USD import/export operation - /// \param context the translator context - AL_USDMAYA_PUBLIC - static void preparePythonTranslators(TranslatorContext::RefPtr context); - - /// \brief Register python translators with this manufacture. - /// \param context the translator context - AL_USDMAYA_PUBLIC - void updatePythonTranslators(TranslatorContext::RefPtr context); - - /// \brief return a list of all registered translator plugins - /// \return the list of registered translators - AL_USDMAYA_PUBLIC - static std::vector getPythonTranslators(); + typedef TfRefPtr RefPtr; ///< handle to a plug-in transla + typedef TfRefPtr ExtraDataPluginPtr; ///< handle to a plug-in transla + typedef std::vector RefPtrVector; + static TfToken TranslatorPrefixAssetType; + AL_USDMAYA_PUBLIC static TfToken TranslatorPrefixSchemaType; + + /// \brief constructs a registry of translator plugins that are currently registered within usd + /// maya. This construction + /// should only happen once per-proxy shape. + /// \param context the translator context for this registry + AL_USDMAYA_PUBLIC + TranslatorManufacture(TranslatorContextPtr context); + + /// \brief returns a translator for the specified prim. + /// \param prim + /// \return the requested translator type + AL_USDMAYA_PUBLIC + TranslatorRefPtr get(const UsdPrim& prim); + + /// \brief returns a translator for the specified MObject (used for Import) + /// \param mayaObject the maya object for which you wish to check for a plugin node translator + /// \return returns the requested translator type + AL_USDMAYA_PUBLIC + TranslatorRefPtr get(const MObject& mayaObject); + + /// \brief we have a string encoding scheme like "schematype:Mesh", "assettype:foo" to record + /// which translator was used to translate a specific prim \param translatorId the string + /// encoding defining which translator to use \return returns the requested translator type + AL_USDMAYA_PUBLIC + TranslatorRefPtr getTranslatorFromId(const std::string& translatorId); + + /// \brief generates the string encoding about what translator will be used to import a prim + /// based off what translators are currently registered/loaded \param prim the prim to construct + /// a translator for \return the string encoding + AL_USDMAYA_PUBLIC + std::string generateTranslatorId(const UsdPrim& prim); + + /// \brief returns a list of extra data plugins that may apply to this node type + /// \param mayaObject + /// \return returns a list of extra data plugins that can be applied to the current node + AL_USDMAYA_PUBLIC + std::vector getExtraDataPlugins(const MObject& mayaObject); + + /// \brief activates the translator of the specified type + /// \param types the type names of the translator(s) to activate + /// \return returns the requested translator type + AL_USDMAYA_PUBLIC + void activate(const TfTokenVector& types); + + /// \brief returns a translator for the specified prim type. + /// \param types the type names of the translator(s) to activate + /// \return returns the requested translator type + AL_USDMAYA_PUBLIC + void deactivate(const TfTokenVector& types); + + /// \brief activates the translator of the specified type + /// \param type_name the name of the translator to activate + /// \return returns the requested translator type + AL_USDMAYA_PUBLIC + void activateAll(); + + /// \brief deactivate all translators + AL_USDMAYA_PUBLIC + void deactivateAll(); + + /// \brief check to see if a python translator has been registered for the specified maya node + /// (used for Export) \param mayaObject the maya object to locate a translator for \return + /// returns the python translator (if one is available) + AL_USDMAYA_PUBLIC + static TranslatorRefPtr getPythonTranslator(const MObject& mayaObject); + + /// \brief If a translator is registered for the specified type, delete it. + /// \param type_name the type of the traslator to query + /// \return returns true if the translator was found and deleted, false otherwise + AL_USDMAYA_PUBLIC + static bool deletePythonTranslator(const TfType type_name); + + /// \brief add a new python translator into the context + /// \param traslatorHandle the translator to register + /// \param assetTypeValue the type of asset you wish to process with this translator + /// \return true if the translator returns a valid TfType + AL_USDMAYA_PUBLIC + static bool addPythonTranslator( + TranslatorRefPtr translatorHandle, + const TfToken& assetTypeValue = TfToken()); + + /// \brief delete all registered python translators + AL_USDMAYA_PUBLIC + static void clearPythonTranslators(); + + /// \brief prepare python translators for use prior to a USD import/export operation + /// \param context the translator context + AL_USDMAYA_PUBLIC + static void preparePythonTranslators(TranslatorContext::RefPtr context); + + /// \brief Register python translators with this manufacture. + /// \param context the translator context + AL_USDMAYA_PUBLIC + void updatePythonTranslators(TranslatorContext::RefPtr context); + + /// \brief return a list of all registered translator plugins + /// \return the list of registered translators + AL_USDMAYA_PUBLIC + static std::vector getPythonTranslators(); private: - /// \brief returns a translator for the specified schema - /// \param type_name the schema name - /// \return returns the requested translator type - /// \note any codes that using this probably needs to change to support assettype metadata lookup also!!! (mostly related to update, not done for POC) - TranslatorRefPtr getTranslatorBySchemaType(const TfToken type_name); - - /// \brief returns a translator for the specified metadata value - /// \param assetTypeValue the metadata value - /// \return returns the requested translator type - TranslatorRefPtr getTranslatorByAssetTypeMetadata(const std::string& assetTypeValue); - - /// \brief check to see if a python translator has been registered for the given type name - /// \param type_name the type of the traslator to query - /// \return returns the python translator (if one is available) - static TranslatorRefPtr getPythonTranslatorBySchemaType(const TfToken type_name); - - std::unordered_map m_translatorsMap; - static std::unordered_map m_assetTypeToPythonTranslatorsMap; - std::vector m_extraDataPlugins; - static TranslatorRefPtrVector m_pythonTranslators; - TranslatorRefPtrVector m_contextualisedPythonTranslators; + /// \brief returns a translator for the specified schema + /// \param type_name the schema name + /// \return returns the requested translator type + /// \note any codes that using this probably needs to change to support assettype metadata + /// lookup also!!! (mostly related to update, not done for POC) + TranslatorRefPtr getTranslatorBySchemaType(const TfToken type_name); + + /// \brief returns a translator for the specified metadata value + /// \param assetTypeValue the metadata value + /// \return returns the requested translator type + TranslatorRefPtr getTranslatorByAssetTypeMetadata(const std::string& assetTypeValue); + + /// \brief check to see if a python translator has been registered for the given type name + /// \param type_name the type of the traslator to query + /// \return returns the python translator (if one is available) + static TranslatorRefPtr getPythonTranslatorBySchemaType(const TfToken type_name); + + std::unordered_map m_translatorsMap; + static std::unordered_map m_assetTypeToPythonTranslatorsMap; + std::vector m_extraDataPlugins; + static TranslatorRefPtrVector m_pythonTranslators; + TranslatorRefPtrVector m_contextualisedPythonTranslators; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief the factory interface, used to create an instance of a particular translator type /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -class TranslatorFactoryBase - : public TfType::FactoryBase +class TranslatorFactoryBase : public TfType::FactoryBase { public: - /// \brief overridden by the TranslatorFactory to create a new translator for a given type - /// \param ctx the current translator context - /// \return the plugin translator - AL_USDMAYA_PUBLIC - virtual TfRefPtr create(TranslatorContextPtr ctx) const = 0; + /// \brief overridden by the TranslatorFactory to create a new translator for a given type + /// \param ctx the current translator context + /// \return the plugin translator + AL_USDMAYA_PUBLIC + virtual TfRefPtr create(TranslatorContextPtr ctx) const = 0; }; //---------------------------------------------------------------------------------------------------------------------- /// \brief the factory instance for a given translator type - /// \ingroup translators +/// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -template -class TranslatorFactory : public TranslatorFactoryBase +template class TranslatorFactory : public TranslatorFactoryBase { public: - /// \brief creates a new translator for a given type T - /// \param ctx the current translator context - /// \return the plugin translator associated with type T - TfRefPtr create(TranslatorContextPtr ctx) const override - { return T::create(ctx); } + /// \brief creates a new translator for a given type T + /// \param ctx the current translator context + /// \return the plugin translator associated with type T + TfRefPtr create(TranslatorContextPtr ctx) const override + { + return T::create(ctx); + } }; //---------------------------------------------------------------------------------------------------------------------- /// \brief a macro to declare a plug-in translator /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -#define AL_USDMAYA_DECLARE_TRANSLATOR(PlugClass) \ -typedef PlugClass This; \ -typedef TfRefPtr RefPtr; \ -typedef TfWeakPtr Ptr; \ -AL_MAYA_MACROS_PUBLIC \ -static RefPtr create(TranslatorContextPtr context); - +#define AL_USDMAYA_DECLARE_TRANSLATOR(PlugClass) \ + typedef PlugClass This; \ + typedef TfRefPtr RefPtr; \ + typedef TfWeakPtr Ptr; \ + AL_MAYA_MACROS_PUBLIC \ + static RefPtr create(TranslatorContextPtr context); //---------------------------------------------------------------------------------------------------------------------- /// \brief a macro to define a plug-in translator /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- -#define AL_USDMAYA_DEFINE_TRANSLATOR(PlugClass, TranslatedType) \ -TfRefPtr \ -PlugClass::create(TranslatorContextPtr context) { \ - TfType const &type = TfType::Find(); \ - if(!type.IsUnknown()) { \ - TfRefPtr plugin = TfCreateRefPtr(new This()); \ - plugin->setTranslatedType(type); \ - plugin->setContext(context); \ - if(!plugin->initialize()) return TfRefPtr(); \ - return plugin; \ - } \ - else { \ - TF_CODING_ERROR( \ - "Failed to get %s usd type, maybe the needed plugin is not loaded", \ - typeid(TranslatedType).name()); \ - return TfNullPtr; \ - } \ -} \ - \ -TF_REGISTRY_FUNCTION(TfType) \ -{ \ - TfType::Define>() \ - .SetFactory>(); \ -} +#define AL_USDMAYA_DEFINE_TRANSLATOR(PlugClass, TranslatedType) \ + TfRefPtr PlugClass::create(TranslatorContextPtr context) \ + { \ + TfType const& type = TfType::Find(); \ + if (!type.IsUnknown()) { \ + TfRefPtr plugin = TfCreateRefPtr(new This()); \ + plugin->setTranslatedType(type); \ + plugin->setContext(context); \ + if (!plugin->initialize()) \ + return TfRefPtr(); \ + return plugin; \ + } else { \ + TF_CODING_ERROR( \ + "Failed to get %s usd type, maybe the needed plugin is not loaded", \ + typeid(TranslatedType).name()); \ + return TfNullPtr; \ + } \ + } \ + \ + TF_REGISTRY_FUNCTION(TfType) \ + { \ + TfType::Define>() \ + .SetFactory>(); \ + } //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorContext.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorContext.cpp index ba6e83b219..48a8fb17b6 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorContext.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorContext.cpp @@ -14,10 +14,12 @@ // limitations under the License. // #include "AL/usdmaya/fileio/translators/TranslatorContext.h" -#include "AL/usdmaya/nodes/ProxyShape.h" + #include "AL/usdmaya/DebugCodes.h" -#include +#include "AL/usdmaya/nodes/ProxyShape.h" + #include +#include #include @@ -27,821 +29,823 @@ namespace fileio { namespace translators { //---------------------------------------------------------------------------------------------------------------------- -TranslatorContext::~TranslatorContext() -{ -} +TranslatorContext::~TranslatorContext() { } //---------------------------------------------------------------------------------------------------------------------- UsdStageRefPtr TranslatorContext::getUsdStage() const { - if(m_proxyShape) - return m_proxyShape->usdStage(); - return UsdStageRefPtr(); + if (m_proxyShape) + return m_proxyShape->usdStage(); + return UsdStageRefPtr(); } //---------------------------------------------------------------------------------------------------------------------- void TranslatorContext::validatePrims() { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::validatePrims ** VALIDATE PRIMS **\n"); - for(auto it : m_primMapping) - { - if(it.objectHandle().isValid() && it.objectHandle().isAlive()) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::validatePrims ** VALID HANDLE DETECTED %s **\n", it.path().GetText()); - } - } + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::validatePrims ** VALIDATE PRIMS **\n"); + for (auto it : m_primMapping) { + if (it.objectHandle().isValid() && it.objectHandle().isAlive()) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::validatePrims ** VALID HANDLE DETECTED %s **\n", + it.path().GetText()); + } + } } //---------------------------------------------------------------------------------------------------------------------- bool TranslatorContext::getTransform(const SdfPath& path, MObjectHandle& object) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getTransform %s\n", path.GetText()); - auto it = find(path); - if(it != m_primMapping.end()) - { - if(!it->objectHandle().isValid()) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getTransform - invalid handle\n"); - return false; - } - object = it->object(); - return true; - } - return false; + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getTransform %s\n", path.GetText()); + auto it = find(path); + if (it != m_primMapping.end()) { + if (!it->objectHandle().isValid()) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorContext::getTransform - invalid handle\n"); + return false; + } + object = it->object(); + return true; + } + return false; } //---------------------------------------------------------------------------------------------------------------------- void TranslatorContext::updatePrimTypes() { - auto stage = m_proxyShape->usdStage(); - for(auto it = m_primMapping.begin(); it != m_primMapping.end(); ) - { - SdfPath path(it->path()); - UsdPrim prim = stage->GetPrimAtPath(path); - bool modifiedIt = false; - if(!prim) - { - it = m_primMapping.erase(it); - modifiedIt=true; - } - else - { - std::string translatorId = m_proxyShape->translatorManufacture().generateTranslatorId(prim); - if(it->translatorId()!= translatorId) - { - it->translatorId() = translatorId; - ++it; - modifiedIt=true; - } - } - if (!modifiedIt) - { - ++it; - } - } + auto stage = m_proxyShape->usdStage(); + for (auto it = m_primMapping.begin(); it != m_primMapping.end();) { + SdfPath path(it->path()); + UsdPrim prim = stage->GetPrimAtPath(path); + bool modifiedIt = false; + if (!prim) { + it = m_primMapping.erase(it); + modifiedIt = true; + } else { + std::string translatorId + = m_proxyShape->translatorManufacture().generateTranslatorId(prim); + if (it->translatorId() != translatorId) { + it->translatorId() = translatorId; + ++it; + modifiedIt = true; + } + } + if (!modifiedIt) { + ++it; + } + } } //---------------------------------------------------------------------------------------------------------------------- bool TranslatorContext::getMObject(const SdfPath& path, MObjectHandle& object, MTypeId typeId) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getMObject '%s' \n", path.GetText()); - - auto it = find(path); - if(it != m_primMapping.end()) - { - const MTypeId zero(0); - if(zero != typeId) - { - for(auto temp : it->createdNodes()) - { - MFnDependencyNode fn(temp.object()); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getMObject getting %s\n", fn.typeName().asChar()); - if(fn.typeId() == typeId) - { - object = temp; - if(!object.isAlive()) - MGlobal::displayError(MString("VALIDATION: ") + path.GetText() + MString(" is not alive")); - if(!object.isValid()) - MGlobal::displayError(MString("VALIDATION: ") + path.GetText() + MString(" is not valid")); - return true; + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getMObject '%s' \n", path.GetText()); + + auto it = find(path); + if (it != m_primMapping.end()) { + const MTypeId zero(0); + if (zero != typeId) { + for (auto temp : it->createdNodes()) { + MFnDependencyNode fn(temp.object()); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorContext::getMObject getting %s\n", fn.typeName().asChar()); + if (fn.typeId() == typeId) { + object = temp; + if (!object.isAlive()) + MGlobal::displayError( + MString("VALIDATION: ") + path.GetText() + MString(" is not alive")); + if (!object.isValid()) + MGlobal::displayError( + MString("VALIDATION: ") + path.GetText() + MString(" is not valid")); + return true; + } + } + } else { + if (!it->createdNodes().empty()) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::getMObject getting anything %s\n", + path.GetString().c_str()); + object = it->createdNodes()[0]; + + if (!object.isAlive()) + MGlobal::displayError( + MString("VALIDATION: ") + path.GetText() + MString(" is not alive")); + if (!object.isValid()) + MGlobal::displayError( + MString("VALIDATION: ") + path.GetText() + MString(" is not valid")); + return true; + } } - } - } - else - { - if(!it->createdNodes().empty()) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getMObject getting anything %s\n", path.GetString().c_str()); - object = it->createdNodes()[0]; - - if(!object.isAlive()) - MGlobal::displayError(MString("VALIDATION: ") + path.GetText() + MString(" is not alive")); - if(!object.isValid()) - MGlobal::displayError(MString("VALIDATION: ") + path.GetText() + MString(" is not valid")); - return true; - } } - } - return false; + return false; } //---------------------------------------------------------------------------------------------------------------------- bool TranslatorContext::getMObject(const SdfPath& path, MObjectHandle& object, MFn::Type type) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getMObject '%s' \n", path.GetText()); - - auto it = find(path); - if(it != m_primMapping.end()) - { - const MTypeId zero(0); - if(MFn::kInvalid != type) - { - for(auto temp : it->createdNodes()) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getMObject getting: %s\n", temp.object().apiTypeStr()); - if(temp.object().apiType() == type) - { - object = temp; - if(!object.isAlive()) - MGlobal::displayError(MString("VALIDATION: ") + path.GetText() + MString(" is not alive")); - if(!object.isValid()) - MGlobal::displayError(MString("VALIDATION: ") + path.GetText() + MString(" is not valid")); - return true; + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getMObject '%s' \n", path.GetText()); + + auto it = find(path); + if (it != m_primMapping.end()) { + const MTypeId zero(0); + if (MFn::kInvalid != type) { + for (auto temp : it->createdNodes()) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorContext::getMObject getting: %s\n", temp.object().apiTypeStr()); + if (temp.object().apiType() == type) { + object = temp; + if (!object.isAlive()) + MGlobal::displayError( + MString("VALIDATION: ") + path.GetText() + MString(" is not alive")); + if (!object.isValid()) + MGlobal::displayError( + MString("VALIDATION: ") + path.GetText() + MString(" is not valid")); + return true; + } + } + } else { + if (!it->createdNodes().empty()) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::getMObject getting anything: %s\n", + path.GetString().c_str()); + object = it->createdNodes()[0]; + + if (!object.isAlive()) + MGlobal::displayError( + MString("VALIDATION: ") + path.GetText() + MString(" is not alive")); + if (!object.isValid()) + MGlobal::displayError( + MString("VALIDATION: ") + path.GetText() + MString(" is not valid")); + return true; + } } - } - } - else - { - if(!it->createdNodes().empty()) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getMObject getting anything: %s\n", path.GetString().c_str()); - object = it->createdNodes()[0]; - - if(!object.isAlive()) - MGlobal::displayError(MString("VALIDATION: ") + path.GetText() + MString(" is not alive")); - if(!object.isValid()) - MGlobal::displayError(MString("VALIDATION: ") + path.GetText() + MString(" is not valid")); - return true; - } } - } - return false; + return false; } //---------------------------------------------------------------------------------------------------------------------- bool TranslatorContext::getMObjects(const SdfPath& path, MObjectHandleArray& returned) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getMObjects: %s\n", path.GetText()); - auto it = find(path); - if(it != m_primMapping.end()) - { - returned = it->createdNodes(); - return true; - } - return false; + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getMObjects: %s\n", path.GetText()); + auto it = find(path); + if (it != m_primMapping.end()) { + returned = it->createdNodes(); + return true; + } + return false; } //---------------------------------------------------------------------------------------------------------------------- void TranslatorContext::registerItem(const UsdPrim& prim, MObjectHandle object) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::registerItem adding entry %s[%s]\n", prim.GetPath().GetText(), object.object().apiTypeStr()); - auto iter = findLocation(prim.GetPath()); - if(iter == m_primMapping.end() || iter->path() != prim.GetPath()) - { - //We keep around this legacy plugin identification by type only to allow tests which don't create a proxy shape to run.. - std::string translatorId = m_proxyShape ? m_proxyShape->translatorManufacture().generateTranslatorId(prim) : "schematype:" + prim.GetTypeName().GetString(); - - iter = m_primMapping.insert(iter, PrimLookup(prim.GetPath(), translatorId, object.object())); - } - else - { - iter->setNode(object.object()); - } - - if(object.object() == MObject::kNullObj) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::registerItem primPath=%s translatorId=%s to null MObject\n", prim.GetPath().GetText(), iter->translatorId().c_str()); - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::registerItem primPath=%s translatorId=%s to MObject type %s\n", prim.GetPath().GetText(), iter->translatorId().c_str(), object.object().apiTypeStr()); - } + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::registerItem adding entry %s[%s]\n", + prim.GetPath().GetText(), + object.object().apiTypeStr()); + auto iter = findLocation(prim.GetPath()); + if (iter == m_primMapping.end() || iter->path() != prim.GetPath()) { + // We keep around this legacy plugin identification by type only to allow tests which don't + // create a proxy shape to run.. + std::string translatorId = m_proxyShape + ? m_proxyShape->translatorManufacture().generateTranslatorId(prim) + : "schematype:" + prim.GetTypeName().GetString(); + + iter + = m_primMapping.insert(iter, PrimLookup(prim.GetPath(), translatorId, object.object())); + } else { + iter->setNode(object.object()); + } + + if (object.object() == MObject::kNullObj) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::registerItem primPath=%s translatorId=%s to null MObject\n", + prim.GetPath().GetText(), + iter->translatorId().c_str()); + } else { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::registerItem primPath=%s translatorId=%s to MObject type %s\n", + prim.GetPath().GetText(), + iter->translatorId().c_str(), + object.object().apiTypeStr()); + } } //---------------------------------------------------------------------------------------------------------------------- void TranslatorContext::insertItem(const UsdPrim& prim, MObjectHandle object) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::insertItem adding entry %s[%s]\n", prim.GetPath().GetText(), object.object().apiTypeStr()); - - auto iter = findLocation(prim.GetPath()); - if(iter == m_primMapping.end() || iter->path() != prim.GetPath()) - { - //We keep around this legacy plugin identification by type only to allow tests which don't create a proxy shape to run.. - std::string translatorId = m_proxyShape ? m_proxyShape->translatorManufacture().generateTranslatorId(prim) : "schematype:" + prim.GetTypeName().GetString(); - - iter = m_primMapping.insert(iter, PrimLookup(prim.GetPath(), translatorId, MObject())); - } - - if(object.object() == MObject::kNullObj) - { - return; - } - - iter->createdNodes().push_back(object); - - if(object.object() == MObject::kNullObj) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::insertItem primPath=%s translatorId=%s to null MObject\n", prim.GetPath().GetText(), iter->translatorId().c_str()); - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::insertItem primPath=%s translatorId=%s to MObject type %s\n", prim.GetPath().GetText(), iter->translatorId().c_str(), object.object().apiTypeStr()); - } + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::insertItem adding entry %s[%s]\n", + prim.GetPath().GetText(), + object.object().apiTypeStr()); + + auto iter = findLocation(prim.GetPath()); + if (iter == m_primMapping.end() || iter->path() != prim.GetPath()) { + // We keep around this legacy plugin identification by type only to allow tests which don't + // create a proxy shape to run.. + std::string translatorId = m_proxyShape + ? m_proxyShape->translatorManufacture().generateTranslatorId(prim) + : "schematype:" + prim.GetTypeName().GetString(); + + iter = m_primMapping.insert(iter, PrimLookup(prim.GetPath(), translatorId, MObject())); + } + + if (object.object() == MObject::kNullObj) { + return; + } + + iter->createdNodes().push_back(object); + + if (object.object() == MObject::kNullObj) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::insertItem primPath=%s translatorId=%s to null MObject\n", + prim.GetPath().GetText(), + iter->translatorId().c_str()); + } else { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::insertItem primPath=%s translatorId=%s to MObject type %s\n", + prim.GetPath().GetText(), + iter->translatorId().c_str(), + object.object().apiTypeStr()); + } } - //---------------------------------------------------------------------------------------------------------------------- void TranslatorContext::removeItems(const SdfPath& path) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::removeItems remove under primPath=%s\n", path.GetText()); - auto it = find(path); - if(it != m_primMapping.end() && it->path() == path) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::removeItems removing path=%s\n", it->path().GetText()); - MDGModifier modifier1; - MDagModifier modifier2; - MObjectHandleArray tempXforms; - MStatus status; - - // Store the DAG nodes to delete in a vector which we will sort via their path length - std::vector> dagNodesToDelete; - - auto& nodes = it->createdNodes(); - for(std::size_t j = 0, n = nodes.size(); j < n; ++j) - { - if(nodes[j].isAlive() && nodes[j].isValid()) - { - // Need to reparent nodes first to avoid transform getting deleted and triggering ancestor deletion - // rather than just deleting directly. - MObject obj = nodes[j].object(); - - if(obj.hasFn(MFn::kDagNode)) - { - MFnDagNode fn(obj); - MDagPath path; - fn.getPath(path); - dagNodesToDelete.emplace_back(path.fullPathName().length(), obj); - AL_MAYA_CHECK_ERROR2(status, "failed to delete dag node"); - } - else - { - status = modifier1.deleteNode(obj); - status = modifier1.doIt(); - AL_MAYA_CHECK_ERROR2(status, MString("failed to delete node")); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorContext::removeItems remove under primPath=%s\n", path.GetText()); + auto it = find(path); + if (it != m_primMapping.end() && it->path() == path) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorContext::removeItems removing path=%s\n", it->path().GetText()); + MDGModifier modifier1; + MDagModifier modifier2; + MObjectHandleArray tempXforms; + MStatus status; + + // Store the DAG nodes to delete in a vector which we will sort via their path length + std::vector> dagNodesToDelete; + + auto& nodes = it->createdNodes(); + for (std::size_t j = 0, n = nodes.size(); j < n; ++j) { + if (nodes[j].isAlive() && nodes[j].isValid()) { + // Need to reparent nodes first to avoid transform getting deleted and triggering + // ancestor deletion rather than just deleting directly. + MObject obj = nodes[j].object(); + + if (obj.hasFn(MFn::kDagNode)) { + MFnDagNode fn(obj); + MDagPath path; + fn.getPath(path); + dagNodesToDelete.emplace_back(path.fullPathName().length(), obj); + AL_MAYA_CHECK_ERROR2(status, "failed to delete dag node"); + } else { + status = modifier1.deleteNode(obj); + status = modifier1.doIt(); + AL_MAYA_CHECK_ERROR2(status, MString("failed to delete node")); + } + } else { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::removeItems Invalid MObject was registered with the " + "primPath \"%s\"\n", + path.GetText()); + } } - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::removeItems Invalid MObject was registered with the primPath \"%s\"\n", path.GetText()); - } - } - nodes.clear(); - - if(!dagNodesToDelete.empty()) - { - std::sort(dagNodesToDelete.begin(), dagNodesToDelete.end(), - [](const std::pair& a, const std::pair& b) { return a.first > b.first; }); - - for(auto it : dagNodesToDelete) - { - MObjectHandle handle(it.second); - if(handle.isAlive() && handle.isValid()) - { - if(it.second.hasFn(MFn::kPluginEmitterNode) || - it.second.hasFn(MFn::kPluginTransformNode)|| - it.second.hasFn(MFn::kPluginConstraintNode)|| - it.second.hasFn(MFn::kTransform)) - { - // reparent custom transform nodes under the world prior to deletion. - // This avoids the problem where deleting a custom transform node automatically - // deletes the parent transform (which cascades up the hierarchy until the entire - // scene has been deleted) - status = modifier2.reparentNode(it.second); - modifier2.deleteNode(it.second); - } - else - if(it.second.hasFn(MFn::kPluginShape) || - it.second.hasFn(MFn::kPluginImagePlaneNode)|| - it.second.hasFn(MFn::kShape)) - { - // same issue exists with custom shape nodes, except that we need to create a temp transform - // node to parent the shape under (otherwise the reparent operation will fail!) - MObject node = modifier2.createNode("transform"); - status = modifier2.reparentNode(it.second, node); - status = modifier2.doIt(); - modifier2.deleteNode(node); - } - else - { - modifier2.deleteNode(it.second); - } - status = modifier2.doIt(); + nodes.clear(); + + if (!dagNodesToDelete.empty()) { + std::sort( + dagNodesToDelete.begin(), + dagNodesToDelete.end(), + [](const std::pair& a, const std::pair& b) { + return a.first > b.first; + }); + + for (auto it : dagNodesToDelete) { + MObjectHandle handle(it.second); + if (handle.isAlive() && handle.isValid()) { + if (it.second.hasFn(MFn::kPluginEmitterNode) + || it.second.hasFn(MFn::kPluginTransformNode) + || it.second.hasFn(MFn::kPluginConstraintNode) + || it.second.hasFn(MFn::kTransform)) { + // reparent custom transform nodes under the world prior to deletion. + // This avoids the problem where deleting a custom transform node + // automatically deletes the parent transform (which cascades up the + // hierarchy until the entire scene has been deleted) + status = modifier2.reparentNode(it.second); + modifier2.deleteNode(it.second); + } else if ( + it.second.hasFn(MFn::kPluginShape) + || it.second.hasFn(MFn::kPluginImagePlaneNode) + || it.second.hasFn(MFn::kShape)) { + // same issue exists with custom shape nodes, except that we need to create + // a temp transform node to parent the shape under (otherwise the reparent + // operation will fail!) + MObject node = modifier2.createNode("transform"); + status = modifier2.reparentNode(it.second, node); + status = modifier2.doIt(); + modifier2.deleteNode(node); + } else { + modifier2.deleteNode(it.second); + } + status = modifier2.doIt(); + } + } + AL_MAYA_CHECK_ERROR2(status, "failed to delete dag nodes"); } - } - AL_MAYA_CHECK_ERROR2(status, "failed to delete dag nodes"); + m_primMapping.erase(it); } - m_primMapping.erase(it); - } - validatePrims(); + validatePrims(); } //---------------------------------------------------------------------------------------------------------------------- MString getNodeName(MObject obj) { - if(obj.hasFn(MFn::kDagNode)) - { - MFnDagNode fn(obj); - MDagPath path; - fn.getPath(path); - return path.fullPathName(); - } - MFnDependencyNode fn(obj); - return fn.name(); + if (obj.hasFn(MFn::kDagNode)) { + MFnDagNode fn(obj); + MDagPath path; + fn.getPath(path); + return path.fullPathName(); + } + MFnDependencyNode fn(obj); + return fn.name(); } //---------------------------------------------------------------------------------------------------------------------- MString TranslatorContext::serialise() const { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext:serialise\n"); - std::ostringstream oss; - for(auto& path : m_excludedGeometry) - { - oss << path.first.GetString() << ","; - } - - m_proxyShape->excludedTranslatedGeometryPlug().setString(MString(oss.str().c_str())); - - oss.str(""); - oss.clear(); - - for(auto it : m_primMapping) - { - oss << it.path() << "=" << it.translatorId() << ","; - oss << getNodeName(it.object()); - for(uint32_t i = 0; i < it.createdNodes().size(); ++i) - { - oss << "," << getNodeName(it.createdNodes()[i].object()); - } - if (it.uniqueKey()) - { - oss << ",uniquekey:" << it.uniqueKey(); - } - oss << ";"; - } - return MString(oss.str().c_str()); + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext:serialise\n"); + std::ostringstream oss; + for (auto& path : m_excludedGeometry) { + oss << path.first.GetString() << ","; + } + + m_proxyShape->excludedTranslatedGeometryPlug().setString(MString(oss.str().c_str())); + + oss.str(""); + oss.clear(); + + for (auto it : m_primMapping) { + oss << it.path() << "=" << it.translatorId() << ","; + oss << getNodeName(it.object()); + for (uint32_t i = 0; i < it.createdNodes().size(); ++i) { + oss << "," << getNodeName(it.createdNodes()[i].object()); + } + if (it.uniqueKey()) { + oss << ",uniquekey:" << it.uniqueKey(); + } + oss << ";"; + } + return MString(oss.str().c_str()); } //---------------------------------------------------------------------------------------------------------------------- void TranslatorContext::deserialise(const MString& string) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext:deserialise\n"); - MStringArray strings; - string.split(';', strings); - - for(uint32_t i = 0; i < strings.length(); ++i) - { - MStringArray strings2; - strings[i].split('=', strings2); - - MStringArray strings3; - strings2[1].split(',', strings3); - - MObject obj; - { - MSelectionList sl; - sl.add(strings3[1].asChar()); - sl.getDependNode(0, obj); - } + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext:deserialise\n"); + MStringArray strings; + string.split(';', strings); - PrimLookup lookup(SdfPath(strings2[0].asChar()), strings3[0].asChar(), obj); + for (uint32_t i = 0; i < strings.length(); ++i) { + MStringArray strings2; + strings[i].split('=', strings2); - static const MString uniqueKeyPrefix("uniquekey:"); + MStringArray strings3; + strings2[1].split(',', strings3); - for(uint32_t j = 2; j < strings3.length(); ++j) - { - if (strings3[j].substring(0, 10) == uniqueKeyPrefix) - { - auto keyStr(strings3[j].substring(10, strings3[j].length())); - if (keyStr.length()) + MObject obj; { - try - { - lookup.setUniqueKey(std::stoul(keyStr.asChar())); - } - catch (std::logic_error&) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext:deserialise ignored invalid hash value for prim='%s' [hash='%s']\n", lookup.path().GetText(), keyStr.asChar()); - } + MSelectionList sl; + sl.add(strings3[1].asChar()); + sl.getDependNode(0, obj); } - continue; - } - MSelectionList sl; - sl.add(strings3[j].asChar()); - MObject obj; - sl.getDependNode(0, obj); - lookup.createdNodes().push_back(obj); - } + PrimLookup lookup(SdfPath(strings2[0].asChar()), strings3[0].asChar(), obj); + + static const MString uniqueKeyPrefix("uniquekey:"); + + for (uint32_t j = 2; j < strings3.length(); ++j) { + if (strings3[j].substring(0, 10) == uniqueKeyPrefix) { + auto keyStr(strings3[j].substring(10, strings3[j].length())); + if (keyStr.length()) { + try { + lookup.setUniqueKey(std::stoul(keyStr.asChar())); + } catch (std::logic_error&) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext:deserialise ignored invalid hash value for " + "prim='%s' [hash='%s']\n", + lookup.path().GetText(), + keyStr.asChar()); + } + } + continue; + } + + MSelectionList sl; + sl.add(strings3[j].asChar()); + MObject obj; + sl.getDependNode(0, obj); + lookup.createdNodes().push_back(obj); + } - m_primMapping.push_back(lookup); - } + m_primMapping.push_back(lookup); + } - SdfPathVector vec = m_proxyShape->getPrimPathsFromCommaJoinedString(m_proxyShape->excludedTranslatedGeometryPlug().asString()); - for(auto& it : vec) - { - m_excludedGeometry.emplace(it, it); - } + SdfPathVector vec = m_proxyShape->getPrimPathsFromCommaJoinedString( + m_proxyShape->excludedTranslatedGeometryPlug().asString()); + for (auto& it : vec) { + m_excludedGeometry.emplace(it, it); + } } //---------------------------------------------------------------------------------------------------------------------- -void TranslatorContext::preRemoveEntry(const SdfPath& primPath, SdfPathVector& itemsToRemove, bool callPreUnload) +void TranslatorContext::preRemoveEntry( + const SdfPath& primPath, + SdfPathVector& itemsToRemove, + bool callPreUnload) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::preRemoveEntry primPath=%s\n", primPath.GetText()); - - PrimLookups::iterator end = m_primMapping.end(); - PrimLookups::iterator range_begin = std::lower_bound(m_primMapping.begin(), end, primPath, value_compare()); - PrimLookups::iterator range_end = range_begin; - for(; range_end != end; ++range_end) - { - // due to the joys of sorting, any child prims of this prim being destroyed should appear next to each - // other (one would assume); So if compare does not find a match (the value is something other than zero), - // we are no longer in the same prim root - const SdfPath& childPath = range_end->path(); - - if(!childPath.HasPrefix(primPath)) - { - break; - } - } - - auto stage = m_proxyShape->usdStage(); - - // run the preTearDown stage on each prim. We will walk over the prims in the reverse order here (which will guarentee - // the the itemsToRemove will be ordered such that the child prims will be destroyed before their parents). - auto iter = range_end; - itemsToRemove.reserve(itemsToRemove.size() + range_end - range_begin); - while(iter != range_begin) - { - --iter; - PrimLookup& node = *iter; - - if(std::find(itemsToRemove.begin(), itemsToRemove.end(), node.path()) != itemsToRemove.end()) - { - // Same exact path has already been processed and added to the list of itemsToRemove. - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::preRemoveEntry skipping path thats already in " - "itemsToRemove. primPath=%s\n", primPath.GetText()); - } - else - { - itemsToRemove.push_back(node.path()); - auto prim = stage->GetPrimAtPath(node.path()); - if (prim && callPreUnload) - { - preUnloadPrim(prim, node.object()); - } - } - } + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorContext::preRemoveEntry primPath=%s\n", primPath.GetText()); + + PrimLookups::iterator end = m_primMapping.end(); + PrimLookups::iterator range_begin + = std::lower_bound(m_primMapping.begin(), end, primPath, value_compare()); + PrimLookups::iterator range_end = range_begin; + for (; range_end != end; ++range_end) { + // due to the joys of sorting, any child prims of this prim being destroyed should appear + // next to each other (one would assume); So if compare does not find a match (the value is + // something other than zero), we are no longer in the same prim root + const SdfPath& childPath = range_end->path(); + + if (!childPath.HasPrefix(primPath)) { + break; + } + } + + auto stage = m_proxyShape->usdStage(); + + // run the preTearDown stage on each prim. We will walk over the prims in the reverse order here + // (which will guarentee the the itemsToRemove will be ordered such that the child prims will be + // destroyed before their parents). + auto iter = range_end; + itemsToRemove.reserve(itemsToRemove.size() + range_end - range_begin); + while (iter != range_begin) { + --iter; + PrimLookup& node = *iter; + + if (std::find(itemsToRemove.begin(), itemsToRemove.end(), node.path()) + != itemsToRemove.end()) { + // Same exact path has already been processed and added to the list of itemsToRemove. + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::preRemoveEntry skipping path thats already in " + "itemsToRemove. primPath=%s\n", + primPath.GetText()); + } else { + itemsToRemove.push_back(node.path()); + auto prim = stage->GetPrimAtPath(node.path()); + if (prim && callPreUnload) { + preUnloadPrim(prim, node.object()); + } + } + } } //---------------------------------------------------------------------------------------------------------------------- void TranslatorContext::removeEntries(const SdfPathVector& itemsToRemove) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::removeEntries\n"); - auto stage = m_proxyShape->usdStage(); - - MDagModifier modifier; - MStatus status; + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::removeEntries\n"); + auto stage = m_proxyShape->usdStage(); + + MDagModifier modifier; + MStatus status; + + // so now we need to unload the prims (itemsToRemove is reverse sorted so we won't nuke parents + // before children) + auto iter = itemsToRemove.begin(); + while (iter != itemsToRemove.end()) { + auto path = *iter; + auto node + = std::lower_bound(m_primMapping.begin(), m_primMapping.end(), path, value_compare()); + if (node == m_primMapping.end()) { + ++iter; + continue; + } + bool isInTransformChain = isPrimInTransformChain(path); - // so now we need to unload the prims (itemsToRemove is reverse sorted so we won't nuke parents before children) - auto iter = itemsToRemove.begin(); - while(iter != itemsToRemove.end()) - { - auto path = *iter; - auto node = std::lower_bound(m_primMapping.begin(), m_primMapping.end(), path, value_compare()); - if(node == m_primMapping.end()) - { - ++iter; - continue; - } - bool isInTransformChain = isPrimInTransformChain(path); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorContext::removeEntries removing: %s\n", iter->GetText()); + if (node->objectHandle().isValid() && node->objectHandle().isAlive()) { + unloadPrim(path, node->object()); + } - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::removeEntries removing: %s\n", iter->GetText()); - if(node->objectHandle().isValid() && node->objectHandle().isAlive()) - { - unloadPrim(path, node->object()); - } + // The item might already have been removed by a translator... + if (node != m_primMapping.end() && node->path() == path) { + // remove nodes from map + m_primMapping.erase(node); + } - // The item might already have been removed by a translator... - if(node != m_primMapping.end() && node->path() == path) - { - // remove nodes from map - m_primMapping.erase(node); - } + if (isInTransformChain) { + m_proxyShape->removeUsdTransformChain(path, modifier, nodes::ProxyShape::kRequired); + } - if(isInTransformChain) - { - m_proxyShape->removeUsdTransformChain(path, modifier, nodes::ProxyShape::kRequired); + ++iter; } - - ++iter; - } - status = modifier.doIt(); - AL_MAYA_CHECK_ERROR2(status, "failed to remove translator prims."); + status = modifier.doIt(); + AL_MAYA_CHECK_ERROR2(status, "failed to remove translator prims."); } //---------------------------------------------------------------------------------------------------------------------- void TranslatorContext::updateUniqueKeys() { - auto stage = getUsdStage(); - for (auto& lookup: m_primMapping) - { - const auto& prim = stage->GetPrimAtPath(lookup.path()); - if (prim) - { - std::string translatorId = getTranslatorIdForPath(lookup.path()); - auto translator = m_proxyShape->translatorManufacture().getTranslatorFromId(translatorId); - if(translator) - { - auto key(translator->generateUniqueKey(prim)); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::updateUniqueKeys [generateUniqueKey] prim='%s', uniqueKey='%lu'\n", lookup.path().GetText(), key); - lookup.setUniqueKey(key); - } - } - } + auto stage = getUsdStage(); + for (auto& lookup : m_primMapping) { + const auto& prim = stage->GetPrimAtPath(lookup.path()); + if (prim) { + std::string translatorId = getTranslatorIdForPath(lookup.path()); + auto translator + = m_proxyShape->translatorManufacture().getTranslatorFromId(translatorId); + if (translator) { + auto key(translator->generateUniqueKey(prim)); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::updateUniqueKeys [generateUniqueKey] prim='%s', " + "uniqueKey='%lu'\n", + lookup.path().GetText(), + key); + lookup.setUniqueKey(key); + } + } + } } //---------------------------------------------------------------------------------------------------------------------- void TranslatorContext::updateUniqueKey(const UsdPrim& prim) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::updateUniqueKey\n"); - - const auto path(prim.GetPath()); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::updateUniqueKey [generateUniqueKey] updating unique key for prim='%s'\n", path.GetText()); - - std::string translatorId = getTranslatorIdForPath(path); - auto translator = m_proxyShape->translatorManufacture().getTranslatorFromId(translatorId); - if(translator) - { - auto it = find(path); - if(it != m_primMapping.end() && it->path() == path) - { - auto key(translator->generateUniqueKey(prim)); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::updateUniqueKey [generateUniqueKey] prim='%s', uniqueKey='%lu', previousUniqueKey='%lu'\n", path.GetText(), key, it->uniqueKey()); - it->setUniqueKey(key); + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::updateUniqueKey\n"); + + const auto path(prim.GetPath()); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::updateUniqueKey [generateUniqueKey] updating unique key for " + "prim='%s'\n", + path.GetText()); + + std::string translatorId = getTranslatorIdForPath(path); + auto translator = m_proxyShape->translatorManufacture().getTranslatorFromId(translatorId); + if (translator) { + auto it = find(path); + if (it != m_primMapping.end() && it->path() == path) { + auto key(translator->generateUniqueKey(prim)); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::updateUniqueKey [generateUniqueKey] prim='%s', " + "uniqueKey='%lu', previousUniqueKey='%lu'\n", + path.GetText(), + key, + it->uniqueKey()); + it->setUniqueKey(key); + } } - } } //---------------------------------------------------------------------------------------------------------------------- void TranslatorContext::preUnloadPrim(UsdPrim& prim, const MObject& primObj) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::preUnloadPrim %s", prim.GetPath().GetText()); - assert(m_proxyShape); - auto stage = m_proxyShape->getUsdStage(); - if(stage) - { - std::string translatorId = m_proxyShape->context()->getTranslatorIdForPath(prim.GetPath()); - - fileio::translators::TranslatorRefPtr translator = m_proxyShape->translatorManufacture().getTranslatorFromId(translatorId); - if(translator) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::preUnloadPrim [preTearDown] prim=%s\n", prim.GetPath().GetText()); - translator->preTearDown(prim); - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::preUnloadPrim [preTearDown] prim=%s\n. Could not find usd translator plugin instance for prim!", prim.GetPath().GetText()); - MGlobal::displayError(MString("TranslatorContext::preUnloadPrim could not find usd translator plugin instance for prim: ") + prim.GetPath().GetText() + " type: " + translatorId.c_str()); - } - } - else - { - MGlobal::displayError(MString("Could not unload prim: \"") + prim.GetPath().GetText() + MString("\", the stage is invalid")); - } + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorContext::preUnloadPrim %s", prim.GetPath().GetText()); + assert(m_proxyShape); + auto stage = m_proxyShape->getUsdStage(); + if (stage) { + std::string translatorId = m_proxyShape->context()->getTranslatorIdForPath(prim.GetPath()); + + fileio::translators::TranslatorRefPtr translator + = m_proxyShape->translatorManufacture().getTranslatorFromId(translatorId); + if (translator) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::preUnloadPrim [preTearDown] prim=%s\n", + prim.GetPath().GetText()); + translator->preTearDown(prim); + } else { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::preUnloadPrim [preTearDown] prim=%s\n. Could not find usd " + "translator plugin instance for prim!", + prim.GetPath().GetText()); + MGlobal::displayError( + MString("TranslatorContext::preUnloadPrim could not find usd translator plugin " + "instance for prim: ") + + prim.GetPath().GetText() + " type: " + translatorId.c_str()); + } + } else { + MGlobal::displayError( + MString("Could not unload prim: \"") + prim.GetPath().GetText() + + MString("\", the stage is invalid")); + } } //---------------------------------------------------------------------------------------------------------------------- void TranslatorContext::unloadPrim(const SdfPath& path, const MObject& primObj) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::unloadPrim\n"); - assert(m_proxyShape); - auto stage = m_proxyShape->usdStage(); - if(stage) - { - std::string translatorId = m_proxyShape->context()->getTranslatorIdForPath(path); - - fileio::translators::TranslatorRefPtr translator = m_proxyShape->translatorManufacture().getTranslatorFromId(translatorId); - if(translator) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::unloadPrim [tearDown] prim=%s\n", path.GetText()); - - UsdPrim prim = stage->GetPrimAtPath(path); - if(prim) - { - // run through the extra data plugins to apply to this prim - auto dataPlugins = m_proxyShape->translatorManufacture().getExtraDataPlugins(primObj); - for(auto dataPlugin : dataPlugins) - { - dataPlugin->preTearDown(prim); + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::unloadPrim\n"); + assert(m_proxyShape); + auto stage = m_proxyShape->usdStage(); + if (stage) { + std::string translatorId = m_proxyShape->context()->getTranslatorIdForPath(path); + + fileio::translators::TranslatorRefPtr translator + = m_proxyShape->translatorManufacture().getTranslatorFromId(translatorId); + if (translator) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorContext::unloadPrim [tearDown] prim=%s\n", path.GetText()); + + UsdPrim prim = stage->GetPrimAtPath(path); + if (prim) { + // run through the extra data plugins to apply to this prim + auto dataPlugins + = m_proxyShape->translatorManufacture().getExtraDataPlugins(primObj); + for (auto dataPlugin : dataPlugins) { + dataPlugin->preTearDown(prim); + } + + translator->preTearDown(prim); + } else { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::preTearDown was skipped because the path '%s' was " + "invalid\n", + path.GetText()); + } + + MStatus status = translator->tearDown(path); + switch (status.statusCode()) { + case MStatus::kSuccess: break; + + case MStatus::kNotImplemented: + MGlobal::displayError( + MString("A variant switch has occurred on a NON-CONFORMING prim, of type: ") + + translatorId.c_str() + MString(" located at prim path \"") + path.GetText() + + MString("\"")); + break; + + default: + MGlobal::displayError( + MString("A variant switch has caused an error on tear down on prim, of type: ") + + translatorId.c_str() + MString(" located at prim path \"") + path.GetText() + + MString("\"")); + break; + } + } else { + MGlobal::displayError( + MString("could not find usd translator plugin instance for prim: ") + path.GetText() + + " translatorId: " + translatorId.c_str()); } - - translator->preTearDown(prim); - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::preTearDown was skipped because the path '%s' was invalid\n", path.GetText()); - } - - MStatus status = translator->tearDown(path); - switch(status.statusCode()) - { - case MStatus::kSuccess: - break; - - case MStatus::kNotImplemented: - MGlobal::displayError( - MString("A variant switch has occurred on a NON-CONFORMING prim, of type: ") + translatorId.c_str() + - MString(" located at prim path \"") + path.GetText() + MString("\"") - ); - break; - - default: + } else { MGlobal::displayError( - MString("A variant switch has caused an error on tear down on prim, of type: ") + translatorId.c_str() + - MString(" located at prim path \"") + path.GetText() + MString("\"") - ); - break; - } - } - else - { - MGlobal::displayError(MString("could not find usd translator plugin instance for prim: ") + path.GetText() + " translatorId: " + translatorId.c_str()); - } - } - else - { - MGlobal::displayError(MString("Could not unload prim: \"") + path.GetText() + MString("\", the stage is invalid")); - } + MString("Could not unload prim: \"") + path.GetText() + + MString("\", the stage is invalid")); + } } //---------------------------------------------------------------------------------------------------------------------- -bool TranslatorContext::isNodeAncestorOf(MObjectHandle ancestorHandle, MObjectHandle objectHandleToTest) +bool TranslatorContext::isNodeAncestorOf( + MObjectHandle ancestorHandle, + MObjectHandle objectHandleToTest) { - if(!ancestorHandle.isValid() || !ancestorHandle.isAlive()) - { - return false; - } - - if(!objectHandleToTest.isValid() || !objectHandleToTest.isAlive()) - { - return false; - } + if (!ancestorHandle.isValid() || !ancestorHandle.isAlive()) { + return false; + } - MObject ancestorNode = ancestorHandle.object(); - MObject nodeToTest = objectHandleToTest.object(); - if(ancestorNode == nodeToTest) - { - return false; - } + if (!objectHandleToTest.isValid() || !objectHandleToTest.isAlive()) { + return false; + } - MStatus parentStatus = MS::kSuccess; - MFnDagNode dagFn(nodeToTest, &parentStatus); + MObject ancestorNode = ancestorHandle.object(); + MObject nodeToTest = objectHandleToTest.object(); + if (ancestorNode == nodeToTest) { + return false; + } - // If it is not a DAG node: - if(!parentStatus) - { - return false; - } + MStatus parentStatus = MS::kSuccess; + MFnDagNode dagFn(nodeToTest, &parentStatus); - bool isParent = dagFn.isChildOf(ancestorNode, &parentStatus); - if(isParent) - { - return true; - } + // If it is not a DAG node: + if (!parentStatus) { + return false; + } - unsigned int parentC = dagFn.parentCount(&parentStatus); - if(!parentStatus) - { - return false; - } + bool isParent = dagFn.isChildOf(ancestorNode, &parentStatus); + if (isParent) { + return true; + } - for(unsigned int i=0; iparentTransform(); - MObject proxyTransformNode = proxyShapeTransformDagPath.node(); - MObjectHandle proxyTransformNodeHandle(proxyTransformNode); - - - // First test the Maya node that prim is for, this is for MayaReference.. - MObjectHandle parentHandle; - if(getTransform(path, parentHandle)) - { - if(isNodeAncestorOf(proxyTransformNodeHandle, parentHandle)) - { - return true; + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("TranslatorContext::isPrimInTransformChain %s\n", path.GetText()); + + MDagPath proxyShapeTransformDagPath = m_proxyShape->parentTransform(); + MObject proxyTransformNode = proxyShapeTransformDagPath.node(); + MObjectHandle proxyTransformNodeHandle(proxyTransformNode); + + // First test the Maya node that prim is for, this is for MayaReference.. + MObjectHandle parentHandle; + if (getTransform(path, parentHandle)) { + if (isNodeAncestorOf(proxyTransformNodeHandle, parentHandle)) { + return true; + } } - } - // Now test the Maya node that translator created, this is for DAG hierarchy transform|shape.. - MObjectHandleArray mayaNodes; - bool everCreatedNodes = getMObjects(path, mayaNodes); - if(!everCreatedNodes) - { - return false; - } + // Now test the Maya node that translator created, this is for DAG hierarchy transform|shape.. + MObjectHandleArray mayaNodes; + bool everCreatedNodes = getMObjects(path, mayaNodes); + if (!everCreatedNodes) { + return false; + } - size_t nodeCount = mayaNodes.size(); - for(size_t i=0; iGetPrimAtPath(pathToAdd); - if(!parentPrim) - break; - - if(parentPrim.IsInstance()) + if (m_proxyShape) { + auto foundPath = m_excludedGeometry.find(newPath); + if (foundPath != m_excludedGeometry.end()) { + return false; + } + + UsdStageRefPtr stage = getUsdStage(); + SdfPath pathToAdd = newPath; + bool hasInstanceParent = false; { - hasInstanceParent = true; - break; + UsdPrim parentPrim; + do { + pathToAdd = pathToAdd.GetParentPath(); + parentPrim = stage->GetPrimAtPath(pathToAdd); + if (!parentPrim) + break; + + if (parentPrim.IsInstance()) { + hasInstanceParent = true; + break; + } + } while (!pathToAdd.IsEmpty()); } - } - while(!pathToAdd.IsEmpty()); - } - if(hasInstanceParent) - { - m_excludedGeometry.emplace(newPath, pathToAdd); - } - else - { - m_excludedGeometry.emplace(newPath, newPath); + if (hasInstanceParent) { + m_excludedGeometry.emplace(newPath, pathToAdd); + } else { + m_excludedGeometry.emplace(newPath, newPath); + } + m_isExcludedGeometryDirty = true; + return true; } - m_isExcludedGeometryDirty = true; - return true; - } - return false; + return false; } //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorContext.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorContext.h index bcad9f3e2d..1c572f9215 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorContext.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorContext.h @@ -18,7 +18,6 @@ #include #include #include -#include #include #include @@ -32,12 +31,13 @@ #include #include +#include + #include #include PXR_NAMESPACE_USING_DIRECTIVE - namespace AL { namespace usdmaya { namespace fileio { @@ -46,486 +46,510 @@ namespace translators { typedef std::vector MObjectHandleArray; typedef std::map SdfInstanceMap; - //---------------------------------------------------------------------------------------------------------------------- -/// \brief Transient aggregate of values that aims to direct the Translation of Prims. Typically an object of this struct -/// is created and used for a set group of prim path translations then it is destroyed. +/// \brief Transient aggregate of values that aims to direct the Translation of Prims. Typically +/// an object of this struct is created and used for a set group of prim path translations then it +/// is destroyed. /// /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- struct TranslatorParameters { - /// \brief Flag that determines if all Prim schema types should be forced to be imported - inline void setForcePrimImport(bool forceImport) - { m_forcePrimImport = forceImport; } + /// \brief Flag that determines if all Prim schema types should be forced to be imported + inline void setForcePrimImport(bool forceImport) { m_forcePrimImport = forceImport; } - /// \brief Retrieves the flag that determines if all the Prim schema types should be imported - inline bool forceTranslatorImport() const - { return m_forcePrimImport; } + /// \brief Retrieves the flag that determines if all the Prim schema types should be imported + inline bool forceTranslatorImport() const { return m_forcePrimImport; } - /// \brief should pushToPrim be enabled on created transforms - inline void setPushToPrim(bool value) - { m_pushToPrim = value; } + /// \brief should pushToPrim be enabled on created transforms + inline void setPushToPrim(bool value) { m_pushToPrim = value; } - /// \brief should pushToPrim be enabled on created transforms - inline bool pushToPrim() const - { return m_pushToPrim; } + /// \brief should pushToPrim be enabled on created transforms + inline bool pushToPrim() const { return m_pushToPrim; } - /// \brief should readAnimatedValues be enabled on created transforms - inline void setReadAnimatedValues(bool value) - { m_readAnimatedValues = value; } + /// \brief should readAnimatedValues be enabled on created transforms + inline void setReadAnimatedValues(bool value) { m_readAnimatedValues = value; } - /// \brief should readAnimatedValues be enabled on created transforms - inline bool readAnimatedValues() const - { return m_readAnimatedValues; } + /// \brief should readAnimatedValues be enabled on created transforms + inline bool readAnimatedValues() const { return m_readAnimatedValues; } private: - bool m_forcePrimImport = false; - bool m_pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"); - bool m_readAnimatedValues = false; + bool m_forcePrimImport = false; + bool m_pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"); + bool m_readAnimatedValues = false; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief This class provides a context to store mappings between UsdPrims, and the Maya nodes that represent them. +/// \brief This class provides a context to store mappings between UsdPrims, and the Maya nodes +/// that represent them. /// /// \ingroup translators //---------------------------------------------------------------------------------------------------------------------- struct TranslatorContext - : public TfRefBase, TfWeakBase + : public TfRefBase + , TfWeakBase { public: - typedef TranslatorContext This; ///< this type - typedef TfRefPtr RefPtr; ///< pointer to this type + typedef TranslatorContext This; ///< this type + typedef TfRefPtr RefPtr; ///< pointer to this type - /// \brief construct a new context for the specified proxy shape node - /// \param proxyShape the proxy shape to associate the context with - /// \return a new context - static RefPtr create(nodes::ProxyShape* proxyShape) + /// \brief construct a new context for the specified proxy shape node + /// \param proxyShape the proxy shape to associate the context with + /// \return a new context + static RefPtr create(nodes::ProxyShape* proxyShape) { - RefPtr res = TfCreateRefPtr(new This(proxyShape)); - res->setForceDefaultRead(false); - return res; + RefPtr res = TfCreateRefPtr(new This(proxyShape)); + res->setForceDefaultRead(false); + return res; } - /// \brief return the proxy shape associated with this context - /// \return the proxy shape - const nodes::ProxyShape* getProxyShape() const - { return m_proxyShape; } - - /// \brief return the usd stage associated with this context - /// \return the usd stage - AL_USDMAYA_PUBLIC - UsdStageRefPtr getUsdStage() const; - - /// \brief given a USD prim, this will see whether a maya node exists for it. If it does, that will - /// be returned in the object handle. If the object is found, true is returned, otherwise false. - /// \param prim the usd prim - /// \param object the returned handle - /// \return true if the prim exists - bool getTransform(const UsdPrim& prim, MObjectHandle& object) - { return getTransform(prim.GetPath(), object); } - - /// \brief given a USD prim path, this will see whether a maya node exists for it. If it does, that will - /// be returned in the object handle. If the object is found, true is returned, otherwise false. - /// \param path the usd prim path - /// \param object the returned handle - /// \return true if the prim exists - AL_USDMAYA_PUBLIC - bool getTransform(const SdfPath& path, MObjectHandle& object); - - /// \brief given a USD prim, this will see whether a maya node exists for it. If it does, that will - /// be returned in the object handle. If the object is found, true is returned, otherwise false. - /// \param prim the usd prim - /// \param object the returned handle - /// \param type the type ID of the maya object you wish to retrieve. If the type ID is 0, the first node - /// found will be returned. This may be useful if a prim type may create a type of node - /// that is not known at compile time (e.g. a prim that creates a lambert, blinn, or phong based on - /// some enum attribute). Another alternative would be to query all of the maya nodes via getMObjects - /// \return true if the prim exists - bool getMObject(const UsdPrim& prim, MObjectHandle& object, MTypeId type) - { return getMObject(prim.GetPath(), object, type); } - - /// \brief given a USD prim path, this will see whether a maya node exists for it. If it does, that will - /// be returned in the object handle. If the object is found, true is returned, otherwise false. - /// \param path the usd prim path - /// \param object the returned handle - /// \param type the type ID of the maya object you wish to retrieve. If the type ID is 0, the first node - /// found will be returned. This may be useful if a prim type may create a type of node - /// that is not known at compile time (e.g. a prim that creates a lambert, blinn, or phong based on - /// some enum attribute). Another alternative would be to query all of the maya nodes via getMObjects - /// \return true if the prim exists - AL_USDMAYA_PUBLIC - bool getMObject(const SdfPath& path, MObjectHandle& object, MTypeId type); - - /// \brief given a USD prim, this will see whether a maya node exists for it. If it does, that will - /// be returned in the object handle. If the object is found, true is returned, otherwise false. - /// \param prim the usd prim - /// \param object the returned handle - /// \param type the type of the maya object you wish to retrieve. If the type is MFn::kInvalid, then the - /// first node found will be returned. This may be useful if a prim type may create a type of node - /// that is not known at compile time (e.g. a prim that creates a lambert, blinn, or phong based on - /// some enum attribute). Another alternative would be to query all of the maya nodes via getMObjects - /// \return true if the prim exists - bool getMObject(const UsdPrim& prim, MObjectHandle& object, MFn::Type type) - { return getMObject(prim.GetPath(), object, type); } - - /// \brief given a USD prim path, this will see whether a maya node exists for it. If it does, that will - /// be returned in the object handle. If the object is found, true is returned, otherwise false. - /// \param path the usd prim path - /// \param object the returned handle - /// \param type the type of the maya object you wish to retrieve. If the type is MFn::kInvalid, then the - /// first node found will be returned. This may be useful if a prim type may create a type of node - /// that is not known at compile time (e.g. a prim that creates a lambert, blinn, or phong based on - /// some enum attribute). Another alternative would be to query all of the maya nodes via getMObjects - /// \return true if the prim exists - AL_USDMAYA_PUBLIC - bool getMObject(const SdfPath& path, MObjectHandle& object, MFn::Type type); - - /// \brief returns all of the maya nodes that were created by the specific prim - /// \param prim the prim to query - /// \param returned the returned list of MObjects - /// \return true if a reference to the prim was found - bool getMObjects(const UsdPrim& prim, MObjectHandleArray& returned) - { return getMObjects(prim.GetPath(), returned); } - - /// \brief returns all of the maya nodes that were created by the specific prim - /// \param path the path to the prim to query - /// \param returned the returned list of MObjects - /// \return true if a reference to the prim was found - AL_USDMAYA_PUBLIC - bool getMObjects(const SdfPath& path, MObjectHandleArray& returned); - - /// \brief If within your custom translator plug-in you need to create any maya nodes, associate that maya - /// node with the prim path by calling this method - /// \param prim the prim you are currently importing in a translator - /// \param object the handle to the maya node you have created. - AL_USDMAYA_PUBLIC - void insertItem(const UsdPrim& prim, MObjectHandle object); - - /// \brief during a variant switch, if we lose a prim, then it's path will be passed into this method, and - /// all the maya nodes that were created for it will be nuked. - /// \param prim the usd prim that was removed due to a variant switch - void removeItems(const UsdPrim& prim) - { removeItems(prim.GetPath()); } - - /// \brief during a variant switch, if we lose a prim, then it's path will be passed into this method, and - /// all the maya nodes that were created for it will be nuked. - /// \param path path to the usd prim that was removed due to a variant switch - AL_USDMAYA_PUBLIC - void removeItems(const SdfPath& path); - - /// \brief dtor - AL_USDMAYA_PUBLIC - ~TranslatorContext(); - - /// \brief given a path to a prim, return the translator we are aware of at that path - /// \param path the prim path of a prim that was imported via a custom translator plug-in - /// \return the type name for that prim - std::string getTranslatorIdForPath(SdfPath path) const - { - const auto it = find(path); - if(it != m_primMapping.end()) + /// \brief return the proxy shape associated with this context + /// \return the proxy shape + const nodes::ProxyShape* getProxyShape() const { return m_proxyShape; } + + /// \brief return the usd stage associated with this context + /// \return the usd stage + AL_USDMAYA_PUBLIC + UsdStageRefPtr getUsdStage() const; + + /// \brief given a USD prim, this will see whether a maya node exists for it. If it does, that + /// will + /// be returned in the object handle. If the object is found, true is returned, + /// otherwise false. + /// \param prim the usd prim + /// \param object the returned handle + /// \return true if the prim exists + bool getTransform(const UsdPrim& prim, MObjectHandle& object) { - return it->translatorId(); + return getTransform(prim.GetPath(), object); } - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("TranslatorContext::getTranslatorForPath did not find item in mapping.%s\n", path.GetText()); - return std::string(); - } - - /// \brief this method is used after a variant switch to check to see if the prim types have changed in the - /// stage, and will update the internal state accordingly. - AL_USDMAYA_PUBLIC - void updatePrimTypes(); - - /// \brief Internal method. - /// If within your custom translator plug-in you need to create any maya nodes, associate that maya - /// node with the prim path by calling this method - /// \param prim the prim you are currently importing in a translator - /// \param object the handle to the maya node you have created. - AL_USDMAYA_PUBLIC - void registerItem(const UsdPrim& prim, MObjectHandle object); - - /// \brief serialises the content of the translator context to a text string. - /// \return the translator context serialised into a string - AL_USDMAYA_PUBLIC - MString serialise() const; - - /// \brief deserialises the string back into the translator context - /// \param string the string to deserialised - AL_USDMAYA_PUBLIC - void deserialise(const MString& string); - - /// \brief debugging utility to help keep track of prims during a variant switch - AL_USDMAYA_PUBLIC - void validatePrims(); - - /// \brief This method is used to determine whether this DB has an entry for the specified prim path and the given translator. - /// This is used within a variant switch to determine if a node can be updated, or whether it needs to be imported. - /// \param path the path to the prim to query - /// \param translatorId - /// \return true if an entry is found that matches, false otherwise - bool hasEntry(const SdfPath& path, const std::string& translatorId) - { - auto it = find(path); - if(it != m_primMapping.end()) + + /// \brief given a USD prim path, this will see whether a maya node exists for it. If it does, + /// that will + /// be returned in the object handle. If the object is found, true is returned, + /// otherwise false. + /// \param path the usd prim path + /// \param object the returned handle + /// \return true if the prim exists + AL_USDMAYA_PUBLIC + bool getTransform(const SdfPath& path, MObjectHandle& object); + + /// \brief given a USD prim, this will see whether a maya node exists for it. If it does, that + /// will + /// be returned in the object handle. If the object is found, true is returned, + /// otherwise false. + /// \param prim the usd prim + /// \param object the returned handle + /// \param type the type ID of the maya object you wish to retrieve. If the type ID is 0, the + /// first node + /// found will be returned. This may be useful if a prim type may create a type of node + /// that is not known at compile time (e.g. a prim that creates a lambert, blinn, or + /// phong based on some enum attribute). Another alternative would be to query all of + /// the maya nodes via getMObjects + /// \return true if the prim exists + bool getMObject(const UsdPrim& prim, MObjectHandle& object, MTypeId type) + { + return getMObject(prim.GetPath(), object, type); + } + + /// \brief given a USD prim path, this will see whether a maya node exists for it. If it does, + /// that will + /// be returned in the object handle. If the object is found, true is returned, + /// otherwise false. + /// \param path the usd prim path + /// \param object the returned handle + /// \param type the type ID of the maya object you wish to retrieve. If the type ID is 0, the + /// first node + /// found will be returned. This may be useful if a prim type may create a type of node + /// that is not known at compile time (e.g. a prim that creates a lambert, blinn, or + /// phong based on some enum attribute). Another alternative would be to query all of + /// the maya nodes via getMObjects + /// \return true if the prim exists + AL_USDMAYA_PUBLIC + bool getMObject(const SdfPath& path, MObjectHandle& object, MTypeId type); + + /// \brief given a USD prim, this will see whether a maya node exists for it. If it does, that + /// will + /// be returned in the object handle. If the object is found, true is returned, + /// otherwise false. + /// \param prim the usd prim + /// \param object the returned handle + /// \param type the type of the maya object you wish to retrieve. If the type is MFn::kInvalid, + /// then the + /// first node found will be returned. This may be useful if a prim type may create a + /// type of node that is not known at compile time (e.g. a prim that creates a lambert, + /// blinn, or phong based on some enum attribute). Another alternative would be to query + /// all of the maya nodes via getMObjects + /// \return true if the prim exists + bool getMObject(const UsdPrim& prim, MObjectHandle& object, MFn::Type type) { - return translatorId == it->translatorId(); + return getMObject(prim.GetPath(), object, type); } - return false; - } - - /// \brief This is called during a variant switch to determine whether the variant switch will allow Maya nodes - /// to be updated, or whether they need to be deleted. - /// \param primPath the path to the prim that triggered the variant switch - /// \param itemsToRemove the returned list of items that need to be removed - /// \param callPreUnload true calling the preUnload on all the prims is needed. - AL_USDMAYA_PUBLIC - void preRemoveEntry(const SdfPath& primPath, SdfPathVector& itemsToRemove, bool callPreUnload=true); - - /// \brief call this to remove a prim from the DB (you do not need to lock/unlock here). - /// \param itemsToRemove the prims that need to be removed from the DB. tearDown will be called on each prim - AL_USDMAYA_PUBLIC - void removeEntries(const SdfPathVector& itemsToRemove); - - /// \brief Get unique key for specified prim path. - /// \param path target prim path - /// \return unique key value - std::size_t getUniqueKeyForPath(const SdfPath& path) - { - auto it = find(path); - if(it != m_primMapping.end()) + + /// \brief given a USD prim path, this will see whether a maya node exists for it. If it does, + /// that will + /// be returned in the object handle. If the object is found, true is returned, + /// otherwise false. + /// \param path the usd prim path + /// \param object the returned handle + /// \param type the type of the maya object you wish to retrieve. If the type is MFn::kInvalid, + /// then the + /// first node found will be returned. This may be useful if a prim type may create a + /// type of node that is not known at compile time (e.g. a prim that creates a lambert, + /// blinn, or phong based on some enum attribute). Another alternative would be to query + /// all of the maya nodes via getMObjects + /// \return true if the prim exists + AL_USDMAYA_PUBLIC + bool getMObject(const SdfPath& path, MObjectHandle& object, MFn::Type type); + + /// \brief returns all of the maya nodes that were created by the specific prim + /// \param prim the prim to query + /// \param returned the returned list of MObjects + /// \return true if a reference to the prim was found + bool getMObjects(const UsdPrim& prim, MObjectHandleArray& returned) { - return it->uniqueKey(); + return getMObjects(prim.GetPath(), returned); } - return 0; - } - - /// \brief Update all unique keys when saving Maya scene. - AL_USDMAYA_PUBLIC - void updateUniqueKeys(); - - /// \brief Update unique key for a specified prim. - /// \param prim target prim - AL_USDMAYA_PUBLIC - void updateUniqueKey(const UsdPrim& prim); - - /// \brief An internal structure used to store a mapping between an SdfPath, the type of prim found at that location, - /// the maya transform that may have been created (assuming the translator plugin specifies that it needs - /// a parent transform), and any nodes that the translator plugin may have created. - struct PrimLookup - { - /// \brief ctor - /// \param path the prim path of the items we will be tracking - /// \param translatorId Used to help us determine which translator plugin to call to tear down this prim. - /// \param mayaObj the maya transform - PrimLookup(const SdfPath& path, const std::string& translatorId, MObject mayaObj) - : m_path(path), m_translatorId(translatorId), m_uniqueKey(0), m_object(mayaObj), m_createdNodes() { } + + /// \brief returns all of the maya nodes that were created by the specific prim + /// \param path the path to the prim to query + /// \param returned the returned list of MObjects + /// \return true if a reference to the prim was found + AL_USDMAYA_PUBLIC + bool getMObjects(const SdfPath& path, MObjectHandleArray& returned); + + /// \brief If within your custom translator plug-in you need to create any maya nodes, + /// associate that maya + /// node with the prim path by calling this method + /// \param prim the prim you are currently importing in a translator + /// \param object the handle to the maya node you have created. + AL_USDMAYA_PUBLIC + void insertItem(const UsdPrim& prim, MObjectHandle object); + + /// \brief during a variant switch, if we lose a prim, then it's path will be passed into this + /// method, and + /// all the maya nodes that were created for it will be nuked. + /// \param prim the usd prim that was removed due to a variant switch + void removeItems(const UsdPrim& prim) { removeItems(prim.GetPath()); } + + /// \brief during a variant switch, if we lose a prim, then it's path will be passed into this + /// method, and + /// all the maya nodes that were created for it will be nuked. + /// \param path path to the usd prim that was removed due to a variant switch + AL_USDMAYA_PUBLIC + void removeItems(const SdfPath& path); /// \brief dtor - ~PrimLookup() {} - - /// \brief get the prim path of this reference - /// \return the prim path for this reference - const SdfPath& path() const - { return m_path; } - - /// \brief get the maya object of the node - /// \return the maya node for this reference - MObjectHandle objectHandle() const - { return m_object; } - - /// \brief get the maya object of the node - /// \return the maya node for this reference - MObject object() const - { return m_object.object(); } - - /// \brief get the schema type of the prim - /// \return the schema type stored for this prim - std::string translatorId() const - { return m_translatorId; } - - /// \brief get the unique key of the prim - /// \return the unique key for this prim - const std::size_t uniqueKey() const - { return m_uniqueKey; } - - /// \brief set the unique key for this prim - /// \param key the unique key for this prim - void setUniqueKey(const std::size_t key) - { m_uniqueKey = key; } - - /// \brief get the prim type - /// \return the type stored for this prim - TfToken type() const - { return m_type; } - - /// \brief get the maya object of the node - /// \return the maya node for this reference - void setNode(MObject node) - { m_object = node; } - - /// \brief get created maya nodes - /// \return the created maya nodes for this prim translator - MObjectHandleArray& createdNodes() - { return m_createdNodes; } - - /// \brief get created maya nodes - /// \return the created maya nodes for this prim translator - const MObjectHandleArray& createdNodes() const - { return m_createdNodes; } - - private: - SdfPath m_path; - std::string m_translatorId; - std::size_t m_uniqueKey; - TfToken m_type; - MObjectHandle m_object; - MObjectHandleArray m_createdNodes; - }; - - /// a sorted array of prim mappings - typedef std::vector PrimLookups; - - /// comparison utility (for sorting array of pointers to node references based on their path) - struct value_compare - { - /// \brief compare schema node ref to path - /// \param a the node ref pointer on the left of the < operator - /// \param b the sdf path on the right of the < operator - /// \return true if a->primPath() < b, false otherwise - inline bool operator() (const PrimLookup& a, const SdfPath& b) const - { return a.path() < b; } - - /// \brief compare schema node ref to path - /// \param a the sdf path on the left of the < operator - /// \param b the node ref pointer on the right of the < operator - /// \return true if a < b->primPath(), false otherwise - inline bool operator() (const SdfPath& a, const PrimLookup& b) const - { return a < b.path(); } - - /// compare schema node ref to schema node ref - /// \brief compare schema node ref to path - /// \param a the node ref pointer on the left of the < operator - /// \param b the node ref pointer on the right of the < operator - /// \return true if a->primPath() < b->primPath(), false otherwise - inline bool operator() (const PrimLookup& a, const PrimLookup& b) const - { return a.path() < b.path(); } - }; - - /// \brief This is used for testing only. Do not call. - void clearPrimMappings() - { m_primMapping.clear(); } - - /// \brief add geometry to the exclusion list - /// \param newPath the path to add as an excluded translator path - /// \return true if the exclusion was added, false if it wasn't added since it might be already there - AL_USDMAYA_PUBLIC - bool addExcludedGeometry(const SdfPath& newPath); - - /// \brief remove geometry from the exclusion list - /// \param newPath the path to add as an excluded translator path - /// \return true if the exclusion was removed, false if it wasn't removed or it may have never existed - AL_USDMAYA_PUBLIC - bool removeExcludedGeometry(const SdfPath& newPath) - { - auto foundPath = m_excludedGeometry.find(newPath); - if(foundPath == m_excludedGeometry.end()) + AL_USDMAYA_PUBLIC + ~TranslatorContext(); + + /// \brief given a path to a prim, return the translator we are aware of at that path + /// \param path the prim path of a prim that was imported via a custom translator plug-in + /// \return the type name for that prim + std::string getTranslatorIdForPath(SdfPath path) const { - return false; + const auto it = find(path); + if (it != m_primMapping.end()) { + return it->translatorId(); + } + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "TranslatorContext::getTranslatorForPath did not find item in mapping.%s\n", + path.GetText()); + return std::string(); } - m_excludedGeometry.erase(newPath); - m_isExcludedGeometryDirty = true; - return true; - } - /// \brief retrieve currently excluded translator geometries - /// \return retrieve currently excluded translator geometries - inline const SdfInstanceMap& excludedGeometry() - {return m_excludedGeometry;} + /// \brief this method is used after a variant switch to check to see if the prim types have + /// changed in the + /// stage, and will update the internal state accordingly. + AL_USDMAYA_PUBLIC + void updatePrimTypes(); + + /// \brief Internal method. + /// If within your custom translator plug-in you need to create any maya nodes, + /// associate that maya node with the prim path by calling this method + /// \param prim the prim you are currently importing in a translator + /// \param object the handle to the maya node you have created. + AL_USDMAYA_PUBLIC + void registerItem(const UsdPrim& prim, MObjectHandle object); + + /// \brief serialises the content of the translator context to a text string. + /// \return the translator context serialised into a string + AL_USDMAYA_PUBLIC + MString serialise() const; + + /// \brief deserialises the string back into the translator context + /// \param string the string to deserialised + AL_USDMAYA_PUBLIC + void deserialise(const MString& string); + + /// \brief debugging utility to help keep track of prims during a variant switch + AL_USDMAYA_PUBLIC + void validatePrims(); + + /// \brief This method is used to determine whether this DB has an entry for the specified prim + /// path and the given translator. + /// This is used within a variant switch to determine if a node can be updated, or + /// whether it needs to be imported. + /// \param path the path to the prim to query + /// \param translatorId + /// \return true if an entry is found that matches, false otherwise + bool hasEntry(const SdfPath& path, const std::string& translatorId) + { + auto it = find(path); + if (it != m_primMapping.end()) { + return translatorId == it->translatorId(); + } + return false; + } - /// \brief Retrieves if the the excluded geometry has been pushed to the renderer - /// \return true if the excluded list hasn't been pushed the the renderer yet - inline bool isExcludedGeometryDirty() - {return m_isExcludedGeometryDirty;} + /// \brief This is called during a variant switch to determine whether the variant switch will + /// allow Maya nodes + /// to be updated, or whether they need to be deleted. + /// \param primPath the path to the prim that triggered the variant switch + /// \param itemsToRemove the returned list of items that need to be removed + /// \param callPreUnload true calling the preUnload on all the prims is needed. + AL_USDMAYA_PUBLIC + void preRemoveEntry( + const SdfPath& primPath, + SdfPathVector& itemsToRemove, + bool callPreUnload = true); + + /// \brief call this to remove a prim from the DB (you do not need to lock/unlock here). + /// \param itemsToRemove the prims that need to be removed from the DB. tearDown will be called + /// on each prim + AL_USDMAYA_PUBLIC + void removeEntries(const SdfPathVector& itemsToRemove); + + /// \brief Get unique key for specified prim path. + /// \param path target prim path + /// \return unique key value + std::size_t getUniqueKeyForPath(const SdfPath& path) + { + auto it = find(path); + if (it != m_primMapping.end()) { + return it->uniqueKey(); + } + return 0; + } -private: - void unloadPrim( - const SdfPath& primPath, - const MObject& primObj); - void preUnloadPrim( - UsdPrim& primPath, - const MObject& primObj); - - bool isNodeAncestorOf(MObjectHandle ancestorHandle, MObjectHandle objectHandleToTest); - - /// \brief test if the prim was translated into any MObject(s), that sits underneath the parent MObject. - /// \return true if the prim maps to a MObject inside the Maya Dag tree. - bool isPrimInTransformChain(const SdfPath& path); - - inline PrimLookups::iterator find(const SdfPath& path) - { - PrimLookups::iterator end = m_primMapping.end(); - PrimLookups::iterator it = std::lower_bound(m_primMapping.begin(), end, path, value_compare()); - if(it != end) + /// \brief Update all unique keys when saving Maya scene. + AL_USDMAYA_PUBLIC + void updateUniqueKeys(); + + /// \brief Update unique key for a specified prim. + /// \param prim target prim + AL_USDMAYA_PUBLIC + void updateUniqueKey(const UsdPrim& prim); + + /// \brief An internal structure used to store a mapping between an SdfPath, the type of prim + /// found at that location, + /// the maya transform that may have been created (assuming the translator plugin + /// specifies that it needs a parent transform), and any nodes that the translator + /// plugin may have created. + struct PrimLookup { - if(it->path() == path) - return it; + /// \brief ctor + /// \param path the prim path of the items we will be tracking + /// \param translatorId Used to help us determine which translator plugin to call to tear + /// down this prim. \param mayaObj the maya transform + PrimLookup(const SdfPath& path, const std::string& translatorId, MObject mayaObj) + : m_path(path) + , m_translatorId(translatorId) + , m_uniqueKey(0) + , m_object(mayaObj) + , m_createdNodes() + { + } + + /// \brief dtor + ~PrimLookup() { } + + /// \brief get the prim path of this reference + /// \return the prim path for this reference + const SdfPath& path() const { return m_path; } + + /// \brief get the maya object of the node + /// \return the maya node for this reference + MObjectHandle objectHandle() const { return m_object; } + + /// \brief get the maya object of the node + /// \return the maya node for this reference + MObject object() const { return m_object.object(); } + + /// \brief get the schema type of the prim + /// \return the schema type stored for this prim + std::string translatorId() const { return m_translatorId; } + + /// \brief get the unique key of the prim + /// \return the unique key for this prim + const std::size_t uniqueKey() const { return m_uniqueKey; } + + /// \brief set the unique key for this prim + /// \param key the unique key for this prim + void setUniqueKey(const std::size_t key) { m_uniqueKey = key; } + + /// \brief get the prim type + /// \return the type stored for this prim + TfToken type() const { return m_type; } + + /// \brief get the maya object of the node + /// \return the maya node for this reference + void setNode(MObject node) { m_object = node; } + + /// \brief get created maya nodes + /// \return the created maya nodes for this prim translator + MObjectHandleArray& createdNodes() { return m_createdNodes; } + + /// \brief get created maya nodes + /// \return the created maya nodes for this prim translator + const MObjectHandleArray& createdNodes() const { return m_createdNodes; } + + private: + SdfPath m_path; + std::string m_translatorId; + std::size_t m_uniqueKey; + TfToken m_type; + MObjectHandle m_object; + MObjectHandleArray m_createdNodes; + }; + + /// a sorted array of prim mappings + typedef std::vector PrimLookups; + + /// comparison utility (for sorting array of pointers to node references based on their path) + struct value_compare + { + /// \brief compare schema node ref to path + /// \param a the node ref pointer on the left of the < operator + /// \param b the sdf path on the right of the < operator + /// \return true if a->primPath() < b, false otherwise + inline bool operator()(const PrimLookup& a, const SdfPath& b) const { return a.path() < b; } + + /// \brief compare schema node ref to path + /// \param a the sdf path on the left of the < operator + /// \param b the node ref pointer on the right of the < operator + /// \return true if a < b->primPath(), false otherwise + inline bool operator()(const SdfPath& a, const PrimLookup& b) const { return a < b.path(); } + + /// compare schema node ref to schema node ref + /// \brief compare schema node ref to path + /// \param a the node ref pointer on the left of the < operator + /// \param b the node ref pointer on the right of the < operator + /// \return true if a->primPath() < b->primPath(), false otherwise + inline bool operator()(const PrimLookup& a, const PrimLookup& b) const + { + return a.path() < b.path(); + } + }; + + /// \brief This is used for testing only. Do not call. + void clearPrimMappings() { m_primMapping.clear(); } + + /// \brief add geometry to the exclusion list + /// \param newPath the path to add as an excluded translator path + /// \return true if the exclusion was added, false if it wasn't added since it might be already + /// there + AL_USDMAYA_PUBLIC + bool addExcludedGeometry(const SdfPath& newPath); + + /// \brief remove geometry from the exclusion list + /// \param newPath the path to add as an excluded translator path + /// \return true if the exclusion was removed, false if it wasn't removed or it may have never + /// existed + AL_USDMAYA_PUBLIC + bool removeExcludedGeometry(const SdfPath& newPath) + { + auto foundPath = m_excludedGeometry.find(newPath); + if (foundPath == m_excludedGeometry.end()) { + return false; + } + m_excludedGeometry.erase(newPath); + m_isExcludedGeometryDirty = true; + return true; } - return end; - } - - inline PrimLookups::const_iterator find(const SdfPath& path) const - { - PrimLookups::const_iterator end = m_primMapping.end(); - PrimLookups::const_iterator it = std::lower_bound(m_primMapping.begin(), end, path, value_compare()); - if(it != end) + + /// \brief retrieve currently excluded translator geometries + /// \return retrieve currently excluded translator geometries + inline const SdfInstanceMap& excludedGeometry() { return m_excludedGeometry; } + + /// \brief Retrieves if the the excluded geometry has been pushed to the renderer + /// \return true if the excluded list hasn't been pushed the the renderer yet + inline bool isExcludedGeometryDirty() { return m_isExcludedGeometryDirty; } + +private: + void unloadPrim(const SdfPath& primPath, const MObject& primObj); + void preUnloadPrim(UsdPrim& primPath, const MObject& primObj); + + bool isNodeAncestorOf(MObjectHandle ancestorHandle, MObjectHandle objectHandleToTest); + + /// \brief test if the prim was translated into any MObject(s), that sits underneath the parent + /// MObject. \return true if the prim maps to a MObject inside the Maya Dag tree. + bool isPrimInTransformChain(const SdfPath& path); + + inline PrimLookups::iterator find(const SdfPath& path) { - if(it->path() == path) - return it; + PrimLookups::iterator end = m_primMapping.end(); + PrimLookups::iterator it + = std::lower_bound(m_primMapping.begin(), end, path, value_compare()); + if (it != end) { + if (it->path() == path) + return it; + } + return end; } - return end; - } - inline PrimLookups::iterator findLocation(const SdfPath& path) - { - PrimLookups::iterator end = m_primMapping.end(); - PrimLookups::iterator it = std::lower_bound(m_primMapping.begin(), end, path, value_compare()); - return it; - } + inline PrimLookups::const_iterator find(const SdfPath& path) const + { + PrimLookups::const_iterator end = m_primMapping.end(); + PrimLookups::const_iterator it + = std::lower_bound(m_primMapping.begin(), end, path, value_compare()); + if (it != end) { + if (it->path() == path) + return it; + } + return end; + } + inline PrimLookups::iterator findLocation(const SdfPath& path) + { + PrimLookups::iterator end = m_primMapping.end(); + PrimLookups::iterator it + = std::lower_bound(m_primMapping.begin(), end, path, value_compare()); + return it; + } - TranslatorContext(nodes::ProxyShape* proxyShape) - : m_proxyShape(proxyShape), m_primMapping() - {} + TranslatorContext(nodes::ProxyShape* proxyShape) + : m_proxyShape(proxyShape) + , m_primMapping() + { + } - nodes::ProxyShape* m_proxyShape; + nodes::ProxyShape* m_proxyShape; - // map between a usd prim path and either a dag parent node or - // a dependency node - PrimLookups m_primMapping; + // map between a usd prim path and either a dag parent node or + // a dependency node + PrimLookups m_primMapping; - // list of geometry that has been request to be excluded during the translation - SdfInstanceMap m_excludedGeometry; - bool m_isExcludedGeometryDirty; + // list of geometry that has been request to be excluded during the translation + SdfInstanceMap m_excludedGeometry; + bool m_isExcludedGeometryDirty; public: - void setForceDefaultRead(bool forceDefaultRead) - { m_forceDefaultRead = forceDefaultRead; } + void setForceDefaultRead(bool forceDefaultRead) { m_forceDefaultRead = forceDefaultRead; } - bool getForceDefaultRead() - { return m_forceDefaultRead; } + bool getForceDefaultRead() { return m_forceDefaultRead; } private: - // If true, will explicitly read default attribute values. - bool m_forceDefaultRead; - + // If true, will explicitly read default attribute values. + bool m_forceDefaultRead; }; typedef TfRefPtr TranslatorContextPtr; //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestPlugin.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestPlugin.cpp index 28bebaac20..35df134108 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestPlugin.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestPlugin.cpp @@ -26,54 +26,45 @@ namespace translators { AL_USDMAYA_DEFINE_TRANSLATOR(TranslatorTestPlugin, TranslatorTestType); //---------------------------------------------------------------------------------------------------------------------- -MStatus TranslatorTestPlugin::initialize() -{ - return MStatus::kSuccess; -} +MStatus TranslatorTestPlugin::initialize() { return MStatus::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus TranslatorTestPlugin::import(const UsdPrim& prim, MObject& parent, MObject& createdObj) { - MObject distanceShape = MFnDagNode().create("distanceDimShape", parent); - createdObj = distanceShape; - context()->insertItem(prim, createdObj); - return MStatus::kSuccess; + MObject distanceShape = MFnDagNode().create("distanceDimShape", parent); + createdObj = distanceShape; + context()->insertItem(prim, createdObj); + return MStatus::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -MStatus TranslatorTestPlugin::postImport(const UsdPrim& prim) -{ - return MStatus::kSuccess; -} +MStatus TranslatorTestPlugin::postImport(const UsdPrim& prim) { return MStatus::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -MStatus TranslatorTestPlugin::preTearDown(UsdPrim& path) -{ - return MStatus::kSuccess; -} +MStatus TranslatorTestPlugin::preTearDown(UsdPrim& path) { return MStatus::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus TranslatorTestPlugin::tearDown(const SdfPath& path) { - context()->removeItems(path); - return MStatus::kSuccess; + context()->removeItems(path); + return MStatus::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- UsdPrim TranslatorTestPlugin::exportObject( - UsdStageRefPtr stage, - MDagPath dagPath, - const SdfPath& usdPath, - const ExporterParams& params) + UsdStageRefPtr stage, + MDagPath dagPath, + const SdfPath& usdPath, + const ExporterParams& params) { - MFnDagNode fn(dagPath); - TranslatorTestType node = TranslatorTestType::Define(stage, usdPath); - return node.GetPrim(); + MFnDagNode fn(dagPath); + TranslatorTestType node = TranslatorTestType::Define(stage, usdPath); + return node.GetPrim(); } //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestPlugin.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestPlugin.h index 960bf1c7fa..fba52ee1ba 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestPlugin.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestPlugin.h @@ -18,10 +18,11 @@ #include "AL/usdmaya/fileio/translators/TranslatorBase.h" #include "AL/usdmaya/fileio/translators/TranslatorContext.h" #include "AL/usdmaya/fileio/translators/TranslatorTestType.h" -#include -#include #include +#include + +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -32,28 +33,33 @@ namespace translators { //---------------------------------------------------------------------------------------------------------------------- #ifndef AL_GENERATING_DOCS -class TranslatorTestPlugin - : public TranslatorBase +class TranslatorTestPlugin : public TranslatorBase { public: - - AL_USDMAYA_DECLARE_TRANSLATOR(TranslatorTestPlugin); + AL_USDMAYA_DECLARE_TRANSLATOR(TranslatorTestPlugin); private: - UsdPrim exportObject(UsdStageRefPtr stage, MDagPath dagPath, const SdfPath& usdPath, const ExporterParams& params) override; - MStatus initialize() override; - MStatus import(const UsdPrim& prim, MObject& parent, MObject& createdObj) override; - MStatus postImport(const UsdPrim& prim) override; - MStatus preTearDown(UsdPrim& path) override; - MStatus tearDown(const SdfPath& path) override; - ExportFlag canExport(const MObject& obj) override - { return (obj.hasFn(MFn::kDistance) ? ExportFlag::kFallbackSupport : ExportFlag::kNotSupported); } + UsdPrim exportObject( + UsdStageRefPtr stage, + MDagPath dagPath, + const SdfPath& usdPath, + const ExporterParams& params) override; + MStatus initialize() override; + MStatus import(const UsdPrim& prim, MObject& parent, MObject& createdObj) override; + MStatus postImport(const UsdPrim& prim) override; + MStatus preTearDown(UsdPrim& path) override; + MStatus tearDown(const SdfPath& path) override; + ExportFlag canExport(const MObject& obj) override + { + return ( + obj.hasFn(MFn::kDistance) ? ExportFlag::kFallbackSupport : ExportFlag::kNotSupported); + } }; #endif //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestType.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestType.cpp index 1deaaba065..53441dfb7e 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestType.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestType.cpp @@ -14,11 +14,11 @@ // limitations under the License. // #include "AL/usdmaya/fileio/translators/TranslatorTestType.h" -#include -#include -#include #include +#include +#include +#include namespace AL { namespace usdmaya { @@ -26,88 +26,76 @@ namespace fileio { namespace translators { //---------------------------------------------------------------------------------------------------------------------- -TF_REGISTRY_FUNCTION(TfType) -{ - TfType::Define >(); - -} +TF_REGISTRY_FUNCTION(TfType) { TfType::Define>(); } //---------------------------------------------------------------------------------------------------------------------- -TranslatorTestType::~TranslatorTestType() -{ -} +TranslatorTestType::~TranslatorTestType() { } //---------------------------------------------------------------------------------------------------------------------- -TranslatorTestType TranslatorTestType::Get(const UsdStagePtr &stage, const SdfPath &path) +TranslatorTestType TranslatorTestType::Get(const UsdStagePtr& stage, const SdfPath& path) { - if (!stage) - { - TF_CODING_ERROR("Invalid stage"); - return TranslatorTestType(); - } - return TranslatorTestType(stage->GetPrimAtPath(path)); + if (!stage) { + TF_CODING_ERROR("Invalid stage"); + return TranslatorTestType(); + } + return TranslatorTestType(stage->GetPrimAtPath(path)); } //---------------------------------------------------------------------------------------------------------------------- -TranslatorTestType TranslatorTestType::Define(const UsdStagePtr &stage, const SdfPath &path) +TranslatorTestType TranslatorTestType::Define(const UsdStagePtr& stage, const SdfPath& path) { - static TfToken usdPrimTypeName("AL::usdmaya::fileio::translators::TranslatorTestType"); - if (!stage) - { - TF_CODING_ERROR("Invalid stage"); - return TranslatorTestType(); - } - return TranslatorTestType(stage->DefinePrim(path, usdPrimTypeName)); + static TfToken usdPrimTypeName("AL::usdmaya::fileio::translators::TranslatorTestType"); + if (!stage) { + TF_CODING_ERROR("Invalid stage"); + return TranslatorTestType(); + } + return TranslatorTestType(stage->DefinePrim(path, usdPrimTypeName)); } //---------------------------------------------------------------------------------------------------------------------- const TfType& TranslatorTestType::_GetStaticTfType() { - static TfType tfType = TfType::Find(); - return tfType; + static TfType tfType = TfType::Find(); + return tfType; } //---------------------------------------------------------------------------------------------------------------------- bool TranslatorTestType::_IsTypedSchema() { - static bool isTyped = _GetStaticTfType().IsA(); - return isTyped; + static bool isTyped = _GetStaticTfType().IsA(); + return isTyped; } //---------------------------------------------------------------------------------------------------------------------- -const TfType& TranslatorTestType::_GetTfType() const -{ - return _GetStaticTfType(); -} +const TfType& TranslatorTestType::_GetTfType() const { return _GetStaticTfType(); } //---------------------------------------------------------------------------------------------------------------------- -static inline TfTokenVector _ConcatenateAttributeNames(const TfTokenVector& left, const TfTokenVector& right) +static inline TfTokenVector +_ConcatenateAttributeNames(const TfTokenVector& left, const TfTokenVector& right) { - TfTokenVector result; - result.reserve(left.size() + right.size()); - result.insert(result.end(), left.begin(), left.end()); - result.insert(result.end(), right.begin(), right.end()); - return result; + TfTokenVector result; + result.reserve(left.size() + right.size()); + result.insert(result.end(), left.begin(), left.end()); + result.insert(result.end(), right.begin(), right.end()); + return result; } //---------------------------------------------------------------------------------------------------------------------- const TfTokenVector& TranslatorTestType::GetSchemaAttributeNames(bool includeInherited) { - static TfTokenVector localNames = {}; - static TfTokenVector allNames = - _ConcatenateAttributeNames( - UsdTyped::GetSchemaAttributeNames(true), - localNames); + static TfTokenVector localNames = {}; + static TfTokenVector allNames + = _ConcatenateAttributeNames(UsdTyped::GetSchemaAttributeNames(true), localNames); - if (includeInherited) - return allNames; - else - return localNames; + if (includeInherited) + return allNames; + else + return localNames; } //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestType.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestType.h index 7a94387215..3414de445f 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestType.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/TranslatorTestType.h @@ -17,16 +17,15 @@ #include -#include #include #include +#include #include #include #include PXR_NAMESPACE_USING_DIRECTIVE - namespace AL { namespace usdmaya { namespace fileio { @@ -34,96 +33,95 @@ namespace translators { //---------------------------------------------------------------------------------------------------------------------- #ifndef AL_GENERATING_DOCS -class TranslatorTestType - : public UsdTyped +class TranslatorTestType : public UsdTyped { public: - /// Compile-time constant indicating whether or not this class corresponds - /// to a concrete instantiable prim type in scene description. If this is - /// true, GetStaticPrimDefinition() will return a valid prim definition with - /// a non-empty typeName. - AL_USDMAYA_PUBLIC - static const bool IsConcrete = true; - - /// Construct a TranslatorTestType on UsdPrim \p prim . - /// Equivalent to TranslatorTestType::Get(prim.GetStage(), prim.GetPath()) - /// for a \em valid \p prim, but will not immediately throw an error for - /// an invalid \p prim - explicit TranslatorTestType(const UsdPrim& prim=UsdPrim()) - : UsdTyped(prim) - { - } - - /// Construct a TranslatorTestType on the prim held by \p schemaObj . - /// Should be preferred over TranslatorTestType(schemaObj.GetPrim()), - /// as it preserves SchemaBase state. - explicit TranslatorTestType(const UsdSchemaBase& schemaObj) - : UsdTyped(schemaObj) - { - } - - /// Destructor. - AL_USDMAYA_PUBLIC - virtual ~TranslatorTestType(); - - /// Return a vector of names of all pre-declared attributes for this schema - /// class and all its ancestor classes. Does not include attributes that - /// may be authored by custom/extended methods of the schemas involved. - AL_USDMAYA_PUBLIC - static const TfTokenVector& GetSchemaAttributeNames(bool includeInherited = true); - - /// \brief Return a TranslatorTestType holding the prim adhering to this - /// schema at \p path on \p stage. If no prim exists at \p path on - /// \p stage, or if the prim at that path does not adhere to this schema, - /// return an invalid schema object. This is shorthand for the following: - /// - /// \code - /// TranslatorTestType(stage->GetPrimAtPath(path)); - /// \endcode - /// - AL_USDMAYA_PUBLIC - static TranslatorTestType Get(const UsdStagePtr &stage, const SdfPath &path); - - /// \brief Attempt to ensure a \a UsdPrim adhering to this schema at \p path - /// is defined (according to UsdPrim::IsDefined()) on this stage. - /// - /// If a prim adhering to this schema at \p path is already defined on this - /// stage, return that prim. Otherwise author an \a SdfPrimSpec with - /// \a specifier == \a SdfSpecifierDef and this schema's prim type name for - /// the prim at \p path at the current EditTarget. Author \a SdfPrimSpec s - /// with \p specifier == \a SdfSpecifierDef and empty typeName at the - /// current EditTarget for any nonexistent, or existing but not \a Defined - /// ancestors. - /// - /// The given \a path must be an absolute prim path that does not contain - /// any variant selections. - /// - /// If it is impossible to author any of the necessary PrimSpecs, (for - /// example, in case \a path cannot map to the current UsdEditTarget's - /// namespace) issue an error and return an invalid \a UsdPrim. - /// - /// Note that this method may return a defined prim whose typeName does not - /// specify this schema class, in case a stronger typeName opinion overrides - /// the opinion at the current EditTarget. - /// - AL_USDMAYA_PUBLIC - static TranslatorTestType Define(const UsdStagePtr &stage, const SdfPath &path); + /// Compile-time constant indicating whether or not this class corresponds + /// to a concrete instantiable prim type in scene description. If this is + /// true, GetStaticPrimDefinition() will return a valid prim definition with + /// a non-empty typeName. + AL_USDMAYA_PUBLIC + static const bool IsConcrete = true; + + /// Construct a TranslatorTestType on UsdPrim \p prim . + /// Equivalent to TranslatorTestType::Get(prim.GetStage(), prim.GetPath()) + /// for a \em valid \p prim, but will not immediately throw an error for + /// an invalid \p prim + explicit TranslatorTestType(const UsdPrim& prim = UsdPrim()) + : UsdTyped(prim) + { + } + + /// Construct a TranslatorTestType on the prim held by \p schemaObj . + /// Should be preferred over TranslatorTestType(schemaObj.GetPrim()), + /// as it preserves SchemaBase state. + explicit TranslatorTestType(const UsdSchemaBase& schemaObj) + : UsdTyped(schemaObj) + { + } + + /// Destructor. + AL_USDMAYA_PUBLIC + virtual ~TranslatorTestType(); + + /// Return a vector of names of all pre-declared attributes for this schema + /// class and all its ancestor classes. Does not include attributes that + /// may be authored by custom/extended methods of the schemas involved. + AL_USDMAYA_PUBLIC + static const TfTokenVector& GetSchemaAttributeNames(bool includeInherited = true); + + /// \brief Return a TranslatorTestType holding the prim adhering to this + /// schema at \p path on \p stage. If no prim exists at \p path on + /// \p stage, or if the prim at that path does not adhere to this schema, + /// return an invalid schema object. This is shorthand for the following: + /// + /// \code + /// TranslatorTestType(stage->GetPrimAtPath(path)); + /// \endcode + /// + AL_USDMAYA_PUBLIC + static TranslatorTestType Get(const UsdStagePtr& stage, const SdfPath& path); + + /// \brief Attempt to ensure a \a UsdPrim adhering to this schema at \p path + /// is defined (according to UsdPrim::IsDefined()) on this stage. + /// + /// If a prim adhering to this schema at \p path is already defined on this + /// stage, return that prim. Otherwise author an \a SdfPrimSpec with + /// \a specifier == \a SdfSpecifierDef and this schema's prim type name for + /// the prim at \p path at the current EditTarget. Author \a SdfPrimSpec s + /// with \p specifier == \a SdfSpecifierDef and empty typeName at the + /// current EditTarget for any nonexistent, or existing but not \a Defined + /// ancestors. + /// + /// The given \a path must be an absolute prim path that does not contain + /// any variant selections. + /// + /// If it is impossible to author any of the necessary PrimSpecs, (for + /// example, in case \a path cannot map to the current UsdEditTarget's + /// namespace) issue an error and return an invalid \a UsdPrim. + /// + /// Note that this method may return a defined prim whose typeName does not + /// specify this schema class, in case a stronger typeName opinion overrides + /// the opinion at the current EditTarget. + /// + AL_USDMAYA_PUBLIC + static TranslatorTestType Define(const UsdStagePtr& stage, const SdfPath& path); private: - // needs to invoke _GetStaticTfType. - friend class UsdSchemaRegistry; - static const TfType &_GetStaticTfType(); + // needs to invoke _GetStaticTfType. + friend class UsdSchemaRegistry; + static const TfType& _GetStaticTfType(); - static bool _IsTypedSchema(); + static bool _IsTypedSchema(); - // override SchemaBase virtuals. - virtual const TfType &_GetTfType() const; + // override SchemaBase virtuals. + virtual const TfType& _GetTfType() const; }; #endif //---------------------------------------------------------------------------------------------------------------------- -} // translators -} // fileio -} // usdmaya -} // AL +} // namespace translators +} // namespace fileio +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/wrapTranslatorBase.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/wrapTranslatorBase.cpp index 262bc492b5..890c11e959 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/wrapTranslatorBase.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/wrapTranslatorBase.cpp @@ -13,30 +13,30 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/nodes/ProxyShape.h" #include "AL/maya/utils/Utils.h" #include "AL/usdmaya/fileio/translators/TranslatorBase.h" #include "AL/usdmaya/fileio/translators/TranslatorContext.h" +#include "AL/usdmaya/nodes/ProxyShape.h" -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include +#include +#include #include #include -#include -#include -#include #include +#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include #include #include @@ -48,220 +48,216 @@ namespace { struct MStatusFromPythonBool { - static void Register() { - // from-python - boost::python::converter::registry::push_back(&_convertible, &_construct, - boost::python::type_id()); - } + static void Register() + { + // from-python + boost::python::converter::registry::push_back( + &_convertible, &_construct, boost::python::type_id()); + } private: - // from-python - static void *_convertible(PyObject *p) { - return PyBool_Check(p) ? p : nullptr; - } - static void _construct(PyObject *p, boost::python::converter:: - rvalue_from_python_stage1_data *data) { - // Turn the python float into a C++ double, make a GfHalf from that - // double, and store it where boost.python expects it. - void *storage = ( - (boost::python::converter::rvalue_from_python_storage*) - data)->storage.bytes; - MStatus status = PyObject_IsTrue(p) ? MStatus::kSuccess : MStatus::kFailure; - new (storage) MStatus(status); - data->convertible = storage; - } + // from-python + static void* _convertible(PyObject* p) { return PyBool_Check(p) ? p : nullptr; } + static void + _construct(PyObject* p, boost::python::converter::rvalue_from_python_stage1_data* data) + { + // Turn the python float into a C++ double, make a GfHalf from that + // double, and store it where boost.python expects it. + void* storage + = ((boost::python::converter::rvalue_from_python_storage*)data)->storage.bytes; + MStatus status = PyObject_IsTrue(p) ? MStatus::kSuccess : MStatus::kFailure; + new (storage) MStatus(status); + data->convertible = storage; + } }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief boost python binding for the PluginTranslator +/// \brief boost python binding for the PluginTranslator //---------------------------------------------------------------------------------------------------------------------- class TranslatorBaseWrapper - : public TranslatorBase, - public TfPyPolymorphic + : public TranslatorBase + , public TfPyPolymorphic { public: - typedef TranslatorBaseWrapper This; - typedef TranslatorBase base_t; - typedef TranslatorRefPtr refptr_t; - typedef TranslatorManufacture manufacture_t; - - static TfRefPtr New() - { - return TfCreateRefPtr(new TranslatorBaseWrapper); - } - - virtual ~TranslatorBaseWrapper(); - - TfType getTranslatedType() const override - { - return this->CallPureVirtual("getTranslatedType")(); - } - - std::size_t generateUniqueKey(const UsdPrim& prim) const override - { - if (Override o = GetOverride("generateUniqueKey")) + typedef TranslatorBaseWrapper This; + typedef TranslatorBase base_t; + typedef TranslatorRefPtr refptr_t; + typedef TranslatorManufacture manufacture_t; + + static TfRefPtr New() + { + return TfCreateRefPtr(new TranslatorBaseWrapper); + } + + virtual ~TranslatorBaseWrapper(); + + TfType getTranslatedType() const override + { + return this->CallPureVirtual("getTranslatedType")(); + } + + std::size_t generateUniqueKey(const UsdPrim& prim) const override { - auto res = std::function(TfPyCall(o))(prim); - if (!res) { + if (Override o = GetOverride("generateUniqueKey")) { + auto res = std::function( + TfPyCall(o))(prim); + if (!res) { + return 0; + } + TfPyLock pyLock; + boost::python::str strObj(res); + boost::python::extract strValue(strObj); + if (strValue.check()) { + return std::hash {}(strValue); + } + } return 0; - } - TfPyLock pyLock; - boost::python::str strObj(res); - boost::python::extract strValue(strObj); - if (strValue.check()) - { - return std::hash{}(strValue); - } } - return 0; - } - - bool needsTransformParent() const override - { - return this->CallVirtual("needsTransformParent", &This::needsTransformParent)(); - } - - bool supportsUpdate() const override - { - return this->CallVirtual("supportsUpdate", &This::supportsUpdate)(); - } - - bool importableByDefault() const override - { - return this->CallVirtual("importableByDefault", &This::importableByDefault)(); - } - - MStatus initialize() override - { - return this->CallVirtual("initialize", &This::initialize)(); - } - - MStatus import(const UsdPrim& prim, MObject& parent, MObject& createdObj) override - { - // "import" is a python keyword so python's override will be called - // "importObject" instead - if (Override o = GetOverride("importObject")) { - MDagPath path; - MDagPath::getAPathTo(parent, path); - - auto res = std::function - (TfPyCall(o))(prim, path.fullPathName().asChar()); - return res ? MS::kSuccess : MS::kFailure; + + bool needsTransformParent() const override + { + return this->CallVirtual("needsTransformParent", &This::needsTransformParent)(); } - return MS::kSuccess; - } - - MStatus postImport(const UsdPrim& prim) override - { - if (Override o = GetOverride("postImport")) { - auto res = std::function(TfPyCall(o))(prim); - return res ? MS::kSuccess : MS::kFailure; + + bool supportsUpdate() const override + { + return this->CallVirtual("supportsUpdate", &This::supportsUpdate)(); } - return MS::kSuccess; - } - - MStatus preTearDown(UsdPrim& prim) override - { - return this->CallVirtual("preTearDown", &This::preTearDown)(prim); - } - - MStatus tearDown(const SdfPath& path) override - { - return this->CallVirtual("tearDown", &This::tearDown)(path); - } - - MStatus update(const UsdPrim& prim) override - { - return this->CallVirtual("update", &This::update)(prim); - } - - ExportFlag canExport(const MObject& obj) override - { - MFnDependencyNode fn(obj); - std::string name(fn.name().asChar()); - return this->CallVirtual("canExport", &This::canExport)(obj); - } - - UsdPrim exportObject(UsdStageRefPtr stage, MDagPath dagPath, const SdfPath& usdPath, const AL::usdmaya::fileio::ExporterParams& params) override - { - std::string name(dagPath.fullPathName().asChar()); - return this->CallVirtual("exportObject", &This::exportObject)(stage, dagPath, usdPath, params); - } - - static void registerTranslator(refptr_t plugin, const TfToken& assetType=TfToken()) - { - if(!manufacture_t::addPythonTranslator(plugin, assetType)) + + bool importableByDefault() const override + { + return this->CallVirtual("importableByDefault", &This::importableByDefault)(); + } + + MStatus initialize() override + { + return this->CallVirtual("initialize", &This::initialize)(); + } + + MStatus import(const UsdPrim& prim, MObject& parent, MObject& createdObj) override { - MGlobal::displayWarning("Cannot register python translator because of unknown type"); - return; + // "import" is a python keyword so python's override will be called + // "importObject" instead + if (Override o = GetOverride("importObject")) { + MDagPath path; + MDagPath::getAPathTo(parent, path); + + auto res = std::function(TfPyCall(o))( + prim, path.fullPathName().asChar()); + return res ? MS::kSuccess : MS::kFailure; + } + return MS::kSuccess; } - MFnDependencyNode fn; - MItDependencyNodes iter(MFn::kPluginShape); - for(; !iter.isDone(); iter.next()) + MStatus postImport(const UsdPrim& prim) override { - auto mobj = iter.thisNode(); - fn.setObject(mobj); - if(fn.typeId() != ProxyShape::kTypeId) continue; - if(auto proxyShape = static_cast(fn.userNode())) - { - auto manufacture = proxyShape->translatorManufacture(); - auto context = proxyShape->context(); - manufacture.updatePythonTranslators(context); - } + if (Override o = GetOverride("postImport")) { + auto res = std::function(TfPyCall(o))(prim); + return res ? MS::kSuccess : MS::kFailure; + } + return MS::kSuccess; } - } - - static bool unregisterTranslator(const std::string& typeName) - { - auto type = TfType::FindByName(typeName); - return manufacture_t::deletePythonTranslator(type); - } - - static void clearTranslators() - { - manufacture_t::clearPythonTranslators(); - } - - UsdStageRefPtr stage() const - { - return context()->getUsdStage(); - } - - void insertItem(const boost::shared_ptr& primBeingImported, const std::string& nodeNameOrPath) - { - MSelectionList sl; - MObject object; - sl.add(nodeNameOrPath.c_str()); - sl.getDependNode(0, object); - auto ctx = context(); - ctx->insertItem(*primBeingImported, object); - } - - void removeItems(const boost::shared_ptr& primPathBeingRemoved) - { - auto ctx = context(); - ctx->removeItems(*primPathBeingRemoved); - } - - std::vector getMObjects(boost::shared_ptr prim) - { - MObjectHandleArray returned; - context()->getMObjects(*prim, returned); - std::vector names(returned.size()); - MFnDependencyNode fn; - for(size_t i = 0, n = returned.size(); i != n; ++i) + + MStatus preTearDown(UsdPrim& prim) override + { + return this->CallVirtual("preTearDown", &This::preTearDown)(prim); + } + + MStatus tearDown(const SdfPath& path) override + { + return this->CallVirtual("tearDown", &This::tearDown)(path); + } + + MStatus update(const UsdPrim& prim) override + { + return this->CallVirtual("update", &This::update)(prim); + } + + ExportFlag canExport(const MObject& obj) override + { + MFnDependencyNode fn(obj); + std::string name(fn.name().asChar()); + return this->CallVirtual("canExport", &This::canExport)(obj); + } + + UsdPrim exportObject( + UsdStageRefPtr stage, + MDagPath dagPath, + const SdfPath& usdPath, + const AL::usdmaya::fileio::ExporterParams& params) override + { + std::string name(dagPath.fullPathName().asChar()); + return this->CallVirtual("exportObject", &This::exportObject)( + stage, dagPath, usdPath, params); + } + + static void registerTranslator(refptr_t plugin, const TfToken& assetType = TfToken()) + { + if (!manufacture_t::addPythonTranslator(plugin, assetType)) { + MGlobal::displayWarning("Cannot register python translator because of unknown type"); + return; + } + + MFnDependencyNode fn; + MItDependencyNodes iter(MFn::kPluginShape); + for (; !iter.isDone(); iter.next()) { + auto mobj = iter.thisNode(); + fn.setObject(mobj); + if (fn.typeId() != ProxyShape::kTypeId) + continue; + if (auto proxyShape = static_cast(fn.userNode())) { + auto manufacture = proxyShape->translatorManufacture(); + auto context = proxyShape->context(); + manufacture.updatePythonTranslators(context); + } + } + } + + static bool unregisterTranslator(const std::string& typeName) + { + auto type = TfType::FindByName(typeName); + return manufacture_t::deletePythonTranslator(type); + } + + static void clearTranslators() { manufacture_t::clearPythonTranslators(); } + + UsdStageRefPtr stage() const { return context()->getUsdStage(); } + + void insertItem( + const boost::shared_ptr& primBeingImported, + const std::string& nodeNameOrPath) + { + MSelectionList sl; + MObject object; + sl.add(nodeNameOrPath.c_str()); + sl.getDependNode(0, object); + auto ctx = context(); + ctx->insertItem(*primBeingImported, object); + } + + void removeItems(const boost::shared_ptr& primPathBeingRemoved) + { + auto ctx = context(); + ctx->removeItems(*primPathBeingRemoved); + } + + std::vector getMObjects(boost::shared_ptr prim) { - fn.setObject(returned[i].object()); - names[i] = fn.name().asChar(); + MObjectHandleArray returned; + context()->getMObjects(*prim, returned); + std::vector names(returned.size()); + MFnDependencyNode fn; + for (size_t i = 0, n = returned.size(); i != n; ++i) { + fn.setObject(returned[i].object()); + names[i] = fn.name().asChar(); + } + return names; } - return names; - } }; TranslatorBaseWrapper::~TranslatorBaseWrapper() { - // + // } } // namespace @@ -269,48 +265,60 @@ TranslatorBaseWrapper::~TranslatorBaseWrapper() //---------------------------------------------------------------------------------------------------------------------- void wrapTranslatorBase() { - typedef TfWeakPtr TranslatorBaseWrapperPtr; - typedef TfRefPtr TranslatorBasePtr; - - boost::python::import("maya"); - - boost::python::enum_("ExportFlag") - .value("kNotSupported", ExportFlag::kNotSupported) - .value("kFallbackSupport", ExportFlag::kFallbackSupport) - .value("kSupported", ExportFlag::kSupported); - - boost::python::class_< - TranslatorBaseWrapper, TranslatorBaseWrapperPtr, boost::noncopyable> - ("TranslatorBase", boost::python::no_init) - .def(TfPyRefAndWeakPtr()) - .def(TfMakePyConstructor(&TranslatorBaseWrapper::New)) - .def("initialize", &TranslatorBase::initialize, &TranslatorBaseWrapper::initialize) - .def("getTranslatedType", boost::python::pure_virtual(&TranslatorBase::getTranslatedType)) - .def("generateUniqueKey", &TranslatorBase::generateUniqueKey, &TranslatorBaseWrapper::generateUniqueKey) - .def("context", &TranslatorBase::context) - .def("needsTransformParent", &TranslatorBase::needsTransformParent, &TranslatorBaseWrapper::needsTransformParent) - .def("importableByDefault", &TranslatorBase::importableByDefault, &TranslatorBaseWrapper::importableByDefault) - .def("importObject", &TranslatorBase::import, &TranslatorBaseWrapper::import) - .def("exportObject", &TranslatorBase::exportObject, &TranslatorBaseWrapper::exportObject) - .def("postImport", &TranslatorBase::postImport, &TranslatorBaseWrapper::postImport) - .def("preTearDown", &TranslatorBase::preTearDown, &TranslatorBaseWrapper::preTearDown) - .def("tearDown", &TranslatorBase::tearDown, &TranslatorBaseWrapper::tearDown) - .def("canExport", &TranslatorBase::canExport, &TranslatorBaseWrapper::canExport) - .def("stage", &TranslatorBaseWrapper::stage) - .def("getMObjects", &TranslatorBaseWrapper::getMObjects) - .def("registerTranslator", &TranslatorBaseWrapper::registerTranslator, - (boost::python::arg("translator"), boost::python::arg("assetType")=TfToken())) + typedef TfWeakPtr TranslatorBaseWrapperPtr; + typedef TfRefPtr TranslatorBasePtr; + + boost::python::import("maya"); + + boost::python::enum_("ExportFlag") + .value("kNotSupported", ExportFlag::kNotSupported) + .value("kFallbackSupport", ExportFlag::kFallbackSupport) + .value("kSupported", ExportFlag::kSupported); + + boost::python::class_( + "TranslatorBase", boost::python::no_init) + .def(TfPyRefAndWeakPtr()) + .def(TfMakePyConstructor(&TranslatorBaseWrapper::New)) + .def("initialize", &TranslatorBase::initialize, &TranslatorBaseWrapper::initialize) + .def("getTranslatedType", boost::python::pure_virtual(&TranslatorBase::getTranslatedType)) + .def( + "generateUniqueKey", + &TranslatorBase::generateUniqueKey, + &TranslatorBaseWrapper::generateUniqueKey) + .def("context", &TranslatorBase::context) + .def( + "needsTransformParent", + &TranslatorBase::needsTransformParent, + &TranslatorBaseWrapper::needsTransformParent) + .def( + "importableByDefault", + &TranslatorBase::importableByDefault, + &TranslatorBaseWrapper::importableByDefault) + .def("importObject", &TranslatorBase::import, &TranslatorBaseWrapper::import) + .def("exportObject", &TranslatorBase::exportObject, &TranslatorBaseWrapper::exportObject) + .def("postImport", &TranslatorBase::postImport, &TranslatorBaseWrapper::postImport) + .def("preTearDown", &TranslatorBase::preTearDown, &TranslatorBaseWrapper::preTearDown) + .def("tearDown", &TranslatorBase::tearDown, &TranslatorBaseWrapper::tearDown) + .def("canExport", &TranslatorBase::canExport, &TranslatorBaseWrapper::canExport) + .def("stage", &TranslatorBaseWrapper::stage) + .def("getMObjects", &TranslatorBaseWrapper::getMObjects) + .def( + "registerTranslator", + &TranslatorBaseWrapper::registerTranslator, + (boost::python::arg("translator"), boost::python::arg("assetType") = TfToken())) .staticmethod("registerTranslator") - .def("clearTranslators", &TranslatorBaseWrapper::clearTranslators) + .def("clearTranslators", &TranslatorBaseWrapper::clearTranslators) .staticmethod("clearTranslators") - .def("unregisterTranslator", &TranslatorBaseWrapper::unregisterTranslator) + .def("unregisterTranslator", &TranslatorBaseWrapper::unregisterTranslator) .staticmethod("unregisterTranslator") - .def("insertItem", &TranslatorBaseWrapper::insertItem) - .def("removeItems", &TranslatorBaseWrapper::removeItems) - .def("getPythonTranslators", &TranslatorManufacture::getPythonTranslators) + .def("insertItem", &TranslatorBaseWrapper::insertItem) + .def("removeItems", &TranslatorBaseWrapper::removeItems) + .def("getPythonTranslators", &TranslatorManufacture::getPythonTranslators) .staticmethod("getPythonTranslators"); - boost::python::to_python_converter< std::vector,TfPySequenceToPython< std::vector > >(); + boost::python::to_python_converter< + std::vector, + TfPySequenceToPython>>(); MStatusFromPythonBool::Register(); } diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/wrapTranslatorContext.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/wrapTranslatorContext.cpp index d983c63a3e..51b99ba757 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/wrapTranslatorContext.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/fileio/translators/wrapTranslatorContext.cpp @@ -13,16 +13,16 @@ // See the License for the specific language governing permissions and // limitations under the License. // +#include "AL/maya/utils/Utils.h" #include "AL/usdmaya/fileio/translators/TranslatorContext.h" #include "AL/usdmaya/nodes/ProxyShape.h" -#include "AL/maya/utils/Utils.h" #include #include -#include -#include #include +#include +#include #include @@ -34,81 +34,80 @@ using namespace boost::python; namespace { -static std::string _getTransform(TranslatorContext &self, const SdfPath &path) +static std::string _getTransform(TranslatorContext& self, const SdfPath& path) { - MObjectHandle handle; - if(self.getTransform(path, handle)) - { - MFnDagNode fn(handle.object()); - return fn.fullPathName().asChar(); - } - return {}; + MObjectHandle handle; + if (self.getTransform(path, handle)) { + MFnDagNode fn(handle.object()); + return fn.fullPathName().asChar(); + } + return {}; } -static std::string _getTransform(TranslatorContext &self, const UsdPrim &prim) +static std::string _getTransform(TranslatorContext& self, const UsdPrim& prim) { - return _getTransform(self, prim.GetPath()); + return _getTransform(self, prim.GetPath()); } -static std::string _getMObjectPathWithTypeId(TranslatorContext &self, const SdfPath& path, uint32_t type) +static std::string +_getMObjectPathWithTypeId(TranslatorContext& self, const SdfPath& path, uint32_t type) { - MObjectHandle handle; - if(self.getMObject(path, handle, MTypeId(type))) - { - MFnDagNode fn(handle.object()); - return fn.fullPathName().asChar(); - } - return {}; + MObjectHandle handle; + if (self.getMObject(path, handle, MTypeId(type))) { + MFnDagNode fn(handle.object()); + return fn.fullPathName().asChar(); + } + return {}; } -static std::string _getMObjectPathWithTypeId(TranslatorContext &self, const UsdPrim& prim, uint32_t type) +static std::string +_getMObjectPathWithTypeId(TranslatorContext& self, const UsdPrim& prim, uint32_t type) { - return _getMObjectPathWithTypeId(self, prim.GetPath(), type); + return _getMObjectPathWithTypeId(self, prim.GetPath(), type); } -static std::string _getMObjectPathWithFnType(TranslatorContext &self, const SdfPath& path, uint32_t type) +static std::string +_getMObjectPathWithFnType(TranslatorContext& self, const SdfPath& path, uint32_t type) { - MObjectHandle handle; - if(self.getMObject(path, handle, static_cast(type))) - { - MFnDagNode fn(handle.object()); - return fn.fullPathName().asChar(); - } - return {}; + MObjectHandle handle; + if (self.getMObject(path, handle, static_cast(type))) { + MFnDagNode fn(handle.object()); + return fn.fullPathName().asChar(); + } + return {}; } -static std::string _getMObjectPathWithFnType(TranslatorContext &self, const UsdPrim& prim, uint32_t type) +static std::string +_getMObjectPathWithFnType(TranslatorContext& self, const UsdPrim& prim, uint32_t type) { - return _getMObjectPathWithFnType(self, prim.GetPath(), type); + return _getMObjectPathWithFnType(self, prim.GetPath(), type); } -static std::vector _getMObjectsPath(TranslatorContext &self, const SdfPath& path) +static std::vector _getMObjectsPath(TranslatorContext& self, const SdfPath& path) { - std::vector paths; + std::vector paths; - MObjectHandleArray array; - if(!self.getMObjects(path, array)) - { - return {}; - } + MObjectHandleArray array; + if (!self.getMObjects(path, array)) { + return {}; + } - for(const auto& handle: array) - { - MFnDependencyNode fn(handle.object()); - paths.push_back(fn.name().asChar()); - } + for (const auto& handle : array) { + MFnDependencyNode fn(handle.object()); + paths.push_back(fn.name().asChar()); + } - return paths; + return paths; } -static std::vector _getMObjectsPath(TranslatorContext &self, const UsdPrim& prim) +static std::vector _getMObjectsPath(TranslatorContext& self, const UsdPrim& prim) { - return _getMObjectsPath(self, prim.GetPath()); + return _getMObjectsPath(self, prim.GetPath()); } -static void _insertItem(TranslatorContext &self, const UsdPrim& prim, const std::string& path) +static void _insertItem(TranslatorContext& self, const UsdPrim& prim, const std::string& path) { - self.insertItem(prim, findMayaObject(MString(path.c_str()))); + self.insertItem(prim, findMayaObject(MString(path.c_str()))); } } // namespace @@ -116,59 +115,52 @@ static void _insertItem(TranslatorContext &self, const UsdPrim& prim, const std: //---------------------------------------------------------------------------------------------------------------------- void wrapTranslatorContext() { - typedef TfWeakPtr TranslatorContextPtr; - - class_< - TranslatorContext, TranslatorContextPtr, boost::noncopyable> - ("TranslatorContext", no_init) - .def(TfPyRefAndWeakPtr()) - .def("create", - &TranslatorContext::create, - return_value_policy >()) - .staticmethod("create") - .def("getProxyShape", - &TranslatorContext::getProxyShape, - return_internal_reference<>()) - .def("getUsdStage", &TranslatorContext::getUsdStage) - .def("getTransformPath", - (std::string (*)(TranslatorContext &, const UsdPrim&)) - &_getTransform, - (arg("prim"))) - .def("getTransformPath", - (std::string (*)(TranslatorContext &, const SdfPath&)) - &_getTransform, - (arg("sdfPath"))) - .def("getMObjectPathWithTypeId", - (std::string (*)(TranslatorContext&, const SdfPath&, uint32_t)) - &_getMObjectPathWithTypeId, - (arg("sdfPath"), - arg("typeId"))) - .def("getMObjectPathWithTypeId", - (std::string (*)(TranslatorContext&, const UsdPrim&, uint32_t)) - &_getMObjectPathWithTypeId, - (arg("prim"), - arg("typeId"))) - .def("getMObjectPathWithFnType", - (std::string (*)(TranslatorContext&, const SdfPath&, uint32_t)) - &_getMObjectPathWithFnType, - (arg("sdfPath"), - arg("fnType"))) - .def("getMObjectPathWithFnType", - (std::string (*)(TranslatorContext&, const UsdPrim&, uint32_t)) - &_getMObjectPathWithFnType, - (arg("prim"), - arg("fnType"))) - .def("getMObjectsPath", - (std::vector (*)(TranslatorContext&, const SdfPath&)) - &_getMObjectsPath, - (arg("sdfPath"))) - .def("getMObjectsPath", - (std::vector (*)(TranslatorContext&, const UsdPrim&)) - &_getMObjectsPath, - (arg("prim"))) - .def("insertItem", - &_insertItem); + typedef TfWeakPtr TranslatorContextPtr; + + class_( + "TranslatorContext", no_init) + .def(TfPyRefAndWeakPtr()) + .def("create", &TranslatorContext::create, return_value_policy>()) + .staticmethod("create") + .def("getProxyShape", &TranslatorContext::getProxyShape, return_internal_reference<>()) + .def("getUsdStage", &TranslatorContext::getUsdStage) + .def( + "getTransformPath", + (std::string(*)(TranslatorContext&, const UsdPrim&)) & _getTransform, + (arg("prim"))) + .def( + "getTransformPath", + (std::string(*)(TranslatorContext&, const SdfPath&)) & _getTransform, + (arg("sdfPath"))) + .def( + "getMObjectPathWithTypeId", + (std::string(*)(TranslatorContext&, const SdfPath&, uint32_t)) + & _getMObjectPathWithTypeId, + (arg("sdfPath"), arg("typeId"))) + .def( + "getMObjectPathWithTypeId", + (std::string(*)(TranslatorContext&, const UsdPrim&, uint32_t)) + & _getMObjectPathWithTypeId, + (arg("prim"), arg("typeId"))) + .def( + "getMObjectPathWithFnType", + (std::string(*)(TranslatorContext&, const SdfPath&, uint32_t)) + & _getMObjectPathWithFnType, + (arg("sdfPath"), arg("fnType"))) + .def( + "getMObjectPathWithFnType", + (std::string(*)(TranslatorContext&, const UsdPrim&, uint32_t)) + & _getMObjectPathWithFnType, + (arg("prim"), arg("fnType"))) + .def( + "getMObjectsPath", + (std::vector(*)(TranslatorContext&, const SdfPath&)) & _getMObjectsPath, + (arg("sdfPath"))) + .def( + "getMObjectsPath", + (std::vector(*)(TranslatorContext&, const UsdPrim&)) & _getMObjectsPath, + (arg("prim"))) + .def("insertItem", &_insertItem); } - TF_REFPTR_CONST_VOLATILE_GET(TranslatorContext) diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/module.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/module.cpp index fc6a03d369..91502f0afd 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/module.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/module.cpp @@ -13,12 +13,13 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include #include +#include PXR_NAMESPACE_USING_DIRECTIVE -TF_WRAP_MODULE { +TF_WRAP_MODULE +{ TF_WRAP(LayerManager); TF_WRAP(ProxyShape); TF_WRAP(StageCache); diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/moduleDeps.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/moduleDeps.cpp index 074cfb967c..5c848e1d45 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/moduleDeps.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/moduleDeps.cpp @@ -13,22 +13,21 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include #include #include #include +#include #include PXR_NAMESPACE_OPEN_SCOPE -TF_REGISTRY_FUNCTION(TfScriptModuleLoader) { +TF_REGISTRY_FUNCTION(TfScriptModuleLoader) +{ // List of direct dependencies for this library. - const std::vector reqs = { - TfToken("usd") - }; - TfScriptModuleLoader::GetInstance(). - RegisterLibrary(TfToken("AL_USDMaya"), TfToken("AL.usdmaya"), reqs); + const std::vector reqs = { TfToken("usd") }; + TfScriptModuleLoader::GetInstance().RegisterLibrary( + TfToken("AL_USDMaya"), TfToken("AL.usdmaya"), reqs); } PXR_NAMESPACE_CLOSE_SCOPE diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/BasicTransformationMatrix.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/BasicTransformationMatrix.cpp index 552fa24b6d..60aa4ed12e 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/BasicTransformationMatrix.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/BasicTransformationMatrix.cpp @@ -13,10 +13,11 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/TypeIDs.h" -#include "AL/usdmaya/DebugCodes.h" #include "AL/usdmaya/nodes/BasicTransformationMatrix.h" +#include "AL/usdmaya/DebugCodes.h" +#include "AL/usdmaya/TypeIDs.h" + namespace AL { namespace usdmaya { namespace nodes { @@ -24,43 +25,43 @@ namespace nodes { class Scope; BasicTransformationMatrix::BasicTransformationMatrix() - : MPxTransformationMatrix(), - m_prim() + : MPxTransformationMatrix() + , m_prim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("BasicTransformationMatrix::BasicTransformationMatrix\n"); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("BasicTransformationMatrix::BasicTransformationMatrix\n"); } BasicTransformationMatrix::BasicTransformationMatrix(const UsdPrim& prim) -: MPxTransformationMatrix(), - m_prim(prim) + : MPxTransformationMatrix() + , m_prim(prim) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("BasicTransformationMatrix::BasicTransformationMatrix\n"); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("BasicTransformationMatrix::BasicTransformationMatrix\n"); } MPxTransformationMatrix* BasicTransformationMatrix::creator() { - return new BasicTransformationMatrix; + return new BasicTransformationMatrix; } const MTypeId BasicTransformationMatrix::kTypeId(AL_USDMAYA_IDENTITY_MATRIX); void BasicTransformationMatrix::setPrim(const UsdPrim& prim, Scope* scopeNode) { - if(prim.IsValid()) - { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("BasicTransformationMatrix::setPrim %s\n", prim.GetName().GetText()); - m_prim = prim; - UsdGeomScope scope(prim); - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("BasicTransformationMatrix::setPrim null\n"); - m_prim = UsdPrim(); - } + if (prim.IsValid()) { + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("BasicTransformationMatrix::setPrim %s\n", prim.GetName().GetText()); + m_prim = prim; + UsdGeomScope scope(prim); + } else { + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("BasicTransformationMatrix::setPrim null\n"); + m_prim = UsdPrim(); + } } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/BasicTransformationMatrix.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/BasicTransformationMatrix.h index 4f408d8332..bf725eb618 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/BasicTransformationMatrix.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/BasicTransformationMatrix.h @@ -15,14 +15,13 @@ // #pragma once -#include -#include - #include "AL/usdmaya/Api.h" -#include #include +#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -32,66 +31,59 @@ namespace nodes { class Scope; - //---------------------------------------------------------------------------------------------------------------------- -/// \brief This class provides a very basic transformation matrix that can store a USD Prim and a Maya Node it's -/// able to manipulate. The implementation is very basic, it's also used as an interface for more sophisticated -/// AL_USDMaya transformation matrix implementantations -/// \ingroup nodes +/// \brief This class provides a very basic transformation matrix that can store a USD Prim and a +/// Maya Node it's able to manipulate. The implementation is very basic, it's also used as an +/// interface for more sophisticated AL_USDMaya transformation matrix implementantations \ingroup +/// nodes //---------------------------------------------------------------------------------------------------------------------- -class BasicTransformationMatrix - : public MPxTransformationMatrix +class BasicTransformationMatrix : public MPxTransformationMatrix { public: - /// \brief ctor - BasicTransformationMatrix(); + /// \brief ctor + BasicTransformationMatrix(); - /// \brief ctor - /// \param prim the USD prim that this matrix should represent - BasicTransformationMatrix(const UsdPrim& prim); + /// \brief ctor + /// \param prim the USD prim that this matrix should represent + BasicTransformationMatrix(const UsdPrim& prim); - /// \brief dtor - virtual ~BasicTransformationMatrix() {} + /// \brief dtor + virtual ~BasicTransformationMatrix() { } - /// \brief set the prim that this transformation matrix will read/write to. - /// \param prim the prim - /// \param scopeNode the owning maya node - virtual void setPrim(const UsdPrim& prim, Scope* scopeNode); + /// \brief set the prim that this transformation matrix will read/write to. + /// \param prim the prim + /// \param scopeNode the owning maya node + virtual void setPrim(const UsdPrim& prim, Scope* scopeNode); - /// \brief sets the MObject for the transform - /// \param object the MObject for the custom transform node - void setMObject(const MObject object) - { m_transformNode = object; } + /// \brief sets the MObject for the transform + /// \param object the MObject for the custom transform node + void setMObject(const MObject object) { m_transformNode = object; } - /// \brief Is this transform set to write back onto the USD prim, and is it currently possible? - virtual bool pushToPrimAvailable() const - { return false; } + /// \brief Is this transform set to write back onto the USD prim, and is it currently possible? + virtual bool pushToPrimAvailable() const { return false; } - /// \brief return the prim this transform matrix is attached to - /// \return the prim this transform matrix is controlling - inline const UsdPrim& prim() const - { return m_prim; } + /// \brief return the prim this transform matrix is attached to + /// \return the prim this transform matrix is controlling + inline const UsdPrim& prim() const { return m_prim; } - virtual void initialiseToPrim(bool readFromPrim = true, Scope* node = 0) {} + virtual void initialiseToPrim(bool readFromPrim = true, Scope* node = 0) { } - /// \brief the type ID of the transformation matrix - AL_USDMAYA_PUBLIC - static const MTypeId kTypeId; + /// \brief the type ID of the transformation matrix + AL_USDMAYA_PUBLIC + static const MTypeId kTypeId; - /// \brief create an instance of this transformation matrix - /// \return a new instance of this transformation matrix - AL_USDMAYA_PUBLIC - static MPxTransformationMatrix* creator(); + /// \brief create an instance of this transformation matrix + /// \return a new instance of this transformation matrix + AL_USDMAYA_PUBLIC + static MPxTransformationMatrix* creator(); protected: - UsdPrim m_prim; - MObjectHandle m_transformNode; - + UsdPrim m_prim; + MObjectHandle m_transformNode; }; - //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Engine.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Engine.cpp index 679b9a0b40..b89e1031d5 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Engine.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Engine.cpp @@ -28,7 +28,6 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include #include "AL/usdmaya/nodes/Engine.h" #include @@ -36,103 +35,105 @@ #include #include +#include + namespace AL { namespace usdmaya { namespace nodes { Engine::Engine(const SdfPath& rootPath, const SdfPathVector& excludedPaths) - : UsdImagingGLEngine(rootPath, excludedPaths) {} + : UsdImagingGLEngine(rootPath, excludedPaths) +{ +} bool Engine::TestIntersectionBatch( - const GfMatrix4d &viewMatrix, - const GfMatrix4d &projectionMatrix, - const GfMatrix4d &worldToLocalSpace, - const SdfPathVector& paths, - UsdImagingGLRenderParams params, - unsigned int pickResolution, - PathTranslatorCallback pathTranslator, - HitBatch *outHit) { - if (ARCH_UNLIKELY(_legacyImpl)) { - return false; - } - - _UpdateHydraCollection(&_intersectCollection, paths, params); - - TfTokenVector renderTags; - _ComputeRenderTags(params, &renderTags); - _taskController->SetRenderTags(renderTags); - - HdxPickHitVector allHits; - - HdxRenderTaskParams hdParams = _MakeHydraUsdImagingGLRenderParams(params); - _taskController->SetRenderParams(hdParams); - - - HdxPickTaskContextParams pickParams; - pickParams.resolution = GfVec2i(pickResolution, pickResolution); - pickParams.resolveMode = HdxPickTokens->resolveUnique; - pickParams.viewMatrix = worldToLocalSpace * viewMatrix; - pickParams.projectionMatrix = projectionMatrix; - pickParams.clipPlanes = params.clipPlanes; - pickParams.collection = _intersectCollection; - pickParams.outHits = &allHits; - VtValue vtPickParams(pickParams); + const GfMatrix4d& viewMatrix, + const GfMatrix4d& projectionMatrix, + const GfMatrix4d& worldToLocalSpace, + const SdfPathVector& paths, + UsdImagingGLRenderParams params, + unsigned int pickResolution, + PathTranslatorCallback pathTranslator, + HitBatch* outHit) +{ + if (ARCH_UNLIKELY(_legacyImpl)) { + return false; + } + + _UpdateHydraCollection(&_intersectCollection, paths, params); + + TfTokenVector renderTags; + _ComputeRenderTags(params, &renderTags); + _taskController->SetRenderTags(renderTags); + + HdxPickHitVector allHits; + + HdxRenderTaskParams hdParams = _MakeHydraUsdImagingGLRenderParams(params); + _taskController->SetRenderParams(hdParams); + + HdxPickTaskContextParams pickParams; + pickParams.resolution = GfVec2i(pickResolution, pickResolution); + pickParams.resolveMode = HdxPickTokens->resolveUnique; + pickParams.viewMatrix = worldToLocalSpace * viewMatrix; + pickParams.projectionMatrix = projectionMatrix; + pickParams.clipPlanes = params.clipPlanes; + pickParams.collection = _intersectCollection; + pickParams.outHits = &allHits; + VtValue vtPickParams(pickParams); #if defined(USDIMAGINGGL_API_VERSION) && USDIMAGINGGL_API_VERSION >= 6 - HdEngine* hdEngine = _GetHdEngine(); + HdEngine* hdEngine = _GetHdEngine(); #else - HdEngine* hdEngine = &_engine; + HdEngine* hdEngine = &_engine; #endif - hdEngine->SetTaskContextData(HdxPickTokens->pickParams, vtPickParams); - auto pickingTasks = _taskController->GetPickingTasks(); - hdEngine->Execute(_taskController->GetRenderIndex(), &pickingTasks); + hdEngine->SetTaskContextData(HdxPickTokens->pickParams, vtPickParams); + auto pickingTasks = _taskController->GetPickingTasks(); + hdEngine->Execute(_taskController->GetRenderIndex(), &pickingTasks); - if (allHits.size() == 0) { - return false; - } + if (allHits.size() == 0) { + return false; + } - if (!outHit) { - return true; - } + if (!outHit) { + return true; + } - for (const auto& hit : allHits) { - SdfPath primPath = hit.objectId; - SdfPath instancerPath = hit.instancerId; - int instanceIndex = hit.instanceIndex; + for (const auto& hit : allHits) { + SdfPath primPath = hit.objectId; + SdfPath instancerPath = hit.instancerId; + int instanceIndex = hit.instanceIndex; #if defined(USDIMAGINGGL_API_VERSION) && USDIMAGINGGL_API_VERSION >= 5 - // See similar code in usdImagingGL/engine.cpp... - primPath = _GetSceneDelegate()->GetScenePrimPath(primPath, instanceIndex); - instancerPath = _GetSceneDelegate()->ConvertIndexPathToCachePath(instancerPath) - .GetAbsoluteRootOrPrimPath(); + // See similar code in usdImagingGL/engine.cpp... + primPath = _GetSceneDelegate()->GetScenePrimPath(primPath, instanceIndex); + instancerPath = _GetSceneDelegate() + ->ConvertIndexPathToCachePath(instancerPath) + .GetAbsoluteRootOrPrimPath(); #elif defined(USDIMAGINGGL_API_VERSION) && USDIMAGINGGL_API_VERSION >= 3 - // See similar code in usdImagingGL/engine.cpp... - primPath = _delegate->GetScenePrimPath(primPath, instanceIndex); - instancerPath = _delegate->ConvertIndexPathToCachePath(instancerPath) - .GetAbsoluteRootOrPrimPath(); + // See similar code in usdImagingGL/engine.cpp... + primPath = _delegate->GetScenePrimPath(primPath, instanceIndex); + instancerPath + = _delegate->ConvertIndexPathToCachePath(instancerPath).GetAbsoluteRootOrPrimPath(); #else - SdfPath resolvedPath = - GetPrimPathFromInstanceIndex(primPath, instanceIndex); - if (!resolvedPath.IsEmpty()) { - primPath = resolvedPath; - } else { - primPath = primPath.StripAllVariantSelections(); - } + SdfPath resolvedPath = GetPrimPathFromInstanceIndex(primPath, instanceIndex); + if (!resolvedPath.IsEmpty()) { + primPath = resolvedPath; + } else { + primPath = primPath.StripAllVariantSelections(); + } #endif - HitInfo& info = (*outHit)[pathTranslator(primPath, instancerPath, - instanceIndex)]; + HitInfo& info = (*outHit)[pathTranslator(primPath, instancerPath, instanceIndex)]; - info.worldSpaceHitPoint = GfVec3d(hit.worldSpaceHitPoint[0], - hit.worldSpaceHitPoint[1], - hit.worldSpaceHitPoint[2]); - info.hitInstanceIndex = instanceIndex; - } + info.worldSpaceHitPoint = GfVec3d( + hit.worldSpaceHitPoint[0], hit.worldSpaceHitPoint[1], hit.worldSpaceHitPoint[2]); + info.hitInstanceIndex = instanceIndex; + } - return true; + return true; } -} -} -} +} // namespace nodes +} // namespace usdmaya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Engine.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Engine.h index 59979c6446..1163f6ac66 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Engine.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Engine.h @@ -24,30 +24,32 @@ namespace AL { namespace usdmaya { namespace nodes { -class Engine : public UsdImagingGLEngine { +class Engine : public UsdImagingGLEngine +{ public: - Engine(const SdfPath& rootPath, - const SdfPathVector& excludedPaths); - - struct HitInfo { - GfVec3d worldSpaceHitPoint; - int hitInstanceIndex; - }; - typedef TfHashMap HitBatch; - - typedef std::function PathTranslatorCallback; - - bool TestIntersectionBatch( - const GfMatrix4d &viewMatrix, - const GfMatrix4d &projectionMatrix, - const GfMatrix4d &worldToLocalSpace, - const SdfPathVector& paths, - UsdImagingGLRenderParams params, - unsigned int pickResolution, - PathTranslatorCallback pathTranslator, - HitBatch *outHit); + Engine(const SdfPath& rootPath, const SdfPathVector& excludedPaths); + + struct HitInfo + { + GfVec3d worldSpaceHitPoint; + int hitInstanceIndex; + }; + typedef TfHashMap HitBatch; + + typedef std::function + PathTranslatorCallback; + + bool TestIntersectionBatch( + const GfMatrix4d& viewMatrix, + const GfMatrix4d& projectionMatrix, + const GfMatrix4d& worldToLocalSpace, + const SdfPathVector& paths, + UsdImagingGLRenderParams params, + unsigned int pickResolution, + PathTranslatorCallback pathTranslator, + HitBatch* outHit); }; -} -} -} +} // namespace nodes +} // namespace usdmaya +} // namespace AL diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Layer.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Layer.cpp index 9599e2d0ca..92593d09e1 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Layer.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Layer.cpp @@ -13,10 +13,11 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/TypeIDs.h" -#include "AL/usdmaya/DebugCodes.h" #include "AL/usdmaya/nodes/Layer.h" +#include "AL/usdmaya/DebugCodes.h" +#include "AL/usdmaya/TypeIDs.h" + PXR_NAMESPACE_USING_DIRECTIVE namespace AL { @@ -60,54 +61,66 @@ MObject Layer::m_hasBeenEditTarget = MObject::kNullObj; //---------------------------------------------------------------------------------------------------------------------- MStatus Layer::initialise() { - TF_DEBUG(ALUSDMAYA_LAYERS).Msg("Layer::initialise\n"); - try - { - setNodeType(kTypeName); - addFrame("USD Layer Info"); + TF_DEBUG(ALUSDMAYA_LAYERS).Msg("Layer::initialise\n"); + try { + setNodeType(kTypeName); + addFrame("USD Layer Info"); - // do not write these nodes to the file. They will be created automagically by the proxy shape - m_comment = addStringAttr("comment", "cm", kReadable | kWritable); - m_defaultPrim = addStringAttr("defaultPrim", "dp", kReadable | kWritable); - m_documentation = addStringAttr("documentation", "docs", kReadable | kWritable); - m_startTime = addDoubleAttr("startTime", "stc", 0, kReadable | kWritable); - m_endTime = addDoubleAttr("endTime", "etc", 0, kReadable | kWritable); - m_timeCodesPerSecond = addDoubleAttr("timeCodesPerSecond", "tcps", 0, kReadable | kWritable); - m_framePrecision = addInt32Attr("framePrecision", "fp", 0, kReadable | kWritable); - m_owner = addStringAttr("owner", "own", kReadable | kWritable); - m_sessionOwner = addStringAttr("sessionOwner", "sho", kReadable | kWritable); - m_permissionToEdit = addBoolAttr("permissionToEdit", "pte", false, kReadable | kWritable); - m_permissionToSave = addBoolAttr("permissionToSave", "pts", false, kReadable | kWritable); + // do not write these nodes to the file. They will be created automagically by the proxy + // shape + m_comment = addStringAttr("comment", "cm", kReadable | kWritable); + m_defaultPrim = addStringAttr("defaultPrim", "dp", kReadable | kWritable); + m_documentation = addStringAttr("documentation", "docs", kReadable | kWritable); + m_startTime = addDoubleAttr("startTime", "stc", 0, kReadable | kWritable); + m_endTime = addDoubleAttr("endTime", "etc", 0, kReadable | kWritable); + m_timeCodesPerSecond + = addDoubleAttr("timeCodesPerSecond", "tcps", 0, kReadable | kWritable); + m_framePrecision = addInt32Attr("framePrecision", "fp", 0, kReadable | kWritable); + m_owner = addStringAttr("owner", "own", kReadable | kWritable); + m_sessionOwner = addStringAttr("sessionOwner", "sho", kReadable | kWritable); + m_permissionToEdit = addBoolAttr("permissionToEdit", "pte", false, kReadable | kWritable); + m_permissionToSave = addBoolAttr("permissionToSave", "pts", false, kReadable | kWritable); - // parent/child relationships - m_proxyShape = addMessageAttr("proxyShape", "psh", kConnectable | kReadable | kWritable | kHidden | kStorable); - m_subLayers = addMessageAttr("subLayers", "sl", kConnectable | kReadable | kWritable | kHidden | kArray | kUsesArrayDataBuilder | kStorable); - m_parentLayer = addMessageAttr("parentLayer", "pl", kConnectable | kReadable | kWritable | kHidden | kStorable); - m_childLayers = addMessageAttr("childLayer", "cl", kConnectable | kReadable | kWritable | kHidden | kArray | kUsesArrayDataBuilder | kStorable); + // parent/child relationships + m_proxyShape = addMessageAttr( + "proxyShape", "psh", kConnectable | kReadable | kWritable | kHidden | kStorable); + m_subLayers = addMessageAttr( + "subLayers", + "sl", + kConnectable | kReadable | kWritable | kHidden | kArray | kUsesArrayDataBuilder + | kStorable); + m_parentLayer = addMessageAttr( + "parentLayer", "pl", kConnectable | kReadable | kWritable | kHidden | kStorable); + m_childLayers = addMessageAttr( + "childLayer", + "cl", + kConnectable | kReadable | kWritable | kHidden | kArray | kUsesArrayDataBuilder + | kStorable); - addFrame("USD Layer Identification"); - m_displayName = addStringAttr("displayName", "dn", kReadable | kWritable); - m_realPath = addStringAttr("realPath", "rp", kReadable | kWritable); - m_fileExtension = addStringAttr("fileExtension", "fe", kReadable | kWritable); - m_version = addStringAttr("version", "ver", kWritable | kReadable); - m_repositoryPath = addStringAttr("repositoryPath", "rpath", kReadable | kWritable); - m_assetName = addStringAttr("assetName", "an", kReadable | kWritable); + addFrame("USD Layer Identification"); + m_displayName = addStringAttr("displayName", "dn", kReadable | kWritable); + m_realPath = addStringAttr("realPath", "rp", kReadable | kWritable); + m_fileExtension = addStringAttr("fileExtension", "fe", kReadable | kWritable); + m_version = addStringAttr("version", "ver", kWritable | kReadable); + m_repositoryPath = addStringAttr("repositoryPath", "rpath", kReadable | kWritable); + m_assetName = addStringAttr("assetName", "an", kReadable | kWritable); - // add attributes to store the serialisation info - m_serialized = addStringAttr("serialised", "szd", kReadable | kWritable | kStorable | kHidden); - m_nameOnLoad = addStringAttr("nameOnLoad", "nol", kReadable | kWritable | kStorable | kHidden); - m_hasBeenEditTarget = addBoolAttr("hasBeenEditTarget", "hbet", false, kReadable | kWritable | kStorable | kHidden); - } - catch(const MStatus& status) - { - return status; - } - generateAETemplate(); - return MS::kSuccess; + // add attributes to store the serialisation info + m_serialized + = addStringAttr("serialised", "szd", kReadable | kWritable | kStorable | kHidden); + m_nameOnLoad + = addStringAttr("nameOnLoad", "nol", kReadable | kWritable | kStorable | kHidden); + m_hasBeenEditTarget = addBoolAttr( + "hasBeenEditTarget", "hbet", false, kReadable | kWritable | kStorable | kHidden); + } catch (const MStatus& status) { + return status; + } + generateAETemplate(); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Layer.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Layer.h index acf46d4170..33697c0d00 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Layer.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Layer.h @@ -25,255 +25,255 @@ namespace usdmaya { namespace nodes { //---------------------------------------------------------------------------------------------------------------------- -/// \brief The layer node stores a reference to an SdfLayer. Obsolete. LayerManager now used instead. -/// \ingroup nodes +/// \brief The layer node stores a reference to an SdfLayer. Obsolete. LayerManager now used +/// instead. \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- class Layer - : public MPxNode, - public AL::maya::utils::NodeHelper + : public MPxNode + , public AL::maya::utils::NodeHelper { public: - - /// \brief ctor - inline Layer() - : MPxNode(), NodeHelper() {} - - //-------------------------------------------------------------------------------------------------------------------- - /// Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- - AL_MAYA_DECLARE_NODE(); - - //-------------------------------------------------------------------------------------------------------------------- - /// Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- - - AL_DECL_ATTRIBUTE(comment); - AL_DECL_ATTRIBUTE(defaultPrim); - AL_DECL_ATTRIBUTE(documentation); - AL_DECL_ATTRIBUTE(startTime); - AL_DECL_ATTRIBUTE(endTime); - AL_DECL_ATTRIBUTE(timeCodesPerSecond); - AL_DECL_ATTRIBUTE(framePrecision); - AL_DECL_ATTRIBUTE(owner); - AL_DECL_ATTRIBUTE(sessionOwner); - AL_DECL_ATTRIBUTE(permissionToEdit); - AL_DECL_ATTRIBUTE(permissionToSave); - AL_DECL_ATTRIBUTE(proxyShape); - AL_DECL_ATTRIBUTE(subLayers); - AL_DECL_ATTRIBUTE(childLayers); - AL_DECL_ATTRIBUTE(parentLayer); - - // read only identification - AL_DECL_ATTRIBUTE(displayName); - AL_DECL_ATTRIBUTE(realPath); - AL_DECL_ATTRIBUTE(fileExtension); - AL_DECL_ATTRIBUTE(version); - AL_DECL_ATTRIBUTE(repositoryPath); - AL_DECL_ATTRIBUTE(assetName); - - // attribute to store the serialised layer (used for file IO only) - AL_DECL_ATTRIBUTE(serialized); - AL_DECL_ATTRIBUTE(nameOnLoad); - AL_DECL_ATTRIBUTE(hasBeenEditTarget); + /// \brief ctor + inline Layer() + : MPxNode() + , NodeHelper() + { + } + + //-------------------------------------------------------------------------------------------------------------------- + /// Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- + AL_MAYA_DECLARE_NODE(); + + //-------------------------------------------------------------------------------------------------------------------- + /// Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- + + AL_DECL_ATTRIBUTE(comment); + AL_DECL_ATTRIBUTE(defaultPrim); + AL_DECL_ATTRIBUTE(documentation); + AL_DECL_ATTRIBUTE(startTime); + AL_DECL_ATTRIBUTE(endTime); + AL_DECL_ATTRIBUTE(timeCodesPerSecond); + AL_DECL_ATTRIBUTE(framePrecision); + AL_DECL_ATTRIBUTE(owner); + AL_DECL_ATTRIBUTE(sessionOwner); + AL_DECL_ATTRIBUTE(permissionToEdit); + AL_DECL_ATTRIBUTE(permissionToSave); + AL_DECL_ATTRIBUTE(proxyShape); + AL_DECL_ATTRIBUTE(subLayers); + AL_DECL_ATTRIBUTE(childLayers); + AL_DECL_ATTRIBUTE(parentLayer); + + // read only identification + AL_DECL_ATTRIBUTE(displayName); + AL_DECL_ATTRIBUTE(realPath); + AL_DECL_ATTRIBUTE(fileExtension); + AL_DECL_ATTRIBUTE(version); + AL_DECL_ATTRIBUTE(repositoryPath); + AL_DECL_ATTRIBUTE(assetName); + + // attribute to store the serialised layer (used for file IO only) + AL_DECL_ATTRIBUTE(serialized); + AL_DECL_ATTRIBUTE(nameOnLoad); + AL_DECL_ATTRIBUTE(hasBeenEditTarget); private: + /// \var static MObject comment(); + /// \brief access the comment attribute handle + /// \return the handle to the comment attribute - /// \var static MObject comment(); - /// \brief access the comment attribute handle - /// \return the handle to the comment attribute - - /// \var static MObject defaultPrim(); - /// \brief access the defaultPrim attribute handle - /// \return the handle to the defaultPrim attribute + /// \var static MObject defaultPrim(); + /// \brief access the defaultPrim attribute handle + /// \return the handle to the defaultPrim attribute - /// \var static MObject documentation(); - /// \brief access the documentation attribute handle - /// \return the handle to the documentation attribute + /// \var static MObject documentation(); + /// \brief access the documentation attribute handle + /// \return the handle to the documentation attribute - /// \var static MObject startTime(); - /// \brief access the startTime attribute handle - /// \return the handle to the startTime attribute + /// \var static MObject startTime(); + /// \brief access the startTime attribute handle + /// \return the handle to the startTime attribute - /// \var static MObject endTime(); - /// \brief access the endTime attribute handle - /// \return the handle to the endTime attribute + /// \var static MObject endTime(); + /// \brief access the endTime attribute handle + /// \return the handle to the endTime attribute - /// \var static MObject timeCodesPerSecond(); - /// \brief access the timeCodesPerSecond attribute handle - /// \return the handle to the timeCodesPerSecond attribute + /// \var static MObject timeCodesPerSecond(); + /// \brief access the timeCodesPerSecond attribute handle + /// \return the handle to the timeCodesPerSecond attribute - /// \var static MObject framePrecision(); - /// \brief access the framePrecision attribute handle - /// \return the handle to the framePrecision attribute + /// \var static MObject framePrecision(); + /// \brief access the framePrecision attribute handle + /// \return the handle to the framePrecision attribute - /// \var static MObject owner(); - /// \brief access the owner attribute handle - /// \return the handle to the owner attribute + /// \var static MObject owner(); + /// \brief access the owner attribute handle + /// \return the handle to the owner attribute - /// \var static MObject sessionOwner(); - /// \brief access the sessionOwner attribute handle - /// \return the handle to the sessionOwner attribute + /// \var static MObject sessionOwner(); + /// \brief access the sessionOwner attribute handle + /// \return the handle to the sessionOwner attribute - /// \var static MObject permissionToEdit(); - /// \brief access the permissionToEdit attribute handle - /// \return the handle to the permissionToEdit attribute + /// \var static MObject permissionToEdit(); + /// \brief access the permissionToEdit attribute handle + /// \return the handle to the permissionToEdit attribute - /// \var static MObject permissionToSave(); - /// \brief access the permissionToSave attribute handle - /// \return the handle to the permissionToSave attribute + /// \var static MObject permissionToSave(); + /// \brief access the permissionToSave attribute handle + /// \return the handle to the permissionToSave attribute - /// \var static MObject proxyShape(); - /// \brief access the proxyShape attribute handle - /// \return the handle to the proxyShape attribute + /// \var static MObject proxyShape(); + /// \brief access the proxyShape attribute handle + /// \return the handle to the proxyShape attribute - /// \var static MObject subLayers(); - /// \brief access the subLayers attribute handle - /// \return the handle to the owner attribute + /// \var static MObject subLayers(); + /// \brief access the subLayers attribute handle + /// \return the handle to the owner attribute - /// \var static MObject childLayers(); - /// \brief access the childLayers attribute handle - /// \return the handle to the childLayers attribute + /// \var static MObject childLayers(); + /// \brief access the childLayers attribute handle + /// \return the handle to the childLayers attribute - /// \var static MObject parentLayer(); - /// \brief access the parentLayer attribute handle - /// \return the handle to the parentLayer attribute + /// \var static MObject parentLayer(); + /// \brief access the parentLayer attribute handle + /// \return the handle to the parentLayer attribute - /// \var static MObject displayName(); - /// \brief access the displayName attribute handle - /// \return the handle to the displayName attribute + /// \var static MObject displayName(); + /// \brief access the displayName attribute handle + /// \return the handle to the displayName attribute - /// \var static MObject realPath(); - /// \brief access the realPath attribute handle - /// \return the plug to the realPath attribute + /// \var static MObject realPath(); + /// \brief access the realPath attribute handle + /// \return the plug to the realPath attribute - /// \var static MObject fileExtension(); - /// \brief access the fileExtension attribute handle - /// \return the handle to the fileExtension attribute + /// \var static MObject fileExtension(); + /// \brief access the fileExtension attribute handle + /// \return the handle to the fileExtension attribute - /// \var static MObject version(); - /// \brief access the version attribute handle - /// \return the handle to the version attribute + /// \var static MObject version(); + /// \brief access the version attribute handle + /// \return the handle to the version attribute - /// \var static MObject repositoryPath(); - /// \brief access the repositoryPath attribute handle - /// \return the handle to the repositoryPath attribute + /// \var static MObject repositoryPath(); + /// \brief access the repositoryPath attribute handle + /// \return the handle to the repositoryPath attribute - /// \var static MObject assetName(); - /// \brief access the assetName attribute handle - /// \return the handle to the assetName attribute + /// \var static MObject assetName(); + /// \brief access the assetName attribute handle + /// \return the handle to the assetName attribute - /// \var static MObject serialized(); - /// \brief access the serialized attribute handle - /// \return the handle to the serialized attribute + /// \var static MObject serialized(); + /// \brief access the serialized attribute handle + /// \return the handle to the serialized attribute - /// \var static MObject nameOnLoad(); - /// \brief access the nameOnLoad attribute handle - /// \return the handle to the nameOnLoad attribute + /// \var static MObject nameOnLoad(); + /// \brief access the nameOnLoad attribute handle + /// \return the handle to the nameOnLoad attribute - /// \var static MObject hasBeenEditTarget(); - /// \brief access the owner attribute handle - /// \return the handle to the hasBeenEditTarget attribute + /// \var static MObject hasBeenEditTarget(); + /// \brief access the owner attribute handle + /// \return the handle to the hasBeenEditTarget attribute - /// \var MPlug commentPlug() const; - /// \brief access the comment attribute plug on this node instance. - /// \return the plug to the comment attribute + /// \var MPlug commentPlug() const; + /// \brief access the comment attribute plug on this node instance. + /// \return the plug to the comment attribute - /// \var MPlug defaultPrimPlug() const; - /// \brief access the defaultPrim attribute plug on this node instance. - /// \return the plug to the defaultPrim attribute + /// \var MPlug defaultPrimPlug() const; + /// \brief access the defaultPrim attribute plug on this node instance. + /// \return the plug to the defaultPrim attribute - /// \var MPlug documentationPlug() const; - /// \brief access the documentation attribute plug on this node instance. - /// \return the plug to the documentation attribute + /// \var MPlug documentationPlug() const; + /// \brief access the documentation attribute plug on this node instance. + /// \return the plug to the documentation attribute - /// \var MPlug startTimePlug() const; - /// \brief access the startTime attribute plug on this node instance. - /// \return the plug to the startTime attribute + /// \var MPlug startTimePlug() const; + /// \brief access the startTime attribute plug on this node instance. + /// \return the plug to the startTime attribute - /// \var MPlug endTimePlug() const; - /// \brief access the endTime attribute plug on this node instance. - /// \return the plug to the endTime attribute + /// \var MPlug endTimePlug() const; + /// \brief access the endTime attribute plug on this node instance. + /// \return the plug to the endTime attribute - /// \var MPlug timeCodesPerSecondPlug() const; - /// \brief access the timeCodesPerSecond attribute plug on this node instance. - /// \return the plug to the timeCodesPerSecond attribute + /// \var MPlug timeCodesPerSecondPlug() const; + /// \brief access the timeCodesPerSecond attribute plug on this node instance. + /// \return the plug to the timeCodesPerSecond attribute - /// \var MPlug framePrecisionPlug() const; - /// \brief access the framePrecision attribute plug on this node instance. - /// \return the plug to the framePrecision attribute + /// \var MPlug framePrecisionPlug() const; + /// \brief access the framePrecision attribute plug on this node instance. + /// \return the plug to the framePrecision attribute - /// \var MPlug ownerPlug() const; - /// \brief access the owner attribute plug on this node instance. - /// \return the plug to the owner attribute + /// \var MPlug ownerPlug() const; + /// \brief access the owner attribute plug on this node instance. + /// \return the plug to the owner attribute - /// \var MPlug sessionOwnerPlug() const; - /// \brief access the sessionOwner attribute plug on this node instance. - /// \return the plug to the sessionOwner attribute + /// \var MPlug sessionOwnerPlug() const; + /// \brief access the sessionOwner attribute plug on this node instance. + /// \return the plug to the sessionOwner attribute - /// \var MPlug permissionToEditPlug() const; - /// \brief access the permissionToEdit attribute plug on this node instance. - /// \return the plug to the permissionToEdit attribute + /// \var MPlug permissionToEditPlug() const; + /// \brief access the permissionToEdit attribute plug on this node instance. + /// \return the plug to the permissionToEdit attribute - /// \var MPlug permissionToSavePlug() const; - /// \brief access the permissionToSave attribute plug on this node instance. - /// \return the plug to the permissionToSave attribute + /// \var MPlug permissionToSavePlug() const; + /// \brief access the permissionToSave attribute plug on this node instance. + /// \return the plug to the permissionToSave attribute - /// \var MPlug proxyShapePlug() const; - /// \brief access the proxyShape attribute plug on this node instance. - /// \return the plug to the proxyShape attribute + /// \var MPlug proxyShapePlug() const; + /// \brief access the proxyShape attribute plug on this node instance. + /// \return the plug to the proxyShape attribute - /// \var MPlug subLayersPlug() const; - /// \brief access the subLayers attribute plug on this node instance. - /// \return the plug to the owner attribute + /// \var MPlug subLayersPlug() const; + /// \brief access the subLayers attribute plug on this node instance. + /// \return the plug to the owner attribute - /// \var MPlug childLayersPlug() const; - /// \brief access the childLayers attribute plug on this node instance. - /// \return the plug to the childLayers attribute + /// \var MPlug childLayersPlug() const; + /// \brief access the childLayers attribute plug on this node instance. + /// \return the plug to the childLayers attribute - /// \var MPlug parentLayerPlug() const; - /// \brief access the parentLayer attribute plug on this node instance. - /// \return the plug to the parentLayer attribute + /// \var MPlug parentLayerPlug() const; + /// \brief access the parentLayer attribute plug on this node instance. + /// \return the plug to the parentLayer attribute - /// \var MPlug displayNamePlug() const; - /// \brief access the displayName attribute plug on this node instance. - /// \return the plug to the displayName attribute + /// \var MPlug displayNamePlug() const; + /// \brief access the displayName attribute plug on this node instance. + /// \return the plug to the displayName attribute - /// \var MPlug realPathPlug() const; - /// \brief access the realPath attribute plug on this node instance. - /// \return the plug to the realPath attribute + /// \var MPlug realPathPlug() const; + /// \brief access the realPath attribute plug on this node instance. + /// \return the plug to the realPath attribute - /// \var MPlug fileExtensionPlug() const; - /// \brief access the fileExtension attribute plug on this node instance. - /// \return the plug to the fileExtension attribute + /// \var MPlug fileExtensionPlug() const; + /// \brief access the fileExtension attribute plug on this node instance. + /// \return the plug to the fileExtension attribute - /// \var MPlug versionPlug() const; - /// \brief access the version attribute plug on this node instance. - /// \return the plug to the version attribute + /// \var MPlug versionPlug() const; + /// \brief access the version attribute plug on this node instance. + /// \return the plug to the version attribute - /// \var MPlug repositoryPathPlug() const; - /// \brief access the repositoryPath attribute plug on this node instance. - /// \return the plug to the repositoryPath attribute + /// \var MPlug repositoryPathPlug() const; + /// \brief access the repositoryPath attribute plug on this node instance. + /// \return the plug to the repositoryPath attribute - /// \var MPlug assetNamePlug() const; - /// \brief access the assetName attribute plug on this node instance. - /// \return the plug to the assetName attribute + /// \var MPlug assetNamePlug() const; + /// \brief access the assetName attribute plug on this node instance. + /// \return the plug to the assetName attribute - /// \var MPlug serializedPlug() const; - /// \brief access the serialized attribute plug on this node instance. - /// \return the plug to the serialized attribute + /// \var MPlug serializedPlug() const; + /// \brief access the serialized attribute plug on this node instance. + /// \return the plug to the serialized attribute - /// \var MPlug nameOnLoadPlug() const; - /// \brief access the nameOnLoad attribute plug on this node instance. - /// \return the plug to the nameOnLoad attribute + /// \var MPlug nameOnLoadPlug() const; + /// \brief access the nameOnLoad attribute plug on this node instance. + /// \return the plug to the nameOnLoad attribute - /// \var MPlug hasBeenEditTargetPlug() const; - /// \brief access the owner attribute plug on this node instance. - /// \return the plug to the hasBeenEditTarget attribute + /// \var MPlug hasBeenEditTargetPlug() const; + /// \brief access the owner attribute plug on this node instance. + /// \return the plug to the hasBeenEditTarget attribute }; //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/LayerManager.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/LayerManager.cpp index a03e8b8da8..9dd68757e3 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/LayerManager.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/LayerManager.cpp @@ -13,16 +13,16 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/maya/utils/Utils.h" +#include "AL/usdmaya/nodes/LayerManager.h" +#include "AL/maya/utils/Utils.h" #include "AL/usdmaya/DebugCodes.h" #include "AL/usdmaya/TypeIDs.h" -#include "AL/usdmaya/nodes/LayerManager.h" #include +#include #include #include -#include #include #include @@ -33,76 +33,72 @@ #include #include + #include namespace { - // Global mutex protecting _findNode / findOrCreateNode. - // Recursive because we need to get the mutex inside of conditionalCreator, - // but that may be triggered by the node creation inside of findOrCreateNode. - - // Note on layerManager / multithreading: - // I don't know that layerManager will be used in a multithreaded manner... but I also don't know it COULDN'T be. - // (I haven't really looked into the way maya's new multithreaded node evaluation works, for instance.) This is - // essentially a globally shared resource, so I figured better be safe... - static std::recursive_mutex _findNodeMutex; - - - // Utility func to disconnect an array plug, and all it's element plugs, and all - // their child plugs. - // Not in Utils, because it's not generic - ie, doesn't handle general case - // where compound/array plugs may be nested arbitrarily deep... - MStatus disconnectCompoundArrayPlug(MPlug arrayPlug) - { +// Global mutex protecting _findNode / findOrCreateNode. +// Recursive because we need to get the mutex inside of conditionalCreator, +// but that may be triggered by the node creation inside of findOrCreateNode. + +// Note on layerManager / multithreading: +// I don't know that layerManager will be used in a multithreaded manner... but I also don't know it +// COULDN'T be. (I haven't really looked into the way maya's new multithreaded node evaluation +// works, for instance.) This is essentially a globally shared resource, so I figured better be +// safe... +static std::recursive_mutex _findNodeMutex; + +// Utility func to disconnect an array plug, and all it's element plugs, and all +// their child plugs. +// Not in Utils, because it's not generic - ie, doesn't handle general case +// where compound/array plugs may be nested arbitrarily deep... +MStatus disconnectCompoundArrayPlug(MPlug arrayPlug) +{ const char* errorString = "disconnectCompoundArrayPlug"; - MStatus status; - MPlug elemPlug; - MPlug srcPlug; - MPlugArray destPlugs; + MStatus status; + MPlug elemPlug; + MPlug srcPlug; + MPlugArray destPlugs; MDGModifier dgmod; auto disconnectPlug = [&](MPlug plug) -> MStatus { - MStatus status; - srcPlug = plug.source(&status); - AL_MAYA_CHECK_ERROR(status, errorString); - if(!srcPlug.isNull()) - { - dgmod.disconnect(srcPlug, plug); - } - destPlugs.clear(); - plug.destinations(destPlugs, &status); - AL_MAYA_CHECK_ERROR(status, errorString); - for(size_t i=0; i < destPlugs.length(); ++i) - { - dgmod.disconnect(plug, destPlugs[i]); - } - return status; + MStatus status; + srcPlug = plug.source(&status); + AL_MAYA_CHECK_ERROR(status, errorString); + if (!srcPlug.isNull()) { + dgmod.disconnect(srcPlug, plug); + } + destPlugs.clear(); + plug.destinations(destPlugs, &status); + AL_MAYA_CHECK_ERROR(status, errorString); + for (size_t i = 0; i < destPlugs.length(); ++i) { + dgmod.disconnect(plug, destPlugs[i]); + } + return status; }; - // Considered using numConnectedElements, but for arrays-of-compound attributes, not sure if this will - // also detect connections to a child-of-an-element... so just iterating through all plugs. Shouldn't - // be too many... + // Considered using numConnectedElements, but for arrays-of-compound attributes, not sure if + // this will also detect connections to a child-of-an-element... so just iterating through all + // plugs. Shouldn't be too many... const size_t numElements = arrayPlug.evaluateNumElements(); // Iterate over all elements... - for(size_t elemI = 0; elemI < numElements; ++elemI) - { - elemPlug = arrayPlug.elementByPhysicalIndex(elemI, &status); - - // Disconnect the element compound attribute - AL_MAYA_CHECK_ERROR(status, errorString); - AL_MAYA_CHECK_ERROR(disconnectPlug(elemPlug), errorString); - - // ...then disconnect any children - if(elemPlug.numConnectedChildren() > 0) - { - for(size_t childI = 0; childI < elemPlug.numChildren(); ++childI) - { - AL_MAYA_CHECK_ERROR(disconnectPlug(elemPlug.child(childI)), errorString); + for (size_t elemI = 0; elemI < numElements; ++elemI) { + elemPlug = arrayPlug.elementByPhysicalIndex(elemI, &status); + + // Disconnect the element compound attribute + AL_MAYA_CHECK_ERROR(status, errorString); + AL_MAYA_CHECK_ERROR(disconnectPlug(elemPlug), errorString); + + // ...then disconnect any children + if (elemPlug.numConnectedChildren() > 0) { + for (size_t childI = 0; childI < elemPlug.numChildren(); ++childI) { + AL_MAYA_CHECK_ERROR(disconnectPlug(elemPlug.child(childI)), errorString); + } } - } } return dgmod.doIt(); - } } +} // namespace namespace AL { namespace usdmaya { @@ -111,133 +107,122 @@ namespace nodes { //---------------------------------------------------------------------------------------------------------------------- bool LayerDatabase::addLayer(SdfLayerRefPtr layer, const std::string& identifier) { - auto insertLayerResult = m_layerToIds.emplace(std::piecewise_construct, - std::forward_as_tuple(layer), - std::forward_as_tuple()); - auto& idsForLayer = insertLayerResult.first->second; - - _addLayer(layer, layer->GetIdentifier(), idsForLayer); - if (identifier != layer->GetIdentifier() && !identifier.empty()) - { - _addLayer(layer, identifier, idsForLayer); - } - return insertLayerResult.second; + auto insertLayerResult = m_layerToIds.emplace( + std::piecewise_construct, std::forward_as_tuple(layer), std::forward_as_tuple()); + auto& idsForLayer = insertLayerResult.first->second; + + _addLayer(layer, layer->GetIdentifier(), idsForLayer); + if (identifier != layer->GetIdentifier() && !identifier.empty()) { + _addLayer(layer, identifier, idsForLayer); + } + return insertLayerResult.second; } //---------------------------------------------------------------------------------------------------------------------- bool LayerDatabase::removeLayer(SdfLayerRefPtr layer) { - auto foundLayerAndIds = m_layerToIds.find(layer); - if (foundLayerAndIds == m_layerToIds.end()) return false; + auto foundLayerAndIds = m_layerToIds.find(layer); + if (foundLayerAndIds == m_layerToIds.end()) + return false; - for (std::string& oldId : foundLayerAndIds->second) - { - auto oldIdPosition = m_idToLayer.find(oldId); + for (std::string& oldId : foundLayerAndIds->second) { + auto oldIdPosition = m_idToLayer.find(oldId); #ifdef DEBUG - assert (oldIdPosition != m_idToLayer.end()); + assert(oldIdPosition != m_idToLayer.end()); #else - if (oldIdPosition == m_idToLayer.end()) - { - MGlobal::displayError(MString("Error - layer '") + AL::maya::utils::convert(layer->GetIdentifier()) - + "' could be found indexed by layer, but not by identifier '" - + AL::maya::utils::convert(oldId) + "'"); - } - else + if (oldIdPosition == m_idToLayer.end()) { + MGlobal::displayError( + MString("Error - layer '") + AL::maya::utils::convert(layer->GetIdentifier()) + + "' could be found indexed by layer, but not by identifier '" + + AL::maya::utils::convert(oldId) + "'"); + } else #endif // DEBUG - { - m_idToLayer.erase(oldIdPosition); + { + m_idToLayer.erase(oldIdPosition); + } } - } - m_layerToIds.erase(foundLayerAndIds); - return true; + m_layerToIds.erase(foundLayerAndIds); + return true; } SdfLayerHandle LayerDatabase::findLayer(std::string identifier) const { - auto foundIdAndLayer = m_idToLayer.find(identifier); - if(foundIdAndLayer != m_idToLayer.end()) - { - // Non-dirty layers may be placed in the database "temporarily" - - // ie, current edit targets for proxyShape stages, that have not - // yet been edited. Filter those out. - if(foundIdAndLayer->second->IsDirty()) - { - return foundIdAndLayer->second; + auto foundIdAndLayer = m_idToLayer.find(identifier); + if (foundIdAndLayer != m_idToLayer.end()) { + // Non-dirty layers may be placed in the database "temporarily" - + // ie, current edit targets for proxyShape stages, that have not + // yet been edited. Filter those out. + if (foundIdAndLayer->second->IsDirty()) { + return foundIdAndLayer->second; + } } - } - return SdfLayerHandle(); + return SdfLayerHandle(); } - //---------------------------------------------------------------------------------------------------------------------- -void LayerDatabase::_addLayer(SdfLayerRefPtr layer, const std::string& identifier, +void LayerDatabase::_addLayer( + SdfLayerRefPtr layer, + const std::string& identifier, std::vector& idsForLayer) { - // Try to insert into m_idToLayer... - auto insertIdResult = m_idToLayer.emplace(identifier, layer); - if (!insertIdResult.second) - { - // We've seen this identifier before... - if (insertIdResult.first->second == layer) - { - // ...and it was referring to the same layer. Nothing to do! - return; - } + // Try to insert into m_idToLayer... + auto insertIdResult = m_idToLayer.emplace(identifier, layer); + if (!insertIdResult.second) { + // We've seen this identifier before... + if (insertIdResult.first->second == layer) { + // ...and it was referring to the same layer. Nothing to do! + return; + } - // If it was pointing to a DIFFERENT layer, we need to first remove - // this id from the set of ids for the OLD layer... - SdfLayerRefPtr oldLayer = insertIdResult.first->second; - auto oldLayerAndIds = m_layerToIds.find(oldLayer); + // If it was pointing to a DIFFERENT layer, we need to first remove + // this id from the set of ids for the OLD layer... + SdfLayerRefPtr oldLayer = insertIdResult.first->second; + auto oldLayerAndIds = m_layerToIds.find(oldLayer); #ifdef DEBUG - assert (oldLayerAndIds != m_layerToIds.end()); + assert(oldLayerAndIds != m_layerToIds.end()); #else - if (oldLayerAndIds == m_layerToIds.end()) - { - // The layer didn't exist in the opposite direction - this should - // never happen, but don't want to crash if it does - MGlobal::displayError(MString("Error - layer '") + AL::maya::utils::convert(identifier) - + "' could be found indexed by identifier, but not by layer"); - } - else + if (oldLayerAndIds == m_layerToIds.end()) { + // The layer didn't exist in the opposite direction - this should + // never happen, but don't want to crash if it does + MGlobal::displayError( + MString("Error - layer '") + AL::maya::utils::convert(identifier) + + "' could be found indexed by identifier, but not by layer"); + } else #endif // DEBUG - { - auto& oldLayerIds = oldLayerAndIds->second; - if (oldLayerIds.size() <= 1) - { - // This was the ONLY identifier for the layer - so delete - // the layer entirely! - m_layerToIds.erase(oldLayerAndIds); - } - else - { - auto idLocation = std::find(oldLayerIds.begin(), oldLayerIds.end(), - identifier); + { + auto& oldLayerIds = oldLayerAndIds->second; + if (oldLayerIds.size() <= 1) { + // This was the ONLY identifier for the layer - so delete + // the layer entirely! + m_layerToIds.erase(oldLayerAndIds); + } else { + auto idLocation = std::find(oldLayerIds.begin(), oldLayerIds.end(), identifier); #ifdef DEBUG - assert (idLocation != oldLayerIds.end()); + assert(idLocation != oldLayerIds.end()); #else - if(idLocation == oldLayerIds.end()) - { - MGlobal::displayError(MString("Error - layer '") + AL::maya::utils::convert(identifier) - + "' could be found indexed by identifier, but was not in layer's list of identifiers"); - } - else + if (idLocation == oldLayerIds.end()) { + MGlobal::displayError( + MString("Error - layer '") + AL::maya::utils::convert(identifier) + + "' could be found indexed by identifier, but was not in layer's list of " + "identifiers"); + } else #endif - { - oldLayerIds.erase(idLocation); + { + oldLayerIds.erase(idLocation); + } + } } - } - } - // Ok, we've cleaned up the OLD layer - now make the id point to our - // NEW layer - insertIdResult.first->second = layer; - } + // Ok, we've cleaned up the OLD layer - now make the id point to our + // NEW layer + insertIdResult.first->second = layer; + } - // Ok, we've now added the layer to m_idToLayer, and cleaned up - // any potential old entries from m_layerToIds. Now we just need - // to add the identifier to idsForLayer (which should be == m_layerToIds[layer]) - idsForLayer.push_back(identifier); + // Ok, we've now added the layer to m_idToLayer, and cleaned up + // any potential old entries from m_layerToIds. Now we just need + // to add the identifier to idsForLayer (which should be == m_layerToIds[layer]) + idsForLayer.push_back(identifier); } //---------------------------------------------------------------------------------------------------------------------- @@ -252,352 +237,339 @@ MObject LayerManager::m_anonymous = MObject::kNullObj; //---------------------------------------------------------------------------------------------------------------------- void* LayerManager::conditionalCreator() { - // If we were called from findOrCreate, we don't need to call findNode, we already did - MObject theManager = findNode(); - if (!theManager.isNull()) - { - MFnDependencyNode fn(theManager); - MGlobal::displayError(MString("cannot create a new '") + kTypeName + "' node, an unreferenced" - " one already exists: " + fn.name()); - return nullptr; - } - return creator(); + // If we were called from findOrCreate, we don't need to call findNode, we already did + MObject theManager = findNode(); + if (!theManager.isNull()) { + MFnDependencyNode fn(theManager); + MGlobal::displayError( + MString("cannot create a new '") + kTypeName + + "' node, an unreferenced" + " one already exists: " + + fn.name()); + return nullptr; + } + return creator(); } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerManager::initialise() { - TF_DEBUG(ALUSDMAYA_LAYERS).Msg("LayerManager::initialize\n"); - try - { - setNodeType(kTypeName); - addFrame("USD Layer Manager Node"); - - addFrame("Serialization infos"); - - // add attributes to store the serialization info - m_identifier = addStringAttr("identifier", "id", kCached | kReadable | kStorable | kHidden); - m_serialized = addStringAttr("serialized", "szd", kCached | kReadable | kStorable | kHidden); - m_anonymous = addBoolAttr("anonymous", "ann", false, kCached | kReadable | kStorable | kHidden); - m_layers = addCompoundAttr("layers", "lyr", - kCached | kReadable | kWritable | kStorable | kConnectable | kHidden | kArray | kUsesArrayDataBuilder, - {m_identifier, m_serialized, m_anonymous}); - } - catch(const MStatus& status) - { - return status; - } - generateAETemplate(); - return MS::kSuccess; + TF_DEBUG(ALUSDMAYA_LAYERS).Msg("LayerManager::initialize\n"); + try { + setNodeType(kTypeName); + addFrame("USD Layer Manager Node"); + + addFrame("Serialization infos"); + + // add attributes to store the serialization info + m_identifier = addStringAttr("identifier", "id", kCached | kReadable | kStorable | kHidden); + m_serialized + = addStringAttr("serialized", "szd", kCached | kReadable | kStorable | kHidden); + m_anonymous + = addBoolAttr("anonymous", "ann", false, kCached | kReadable | kStorable | kHidden); + m_layers = addCompoundAttr( + "layers", + "lyr", + kCached | kReadable | kWritable | kStorable | kConnectable | kHidden | kArray + | kUsesArrayDataBuilder, + { m_identifier, m_serialized, m_anonymous }); + } catch (const MStatus& status) { + return status; + } + generateAETemplate(); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MObject LayerManager::findNode() { - std::lock_guard lock(_findNodeMutex); - return _findNode(); + std::lock_guard lock(_findNodeMutex); + return _findNode(); } //---------------------------------------------------------------------------------------------------------------------- MObject LayerManager::_findNode() { - MFnDependencyNode fn; - MItDependencyNodes iter(MFn::kPluginDependNode); - for(; !iter.isDone(); iter.next()) - { - MObject mobj = iter.item(); - fn.setObject(mobj); - if(fn.typeId() == kTypeId && !fn.isFromReferencedFile()) - { - return mobj; + MFnDependencyNode fn; + MItDependencyNodes iter(MFn::kPluginDependNode); + for (; !iter.isDone(); iter.next()) { + MObject mobj = iter.item(); + fn.setObject(mobj); + if (fn.typeId() == kTypeId && !fn.isFromReferencedFile()) { + return mobj; + } } - } - return MObject::kNullObj; + return MObject::kNullObj; } - //---------------------------------------------------------------------------------------------------------------------- // TODO: make it take an optional MDGModifier MObject LayerManager::findOrCreateNode(MDGModifier* dgmod, bool* wasCreated) { - TF_DEBUG(ALUSDMAYA_LAYERS).Msg("LayerManager::findOrCreateNode\n"); - std::lock_guard lock(_findNodeMutex); - MObject theManager = _findNode(); - - if (!theManager.isNull()) - { - if (wasCreated) *wasCreated = false; - return theManager; - } - - if (wasCreated) *wasCreated = true; - - if (dgmod) - { - return dgmod->createNode(kTypeId); - } - else - { - MDGModifier modifier; - MObject node = modifier.createNode(kTypeId); - modifier.doIt(); - return node; - } + TF_DEBUG(ALUSDMAYA_LAYERS).Msg("LayerManager::findOrCreateNode\n"); + std::lock_guard lock(_findNodeMutex); + MObject theManager = _findNode(); + + if (!theManager.isNull()) { + if (wasCreated) + *wasCreated = false; + return theManager; + } + + if (wasCreated) + *wasCreated = true; + + if (dgmod) { + return dgmod->createNode(kTypeId); + } else { + MDGModifier modifier; + MObject node = modifier.createNode(kTypeId); + modifier.doIt(); + return node; + } } //---------------------------------------------------------------------------------------------------------------------- LayerManager* LayerManager::findManager() { - MObject manager = findNode(); - if(manager.isNull()) - { - return nullptr; - } - return static_cast(MFnDependencyNode(manager).userNode()); + MObject manager = findNode(); + if (manager.isNull()) { + return nullptr; + } + return static_cast(MFnDependencyNode(manager).userNode()); } //---------------------------------------------------------------------------------------------------------------------- LayerManager* LayerManager::findOrCreateManager(MDGModifier* dgmod, bool* wasCreated) { - return static_cast(MFnDependencyNode(findOrCreateNode(dgmod, - wasCreated)).userNode()); + return static_cast( + MFnDependencyNode(findOrCreateNode(dgmod, wasCreated)).userNode()); } //---------------------------------------------------------------------------------------------------------------------- bool LayerManager::addLayer(SdfLayerHandle layer, const std::string& identifier) { - SdfLayerRefPtr layerRef(layer); - if (!layerRef) - { - MGlobal::displayError("LayerManager::addLayer - given layer is no longer valid"); - return false; - } - boost::unique_lock lock(m_layersMutex); - return m_layerDatabase.addLayer(layerRef, identifier); + SdfLayerRefPtr layerRef(layer); + if (!layerRef) { + MGlobal::displayError("LayerManager::addLayer - given layer is no longer valid"); + return false; + } + boost::unique_lock lock(m_layersMutex); + return m_layerDatabase.addLayer(layerRef, identifier); } //---------------------------------------------------------------------------------------------------------------------- bool LayerManager::removeLayer(SdfLayerHandle layer) { - SdfLayerRefPtr layerRef(layer); - if (!layerRef) - { - MGlobal::displayError("LayerManager::removeLayer - given layer is no longer valid"); - return false; - } - boost::unique_lock lock(m_layersMutex); - return m_layerDatabase.removeLayer(layerRef); + SdfLayerRefPtr layerRef(layer); + if (!layerRef) { + MGlobal::displayError("LayerManager::removeLayer - given layer is no longer valid"); + return false; + } + boost::unique_lock lock(m_layersMutex); + return m_layerDatabase.removeLayer(layerRef); } //---------------------------------------------------------------------------------------------------------------------- SdfLayerHandle LayerManager::findLayer(std::string identifier) { - boost::shared_lock_guard lock(m_layersMutex); - return m_layerDatabase.findLayer(identifier); + boost::shared_lock_guard lock(m_layersMutex); + return m_layerDatabase.findLayer(identifier); } //---------------------------------------------------------------------------------------------------------------------- void LayerManager::getLayerIdentifiers(MStringArray& outputNames) { - outputNames.clear(); - for(const auto& layerAndIds : m_layerDatabase) - { - outputNames.append(layerAndIds.first->GetIdentifier().c_str()); - } + outputNames.clear(); + for (const auto& layerAndIds : m_layerDatabase) { + outputNames.append(layerAndIds.first->GetIdentifier().c_str()); + } } //---------------------------------------------------------------------------------------------------------------------- MStatus LayerManager::populateSerialisationAttributes() { - TF_DEBUG(ALUSDMAYA_LAYERS).Msg("LayerManager::populateSerialisationAttributes\n"); - const char* errorString = "LayerManager::populateSerialisationAttributes"; + TF_DEBUG(ALUSDMAYA_LAYERS).Msg("LayerManager::populateSerialisationAttributes\n"); + const char* errorString = "LayerManager::populateSerialisationAttributes"; - MStatus status; - MPlug arrayPlug = layersPlug(); + MStatus status; + MPlug arrayPlug = layersPlug(); - // First, disconnect any connected attributes - AL_MAYA_CHECK_ERROR(disconnectCompoundArrayPlug(arrayPlug), errorString); + // First, disconnect any connected attributes + AL_MAYA_CHECK_ERROR(disconnectCompoundArrayPlug(arrayPlug), errorString); - // Then fill out the array attribute - MDataBlock dataBlock = forceCache(); + // Then fill out the array attribute + MDataBlock dataBlock = forceCache(); - MArrayDataHandle layersArrayHandle = dataBlock.outputArrayValue(m_layers, &status); - AL_MAYA_CHECK_ERROR(status, errorString); - { - boost::shared_lock_guard lock(m_layersMutex); - MArrayDataBuilder builder(&dataBlock, layers(), m_layerDatabase.max_size(), &status); + MArrayDataHandle layersArrayHandle = dataBlock.outputArrayValue(m_layers, &status); AL_MAYA_CHECK_ERROR(status, errorString); - std::string temp; - for (const auto& layerAndIds : m_layerDatabase) { - auto& layer = layerAndIds.first; - MDataHandle layersElemHandle = builder.addLast(&status); - AL_MAYA_CHECK_ERROR(status, errorString); - MDataHandle idHandle = layersElemHandle.child(m_identifier); - idHandle.setString(AL::maya::utils::convert(layer->GetIdentifier())); - MDataHandle serializedHandle = layersElemHandle.child(m_serialized); - layer->ExportToString(&temp); - serializedHandle.setString(AL::maya::utils::convert(temp)); - MDataHandle anonHandle = layersElemHandle.child(m_anonymous); - anonHandle.setBool(layer->IsAnonymous()); + boost::shared_lock_guard lock(m_layersMutex); + MArrayDataBuilder builder(&dataBlock, layers(), m_layerDatabase.max_size(), &status); + AL_MAYA_CHECK_ERROR(status, errorString); + std::string temp; + for (const auto& layerAndIds : m_layerDatabase) { + auto& layer = layerAndIds.first; + MDataHandle layersElemHandle = builder.addLast(&status); + AL_MAYA_CHECK_ERROR(status, errorString); + MDataHandle idHandle = layersElemHandle.child(m_identifier); + idHandle.setString(AL::maya::utils::convert(layer->GetIdentifier())); + MDataHandle serializedHandle = layersElemHandle.child(m_serialized); + layer->ExportToString(&temp); + serializedHandle.setString(AL::maya::utils::convert(temp)); + MDataHandle anonHandle = layersElemHandle.child(m_anonymous); + anonHandle.setBool(layer->IsAnonymous()); + } + AL_MAYA_CHECK_ERROR(layersArrayHandle.set(builder), errorString); } - AL_MAYA_CHECK_ERROR(layersArrayHandle.set(builder), errorString); - } - AL_MAYA_CHECK_ERROR(layersArrayHandle.setAllClean(), errorString); - AL_MAYA_CHECK_ERROR(dataBlock.setClean(layers()), errorString); - return status; + AL_MAYA_CHECK_ERROR(layersArrayHandle.setAllClean(), errorString); + AL_MAYA_CHECK_ERROR(dataBlock.setClean(layers()), errorString); + return status; } MStatus LayerManager::clearSerialisationAttributes() { - TF_DEBUG(ALUSDMAYA_LAYERS).Msg("LayerManager::clearSerialisationAttributes\n"); - const char* errorString = "LayerManager::clearSerialisationAttributes"; - - MStatus status; - MPlug arrayPlug = layersPlug(); - - // First, disconnect any connected attributes - AL_MAYA_CHECK_ERROR(disconnectCompoundArrayPlug(arrayPlug), errorString); - - // Then wipe the array attribute - MDataBlock dataBlock = forceCache(); - MArrayDataHandle layersArrayHandle = dataBlock.outputArrayValue(m_layers, &status); - AL_MAYA_CHECK_ERROR(status, errorString); - - MArrayDataBuilder builder(&dataBlock, layers(), 0, &status); - AL_MAYA_CHECK_ERROR(status, errorString); - AL_MAYA_CHECK_ERROR(layersArrayHandle.set(builder), errorString); - AL_MAYA_CHECK_ERROR(layersArrayHandle.setAllClean(), errorString); - AL_MAYA_CHECK_ERROR(dataBlock.setClean(layers()), errorString); - return status; + TF_DEBUG(ALUSDMAYA_LAYERS).Msg("LayerManager::clearSerialisationAttributes\n"); + const char* errorString = "LayerManager::clearSerialisationAttributes"; + + MStatus status; + MPlug arrayPlug = layersPlug(); + + // First, disconnect any connected attributes + AL_MAYA_CHECK_ERROR(disconnectCompoundArrayPlug(arrayPlug), errorString); + + // Then wipe the array attribute + MDataBlock dataBlock = forceCache(); + MArrayDataHandle layersArrayHandle = dataBlock.outputArrayValue(m_layers, &status); + AL_MAYA_CHECK_ERROR(status, errorString); + + MArrayDataBuilder builder(&dataBlock, layers(), 0, &status); + AL_MAYA_CHECK_ERROR(status, errorString); + AL_MAYA_CHECK_ERROR(layersArrayHandle.set(builder), errorString); + AL_MAYA_CHECK_ERROR(layersArrayHandle.setAllClean(), errorString); + AL_MAYA_CHECK_ERROR(dataBlock.setClean(layers()), errorString); + return status; } void LayerManager::loadAllLayers() { - TF_DEBUG(ALUSDMAYA_LAYERS).Msg("LayerManager::loadAllLayers\n"); - const char* errorString = "LayerManager::loadAllLayers"; - const char* identifierTempSuffix = "_tmp"; - MStatus status; - MPlug allLayersPlug = layersPlug(); - MPlug singleLayerPlug; - MPlug idPlug; - MPlug anonymousPlug; - MPlug serializedPlug; - std::string identifierVal; - std::string serializedVal; - SdfLayerRefPtr layer; - // We DON'T want to use evaluate num elements, because we don't want to trigger - // a compute - we want the value(s) as read from the file! - const unsigned int numElements = allLayersPlug.numElements(); - for(unsigned int i=0; i < numElements; ++i) - { - singleLayerPlug = allLayersPlug.elementByPhysicalIndex(i, &status); - AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); - idPlug = singleLayerPlug.child(m_identifier, &status); - AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); - anonymousPlug = singleLayerPlug.child(m_anonymous, &status); - AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); - serializedPlug = singleLayerPlug.child(m_serialized, &status); - AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); - - identifierVal = idPlug.asString(MDGContext::fsNormal, &status).asChar(); - AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); - if(identifierVal.empty()) - { - MGlobal::displayError(MString("Error - plug ") + idPlug.partialName(true) + "had empty identifier"); - continue; - } - serializedVal = serializedPlug.asString(MDGContext::fsNormal, &status).asChar(); - AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); - if(serializedVal.empty()) - { - MGlobal::displayError(MString("Error - plug ") + serializedPlug.partialName(true) + "had empty serialization"); - continue; - } - - bool isAnon = anonymousPlug.asBool(MDGContext::fsNormal, &status); - AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); - if(isAnon) - { - // Note that the new identifier will not match the old identifier - only the "tag" will be retained - layer = SdfLayer::CreateAnonymous(SdfLayer::GetDisplayNameFromIdentifier(identifierVal)); - } - else - { - SdfLayerHandle layerHandle = SdfLayer::Find(identifierVal); - if (layerHandle) - { - layer = layerHandle; - } - else - { - // TODO: currently, there is a small window here, after the find, and before the New, where - // another process might sneak in and create a layer with the same identifier, which could cause - // an error. This seems unlikely, but we have a discussion with Pixar to find a way to avoid this. - - SdfFileFormatConstPtr fileFormat; - if(TfStringStartsWith(serializedVal, "#usda ")) - { - // In order to make the layer reloadable by SdfLayer::Reload(), we need the - // correct file format from identifier. - if(TfStringEndsWith(identifierVal, ".usd")) - { - fileFormat = SdfFileFormat::FindById(UsdUsdFileFormatTokens->Id); - } - else if(TfStringEndsWith(identifierVal, ".usdc")) - { - fileFormat = SdfFileFormat::FindById(UsdUsdcFileFormatTokens->Id); - } - else - { - fileFormat = SdfFileFormat::FindById(UsdUsdaFileFormatTokens->Id); - } + TF_DEBUG(ALUSDMAYA_LAYERS).Msg("LayerManager::loadAllLayers\n"); + const char* errorString = "LayerManager::loadAllLayers"; + const char* identifierTempSuffix = "_tmp"; + MStatus status; + MPlug allLayersPlug = layersPlug(); + MPlug singleLayerPlug; + MPlug idPlug; + MPlug anonymousPlug; + MPlug serializedPlug; + std::string identifierVal; + std::string serializedVal; + SdfLayerRefPtr layer; + // We DON'T want to use evaluate num elements, because we don't want to trigger + // a compute - we want the value(s) as read from the file! + const unsigned int numElements = allLayersPlug.numElements(); + for (unsigned int i = 0; i < numElements; ++i) { + singleLayerPlug = allLayersPlug.elementByPhysicalIndex(i, &status); + AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); + idPlug = singleLayerPlug.child(m_identifier, &status); + AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); + anonymousPlug = singleLayerPlug.child(m_anonymous, &status); + AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); + serializedPlug = singleLayerPlug.child(m_serialized, &status); + AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); + + identifierVal = idPlug.asString(MDGContext::fsNormal, &status).asChar(); + AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); + if (identifierVal.empty()) { + MGlobal::displayError( + MString("Error - plug ") + idPlug.partialName(true) + "had empty identifier"); + continue; } - else - { - fileFormat = SdfFileFormat::FindById(SdfTextFileFormatTokens->Id); + serializedVal = serializedPlug.asString(MDGContext::fsNormal, &status).asChar(); + AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); + if (serializedVal.empty()) { + MGlobal::displayError( + MString("Error - plug ") + serializedPlug.partialName(true) + + "had empty serialization"); + continue; } - // In order to make the layer reloadable by SdfLayer::Reload(), we hack the identifier - // with temp one on creation and call layer->SetIdentifier() again to set the timestamp: - layer = SdfLayer::New(fileFormat, identifierVal+identifierTempSuffix); - if (!layer) - { - MGlobal::displayError(MString("Error - failed to create new layer for identifier '") + identifierVal.c_str() - + "' for plug " + idPlug.partialName(true)); - continue; + bool isAnon = anonymousPlug.asBool(MDGContext::fsNormal, &status); + AL_MAYA_CHECK_ERROR_CONTINUE(status, errorString); + if (isAnon) { + // Note that the new identifier will not match the old identifier - only the "tag" will + // be retained + layer + = SdfLayer::CreateAnonymous(SdfLayer::GetDisplayNameFromIdentifier(identifierVal)); + } else { + SdfLayerHandle layerHandle = SdfLayer::Find(identifierVal); + if (layerHandle) { + layer = layerHandle; + } else { + // TODO: currently, there is a small window here, after the find, and before the + // New, where another process might sneak in and create a layer with the same + // identifier, which could cause an error. This seems unlikely, but we have a + // discussion with Pixar to find a way to avoid this. + + SdfFileFormatConstPtr fileFormat; + if (TfStringStartsWith(serializedVal, "#usda ")) { + // In order to make the layer reloadable by SdfLayer::Reload(), we need the + // correct file format from identifier. + if (TfStringEndsWith(identifierVal, ".usd")) { + fileFormat = SdfFileFormat::FindById(UsdUsdFileFormatTokens->Id); + } else if (TfStringEndsWith(identifierVal, ".usdc")) { + fileFormat = SdfFileFormat::FindById(UsdUsdcFileFormatTokens->Id); + } else { + fileFormat = SdfFileFormat::FindById(UsdUsdaFileFormatTokens->Id); + } + } else { + fileFormat = SdfFileFormat::FindById(SdfTextFileFormatTokens->Id); + } + + // In order to make the layer reloadable by SdfLayer::Reload(), we hack the + // identifier with temp one on creation and call layer->SetIdentifier() again to set + // the timestamp: + layer = SdfLayer::New(fileFormat, identifierVal + identifierTempSuffix); + if (!layer) { + MGlobal::displayError( + MString("Error - failed to create new layer for identifier '") + + identifierVal.c_str() + "' for plug " + idPlug.partialName(true)); + continue; + } + layer->SetIdentifier(identifierVal); // Make it reloadable by SdfLayer::Reload(true) + layer->Clear(); // Mark it dirty to make it reloadable by SdfLayer::Reload() without + // force=true + } } - layer->SetIdentifier(identifierVal); // Make it reloadable by SdfLayer::Reload(true) - layer->Clear(); // Mark it dirty to make it reloadable by SdfLayer::Reload() without force=true - } - } - TF_DEBUG(ALUSDMAYA_LAYERS).Msg( - "################################################\n" - "Importing layer from serialised data:\n" - "old identifier: %s\n" - "new identifier: %s\n" - "format: %s\n", - identifierVal.c_str(), - layer->GetIdentifier().c_str(), - layer->GetFileFormat()->GetFormatId().GetText() - ); - - if(!layer->ImportFromString(serializedVal)) - { - TF_DEBUG(ALUSDMAYA_LAYERS).Msg("Import result: failed!\n" - "################################################\n"); - MGlobal::displayError(MString("Failed to import serialized layer: ") + serializedVal.c_str()); - continue; + TF_DEBUG(ALUSDMAYA_LAYERS) + .Msg( + "################################################\n" + "Importing layer from serialised data:\n" + "old identifier: %s\n" + "new identifier: %s\n" + "format: %s\n", + identifierVal.c_str(), + layer->GetIdentifier().c_str(), + layer->GetFileFormat()->GetFormatId().GetText()); + + if (!layer->ImportFromString(serializedVal)) { + TF_DEBUG(ALUSDMAYA_LAYERS) + .Msg("Import result: failed!\n" + "################################################\n"); + MGlobal::displayError( + MString("Failed to import serialized layer: ") + serializedVal.c_str()); + continue; + } + TF_DEBUG(ALUSDMAYA_LAYERS) + .Msg("Import result: success!\n" + "################################################\n"); + addLayer(layer, identifierVal); } - TF_DEBUG(ALUSDMAYA_LAYERS).Msg("Import result: success!\n" - "################################################\n"); - addLayer(layer, identifierVal); - } } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/LayerManager.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/LayerManager.h index 9476ef9ed5..77c2a5c5a1 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/LayerManager.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/LayerManager.h @@ -15,15 +15,14 @@ // #pragma once -#include "AL/usdmaya/Api.h" - #include "AL/maya/utils/MayaHelperMacros.h" #include "AL/maya/utils/NodeHelper.h" - -#include +#include "AL/usdmaya/Api.h" #include +#include + #include #include @@ -32,12 +31,12 @@ // boost includes. Disabling those warnings for the specific includes // for now instead of disabling the strict settings at a higher level. #ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable : 4002 ) +#pragma warning(push) +#pragma warning(disable : 4002) #endif - #include +#include #ifdef _MSC_VER -#pragma warning( pop ) +#pragma warning(pop) #endif PXR_NAMESPACE_USING_DIRECTIVE @@ -53,359 +52,377 @@ class ProxyShape; /// Implemented as a template to define const / non-const iterator at same time /// \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- -template -class DirtyOnlyIterator +template class DirtyOnlyIterator // : public std::iterator { public: - typedef typename WrappedIterator::value_type value_type; - - /// \brief ctor - /// \param it the start of the iteration range - /// \param end the end of the iteration range - DirtyOnlyIterator(WrappedIterator it, WrappedIterator end): - m_iter(it), - m_end(end) - { - SetToNextDirty(); - } - - /// \brief copy ctor - /// \param other the iterator to copy - DirtyOnlyIterator(const DirtyOnlyIterator& other): - m_iter(other.m_iter), - m_end(other.m_end) - { - SetToNextDirty(); - } - - /// \brief pre-increment operator - /// \return a reference to this - DirtyOnlyIterator& operator++() - { - ++m_iter; - SetToNextDirty(); - return *this; - } - - /// \brief post-increment operator - /// \return a copy of the original iterator value - DirtyOnlyIterator operator++(int) - { - WrappedIterator tmp(*this); - operator++(); - return tmp; - } - - /// \brief equivalence operator - /// \param rhs the iterator to compare against - /// \return true if equivalent - bool operator == (const DirtyOnlyIterator& rhs) const - { - // You could argue we should check m_end too, - // but all we really care about is whether we're pointed - // at the same place, and it's faster... - return m_iter == rhs.m_iter; - } - - /// \brief non equivalence operator - /// \param rhs the iterator to compare against - /// \return false if equivalent, true otherwise - bool operator != (const DirtyOnlyIterator& rhs) const - { - return m_iter != rhs.m_iter; - } - - /// \brief dereference operator - value_type& operator * () - { return *m_iter; } + typedef typename WrappedIterator::value_type value_type; + + /// \brief ctor + /// \param it the start of the iteration range + /// \param end the end of the iteration range + DirtyOnlyIterator(WrappedIterator it, WrappedIterator end) + : m_iter(it) + , m_end(end) + { + SetToNextDirty(); + } + + /// \brief copy ctor + /// \param other the iterator to copy + DirtyOnlyIterator(const DirtyOnlyIterator& other) + : m_iter(other.m_iter) + , m_end(other.m_end) + { + SetToNextDirty(); + } + + /// \brief pre-increment operator + /// \return a reference to this + DirtyOnlyIterator& operator++() + { + ++m_iter; + SetToNextDirty(); + return *this; + } + + /// \brief post-increment operator + /// \return a copy of the original iterator value + DirtyOnlyIterator operator++(int) + { + WrappedIterator tmp(*this); + operator++(); + return tmp; + } + + /// \brief equivalence operator + /// \param rhs the iterator to compare against + /// \return true if equivalent + bool operator==(const DirtyOnlyIterator& rhs) const + { + // You could argue we should check m_end too, + // but all we really care about is whether we're pointed + // at the same place, and it's faster... + return m_iter == rhs.m_iter; + } + + /// \brief non equivalence operator + /// \param rhs the iterator to compare against + /// \return false if equivalent, true otherwise + bool operator!=(const DirtyOnlyIterator& rhs) const { return m_iter != rhs.m_iter; } + + /// \brief dereference operator + value_type& operator*() { return *m_iter; } private: - void SetToNextDirty() - { - while (m_iter != m_end && !m_iter->first->IsDirty()) + void SetToNextDirty() { - ++m_iter; + while (m_iter != m_end && !m_iter->first->IsDirty()) { + ++m_iter; + } } - } - WrappedIterator m_iter; - WrappedIterator m_end; + WrappedIterator m_iter; + WrappedIterator m_end; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief Stores layers, in a way that they may be looked up by the layer ref ptr, or by identifier +/// \brief Stores layers, in a way that they may be looked up by the layer ref ptr, or by +/// identifier /// Also, unlike boost::multi_index, we can have multiple identifiers per layer -/// You can add non-dirty layers to the database, but the query operations will "hide" them - -/// ie, iteration will skip by them, and findLayer will return an invalid ptr if it's not dirty -/// We allow adding non-dirty items because if we want to guarantee we always have all the latest -/// items, we need to deal with the situation where the current edit target starts out not -/// dirty... and it's easiest to just add it then filter it if it's not dirty +/// You can add non-dirty layers to the database, but the query operations will "hide" them +/// - ie, iteration will skip by them, and findLayer will return an invalid ptr if it's not +/// dirty We allow adding non-dirty items because if we want to guarantee we always have all +/// the latest items, we need to deal with the situation where the current edit target +/// starts out not dirty... and it's easiest to just add it then filter it if it's not dirty /// \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- class LayerDatabase { public: - typedef std::map> LayerToIdsMap; - typedef std::map IdToLayerMap; - - /// \brief Add the given layer to the set of layers in this LayerDatabase, if not already present, - /// and optionally add an extra identifier as a key to it - /// \param layer What layer to add to this database - /// \param identifier Extra identifier to add as a key to this layer; note that the "canonical" identifier, - /// as returned by layer.GetIdentifier(), is ALWAYS added as an identifier key for this layer so this - /// is intended as a way to provide a second identifier for the same layer (or third or more, if you - /// call it repeatedly). This is useful both because multiple identifiers may resolve to the same - /// underlying layer (especially when considering asset resolution), and for serializing and deserializing - /// anonymous layers, the "canonical" identifier will change every time it is serialized and deserialized - /// (and it can be necessary to refer to the layer both by it's "old" and "new" ids). If this is - /// an empty string, it is ignored. - /// \return bool which is true if the layer was actually added to the set of layers managed by this node - /// (ie, if it wasn't already managed) - bool addLayer(SdfLayerRefPtr layer, const std::string& identifier = std::string()); - - /// \brief Remove the given layer to the list of layers managed by this node, if present. - /// \return bool which is true if the layer was actually removed from the set of layers managed by this node - /// (ie, if was previously managed) - bool removeLayer(SdfLayerRefPtr layer); - - /// \brief Find the layer in the set of layers managed by this node, by identifier - /// \param identifier the identifier the full identifier of the layer to locate - /// \return The found layer handle in the layer list managed by this node (invalid if not found or not dirty) - SdfLayerHandle findLayer(std::string identifier) const; - - /// Because we may have an unknown number of non-dirty member layers which we're treating - /// as not-existing, we can't get a size without iterating over all the layers; we can, - /// however, do an empty/non-empty boolean check by seeing if begin() == end(); in the - /// worst case, when the LayerDatabase consists of nothing but non-dirty layers, begin() - /// will will still end up iterating through all the layers attempting to find a - /// non-dirty layer to start at, but the average case should be pretty fast - /// - /// We use the safe-bool idiom to avoid nasty automatic conversions, etc + typedef std::map> LayerToIdsMap; + typedef std::map IdToLayerMap; + + /// \brief Add the given layer to the set of layers in this LayerDatabase, if not already + /// present, + /// and optionally add an extra identifier as a key to it + /// \param layer What layer to add to this database + /// \param identifier Extra identifier to add as a key to this layer; note that the "canonical" + /// identifier, + /// as returned by layer.GetIdentifier(), is ALWAYS added as an identifier key for this + /// layer so this is intended as a way to provide a second identifier for the same layer + /// (or third or more, if you call it repeatedly). This is useful both because multiple + /// identifiers may resolve to the same underlying layer (especially when considering + /// asset resolution), and for serializing and deserializing anonymous layers, the + /// "canonical" identifier will change every time it is serialized and deserialized (and + /// it can be necessary to refer to the layer both by it's "old" and "new" ids). If this + /// is an empty string, it is ignored. + /// \return bool which is true if the layer was actually added to the set of layers managed by + /// this node + /// (ie, if it wasn't already managed) + bool addLayer(SdfLayerRefPtr layer, const std::string& identifier = std::string()); + + /// \brief Remove the given layer to the list of layers managed by this node, if present. + /// \return bool which is true if the layer was actually removed from the set of layers managed + /// by this node + /// (ie, if was previously managed) + bool removeLayer(SdfLayerRefPtr layer); + + /// \brief Find the layer in the set of layers managed by this node, by identifier + /// \param identifier the identifier the full identifier of the layer to locate + /// \return The found layer handle in the layer list managed by this node (invalid if not found + /// or not dirty) + SdfLayerHandle findLayer(std::string identifier) const; + + /// Because we may have an unknown number of non-dirty member layers which we're treating + /// as not-existing, we can't get a size without iterating over all the layers; we can, + /// however, do an empty/non-empty boolean check by seeing if begin() == end(); in the + /// worst case, when the LayerDatabase consists of nothing but non-dirty layers, begin() + /// will will still end up iterating through all the layers attempting to find a + /// non-dirty layer to start at, but the average case should be pretty fast + /// + /// We use the safe-bool idiom to avoid nasty automatic conversions, etc private: - typedef const LayerToIdsMap LayerDatabase::*_UnspecifiedBoolType; + typedef const LayerToIdsMap LayerDatabase::*_UnspecifiedBoolType; + public: - operator _UnspecifiedBoolType() const - { return begin() == end() ? &LayerDatabase::m_layerToIds : nullptr; } - - /// \brief Upper bound for the number of non-dirty layers in this object - /// This is the count of all tracked layers, dirty-and-non-dirty; - /// If it is zero, it can be guaranteed that there are no dirty - /// layers, but if it is non-zero, we cannot guarantee that there - /// are any non-dirty layers. Use boolean conversion above to test - /// that. - size_t max_size() const - { return m_layerToIds.size(); } - - // Iterator interface - skips past non-dirty items - typedef DirtyOnlyIterator iterator; - typedef DirtyOnlyIterator const_iterator; - - /// \brief returns start of layer range - iterator begin() - { return iterator(m_layerToIds.begin(), m_layerToIds.end()); } - - /// \brief returns start of layer range - const_iterator begin() const - { return const_iterator(m_layerToIds.cbegin(), m_layerToIds.cend()); } - - /// \brief returns start of layer range - const_iterator cbegin() const - { return const_iterator(m_layerToIds.cbegin(), m_layerToIds.cend()); } - - /// \brief returns end of layer range - iterator end() - { return iterator(m_layerToIds.end(), m_layerToIds.end()); } - - /// \brief returns end of layer range - const_iterator end() const - { return const_iterator(m_layerToIds.cend(), m_layerToIds.cend()); } - - /// \brief returns end of layer range - const_iterator cend() const - { return const_iterator(m_layerToIds.cend(), m_layerToIds.cend()); } + operator _UnspecifiedBoolType() const + { + return begin() == end() ? &LayerDatabase::m_layerToIds : nullptr; + } + + /// \brief Upper bound for the number of non-dirty layers in this object + /// This is the count of all tracked layers, dirty-and-non-dirty; + /// If it is zero, it can be guaranteed that there are no dirty + /// layers, but if it is non-zero, we cannot guarantee that there + /// are any non-dirty layers. Use boolean conversion above to test + /// that. + size_t max_size() const { return m_layerToIds.size(); } + + // Iterator interface - skips past non-dirty items + typedef DirtyOnlyIterator iterator; + typedef DirtyOnlyIterator const_iterator; + + /// \brief returns start of layer range + iterator begin() { return iterator(m_layerToIds.begin(), m_layerToIds.end()); } + + /// \brief returns start of layer range + const_iterator begin() const + { + return const_iterator(m_layerToIds.cbegin(), m_layerToIds.cend()); + } + + /// \brief returns start of layer range + const_iterator cbegin() const + { + return const_iterator(m_layerToIds.cbegin(), m_layerToIds.cend()); + } + + /// \brief returns end of layer range + iterator end() { return iterator(m_layerToIds.end(), m_layerToIds.end()); } + + /// \brief returns end of layer range + const_iterator end() const { return const_iterator(m_layerToIds.cend(), m_layerToIds.cend()); } + + /// \brief returns end of layer range + const_iterator cend() const { return const_iterator(m_layerToIds.cend(), m_layerToIds.cend()); } private: - void _addLayer(SdfLayerRefPtr layer, const std::string& identifier, - std::vector& idsForLayer); + void _addLayer( + SdfLayerRefPtr layer, + const std::string& identifier, + std::vector& idsForLayer); - LayerToIdsMap m_layerToIds; - IdToLayerMap m_idToLayer; + LayerToIdsMap m_layerToIds; + IdToLayerMap m_idToLayer; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief The layer manager node handles serialization and deserialization of all layers used by all ProxyShapes -/// It may temporarily contain non-dirty layers, but those will be filtered out by query operations. +/// \brief The layer manager node handles serialization and deserialization of all layers used by +/// all ProxyShapes +/// It may temporarily contain non-dirty layers, but those will be filtered out by query +/// operations. /// \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- class LayerManager - : public MPxNode, - public AL::maya::utils::NodeHelper + : public MPxNode + , public AL::maya::utils::NodeHelper { public: + /// \brief ctor + inline LayerManager() + : MPxNode() + , NodeHelper() + { + } - /// \brief ctor - inline LayerManager() - : MPxNode(), NodeHelper() {} - - /// \brief Find the already-existing non-referenced LayerManager node in the scene, or return a null MObject - /// \return the found LayerManager node, or a null MObject - AL_USDMAYA_PUBLIC - static MObject findNode(); - - /// \brief Either find the already-existing non-referenced LayerManager node in the scene, or make one - /// \param dgmod An optional dgmodifier to create the node, if necessary. Note that if one is passed in, - /// createNode might be called on it, but doIt never will be, so the layer manager node - /// may not be added to the scene graph yet - /// \param wasCreated If given, whether a new layer manager had to be created is stored here. - /// \return the found-or-created LayerManager node - AL_USDMAYA_PUBLIC - static MObject findOrCreateNode(MDGModifier* dgmod = nullptr, bool* wasCreated = nullptr); - - /// \brief Find the already-existing non-referenced LayerManager node in the scene, or return a nullptr - /// \return the found LayerManager, or a nullptr - AL_USDMAYA_PUBLIC - static LayerManager* findManager(); - - /// \brief Either find the already-existing non-referenced LayerManager in the scene, or make one - /// \param dgmod An optional dgmodifier to create the node, if necessary. Note that if one is passed in, - /// createNode might be called on it, but doIt never will be, so the layer manager node - /// may not be added to the scene graph yet - /// \param wasCreated If given, whether a new layer manager had to be created is stored here. - /// \return the found-or-created LayerManager - AL_USDMAYA_PUBLIC - static LayerManager* findOrCreateManager(MDGModifier* dgmod = nullptr, bool* wasCreated = nullptr); - - //-------------------------------------------------------------------------------------------------------------------- - /// Methods to handle the saving and restoring of layer data - //-------------------------------------------------------------------------------------------------------------------- - - /// \brief Add the given layer to the list of layers managed by this node, if not already present. - /// \param layer What layer to add to this LayerManager - /// \param identifier Extra identifier to add as a key to this layer; note that the "canonical" identifier, - /// as returned by layer.GetIdentifier(), is ALWAYS added as an identifier key for this layer so this - /// is intended as a way to provide a second identifier for the same layer (or third or more, if you - /// call it repeatedly). This is useful both because multiple identifiers may resolve to the same - /// underlying layer (especially when considering asset resolution), and for serializing and deserializing - /// anonymous layers, the "canonical" identifier will change every time it is serialized and deserialized - /// (and it can be necessary to refer to the layer both by it's "old" and "new" ids). If this is - /// an empty string, it is ignored. - /// \return bool which is true if the layer was actually added to the list of layers managed by this node - /// (ie, if it wasn't already managed, and the given layer handle was valid) - AL_USDMAYA_PUBLIC - bool addLayer(SdfLayerHandle layer, const std::string& identifier = std::string()); - - /// \brief Remove the given layer to the list of layers managed by this node, if present. - /// \return bool which is true if the layer was actually removed from the list of layers managed by this node - /// (ie, if it was previously managed, and the given layer handle was valid) - AL_USDMAYA_PUBLIC - bool removeLayer(SdfLayerHandle layer); - - /// \brief Find the layer in the list of layers managed by this node, by identifier - /// \return The found layer handle in the layer list managed by this node (invalid if not found) - AL_USDMAYA_PUBLIC - SdfLayerHandle findLayer(std::string identifier); - - /// \brief Store a list of the managed layers' identifiers in the given MStringArray - /// \param outputNames The array to hold the identifier names; will be cleared before being filled. - /// No guarantees are made about the order in which the layer identifiers will be returned. - AL_USDMAYA_PUBLIC - void getLayerIdentifiers(MStringArray& outputNames); - - /// \brief Ensures that the layers attribute will be filled out with serialized versions of all tracked layers. - AL_USDMAYA_PUBLIC - MStatus populateSerialisationAttributes(); - - /// \brief Clears the layers attribute. - AL_USDMAYA_PUBLIC - MStatus clearSerialisationAttributes(); - - /// \brief For every serialized layer stored in attributes, loads them as sdf layers - AL_USDMAYA_PUBLIC - void loadAllLayers(); - - //-------------------------------------------------------------------------------------------------------------------- - /// Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- - AL_MAYA_DECLARE_NODE(); - - /// \brief Creates the node, but only if there is not a non-referenced one in the scene already. - AL_USDMAYA_PUBLIC - static void* conditionalCreator(); - - //-------------------------------------------------------------------------------------------------------------------- - /// Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- - - // attributes to store the serialised layers (used for file IO only) - - // Note that the layers attribute should ONLY used during serialization, as this is the ONLY - // times at which these attributes are guaranteed to "line up" to the internal layer register - // (m_layerList). Ie, immediately before save (due to the pre-save callback), the attributes will - // be written from m_layerList; and immediate after open (due to the post-open callback), m_layerList - // will be initialized from the attributes. At all other times, the attributes will be OUT OF SYNC - // (and, in fact, are intentionally set to be "empty", so there's no confusion / someone doesn't - // try to use "out of date" information) - AL_DECL_ATTRIBUTE(layers); - // Not using AL_DECL_ATTRIBUTE for these, because we never want a generic, ie, identifierPlug() - - // they only make sense for a particular index of the parent array-attribute... and it taking up - // the "identifierPlug" name is confusing - AL_DECL_MULTI_CHILD_ATTRIBUTE(identifier); - AL_DECL_MULTI_CHILD_ATTRIBUTE(serialized); - AL_DECL_MULTI_CHILD_ATTRIBUTE(anonymous); + /// \brief Find the already-existing non-referenced LayerManager node in the scene, or return a + /// null MObject \return the found LayerManager node, or a null MObject + AL_USDMAYA_PUBLIC + static MObject findNode(); + + /// \brief Either find the already-existing non-referenced LayerManager node in the scene, or + /// make one \param dgmod An optional dgmodifier to create the node, if necessary. Note that if + /// one is passed in, + /// createNode might be called on it, but doIt never will be, so the layer manager + /// node may not be added to the scene graph yet + /// \param wasCreated If given, whether a new layer manager had to be created is stored here. + /// \return the found-or-created LayerManager node + AL_USDMAYA_PUBLIC + static MObject findOrCreateNode(MDGModifier* dgmod = nullptr, bool* wasCreated = nullptr); + + /// \brief Find the already-existing non-referenced LayerManager node in the scene, or return a + /// nullptr \return the found LayerManager, or a nullptr + AL_USDMAYA_PUBLIC + static LayerManager* findManager(); + + /// \brief Either find the already-existing non-referenced LayerManager in the scene, or make + /// one \param dgmod An optional dgmodifier to create the node, if necessary. Note that if one + /// is passed in, + /// createNode might be called on it, but doIt never will be, so the layer manager + /// node may not be added to the scene graph yet + /// \param wasCreated If given, whether a new layer manager had to be created is stored here. + /// \return the found-or-created LayerManager + AL_USDMAYA_PUBLIC + static LayerManager* + findOrCreateManager(MDGModifier* dgmod = nullptr, bool* wasCreated = nullptr); + + //-------------------------------------------------------------------------------------------------------------------- + /// Methods to handle the saving and restoring of layer data + //-------------------------------------------------------------------------------------------------------------------- + + /// \brief Add the given layer to the list of layers managed by this node, if not already + /// present. \param layer What layer to add to this LayerManager \param identifier Extra + /// identifier to add as a key to this layer; note that the "canonical" identifier, + /// as returned by layer.GetIdentifier(), is ALWAYS added as an identifier key for this + /// layer so this is intended as a way to provide a second identifier for the same layer + /// (or third or more, if you call it repeatedly). This is useful both because multiple + /// identifiers may resolve to the same underlying layer (especially when considering + /// asset resolution), and for serializing and deserializing anonymous layers, the + /// "canonical" identifier will change every time it is serialized and deserialized (and + /// it can be necessary to refer to the layer both by it's "old" and "new" ids). If this + /// is an empty string, it is ignored. + /// \return bool which is true if the layer was actually added to the list of layers managed by + /// this node + /// (ie, if it wasn't already managed, and the given layer handle was valid) + AL_USDMAYA_PUBLIC + bool addLayer(SdfLayerHandle layer, const std::string& identifier = std::string()); + + /// \brief Remove the given layer to the list of layers managed by this node, if present. + /// \return bool which is true if the layer was actually removed from the list of layers managed + /// by this node + /// (ie, if it was previously managed, and the given layer handle was valid) + AL_USDMAYA_PUBLIC + bool removeLayer(SdfLayerHandle layer); + + /// \brief Find the layer in the list of layers managed by this node, by identifier + /// \return The found layer handle in the layer list managed by this node (invalid if not found) + AL_USDMAYA_PUBLIC + SdfLayerHandle findLayer(std::string identifier); + + /// \brief Store a list of the managed layers' identifiers in the given MStringArray + /// \param outputNames The array to hold the identifier names; will be cleared before being + /// filled. + /// No guarantees are made about the order in which the layer identifiers will be + /// returned. + AL_USDMAYA_PUBLIC + void getLayerIdentifiers(MStringArray& outputNames); + + /// \brief Ensures that the layers attribute will be filled out with serialized versions of all + /// tracked layers. + AL_USDMAYA_PUBLIC + MStatus populateSerialisationAttributes(); + + /// \brief Clears the layers attribute. + AL_USDMAYA_PUBLIC + MStatus clearSerialisationAttributes(); + + /// \brief For every serialized layer stored in attributes, loads them as sdf layers + AL_USDMAYA_PUBLIC + void loadAllLayers(); + + //-------------------------------------------------------------------------------------------------------------------- + /// Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- + AL_MAYA_DECLARE_NODE(); + + /// \brief Creates the node, but only if there is not a non-referenced one in the scene + /// already. + AL_USDMAYA_PUBLIC + static void* conditionalCreator(); + + //-------------------------------------------------------------------------------------------------------------------- + /// Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- + + // attributes to store the serialised layers (used for file IO only) + + // Note that the layers attribute should ONLY used during serialization, as this is the ONLY + // times at which these attributes are guaranteed to "line up" to the internal layer register + // (m_layerList). Ie, immediately before save (due to the pre-save callback), the attributes + // will be written from m_layerList; and immediate after open (due to the post-open callback), + // m_layerList will be initialized from the attributes. At all other times, the attributes will + // be OUT OF SYNC (and, in fact, are intentionally set to be "empty", so there's no confusion / + // someone doesn't try to use "out of date" information) + AL_DECL_ATTRIBUTE(layers); + // Not using AL_DECL_ATTRIBUTE for these, because we never want a generic, ie, identifierPlug() + // - they only make sense for a particular index of the parent array-attribute... and it taking + // up the "identifierPlug" name is confusing + AL_DECL_MULTI_CHILD_ATTRIBUTE(identifier); + AL_DECL_MULTI_CHILD_ATTRIBUTE(serialized); + AL_DECL_MULTI_CHILD_ATTRIBUTE(anonymous); private: - static MObject _findNode(); + static MObject _findNode(); - LayerDatabase m_layerDatabase; + LayerDatabase m_layerDatabase; - // Note on layerManager / multithreading: - // I don't know that layerManager will be used in a multihreaded manenr... but I also don't know it COULDN'T be. - // (I haven't really looked into the way maya's new multi-threaded node evaluation works, for instance.) This is - // essentially a globally shared resource, so I figured better be safe... - boost::shared_mutex m_layersMutex; + // Note on layerManager / multithreading: + // I don't know that layerManager will be used in a multihreaded manenr... but I also don't know + // it COULDN'T be. (I haven't really looked into the way maya's new multi-threaded node + // evaluation works, for instance.) This is essentially a globally shared resource, so I figured + // better be safe... + boost::shared_mutex m_layersMutex; - //-------------------------------------------------------------------------------------------------------------------- - /// MPxNode overrides - //-------------------------------------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------------------------------------- + /// MPxNode overrides + //-------------------------------------------------------------------------------------------------------------------- - /// \var static MObject layers(); - /// \brief access the layers attribute handle - /// \return the handle to the layers attribute + /// \var static MObject layers(); + /// \brief access the layers attribute handle + /// \return the handle to the layers attribute - /// \var static MObject serialized(); - /// \brief access the serialized attribute handle - /// \return the handle to the serialized attribute + /// \var static MObject serialized(); + /// \brief access the serialized attribute handle + /// \return the handle to the serialized attribute - /// \var static MObject identifier(); - /// \brief access the identifier attribute handle - /// \return the handle to the identifier attribute + /// \var static MObject identifier(); + /// \brief access the identifier attribute handle + /// \return the handle to the identifier attribute - /// \var static MObject anonymous(); - /// \brief access the anonymous attribute handle - /// \return the handle to the anonymous attribute + /// \var static MObject anonymous(); + /// \brief access the anonymous attribute handle + /// \return the handle to the anonymous attribute - /// \var MPlug layersPlug() const; - /// \brief access the serialized layers plug on this node instance. - /// \return the plug to the layers attribute + /// \var MPlug layersPlug() const; + /// \brief access the serialized layers plug on this node instance. + /// \return the plug to the layers attribute - /// \var MPlug serializedPlug() const; - /// \brief access the serialized attribute plug on this node instance. - /// \return the plug to the serialized attribute + /// \var MPlug serializedPlug() const; + /// \brief access the serialized attribute plug on this node instance. + /// \return the plug to the serialized attribute - /// \var MPlug identifier() const; - /// \brief access the identifier attribute plug on this node instance. - /// \return the plug to the identifier attribute - - /// \var MPlug anonymous() const; - /// \brief access the anonymous attribute plug on this node instance. - /// \return the plug to the anonymous attribute + /// \var MPlug identifier() const; + /// \brief access the identifier attribute plug on this node instance. + /// \return the plug to the identifier attribute + /// \var MPlug anonymous() const; + /// \brief access the anonymous attribute plug on this node instance. + /// \return the plug to the anonymous attribute }; -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimCreator.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimCreator.cpp index 17984db837..c035e75170 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimCreator.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimCreator.cpp @@ -13,21 +13,21 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/maya/utils/Utils.h" +#include "AL/usdmaya/nodes/MeshAnimCreator.h" -#include "AL/usdmaya/TypeIDs.h" +#include "AL/maya/utils/Utils.h" #include "AL/usdmaya/DebugCodes.h" -#include "AL/usdmaya/nodes/MeshAnimCreator.h" +#include "AL/usdmaya/TypeIDs.h" #include "AL/usdmaya/nodes/ProxyShape.h" -#include "AL/usdmaya/utils/Utils.h" #include "AL/usdmaya/utils/MeshUtils.h" +#include "AL/usdmaya/utils/Utils.h" -#include -#include +#include #include -#include +#include +#include namespace AL { namespace usdmaya { @@ -45,139 +45,137 @@ MObject MeshAnimCreator::m_outMesh = MObject::kNullObj; //---------------------------------------------------------------------------------------------------------------------- MStatus MeshAnimCreator::initialise() { - try - { - setNodeType(kTypeName); - addFrame("Mesh Animation Createor"); - - // do not write these nodes to the file. They will be created automagically by the proxy shape - m_primPath = addStringAttr("primPath", "pp", kReadable | kWritable); - m_inTime = addTimeAttr("inTime", "it", MTime(), kReadable | kWritable | kStorable | kConnectable); - m_inStageData = addDataAttr("inStageData", "isd", MayaUsdStageData::mayaTypeId, kWritable | kStorable | kConnectable); - m_outMesh = addMeshAttr("outMesh", "out", kReadable | kStorable | kConnectable); - attributeAffects(m_primPath, m_outMesh); - attributeAffects(m_inTime, m_outMesh); - attributeAffects(m_inStageData, m_outMesh); - } - catch(const MStatus& status) - { - return status; - } - generateAETemplate(); - return MS::kSuccess; + try { + setNodeType(kTypeName); + addFrame("Mesh Animation Createor"); + + // do not write these nodes to the file. They will be created automagically by the proxy + // shape + m_primPath = addStringAttr("primPath", "pp", kReadable | kWritable); + m_inTime = addTimeAttr( + "inTime", "it", MTime(), kReadable | kWritable | kStorable | kConnectable); + m_inStageData = addDataAttr( + "inStageData", + "isd", + MayaUsdStageData::mayaTypeId, + kWritable | kStorable | kConnectable); + m_outMesh = addMeshAttr("outMesh", "out", kReadable | kStorable | kConnectable); + attributeAffects(m_primPath, m_outMesh); + attributeAffects(m_inTime, m_outMesh); + attributeAffects(m_inStageData, m_outMesh); + } catch (const MStatus& status) { + return status; + } + generateAETemplate(); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus MeshAnimCreator::compute(const MPlug& plug, MDataBlock& data) { - TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimCreator::compute ==> %s\n", plug.name().asChar()); + TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER) + .Msg("MeshAnimCreator::compute ==> %s\n", plug.name().asChar()); + + MStatus status = MS::kInvalidParameter; + if (plug != m_outMesh) { + return status; + } - MStatus status = MS::kInvalidParameter; - if (plug != m_outMesh) - { + MTime inTimeVal = inputTimeValue(data, m_inTime); + UsdTimeCode usdTime(inTimeVal.value()); + + MDataHandle outputHandle = data.outputValue(m_outMesh, &status); + UsdStageRefPtr stage = getStage(); + if (stage) { + UsdPrim prim = stage->GetPrimAtPath(m_cachePath); + UsdGeomMesh mesh(prim); + + MFnMeshData fnData; + MObject obj = fnData.create(); + + utils::MeshImportContext context(mesh, obj, MString(), usdTime); + context.applyHoleFaces(); + context.applyVertexNormals(); + context.applyEdgeCreases(); + context.applyVertexCreases(); + context.applyUVs(); + context.applyColourSetData(); + outputHandle.set(obj); + } return status; - } - - MTime inTimeVal = inputTimeValue(data, m_inTime); - UsdTimeCode usdTime(inTimeVal.value()); - - MDataHandle outputHandle = data.outputValue(m_outMesh, &status); - UsdStageRefPtr stage = getStage(); - if(stage) - { - UsdPrim prim = stage->GetPrimAtPath(m_cachePath); - UsdGeomMesh mesh(prim); - - MFnMeshData fnData; - MObject obj = fnData.create(); - - utils::MeshImportContext context(mesh, obj, MString(), usdTime); - context.applyHoleFaces(); - context.applyVertexNormals(); - context.applyEdgeCreases(); - context.applyVertexCreases(); - context.applyUVs(); - context.applyColourSetData(); - outputHandle.set(obj); - } - return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus MeshAnimCreator::connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) { - TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimCreator::connectionMade\n"); - if(!asSrc && plug == m_inStageData) - { - MFnDependencyNode otherNode(otherPlug.node()); - if (otherNode.typeId() == ProxyShape::kTypeId) - { - proxyShapeHandle = otherPlug.node(); + TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimCreator::connectionMade\n"); + if (!asSrc && plug == m_inStageData) { + MFnDependencyNode otherNode(otherPlug.node()); + if (otherNode.typeId() == ProxyShape::kTypeId) { + proxyShapeHandle = otherPlug.node(); + } } - } - return MPxNode::connectionMade(plug, otherPlug, asSrc); + return MPxNode::connectionMade(plug, otherPlug, asSrc); } //---------------------------------------------------------------------------------------------------------------------- MStatus MeshAnimCreator::connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) { - TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimCreator::connectionBroken\n"); - if(!asSrc && plug == m_inStageData) - { - MFnDependencyNode otherNode(otherPlug.node()); - if (otherNode.typeId() == ProxyShape::kTypeId) - { - proxyShapeHandle = MObject(); + TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimCreator::connectionBroken\n"); + if (!asSrc && plug == m_inStageData) { + MFnDependencyNode otherNode(otherPlug.node()); + if (otherNode.typeId() == ProxyShape::kTypeId) { + proxyShapeHandle = MObject(); + } } - } - return MPxNode::connectionBroken(plug, otherPlug, asSrc); + return MPxNode::connectionBroken(plug, otherPlug, asSrc); } //---------------------------------------------------------------------------------------------------------------------- UsdStageRefPtr MeshAnimCreator::getStage() { - TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimCreator::getStage\n"); - if(proxyShapeHandle.isValid() && proxyShapeHandle.isAlive()) - { - MFnDependencyNode fn(proxyShapeHandle.object()); - ProxyShape* node = (ProxyShape*)fn.userNode(); - if(node) - { - return node->usdStage(); + TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimCreator::getStage\n"); + if (proxyShapeHandle.isValid() && proxyShapeHandle.isAlive()) { + MFnDependencyNode fn(proxyShapeHandle.object()); + ProxyShape* node = (ProxyShape*)fn.userNode(); + if (node) { + return node->usdStage(); + } } - } - return UsdStageRefPtr(); + return UsdStageRefPtr(); } //---------------------------------------------------------------------------------------------------------------------- void MeshAnimCreator::postConstructor() { - auto obj = thisMObject(); - m_attributeChanged = MNodeMessage::addAttributeChangedCallback(obj, onAttributeChanged, (void*)this); + auto obj = thisMObject(); + m_attributeChanged + = MNodeMessage::addAttributeChangedCallback(obj, onAttributeChanged, (void*)this); } //---------------------------------------------------------------------------------------------------------------------- -void MeshAnimCreator::onAttributeChanged(MNodeMessage::AttributeMessage msg, MPlug& plug, MPlug&, void* clientData) +void MeshAnimCreator::onAttributeChanged( + MNodeMessage::AttributeMessage msg, + MPlug& plug, + MPlug&, + void* clientData) { - TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimCreator::onAttributeChanged\n"); - MeshAnimCreator* deformer = (MeshAnimCreator*)clientData; - if(msg & MNodeMessage::kAttributeSet) - { - if(plug == m_primPath) - { - // Get the prim - // If no primPath string specified, then use the pseudo-root. - MString primPathStr = plug.asString(); - if (primPathStr.length()) - { - deformer->m_cachePath = SdfPath(AL::maya::utils::convert(primPathStr)); - } + TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimCreator::onAttributeChanged\n"); + MeshAnimCreator* deformer = (MeshAnimCreator*)clientData; + if (msg & MNodeMessage::kAttributeSet) { + if (plug == m_primPath) { + // Get the prim + // If no primPath string specified, then use the pseudo-root. + MString primPathStr = plug.asString(); + if (primPathStr.length()) { + deformer->m_cachePath = SdfPath(AL::maya::utils::convert(primPathStr)); + } + } } - } } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimCreator.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimCreator.h index 627a3701d6..e96f5ab4b4 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimCreator.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimCreator.h @@ -15,14 +15,14 @@ // #pragma once -#include "AL/maya/utils/NodeHelper.h" #include "AL/maya/utils/MayaHelperMacros.h" +#include "AL/maya/utils/NodeHelper.h" #include -#include #include #include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -31,53 +31,55 @@ namespace usdmaya { namespace nodes { //---------------------------------------------------------------------------------------------------------------------- -/// \brief The MeshAnimCreator node acts as a polyCreator node within the DG that is driven by time. When the time -/// changes, +/// \brief The MeshAnimCreator node acts as a polyCreator node within the DG that is driven by +/// time. When the time +/// changes, /// \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- class MeshAnimCreator - : public MPxNode, - public AL::maya::utils::NodeHelper + : public MPxNode + , public AL::maya::utils::NodeHelper { public: + /// \brief ctor + inline MeshAnimCreator() + : MPxNode() + , NodeHelper() + { + } - /// \brief ctor - inline MeshAnimCreator() - : MPxNode(), NodeHelper() - {} - - inline ~MeshAnimCreator() - { MNodeMessage::removeCallback(m_attributeChanged); } + inline ~MeshAnimCreator() { MNodeMessage::removeCallback(m_attributeChanged); } - //-------------------------------------------------------------------------------------------------------------------- - /// Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- - AL_MAYA_DECLARE_NODE(); + //-------------------------------------------------------------------------------------------------------------------- + /// Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- + AL_MAYA_DECLARE_NODE(); - //-------------------------------------------------------------------------------------------------------------------- - /// Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------------------------------------- + /// Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- - AL_DECL_ATTRIBUTE(primPath); - AL_DECL_ATTRIBUTE(inTime); - AL_DECL_ATTRIBUTE(inStageData); - AL_DECL_ATTRIBUTE(outMesh); + AL_DECL_ATTRIBUTE(primPath); + AL_DECL_ATTRIBUTE(inTime); + AL_DECL_ATTRIBUTE(inStageData); + AL_DECL_ATTRIBUTE(outMesh); private: - void postConstructor() override; - MStatus connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; - MStatus connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; - static void onAttributeChanged(MNodeMessage::AttributeMessage, MPlug&, MPlug&, void*); - MStatus compute(const MPlug& plug, MDataBlock& data) override; - UsdStageRefPtr getStage(); + void postConstructor() override; + MStatus connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; + MStatus connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; + static void onAttributeChanged(MNodeMessage::AttributeMessage, MPlug&, MPlug&, void*); + MStatus compute(const MPlug& plug, MDataBlock& data) override; + UsdStageRefPtr getStage(); + private: - SdfPath m_cachePath; - MObjectHandle proxyShapeHandle; - MCallbackId m_attributeChanged = 0; + SdfPath m_cachePath; + MObjectHandle proxyShapeHandle; + MCallbackId m_attributeChanged = 0; }; //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimDeformer.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimDeformer.cpp index 6ab4b52f7d..530c07dc5c 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimDeformer.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimDeformer.cpp @@ -13,20 +13,20 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/maya/utils/Utils.h" +#include "AL/usdmaya/nodes/MeshAnimDeformer.h" -#include "AL/usdmaya/TypeIDs.h" +#include "AL/maya/utils/Utils.h" #include "AL/usdmaya/DebugCodes.h" -#include "AL/usdmaya/nodes/MeshAnimDeformer.h" +#include "AL/usdmaya/TypeIDs.h" #include "AL/usdmaya/nodes/ProxyShape.h" #include "AL/usdmaya/utils/Utils.h" -#include -#include +#include #include -#include +#include +#include namespace AL { namespace usdmaya { @@ -45,166 +45,158 @@ MObject MeshAnimDeformer::m_inMesh = MObject::kNullObj; //---------------------------------------------------------------------------------------------------------------------- MStatus MeshAnimDeformer::initialise() { - try - { - setNodeType(kTypeName); - addFrame("Mesh Animation Deformer"); - - // do not write these nodes to the file. They will be created automagically by the proxy shape - m_primPath = addStringAttr("primPath", "pp", kReadable | kWritable); - m_inTime = addTimeAttr("inTime", "it", MTime(), kReadable | kWritable | kStorable | kConnectable); - m_inStageData = addDataAttr("inStageData", "isd", MayaUsdStageData::mayaTypeId, kWritable | kStorable | kConnectable); - m_outMesh = addMeshAttr("outMesh", "out", kReadable | kStorable | kConnectable); - m_inMesh = addMeshAttr("inMesh", "in", kWritable | kStorable | kConnectable); - attributeAffects(m_primPath, m_outMesh); - attributeAffects(m_inTime, m_outMesh); - attributeAffects(m_inStageData, m_outMesh); - attributeAffects(m_inMesh, m_outMesh); - } - catch(const MStatus& status) - { - return status; - } - generateAETemplate(); - return MS::kSuccess; + try { + setNodeType(kTypeName); + addFrame("Mesh Animation Deformer"); + + // do not write these nodes to the file. They will be created automagically by the proxy + // shape + m_primPath = addStringAttr("primPath", "pp", kReadable | kWritable); + m_inTime = addTimeAttr( + "inTime", "it", MTime(), kReadable | kWritable | kStorable | kConnectable); + m_inStageData = addDataAttr( + "inStageData", + "isd", + MayaUsdStageData::mayaTypeId, + kWritable | kStorable | kConnectable); + m_outMesh = addMeshAttr("outMesh", "out", kReadable | kStorable | kConnectable); + m_inMesh = addMeshAttr("inMesh", "in", kWritable | kStorable | kConnectable); + attributeAffects(m_primPath, m_outMesh); + attributeAffects(m_inTime, m_outMesh); + attributeAffects(m_inStageData, m_outMesh); + attributeAffects(m_inMesh, m_outMesh); + } catch (const MStatus& status) { + return status; + } + generateAETemplate(); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus MeshAnimDeformer::compute(const MPlug& plug, MDataBlock& data) { - TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimDeformer::compute ==> %s\n", plug.name().asChar()); + TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER) + .Msg("MeshAnimDeformer::compute ==> %s\n", plug.name().asChar()); - MStatus status = MS::kInvalidParameter; - if (plug != m_outMesh) - { - return status; - } - - MTime inTimeVal = inputTimeValue(data, m_inTime); - UsdTimeCode usdTime(inTimeVal.value()); - - MDataHandle inputHandle = data.inputValue(m_inMesh, &status); - MDataHandle outputHandle = data.outputValue(m_outMesh, &status); - - MObject obj = inputHandle.asMesh(); - - UsdStageRefPtr stage = getStage(); - if(stage) - { - UsdPrim prim = stage->GetPrimAtPath(m_cachePath); - UsdGeomMesh mesh(prim); - - MFnMesh fnMesh(obj); - float* const ptr = (float*)fnMesh.getRawPoints(&status); - if(ptr) - { - UsdAttribute points = mesh.GetPointsAttr(); - if(points.GetNumTimeSamples() > 1) - { - VtArray pointData; - points.Get(&pointData, usdTime); - const size_t numPoints = pointData.size(); - std::memcpy(ptr, pointData.cdata(), sizeof(float) * 3 * numPoints); - } + MStatus status = MS::kInvalidParameter; + if (plug != m_outMesh) { + return status; } - float* const nptr = (float*)fnMesh.getRawNormals(&status); - if(nptr) - { - UsdAttribute normals = mesh.GetNormalsAttr(); - if(normals.GetNumTimeSamples() > 1) - { - VtArray normalData; - normals.Get(&normalData, usdTime); - const size_t numNormals = normalData.size(); - std::memcpy(nptr, normalData.cdata(), sizeof(float) * 3 * numNormals); - } + MTime inTimeVal = inputTimeValue(data, m_inTime); + UsdTimeCode usdTime(inTimeVal.value()); + + MDataHandle inputHandle = data.inputValue(m_inMesh, &status); + MDataHandle outputHandle = data.outputValue(m_outMesh, &status); + + MObject obj = inputHandle.asMesh(); + + UsdStageRefPtr stage = getStage(); + if (stage) { + UsdPrim prim = stage->GetPrimAtPath(m_cachePath); + UsdGeomMesh mesh(prim); + + MFnMesh fnMesh(obj); + float* const ptr = (float*)fnMesh.getRawPoints(&status); + if (ptr) { + UsdAttribute points = mesh.GetPointsAttr(); + if (points.GetNumTimeSamples() > 1) { + VtArray pointData; + points.Get(&pointData, usdTime); + const size_t numPoints = pointData.size(); + std::memcpy(ptr, pointData.cdata(), sizeof(float) * 3 * numPoints); + } + } + + float* const nptr = (float*)fnMesh.getRawNormals(&status); + if (nptr) { + UsdAttribute normals = mesh.GetNormalsAttr(); + if (normals.GetNumTimeSamples() > 1) { + VtArray normalData; + normals.Get(&normalData, usdTime); + const size_t numNormals = normalData.size(); + std::memcpy(nptr, normalData.cdata(), sizeof(float) * 3 * numNormals); + } + } + outputHandle.set(obj); } - outputHandle.set(obj); - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus MeshAnimDeformer::connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) { - TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimDeformer::connectionMade\n"); - if(!asSrc && plug == m_inStageData) - { - MFnDependencyNode otherNode(otherPlug.node()); - if (otherNode.typeId() == ProxyShape::kTypeId) - { - proxyShapeHandle = otherPlug.node(); + TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimDeformer::connectionMade\n"); + if (!asSrc && plug == m_inStageData) { + MFnDependencyNode otherNode(otherPlug.node()); + if (otherNode.typeId() == ProxyShape::kTypeId) { + proxyShapeHandle = otherPlug.node(); + } } - } - return MPxNode::connectionMade(plug, otherPlug, asSrc); + return MPxNode::connectionMade(plug, otherPlug, asSrc); } //---------------------------------------------------------------------------------------------------------------------- MStatus MeshAnimDeformer::connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) { - TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimDeformer::connectionBroken\n"); - if(!asSrc && plug == m_inStageData) - { - MFnDependencyNode otherNode(otherPlug.node()); - if (otherNode.typeId() == ProxyShape::kTypeId) - { - proxyShapeHandle = MObject(); + TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimDeformer::connectionBroken\n"); + if (!asSrc && plug == m_inStageData) { + MFnDependencyNode otherNode(otherPlug.node()); + if (otherNode.typeId() == ProxyShape::kTypeId) { + proxyShapeHandle = MObject(); + } } - } - return MPxNode::connectionBroken(plug, otherPlug, asSrc); + return MPxNode::connectionBroken(plug, otherPlug, asSrc); } //---------------------------------------------------------------------------------------------------------------------- UsdStageRefPtr MeshAnimDeformer::getStage() { - TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimDeformer::getStage\n"); - if(proxyShapeHandle.isValid() && proxyShapeHandle.isAlive()) - { - MFnDependencyNode fn(proxyShapeHandle.object()); - ProxyShape* node = (ProxyShape*)fn.userNode(); - if(node) - { - return node->usdStage(); + TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimDeformer::getStage\n"); + if (proxyShapeHandle.isValid() && proxyShapeHandle.isAlive()) { + MFnDependencyNode fn(proxyShapeHandle.object()); + ProxyShape* node = (ProxyShape*)fn.userNode(); + if (node) { + return node->usdStage(); + } } - } - return UsdStageRefPtr(); + return UsdStageRefPtr(); } //---------------------------------------------------------------------------------------------------------------------- void MeshAnimDeformer::postConstructor() { - auto obj = thisMObject(); - m_attributeChanged = MNodeMessage::addAttributeChangedCallback(obj, onAttributeChanged, (void*)this); + auto obj = thisMObject(); + m_attributeChanged + = MNodeMessage::addAttributeChangedCallback(obj, onAttributeChanged, (void*)this); } //---------------------------------------------------------------------------------------------------------------------- -void MeshAnimDeformer::onAttributeChanged(MNodeMessage::AttributeMessage msg, MPlug& plug, MPlug&, void* clientData) +void MeshAnimDeformer::onAttributeChanged( + MNodeMessage::AttributeMessage msg, + MPlug& plug, + MPlug&, + void* clientData) { - TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimDeformer::onAttributeChanged\n"); - - MeshAnimDeformer* deformer = (MeshAnimDeformer*)clientData; - if(msg & MNodeMessage::kAttributeSet) - { - if(plug == m_primPath) - { - // Get the prim - // If no primPath string specified, then use the pseudo-root. - MString primPathStr = plug.asString(); - if (primPathStr.length()) - { - deformer->m_cachePath = SdfPath(AL::maya::utils::convert(primPathStr)); - } - else - { - deformer->m_cachePath = SdfPath(); - } + TF_DEBUG(ALUSDMAYA_GEOMETRY_DEFORMER).Msg("MeshAnimDeformer::onAttributeChanged\n"); + + MeshAnimDeformer* deformer = (MeshAnimDeformer*)clientData; + if (msg & MNodeMessage::kAttributeSet) { + if (plug == m_primPath) { + // Get the prim + // If no primPath string specified, then use the pseudo-root. + MString primPathStr = plug.asString(); + if (primPathStr.length()) { + deformer->m_cachePath = SdfPath(AL::maya::utils::convert(primPathStr)); + } else { + deformer->m_cachePath = SdfPath(); + } + } } - } } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimDeformer.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimDeformer.h index 1371b54b86..f95a48b6a2 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimDeformer.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/MeshAnimDeformer.h @@ -14,14 +14,14 @@ // limitations under the License. // #pragma once -#include "AL/maya/utils/NodeHelper.h" #include "AL/maya/utils/MayaHelperMacros.h" +#include "AL/maya/utils/NodeHelper.h" #include -#include #include #include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -30,53 +30,54 @@ namespace usdmaya { namespace nodes { //---------------------------------------------------------------------------------------------------------------------- -/// \brief This node is a simple deformer that modifies +/// \brief This node is a simple deformer that modifies /// \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- class MeshAnimDeformer - : public MPxNode, - public AL::maya::utils::NodeHelper + : public MPxNode + , public AL::maya::utils::NodeHelper { public: + /// \brief ctor + inline MeshAnimDeformer() + : MPxNode() + , NodeHelper() + { + } - /// \brief ctor - inline MeshAnimDeformer() - : MPxNode(), NodeHelper() - {} - - inline ~MeshAnimDeformer() - { MNodeMessage::removeCallback(m_attributeChanged); } + inline ~MeshAnimDeformer() { MNodeMessage::removeCallback(m_attributeChanged); } - //-------------------------------------------------------------------------------------------------------------------- - /// Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- - AL_MAYA_DECLARE_NODE(); + //-------------------------------------------------------------------------------------------------------------------- + /// Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- + AL_MAYA_DECLARE_NODE(); - //-------------------------------------------------------------------------------------------------------------------- - /// Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------------------------------------- + /// Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- - AL_DECL_ATTRIBUTE(primPath); - AL_DECL_ATTRIBUTE(inTime); - AL_DECL_ATTRIBUTE(inStageData); - AL_DECL_ATTRIBUTE(inMesh); - AL_DECL_ATTRIBUTE(outMesh); + AL_DECL_ATTRIBUTE(primPath); + AL_DECL_ATTRIBUTE(inTime); + AL_DECL_ATTRIBUTE(inStageData); + AL_DECL_ATTRIBUTE(inMesh); + AL_DECL_ATTRIBUTE(outMesh); private: - void postConstructor() override; - MStatus connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; - MStatus connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; - static void onAttributeChanged(MNodeMessage::AttributeMessage, MPlug&, MPlug&, void*); - MStatus compute(const MPlug& plug, MDataBlock& data) override; - UsdStageRefPtr getStage(); + void postConstructor() override; + MStatus connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; + MStatus connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; + static void onAttributeChanged(MNodeMessage::AttributeMessage, MPlug&, MPlug&, void*); + MStatus compute(const MPlug& plug, MDataBlock& data) override; + UsdStageRefPtr getStage(); + private: - SdfPath m_cachePath; - MObjectHandle proxyShapeHandle; - MCallbackId m_attributeChanged = 0; + SdfPath m_cachePath; + MObjectHandle proxyShapeHandle; + MCallbackId m_attributeChanged = 0; }; //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyDrawOverride.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyDrawOverride.cpp index 7c5391ce23..248272d4a9 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyDrawOverride.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyDrawOverride.cpp @@ -15,10 +15,11 @@ // #include +#include "AL/usdmaya/nodes/ProxyDrawOverride.h" + #include "AL/usdmaya/DebugCodes.h" #include "AL/usdmaya/nodes/Engine.h" #include "AL/usdmaya/nodes/ProxyShape.h" -#include "AL/usdmaya/nodes/ProxyDrawOverride.h" #include #include @@ -32,12 +33,13 @@ #if defined(WANT_UFE_BUILD) #include "AL/usdmaya/TypeIDs.h" -#include -#include "ufe/sceneItem.h" -#include "ufe/runTimeMgr.h" #include "ufe/globalSelection.h" -#include "ufe/observableSelection.h" #include "ufe/log.h" +#include "ufe/observableSelection.h" +#include "ufe/runTimeMgr.h" +#include "ufe/sceneItem.h" + +#include #endif namespace AL { @@ -47,26 +49,24 @@ namespace { //---------------------------------------------------------------------------------------------------------------------- /// \brief user data struct - holds the info needed to render the scene //---------------------------------------------------------------------------------------------------------------------- -class RenderUserData - : public MUserData +class RenderUserData : public MUserData { public: + // Constructor to use when shape is drawn but no bounding box. + RenderUserData() + : MUserData(false) + { + } - // Constructor to use when shape is drawn but no bounding box. - RenderUserData() - : MUserData(false) - {} - - // Make sure everything gets freed! - ~RenderUserData() - {} + // Make sure everything gets freed! + ~RenderUserData() { } - UsdImagingGLRenderParams m_params; - UsdPrim m_rootPrim; - ProxyShape* m_shape = 0; - MDagPath m_objPath; + UsdImagingGLRenderParams m_params; + UsdPrim m_rootPrim; + ProxyShape* m_shape = 0; + MDagPath m_objPath; }; -} +} // namespace //---------------------------------------------------------------------------------------------------------------------- MString ProxyDrawOverride::kDrawDbClassification("drawdb/geometry/AL_usdmaya"); @@ -76,887 +76,784 @@ MUint64 ProxyDrawOverride::s_lastRefreshFrameStamp = 0; //---------------------------------------------------------------------------------------------------------------------- ProxyDrawOverride::ProxyDrawOverride(const MObject& obj) #if MAYA_API_VERSION >= 20190000 - : MHWRender::MPxDrawOverride(obj, draw, true) + : MHWRender::MPxDrawOverride(obj, draw, true) #elif MAYA_API_VERSION >= 20180600 - : MHWRender::MPxDrawOverride2(obj, draw, true) + : MHWRender::MPxDrawOverride2(obj, draw, true) #else - : MHWRender::MPxDrawOverride(obj, draw, true) + : MHWRender::MPxDrawOverride(obj, draw, true) #endif { - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::ProxyDrawOverride\n"); + TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::ProxyDrawOverride\n"); } //---------------------------------------------------------------------------------------------------------------------- -ProxyDrawOverride::~ProxyDrawOverride() -{ -} +ProxyDrawOverride::~ProxyDrawOverride() { } //---------------------------------------------------------------------------------------------------------------------- MHWRender::MPxDrawOverride* ProxyDrawOverride::creator(const MObject& obj) { - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::creator\n"); - return new ProxyDrawOverride(obj); + TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::creator\n"); + return new ProxyDrawOverride(obj); } //---------------------------------------------------------------------------------------------------------------------- -bool ProxyDrawOverride::isBounded( - const MDagPath& objPath, - const MDagPath& cameraPath) const +bool ProxyDrawOverride::isBounded(const MDagPath& objPath, const MDagPath& cameraPath) const { - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::isBounded\n"); - return true; + TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::isBounded\n"); + return true; } //---------------------------------------------------------------------------------------------------------------------- -MBoundingBox ProxyDrawOverride::boundingBox( - const MDagPath& objPath, - const MDagPath& cameraPath) const +MBoundingBox +ProxyDrawOverride::boundingBox(const MDagPath& objPath, const MDagPath& cameraPath) const { - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::boundingBox\n"); - ProxyShape* pShape = getShape(objPath); - if (!pShape) - { - return MBoundingBox(); - } - return pShape->boundingBox(); + TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::boundingBox\n"); + ProxyShape* pShape = getShape(objPath); + if (!pShape) { + return MBoundingBox(); + } + return pShape->boundingBox(); } //---------------------------------------------------------------------------------------------------------------------- MUserData* ProxyDrawOverride::prepareForDraw( - const MDagPath& objPath, - const MDagPath& cameraPath, + const MDagPath& objPath, + const MDagPath& cameraPath, const MHWRender::MFrameContext& frameContext, - MUserData* userData) + MUserData* userData) { - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::prepareForDraw\n"); - MFnDagNode fn(objPath); - - auto data = static_cast(userData); - auto shape = static_cast(fn.userNode()); - if (!shape) - return nullptr; - - auto engine = shape->engine(); - if(!engine) - { - return nullptr; - } - - RenderUserData* newData = nullptr; - if (data == nullptr) - { - data = newData = new RenderUserData; - } - - if(!shape->getRenderAttris(data->m_params, frameContext, objPath)) - { - delete newData; - return nullptr; - } - - data->m_objPath = objPath; - data->m_shape = shape; - data->m_rootPrim = shape->getRootPrim(); - - return data; -} + TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::prepareForDraw\n"); + MFnDagNode fn(objPath); -//---------------------------------------------------------------------------------------------------------------------- -void ProxyDrawOverride::draw(const MHWRender::MDrawContext& context, const MUserData* data) -{ - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::draw\n"); + auto data = static_cast(userData); + auto shape = static_cast(fn.userNode()); + if (!shape) + return nullptr; - float clearCol[4]; - glGetFloatv(GL_COLOR_CLEAR_VALUE, clearCol); - - RenderUserData* ptr = (RenderUserData*)data; - if(ptr && ptr->m_rootPrim) - { - ptr->m_shape->onRedraw(); - auto* engine = ptr->m_shape->engine(); - if (!engine) - { - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::draw - Error constructing usd opengl drawing engine - aborting draw\n"); - return; + auto engine = shape->engine(); + if (!engine) { + return nullptr; } - MHWRender::MStateManager* stateManager = context.getStateManager(); - MHWRender::MDepthStencilStateDesc depthDesc; - auto depthState = MHWRender::MStateManager::acquireDepthStencilState(depthDesc); - auto previousDepthState = stateManager->getDepthStencilState(); - stateManager->setDepthStencilState(depthState); + RenderUserData* newData = nullptr; + if (data == nullptr) { + data = newData = new RenderUserData; + } - float minR, maxR; - context.getDepthRange(minR, maxR); + if (!shape->getRenderAttris(data->m_params, frameContext, objPath)) { + delete newData; + return nullptr; + } - MHWRender::MDrawContext::LightFilter considerAllSceneLights = MHWRender::MDrawContext::kFilteredToLightLimit; + data->m_objPath = objPath; + data->m_shape = shape; + data->m_rootPrim = shape->getRootPrim(); - uint32_t numLights = context.numberOfActiveLights(considerAllSceneLights); + return data; +} - GlfSimpleLightVector lights; - lights.reserve(numLights); - for(uint32_t i = 0; i < numLights; ++i) - { - MFloatPointArray positions; - MFloatVector direction; - float intensity; - MColor color; - bool hasDirection; - bool hasPosition; - context.getLightInformation(i, positions, direction, intensity, color, hasDirection, hasPosition, considerAllSceneLights); - GlfSimpleLight light; - if(hasPosition) - { - if(positions.length() == 1) - { - GfVec4f pos(positions[0].x, positions[0].y, positions[0].z, positions[0].w); - light.SetPosition(pos); - } - else - { - MFloatPoint fp(0,0,0); - for(uint32_t j = 0; j < positions.length(); ++j) - { - fp += positions[j]; - } - float value = (1.0f / positions.length()); - fp.x*=value;fp.y*=value;fp.z*=value; - light.SetPosition(GfVec4f(fp.x, fp.y, fp.z, 1.0f)); +//---------------------------------------------------------------------------------------------------------------------- +void ProxyDrawOverride::draw(const MHWRender::MDrawContext& context, const MUserData* data) +{ + TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::draw\n"); + + float clearCol[4]; + glGetFloatv(GL_COLOR_CLEAR_VALUE, clearCol); + + RenderUserData* ptr = (RenderUserData*)data; + if (ptr && ptr->m_rootPrim) { + ptr->m_shape->onRedraw(); + auto* engine = ptr->m_shape->engine(); + if (!engine) { + TF_DEBUG(ALUSDMAYA_DRAW) + .Msg("ProxyDrawOverride::draw - Error constructing usd opengl drawing engine - " + "aborting draw\n"); + return; } - } - - if(hasDirection) - { - GfVec3f dir(direction.x, direction.y, direction.z); - light.SetSpotDirection(dir); - } - - MHWRender::MLightParameterInformation* lightParam = context.getLightParameterInformation(i, considerAllSceneLights); - if(lightParam) - { - MStringArray paramNames; - lightParam->parameterList(paramNames); - for(uint32_t i = 0, n = paramNames.length(); i != n; ++i) - { - auto semantic = lightParam->parameterSemantic(paramNames[i]); - switch(semantic) - { - case MHWRender::MLightParameterInformation::kIntensity: - { - MFloatArray fa; - lightParam->getParameter(paramNames[i], fa); - } - break; - - case MHWRender::MLightParameterInformation::kColor: - { - MFloatArray fa; - lightParam->getParameter(paramNames[i], fa); - if(fa.length() == 3) - { - GfVec4f c(intensity * fa[0], intensity * fa[1], intensity * fa[2], 1.0f); - light.SetDiffuse(c); - light.SetSpecular(c); - } - } - break; - case MHWRender::MLightParameterInformation::kEmitsDiffuse: - case MHWRender::MLightParameterInformation::kEmitsSpecular: - { - MIntArray ia; - lightParam->getParameter(paramNames[i], ia); - } - break; - case MHWRender::MLightParameterInformation::kDecayRate: - { - MFloatArray fa; - lightParam->getParameter(paramNames[i], fa); - if (fa[0] == 0) - { - light.SetAttenuation(GfVec3f(1.0f, 0.0f, 0.0f)); - } - else if (fa[0] == 1) - { - light.SetAttenuation(GfVec3f(0.0f, 1.0f, 0.0f)); - } - else if (fa[0] == 2) { - light.SetAttenuation(GfVec3f(0.0f, 0.0f, 1.0f)); - } - } - break; - case MHWRender::MLightParameterInformation::kDropoff: - { - MFloatArray fa; - lightParam->getParameter(paramNames[i], fa); - light.SetSpotFalloff(fa[0]); - } - break; - case MHWRender::MLightParameterInformation::kCosConeAngle: - { - MFloatArray fa; - lightParam->getParameter(paramNames[i], fa); - fa[0] = acos(fa[0]) * 57.295779506f; - light.SetSpotCutoff(fa[0]); + MHWRender::MStateManager* stateManager = context.getStateManager(); + MHWRender::MDepthStencilStateDesc depthDesc; + + auto depthState = MHWRender::MStateManager::acquireDepthStencilState(depthDesc); + auto previousDepthState = stateManager->getDepthStencilState(); + stateManager->setDepthStencilState(depthState); + + float minR, maxR; + context.getDepthRange(minR, maxR); + + MHWRender::MDrawContext::LightFilter considerAllSceneLights + = MHWRender::MDrawContext::kFilteredToLightLimit; + + uint32_t numLights = context.numberOfActiveLights(considerAllSceneLights); + + GlfSimpleLightVector lights; + lights.reserve(numLights); + for (uint32_t i = 0; i < numLights; ++i) { + MFloatPointArray positions; + MFloatVector direction; + float intensity; + MColor color; + bool hasDirection; + bool hasPosition; + context.getLightInformation( + i, + positions, + direction, + intensity, + color, + hasDirection, + hasPosition, + considerAllSceneLights); + GlfSimpleLight light; + if (hasPosition) { + if (positions.length() == 1) { + GfVec4f pos(positions[0].x, positions[0].y, positions[0].z, positions[0].w); + light.SetPosition(pos); + } else { + MFloatPoint fp(0, 0, 0); + for (uint32_t j = 0; j < positions.length(); ++j) { + fp += positions[j]; + } + float value = (1.0f / positions.length()); + fp.x *= value; + fp.y *= value; + fp.z *= value; + light.SetPosition(GfVec4f(fp.x, fp.y, fp.z, 1.0f)); + } } - break; - case MHWRender::MLightParameterInformation::kStartShadowParameters: - case MHWRender::MLightParameterInformation::kShadowBias: - { - MFloatArray fa; - lightParam->getParameter(paramNames[i], fa); + + if (hasDirection) { + GfVec3f dir(direction.x, direction.y, direction.z); + light.SetSpotDirection(dir); } - break; - case MHWRender::MLightParameterInformation::kShadowMapSize: - case MHWRender::MLightParameterInformation::kShadowViewProj: - { - MMatrix value; - lightParam->getParameter(paramNames[i], value); - GfMatrix4d m(value.matrix); + + MHWRender::MLightParameterInformation* lightParam + = context.getLightParameterInformation(i, considerAllSceneLights); + if (lightParam) { + MStringArray paramNames; + lightParam->parameterList(paramNames); + for (uint32_t i = 0, n = paramNames.length(); i != n; ++i) { + auto semantic = lightParam->parameterSemantic(paramNames[i]); + switch (semantic) { + case MHWRender::MLightParameterInformation::kIntensity: { + MFloatArray fa; + lightParam->getParameter(paramNames[i], fa); + } break; + + case MHWRender::MLightParameterInformation::kColor: { + MFloatArray fa; + lightParam->getParameter(paramNames[i], fa); + if (fa.length() == 3) { + GfVec4f c( + intensity * fa[0], intensity * fa[1], intensity * fa[2], 1.0f); + light.SetDiffuse(c); + light.SetSpecular(c); + } + } break; + case MHWRender::MLightParameterInformation::kEmitsDiffuse: + case MHWRender::MLightParameterInformation::kEmitsSpecular: { + MIntArray ia; + lightParam->getParameter(paramNames[i], ia); + } break; + case MHWRender::MLightParameterInformation::kDecayRate: { + MFloatArray fa; + lightParam->getParameter(paramNames[i], fa); + if (fa[0] == 0) { + light.SetAttenuation(GfVec3f(1.0f, 0.0f, 0.0f)); + } else if (fa[0] == 1) { + light.SetAttenuation(GfVec3f(0.0f, 1.0f, 0.0f)); + } else if (fa[0] == 2) { + light.SetAttenuation(GfVec3f(0.0f, 0.0f, 1.0f)); + } + } break; + case MHWRender::MLightParameterInformation::kDropoff: { + MFloatArray fa; + lightParam->getParameter(paramNames[i], fa); + light.SetSpotFalloff(fa[0]); + } break; + case MHWRender::MLightParameterInformation::kCosConeAngle: { + MFloatArray fa; + lightParam->getParameter(paramNames[i], fa); + fa[0] = acos(fa[0]) * 57.295779506f; + light.SetSpotCutoff(fa[0]); + } break; + case MHWRender::MLightParameterInformation::kStartShadowParameters: + case MHWRender::MLightParameterInformation::kShadowBias: { + MFloatArray fa; + lightParam->getParameter(paramNames[i], fa); + } break; + case MHWRender::MLightParameterInformation::kShadowMapSize: + case MHWRender::MLightParameterInformation::kShadowViewProj: { + MMatrix value; + lightParam->getParameter(paramNames[i], value); + GfMatrix4d m(value.matrix); #if HDX_API_VERSION >= 6 - light.SetShadowMatrices({m}); + light.SetShadowMatrices({ m }); #else - light.SetShadowMatrix(m); + light.SetShadowMatrix(m); #endif - } - break; - case MHWRender::MLightParameterInformation::kShadowColor: - { - MFloatArray fa; - lightParam->getParameter(paramNames[i], fa); - if(fa.length() == 3) - { - GfVec4f c(fa[0], fa[1], fa[2], 1.0f); - } - } - break; - case MHWRender::MLightParameterInformation::kGlobalShadowOn: - case MHWRender::MLightParameterInformation::kShadowOn: - { - MIntArray ia; - lightParam->getParameter(paramNames[i], ia); - if(ia.length()) - light.SetHasShadow(ia[0]); - } - break; - default: - break; - } - } - - MStatus status; - MDagPath lightPath = lightParam->lightPath(&status); - if(status) - { - MMatrix wsm = lightPath.inclusiveMatrix(); - light.SetIsCameraSpaceLight(false); - GfMatrix4d tm(wsm.inverse().matrix); - light.SetTransform(tm); - } - else - { - light.SetIsCameraSpaceLight(true); - } - lights.push_back(light); - } - } - - auto getColour = [] (const MPlug& p) { - GfVec4f col(0, 0, 0, 1.0f); - MStatus status; - MPlug pr = p.child(0, &status); - if(status) col[0] = pr.asFloat(); - MPlug pg = p.child(1, &status); - if(status) col[1] = pg.asFloat(); - MPlug pb = p.child(2, &status); - if(status) col[2] = pb.asFloat(); - return col; - }; - - GlfSimpleMaterial material; - material.SetAmbient(getColour(ptr->m_shape->ambientPlug())); - material.SetDiffuse(getColour(ptr->m_shape->diffusePlug())); - material.SetSpecular(getColour(ptr->m_shape->specularPlug())); - material.SetEmission(getColour(ptr->m_shape->emissionPlug())); - material.SetShininess(ptr->m_shape->shininessPlug().asFloat()); - - GLint uboBinding = -1; - glGetIntegeri_v(GL_UNIFORM_BUFFER_BINDING, 4, &uboBinding); - - engine->SetLightingState(lights, material, GfVec4f(0.05f)); - glDepthFunc(GL_LESS); - - int originX, originY, width, height; - context.getViewportDimensions(originX, originY, width, height); - - engine->SetCameraState( - GfMatrix4d(context.getMatrix(MHWRender::MFrameContext::kViewMtx).matrix), - GfMatrix4d(context.getMatrix(MHWRender::MFrameContext::kProjectionMtx).matrix)); - engine->SetRenderViewport(GfVec4d(originX, originY, width, height)); - - engine->SetRootTransform(GfMatrix4d(ptr->m_objPath.inclusiveMatrix().matrix)); - - auto view = M3dView::active3dView(); - const auto& paths1 = ptr->m_shape->selectedPaths(); - const auto& paths2 = ptr->m_shape->selectionList().paths(); - SdfPathVector combined; - combined.reserve(paths1.size() + paths2.size()); - combined.insert(combined.end(), paths1.begin(), paths1.end()); - combined.insert(combined.end(), paths2.begin(), paths2.end()); - - ptr->m_params.frame = ptr->m_shape->outTimePlug().asMTime().as(MTime::uiUnit()); - engine->Render(ptr->m_rootPrim, ptr->m_params); - - if(combined.size()) - { - UsdImagingGLRenderParams params = ptr->m_params; - params.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME; - MColor colour = M3dView::leadColor(); - params.wireframeColor = GfVec4f(colour.r, colour.g, colour.b, 1.0f); - glDepthFunc(GL_LEQUAL); - // Geometry already rendered, can't offset it deeper. Push - // lines in front with negative offset. - glEnable(GL_POLYGON_OFFSET_LINE); - glPolygonOffset(-1.0, -1.0); - engine->RenderBatch(combined, params); - glDisable(GL_POLYGON_OFFSET_LINE); - } + } break; + case MHWRender::MLightParameterInformation::kShadowColor: { + MFloatArray fa; + lightParam->getParameter(paramNames[i], fa); + if (fa.length() == 3) { + GfVec4f c(fa[0], fa[1], fa[2], 1.0f); + } + } break; + case MHWRender::MLightParameterInformation::kGlobalShadowOn: + case MHWRender::MLightParameterInformation::kShadowOn: { + MIntArray ia; + lightParam->getParameter(paramNames[i], ia); + if (ia.length()) + light.SetHasShadow(ia[0]); + } break; + default: break; + } + } -#if defined(WANT_UFE_BUILD) - if (ArchHasEnv("MAYA_WANT_UFE_SELECTION")) - { - // Draw selection highlighting for all USD items in the UFE selection. - SdfPathVector ufePaths; - auto ufeSelList = Ufe::GlobalSelection::get(); - - Ufe::PathSegment proxyUfePath = ptr->m_shape->ufePathSegment(); - for (const auto& sceneItem : *ufeSelList) - { - if (sceneItem->runTimeId() == USD_UFE_RUNTIME_ID) - { - const Ufe::Path& itemPath = sceneItem->path(); - const Ufe::PathSegment& usdPathSegment = itemPath.getSegments().back(); - if (usdPathSegment.runTimeId() == USD_UFE_RUNTIME_ID - && itemPath.getSegments().size() == 2) - { - const Ufe::PathSegment& mayaPathSegment = itemPath.getSegments().front(); - if(mayaPathSegment == proxyUfePath) - { - ufePaths.emplace_back(usdPathSegment.string()); - } + MStatus status; + MDagPath lightPath = lightParam->lightPath(&status); + if (status) { + MMatrix wsm = lightPath.inclusiveMatrix(); + light.SetIsCameraSpaceLight(false); + GfMatrix4d tm(wsm.inverse().matrix); + light.SetTransform(tm); + } else { + light.SetIsCameraSpaceLight(true); } + lights.push_back(light); } } - if (!ufePaths.empty()) - { + + auto getColour = [](const MPlug& p) { + GfVec4f col(0, 0, 0, 1.0f); + MStatus status; + MPlug pr = p.child(0, &status); + if (status) + col[0] = pr.asFloat(); + MPlug pg = p.child(1, &status); + if (status) + col[1] = pg.asFloat(); + MPlug pb = p.child(2, &status); + if (status) + col[2] = pb.asFloat(); + return col; + }; + + GlfSimpleMaterial material; + material.SetAmbient(getColour(ptr->m_shape->ambientPlug())); + material.SetDiffuse(getColour(ptr->m_shape->diffusePlug())); + material.SetSpecular(getColour(ptr->m_shape->specularPlug())); + material.SetEmission(getColour(ptr->m_shape->emissionPlug())); + material.SetShininess(ptr->m_shape->shininessPlug().asFloat()); + + GLint uboBinding = -1; + glGetIntegeri_v(GL_UNIFORM_BUFFER_BINDING, 4, &uboBinding); + + engine->SetLightingState(lights, material, GfVec4f(0.05f)); + glDepthFunc(GL_LESS); + + int originX, originY, width, height; + context.getViewportDimensions(originX, originY, width, height); + + engine->SetCameraState( + GfMatrix4d(context.getMatrix(MHWRender::MFrameContext::kViewMtx).matrix), + GfMatrix4d(context.getMatrix(MHWRender::MFrameContext::kProjectionMtx).matrix)); + engine->SetRenderViewport(GfVec4d(originX, originY, width, height)); + + engine->SetRootTransform(GfMatrix4d(ptr->m_objPath.inclusiveMatrix().matrix)); + + auto view = M3dView::active3dView(); + const auto& paths1 = ptr->m_shape->selectedPaths(); + const auto& paths2 = ptr->m_shape->selectionList().paths(); + SdfPathVector combined; + combined.reserve(paths1.size() + paths2.size()); + combined.insert(combined.end(), paths1.begin(), paths1.end()); + combined.insert(combined.end(), paths2.begin(), paths2.end()); + + ptr->m_params.frame = ptr->m_shape->outTimePlug().asMTime().as(MTime::uiUnit()); + engine->Render(ptr->m_rootPrim, ptr->m_params); + + if (combined.size()) { UsdImagingGLRenderParams params = ptr->m_params; params.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME; - MColor colour = M3dView::leadColor(); // Maya selection color + MColor colour = M3dView::leadColor(); params.wireframeColor = GfVec4f(colour.r, colour.g, colour.b, 1.0f); glDepthFunc(GL_LEQUAL); // Geometry already rendered, can't offset it deeper. Push // lines in front with negative offset. glEnable(GL_POLYGON_OFFSET_LINE); glPolygonOffset(-1.0, -1.0); - engine->RenderBatch(ufePaths, params); + engine->RenderBatch(combined, params); glDisable(GL_POLYGON_OFFSET_LINE); } - } + +#if defined(WANT_UFE_BUILD) + if (ArchHasEnv("MAYA_WANT_UFE_SELECTION")) { + // Draw selection highlighting for all USD items in the UFE selection. + SdfPathVector ufePaths; + auto ufeSelList = Ufe::GlobalSelection::get(); + + Ufe::PathSegment proxyUfePath = ptr->m_shape->ufePathSegment(); + for (const auto& sceneItem : *ufeSelList) { + if (sceneItem->runTimeId() == USD_UFE_RUNTIME_ID) { + const Ufe::Path& itemPath = sceneItem->path(); + const Ufe::PathSegment& usdPathSegment = itemPath.getSegments().back(); + if (usdPathSegment.runTimeId() == USD_UFE_RUNTIME_ID + && itemPath.getSegments().size() == 2) { + const Ufe::PathSegment& mayaPathSegment = itemPath.getSegments().front(); + if (mayaPathSegment == proxyUfePath) { + ufePaths.emplace_back(usdPathSegment.string()); + } + } + } + } + if (!ufePaths.empty()) { + UsdImagingGLRenderParams params = ptr->m_params; + params.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME; + MColor colour = M3dView::leadColor(); // Maya selection color + params.wireframeColor = GfVec4f(colour.r, colour.g, colour.b, 1.0f); + glDepthFunc(GL_LEQUAL); + // Geometry already rendered, can't offset it deeper. Push + // lines in front with negative offset. + glEnable(GL_POLYGON_OFFSET_LINE); + glPolygonOffset(-1.0, -1.0); + engine->RenderBatch(ufePaths, params); + glDisable(GL_POLYGON_OFFSET_LINE); + } + } #endif - // HACK: Maya doesn't restore this ONE buffer binding after our override is done so we have to do it for them. - glBindBufferBase(GL_UNIFORM_BUFFER, 4, uboBinding); + // HACK: Maya doesn't restore this ONE buffer binding after our override is done so we have + // to do it for them. + glBindBufferBase(GL_UNIFORM_BUFFER, 4, uboBinding); - stateManager->setDepthStencilState(previousDepthState); - MHWRender::MStateManager::releaseDepthStencilState(depthState); + stateManager->setDepthStencilState(previousDepthState); + MHWRender::MStateManager::releaseDepthStencilState(depthState); - // Check framestamp b/c we don't want to put multiple refresh commands - // on the idle queue for a single frame-render... especially if we have - // multiple ProxyShapes... - if (!engine->IsConverged() && context.getFrameStamp() != s_lastRefreshFrameStamp) - { - s_lastRefreshFrameStamp = context.getFrameStamp(); - // Force another refresh of the current viewport - MGlobal::executeCommandOnIdle("refresh -cv -f"); + // Check framestamp b/c we don't want to put multiple refresh commands + // on the idle queue for a single frame-render... especially if we have + // multiple ProxyShapes... + if (!engine->IsConverged() && context.getFrameStamp() != s_lastRefreshFrameStamp) { + s_lastRefreshFrameStamp = context.getFrameStamp(); + // Force another refresh of the current viewport + MGlobal::executeCommandOnIdle("refresh -cv -f"); + } } - } - glClearColor(clearCol[0], clearCol[1], clearCol[2], clearCol[3]); + glClearColor(clearCol[0], clearCol[1], clearCol[2], clearCol[3]); } //---------------------------------------------------------------------------------------------------------------------- ProxyShape* ProxyDrawOverride::getShape(const MDagPath& objPath) { - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::getShape\n"); - MObject obj = objPath.node(); - MFnDependencyNode dnNode(obj); - if(obj.apiType() != MFn::kPluginShape) - { - return 0; - } - return static_cast(dnNode.userNode()); + TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyDrawOverride::getShape\n"); + MObject obj = objPath.node(); + MFnDependencyNode dnNode(obj); + if (obj.apiType() != MFn::kPluginShape) { + return 0; + } + return static_cast(dnNode.userNode()); } //---------------------------------------------------------------------------------------------------------------------- class ProxyDrawOverrideSelectionHelper { public: - - static SdfPath path_ting(const SdfPath& a, const SdfPath& b, const int c) - { - m_paths.push_back(a); - return a; - } - static SdfPathVector m_paths; + static SdfPath path_ting(const SdfPath& a, const SdfPath& b, const int c) + { + m_paths.push_back(a); + return a; + } + static SdfPathVector m_paths; }; SdfPathVector ProxyDrawOverrideSelectionHelper::m_paths; - #if MAYA_API_VERSION >= 20180600 //---------------------------------------------------------------------------------------------------------------------- bool ProxyDrawOverride::userSelect( const MHWRender::MSelectionInfo& selectInfo, - const MHWRender::MDrawContext& context, - const MDagPath& objPath, - const MUserData* data, - MSelectionList& selectionList, - MPointArray& worldSpaceHitPts) + const MHWRender::MDrawContext& context, + const MDagPath& objPath, + const MUserData* data, + MSelectionList& selectionList, + MPointArray& worldSpaceHitPts) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyDrawOverride::userSelect\n"); - - MString fullSelPath = objPath.fullPathName(); - - if(!MGlobal::optionVarIntValue("AL_usdmaya_selectionEnabled")) - return false; - - MString selectionMaskName(ProxyShape::s_selectionMaskName); - MSelectionMask mask(selectionMaskName); - if (!selectInfo.selectable(mask)) - return false; - - MStatus status; - MMatrix worldViewMatrix = context.getMatrix( - MHWRender::MFrameContext::kWorldViewMtx, &status); - if (status != MStatus::kSuccess) return false; - - MMatrix projectionMatrix = context.getMatrix( - MHWRender::MFrameContext::kProjectionMtx, &status); - if (status != MStatus::kSuccess) return false; - - // Compute a pick matrix that, when it is post-multiplied with the projection - // matrix, will cause the picking region to fill the entire viewport for - // OpenGL selection. - { - int view_x, view_y, view_w, view_h; - context.getViewportDimensions(view_x, view_y, view_w, view_h); - - unsigned int sel_x, sel_y, sel_w, sel_h; - selectInfo.selectRect(sel_x, sel_y, sel_w, sel_h); - - double center_x = sel_x + sel_w * 0.5; - double center_y = sel_y + sel_h * 0.5; - - MMatrix pickMatrix; - pickMatrix[0][0] = view_w / double(sel_w); - pickMatrix[1][1] = view_h / double(sel_h); - pickMatrix[3][0] = (view_w - 2.0 * (center_x - view_x)) / double(sel_w); - pickMatrix[3][1] = (view_h - 2.0 * (center_y - view_y)) / double(sel_h); - - projectionMatrix *= pickMatrix; - } - - // Get world to local matrix - MMatrix invMatrix = objPath.inclusiveMatrixInverse(); - GfMatrix4d worldToLocalSpace(invMatrix.matrix); - - - auto* proxyShape = static_cast(getShape(objPath)); - auto engine = proxyShape->engine(); - if (!engine) return false; - - // The commands we execute inside this function shouldn't do special - // processing of the proxy we are currently handling here if they - // should run across it. - proxyShape->m_pleaseIgnoreSelection = true; - - UsdImagingGLRenderParams params; - // Mostly want to get render params to set renderGuides/proxyGuides/etc - proxyShape->getRenderAttris(params, context, objPath); - - UsdPrim root = proxyShape->getUsdStage()->GetPseudoRoot(); - - Engine::HitBatch hitBatch; - SdfPathVector rootPath; - rootPath.push_back(root.GetPath()); - - int resolution = 10; - MGlobal::getOptionVarValue("AL_usdmaya_selectResolution", resolution); - if (resolution < 10) { resolution = 10; } - if (resolution > 1024) { resolution = 1024; } - - - bool hitSelected = engine->TestIntersectionBatch( - GfMatrix4d(worldViewMatrix.matrix), - GfMatrix4d(projectionMatrix.matrix), - worldToLocalSpace, - rootPath, - params, - resolution, - ProxyDrawOverrideSelectionHelper::path_ting, - &hitBatch); - - auto selected = false; - - auto addSelection = [&hitBatch, &selectionList, - &worldSpaceHitPts, proxyShape, &selected] - (const MString& command) - { - selected = true; - MStringArray nodes; - MGlobal::executeCommand(command, nodes, false, true); - - for(const auto& it : hitBatch) - { - auto path = it.first; - auto obj = proxyShape->findRequiredPath(path); - if (obj != MObject::kNullObj) - { - MFnDagNode dagNode(obj); - MDagPath dg; - dagNode.getPath(dg); - const double* p = it.second.worldSpaceHitPoint.GetArray(); - - selectionList.add(dg); - worldSpaceHitPts.append(MPoint(p[0], p[1], p[2])); - } - } - }; - - // Maya determines the selection list adjustment mode by Ctrl/Shift modifiers. - int modifiers = 0; - MGlobal::executeCommand("getModifiers", modifiers); - - const bool shiftHeld = (modifiers % 2); - const bool ctrlHeld = (modifiers / 4 % 2); - - MGlobal::ListAdjustment listAdjustment = MGlobal::kReplaceList; - if (shiftHeld && ctrlHeld) - { - listAdjustment = MGlobal::kAddToList; - } - else if (ctrlHeld) - { - listAdjustment = MGlobal::kRemoveFromList; - } - else if (shiftHeld) - { - listAdjustment = MGlobal::kXORWithList; - } - - // Currently we have two approaches to selection. One method works with undo (but does not - // play nicely with maya geometry). The second method doesn't work with undo, but does play - // nicely with maya geometry. - const int selectionMode = MGlobal::optionVarIntValue("AL_usdmaya_selectMode"); - if(1 == selectionMode) - { - if(hitSelected) + TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyDrawOverride::userSelect\n"); + + MString fullSelPath = objPath.fullPathName(); + + if (!MGlobal::optionVarIntValue("AL_usdmaya_selectionEnabled")) + return false; + + MString selectionMaskName(ProxyShape::s_selectionMaskName); + MSelectionMask mask(selectionMaskName); + if (!selectInfo.selectable(mask)) + return false; + + MStatus status; + MMatrix worldViewMatrix = context.getMatrix(MHWRender::MFrameContext::kWorldViewMtx, &status); + if (status != MStatus::kSuccess) + return false; + + MMatrix projectionMatrix = context.getMatrix(MHWRender::MFrameContext::kProjectionMtx, &status); + if (status != MStatus::kSuccess) + return false; + + // Compute a pick matrix that, when it is post-multiplied with the projection + // matrix, will cause the picking region to fill the entire viewport for + // OpenGL selection. { - MString command = "AL_usdmaya_ProxyShapeSelect"; - switch(listAdjustment) - { - case MGlobal::kReplaceList: command += " -r"; break; - case MGlobal::kRemoveFromList: command += " -d"; break; - case MGlobal::kXORWithList: command += " -tgl"; break; - case MGlobal::kAddToList: command += " -a"; break; - case MGlobal::kAddToHeadOfList: /* should never get here */ break; - } - - for(const auto& it : hitBatch) - { - auto path = it.first; - command += " -pp \""; - command += path.GetText(); - command += "\""; - } - - command += " \""; - command += fullSelPath; - command += "\""; - MGlobal::executeCommandOnIdle(command, false); + int view_x, view_y, view_w, view_h; + context.getViewportDimensions(view_x, view_y, view_w, view_h); + + unsigned int sel_x, sel_y, sel_w, sel_h; + selectInfo.selectRect(sel_x, sel_y, sel_w, sel_h); + + double center_x = sel_x + sel_w * 0.5; + double center_y = sel_y + sel_h * 0.5; + + MMatrix pickMatrix; + pickMatrix[0][0] = view_w / double(sel_w); + pickMatrix[1][1] = view_h / double(sel_h); + pickMatrix[3][0] = (view_w - 2.0 * (center_x - view_x)) / double(sel_w); + pickMatrix[3][1] = (view_h - 2.0 * (center_y - view_y)) / double(sel_h); + + projectionMatrix *= pickMatrix; } - else - { - MString command = "AL_usdmaya_ProxyShapeSelect -cl "; - command += " \""; - command += fullSelPath; - command += "\""; - MGlobal::executeCommandOnIdle(command, false); + + // Get world to local matrix + MMatrix invMatrix = objPath.inclusiveMatrixInverse(); + GfMatrix4d worldToLocalSpace(invMatrix.matrix); + + auto* proxyShape = static_cast(getShape(objPath)); + auto engine = proxyShape->engine(); + if (!engine) + return false; + + // The commands we execute inside this function shouldn't do special + // processing of the proxy we are currently handling here if they + // should run across it. + proxyShape->m_pleaseIgnoreSelection = true; + + UsdImagingGLRenderParams params; + // Mostly want to get render params to set renderGuides/proxyGuides/etc + proxyShape->getRenderAttris(params, context, objPath); + + UsdPrim root = proxyShape->getUsdStage()->GetPseudoRoot(); + + Engine::HitBatch hitBatch; + SdfPathVector rootPath; + rootPath.push_back(root.GetPath()); + + int resolution = 10; + MGlobal::getOptionVarValue("AL_usdmaya_selectResolution", resolution); + if (resolution < 10) { + resolution = 10; } - } - else - { - SdfPathVector paths; - if (!hitBatch.empty()) - { - paths.reserve(hitBatch.size()); - - auto addHit = [&paths](Engine::HitBatch::const_reference& it) - { - paths.push_back(it.first); - }; - - // Due to the inaccuracies in the selection method in gl engine - // we still need to find the closest selection. - // Around the edges it often selects two or more prims. - if (selectInfo.singleSelection()) - { - auto closestHit = hitBatch.cbegin(); - - if (hitBatch.size() > 1) - { - MDagPath cameraPath; - M3dView::active3dView().getCamera(cameraPath); - const auto cameraPoint = cameraPath.inclusiveMatrix() * MPoint(0.0, 0.0, 0.0, 1.0); - auto distanceToCameraSq = [&cameraPoint] (Engine::HitBatch::const_reference& it) -> double - { - const auto dx = cameraPoint.x - it.second.worldSpaceHitPoint[0]; - const auto dy = cameraPoint.y - it.second.worldSpaceHitPoint[1]; - const auto dz = cameraPoint.z - it.second.worldSpaceHitPoint[2]; - return dx * dx + dy * dy + dz * dz; - }; - - auto closestDistance = distanceToCameraSq(*closestHit); - for (auto it = ++hitBatch.cbegin(), itEnd = hitBatch.cend(); it != itEnd; ++it) - { - const auto currentDistance = distanceToCameraSq(*it); - if (currentDistance < closestDistance) - { - closestDistance = currentDistance; - closestHit = it; - } - } - } - addHit(*closestHit); - } - else - { - for (const auto& it : hitBatch) - { - addHit(it); - } - } + if (resolution > 1024) { + resolution = 1024; } -#if defined(WANT_UFE_BUILD) - if (ArchHasEnv("MAYA_WANT_UFE_SELECTION")) - { - // Get the Hierarchy Handler of USD - Id = 2 - Ufe::HierarchyHandler::Ptr handler = - Ufe::RunTimeMgr::instance().hierarchyHandler(2); - if (handler == nullptr) - { - MGlobal::displayError("USD Hierarchy handler has not been loaded - Picking is not possible"); - return false; - } - - if (paths.size()) - { - auto globalSelection = Ufe::GlobalSelection::get(); - - for (const auto& it : paths) - { - // Build a path segment of the USD picked object - Ufe::PathSegment ps_usd(it.GetText(), 2, '/'); - - // Create a sceneItem - const Ufe::SceneItem::Ptr& si{ handler->createItem(proxyShape->ufePath() + ps_usd) }; - - switch (listAdjustment) - { - case MGlobal::kReplaceList: - // The list has been cleared before viewport selection runs, so we - // can add the new hits directly. UFE selection list is a superset - // of Maya selection list, calling clear()/replaceWith() on UFE - // selection list would clear Maya selection list. - globalSelection->append(si); - break; - case MGlobal::kAddToList: - globalSelection->append(si); - break; - case MGlobal::kRemoveFromList: - globalSelection->remove(si); - break; - case MGlobal::kXORWithList: - if (!globalSelection->remove(si)) - { - globalSelection->append(si); + bool hitSelected = engine->TestIntersectionBatch( + GfMatrix4d(worldViewMatrix.matrix), + GfMatrix4d(projectionMatrix.matrix), + worldToLocalSpace, + rootPath, + params, + resolution, + ProxyDrawOverrideSelectionHelper::path_ting, + &hitBatch); + + auto selected = false; + + auto addSelection = [&hitBatch, &selectionList, &worldSpaceHitPts, proxyShape, &selected]( + const MString& command) { + selected = true; + MStringArray nodes; + MGlobal::executeCommand(command, nodes, false, true); + + for (const auto& it : hitBatch) { + auto path = it.first; + auto obj = proxyShape->findRequiredPath(path); + if (obj != MObject::kNullObj) { + MFnDagNode dagNode(obj); + MDagPath dg; + dagNode.getPath(dg); + const double* p = it.second.worldSpaceHitPoint.GetArray(); + + selectionList.add(dg); + worldSpaceHitPts.append(MPoint(p[0], p[1], p[2])); } - break; - case MGlobal::kAddToHeadOfList: - // No such operation on UFE selection. - UFE_LOG("UFE does not support prepend to selection."); - break; - } } - } + }; + + // Maya determines the selection list adjustment mode by Ctrl/Shift modifiers. + int modifiers = 0; + MGlobal::executeCommand("getModifiers", modifiers); + + const bool shiftHeld = (modifiers % 2); + const bool ctrlHeld = (modifiers / 4 % 2); + + MGlobal::ListAdjustment listAdjustment = MGlobal::kReplaceList; + if (shiftHeld && ctrlHeld) { + listAdjustment = MGlobal::kAddToList; + } else if (ctrlHeld) { + listAdjustment = MGlobal::kRemoveFromList; + } else if (shiftHeld) { + listAdjustment = MGlobal::kXORWithList; } - else - { -#endif - switch (listAdjustment) - { - case MGlobal::kReplaceList: - { - MString command; - if(!proxyShape->selectedPaths().empty()) - { - command = "AL_usdmaya_ProxyShapeSelect -i -cl "; - command += " \""; - command += fullSelPath; - command += "\";"; - } - if(!paths.empty()) - { - command += "AL_usdmaya_ProxyShapeSelect -i -a "; - for(const auto& it : paths) - { - command += " -pp \""; - command += it.GetText(); - command += "\""; - } - command += " \""; - command += fullSelPath; - command += "\""; + // Currently we have two approaches to selection. One method works with undo (but does not + // play nicely with maya geometry). The second method doesn't work with undo, but does play + // nicely with maya geometry. + const int selectionMode = MGlobal::optionVarIntValue("AL_usdmaya_selectMode"); + if (1 == selectionMode) { + if (hitSelected) { + MString command = "AL_usdmaya_ProxyShapeSelect"; + switch (listAdjustment) { + case MGlobal::kReplaceList: command += " -r"; break; + case MGlobal::kRemoveFromList: command += " -d"; break; + case MGlobal::kXORWithList: command += " -tgl"; break; + case MGlobal::kAddToList: command += " -a"; break; + case MGlobal::kAddToHeadOfList: /* should never get here */ break; + } - } + for (const auto& it : hitBatch) { + auto path = it.first; + command += " -pp \""; + command += path.GetText(); + command += "\""; + } - if(command.length() > 0) - { - addSelection(command); - } - } - break; - - case MGlobal::kAddToHeadOfList: - case MGlobal::kAddToList: - { - MString command; - if(paths.size()) - { - command = "AL_usdmaya_ProxyShapeSelect -i -a "; - for(const auto& it : paths) - { - command += " -pp \""; - command += it.GetText(); + command += " \""; + command += fullSelPath; command += "\""; - } - command += " \""; - command += fullSelPath; - command += "\""; - } - - if(command.length() > 0) - { - selected = true; - addSelection(command); - } - } - break; - - case MGlobal::kRemoveFromList: - { - if(!proxyShape->selectedPaths().empty() && paths.size()) - { - MString command = "AL_usdmaya_ProxyShapeSelect -d "; - for(const auto& it : paths) - { - command += " -pp \""; - command += it.GetText(); + MGlobal::executeCommandOnIdle(command, false); + } else { + MString command = "AL_usdmaya_ProxyShapeSelect -cl "; + command += " \""; + command += fullSelPath; command += "\""; - } - command += " \""; - command += fullSelPath; - command += "\""; - MGlobal::executeCommandOnIdle(command, false); + MGlobal::executeCommandOnIdle(command, false); } - } - break; - - case MGlobal::kXORWithList: - { - auto& slpaths = proxyShape->selectedPaths(); - bool hasSelectedItems = false; - bool hasDeletedItems = false; - - MString selectcommand = "AL_usdmaya_ProxyShapeSelect -i -a "; - MString deselectcommand = "AL_usdmaya_ProxyShapeSelect -d "; - for(const auto& it : paths) - { - bool flag = false; - for(auto sit : slpaths) - { - if(sit == it) - { - flag = true; - break; + } else { + SdfPathVector paths; + if (!hitBatch.empty()) { + paths.reserve(hitBatch.size()); + + auto addHit + = [&paths](Engine::HitBatch::const_reference& it) { paths.push_back(it.first); }; + + // Due to the inaccuracies in the selection method in gl engine + // we still need to find the closest selection. + // Around the edges it often selects two or more prims. + if (selectInfo.singleSelection()) { + auto closestHit = hitBatch.cbegin(); + + if (hitBatch.size() > 1) { + MDagPath cameraPath; + M3dView::active3dView().getCamera(cameraPath); + const auto cameraPoint + = cameraPath.inclusiveMatrix() * MPoint(0.0, 0.0, 0.0, 1.0); + auto distanceToCameraSq + = [&cameraPoint](Engine::HitBatch::const_reference& it) -> double { + const auto dx = cameraPoint.x - it.second.worldSpaceHitPoint[0]; + const auto dy = cameraPoint.y - it.second.worldSpaceHitPoint[1]; + const auto dz = cameraPoint.z - it.second.worldSpaceHitPoint[2]; + return dx * dx + dy * dy + dz * dz; + }; + + auto closestDistance = distanceToCameraSq(*closestHit); + for (auto it = ++hitBatch.cbegin(), itEnd = hitBatch.cend(); it != itEnd; + ++it) { + const auto currentDistance = distanceToCameraSq(*it); + if (currentDistance < closestDistance) { + closestDistance = currentDistance; + closestHit = it; + } + } + } + addHit(*closestHit); + } else { + for (const auto& it : hitBatch) { + addHit(it); + } } - } - if(flag) - { - deselectcommand += " -pp \""; - deselectcommand += it.GetText(); - deselectcommand += "\""; - hasDeletedItems = true; - } - else - { - selectcommand += " -pp \""; - selectcommand += it.GetText(); - selectcommand += "\""; - hasSelectedItems = true; - } - } - selectcommand += " \""; - selectcommand += fullSelPath; - selectcommand += "\""; - deselectcommand += " \""; - deselectcommand += fullSelPath; - deselectcommand += "\""; - - if(hasSelectedItems) - { - addSelection(selectcommand); } - if(hasDeletedItems) - { - MGlobal::executeCommandOnIdle(deselectcommand, false); - } - } - break; - } - - MString final_command = "AL_usdmaya_ProxyShapePostSelect \""; - final_command += fullSelPath; - final_command += "\""; - proxyShape->setChangedSelectionState(true); - MGlobal::executeCommandOnIdle(final_command, false); #if defined(WANT_UFE_BUILD) - } // else MAYA_WANT_UFE_SELECTION + if (ArchHasEnv("MAYA_WANT_UFE_SELECTION")) { + // Get the Hierarchy Handler of USD - Id = 2 + Ufe::HierarchyHandler::Ptr handler = Ufe::RunTimeMgr::instance().hierarchyHandler(2); + if (handler == nullptr) { + MGlobal::displayError( + "USD Hierarchy handler has not been loaded - Picking is not possible"); + return false; + } + + if (paths.size()) { + auto globalSelection = Ufe::GlobalSelection::get(); + + for (const auto& it : paths) { + // Build a path segment of the USD picked object + Ufe::PathSegment ps_usd(it.GetText(), 2, '/'); + + // Create a sceneItem + const Ufe::SceneItem::Ptr& si { handler->createItem( + proxyShape->ufePath() + ps_usd) }; + + switch (listAdjustment) { + case MGlobal::kReplaceList: + // The list has been cleared before viewport selection runs, so we + // can add the new hits directly. UFE selection list is a superset + // of Maya selection list, calling clear()/replaceWith() on UFE + // selection list would clear Maya selection list. + globalSelection->append(si); + break; + case MGlobal::kAddToList: globalSelection->append(si); break; + case MGlobal::kRemoveFromList: globalSelection->remove(si); break; + case MGlobal::kXORWithList: + if (!globalSelection->remove(si)) { + globalSelection->append(si); + } + break; + case MGlobal::kAddToHeadOfList: + // No such operation on UFE selection. + UFE_LOG("UFE does not support prepend to selection."); + break; + } + } + } + } else { #endif - } + switch (listAdjustment) { + case MGlobal::kReplaceList: { + MString command; + if (!proxyShape->selectedPaths().empty()) { + command = "AL_usdmaya_ProxyShapeSelect -i -cl "; + command += " \""; + command += fullSelPath; + command += "\";"; + } + + if (!paths.empty()) { + command += "AL_usdmaya_ProxyShapeSelect -i -a "; + for (const auto& it : paths) { + command += " -pp \""; + command += it.GetText(); + command += "\""; + } + command += " \""; + command += fullSelPath; + command += "\""; + } + + if (command.length() > 0) { + addSelection(command); + } + } break; + + case MGlobal::kAddToHeadOfList: + case MGlobal::kAddToList: { + MString command; + if (paths.size()) { + command = "AL_usdmaya_ProxyShapeSelect -i -a "; + for (const auto& it : paths) { + command += " -pp \""; + command += it.GetText(); + command += "\""; + } + command += " \""; + command += fullSelPath; + command += "\""; + } + + if (command.length() > 0) { + selected = true; + addSelection(command); + } + } break; + + case MGlobal::kRemoveFromList: { + if (!proxyShape->selectedPaths().empty() && paths.size()) { + MString command = "AL_usdmaya_ProxyShapeSelect -d "; + for (const auto& it : paths) { + command += " -pp \""; + command += it.GetText(); + command += "\""; + } + command += " \""; + command += fullSelPath; + command += "\""; + MGlobal::executeCommandOnIdle(command, false); + } + } break; + + case MGlobal::kXORWithList: { + auto& slpaths = proxyShape->selectedPaths(); + bool hasSelectedItems = false; + bool hasDeletedItems = false; + + MString selectcommand = "AL_usdmaya_ProxyShapeSelect -i -a "; + MString deselectcommand = "AL_usdmaya_ProxyShapeSelect -d "; + for (const auto& it : paths) { + bool flag = false; + for (auto sit : slpaths) { + if (sit == it) { + flag = true; + break; + } + } + if (flag) { + deselectcommand += " -pp \""; + deselectcommand += it.GetText(); + deselectcommand += "\""; + hasDeletedItems = true; + } else { + selectcommand += " -pp \""; + selectcommand += it.GetText(); + selectcommand += "\""; + hasSelectedItems = true; + } + } + selectcommand += " \""; + selectcommand += fullSelPath; + selectcommand += "\""; + deselectcommand += " \""; + deselectcommand += fullSelPath; + deselectcommand += "\""; + + if (hasSelectedItems) { + addSelection(selectcommand); + } + + if (hasDeletedItems) { + MGlobal::executeCommandOnIdle(deselectcommand, false); + } + } break; + } + + MString final_command = "AL_usdmaya_ProxyShapePostSelect \""; + final_command += fullSelPath; + final_command += "\""; + proxyShape->setChangedSelectionState(true); + MGlobal::executeCommandOnIdle(final_command, false); +#if defined(WANT_UFE_BUILD) + } // else MAYA_WANT_UFE_SELECTION +#endif + } + + ProxyDrawOverrideSelectionHelper::m_paths.clear(); - ProxyDrawOverrideSelectionHelper::m_paths.clear(); + // We are done executing commands that needed to handle our current + // proxy as a special case. Unset the ignore state on the proxy. + proxyShape->m_pleaseIgnoreSelection = false; - // We are done executing commands that needed to handle our current - // proxy as a special case. Unset the ignore state on the proxy. - proxyShape->m_pleaseIgnoreSelection = false; - - return selected; + return selected; } #endif //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyDrawOverride.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyDrawOverride.h index c7dd8b72cb..293cef2c60 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyDrawOverride.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyDrawOverride.h @@ -17,11 +17,11 @@ #include "AL/usdmaya/Api.h" -#include - #include #include +#include + PXR_NAMESPACE_USING_DIRECTIVE namespace AL { @@ -44,97 +44,92 @@ class ProxyDrawOverride : public MHWRender::MPxDrawOverride #endif { public: - - /// \brief ctor - /// \param obj the object this override will be rendering - ProxyDrawOverride(const MObject& obj); - - /// \brief dtor - ~ProxyDrawOverride(); - - /// \brief static creator method - /// \param obj the handle to pass to the constructor - /// \return the new draw override instance - AL_USDMAYA_PUBLIC - static MHWRender::MPxDrawOverride* creator(const MObject& obj); - - /// \brief Called by Maya to determine if the drawable object is bounded or not. - /// \param objPath The path to the object being drawn - /// \param cameraPath The path to the camera that is being used to draw - /// \return true if the object is bounded - bool isBounded( - const MDagPath& objPath, - const MDagPath& cameraPath) const override; - - /// \brief Called by Maya whenever the bounding box of the drawable object is needed. - /// \param objPath The path to the object being drawn - /// \param cameraPath The path to the camera that is being used to draw - /// \return the objects bounding box - MBoundingBox boundingBox( - const MDagPath& objPath, - const MDagPath& cameraPath) const override; - - /// \brief Called by Maya whenever the object is dirty and needs to update for draw. - /// \param objPath The path to the object being drawn - /// \param cameraPath The path to the camera that is being used to draw - /// \param frameContext Frame level context information - /// \param oldData Data cached by the previous draw of the instance - /// \return Pointer to data to be passed to the draw callback method - MUserData* prepareForDraw( - const MDagPath& objPath, - const MDagPath& cameraPath, - const MHWRender::MFrameContext& frameContext, - MUserData* oldData) override; - - /// \brief draw classification string for this override - AL_USDMAYA_PUBLIC - static MString kDrawDbClassification; - - /// \brief draw registration id for this override - AL_USDMAYA_PUBLIC - static MString kDrawRegistrantId; - - /// \brief The draw callback, performs the actual rendering for the draw override. - /// \param context the current draw context - /// \param data the user data generated om the prepareForDraw method - AL_USDMAYA_PUBLIC - static void draw(const MHWRender::MDrawContext& context, const MUserData* data); - - /// \brief utility function to get a pointer to the proxy shape node given the specified path - /// \param objPath the path to the shape you wish to query - /// \return returns a pointer to the proxy shape node at the path (or null if not found) - AL_USDMAYA_PUBLIC - static ProxyShape* getShape(const MDagPath& objPath); - - /// \brief We support the legacy and VP2 core profile rendering. - /// \return MHWRender::kOpenGL | MHWRender::kOpenGLCoreProfile - MHWRender::DrawAPI supportedDrawAPIs() const override - { return MHWRender::kOpenGL | MHWRender::kOpenGLCoreProfile; } - - /// \brief ensure this draw override participates in post fx - /// \return false - bool excludedFromPostEffects() const override - { return false; } + /// \brief ctor + /// \param obj the object this override will be rendering + ProxyDrawOverride(const MObject& obj); + + /// \brief dtor + ~ProxyDrawOverride(); + + /// \brief static creator method + /// \param obj the handle to pass to the constructor + /// \return the new draw override instance + AL_USDMAYA_PUBLIC + static MHWRender::MPxDrawOverride* creator(const MObject& obj); + + /// \brief Called by Maya to determine if the drawable object is bounded or not. + /// \param objPath The path to the object being drawn + /// \param cameraPath The path to the camera that is being used to draw + /// \return true if the object is bounded + bool isBounded(const MDagPath& objPath, const MDagPath& cameraPath) const override; + + /// \brief Called by Maya whenever the bounding box of the drawable object is needed. + /// \param objPath The path to the object being drawn + /// \param cameraPath The path to the camera that is being used to draw + /// \return the objects bounding box + MBoundingBox boundingBox(const MDagPath& objPath, const MDagPath& cameraPath) const override; + + /// \brief Called by Maya whenever the object is dirty and needs to update for draw. + /// \param objPath The path to the object being drawn + /// \param cameraPath The path to the camera that is being used to draw + /// \param frameContext Frame level context information + /// \param oldData Data cached by the previous draw of the instance + /// \return Pointer to data to be passed to the draw callback method + MUserData* prepareForDraw( + const MDagPath& objPath, + const MDagPath& cameraPath, + const MHWRender::MFrameContext& frameContext, + MUserData* oldData) override; + + /// \brief draw classification string for this override + AL_USDMAYA_PUBLIC + static MString kDrawDbClassification; + + /// \brief draw registration id for this override + AL_USDMAYA_PUBLIC + static MString kDrawRegistrantId; + + /// \brief The draw callback, performs the actual rendering for the draw override. + /// \param context the current draw context + /// \param data the user data generated om the prepareForDraw method + AL_USDMAYA_PUBLIC + static void draw(const MHWRender::MDrawContext& context, const MUserData* data); + + /// \brief utility function to get a pointer to the proxy shape node given the specified path + /// \param objPath the path to the shape you wish to query + /// \return returns a pointer to the proxy shape node at the path (or null if not found) + AL_USDMAYA_PUBLIC + static ProxyShape* getShape(const MDagPath& objPath); + + /// \brief We support the legacy and VP2 core profile rendering. + /// \return MHWRender::kOpenGL | MHWRender::kOpenGLCoreProfile + MHWRender::DrawAPI supportedDrawAPIs() const override + { + return MHWRender::kOpenGL | MHWRender::kOpenGLCoreProfile; + } + + /// \brief ensure this draw override participates in post fx + /// \return false + bool excludedFromPostEffects() const override { return false; } private: - static MUint64 s_lastRefreshFrameStamp; - + static MUint64 s_lastRefreshFrameStamp; + #if MAYA_API_VERSION >= 20180600 - bool wantUserSelection() const override {return true;} - - bool userSelect( - const MHWRender::MSelectionInfo& selectInfo, - const MHWRender::MDrawContext& context, - const MDagPath& objPath, - const MUserData* data, - MSelectionList& selectionList, - MPointArray& worldSpaceHitPts) override; + bool wantUserSelection() const override { return true; } + + bool userSelect( + const MHWRender::MSelectionInfo& selectInfo, + const MHWRender::MDrawContext& context, + const MDagPath& objPath, + const MUserData* data, + MSelectionList& selectionList, + MPointArray& worldSpaceHitPts) override; #endif - }; //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShape.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShape.cpp index 567eb702a4..cf3aba2ea8 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShape.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShape.cpp @@ -20,24 +20,15 @@ */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - #include "AL/maya/utils/Utils.h" - -#include "AL/usdmaya/cmds/ProxyShapePostLoadProcess.h" +#include "AL/usd/transaction/TransactionManager.h" #include "AL/usdmaya/CodeTimings.h" #include "AL/usdmaya/Global.h" #include "AL/usdmaya/Metadata.h" +#include "AL/usdmaya/StageCache.h" +#include "AL/usdmaya/TypeIDs.h" +#include "AL/usdmaya/Version.h" +#include "AL/usdmaya/cmds/ProxyShapePostLoadProcess.h" #include "AL/usdmaya/fileio/SchemaPrims.h" #include "AL/usdmaya/fileio/TransformIterator.h" #include "AL/usdmaya/nodes/Engine.h" @@ -46,25 +37,31 @@ #include "AL/usdmaya/nodes/RendererManager.h" #include "AL/usdmaya/nodes/Transform.h" #include "AL/usdmaya/nodes/TransformationMatrix.h" -#include "AL/usdmaya/StageCache.h" -#include "AL/usdmaya/TypeIDs.h" -#include "AL/usdmaya/Version.h" #include "AL/usdmaya/utils/Utils.h" -#include "AL/usd/transaction/TransactionManager.h" +#include +#include +#include #include - -#include -#include #include #include +#include +#include #include #include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -75,31 +72,32 @@ namespace AL { namespace usdmaya { namespace nodes { -typedef void (*proxy_function_prototype)(void* userData, AL::usdmaya::nodes::ProxyShape* proxyInstance); +typedef void ( + *proxy_function_prototype)(void* userData, AL::usdmaya::nodes::ProxyShape* proxyInstance); const char* ProxyShape::s_selectionMaskName = "al_ProxyShape"; //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::serialiseTranslatorContext() { - triggerEvent("PreSerialiseContext"); + triggerEvent("PreSerialiseContext"); - context()->updateUniqueKeys(); - serializedTrCtxPlug().setValue(context()->serialise()); + context()->updateUniqueKeys(); + serializedTrCtxPlug().setValue(context()->serialise()); - triggerEvent("PostSerialiseContext"); + triggerEvent("PostSerialiseContext"); } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::deserialiseTranslatorContext() { - triggerEvent("PreDeserialiseContext"); + triggerEvent("PreDeserialiseContext"); - MString value; - serializedTrCtxPlug().getValue(value); - context()->deserialise(value); + MString value; + serializedTrCtxPlug().getValue(value); + context()->deserialise(value); - triggerEvent("PostDeserialiseContext"); + triggerEvent("PostDeserialiseContext"); } //---------------------------------------------------------------------------------------------------------------------- @@ -135,1416 +133,1425 @@ std::vector ProxyShape::m_unloadedProxyShapes; //---------------------------------------------------------------------------------------------------------------------- UsdPrim ProxyShape::getUsdPrim(MDataBlock& dataBlock) const { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::getUsdPrim\n"); - return _GetUsdPrim(dataBlock); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::getUsdPrim\n"); + return _GetUsdPrim(dataBlock); } //---------------------------------------------------------------------------------------------------------------------- -UsdStagePopulationMask ProxyShape::constructStagePopulationMask(const MString &paths) const +UsdStagePopulationMask ProxyShape::constructStagePopulationMask(const MString& paths) const { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::constructStagePopulationMask(%s)\n", paths.asChar()); - UsdStagePopulationMask mask; - SdfPathVector list = getPrimPathsFromCommaJoinedString(paths); - if(list.empty()) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape: No mask specified, will mask none.\n"); - return UsdStagePopulationMask::All(); - } - - for(const SdfPath &path : list) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape: Add include to mask:(%s)\n", path.GetText()); - mask.Add(path); - } - return mask; + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg("ProxyShape::constructStagePopulationMask(%s)\n", paths.asChar()); + UsdStagePopulationMask mask; + SdfPathVector list = getPrimPathsFromCommaJoinedString(paths); + if (list.empty()) { + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape: No mask specified, will mask none.\n"); + return UsdStagePopulationMask::All(); + } + + for (const SdfPath& path : list) { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg("ProxyShape: Add include to mask:(%s)\n", path.GetText()); + mask.Add(path); + } + return mask; } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::translatePrimPathsIntoMaya( - const SdfPathVector& importPaths, - const SdfPathVector& teardownPaths, + const SdfPathVector& importPaths, + const SdfPathVector& teardownPaths, const fileio::translators::TranslatorParameters& param) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape:translatePrimPathsIntoMaya ImportSize='%zd' TearDownSize='%zd' \n", - importPaths.size(), - teardownPaths.size()); - - //Resolve SdfPathSet to UsdPrimVector - UsdPrimVector importPrims; - for(const SdfPath& path : importPaths) - { - UsdPrim prim = m_stage->GetPrimAtPath(path); - if(prim.IsValid()) - { - importPrims.push_back(prim); - } - else - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape:translatePrimPathsIntoMaya Path for import '%s' resolves to an invalid prim\n", path.GetText()); + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "ProxyShape:translatePrimPathsIntoMaya ImportSize='%zd' TearDownSize='%zd' \n", + importPaths.size(), + teardownPaths.size()); + + // Resolve SdfPathSet to UsdPrimVector + UsdPrimVector importPrims; + for (const SdfPath& path : importPaths) { + UsdPrim prim = m_stage->GetPrimAtPath(path); + if (prim.IsValid()) { + importPrims.push_back(prim); + } else { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "ProxyShape:translatePrimPathsIntoMaya Path for import '%s' resolves to an " + "invalid prim\n", + path.GetText()); + } } - } - translatePrimsIntoMaya(importPrims, teardownPaths, param); + translatePrimsIntoMaya(importPrims, teardownPaths, param); } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::translatePrimsIntoMaya( - const UsdPrimVector& importPrims, - const SdfPathVector& teardownPrims, + const UsdPrimVector& importPrims, + const SdfPathVector& teardownPrims, const fileio::translators::TranslatorParameters& param) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape:translatePrimsIntoMaya ImportSize='%zd' TearDownSize='%zd' \n", importPrims.size(), teardownPrims.size()); + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "ProxyShape:translatePrimsIntoMaya ImportSize='%zd' TearDownSize='%zd' \n", + importPrims.size(), + teardownPrims.size()); + + proxy::PrimFilter filter(teardownPrims, importPrims, this, param.forceTranslatorImport()); + + if (TfDebug::IsEnabled(ALUSDMAYA_TRANSLATORS)) { + std::cout << "new prims" << std::endl; + for (auto it : filter.newPrimSet()) { + std::cout << it.GetPath().GetText() << ' ' << it.GetTypeName().GetText() << std::endl; + } + std::cout << "new transforms" << std::endl; + for (auto it : filter.transformsToCreate()) { + std::cout << it.GetPath().GetText() << ' ' << it.GetTypeName().GetText() << std::endl; + } + std::cout << "updateable prims" << std::endl; + for (auto it : filter.updatablePrimSet()) { + std::cout << it.GetPath().GetText() << '\n'; + } + std::cout << "removed prims" << std::endl; + for (auto it : filter.removedPrimSet()) { + std::cout << it.GetText() << '\n'; + } + } - proxy::PrimFilter filter(teardownPrims, importPrims, this, param.forceTranslatorImport()); + // content to remove needs to be dealt with first + // as some nodes might be re-imported and we have + // to make sure their "old" version is gone before + // recreating them. + context()->removeEntries(filter.removedPrimSet()); + + cmds::ProxyShapePostLoadProcess::MObjectToPrim objsToCreate; + if (!filter.transformsToCreate().empty()) { + cmds::ProxyShapePostLoadProcess::createTranformChainsForSchemaPrims( + this, + filter.transformsToCreate(), + parentTransform(), + objsToCreate, + param.pushToPrim(), + param.readAnimatedValues()); + } - if(TfDebug::IsEnabled(ALUSDMAYA_TRANSLATORS)) - { - std::cout << "new prims" << std::endl; - for(auto it : filter.newPrimSet()) - { - std::cout << it.GetPath().GetText() << ' ' << it.GetTypeName().GetText() << std::endl; + if (!filter.newPrimSet().empty()) { + cmds::ProxyShapePostLoadProcess::createSchemaPrims(this, filter.newPrimSet(), param); } - std::cout << "new transforms" << std::endl; - for(auto it : filter.transformsToCreate()) - { - std::cout << it.GetPath().GetText() << ' ' << it.GetTypeName().GetText() << std::endl; + + if (!filter.updatablePrimSet().empty()) { + cmds::ProxyShapePostLoadProcess::updateSchemaPrims(this, filter.updatablePrimSet()); } - std::cout << "updateable prims" << std::endl; - for(auto it : filter.updatablePrimSet()) - { - std::cout << it.GetPath().GetText() << '\n'; + + cleanupTransformRefs(); + + context()->updatePrimTypes(); + + // now perform any post-creation fix up + if (!filter.newPrimSet().empty()) { + cmds::ProxyShapePostLoadProcess::connectSchemaPrims(this, filter.newPrimSet()); } - std::cout << "removed prims" << std::endl; - for(auto it : filter.removedPrimSet()) - { - std::cout << it.GetText() << '\n'; + + if (!filter.updatablePrimSet().empty()) { + cmds::ProxyShapePostLoadProcess::connectSchemaPrims(this, filter.updatablePrimSet()); + } + + if (context()->isExcludedGeometryDirty()) { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg("ProxyShape:translatePrimsIntoMaya excluded geometry has been modified, " + "reconstructing imaging engine \n"); + constructExcludedPrims(); // if excluded prims changed, this will call + // constructGLImagingEngine } - } - - // content to remove needs to be dealt with first - // as some nodes might be re-imported and we have - // to make sure their "old" version is gone before - // recreating them. - context()->removeEntries(filter.removedPrimSet()); - - cmds::ProxyShapePostLoadProcess::MObjectToPrim objsToCreate; - if(!filter.transformsToCreate().empty()) - { - cmds::ProxyShapePostLoadProcess::createTranformChainsForSchemaPrims( - this, - filter.transformsToCreate(), - parentTransform(), - objsToCreate, - param.pushToPrim(), - param.readAnimatedValues()); - } - - - if(!filter.newPrimSet().empty()) - { - cmds::ProxyShapePostLoadProcess::createSchemaPrims(this, filter.newPrimSet(), param); - } - - if(!filter.updatablePrimSet().empty()) - { - cmds::ProxyShapePostLoadProcess::updateSchemaPrims(this, filter.updatablePrimSet()); - } - - cleanupTransformRefs(); - - context()->updatePrimTypes(); - - // now perform any post-creation fix up - if(!filter.newPrimSet().empty()) - { - cmds::ProxyShapePostLoadProcess::connectSchemaPrims(this, filter.newPrimSet()); - } - - if(!filter.updatablePrimSet().empty()) - { - cmds::ProxyShapePostLoadProcess::connectSchemaPrims(this, filter.updatablePrimSet()); - } - - if(context()->isExcludedGeometryDirty()) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape:translatePrimsIntoMaya excluded geometry has been modified, reconstructing imaging engine \n"); - constructExcludedPrims(); //if excluded prims changed, this will call constructGLImagingEngine - } } //---------------------------------------------------------------------------------------------------------------------- -SdfPathVector ProxyShape::getPrimPathsFromCommaJoinedString(const MString &paths) const +SdfPathVector ProxyShape::getPrimPathsFromCommaJoinedString(const MString& paths) const { - SdfPathVector result; - if(paths.length()) - { - const char* begin = paths.asChar(); - const char* end = paths.asChar() + paths.length(); - const char* iter = std::find(begin, end, ','); - while(iter != end) - { - result.push_back(SdfPath(std::string(begin, iter))); - begin = iter + 1; - iter = std::find(begin, end, ','); - } + SdfPathVector result; + if (paths.length()) { + const char* begin = paths.asChar(); + const char* end = paths.asChar() + paths.length(); + const char* iter = std::find(begin, end, ','); + while (iter != end) { + result.push_back(SdfPath(std::string(begin, iter))); + begin = iter + 1; + iter = std::find(begin, end, ','); + } - result.push_back(SdfPath(std::string(begin, end))); - } - return result; + result.push_back(SdfPath(std::string(begin, end))); + } + return result; } //---------------------------------------------------------------------------------------------------------------------- Engine* ProxyShape::engine(bool construct) { - if (!m_engine && construct) - { - constructGLImagingEngine(); - } - return m_engine; + if (!m_engine && construct) { + constructGLImagingEngine(); + } + return m_engine; } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::destroyGLImagingEngine() { - if(m_engine) - { - triggerEvent("DestroyGLEngine"); - delete m_engine; - m_engine = nullptr; - } + if (m_engine) { + triggerEvent("DestroyGLEngine"); + delete m_engine; + m_engine = nullptr; + } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::constructGLImagingEngine() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::constructGLImagingEngine\n"); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::constructGLImagingEngine\n"); + + // kBatch does not cover mayapy use, we only need this in interactive mode: + if (MGlobal::mayaState() == MGlobal::kInteractive) { + if (m_stage) { + // function prototype of callback we wish to register + typedef void (*proxy_function_prototype)(void*, AL::usdmaya::nodes::ProxyShape*); + + // delete previous instance + destroyGLImagingEngine(); + + const auto& translatedGeo = m_context->excludedGeometry(); + + // combine the excluded paths + SdfPathVector excludedGeometryPaths; + excludedGeometryPaths.reserve( + m_excludedTaggedGeometry.size() + m_excludedGeometry.size() + translatedGeo.size()); + excludedGeometryPaths.assign( + m_excludedTaggedGeometry.begin(), m_excludedTaggedGeometry.end()); + excludedGeometryPaths.insert( + excludedGeometryPaths.end(), m_excludedGeometry.begin(), m_excludedGeometry.end()); + for (auto& it : translatedGeo) { + excludedGeometryPaths.push_back(it.second); + } - // kBatch does not cover mayapy use, we only need this in interactive mode: - if (MGlobal::mayaState() == MGlobal::kInteractive) - { - if(m_stage) - { - // function prototype of callback we wish to register - typedef void (*proxy_function_prototype)(void*, AL::usdmaya::nodes::ProxyShape*); - - // delete previous instance - destroyGLImagingEngine(); - - const auto& translatedGeo = m_context->excludedGeometry(); - - // combine the excluded paths - SdfPathVector excludedGeometryPaths; - excludedGeometryPaths.reserve(m_excludedTaggedGeometry.size() + m_excludedGeometry.size() + translatedGeo.size()); - excludedGeometryPaths.assign(m_excludedTaggedGeometry.begin(), m_excludedTaggedGeometry.end()); - excludedGeometryPaths.insert(excludedGeometryPaths.end(), m_excludedGeometry.begin(), m_excludedGeometry.end()); - for(auto& it : translatedGeo) - { - excludedGeometryPaths.push_back(it.second); - } - - m_engine = new Engine(m_path, excludedGeometryPaths); - // set renderer plugin based on RendererManager setting - RendererManager* manager = RendererManager::findManager(); - if(manager && m_engine) - { - manager->changeRendererPlugin(this, true); - } - - triggerEvent("ConstructGLEngine"); + m_engine = new Engine(m_path, excludedGeometryPaths); + // set renderer plugin based on RendererManager setting + RendererManager* manager = RendererManager::findManager(); + if (manager && m_engine) { + manager->changeRendererPlugin(this, true); + } + + triggerEvent("ConstructGLEngine"); + } } - } } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShape::setDependentsDirty(const MPlug& plugBeingDirtied, MPlugArray& plugs) { - // I thought that, if your ProxyDrawOverride is set to not always be dirty, - // prepareForDraw would automatically be triggered whenever any attribute - // that was marked as affectsAppearance was dirtied; however, this is not - // the case, so we mark the draw geo dirty ourselves. - { - MStatus status; - MFnAttribute attr(plugBeingDirtied, &status); - if (!status) + // I thought that, if your ProxyDrawOverride is set to not always be dirty, + // prepareForDraw would automatically be triggered whenever any attribute + // that was marked as affectsAppearance was dirtied; however, this is not + // the case, so we mark the draw geo dirty ourselves. { - if (plugBeingDirtied.isNull()) - { - TF_CODING_ERROR(TfStringPrintf( - "ProxyShape setInternalValue given invalid plug - shape: %s", - name().asChar())); + MStatus status; + MFnAttribute attr(plugBeingDirtied, &status); + if (!status) { + if (plugBeingDirtied.isNull()) { + TF_CODING_ERROR(TfStringPrintf( + "ProxyShape setInternalValue given invalid plug - shape: %s", name().asChar())); + } else { + TF_CODING_ERROR(TfStringPrintf( + "Unable to retrieve attribute from plug: %s", + plugBeingDirtied.name().asChar())); + } + } else { + if (attr.affectsAppearance()) { + MHWRender::MRenderer::setGeometryDrawDirty(thisMObject()); + } } - else - { - TF_CODING_ERROR(TfStringPrintf( - "Unable to retrieve attribute from plug: %s", - plugBeingDirtied.name().asChar())); - } } - else - { - if (attr.affectsAppearance()) - { - MHWRender::MRenderer::setGeometryDrawDirty(thisMObject()); - } + + if (plugBeingDirtied == time() || plugBeingDirtied == m_timeOffset + || plugBeingDirtied == m_timeScalar) { + plugs.append(outTimePlug()); + return MS::kSuccess; + } + if (plugBeingDirtied == filePath()) { + MHWRender::MRenderer::setGeometryDrawDirty(thisMObject(), true); } - } - if(plugBeingDirtied == time() || plugBeingDirtied == m_timeOffset || plugBeingDirtied == m_timeScalar) - { - plugs.append(outTimePlug()); - return MS::kSuccess; - } - if(plugBeingDirtied == filePath()) - { - MHWRender::MRenderer::setGeometryDrawDirty(thisMObject(), true); - } - - if (plugBeingDirtied == outStageData() || - // All the plugs that affect outStageDataAttr - plugBeingDirtied == filePath() || - plugBeingDirtied == primPath() || - plugBeingDirtied == m_populationMaskIncludePaths || - plugBeingDirtied == m_stageDataDirty || - plugBeingDirtied == m_assetResolverConfig) - { - MayaUsdProxyStageInvalidateNotice(*this).Send(); - } - - return MPxSurfaceShape::setDependentsDirty(plugBeingDirtied, plugs); + if (plugBeingDirtied == outStageData() || + // All the plugs that affect outStageDataAttr + plugBeingDirtied == filePath() || plugBeingDirtied == primPath() + || plugBeingDirtied == m_populationMaskIncludePaths || plugBeingDirtied == m_stageDataDirty + || plugBeingDirtied == m_assetResolverConfig) { + MayaUsdProxyStageInvalidateNotice(*this).Send(); + } + + return MPxSurfaceShape::setDependentsDirty(plugBeingDirtied, plugs); } //---------------------------------------------------------------------------------------------------------------------- -MStatus ProxyShape::preEvaluation(const MDGContext & context, const MEvaluationNode& evaluationNode) +MStatus ProxyShape::preEvaluation(const MDGContext& context, const MEvaluationNode& evaluationNode) { - if( !context.isNormal() ) - return MStatus::kFailure; - return MStatus::kSuccess; + if (!context.isNormal()) + return MStatus::kFailure; + return MStatus::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -bool ProxyShape::getRenderAttris(UsdImagingGLRenderParams& attribs, const MHWRender::MFrameContext& drawRequest, const MDagPath& objPath) +bool ProxyShape::getRenderAttris( + UsdImagingGLRenderParams& attribs, + const MHWRender::MFrameContext& drawRequest, + const MDagPath& objPath) { - uint32_t displayStyle = drawRequest.getDisplayStyle(); - uint32_t displayStatus = MHWRender::MGeometryUtilities::displayStatus(objPath); - - // set wireframe colour - MColor wireColour = MHWRender::MGeometryUtilities::wireframeColor(objPath); - attribs.wireframeColor = GfVec4f(wireColour.r, wireColour.g, wireColour.b, wireColour.a); - - // determine the shading mode - const uint32_t wireframeOnShaded1 = (MHWRender::MFrameContext::kWireFrame | MHWRender::MFrameContext::kGouraudShaded); - const uint32_t wireframeOnShaded2 = (MHWRender::MFrameContext::kWireFrame | MHWRender::MFrameContext::kFlatShaded); - if((displayStyle & wireframeOnShaded1) == wireframeOnShaded1 || - (displayStyle & wireframeOnShaded2) == wireframeOnShaded2) { - attribs.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME_ON_SURFACE; - } - else - if(displayStyle & MHWRender::MFrameContext::kWireFrame) { - attribs.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME; - } - else - if(displayStyle & MHWRender::MFrameContext::kFlatShaded) { - attribs.drawMode = UsdImagingGLDrawMode::DRAW_SHADED_FLAT; - if ((displayStatus == MHWRender::kActive) || - (displayStatus == MHWRender::kLead) || - (displayStatus == MHWRender::kHilite)) { - attribs.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME_ON_SURFACE; + uint32_t displayStyle = drawRequest.getDisplayStyle(); + uint32_t displayStatus = MHWRender::MGeometryUtilities::displayStatus(objPath); + + // set wireframe colour + MColor wireColour = MHWRender::MGeometryUtilities::wireframeColor(objPath); + attribs.wireframeColor = GfVec4f(wireColour.r, wireColour.g, wireColour.b, wireColour.a); + + // determine the shading mode + const uint32_t wireframeOnShaded1 + = (MHWRender::MFrameContext::kWireFrame | MHWRender::MFrameContext::kGouraudShaded); + const uint32_t wireframeOnShaded2 + = (MHWRender::MFrameContext::kWireFrame | MHWRender::MFrameContext::kFlatShaded); + if ((displayStyle & wireframeOnShaded1) == wireframeOnShaded1 + || (displayStyle & wireframeOnShaded2) == wireframeOnShaded2) { + attribs.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME_ON_SURFACE; + } else if (displayStyle & MHWRender::MFrameContext::kWireFrame) { + attribs.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME; + } else if (displayStyle & MHWRender::MFrameContext::kFlatShaded) { + attribs.drawMode = UsdImagingGLDrawMode::DRAW_SHADED_FLAT; + if ((displayStatus == MHWRender::kActive) || (displayStatus == MHWRender::kLead) + || (displayStatus == MHWRender::kHilite)) { + attribs.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME_ON_SURFACE; + } + } else if (displayStyle & MHWRender::MFrameContext::kGouraudShaded) { + attribs.drawMode = UsdImagingGLDrawMode::DRAW_SHADED_SMOOTH; + if ((displayStatus == MHWRender::kActive) || (displayStatus == MHWRender::kLead) + || (displayStatus == MHWRender::kHilite)) { + attribs.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME_ON_SURFACE; + } + } else if (displayStyle & MHWRender::MFrameContext::kBoundingBox) { + attribs.drawMode = UsdImagingGLDrawMode::DRAW_POINTS; } - } - else - if(displayStyle & MHWRender::MFrameContext::kGouraudShaded) { - attribs.drawMode = UsdImagingGLDrawMode::DRAW_SHADED_SMOOTH; - if ((displayStatus == MHWRender::kActive) || - (displayStatus == MHWRender::kLead) || - (displayStatus == MHWRender::kHilite)) { - attribs.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME_ON_SURFACE; + + // determine whether to use the default material for everything + attribs.enableSceneMaterials = !(displayStyle & MHWRender::MFrameContext::kDefaultMaterial); + + // set the time for the scene + attribs.frame = outTimePlug().asMTime().as(MTime::uiUnit()); + + if (displayStyle & MHWRender::MFrameContext::kBackfaceCulling) { + attribs.cullStyle = UsdImagingGLCullStyle::CULL_STYLE_BACK; + } else { + attribs.cullStyle = UsdImagingGLCullStyle::CULL_STYLE_NOTHING; } - } - else - if(displayStyle & MHWRender::MFrameContext::kBoundingBox) { - attribs.drawMode = UsdImagingGLDrawMode::DRAW_POINTS; - } - - // determine whether to use the default material for everything - attribs.enableSceneMaterials = !(displayStyle & MHWRender::MFrameContext::kDefaultMaterial); - - // set the time for the scene - attribs.frame = outTimePlug().asMTime().as(MTime::uiUnit()); - - if(displayStyle & MHWRender::MFrameContext::kBackfaceCulling) { - attribs.cullStyle = UsdImagingGLCullStyle::CULL_STYLE_BACK; - } - else { - attribs.cullStyle = UsdImagingGLCullStyle::CULL_STYLE_NOTHING; - } - - const float complexities[] = {1.05f, 1.15f, 1.25f, 1.35f, 1.45f, 1.55f, 1.65f, 1.75f, 1.9f}; - attribs.complexity = complexities[complexityPlug().asInt()]; - attribs.showGuides = drawGuidePurposePlug().asBool(); - attribs.showProxy = drawProxyPurposePlug().asBool(); - attribs.showRender = drawRenderPurposePlug().asBool(); - return true; + + const float complexities[] = { 1.05f, 1.15f, 1.25f, 1.35f, 1.45f, 1.55f, 1.65f, 1.75f, 1.9f }; + attribs.complexity = complexities[complexityPlug().asInt()]; + attribs.showGuides = drawGuidePurposePlug().asBool(); + attribs.showProxy = drawProxyPurposePlug().asBool(); + attribs.showRender = drawRenderPurposePlug().asBool(); + return true; } //---------------------------------------------------------------------------------------------------------------------- ProxyShape::ProxyShape() - : MayaUsdProxyShapeBase(), AL::maya::utils::NodeHelper(), AL::event::NodeEvents(&AL::event::EventScheduler::getScheduler()), - m_context(fileio::translators::TranslatorContext::create(this)), - m_translatorManufacture(context()) + : MayaUsdProxyShapeBase() + , AL::maya::utils::NodeHelper() + , AL::event::NodeEvents(&AL::event::EventScheduler::getScheduler()) + , m_context(fileio::translators::TranslatorContext::create(this)) + , m_translatorManufacture(context()) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::ProxyShape\n"); - m_onSelectionChanged = MEventMessage::addEventCallback(MString("SelectionChanged"), onSelectionChanged, this); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::ProxyShape\n"); + m_onSelectionChanged + = MEventMessage::addEventCallback(MString("SelectionChanged"), onSelectionChanged, this); - TfWeakPtr me(this); + TfWeakPtr me(this); - m_variantChangedNoticeKey = TfNotice::Register(me, &ProxyShape::variantSelectionListener); - m_objectsChangedNoticeKey = TfNotice::Register(me, &ProxyShape::onObjectsChanged, m_stage); - m_editTargetChanged = TfNotice::Register(me, &ProxyShape::onEditTargetChanged, m_stage); + m_variantChangedNoticeKey = TfNotice::Register(me, &ProxyShape::variantSelectionListener); + m_objectsChangedNoticeKey = TfNotice::Register(me, &ProxyShape::onObjectsChanged, m_stage); + m_editTargetChanged = TfNotice::Register(me, &ProxyShape::onEditTargetChanged, m_stage); - TfWeakPtr stage(m_stage); - m_transactionNoticeKey = TfNotice::Register(me, &ProxyShape::onTransactionNotice, stage); + TfWeakPtr stage(m_stage); + m_transactionNoticeKey = TfNotice::Register(me, &ProxyShape::onTransactionNotice, stage); - registerEvents(); + registerEvents(); } //---------------------------------------------------------------------------------------------------------------------- ProxyShape::~ProxyShape() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::~ProxyShape\n"); - triggerEvent("PreDestroyProxyShape"); - MEventMessage::removeCallback(m_onSelectionChanged); - TfNotice::Revoke(m_variantChangedNoticeKey); - TfNotice::Revoke(m_objectsChangedNoticeKey); - TfNotice::Revoke(m_editTargetChanged); - TfNotice::Revoke(m_transactionNoticeKey); - destroyGLImagingEngine(); - triggerEvent("PostDestroyProxyShape"); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::~ProxyShape\n"); + triggerEvent("PreDestroyProxyShape"); + MEventMessage::removeCallback(m_onSelectionChanged); + TfNotice::Revoke(m_variantChangedNoticeKey); + TfNotice::Revoke(m_objectsChangedNoticeKey); + TfNotice::Revoke(m_editTargetChanged); + TfNotice::Revoke(m_transactionNoticeKey); + destroyGLImagingEngine(); + triggerEvent("PostDestroyProxyShape"); } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShape::initialise() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::initialise\n"); - - MStatus retValue = inheritAttributesFrom(MayaUsdProxyShapeBase::typeName); - CHECK_MSTATUS_AND_RETURN_IT(retValue); - - const char* errorString = "ProxyShape::initialize"; - try - { - setNodeType(kTypeName); - addFrame("USD Proxy Shape Node"); - m_serializedSessionLayer = addStringAttr("serializedSessionLayer", "ssl", kCached|kReadable|kWritable|kStorable|kHidden); - m_sessionLayerName = addStringAttr("sessionLayerName", "sln", kCached|kReadable|kWritable|kStorable|kHidden); - - //for backward compatibility (or at least to stop maya spewing out errors on scene open). This attribute was removed in 0.32.17 - addStringAttr("serializedArCtx", "arcd", kReadable|kWritable|kHidden); - // m_filePath / m_primPath / m_excludePrimPaths are internal just so we get notification on change - inheritFilePathAttr("filePath", kCached | kReadable | kWritable | kStorable | kAffectsAppearance | kInternal, kLoad, "USD Files (*.usd*) (*.usd*);;Alembic Files (*.abc)"); - - inheritStringAttr("primPath", kCached | kReadable | kWritable | kStorable | kAffectsAppearance | kInternal); - inheritStringAttr("excludePrimPaths", kCached | kReadable | kWritable | kStorable | kAffectsAppearance | kInternal); - m_populationMaskIncludePaths = addStringAttr("populationMaskIncludePaths", "pmi", kCached | kReadable | kWritable | kStorable | kAffectsAppearance); - m_excludedTranslatedGeometry = addStringAttr("excludedTranslatedGeometry", "etg", kCached | kReadable | kWritable | kStorable | kAffectsAppearance); - - inheritInt32Attr("complexity", kCached | kConnectable | kReadable | kWritable | kAffectsAppearance | kKeyable | kStorable); - // outStageData attribute already added in base class. - inheritBoolAttr("drawGuidePurpose", kCached | kKeyable | kWritable | kAffectsAppearance | kStorable); - inheritBoolAttr("drawProxyPurpose", kCached | kKeyable | kWritable | kAffectsAppearance | kStorable); - inheritBoolAttr("drawRenderPurpose", kCached | kKeyable | kWritable | kAffectsAppearance | kStorable); - m_unloaded = addBoolAttr("unloaded", "ul", false, kCached | kKeyable | kWritable | kAffectsAppearance | kStorable); - m_serializedTrCtx = addStringAttr("serializedTrCtx", "srtc", kReadable|kWritable|kStorable|kHidden); - - addFrame("USD Timing Information"); - inheritTimeAttr("time", kCached | kConnectable | kReadable | kWritable | kStorable | kAffectsAppearance); - m_timeOffset = addTimeAttr("timeOffset", "tmo", MTime(0.0), kCached | kConnectable | kReadable | kWritable | kStorable | kAffectsAppearance); - m_timeScalar = addDoubleAttr("timeScalar", "tms", 1.0, kCached | kConnectable | kReadable | kWritable | kStorable | kAffectsAppearance); - inheritTimeAttr("outTime", kCached | kConnectable | kReadable | kAffectsAppearance); - m_layers = addMessageAttr("layers", "lys", kWritable | kReadable | kConnectable | kHidden); - - addFrame("OpenGL Display"); - m_ambient = addColourAttr("ambientColour", "amc", MColor(0.1f, 0.1f, 0.1f), kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance); - m_diffuse = addColourAttr("diffuseColour", "dic", MColor(0.7f, 0.7f, 0.7f), kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance); - m_specular = addColourAttr("specularColour", "spc", MColor(0.6f, 0.6f, 0.6f), kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance); - m_emission = addColourAttr("emissionColour", "emc", MColor(0.0f, 0.0f, 0.0f), kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance); - m_shininess = addFloatAttr("shininess", "shi", 5.0f, kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance); - - m_serializedRefCounts = addStringAttr("serializedRefCounts", "strcs", kReadable | kWritable | kStorable | kHidden); - - m_version = addStringAttr( - "version", "vrs", getVersion(), - kReadable | kStorable | kHidden); - - MNodeClass ncTransform("transform"); - m_transformTranslate = ncTransform.attribute("t"); - m_transformRotate = ncTransform.attribute("r"); - m_transformScale = ncTransform.attribute("s"); - - MNodeClass ncProxyShape(kTypeId); - m_visibleInReflections = ncProxyShape.attribute("visibleInReflections"); - m_visibleInRefractions = ncProxyShape.attribute("visibleInRefractions"); - - m_stageDataDirty = addBoolAttr("stageDataDirty", "sdd", false, kWritable | kAffectsAppearance | kInternal); - - inheritInt32Attr("stageCacheId", kCached | kConnectable | kReadable | kInternal ); - - m_assetResolverConfig = addStringAttr("assetResolverConfig", "arc", kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance | kInternal); - m_variantFallbacks = addStringAttr("variantFallbacks", "vfs", kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance | kInternal); - - AL_MAYA_CHECK_ERROR(attributeAffects(time(), outTime()), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(m_timeOffset, outTime()), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(m_timeScalar, outTime()), errorString); - // file path and prim path affects on out stage data already done in base - // class. - AL_MAYA_CHECK_ERROR(attributeAffects(m_populationMaskIncludePaths, outStageData()), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(m_stageDataDirty, outStageData()), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(m_assetResolverConfig, outStageData()), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(m_variantFallbacks, outStageData()), errorString); - } - catch (const MStatus& status) - { - return status; - } + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::initialise\n"); + + MStatus retValue = inheritAttributesFrom(MayaUsdProxyShapeBase::typeName); + CHECK_MSTATUS_AND_RETURN_IT(retValue); + + const char* errorString = "ProxyShape::initialize"; + try { + setNodeType(kTypeName); + addFrame("USD Proxy Shape Node"); + m_serializedSessionLayer = addStringAttr( + "serializedSessionLayer", "ssl", kCached | kReadable | kWritable | kStorable | kHidden); + m_sessionLayerName = addStringAttr( + "sessionLayerName", "sln", kCached | kReadable | kWritable | kStorable | kHidden); + + // for backward compatibility (or at least to stop maya spewing out errors on scene open). + // This attribute was removed in 0.32.17 + addStringAttr("serializedArCtx", "arcd", kReadable | kWritable | kHidden); + // m_filePath / m_primPath / m_excludePrimPaths are internal just so we get notification on + // change + inheritFilePathAttr( + "filePath", + kCached | kReadable | kWritable | kStorable | kAffectsAppearance | kInternal, + kLoad, + "USD Files (*.usd*) (*.usd*);;Alembic Files (*.abc)"); + + inheritStringAttr( + "primPath", + kCached | kReadable | kWritable | kStorable | kAffectsAppearance | kInternal); + inheritStringAttr( + "excludePrimPaths", + kCached | kReadable | kWritable | kStorable | kAffectsAppearance | kInternal); + m_populationMaskIncludePaths = addStringAttr( + "populationMaskIncludePaths", + "pmi", + kCached | kReadable | kWritable | kStorable | kAffectsAppearance); + m_excludedTranslatedGeometry = addStringAttr( + "excludedTranslatedGeometry", + "etg", + kCached | kReadable | kWritable | kStorable | kAffectsAppearance); + + inheritInt32Attr( + "complexity", + kCached | kConnectable | kReadable | kWritable | kAffectsAppearance | kKeyable + | kStorable); + // outStageData attribute already added in base class. + inheritBoolAttr( + "drawGuidePurpose", kCached | kKeyable | kWritable | kAffectsAppearance | kStorable); + inheritBoolAttr( + "drawProxyPurpose", kCached | kKeyable | kWritable | kAffectsAppearance | kStorable); + inheritBoolAttr( + "drawRenderPurpose", kCached | kKeyable | kWritable | kAffectsAppearance | kStorable); + m_unloaded = addBoolAttr( + "unloaded", + "ul", + false, + kCached | kKeyable | kWritable | kAffectsAppearance | kStorable); + m_serializedTrCtx + = addStringAttr("serializedTrCtx", "srtc", kReadable | kWritable | kStorable | kHidden); + + addFrame("USD Timing Information"); + inheritTimeAttr( + "time", + kCached | kConnectable | kReadable | kWritable | kStorable | kAffectsAppearance); + m_timeOffset = addTimeAttr( + "timeOffset", + "tmo", + MTime(0.0), + kCached | kConnectable | kReadable | kWritable | kStorable | kAffectsAppearance); + m_timeScalar = addDoubleAttr( + "timeScalar", + "tms", + 1.0, + kCached | kConnectable | kReadable | kWritable | kStorable | kAffectsAppearance); + inheritTimeAttr("outTime", kCached | kConnectable | kReadable | kAffectsAppearance); + m_layers = addMessageAttr("layers", "lys", kWritable | kReadable | kConnectable | kHidden); + + addFrame("OpenGL Display"); + m_ambient = addColourAttr( + "ambientColour", + "amc", + MColor(0.1f, 0.1f, 0.1f), + kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance); + m_diffuse = addColourAttr( + "diffuseColour", + "dic", + MColor(0.7f, 0.7f, 0.7f), + kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance); + m_specular = addColourAttr( + "specularColour", + "spc", + MColor(0.6f, 0.6f, 0.6f), + kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance); + m_emission = addColourAttr( + "emissionColour", + "emc", + MColor(0.0f, 0.0f, 0.0f), + kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance); + m_shininess = addFloatAttr( + "shininess", + "shi", + 5.0f, + kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance); + + m_serializedRefCounts = addStringAttr( + "serializedRefCounts", "strcs", kReadable | kWritable | kStorable | kHidden); + + m_version = addStringAttr("version", "vrs", getVersion(), kReadable | kStorable | kHidden); + + MNodeClass ncTransform("transform"); + m_transformTranslate = ncTransform.attribute("t"); + m_transformRotate = ncTransform.attribute("r"); + m_transformScale = ncTransform.attribute("s"); + + MNodeClass ncProxyShape(kTypeId); + m_visibleInReflections = ncProxyShape.attribute("visibleInReflections"); + m_visibleInRefractions = ncProxyShape.attribute("visibleInRefractions"); + + m_stageDataDirty = addBoolAttr( + "stageDataDirty", "sdd", false, kWritable | kAffectsAppearance | kInternal); + + inheritInt32Attr("stageCacheId", kCached | kConnectable | kReadable | kInternal); + + m_assetResolverConfig = addStringAttr( + "assetResolverConfig", + "arc", + kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance | kInternal); + m_variantFallbacks = addStringAttr( + "variantFallbacks", + "vfs", + kReadable | kWritable | kConnectable | kStorable | kAffectsAppearance | kInternal); + + AL_MAYA_CHECK_ERROR(attributeAffects(time(), outTime()), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(m_timeOffset, outTime()), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(m_timeScalar, outTime()), errorString); + // file path and prim path affects on out stage data already done in base + // class. + AL_MAYA_CHECK_ERROR( + attributeAffects(m_populationMaskIncludePaths, outStageData()), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(m_stageDataDirty, outStageData()), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(m_assetResolverConfig, outStageData()), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(m_variantFallbacks, outStageData()), errorString); + } catch (const MStatus& status) { + return status; + } - addBaseTemplate("AEsurfaceShapeTemplate"); - generateAETemplate(); + addBaseTemplate("AEsurfaceShapeTemplate"); + generateAETemplate(); - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -void ProxyShape::onEditTargetChanged(UsdNotice::StageEditTargetChanged const& notice, UsdStageWeakPtr const& sender) +void ProxyShape::onEditTargetChanged( + UsdNotice::StageEditTargetChanged const& notice, + UsdStageWeakPtr const& sender) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::onEditTargetChanged\n"); - if (!sender || sender != m_stage) - return; + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::onEditTargetChanged\n"); + if (!sender || sender != m_stage) + return; - trackEditTargetLayer(); + trackEditTargetLayer(); } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::trackEditTargetLayer(LayerManager* layerManager) { - TF_DEBUG(ALUSDMAYA_LAYERS).Msg("ProxyShape::trackEditTargetLayer\n"); - auto stage = getUsdStage(); + TF_DEBUG(ALUSDMAYA_LAYERS).Msg("ProxyShape::trackEditTargetLayer\n"); + auto stage = getUsdStage(); - if(!stage) - { - TF_DEBUG(ALUSDMAYA_LAYERS).Msg(" - no stage\n"); - return; - } + if (!stage) { + TF_DEBUG(ALUSDMAYA_LAYERS).Msg(" - no stage\n"); + return; + } - auto currTargetLayer = stage->GetEditTarget().GetLayer(); + auto currTargetLayer = stage->GetEditTarget().GetLayer(); - TF_DEBUG(ALUSDMAYA_LAYERS).Msg(" - curr target layer: %s\n", currTargetLayer->GetIdentifier().c_str()); + TF_DEBUG(ALUSDMAYA_LAYERS) + .Msg(" - curr target layer: %s\n", currTargetLayer->GetIdentifier().c_str()); - if (m_prevEditTarget != currTargetLayer) - { - if(!layerManager) - { - layerManager = LayerManager::findOrCreateManager(); - // findOrCreateManager SHOULD always return a result, but we check anyway, - // to avoid any potential crash... - if(!layerManager) - { - std::cerr << "Error creating / finding a layerManager node!" << std::endl; - return; - } - } + if (m_prevEditTarget != currTargetLayer) { + if (!layerManager) { + layerManager = LayerManager::findOrCreateManager(); + // findOrCreateManager SHOULD always return a result, but we check anyway, + // to avoid any potential crash... + if (!layerManager) { + std::cerr << "Error creating / finding a layerManager node!" << std::endl; + return; + } + } - if (m_prevEditTarget && !m_prevEditTarget->IsDirty()) - { - // If the old edit target still isn't dirty, and we're switching to a new - // edit target, we can remove it from the layer manager - layerManager->removeLayer(m_prevEditTarget); - } + if (m_prevEditTarget && !m_prevEditTarget->IsDirty()) { + // If the old edit target still isn't dirty, and we're switching to a new + // edit target, we can remove it from the layer manager + layerManager->removeLayer(m_prevEditTarget); + } - layerManager->addLayer(currTargetLayer); - m_prevEditTarget = currTargetLayer; + layerManager->addLayer(currTargetLayer); + m_prevEditTarget = currTargetLayer; - triggerEvent("EditTargetChanged"); - } + triggerEvent("EditTargetChanged"); + } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::trackAllDirtyLayers(LayerManager* layerManager) { - trackEditTargetLayer(layerManager); - if (!layerManager) - layerManager = LayerManager::findOrCreateManager(); - auto usedLayer = m_stage->GetUsedLayers(); - for (auto& _layer: usedLayer) - { - if (_layer->IsDirty()) - layerManager->addLayer(_layer); - } + trackEditTargetLayer(layerManager); + if (!layerManager) + layerManager = LayerManager::findOrCreateManager(); + auto usedLayer = m_stage->GetUsedLayers(); + for (auto& _layer : usedLayer) { + if (_layer->IsDirty()) + layerManager->addLayer(_layer); + } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::onPrimResync(SdfPath primPath, SdfPathVector& previousPrims) { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::onPrimResync checking %s\n", primPath.GetText()); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("ProxyShape::onPrimResync checking %s\n", primPath.GetText()); - UsdPrim resyncPrim = m_stage->GetPrimAtPath(primPath); - if(!resyncPrim.IsValid()) - { - return; - } + UsdPrim resyncPrim = m_stage->GetPrimAtPath(primPath); + if (!resyncPrim.IsValid()) { + return; + } - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::onPrimResync begin:\n%s\n", context()->serialise().asChar()); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("ProxyShape::onPrimResync begin:\n%s\n", context()->serialise().asChar()); - AL_BEGIN_PROFILE_SECTION(ObjectChanged); - MFnDagNode fn(thisMObject()); - MDagPath proxyTransformPath; - fn.getPath(proxyTransformPath); - proxyTransformPath.pop(); + AL_BEGIN_PROFILE_SECTION(ObjectChanged); + MFnDagNode fn(thisMObject()); + MDagPath proxyTransformPath; + fn.getPath(proxyTransformPath); + proxyTransformPath.pop(); - // find the new set of prims - UsdPrimVector newPrimSet = huntForNativeNodesUnderPrim(proxyTransformPath, primPath, translatorManufacture()); + // find the new set of prims + UsdPrimVector newPrimSet + = huntForNativeNodesUnderPrim(proxyTransformPath, primPath, translatorManufacture()); - // Remove prims that have disappeared and translate in new prims - translatePrimsIntoMaya(newPrimSet, previousPrims); + // Remove prims that have disappeared and translate in new prims + translatePrimsIntoMaya(newPrimSet, previousPrims); - previousPrims.clear(); + previousPrims.clear(); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::onPrimResync end:\n%s\n", context()->serialise().asChar()); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("ProxyShape::onPrimResync end:\n%s\n", context()->serialise().asChar()); - AL_END_PROFILE_SECTION(); + AL_END_PROFILE_SECTION(); - validateTransforms(); + validateTransforms(); } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::resync(const SdfPath& primPath) { - // FIMXE: This method was needed to call update() on all translators in the maya scene. Since then some new - // locking and selectability functionality has been added to onObjectsChanged(). I would want to call the logic in - // that method to handle this resyncing but it would need to be refactored. + // FIMXE: This method was needed to call update() on all translators in the maya scene. Since + // then some new locking and selectability functionality has been added to onObjectsChanged(). I + // would want to call the logic in that method to handle this resyncing but it would need to be + // refactored. - SdfPathVector existingSchemaPrims; + SdfPathVector existingSchemaPrims; - // populates list of prims from prim mapping that will change under the path to resync. - onPrePrimChanged(primPath, existingSchemaPrims); + // populates list of prims from prim mapping that will change under the path to resync. + onPrePrimChanged(primPath, existingSchemaPrims); - onPrimResync(primPath, existingSchemaPrims); + onPrimResync(primPath, existingSchemaPrims); } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::serialize(UsdStageRefPtr stage, LayerManager* layerManager) { - if(stage) - { - if (layerManager) - { - // Make sure the sessionLayer is always serialized (even if it's never an edit target) - auto sessionLayer = stage->GetSessionLayer(); - layerManager->addLayer(sessionLayer); - - auto identifier = sessionLayer->GetIdentifier(); - if(layerManager->findLayer(identifier)) - { - // ...and store the name for the (anonymous) session layer so we can find it! - sessionLayerNamePlug().setValue(AL::maya::utils::convert(identifier)); - } - else - { - // ...make sure for the old Maya scene, we clear the sessionLayerName plug so there is no - // complaint when we open it. - sessionLayerNamePlug().setValue(""); - } - - auto rootLayer = stage->GetRootLayer(); - if (rootLayer->IsAnonymous()) - { - // For an anonymous root layer we need to update the file path to match the new - // identifier the layer manager may have associated the layer with. - MPlug filePathPlug = this->filePathPlug(); - const std::string currentRootLayerId = AL::maya::utils::convert(filePathPlug.asString()); - const std::string &newRootLayerId = rootLayer->GetIdentifier(); - if (currentRootLayerId != newRootLayerId) - { - filePathPlug.setString(AL::maya::utils::convert(newRootLayerId)); + if (stage) { + if (layerManager) { + // Make sure the sessionLayer is always serialized (even if it's never an edit target) + auto sessionLayer = stage->GetSessionLayer(); + layerManager->addLayer(sessionLayer); + + auto identifier = sessionLayer->GetIdentifier(); + if (layerManager->findLayer(identifier)) { + // ...and store the name for the (anonymous) session layer so we can find it! + sessionLayerNamePlug().setValue(AL::maya::utils::convert(identifier)); + } else { + // ...make sure for the old Maya scene, we clear the sessionLayerName plug so there + // is no complaint when we open it. + sessionLayerNamePlug().setValue(""); + } + + auto rootLayer = stage->GetRootLayer(); + if (rootLayer->IsAnonymous()) { + // For an anonymous root layer we need to update the file path to match the new + // identifier the layer manager may have associated the layer with. + MPlug filePathPlug = this->filePathPlug(); + const std::string currentRootLayerId + = AL::maya::utils::convert(filePathPlug.asString()); + const std::string& newRootLayerId = rootLayer->GetIdentifier(); + if (currentRootLayerId != newRootLayerId) { + filePathPlug.setString(AL::maya::utils::convert(newRootLayerId)); + } + } + + // Then add in the current edit target + trackEditTargetLayer(layerManager); + } else { + MGlobal::displayError( + "ProxyShape::serialize was passed a nullptr for the layerManager"); } - } + // Make sure our session layer is added to the layer manager to get it serialized. - // Then add in the current edit target - trackEditTargetLayer(layerManager); - } - else - { - MGlobal::displayError("ProxyShape::serialize was passed a nullptr for the layerManager"); + serialiseTranslatorContext(); + serialiseTransformRefs(); } - // Make sure our session layer is added to the layer manager to get it serialized. - - serialiseTranslatorContext(); - serialiseTransformRefs(); - } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::serializeAll() { - TF_DEBUG(ALUSDMAYA_LAYERS).Msg("ProxyShape::serializeAll\n"); - const char* errorString = "ProxyShape::serializeAll"; - // Now iterate over all proxyShapes... - MFnDependencyNode fn; - - // Don't create a layerManager unless we find at least one proxy shape - LayerManager* layerManager = nullptr; - { - MItDependencyNodes iter(MFn::kPluginShape); - for(; !iter.isDone(); iter.next()) + TF_DEBUG(ALUSDMAYA_LAYERS).Msg("ProxyShape::serializeAll\n"); + const char* errorString = "ProxyShape::serializeAll"; + // Now iterate over all proxyShapes... + MFnDependencyNode fn; + + // Don't create a layerManager unless we find at least one proxy shape + LayerManager* layerManager = nullptr; { - MObject mobj = iter.item(); - fn.setObject(mobj); - if(fn.typeId() != ProxyShape::kTypeId) continue; + MItDependencyNodes iter(MFn::kPluginShape); + for (; !iter.isDone(); iter.next()) { + MObject mobj = iter.item(); + fn.setObject(mobj); + if (fn.typeId() != ProxyShape::kTypeId) + continue; + + if (layerManager == nullptr) { + layerManager = LayerManager::findOrCreateManager(); + } - if (layerManager == nullptr) - { - layerManager = LayerManager::findOrCreateManager(); - } - - if(!layerManager) - { - MGlobal::displayError(MString("Error creating layerManager")); - continue; - } - - auto proxyShape = static_cast(fn.userNode()); - if(proxyShape == nullptr) - { - MGlobal::displayError(MString("ProxyShape had no mpx data: ") + fn.name()); - continue; - } - - UsdStageRefPtr stage = proxyShape->getUsdStage(); - - if(!stage) - { - MGlobal::displayError(MString("Could not get stage for proxyShape: ") + fn.name()); - continue; - } - - proxyShape->serialize(stage, layerManager); - } + if (!layerManager) { + MGlobal::displayError(MString("Error creating layerManager")); + continue; + } + + auto proxyShape = static_cast(fn.userNode()); + if (proxyShape == nullptr) { + MGlobal::displayError(MString("ProxyShape had no mpx data: ") + fn.name()); + continue; + } + + UsdStageRefPtr stage = proxyShape->getUsdStage(); + + if (!stage) { + MGlobal::displayError(MString("Could not get stage for proxyShape: ") + fn.name()); + continue; + } + + proxyShape->serialize(stage, layerManager); + } - // Bail if no proxyShapes were found... - if(!layerManager) return; + // Bail if no proxyShapes were found... + if (!layerManager) + return; - // Now that all layers are added, serialize to attributes - AL_MAYA_CHECK_ERROR_RETURN(layerManager->populateSerialisationAttributes(), errorString); - } + // Now that all layers are added, serialize to attributes + AL_MAYA_CHECK_ERROR_RETURN(layerManager->populateSerialisationAttributes(), errorString); + } } //---------------------------------------------------------------------------------------------------------------------- -void ProxyShape::onObjectsChanged(UsdNotice::ObjectsChanged const& notice, UsdStageWeakPtr const& sender) +void ProxyShape::onObjectsChanged( + UsdNotice::ObjectsChanged const& notice, + UsdStageWeakPtr const& sender) { - if(MFileIO::isReadingFile() || AL::usdmaya::utils::BlockNotifications::isBlockingNotifications()) - return; - - if (!sender || sender != m_stage) - return; - - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::onObjectsChanged called m_compositionHasChanged=%i\n", m_compositionHasChanged); + if (MFileIO::isReadingFile() + || AL::usdmaya::utils::BlockNotifications::isBlockingNotifications()) + return; - if (!AL::usd::transaction::TransactionManager::InProgress(sender)) - { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::onObjectsChanged - no transaction in progress - processing all changes\n"); - const UsdNotice::ObjectsChanged::PathRange resyncedPaths = notice.GetResyncedPaths(); - const UsdNotice::ObjectsChanged::PathRange changedOnlyPaths = notice.GetChangedInfoOnlyPaths(); - processChangedObjects(SdfPathVector(resyncedPaths), SdfPathVector(changedOnlyPaths)); + if (!sender || sender != m_stage) + return; - // If redraw wasn't requested from Maya i.e. external stage modification - // We need to request redraw on idle, so viewport is updated - if (!m_requestedRedraw) - { - m_requestedRedraw = true; - MGlobal::executeCommandOnIdle("refresh"); + TF_DEBUG(ALUSDMAYA_EVENTS) + .Msg( + "ProxyShape::onObjectsChanged called m_compositionHasChanged=%i\n", + m_compositionHasChanged); + + if (!AL::usd::transaction::TransactionManager::InProgress(sender)) { + TF_DEBUG(ALUSDMAYA_EVENTS) + .Msg("ProxyShape::onObjectsChanged - no transaction in progress - processing all " + "changes\n"); + const UsdNotice::ObjectsChanged::PathRange resyncedPaths = notice.GetResyncedPaths(); + const UsdNotice::ObjectsChanged::PathRange changedOnlyPaths + = notice.GetChangedInfoOnlyPaths(); + processChangedObjects(SdfPathVector(resyncedPaths), SdfPathVector(changedOnlyPaths)); + + // If redraw wasn't requested from Maya i.e. external stage modification + // We need to request redraw on idle, so viewport is updated + if (!m_requestedRedraw) { + m_requestedRedraw = true; + MGlobal::executeCommandOnIdle("refresh"); + } } - } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::validateTransforms() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("validateTransforms\n"); - if(m_stage) - { - SdfPathVector pathsToNuke; - for(auto& it : m_requiredPaths) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("validateTransforms %s\n", it.first.GetText()); - - MObject node = it.second.node(); - MObjectHandle handle(node); - if(!handle.isValid() || !handle.isAlive()) - { - continue; - } - - if(node.isNull()) - { - continue; - } - - Scope* tm = it.second.getTransformNode(); - if(!tm) - { - UsdPrim newPrim = m_stage->GetPrimAtPath(it.first); - if(!newPrim) - { - pathsToNuke.push_back(it.first); - } - continue; - } - - UsdPrim newPrim = m_stage->GetPrimAtPath(it.first); - if(newPrim) - { - std::string transformType; - newPrim.GetMetadata(Metadata::transformType, &transformType); - if(newPrim && transformType.empty()) - { - tm->transform()->setPrim(newPrim, tm); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("validateTransforms\n"); + if (m_stage) { + SdfPathVector pathsToNuke; + for (auto& it : m_requiredPaths) { + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("validateTransforms %s\n", it.first.GetText()); + + MObject node = it.second.node(); + MObjectHandle handle(node); + if (!handle.isValid() || !handle.isAlive()) { + continue; + } + + if (node.isNull()) { + continue; + } + + Scope* tm = it.second.getTransformNode(); + if (!tm) { + UsdPrim newPrim = m_stage->GetPrimAtPath(it.first); + if (!newPrim) { + pathsToNuke.push_back(it.first); + } + continue; + } + + UsdPrim newPrim = m_stage->GetPrimAtPath(it.first); + if (newPrim) { + std::string transformType; + newPrim.GetMetadata(Metadata::transformType, &transformType); + if (newPrim && transformType.empty()) { + tm->transform()->setPrim(newPrim, tm); + } + } else { + pathsToNuke.push_back(it.first); + } } - } - else - { - pathsToNuke.push_back(it.first); - } } - } - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("/validateTransforms\n"); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("/validateTransforms\n"); } //---------------------------------------------------------------------------------------------------------------------- -void ProxyShape::onTransactionNotice(AL::usd::transaction::CloseNotice const ¬ice, const UsdStageWeakPtr& stage) +void ProxyShape::onTransactionNotice( + AL::usd::transaction::CloseNotice const& notice, + const UsdStageWeakPtr& stage) { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::onTransactionNotice - transaction closed - processing changes\n"); + TF_DEBUG(ALUSDMAYA_EVENTS) + .Msg("ProxyShape::onTransactionNotice - transaction closed - processing changes\n"); - processChangedObjects(notice.GetResyncedPaths(), notice.GetChangedInfoOnlyPaths()); - if (!m_requestedRedraw) - { - m_requestedRedraw = true; - MGlobal::executeCommandOnIdle("refresh"); - } + processChangedObjects(notice.GetResyncedPaths(), notice.GetChangedInfoOnlyPaths()); + if (!m_requestedRedraw) { + m_requestedRedraw = true; + MGlobal::executeCommandOnIdle("refresh"); + } } //---------------------------------------------------------------------------------------------------------------------- -void ProxyShape::processChangedObjects(const SdfPathVector& resyncedPaths, const SdfPathVector& changedOnlyPaths) +void ProxyShape::processChangedObjects( + const SdfPathVector& resyncedPaths, + const SdfPathVector& changedOnlyPaths) { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::processChangedObjects - processing changes\n"); - - bool shouldCleanBBoxCache = false; + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::processChangedObjects - processing changes\n"); - if (!m_stage) - { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::processChangedObjects - Invalid stage\n"); - return; - } + bool shouldCleanBBoxCache = false; - for(const SdfPath& path : resyncedPaths) - { - auto it = m_requiredPaths.find(path); - if(it != m_requiredPaths.end()) - { - UsdPrim newPrim = m_stage->GetPrimAtPath(path); - if (!newPrim.IsValid()) - { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::processChangedObjects - resyncedPaths (1) contains invalid path %s\n", path.GetText()); - continue; - } - Scope* tm = it->second.getTransformNode(); - if(!tm) - continue; - BasicTransformationMatrix* tmm = tm->transform(); - if(!tmm) - continue; - tmm->setPrim(newPrim, tm); // Might be (invalid/nullptr) but that's OK at least it won't crash + if (!m_stage) { + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::processChangedObjects - Invalid stage\n"); + return; } - else - { - UsdPrim newPrim = m_stage->GetPrimAtPath(path); - if (!newPrim.IsValid()) - { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::processChangedObjects - resyncedPaths (2) contains invalid path %s\n", path.GetText()); - continue; - } - if(newPrim && newPrim.IsA()) - { - shouldCleanBBoxCache = true; - } + + for (const SdfPath& path : resyncedPaths) { + auto it = m_requiredPaths.find(path); + if (it != m_requiredPaths.end()) { + UsdPrim newPrim = m_stage->GetPrimAtPath(path); + if (!newPrim.IsValid()) { + TF_DEBUG(ALUSDMAYA_EVENTS) + .Msg( + "ProxyShape::processChangedObjects - resyncedPaths (1) contains invalid " + "path %s\n", + path.GetText()); + continue; + } + Scope* tm = it->second.getTransformNode(); + if (!tm) + continue; + BasicTransformationMatrix* tmm = tm->transform(); + if (!tmm) + continue; + tmm->setPrim( + newPrim, tm); // Might be (invalid/nullptr) but that's OK at least it won't crash + } else { + UsdPrim newPrim = m_stage->GetPrimAtPath(path); + if (!newPrim.IsValid()) { + TF_DEBUG(ALUSDMAYA_EVENTS) + .Msg( + "ProxyShape::processChangedObjects - resyncedPaths (2) contains invalid " + "path %s\n", + path.GetText()); + continue; + } + if (newPrim && newPrim.IsA()) { + shouldCleanBBoxCache = true; + } + } } - } - // check to see if any transform ops have been modified (update the bounds accordingly) - if(!shouldCleanBBoxCache) - { - for(const SdfPath& path : changedOnlyPaths) - { - UsdPrim changedPrim = m_stage->GetPrimAtPath(path); - if(path.IsPrimPropertyPath()) - { - const std::string tokenString = path.GetElementString(); - if(std::strncmp(tokenString.c_str(), ".xformOp", 8) == 0) - { - shouldCleanBBoxCache = true; - break; + // check to see if any transform ops have been modified (update the bounds accordingly) + if (!shouldCleanBBoxCache) { + for (const SdfPath& path : changedOnlyPaths) { + UsdPrim changedPrim = m_stage->GetPrimAtPath(path); + if (path.IsPrimPropertyPath()) { + const std::string tokenString = path.GetElementString(); + if (std::strncmp(tokenString.c_str(), ".xformOp", 8) == 0) { + shouldCleanBBoxCache = true; + break; + } + } } - } } - } - - // do we need to clear the bounding box cache? - if(shouldCleanBBoxCache) - { - clearBoundingBoxCache(); - - // Ideally we want to have a way to force maya to call ProxyShape::boundingBox() again to update the bbox attributes. - // This may lead to a delay in the bbox updates (e.g. usually you need to reselect the proxy before the bounds will - // be updated). - } - - if(isLockPrimFeatureActive()) - { - processChangedMetaData(resyncedPaths, changedOnlyPaths); - } - - // These paths are subtree-roots representing entire subtrees that may have - // changed. In this case, we must dump all cached data below these points - // and repopulate those trees. - if(m_compositionHasChanged) - { - m_compositionHasChanged = false; - onPrimResync(m_changedPath, m_variantSwitchedPrims); - m_variantSwitchedPrims.clear(); - m_changedPath = SdfPath(); - - std::stringstream strstr; - strstr << "Breakdown for Variant Switch:\n"; - AL::usdmaya::Profiler::printReport(strstr); - } + + // do we need to clear the bounding box cache? + if (shouldCleanBBoxCache) { + clearBoundingBoxCache(); + + // Ideally we want to have a way to force maya to call ProxyShape::boundingBox() again to + // update the bbox attributes. This may lead to a delay in the bbox updates (e.g. usually + // you need to reselect the proxy before the bounds will be updated). + } + + if (isLockPrimFeatureActive()) { + processChangedMetaData(resyncedPaths, changedOnlyPaths); + } + + // These paths are subtree-roots representing entire subtrees that may have + // changed. In this case, we must dump all cached data below these points + // and repopulate those trees. + if (m_compositionHasChanged) { + m_compositionHasChanged = false; + onPrimResync(m_changedPath, m_variantSwitchedPrims); + m_variantSwitchedPrims.clear(); + m_changedPath = SdfPath(); + + std::stringstream strstr; + strstr << "Breakdown for Variant Switch:\n"; + AL::usdmaya::Profiler::printReport(strstr); + } } //---------------------------------------------------------------------------------------------------------------------- std::vector ProxyShape::huntForNativeNodesUnderPrim( - const MDagPath& proxyTransformPath, - SdfPath startPath, + const MDagPath& proxyTransformPath, + SdfPath startPath, fileio::translators::TranslatorManufacture& manufacture, - const bool importAll) + const bool importAll) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::huntForNativeNodesUnderPrim\n"); - std::vector prims; - fileio::SchemaPrimsUtils utils(manufacture); - - const UsdPrim prim = m_stage->GetPrimAtPath(startPath); - if (!prim.IsValid()) - { - MString errorString; - errorString.format(MString("'^1s' is not a valid prim path in proxy shape: '^2s'"), - startPath.GetString().c_str(), - proxyTransformPath.fullPathName()); - MGlobal::displayError(errorString); - return prims; - } - - fileio::TransformIterator it(prim, proxyTransformPath); - for(; !it.done(); it.next()) - { - UsdPrim prim = it.prim(); - if(!prim.IsValid()) - { - continue; + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::huntForNativeNodesUnderPrim\n"); + std::vector prims; + fileio::SchemaPrimsUtils utils(manufacture); + + const UsdPrim prim = m_stage->GetPrimAtPath(startPath); + if (!prim.IsValid()) { + MString errorString; + errorString.format( + MString("'^1s' is not a valid prim path in proxy shape: '^2s'"), + startPath.GetString().c_str(), + proxyTransformPath.fullPathName()); + MGlobal::displayError(errorString); + return prims; } - fileio::translators::TranslatorRefPtr trans = utils.isSchemaPrim(prim); - if(trans && (trans->importableByDefault() || importAll)) - { - prims.push_back(prim); + fileio::TransformIterator it(prim, proxyTransformPath); + for (; !it.done(); it.next()) { + UsdPrim prim = it.prim(); + if (!prim.IsValid()) { + continue; + } + + fileio::translators::TranslatorRefPtr trans = utils.isSchemaPrim(prim); + if (trans && (trans->importableByDefault() || importAll)) { + prims.push_back(prim); + } } - } - return prims; + return prims; } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::onPrePrimChanged(const SdfPath& path, SdfPathVector& outPathVector) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::onPrePrimChanged\n"); - context()->preRemoveEntry(path, outPathVector); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::onPrePrimChanged\n"); + context()->preRemoveEntry(path, outPathVector); } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::variantSelectionListener(SdfNotice::LayersDidChange const& notice) -// In order to detect changes to the variant selection we listen on the SdfNotice::LayersDidChange global notice which is -// sent to indicate that layer contents have changed. We are then able to access the change list to check if a variant -// selection change happened. If so, we trigger a ProxyShapePostLoadProcess() which will regenerate the alTransform -// nodes based on the contents of the new variant selection. +// In order to detect changes to the variant selection we listen on the SdfNotice::LayersDidChange +// global notice which is sent to indicate that layer contents have changed. We are then able to +// access the change list to check if a variant selection change happened. If so, we trigger a +// ProxyShapePostLoadProcess() which will regenerate the alTransform nodes based on the contents of +// the new variant selection. { - if(MFileIO::isReadingFile()) - return; + if (MFileIO::isReadingFile()) + return; - if (!m_stage) - return; + if (!m_stage) + return; - const SdfLayerHandleVector stack = m_stage->GetLayerStack(); + const SdfLayerHandleVector stack = m_stage->GetLayerStack(); #if USD_VERSION_NUM > 1911 - TF_FOR_ALL(itr, notice.GetChangeListVec()) + TF_FOR_ALL(itr, notice.GetChangeListVec()) #else - TF_FOR_ALL(itr, notice.GetChangeListMap()) + TF_FOR_ALL(itr, notice.GetChangeListMap()) #endif - { - if (std::find(stack.begin(), stack.end(), itr->first) == stack.end()) - continue; - - TF_FOR_ALL(entryIter, itr->second.GetEntryList()) { - const SdfPath &path = entryIter->first; - const SdfChangeList::Entry &entry = entryIter->second; + if (std::find(stack.begin(), stack.end(), itr->first) == stack.end()) + continue; - TF_FOR_ALL(it, entry.infoChanged) - { - if (it->first == SdfFieldKeys->VariantSelection || - it->first == SdfFieldKeys->Active) + TF_FOR_ALL(entryIter, itr->second.GetEntryList()) { - triggerEvent("PreVariantChangedCB"); - - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::variantSelectionListener oldPath=%s, oldIdentifier=%s, path=%s, layer=%s\n", - entry.oldPath.GetText(), - entry.oldIdentifier.c_str(), - path.GetText(), - itr->first->GetIdentifier().c_str()); - if(!m_compositionHasChanged) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::Not yet in a composition change state. Recording path. \n"); - m_changedPath = path; - } - m_compositionHasChanged = true; - onPrePrimChanged(path, m_variantSwitchedPrims); - - triggerEvent("PostVariantChangedCB"); + const SdfPath& path = entryIter->first; + const SdfChangeList::Entry& entry = entryIter->second; + + TF_FOR_ALL(it, entry.infoChanged) + { + if (it->first == SdfFieldKeys->VariantSelection + || it->first == SdfFieldKeys->Active) { + triggerEvent("PreVariantChangedCB"); + + TF_DEBUG(ALUSDMAYA_EVENTS) + .Msg( + "ProxyShape::variantSelectionListener oldPath=%s, oldIdentifier=%s, " + "path=%s, layer=%s\n", + entry.oldPath.GetText(), + entry.oldIdentifier.c_str(), + path.GetText(), + itr->first->GetIdentifier().c_str()); + if (!m_compositionHasChanged) { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg("ProxyShape::Not yet in a composition change state. Recording " + "path. \n"); + m_changedPath = path; + } + m_compositionHasChanged = true; + onPrePrimChanged(path, m_variantSwitchedPrims); + + triggerEvent("PostVariantChangedCB"); + } + } } - } } - } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::loadStage() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::loadStage\n"); - - triggerEvent("PreStageLoaded"); - - AL_BEGIN_PROFILE_SECTION(LoadStage); - MDataBlock dataBlock = forceCache(); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::loadStage\n"); + + triggerEvent("PreStageLoaded"); + + AL_BEGIN_PROFILE_SECTION(LoadStage); + MDataBlock dataBlock = forceCache(); + + const int stageIdVal = inputInt32Value(dataBlock, stageCacheId()); + UsdStageCache::Id stageId = UsdStageCache::Id().FromLongInt(stageIdVal); + MString file = inputStringValue(dataBlock, filePath()); + + if (m_stage) { + // In case there was already a stage in m_stage, check to see if it's edit target has been + // altered. + trackEditTargetLayer(); + + if (StageCache::Get().Contains(stageId)) { + auto stageFromId = StageCache::Get().Find(stageId); + const MString stageFilePath + = AL::maya::utils::convert(stageFromId->GetRootLayer()->GetIdentifier()); + if (file != stageFilePath) { + // When we have an existing stage and a valid stageCacheId, if file paths of the + // stage from cache doesn't match that the one we are holding on to, then looks like + // file path was changed. Drop the current cache Id. + stageId = UsdStageCache::Id(); + } + } + } - const int stageIdVal = inputInt32Value(dataBlock, stageCacheId()); - UsdStageCache::Id stageId = UsdStageCache::Id().FromLongInt(stageIdVal); - MString file = inputStringValue(dataBlock, filePath()); + if (stageId.IsValid()) { + // Load stage from cache. + if (StageCache::Get().Contains(stageId)) { + m_stage = StageCache::Get().Find(stageId); + // Save the initial edit target and all dirty layers. + trackAllDirtyLayers(); + file.set(m_stage->GetRootLayer()->GetIdentifier().c_str()); + outputStringValue(dataBlock, filePath(), file); + } else { + MGlobal::displayError( + MString("ProxyShape::loadStage called with non-existent stageCacheId ") + + stageId.ToString().c_str()); + stageId = UsdStageCache::Id(); + } - if (m_stage) - { - // In case there was already a stage in m_stage, check to see if it's edit target has been altered. - trackEditTargetLayer(); + // Save variant fallbacks from session layer to Maya node attribute + if (m_stage) { + saveVariantFallbacks( + getVariantFallbacksFromLayer(m_stage->GetSessionLayer()), dataBlock); + } + } else { + m_stage = UsdStageRefPtr(); - if (StageCache::Get().Contains(stageId)) - { - auto stageFromId = StageCache::Get().Find(stageId); - const MString stageFilePath = AL::maya::utils::convert(stageFromId->GetRootLayer()->GetIdentifier()); - if (file != stageFilePath) - { - // When we have an existing stage and a valid stageCacheId, if file paths of the stage from cache - // doesn't match that the one we are holding on to, then looks like file path was changed. Drop the current - // cache Id. - stageId = UsdStageCache::Id(); - } - } - } + // Get input attr values + const MString sessionLayerName = inputStringValue(dataBlock, m_sessionLayerName); - if (stageId.IsValid()) - { - // Load stage from cache. - if (StageCache::Get().Contains(stageId)) - { - m_stage = StageCache::Get().Find(stageId); - // Save the initial edit target and all dirty layers. - trackAllDirtyLayers(); - file.set(m_stage->GetRootLayer()->GetIdentifier().c_str()); - outputStringValue(dataBlock, filePath(), file); - } - else - { - MGlobal::displayError(MString("ProxyShape::loadStage called with non-existent stageCacheId ") + stageId.ToString().c_str()); - stageId = UsdStageCache::Id(); - } + const MString populationMaskIncludePaths + = inputStringValue(dataBlock, m_populationMaskIncludePaths); + UsdStagePopulationMask mask = constructStagePopulationMask(populationMaskIncludePaths); - // Save variant fallbacks from session layer to Maya node attribute - if (m_stage) - { - saveVariantFallbacks(getVariantFallbacksFromLayer(m_stage->GetSessionLayer()), dataBlock); - } - } - else - { - m_stage = UsdStageRefPtr(); + // TODO initialise the context using the serialised attribute - // Get input attr values - const MString sessionLayerName = inputStringValue(dataBlock, m_sessionLayerName); + // let the usd stage cache deal with caching the usd stage data + std::string fileString = TfStringTrimRight(file.asChar()); - const MString populationMaskIncludePaths = inputStringValue(dataBlock, m_populationMaskIncludePaths); - UsdStagePopulationMask mask = constructStagePopulationMask(populationMaskIncludePaths); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("ProxyShape::reloadStage original USD file path is %s\n", fileString.c_str()); - // TODO initialise the context using the serialised attribute + SdfLayerRefPtr rootLayer; + if (SdfLayer::IsAnonymousLayerIdentifier(fileString)) { + // For anonymous root layer we must explicitly ask for from the layer manager. + // This is because USD does not allow us to create a new anonymous SdfLayer + // with the exact same identifier. The best we can do is to ask the layer manager + // to create the anonymous layer, and let it manage the identifier mappings. + if (auto layerManager = LayerManager::findManager()) { + rootLayer = layerManager->findLayer(fileString); + } - // let the usd stage cache deal with caching the usd stage data - std::string fileString = TfStringTrimRight(file.asChar()); + if (rootLayer) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShape::reloadStage found anonymous layer %s from layer manager\n", + fileString.c_str()); + } else { + const std::string tag = SdfLayer::GetDisplayNameFromIdentifier(fileString); + rootLayer = SdfLayer::CreateAnonymous(tag); + if (rootLayer) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShape::reloadStage created anonymous layer %s (renamed to %s)\n", + fileString.c_str(), + rootLayer->GetIdentifier().c_str()); + } + } + } else { + boost::filesystem::path filestringPath(fileString); + if (filestringPath.is_absolute()) { + fileString = UsdMayaUtilFileSystem::resolvePath(fileString); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShape::reloadStage resolved the USD file path to %s\n", + fileString.c_str()); + } else { + fileString = UsdMayaUtilFileSystem::resolveRelativePathWithinMayaContext( + thisMObject(), fileString); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "ProxyShape::reloadStage resolved the relative USD file path to %s\n", + fileString.c_str()); + } - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::reloadStage original USD file path is %s\n", fileString.c_str()); + // Fall back on providing the path "as is" to USD + if (fileString.empty()) { + fileString.assign(file.asChar(), file.length()); + } - SdfLayerRefPtr rootLayer; - if (SdfLayer::IsAnonymousLayerIdentifier(fileString)) - { - // For anonymous root layer we must explicitly ask for from the layer manager. - // This is because USD does not allow us to create a new anonymous SdfLayer - // with the exact same identifier. The best we can do is to ask the layer manager - // to create the anonymous layer, and let it manage the identifier mappings. - if (auto layerManager = LayerManager::findManager()) - { - rootLayer = layerManager->findLayer(fileString); - } - - if (rootLayer) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg( - "ProxyShape::reloadStage found anonymous layer %s from layer manager\n", - fileString.c_str() - ); - } - else - { - const std::string tag = SdfLayer::GetDisplayNameFromIdentifier(fileString); - rootLayer = SdfLayer::CreateAnonymous(tag); - if (rootLayer) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg( - "ProxyShape::reloadStage created anonymous layer %s (renamed to %s)\n", - fileString.c_str(), - rootLayer->GetIdentifier().c_str() - ); + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("ProxyShape::loadStage called for the usd file: %s\n", fileString.c_str()); + rootLayer = SdfLayer::FindOrOpen(fileString); } - } - } - else - { - boost::filesystem::path filestringPath(fileString); - if (filestringPath.is_absolute()) - { - fileString = UsdMayaUtilFileSystem::resolvePath(fileString); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::reloadStage resolved the USD file path to %s\n", - fileString.c_str()); - } - else - { - fileString = UsdMayaUtilFileSystem::resolveRelativePathWithinMayaContext(thisMObject(), fileString); - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::reloadStage resolved the relative USD file path to %s\n", - fileString.c_str()); - } - - // Fall back on providing the path "as is" to USD - if (fileString.empty()) - { - fileString.assign(file.asChar(), file.length()); - } - - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::loadStage called for the usd file: %s\n", fileString.c_str()); - rootLayer = SdfLayer::FindOrOpen(fileString); - } - // Only try to create a stage for layers that can be opened. - if (rootLayer) - { - MStatus status; - SdfLayerRefPtr sessionLayer; + // Only try to create a stage for layers that can be opened. + if (rootLayer) { + MStatus status; + SdfLayerRefPtr sessionLayer; - AL_BEGIN_PROFILE_SECTION(OpeningUsdStage); - AL_BEGIN_PROFILE_SECTION(OpeningSessionLayer); - { - // Grab the session layer from the layer manager - if (sessionLayerName.length() > 0) - { - auto layerManager = LayerManager::findManager(); - if (layerManager) + AL_BEGIN_PROFILE_SECTION(OpeningUsdStage); + AL_BEGIN_PROFILE_SECTION(OpeningSessionLayer); { - sessionLayer = layerManager->findLayer(AL::maya::utils::convert(sessionLayerName)); - if (!sessionLayer) - { - MGlobal::displayError(MString("ProxyShape \"") + name() + "\" had a serialized session layer" - " named \"" + sessionLayerName + - "\", but no matching layer could be found in the layerManager"); - } + // Grab the session layer from the layer manager + if (sessionLayerName.length() > 0) { + auto layerManager = LayerManager::findManager(); + if (layerManager) { + sessionLayer + = layerManager->findLayer(AL::maya::utils::convert(sessionLayerName)); + if (!sessionLayer) { + MGlobal::displayError( + MString("ProxyShape \"") + name() + + "\" had a serialized session layer" + " named \"" + + sessionLayerName + + "\", but no matching layer could be found in the layerManager"); + } + } else { + MGlobal::displayError( + MString("ProxyShape \"") + name() + + "\" had a serialized session layer," + " but no layerManager node was found"); + } + } + + // If we still have no sessionLayer, but there's data in serializedSessionLayer, + // then assume we're reading an "old" file, and read it for backwards compatibility. + if (!sessionLayer) { + const MString serializedSessionLayer + = inputStringValue(dataBlock, m_serializedSessionLayer); + if (serializedSessionLayer.length() != 0) { + sessionLayer = SdfLayer::CreateAnonymous(); + sessionLayer->ImportFromString( + AL::maya::utils::convert(serializedSessionLayer)); + } + } } - else - { - MGlobal::displayError(MString("ProxyShape \"") + name() + "\" had a serialized session layer," - " but no layerManager node was found"); - } - } - - // If we still have no sessionLayer, but there's data in serializedSessionLayer, then - // assume we're reading an "old" file, and read it for backwards compatibility. - if (!sessionLayer) - { - const MString serializedSessionLayer = inputStringValue(dataBlock, m_serializedSessionLayer); - if (serializedSessionLayer.length() != 0) - { - sessionLayer = SdfLayer::CreateAnonymous(); - sessionLayer->ImportFromString(AL::maya::utils::convert(serializedSessionLayer)); + AL_END_PROFILE_SECTION(); + + AL_BEGIN_PROFILE_SECTION(OpenRootLayer); + + const MString assetResolverConfig = inputStringValue(dataBlock, m_assetResolverConfig); + + if (assetResolverConfig.length() == 0) { + // Initialise the asset resolver with the filepath + PXR_NS::ArGetResolver().ConfigureResolverForAsset(fileString); + } else { + // Initialise the asset resolver with the resolverConfig string + PXR_NS::ArGetResolver().ConfigureResolverForAsset(assetResolverConfig.asChar()); } - } - } - AL_END_PROFILE_SECTION(); + AL_END_PROFILE_SECTION(); - AL_BEGIN_PROFILE_SECTION(OpenRootLayer); + AL_BEGIN_PROFILE_SECTION(UpdateGlobalVariantFallbacks); + PcpVariantFallbackMap defaultVariantFallbacks; + PcpVariantFallbackMap fallbacks( + updateVariantFallbacks(defaultVariantFallbacks, dataBlock)); + AL_END_PROFILE_SECTION(); - const MString assetResolverConfig = inputStringValue(dataBlock, m_assetResolverConfig); + AL_BEGIN_PROFILE_SECTION(UsdStageOpen); + { + UsdStageCacheContext ctx(StageCache::Get()); + + bool unloadedFlag = inputBoolValue(dataBlock, m_unloaded); + UsdStage::InitialLoadSet loadOperation + = unloadedFlag ? UsdStage::LoadNone : UsdStage::LoadAll; + + if (sessionLayer) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("ProxyShape::loadStage is called with extra session layer.\n"); + m_stage = UsdStage::OpenMasked(rootLayer, sessionLayer, mask, loadOperation); + } else { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("ProxyShape::loadStage is called without any session layer.\n"); + m_stage = UsdStage::OpenMasked(rootLayer, mask, loadOperation); + } + + // Expand the mask, since we do not really want to mask the possible relation + // targets. + m_stage->ExpandPopulationMask(); + + stageId = StageCache::Get().Insert(m_stage); + outputInt32Value(dataBlock, stageCacheId(), stageId.ToLongInt()); + + // Set the stage in datablock so it's ready in case it needs to be accessed + MObject data; + MayaUsdStageData* usdStageData + = createData(MayaUsdStageData::mayaTypeId, data); + usdStageData->stage = m_stage; + usdStageData->primPath = m_path; + outputDataValue(dataBlock, outStageData(), usdStageData); + + // Set the edit target to the session layer so any user interaction will wind up + // there + m_stage->SetEditTarget(m_stage->GetSessionLayer()); + // Save the initial edit target + trackEditTargetLayer(); + } + AL_END_PROFILE_SECTION(); + + AL_BEGIN_PROFILE_SECTION(ResetGlobalVariantFallbacks); + // reset only if the global variant fallbacks has been modified + if (!fallbacks.empty()) { + saveVariantFallbacks(convertVariantFallbacksToStr(fallbacks), dataBlock); + // restore default value + UsdStage::SetGlobalVariantFallbacks(defaultVariantFallbacks); + } + AL_END_PROFILE_SECTION(); - if (assetResolverConfig.length()==0) - { - // Initialise the asset resolver with the filepath - PXR_NS::ArGetResolver().ConfigureResolverForAsset(fileString); + AL_END_PROFILE_SECTION(); + } else if (!fileString.empty()) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("ProxyShape::loadStage failed to open the usd file: %s.\n", file.asChar()); + MGlobal::displayWarning(MString("Failed to open usd file \"") + file + "\""); } - else - { - // Initialise the asset resolver with the resolverConfig string - PXR_NS::ArGetResolver().ConfigureResolverForAsset(assetResolverConfig.asChar()); - } - AL_END_PROFILE_SECTION(); - - AL_BEGIN_PROFILE_SECTION(UpdateGlobalVariantFallbacks); - PcpVariantFallbackMap defaultVariantFallbacks; - PcpVariantFallbackMap fallbacks(updateVariantFallbacks(defaultVariantFallbacks, dataBlock)); - AL_END_PROFILE_SECTION(); + } - AL_BEGIN_PROFILE_SECTION(UsdStageOpen); - { - UsdStageCacheContext ctx(StageCache::Get()); - - bool unloadedFlag = inputBoolValue(dataBlock, m_unloaded); - UsdStage::InitialLoadSet loadOperation = unloadedFlag ? UsdStage::LoadNone : UsdStage::LoadAll; - - if (sessionLayer) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::loadStage is called with extra session layer.\n"); - m_stage = UsdStage::OpenMasked(rootLayer, sessionLayer, mask, loadOperation); - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::loadStage is called without any session layer.\n"); - m_stage = UsdStage::OpenMasked(rootLayer, mask, loadOperation); - } - - // Expand the mask, since we do not really want to mask the possible relation targets. - m_stage->ExpandPopulationMask(); - - stageId = StageCache::Get().Insert(m_stage); - outputInt32Value(dataBlock, stageCacheId(), stageId.ToLongInt()); - - // Set the stage in datablock so it's ready in case it needs to be accessed - MObject data; - MayaUsdStageData* usdStageData = createData(MayaUsdStageData::mayaTypeId, data); - usdStageData->stage = m_stage; - usdStageData->primPath = m_path; - outputDataValue(dataBlock, outStageData(), usdStageData); - - // Set the edit target to the session layer so any user interaction will wind up there - m_stage->SetEditTarget(m_stage->GetSessionLayer()); - // Save the initial edit target - trackEditTargetLayer(); + // Get the prim + // If no primPath string specified, then use the pseudo-root. + const SdfPath rootPath(std::string("/")); + MString primPathStr = inputStringValue(dataBlock, primPath()); + if (primPathStr.length()) { + m_path = SdfPath(AL::maya::utils::convert(primPathStr)); + UsdPrim prim = m_stage->GetPrimAtPath(m_path); + if (!prim) { + m_path = rootPath; } - AL_END_PROFILE_SECTION(); + } else { + m_path = rootPath; + } - AL_BEGIN_PROFILE_SECTION(ResetGlobalVariantFallbacks); - // reset only if the global variant fallbacks has been modified - if (!fallbacks.empty()) - { - saveVariantFallbacks(convertVariantFallbacksToStr(fallbacks), dataBlock); - // restore default value - UsdStage::SetGlobalVariantFallbacks(defaultVariantFallbacks); + if (m_stage && !MFileIO::isReadingFile()) { + AL_BEGIN_PROFILE_SECTION(PostLoadProcess); + // execute the post load process to import any custom prims + cmds::ProxyShapePostLoadProcess::initialise(this); + if (isLockPrimFeatureActive()) { + findPrimsWithMetaData(); } AL_END_PROFILE_SECTION(); - - AL_END_PROFILE_SECTION(); - } - else if (!fileString.empty()) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::loadStage failed to open the usd file: %s.\n", file.asChar()); - MGlobal::displayWarning(MString("Failed to open usd file \"") + file + "\""); - } - } - - // Get the prim - // If no primPath string specified, then use the pseudo-root. - const SdfPath rootPath(std::string("/")); - MString primPathStr = inputStringValue(dataBlock, primPath()); - if (primPathStr.length()) - { - m_path = SdfPath(AL::maya::utils::convert(primPathStr)); - UsdPrim prim = m_stage->GetPrimAtPath(m_path); - if(!prim) - { - m_path = rootPath; } - } - else - { - m_path = rootPath; - } - - if(m_stage && !MFileIO::isReadingFile()) - { - AL_BEGIN_PROFILE_SECTION(PostLoadProcess); - // execute the post load process to import any custom prims - cmds::ProxyShapePostLoadProcess::initialise(this); - if(isLockPrimFeatureActive()) - { - findPrimsWithMetaData(); - } - AL_END_PROFILE_SECTION(); - } - AL_END_PROFILE_SECTION(); + AL_END_PROFILE_SECTION(); - if(MGlobal::kInteractive == MGlobal::mayaState()) - { - std::stringstream strstr; - strstr << "Breakdown for file: " << file << std::endl; - AL::usdmaya::Profiler::printReport(strstr); - MGlobal::displayInfo(AL::maya::utils::convert(strstr.str())); - } + if (MGlobal::kInteractive == MGlobal::mayaState()) { + std::stringstream strstr; + strstr << "Breakdown for file: " << file << std::endl; + AL::usdmaya::Profiler::printReport(strstr); + MGlobal::displayInfo(AL::maya::utils::convert(strstr.str())); + } - destroyGLImagingEngine(); - stageDataDirtyPlug().setValue(true); + destroyGLImagingEngine(); + stageDataDirtyPlug().setValue(true); - triggerEvent("PostStageLoaded"); + triggerEvent("PostStageLoaded"); } - //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::postConstructor() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::postConstructor\n"); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::postConstructor\n"); - ParentClass::postConstructor(); + ParentClass::postConstructor(); - // Apply render defaults - MPlug(thisMObject(), m_visibleInReflections).setValue(true); - MPlug(thisMObject(), m_visibleInRefractions).setValue(true); + // Apply render defaults + MPlug(thisMObject(), m_visibleInReflections).setValue(true); + MPlug(thisMObject(), m_visibleInRefractions).setValue(true); } //---------------------------------------------------------------------------------------------------------------------- -MString ProxyShape::recordUsdPrimToMayaPath(const UsdPrim &usdPrim, - const MObject &mayaObject) +MString ProxyShape::recordUsdPrimToMayaPath(const UsdPrim& usdPrim, const MObject& mayaObject) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::recordUsdPrimToMayaPath store path to %s\n", usdPrim.GetPrimPath().GetText()); - - // Retrieve the proxy shapes transform path which will be used in the - // UsdPrim->MayaNode mapping in the case where there is delayed node creation. - MFnDagNode shapeFn(thisMObject()); - const MObject shapeParent = shapeFn.parent(0); - MDagPath mayaPath; - // Note: This doesn't account for the possibility of multiple paths to a node, but so far this - // is only used for recently created transforms that should only have single paths. - MDagPath::getAPathTo(shapeParent, mayaPath); - - MString resultingPath; - SdfPath primPath(usdPrim.GetPath()); - resultingPath = AL::usdmaya::utils::mapUsdPrimToMayaNode(usdPrim, mayaObject, &mayaPath); - m_primPathToDagPath.emplace(primPath, resultingPath); - - return resultingPath; + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "ProxyShape::recordUsdPrimToMayaPath store path to %s\n", + usdPrim.GetPrimPath().GetText()); + + // Retrieve the proxy shapes transform path which will be used in the + // UsdPrim->MayaNode mapping in the case where there is delayed node creation. + MFnDagNode shapeFn(thisMObject()); + const MObject shapeParent = shapeFn.parent(0); + MDagPath mayaPath; + // Note: This doesn't account for the possibility of multiple paths to a node, but so far this + // is only used for recently created transforms that should only have single paths. + MDagPath::getAPathTo(shapeParent, mayaPath); + + MString resultingPath; + SdfPath primPath(usdPrim.GetPath()); + resultingPath = AL::usdmaya::utils::mapUsdPrimToMayaNode(usdPrim, mayaObject, &mayaPath); + m_primPathToDagPath.emplace(primPath, resultingPath); + + return resultingPath; } //---------------------------------------------------------------------------------------------------------------------- MString ProxyShape::getMayaPathFromUsdPrim(const UsdPrim& usdPrim) const { - PrimPathToDagPath::const_iterator itr = m_primPathToDagPath.find(usdPrim.GetPath()); - if (itr == m_primPathToDagPath.end()){ - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::getMayaPathFromUsdPrim could not find stored MayaPath\n"); - return MString(); - } - return itr->second; + PrimPathToDagPath::const_iterator itr = m_primPathToDagPath.find(usdPrim.GetPath()); + if (itr == m_primPathToDagPath.end()) { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg("ProxyShape::getMayaPathFromUsdPrim could not find stored MayaPath\n"); + return MString(); + } + return itr->second; } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::copyInternalData(MPxNode* srcNode) { - // On duplication, the ProxyShape has a null stage, and m_filePathDirty is - // false, even if the file path attribute is set. We must ensure the next - // call to computeOutStageData() calls loadStage(). - m_filePathDirty = true; + // On duplication, the ProxyShape has a null stage, and m_filePathDirty is + // false, even if the file path attribute is set. We must ensure the next + // call to computeOutStageData() calls loadStage(). + m_filePathDirty = true; } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShape::computeOutStageData(const MPlug& plug, MDataBlock& dataBlock) { - // create new stage data - MObject data; - MayaUsdStageData* usdStageData = createData(MayaUsdStageData::mayaTypeId, data); - if(!usdStageData) - { - return MS::kFailure; - } - - // make sure a stage is loaded - if (!m_stage && m_filePathDirty) - { - m_filePathDirty = false; - loadStage(); - } - // Set the output stage data params - usdStageData->stage = m_stage; - usdStageData->primPath = m_path; - - // set the cached output value, and flush - MStatus status = outputDataValue(dataBlock, outStageData(), usdStageData); - if(!status) - { - return MS::kFailure; - } - - MayaUsdProxyStageSetNotice(*this).Send(); - - return status; + // create new stage data + MObject data; + MayaUsdStageData* usdStageData + = createData(MayaUsdStageData::mayaTypeId, data); + if (!usdStageData) { + return MS::kFailure; + } + + // make sure a stage is loaded + if (!m_stage && m_filePathDirty) { + m_filePathDirty = false; + loadStage(); + } + // Set the output stage data params + usdStageData->stage = m_stage; + usdStageData->primPath = m_path; + + // set the cached output value, and flush + MStatus status = outputDataValue(dataBlock, outStageData(), usdStageData); + if (!status) { + return MS::kFailure; + } + + MayaUsdProxyStageSetNotice(*this).Send(); + + return status; } //---------------------------------------------------------------------------------------------------------------------- bool ProxyShape::isStageValid() const { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::isStageValid\n"); - MDataBlock dataBlock = const_cast(this)->forceCache(); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::isStageValid\n"); + MDataBlock dataBlock = const_cast(this)->forceCache(); - MayaUsdStageData* outData = inputDataValue(dataBlock, outStageData()); - if(outData && outData->stage) - return true; + MayaUsdStageData* outData = inputDataValue(dataBlock, outStageData()); + if (outData && outData->stage) + return true; - return false; + return false; } //---------------------------------------------------------------------------------------------------------------------- UsdStageRefPtr ProxyShape::getUsdStage() const { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::getUsdStage\n"); - - MPlug plug(thisMObject(), outStageData()); - MObject data; - plug.getValue(data); - MFnPluginData fnData(data); - MayaUsdStageData* outData = static_cast(fnData.data()); - if(outData) - { - return outData->stage; - } - return UsdStageRefPtr(); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::getUsdStage\n"); + + MPlug plug(thisMObject(), outStageData()); + MObject data; + plug.getValue(data); + MFnPluginData fnData(data); + MayaUsdStageData* outData = static_cast(fnData.data()); + if (outData) { + return outData->stage; + } + return UsdStageRefPtr(); } UsdTimeCode ProxyShape::getTime() const @@ -1555,369 +1562,354 @@ UsdTimeCode ProxyShape::getTime() const //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShape::computeOutputTime(const MPlug& plug, MDataBlock& dataBlock, MTime& currentTime) { - MTime inTime = inputTimeValue(dataBlock, time()); - MTime inTimeOffset = inputTimeValue(dataBlock, m_timeOffset); - double inTimeScalar = inputDoubleValue(dataBlock, m_timeScalar); - currentTime.setValue((inTime.as(MTime::uiUnit()) - inTimeOffset.as(MTime::uiUnit())) * inTimeScalar); - return outputTimeValue(dataBlock, outTime(), currentTime); + MTime inTime = inputTimeValue(dataBlock, time()); + MTime inTimeOffset = inputTimeValue(dataBlock, m_timeOffset); + double inTimeScalar = inputDoubleValue(dataBlock, m_timeScalar); + currentTime.setValue( + (inTime.as(MTime::uiUnit()) - inTimeOffset.as(MTime::uiUnit())) * inTimeScalar); + return outputTimeValue(dataBlock, outTime(), currentTime); } //---------------------------------------------------------------------------------------------------------------------- MStatus ProxyShape::compute(const MPlug& plug, MDataBlock& dataBlock) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::compute %s\n", plug.name().asChar()); - // When shape is computed Maya will request redraw by itself - m_requestedRedraw = true; - MTime currentTime; - if(plug == outTime()) - { - return computeOutputTime(plug, dataBlock, currentTime); - } - else - if(plug == outStageData()) - { - MStatus status = computeOutputTime(MPlug(plug.node(), outTime()), dataBlock, currentTime); - return status == MS::kSuccess ? computeOutStageData(plug, dataBlock) : status; - } - // Completely skip over parent class compute(), because it has inStageData - // and inStageDataCached attributes we don't use. - return MPxSurfaceShape::compute(plug, dataBlock); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::compute %s\n", plug.name().asChar()); + // When shape is computed Maya will request redraw by itself + m_requestedRedraw = true; + MTime currentTime; + if (plug == outTime()) { + return computeOutputTime(plug, dataBlock, currentTime); + } else if (plug == outStageData()) { + MStatus status = computeOutputTime(MPlug(plug.node(), outTime()), dataBlock, currentTime); + return status == MS::kSuccess ? computeOutStageData(plug, dataBlock) : status; + } + // Completely skip over parent class compute(), because it has inStageData + // and inStageDataCached attributes we don't use. + return MPxSurfaceShape::compute(plug, dataBlock); } //---------------------------------------------------------------------------------------------------------------------- bool ProxyShape::setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) { - // We set the value in the datablock ourselves, so that the plug's value is - // can be queried from subfunctions (ie, loadStage, constructExcludedPrims, etc) - // - // If we simply returned "false", the "standard" implementation would set - // the datablock for us, but this would be too late for these subfunctions - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::setInternalValue %s\n", plug.name().asChar()); - - if(plug == filePath() || plug == m_assetResolverConfig || plug == stageCacheId() || plug == m_variantFallbacks) - { - m_filePathDirty = true; - - // can't use dataHandle.datablock(), as this is a temporary datahandle - MDataBlock datablock = forceCache(); - - if (plug == filePath() || plug == m_assetResolverConfig || plug == m_variantFallbacks) - { - AL_MAYA_CHECK_ERROR_RETURN_VAL(outputStringValue(datablock, plug, dataHandle.asString()), - false, - "ProxyShape::setInternalValue - error setting filePath, assetResolverConfig or variantFallbacks"); - } - else - { - AL_MAYA_CHECK_ERROR_RETURN_VAL(outputInt32Value(datablock, plug, dataHandle.asInt()), - false, - "ProxyShape::setInternalValue - error setting stageCacheId"); - } - // Delay stage creation if opening a file, because we haven't created the LayerManager node yet - if (MFileIO::isReadingFile()) - { - m_unloadedProxyShapes.push_back(MObjectHandle(thisMObject())); - } - else - { - loadStage(); - } - return true; - } - else - if(plug == primPath()) - { - // can't use dataHandle.datablock(), as this is a temporary datahandle - MDataBlock datablock = forceCache(); - AL_MAYA_CHECK_ERROR_RETURN_VAL(outputStringValue(datablock, primPath(), dataHandle.asString()), - false, "ProxyShape::setInternalValue - error setting primPath"); - - if(m_stage) - { - // Get the prim - // If no primPath string specified, then use the pseudo-root. - MString primPathStr = dataHandle.asString(); - if (primPathStr.length()) - { - m_path = SdfPath(AL::maya::utils::convert(primPathStr)); - UsdPrim prim = m_stage->GetPrimAtPath(m_path); - if(!prim) - { - m_path = SdfPath::AbsoluteRootPath(); + // We set the value in the datablock ourselves, so that the plug's value is + // can be queried from subfunctions (ie, loadStage, constructExcludedPrims, etc) + // + // If we simply returned "false", the "standard" implementation would set + // the datablock for us, but this would be too late for these subfunctions + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::setInternalValue %s\n", plug.name().asChar()); + + if (plug == filePath() || plug == m_assetResolverConfig || plug == stageCacheId() + || plug == m_variantFallbacks) { + m_filePathDirty = true; + + // can't use dataHandle.datablock(), as this is a temporary datahandle + MDataBlock datablock = forceCache(); + + if (plug == filePath() || plug == m_assetResolverConfig || plug == m_variantFallbacks) { + AL_MAYA_CHECK_ERROR_RETURN_VAL( + outputStringValue(datablock, plug, dataHandle.asString()), + false, + "ProxyShape::setInternalValue - error setting filePath, assetResolverConfig or " + "variantFallbacks"); + } else { + AL_MAYA_CHECK_ERROR_RETURN_VAL( + outputInt32Value(datablock, plug, dataHandle.asInt()), + false, + "ProxyShape::setInternalValue - error setting stageCacheId"); } - } - else - { - m_path = SdfPath::AbsoluteRootPath(); - } - constructGLImagingEngine(); - } - return true; - } - else - if(plug == excludePrimPaths() || plug == m_excludedTranslatedGeometry) - { - // can't use dataHandle.datablock(), as this is a temporary datahandle - MDataBlock datablock = forceCache(); - AL_MAYA_CHECK_ERROR_RETURN_VAL(outputStringValue(datablock, plug.attribute(), dataHandle.asString()), - false, MString("ProxyShape::setInternalValue - error setting ") + plug.name()); - - if(m_stage) - { - constructExcludedPrims(); + // Delay stage creation if opening a file, because we haven't created the LayerManager node + // yet + if (MFileIO::isReadingFile()) { + m_unloadedProxyShapes.push_back(MObjectHandle(thisMObject())); + } else { + loadStage(); + } + return true; + } else if (plug == primPath()) { + // can't use dataHandle.datablock(), as this is a temporary datahandle + MDataBlock datablock = forceCache(); + AL_MAYA_CHECK_ERROR_RETURN_VAL( + outputStringValue(datablock, primPath(), dataHandle.asString()), + false, + "ProxyShape::setInternalValue - error setting primPath"); + + if (m_stage) { + // Get the prim + // If no primPath string specified, then use the pseudo-root. + MString primPathStr = dataHandle.asString(); + if (primPathStr.length()) { + m_path = SdfPath(AL::maya::utils::convert(primPathStr)); + UsdPrim prim = m_stage->GetPrimAtPath(m_path); + if (!prim) { + m_path = SdfPath::AbsoluteRootPath(); + } + } else { + m_path = SdfPath::AbsoluteRootPath(); + } + constructGLImagingEngine(); + } + return true; + } else if (plug == excludePrimPaths() || plug == m_excludedTranslatedGeometry) { + // can't use dataHandle.datablock(), as this is a temporary datahandle + MDataBlock datablock = forceCache(); + AL_MAYA_CHECK_ERROR_RETURN_VAL( + outputStringValue(datablock, plug.attribute(), dataHandle.asString()), + false, + MString("ProxyShape::setInternalValue - error setting ") + plug.name()); + + if (m_stage) { + constructExcludedPrims(); + } + return true; } - return true; - } - return false; + return false; } //---------------------------------------------------------------------------------------------------------------------- bool ProxyShape::getInternalValue(const MPlug& plug, MDataHandle& dataHandle) { - // Not sure if this is needed... don't know behavior of default implementation? - return false; + // Not sure if this is needed... don't know behavior of default implementation? + return false; } //---------------------------------------------------------------------------------------------------------------------- -bool ProxyShape::isBounded() const -{ - return true; -} +bool ProxyShape::isBounded() const { return true; } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::CacheEmptyBoundingBox(MBoundingBox& cachedBBox) { - cachedBBox = MBoundingBox( - MPoint(-100000.0f, -100000.0f, -100000.0f), - MPoint( 100000.0f, 100000.0f, 100000.0f)); + cachedBBox = MBoundingBox( + MPoint(-100000.0f, -100000.0f, -100000.0f), MPoint(100000.0f, 100000.0f, 100000.0f)); } //---------------------------------------------------------------------------------------------------------------------- UsdTimeCode ProxyShape::GetOutputTime(MDataBlock dataBlock) const { - return UsdTimeCode(inputDoubleValue(dataBlock, outTime())); + return UsdTimeCode(inputDoubleValue(dataBlock, outTime())); } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::unloadMayaReferences() { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::unloadMayaReferences called\n"); - MObjectArray references; - for(auto it = m_requiredPaths.begin(), e = m_requiredPaths.end(); it != e; ++it) - { - MStatus status; - MFnDependencyNode fn(it->second.node(), &status); - if(status) - { - MPlug plug = fn.findPlug("message", &status); - if(status) - { - MPlugArray plugs; - plug.connectedTo(plugs, false, true); - for(uint32_t i = 0; i < plugs.length(); ++i) - { - MObject temp = plugs[i].node(); - if(temp.hasFn(MFn::kReference)) - { - MFnReference mfnRef(temp); - MString referenceFilename = mfnRef.fileName( - true /*resolvedName*/, - true /*includePath*/, - true /*includeCopyNumber*/); - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::unloadMayaReferences unloading %s\n", referenceFilename.asChar()); - MFileIO::unloadReferenceByNode(temp); - } + TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::unloadMayaReferences called\n"); + MObjectArray references; + for (auto it = m_requiredPaths.begin(), e = m_requiredPaths.end(); it != e; ++it) { + MStatus status; + MFnDependencyNode fn(it->second.node(), &status); + if (status) { + MPlug plug = fn.findPlug("message", &status); + if (status) { + MPlugArray plugs; + plug.connectedTo(plugs, false, true); + for (uint32_t i = 0; i < plugs.length(); ++i) { + MObject temp = plugs[i].node(); + if (temp.hasFn(MFn::kReference)) { + MFnReference mfnRef(temp); + MString referenceFilename = mfnRef.fileName( + true /*resolvedName*/, + true /*includePath*/, + true /*includeCopyNumber*/); + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "ProxyShape::unloadMayaReferences unloading %s\n", + referenceFilename.asChar()); + MFileIO::unloadReferenceByNode(temp); + } + } + } } - } } - } } - //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::serialiseTransformRefs() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::serialiseTransformRefs\n"); - triggerEvent("PreSerialiseTransformRefs"); - - std::ostringstream oss; - for(auto iter : m_requiredPaths) - { - MStatus status; - MObjectHandle handle(iter.second.node()); - - if(handle.isAlive() && handle.isValid()) - { - MFnDagNode fn(handle.object(), &status); - if(status) - { - MDagPath path; - fn.getPath(path); - oss << path.fullPathName() << " " - << iter.first.GetText() << " " - << uint32_t(iter.second.required()) << " " - << uint32_t(iter.second.selected()) << " " - << uint32_t(iter.second.refCount()) << ";"; - } + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::serialiseTransformRefs\n"); + triggerEvent("PreSerialiseTransformRefs"); + + std::ostringstream oss; + for (auto iter : m_requiredPaths) { + MStatus status; + MObjectHandle handle(iter.second.node()); + + if (handle.isAlive() && handle.isValid()) { + MFnDagNode fn(handle.object(), &status); + if (status) { + MDagPath path; + fn.getPath(path); + oss << path.fullPathName() << " " << iter.first.GetText() << " " + << uint32_t(iter.second.required()) << " " << uint32_t(iter.second.selected()) + << " " << uint32_t(iter.second.refCount()) << ";"; + } + } } - } - serializedRefCountsPlug().setString(oss.str().c_str()); + serializedRefCountsPlug().setString(oss.str().c_str()); - triggerEvent("PostSerialiseTransformRefs"); + triggerEvent("PostSerialiseTransformRefs"); } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::deserialiseTransformRefs() { - triggerEvent("PreDeserialiseTransformRefs"); - - MString str = serializedRefCountsPlug().asString(); - MStringArray strs; - str.split(';', strs); - - for(uint32_t i = 0, n = strs.length(); i < n; ++i) - { - if(strs[i].length()) - { - MStringArray tstrs; - strs[i].split(' ', tstrs); - MString nodeName = tstrs[0]; - - MSelectionList sl; - if(sl.add(nodeName)) - { - MObject node; - if(sl.getDependNode(0, node)) - { - MFnDependencyNode fn(node); - Scope* transformNode = dynamic_cast(fn.userNode()); - if(transformNode) - { - const uint32_t required = tstrs[2].asUnsigned(); - const uint32_t selected = tstrs[3].asUnsigned(); - const uint32_t refCounts = tstrs[4].asUnsigned(); - SdfPath path(tstrs[1].asChar()); - m_requiredPaths.emplace(path, TransformReference(node, transformNode, required, selected, refCounts)); - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::deserialiseTransformRefs m_requiredPaths added AL_usdmaya_Transform TransformReference: %s\n", path.GetText()); - } - else - { - const uint32_t required = tstrs[2].asUnsigned(); - const uint32_t selected = tstrs[3].asUnsigned(); - const uint32_t refCounts = tstrs[4].asUnsigned(); - SdfPath path(tstrs[1].asChar()); - m_requiredPaths.emplace(path, TransformReference(node, nullptr, required, selected, refCounts)); - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::deserialiseTransformRefs m_requiredPaths added TransformReference: %s\n", path.GetText()); - } + triggerEvent("PreDeserialiseTransformRefs"); + + MString str = serializedRefCountsPlug().asString(); + MStringArray strs; + str.split(';', strs); + + for (uint32_t i = 0, n = strs.length(); i < n; ++i) { + if (strs[i].length()) { + MStringArray tstrs; + strs[i].split(' ', tstrs); + MString nodeName = tstrs[0]; + + MSelectionList sl; + if (sl.add(nodeName)) { + MObject node; + if (sl.getDependNode(0, node)) { + MFnDependencyNode fn(node); + Scope* transformNode = dynamic_cast(fn.userNode()); + if (transformNode) { + const uint32_t required = tstrs[2].asUnsigned(); + const uint32_t selected = tstrs[3].asUnsigned(); + const uint32_t refCounts = tstrs[4].asUnsigned(); + SdfPath path(tstrs[1].asChar()); + m_requiredPaths.emplace( + path, + TransformReference(node, transformNode, required, selected, refCounts)); + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "ProxyShape::deserialiseTransformRefs m_requiredPaths added " + "AL_usdmaya_Transform TransformReference: %s\n", + path.GetText()); + } else { + const uint32_t required = tstrs[2].asUnsigned(); + const uint32_t selected = tstrs[3].asUnsigned(); + const uint32_t refCounts = tstrs[4].asUnsigned(); + SdfPath path(tstrs[1].asChar()); + m_requiredPaths.emplace( + path, TransformReference(node, nullptr, required, selected, refCounts)); + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "ProxyShape::deserialiseTransformRefs m_requiredPaths added " + "TransformReference: %s\n", + path.GetText()); + } + } + } } - } } - } - serializedRefCountsPlug().setString(""); + serializedRefCountsPlug().setString(""); - triggerEvent("PostDeserialiseTransformRefs"); + triggerEvent("PostDeserialiseTransformRefs"); } //---------------------------------------------------------------------------------------------------------------------- -ProxyShape::TransformReference::TransformReference(MObject mayaNode, Scope* node, uint32_t r, uint32_t s, uint32_t rc) - : m_node(mayaNode) - , m_transform(nullptr) +ProxyShape::TransformReference::TransformReference( + MObject mayaNode, + Scope* node, + uint32_t r, + uint32_t s, + uint32_t rc) + : m_node(mayaNode) + , m_transform(nullptr) { - m_required = r; - m_selected = s; - m_selectedTemp = 0; - m_refCount = rc; - m_transform = getTransformNode(); + m_required = r; + m_selected = s; + m_selectedTemp = 0; + m_refCount = rc; + m_transform = getTransformNode(); } //---------------------------------------------------------------------------------------------------------------------- Scope* ProxyShape::TransformReference::getTransformNode() const { - MObjectHandle n(node()); - if(n.isValid() && n.isAlive()) - { - MStatus status; - MFnDependencyNode fn(n.object(), &status); - if(status == MS::kSuccess) - { - Scope* transformNode = dynamic_cast(fn.userNode()); - if(transformNode) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("TransformReference::transform found valid AL_usdmaya Transform or Scope: %s\n", fn.absoluteName().asChar()); - return (Scope*)fn.userNode(); - } - else - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("TransformReference::transform found non AL_usdmaya_Tranform: %s\n", fn.absoluteName().asChar()); - return nullptr; - } - } - else - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("TransformReference::transform found invalid transform\n"); - return nullptr; + MObjectHandle n(node()); + if (n.isValid() && n.isAlive()) { + MStatus status; + MFnDependencyNode fn(n.object(), &status); + if (status == MS::kSuccess) { + Scope* transformNode = dynamic_cast(fn.userNode()); + if (transformNode) { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "TransformReference::transform found valid AL_usdmaya Transform or Scope: " + "%s\n", + fn.absoluteName().asChar()); + return (Scope*)fn.userNode(); + } else { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "TransformReference::transform found non AL_usdmaya_Tranform: %s\n", + fn.absoluteName().asChar()); + return nullptr; + } + } else { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg("TransformReference::transform found invalid transform\n"); + return nullptr; + } } - } - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("TransformReference::transform found null transform\n"); - return nullptr; + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("TransformReference::transform found null transform\n"); + return nullptr; } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::cleanupTransformRefs() { - for(auto it = m_requiredPaths.begin(); it != m_requiredPaths.end(); ) - { - if(!it->second.selected() && !it->second.required() && !it->second.refCount()) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::cleanupTransformRefs m_requiredPaths removed TransformReference: %s\n", it->first.GetText()); - m_requiredPaths.erase(it++); - } - else - { - ++it; + for (auto it = m_requiredPaths.begin(); it != m_requiredPaths.end();) { + if (!it->second.selected() && !it->second.required() && !it->second.refCount()) { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "ProxyShape::cleanupTransformRefs m_requiredPaths removed TransformReference: " + "%s\n", + it->first.GetText()); + m_requiredPaths.erase(it++); + } else { + ++it; + } } - } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::registerEvents() { - registerEvent("PreDestroyProxyShape", AL::event::kUSDMayaEventType); - registerEvent("PostDestroyProxyShape", AL::event::kUSDMayaEventType); - registerEvent("PreStageLoaded", AL::event::kUSDMayaEventType); - registerEvent("PostStageLoaded", AL::event::kUSDMayaEventType); - registerEvent("ConstructGLEngine", AL::event::kUSDMayaEventType); - registerEvent("DestroyGLEngine", AL::event::kUSDMayaEventType); - registerEvent("PreSelectionChanged", AL::event::kUSDMayaEventType); - registerEvent("PostSelectionChanged", AL::event::kUSDMayaEventType); - registerEvent("PreVariantChanged", AL::event::kUSDMayaEventType); - registerEvent("PostVariantChanged", AL::event::kUSDMayaEventType); - registerEvent("PreSerialiseContext", AL::event::kUSDMayaEventType, Global::postSave()); - registerEvent("PostSerialiseContext", AL::event::kUSDMayaEventType, Global::postSave()); - registerEvent("PreDeserialiseContext", AL::event::kUSDMayaEventType, Global::postRead()); - registerEvent("PostDeserialiseContext", AL::event::kUSDMayaEventType, Global::postRead()); - registerEvent("PreSerialiseTransformRefs", AL::event::kUSDMayaEventType, Global::postSave()); - registerEvent("PostSerialiseTransformRefs", AL::event::kUSDMayaEventType, Global::postSave()); - registerEvent("PreDeserialiseTransformRefs", AL::event::kUSDMayaEventType, Global::postRead()); - registerEvent("PostDeserialiseTransformRefs", AL::event::kUSDMayaEventType, Global::postRead()); - registerEvent("EditTargetChanged", AL::event::kUSDMayaEventType); - registerEvent("SelectionStarted", AL::event::kUSDMayaEventType); - registerEvent("SelectionEnded", AL::event::kUSDMayaEventType); + registerEvent("PreDestroyProxyShape", AL::event::kUSDMayaEventType); + registerEvent("PostDestroyProxyShape", AL::event::kUSDMayaEventType); + registerEvent("PreStageLoaded", AL::event::kUSDMayaEventType); + registerEvent("PostStageLoaded", AL::event::kUSDMayaEventType); + registerEvent("ConstructGLEngine", AL::event::kUSDMayaEventType); + registerEvent("DestroyGLEngine", AL::event::kUSDMayaEventType); + registerEvent("PreSelectionChanged", AL::event::kUSDMayaEventType); + registerEvent("PostSelectionChanged", AL::event::kUSDMayaEventType); + registerEvent("PreVariantChanged", AL::event::kUSDMayaEventType); + registerEvent("PostVariantChanged", AL::event::kUSDMayaEventType); + registerEvent("PreSerialiseContext", AL::event::kUSDMayaEventType, Global::postSave()); + registerEvent("PostSerialiseContext", AL::event::kUSDMayaEventType, Global::postSave()); + registerEvent("PreDeserialiseContext", AL::event::kUSDMayaEventType, Global::postRead()); + registerEvent("PostDeserialiseContext", AL::event::kUSDMayaEventType, Global::postRead()); + registerEvent("PreSerialiseTransformRefs", AL::event::kUSDMayaEventType, Global::postSave()); + registerEvent("PostSerialiseTransformRefs", AL::event::kUSDMayaEventType, Global::postSave()); + registerEvent("PreDeserialiseTransformRefs", AL::event::kUSDMayaEventType, Global::postRead()); + registerEvent("PostDeserialiseTransformRefs", AL::event::kUSDMayaEventType, Global::postRead()); + registerEvent("EditTargetChanged", AL::event::kUSDMayaEventType); + registerEvent("SelectionStarted", AL::event::kUSDMayaEventType); + registerEvent("SelectionEnded", AL::event::kUSDMayaEventType); } //---------------------------------------------------------------------------------------------------------------------- MSelectionMask ProxyShape::getShapeSelectionMask() const { - MSelectionMask::SelectionType selType = MSelectionMask::kSelectMeshes; - return MSelectionMask(selType); + MSelectionMask::SelectionType selType = MSelectionMask::kSelectMeshes; + return MSelectionMask(selType); } #if defined(WANT_UFE_BUILD) //---------------------------------------------------------------------------------------------------------------------- Ufe::PathSegment ProxyShape::ufePathSegment() const { - //Build a path segment to proxyShape + // Build a path segment to proxyShape MDagPath thisPath; MDagPath::getAPathTo(thisMObject(), thisPath); @@ -1927,15 +1919,11 @@ Ufe::PathSegment ProxyShape::ufePathSegment() const return Ufe::PathSegment(fullpath.asChar(), MAYA_UFE_RUNTIME_ID, MAYA_UFE_SEPARATOR); } - -Ufe::Path ProxyShape::ufePath() const -{ - return Ufe::Path(ProxyShape::ufePathSegment()); -} +Ufe::Path ProxyShape::ufePath() const { return Ufe::Path(ProxyShape::ufePathSegment()); } #endif //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShape.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShape.h index 7318eb2a91..37af80d1f6 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShape.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShape.h @@ -16,27 +16,18 @@ #pragma once #include "AL/maya/event/MayaEventManager.h" - #include "AL/maya/utils/MayaHelperMacros.h" #include "AL/maya/utils/NodeHelper.h" - +#include "AL/usd/transaction/Notice.h" #include "AL/usdmaya/Api.h" - #include "AL/usdmaya/ForwardDeclares.h" +#include "AL/usdmaya/SelectabilityDB.h" #include "AL/usdmaya/fileio/translators/TranslatorBase.h" #include "AL/usdmaya/fileio/translators/TranslatorContext.h" #include "AL/usdmaya/nodes/proxy/LockManager.h" #include "AL/usdmaya/nodes/proxy/PrimFilter.h" -#include "AL/usdmaya/SelectabilityDB.h" -#include "AL/usd/transaction/Notice.h" - -#include -#include -#include -#include -#include -#include +#include #include #include @@ -44,12 +35,18 @@ #include #include -#include +#include +#include +#include +#include +#include +#include #if defined(WANT_UFE_BUILD) #include "ufe/ufe.h" -UFE_NS_DEF { +UFE_NS_DEF +{ class Path; class PathSegment; } @@ -78,7 +75,8 @@ namespace nodes { class Engine; //---------------------------------------------------------------------------------------------------------------------- -/// \brief A helper class to store the state that is modified during a change to the current selection within a +/// \brief A helper class to store the state that is modified during a change to the current +/// selection within a /// proxy shape. The state it maintains includes: /// /// \li The USD paths to be selected / deselected @@ -87,1030 +85,1082 @@ class Engine; /// \li The maya selection list after the selection change /// \li The internal transformation references before and after the selection change /// -/// This class is intended to exist as a member variable on a MEL selection command. Once constructed, the class -/// should be passed to the ProxyShape::doSelect method to construct the internal state changes. At that point, -/// you may call doIt() to perform the changes, undoIt() to revert the changes. +/// This class is intended to exist as a member variable on a MEL selection command. Once +/// constructed, the class should be passed to the ProxyShape::doSelect method to construct +/// the internal state changes. At that point, you may call doIt() to perform the changes, +/// undoIt() to revert the changes. //---------------------------------------------------------------------------------------------------------------------- struct SelectionUndoHelper { - /// a hash set of SdfPaths - typedef TfHashSet SdfPathHashSet; - - /// \brief Construct with the arguments to select / deselect nodes on a proxy shape - /// \param proxy pointer to the maya node on which the selection operation will be performed. - /// \param paths the USD paths to be selected / toggled / unselected - /// \param mode the selection mode (add, remove, xor, etc) - /// \param internal if the internal flag is set, then modifications to Maya's selection list will NOT occur. - SelectionUndoHelper(nodes::ProxyShape* proxy, const SdfPathHashSet& paths, MGlobal::ListAdjustment mode, bool internal = false); - - /// \brief performs the selection changes - void doIt(); - - /// \brief will undo the selection changes - void undoIt(); + /// a hash set of SdfPaths + typedef TfHashSet SdfPathHashSet; + + /// \brief Construct with the arguments to select / deselect nodes on a proxy shape + /// \param proxy pointer to the maya node on which the selection operation will be performed. + /// \param paths the USD paths to be selected / toggled / unselected + /// \param mode the selection mode (add, remove, xor, etc) + /// \param internal if the internal flag is set, then modifications to Maya's selection list + /// will NOT occur. + SelectionUndoHelper( + nodes::ProxyShape* proxy, + const SdfPathHashSet& paths, + MGlobal::ListAdjustment mode, + bool internal = false); + + /// \brief performs the selection changes + void doIt(); + + /// \brief will undo the selection changes + void undoIt(); private: - friend class ProxyShape; - nodes::ProxyShape* m_proxy; - SdfPathHashSet m_paths; - SdfPathHashSet m_previousPaths; - MGlobal::ListAdjustment m_mode; - MDagModifier m_modifier1; - MDagModifier m_modifier2; - MSelectionList m_previousSelection; - MSelectionList m_newSelection; - std::vector> m_insertedRefs; - std::vector> m_removedRefs; - bool m_internal; + friend class ProxyShape; + nodes::ProxyShape* m_proxy; + SdfPathHashSet m_paths; + SdfPathHashSet m_previousPaths; + MGlobal::ListAdjustment m_mode; + MDagModifier m_modifier1; + MDagModifier m_modifier2; + MSelectionList m_previousSelection; + MSelectionList m_newSelection; + std::vector> m_insertedRefs; + std::vector> m_removedRefs; + bool m_internal; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief Used as a way to construct a simple selection list that allows for selection highlighting without +/// \brief Used as a way to construct a simple selection list that allows for selection +/// highlighting without /// creating/destroying transforms. //---------------------------------------------------------------------------------------------------------------------- class SelectionList { public: - /// a hash set of SdfPaths - typedef TfHashSet SdfPathHashSet; + /// a hash set of SdfPaths + typedef TfHashSet SdfPathHashSet; - /// \brief default ctor - SelectionList() = default; + /// \brief default ctor + SelectionList() = default; - /// \brief copy ctor - /// \param sl the selection list to copy - SelectionList(const SelectionList& sl) = default; + /// \brief copy ctor + /// \param sl the selection list to copy + SelectionList(const SelectionList& sl) = default; - /// \brief dtor - ~SelectionList() = default; + /// \brief dtor + ~SelectionList() = default; - /// \brief clear the selection list - inline void clear() - { m_selected.clear(); } + /// \brief clear the selection list + inline void clear() { m_selected.clear(); } - /// \brief adds a path to the selection - /// \param path to add - inline void add(SdfPath path) - { - m_selected.insert(path); - } + /// \brief adds a path to the selection + /// \param path to add + inline void add(SdfPath path) { m_selected.insert(path); } - /// \brief removes the path from the selection - /// \param path to remove - inline void remove(SdfPath path) + /// \brief removes the path from the selection + /// \param path to remove + inline void remove(SdfPath path) { - auto it = m_selected.find(path); - if(it != m_selected.end()) - { - m_selected.erase(it); - } + auto it = m_selected.find(path); + if (it != m_selected.end()) { + m_selected.erase(it); + } } - /// \brief toggles the path in the selection - /// \param path to toggle - inline void toggle(SdfPath path) + /// \brief toggles the path in the selection + /// \param path to toggle + inline void toggle(SdfPath path) { - auto insertResult = m_selected.insert(path); - if (!insertResult.second) - { - m_selected.erase(insertResult.first); - } + auto insertResult = m_selected.insert(path); + if (!insertResult.second) { + m_selected.erase(insertResult.first); + } } - /// \brief toggles the path in the selection - /// \param path to toggle - inline bool isSelected(const SdfPath& path) const - { return m_selected.count(path) > 0; } + /// \brief toggles the path in the selection + /// \param path to toggle + inline bool isSelected(const SdfPath& path) const { return m_selected.count(path) > 0; } - /// \brief the paths in the selection list - /// \return the selected paths - inline const SdfPathHashSet& paths() const - { return m_selected; } + /// \brief the paths in the selection list + /// \return the selected paths + inline const SdfPathHashSet& paths() const { return m_selected; } - /// \brief the paths in the selection list - /// \return the selected paths - inline size_t size() const - { return m_selected.size(); } + /// \brief the paths in the selection list + /// \return the selected paths + inline size_t size() const { return m_selected.size(); } private: - SdfPathHashSet m_selected; + SdfPathHashSet m_selected; }; -typedef std::unordered_map PrimPathToDagPath; +typedef std::unordered_map PrimPathToDagPath; extern AL::event::EventId kPreClearStageCache; extern AL::event::EventId kPostClearStageCache; //---------------------------------------------------------------------------------------------------------------------- /// \brief A custom proxy shape node that attaches itself to a USD file, and then renders it. -/// The stage is held internally as a member variable, and it will be composed based on a change to the -/// "filePath" attribute. +/// The stage is held internally as a member variable, and it will be composed based on a +/// change to the "filePath" attribute. /// \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- class ProxyShape - : public MayaUsdProxyShapeBase, - public AL::maya::utils::NodeHelper, - public proxy::PrimFilterInterface, - public AL::event::NodeEvents, - public TfWeakBase + : public MayaUsdProxyShapeBase + , public AL::maya::utils::NodeHelper + , public proxy::PrimFilterInterface + , public AL::event::NodeEvents + , public TfWeakBase { - friend struct SelectionUndoHelper; - friend class ProxyShapeUI; - friend class StageReloadGuard; - friend class ProxyDrawOverride; + friend struct SelectionUndoHelper; + friend class ProxyShapeUI; + friend class StageReloadGuard; + friend class ProxyDrawOverride; + + typedef MayaUsdProxyShapeBase ParentClass; - typedef MayaUsdProxyShapeBase ParentClass; public: + /// a method that registers all of the events in the ProxyShape + AL_USDMAYA_PUBLIC + void registerEvents(); - /// a method that registers all of the events in the ProxyShape - AL_USDMAYA_PUBLIC - void registerEvents(); + /// a set of SdfPaths + typedef TfHashSet SdfPathHashSet; - /// a set of SdfPaths - typedef TfHashSet SdfPathHashSet; + /// \brief a mapping between a maya transform (or MObject::kNullObj), and the prim that exists + /// at that location + /// in the DAG graph. + typedef std::vector> MObjectToPrim; + AL_USDMAYA_PUBLIC + static const char* s_selectionMaskName; - /// \brief a mapping between a maya transform (or MObject::kNullObj), and the prim that exists at that location - /// in the DAG graph. - typedef std::vector > MObjectToPrim; - AL_USDMAYA_PUBLIC - static const char* s_selectionMaskName; + /// \brief ctor + AL_USDMAYA_PUBLIC + ProxyShape(); - /// \brief ctor - AL_USDMAYA_PUBLIC - ProxyShape(); + /// \brief dtor + AL_USDMAYA_PUBLIC + ~ProxyShape(); - /// \brief dtor - AL_USDMAYA_PUBLIC - ~ProxyShape(); + //-------------------------------------------------------------------------------------------------------------------- + /// \name Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- + AL_MAYA_DECLARE_NODE(); - //-------------------------------------------------------------------------------------------------------------------- - /// \name Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- - AL_MAYA_DECLARE_NODE(); + //-------------------------------------------------------------------------------------------------------------------- + /// \name Input Attributes + //-------------------------------------------------------------------------------------------------------------------- - //-------------------------------------------------------------------------------------------------------------------- - /// \name Input Attributes - //-------------------------------------------------------------------------------------------------------------------- + // Convenience declarations for attributes inherited from proxy shape + // base class. +#define AL_INHERIT_ATTRIBUTE(XX) \ + AL_USDMAYA_PUBLIC \ + static const MObject& XX() { return XX##Attr; } \ + AL_USDMAYA_PUBLIC \ + MPlug XX##Plug() const { return MPlug(thisMObject(), XX##Attr); } - // Convenience declarations for attributes inherited from proxy shape - // base class. -#define AL_INHERIT_ATTRIBUTE(XX) \ - AL_USDMAYA_PUBLIC \ - static const MObject& XX() { return XX##Attr; } \ - AL_USDMAYA_PUBLIC \ - MPlug XX##Plug() const { return MPlug( thisMObject(), XX##Attr ); } + /// the input USD file path for this proxy + AL_INHERIT_ATTRIBUTE(filePath); - /// the input USD file path for this proxy - AL_INHERIT_ATTRIBUTE(filePath); + /// a path to a prim you want to view with this shape + AL_INHERIT_ATTRIBUTE(primPath); - /// a path to a prim you want to view with this shape - AL_INHERIT_ATTRIBUTE(primPath); + /// a comma seperated list of prims you *don't* want to see. + AL_INHERIT_ATTRIBUTE(excludePrimPaths); - /// a comma seperated list of prims you *don't* want to see. - AL_INHERIT_ATTRIBUTE(excludePrimPaths); + /// the input time value (probably connected to time1.outTime) + AL_INHERIT_ATTRIBUTE(time); - /// the input time value (probably connected to time1.outTime) - AL_INHERIT_ATTRIBUTE(time); + /// an offset, in GUI time units, where the animation should start playback + AL_DECL_ATTRIBUTE(timeOffset); - /// an offset, in GUI time units, where the animation should start playback - AL_DECL_ATTRIBUTE(timeOffset); + /// a scalar value that can speed up (values greater than 1) or slow down (values less than one) + /// or reverse (negative values) the playback of the animation. + AL_DECL_ATTRIBUTE(timeScalar); - /// a scalar value that can speed up (values greater than 1) or slow down (values less than one) or reverse (negative - /// values) the playback of the animation. - AL_DECL_ATTRIBUTE(timeScalar); + /// the subdiv complexity used + AL_INHERIT_ATTRIBUTE(complexity); - /// the subdiv complexity used - AL_INHERIT_ATTRIBUTE(complexity); + /// display guide - sets shape to display geometry of purpose "guide". See imageable.h + AL_INHERIT_ATTRIBUTE(drawGuidePurpose); - /// display guide - sets shape to display geometry of purpose "guide". See imageable.h - AL_INHERIT_ATTRIBUTE(drawGuidePurpose); + /// display guide - sets shape to display geometry of purpose "proxy". See imageable.h + AL_INHERIT_ATTRIBUTE(drawProxyPurpose); - /// display guide - sets shape to display geometry of purpose "proxy". See imageable.h - AL_INHERIT_ATTRIBUTE(drawProxyPurpose); + /// display render guide - sets shape to display geometry of purpose "render". See imageable.h + AL_INHERIT_ATTRIBUTE(drawRenderPurpose); - /// display render guide - sets shape to display geometry of purpose "render". See imageable.h - AL_INHERIT_ATTRIBUTE(drawRenderPurpose); + /// Cache ID of the currently loaded stage) + AL_INHERIT_ATTRIBUTE(stageCacheId); - /// Cache ID of the currently loaded stage) - AL_INHERIT_ATTRIBUTE(stageCacheId); + /// Connection to any layer DG nodes + AL_DECL_ATTRIBUTE(layers); - /// Connection to any layer DG nodes - AL_DECL_ATTRIBUTE(layers); + /// serialised session layer (obsolete / deprecated) + AL_DECL_ATTRIBUTE(serializedSessionLayer); - /// serialised session layer (obsolete / deprecated) - AL_DECL_ATTRIBUTE(serializedSessionLayer); + /// name of serialized session layer (on the LayerManager) + AL_DECL_ATTRIBUTE(sessionLayerName); - /// name of serialized session layer (on the LayerManager) - AL_DECL_ATTRIBUTE(sessionLayerName); + /// serialised translator context + AL_DECL_ATTRIBUTE(serializedTrCtx); - /// serialised translator context - AL_DECL_ATTRIBUTE(serializedTrCtx); + /// Open the stage unloaded. + AL_DECL_ATTRIBUTE(unloaded); - /// Open the stage unloaded. - AL_DECL_ATTRIBUTE(unloaded); + /// ambient display colour + AL_DECL_ATTRIBUTE(ambient); - /// ambient display colour - AL_DECL_ATTRIBUTE(ambient); + /// diffuse display colour + AL_DECL_ATTRIBUTE(diffuse); - /// diffuse display colour - AL_DECL_ATTRIBUTE(diffuse); + /// specular display colour + AL_DECL_ATTRIBUTE(specular); - /// specular display colour - AL_DECL_ATTRIBUTE(specular); + /// emission display colour + AL_DECL_ATTRIBUTE(emission); - /// emission display colour - AL_DECL_ATTRIBUTE(emission); + /// material shininess + AL_DECL_ATTRIBUTE(shininess); - /// material shininess - AL_DECL_ATTRIBUTE(shininess); + /// Serialised reference counts to rebuild the transform reference information + AL_DECL_ATTRIBUTE(serializedRefCounts); - /// Serialised reference counts to rebuild the transform reference information - AL_DECL_ATTRIBUTE(serializedRefCounts); + /// The path list joined by ",", that will be used as a mask when doing UsdStage::OpenMask() + AL_DECL_ATTRIBUTE(populationMaskIncludePaths); - /// The path list joined by ",", that will be used as a mask when doing UsdStage::OpenMask() - AL_DECL_ATTRIBUTE(populationMaskIncludePaths); + /// Version of the plugin at the time of creation (read-only) + AL_DECL_ATTRIBUTE(version); - /// Version of the plugin at the time of creation (read-only) - AL_DECL_ATTRIBUTE(version); + /// Force the outStageData to be marked dirty (write-only) + AL_DECL_ATTRIBUTE(stageDataDirty); - /// Force the outStageData to be marked dirty (write-only) - AL_DECL_ATTRIBUTE(stageDataDirty); + /// Excluded geometry that has been explicitly translated + AL_DECL_ATTRIBUTE(excludedTranslatedGeometry); - /// Excluded geometry that has been explicitly translated - AL_DECL_ATTRIBUTE(excludedTranslatedGeometry); + /// A place to put a custom assetResolver Config string that's passed to the Resolver Context + /// when stage is opened + AL_DECL_ATTRIBUTE(assetResolverConfig); - /// A place to put a custom assetResolver Config string that's passed to the Resolver Context when stage is opened - AL_DECL_ATTRIBUTE(assetResolverConfig); + /// Variant fallbacks if stage was opened and/reopened a Maya scene with custom variants + /// fallbacks + AL_DECL_ATTRIBUTE(variantFallbacks); - /// Variant fallbacks if stage was opened and/reopened a Maya scene with custom variants fallbacks - AL_DECL_ATTRIBUTE(variantFallbacks); + //-------------------------------------------------------------------------------------------------------------------- + /// \name Output Attributes + //-------------------------------------------------------------------------------------------------------------------- - //-------------------------------------------------------------------------------------------------------------------- - /// \name Output Attributes - //-------------------------------------------------------------------------------------------------------------------- + /// outTime = (time - timeOffset) * timeScalar + AL_INHERIT_ATTRIBUTE(outTime); - /// outTime = (time - timeOffset) * timeScalar - AL_INHERIT_ATTRIBUTE(outTime); + /// Inject m_stage and m_path members into DG as a data attribute. + AL_INHERIT_ATTRIBUTE(outStageData); - /// Inject m_stage and m_path members into DG as a data attribute. - AL_INHERIT_ATTRIBUTE(outStageData); + //-------------------------------------------------------------------------------------------------------------------- + /// \name Public Utils + //-------------------------------------------------------------------------------------------------------------------- + /// \brief provides access to the UsdStage that this proxy shape is currently representing. + /// This will cause a compute + /// on the output stage. + /// \return the proxy shape + AL_USDMAYA_PUBLIC + UsdStageRefPtr getUsdStage() const override; - //-------------------------------------------------------------------------------------------------------------------- - /// \name Public Utils - //-------------------------------------------------------------------------------------------------------------------- + AL_USDMAYA_PUBLIC + UsdTimeCode getTime() const override; - /// \brief provides access to the UsdStage that this proxy shape is currently representing. This will cause a compute - /// on the output stage. - /// \return the proxy shape - AL_USDMAYA_PUBLIC - UsdStageRefPtr getUsdStage() const override; + /// \brief provides access to the UsdStage that this proxy shape is currently representing + /// \return the proxy shape + UsdStageRefPtr usdStage() const { return m_stage; } - AL_USDMAYA_PUBLIC - UsdTimeCode getTime() const override; - - /// \brief provides access to the UsdStage that this proxy shape is currently representing - /// \return the proxy shape - UsdStageRefPtr usdStage() const - { return m_stage; } + /// \brief gets hold of the attributes on this node that control the rendering in some way + /// \param attribs the returned set of render attributes + /// \param frameContext the frame context for rendering + /// \param dagPath the dag path of the node being rendered + /// \return true if the attribs could be retrieved (i.e. is the stage is valid) + bool getRenderAttris( + UsdImagingGLRenderParams& attribs, + const MHWRender::MFrameContext& frameContext, + const MDagPath& dagPath); - /// \brief gets hold of the attributes on this node that control the rendering in some way - /// \param attribs the returned set of render attributes - /// \param frameContext the frame context for rendering - /// \param dagPath the dag path of the node being rendered - /// \return true if the attribs could be retrieved (i.e. is the stage is valid) - bool getRenderAttris(UsdImagingGLRenderParams& attribs, const MHWRender::MFrameContext& frameContext, const MDagPath& dagPath); + //-------------------------------------------------------------------------------------------------------------------- + /// \name AL_usdmaya_Transform utils + /// \brief A set of commands to manipulate the chains of transforms that map to the usd prims + /// found in a stage. + /// There are 3 main reasons for a transform node to exist within maya: + /// \li They are required to provide a parent transform for a schema prim that will be + /// imported into maya. \li They are the parent node of an object that has been selected + /// \li The user has requested that they be imported + //-------------------------------------------------------------------------------------------------------------------- - //-------------------------------------------------------------------------------------------------------------------- - /// \name AL_usdmaya_Transform utils - /// \brief A set of commands to manipulate the chains of transforms that map to the usd prims found in a stage. - /// There are 3 main reasons for a transform node to exist within maya: - /// \li They are required to provide a parent transform for a schema prim that will be imported into maya. - /// \li They are the parent node of an object that has been selected - /// \li The user has requested that they be imported - //-------------------------------------------------------------------------------------------------------------------- + /// an enum describing the reason that a transform exists in the scene + enum TransformReason + { + kSelection = 1 << 0, ///< the node exists for selection + kRequested = 1 << 1, ///< the node has been requested by a user + kRequired = 1 << 2 ///< the node is required for an imported schema prim + }; - /// an enum describing the reason that a transform exists in the scene - enum TransformReason - { - kSelection = 1 << 0, ///< the node exists for selection - kRequested = 1 << 1, ///< the node has been requested by a user - kRequired = 1 << 2 ///< the node is required for an imported schema prim - }; - - /// Selection pick modes (based on USD View application) - enum class PickMode : int - { - kPrims = 0, ///< Pick the target prim - kModels = 1, ///< Pick the nearest model kind ancestor of target - kInstances = 2, ///< Pick an instance of the target (if available) - }; - - /// \brief returns true if the path is required for an imported schema prim - /// \param path the path to query - /// \return true if the path represents a prim that is required. - inline bool isRequiredPath(const SdfPath& path) const - { return m_requiredPaths.find(path) != m_requiredPaths.end(); } - - /// \brief returns the MObject of the maya transform for requested path (or MObject::kNullObj) - /// \param path the usd prim path to look up - /// \return the MObject for the parent transform to the path specified - inline MObject findRequiredPath(const SdfPath& path) const + /// Selection pick modes (based on USD View application) + enum class PickMode : int { - const auto it = m_requiredPaths.find(path); - if(it != m_requiredPaths.end()) - { - const MObject& object = it->second.node(); - const MObjectHandle handle(object); - if(handle.isValid() && handle.isAlive()) - { - return object; + kPrims = 0, ///< Pick the target prim + kModels = 1, ///< Pick the nearest model kind ancestor of target + kInstances = 2, ///< Pick an instance of the target (if available) + }; + + /// \brief returns true if the path is required for an imported schema prim + /// \param path the path to query + /// \return true if the path represents a prim that is required. + inline bool isRequiredPath(const SdfPath& path) const + { + return m_requiredPaths.find(path) != m_requiredPaths.end(); + } + + /// \brief returns the MObject of the maya transform for requested path (or MObject::kNullObj) + /// \param path the usd prim path to look up + /// \return the MObject for the parent transform to the path specified + inline MObject findRequiredPath(const SdfPath& path) const + { + const auto it = m_requiredPaths.find(path); + if (it != m_requiredPaths.end()) { + const MObject& object = it->second.node(); + const MObjectHandle handle(object); + if (handle.isValid() && handle.isAlive()) { + return object; + } } - } - return MObject::kNullObj; + return MObject::kNullObj; } - /// \brief traverses the UsdStage looking for the prims that are going to be handled by custom transformer - /// plug-ins. - /// \param proxyTransformPath the DAG path of the proxy shape - /// \param startPath the path from which iteration needs to start in the UsdStage - /// \param manufacture the translator registry - /// \return the array of prims found that will need to be imported - AL_USDMAYA_PUBLIC - std::vector huntForNativeNodesUnderPrim( - const MDagPath& proxyTransformPath, - SdfPath startPath, - fileio::translators::TranslatorManufacture& manufacture, - bool importAll = false); - - /// \brief constructs a single chain of transform nodes from the usdPrim to the root of this proxy shape. - /// \param usdPrim the leaf of the prim we wish to create - /// \param modifier will store the changes as this path is constructed. - /// \param reason the reason why this path is being generated. - /// \param modifier2 is specified, the modifier will end up containing a set of commands to switch the pushToPrim - /// flags to true. (This has to be done after the transform has been created and initialized, otherwise - /// the default maya values will be pushed in the UsdPrim, wiping out the values you just loaded) - /// \param createCount the returned number of transforms that were created. - /// \param pushToPrim the initial value for the pushToPrim attributes on the generate transform nodes - /// \param readAnimatedValues the initial value for the readAnimatedValues attributes on the generate transform nodes - /// \return the MObject of the parent transform node for the usdPrim - /// \todo The mode ProxyShape::kSelection will cause the possibility of instability in the selection system. - /// This mode will be removed at a future date - AL_USDMAYA_PUBLIC - MObject makeUsdTransformChain( - const UsdPrim& usdPrim, - MDagModifier& modifier, - TransformReason reason, - MDGModifier* modifier2 = 0, - uint32_t* createCount = 0, - bool pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"), - bool readAnimatedValues = MGlobal::optionVarIntValue("AL_usdmaya_readAnimatedValues")); - - /// \brief Will construct AL_usdmaya_Transform nodes for all of the prims from the specified usdPrim and down. - /// \param usdPrim the root for the transforms to be created - /// \param modifier the modifier that will store the creation steps for the transforms - /// \param reason the reason for creating the transforms (use with selection, etc). - /// \param modifier2 if specified, this will contain a set of commands that turn on the pushToPrim flag on the transform - /// nodes. These flags need to be set after the transforms have been created - /// \todo The mode ProxyShape::kSelection will cause the possibility of instability in the selection system. - /// This mode will be removed at a future date - AL_USDMAYA_PUBLIC - MObject makeUsdTransforms( - const UsdPrim& usdPrim, - MDagModifier& modifier, - TransformReason reason, - MDGModifier* modifier2 = 0); - - /// \brief will destroy all of the AL_usdmaya_Transform nodes from the prim specified, up to the root (unless any - /// of those transform nodes are in use by another imported prim). - /// \param usdPrim the leaf node in the chain of transforms we wish to remove - /// \param modifier will store the changes as this path is removed. - /// \param reason the reason why this path is being removed. - /// \todo The mode ProxyShape::kSelection will cause the possibility of instability in the selection system. - /// This mode will be removed at a future date - AL_USDMAYA_PUBLIC - void removeUsdTransformChain( - const UsdPrim& usdPrim, - MDagModifier& modifier, - TransformReason reason); - - /// \brief will destroy all of the AL_usdmaya_Transform nodes from the prim specified, up to the root (unless any - /// of those transform nodes are in use by another imported prim). - /// \param path the leaf node in the chain of transforms we wish to remove - /// \param modifier will store the changes as this path is removed. - /// \param reason the reason why this path is being removed. - AL_USDMAYA_PUBLIC - void removeUsdTransformChain( - const SdfPath& path, - MDagModifier& modifier, - TransformReason reason); - - /// \brief Will destroy all AL_usdmaya_Transform nodes found underneath the prim (unless those nodes are required - /// for another purpose). - /// \param usdPrim - /// \param modifier the modifier that will be filled with the instructions to delete the transform nodes - /// \param reason Are we deleting selected transforms, or those that are required, or requested? - /// \todo The mode ProxyShape::kSelection will cause the possibility of instability in the selection system. - /// This mode will be removed at a future date - AL_USDMAYA_PUBLIC - void removeUsdTransforms( - const UsdPrim& usdPrim, - MDagModifier& modifier, - TransformReason reason); - - /// \brief Debugging util - prints out the reference counts for each AL_usdmaya_Transform that currently exists - /// in the scene - AL_USDMAYA_PUBLIC - void printRefCounts() const; - - /// \brief destroys all internal transform references - void destroyTransformReferences() - { m_requiredPaths.clear(); } - - /// \brief Internal method. Used to filter out a set of paths into groups that need to be created, deleted, or updating. - /// \param previousPrims the previous list of prims underneath a prim in the process of a variant change - /// \param newPrimSet the list of prims found under neath the prim after the variant change. Prims that can be - /// updated will be removed from this list, leaving only the prims that need to be created. - /// \param transformsToCreate of the new nodes that can be created, if they are a DAG node (i.e. require a transform), - /// then this list will contain those nodes - /// \param updatablePrimSet a returned list of prims that can be updated - /// \param removedPrimSet a returned set of paths for objects that need to be deleted. - AL_USDMAYA_PUBLIC - void filterPrims( - const SdfPathVector& previousPrims, - std::vector& newPrimSet, - std::vector& transformsToCreate, - std::vector& updatablePrimSet, - SdfPathVector& removedPrimSet); - - /// \brief a method that is used within testing only. Returns the current reference count state for the path - /// \param path the prim path to test - /// \param selected the returned selected reference count - /// \param required the returned required reference count - /// \param refCount the returned refCount reference count - AL_USDMAYA_PUBLIC - void getCounts(SdfPath path, uint32_t& selected, uint32_t& required, uint32_t& refCount) - { - auto it = m_requiredPaths.find(path); - if(it != m_requiredPaths.end()) + /// \brief traverses the UsdStage looking for the prims that are going to be handled by custom + /// transformer + /// plug-ins. + /// \param proxyTransformPath the DAG path of the proxy shape + /// \param startPath the path from which iteration needs to start in the UsdStage + /// \param manufacture the translator registry + /// \return the array of prims found that will need to be imported + AL_USDMAYA_PUBLIC + std::vector huntForNativeNodesUnderPrim( + const MDagPath& proxyTransformPath, + SdfPath startPath, + fileio::translators::TranslatorManufacture& manufacture, + bool importAll = false); + + /// \brief constructs a single chain of transform nodes from the usdPrim to the root of this + /// proxy shape. \param usdPrim the leaf of the prim we wish to create \param modifier will + /// store the changes as this path is constructed. \param reason the reason why this path is + /// being generated. \param modifier2 is specified, the modifier will end up containing a set + /// of commands to switch the pushToPrim + /// flags to true. (This has to be done after the transform has been created and + /// initialized, otherwise the default maya values will be pushed in the UsdPrim, wiping + /// out the values you just loaded) + /// \param createCount the returned number of transforms that were created. + /// \param pushToPrim the initial value for the pushToPrim attributes on the generate transform + /// nodes \param readAnimatedValues the initial value for the readAnimatedValues attributes on + /// the generate transform nodes \return the MObject of the parent transform node for the + /// usdPrim \todo The mode ProxyShape::kSelection will cause the possibility of instability in + /// the selection system. + /// This mode will be removed at a future date + AL_USDMAYA_PUBLIC + MObject makeUsdTransformChain( + const UsdPrim& usdPrim, + MDagModifier& modifier, + TransformReason reason, + MDGModifier* modifier2 = 0, + uint32_t* createCount = 0, + bool pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"), + bool readAnimatedValues = MGlobal::optionVarIntValue("AL_usdmaya_readAnimatedValues")); + + /// \brief Will construct AL_usdmaya_Transform nodes for all of the prims from the specified + /// usdPrim and down. \param usdPrim the root for the transforms to be created \param modifier + /// the modifier that will store the creation steps for the transforms \param reason the reason + /// for creating the transforms (use with selection, etc). \param modifier2 if specified, this + /// will contain a set of commands that turn on the pushToPrim flag on the transform + /// nodes. These flags need to be set after the transforms have been created + /// \todo The mode ProxyShape::kSelection will cause the possibility of instability in the + /// selection system. + /// This mode will be removed at a future date + AL_USDMAYA_PUBLIC + MObject makeUsdTransforms( + const UsdPrim& usdPrim, + MDagModifier& modifier, + TransformReason reason, + MDGModifier* modifier2 = 0); + + /// \brief will destroy all of the AL_usdmaya_Transform nodes from the prim specified, up to + /// the root (unless any + /// of those transform nodes are in use by another imported prim). + /// \param usdPrim the leaf node in the chain of transforms we wish to remove + /// \param modifier will store the changes as this path is removed. + /// \param reason the reason why this path is being removed. + /// \todo The mode ProxyShape::kSelection will cause the possibility of instability in the + /// selection system. + /// This mode will be removed at a future date + AL_USDMAYA_PUBLIC + void + removeUsdTransformChain(const UsdPrim& usdPrim, MDagModifier& modifier, TransformReason reason); + + /// \brief will destroy all of the AL_usdmaya_Transform nodes from the prim specified, up to + /// the root (unless any + /// of those transform nodes are in use by another imported prim). + /// \param path the leaf node in the chain of transforms we wish to remove + /// \param modifier will store the changes as this path is removed. + /// \param reason the reason why this path is being removed. + AL_USDMAYA_PUBLIC + void + removeUsdTransformChain(const SdfPath& path, MDagModifier& modifier, TransformReason reason); + + /// \brief Will destroy all AL_usdmaya_Transform nodes found underneath the prim (unless those + /// nodes are required + /// for another purpose). + /// \param usdPrim + /// \param modifier the modifier that will be filled with the instructions to delete the + /// transform nodes \param reason Are we deleting selected transforms, or those that are + /// required, or requested? \todo The mode ProxyShape::kSelection will cause the possibility + /// of instability in the selection system. + /// This mode will be removed at a future date + AL_USDMAYA_PUBLIC + void + removeUsdTransforms(const UsdPrim& usdPrim, MDagModifier& modifier, TransformReason reason); + + /// \brief Debugging util - prints out the reference counts for each AL_usdmaya_Transform that + /// currently exists + /// in the scene + AL_USDMAYA_PUBLIC + void printRefCounts() const; + + /// \brief destroys all internal transform references + void destroyTransformReferences() { m_requiredPaths.clear(); } + + /// \brief Internal method. Used to filter out a set of paths into groups that need to be + /// created, deleted, or updating. \param previousPrims the previous list of prims underneath a + /// prim in the process of a variant change \param newPrimSet the list of prims found under + /// neath the prim after the variant change. Prims that can be + /// updated will be removed from this list, leaving only the prims that need to be + /// created. + /// \param transformsToCreate of the new nodes that can be created, if they are a DAG node + /// (i.e. require a transform), + /// then this list will contain those nodes + /// \param updatablePrimSet a returned list of prims that can be updated + /// \param removedPrimSet a returned set of paths for objects that need to be deleted. + AL_USDMAYA_PUBLIC + void filterPrims( + const SdfPathVector& previousPrims, + std::vector& newPrimSet, + std::vector& transformsToCreate, + std::vector& updatablePrimSet, + SdfPathVector& removedPrimSet); + + /// \brief a method that is used within testing only. Returns the current reference count state + /// for the path \param path the prim path to test \param selected the returned selected + /// reference count \param required the returned required reference count \param refCount the + /// returned refCount reference count + AL_USDMAYA_PUBLIC + void getCounts(SdfPath path, uint32_t& selected, uint32_t& required, uint32_t& refCount) { - selected = it->second.selected(); - required = it->second.required(); - refCount = it->second.refCount(); + auto it = m_requiredPaths.find(path); + if (it != m_requiredPaths.end()) { + selected = it->second.selected(); + required = it->second.required(); + refCount = it->second.refCount(); + } } - } - - /// \brief Tests to see if a given MObject is currently selected in the proxy shape. If the specified MObject is - /// selected, then the path will be filled with the corresponding usd prim path. - /// \param obj the input MObject to see if it's selected. - /// \param path the returned prim path (if the node is found) - /// \return true if the maya node is currently selected - AL_USDMAYA_PUBLIC - bool isSelectedMObject(MObject obj, SdfPath& path) - { - for(auto it : m_requiredPaths) + + /// \brief Tests to see if a given MObject is currently selected in the proxy shape. If the + /// specified MObject is + /// selected, then the path will be filled with the corresponding usd prim path. + /// \param obj the input MObject to see if it's selected. + /// \param path the returned prim path (if the node is found) + /// \return true if the maya node is currently selected + AL_USDMAYA_PUBLIC + bool isSelectedMObject(MObject obj, SdfPath& path) { - if(obj == it.second.node()) - { - path = it.first; - if(m_selectedPaths.count(it.first) > 0) - { - return true; + for (auto it : m_requiredPaths) { + if (obj == it.second.node()) { + path = it.first; + if (m_selectedPaths.count(it.first) > 0) { + return true; + } + break; + } } - break; - } + return false; } - return false; - } - - //-------------------------------------------------------------------------------------------------------------------- - /// \name Plug-in Translator node methods - //-------------------------------------------------------------------------------------------------------------------- - - /// \brief serialises the translator context - AL_USDMAYA_PUBLIC - void serialiseTranslatorContext(); - - /// \brief deserialises the translator context - AL_USDMAYA_PUBLIC - void deserialiseTranslatorContext(); - - /// \brief gets the maya node path for a prim, stores the mapping and returns it - /// \param usdPrim the prim we are bringing in to maya - /// \param mayaObject the corresponding maya node - /// \return a dag path to the maya object - AL_USDMAYA_PUBLIC - MString recordUsdPrimToMayaPath(const UsdPrim &usdPrim, - const MObject &mayaObject); - - /// \brief returns the stored maya node path for a prim - /// \param usdPrim a prim that has been brought into maya - /// \return a dag path to the maya object - AL_USDMAYA_PUBLIC - MString getMayaPathFromUsdPrim(const UsdPrim& usdPrim) const; - - /// \brief aggregates logic that needs to iterate through the hierarchy looking for properties/metdata on prims - AL_USDMAYA_PUBLIC - void findPrimsWithMetaData(); - - /// \brief returns the plugin translator registry assigned to this shape - /// \return the translator registry - fileio::translators::TranslatorManufacture& translatorManufacture() - { return m_translatorManufacture; } - - /// \brief returns the plugin translator context assigned to this shape - /// \return the translator context - inline fileio::translators::TranslatorContextPtr& context() - { return m_context; } - - //-------------------------------------------------------------------------------------------------------------------- - /// \name ProxyShape selection - //-------------------------------------------------------------------------------------------------------------------- - - /// \brief returns the paths of the selected items within the proxy shape - /// \return the paths of the selected prims - AL_USDMAYA_PUBLIC - SdfPathHashSet& selectedPaths() - { return m_selectedPaths; } - - /// \brief Performs a selection operation on this node. Intended for use by the ProxyShapeSelect command only - /// \param helper provides the arguments to the selection system, and stores the internal proxy shape state - /// changes that need to be done/undone - /// \param orderedPaths provides the original (deduplicated) input paths, in order; provided just so that the - /// selection commands will return results in the same order they were provided - this is useful so that, if - /// the user does, ie, "AL_usdmaya_ProxyShapeSelect -pp /foo/bar -pp /some/thing -proxy myProxyShape", - // they will get as the result of the command, ["|proxyRoot|foo|bar", "|proxyRoot|some|thing"], and be able - // to know what input SdfPath corresponds to what ouptut maya path - /// \return true if the operation succeeded - AL_USDMAYA_PUBLIC - bool doSelect(SelectionUndoHelper& helper, const SdfPathVector& orderedPaths); - - //-------------------------------------------------------------------------------------------------------------------- - /// \name UsdImaging - //-------------------------------------------------------------------------------------------------------------------- - - /// \brief returns and optionally constructs the usd imaging engine for this proxy shape - /// \return the imagine engine instance for this shape (shared between draw override and shape ui) - AL_USDMAYA_PUBLIC - Engine* engine(bool construct=true); - - //-------------------------------------------------------------------------------------------------------------------- - /// \name Miscellaneous - //-------------------------------------------------------------------------------------------------------------------- - - /// \brief unloads all maya references - /// \todo I think we could remove this now? The only place this is used is within the post load process to ensure we - /// don't duplicate any references in the scene. This can probably be removed. - AL_USDMAYA_PUBLIC - void unloadMayaReferences(); - - /// \brief if a root prim has been specified by the user in the proxy shape AE, then this method will return - /// the associated prim (used by the Hydra rendering code to select a root to render from). If no prim - /// has been specified, the pseudo root will be passed to UsdImaging - /// \return the prim specified by the user (if valid), the pseudo root if no prim has been specified, or a NULL - /// prim if the stage is invalid. - UsdPrim getRootPrim() + + //-------------------------------------------------------------------------------------------------------------------- + /// \name Plug-in Translator node methods + //-------------------------------------------------------------------------------------------------------------------- + + /// \brief serialises the translator context + AL_USDMAYA_PUBLIC + void serialiseTranslatorContext(); + + /// \brief deserialises the translator context + AL_USDMAYA_PUBLIC + void deserialiseTranslatorContext(); + + /// \brief gets the maya node path for a prim, stores the mapping and returns it + /// \param usdPrim the prim we are bringing in to maya + /// \param mayaObject the corresponding maya node + /// \return a dag path to the maya object + AL_USDMAYA_PUBLIC + MString recordUsdPrimToMayaPath(const UsdPrim& usdPrim, const MObject& mayaObject); + + /// \brief returns the stored maya node path for a prim + /// \param usdPrim a prim that has been brought into maya + /// \return a dag path to the maya object + AL_USDMAYA_PUBLIC + MString getMayaPathFromUsdPrim(const UsdPrim& usdPrim) const; + + /// \brief aggregates logic that needs to iterate through the hierarchy looking for + /// properties/metdata on prims + AL_USDMAYA_PUBLIC + void findPrimsWithMetaData(); + + /// \brief returns the plugin translator registry assigned to this shape + /// \return the translator registry + fileio::translators::TranslatorManufacture& translatorManufacture() { - if(m_stage) - { - if(!m_path.IsEmpty()) - { - UsdPrim prim = m_stage->GetPrimAtPath(m_path); - if(prim) - return prim; + return m_translatorManufacture; + } + + /// \brief returns the plugin translator context assigned to this shape + /// \return the translator context + inline fileio::translators::TranslatorContextPtr& context() { return m_context; } + + //-------------------------------------------------------------------------------------------------------------------- + /// \name ProxyShape selection + //-------------------------------------------------------------------------------------------------------------------- + + /// \brief returns the paths of the selected items within the proxy shape + /// \return the paths of the selected prims + AL_USDMAYA_PUBLIC + SdfPathHashSet& selectedPaths() { return m_selectedPaths; } + + /// \brief Performs a selection operation on this node. Intended for use by the + /// ProxyShapeSelect command only \param helper provides the arguments to the selection system, + /// and stores the internal proxy shape state + /// changes that need to be done/undone + /// \param orderedPaths provides the original (deduplicated) input paths, in order; provided + /// just so that the + /// selection commands will return results in the same order they were provided - this + /// is useful so that, if the user does, ie, "AL_usdmaya_ProxyShapeSelect -pp /foo/bar + /// -pp /some/thing -proxy myProxyShape", + // they will get as the result of the command, ["|proxyRoot|foo|bar", + // "|proxyRoot|some|thing"], and be able to know what input SdfPath corresponds to what + // ouptut maya path + /// \return true if the operation succeeded + AL_USDMAYA_PUBLIC + bool doSelect(SelectionUndoHelper& helper, const SdfPathVector& orderedPaths); + + //-------------------------------------------------------------------------------------------------------------------- + /// \name UsdImaging + //-------------------------------------------------------------------------------------------------------------------- + + /// \brief returns and optionally constructs the usd imaging engine for this proxy shape + /// \return the imagine engine instance for this shape (shared between draw override and shape + /// ui) + AL_USDMAYA_PUBLIC + Engine* engine(bool construct = true); + + //-------------------------------------------------------------------------------------------------------------------- + /// \name Miscellaneous + //-------------------------------------------------------------------------------------------------------------------- + + /// \brief unloads all maya references + /// \todo I think we could remove this now? The only place this is used is within the post + /// load process to ensure we + /// don't duplicate any references in the scene. This can probably be removed. + AL_USDMAYA_PUBLIC + void unloadMayaReferences(); + + /// \brief if a root prim has been specified by the user in the proxy shape AE, then this + /// method will return + /// the associated prim (used by the Hydra rendering code to select a root to render + /// from). If no prim has been specified, the pseudo root will be passed to UsdImaging + /// \return the prim specified by the user (if valid), the pseudo root if no prim has been + /// specified, or a NULL + /// prim if the stage is invalid. + UsdPrim getRootPrim() + { + if (m_stage) { + if (!m_path.IsEmpty()) { + UsdPrim prim = m_stage->GetPrimAtPath(m_path); + if (prim) + return prim; + } + return m_stage->GetPseudoRoot(); } - return m_stage->GetPseudoRoot(); - } - return UsdPrim(); + return UsdPrim(); } - /// \brief serialise the state of the transform ref counts prior to saving the file - AL_USDMAYA_PUBLIC - void serialiseTransformRefs(); - - /// \brief deserialise the state of the transform ref counts prior to saving the file - AL_USDMAYA_PUBLIC - void deserialiseTransformRefs(); - - /// \brief Finds the corresponding translator for each decendant prim that has a corresponding Translator - /// and calls preTearDown. - /// \param[in] path of the point in the hierarchy that is potentially undergoing structural changes - /// \param[out] outPathVector of SdfPaths that are decendants of 'path' - AL_USDMAYA_PUBLIC - void onPrePrimChanged(const SdfPath& path, SdfPathVector& outPathVector); - - // \brief process any USD objects which have been changed, normally by a notice of some kind - /// \param[in] resyncedPaths vector of topmost paths for which hierarchy has changed - /// \param[in] changedOnlyPaths vector of paths that changed properties - /// \note do we need to handle the complex prim locking and selection logic that is curently on by default? - void processChangedObjects(const SdfPathVector& resyncedPaths, const SdfPathVector& changedOnlyPaths); - - /// \brief Re-Creates and updates the maya prim hierarchy starting from the specified primpath - /// \param[in] primPath of the point in the hierarchy that is potentially undergoing structural changes - /// \param[in] changedPaths are child paths that existed previously and may not be existing now. - AL_USDMAYA_PUBLIC - void onPrimResync(SdfPath primPath, SdfPathVector& changedPaths); - - /// \brief Preps translators for change, and then re-ceates and updates the maya prim hierarchy below the - /// specified primPath as if a variant change occurred. - /// \param[in] primPath of the point in the hierarchy that is potentially undergoing structural changes - AL_USDMAYA_PUBLIC - void resync(const SdfPath& primPath); - - - // \brief Serialize information unique to this shape - AL_USDMAYA_PUBLIC - void serialize(UsdStageRefPtr stage, LayerManager* layerManager); - - // \brief Serialize all layers in proxyShapes to layerManager attributes; called before saving - AL_USDMAYA_PUBLIC - static void serializeAll(); - - static inline std::vector& GetUnloadedProxyShapes() - { - return m_unloadedProxyShapes; - } - - /// \brief This function starts the prim changed process within the proxyshape - /// \param[in] changePath is point at which the scene is going to be modified. - inline void primChangedAtPath(const SdfPath& changePath) - { - UsdPrim p = m_stage->GetPrimAtPath(changePath); - - if(!p.IsValid()) + /// \brief serialise the state of the transform ref counts prior to saving the file + AL_USDMAYA_PUBLIC + void serialiseTransformRefs(); + + /// \brief deserialise the state of the transform ref counts prior to saving the file + AL_USDMAYA_PUBLIC + void deserialiseTransformRefs(); + + /// \brief Finds the corresponding translator for each decendant prim that has a corresponding + /// Translator + /// and calls preTearDown. + /// \param[in] path of the point in the hierarchy that is potentially undergoing structural + /// changes \param[out] outPathVector of SdfPaths that are decendants of 'path' + AL_USDMAYA_PUBLIC + void onPrePrimChanged(const SdfPath& path, SdfPathVector& outPathVector); + + // \brief process any USD objects which have been changed, normally by a notice of some kind + /// \param[in] resyncedPaths vector of topmost paths for which hierarchy has changed + /// \param[in] changedOnlyPaths vector of paths that changed properties + /// \note do we need to handle the complex prim locking and selection logic that is curently on + /// by default? + void processChangedObjects( + const SdfPathVector& resyncedPaths, + const SdfPathVector& changedOnlyPaths); + + /// \brief Re-Creates and updates the maya prim hierarchy starting from the specified primpath + /// \param[in] primPath of the point in the hierarchy that is potentially undergoing structural + /// changes \param[in] changedPaths are child paths that existed previously and may not be + /// existing now. + AL_USDMAYA_PUBLIC + void onPrimResync(SdfPath primPath, SdfPathVector& changedPaths); + + /// \brief Preps translators for change, and then re-ceates and updates the maya prim hierarchy + /// below the + /// specified primPath as if a variant change occurred. + /// \param[in] primPath of the point in the hierarchy that is potentially undergoing structural + /// changes + AL_USDMAYA_PUBLIC + void resync(const SdfPath& primPath); + + // \brief Serialize information unique to this shape + AL_USDMAYA_PUBLIC + void serialize(UsdStageRefPtr stage, LayerManager* layerManager); + + // \brief Serialize all layers in proxyShapes to layerManager attributes; called before saving + AL_USDMAYA_PUBLIC + static void serializeAll(); + + static inline std::vector& GetUnloadedProxyShapes() { - MGlobal::displayInfo("ProxyShape: Could not change prim at path since there was no valid prim at the passed in path"); - return; + return m_unloadedProxyShapes; } - m_compositionHasChanged = true; - m_changedPath = changePath; - onPrePrimChanged(m_changedPath, m_variantSwitchedPrims); - } - - /// \brief change the status of the composition changed status - /// \param hasObjectsChanged - inline void setHaveObjectsChangedAtPath(const bool hasObjectsChanged) - { m_compositionHasChanged = hasObjectsChanged; } - - /// \brief provides access to the selection list on this proxy shape - /// \return the internal selection list - SelectionList& selectionList() - { return m_selectionList; } - - /// \brief internal method used to correctly schedule changes to the selection list - /// \param hasSelectabilityChanged the state - inline void setChangedSelectionState(const bool hasSelectabilityChanged) - { m_hasChangedSelection = hasSelectabilityChanged; } - - /// \brief Returns the SelectionDatabase owned by the ProxyShape - /// \return A SelectableDB owned by the ProxyShape - AL::usdmaya::SelectabilityDB& selectabilityDB() - { return m_selectabilityDB; } - - /// \brief Returns the SelectionDatabase owned by the ProxyShape - /// \return A constant SelectableDB owned by the ProxyShape - const AL::usdmaya::SelectabilityDB& selectabilityDB() const - { return const_cast(this)->selectabilityDB(); } - - /// \brief used to reload the stage after file open - AL_USDMAYA_PUBLIC - void loadStage(); - - AL_USDMAYA_PUBLIC - void constructLockPrims(); - - /// \brief Translates prims at the specified paths, the operation conducted by the translator depends on - /// which list you populate. - /// \param importPaths paths you wish to import - /// \param teardownPaths paths you wish to teardown - /// \param param are params which direct the translation of the prims - AL_USDMAYA_PUBLIC - void translatePrimPathsIntoMaya( - const SdfPathVector& importPaths, - const SdfPathVector& teardownPaths, - const fileio::translators::TranslatorParameters& param = fileio::translators::TranslatorParameters()); - - /// \brief Translates prims at the specified paths, the operation conducted by the translator depends on - /// which list you populate. - /// \param importPrims array of prims you wish to import - /// \param teardownPaths paths you wish to teardown - /// \param param are flags which direct the translation of the prims - AL_USDMAYA_PUBLIC - void translatePrimsIntoMaya( - const MayaUsdUtils::UsdPrimVector& importPrims, - const SdfPathVector& teardownPaths, - const fileio::translators::TranslatorParameters& param = fileio::translators::TranslatorParameters()); - - /// \brief Breaks a comma separated string up into a SdfPath Vector - /// \param paths the comma separated list of paths - /// \return the separated list of paths - AL_USDMAYA_PUBLIC - SdfPathVector getPrimPathsFromCommaJoinedString(const MString &paths) const; -#if defined(WANT_UFE_BUILD) - /// \brief Get the UFE path of the maya proxy shape - /// \return An UFE path containing the path to the proxy shape - AL_USDMAYA_PUBLIC - Ufe::Path ufePath() const; - - /// \brief Get the UFE path segment of the maya proxy shape - /// \return An UFE path segment containing the maya path to the proxy shape - AL_USDMAYA_PUBLIC - Ufe::PathSegment ufePathSegment() const; -#endif + /// \brief This function starts the prim changed process within the proxyshape + /// \param[in] changePath is point at which the scene is going to be modified. + inline void primChangedAtPath(const SdfPath& changePath) + { + UsdPrim p = m_stage->GetPrimAtPath(changePath); - /// \brief Returns the selection mask of the shape - AL_USDMAYA_PUBLIC - MSelectionMask getShapeSelectionMask() const override; + if (!p.IsValid()) { + MGlobal::displayInfo("ProxyShape: Could not change prim at path since there was no " + "valid prim at the passed in path"); + return; + } + m_compositionHasChanged = true; + m_changedPath = changePath; + onPrePrimChanged(m_changedPath, m_variantSwitchedPrims); + } + /// \brief change the status of the composition changed status + /// \param hasObjectsChanged + inline void setHaveObjectsChangedAtPath(const bool hasObjectsChanged) + { + m_compositionHasChanged = hasObjectsChanged; + } - /// \brief determines if this prim has a parent that has been tagged as excluded geometry - /// (i.e. will not be shown in the viewport) - /// \param prim the prim to check - /// \return true if the prim (or a parent prim) has been tagged as excluded - AL_USDMAYA_PUBLIC - bool primHasExcludedParent(UsdPrim prim); + /// \brief provides access to the selection list on this proxy shape + /// \return the internal selection list + SelectionList& selectionList() { return m_selectionList; } -private: - /// \brief constructs the USD imaging engine for this shape - void constructGLImagingEngine(); - - /// \brief destroys the USD imaging engine for this shape - void destroyGLImagingEngine(); - - static void onSelectionChanged(void* ptr); - bool removeAllSelectedNodes(SelectionUndoHelper& helper); - void removeTransformRefs(const std::vector>& removedRefs, TransformReason reason); - void insertTransformRefs(const std::vector>& removedRefs, TransformReason reason); - - void constructExcludedPrims(); - - MObject makeUsdTransformChain_internal( - const UsdPrim& usdPrim, - MDagModifier& modifier, - TransformReason reason, - MDGModifier* modifier2 = 0, - uint32_t* createCount = 0, - MString* newPath = 0, - bool pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"), - bool readAnimatedValues = MGlobal::optionVarIntValue("AL_usdmaya_readAnimatedValues")); - - void removeUsdTransformChain_internal( - const UsdPrim& usdPrim, - MDagModifier& modifier, - TransformReason reason); - - MObject makeUsdTransformChain( - UsdPrim usdPrim, - const MPlug& outStage, - const MPlug& outTime, - const MObject& parentXForm, - MDagModifier& modifier, - TransformReason reason, - MDGModifier* modifier2, - uint32_t* createCount, - MString* newPath = 0, - bool pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"), - bool readAnimatedValues = MGlobal::optionVarIntValue("AL_usdmaya_readAnimatedValues")); - - void makeUsdTransformsInternal( - const UsdPrim& usdPrim, - const MObject& parentXForm, - MDagModifier& modifier, - TransformReason reason, - MDGModifier* modifier2, - bool pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"), - bool readAnimatedValues = MGlobal::optionVarIntValue("AL_usdmaya_readAnimatedValues")); - - void removeUsdTransformsInternal( - const UsdPrim& usdPrim, - MDagModifier& modifier, - TransformReason reason); - - struct TransformReference - { - TransformReference(const MObject& node, const TransformReason reason); - TransformReference(MObject mayaNode, Scope* node, uint32_t r, uint32_t s, uint32_t rc); - MObject node() const { return m_node; } - Scope* getTransformNode() const; - - bool decRef(const TransformReason reason); - void incRef(const TransformReason reason); - void checkIncRef(const TransformReason reason); - bool checkRef(const TransformReason reason); - - void printRefCounts() const + /// \brief internal method used to correctly schedule changes to the selection list + /// \param hasSelectabilityChanged the state + inline void setChangedSelectionState(const bool hasSelectabilityChanged) + { + m_hasChangedSelection = hasSelectabilityChanged; + } + + /// \brief Returns the SelectionDatabase owned by the ProxyShape + /// \return A SelectableDB owned by the ProxyShape + AL::usdmaya::SelectabilityDB& selectabilityDB() { return m_selectabilityDB; } + + /// \brief Returns the SelectionDatabase owned by the ProxyShape + /// \return A constant SelectableDB owned by the ProxyShape + const AL::usdmaya::SelectabilityDB& selectabilityDB() const { - MObjectHandle handle(m_node); - std::cout << "[valid = " << handle.isValid() << ", alive = " << handle.isAlive() << "] "; - std::cout - << m_required << ":" - << m_selectedTemp << ":" - << m_selected << ":" - << int(m_refCount) << std::endl; + return const_cast(this)->selectabilityDB(); } - uint16_t selected() const { return m_selected; } - uint16_t required() const { return m_required; } - uint16_t refCount() const { return m_refCount; } - void prepSelect() - { m_selectedTemp = m_selected; } - private: - MObject m_node; - Scope* m_transform; - // ref counting values - struct + + /// \brief used to reload the stage after file open + AL_USDMAYA_PUBLIC + void loadStage(); + + AL_USDMAYA_PUBLIC + void constructLockPrims(); + + /// \brief Translates prims at the specified paths, the operation conducted by the translator + /// depends on + /// which list you populate. + /// \param importPaths paths you wish to import + /// \param teardownPaths paths you wish to teardown + /// \param param are params which direct the translation of the prims + AL_USDMAYA_PUBLIC + void translatePrimPathsIntoMaya( + const SdfPathVector& importPaths, + const SdfPathVector& teardownPaths, + const fileio::translators::TranslatorParameters& param + = fileio::translators::TranslatorParameters()); + + /// \brief Translates prims at the specified paths, the operation conducted by the translator + /// depends on + /// which list you populate. + /// \param importPrims array of prims you wish to import + /// \param teardownPaths paths you wish to teardown + /// \param param are flags which direct the translation of the prims + AL_USDMAYA_PUBLIC + void translatePrimsIntoMaya( + const MayaUsdUtils::UsdPrimVector& importPrims, + const SdfPathVector& teardownPaths, + const fileio::translators::TranslatorParameters& param + = fileio::translators::TranslatorParameters()); + + /// \brief Breaks a comma separated string up into a SdfPath Vector + /// \param paths the comma separated list of paths + /// \return the separated list of paths + AL_USDMAYA_PUBLIC + SdfPathVector getPrimPathsFromCommaJoinedString(const MString& paths) const; + +#if defined(WANT_UFE_BUILD) + /// \brief Get the UFE path of the maya proxy shape + /// \return An UFE path containing the path to the proxy shape + AL_USDMAYA_PUBLIC + Ufe::Path ufePath() const; + + /// \brief Get the UFE path segment of the maya proxy shape + /// \return An UFE path segment containing the maya path to the proxy shape + AL_USDMAYA_PUBLIC + Ufe::PathSegment ufePathSegment() const; +#endif + + /// \brief Returns the selection mask of the shape + AL_USDMAYA_PUBLIC + MSelectionMask getShapeSelectionMask() const override; + + /// \brief determines if this prim has a parent that has been tagged as excluded geometry + /// (i.e. will not be shown in the viewport) + /// \param prim the prim to check + /// \return true if the prim (or a parent prim) has been tagged as excluded + AL_USDMAYA_PUBLIC + bool primHasExcludedParent(UsdPrim prim); + +private: + /// \brief constructs the USD imaging engine for this shape + void constructGLImagingEngine(); + + /// \brief destroys the USD imaging engine for this shape + void destroyGLImagingEngine(); + + static void onSelectionChanged(void* ptr); + bool removeAllSelectedNodes(SelectionUndoHelper& helper); + void removeTransformRefs( + const std::vector>& removedRefs, + TransformReason reason); + void insertTransformRefs( + const std::vector>& removedRefs, + TransformReason reason); + + void constructExcludedPrims(); + + MObject makeUsdTransformChain_internal( + const UsdPrim& usdPrim, + MDagModifier& modifier, + TransformReason reason, + MDGModifier* modifier2 = 0, + uint32_t* createCount = 0, + MString* newPath = 0, + bool pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"), + bool readAnimatedValues = MGlobal::optionVarIntValue("AL_usdmaya_readAnimatedValues")); + + void removeUsdTransformChain_internal( + const UsdPrim& usdPrim, + MDagModifier& modifier, + TransformReason reason); + + MObject makeUsdTransformChain( + UsdPrim usdPrim, + const MPlug& outStage, + const MPlug& outTime, + const MObject& parentXForm, + MDagModifier& modifier, + TransformReason reason, + MDGModifier* modifier2, + uint32_t* createCount, + MString* newPath = 0, + bool pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"), + bool readAnimatedValues = MGlobal::optionVarIntValue("AL_usdmaya_readAnimatedValues")); + + void makeUsdTransformsInternal( + const UsdPrim& usdPrim, + const MObject& parentXForm, + MDagModifier& modifier, + TransformReason reason, + MDGModifier* modifier2, + bool pushToPrim = MGlobal::optionVarIntValue("AL_usdmaya_pushToPrim"), + bool readAnimatedValues = MGlobal::optionVarIntValue("AL_usdmaya_readAnimatedValues")); + + void removeUsdTransformsInternal( + const UsdPrim& usdPrim, + MDagModifier& modifier, + TransformReason reason); + + struct TransformReference { - uint16_t m_required; - uint16_t m_selectedTemp; - uint16_t m_selected; - uint16_t m_refCount; + TransformReference(const MObject& node, const TransformReason reason); + TransformReference(MObject mayaNode, Scope* node, uint32_t r, uint32_t s, uint32_t rc); + MObject node() const { return m_node; } + Scope* getTransformNode() const; + + bool decRef(const TransformReason reason); + void incRef(const TransformReason reason); + void checkIncRef(const TransformReason reason); + bool checkRef(const TransformReason reason); + + void printRefCounts() const + { + MObjectHandle handle(m_node); + std::cout << "[valid = " << handle.isValid() << ", alive = " << handle.isAlive() + << "] "; + std::cout << m_required << ":" << m_selectedTemp << ":" << m_selected << ":" + << int(m_refCount) << std::endl; + } + uint16_t selected() const { return m_selected; } + uint16_t required() const { return m_required; } + uint16_t refCount() const { return m_refCount; } + void prepSelect() { m_selectedTemp = m_selected; } + + private: + MObject m_node; + Scope* m_transform; + // ref counting values + struct + { + uint16_t m_required; + uint16_t m_selectedTemp; + uint16_t m_selected; + uint16_t m_refCount; + }; }; - }; - - /// if the USD stage contains a maya reference et-al, then we have a set of *REQUIRED* AL::usdmaya::nodes::Transform nodes. - /// If we then later create a USD transform node (because we're bringing in all of them, or just a selection of them), - /// then we must make sure that we don't end up duplicating paths. This map is use to store a LUT of the paths that - /// must always exist, and never get deleted. - typedef std::map TransformReferenceMap; - TransformReferenceMap m_requiredPaths; - - - /// it is possible to end up with some invalid data in here as a result of a variant switch. When it looks as though a - /// schema prim is going to change type, in cases where a payload fails to resolve, we can end up with null prims in the - /// stage. As a result, it's corresponding transform ref can fail to load. - void cleanupTransformRefs(); - - /// insert a new path into the requiredPaths map - void makeTransformReference(const SdfPath& path, const MObject& node, TransformReason reason); - - /// selection can cause multiple transform chains to be removed. To ensure the ref counts are correctly correlated, - /// we need to make sure we can remove - void prepSelect(); - - //-------------------------------------------------------------------------------------------------------------------- - /// \name Virtual overrides - //-------------------------------------------------------------------------------------------------------------------- - - void postConstructor() override; - MStatus compute(const MPlug& plug, MDataBlock& dataBlock) override; - bool setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) override; - bool getInternalValue(const MPlug& plug, MDataHandle& dataHandle) override; - MStatus setDependentsDirty(const MPlug& plugBeingDirtied, MPlugArray& plugs) override; - bool isBounded() const override; - MPxNode::SchedulingType schedulingType() const override { return kSerial; } - MStatus preEvaluation(const MDGContext & context, const MEvaluationNode& evaluationNode) override; - void CacheEmptyBoundingBox(MBoundingBox&) override; - UsdTimeCode GetOutputTime(MDataBlock) const override; - void copyInternalData(MPxNode* srcNode) override; - - //-------------------------------------------------------------------------------------------------------------------- - /// \name Compute methods - //-------------------------------------------------------------------------------------------------------------------- - - // split out compute methods. - MStatus computeInStageDataCached(const MPlug& plug, MDataBlock& dataBlock); - MStatus computeOutStageData(const MPlug& plug, MDataBlock& dataBlock); - MStatus computeOutputTime(const MPlug& plug, MDataBlock& dataBlock, MTime&); - - //-------------------------------------------------------------------------------------------------------------------- - /// \name Utils - //-------------------------------------------------------------------------------------------------------------------- - - UsdPrim getUsdPrim(MDataBlock& dataBlock) const; - SdfPathVector getExcludePrimPaths() const override; - UsdStagePopulationMask constructStagePopulationMask(const MString &paths) const; - - /// \brief Convert variant fallbacks from string (attribute value) - /// \param fallbacksStr attribute value - /// \return PcpVariantFallbackMap type of variant fallbacks - PcpVariantFallbackMap convertVariantFallbackFromStr(const MString& fallbacksStr) const; - - /// \brief Convert variant fallbacks to string - /// \param fallbacks variant fallbacks map - /// \return MString string form of variant fallbacks - MString convertVariantFallbacksToStr(const PcpVariantFallbackMap& fallbacks) const; - - /// \brief Get variant fallbacks from session layer - /// \param layer session layer pointer - /// \return MString string form of variant fallbacks JSON data - MString getVariantFallbacksFromLayer(const SdfLayerRefPtr& layer) const; - - /// \brief Set global variant fallbacks if found from attribute ".variantFallbacks" - /// \param defaultVariantFallbacks default global variant fallbacks before updating - /// \param dataBlock attribute data block - /// \return PcpVariantFallbackMap variant fallbacks that applied to global variant fallbacks, would be empty if nothing applied - PcpVariantFallbackMap updateVariantFallbacks(PcpVariantFallbackMap& defaultVariantFallbacks, MDataBlock& dataBlock) const; - - /// \brief Save variant fallbacks from session layer customLayerData to attribute - /// \param fallbacksStr string format of variant fallbacks to save to the node attribute - /// \param dataBlock attribute data block - void saveVariantFallbacks(const MString& fallbacksStr, MDataBlock& dataBlock) const; - - bool isStageValid() const; - bool initPrim(const uint32_t index, MDGContext& ctx); - - void layerIdChanged(SdfNotice::LayerIdentifierDidChange const& notice, UsdStageWeakPtr const& sender); - void onObjectsChanged(UsdNotice::ObjectsChanged const&, UsdStageWeakPtr const& sender); - void variantSelectionListener(SdfNotice::LayersDidChange const& notice); - void onEditTargetChanged(UsdNotice::StageEditTargetChanged const& notice, UsdStageWeakPtr const& sender); - void trackEditTargetLayer(LayerManager* layerManager=nullptr); - void trackAllDirtyLayers(LayerManager* layerManager=nullptr); - void validateTransforms(); - void onTransactionNotice(AL::usd::transaction::CloseNotice const ¬ice, const UsdStageWeakPtr& stage); - void onRedraw() { m_requestedRedraw = false; } - - /// get the stored Translator ID for a Path - std::string getTranslatorIdForPath(const SdfPath& path) override - { return m_context->getTranslatorIdForPath(path); } - - bool getTranslatorInfo(const std::string& translatorId, bool& supportsUpdate, bool& requiresParent, bool& importableByDefault) override + + /// if the USD stage contains a maya reference et-al, then we have a set of *REQUIRED* + /// AL::usdmaya::nodes::Transform nodes. If we then later create a USD transform node (because + /// we're bringing in all of them, or just a selection of them), then we must make sure that we + /// don't end up duplicating paths. This map is use to store a LUT of the paths that must always + /// exist, and never get deleted. + typedef std::map TransformReferenceMap; + TransformReferenceMap m_requiredPaths; + + /// it is possible to end up with some invalid data in here as a result of a variant switch. + /// When it looks as though a schema prim is going to change type, in cases where a payload + /// fails to resolve, we can end up with null prims in the stage. As a result, it's + /// corresponding transform ref can fail to load. + void cleanupTransformRefs(); + + /// insert a new path into the requiredPaths map + void makeTransformReference(const SdfPath& path, const MObject& node, TransformReason reason); + + /// selection can cause multiple transform chains to be removed. To ensure the ref counts are + /// correctly correlated, we need to make sure we can remove + void prepSelect(); + + //-------------------------------------------------------------------------------------------------------------------- + /// \name Virtual overrides + //-------------------------------------------------------------------------------------------------------------------- + + void postConstructor() override; + MStatus compute(const MPlug& plug, MDataBlock& dataBlock) override; + bool setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) override; + bool getInternalValue(const MPlug& plug, MDataHandle& dataHandle) override; + MStatus setDependentsDirty(const MPlug& plugBeingDirtied, MPlugArray& plugs) override; + bool isBounded() const override; + MPxNode::SchedulingType schedulingType() const override { return kSerial; } + MStatus + preEvaluation(const MDGContext& context, const MEvaluationNode& evaluationNode) override; + void CacheEmptyBoundingBox(MBoundingBox&) override; + UsdTimeCode GetOutputTime(MDataBlock) const override; + void copyInternalData(MPxNode* srcNode) override; + + //-------------------------------------------------------------------------------------------------------------------- + /// \name Compute methods + //-------------------------------------------------------------------------------------------------------------------- + + // split out compute methods. + MStatus computeInStageDataCached(const MPlug& plug, MDataBlock& dataBlock); + MStatus computeOutStageData(const MPlug& plug, MDataBlock& dataBlock); + MStatus computeOutputTime(const MPlug& plug, MDataBlock& dataBlock, MTime&); + + //-------------------------------------------------------------------------------------------------------------------- + /// \name Utils + //-------------------------------------------------------------------------------------------------------------------- + + UsdPrim getUsdPrim(MDataBlock& dataBlock) const; + SdfPathVector getExcludePrimPaths() const override; + UsdStagePopulationMask constructStagePopulationMask(const MString& paths) const; + + /// \brief Convert variant fallbacks from string (attribute value) + /// \param fallbacksStr attribute value + /// \return PcpVariantFallbackMap type of variant fallbacks + PcpVariantFallbackMap convertVariantFallbackFromStr(const MString& fallbacksStr) const; + + /// \brief Convert variant fallbacks to string + /// \param fallbacks variant fallbacks map + /// \return MString string form of variant fallbacks + MString convertVariantFallbacksToStr(const PcpVariantFallbackMap& fallbacks) const; + + /// \brief Get variant fallbacks from session layer + /// \param layer session layer pointer + /// \return MString string form of variant fallbacks JSON data + MString getVariantFallbacksFromLayer(const SdfLayerRefPtr& layer) const; + + /// \brief Set global variant fallbacks if found from attribute ".variantFallbacks" + /// \param defaultVariantFallbacks default global variant fallbacks before updating + /// \param dataBlock attribute data block + /// \return PcpVariantFallbackMap variant fallbacks that applied to global variant fallbacks, + /// would be empty if nothing applied + PcpVariantFallbackMap updateVariantFallbacks( + PcpVariantFallbackMap& defaultVariantFallbacks, + MDataBlock& dataBlock) const; + + /// \brief Save variant fallbacks from session layer customLayerData to attribute + /// \param fallbacksStr string format of variant fallbacks to save to the node attribute + /// \param dataBlock attribute data block + void saveVariantFallbacks(const MString& fallbacksStr, MDataBlock& dataBlock) const; + + bool isStageValid() const; + bool initPrim(const uint32_t index, MDGContext& ctx); + + void layerIdChanged( + SdfNotice::LayerIdentifierDidChange const& notice, + UsdStageWeakPtr const& sender); + void onObjectsChanged(UsdNotice::ObjectsChanged const&, UsdStageWeakPtr const& sender); + void variantSelectionListener(SdfNotice::LayersDidChange const& notice); + void onEditTargetChanged( + UsdNotice::StageEditTargetChanged const& notice, + UsdStageWeakPtr const& sender); + void trackEditTargetLayer(LayerManager* layerManager = nullptr); + void trackAllDirtyLayers(LayerManager* layerManager = nullptr); + void validateTransforms(); + void onTransactionNotice( + AL::usd::transaction::CloseNotice const& notice, + const UsdStageWeakPtr& stage); + void onRedraw() { m_requestedRedraw = false; } + + /// get the stored Translator ID for a Path + std::string getTranslatorIdForPath(const SdfPath& path) override { - auto translator = m_translatorManufacture.getTranslatorFromId(translatorId); - if(translator) - { - supportsUpdate = translator->supportsUpdate(); - requiresParent = translator->needsTransformParent(); - importableByDefault = translator->importableByDefault(); - } - return translator != 0; + return m_context->getTranslatorIdForPath(path); } - /// generate the Translator ID for a Path - this is used for testing only - std::string generateTranslatorId(UsdPrim prim) override - { return m_translatorManufacture.generateTranslatorId(prim); } + bool getTranslatorInfo( + const std::string& translatorId, + bool& supportsUpdate, + bool& requiresParent, + bool& importableByDefault) override + { + auto translator = m_translatorManufacture.getTranslatorFromId(translatorId); + if (translator) { + supportsUpdate = translator->supportsUpdate(); + requiresParent = translator->needsTransformParent(); + importableByDefault = translator->importableByDefault(); + } + return translator != 0; + } + + /// generate the Translator ID for a Path - this is used for testing only + std::string generateTranslatorId(UsdPrim prim) override + { + return m_translatorManufacture.generateTranslatorId(prim); + } public: - bool isLockPrimFeatureActive() const - { - bool ignoreLockPrims = MGlobal::optionVarIntValue("AL_usdmaya_ignoreLockPrims"); - //The lock Prim functionality is a UI thing - no need to have it on in batch mode - //However, this also causes the tests to fail which is bad - return (/*(MGlobal::mayaState() == MGlobal::kInteractive) &&*/ !ignoreLockPrims); - } - - void processChangedMetaData(const SdfPathVector& resyncedPaths, const SdfPathVector& changedOnlyPaths); - void removeMetaData(const SdfPathVector& removedPaths); - - bool isPrimDirty(const UsdPrim& prim) override - { - const SdfPath path(prim.GetPath()); - auto previous(m_context->getUniqueKeyForPath(path)); - if (!previous) + bool isLockPrimFeatureActive() const { - return true; + bool ignoreLockPrims = MGlobal::optionVarIntValue("AL_usdmaya_ignoreLockPrims"); + // The lock Prim functionality is a UI thing - no need to have it on in batch mode + // However, this also causes the tests to fail which is bad + return (/*(MGlobal::mayaState() == MGlobal::kInteractive) &&*/ !ignoreLockPrims); + } + + void processChangedMetaData( + const SdfPathVector& resyncedPaths, + const SdfPathVector& changedOnlyPaths); + void removeMetaData(const SdfPathVector& removedPaths); + + bool isPrimDirty(const UsdPrim& prim) override + { + const SdfPath path(prim.GetPath()); + auto previous(m_context->getUniqueKeyForPath(path)); + if (!previous) { + return true; + } + std::string translatorId = m_translatorManufacture.generateTranslatorId(prim); + auto translator = m_translatorManufacture.getTranslatorFromId(translatorId); + auto current(translator->generateUniqueKey(prim)); + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "ProxyShape:isPrimDirty prim='%s' uniqueKey='%lu', previous='%lu'\n", + path.GetText(), + current, + previous); + return !current || current != previous; } - std::string translatorId = m_translatorManufacture.generateTranslatorId(prim); - auto translator = m_translatorManufacture.getTranslatorFromId(translatorId); - auto current(translator->generateUniqueKey(prim)); - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg( - "ProxyShape:isPrimDirty prim='%s' uniqueKey='%lu', previous='%lu'\n", - path.GetText(), current, previous); - return !current || current != previous; - } private: - SdfPathVector m_pathsOrdered; - AL_USDMAYA_PUBLIC - static std::vector m_unloadedProxyShapes; - - AL::usdmaya::SelectabilityDB m_selectabilityDB; - SelectionList m_selectionList; - SdfPathHashSet m_selectedPaths; - PrimPathToDagPath m_primPathToDagPath; - std::vector m_paths; - std::vector m_prims; - TfNotice::Key m_objectsChangedNoticeKey; - TfNotice::Key m_variantChangedNoticeKey; - TfNotice::Key m_editTargetChanged; - TfNotice::Key m_transactionNoticeKey; - - MCallbackId m_onSelectionChanged = 0; - SdfPathVector m_excludedGeometry; - SdfPathVector m_excludedTaggedGeometry; - proxy::LockManager m_lockManager; - static MObject m_transformTranslate; - static MObject m_transformRotate; - static MObject m_transformScale; - static MObject m_visibleInReflections; - static MObject m_visibleInRefractions; - UsdStageRefPtr m_stage; - SdfPath m_path; - fileio::translators::TranslatorContextPtr m_context; - fileio::translators::TranslatorManufacture m_translatorManufacture; - SdfPath m_changedPath; - SdfPathVector m_variantSwitchedPrims; - SdfLayerHandle m_prevEditTarget; - Engine* m_engine = 0; - - uint32_t m_engineRefCount = 0; - bool m_compositionHasChanged = false; - bool m_pleaseIgnoreSelection = false; - bool m_hasChangedSelection = false; - bool m_filePathDirty = false; - bool m_requestedRedraw = false; + SdfPathVector m_pathsOrdered; + AL_USDMAYA_PUBLIC + static std::vector m_unloadedProxyShapes; + + AL::usdmaya::SelectabilityDB m_selectabilityDB; + SelectionList m_selectionList; + SdfPathHashSet m_selectedPaths; + PrimPathToDagPath m_primPathToDagPath; + std::vector m_paths; + std::vector m_prims; + TfNotice::Key m_objectsChangedNoticeKey; + TfNotice::Key m_variantChangedNoticeKey; + TfNotice::Key m_editTargetChanged; + TfNotice::Key m_transactionNoticeKey; + + MCallbackId m_onSelectionChanged = 0; + SdfPathVector m_excludedGeometry; + SdfPathVector m_excludedTaggedGeometry; + proxy::LockManager m_lockManager; + static MObject m_transformTranslate; + static MObject m_transformRotate; + static MObject m_transformScale; + static MObject m_visibleInReflections; + static MObject m_visibleInRefractions; + UsdStageRefPtr m_stage; + SdfPath m_path; + fileio::translators::TranslatorContextPtr m_context; + fileio::translators::TranslatorManufacture m_translatorManufacture; + SdfPath m_changedPath; + SdfPathVector m_variantSwitchedPrims; + SdfLayerHandle m_prevEditTarget; + Engine* m_engine = 0; + + uint32_t m_engineRefCount = 0; + bool m_compositionHasChanged = false; + bool m_pleaseIgnoreSelection = false; + bool m_hasChangedSelection = false; + bool m_filePathDirty = false; + bool m_requestedRedraw = false; }; //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeSelection.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeSelection.cpp index 1207c0361c..da3bcecae2 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeSelection.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeSelection.cpp @@ -13,1420 +13,1446 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include - #include "AL/maya/utils/Utils.h" - #include "AL/usdmaya/Metadata.h" #include "AL/usdmaya/nodes/ProxyShape.h" -#include "AL/usdmaya/nodes/Transform.h" #include "AL/usdmaya/nodes/Scope.h" +#include "AL/usdmaya/nodes/Transform.h" #include "AL/usdmaya/nodes/TransformationMatrix.h" #include #include +#include + namespace AL { namespace usdmaya { namespace nodes { namespace { -typedef void (*proxy_function_prototype)(void* userData, AL::usdmaya::nodes::ProxyShape* proxyInstance); +typedef void ( + *proxy_function_prototype)(void* userData, AL::usdmaya::nodes::ProxyShape* proxyInstance); inline void addObjToSelectionList(MSelectionList& list, const MObject& object) { - if(object.hasFn(MFn::kDagNode)) - { - MFnDagNode dgNode(object); - MDagPath dg; dgNode.getPath(dg); - list.add(dg, MObject::kNullObj, true); - } - else - { - list.add(object, true); - } + if (object.hasFn(MFn::kDagNode)) { + MFnDagNode dgNode(object); + MDagPath dg; + dgNode.getPath(dg); + list.add(dg, MObject::kNullObj, true); + } else { + list.add(object, true); + } }; -} +} // namespace //---------------------------------------------------------------------------------------------------------------------- -/// I have to handle the case where maya commands are issued (e.g. select -cl) that will remove our transform nodes -/// from mayas global selection list (but will have left those nodes behind, and left them in the transform refs -/// within the proxy shape). -/// In those cases, it should just be a case of traversing the selected paths on the proxy shape, determine which -/// paths are no longer in the maya selection list, and then issue a command to AL_usdmaya_ProxyShapeSelect to deselct -/// those nodes. This will ensure that the nodes are nicely removed, and insert an item into the undo stack. +/// I have to handle the case where maya commands are issued (e.g. select -cl) that will remove our +/// transform nodes from mayas global selection list (but will have left those nodes behind, and +/// left them in the transform refs within the proxy shape). In those cases, it should just be a +/// case of traversing the selected paths on the proxy shape, determine which paths are no longer in +/// the maya selection list, and then issue a command to AL_usdmaya_ProxyShapeSelect to deselct +/// those nodes. This will ensure that the nodes are nicely removed, and insert an item into the +/// undo stack. //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::onSelectionChanged(void* ptr) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::onSelectionChanged %d\n", MGlobal::isUndoing()); - - const int selectionMode = MGlobal::optionVarIntValue("AL_usdmaya_selectMode"); - if(selectionMode) - { - ProxyShape* proxy = (ProxyShape*)ptr; - if(!proxy) - return; - - if(proxy->m_pleaseIgnoreSelection) - return; - - if(proxy->selectedPaths().empty()) - return; - - auto stage = proxy->getUsdStage(); - - MSelectionList sl; - MGlobal::getActiveSelectionList(sl); - - std::vector unselectedSet; - MFnDagNode fnDag; + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg("ProxyShapeSelection::onSelectionChanged %d\n", MGlobal::isUndoing()); + + const int selectionMode = MGlobal::optionVarIntValue("AL_usdmaya_selectMode"); + if (selectionMode) { + ProxyShape* proxy = (ProxyShape*)ptr; + if (!proxy) + return; + + if (proxy->m_pleaseIgnoreSelection) + return; + + if (proxy->selectedPaths().empty()) + return; + + auto stage = proxy->getUsdStage(); + + MSelectionList sl; + MGlobal::getActiveSelectionList(sl); + + std::vector unselectedSet; + MFnDagNode fnDag; + + // now attempt to find any items that have been selected via maya (e.g. by clicking on the + // parent node in the outliner) + bool hasNewItems = false; + MString precommand = "AL_usdmaya_ProxyShapeSelect -i -a"; + for (uint32_t i = 0; i < sl.length(); ++i) { + MObject obj; + sl.getDependNode(i, obj); + SdfPath path; + if (!proxy->isSelectedMObject(obj, path)) { + if (path.IsAbsolutePath()) { + precommand += " -pp \""; + precommand += path.GetText(); + precommand += "\""; + hasNewItems = true; + } + } + } - // now attempt to find any items that have been selected via maya (e.g. by clicking on the parent node in the outliner) - bool hasNewItems = false; - MString precommand = "AL_usdmaya_ProxyShapeSelect -i -a"; - for(uint32_t i = 0; i < sl.length(); ++i) - { - MObject obj; - sl.getDependNode(i, obj); - SdfPath path; - if(!proxy->isSelectedMObject(obj, path)) - { - if(path.IsAbsolutePath()) + struct compare_length { - precommand += " -pp \""; - precommand += path.GetText(); - precommand += "\""; - hasNewItems = true; + bool operator()(const SdfPath& a, const SdfPath& b) const + { + return a.GetString().size() > b.GetString().size(); + } + }; + std::sort(unselectedSet.begin(), unselectedSet.end(), compare_length()); + + // construct command to unselect the nodes (specifying the internal flag to ensure the + // selection list is not modified) + MString command = "AL_usdmaya_ProxyShapeSelect -i -d"; + for (auto removed : unselectedSet) { + command += " -pp \""; + command += removed.GetText(); + command += "\""; } - } - } - - struct compare_length { - bool operator() (const SdfPath& a, const SdfPath& b) const { - return a.GetString().size() > b.GetString().size(); - } - }; - std::sort(unselectedSet.begin(), unselectedSet.end(), compare_length()); - - // construct command to unselect the nodes (specifying the internal flag to ensure the selection list is not modified) - MString command = "AL_usdmaya_ProxyShapeSelect -i -d"; - for(auto removed : unselectedSet) - { - command += " -pp \""; - command += removed.GetText(); - command += "\""; - } - - fnDag.setObject(proxy->thisMObject()); - - command += " \""; - command += fnDag.fullPathName(); - command += "\""; - - if(hasNewItems) - { - precommand += " \""; - precommand += fnDag.fullPathName(); - precommand += "\";"; - if(!unselectedSet.empty()) - { - command = precommand + command; - } - else - { - command = precommand; - } - } - - if(unselectedSet.empty() && !hasNewItems) - { - proxy->m_pleaseIgnoreSelection = true; - MGlobal::executeCommand(command, false, true); - } - } - else - { - ProxyShape* proxy = (ProxyShape*)ptr; - if(!proxy) - return; - - if(proxy->m_pleaseIgnoreSelection) - return; - - if(proxy->m_hasChangedSelection) - return; - if(proxy->selectedPaths().empty()) - return; + fnDag.setObject(proxy->thisMObject()); - MSelectionList sl; - MGlobal::getActiveSelectionList(sl, false); + command += " \""; + command += fnDag.fullPathName(); + command += "\""; - bool hasItems = false; - bool hasNewItems = false; - MString precommand = "AL_usdmaya_ProxyShapeSelect -i -a"; - MString command = "AL_usdmaya_ProxyShapeSelect -i -d"; + if (hasNewItems) { + precommand += " \""; + precommand += fnDag.fullPathName(); + precommand += "\";"; + if (!unselectedSet.empty()) { + command = precommand + command; + } else { + command = precommand; + } + } - // maya bug work around. - auto hasObject = [] (MSelectionList sl, MObject node) - { - for(uint32_t i = 0; i < sl.length(); ++i) - { - MObject obj; - sl.getDependNode(i, obj); - if(node == obj) - return true; - } - return false; - }; + if (unselectedSet.empty() && !hasNewItems) { + proxy->m_pleaseIgnoreSelection = true; + MGlobal::executeCommand(command, false, true); + } + } else { + ProxyShape* proxy = (ProxyShape*)ptr; + if (!proxy) + return; + + if (proxy->m_pleaseIgnoreSelection) + return; + + if (proxy->m_hasChangedSelection) + return; + + if (proxy->selectedPaths().empty()) + return; + + MSelectionList sl; + MGlobal::getActiveSelectionList(sl, false); + + bool hasItems = false; + bool hasNewItems = false; + MString precommand = "AL_usdmaya_ProxyShapeSelect -i -a"; + MString command = "AL_usdmaya_ProxyShapeSelect -i -d"; + + // maya bug work around. + auto hasObject = [](MSelectionList sl, MObject node) { + for (uint32_t i = 0; i < sl.length(); ++i) { + MObject obj; + sl.getDependNode(i, obj); + if (node == obj) + return true; + } + return false; + }; - for(auto selected : proxy->selectedPaths()) - { - MObject obj = proxy->findRequiredPath(selected); - if(!hasObject(sl, obj)) - { - hasItems = true; - command += " -pp \""; - command += selected.GetText(); - command += "\""; - } - } + for (auto selected : proxy->selectedPaths()) { + MObject obj = proxy->findRequiredPath(selected); + if (!hasObject(sl, obj)) { + hasItems = true; + command += " -pp \""; + command += selected.GetText(); + command += "\""; + } + } - // now attempt to find any items that have been selected via maya (e.g. by clicking on the parent node in the outliner) - for(uint32_t i = 0; i < sl.length(); ++i) - { - MObject obj; - sl.getDependNode(i, obj); - SdfPath path; - if(!proxy->isSelectedMObject(obj, path)) - { - if(path.IsAbsolutePath()) - { - precommand += " -pp \""; - precommand += path.GetText(); - precommand += "\""; - hasNewItems = true; + // now attempt to find any items that have been selected via maya (e.g. by clicking on the + // parent node in the outliner) + for (uint32_t i = 0; i < sl.length(); ++i) { + MObject obj; + sl.getDependNode(i, obj); + SdfPath path; + if (!proxy->isSelectedMObject(obj, path)) { + if (path.IsAbsolutePath()) { + precommand += " -pp \""; + precommand += path.GetText(); + precommand += "\""; + hasNewItems = true; + } + } } - } - } - if(hasItems) - { - MFnDagNode fnDag(proxy->thisMObject()); - command += " \""; - command += fnDag.fullPathName(); - command += "\""; - if(hasNewItems) - { - precommand += " \""; - precommand += fnDag.fullPathName(); - precommand += "\";"; - command = precommand + command; - } - proxy->m_pleaseIgnoreSelection = true; - MGlobal::executeCommand(command, false, true); - proxy->m_pleaseIgnoreSelection = false; - } - else - if(hasNewItems) - { - MFnDagNode fnDag(proxy->thisMObject()); - precommand += " \""; - precommand += fnDag.fullPathName(); - precommand += "\";"; - proxy->m_pleaseIgnoreSelection = true; - MGlobal::executeCommand(precommand, false, true); - proxy->m_pleaseIgnoreSelection = false; + if (hasItems) { + MFnDagNode fnDag(proxy->thisMObject()); + command += " \""; + command += fnDag.fullPathName(); + command += "\""; + if (hasNewItems) { + precommand += " \""; + precommand += fnDag.fullPathName(); + precommand += "\";"; + command = precommand + command; + } + proxy->m_pleaseIgnoreSelection = true; + MGlobal::executeCommand(command, false, true); + proxy->m_pleaseIgnoreSelection = false; + } else if (hasNewItems) { + MFnDagNode fnDag(proxy->thisMObject()); + precommand += " \""; + precommand += fnDag.fullPathName(); + precommand += "\";"; + proxy->m_pleaseIgnoreSelection = true; + MGlobal::executeCommand(precommand, false, true); + proxy->m_pleaseIgnoreSelection = false; + } } - } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::printRefCounts() const { - for(auto it = m_requiredPaths.begin(); it != m_requiredPaths.end(); ++it) - { - std::cout << it->first.GetText() << " (" << MFnDagNode(it->second.node()).typeName() << ") :- "; - it->second.printRefCounts(); - } + for (auto it = m_requiredPaths.begin(); it != m_requiredPaths.end(); ++it) { + std::cout << it->first.GetText() << " (" << MFnDagNode(it->second.node()).typeName() + << ") :- "; + it->second.printRefCounts(); + } } //---------------------------------------------------------------------------------------------------------------------- inline bool ProxyShape::TransformReference::decRef(const TransformReason reason) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::TransformReference::decRef %" PRIu16 " %" PRIu16 " %" PRIu16 "\n", m_selected, m_refCount, m_required); - switch(reason) - { - case kSelection: assert(m_selected); --m_selected; break; - case kRequested: assert(m_refCount); --m_refCount; break; - case kRequired: assert(m_required); --m_required; break; - default: - assert(0); - break; - } - - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::TransformReference::decRefEnd %" PRIu16 " %" PRIu16 " %" PRIu16 "\n", m_selected, m_refCount, m_required); - return !m_required && !m_selected && !m_refCount; + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::TransformReference::decRef %" PRIu16 " %" PRIu16 " %" PRIu16 "\n", + m_selected, + m_refCount, + m_required); + switch (reason) { + case kSelection: + assert(m_selected); + --m_selected; + break; + case kRequested: + assert(m_refCount); + --m_refCount; + break; + case kRequired: + assert(m_required); + --m_required; + break; + default: assert(0); break; + } + + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::TransformReference::decRefEnd %" PRIu16 " %" PRIu16 " %" PRIu16 + "\n", + m_selected, + m_refCount, + m_required); + return !m_required && !m_selected && !m_refCount; } //---------------------------------------------------------------------------------------------------------------------- inline void ProxyShape::TransformReference::incRef(const TransformReason reason) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::TransformReference::incRef %" PRIu16 " %" PRIu16 " %" PRIu16 "\n", m_selected, m_refCount, m_required); - switch(reason) - { - case kSelection: ++m_selected; break; - case kRequested: ++m_refCount; break; - case kRequired: ++m_required; break; - default: assert(0); break; - } - - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::TransformReference::incRefEnd %" PRIu16 " %" PRIu16 " %" PRIu16 "\n", m_selected, m_refCount, m_required); + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::TransformReference::incRef %" PRIu16 " %" PRIu16 " %" PRIu16 "\n", + m_selected, + m_refCount, + m_required); + switch (reason) { + case kSelection: ++m_selected; break; + case kRequested: ++m_refCount; break; + case kRequired: ++m_required; break; + default: assert(0); break; + } + + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::TransformReference::incRefEnd %" PRIu16 " %" PRIu16 " %" PRIu16 + "\n", + m_selected, + m_refCount, + m_required); } //---------------------------------------------------------------------------------------------------------------------- inline void ProxyShape::TransformReference::checkIncRef(const TransformReason reason) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::TransformReference::checkIncRef %" PRIu16 " %" PRIu16 " %" PRIu16 "\n", m_selected, m_refCount, m_required); - switch(reason) - { - case kSelection: ++m_selectedTemp; break; - default: break; - } + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::TransformReference::checkIncRef %" PRIu16 " %" PRIu16 " %" PRIu16 + "\n", + m_selected, + m_refCount, + m_required); + switch (reason) { + case kSelection: ++m_selectedTemp; break; + default: break; + } } //---------------------------------------------------------------------------------------------------------------------- inline bool ProxyShape::TransformReference::checkRef(const TransformReason reason) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::TransformReference::checkRef %" PRIu16 " : %" PRIu16 " %" PRIu16 " %" PRIu16 "\n", m_selectedTemp, m_selected, m_refCount, m_required); - uint32_t sl = m_selected; - uint32_t rc = m_refCount; - uint32_t rq = m_required; - - switch(reason) - { - case kSelection: assert(m_selected); --sl; --m_selectedTemp; break; - case kRequested: assert(m_refCount); --rc; break; - case kRequired: assert(m_required); --rq; break; - default: assert(0); break; - } - return !rq && !m_selectedTemp && !rc; + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::TransformReference::checkRef %" PRIu16 " : %" PRIu16 " %" PRIu16 + " %" PRIu16 "\n", + m_selectedTemp, + m_selected, + m_refCount, + m_required); + uint32_t sl = m_selected; + uint32_t rc = m_refCount; + uint32_t rq = m_required; + + switch (reason) { + case kSelection: + assert(m_selected); + --sl; + --m_selectedTemp; + break; + case kRequested: + assert(m_refCount); + --rc; + break; + case kRequired: + assert(m_required); + --rq; + break; + default: assert(0); break; + } + return !rq && !m_selectedTemp && !rc; } //---------------------------------------------------------------------------------------------------------------------- -inline ProxyShape::TransformReference::TransformReference(const MObject& node, const TransformReason reason) - : m_node(node) - , m_transform(nullptr) +inline ProxyShape::TransformReference::TransformReference( + const MObject& node, + const TransformReason reason) + : m_node(node) + , m_transform(nullptr) { - m_required = 0; - m_selected = 0; - m_selectedTemp = 0; - m_refCount = 0; - m_transform = getTransformNode(); + m_required = 0; + m_selected = 0; + m_selectedTemp = 0; + m_refCount = 0; + m_transform = getTransformNode(); } //---------------------------------------------------------------------------------------------------------------------- -void ProxyShape::makeTransformReference(const SdfPath& path, const MObject& node, TransformReason reason) +void ProxyShape::makeTransformReference( + const SdfPath& path, + const MObject& node, + TransformReason reason) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::makeTransformReference %s\n", path.GetText()); - - SdfPath tempPath = path; - MDagPath dagPath; - MStatus status; - MObjectHandle handle(node); - if(handle.isAlive() && handle.isValid()) - { - MFnDagNode fn(node, &status); - status = fn.getPath(dagPath); - while(tempPath != SdfPath("/")) - { - MObject tempNode = dagPath.node(&status); - auto existing = m_requiredPaths.find(tempPath); - if(existing != m_requiredPaths.end()) - { - existing->second.incRef(reason); - } - else - { - TransformReference ref(tempNode, reason); - ref.incRef(reason); - m_requiredPaths.emplace(tempPath, ref); - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::makeTransformReference m_requiredPaths added TransformReference: %s\n", tempPath.GetText()); - } - status = dagPath.pop(); - tempPath = tempPath.GetParentPath(); - } - } - else - { - while(tempPath != SdfPath("/")) - { - auto existing = m_requiredPaths.find(tempPath); - if(existing != m_requiredPaths.end()) - { - existing->second.incRef(reason); - } - else - { - MGlobal::displayError("invalid MObject encountered when making transform reference"); - } - tempPath = tempPath.GetParentPath(); + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg("ProxyShapeSelection::makeTransformReference %s\n", path.GetText()); + + SdfPath tempPath = path; + MDagPath dagPath; + MStatus status; + MObjectHandle handle(node); + if (handle.isAlive() && handle.isValid()) { + MFnDagNode fn(node, &status); + status = fn.getPath(dagPath); + while (tempPath != SdfPath("/")) { + MObject tempNode = dagPath.node(&status); + auto existing = m_requiredPaths.find(tempPath); + if (existing != m_requiredPaths.end()) { + existing->second.incRef(reason); + } else { + TransformReference ref(tempNode, reason); + ref.incRef(reason); + m_requiredPaths.emplace(tempPath, ref); + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::makeTransformReference m_requiredPaths added " + "TransformReference: %s\n", + tempPath.GetText()); + } + status = dagPath.pop(); + tempPath = tempPath.GetParentPath(); + } + } else { + while (tempPath != SdfPath("/")) { + auto existing = m_requiredPaths.find(tempPath); + if (existing != m_requiredPaths.end()) { + existing->second.incRef(reason); + } else { + MGlobal::displayError( + "invalid MObject encountered when making transform reference"); + } + tempPath = tempPath.GetParentPath(); + } } - } } //---------------------------------------------------------------------------------------------------------------------- inline void ProxyShape::prepSelect() { - for(auto& iter : m_requiredPaths) - { - iter.second.prepSelect(); - } + for (auto& iter : m_requiredPaths) { + iter.second.prepSelect(); + } } //---------------------------------------------------------------------------------------------------------------------- MObject ProxyShape::makeUsdTransformChain_internal( - const UsdPrim& usdPrim, - MDagModifier& modifier, + const UsdPrim& usdPrim, + MDagModifier& modifier, TransformReason reason, - MDGModifier* modifier2, - uint32_t* createCount, - MString* resultingPath, - bool pushToPrim, - bool readAnimatedValues) + MDGModifier* modifier2, + uint32_t* createCount, + MString* resultingPath, + bool pushToPrim, + bool readAnimatedValues) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::makeUsdTransformChain_internal\n"); - - const MPlug outTimeAttr = outTimePlug(); - const MPlug outStageAttr = outStageDataPlug(); - - // makes the assumption that instancing isn't supported. - MFnDagNode fn(thisMObject()); - const MObject parent = fn.parent(0); - auto ret = makeUsdTransformChain(usdPrim, outStageAttr, outTimeAttr, parent, modifier, reason, modifier2, createCount, resultingPath, pushToPrim, readAnimatedValues); - return ret; + TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::makeUsdTransformChain_internal\n"); + + const MPlug outTimeAttr = outTimePlug(); + const MPlug outStageAttr = outStageDataPlug(); + + // makes the assumption that instancing isn't supported. + MFnDagNode fn(thisMObject()); + const MObject parent = fn.parent(0); + auto ret = makeUsdTransformChain( + usdPrim, + outStageAttr, + outTimeAttr, + parent, + modifier, + reason, + modifier2, + createCount, + resultingPath, + pushToPrim, + readAnimatedValues); + return ret; } //---------------------------------------------------------------------------------------------------------------------- MObject ProxyShape::makeUsdTransformChain( - const UsdPrim& usdPrim, - MDagModifier& modifier, + const UsdPrim& usdPrim, + MDagModifier& modifier, TransformReason reason, - MDGModifier* modifier2, - uint32_t* createCount, - bool pushToPrim, - bool readAnimatedValues) + MDGModifier* modifier2, + uint32_t* createCount, + bool pushToPrim, + bool readAnimatedValues) { - if(!usdPrim) - { - return MObject::kNullObj; - } - - // special case for selection. Do not allow duplicate paths to be selected. - if(reason == kSelection) - { - auto insertResult = m_selectedPaths.insert(usdPrim.GetPath()); - if(!insertResult.second) - { - TransformReferenceMap::iterator previous = m_requiredPaths.find(usdPrim.GetPath()); - return previous->second.node(); + if (!usdPrim) { + return MObject::kNullObj; } - } - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg("ProxyShape::makeUsdTransformChain on %s\n", usdPrim.GetPath().GetText()); - MObject newNode = makeUsdTransformChain_internal(usdPrim, modifier, reason, modifier2, createCount, 0, pushToPrim, readAnimatedValues); - insertTransformRefs( { std::pair(usdPrim.GetPath(), newNode) }, reason); - return newNode; + // special case for selection. Do not allow duplicate paths to be selected. + if (reason == kSelection) { + auto insertResult = m_selectedPaths.insert(usdPrim.GetPath()); + if (!insertResult.second) { + TransformReferenceMap::iterator previous = m_requiredPaths.find(usdPrim.GetPath()); + return previous->second.node(); + } + } + + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg("ProxyShape::makeUsdTransformChain on %s\n", usdPrim.GetPath().GetText()); + MObject newNode = makeUsdTransformChain_internal( + usdPrim, modifier, reason, modifier2, createCount, 0, pushToPrim, readAnimatedValues); + insertTransformRefs({ std::pair(usdPrim.GetPath(), newNode) }, reason); + return newNode; } static void createMayaNode( const UsdPrim& usdPrim, - MObject& node, + MObject& node, const MObject& parentNode, - MDagModifier& modifier, - MDGModifier* modifier2, - const MPlug& outStage, - const MPlug& outTime, - bool pushToPrim, - bool readAnimatedValues) + MDagModifier& modifier, + MDGModifier* modifier2, + const MPlug& outStage, + const MPlug& outTime, + bool pushToPrim, + bool readAnimatedValues) { - MFnDagNode fn; - - bool isUsdXFormable = usdPrim.IsA(); - - enum MayaNodeTypeCreated { customMayaTransforn, AL_USDMayaScope, AL_USDMayaTransform }; - - std::string transformType; - - MayaNodeTypeCreated createdNodeType = AL_USDMayaTransform; - - bool hasMetadata = usdPrim.GetMetadata(Metadata::transformType, &transformType); - if(hasMetadata && !transformType.empty()) - { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::createMayaNode: creating custom transform node\n"); - node = modifier.createNode(AL::maya::utils::convert(transformType), parentNode); - createdNodeType = customMayaTransforn; - } - else if (usdPrim.IsA()) - { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::createMayaNode: creating scope node\n"); - node = modifier.createNode(Scope::kTypeId, parentNode); - transformType = "AL_usdmaya_Scope"; - createdNodeType = AL_USDMayaScope; - } - else - { - //for any other USD type, we'll create an AL_USDMaya Transform node - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::createMayaNode: creating transform node\n"); - node = modifier.createNode(Transform::kTypeId, parentNode); - transformType = "AL_usdmaya_Transform"; - createdNodeType = AL_USDMayaTransform; - } - - if(fn.setObject(node)) - { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShape::createMayaNode created transformType=%s name=%s\n", - transformType.c_str(), - usdPrim.GetName().GetText()); - } - else - { - MString err; - err.format("USDMaya is unable to create the node with transformType=^1s, name=^2s.", - transformType.c_str(), - usdPrim.GetName().GetText()); - MGlobal::displayError(err); - } - - fn.setName(AL::maya::utils::convert(usdPrim.GetName().GetString())); - const SdfPath path{usdPrim.GetPath()}; - - if(createdNodeType==AL_USDMayaTransform) - { - Transform* ptrNode = (Transform*)fn.userNode(); - MPlug inStageData = ptrNode->inStageDataPlug(); - MPlug inTime = ptrNode->timePlug(); - - if(modifier2) - { - if(pushToPrim) modifier2->newPlugValueBool(ptrNode->pushToPrimPlug(), pushToPrim); - modifier2->newPlugValueBool(ptrNode->readAnimatedValuesPlug(), readAnimatedValues); - } - - if(!isUsdXFormable) - { - //It's not a USD Xform - so no point in allowing this stuff to be writeable - MPlug(node, MPxTransform::translate).setLocked(true); - MPlug(node, MPxTransform::rotate).setLocked(true); - MPlug(node, MPxTransform::scale).setLocked(true); - MPlug(node, MPxTransform::transMinusRotatePivot).setLocked(true); - MPlug(node, MPxTransform::rotateAxis).setLocked(true); - MPlug(node, MPxTransform::scalePivotTranslate).setLocked(true); - MPlug(node, MPxTransform::scalePivot).setLocked(true); - MPlug(node, MPxTransform::rotatePivotTranslate).setLocked(true); - MPlug(node, MPxTransform::rotatePivot).setLocked(true); - MPlug(node, MPxTransform::shearXY).setLocked(true); - MPlug(node, MPxTransform::shearXZ).setLocked(true); - MPlug(node, MPxTransform::shearYZ).setLocked(true); - } - else - { - // only connect time and stage if transform can change - modifier.connect(outTime, inTime); - modifier.connect(outStage, inStageData); - } - - // set the primitive path - - modifier.newPlugValueString(ptrNode->primPathPlug(), path.GetText()); - } - else if (createdNodeType==AL_USDMayaScope) - { - Scope* ptrNode = (Scope*)fn.userNode(); - - // only connect stage if transform can change - MPlug inStageData = ptrNode->inStageDataPlug(); - modifier.connect(outStage, inStageData); - modifier.newPlugValueString(ptrNode->primPathPlug(), path.GetText()); - } - -} + MFnDagNode fn; + bool isUsdXFormable = usdPrim.IsA(); + enum MayaNodeTypeCreated + { + customMayaTransforn, + AL_USDMayaScope, + AL_USDMayaTransform + }; -//---------------------------------------------------------------------------------------------------------------------- -MObject ProxyShape::makeUsdTransformChain( - UsdPrim usdPrim, - const MPlug& outStage, - const MPlug& outTime, - const MObject& parentXForm, - MDagModifier& modifier, - TransformReason reason, - MDGModifier* modifier2, - uint32_t* createCount, - MString* resultingPath, - bool pushToPrim, - bool readAnimatedValues) -{ - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::makeUsdTransformChain %s\n", usdPrim.GetPath().GetText()); - - const SdfPath path{usdPrim.GetPath()}; + std::string transformType; + + MayaNodeTypeCreated createdNodeType = AL_USDMayaTransform; + + bool hasMetadata = usdPrim.GetMetadata(Metadata::transformType, &transformType); + if (hasMetadata && !transformType.empty()) { + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg("ProxyShapeSelection::createMayaNode: creating custom transform node\n"); + node = modifier.createNode(AL::maya::utils::convert(transformType), parentNode); + createdNodeType = customMayaTransforn; + } else if (usdPrim.IsA()) { + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg("ProxyShapeSelection::createMayaNode: creating scope node\n"); + node = modifier.createNode(Scope::kTypeId, parentNode); + transformType = "AL_usdmaya_Scope"; + createdNodeType = AL_USDMayaScope; + } else { + // for any other USD type, we'll create an AL_USDMaya Transform node + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg("ProxyShapeSelection::createMayaNode: creating transform node\n"); + node = modifier.createNode(Transform::kTypeId, parentNode); + transformType = "AL_usdmaya_Transform"; + createdNodeType = AL_USDMayaTransform; + } - auto iter = m_requiredPaths.find(path); + if (fn.setObject(node)) { + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShape::createMayaNode created transformType=%s name=%s\n", + transformType.c_str(), + usdPrim.GetName().GetText()); + } else { + MString err; + err.format( + "USDMaya is unable to create the node with transformType=^1s, name=^2s.", + transformType.c_str(), + usdPrim.GetName().GetText()); + MGlobal::displayError(err); + } - // If this path has been found. - if(iter != m_requiredPaths.end()) - { - MObject nodeToReturn = iter->second.node(); - switch(reason) - { - case kSelection: - { - while(usdPrim && iter != m_requiredPaths.end()) - { - iter->second.checkIncRef(reason); + fn.setName(AL::maya::utils::convert(usdPrim.GetName().GetString())); + const SdfPath path { usdPrim.GetPath() }; - // grab the parent. - usdPrim = usdPrim.GetParent(); + if (createdNodeType == AL_USDMayaTransform) { + Transform* ptrNode = (Transform*)fn.userNode(); + MPlug inStageData = ptrNode->inStageDataPlug(); + MPlug inTime = ptrNode->timePlug(); - // if valid, grab reference to path - if(usdPrim) - { - iter = m_requiredPaths.find(usdPrim.GetPath()); - } - }; - } - break; + if (modifier2) { + if (pushToPrim) + modifier2->newPlugValueBool(ptrNode->pushToPrimPlug(), pushToPrim); + modifier2->newPlugValueBool(ptrNode->readAnimatedValuesPlug(), readAnimatedValues); + } - case kRequested: - { - while(usdPrim && iter != m_requiredPaths.end()) - { - // grab the parent. - usdPrim = usdPrim.GetParent(); - - // if valid, grab reference to path - if(usdPrim) - { - iter = m_requiredPaths.find(usdPrim.GetPath()); - } - }; - } - break; + if (!isUsdXFormable) { + // It's not a USD Xform - so no point in allowing this stuff to be writeable + MPlug(node, MPxTransform::translate).setLocked(true); + MPlug(node, MPxTransform::rotate).setLocked(true); + MPlug(node, MPxTransform::scale).setLocked(true); + MPlug(node, MPxTransform::transMinusRotatePivot).setLocked(true); + MPlug(node, MPxTransform::rotateAxis).setLocked(true); + MPlug(node, MPxTransform::scalePivotTranslate).setLocked(true); + MPlug(node, MPxTransform::scalePivot).setLocked(true); + MPlug(node, MPxTransform::rotatePivotTranslate).setLocked(true); + MPlug(node, MPxTransform::rotatePivot).setLocked(true); + MPlug(node, MPxTransform::shearXY).setLocked(true); + MPlug(node, MPxTransform::shearXZ).setLocked(true); + MPlug(node, MPxTransform::shearYZ).setLocked(true); + } else { + // only connect time and stage if transform can change + modifier.connect(outTime, inTime); + modifier.connect(outStage, inStageData); + } - case kRequired: - { - while(usdPrim && iter != m_requiredPaths.end() && !iter->second.required()) - { - iter->second.checkIncRef(reason); + // set the primitive path - // grab the parent. - usdPrim = usdPrim.GetParent(); + modifier.newPlugValueString(ptrNode->primPathPlug(), path.GetText()); + } else if (createdNodeType == AL_USDMayaScope) { + Scope* ptrNode = (Scope*)fn.userNode(); - // if valid, grab reference to path - if(usdPrim) - { - iter = m_requiredPaths.find(usdPrim.GetPath()); - } - }; - } - break; + // only connect stage if transform can change + MPlug inStageData = ptrNode->inStageDataPlug(); + modifier.connect(outStage, inStageData); + modifier.newPlugValueString(ptrNode->primPathPlug(), path.GetText()); } - if(resultingPath) - { - MFnDagNode fn(nodeToReturn); - MDagPath mpath; - fn.getPath(mpath); - *resultingPath = mpath.fullPathName(); - } - // return the lowest point on the found chain. - return nodeToReturn; - } - - MObject parentPath; - // descend into the parent first - if(path.GetPathElementCount() > 1) - { - // if there is a parent to this node, continue building the chain. - parentPath = makeUsdTransformChain(usdPrim.GetParent(), outStage, outTime, parentXForm, modifier, reason, modifier2, createCount, resultingPath, pushToPrim, readAnimatedValues); - } - - // if we've hit the top of the chain, make sure we get the correct parent - if(parentPath == MObject::kNullObj) - { - parentPath = parentXForm; - } - - if(createCount) (*createCount)++; - - MFnDagNode fn; - MObject parentNode = parentPath; - - MObject node; - - createMayaNode(usdPrim, node, parentNode, modifier, modifier2, outStage, outTime, pushToPrim, readAnimatedValues); - - // build up new lock-prim list - TfToken lockPropertyToken; - if (usdPrim.GetMetadata(Metadata::locked, & lockPropertyToken)) - { - if (lockPropertyToken == Metadata::lockTransform) - { - m_lockManager.setLocked(usdPrim.GetPath()); - } - else - if (lockPropertyToken == Metadata::lockUnlocked) - { - m_lockManager.setUnlocked(usdPrim.GetPath()); - } - else - if (lockPropertyToken == Metadata::lockInherited) - { - m_lockManager.setInherited(usdPrim.GetPath()); - } - } - else - { - m_lockManager.setInherited(usdPrim.GetPath()); - } +} +//---------------------------------------------------------------------------------------------------------------------- +MObject ProxyShape::makeUsdTransformChain( + UsdPrim usdPrim, + const MPlug& outStage, + const MPlug& outTime, + const MObject& parentXForm, + MDagModifier& modifier, + TransformReason reason, + MDGModifier* modifier2, + uint32_t* createCount, + MString* resultingPath, + bool pushToPrim, + bool readAnimatedValues) +{ + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg("ProxyShapeSelection::makeUsdTransformChain %s\n", usdPrim.GetPath().GetText()); + + const SdfPath path { usdPrim.GetPath() }; + + auto iter = m_requiredPaths.find(path); + + // If this path has been found. + if (iter != m_requiredPaths.end()) { + MObject nodeToReturn = iter->second.node(); + switch (reason) { + case kSelection: { + while (usdPrim && iter != m_requiredPaths.end()) { + iter->second.checkIncRef(reason); + + // grab the parent. + usdPrim = usdPrim.GetParent(); + + // if valid, grab reference to path + if (usdPrim) { + iter = m_requiredPaths.find(usdPrim.GetPath()); + } + }; + } break; + + case kRequested: { + while (usdPrim && iter != m_requiredPaths.end()) { + // grab the parent. + usdPrim = usdPrim.GetParent(); + + // if valid, grab reference to path + if (usdPrim) { + iter = m_requiredPaths.find(usdPrim.GetPath()); + } + }; + } break; + + case kRequired: { + while (usdPrim && iter != m_requiredPaths.end() && !iter->second.required()) { + iter->second.checkIncRef(reason); + + // grab the parent. + usdPrim = usdPrim.GetParent(); + + // if valid, grab reference to path + if (usdPrim) { + iter = m_requiredPaths.find(usdPrim.GetPath()); + } + }; + } break; + } + if (resultingPath) { + MFnDagNode fn(nodeToReturn); + MDagPath mpath; + fn.getPath(mpath); + *resultingPath = mpath.fullPathName(); + } + // return the lowest point on the found chain. + return nodeToReturn; + } - if(resultingPath) - *resultingPath = recordUsdPrimToMayaPath(usdPrim, node); - else - recordUsdPrimToMayaPath(usdPrim, node); + MObject parentPath; + // descend into the parent first + if (path.GetPathElementCount() > 1) { + // if there is a parent to this node, continue building the chain. + parentPath = makeUsdTransformChain( + usdPrim.GetParent(), + outStage, + outTime, + parentXForm, + modifier, + reason, + modifier2, + createCount, + resultingPath, + pushToPrim, + readAnimatedValues); + } + // if we've hit the top of the chain, make sure we get the correct parent + if (parentPath == MObject::kNullObj) { + parentPath = parentXForm; + } - TransformReference transformRef(node, reason); - transformRef.checkIncRef(reason); - m_requiredPaths.emplace(path, transformRef); + if (createCount) + (*createCount)++; + + MFnDagNode fn; + MObject parentNode = parentPath; + + MObject node; + + createMayaNode( + usdPrim, + node, + parentNode, + modifier, + modifier2, + outStage, + outTime, + pushToPrim, + readAnimatedValues); + + // build up new lock-prim list + TfToken lockPropertyToken; + if (usdPrim.GetMetadata(Metadata::locked, &lockPropertyToken)) { + if (lockPropertyToken == Metadata::lockTransform) { + m_lockManager.setLocked(usdPrim.GetPath()); + } else if (lockPropertyToken == Metadata::lockUnlocked) { + m_lockManager.setUnlocked(usdPrim.GetPath()); + } else if (lockPropertyToken == Metadata::lockInherited) { + m_lockManager.setInherited(usdPrim.GetPath()); + } + } else { + m_lockManager.setInherited(usdPrim.GetPath()); + } - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::makeUsdTransformChain m_requiredPaths added TransformReference: %s\n", path.GetText()); - return node; + if (resultingPath) + *resultingPath = recordUsdPrimToMayaPath(usdPrim, node); + else + recordUsdPrimToMayaPath(usdPrim, node); + + TransformReference transformRef(node, reason); + transformRef.checkIncRef(reason); + m_requiredPaths.emplace(path, transformRef); + + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::makeUsdTransformChain m_requiredPaths added TransformReference: " + "%s\n", + path.GetText()); + return node; } //---------------------------------------------------------------------------------------------------------------------- -MObject ProxyShape::makeUsdTransforms(const UsdPrim& usdPrim, MDagModifier& modifier, TransformReason reason, MDGModifier* modifier2) +MObject ProxyShape::makeUsdTransforms( + const UsdPrim& usdPrim, + MDagModifier& modifier, + TransformReason reason, + MDGModifier* modifier2) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::makeUsdTransforms\n"); + TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::makeUsdTransforms\n"); - // Ok, so let's go wondering up the transform chain making sure we have all of those transforms created. - MObject node = makeUsdTransformChain(usdPrim, modifier, reason, modifier2, 0); + // Ok, so let's go wondering up the transform chain making sure we have all of those transforms + // created. + MObject node = makeUsdTransformChain(usdPrim, modifier, reason, modifier2, 0); - // we only need child transforms if they have been requested - if(reason == kRequested) - { - makeUsdTransformsInternal(usdPrim, node, modifier, reason, modifier2); - } + // we only need child transforms if they have been requested + if (reason == kRequested) { + makeUsdTransformsInternal(usdPrim, node, modifier, reason, modifier2); + } - return node; + return node; } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::makeUsdTransformsInternal( - const UsdPrim& usdPrim, - const MObject& parentNode, - MDagModifier& modifier, + const UsdPrim& usdPrim, + const MObject& parentNode, + MDagModifier& modifier, TransformReason reason, - MDGModifier* modifier2, - bool pushToPrim, - bool readAnimatedValues) + MDGModifier* modifier2, + bool pushToPrim, + bool readAnimatedValues) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::makeUsdTransformsInternal\n"); - MFnDagNode fn; - - MPlug outStageAttr = outStageDataPlug(); - MPlug outTimeAttr = outTimePlug(); - - for(auto it = usdPrim.GetChildren().begin(), e = usdPrim.GetChildren().end(); it != e; ++it) - { - UsdPrim prim = *it; - /// must always exist, and never get deleted. - auto check = m_requiredPaths.find(prim.GetPath()); - if(check == m_requiredPaths.end()) - { - UsdPrim prim = *it; - - MObject node; - createMayaNode(prim, node, parentNode, modifier, modifier2, outStageAttr, outTimeAttr, pushToPrim, readAnimatedValues); - - TransformReference transformRef(node, reason); - transformRef.checkIncRef(reason); - const SdfPath path{usdPrim.GetPath()}; - m_requiredPaths.emplace(path, transformRef); - - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::makeUsdTransformsInternal m_requiredPaths added TransformReference: %s\n", path.GetText()); - - makeUsdTransformsInternal(prim, node, modifier, reason, modifier2, pushToPrim, readAnimatedValues); - } - else - { - makeUsdTransformsInternal(prim, check->second.node(), modifier, reason, modifier2, pushToPrim, readAnimatedValues); + TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::makeUsdTransformsInternal\n"); + MFnDagNode fn; + + MPlug outStageAttr = outStageDataPlug(); + MPlug outTimeAttr = outTimePlug(); + + for (auto it = usdPrim.GetChildren().begin(), e = usdPrim.GetChildren().end(); it != e; ++it) { + UsdPrim prim = *it; + /// must always exist, and never get deleted. + auto check = m_requiredPaths.find(prim.GetPath()); + if (check == m_requiredPaths.end()) { + UsdPrim prim = *it; + + MObject node; + createMayaNode( + prim, + node, + parentNode, + modifier, + modifier2, + outStageAttr, + outTimeAttr, + pushToPrim, + readAnimatedValues); + + TransformReference transformRef(node, reason); + transformRef.checkIncRef(reason); + const SdfPath path { usdPrim.GetPath() }; + m_requiredPaths.emplace(path, transformRef); + + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::makeUsdTransformsInternal m_requiredPaths added " + "TransformReference: %s\n", + path.GetText()); + + makeUsdTransformsInternal( + prim, node, modifier, reason, modifier2, pushToPrim, readAnimatedValues); + } else { + makeUsdTransformsInternal( + prim, + check->second.node(), + modifier, + reason, + modifier2, + pushToPrim, + readAnimatedValues); + } } - } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::removeUsdTransformChain_internal( - const UsdPrim& usdPrim, - MDagModifier& modifier, + const UsdPrim& usdPrim, + MDagModifier& modifier, TransformReason reason) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransformChain\n"); - UsdPrim parentPrim = usdPrim; - MObject parentTM = MObject::kNullObj; - MObject object = MObject::kNullObj; - while(parentPrim) - { - SdfPath primPath = parentPrim.GetPath(); - auto it = m_requiredPaths.find(primPath); - if(it == m_requiredPaths.end()) - { - return; - } + TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransformChain\n"); + UsdPrim parentPrim = usdPrim; + MObject parentTM = MObject::kNullObj; + MObject object = MObject::kNullObj; + while (parentPrim) { + SdfPath primPath = parentPrim.GetPath(); + auto it = m_requiredPaths.find(primPath); + if (it == m_requiredPaths.end()) { + return; + } - if(it->second.checkRef(reason)) - { - MObject object = it->second.node(); - if(object != MObject::kNullObj) - { - modifier.reparentNode(object); - modifier.deleteNode(object); - } - m_lockManager.setInherited(primPath); - } + if (it->second.checkRef(reason)) { + MObject object = it->second.node(); + if (object != MObject::kNullObj) { + modifier.reparentNode(object); + modifier.deleteNode(object); + } + m_lockManager.setInherited(primPath); + } - parentPrim = parentPrim.GetParent(); - } + parentPrim = parentPrim.GetParent(); + } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::removeUsdTransformChain( - const SdfPath& path, - MDagModifier& modifier, + const SdfPath& path, + MDagModifier& modifier, TransformReason reason) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransformChain\n"); - SdfPath parentPrim = path; - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShape::removeUsdTransformChain %s\n", path.GetText()); - MObject parentTM = MObject::kNullObj; - MObject object = MObject::kNullObj; - - // ensure the transforms have been removed from the selectability and lock db's. - m_lockManager.setInherited(path); - while(!parentPrim.IsEmpty()) - { - auto it = m_requiredPaths.find(parentPrim); - if(it == m_requiredPaths.end()) - { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShape -- %s path has not been found\n", path.GetText()); - } - else - if(it->second.decRef(reason)) - { - MObject object = it->second.node(); - if(object != MObject::kNullObj) - { - MObjectHandle h = object; - - // The Xform of the shape may have already been deleted when the shape was deleted - if(h.isAlive() && h.isValid()) - { - modifier.reparentNode(object); - modifier.deleteNode(object); - - m_lockManager.setInherited(parentPrim); + TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransformChain\n"); + SdfPath parentPrim = path; + TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShape::removeUsdTransformChain %s\n", path.GetText()); + MObject parentTM = MObject::kNullObj; + MObject object = MObject::kNullObj; + + // ensure the transforms have been removed from the selectability and lock db's. + m_lockManager.setInherited(path); + while (!parentPrim.IsEmpty()) { + auto it = m_requiredPaths.find(parentPrim); + if (it == m_requiredPaths.end()) { + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg("ProxyShape -- %s path has not been found\n", path.GetText()); + } else if (it->second.decRef(reason)) { + MObject object = it->second.node(); + if (object != MObject::kNullObj) { + MObjectHandle h = object; + + // The Xform of the shape may have already been deleted when the shape was deleted + if (h.isAlive() && h.isValid()) { + modifier.reparentNode(object); + modifier.deleteNode(object); + + m_lockManager.setInherited(parentPrim); + } + } + + m_requiredPaths.erase(it); + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::removeUsdTransformChain m_requiredPaths removed " + "TransformReference: %s\n", + it->first.GetText()); } - } - m_requiredPaths.erase(it); - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransformChain m_requiredPaths removed TransformReference: %s\n", it->first.GetText()); + parentPrim = parentPrim.GetParentPath(); } - - parentPrim = parentPrim.GetParentPath(); - } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::removeUsdTransformChain( - const UsdPrim& usdPrim, - MDagModifier& modifier, + const UsdPrim& usdPrim, + MDagModifier& modifier, TransformReason reason) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransformChain\n"); - if(!usdPrim) - { - return; - } - - if(reason == kSelection) - { - auto selectedPath = m_selectedPaths.find(usdPrim.GetPath()); - if(selectedPath != m_selectedPaths.end()) - { - m_selectedPaths.erase(selectedPath); - } - else - { - return; - } - } - - UsdPrim parentPrim = usdPrim; - MObject parentTM = MObject::kNullObj; - MObject object = MObject::kNullObj; - while(parentPrim) - { - auto it = m_requiredPaths.find(parentPrim.GetPath()); - if(it == m_requiredPaths.end()) - { - return; + TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransformChain\n"); + if (!usdPrim) { + return; } - if(it->second.decRef(reason)) - { - MObject object = it->second.node(); - if(object != MObject::kNullObj) - { - modifier.reparentNode(object); - modifier.deleteNode(object); - } - - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransformChain m_requiredPaths removed TransformReference: %s\n", it->first.GetText()); - m_requiredPaths.erase(it); + if (reason == kSelection) { + auto selectedPath = m_selectedPaths.find(usdPrim.GetPath()); + if (selectedPath != m_selectedPaths.end()) { + m_selectedPaths.erase(selectedPath); + } else { + return; + } } - parentPrim = parentPrim.GetParent(); - } + UsdPrim parentPrim = usdPrim; + MObject parentTM = MObject::kNullObj; + MObject object = MObject::kNullObj; + while (parentPrim) { + auto it = m_requiredPaths.find(parentPrim.GetPath()); + if (it == m_requiredPaths.end()) { + return; + } + + if (it->second.decRef(reason)) { + MObject object = it->second.node(); + if (object != MObject::kNullObj) { + modifier.reparentNode(object); + modifier.deleteNode(object); + } + + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::removeUsdTransformChain m_requiredPaths removed " + "TransformReference: %s\n", + it->first.GetText()); + m_requiredPaths.erase(it); + } + + parentPrim = parentPrim.GetParent(); + } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::removeUsdTransformsInternal( - const UsdPrim& usdPrim, - MDagModifier& modifier, + const UsdPrim& usdPrim, + MDagModifier& modifier, TransformReason reason) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransformsInternal %s\n", usdPrim.GetPath().GetText()); - // can we find the prim in the current set? - auto it = m_requiredPaths.find(usdPrim.GetPath()); - if(it == m_requiredPaths.end()) - { - return; - } - - // first go remove the children - for(auto iter = usdPrim.GetChildren().begin(), end = usdPrim.GetChildren().end(); iter != end; ++iter) - { - removeUsdTransformsInternal(*iter, modifier, ProxyShape::kRequested); - } - - if(it->second.decRef(reason)) - { - // work around for Maya's love of deleting the parent transforms of custom transform nodes :( - modifier.reparentNode(it->second.node()); - modifier.deleteNode(it->second.node()); - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransformsInternal m_requiredPaths removed TransformReference: %s\n", it->first.GetText()); - m_requiredPaths.erase(it); - } + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg("ProxyShapeSelection::removeUsdTransformsInternal %s\n", usdPrim.GetPath().GetText()); + // can we find the prim in the current set? + auto it = m_requiredPaths.find(usdPrim.GetPath()); + if (it == m_requiredPaths.end()) { + return; + } + + // first go remove the children + for (auto iter = usdPrim.GetChildren().begin(), end = usdPrim.GetChildren().end(); iter != end; + ++iter) { + removeUsdTransformsInternal(*iter, modifier, ProxyShape::kRequested); + } + + if (it->second.decRef(reason)) { + // work around for Maya's love of deleting the parent transforms of custom transform nodes + // :( + modifier.reparentNode(it->second.node()); + modifier.deleteNode(it->second.node()); + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::removeUsdTransformsInternal m_requiredPaths removed " + "TransformReference: %s\n", + it->first.GetText()); + m_requiredPaths.erase(it); + } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::removeUsdTransforms( - const UsdPrim& usdPrim, - MDagModifier& modifier, + const UsdPrim& usdPrim, + MDagModifier& modifier, TransformReason reason) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransforms\n"); - - // can we find the prim in the current set? - auto it = m_requiredPaths.find(usdPrim.GetPath()); - if(it == m_requiredPaths.end()) - { - return; - } - - // no need to iterate through children if we are requesting a shape - if(reason == kRequested) - { - // first go remove the children - for(auto it = usdPrim.GetChildren().begin(), end = usdPrim.GetChildren().end(); it != end; ++it) - { - removeUsdTransformsInternal(*it, modifier, ProxyShape::kRequested); + TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeUsdTransforms\n"); + + // can we find the prim in the current set? + auto it = m_requiredPaths.find(usdPrim.GetPath()); + if (it == m_requiredPaths.end()) { + return; } - } - // finally walk back up the chain and do magic. I'm not sure I want to do this? - removeUsdTransformChain(usdPrim, modifier, reason); + // no need to iterate through children if we are requesting a shape + if (reason == kRequested) { + // first go remove the children + for (auto it = usdPrim.GetChildren().begin(), end = usdPrim.GetChildren().end(); it != end; + ++it) { + removeUsdTransformsInternal(*it, modifier, ProxyShape::kRequested); + } + } + + // finally walk back up the chain and do magic. I'm not sure I want to do this? + removeUsdTransformChain(usdPrim, modifier, reason); } //---------------------------------------------------------------------------------------------------------------------- -void ProxyShape::insertTransformRefs(const std::vector>& removedRefs, TransformReason reason) +void ProxyShape::insertTransformRefs( + const std::vector>& removedRefs, + TransformReason reason) { - for(auto iter : removedRefs) - { - makeTransformReference(iter.first, iter.second, reason); - } + for (auto iter : removedRefs) { + makeTransformReference(iter.first, iter.second, reason); + } } //---------------------------------------------------------------------------------------------------------------------- -SelectionUndoHelper::SelectionUndoHelper(nodes::ProxyShape* proxy, const SdfPathHashSet& paths, MGlobal::ListAdjustment mode, bool internal) - : m_proxy(proxy), m_paths(paths), m_mode(mode), m_modifier1(), m_modifier2(), m_insertedRefs(), m_removedRefs(), m_internal(internal) +SelectionUndoHelper::SelectionUndoHelper( + nodes::ProxyShape* proxy, + const SdfPathHashSet& paths, + MGlobal::ListAdjustment mode, + bool internal) + : m_proxy(proxy) + , m_paths(paths) + , m_mode(mode) + , m_modifier1() + , m_modifier2() + , m_insertedRefs() + , m_removedRefs() + , m_internal(internal) { } //---------------------------------------------------------------------------------------------------------------------- void SelectionUndoHelper::doIt() { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::SelectionUndoHelper::doIt %lu %lu\n", m_insertedRefs.size(), m_removedRefs.size()); - m_proxy->m_pleaseIgnoreSelection = true; - m_modifier1.doIt(); - m_modifier2.doIt(); - m_proxy->insertTransformRefs(m_insertedRefs, nodes::ProxyShape::kSelection); - m_proxy->removeTransformRefs(m_removedRefs, nodes::ProxyShape::kSelection); - m_proxy->selectedPaths() = m_paths; - if(!m_internal) - { - MGlobal::setActiveSelectionList(m_newSelection, MGlobal::kReplaceList); - } - m_proxy->m_pleaseIgnoreSelection = false; - if(!MGlobal::optionVarIntValue("AL_usdmaya_ignoreLockPrims")) - { - m_proxy->constructLockPrims(); - } + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::SelectionUndoHelper::doIt %lu %lu\n", + m_insertedRefs.size(), + m_removedRefs.size()); + m_proxy->m_pleaseIgnoreSelection = true; + m_modifier1.doIt(); + m_modifier2.doIt(); + m_proxy->insertTransformRefs(m_insertedRefs, nodes::ProxyShape::kSelection); + m_proxy->removeTransformRefs(m_removedRefs, nodes::ProxyShape::kSelection); + m_proxy->selectedPaths() = m_paths; + if (!m_internal) { + MGlobal::setActiveSelectionList(m_newSelection, MGlobal::kReplaceList); + } + m_proxy->m_pleaseIgnoreSelection = false; + if (!MGlobal::optionVarIntValue("AL_usdmaya_ignoreLockPrims")) { + m_proxy->constructLockPrims(); + } } //---------------------------------------------------------------------------------------------------------------------- void SelectionUndoHelper::undoIt() { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::SelectionUndoHelper::undoIt %lu %lu\n", m_insertedRefs.size(), m_removedRefs.size()); - m_proxy->m_pleaseIgnoreSelection = true; - m_modifier2.undoIt(); - m_modifier1.undoIt(); - m_proxy->insertTransformRefs(m_removedRefs, nodes::ProxyShape::kSelection); - m_proxy->removeTransformRefs(m_insertedRefs, nodes::ProxyShape::kSelection); - m_proxy->selectedPaths() = m_previousPaths; - if(!m_internal) - { - MGlobal::setActiveSelectionList(m_previousSelection, MGlobal::kReplaceList); - } - m_proxy->m_pleaseIgnoreSelection = false; - if(!MGlobal::optionVarIntValue("AL_usdmaya_ignoreLockPrims")) - { - m_proxy->constructLockPrims(); - } + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg( + "ProxyShapeSelection::SelectionUndoHelper::undoIt %lu %lu\n", + m_insertedRefs.size(), + m_removedRefs.size()); + m_proxy->m_pleaseIgnoreSelection = true; + m_modifier2.undoIt(); + m_modifier1.undoIt(); + m_proxy->insertTransformRefs(m_removedRefs, nodes::ProxyShape::kSelection); + m_proxy->removeTransformRefs(m_insertedRefs, nodes::ProxyShape::kSelection); + m_proxy->selectedPaths() = m_previousPaths; + if (!m_internal) { + MGlobal::setActiveSelectionList(m_previousSelection, MGlobal::kReplaceList); + } + m_proxy->m_pleaseIgnoreSelection = false; + if (!MGlobal::optionVarIntValue("AL_usdmaya_ignoreLockPrims")) { + m_proxy->constructLockPrims(); + } } //---------------------------------------------------------------------------------------------------------------------- -void ProxyShape::removeTransformRefs(const std::vector>& removedRefs, TransformReason reason) +void ProxyShape::removeTransformRefs( + const std::vector>& removedRefs, + TransformReason reason) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeTransformRefs %lu\n", removedRefs.size()); - for(auto iter : removedRefs) - { - UsdPrim parentPrim = m_stage->GetPrimAtPath(iter.first); - while(parentPrim) - { - auto it = m_requiredPaths.find(parentPrim.GetPath()); - if(it != m_requiredPaths.end()) - { - if(it->second.decRef(reason)) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::removeTransformRefs m_requiredPaths removed TransformReference: %s\n", it->first.GetText()); - m_requiredPaths.erase(it); - m_lockManager.setInherited(iter.first); + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg("ProxyShapeSelection::removeTransformRefs %lu\n", removedRefs.size()); + for (auto iter : removedRefs) { + UsdPrim parentPrim = m_stage->GetPrimAtPath(iter.first); + while (parentPrim) { + auto it = m_requiredPaths.find(parentPrim.GetPath()); + if (it != m_requiredPaths.end()) { + if (it->second.decRef(reason)) { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "ProxyShape::removeTransformRefs m_requiredPaths removed " + "TransformReference: %s\n", + it->first.GetText()); + m_requiredPaths.erase(it); + m_lockManager.setInherited(iter.first); + } + } + + parentPrim = parentPrim.GetParent(); + if (parentPrim.GetPath() == SdfPath("/")) { + break; + } } - } - - parentPrim = parentPrim.GetParent(); - if(parentPrim.GetPath() == SdfPath("/")) - { - break; - } } - } } //---------------------------------------------------------------------------------------------------------------------- bool ProxyShape::removeAllSelectedNodes(SelectionUndoHelper& helper) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::removeAllSelectedNodes %lu\n", m_selectedPaths.size()); - - std::vector toRemove; - - auto it = m_requiredPaths.begin(); - auto end = m_requiredPaths.end(); - for(; it != end; ++it) - { - // decrement the ref count. If this comes back as 'please remove' - if(it->second.checkRef(ProxyShape::kSelection)) - { - // add it to the list of things to kill - toRemove.push_back(it); + TF_DEBUG(ALUSDMAYA_SELECTION) + .Msg("ProxyShapeSelection::removeAllSelectedNodes %lu\n", m_selectedPaths.size()); + + std::vector toRemove; + + auto it = m_requiredPaths.begin(); + auto end = m_requiredPaths.end(); + for (; it != end; ++it) { + // decrement the ref count. If this comes back as 'please remove' + if (it->second.checkRef(ProxyShape::kSelection)) { + // add it to the list of things to kill + toRemove.push_back(it); + } } - } - - if(toRemove.size() > 1) - { - // sort the array of iterators so that the transforms with the longest path appear first. Those with shorter - // paths will appear at the end. This is to ensure the child nodes are deleted before their parents. - struct compare_length { - bool operator() (const TransformReferenceMap::iterator a, const TransformReferenceMap::iterator b) const { - return a->first.GetString().size() > b->first.GetString().size(); - } - }; - std::sort(toRemove.begin(), toRemove.end(), compare_length()); - } - - if(!toRemove.empty()) - { - std::vector tempNodes; - - // now go and delete all of the nodes in order - for(auto value = toRemove.begin(), e = toRemove.end(); value != e; ++value) - { - // reparent the custom transform under world prior to deleting - MObject temp = (*value)->second.node(); - helper.m_modifier1.reparentNode(temp); - - // now we can delete (without accidentally nuking all parent transforms in the chain) - helper.m_modifier1.deleteNode(temp); - auto& paths = selectedPaths(); - for(auto iter = paths.begin(), end = paths.end(); iter != end; ++iter) - { - if(*iter == (*value)->first) + if (toRemove.size() > 1) { + // sort the array of iterators so that the transforms with the longest path appear first. + // Those with shorter paths will appear at the end. This is to ensure the child nodes are + // deleted before their parents. + struct compare_length { - helper.m_removedRefs.emplace_back((*value)->first, temp); - paths.erase(iter); - break; - } - } + bool operator()( + const TransformReferenceMap::iterator a, + const TransformReferenceMap::iterator b) const + { + return a->first.GetString().size() > b->first.GetString().size(); + } + }; + std::sort(toRemove.begin(), toRemove.end(), compare_length()); } - m_selectedPaths.clear(); - return true; - } - return false; + if (!toRemove.empty()) { + std::vector tempNodes; + + // now go and delete all of the nodes in order + for (auto value = toRemove.begin(), e = toRemove.end(); value != e; ++value) { + // reparent the custom transform under world prior to deleting + MObject temp = (*value)->second.node(); + helper.m_modifier1.reparentNode(temp); + + // now we can delete (without accidentally nuking all parent transforms in the chain) + helper.m_modifier1.deleteNode(temp); + + auto& paths = selectedPaths(); + for (auto iter = paths.begin(), end = paths.end(); iter != end; ++iter) { + if (*iter == (*value)->first) { + helper.m_removedRefs.emplace_back((*value)->first, temp); + paths.erase(iter); + break; + } + } + } + m_selectedPaths.clear(); + + return true; + } + return false; } //---------------------------------------------------------------------------------------------------------------------- bool ProxyShape::doSelect(SelectionUndoHelper& helper, const SdfPathVector& orderedPaths) { - TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::doSelect\n"); - auto stage = m_stage; - if(!stage) - return false; - triggerEvent("SelectionStarted"); + TF_DEBUG(ALUSDMAYA_SELECTION).Msg("ProxyShapeSelection::doSelect\n"); + auto stage = m_stage; + if (!stage) + return false; + triggerEvent("SelectionStarted"); - m_pleaseIgnoreSelection = true; - prepSelect(); + m_pleaseIgnoreSelection = true; + prepSelect(); - MGlobal::getActiveSelectionList(helper.m_previousSelection); + MGlobal::getActiveSelectionList(helper.m_previousSelection); - helper.m_previousPaths = selectedPaths(); - if(MGlobal::kReplaceList == helper.m_mode) - { - if(helper.m_paths.empty()) - { - helper.m_mode = MGlobal::kRemoveFromList; - helper.m_paths = selectedPaths(); - } - } - else - { - helper.m_newSelection = helper.m_previousSelection; - } - MStringArray newlySelectedPaths; - - auto removeFromMSel = [](MSelectionList& sel, const MObject& toRemove) -> bool { - for(uint32_t i = 0, n = sel.length(); i < n; ++i) - { - MObject obj; - sel.getDependNode(i, obj); - if(obj == toRemove) - { - sel.remove(i); - return true; - } + helper.m_previousPaths = selectedPaths(); + if (MGlobal::kReplaceList == helper.m_mode) { + if (helper.m_paths.empty()) { + helper.m_mode = MGlobal::kRemoveFromList; + helper.m_paths = selectedPaths(); + } + } else { + helper.m_newSelection = helper.m_previousSelection; } - return false; - }; - - switch(helper.m_mode) - { - case MGlobal::kReplaceList: - { - std::vector keepPrims; - std::vector insertPrims; - for(auto path : orderedPaths) - { - bool alreadySelected = m_selectedPaths.count(path) > 0; - - auto prim = stage->GetPrimAtPath(path); - if(prim) - { - if(!alreadySelected) - insertPrims.push_back(prim); - else - keepPrims.push_back(path); + MStringArray newlySelectedPaths; + + auto removeFromMSel = [](MSelectionList& sel, const MObject& toRemove) -> bool { + for (uint32_t i = 0, n = sel.length(); i < n; ++i) { + MObject obj; + sel.getDependNode(i, obj); + if (obj == toRemove) { + sel.remove(i); + return true; + } } - } - - if(keepPrims.empty() && insertPrims.empty()) - { - m_pleaseIgnoreSelection = false; - triggerEvent("PreSelectionChanged"); - triggerEvent("PostSelectionChanged"); - triggerEvent("SelectionEnded"); return false; - } - - std::sort(keepPrims.begin(), keepPrims.end()); - - m_selectedPaths.clear(); + }; - uint32_t hasNodesToCreate = 0; - for(auto prim : insertPrims) - { - if(prim.IsPseudoRoot()) - { - // For pseudo root, just modify maya's selection, don't alter - // our internal paths - newlySelectedPaths.append(MFnDagNode(thisMObject()).fullPathName()); - addObjToSelectionList(helper.m_newSelection, thisMObject()); - continue; - } - m_selectedPaths.insert(prim.GetPath()); - MString pathName; - MObject object = makeUsdTransformChain_internal(prim, helper.m_modifier1, ProxyShape::kSelection, &helper.m_modifier2, &hasNodesToCreate, &pathName); - newlySelectedPaths.append(pathName); - addObjToSelectionList(helper.m_newSelection, object); - helper.m_insertedRefs.emplace_back(prim.GetPath(), object); - } - - for(auto iter : helper.m_previousPaths) - { - auto temp = m_requiredPaths.find(iter); - MObject object = temp->second.node(); - if(!std::binary_search(keepPrims.begin(), keepPrims.end(), iter)) - { - auto prim = stage->GetPrimAtPath(iter); - removeUsdTransformChain_internal(prim, helper.m_modifier1, ProxyShape::kSelection); - helper.m_removedRefs.emplace_back(iter, object); - } - else - { - addObjToSelectionList(helper.m_newSelection, object); - m_selectedPaths.insert(iter); + switch (helper.m_mode) { + case MGlobal::kReplaceList: { + std::vector keepPrims; + std::vector insertPrims; + for (auto path : orderedPaths) { + bool alreadySelected = m_selectedPaths.count(path) > 0; + + auto prim = stage->GetPrimAtPath(path); + if (prim) { + if (!alreadySelected) + insertPrims.push_back(prim); + else + keepPrims.push_back(path); + } } - } - - helper.m_paths = m_selectedPaths; - } - break; - - case MGlobal::kAddToHeadOfList: - case MGlobal::kAddToList: - { - std::vector prims; - for(auto path : orderedPaths) - { - bool alreadySelected = m_selectedPaths.count(path) > 0; - if(!alreadySelected) - { - auto prim = stage->GetPrimAtPath(path); - if(prim) - { - prims.push_back(prim); - } + if (keepPrims.empty() && insertPrims.empty()) { + m_pleaseIgnoreSelection = false; + triggerEvent("PreSelectionChanged"); + triggerEvent("PostSelectionChanged"); + triggerEvent("SelectionEnded"); + return false; } - } - - helper.m_paths.insert(helper.m_previousPaths.begin(), helper.m_previousPaths.end()); - uint32_t hasNodesToCreate = 0; - for(auto prim : prims) - { - if(prim.IsPseudoRoot()) - { - // For pseudo root, just modify maya's selection - // However, since we don't want the pseudo root to "pollute" our - // internal selected paths, we also need to make sure we clear - // it from m_paths. (We don't need to do those in other modes, - // because those set m_paths to m_selectePaths). - newlySelectedPaths.append(MFnDagNode(thisMObject()).fullPathName()); - addObjToSelectionList(helper.m_newSelection, thisMObject()); - helper.m_paths.erase(prim.GetPath()); - continue; + std::sort(keepPrims.begin(), keepPrims.end()); + + m_selectedPaths.clear(); + + uint32_t hasNodesToCreate = 0; + for (auto prim : insertPrims) { + if (prim.IsPseudoRoot()) { + // For pseudo root, just modify maya's selection, don't alter + // our internal paths + newlySelectedPaths.append(MFnDagNode(thisMObject()).fullPathName()); + addObjToSelectionList(helper.m_newSelection, thisMObject()); + continue; + } + m_selectedPaths.insert(prim.GetPath()); + MString pathName; + MObject object = makeUsdTransformChain_internal( + prim, + helper.m_modifier1, + ProxyShape::kSelection, + &helper.m_modifier2, + &hasNodesToCreate, + &pathName); + newlySelectedPaths.append(pathName); + addObjToSelectionList(helper.m_newSelection, object); + helper.m_insertedRefs.emplace_back(prim.GetPath(), object); } - m_selectedPaths.insert(prim.GetPath()); - MString pathName; - MObject object = makeUsdTransformChain_internal(prim, helper.m_modifier1, ProxyShape::kSelection, &helper.m_modifier2, &hasNodesToCreate, &pathName); - newlySelectedPaths.append(pathName); - addObjToSelectionList(helper.m_newSelection, object); - helper.m_insertedRefs.emplace_back(prim.GetPath(), object); - } - } - break; - - case MGlobal::kRemoveFromList: - { - std::vector prims; - - // We use helper.m_paths, not orderedPaths here, because - // if mode was MGlobal::kReplaceList at start, but helper.m_paths - // was empty, we switch mode to kRemoveFromList, and - // changed helper.m_paths to previousPaths. This is fine, though - // because we only need order so we can get right order for - // newlySelectedPaths - which is not altered in this branch - for(auto path : helper.m_paths) - { - bool alreadySelected; - if(path == SdfPath::AbsoluteRootPath()) - { - // For pseudo-root, remove proxy shape from maya's selection - alreadySelected = removeFromMSel(helper.m_newSelection, thisMObject()); - } - else - { - alreadySelected = m_selectedPaths.count(path) > 0; + for (auto iter : helper.m_previousPaths) { + auto temp = m_requiredPaths.find(iter); + MObject object = temp->second.node(); + if (!std::binary_search(keepPrims.begin(), keepPrims.end(), iter)) { + auto prim = stage->GetPrimAtPath(iter); + removeUsdTransformChain_internal(prim, helper.m_modifier1, ProxyShape::kSelection); + helper.m_removedRefs.emplace_back(iter, object); + } else { + addObjToSelectionList(helper.m_newSelection, object); + m_selectedPaths.insert(iter); + } } - if(alreadySelected) - { - auto prim = stage->GetPrimAtPath(path); - - if(prim) - { - prims.push_back(prim); - } + helper.m_paths = m_selectedPaths; + } break; + + case MGlobal::kAddToHeadOfList: + case MGlobal::kAddToList: { + std::vector prims; + for (auto path : orderedPaths) { + bool alreadySelected = m_selectedPaths.count(path) > 0; + + if (!alreadySelected) { + auto prim = stage->GetPrimAtPath(path); + if (prim) { + prims.push_back(prim); + } + } } - } - - if(prims.empty()) - { - m_pleaseIgnoreSelection = false; - triggerEvent("PreSelectionChanged"); - triggerEvent("PostSelectionChanged"); - triggerEvent("SelectionEnded"); - return false; - } - for(auto prim : prims) - { - if(prim.IsPseudoRoot()) - { - // We've already removed this when iterating helper.m_paths, - // we just added to prims so the "prims.empty" early-exit test wouldn't - // fire - continue; + helper.m_paths.insert(helper.m_previousPaths.begin(), helper.m_previousPaths.end()); + + uint32_t hasNodesToCreate = 0; + for (auto prim : prims) { + if (prim.IsPseudoRoot()) { + // For pseudo root, just modify maya's selection + // However, since we don't want the pseudo root to "pollute" our + // internal selected paths, we also need to make sure we clear + // it from m_paths. (We don't need to do those in other modes, + // because those set m_paths to m_selectePaths). + newlySelectedPaths.append(MFnDagNode(thisMObject()).fullPathName()); + addObjToSelectionList(helper.m_newSelection, thisMObject()); + helper.m_paths.erase(prim.GetPath()); + continue; + } + + m_selectedPaths.insert(prim.GetPath()); + MString pathName; + MObject object = makeUsdTransformChain_internal( + prim, + helper.m_modifier1, + ProxyShape::kSelection, + &helper.m_modifier2, + &hasNodesToCreate, + &pathName); + newlySelectedPaths.append(pathName); + addObjToSelectionList(helper.m_newSelection, object); + helper.m_insertedRefs.emplace_back(prim.GetPath(), object); + } + } break; + + case MGlobal::kRemoveFromList: { + std::vector prims; + + // We use helper.m_paths, not orderedPaths here, because + // if mode was MGlobal::kReplaceList at start, but helper.m_paths + // was empty, we switch mode to kRemoveFromList, and + // changed helper.m_paths to previousPaths. This is fine, though + // because we only need order so we can get right order for + // newlySelectedPaths - which is not altered in this branch + for (auto path : helper.m_paths) { + bool alreadySelected; + if (path == SdfPath::AbsoluteRootPath()) { + // For pseudo-root, remove proxy shape from maya's selection + alreadySelected = removeFromMSel(helper.m_newSelection, thisMObject()); + } else { + alreadySelected = m_selectedPaths.count(path) > 0; + } + + if (alreadySelected) { + auto prim = stage->GetPrimAtPath(path); + + if (prim) { + prims.push_back(prim); + } + } } - auto temp = m_requiredPaths.find(prim.GetPath()); - MObject object = temp->second.node(); - - m_selectedPaths.erase(prim.GetPath()); - removeUsdTransformChain_internal(prim, helper.m_modifier1, ProxyShape::kSelection); - removeFromMSel(helper.m_newSelection, object); - helper.m_removedRefs.emplace_back(prim.GetPath(), object); - } - helper.m_paths = m_selectedPaths; - } - break; + if (prims.empty()) { + m_pleaseIgnoreSelection = false; + triggerEvent("PreSelectionChanged"); + triggerEvent("PostSelectionChanged"); + triggerEvent("SelectionEnded"); + return false; + } - case MGlobal::kXORWithList: - { - std::vector removePrims; - std::vector insertPrims; - for(auto path : orderedPaths) - { - bool alreadySelected; - if(path == SdfPath::AbsoluteRootPath()) - { - // For pseudo-root, remove proxy shape from maya's selection - alreadySelected = removeFromMSel(helper.m_newSelection, thisMObject()); + for (auto prim : prims) { + if (prim.IsPseudoRoot()) { + // We've already removed this when iterating helper.m_paths, + // we just added to prims so the "prims.empty" early-exit test wouldn't + // fire + continue; + } + auto temp = m_requiredPaths.find(prim.GetPath()); + MObject object = temp->second.node(); + + m_selectedPaths.erase(prim.GetPath()); + + removeUsdTransformChain_internal(prim, helper.m_modifier1, ProxyShape::kSelection); + removeFromMSel(helper.m_newSelection, object); + helper.m_removedRefs.emplace_back(prim.GetPath(), object); } - else - { - alreadySelected = m_selectedPaths.count(path) > 0; + helper.m_paths = m_selectedPaths; + } break; + + case MGlobal::kXORWithList: { + std::vector removePrims; + std::vector insertPrims; + for (auto path : orderedPaths) { + bool alreadySelected; + if (path == SdfPath::AbsoluteRootPath()) { + // For pseudo-root, remove proxy shape from maya's selection + alreadySelected = removeFromMSel(helper.m_newSelection, thisMObject()); + } else { + alreadySelected = m_selectedPaths.count(path) > 0; + } + + auto prim = stage->GetPrimAtPath(path); + if (prim) { + if (alreadySelected) + removePrims.push_back(prim); + else { + insertPrims.push_back(prim); + } + } } - auto prim = stage->GetPrimAtPath(path); - if(prim) - { - if(alreadySelected) - removePrims.push_back(prim); - else - { - insertPrims.push_back(prim); - } + if (removePrims.empty() && insertPrims.empty()) { + m_pleaseIgnoreSelection = false; + triggerEvent("PreSelectionChanged"); + triggerEvent("PostSelectionChanged"); + triggerEvent("SelectionEnded"); + return false; } - } - - if(removePrims.empty() && insertPrims.empty()) - { - m_pleaseIgnoreSelection = false; - triggerEvent("PreSelectionChanged"); - triggerEvent("PostSelectionChanged"); - triggerEvent("SelectionEnded"); - return false; - } - for(auto prim : removePrims) - { - if(prim.IsPseudoRoot()) - { - // We've already removed this when iterating orderedPaths, - // we just added to removePrims so the "removePrims.empty" early-exit test - // wouldn't fire - continue; + for (auto prim : removePrims) { + if (prim.IsPseudoRoot()) { + // We've already removed this when iterating orderedPaths, + // we just added to removePrims so the "removePrims.empty" early-exit test + // wouldn't fire + continue; + } + auto temp = m_requiredPaths.find(prim.GetPath()); + MObject object = temp->second.node(); + + m_selectedPaths.erase(prim.GetPath()); + + removeUsdTransformChain_internal(prim, helper.m_modifier1, ProxyShape::kSelection); + removeFromMSel(helper.m_newSelection, object); + helper.m_removedRefs.emplace_back(prim.GetPath(), object); } - auto temp = m_requiredPaths.find(prim.GetPath()); - MObject object = temp->second.node(); - - m_selectedPaths.erase(prim.GetPath()); - removeUsdTransformChain_internal(prim, helper.m_modifier1, ProxyShape::kSelection); - removeFromMSel(helper.m_newSelection, object); - helper.m_removedRefs.emplace_back(prim.GetPath(), object); - } - - uint32_t hasNodesToCreate = 0; - for(auto prim : insertPrims) - { - if(prim.IsPseudoRoot()) - { - // For pseudo root, just modify maya's selection, don't alter - // our internal paths - newlySelectedPaths.append(MFnDagNode(thisMObject()).fullPathName()); - addObjToSelectionList(helper.m_newSelection, thisMObject()); - continue; + uint32_t hasNodesToCreate = 0; + for (auto prim : insertPrims) { + if (prim.IsPseudoRoot()) { + // For pseudo root, just modify maya's selection, don't alter + // our internal paths + newlySelectedPaths.append(MFnDagNode(thisMObject()).fullPathName()); + addObjToSelectionList(helper.m_newSelection, thisMObject()); + continue; + } + m_selectedPaths.insert(prim.GetPath()); + MString pathName; + MObject object = makeUsdTransformChain_internal( + prim, + helper.m_modifier1, + ProxyShape::kSelection, + &helper.m_modifier2, + &hasNodesToCreate, + &pathName); + newlySelectedPaths.append(pathName); + addObjToSelectionList(helper.m_newSelection, object); + helper.m_insertedRefs.emplace_back(prim.GetPath(), object); } - m_selectedPaths.insert(prim.GetPath()); - MString pathName; - MObject object = makeUsdTransformChain_internal(prim, helper.m_modifier1, ProxyShape::kSelection, &helper.m_modifier2, &hasNodesToCreate, &pathName); - newlySelectedPaths.append(pathName); - addObjToSelectionList(helper.m_newSelection, object); - helper.m_insertedRefs.emplace_back(prim.GetPath(), object); - } - helper.m_paths = m_selectedPaths; + helper.m_paths = m_selectedPaths; + } break; } - break; - } - - triggerEvent("PreSelectionChanged"); - if(newlySelectedPaths.length()) - { - MPxCommand::setResult(newlySelectedPaths); - } - triggerEvent("PostSelectionChanged"); - - m_pleaseIgnoreSelection = false; - triggerEvent("SelectionEnded"); - return true; + + triggerEvent("PreSelectionChanged"); + if (newlySelectedPaths.length()) { + MPxCommand::setResult(newlySelectedPaths); + } + triggerEvent("PostSelectionChanged"); + + m_pleaseIgnoreSelection = false; + triggerEvent("SelectionEnded"); + return true; } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeUI.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeUI.cpp index d17d2eb878..e80ed52fde 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeUI.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeUI.cpp @@ -13,16 +13,12 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include +#include "AL/usdmaya/nodes/ProxyShapeUI.h" #include "AL/usdmaya/DebugCodes.h" #include "AL/usdmaya/nodes/Engine.h" #include "AL/usdmaya/nodes/ProxyShape.h" -#include "AL/usdmaya/nodes/ProxyShapeUI.h" -#include -#include -#include #include #include #include @@ -30,753 +26,678 @@ #include #include #include +#include #if defined(WANT_UFE_BUILD) #include "AL/usdmaya/TypeIDs.h" -#include -#include "ufe/hierarchyHandler.h" -#include "ufe/sceneItem.h" -#include "ufe/runTimeMgr.h" #include "ufe/globalSelection.h" -#include "ufe/observableSelection.h" +#include "ufe/hierarchyHandler.h" #include "ufe/log.h" +#include "ufe/observableSelection.h" +#include "ufe/runTimeMgr.h" +#include "ufe/sceneItem.h" + +#include #endif -#include #include +#include namespace AL { namespace usdmaya { namespace nodes { //---------------------------------------------------------------------------------------------------------------------- -/// \brief Retarget a prim based on the AL_USDMaya's pick mode settings. This will either return new prim to select, +/// \brief Retarget a prim based on the AL_USDMaya's pick mode settings. This will either return new +/// prim to select, /// or the original prim if no retargetting occurred. /// \param prim Attempt to retarget this prim. /// \return The retargetted prim, or the original. -UsdPrim retargetSelectPrim(const UsdPrim &prim) +UsdPrim retargetSelectPrim(const UsdPrim& prim) { - switch(ProxyShape::PickMode(MGlobal::optionVarIntValue("AL_usdmaya_pickMode"))){ + switch (ProxyShape::PickMode(MGlobal::optionVarIntValue("AL_usdmaya_pickMode"))) { // Read up prim hierarchy and return first Model kind ancestor as the target prim - case ProxyShape::PickMode::kModels: - { - UsdPrim tmpPrim = prim; - while(tmpPrim.IsValid()) { - TfToken kind; - UsdModelAPI(tmpPrim).GetKind(&kind); - if (KindRegistry::GetInstance().IsA(kind, KindTokens->model)) { - return tmpPrim; + case ProxyShape::PickMode::kModels: { + UsdPrim tmpPrim = prim; + while (tmpPrim.IsValid()) { + TfToken kind; + UsdModelAPI(tmpPrim).GetKind(&kind); + if (KindRegistry::GetInstance().IsA(kind, KindTokens->model)) { + return tmpPrim; + } + tmpPrim = tmpPrim.GetParent(); } - tmpPrim = tmpPrim.GetParent(); - } } case ProxyShape::PickMode::kPrims: case ProxyShape::PickMode::kInstances: - default: - { - break; + default: { + break; + } } - } - return prim; + return prim; } - //---------------------------------------------------------------------------------------------------------------------- -ProxyShapeUI::ProxyShapeUI() -{ - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyShapeUI::ProxyShapeUI\n"); -} +ProxyShapeUI::ProxyShapeUI() { TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyShapeUI::ProxyShapeUI\n"); } //---------------------------------------------------------------------------------------------------------------------- -ProxyShapeUI::~ProxyShapeUI() -{ - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyShapeUI::~ProxyShapeUI\n"); -} +ProxyShapeUI::~ProxyShapeUI() { TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyShapeUI::~ProxyShapeUI\n"); } //---------------------------------------------------------------------------------------------------------------------- -void* ProxyShapeUI::creator() -{ - return new ProxyShapeUI; -} +void* ProxyShapeUI::creator() { return new ProxyShapeUI; } //---------------------------------------------------------------------------------------------------------------------- -void ProxyShapeUI::getDrawRequests(const MDrawInfo& drawInfo, bool isObjectAndActiveOnly, MDrawRequestQueue& requests) +void ProxyShapeUI::getDrawRequests( + const MDrawInfo& drawInfo, + bool isObjectAndActiveOnly, + MDrawRequestQueue& requests) { - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyShapeUI::getDrawRequests\n"); + TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyShapeUI::getDrawRequests\n"); - MDrawRequest request = drawInfo.getPrototype(*this); + MDrawRequest request = drawInfo.getPrototype(*this); - // If there are no side effects to calling surfaceShape(), the following two - // lines can be removed, as they are unused. PPT, 8-Jan-2020. - ProxyShape* shape = static_cast(surfaceShape()); - (void) shape; + // If there are no side effects to calling surfaceShape(), the following two + // lines can be removed, as they are unused. PPT, 8-Jan-2020. + ProxyShape* shape = static_cast(surfaceShape()); + (void)shape; - // add the request to the queue - requests.add(request); + // add the request to the queue + requests.add(request); } -// UsdImagingGL doesn't seem to like VP1 all that much, unless it sets the values directly from the OpenGL state. +// UsdImagingGL doesn't seem to like VP1 all that much, unless it sets the values directly from the +// OpenGL state. #define USE_GL_LIGHTING_STATE 1 //---------------------------------------------------------------------------------------------------------------------- void ProxyShapeUI::draw(const MDrawRequest& request, M3dView& view) const { - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyShapeUI::draw\n"); - - // - view.beginGL(); - - // clear colour is not restored by hydra - float clearCol[4]; - glGetFloatv(GL_COLOR_CLEAR_VALUE, clearCol); - - glPushAttrib(GL_ALL_ATTRIB_BITS); - glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS); - - ProxyShape* shape = static_cast(surfaceShape()); - Engine* engine = shape->engine(); - if(!engine) - { - return; - } - - auto stage = shape->getUsdStage(); - UsdImagingGLRenderParams params; - - params.showGuides = shape->drawGuidePurposePlug().asBool(); - params.showProxy = shape->drawProxyPurposePlug().asBool(); - params.showRender = shape->drawRenderPurposePlug().asBool(); - - params.frame = UsdTimeCode(shape->outTimePlug().asMTime().as(MTime::uiUnit())); - params.complexity = 1.0f; - - MMatrix viewMatrix, projection, model; - view.projectionMatrix(projection); - view.modelViewMatrix(viewMatrix); - model = request.multiPath().inclusiveMatrix(); - MMatrix invViewMatrix = viewMatrix.inverse(); - engine->SetRootTransform(GfMatrix4d(model.matrix)); - - unsigned int x, y, w, h; - view.viewport(x, y, w, h); - - engine->SetCameraState( - GfMatrix4d((model.inverse() * viewMatrix).matrix), - GfMatrix4d(projection.matrix)); - engine->SetRenderViewport(GfVec4d(x, y, w, h)); - - switch(request.displayStyle()) - { - case M3dView::kBoundingBox: - params.drawMode = UsdImagingGLDrawMode::DRAW_POINTS; - break; - - case M3dView::kFlatShaded: - params.drawMode = UsdImagingGLDrawMode::DRAW_SHADED_FLAT; - break; - - case M3dView::kGouraudShaded: - params.drawMode = UsdImagingGLDrawMode::DRAW_SHADED_SMOOTH; - break; - - case M3dView::kWireFrame: - params.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME; - break; - - case M3dView::kPoints: - params.drawMode = UsdImagingGLDrawMode::DRAW_POINTS; - break; - } - - if(request.displayCulling()) - { - if(!request.displayCullOpposite()) - { - params.cullStyle = UsdImagingGLCullStyle::CULL_STYLE_BACK; - } - else - { - params.cullStyle = UsdImagingGLCullStyle::CULL_STYLE_FRONT; + TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyShapeUI::draw\n"); + + // + view.beginGL(); + + // clear colour is not restored by hydra + float clearCol[4]; + glGetFloatv(GL_COLOR_CLEAR_VALUE, clearCol); + + glPushAttrib(GL_ALL_ATTRIB_BITS); + glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS); + + ProxyShape* shape = static_cast(surfaceShape()); + Engine* engine = shape->engine(); + if (!engine) { + return; } - } - else - { - params.cullStyle = UsdImagingGLCullStyle::CULL_STYLE_NOTHING; - } - - #if !USE_GL_LIGHTING_STATE - MColor color = request.color(); - params.wireframeColor = GfVec4f(color.r, color.g, color.b, 1.0f); - - auto asMColor = [] (const MPlug& plug) { - MColor c; - c.r = plug.child(0).asFloat(); - c.g = plug.child(1).asFloat(); - c.b = plug.child(2).asFloat(); - return c; - }; - - const MColor amb = asMColor(shape->ambientPlug()); - const MColor dif = asMColor(shape->diffusePlug()); - const MColor spc = asMColor(shape->specularPlug()); - const MColor emi = asMColor(shape->emissionPlug()); - const float shine = shape->shininessPlug().asFloat(); - - GlfSimpleMaterial usdmaterial; - usdmaterial.SetAmbient(GfVec4f(amb.r, amb.g, amb.b, 1.0f)); - usdmaterial.SetDiffuse(GfVec4f(dif.r, dif.g, dif.b, 1.0f)); - usdmaterial.SetSpecular(GfVec4f(spc.r, spc.g, spc.b, 1.0f)); - usdmaterial.SetEmission(GfVec4f(emi.r, emi.g, emi.b, 1.0f)); - usdmaterial.SetShininess(shine); - - GLint nLights = 0; - glGetIntegerv(GL_MAX_LIGHTS, &nLights); - nLights += GL_LIGHT0; - - GlfSimpleLightVector lights; - lights.reserve(nLights); - - GlfSimpleLight light; - for(int i = GL_LIGHT0; i < nLights; ++i) - { - if (glIsEnabled(i)) - { - GLfloat position[4], color[4]; - glGetLightfv(i, GL_POSITION, position); - MPoint temp = MPoint(position) * invViewMatrix; - light.SetPosition(GfVec4f(temp.x, temp.y, temp.z, 1.0f)); - glGetLightfv(i, GL_AMBIENT, color); - light.SetAmbient(GfVec4f(color[0], color[1], color[2], 1.0f)); + auto stage = shape->getUsdStage(); + UsdImagingGLRenderParams params; + + params.showGuides = shape->drawGuidePurposePlug().asBool(); + params.showProxy = shape->drawProxyPurposePlug().asBool(); + params.showRender = shape->drawRenderPurposePlug().asBool(); + + params.frame = UsdTimeCode(shape->outTimePlug().asMTime().as(MTime::uiUnit())); + params.complexity = 1.0f; + + MMatrix viewMatrix, projection, model; + view.projectionMatrix(projection); + view.modelViewMatrix(viewMatrix); + model = request.multiPath().inclusiveMatrix(); + MMatrix invViewMatrix = viewMatrix.inverse(); + engine->SetRootTransform(GfMatrix4d(model.matrix)); + + unsigned int x, y, w, h; + view.viewport(x, y, w, h); - glGetLightfv(i, GL_DIFFUSE, color); - light.SetDiffuse(GfVec4f(color[0], color[1], color[2], 1.0f)); + engine->SetCameraState( + GfMatrix4d((model.inverse() * viewMatrix).matrix), GfMatrix4d(projection.matrix)); + engine->SetRenderViewport(GfVec4d(x, y, w, h)); - glGetLightfv(i, GL_SPECULAR, color); - light.SetSpecular(GfVec4f(color[0], color[1], color[2], 1.0f)); + switch (request.displayStyle()) { + case M3dView::kBoundingBox: params.drawMode = UsdImagingGLDrawMode::DRAW_POINTS; break; - lights.push_back(light); + case M3dView::kFlatShaded: params.drawMode = UsdImagingGLDrawMode::DRAW_SHADED_FLAT; break; + + case M3dView::kGouraudShaded: params.drawMode = UsdImagingGLDrawMode::DRAW_SHADED_SMOOTH; break; + + case M3dView::kWireFrame: params.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME; break; + + case M3dView::kPoints: params.drawMode = UsdImagingGLDrawMode::DRAW_POINTS; break; } - } - engine->SetLightingState(lights, usdmaterial, GfVec4f(0.05f)); + if (request.displayCulling()) { + if (!request.displayCullOpposite()) { + params.cullStyle = UsdImagingGLCullStyle::CULL_STYLE_BACK; + } else { + params.cullStyle = UsdImagingGLCullStyle::CULL_STYLE_FRONT; + } + } else { + params.cullStyle = UsdImagingGLCullStyle::CULL_STYLE_NOTHING; + } - #else +#if !USE_GL_LIGHTING_STATE + MColor color = request.color(); + params.wireframeColor = GfVec4f(color.r, color.g, color.b, 1.0f); + + auto asMColor = [](const MPlug& plug) { + MColor c; + c.r = plug.child(0).asFloat(); + c.g = plug.child(1).asFloat(); + c.b = plug.child(2).asFloat(); + return c; + }; + + const MColor amb = asMColor(shape->ambientPlug()); + const MColor dif = asMColor(shape->diffusePlug()); + const MColor spc = asMColor(shape->specularPlug()); + const MColor emi = asMColor(shape->emissionPlug()); + const float shine = shape->shininessPlug().asFloat(); + + GlfSimpleMaterial usdmaterial; + usdmaterial.SetAmbient(GfVec4f(amb.r, amb.g, amb.b, 1.0f)); + usdmaterial.SetDiffuse(GfVec4f(dif.r, dif.g, dif.b, 1.0f)); + usdmaterial.SetSpecular(GfVec4f(spc.r, spc.g, spc.b, 1.0f)); + usdmaterial.SetEmission(GfVec4f(emi.r, emi.g, emi.b, 1.0f)); + usdmaterial.SetShininess(shine); + + GLint nLights = 0; + glGetIntegerv(GL_MAX_LIGHTS, &nLights); + nLights += GL_LIGHT0; + + GlfSimpleLightVector lights; + lights.reserve(nLights); + + GlfSimpleLight light; + for (int i = GL_LIGHT0; i < nLights; ++i) { + if (glIsEnabled(i)) { + GLfloat position[4], color[4]; + glGetLightfv(i, GL_POSITION, position); + MPoint temp = MPoint(position) * invViewMatrix; + light.SetPosition(GfVec4f(temp.x, temp.y, temp.z, 1.0f)); + + glGetLightfv(i, GL_AMBIENT, color); + light.SetAmbient(GfVec4f(color[0], color[1], color[2], 1.0f)); + + glGetLightfv(i, GL_DIFFUSE, color); + light.SetDiffuse(GfVec4f(color[0], color[1], color[2], 1.0f)); + + glGetLightfv(i, GL_SPECULAR, color); + light.SetSpecular(GfVec4f(color[0], color[1], color[2], 1.0f)); + + lights.push_back(light); + } + } - engine->SetLightingStateFromOpenGL(); + engine->SetLightingState(lights, usdmaterial, GfVec4f(0.05f)); - #endif +#else - SdfPathVector paths(shape->selectedPaths().cbegin(), shape->selectedPaths().cend()); - auto style = params.drawMode; - auto colour = params.wireframeColor; - if(paths.size()) - { - MColor colour = M3dView::leadColor(); - params.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME; - params.wireframeColor = GfVec4f(colour.r, colour.g, colour.b, 1.0f); - glDepthFunc(GL_LEQUAL); - engine->RenderBatch(paths, params); - glDepthFunc(GL_LESS); - } + engine->SetLightingStateFromOpenGL(); - params.drawMode = style; - params.wireframeColor = colour; - engine->SetSelected(paths); - engine->SetSelectionColor(GfVec4f(1.0f, 2.0f/3.0f, 0.0f, 1.0f)); - engine->Render(shape->getRootPrim(), params); +#endif + SdfPathVector paths(shape->selectedPaths().cbegin(), shape->selectedPaths().cend()); + auto style = params.drawMode; + auto colour = params.wireframeColor; + if (paths.size()) { + MColor colour = M3dView::leadColor(); + params.drawMode = UsdImagingGLDrawMode::DRAW_WIREFRAME; + params.wireframeColor = GfVec4f(colour.r, colour.g, colour.b, 1.0f); + glDepthFunc(GL_LEQUAL); + engine->RenderBatch(paths, params); + glDepthFunc(GL_LESS); + } + + params.drawMode = style; + params.wireframeColor = colour; + engine->SetSelected(paths); + engine->SetSelectionColor(GfVec4f(1.0f, 2.0f / 3.0f, 0.0f, 1.0f)); + engine->Render(shape->getRootPrim(), params); - glClearColor(clearCol[0], clearCol[1], clearCol[2], clearCol[3]); - glPopClientAttrib(); - glPopAttrib(); - view.endGL(); + glClearColor(clearCol[0], clearCol[1], clearCol[2], clearCol[3]); + glPopClientAttrib(); + glPopAttrib(); + view.endGL(); } //---------------------------------------------------------------------------------------------------------------------- class ProxyShapeSelectionHelper { public: - - static SdfPath path_ting(const SdfPath& a, const SdfPath& b, const int c) - { - m_paths.push_back(a); - return a; - } - static SdfPathVector m_paths; + static SdfPath path_ting(const SdfPath& a, const SdfPath& b, const int c) + { + m_paths.push_back(a); + return a; + } + static SdfPathVector m_paths; }; SdfPathVector ProxyShapeSelectionHelper::m_paths; - //---------------------------------------------------------------------------------------------------------------------- -bool ProxyShapeUI::select(MSelectInfo& selectInfo, MSelectionList& selectionList, MPointArray& worldSpaceSelectPoints) const +bool ProxyShapeUI::select( + MSelectInfo& selectInfo, + MSelectionList& selectionList, + MPointArray& worldSpaceSelectPoints) const { - TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyShapeUI::select\n"); - - if(!MGlobal::optionVarIntValue("AL_usdmaya_selectionEnabled")) - return false; - - float clearCol[4]; - glGetFloatv(GL_COLOR_CLEAR_VALUE, clearCol); - - M3dView view = selectInfo.view(); - - MSelectionMask objectsMask(ProxyShape::s_selectionMaskName); - - // selectable() takes MSelectionMask&, not const MSelectionMask. :(. - if(!selectInfo.selectable(objectsMask)) - return false; - - MDagPath selectPath = selectInfo.selectPath(); - MMatrix invMatrix = selectPath.inclusiveMatrixInverse(); - - MMatrix viewMatrix, projectionMatrix; - GfMatrix4d worldToLocalSpace(invMatrix.matrix); - - GLuint glHitRecord; - view.beginSelect(&glHitRecord, 1); - glGetDoublev(GL_MODELVIEW_MATRIX, viewMatrix[0]); - glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix[0]); - view.endSelect(); - - auto* proxyShape = static_cast(surfaceShape()); - auto engine = proxyShape->engine(); - if (!engine) return false; - proxyShape->m_pleaseIgnoreSelection = true; - - UsdImagingGLRenderParams params; - params.showGuides = proxyShape->drawGuidePurposePlug().asBool(); - params.showProxy = proxyShape->drawProxyPurposePlug().asBool(); - params.showRender = proxyShape->drawRenderPurposePlug().asBool(); - - UsdPrim root = proxyShape->getUsdStage()->GetPseudoRoot(); - - Engine::HitBatch hitBatch; - SdfPathVector rootPath; - rootPath.push_back(root.GetPath()); - - int resolution = 10; - MGlobal::getOptionVarValue("AL_usdmaya_selectResolution", resolution); - if (resolution < 10) { resolution = 10; } - if (resolution > 1024) { resolution = 1024; } - - bool hitSelected = engine->TestIntersectionBatch( - GfMatrix4d(viewMatrix.matrix), - GfMatrix4d(projectionMatrix.matrix), - worldToLocalSpace, - rootPath, - params, - resolution, - ProxyShapeSelectionHelper::path_ting, - &hitBatch); - - auto selected = false; - - auto addSelection = [&hitBatch, &selectInfo, &selectionList, - &worldSpaceSelectPoints, &objectsMask, &selected, proxyShape] - (const MString& command) - { - selected = true; - MStringArray nodes; - MGlobal::executeCommand(command, nodes, false, true); - - // If the selection is in a single selection mode, we don't know if your mesh - // will be the actual final selection, because we can't make sure this is going to - // be called the last. So we are returning a deferred command here, that'll run last. - // That'll check if the mesh is still selected, and run an internal deselect command on that. - // const auto singleSelection = selectInfo.singleSelection(); - - for(const auto& it : hitBatch) - { + TF_DEBUG(ALUSDMAYA_DRAW).Msg("ProxyShapeUI::select\n"); - // Retarget hit path based on pick mode policy. The retargeted prim must - // align with the path used in the 'AL_usdmaya_ProxyShapeSelect' command. - const SdfPath hitPath = it.first; - const UsdPrim retargetedHitPrim = retargetSelectPrim(proxyShape->getUsdStage()->GetPrimAtPath(hitPath)); - const MObject obj = proxyShape->findRequiredPath(retargetedHitPrim.GetPath()); - - if (obj != MObject::kNullObj) - { - MSelectionList sl; - MFnDagNode dagNode(obj); - MDagPath dg; - dagNode.getPath(dg); - sl.add(dg); - const double* d = it.second.worldSpaceHitPoint.GetArray(); - selectInfo.addSelection(sl, MPoint(d[0], d[1], d[2], 1.0), selectionList, worldSpaceSelectPoints, objectsMask, false); - } - } - }; - - // Currently we have two approaches to selection. One method works with undo (but does not - // play nicely with maya geometry). The second method doesn't work with undo, but does play - // nicely with maya geometry. - const int selectionMode = MGlobal::optionVarIntValue("AL_usdmaya_selectMode"); - if(1 == selectionMode) - { - if(hitSelected) - { - int mods; - MString cmd = "getModifiers"; - MGlobal::executeCommand(cmd, mods); - - bool shiftHeld = (mods % 2); - bool ctrlHeld = (mods / 4 % 2); - MGlobal::ListAdjustment mode = MGlobal::kReplaceList; - if(shiftHeld && ctrlHeld) - mode = MGlobal::kAddToList; - else - if(ctrlHeld) - mode = MGlobal::kRemoveFromList; - else - if(shiftHeld) - mode = MGlobal::kXORWithList; - - MString command = "AL_usdmaya_ProxyShapeSelect"; - switch(mode) - { - case MGlobal::kReplaceList: command += " -r"; break; - case MGlobal::kRemoveFromList: command += " -d"; break; - case MGlobal::kXORWithList: command += " -tgl"; break; - case MGlobal::kAddToList: command += " -a"; break; - case MGlobal::kAddToHeadOfList: /* should never get here */ break; - } - - for(const auto& it : hitBatch) - { - auto path = it.first; - command += " -pp \""; - command += path.GetText(); - command += "\""; - } - - MFnDagNode fn(proxyShape->thisMObject()); - command += " \""; - command += fn.fullPathName(); - command += "\""; - MGlobal::executeCommandOnIdle(command, false); + if (!MGlobal::optionVarIntValue("AL_usdmaya_selectionEnabled")) + return false; + + float clearCol[4]; + glGetFloatv(GL_COLOR_CLEAR_VALUE, clearCol); + + M3dView view = selectInfo.view(); + + MSelectionMask objectsMask(ProxyShape::s_selectionMaskName); + + // selectable() takes MSelectionMask&, not const MSelectionMask. :(. + if (!selectInfo.selectable(objectsMask)) + return false; + + MDagPath selectPath = selectInfo.selectPath(); + MMatrix invMatrix = selectPath.inclusiveMatrixInverse(); + + MMatrix viewMatrix, projectionMatrix; + GfMatrix4d worldToLocalSpace(invMatrix.matrix); + + GLuint glHitRecord; + view.beginSelect(&glHitRecord, 1); + glGetDoublev(GL_MODELVIEW_MATRIX, viewMatrix[0]); + glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix[0]); + view.endSelect(); + + auto* proxyShape = static_cast(surfaceShape()); + auto engine = proxyShape->engine(); + if (!engine) + return false; + proxyShape->m_pleaseIgnoreSelection = true; + + UsdImagingGLRenderParams params; + params.showGuides = proxyShape->drawGuidePurposePlug().asBool(); + params.showProxy = proxyShape->drawProxyPurposePlug().asBool(); + params.showRender = proxyShape->drawRenderPurposePlug().asBool(); + + UsdPrim root = proxyShape->getUsdStage()->GetPseudoRoot(); + + Engine::HitBatch hitBatch; + SdfPathVector rootPath; + rootPath.push_back(root.GetPath()); + + int resolution = 10; + MGlobal::getOptionVarValue("AL_usdmaya_selectResolution", resolution); + if (resolution < 10) { + resolution = 10; } - else - { - MString command = "AL_usdmaya_ProxyShapeSelect -cl "; - MFnDagNode fn(proxyShape->thisMObject()); - command += " \""; - command += fn.fullPathName(); - command += "\""; - MGlobal::executeCommandOnIdle(command, false); + if (resolution > 1024) { + resolution = 1024; } - } - else - { - int mods; - MString cmd = "getModifiers"; - MGlobal::executeCommand(cmd, mods); - - bool shiftHeld = (mods % 2); - bool ctrlHeld = (mods / 4 % 2); - MGlobal::ListAdjustment mode = MGlobal::kReplaceList; - if(shiftHeld && ctrlHeld) - mode = MGlobal::kAddToList; - else - if(ctrlHeld) - mode = MGlobal::kRemoveFromList; - else - if(shiftHeld) - mode = MGlobal::kXORWithList; - - SdfPathVector paths; - if (!hitBatch.empty()) - { - paths.reserve(hitBatch.size()); - - auto addHit = [&paths](Engine::HitBatch::const_reference& it) - { - paths.push_back(it.first); - }; - - // Do to the inaccuracies in the selection method in gl engine - // we still need to find the closest selection. - // Around the edges it often selects two or more prims. - if (selectInfo.singleSelection()) - { - auto closestHit = hitBatch.cbegin(); - - if (hitBatch.size() > 1) - { - MDagPath cameraPath; - selectInfo.view().getCamera(cameraPath); - const auto cameraPoint = cameraPath.inclusiveMatrix() * MPoint(0.0, 0.0, 0.0, 1.0); - auto distanceToCameraSq = [&cameraPoint] (Engine::HitBatch::const_reference& it) -> double - { - const auto dx = cameraPoint.x - it.second.worldSpaceHitPoint[0]; - const auto dy = cameraPoint.y - it.second.worldSpaceHitPoint[1]; - const auto dz = cameraPoint.z - it.second.worldSpaceHitPoint[2]; - return dx * dx + dy * dy + dz * dz; - }; - - auto closestDistance = distanceToCameraSq(*closestHit); - for (auto it = ++hitBatch.cbegin(), itEnd = hitBatch.cend(); it != itEnd; ++it) - { - const auto currentDistance = distanceToCameraSq(*it); - if (currentDistance < closestDistance) - { - closestDistance = currentDistance; - closestHit = it; + + bool hitSelected = engine->TestIntersectionBatch( + GfMatrix4d(viewMatrix.matrix), + GfMatrix4d(projectionMatrix.matrix), + worldToLocalSpace, + rootPath, + params, + resolution, + ProxyShapeSelectionHelper::path_ting, + &hitBatch); + + auto selected = false; + + auto addSelection = [&hitBatch, + &selectInfo, + &selectionList, + &worldSpaceSelectPoints, + &objectsMask, + &selected, + proxyShape](const MString& command) { + selected = true; + MStringArray nodes; + MGlobal::executeCommand(command, nodes, false, true); + + // If the selection is in a single selection mode, we don't know if your mesh + // will be the actual final selection, because we can't make sure this is going to + // be called the last. So we are returning a deferred command here, that'll run last. + // That'll check if the mesh is still selected, and run an internal deselect command on + // that. const auto singleSelection = selectInfo.singleSelection(); + + for (const auto& it : hitBatch) { + + // Retarget hit path based on pick mode policy. The retargeted prim must + // align with the path used in the 'AL_usdmaya_ProxyShapeSelect' command. + const SdfPath hitPath = it.first; + const UsdPrim retargetedHitPrim + = retargetSelectPrim(proxyShape->getUsdStage()->GetPrimAtPath(hitPath)); + const MObject obj = proxyShape->findRequiredPath(retargetedHitPrim.GetPath()); + + if (obj != MObject::kNullObj) { + MSelectionList sl; + MFnDagNode dagNode(obj); + MDagPath dg; + dagNode.getPath(dg); + sl.add(dg); + const double* d = it.second.worldSpaceHitPoint.GetArray(); + selectInfo.addSelection( + sl, + MPoint(d[0], d[1], d[2], 1.0), + selectionList, + worldSpaceSelectPoints, + objectsMask, + false); } - } - } - addHit(*closestHit); - } - else - { - for (const auto& it : hitBatch) - { - addHit(it); - } - } - } -#if defined(WANT_UFE_BUILD) - if (ArchHasEnv("MAYA_WANT_UFE_SELECTION")) { - Ufe::HierarchyHandler::Ptr handler = - Ufe::RunTimeMgr::instance().hierarchyHandler(USD_UFE_RUNTIME_ID); - if (handler == nullptr) { - MGlobal::displayError("USD Hierarchy handler has not been loaded - Picking is not possible"); - return false; } + }; + + // Currently we have two approaches to selection. One method works with undo (but does not + // play nicely with maya geometry). The second method doesn't work with undo, but does play + // nicely with maya geometry. + const int selectionMode = MGlobal::optionVarIntValue("AL_usdmaya_selectMode"); + if (1 == selectionMode) { + if (hitSelected) { + int mods; + MString cmd = "getModifiers"; + MGlobal::executeCommand(cmd, mods); + + bool shiftHeld = (mods % 2); + bool ctrlHeld = (mods / 4 % 2); + MGlobal::ListAdjustment mode = MGlobal::kReplaceList; + if (shiftHeld && ctrlHeld) + mode = MGlobal::kAddToList; + else if (ctrlHeld) + mode = MGlobal::kRemoveFromList; + else if (shiftHeld) + mode = MGlobal::kXORWithList; + + MString command = "AL_usdmaya_ProxyShapeSelect"; + switch (mode) { + case MGlobal::kReplaceList: command += " -r"; break; + case MGlobal::kRemoveFromList: command += " -d"; break; + case MGlobal::kXORWithList: command += " -tgl"; break; + case MGlobal::kAddToList: command += " -a"; break; + case MGlobal::kAddToHeadOfList: /* should never get here */ break; + } - Ufe::Selection dstSelection; // Only used for kReplaceList - // Get the paths - if (paths.size()) - { - for (const auto& it : paths) - { - // Build a path segment of the USD picked object - Ufe::PathSegment ps_usd(it.GetText(), USD_UFE_RUNTIME_ID, USD_UFE_SEPARATOR); - - // Create a sceneItem - const Ufe::SceneItem::Ptr& si{ handler->createItem(proxyShape->ufePath() + ps_usd) }; - - auto globalSelection = Ufe::GlobalSelection::get(); - - switch (mode) - { - case MGlobal::kReplaceList: - { - // Add the sceneItem to dstSelection - dstSelection.append(si); - } - break; - case MGlobal::kAddToList: - { - // Add the sceneItem to global selection - globalSelection->append(si); + for (const auto& it : hitBatch) { + auto path = it.first; + command += " -pp \""; + command += path.GetText(); + command += "\""; + } + + MFnDagNode fn(proxyShape->thisMObject()); + command += " \""; + command += fn.fullPathName(); + command += "\""; + MGlobal::executeCommandOnIdle(command, false); + } else { + MString command = "AL_usdmaya_ProxyShapeSelect -cl "; + MFnDagNode fn(proxyShape->thisMObject()); + command += " \""; + command += fn.fullPathName(); + command += "\""; + MGlobal::executeCommandOnIdle(command, false); + } + } else { + int mods; + MString cmd = "getModifiers"; + MGlobal::executeCommand(cmd, mods); + + bool shiftHeld = (mods % 2); + bool ctrlHeld = (mods / 4 % 2); + MGlobal::ListAdjustment mode = MGlobal::kReplaceList; + if (shiftHeld && ctrlHeld) + mode = MGlobal::kAddToList; + else if (ctrlHeld) + mode = MGlobal::kRemoveFromList; + else if (shiftHeld) + mode = MGlobal::kXORWithList; + + SdfPathVector paths; + if (!hitBatch.empty()) { + paths.reserve(hitBatch.size()); + + auto addHit + = [&paths](Engine::HitBatch::const_reference& it) { paths.push_back(it.first); }; + + // Do to the inaccuracies in the selection method in gl engine + // we still need to find the closest selection. + // Around the edges it often selects two or more prims. + if (selectInfo.singleSelection()) { + auto closestHit = hitBatch.cbegin(); + + if (hitBatch.size() > 1) { + MDagPath cameraPath; + selectInfo.view().getCamera(cameraPath); + const auto cameraPoint + = cameraPath.inclusiveMatrix() * MPoint(0.0, 0.0, 0.0, 1.0); + auto distanceToCameraSq + = [&cameraPoint](Engine::HitBatch::const_reference& it) -> double { + const auto dx = cameraPoint.x - it.second.worldSpaceHitPoint[0]; + const auto dy = cameraPoint.y - it.second.worldSpaceHitPoint[1]; + const auto dz = cameraPoint.z - it.second.worldSpaceHitPoint[2]; + return dx * dx + dy * dy + dz * dz; + }; + + auto closestDistance = distanceToCameraSq(*closestHit); + for (auto it = ++hitBatch.cbegin(), itEnd = hitBatch.cend(); it != itEnd; + ++it) { + const auto currentDistance = distanceToCameraSq(*it); + if (currentDistance < closestDistance) { + closestDistance = currentDistance; + closestHit = it; + } + } } - break; - case MGlobal::kRemoveFromList: - { - // Remove the sceneItem to global selection - globalSelection->remove(si); + addHit(*closestHit); + } else { + for (const auto& it : hitBatch) { + addHit(it); } - break; - case MGlobal::kXORWithList: - { - if (!globalSelection->remove(si)) { + } + } +#if defined(WANT_UFE_BUILD) + if (ArchHasEnv("MAYA_WANT_UFE_SELECTION")) { + Ufe::HierarchyHandler::Ptr handler + = Ufe::RunTimeMgr::instance().hierarchyHandler(USD_UFE_RUNTIME_ID); + if (handler == nullptr) { + MGlobal::displayError( + "USD Hierarchy handler has not been loaded - Picking is not possible"); + return false; + } + + Ufe::Selection dstSelection; // Only used for kReplaceList + // Get the paths + if (paths.size()) { + for (const auto& it : paths) { + // Build a path segment of the USD picked object + Ufe::PathSegment ps_usd(it.GetText(), USD_UFE_RUNTIME_ID, USD_UFE_SEPARATOR); + + // Create a sceneItem + const Ufe::SceneItem::Ptr& si { handler->createItem( + proxyShape->ufePath() + ps_usd) }; + + auto globalSelection = Ufe::GlobalSelection::get(); + + switch (mode) { + case MGlobal::kReplaceList: { + // Add the sceneItem to dstSelection + dstSelection.append(si); + } break; + case MGlobal::kAddToList: { + // Add the sceneItem to global selection globalSelection->append(si); + } break; + case MGlobal::kRemoveFromList: { + // Remove the sceneItem to global selection + globalSelection->remove(si); + } break; + case MGlobal::kXORWithList: { + if (!globalSelection->remove(si)) { + globalSelection->append(si); + } + } break; + case MGlobal::kAddToHeadOfList: { + // No such operation on UFE selection. + UFE_LOG("UFE does not support prepend to selection."); + } break; } } - break; - case MGlobal::kAddToHeadOfList: - { - // No such operation on UFE selection. - UFE_LOG("UFE does not support prepend to selection."); - } - break; - } - } - if (mode == MGlobal::kReplaceList) { - // Add to Global selection - Ufe::GlobalSelection::get()->replaceWith(dstSelection); + if (mode == MGlobal::kReplaceList) { + // Add to Global selection + Ufe::GlobalSelection::get()->replaceWith(dstSelection); + } } - } - } - else { + } else { #endif - // Massage hit paths to align with pick mode policy - for (std::size_t i = 0; i < paths.size(); ++i) - { - const SdfPath& path = paths[i]; - const UsdPrim retargetedPrim = retargetSelectPrim(proxyShape->getUsdStage()->GetPrimAtPath(path)); - if (retargetedPrim.GetPath() != path) - { - paths[i] = retargetedPrim.GetPath(); - } - } + // Massage hit paths to align with pick mode policy + for (std::size_t i = 0; i < paths.size(); ++i) { + const SdfPath& path = paths[i]; + const UsdPrim retargetedPrim + = retargetSelectPrim(proxyShape->getUsdStage()->GetPrimAtPath(path)); + if (retargetedPrim.GetPath() != path) { + paths[i] = retargetedPrim.GetPath(); + } + } - switch(mode) - { - case MGlobal::kReplaceList: - { - MString command; - if(!proxyShape->selectedPaths().empty()) - { - command = "AL_usdmaya_ProxyShapeSelect -i -cl "; - MFnDagNode fn(proxyShape->thisMObject()); - command += " \""; - command += fn.fullPathName(); - command += "\";"; - } + switch (mode) { + case MGlobal::kReplaceList: { + MString command; + if (!proxyShape->selectedPaths().empty()) { + command = "AL_usdmaya_ProxyShapeSelect -i -cl "; + MFnDagNode fn(proxyShape->thisMObject()); + command += " \""; + command += fn.fullPathName(); + command += "\";"; + } - if(!paths.empty()) - { - command += "AL_usdmaya_ProxyShapeSelect -i -a "; - for(const auto& it : paths) - { - command += " -pp \""; - command += it.GetText(); - command += "\""; - } - MFnDagNode fn(proxyShape->thisMObject()); - command += " \""; - command += fn.fullPathName(); - command += "\""; + if (!paths.empty()) { + command += "AL_usdmaya_ProxyShapeSelect -i -a "; + for (const auto& it : paths) { + command += " -pp \""; + command += it.GetText(); + command += "\""; + } + MFnDagNode fn(proxyShape->thisMObject()); + command += " \""; + command += fn.fullPathName(); + command += "\""; + } - } + if (command.length() > 0) { + addSelection(command); + } + } break; + + case MGlobal::kAddToHeadOfList: + case MGlobal::kAddToList: { + MString command; + if (paths.size()) { + command = "AL_usdmaya_ProxyShapeSelect -i -a "; + for (const auto& it : paths) { + command += " -pp \""; + command += it.GetText(); + command += "\""; + } + MFnDagNode fn(proxyShape->thisMObject()); + command += " \""; + command += fn.fullPathName(); + command += "\""; + } - if(command.length() > 0) - { - addSelection(command); - } - } - break; - - case MGlobal::kAddToHeadOfList: - case MGlobal::kAddToList: - { - MString command; - if(paths.size()) - { - command = "AL_usdmaya_ProxyShapeSelect -i -a "; - for(const auto& it : paths) - { - command += " -pp \""; - command += it.GetText(); - command += "\""; - } - MFnDagNode fn(proxyShape->thisMObject()); - command += " \""; - command += fn.fullPathName(); - command += "\""; - } + if (command.length() > 0) { + selected = true; + addSelection(command); + } + } break; + + case MGlobal::kRemoveFromList: { + if (!proxyShape->selectedPaths().empty() && paths.size()) { + MString command = "AL_usdmaya_ProxyShapeSelect -d "; + for (const auto& it : paths) { + command += " -pp \""; + command += it.GetText(); + command += "\""; + } + MFnDagNode fn(proxyShape->thisMObject()); + command += " \""; + command += fn.fullPathName(); + command += "\""; + MGlobal::executeCommandOnIdle(command, false); + } + } break; + + case MGlobal::kXORWithList: { + auto& slpaths = proxyShape->selectedPaths(); + bool hasSelectedItems = false; + bool hasDeletedItems = false; + + MString selectcommand = "AL_usdmaya_ProxyShapeSelect -i -a "; + MString deselectcommand = "AL_usdmaya_ProxyShapeSelect -d "; + for (const auto& it : paths) { + bool flag = false; + for (auto sit : slpaths) { + if (sit == it) { + flag = true; + break; + } + } + if (flag) { + deselectcommand += " -pp \""; + deselectcommand += it.GetText(); + deselectcommand += "\""; + hasDeletedItems = true; + } else { + selectcommand += " -pp \""; + selectcommand += it.GetText(); + selectcommand += "\""; + hasSelectedItems = true; + } + } + MFnDagNode fn(proxyShape->thisMObject()); + selectcommand += " \""; + selectcommand += fn.fullPathName(); + selectcommand += "\""; + deselectcommand += " \""; + deselectcommand += fn.fullPathName(); + deselectcommand += "\""; + + if (hasSelectedItems) { + addSelection(selectcommand); + } - if(command.length() > 0) - { - selected = true; - addSelection(command); - } - } - break; - - case MGlobal::kRemoveFromList: - { - if(!proxyShape->selectedPaths().empty() && paths.size()) - { - MString command = "AL_usdmaya_ProxyShapeSelect -d "; - for(const auto& it : paths) - { - command += " -pp \""; - command += it.GetText(); - command += "\""; - } - MFnDagNode fn(proxyShape->thisMObject()); - command += " \""; - command += fn.fullPathName(); - command += "\""; - MGlobal::executeCommandOnIdle(command, false); - } - } - break; - - case MGlobal::kXORWithList: - { - auto& slpaths = proxyShape->selectedPaths(); - bool hasSelectedItems = false; - bool hasDeletedItems = false; - - MString selectcommand = "AL_usdmaya_ProxyShapeSelect -i -a "; - MString deselectcommand = "AL_usdmaya_ProxyShapeSelect -d "; - for(const auto& it : paths) - { - bool flag = false; - for(auto sit : slpaths) - { - if(sit == it) - { - flag = true; - break; + if (hasDeletedItems) { + MGlobal::executeCommandOnIdle(deselectcommand, false); + } + } break; } - } - if(flag) - { - deselectcommand += " -pp \""; - deselectcommand += it.GetText(); - deselectcommand += "\""; - hasDeletedItems = true; - } - else - { - selectcommand += " -pp \""; - selectcommand += it.GetText(); - selectcommand += "\""; - hasSelectedItems = true; - } - } - MFnDagNode fn(proxyShape->thisMObject()); - selectcommand += " \""; - selectcommand += fn.fullPathName(); - selectcommand += "\""; - deselectcommand += " \""; - deselectcommand += fn.fullPathName(); - deselectcommand += "\""; - - if(hasSelectedItems) - { - addSelection(selectcommand); - } - - if(hasDeletedItems) - { - MGlobal::executeCommandOnIdle(deselectcommand, false); - } - } - break; - } - MString final_command = "AL_usdmaya_ProxyShapePostSelect \""; - MFnDagNode fn(proxyShape->thisMObject()); - final_command += fn.fullPathName(); - final_command += "\""; - proxyShape->setChangedSelectionState(true); - MGlobal::executeCommandOnIdle(final_command, false); + MString final_command = "AL_usdmaya_ProxyShapePostSelect \""; + MFnDagNode fn(proxyShape->thisMObject()); + final_command += fn.fullPathName(); + final_command += "\""; + proxyShape->setChangedSelectionState(true); + MGlobal::executeCommandOnIdle(final_command, false); #if defined(WANT_UFE_BUILD) - } // else MAYA_WANT_UFE_SELECTION + } // else MAYA_WANT_UFE_SELECTION #endif - } + } - ProxyShapeSelectionHelper::m_paths.clear(); + ProxyShapeSelectionHelper::m_paths.clear(); - // restore clear colour - glClearColor(clearCol[0], clearCol[1], clearCol[2], clearCol[3]); + // restore clear colour + glClearColor(clearCol[0], clearCol[1], clearCol[2], clearCol[3]); - return selected; + return selected; } - //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeUI.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeUI.h index 86a04bae2f..3fdab0acb4 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeUI.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyShapeUI.h @@ -27,42 +27,47 @@ namespace nodes { /// \brief The UI component of the proxy shape node /// \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- -class ProxyShapeUI - : public MPxSurfaceShapeUI +class ProxyShapeUI : public MPxSurfaceShapeUI { - public: +public: + /// \brief ctor + ProxyShapeUI(); - /// \brief ctor - ProxyShapeUI(); + /// \brief dtor + ~ProxyShapeUI(); - /// \brief dtor - ~ProxyShapeUI(); + /// \brief returns a new instance of this UI component + AL_USDMAYA_PUBLIC + static void* creator(); - /// \brief returns a new instance of this UI component - AL_USDMAYA_PUBLIC - static void* creator(); + /// \brief legacy VP1 rendering interface + /// \param drawInfo Drawing state information. + /// \param isObjectAndActiveOnly Used to determine if draw requests for components need to be + /// supplied. If false, some + /// or all components are active and draw requests must be built for all components. + /// \param requests Queue on which to place the draw request. + void getDrawRequests( + const MDrawInfo& drawInfo, + bool isObjectAndActiveOnly, + MDrawRequestQueue& requests) override; - /// \brief legacy VP1 rendering interface - /// \param drawInfo Drawing state information. - /// \param isObjectAndActiveOnly Used to determine if draw requests for components need to be supplied. If false, some - /// or all components are active and draw requests must be built for all components. - /// \param requests Queue on which to place the draw request. - void getDrawRequests(const MDrawInfo& drawInfo, bool isObjectAndActiveOnly, MDrawRequestQueue& requests) override; + /// \param request the drawing request + /// \param view the interactive 3d view in which to draw + void draw(const MDrawRequest& request, M3dView& view) const override; - /// \param request the drawing request - /// \param view the interactive 3d view in which to draw - void draw(const MDrawRequest& request, M3dView& view) const override; - - /// \brief used to select the proxy shape - /// \param selectInfo the Selection state information. - /// \param selectionList List of items selected by this method. - /// \param worldSpaceSelectPts List of points used to sort corresponding selections in single-select mode. - /// \return true if something was selected, false otherwise - bool select(MSelectInfo& selectInfo, MSelectionList& selectionList, MPointArray& worldSpaceSelectPts) const override; + /// \brief used to select the proxy shape + /// \param selectInfo the Selection state information. + /// \param selectionList List of items selected by this method. + /// \param worldSpaceSelectPts List of points used to sort corresponding selections in + /// single-select mode. \return true if something was selected, false otherwise + bool select( + MSelectInfo& selectInfo, + MSelectionList& selectionList, + MPointArray& worldSpaceSelectPts) const override; }; //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyUsdGeomCamera.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyUsdGeomCamera.cpp index 18afad6e0d..1d649096bd 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyUsdGeomCamera.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyUsdGeomCamera.cpp @@ -15,25 +15,25 @@ // #include "ProxyUsdGeomCamera.h" -#include +#include "AL/usdmaya/TypeIDs.h" + +#include +#include + +#include +#include +#include +#include + #include #include #include -#include #include +#include +#include +#include #include #include -#include - -#include -#include -#include -#include - -#include "AL/usdmaya/TypeIDs.h" -#include - -#include namespace AL { namespace usdmaya { @@ -72,577 +72,536 @@ MObject ProxyUsdGeomCamera::m_verticalFilmOffset = MObject::kNullObj; UsdGeomCamera ProxyUsdGeomCamera::getCamera() const { - MStatus status; - MPlug stagePlug(thisMObject(), m_stage); - MObject stageObject; - status = stagePlug.getValue(stageObject); - AL_MAYA_CHECK_ERROR2(status, "Failed to get 'stage' attr"); - - if (status == MStatus::kSuccess ) - { - // Pull in stage data - MFnPluginData fnData(stageObject); - - auto* stageData = static_cast(fnData.data()); - if (stageData != nullptr) - { - // Get prim path - MPlug pathPlug(thisMObject(), m_path); - MString path; - status = pathPlug.getValue(path); - AL_MAYA_CHECK_ERROR2(status, "Failed to get 'path' attr"); - - return UsdGeomCamera(stageData->stage->GetPrimAtPath(SdfPath(path.asChar()))); + MStatus status; + MPlug stagePlug(thisMObject(), m_stage); + MObject stageObject; + status = stagePlug.getValue(stageObject); + AL_MAYA_CHECK_ERROR2(status, "Failed to get 'stage' attr"); + + if (status == MStatus::kSuccess) { + // Pull in stage data + MFnPluginData fnData(stageObject); + + auto* stageData = static_cast(fnData.data()); + if (stageData != nullptr) { + // Get prim path + MPlug pathPlug(thisMObject(), m_path); + MString path; + status = pathPlug.getValue(path); + AL_MAYA_CHECK_ERROR2(status, "Failed to get 'path' attr"); + + return UsdGeomCamera(stageData->stage->GetPrimAtPath(SdfPath(path.asChar()))); + } } - } - return UsdGeomCamera(); + return UsdGeomCamera(); } UsdTimeCode ProxyUsdGeomCamera::getTime() const { - MTime time; - MPlug(thisMObject(), m_time).getValue(time); - return UsdTimeCode(time.as(MTime::uiUnit())); + MTime time; + MPlug(thisMObject(), m_time).getValue(time); + return UsdTimeCode(time.as(MTime::uiUnit())); } // USD -> Maya -bool ProxyUsdGeomCamera::getInternalValue(const MPlug &plug, MDataHandle &dataHandle) +bool ProxyUsdGeomCamera::getInternalValue(const MPlug& plug, MDataHandle& dataHandle) { - const float mm_to_inches = 0.0393701f; - - MStatus status; - bool handledAttribute = false; - - UsdTimeCode usdTime(getTime()); - - const UsdGeomCamera camera(getCamera()); - if(!camera) - return false; - - if (plug == m_nearClipPlane) - { - const UsdAttribute attr(camera.CreateClippingRangeAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - GfVec2f value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setMDistance(MDistance(value[0], MDistance::kCentimeters)); - handledAttribute = true; - } - } - else if (plug == m_farClipPlane) - { - const UsdAttribute attr(camera.GetClippingRangeAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - GfVec2f value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setMDistance(MDistance(value[1], MDistance::kCentimeters)); - handledAttribute = true; - } - } - else if (plug == m_focalLength) - { - const UsdAttribute attr(camera.GetFocalLengthAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - float value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setFloat(value); - handledAttribute = true; - } - } - else if (plug == m_focusDistance) - { - const UsdAttribute attr(camera.GetFocusDistanceAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - float value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setMDistance(MDistance(value, MDistance::kCentimeters)); - handledAttribute = true; - } - } - else if (plug == m_fStop) - { - const UsdAttribute attr(camera.GetFStopAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - float value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setFloat(value); - handledAttribute = true; - } - } - else if (plug == m_horizontalAperture) - { - const UsdAttribute attr(camera.GetHorizontalApertureAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - float value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setFloat(value); - handledAttribute = true; - } - } - else if (plug == m_horizontalFilmAperture) - { - const UsdAttribute attr(camera.GetHorizontalApertureAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - float value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setDouble((double)(mm_to_inches * value)); - handledAttribute = true; - } - } - else if (plug == m_horizontalApertureOffset) - { - const UsdAttribute attr(camera.GetHorizontalApertureOffsetAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - float value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setFloat(value); - handledAttribute = true; - } - } - else if (plug == m_horizontalFilmOffset) - { - const UsdAttribute attr(camera.GetHorizontalApertureOffsetAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - float value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setDouble((double)(mm_to_inches * value)); - handledAttribute = true; - } - } - else if (plug == m_projection) - { - const UsdAttribute attr(camera.GetProjectionAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - TfToken value; - if (attr.Get(&value, usdTime)) - { - if (value == UsdGeomTokens->perspective) - { - dataHandle.setShort(TO_MAYA_ENUM(Projection::Perspective)); - handledAttribute = true; - } - else if (value == UsdGeomTokens->orthographic) - { - dataHandle.setShort(TO_MAYA_ENUM(Projection::Orthographic)); - handledAttribute = true; - } + const float mm_to_inches = 0.0393701f; + + MStatus status; + bool handledAttribute = false; + + UsdTimeCode usdTime(getTime()); + + const UsdGeomCamera camera(getCamera()); + if (!camera) + return false; + + if (plug == m_nearClipPlane) { + const UsdAttribute attr(camera.CreateClippingRangeAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + GfVec2f value; + if (attr.Get(&value, usdTime)) { + dataHandle.setMDistance(MDistance(value[0], MDistance::kCentimeters)); + handledAttribute = true; + } + } else if (plug == m_farClipPlane) { + const UsdAttribute attr(camera.GetClippingRangeAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + GfVec2f value; + if (attr.Get(&value, usdTime)) { + dataHandle.setMDistance(MDistance(value[1], MDistance::kCentimeters)); + handledAttribute = true; + } + } else if (plug == m_focalLength) { + const UsdAttribute attr(camera.GetFocalLengthAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + float value; + if (attr.Get(&value, usdTime)) { + dataHandle.setFloat(value); + handledAttribute = true; + } + } else if (plug == m_focusDistance) { + const UsdAttribute attr(camera.GetFocusDistanceAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + float value; + if (attr.Get(&value, usdTime)) { + dataHandle.setMDistance(MDistance(value, MDistance::kCentimeters)); + handledAttribute = true; + } + } else if (plug == m_fStop) { + const UsdAttribute attr(camera.GetFStopAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + float value; + if (attr.Get(&value, usdTime)) { + dataHandle.setFloat(value); + handledAttribute = true; + } + } else if (plug == m_horizontalAperture) { + const UsdAttribute attr(camera.GetHorizontalApertureAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + float value; + if (attr.Get(&value, usdTime)) { + dataHandle.setFloat(value); + handledAttribute = true; + } + } else if (plug == m_horizontalFilmAperture) { + const UsdAttribute attr(camera.GetHorizontalApertureAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + float value; + if (attr.Get(&value, usdTime)) { + dataHandle.setDouble((double)(mm_to_inches * value)); + handledAttribute = true; + } + } else if (plug == m_horizontalApertureOffset) { + const UsdAttribute attr(camera.GetHorizontalApertureOffsetAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + float value; + if (attr.Get(&value, usdTime)) { + dataHandle.setFloat(value); + handledAttribute = true; + } + } else if (plug == m_horizontalFilmOffset) { + const UsdAttribute attr(camera.GetHorizontalApertureOffsetAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + float value; + if (attr.Get(&value, usdTime)) { + dataHandle.setDouble((double)(mm_to_inches * value)); + handledAttribute = true; + } + } else if (plug == m_projection) { + const UsdAttribute attr(camera.GetProjectionAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + TfToken value; + if (attr.Get(&value, usdTime)) { + if (value == UsdGeomTokens->perspective) { + dataHandle.setShort(TO_MAYA_ENUM(Projection::Perspective)); + handledAttribute = true; + } else if (value == UsdGeomTokens->orthographic) { + dataHandle.setShort(TO_MAYA_ENUM(Projection::Orthographic)); + handledAttribute = true; + } + } + } else if (plug == m_orthographic) { + const UsdAttribute attr(camera.GetProjectionAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + TfToken value; + if (attr.Get(&value, usdTime)) { + const bool orthographic = value == UsdGeomTokens->orthographic; + dataHandle.setBool(orthographic); + handledAttribute = true; + } + } else if (plug == m_shutterClose) { + const UsdAttribute attr(camera.GetShutterCloseAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + double value; + if (attr.Get(&value, usdTime)) { + dataHandle.setDouble(value); + handledAttribute = true; + } + } else if (plug == m_shutterOpen) { + const UsdAttribute attr(camera.GetShutterOpenAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + double value; + if (attr.Get(&value, usdTime)) { + dataHandle.setDouble(value); + handledAttribute = true; + } + } else if (plug == m_stereoRole) { + const UsdAttribute attr(camera.GetStereoRoleAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + TfToken value; + if (attr.Get(&value, usdTime)) { + if (value == UsdGeomTokens->mono) { + dataHandle.setShort(TO_MAYA_ENUM(StereoRole::Mono)); + handledAttribute = true; + } else if (value == UsdGeomTokens->left) { + dataHandle.setShort(TO_MAYA_ENUM(StereoRole::Left)); + handledAttribute = true; + } else if (value == UsdGeomTokens->right) { + dataHandle.setShort(TO_MAYA_ENUM(StereoRole::Right)); + handledAttribute = true; + } + } + } else if (plug == m_verticalAperture) { + const UsdAttribute attr(camera.GetVerticalApertureAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + float value; + if (attr.Get(&value, usdTime)) { + dataHandle.setFloat(value); + handledAttribute = true; + } + } else if (plug == m_verticalFilmAperture) { + const UsdAttribute attr(camera.GetVerticalApertureAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + float value; + if (attr.Get(&value, usdTime)) { + dataHandle.setDouble((double)(mm_to_inches * value)); + handledAttribute = true; + } + } else if (plug == m_verticalApertureOffset) { + const UsdAttribute attr(camera.GetVerticalApertureOffsetAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + float value; + if (attr.Get(&value, usdTime)) { + dataHandle.setFloat(value); + handledAttribute = true; + } + } else if (plug == m_verticalFilmOffset) { + const UsdAttribute attr(camera.GetVerticalApertureOffsetAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + float value; + if (attr.Get(&value, usdTime)) { + dataHandle.setDouble((double)(mm_to_inches * value)); + handledAttribute = true; + } } - } - else if (plug == m_orthographic) - { - const UsdAttribute attr(camera.GetProjectionAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - TfToken value; - if (attr.Get(&value, usdTime)) - { - const bool orthographic = value == UsdGeomTokens->orthographic; - dataHandle.setBool(orthographic); - handledAttribute = true; - } - } - else if (plug == m_shutterClose) - { - const UsdAttribute attr(camera.GetShutterCloseAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - double value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setDouble(value); - handledAttribute = true; - } - } - else if (plug == m_shutterOpen) - { - const UsdAttribute attr(camera.GetShutterOpenAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - double value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setDouble(value); - handledAttribute = true; - } - } - else if (plug == m_stereoRole) - { - const UsdAttribute attr(camera.GetStereoRoleAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - TfToken value; - if (attr.Get(&value, usdTime)) - { - if (value == UsdGeomTokens->mono) - { - dataHandle.setShort(TO_MAYA_ENUM(StereoRole::Mono)); - handledAttribute = true; - } - else if (value == UsdGeomTokens->left) - { - dataHandle.setShort(TO_MAYA_ENUM(StereoRole::Left)); - handledAttribute = true; - } - else if (value == UsdGeomTokens->right) - { - dataHandle.setShort(TO_MAYA_ENUM(StereoRole::Right)); - handledAttribute = true; - } - } - } - else if (plug == m_verticalAperture) - { - const UsdAttribute attr(camera.GetVerticalApertureAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - float value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setFloat(value); - handledAttribute = true; - } - } - else if (plug == m_verticalFilmAperture) - { - const UsdAttribute attr(camera.GetVerticalApertureAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - float value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setDouble((double)(mm_to_inches * value)); - handledAttribute = true; - } - } - else if (plug == m_verticalApertureOffset) - { - const UsdAttribute attr(camera.GetVerticalApertureOffsetAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - float value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setFloat(value); - handledAttribute = true; - } - } - else if (plug == m_verticalFilmOffset) - { - const UsdAttribute attr(camera.GetVerticalApertureOffsetAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - float value; - if (attr.Get(&value, usdTime)) - { - dataHandle.setDouble((double)(mm_to_inches * value)); - handledAttribute = true; - } - } - return handledAttribute; + return handledAttribute; } // Maya -> USD -bool ProxyUsdGeomCamera::setInternalValue(const MPlug &plug, const MDataHandle &dataHandle) +bool ProxyUsdGeomCamera::setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) { - const float inches_to_mm = 1.0f / 0.0393701f; - - bool handledAttribute = false; - MStatus status; - - UsdTimeCode usdTime(getTime()); - - const UsdGeomCamera camera(getCamera()); - if(!camera) - return false; - - if (plug == m_nearClipPlane) - { - const UsdAttribute attr(camera.CreateClippingRangeAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - GfVec2f usdValue; - if (!attr.Get(&usdValue, usdTime)) - usdValue = GfVec2f(0.1f, 10000.0f); - - usdValue[0] = dataHandle.asDistance().value(); - handledAttribute = attr.Set(VtValue(usdValue), usdTime); - } - else if (plug == m_farClipPlane) - { - const UsdAttribute attr(camera.CreateClippingRangeAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - GfVec2f usdValue; - if (!attr.Get(&usdValue, usdTime)) - usdValue = GfVec2f(0.1f, 10000.0f); - - usdValue[1] = dataHandle.asDistance().value(); - handledAttribute = attr.Set(VtValue(usdValue), usdTime); - } - else if (plug == m_focalLength) - { - const UsdAttribute attr(camera.CreateFocalLengthAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); - } - else if (plug == m_focusDistance) - { - const UsdAttribute attr(camera.CreateFocusDistanceAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set((float)dataHandle.asDistance().value(), usdTime); - } - else if (plug == m_fStop) - { - const UsdAttribute attr(camera.CreateFStopAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); - } - else if (plug == m_horizontalAperture) - { - const UsdAttribute attr(camera.CreateHorizontalApertureAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); - } - else if (plug == m_horizontalFilmAperture) - { - const UsdAttribute attr(camera.CreateHorizontalApertureAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set((float)(inches_to_mm * dataHandle.asDouble()), usdTime); - } - else if (plug == m_horizontalApertureOffset) - { - const UsdAttribute attr(camera.CreateHorizontalApertureOffsetAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); - } - else if (plug == m_horizontalFilmOffset) - { - const UsdAttribute attr(camera.CreateHorizontalApertureOffsetAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set((float)(inches_to_mm * dataHandle.asDouble()), usdTime); - } - else if (plug == m_projection) - { - const UsdAttribute attr(camera.CreateProjectionAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - Projection mode = static_cast(dataHandle.asShort()); - switch(mode) - { - case (Projection::Perspective): - handledAttribute = attr.Set(UsdGeomTokens->perspective, usdTime); - break; - case (Projection::Orthographic): - handledAttribute = attr.Set(UsdGeomTokens->orthographic, usdTime); - break; - } - } - else if (plug == m_orthographic) - { - const UsdAttribute attr(camera.CreateProjectionAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - const bool orthographic = dataHandle.asBool(); - if (orthographic) - handledAttribute = attr.Set(UsdGeomTokens->orthographic, usdTime); - else - handledAttribute = attr.Set(UsdGeomTokens->perspective, usdTime); - } - else if (plug == m_shutterClose) - { - const UsdAttribute attr(camera.CreateShutterCloseAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set(dataHandle.asDouble(), usdTime); - } - else if (plug == m_shutterOpen) - { - const UsdAttribute attr(camera.CreateShutterOpenAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set(dataHandle.asDouble(), usdTime); - } - else if (plug == m_stereoRole) - { - const UsdAttribute attr(camera.CreateStereoRoleAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - StereoRole mode = static_cast(dataHandle.asShort()); - switch(mode) - { - case (StereoRole::Mono): - handledAttribute = attr.Set(UsdGeomTokens->mono, usdTime); - break; - case (StereoRole::Left): - handledAttribute = attr.Set(UsdGeomTokens->left, usdTime); - break; - case (StereoRole::Right): - handledAttribute = attr.Set(UsdGeomTokens->right, usdTime); - break; + const float inches_to_mm = 1.0f / 0.0393701f; + + bool handledAttribute = false; + MStatus status; + + UsdTimeCode usdTime(getTime()); + + const UsdGeomCamera camera(getCamera()); + if (!camera) + return false; + + if (plug == m_nearClipPlane) { + const UsdAttribute attr(camera.CreateClippingRangeAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + GfVec2f usdValue; + if (!attr.Get(&usdValue, usdTime)) + usdValue = GfVec2f(0.1f, 10000.0f); + + usdValue[0] = dataHandle.asDistance().value(); + handledAttribute = attr.Set(VtValue(usdValue), usdTime); + } else if (plug == m_farClipPlane) { + const UsdAttribute attr(camera.CreateClippingRangeAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + GfVec2f usdValue; + if (!attr.Get(&usdValue, usdTime)) + usdValue = GfVec2f(0.1f, 10000.0f); + + usdValue[1] = dataHandle.asDistance().value(); + handledAttribute = attr.Set(VtValue(usdValue), usdTime); + } else if (plug == m_focalLength) { + const UsdAttribute attr(camera.CreateFocalLengthAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); + } else if (plug == m_focusDistance) { + const UsdAttribute attr(camera.CreateFocusDistanceAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set((float)dataHandle.asDistance().value(), usdTime); + } else if (plug == m_fStop) { + const UsdAttribute attr(camera.CreateFStopAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); + } else if (plug == m_horizontalAperture) { + const UsdAttribute attr(camera.CreateHorizontalApertureAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); + } else if (plug == m_horizontalFilmAperture) { + const UsdAttribute attr(camera.CreateHorizontalApertureAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set((float)(inches_to_mm * dataHandle.asDouble()), usdTime); + } else if (plug == m_horizontalApertureOffset) { + const UsdAttribute attr(camera.CreateHorizontalApertureOffsetAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); + } else if (plug == m_horizontalFilmOffset) { + const UsdAttribute attr(camera.CreateHorizontalApertureOffsetAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set((float)(inches_to_mm * dataHandle.asDouble()), usdTime); + } else if (plug == m_projection) { + const UsdAttribute attr(camera.CreateProjectionAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + Projection mode = static_cast(dataHandle.asShort()); + switch (mode) { + case (Projection::Perspective): + handledAttribute = attr.Set(UsdGeomTokens->perspective, usdTime); + break; + case (Projection::Orthographic): + handledAttribute = attr.Set(UsdGeomTokens->orthographic, usdTime); + break; + } + } else if (plug == m_orthographic) { + const UsdAttribute attr(camera.CreateProjectionAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + const bool orthographic = dataHandle.asBool(); + if (orthographic) + handledAttribute = attr.Set(UsdGeomTokens->orthographic, usdTime); + else + handledAttribute = attr.Set(UsdGeomTokens->perspective, usdTime); + } else if (plug == m_shutterClose) { + const UsdAttribute attr(camera.CreateShutterCloseAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set(dataHandle.asDouble(), usdTime); + } else if (plug == m_shutterOpen) { + const UsdAttribute attr(camera.CreateShutterOpenAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set(dataHandle.asDouble(), usdTime); + } else if (plug == m_stereoRole) { + const UsdAttribute attr(camera.CreateStereoRoleAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + StereoRole mode = static_cast(dataHandle.asShort()); + switch (mode) { + case (StereoRole::Mono): handledAttribute = attr.Set(UsdGeomTokens->mono, usdTime); break; + case (StereoRole::Left): handledAttribute = attr.Set(UsdGeomTokens->left, usdTime); break; + case (StereoRole::Right): handledAttribute = attr.Set(UsdGeomTokens->right, usdTime); break; + } + } else if (plug == m_verticalAperture) { + const UsdAttribute attr(camera.CreateVerticalApertureAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); + } else if (plug == m_verticalFilmAperture) { + const UsdAttribute attr(camera.CreateVerticalApertureAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set((float)(inches_to_mm * dataHandle.asDouble()), usdTime); + } else if (plug == m_verticalApertureOffset) { + const UsdAttribute attr(camera.CreateVerticalApertureOffsetAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); + } else if (plug == m_verticalFilmOffset) { + const UsdAttribute attr(camera.CreateVerticalApertureOffsetAttr()); + if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) + usdTime = UsdTimeCode::Default(); + handledAttribute = attr.Set((float)(inches_to_mm * dataHandle.asDouble()), usdTime); } - } - else if (plug == m_verticalAperture) - { - const UsdAttribute attr(camera.CreateVerticalApertureAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); - } - else if (plug == m_verticalFilmAperture) - { - const UsdAttribute attr(camera.CreateVerticalApertureAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set((float)(inches_to_mm * dataHandle.asDouble()), usdTime); - } - else if (plug == m_verticalApertureOffset) - { - const UsdAttribute attr(camera.CreateVerticalApertureOffsetAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set(dataHandle.asFloat(), usdTime); - } - else if (plug == m_verticalFilmOffset) - { - const UsdAttribute attr(camera.CreateVerticalApertureOffsetAttr()); - if (attr.GetVariability() != SdfVariability::SdfVariabilityVarying) usdTime = UsdTimeCode::Default(); - handledAttribute = attr.Set((float)(inches_to_mm * dataHandle.asDouble()), usdTime); - } - - return handledAttribute; + + return handledAttribute; } MStatus ProxyUsdGeomCamera::initialise() { - setNodeType(kTypeName); - - const uint32_t defaultFlags = kReadable | kWritable | kConnectable | kInternal; - const uint32_t readOnlyFlags = kReadable | kConnectable | kInternal; - - addFrame("USD Prim"); - - m_path = addStringAttr("path", "p", "", kStorable | kWritable); - - m_stage = addDataAttr("stage", "s", MayaUsdStageData::mayaTypeId, kWritable | kHidden | kConnectable, MFnNumericAttribute::kReset); - - m_time = addTimeAttr("time", "tm", MTime(0.0), kCached | kConnectable | kReadable | kWritable | kHidden | kStorable | kAffectsAppearance); - - // Hidden attributes for connecting to the maya camera attributes. - - m_orthographic = addBoolAttr("orthographic", "o", false, readOnlyFlags); - attributeAffects(m_path, m_orthographic); - - addFrame("Camera Attributes"); - - const char* const projectionKeys[] = { "Perspective", "Orthographic", nullptr }; - const int16_t projectionValues[] = { TO_MAYA_ENUM(Projection::Perspective), TO_MAYA_ENUM(Projection::Orthographic) }; - m_projection = addEnumAttr("projection", "pron", defaultFlags, projectionKeys, projectionValues); - MFnEnumAttribute(m_projection).setDefault(TO_MAYA_ENUM(Projection::Perspective)); - attributeAffects(m_path, m_projection); - - const char* const stereoRoleKeys[] = { "Mono", "Left", "Right", nullptr }; - const int16_t stereoRoleValues[] = { TO_MAYA_ENUM(StereoRole::Mono), TO_MAYA_ENUM(StereoRole::Left), TO_MAYA_ENUM(StereoRole::Right) }; - m_stereoRole = addEnumAttr("stereoRole", "stee", defaultFlags, stereoRoleKeys, stereoRoleValues); - MFnEnumAttribute(m_stereoRole).setDefault(TO_MAYA_ENUM(StereoRole::Mono)); - attributeAffects(m_path, m_stereoRole); - - m_focalLength = addFloatAttr("focalLength", "fl", 50.0f, defaultFlags); - MFnNumericAttribute(m_focalLength).setMin(2.5f); - MFnNumericAttribute(m_focalLength).setMax(100000.0f); - MFnNumericAttribute(m_focalLength).setSoftMax(400.0f); - attributeAffects(m_path, m_focalLength); - - m_nearClipPlane = addDistanceAttr("nearClipPlane", "ncp", MDistance(0.1, MDistance::kCentimeters), defaultFlags | kHidden); - MFnNumericAttribute(m_nearClipPlane).setMin(0.001); - attributeAffects(m_path, m_nearClipPlane); - - m_farClipPlane = addDistanceAttr("farClipPlane", "fcp", MDistance(10000.0, MDistance::kCentimeters), defaultFlags | kHidden); - MFnNumericAttribute(m_farClipPlane).setMin(0.001); - attributeAffects(m_path, m_farClipPlane); - - m_clippingRange = addCompoundAttr("clippingRange", "cr", defaultFlags, { m_nearClipPlane, m_farClipPlane }); - MFnAttribute(m_clippingRange).setNiceNameOverride("Clipping Range"); - - addFrame("Film Back"); - - m_horizontalFilmAperture = addDoubleAttr("horizontalFilmAperture", "hfa", 0.0, defaultFlags | kHidden); - MFnAttribute(m_horizontalFilmAperture).setNiceNameOverride("Horizontal Aperture (inch)"); - MFnNumericAttribute(m_horizontalFilmAperture).setMin(0.001f); - attributeAffects(m_path, m_horizontalFilmAperture); - - m_verticalFilmAperture = addDoubleAttr("verticalFilmAperture", "vfa", 0.0, defaultFlags | kHidden); - MFnAttribute(m_verticalFilmAperture).setNiceNameOverride("Horizontal Aperture Offset (inch)"); - MFnNumericAttribute(m_verticalFilmAperture).setMin(0.001f); - attributeAffects(m_path, m_verticalFilmAperture); - - m_cameraApertureInch = addCompoundAttr("cameraAperture", "cap", defaultFlags, { m_horizontalFilmAperture, m_verticalFilmAperture }); - MFnAttribute(m_cameraApertureInch).setNiceNameOverride("Camera Aperture (inch)"); - - m_horizontalAperture = addFloatAttr("horizontalAperture", "ha", 36.0f, readOnlyFlags | kHidden); - MFnAttribute(m_horizontalAperture).setNiceNameOverride("Horizontal Aperture (mm)"); - MFnNumericAttribute(m_horizontalAperture).setMin(0.001f); - attributeAffects(m_path, m_horizontalAperture); - - m_verticalAperture = addFloatAttr("verticalAperture", "va", 24.0f, readOnlyFlags | kHidden); - MFnAttribute(m_verticalAperture).setNiceNameOverride("Vertical Aperture (mm)"); - MFnNumericAttribute(m_verticalAperture).setMin(0.001f); - attributeAffects(m_path, m_verticalAperture); - - m_cameraApertureMm = addCompoundAttr("cameraApertureMm", "capm", defaultFlags, { m_horizontalAperture, m_verticalAperture }); - MFnAttribute(m_cameraApertureMm).setNiceNameOverride("Camera Aperture (mm)"); - - m_horizontalFilmOffset = addDoubleAttr("horizontalFilmOffset", "hfo", 0.0, defaultFlags | kHidden); - MFnAttribute(m_horizontalFilmOffset).setNiceNameOverride("Vertical Aperture (inch)"); - attributeAffects(m_path, m_horizontalFilmOffset); - - m_verticalFilmOffset = addDoubleAttr("verticalFilmOffset", "vfo", 0.0, defaultFlags | kHidden); - MFnAttribute(m_verticalFilmOffset).setNiceNameOverride("Vertical Aperture Offset (inch)"); - attributeAffects(m_path, m_verticalFilmOffset); - - m_filmOffset = addCompoundAttr("filmOffset", "fio", defaultFlags, { m_horizontalFilmOffset, m_verticalFilmOffset }); - MFnAttribute(m_filmOffset).setNiceNameOverride("Film Offset (inch)"); - - m_horizontalApertureOffset = addFloatAttr("horizontalApertureOffset", "hao", 0.0f, readOnlyFlags | kHidden); - MFnAttribute(m_horizontalApertureOffset).setNiceNameOverride("Horizontal Aperture Offset (mm)"); - attributeAffects(m_path, m_horizontalApertureOffset); - - m_verticalApertureOffset = addFloatAttr("verticalApertureOffset", "vao", 0.0f, readOnlyFlags | kHidden); - MFnAttribute(m_verticalApertureOffset).setNiceNameOverride("Vertical Aperture Offset (mm)"); - attributeAffects(m_path, m_verticalApertureOffset); - - addFrame("Depth of Field"); - - m_focusDistance = addDistanceAttr("focusDistance", "fd", MDistance(5.0, MDistance::kCentimeters), defaultFlags); - MFnNumericAttribute(m_focusDistance).setMin(0.0); - attributeAffects(m_path, m_focusDistance); - - m_fStop = addFloatAttr("fStop", "fs", 5.6f, defaultFlags); - MFnNumericAttribute(m_fStop).setMin(1.0f); - MFnNumericAttribute(m_fStop).setMax(64.0f); - attributeAffects(m_path, m_fStop); - - addFrame("Motion Blur"); - - m_shutterOpen = addDoubleAttr("shutterOpen", "shun", 0.0, defaultFlags); - attributeAffects(m_path, m_shutterOpen); - - m_shutterClose = addDoubleAttr("shutterClose", "shue", 0.0, defaultFlags); - attributeAffects(m_path, m_shutterClose); - - // Translation Attribute Connections - - attributeAffects(m_projection, m_orthographic); - attributeAffects(m_orthographic, m_projection); - - attributeAffects(m_horizontalAperture, m_horizontalFilmAperture); - attributeAffects(m_horizontalFilmAperture, m_horizontalAperture); - attributeAffects(m_horizontalApertureOffset, m_horizontalFilmOffset); - attributeAffects(m_horizontalFilmOffset, m_horizontalApertureOffset); - - attributeAffects(m_verticalAperture, m_verticalFilmAperture); - attributeAffects(m_verticalFilmAperture, m_verticalAperture); - attributeAffects(m_verticalApertureOffset, m_verticalFilmOffset); - attributeAffects(m_verticalFilmOffset, m_verticalApertureOffset); - - generateAETemplate(); - - return MStatus::kSuccess; + setNodeType(kTypeName); + + const uint32_t defaultFlags = kReadable | kWritable | kConnectable | kInternal; + const uint32_t readOnlyFlags = kReadable | kConnectable | kInternal; + + addFrame("USD Prim"); + + m_path = addStringAttr("path", "p", "", kStorable | kWritable); + + m_stage = addDataAttr( + "stage", + "s", + MayaUsdStageData::mayaTypeId, + kWritable | kHidden | kConnectable, + MFnNumericAttribute::kReset); + + m_time = addTimeAttr( + "time", + "tm", + MTime(0.0), + kCached | kConnectable | kReadable | kWritable | kHidden | kStorable | kAffectsAppearance); + + // Hidden attributes for connecting to the maya camera attributes. + + m_orthographic = addBoolAttr("orthographic", "o", false, readOnlyFlags); + attributeAffects(m_path, m_orthographic); + + addFrame("Camera Attributes"); + + const char* const projectionKeys[] = { "Perspective", "Orthographic", nullptr }; + const int16_t projectionValues[] + = { TO_MAYA_ENUM(Projection::Perspective), TO_MAYA_ENUM(Projection::Orthographic) }; + m_projection + = addEnumAttr("projection", "pron", defaultFlags, projectionKeys, projectionValues); + MFnEnumAttribute(m_projection).setDefault(TO_MAYA_ENUM(Projection::Perspective)); + attributeAffects(m_path, m_projection); + + const char* const stereoRoleKeys[] = { "Mono", "Left", "Right", nullptr }; + const int16_t stereoRoleValues[] = { TO_MAYA_ENUM(StereoRole::Mono), + TO_MAYA_ENUM(StereoRole::Left), + TO_MAYA_ENUM(StereoRole::Right) }; + m_stereoRole + = addEnumAttr("stereoRole", "stee", defaultFlags, stereoRoleKeys, stereoRoleValues); + MFnEnumAttribute(m_stereoRole).setDefault(TO_MAYA_ENUM(StereoRole::Mono)); + attributeAffects(m_path, m_stereoRole); + + m_focalLength = addFloatAttr("focalLength", "fl", 50.0f, defaultFlags); + MFnNumericAttribute(m_focalLength).setMin(2.5f); + MFnNumericAttribute(m_focalLength).setMax(100000.0f); + MFnNumericAttribute(m_focalLength).setSoftMax(400.0f); + attributeAffects(m_path, m_focalLength); + + m_nearClipPlane = addDistanceAttr( + "nearClipPlane", "ncp", MDistance(0.1, MDistance::kCentimeters), defaultFlags | kHidden); + MFnNumericAttribute(m_nearClipPlane).setMin(0.001); + attributeAffects(m_path, m_nearClipPlane); + + m_farClipPlane = addDistanceAttr( + "farClipPlane", "fcp", MDistance(10000.0, MDistance::kCentimeters), defaultFlags | kHidden); + MFnNumericAttribute(m_farClipPlane).setMin(0.001); + attributeAffects(m_path, m_farClipPlane); + + m_clippingRange + = addCompoundAttr("clippingRange", "cr", defaultFlags, { m_nearClipPlane, m_farClipPlane }); + MFnAttribute(m_clippingRange).setNiceNameOverride("Clipping Range"); + + addFrame("Film Back"); + + m_horizontalFilmAperture + = addDoubleAttr("horizontalFilmAperture", "hfa", 0.0, defaultFlags | kHidden); + MFnAttribute(m_horizontalFilmAperture).setNiceNameOverride("Horizontal Aperture (inch)"); + MFnNumericAttribute(m_horizontalFilmAperture).setMin(0.001f); + attributeAffects(m_path, m_horizontalFilmAperture); + + m_verticalFilmAperture + = addDoubleAttr("verticalFilmAperture", "vfa", 0.0, defaultFlags | kHidden); + MFnAttribute(m_verticalFilmAperture).setNiceNameOverride("Horizontal Aperture Offset (inch)"); + MFnNumericAttribute(m_verticalFilmAperture).setMin(0.001f); + attributeAffects(m_path, m_verticalFilmAperture); + + m_cameraApertureInch = addCompoundAttr( + "cameraAperture", + "cap", + defaultFlags, + { m_horizontalFilmAperture, m_verticalFilmAperture }); + MFnAttribute(m_cameraApertureInch).setNiceNameOverride("Camera Aperture (inch)"); + + m_horizontalAperture = addFloatAttr("horizontalAperture", "ha", 36.0f, readOnlyFlags | kHidden); + MFnAttribute(m_horizontalAperture).setNiceNameOverride("Horizontal Aperture (mm)"); + MFnNumericAttribute(m_horizontalAperture).setMin(0.001f); + attributeAffects(m_path, m_horizontalAperture); + + m_verticalAperture = addFloatAttr("verticalAperture", "va", 24.0f, readOnlyFlags | kHidden); + MFnAttribute(m_verticalAperture).setNiceNameOverride("Vertical Aperture (mm)"); + MFnNumericAttribute(m_verticalAperture).setMin(0.001f); + attributeAffects(m_path, m_verticalAperture); + + m_cameraApertureMm = addCompoundAttr( + "cameraApertureMm", "capm", defaultFlags, { m_horizontalAperture, m_verticalAperture }); + MFnAttribute(m_cameraApertureMm).setNiceNameOverride("Camera Aperture (mm)"); + + m_horizontalFilmOffset + = addDoubleAttr("horizontalFilmOffset", "hfo", 0.0, defaultFlags | kHidden); + MFnAttribute(m_horizontalFilmOffset).setNiceNameOverride("Vertical Aperture (inch)"); + attributeAffects(m_path, m_horizontalFilmOffset); + + m_verticalFilmOffset = addDoubleAttr("verticalFilmOffset", "vfo", 0.0, defaultFlags | kHidden); + MFnAttribute(m_verticalFilmOffset).setNiceNameOverride("Vertical Aperture Offset (inch)"); + attributeAffects(m_path, m_verticalFilmOffset); + + m_filmOffset = addCompoundAttr( + "filmOffset", "fio", defaultFlags, { m_horizontalFilmOffset, m_verticalFilmOffset }); + MFnAttribute(m_filmOffset).setNiceNameOverride("Film Offset (inch)"); + + m_horizontalApertureOffset + = addFloatAttr("horizontalApertureOffset", "hao", 0.0f, readOnlyFlags | kHidden); + MFnAttribute(m_horizontalApertureOffset).setNiceNameOverride("Horizontal Aperture Offset (mm)"); + attributeAffects(m_path, m_horizontalApertureOffset); + + m_verticalApertureOffset + = addFloatAttr("verticalApertureOffset", "vao", 0.0f, readOnlyFlags | kHidden); + MFnAttribute(m_verticalApertureOffset).setNiceNameOverride("Vertical Aperture Offset (mm)"); + attributeAffects(m_path, m_verticalApertureOffset); + + addFrame("Depth of Field"); + + m_focusDistance = addDistanceAttr( + "focusDistance", "fd", MDistance(5.0, MDistance::kCentimeters), defaultFlags); + MFnNumericAttribute(m_focusDistance).setMin(0.0); + attributeAffects(m_path, m_focusDistance); + + m_fStop = addFloatAttr("fStop", "fs", 5.6f, defaultFlags); + MFnNumericAttribute(m_fStop).setMin(1.0f); + MFnNumericAttribute(m_fStop).setMax(64.0f); + attributeAffects(m_path, m_fStop); + + addFrame("Motion Blur"); + + m_shutterOpen = addDoubleAttr("shutterOpen", "shun", 0.0, defaultFlags); + attributeAffects(m_path, m_shutterOpen); + + m_shutterClose = addDoubleAttr("shutterClose", "shue", 0.0, defaultFlags); + attributeAffects(m_path, m_shutterClose); + + // Translation Attribute Connections + + attributeAffects(m_projection, m_orthographic); + attributeAffects(m_orthographic, m_projection); + + attributeAffects(m_horizontalAperture, m_horizontalFilmAperture); + attributeAffects(m_horizontalFilmAperture, m_horizontalAperture); + attributeAffects(m_horizontalApertureOffset, m_horizontalFilmOffset); + attributeAffects(m_horizontalFilmOffset, m_horizontalApertureOffset); + + attributeAffects(m_verticalAperture, m_verticalFilmAperture); + attributeAffects(m_verticalFilmAperture, m_verticalAperture); + attributeAffects(m_verticalApertureOffset, m_verticalFilmOffset); + attributeAffects(m_verticalFilmOffset, m_verticalApertureOffset); + + generateAETemplate(); + + return MStatus::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyUsdGeomCamera.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyUsdGeomCamera.h index 6a0c93452f..2abaa17398 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyUsdGeomCamera.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/ProxyUsdGeomCamera.h @@ -15,15 +15,15 @@ // #pragma once -#include - #include "AL/usdmaya/Api.h" -#include #include +#include #include +#include + PXR_NAMESPACE_USING_DIRECTIVE namespace AL { @@ -31,92 +31,94 @@ namespace usdmaya { namespace nodes { //---------------------------------------------------------------------------------------------------------------------- -/// \brief The camera proxy node defines all attributes of the UsdGeomCamera as Maya attributes and allows reading and -/// writing directly to those attributes. This node can also be connected to the attributes of a Maya camera -/// to drive its attributes. +/// \brief The camera proxy node defines all attributes of the UsdGeomCamera as Maya attributes and +/// allows reading and +/// writing directly to those attributes. This node can also be connected to the attributes +/// of a Maya camera to drive its attributes. /// \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- -class ProxyUsdGeomCamera : public MPxNode, public maya::utils::NodeHelper +class ProxyUsdGeomCamera + : public MPxNode + , public maya::utils::NodeHelper { public: - /// \brief The enumeration values of the UsdGeomCamera projection attribute. - enum class Projection - { - Perspective, - Orthographic, - }; - - /// \brief The enumeration values of the UsdGeomCamera stereoRole attribute. - enum class StereoRole - { - Mono, - Left, - Right, - }; + /// \brief The enumeration values of the UsdGeomCamera projection attribute. + enum class Projection + { + Perspective, + Orthographic, + }; + + /// \brief The enumeration values of the UsdGeomCamera stereoRole attribute. + enum class StereoRole + { + Mono, + Left, + Right, + }; public: - AL_MAYA_DECLARE_NODE(); + AL_MAYA_DECLARE_NODE(); protected: - /// \brief Returns the UsdGeomCamera this node is proxying. - AL_USDMAYA_PUBLIC - UsdGeomCamera getCamera() const; + /// \brief Returns the UsdGeomCamera this node is proxying. + AL_USDMAYA_PUBLIC + UsdGeomCamera getCamera() const; - /// \brief Returns the UsdTimeCode at which attributes are being accessed. - AL_USDMAYA_PUBLIC - UsdTimeCode getTime() const; + /// \brief Returns the UsdTimeCode at which attributes are being accessed. + AL_USDMAYA_PUBLIC + UsdTimeCode getTime() const; public: - /// \brief ctor - AL_USDMAYA_PUBLIC - ProxyUsdGeomCamera() = default; - - /// \brief dtor - AL_USDMAYA_PUBLIC - ~ProxyUsdGeomCamera() = default; - - /// \brief Writes attribute values from Maya to the UsdGeomCamera this node is proxying. - AL_USDMAYA_PUBLIC - bool setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) override; - - /// \brief Reads attributes from the UsdGeomCamera this node is proxying when requested by Maya. - AL_USDMAYA_PUBLIC - bool getInternalValue(const MPlug& plug, MDataHandle& dataHandle) override; - - AL_DECL_ATTRIBUTE(path); - AL_DECL_ATTRIBUTE(stage); - AL_DECL_ATTRIBUTE(time); - - // Schema - AL_DECL_ATTRIBUTE(clippingRange); - AL_DECL_ATTRIBUTE(focalLength); - AL_DECL_ATTRIBUTE(focusDistance); - AL_DECL_ATTRIBUTE(fStop); - AL_DECL_ATTRIBUTE(horizontalAperture); // mm - AL_DECL_ATTRIBUTE(verticalAperture); // mm - AL_DECL_ATTRIBUTE(filmOffset); // inch - AL_DECL_ATTRIBUTE(horizontalApertureOffset); // mm - AL_DECL_ATTRIBUTE(verticalApertureOffset); // mm - AL_DECL_ATTRIBUTE(projection); - AL_DECL_ATTRIBUTE(shutterClose); - AL_DECL_ATTRIBUTE(shutterOpen); - AL_DECL_ATTRIBUTE(stereoRole); - - // Maya - AL_DECL_ATTRIBUTE(nearClipPlane); - AL_DECL_ATTRIBUTE(farClipPlane); - AL_DECL_ATTRIBUTE(orthographic); - AL_DECL_ATTRIBUTE(cameraApertureMm); // mm - AL_DECL_ATTRIBUTE(cameraApertureInch); // inch - AL_DECL_ATTRIBUTE(horizontalFilmAperture); // inch - AL_DECL_ATTRIBUTE(horizontalFilmOffset); // inch - AL_DECL_ATTRIBUTE(verticalFilmAperture); // inch - AL_DECL_ATTRIBUTE(verticalFilmOffset); // inch - + /// \brief ctor + AL_USDMAYA_PUBLIC + ProxyUsdGeomCamera() = default; + + /// \brief dtor + AL_USDMAYA_PUBLIC + ~ProxyUsdGeomCamera() = default; + + /// \brief Writes attribute values from Maya to the UsdGeomCamera this node is proxying. + AL_USDMAYA_PUBLIC + bool setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) override; + + /// \brief Reads attributes from the UsdGeomCamera this node is proxying when requested by Maya. + AL_USDMAYA_PUBLIC + bool getInternalValue(const MPlug& plug, MDataHandle& dataHandle) override; + + AL_DECL_ATTRIBUTE(path); + AL_DECL_ATTRIBUTE(stage); + AL_DECL_ATTRIBUTE(time); + + // Schema + AL_DECL_ATTRIBUTE(clippingRange); + AL_DECL_ATTRIBUTE(focalLength); + AL_DECL_ATTRIBUTE(focusDistance); + AL_DECL_ATTRIBUTE(fStop); + AL_DECL_ATTRIBUTE(horizontalAperture); // mm + AL_DECL_ATTRIBUTE(verticalAperture); // mm + AL_DECL_ATTRIBUTE(filmOffset); // inch + AL_DECL_ATTRIBUTE(horizontalApertureOffset); // mm + AL_DECL_ATTRIBUTE(verticalApertureOffset); // mm + AL_DECL_ATTRIBUTE(projection); + AL_DECL_ATTRIBUTE(shutterClose); + AL_DECL_ATTRIBUTE(shutterOpen); + AL_DECL_ATTRIBUTE(stereoRole); + + // Maya + AL_DECL_ATTRIBUTE(nearClipPlane); + AL_DECL_ATTRIBUTE(farClipPlane); + AL_DECL_ATTRIBUTE(orthographic); + AL_DECL_ATTRIBUTE(cameraApertureMm); // mm + AL_DECL_ATTRIBUTE(cameraApertureInch); // inch + AL_DECL_ATTRIBUTE(horizontalFilmAperture); // inch + AL_DECL_ATTRIBUTE(horizontalFilmOffset); // inch + AL_DECL_ATTRIBUTE(verticalFilmAperture); // inch + AL_DECL_ATTRIBUTE(verticalFilmOffset); // inch }; //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/RendererManager.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/RendererManager.cpp index 36781689bc..323475b822 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/RendererManager.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/RendererManager.cpp @@ -13,11 +13,12 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/TypeIDs.h" +#include "AL/usdmaya/nodes/RendererManager.h" + #include "AL/usdmaya/DebugCodes.h" +#include "AL/usdmaya/TypeIDs.h" #include "AL/usdmaya/nodes/Engine.h" #include "AL/usdmaya/nodes/ProxyShape.h" -#include "AL/usdmaya/nodes/RendererManager.h" #include #include @@ -26,7 +27,7 @@ namespace { - static std::mutex s_findNodeMutex; +static std::mutex s_findNodeMutex; } @@ -41,241 +42,225 @@ MObject RendererManager::m_rendererPluginName = MObject::kNullObj; MObject RendererManager::m_rendererPlugin = MObject::kNullObj; TfTokenVector RendererManager::m_rendererPluginsTokens; -MStringArray RendererManager::m_rendererPluginsNames; +MStringArray RendererManager::m_rendererPluginsNames; //---------------------------------------------------------------------------------------------------------------------- MStatus RendererManager::initialise() { - TF_DEBUG(ALUSDMAYA_RENDERER).Msg("RendererManager::initialize\n"); - try - { - setNodeType(kTypeName); - addFrame("Renderer plugin"); - - // hydra renderer plugin discovery - m_rendererPluginsTokens = UsdImagingGLEngine::GetRendererPlugins(); - const size_t numTokens = m_rendererPluginsTokens.size(); - m_rendererPluginsNames = MStringArray(numTokens, MString()); - - // as it's not clear what is the lifetime of strings returned from HdEngine::GetRendererPluginDesc - // we store them in array to populate options menu items - std::vector pluginNames(numTokens); - std::vector enumNames(numTokens + 1, nullptr); - std::vector enumValues(numTokens, -1); - for (size_t i = 0; i < numTokens; ++i) - { - pluginNames[i] = UsdImagingGLEngine::GetRendererDisplayName(m_rendererPluginsTokens[i]); - m_rendererPluginsNames[i] = MString(pluginNames[i].data(), pluginNames[i].size()); - enumNames[i] = pluginNames[i].data(); - enumValues[i] = i; + TF_DEBUG(ALUSDMAYA_RENDERER).Msg("RendererManager::initialize\n"); + try { + setNodeType(kTypeName); + addFrame("Renderer plugin"); + + // hydra renderer plugin discovery + m_rendererPluginsTokens = UsdImagingGLEngine::GetRendererPlugins(); + const size_t numTokens = m_rendererPluginsTokens.size(); + m_rendererPluginsNames = MStringArray(numTokens, MString()); + + // as it's not clear what is the lifetime of strings returned from + // HdEngine::GetRendererPluginDesc we store them in array to populate options menu items + std::vector pluginNames(numTokens); + std::vector enumNames(numTokens + 1, nullptr); + std::vector enumValues(numTokens, -1); + for (size_t i = 0; i < numTokens; ++i) { + pluginNames[i] = UsdImagingGLEngine::GetRendererDisplayName(m_rendererPluginsTokens[i]); + m_rendererPluginsNames[i] = MString(pluginNames[i].data(), pluginNames[i].size()); + enumNames[i] = pluginNames[i].data(); + enumValues[i] = i; + } + + m_rendererPluginName = addStringAttr( + "rendererPluginName", + "rpn", + "GL", + kInternal | kCached | kReadable | kWritable | kStorable | kHidden); + m_rendererPlugin = addEnumAttr( + "rendererPlugin", + "rp", + kInternal | kReadable | kWritable, + enumNames.data(), + enumValues.data()); + + } catch (const MStatus& status) { + return status; } - - m_rendererPluginName = addStringAttr( - "rendererPluginName", "rpn", "GL", kInternal | kCached | kReadable | kWritable | kStorable | kHidden); - m_rendererPlugin = addEnumAttr( - "rendererPlugin", "rp", kInternal | kReadable | kWritable, enumNames.data(), enumValues.data() - ); - - } - catch(const MStatus& status) - { - return status; - } - generateAETemplate(); - return MS::kSuccess; + generateAETemplate(); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MObject RendererManager::findNode() { - std::lock_guard lock(s_findNodeMutex); - return _findNode(); + std::lock_guard lock(s_findNodeMutex); + return _findNode(); } //---------------------------------------------------------------------------------------------------------------------- MObject RendererManager::_findNode() { - MFnDependencyNode fn; - MItDependencyNodes iter(MFn::kPluginDependNode); - for(; !iter.isDone(); iter.next()) - { - MObject mobj = iter.item(); - fn.setObject(mobj); - if(fn.typeId() == kTypeId && !fn.isFromReferencedFile()) - { - return mobj; + MFnDependencyNode fn; + MItDependencyNodes iter(MFn::kPluginDependNode); + for (; !iter.isDone(); iter.next()) { + MObject mobj = iter.item(); + fn.setObject(mobj); + if (fn.typeId() == kTypeId && !fn.isFromReferencedFile()) { + return mobj; + } } - } - return MObject::kNullObj; + return MObject::kNullObj; } //---------------------------------------------------------------------------------------------------------------------- MObject RendererManager::findOrCreateNode(MDGModifier* dgmod, bool* wasCreated) { - TF_DEBUG(ALUSDMAYA_RENDERER).Msg("RendererManager::findOrCreateNode\n"); - std::lock_guard lock(s_findNodeMutex); - MObject theManager = _findNode(); - - if (!theManager.isNull()) - { - if (wasCreated) *wasCreated = false; - return theManager; - } - - if (wasCreated) *wasCreated = true; - - if (dgmod) - { - return dgmod->createNode(kTypeId); - } - else - { - MDGModifier modifier; - MObject node = modifier.createNode(kTypeId); - modifier.doIt(); - return node; - } + TF_DEBUG(ALUSDMAYA_RENDERER).Msg("RendererManager::findOrCreateNode\n"); + std::lock_guard lock(s_findNodeMutex); + MObject theManager = _findNode(); + + if (!theManager.isNull()) { + if (wasCreated) + *wasCreated = false; + return theManager; + } + + if (wasCreated) + *wasCreated = true; + + if (dgmod) { + return dgmod->createNode(kTypeId); + } else { + MDGModifier modifier; + MObject node = modifier.createNode(kTypeId); + modifier.doIt(); + return node; + } } //---------------------------------------------------------------------------------------------------------------------- RendererManager* RendererManager::findManager() { - MObject manager = findNode(); - if(manager.isNull()) - { - return nullptr; - } - return static_cast(MFnDependencyNode(manager).userNode()); + MObject manager = findNode(); + if (manager.isNull()) { + return nullptr; + } + return static_cast(MFnDependencyNode(manager).userNode()); } //---------------------------------------------------------------------------------------------------------------------- RendererManager* RendererManager::findOrCreateManager(MDGModifier* dgmod, bool* wasCreated) { - return static_cast(MFnDependencyNode(findOrCreateNode(dgmod, wasCreated)).userNode()); + return static_cast( + MFnDependencyNode(findOrCreateNode(dgmod, wasCreated)).userNode()); } //---------------------------------------------------------------------------------------------------------------------- bool RendererManager::setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) { - if (plug == m_rendererPlugin) - { - short index = dataHandle.asShort(); - if (index >= 0 && index < short(m_rendererPluginsNames.length())) - { - MPlug plug(thisMObject(), m_rendererPluginName); - plug.setString(m_rendererPluginsNames[index]); - return true; + if (plug == m_rendererPlugin) { + short index = dataHandle.asShort(); + if (index >= 0 && index < short(m_rendererPluginsNames.length())) { + MPlug plug(thisMObject(), m_rendererPluginName); + plug.setString(m_rendererPluginsNames[index]); + return true; + } + } else if (plug == m_rendererPluginName) { + // can't use dataHandle.datablock(), as this is a temporary datahandle + // Need to set this before calling onRendererChanged, so it can access the (new) value... + MDataBlock datablock = forceCache(); + AL_MAYA_CHECK_ERROR_RETURN_VAL( + outputStringValue(datablock, plug.attribute(), dataHandle.asString()), + false, + MString("ProxyShape::setInternalValue - error setting ") + plug.name()); + + onRendererChanged(); + return true; } - } - else if(plug == m_rendererPluginName) - { - // can't use dataHandle.datablock(), as this is a temporary datahandle - // Need to set this before calling onRendererChanged, so it can access the (new) value... - MDataBlock datablock = forceCache(); - AL_MAYA_CHECK_ERROR_RETURN_VAL(outputStringValue(datablock, plug.attribute(), dataHandle.asString()), - false, MString("ProxyShape::setInternalValue - error setting ") + plug.name()); - - onRendererChanged(); - return true; - } - return MPxNode::setInternalValue(plug, dataHandle); + return MPxNode::setInternalValue(plug, dataHandle); } //---------------------------------------------------------------------------------------------------------------------- bool RendererManager::getInternalValue(const MPlug& plug, MDataHandle& dataHandle) { - if (plug == m_rendererPlugin) - { - int index = getRendererPluginIndex(); - if (index >= 0) - { - dataHandle.set((short)index); - return true; + if (plug == m_rendererPlugin) { + int index = getRendererPluginIndex(); + if (index >= 0) { + dataHandle.set((short)index); + return true; + } } - } - return MPxNode::getInternalValue(plug, dataHandle); + return MPxNode::getInternalValue(plug, dataHandle); } //---------------------------------------------------------------------------------------------------------------------- void RendererManager::onRendererChanged() { - // Find all proxy shapes and change renderer plugin - MFnDependencyNode fn; - MItDependencyNodes iter(MFn::kPluginShape); - for(; !iter.isDone(); iter.next()) - { - fn.setObject(iter.item()); - if(fn.typeId() == ProxyShape::kTypeId) - { - ProxyShape* proxy = static_cast(fn.userNode()); - changeRendererPlugin(proxy); + // Find all proxy shapes and change renderer plugin + MFnDependencyNode fn; + MItDependencyNodes iter(MFn::kPluginShape); + for (; !iter.isDone(); iter.next()) { + fn.setObject(iter.item()); + if (fn.typeId() == ProxyShape::kTypeId) { + ProxyShape* proxy = static_cast(fn.userNode()); + changeRendererPlugin(proxy); + } } - } - //! We need to refresh viewport to changes take effect - MGlobal::executeCommandOnIdle("refresh -force"); + //! We need to refresh viewport to changes take effect + MGlobal::executeCommandOnIdle("refresh -force"); } //---------------------------------------------------------------------------------------------------------------------- void RendererManager::changeRendererPlugin(ProxyShape* proxy, bool creation) { - TF_DEBUG(ALUSDMAYA_RENDERER).Msg("RendererManager::changeRendererPlugin\n"); - assert(proxy); - if (proxy->engine(false)) - { - int rendererId = getRendererPluginIndex(); - if (rendererId >= 0) - { - // Skip redundant renderer changes on ProxyShape creation - if (rendererId == 0 && creation) - return; - - assert(static_cast(rendererId) < m_rendererPluginsTokens.size()); - TfToken plugin = m_rendererPluginsTokens[rendererId]; - if (!proxy->engine()->SetRendererPlugin(plugin)) - { - MString data(plugin.data()); - MGlobal::displayError(MString("Failed to set renderer plugin: ") + data); - } - } - else - { - MPlug plug(thisMObject(), m_rendererPluginName); - MString pluginName = plug.asString(); - if (pluginName.length()) - MGlobal::displayError(MString("Invalid renderer plugin: ") + pluginName); + TF_DEBUG(ALUSDMAYA_RENDERER).Msg("RendererManager::changeRendererPlugin\n"); + assert(proxy); + if (proxy->engine(false)) { + int rendererId = getRendererPluginIndex(); + if (rendererId >= 0) { + // Skip redundant renderer changes on ProxyShape creation + if (rendererId == 0 && creation) + return; + + assert(static_cast(rendererId) < m_rendererPluginsTokens.size()); + TfToken plugin = m_rendererPluginsTokens[rendererId]; + if (!proxy->engine()->SetRendererPlugin(plugin)) { + MString data(plugin.data()); + MGlobal::displayError(MString("Failed to set renderer plugin: ") + data); + } + } else { + MPlug plug(thisMObject(), m_rendererPluginName); + MString pluginName = plug.asString(); + if (pluginName.length()) + MGlobal::displayError(MString("Invalid renderer plugin: ") + pluginName); + } } - } } //---------------------------------------------------------------------------------------------------------------------- int RendererManager::getRendererPluginIndex() const { - MPlug plug(thisMObject(), m_rendererPluginName); - MString pluginName = plug.asString(); - return m_rendererPluginsNames.indexOf(pluginName); + MPlug plug(thisMObject(), m_rendererPluginName); + MString pluginName = plug.asString(); + return m_rendererPluginsNames.indexOf(pluginName); } //---------------------------------------------------------------------------------------------------------------------- bool RendererManager::setRendererPlugin(const MString& pluginName) { - int index = m_rendererPluginsNames.indexOf(pluginName); - if (index >= 0) - { - TF_DEBUG(ALUSDMAYA_RENDERER).Msg("RendererManager::setRendererPlugin\n"); - MPlug plug(thisMObject(), m_rendererPluginName); - plug.setString(pluginName); - return true; - } - else - { - TF_DEBUG(ALUSDMAYA_RENDERER).Msg("Failed to set renderer plugin!\n"); - MGlobal::displayError(MString("Failed to set renderer plugin: ") + pluginName); - } - return false; + int index = m_rendererPluginsNames.indexOf(pluginName); + if (index >= 0) { + TF_DEBUG(ALUSDMAYA_RENDERER).Msg("RendererManager::setRendererPlugin\n"); + MPlug plug(thisMObject(), m_rendererPluginName); + plug.setString(pluginName); + return true; + } else { + TF_DEBUG(ALUSDMAYA_RENDERER).Msg("Failed to set renderer plugin!\n"); + MGlobal::displayError(MString("Failed to set renderer plugin: ") + pluginName); + } + return false; } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/RendererManager.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/RendererManager.h index 7275ace526..29132c60ee 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/RendererManager.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/RendererManager.h @@ -15,22 +15,22 @@ // #pragma once -#include "AL/usdmaya/Api.h" - #include "AL/maya/utils/MayaHelperMacros.h" #include "AL/maya/utils/NodeHelper.h" +#include "AL/usdmaya/Api.h" + +#include #include #include -#include - /* +#include "AL/maya/utils/MayaHelperMacros.h" + #include #include #include -#include "AL/maya/utils/MayaHelperMacros.h" #include @@ -44,96 +44,98 @@ namespace nodes { class ProxyShape; - //---------------------------------------------------------------------------------------------------------------------- -/// \brief The layer manager node handles serialization and deserialization of all layers used by all ProxyShapes -/// \ingroup nodes +/// \brief The layer manager node handles serialization and deserialization of all layers used by +/// all ProxyShapes \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- class RendererManager - : public MPxNode, - public AL::maya::utils::NodeHelper + : public MPxNode + , public AL::maya::utils::NodeHelper { public: - - /// \brief ctor - inline RendererManager() - : MPxNode(), NodeHelper() {} - - /// \brief Find the already-existing non-referenced RendererManager node in the scene, or return a null MObject - /// \return the found RendererManager node, or a null MObject - static MObject findNode(); - - /// \brief Either find the already-existing non-referenced RendererManager node in the scene, or make one - /// \param dgmod An optional dgmodifier to create the node, if necessary. Note that if one is passed in, - /// createNode might be called on it, but doIt never will be, so the layer manager node - /// may not be added to the scene graph yet - /// \param wasCreated If given, whether a new layer manager had to be created is stored here. - /// \return the found-or-created RendererManager node - static MObject findOrCreateNode(MDGModifier* dgmod=nullptr, bool* wasCreated=nullptr); - - /// \brief Find the already-existing non-referenced RendererManager node in the scene, or return a nullptr - /// \return the found RendererManager, or a nullptr - static RendererManager* findManager(); - - /// \brief Either find the already-existing non-referenced RendererManager in the scene, or make one - /// \param dgmod An optional dgmodifier to create the node, if necessary. Note that if one is passed in, - /// createNode might be called on it, but doIt never will be, so the layer manager node - /// may not be added to the scene graph yet - /// \param wasCreated If given, whether a new layer manager had to be created is stored here. - /// \return the found-or-created RendererManager - static RendererManager* findOrCreateManager(MDGModifier* dgmod=nullptr, bool* wasCreated=nullptr); - - //-------------------------------------------------------------------------------------------------------------------- - /// Methods to handle renderer plugin - //-------------------------------------------------------------------------------------------------------------------- - - /// \brief Set current renderer for all proxy shapes - void onRendererChanged(); - - /// \brief Set current renderer plugin based on provided name - bool setRendererPlugin(const MString& pluginName); - - /// \brief Change current renderer plugin for provided ProxyShape - void changeRendererPlugin(ProxyShape* proxy, bool creation=false); - - /// \brief Get current renderer plugin index - int getRendererPluginIndex() const; - - /// \brief Get list of available Hydra renderer plugin names - static const MStringArray& getRendererPluginList() { return m_rendererPluginsNames; } - - //-------------------------------------------------------------------------------------------------------------------- - /// Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- - AL_MAYA_DECLARE_NODE(); - - //-------------------------------------------------------------------------------------------------------------------- - /// Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- - - /// Hydra renderer plugin name used for rendering (storable) - AL_DECL_ATTRIBUTE(rendererPluginName); - /// Hydra renderer plugin index used for UI (internal) - AL_DECL_ATTRIBUTE(rendererPlugin); + /// \brief ctor + inline RendererManager() + : MPxNode() + , NodeHelper() + { + } + + /// \brief Find the already-existing non-referenced RendererManager node in the scene, or + /// return a null MObject \return the found RendererManager node, or a null MObject + static MObject findNode(); + + /// \brief Either find the already-existing non-referenced RendererManager node in the scene, + /// or make one \param dgmod An optional dgmodifier to create the node, if necessary. Note that + /// if one is passed in, + /// createNode might be called on it, but doIt never will be, so the layer manager + /// node may not be added to the scene graph yet + /// \param wasCreated If given, whether a new layer manager had to be created is stored here. + /// \return the found-or-created RendererManager node + static MObject findOrCreateNode(MDGModifier* dgmod = nullptr, bool* wasCreated = nullptr); + + /// \brief Find the already-existing non-referenced RendererManager node in the scene, or + /// return a nullptr \return the found RendererManager, or a nullptr + static RendererManager* findManager(); + + /// \brief Either find the already-existing non-referenced RendererManager in the scene, or + /// make one \param dgmod An optional dgmodifier to create the node, if necessary. Note that if + /// one is passed in, + /// createNode might be called on it, but doIt never will be, so the layer manager + /// node may not be added to the scene graph yet + /// \param wasCreated If given, whether a new layer manager had to be created is stored here. + /// \return the found-or-created RendererManager + static RendererManager* + findOrCreateManager(MDGModifier* dgmod = nullptr, bool* wasCreated = nullptr); + + //-------------------------------------------------------------------------------------------------------------------- + /// Methods to handle renderer plugin + //-------------------------------------------------------------------------------------------------------------------- + + /// \brief Set current renderer for all proxy shapes + void onRendererChanged(); + + /// \brief Set current renderer plugin based on provided name + bool setRendererPlugin(const MString& pluginName); + + /// \brief Change current renderer plugin for provided ProxyShape + void changeRendererPlugin(ProxyShape* proxy, bool creation = false); + + /// \brief Get current renderer plugin index + int getRendererPluginIndex() const; + + /// \brief Get list of available Hydra renderer plugin names + static const MStringArray& getRendererPluginList() { return m_rendererPluginsNames; } + + //-------------------------------------------------------------------------------------------------------------------- + /// Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- + AL_MAYA_DECLARE_NODE(); + + //-------------------------------------------------------------------------------------------------------------------- + /// Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- + + /// Hydra renderer plugin name used for rendering (storable) + AL_DECL_ATTRIBUTE(rendererPluginName); + /// Hydra renderer plugin index used for UI (internal) + AL_DECL_ATTRIBUTE(rendererPlugin); private: - static MObject _findNode(); + static MObject _findNode(); + + static TfTokenVector m_rendererPluginsTokens; + static MStringArray m_rendererPluginsNames; - static TfTokenVector m_rendererPluginsTokens; - static MStringArray m_rendererPluginsNames; + //-------------------------------------------------------------------------------------------------------------------- + /// MPxNode overrides + //-------------------------------------------------------------------------------------------------------------------- - //-------------------------------------------------------------------------------------------------------------------- - /// MPxNode overrides - //-------------------------------------------------------------------------------------------------------------------- + bool setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) override; - bool setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) override; - - bool getInternalValue(const MPlug& plug, MDataHandle& dataHandle) override; - + bool getInternalValue(const MPlug& plug, MDataHandle& dataHandle) override; }; -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Scope.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Scope.cpp index bf8a020782..7e3fba27be 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Scope.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Scope.cpp @@ -13,10 +13,11 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/TypeIDs.h" +#include "AL/usdmaya/nodes/Scope.h" + #include "AL/usdmaya/DebugCodes.h" +#include "AL/usdmaya/TypeIDs.h" #include "AL/usdmaya/nodes/ProxyShape.h" -#include "AL/usdmaya/nodes/Scope.h" #include @@ -24,7 +25,6 @@ #include #include - namespace AL { namespace usdmaya { namespace nodes { @@ -40,271 +40,260 @@ MObject Scope::m_inStageData = MObject::kNullObj; //---------------------------------------------------------------------------------------------------------------------- void Scope::postConstructor() { - transform()->setMObject(thisMObject()); - MPlug(thisMObject(), MPxTransform::translate).setLocked(true); - MPlug(thisMObject(), MPxTransform::rotate).setLocked(true); - MPlug(thisMObject(), MPxTransform::scale).setLocked(true); - MPlug(thisMObject(), MPxTransform::transMinusRotatePivot).setLocked(true); - MPlug(thisMObject(), MPxTransform::rotateAxis).setLocked(true); - MPlug(thisMObject(), MPxTransform::scalePivotTranslate).setLocked(true); - MPlug(thisMObject(), MPxTransform::scalePivot).setLocked(true); - MPlug(thisMObject(), MPxTransform::rotatePivotTranslate).setLocked(true); - MPlug(thisMObject(), MPxTransform::rotatePivot).setLocked(true); - MPlug(thisMObject(), MPxTransform::shearXY).setLocked(true); - MPlug(thisMObject(), MPxTransform::shearXZ).setLocked(true); - MPlug(thisMObject(), MPxTransform::shearYZ).setLocked(true); + transform()->setMObject(thisMObject()); + MPlug(thisMObject(), MPxTransform::translate).setLocked(true); + MPlug(thisMObject(), MPxTransform::rotate).setLocked(true); + MPlug(thisMObject(), MPxTransform::scale).setLocked(true); + MPlug(thisMObject(), MPxTransform::transMinusRotatePivot).setLocked(true); + MPlug(thisMObject(), MPxTransform::rotateAxis).setLocked(true); + MPlug(thisMObject(), MPxTransform::scalePivotTranslate).setLocked(true); + MPlug(thisMObject(), MPxTransform::scalePivot).setLocked(true); + MPlug(thisMObject(), MPxTransform::rotatePivotTranslate).setLocked(true); + MPlug(thisMObject(), MPxTransform::rotatePivot).setLocked(true); + MPlug(thisMObject(), MPxTransform::shearXY).setLocked(true); + MPlug(thisMObject(), MPxTransform::shearXZ).setLocked(true); + MPlug(thisMObject(), MPxTransform::shearYZ).setLocked(true); } //---------------------------------------------------------------------------------------------------------------------- -Scope::Scope() -{ -} +Scope::Scope() { } //---------------------------------------------------------------------------------------------------------------------- -Scope::~Scope() -{ -} +Scope::~Scope() { } //---------------------------------------------------------------------------------------------------------------------- MPxTransformationMatrix* Scope::createTransformationMatrix() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Scope::createTransformationMatrix\n"); - return new BasicTransformationMatrix; + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Scope::createTransformationMatrix\n"); + return new BasicTransformationMatrix; } //---------------------------------------------------------------------------------------------------------------------- MStatus Scope::initialise() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Scope::initialise\n"); - const char* const errorString = "Scope::initialise"; - try - { - setNodeType(kTypeName); - - addFrame("USD Prim Information"); - m_primPath = addStringAttr("primPath", "pp", kReadable | kWritable | kStorable | kConnectable | kAffectsWorldSpace, true); - m_inStageData = addDataAttr("inStageData", "isd", MayaUsdStageData::mayaTypeId, kWritable | kStorable | kConnectable | kHidden | kAffectsWorldSpace); - - mustCallValidateAndSet(m_primPath); - mustCallValidateAndSet(m_inStageData); - - for(auto& inAttr : {m_primPath, m_inStageData}) - { - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, translate), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotate), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotateOrder), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scale), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, shear), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotatePivot), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotatePivotTranslate), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scalePivot), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scalePivotTranslate), errorString); - // Maya 2018 (checked 2018.2 and 2018.3) has a bug where, if any loaded plugin has an MPxTransform subclass - // that has ANY attribute that connected to rotateAxis, it will cause the rotateAxis to evaluate INCORRECTLY, - // even on the BASE transform class! - // See this gist for full reproduction details: - // https://gist.github.com/elrond79/f9ddb277da3eab2948d27ddb1f84aba0 + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Scope::initialise\n"); + const char* const errorString = "Scope::initialise"; + try { + setNodeType(kTypeName); + + addFrame("USD Prim Information"); + m_primPath = addStringAttr( + "primPath", + "pp", + kReadable | kWritable | kStorable | kConnectable | kAffectsWorldSpace, + true); + m_inStageData = addDataAttr( + "inStageData", + "isd", + MayaUsdStageData::mayaTypeId, + kWritable | kStorable | kConnectable | kHidden | kAffectsWorldSpace); + + mustCallValidateAndSet(m_primPath); + mustCallValidateAndSet(m_inStageData); + + for (auto& inAttr : { m_primPath, m_inStageData }) { + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, translate), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotate), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotateOrder), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scale), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, shear), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotatePivot), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotatePivotTranslate), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scalePivot), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scalePivotTranslate), errorString); + // Maya 2018 (checked 2018.2 and 2018.3) has a bug where, if any loaded plugin has an + // MPxTransform subclass that has ANY attribute that connected to rotateAxis, it will + // cause the rotateAxis to evaluate INCORRECTLY, even on the BASE transform class! See + // this gist for full reproduction details: + // https://gist.github.com/elrond79/f9ddb277da3eab2948d27ddb1f84aba0 #if MAYA_API_VERSION >= 20180600 - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotateAxis), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotateAxis), errorString); #endif - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, matrix), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, worldMatrix), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, inverseMatrix), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, worldInverseMatrix), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, matrix), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, worldMatrix), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, inverseMatrix), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, worldInverseMatrix), errorString); + } + } catch (const MStatus& status) { + return status; } - } - catch(const MStatus& status) - { - return status; - } - - addBaseTemplate("AEtransformMain"); - addBaseTemplate("AEtransformNoScroll"); - addBaseTemplate("AEtransformSkinCluster"); - generateAETemplate(); - - return MS::kSuccess; + + addBaseTemplate("AEtransformMain"); + addBaseTemplate("AEtransformNoScroll"); + addBaseTemplate("AEtransformSkinCluster"); + generateAETemplate(); + + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus Scope::compute(const MPlug& plug, MDataBlock& dataBlock) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Scope::compute %s\n", plug.name().asChar()); - if(plug == m_inStageData) - { - // This should only be computed if there's no connection, so set it to an empty stage - // create new stage data - MObject data; - MayaUsdStageData* usdStageData = createData(MayaUsdStageData::mayaTypeId, data); - if(!usdStageData) - { - return MS::kFailure; - } - - // set the cached output value, and flush - MStatus status = outputDataValue(dataBlock, m_inStageData, usdStageData); - if(!status) - { - return MS::kFailure; + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Scope::compute %s\n", plug.name().asChar()); + if (plug == m_inStageData) { + // This should only be computed if there's no connection, so set it to an empty stage + // create new stage data + MObject data; + MayaUsdStageData* usdStageData + = createData(MayaUsdStageData::mayaTypeId, data); + if (!usdStageData) { + return MS::kFailure; + } + + // set the cached output value, and flush + MStatus status = outputDataValue(dataBlock, m_inStageData, usdStageData); + if (!status) { + return MS::kFailure; + } + return status; } - return status; - } - return MPxTransform::compute(plug, dataBlock); + return MPxTransform::compute(plug, dataBlock); } //---------------------------------------------------------------------------------------------------------------------- MBoundingBox Scope::boundingBox() const { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Scope::boundingBox\n"); - - MFnDagNode fn; - MPlug sourcePlug = inStageDataPlug().source(); - MFnDagNode proxyShape(sourcePlug.node()); - AL::usdmaya::nodes::ProxyShape* foundShape = (AL::usdmaya::nodes::ProxyShape*)proxyShape.userNode(); - - UsdTimeCode usdTime; //Use default time if can't find a connected proxy shape; - if (foundShape) - { - auto outTimePlug = foundShape->outTimePlug(); - MTime outTime = outTimePlug.asMTime(); - usdTime = UsdTimeCode(outTime.as(MTime::uiUnit())); - } - - // Compute Maya bounding box first. Some nodes can contain both Maya and USD boundable descendants. - MBoundingBox bbox = MPxTransform::boundingBox(); - - UsdPrim prim = transform()->prim(); - if(prim) - { - // Get purpose draw states - bool drawRenderPurpose = false; - bool drawProxyPurpose = false; - bool drawGuidePurpose = false; - CHECK_MSTATUS(MPlug(getProxyShape(), ProxyShape::drawRenderPurposeAttr).getValue(drawRenderPurpose)); - CHECK_MSTATUS(MPlug(getProxyShape(), ProxyShape::drawProxyPurposeAttr).getValue(drawProxyPurpose)); - CHECK_MSTATUS(MPlug(getProxyShape(), ProxyShape::drawGuidePurposeAttr).getValue(drawGuidePurpose)); - const TfToken purpose1 = UsdGeomTokens->default_; - const TfToken purpose2 = drawRenderPurpose ? UsdGeomTokens->render : TfToken(); - const TfToken purpose3 = drawProxyPurpose ? UsdGeomTokens->proxy : TfToken(); - const TfToken purpose4 = drawGuidePurpose ? UsdGeomTokens->guide : TfToken(); - - // Compute bounding box - UsdGeomImageable imageable(prim); - const GfBBox3d box = imageable.ComputeLocalBound(usdTime, purpose1, purpose2, purpose3, purpose4); - const GfRange3d range = box.GetRange(); - const GfVec3d usdMin = range.IsEmpty() ? GfVec3d(0.0, 0.0, 0.0) : range.GetMin(); - const GfVec3d usdMax = range.IsEmpty() ? GfVec3d(0.0, 0.0, 0.0) : range.GetMax(); - bbox.expand(MPoint(usdMin[0], usdMin[1], usdMin[2])); - bbox.expand(MPoint(usdMax[0], usdMax[1], usdMax[2])); - MMatrix mayaMx; - const double* matrixArray = box.GetMatrix().GetArray(); - std::copy(matrixArray, matrixArray+16, mayaMx[0]); - bbox.transformUsing(mayaMx); - } - - return bbox; + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Scope::boundingBox\n"); + + MFnDagNode fn; + MPlug sourcePlug = inStageDataPlug().source(); + MFnDagNode proxyShape(sourcePlug.node()); + AL::usdmaya::nodes::ProxyShape* foundShape + = (AL::usdmaya::nodes::ProxyShape*)proxyShape.userNode(); + + UsdTimeCode usdTime; // Use default time if can't find a connected proxy shape; + if (foundShape) { + auto outTimePlug = foundShape->outTimePlug(); + MTime outTime = outTimePlug.asMTime(); + usdTime = UsdTimeCode(outTime.as(MTime::uiUnit())); + } + + // Compute Maya bounding box first. Some nodes can contain both Maya and USD boundable + // descendants. + MBoundingBox bbox = MPxTransform::boundingBox(); + + UsdPrim prim = transform()->prim(); + if (prim) { + // Get purpose draw states + bool drawRenderPurpose = false; + bool drawProxyPurpose = false; + bool drawGuidePurpose = false; + CHECK_MSTATUS( + MPlug(getProxyShape(), ProxyShape::drawRenderPurposeAttr).getValue(drawRenderPurpose)); + CHECK_MSTATUS( + MPlug(getProxyShape(), ProxyShape::drawProxyPurposeAttr).getValue(drawProxyPurpose)); + CHECK_MSTATUS( + MPlug(getProxyShape(), ProxyShape::drawGuidePurposeAttr).getValue(drawGuidePurpose)); + const TfToken purpose1 = UsdGeomTokens->default_; + const TfToken purpose2 = drawRenderPurpose ? UsdGeomTokens->render : TfToken(); + const TfToken purpose3 = drawProxyPurpose ? UsdGeomTokens->proxy : TfToken(); + const TfToken purpose4 = drawGuidePurpose ? UsdGeomTokens->guide : TfToken(); + + // Compute bounding box + UsdGeomImageable imageable(prim); + const GfBBox3d box + = imageable.ComputeLocalBound(usdTime, purpose1, purpose2, purpose3, purpose4); + const GfRange3d range = box.GetRange(); + const GfVec3d usdMin = range.IsEmpty() ? GfVec3d(0.0, 0.0, 0.0) : range.GetMin(); + const GfVec3d usdMax = range.IsEmpty() ? GfVec3d(0.0, 0.0, 0.0) : range.GetMax(); + bbox.expand(MPoint(usdMin[0], usdMin[1], usdMin[2])); + bbox.expand(MPoint(usdMax[0], usdMax[1], usdMax[2])); + MMatrix mayaMx; + const double* matrixArray = box.GetMatrix().GetArray(); + std::copy(matrixArray, matrixArray + 16, mayaMx[0]); + bbox.transformUsing(mayaMx); + } + + return bbox; } //---------------------------------------------------------------------------------------------------------------------- MStatus Scope::connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) { - if(!asSrc && plug == m_inStageData) - { - MFnDependencyNode otherNode(otherPlug.node()); - if (otherNode.typeId() == ProxyShape::kTypeId) - { - proxyShapeHandle = otherPlug.node(); + if (!asSrc && plug == m_inStageData) { + MFnDependencyNode otherNode(otherPlug.node()); + if (otherNode.typeId() == ProxyShape::kTypeId) { + proxyShapeHandle = otherPlug.node(); + } } - } - return MPxTransform::connectionMade(plug, otherPlug, asSrc); + return MPxTransform::connectionMade(plug, otherPlug, asSrc); } //---------------------------------------------------------------------------------------------------------------------- MStatus Scope::connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) { - if(!asSrc && plug == m_inStageData) - { - MFnDependencyNode otherNode(otherPlug.node()); - if (otherNode.typeId() == ProxyShape::kTypeId) - { - proxyShapeHandle = MObject(); + if (!asSrc && plug == m_inStageData) { + MFnDependencyNode otherNode(otherPlug.node()); + if (otherNode.typeId() == ProxyShape::kTypeId) { + proxyShapeHandle = MObject(); + } } - } - return MPxTransform::connectionBroken(plug, otherPlug, asSrc); + return MPxTransform::connectionBroken(plug, otherPlug, asSrc); } //---------------------------------------------------------------------------------------------------------------------- -MStatus Scope::validateAndSetValue(const MPlug& plug, const MDataHandle& handle, const MDGContext& context) +MStatus +Scope::validateAndSetValue(const MPlug& plug, const MDataHandle& handle, const MDGContext& context) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Scope::validateAndSetValue %s\n", plug.name().asChar()); - - if (plug.isNull()) - return MS::kFailure; - - if (plug.isLocked()) - return MS::kSuccess; - - if (plug.isChild() && plug.parent().isLocked()) - return MS::kSuccess; - - if(plug == m_inStageData) - { - MDataBlock dataBlock = forceCache(*(MDGContext *)&context); - MayaUsdStageData* data = inputDataValue(dataBlock, m_inStageData); - if (data && data->stage) - { - MString path = inputStringValue(dataBlock, m_primPath); - SdfPath primPath; - UsdPrim usdPrim; - if(path.length()) - { - primPath = SdfPath(path.asChar()); - usdPrim = data->stage->GetPrimAtPath(primPath); - } - transform()->setPrim(usdPrim, this); - } - else - { - transform()->setPrim(UsdPrim(), this); - } - return MS::kSuccess; - } - else - if(plug == m_primPath) - { - MDataBlock dataBlock = forceCache(*(MDGContext *)&context); - MString path = handle.asString(); - outputStringValue(dataBlock, m_primPath, path); - - MayaUsdStageData* data = inputDataValue(dataBlock, m_inStageData); - if (data && data->stage) - { - SdfPath primPath; - UsdPrim usdPrim; - if(path.length()) - { - primPath = SdfPath(path.asChar()); - usdPrim = UsdPrim(data->stage->GetPrimAtPath(primPath)); - } - transform()->setPrim(usdPrim, this); - } - else - { - if (path.length() > 0) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Could not set '%s' to '%s' - could not retrieve stage\n", - plug.name().asChar(), path.asChar()); - } - transform()->setPrim(UsdPrim(), this); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Scope::validateAndSetValue %s\n", plug.name().asChar()); + + if (plug.isNull()) + return MS::kFailure; + + if (plug.isLocked()) + return MS::kSuccess; + + if (plug.isChild() && plug.parent().isLocked()) + return MS::kSuccess; + + if (plug == m_inStageData) { + MDataBlock dataBlock = forceCache(*(MDGContext*)&context); + MayaUsdStageData* data = inputDataValue(dataBlock, m_inStageData); + if (data && data->stage) { + MString path = inputStringValue(dataBlock, m_primPath); + SdfPath primPath; + UsdPrim usdPrim; + if (path.length()) { + primPath = SdfPath(path.asChar()); + usdPrim = data->stage->GetPrimAtPath(primPath); + } + transform()->setPrim(usdPrim, this); + } else { + transform()->setPrim(UsdPrim(), this); + } + return MS::kSuccess; + } else if (plug == m_primPath) { + MDataBlock dataBlock = forceCache(*(MDGContext*)&context); + MString path = handle.asString(); + outputStringValue(dataBlock, m_primPath, path); + + MayaUsdStageData* data = inputDataValue(dataBlock, m_inStageData); + if (data && data->stage) { + SdfPath primPath; + UsdPrim usdPrim; + if (path.length()) { + primPath = SdfPath(path.asChar()); + usdPrim = UsdPrim(data->stage->GetPrimAtPath(primPath)); + } + transform()->setPrim(usdPrim, this); + } else { + if (path.length() > 0) { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "Could not set '%s' to '%s' - could not retrieve stage\n", + plug.name().asChar(), + path.asChar()); + } + transform()->setPrim(UsdPrim(), this); + } + return MS::kSuccess; } return MS::kSuccess; - } - return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Scope.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Scope.h index 69762ce8d4..f9a343d751 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Scope.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Scope.h @@ -18,13 +18,13 @@ #include "AL/maya/utils/MayaHelperMacros.h" #include "AL/maya/utils/NodeHelper.h" #include "AL/usdmaya/TypeIDs.h" +#include "AL/usdmaya/nodes/BasicTransformationMatrix.h" + +#include #include #include #include -#include "AL/usdmaya/nodes/BasicTransformationMatrix.h" - -#include namespace AL { namespace usdmaya { @@ -32,13 +32,16 @@ namespace nodes { //---------------------------------------------------------------------------------------------------------------------- /// \brief The AL::usdmaya::nodes::Scope node is a custom transform node that represents a USD -// scope type prim directly from inside Maya. It works by providing a custom MPxTransform node which uses a +// scope type prim directly from inside Maya. It works by providing a custom MPxTransform +// node which uses a /// custom MPxTransformationMatrix type (AL::usdmaya::nodes::BasicTransformationMatrix). /// -/// As it's fairly simple, we also use it as the interface for other Transform implementations +/// As it's fairly simple, we also use it as the interface for other Transform +/// implementations /// /// Typically this node should have one input connection: -/// \li \b inStageData - connected from the output stage data of an AL::usdmaya::nodes::ProxyShape +/// \li \b inStageData - connected from the output stage data of an +/// AL::usdmaya::nodes::ProxyShape /// /// The following attribute determines which UsdPrim is being watched: /// \li \b primPath - a Usd path of the prim being watched, e.g. "/root/foo/pCube1" @@ -48,89 +51,89 @@ namespace nodes { #if MAYA_API_VERSION >= 20190200 && MAYA_API_VERSION < 20200000 class Scope - : public MPxTransform_BoundingBox, - public AL::maya::utils::NodeHelper + : public MPxTransform_BoundingBox + , public AL::maya::utils::NodeHelper #else class Scope - : public MPxTransform, - public AL::maya::utils::NodeHelper + : public MPxTransform + , public AL::maya::utils::NodeHelper #endif { public: + Scope(); + virtual ~Scope(); - Scope(); - virtual ~Scope(); + //-------------------------------------------------------------------------------------------------------------------- + // Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- + AL_MAYA_DECLARE_NODE(); - //-------------------------------------------------------------------------------------------------------------------- - // Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- - AL_MAYA_DECLARE_NODE(); + //-------------------------------------------------------------------------------------------------------------------- + // Input Attributes + //-------------------------------------------------------------------------------------------------------------------- + AL_DECL_ATTRIBUTE(primPath); + AL_DECL_ATTRIBUTE(inStageData); - //-------------------------------------------------------------------------------------------------------------------- - // Input Attributes - //-------------------------------------------------------------------------------------------------------------------- - AL_DECL_ATTRIBUTE(primPath); - AL_DECL_ATTRIBUTE(inStageData); + //-------------------------------------------------------------------------------------------------------------------- + /// \name Methods + //-------------------------------------------------------------------------------------------------------------------- - //-------------------------------------------------------------------------------------------------------------------- - /// \name Methods - //-------------------------------------------------------------------------------------------------------------------- + /// \brief returns the transformation matrix for this transform node + /// \return the transformation matrix + inline BasicTransformationMatrix* transform() const + { + return reinterpret_cast(transformationMatrixPtr()); + } - /// \brief returns the transformation matrix for this transform node - /// \return the transformation matrix - inline BasicTransformationMatrix* transform() const - { return reinterpret_cast(transformationMatrixPtr()); } + virtual const MObject getProxyShape() const { return proxyShapeHandle.object(); } - virtual const MObject getProxyShape() const - { return proxyShapeHandle.object(); } - - MBoundingBox boundingBox() const override; + MBoundingBox boundingBox() const override; protected: - - //-------------------------------------------------------------------------------------------------------------------- - /// virtual overrides - //-------------------------------------------------------------------------------------------------------------------- - MStatus compute(const MPlug &plug, MDataBlock &datablock) override; + //-------------------------------------------------------------------------------------------------------------------- + /// virtual overrides + //-------------------------------------------------------------------------------------------------------------------- + MStatus compute(const MPlug& plug, MDataBlock& datablock) override; private: - MPxNode::SchedulingType schedulingType() const override - { return kParallel; } - - MStatus validateAndSetValue(const MPlug& plug, const MDataHandle& handle, const MDGContext& context) override; - MPxTransformationMatrix* createTransformationMatrix() override; - void postConstructor() override; - MStatus connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; - MStatus connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; - bool isBounded() const override - { return true; } - bool treatAsTransform() const override - { return false; } - - //-------------------------------------------------------------------------------------------------------------------- - /// \name Input Attributes - //-------------------------------------------------------------------------------------------------------------------- - - /// \var MPlug primPathPlug() const; - /// \brief access the primPath attribute plug on this node instance. - /// primPath - a Usd path of the prim being watched, e.g. "/root/foo/pCube1" - /// \return the plug to the primPath attribute - /// \var MPlug inStageDataPlug() const; - /// \brief access the inStageData attribute plug on this node instance - /// inStageData - connected from the output stage data of an AL::usdmaya::nodes::ProxyShape - /// \return the plug to the inStageData attribute - /// \var static MObject primPath(); - /// \brief access the primPath attribute handle - /// \return the primPath attribute - /// \var static MObject inStageData(); - /// \brief access the inStageData attribute handle - /// \return the inStageData attribute - - MObjectHandle proxyShapeHandle; + MPxNode::SchedulingType schedulingType() const override { return kParallel; } + + MStatus validateAndSetValue( + const MPlug& plug, + const MDataHandle& handle, + const MDGContext& context) override; + MPxTransformationMatrix* createTransformationMatrix() override; + void postConstructor() override; + MStatus connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; + MStatus connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; + bool isBounded() const override { return true; } + bool treatAsTransform() const override { return false; } + + //-------------------------------------------------------------------------------------------------------------------- + /// \name Input Attributes + //-------------------------------------------------------------------------------------------------------------------- + + /// \var MPlug primPathPlug() const; + /// \brief access the primPath attribute plug on this node instance. + /// primPath - a Usd path of the prim being watched, e.g. "/root/foo/pCube1" + /// \return the plug to the primPath attribute + /// \var MPlug inStageDataPlug() const; + /// \brief access the inStageData attribute plug on this node instance + /// inStageData - connected from the output stage data of an + /// AL::usdmaya::nodes::ProxyShape + /// \return the plug to the inStageData attribute + /// \var static MObject primPath(); + /// \brief access the primPath attribute handle + /// \return the primPath attribute + /// \var static MObject inStageData(); + /// \brief access the inStageData attribute handle + /// \return the inStageData attribute + + MObjectHandle proxyShapeHandle; }; //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Transform.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Transform.cpp index 3fc44654bb..14ba32ae47 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Transform.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Transform.cpp @@ -13,13 +13,15 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/TypeIDs.h" +#include "AL/usdmaya/nodes/Transform.h" + #include "AL/usdmaya/DebugCodes.h" -#include +#include "AL/usdmaya/TypeIDs.h" #include "AL/usdmaya/nodes/ProxyShape.h" -#include "AL/usdmaya/nodes/Transform.h" #include "AL/usdmaya/nodes/TransformationMatrix.h" +#include + #include #include @@ -27,22 +29,20 @@ #include namespace { - // Simple RAII class to ensure boolean gets set to false when done. - struct TempBoolLock - { - TempBoolLock(bool& theVal) : theRef(theVal) +// Simple RAII class to ensure boolean gets set to false when done. +struct TempBoolLock +{ + TempBoolLock(bool& theVal) + : theRef(theVal) { - theRef = true; + theRef = true; } - ~TempBoolLock() - { - theRef = false; - } + ~TempBoolLock() { theRef = false; } bool& theRef; - }; -} +}; +} // namespace namespace AL { namespace usdmaya { @@ -65,418 +65,382 @@ MObject Transform::m_readAnimatedValues = MObject::kNullObj; //---------------------------------------------------------------------------------------------------------------------- void Transform::postConstructor() { - transform()->setMObject(thisMObject()); - getTransMatrix()->enablePushToPrim(pushToPrimPlug().asBool()); + transform()->setMObject(thisMObject()); + getTransMatrix()->enablePushToPrim(pushToPrimPlug().asBool()); } //---------------------------------------------------------------------------------------------------------------------- -Transform::Transform() -{ -} +Transform::Transform() { } //---------------------------------------------------------------------------------------------------------------------- -Transform::~Transform() -{ -} +Transform::~Transform() { } //---------------------------------------------------------------------------------------------------------------------- MPxTransformationMatrix* Transform::createTransformationMatrix() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Transform::createTransformationMatrix\n"); - return new TransformationMatrix; + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Transform::createTransformationMatrix\n"); + return new TransformationMatrix; } //---------------------------------------------------------------------------------------------------------------------- bool Transform::setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) { - if(plug == m_pushToPrim) - { - getTransMatrix()->enablePushToPrim(dataHandle.asBool()); - } - return MPxTransform::setInternalValue(plug, dataHandle); + if (plug == m_pushToPrim) { + getTransMatrix()->enablePushToPrim(dataHandle.asBool()); + } + return MPxTransform::setInternalValue(plug, dataHandle); } //---------------------------------------------------------------------------------------------------------------------- MStatus Transform::initialise() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Transform::initialise\n"); - const char* const errorString = "Transform::initialise"; - try - { - setNodeType(kTypeName); - inheritAttributesFrom("AL_usdmaya_Scope"); - - addFrame("USD Prim Information"); - addFrameAttr("primPath", kReadable | kWritable | kStorable | kConnectable | kAffectsWorldSpace); - addFrameAttr("inStageData", kWritable | kStorable | kConnectable | kHidden | kAffectsWorldSpace); - - addFrame("USD Timing Information"); - m_time = addTimeAttr("time", "tm", MTime(0.0), kKeyable | kConnectable | kReadable | kWritable | kStorable | kAffectsWorldSpace); - m_timeOffset = addTimeAttr("timeOffset", "tmo", MTime(0.0), kKeyable | kConnectable | kReadable | kWritable | kStorable | kAffectsWorldSpace); - m_timeScalar = addDoubleAttr("timeScalar", "tms", 1.0, kKeyable | kConnectable | kReadable | kWritable | kStorable | kAffectsWorldSpace); - m_outTime = addTimeAttr("outTime", "otm", MTime(0.0), kConnectable | kReadable | kAffectsWorldSpace); - - addFrame("USD Experimental Features"); - m_localTranslateOffset = addVectorAttr("localTranslateOffset", "lto", MVector(0,0,0), kReadable | kWritable | kStorable | kConnectable | kAffectsWorldSpace); - m_pushToPrim = addBoolAttr("pushToPrim", "ptp", false, kReadable | kWritable | kStorable | kInternal); - m_readAnimatedValues = addBoolAttr("readAnimatedValues", "rav", true, kReadable | kWritable | kStorable | kAffectsWorldSpace); - - mustCallValidateAndSet(m_time); - mustCallValidateAndSet(m_timeOffset); - mustCallValidateAndSet(m_timeScalar); - mustCallValidateAndSet(m_localTranslateOffset); - mustCallValidateAndSet(m_pushToPrim); - mustCallValidateAndSet(m_primPath); - mustCallValidateAndSet(m_readAnimatedValues); - mustCallValidateAndSet(m_inStageData); - - - AL_MAYA_CHECK_ERROR(attributeAffects(m_time, m_outTime), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(m_timeOffset, m_outTime), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(m_timeScalar, m_outTime), errorString); - - for(auto& inAttr : {m_time, m_timeOffset, m_timeScalar, m_readAnimatedValues}) - { - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, translate), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotate), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotateOrder), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scale), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, shear), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotatePivot), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotatePivotTranslate), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scalePivot), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scalePivotTranslate), errorString); - // Maya 2018 (checked 2018.2 and 2018.3) has a bug where, if any loaded plugin has an MPxTransform subclass - // that has ANY attribute that connected to rotateAxis, it will cause the rotateAxis to evaluate INCORRECTLY, - // even on the BASE transform class! - // See this gist for full reproduction details: - // https://gist.github.com/elrond79/f9ddb277da3eab2948d27ddb1f84aba0 + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Transform::initialise\n"); + const char* const errorString = "Transform::initialise"; + try { + setNodeType(kTypeName); + inheritAttributesFrom("AL_usdmaya_Scope"); + + addFrame("USD Prim Information"); + addFrameAttr( + "primPath", kReadable | kWritable | kStorable | kConnectable | kAffectsWorldSpace); + addFrameAttr( + "inStageData", kWritable | kStorable | kConnectable | kHidden | kAffectsWorldSpace); + + addFrame("USD Timing Information"); + m_time = addTimeAttr( + "time", + "tm", + MTime(0.0), + kKeyable | kConnectable | kReadable | kWritable | kStorable | kAffectsWorldSpace); + m_timeOffset = addTimeAttr( + "timeOffset", + "tmo", + MTime(0.0), + kKeyable | kConnectable | kReadable | kWritable | kStorable | kAffectsWorldSpace); + m_timeScalar = addDoubleAttr( + "timeScalar", + "tms", + 1.0, + kKeyable | kConnectable | kReadable | kWritable | kStorable | kAffectsWorldSpace); + m_outTime = addTimeAttr( + "outTime", "otm", MTime(0.0), kConnectable | kReadable | kAffectsWorldSpace); + + addFrame("USD Experimental Features"); + m_localTranslateOffset = addVectorAttr( + "localTranslateOffset", + "lto", + MVector(0, 0, 0), + kReadable | kWritable | kStorable | kConnectable | kAffectsWorldSpace); + m_pushToPrim = addBoolAttr( + "pushToPrim", "ptp", false, kReadable | kWritable | kStorable | kInternal); + m_readAnimatedValues = addBoolAttr( + "readAnimatedValues", + "rav", + true, + kReadable | kWritable | kStorable | kAffectsWorldSpace); + + mustCallValidateAndSet(m_time); + mustCallValidateAndSet(m_timeOffset); + mustCallValidateAndSet(m_timeScalar); + mustCallValidateAndSet(m_localTranslateOffset); + mustCallValidateAndSet(m_pushToPrim); + mustCallValidateAndSet(m_primPath); + mustCallValidateAndSet(m_readAnimatedValues); + mustCallValidateAndSet(m_inStageData); + + AL_MAYA_CHECK_ERROR(attributeAffects(m_time, m_outTime), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(m_timeOffset, m_outTime), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(m_timeScalar, m_outTime), errorString); + + for (auto& inAttr : { m_time, m_timeOffset, m_timeScalar, m_readAnimatedValues }) { + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, translate), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotate), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotateOrder), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scale), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, shear), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotatePivot), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotatePivotTranslate), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scalePivot), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, scalePivotTranslate), errorString); + // Maya 2018 (checked 2018.2 and 2018.3) has a bug where, if any loaded plugin has an + // MPxTransform subclass that has ANY attribute that connected to rotateAxis, it will + // cause the rotateAxis to evaluate INCORRECTLY, even on the BASE transform class! See + // this gist for full reproduction details: + // https://gist.github.com/elrond79/f9ddb277da3eab2948d27ddb1f84aba0 #if MAYA_API_VERSION >= 20180600 - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotateAxis), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, rotateAxis), errorString); #endif - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, matrix), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, worldMatrix), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, inverseMatrix), errorString); - AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, worldInverseMatrix), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, matrix), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, worldMatrix), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, inverseMatrix), errorString); + AL_MAYA_CHECK_ERROR(attributeAffects(inAttr, worldInverseMatrix), errorString); + } + } catch (const MStatus& status) { + return status; } - } - catch(const MStatus& status) - { - return status; - } - - addBaseTemplate("AEtransformMain"); - addBaseTemplate("AEtransformNoScroll"); - addBaseTemplate("AEtransformSkinCluster"); - generateAETemplate(); - - return MS::kSuccess; + + addBaseTemplate("AEtransformMain"); + addBaseTemplate("AEtransformNoScroll"); + addBaseTemplate("AEtransformSkinCluster"); + generateAETemplate(); + + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus Transform::compute(const MPlug& plug, MDataBlock& dataBlock) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Transform::compute %s\n", plug.name().asChar()); - if(plug == m_time || plug == m_timeOffset || plug == m_timeScalar || plug == m_outTime) - { - updateTransform(dataBlock); - return MS::kSuccess; - } - else - if(plug == m_inStageData) - { - // This should only be computed if there's no connection, so set it to an empty stage - // create new stage data - MObject data; - auto* usdStageData = createData(MayaUsdStageData::mayaTypeId, data); - if(!usdStageData) - { - return MS::kFailure; + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Transform::compute %s\n", plug.name().asChar()); + if (plug == m_time || plug == m_timeOffset || plug == m_timeScalar || plug == m_outTime) { + updateTransform(dataBlock); + return MS::kSuccess; + } else if (plug == m_inStageData) { + // This should only be computed if there's no connection, so set it to an empty stage + // create new stage data + MObject data; + auto* usdStageData = createData(MayaUsdStageData::mayaTypeId, data); + if (!usdStageData) { + return MS::kFailure; + } + + // set the cached output value, and flush + MStatus status = outputDataValue(dataBlock, m_inStageData, usdStageData); + if (!status) { + return MS::kFailure; + } + return status; } - // set the cached output value, and flush - MStatus status = outputDataValue(dataBlock, m_inStageData, usdStageData); - if(!status) - { - return MS::kFailure; + // If the time is dirty, we need to make sure we calculate / update that BEFORE calculating our + // transform. Otherwise, we may read info for the wrong time from usd - and even worse, we may + // push that out-of-date info back to usd! So, we always trigger a compute of outTime to make + // sure it's up to date... + + if (!dataBlock.isClean(m_outTime) && !plug.isNull()) { + // instead of checking if the attr is one in a giant list of attrs affected by m_time, I + // just check if it's affected by world space. + MStatus status; + MFnAttribute plugAttr(plug.attribute(), &status); + AL_MAYA_CHECK_ERROR(status, "error retrieving attribute"); + if (plugAttr.isAffectsWorldSpace()) { + // NOTE: initially thought that I could just fetch value of "m_time" with + // inputTimeValue...but it appears there's a bug where validateAndSetValue is not called + // if there's an incoming connection to m_time, and we're not in GUI mode. So we just + // get the outTime, and rely on it's compute; since it's not writable, it's compute + // should always be called. + inputTimeValue(dataBlock, m_outTime); + } } - return status; - } - - // If the time is dirty, we need to make sure we calculate / update that BEFORE calculating our transform. Otherwise, - // we may read info for the wrong time from usd - and even worse, we may push that out-of-date info back to usd! - // So, we always trigger a compute of outTime to make sure it's up to date... - - if (!dataBlock.isClean(m_outTime) && !plug.isNull()) - { - // instead of checking if the attr is one in a giant list of attrs affected by m_time, I just check if it's - // affected by world space. - MStatus status; - MFnAttribute plugAttr(plug.attribute(), &status); - AL_MAYA_CHECK_ERROR(status, "error retrieving attribute"); - if (plugAttr.isAffectsWorldSpace()) - { - // NOTE: initially thought that I could just fetch value of "m_time" with inputTimeValue...but it appears there's - // a bug where validateAndSetValue is not called if there's an incoming connection to m_time, and we're not in GUI - // mode. So we just get the outTime, and rely on it's compute; since it's not writable, it's compute should always - // be called. - inputTimeValue(dataBlock, m_outTime); - } - } - return Scope::compute(plug, dataBlock); + return Scope::compute(plug, dataBlock); } //---------------------------------------------------------------------------------------------------------------------- void Transform::updateTransform(MDataBlock& dataBlock) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Transform::updateTransform\n"); - - // It's possible that the calls to inputTimeValue below will ALSO trigger a call to - // updateTransform; since there's no need to run this twice, we check for this and - // abort if we're already in the middle of running. - // Note that we don't bother using, say, std::atomic_flag, because multithreaded - // collisions here seem unlikely, and the worst case is just that this function runs twice. - if (updateTransformInProgress) return; - - TempBoolLock updateTransformLock(updateTransformInProgress); - - // compute updated time value - MTime theTime = (inputTimeValue(dataBlock, m_time) - inputTimeValue(dataBlock, m_timeOffset)) * inputDoubleValue(dataBlock, m_timeScalar); - outputTimeValue(dataBlock, m_outTime, theTime); - - UsdTimeCode usdTime(theTime.as(MTime::uiUnit())); - - // update the transformation matrix to the values at the specified time - TransformationMatrix* m = getTransMatrix(); - m->updateToTime(usdTime); - - // if translation animation is present, update the translate attribute (or just flag it as clean if no animation exists) - if(m->hasAnimatedTranslation()) - { - outputVectorValue(dataBlock, MPxTransform::translate, m->translation(MSpace::kTransform)); - } - else - { - dataBlock.setClean(MPxTransform::translate); - } - - // if rotation animation is present, update the rotate attribute (or just flag it as clean if no animation exists) - if(m->hasAnimatedRotation()) - { - outputEulerValue(dataBlock, MPxTransform::rotate, m->eulerRotation(MSpace::kTransform)); - } - else - { - dataBlock.setClean(MPxTransform::rotate); - } - - // if scale animation is present, update the scale attribute (or just flag it as clean if no animation exists) - if(m->hasAnimatedScale()) - { - outputVectorValue(dataBlock, MPxTransform::scale, m->scale(MSpace::kTransform)); - } - else - { - dataBlock.setClean(MPxTransform::scale); - } - - // if translation animation is present, update the translate attribute (or just flag it as clean if no animation exists) - if(m->hasAnimatedMatrix()) - { - outputVectorValue(dataBlock, MPxTransform::scale, m->scale(MSpace::kTransform)); - outputEulerValue(dataBlock, MPxTransform::rotate, m->eulerRotation(MSpace::kTransform)); - outputVectorValue(dataBlock, MPxTransform::translate, m->translation(MSpace::kTransform)); - } - else - { - dataBlock.setClean(MPxTransform::scale); - dataBlock.setClean(MPxTransform::rotate); - dataBlock.setClean(MPxTransform::translate); - } + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Transform::updateTransform\n"); + + // It's possible that the calls to inputTimeValue below will ALSO trigger a call to + // updateTransform; since there's no need to run this twice, we check for this and + // abort if we're already in the middle of running. + // Note that we don't bother using, say, std::atomic_flag, because multithreaded + // collisions here seem unlikely, and the worst case is just that this function runs twice. + if (updateTransformInProgress) + return; + + TempBoolLock updateTransformLock(updateTransformInProgress); + + // compute updated time value + MTime theTime = (inputTimeValue(dataBlock, m_time) - inputTimeValue(dataBlock, m_timeOffset)) + * inputDoubleValue(dataBlock, m_timeScalar); + outputTimeValue(dataBlock, m_outTime, theTime); + + UsdTimeCode usdTime(theTime.as(MTime::uiUnit())); + + // update the transformation matrix to the values at the specified time + TransformationMatrix* m = getTransMatrix(); + m->updateToTime(usdTime); + + // if translation animation is present, update the translate attribute (or just flag it as clean + // if no animation exists) + if (m->hasAnimatedTranslation()) { + outputVectorValue(dataBlock, MPxTransform::translate, m->translation(MSpace::kTransform)); + } else { + dataBlock.setClean(MPxTransform::translate); + } + + // if rotation animation is present, update the rotate attribute (or just flag it as clean if no + // animation exists) + if (m->hasAnimatedRotation()) { + outputEulerValue(dataBlock, MPxTransform::rotate, m->eulerRotation(MSpace::kTransform)); + } else { + dataBlock.setClean(MPxTransform::rotate); + } + + // if scale animation is present, update the scale attribute (or just flag it as clean if no + // animation exists) + if (m->hasAnimatedScale()) { + outputVectorValue(dataBlock, MPxTransform::scale, m->scale(MSpace::kTransform)); + } else { + dataBlock.setClean(MPxTransform::scale); + } + + // if translation animation is present, update the translate attribute (or just flag it as clean + // if no animation exists) + if (m->hasAnimatedMatrix()) { + outputVectorValue(dataBlock, MPxTransform::scale, m->scale(MSpace::kTransform)); + outputEulerValue(dataBlock, MPxTransform::rotate, m->eulerRotation(MSpace::kTransform)); + outputVectorValue(dataBlock, MPxTransform::translate, m->translation(MSpace::kTransform)); + } else { + dataBlock.setClean(MPxTransform::scale); + dataBlock.setClean(MPxTransform::rotate); + dataBlock.setClean(MPxTransform::translate); + } } //---------------------------------------------------------------------------------------------------------------------- MStatus Transform::connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) { - if(!asSrc && plug == m_inStageData) - { - MFnDependencyNode otherNode(otherPlug.node()); - if (otherNode.typeId() == ProxyShape::kTypeId) - { - proxyShapeHandle = otherPlug.node(); + if (!asSrc && plug == m_inStageData) { + MFnDependencyNode otherNode(otherPlug.node()); + if (otherNode.typeId() == ProxyShape::kTypeId) { + proxyShapeHandle = otherPlug.node(); + } } - } - return MPxTransform::connectionMade(plug, otherPlug, asSrc); + return MPxTransform::connectionMade(plug, otherPlug, asSrc); } //---------------------------------------------------------------------------------------------------------------------- MStatus Transform::connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) { - if(!asSrc && plug == m_inStageData) - { - MFnDependencyNode otherNode(otherPlug.node()); - if (otherNode.typeId() == ProxyShape::kTypeId) - { - proxyShapeHandle = MObject(); + if (!asSrc && plug == m_inStageData) { + MFnDependencyNode otherNode(otherPlug.node()); + if (otherNode.typeId() == ProxyShape::kTypeId) { + proxyShapeHandle = MObject(); + } } - } - return MPxTransform::connectionBroken(plug, otherPlug, asSrc); + return MPxTransform::connectionBroken(plug, otherPlug, asSrc); } //---------------------------------------------------------------------------------------------------------------------- -// If any value changes, that affects the resulting transform (the non-animated m_localTranslateOffset value is a good -// example), then it only needs to be set here. If an attribute drives one of the TRS components (e.g. 'time' modifies -// the translate / rotate / scale values), then it needs to be set here, and it also needs to be handled in the compute -// method. That doesn't feel quite right to me, to that is how it appears to work? (If you have any better ideas, -// I'm all ears!). +// If any value changes, that affects the resulting transform (the non-animated +// m_localTranslateOffset value is a good example), then it only needs to be set here. If an +// attribute drives one of the TRS components (e.g. 'time' modifies the translate / rotate / scale +// values), then it needs to be set here, and it also needs to be handled in the compute method. +// That doesn't feel quite right to me, to that is how it appears to work? (If you have any better +// ideas, I'm all ears!). // -MStatus Transform::validateAndSetValue(const MPlug& plug, const MDataHandle& handle, const MDGContext& context) +MStatus Transform::validateAndSetValue( + const MPlug& plug, + const MDataHandle& handle, + const MDGContext& context) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Transform::validateAndSetValue %s\n", plug.name().asChar()); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Transform::validateAndSetValue %s\n", plug.name().asChar()); - if (plug.isNull()) - return MS::kFailure; + if (plug.isNull()) + return MS::kFailure; - if (plug.isLocked()) - return MS::kSuccess; + if (plug.isLocked()) + return MS::kSuccess; - if (plug.isChild() && plug.parent().isLocked()) - return MS::kSuccess; + if (plug.isChild() && plug.parent().isLocked()) + return MS::kSuccess; - // If the time values are changed, store the new values, and then update the transform - if (plug == m_time || plug == m_timeOffset || plug == m_timeScalar) - { - MDataBlock dataBlock = forceCache(*(MDGContext *)&context); - if(plug == m_time) - { - outputTimeValue(dataBlock, m_time, handle.asTime()); - } - else - if(plug == m_timeOffset) - { - outputTimeValue(dataBlock, m_timeOffset, handle.asTime()); - } - else - if(plug == m_timeScalar) - { - outputDoubleValue(dataBlock, m_timeScalar, handle.asDouble()); - } - + // If the time values are changed, store the new values, and then update the transform + if (plug == m_time || plug == m_timeOffset || plug == m_timeScalar) { + MDataBlock dataBlock = forceCache(*(MDGContext*)&context); + if (plug == m_time) { + outputTimeValue(dataBlock, m_time, handle.asTime()); + } else if (plug == m_timeOffset) { + outputTimeValue(dataBlock, m_timeOffset, handle.asTime()); + } else if (plug == m_timeScalar) { + outputDoubleValue(dataBlock, m_timeScalar, handle.asDouble()); + } - updateTransform(dataBlock); - return MS::kSuccess; - } - else - // The local translate offset doesn't drive the TRS, so set the value here, and the transformation update - // should be handled by the MPxTransform without any additional faffing around in compute. - if(plug == m_localTranslateOffset || plug.parent() == m_localTranslateOffset) - { - MPlug parentPlug = plug.parent(); - MVector offset; - // getting access to the X/Y/Z components of the translation offset is a bit of a faff - if(plug == m_localTranslateOffset) - { - offset = handle.asVector(); - } - else - if(parentPlug.child(0) == plug) - { - offset.x = handle.asDouble(); - } - else - if(parentPlug.child(1) == plug) - { - offset.y = handle.asDouble(); - } - else - if(parentPlug.child(2) == plug) - { - offset.z = handle.asDouble(); - } - - MDataBlock dataBlock = forceCache(*(MDGContext *)&context); - outputVectorValue(dataBlock, m_localTranslateOffset, offset); - getTransMatrix()->setLocalTranslationOffset(offset); - return MS::kSuccess; - } - else - if(plug == m_pushToPrim) - { - MDataBlock dataBlock = forceCache(*(MDGContext *)&context); - getTransMatrix()->enablePushToPrim(handle.asBool()); - outputBoolValue(dataBlock, m_pushToPrim, handle.asBool()); - return MS::kSuccess; - } - else - if(plug == m_readAnimatedValues) - { - MDataBlock dataBlock = forceCache(*(MDGContext *)&context); - getTransMatrix()->enableReadAnimatedValues(handle.asBool()); - outputBoolValue(dataBlock, m_readAnimatedValues, handle.asBool()); - updateTransform(dataBlock); - return MS::kSuccess; - } - else - if(plug == m_inStageData) - { - MDataBlock dataBlock = forceCache(*(MDGContext *)&context); - auto* data = inputDataValue(dataBlock, m_inStageData); - if (data && data->stage) - { - MString path = inputStringValue(dataBlock, m_primPath); - SdfPath primPath; - UsdPrim usdPrim; - if(path.length()) - { - primPath = SdfPath(path.asChar()); - usdPrim = data->stage->GetPrimAtPath(primPath); - } - transform()->setPrim(usdPrim, this); - } - else - { - transform()->setPrim(UsdPrim(), this); - } - return MS::kSuccess; - } - else - if(plug == m_primPath) - { - MDataBlock dataBlock = forceCache(*(MDGContext *)&context); - MString path = handle.asString(); - outputStringValue(dataBlock, m_primPath, path); - - auto* data = inputDataValue(dataBlock, m_inStageData); - if (data && data->stage) - { - SdfPath primPath; - UsdPrim usdPrim; - if(path.length()) - { - primPath = SdfPath(path.asChar()); - usdPrim = UsdPrim(data->stage->GetPrimAtPath(primPath)); - } - transform()->setPrim(usdPrim, this); - if(usdPrim) updateTransform(dataBlock); + return MS::kSuccess; + } else + // The local translate offset doesn't drive the TRS, so set the value here, and the + // transformation update should be handled by the MPxTransform without any additional + // faffing around in compute. + if (plug == m_localTranslateOffset || plug.parent() == m_localTranslateOffset) { + MPlug parentPlug = plug.parent(); + MVector offset; + // getting access to the X/Y/Z components of the translation offset is a bit of a faff + if (plug == m_localTranslateOffset) { + offset = handle.asVector(); + } else if (parentPlug.child(0) == plug) { + offset.x = handle.asDouble(); + } else if (parentPlug.child(1) == plug) { + offset.y = handle.asDouble(); + } else if (parentPlug.child(2) == plug) { + offset.z = handle.asDouble(); + } + + MDataBlock dataBlock = forceCache(*(MDGContext*)&context); + outputVectorValue(dataBlock, m_localTranslateOffset, offset); + getTransMatrix()->setLocalTranslationOffset(offset); + return MS::kSuccess; + } else if (plug == m_pushToPrim) { + MDataBlock dataBlock = forceCache(*(MDGContext*)&context); + getTransMatrix()->enablePushToPrim(handle.asBool()); + outputBoolValue(dataBlock, m_pushToPrim, handle.asBool()); + return MS::kSuccess; + } else if (plug == m_readAnimatedValues) { + MDataBlock dataBlock = forceCache(*(MDGContext*)&context); + getTransMatrix()->enableReadAnimatedValues(handle.asBool()); + outputBoolValue(dataBlock, m_readAnimatedValues, handle.asBool()); + updateTransform(dataBlock); + return MS::kSuccess; + } else if (plug == m_inStageData) { + MDataBlock dataBlock = forceCache(*(MDGContext*)&context); + auto* data = inputDataValue(dataBlock, m_inStageData); + if (data && data->stage) { + MString path = inputStringValue(dataBlock, m_primPath); + SdfPath primPath; + UsdPrim usdPrim; + if (path.length()) { + primPath = SdfPath(path.asChar()); + usdPrim = data->stage->GetPrimAtPath(primPath); + } + transform()->setPrim(usdPrim, this); + } else { + transform()->setPrim(UsdPrim(), this); + } + return MS::kSuccess; + } else if (plug == m_primPath) { + MDataBlock dataBlock = forceCache(*(MDGContext*)&context); + MString path = handle.asString(); + outputStringValue(dataBlock, m_primPath, path); + + auto* data = inputDataValue(dataBlock, m_inStageData); + if (data && data->stage) { + SdfPath primPath; + UsdPrim usdPrim; + if (path.length()) { + primPath = SdfPath(path.asChar()); + usdPrim = UsdPrim(data->stage->GetPrimAtPath(primPath)); + } + transform()->setPrim(usdPrim, this); + if (usdPrim) + updateTransform(dataBlock); + } else { + if (path.length() > 0) { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg( + "Could not set '%s' to '%s' - could not retrieve stage\n", + plug.name().asChar(), + path.asChar()); + } + transform()->setPrim(UsdPrim(), this); + } + return MS::kSuccess; } - else - { - if (path.length() > 0) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Could not set '%s' to '%s' - could not retrieve stage\n", - plug.name().asChar(), path.asChar()); - } - transform()->setPrim(UsdPrim(), this); - } - return MS::kSuccess; - } - return MPxTransform::validateAndSetValue(plug, handle, context); + return MPxTransform::validateAndSetValue(plug, handle, context); } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Transform.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Transform.h index c5884f85e7..5947a9d665 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Transform.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/Transform.h @@ -15,9 +15,8 @@ // #pragma once -#include "AL/maya/utils/NodeHelper.h" #include "AL/maya/utils/MayaHelperMacros.h" - +#include "AL/maya/utils/NodeHelper.h" #include "AL/usdmaya/ForwardDeclares.h" #include "AL/usdmaya/nodes/Scope.h" @@ -31,21 +30,25 @@ namespace nodes { class TransformationMatrix; //---------------------------------------------------------------------------------------------------------------------- -/// \brief The AL::usdmaya::nodes::Transform node is a custom transform node that allows you to manipulate a USD -// transform type directly from inside Maya. It works by providing a custom MPxTransform node which uses a -/// custom MPxTransformationMatrix type (AL::usdmaya::nodes::TransformationMatrix). The custom transformation -/// matrix listens for changes that affect the transform (e.g. rotateBy, translateBy, etc), and if \b pushToPrim -/// is enabled, applies those changes to the USD transformation. +/// \brief The AL::usdmaya::nodes::Transform node is a custom transform node that allows you to +/// manipulate a USD +// transform type directly from inside Maya. It works by providing a custom MPxTransform +// node which uses a +/// custom MPxTransformationMatrix type (AL::usdmaya::nodes::TransformationMatrix). The +/// custom transformation matrix listens for changes that affect the transform (e.g. +/// rotateBy, translateBy, etc), and if \b pushToPrim is enabled, applies those changes to +/// the USD transformation. /// /// Typically this node should have two input connections: -/// \li \b inStageData - connected from the output stage data of an AL::usdmaya::nodes::ProxyShape -/// \li \b time - (probably) connected from the output time of an AL::usdmaya::nodes::ProxyShape, or directly to -/// the time1.outAttr or equivalent. +/// \li \b inStageData - connected from the output stage data of an +/// AL::usdmaya::nodes::ProxyShape \li \b time - (probably) connected from the output time +/// of an AL::usdmaya::nodes::ProxyShape, or directly to the time1.outAttr or equivalent. /// /// /// The following attributes can be used to scale and offset the time values: -/// \li \b timeOffset - an offset (in current UI time units) of say 30, means animation wont start until frame 30. -/// \li \b timeScalar - a speed multiplier. 2.0 will double the playback speed, 0.5 will halve it. +/// \li \b timeOffset - an offset (in current UI time units) of say 30, means animation +/// wont start until frame 30. \li \b timeScalar - a speed multiplier. 2.0 will double the +/// playback speed, 0.5 will halve it. /// /// /// The following attribute determines which UsdPrim is being watched: @@ -53,8 +56,9 @@ class TransformationMatrix; /// /// /// We then have these two attributes: -/// \li \b localTranslateOffset - an offset applied *after* all other transforms. Useful for positioning items on a table. -/// \li \b pushToPrim - When enabled, any changes you make to the transform values in maya, will be pushed back onto the USD primitive. +/// \li \b localTranslateOffset - an offset applied *after* all other transforms. Useful +/// for positioning items on a table. \li \b pushToPrim - When enabled, any changes you +/// make to the transform values in maya, will be pushed back onto the USD primitive. /// /// /// Finally we have the following outputs: @@ -62,171 +66,181 @@ class TransformationMatrix; /// /// /// \todo General todo list, and other quirks.... -/// -# pushToPrim when enabled, does not add transform operations into the UsdPrim it is tracking. So for -/// example, if you have a prim with no transform ops, not much is going to happen. If however your prim has -/// the full spectrum of rotate axis, translate, scale, rotate, shear, etc; then you will be able to have full -/// control over the prim. This will need to be addressed at some point soon. One of the more challenging -/// aspects here is that we will need to modify a) the geom op order [e.g. insert a scale op, where there -/// was not one before]; and b) rotation is going to be a PITA [There may be a rotateX op, but after -/// modification that may need to be deleted, and replaced with a rotateXYZ op] -/// -# If pushToPrim is disabled, any modifications to the transform values are stored as offsets from the USD -/// prim values. This works quite well for local space operations such as scale and rotation, semi-works -/// for translation [effectively this is a parent space translation offset - useful for moving an anim clip] -/// However for values such as rotation and scale pivots, yeah, the result might be a little strange. -/// -# I'm not convinced the way that I've organised compute and validateAndSetValue is ideal. It works, +/// -# pushToPrim when enabled, does not add transform operations into the UsdPrim it is +/// tracking. So for +/// example, if you have a prim with no transform ops, not much is going to happen. If +/// however your prim has the full spectrum of rotate axis, translate, scale, rotate, +/// shear, etc; then you will be able to have full control over the prim. This will need +/// to be addressed at some point soon. One of the more challenging aspects here is that +/// we will need to modify a) the geom op order [e.g. insert a scale op, where there was +/// not one before]; and b) rotation is going to be a PITA [There may be a rotateX op, +/// but after modification that may need to be deleted, and replaced with a rotateXYZ op] +/// -# If pushToPrim is disabled, any modifications to the transform values are stored as +/// offsets from the USD +/// prim values. This works quite well for local space operations such as scale and +/// rotation, semi-works for translation [effectively this is a parent space translation +/// offset - useful for moving an anim clip] However for values such as rotation and +/// scale pivots, yeah, the result might be a little strange. +/// -# I'm not convinced the way that I've organised compute and validateAndSetValue is +/// ideal. It works, /// but if anyone has some improvements to suggest, I'm all ears. -/// -# Generally speaking, when localTranslateOffset is (0,0,0), then the translate/rotate/scale tools work quite -/// well. If however localTranslateOffset is not (0,0,0), then the behaviour of the rotate tool is a little odd. -/// Really this should be taken into account within the AL::usdmaya::nodes::TransformationMatrix::rotateBy and +/// -# Generally speaking, when localTranslateOffset is (0,0,0), then the +/// translate/rotate/scale tools work quite +/// well. If however localTranslateOffset is not (0,0,0), then the behaviour of the +/// rotate tool is a little odd. Really this should be taken into account within the +/// AL::usdmaya::nodes::TransformationMatrix::rotateBy and /// AL::usdmaya::nodes::TransformationMatrix::rotateTo methods. /// -# If the usd prim xform stack has only one pivot, any separate modifications of /// scale/rotate pivot in maya will result in an undefined behavior. /// \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- -class Transform - : public Scope +class Transform : public Scope { public: - - Transform(); - ~Transform(); - - //-------------------------------------------------------------------------------------------------------------------- - // Type Info & Registration - //-------------------------------------------------------------------------------------------------------------------- - AL_MAYA_DECLARE_NODE(); - - //-------------------------------------------------------------------------------------------------------------------- - // Input Attributes - //-------------------------------------------------------------------------------------------------------------------- - AL_DECL_ATTRIBUTE(time); - AL_DECL_ATTRIBUTE(timeOffset); - AL_DECL_ATTRIBUTE(timeScalar); - AL_DECL_ATTRIBUTE(localTranslateOffset); - AL_DECL_ATTRIBUTE(pushToPrim); - AL_DECL_ATTRIBUTE(readAnimatedValues); - - //-------------------------------------------------------------------------------------------------------------------- - // Output Attributes - //-------------------------------------------------------------------------------------------------------------------- - AL_DECL_ATTRIBUTE(outTime); - - //-------------------------------------------------------------------------------------------------------------------- - /// \name Methods - //-------------------------------------------------------------------------------------------------------------------- - - const MObject getProxyShape() const override - { return proxyShapeHandle.object(); } - - - inline TransformationMatrix* getTransMatrix() const - { return reinterpret_cast(transformationMatrixPtr()); } + Transform(); + ~Transform(); + + //-------------------------------------------------------------------------------------------------------------------- + // Type Info & Registration + //-------------------------------------------------------------------------------------------------------------------- + AL_MAYA_DECLARE_NODE(); + + //-------------------------------------------------------------------------------------------------------------------- + // Input Attributes + //-------------------------------------------------------------------------------------------------------------------- + AL_DECL_ATTRIBUTE(time); + AL_DECL_ATTRIBUTE(timeOffset); + AL_DECL_ATTRIBUTE(timeScalar); + AL_DECL_ATTRIBUTE(localTranslateOffset); + AL_DECL_ATTRIBUTE(pushToPrim); + AL_DECL_ATTRIBUTE(readAnimatedValues); + + //-------------------------------------------------------------------------------------------------------------------- + // Output Attributes + //-------------------------------------------------------------------------------------------------------------------- + AL_DECL_ATTRIBUTE(outTime); + + //-------------------------------------------------------------------------------------------------------------------- + /// \name Methods + //-------------------------------------------------------------------------------------------------------------------- + + const MObject getProxyShape() const override { return proxyShapeHandle.object(); } + + inline TransformationMatrix* getTransMatrix() const + { + return reinterpret_cast(transformationMatrixPtr()); + } private: - - //-------------------------------------------------------------------------------------------------------------------- - /// virtual overrides - //-------------------------------------------------------------------------------------------------------------------- - - MPxNode::SchedulingType schedulingType() const override - { return kParallel; } - - MStatus validateAndSetValue(const MPlug& plug, const MDataHandle& handle, const MDGContext& context) override; - MPxTransformationMatrix* createTransformationMatrix() override; - MStatus compute(const MPlug &plug, MDataBlock &datablock) override; - void postConstructor() override; - MStatus connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; - MStatus connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; - bool setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) override; - bool isBounded() const override - { return true; } - bool treatAsTransform() const override - { return false; } - - //-------------------------------------------------------------------------------------------------------------------- - /// utils - //-------------------------------------------------------------------------------------------------------------------- - - void updateTransform(MDataBlock& dataBlock); - - //-------------------------------------------------------------------------------------------------------------------- - /// Data members - //-------------------------------------------------------------------------------------------------------------------- - bool updateTransformInProgress = false; - - //-------------------------------------------------------------------------------------------------------------------- - /// \name Input Attributes - //-------------------------------------------------------------------------------------------------------------------- - - /// \var MPlug timePlug() const; - /// \brief access the time attribute plug on this node instance - /// time - (probably) connected from the output time of an AL::usdmaya::nodes::ProxyShape (but it doesn't have to be) - /// \return the plug to the time attribute - /// \var MPlug timeOffsetPlug() const; - /// \brief access the timeOffset attribute plug on this node instance - /// timeOffset - an offset (in current UI time units) of say 30, means animation wont start until frame 30. - /// \return the plug to the timeOffset attribute - /// \var MPlug timeScalarPlug() const; - /// \brief access the timeScalar attribute plug on this node instance - /// timeScalar - a speed multiplier. 2.0 will double the playback speed, 0.5 will halve it. - /// \return the plug to the timeScalar attribute - /// \var MPlug localTranslateOffsetPlug() const; - /// \brief access the localTranslateOffset attribute plug on this node instance - /// localTranslateOffset - an offset applied *after* all other transforms. Useful for positioning items on a table. - /// \return the plug to the localTranslateOffset attribute - /// \var MPlug pushToPrimPlug() const; - /// \brief access the pushToPrim attribute plug on this node instance - /// pushToPrim - When enabled, any changes you make to the transform values in maya, will be pushed back onto the USD primitive. - /// \return the plug to the pushToPrim attribute - /// \var MPlug readAnimatedValuesPlug() const; - /// \brief With USD, we typically have two possible sets of values on any given attribute. There is a 'default' value, - /// and the keyframed values. If this plug is true, the transform node will read the animated values. If the plug - /// is false then the default value will be read. - /// \return the plug to the readAnimatedValues attribute - - /// \var static MObject primPath(); - /// \brief access the primPath attribute handle - /// \return the primPath attribute - /// \var static MObject inStageData(); - /// \brief access the inStageData attribute handle - /// \return the inStageData attribute - /// \var static MObject time(); - /// \brief access the time attribute handle - /// \return the time attribute - /// \var static MObject timeOffset(); - /// \brief access the timeOffset attribute handle - /// \return the timeOffset attribute - /// \var static MObject timeScalar(); - /// \brief access the timeScalar attribute handle - /// \return the timeScalar attribute - /// \var static MObject pushToPrim(); - /// \brief access the pushToPrim attribute handle - /// \return the pushToPrim attribute - /// \var static MObject localTranslateOffset(); - /// \brief access the localTranslateOffset attribute handle - /// \return the localTranslateOffset attribute - /// \var static MObject readAnimatedValues(); - /// \brief access the readAnimatedValues attribute handle - /// \return the readAnimatedValues attribute - - //-------------------------------------------------------------------------------------------------------------------- - /// \name Output Attributes - //-------------------------------------------------------------------------------------------------------------------- - - /// \var MPlug outTimePlug() const; - /// \brief access the outTime attribute plug on this node instance - /// outTime = (time - timeOffset) * timeScalar - /// \return the plug to the outTime attribute - /// \var static MObject outTime(); - /// \brief access the outTime attribute handle - /// \return the outTime attribute - - MObjectHandle proxyShapeHandle; + //-------------------------------------------------------------------------------------------------------------------- + /// virtual overrides + //-------------------------------------------------------------------------------------------------------------------- + + MPxNode::SchedulingType schedulingType() const override { return kParallel; } + + MStatus validateAndSetValue( + const MPlug& plug, + const MDataHandle& handle, + const MDGContext& context) override; + MPxTransformationMatrix* createTransformationMatrix() override; + MStatus compute(const MPlug& plug, MDataBlock& datablock) override; + void postConstructor() override; + MStatus connectionMade(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; + MStatus connectionBroken(const MPlug& plug, const MPlug& otherPlug, bool asSrc) override; + bool setInternalValue(const MPlug& plug, const MDataHandle& dataHandle) override; + bool isBounded() const override { return true; } + bool treatAsTransform() const override { return false; } + + //-------------------------------------------------------------------------------------------------------------------- + /// utils + //-------------------------------------------------------------------------------------------------------------------- + + void updateTransform(MDataBlock& dataBlock); + + //-------------------------------------------------------------------------------------------------------------------- + /// Data members + //-------------------------------------------------------------------------------------------------------------------- + bool updateTransformInProgress = false; + + //-------------------------------------------------------------------------------------------------------------------- + /// \name Input Attributes + //-------------------------------------------------------------------------------------------------------------------- + + /// \var MPlug timePlug() const; + /// \brief access the time attribute plug on this node instance + /// time - (probably) connected from the output time of an + /// AL::usdmaya::nodes::ProxyShape (but it doesn't have to be) + /// \return the plug to the time attribute + /// \var MPlug timeOffsetPlug() const; + /// \brief access the timeOffset attribute plug on this node instance + /// timeOffset - an offset (in current UI time units) of say 30, means animation wont + /// start until frame 30. + /// \return the plug to the timeOffset attribute + /// \var MPlug timeScalarPlug() const; + /// \brief access the timeScalar attribute plug on this node instance + /// timeScalar - a speed multiplier. 2.0 will double the playback speed, 0.5 will halve + /// it. + /// \return the plug to the timeScalar attribute + /// \var MPlug localTranslateOffsetPlug() const; + /// \brief access the localTranslateOffset attribute plug on this node instance + /// localTranslateOffset - an offset applied *after* all other transforms. Useful for + /// positioning items on a table. + /// \return the plug to the localTranslateOffset attribute + /// \var MPlug pushToPrimPlug() const; + /// \brief access the pushToPrim attribute plug on this node instance + /// pushToPrim - When enabled, any changes you make to the transform values in maya, + /// will be pushed back onto the USD primitive. + /// \return the plug to the pushToPrim attribute + /// \var MPlug readAnimatedValuesPlug() const; + /// \brief With USD, we typically have two possible sets of values on any given attribute. + /// There is a 'default' value, + /// and the keyframed values. If this plug is true, the transform node will read the + /// animated values. If the plug is false then the default value will be read. + /// \return the plug to the readAnimatedValues attribute + + /// \var static MObject primPath(); + /// \brief access the primPath attribute handle + /// \return the primPath attribute + /// \var static MObject inStageData(); + /// \brief access the inStageData attribute handle + /// \return the inStageData attribute + /// \var static MObject time(); + /// \brief access the time attribute handle + /// \return the time attribute + /// \var static MObject timeOffset(); + /// \brief access the timeOffset attribute handle + /// \return the timeOffset attribute + /// \var static MObject timeScalar(); + /// \brief access the timeScalar attribute handle + /// \return the timeScalar attribute + /// \var static MObject pushToPrim(); + /// \brief access the pushToPrim attribute handle + /// \return the pushToPrim attribute + /// \var static MObject localTranslateOffset(); + /// \brief access the localTranslateOffset attribute handle + /// \return the localTranslateOffset attribute + /// \var static MObject readAnimatedValues(); + /// \brief access the readAnimatedValues attribute handle + /// \return the readAnimatedValues attribute + + //-------------------------------------------------------------------------------------------------------------------- + /// \name Output Attributes + //-------------------------------------------------------------------------------------------------------------------- + + /// \var MPlug outTimePlug() const; + /// \brief access the outTime attribute plug on this node instance + /// outTime = (time - timeOffset) * timeScalar + /// \return the plug to the outTime attribute + /// \var static MObject outTime(); + /// \brief access the outTime attribute handle + /// \return the outTime attribute + + MObjectHandle proxyShapeHandle; }; //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/TransformationMatrix.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/TransformationMatrix.cpp index cc1fe2ada4..d2fe7a736d 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/TransformationMatrix.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/TransformationMatrix.cpp @@ -14,17 +14,18 @@ // limitations under the License. // -#include "AL/usdmaya/TypeIDs.h" +#include "AL/usdmaya/nodes/TransformationMatrix.h" + #include "AL/usdmaya/DebugCodes.h" +#include "AL/usdmaya/TypeIDs.h" #include "AL/usdmaya/nodes/ProxyShape.h" #include "AL/usdmaya/nodes/Transform.h" -#include "AL/usdmaya/nodes/TransformationMatrix.h" #include "AL/usdmaya/utils/AttributeType.h" #include "AL/usdmaya/utils/Utils.h" #include -#include #include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -37,1276 +38,1165 @@ using AL::usdmaya::utils::UsdDataType; //---------------------------------------------------------------------------------------------------------------------- bool hasEmptyDefaultValue(const UsdGeomXformOp& op, UsdTimeCode time) { - SdfPropertySpecHandleVector propSpecs = op.GetAttr().GetPropertyStack(time); - for(auto propSpec : propSpecs) - { - auto def = propSpec->GetDefaultValue(); - if(def.IsEmpty()) - { - return true; + SdfPropertySpecHandleVector propSpecs = op.GetAttr().GetPropertyStack(time); + for (auto propSpec : propSpecs) { + auto def = propSpec->GetDefaultValue(); + if (def.IsEmpty()) { + return true; + } } - } - return false; + return false; } -} // anon +} // namespace //---------------------------------------------------------------------------------------------------------------------- const MTypeId TransformationMatrix::kTypeId(AL_USDMAYA_TRANSFORMATION_MATRIX); //---------------------------------------------------------------------------------------------------------------------- -MPxTransformationMatrix* TransformationMatrix::creator() -{ - return new TransformationMatrix; -} +MPxTransformationMatrix* TransformationMatrix::creator() { return new TransformationMatrix; } //---------------------------------------------------------------------------------------------------------------------- TransformationMatrix::TransformationMatrix() - : BasicTransformationMatrix(), - m_xform(), - m_time(UsdTimeCode::Default()), - m_scaleTweak(0, 0, 0), - m_rotationTweak(0, 0, 0), - m_translationTweak(0, 0, 0), - m_shearTweak(0, 0, 0), - m_scalePivotTweak(0, 0, 0), - m_scalePivotTranslationTweak(0, 0, 0), - m_rotatePivotTweak(0, 0, 0), - m_rotatePivotTranslationTweak(0, 0, 0), - m_rotateOrientationTweak(0, 0, 0, 1.0), - m_scaleFromUsd(1.0, 1.0, 1.0), - m_rotationFromUsd(0, 0, 0), - m_translationFromUsd(0.0, 0.0, 0.0), - m_shearFromUsd(0, 0, 0), - m_scalePivotFromUsd(0, 0, 0), - m_scalePivotTranslationFromUsd(0, 0, 0), - m_rotatePivotFromUsd(0, 0, 0), - m_rotatePivotTranslationFromUsd(0, 0, 0), - m_rotateOrientationFromUsd(0, 0, 0, 1.0), - m_localTranslateOffset(0, 0, 0), - m_flags(0) + : BasicTransformationMatrix() + , m_xform() + , m_time(UsdTimeCode::Default()) + , m_scaleTweak(0, 0, 0) + , m_rotationTweak(0, 0, 0) + , m_translationTweak(0, 0, 0) + , m_shearTweak(0, 0, 0) + , m_scalePivotTweak(0, 0, 0) + , m_scalePivotTranslationTweak(0, 0, 0) + , m_rotatePivotTweak(0, 0, 0) + , m_rotatePivotTranslationTweak(0, 0, 0) + , m_rotateOrientationTweak(0, 0, 0, 1.0) + , m_scaleFromUsd(1.0, 1.0, 1.0) + , m_rotationFromUsd(0, 0, 0) + , m_translationFromUsd(0.0, 0.0, 0.0) + , m_shearFromUsd(0, 0, 0) + , m_scalePivotFromUsd(0, 0, 0) + , m_scalePivotTranslationFromUsd(0, 0, 0) + , m_rotatePivotFromUsd(0, 0, 0) + , m_rotatePivotTranslationFromUsd(0, 0, 0) + , m_rotateOrientationFromUsd(0, 0, 0, 1.0) + , m_localTranslateOffset(0, 0, 0) + , m_flags(0) { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("TransformationMatrix::TransformationMatrix\n"); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("TransformationMatrix::TransformationMatrix\n"); } //---------------------------------------------------------------------------------------------------------------------- TransformationMatrix::TransformationMatrix(const UsdPrim& prim) - : BasicTransformationMatrix(prim), - m_xform(prim), - m_time(UsdTimeCode::Default()), - m_scaleTweak(0, 0, 0), - m_rotationTweak(0, 0, 0), - m_translationTweak(0, 0, 0), - m_shearTweak(0, 0, 0), - m_scalePivotTweak(0, 0, 0), - m_scalePivotTranslationTweak(0, 0, 0), - m_rotatePivotTweak(0, 0, 0), - m_rotatePivotTranslationTweak(0, 0, 0), - m_rotateOrientationTweak(0, 0, 0, 1.0), - m_scaleFromUsd(1.0, 1.0, 1.0), - m_rotationFromUsd(0, 0, 0), - m_translationFromUsd(0, 0, 0), - m_shearFromUsd(0, 0, 0), - m_scalePivotFromUsd(0, 0, 0), - m_scalePivotTranslationFromUsd(0, 0, 0), - m_rotatePivotFromUsd(0, 0, 0), - m_rotatePivotTranslationFromUsd(0, 0, 0), - m_rotateOrientationFromUsd(0, 0, 0, 1.0), - m_localTranslateOffset(0, 0, 0), - m_flags(0) + : BasicTransformationMatrix(prim) + , m_xform(prim) + , m_time(UsdTimeCode::Default()) + , m_scaleTweak(0, 0, 0) + , m_rotationTweak(0, 0, 0) + , m_translationTweak(0, 0, 0) + , m_shearTweak(0, 0, 0) + , m_scalePivotTweak(0, 0, 0) + , m_scalePivotTranslationTweak(0, 0, 0) + , m_rotatePivotTweak(0, 0, 0) + , m_rotatePivotTranslationTweak(0, 0, 0) + , m_rotateOrientationTweak(0, 0, 0, 1.0) + , m_scaleFromUsd(1.0, 1.0, 1.0) + , m_rotationFromUsd(0, 0, 0) + , m_translationFromUsd(0, 0, 0) + , m_shearFromUsd(0, 0, 0) + , m_scalePivotFromUsd(0, 0, 0) + , m_scalePivotTranslationFromUsd(0, 0, 0) + , m_rotatePivotFromUsd(0, 0, 0) + , m_rotatePivotTranslationFromUsd(0, 0, 0) + , m_rotateOrientationFromUsd(0, 0, 0, 1.0) + , m_localTranslateOffset(0, 0, 0) + , m_flags(0) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::TransformationMatrix\n"); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::TransformationMatrix\n"); } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::setPrim(const UsdPrim& prim, Scope* transformNode) { - m_enableUsdWriteback = false; - if(prim.IsValid()) - { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setPrim %s\n", prim.GetName().GetText()); - m_prim = prim; - UsdGeomXformable xform(prim); - m_xform = xform; - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setPrim null\n"); - m_prim = UsdPrim(); - m_xform = UsdGeomXformable(); - } - // Most of these flags are calculated based on reading the usd prim; however, a few are driven - // "externally" (ie, from attributes on the controlling transform node), and should NOT be reset - // when we're re-initializing - m_flags &= kPreservationMask; - m_scaleTweak = MVector(0, 0, 0); - m_rotationTweak = MEulerRotation(0, 0, 0); - m_translationTweak = MVector(0, 0, 0); - m_shearTweak = MVector(0, 0, 0); - m_scalePivotTweak = MPoint(0, 0, 0); - m_scalePivotTranslationTweak = MVector(0, 0, 0); - m_rotatePivotTweak = MPoint(0, 0, 0); - m_rotatePivotTranslationTweak = MVector(0, 0, 0); - m_rotateOrientationTweak = MQuaternion(0, 0, 0, 1.0); - m_localTranslateOffset = MVector(0, 0, 0); - - if(m_prim.IsValid()) - { - m_scaleFromUsd = MVector(1.0, 1.0, 1.0); - m_rotationFromUsd = MEulerRotation(0, 0, 0); - m_translationFromUsd = MVector(0, 0, 0); - m_shearFromUsd = MVector(0, 0, 0); - m_scalePivotFromUsd = MPoint(0, 0, 0); - m_scalePivotTranslationFromUsd = MVector(0, 0, 0); - m_rotatePivotFromUsd = MPoint(0, 0, 0); - m_rotatePivotTranslationFromUsd = MVector(0, 0, 0); - m_rotateOrientationFromUsd = MQuaternion(0, 0, 0, 1.0); - initialiseToPrim(!MFileIO::isReadingFile(), transformNode); - MPxTransformationMatrix::scaleValue = m_scaleFromUsd; - MPxTransformationMatrix::rotationValue = m_rotationFromUsd; - MPxTransformationMatrix::translationValue = m_translationFromUsd; - MPxTransformationMatrix::shearValue = m_shearFromUsd; - MPxTransformationMatrix::scalePivotValue = m_scalePivotFromUsd; - MPxTransformationMatrix::scalePivotTranslationValue = m_scalePivotTranslationFromUsd; - MPxTransformationMatrix::rotatePivotValue = m_rotatePivotFromUsd; - MPxTransformationMatrix::rotatePivotTranslationValue = m_rotatePivotTranslationFromUsd; - MPxTransformationMatrix::rotateOrientationValue = m_rotateOrientationFromUsd; - } - m_enableUsdWriteback = true; + m_enableUsdWriteback = false; + if (prim.IsValid()) { + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::setPrim %s\n", prim.GetName().GetText()); + m_prim = prim; + UsdGeomXformable xform(prim); + m_xform = xform; + } else { + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setPrim null\n"); + m_prim = UsdPrim(); + m_xform = UsdGeomXformable(); + } + // Most of these flags are calculated based on reading the usd prim; however, a few are driven + // "externally" (ie, from attributes on the controlling transform node), and should NOT be reset + // when we're re-initializing + m_flags &= kPreservationMask; + m_scaleTweak = MVector(0, 0, 0); + m_rotationTweak = MEulerRotation(0, 0, 0); + m_translationTweak = MVector(0, 0, 0); + m_shearTweak = MVector(0, 0, 0); + m_scalePivotTweak = MPoint(0, 0, 0); + m_scalePivotTranslationTweak = MVector(0, 0, 0); + m_rotatePivotTweak = MPoint(0, 0, 0); + m_rotatePivotTranslationTweak = MVector(0, 0, 0); + m_rotateOrientationTweak = MQuaternion(0, 0, 0, 1.0); + m_localTranslateOffset = MVector(0, 0, 0); + + if (m_prim.IsValid()) { + m_scaleFromUsd = MVector(1.0, 1.0, 1.0); + m_rotationFromUsd = MEulerRotation(0, 0, 0); + m_translationFromUsd = MVector(0, 0, 0); + m_shearFromUsd = MVector(0, 0, 0); + m_scalePivotFromUsd = MPoint(0, 0, 0); + m_scalePivotTranslationFromUsd = MVector(0, 0, 0); + m_rotatePivotFromUsd = MPoint(0, 0, 0); + m_rotatePivotTranslationFromUsd = MVector(0, 0, 0); + m_rotateOrientationFromUsd = MQuaternion(0, 0, 0, 1.0); + initialiseToPrim(!MFileIO::isReadingFile(), transformNode); + MPxTransformationMatrix::scaleValue = m_scaleFromUsd; + MPxTransformationMatrix::rotationValue = m_rotationFromUsd; + MPxTransformationMatrix::translationValue = m_translationFromUsd; + MPxTransformationMatrix::shearValue = m_shearFromUsd; + MPxTransformationMatrix::scalePivotValue = m_scalePivotFromUsd; + MPxTransformationMatrix::scalePivotTranslationValue = m_scalePivotTranslationFromUsd; + MPxTransformationMatrix::rotatePivotValue = m_rotatePivotFromUsd; + MPxTransformationMatrix::rotatePivotTranslationValue = m_rotatePivotTranslationFromUsd; + MPxTransformationMatrix::rotateOrientationValue = m_rotateOrientationFromUsd; + } + m_enableUsdWriteback = true; } //---------------------------------------------------------------------------------------------------------------------- -bool TransformationMatrix::readVector(MVector& result, const UsdGeomXformOp& op, UsdTimeCode timeCode) +bool TransformationMatrix::readVector( + MVector& result, + const UsdGeomXformOp& op, + UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readVector\n"); - const SdfValueTypeName vtn = op.GetTypeName(); - UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); - switch(attr_type) - { - case UsdDataType::kVec3d: - { - GfVec3d value; - const bool retValue = op.GetAs(&value, timeCode); - if (!retValue) - { - return false; - } - result.x = value[0]; - result.y = value[1]; - result.z = value[2]; - } - break; - - case UsdDataType::kVec3f: - { - GfVec3f value; - const bool retValue = op.GetAs(&value, timeCode); - if (!retValue) - { - return false; - } - result.x = double(value[0]); - result.y = double(value[1]); - result.z = double(value[2]); - } - break; - - case UsdDataType::kVec3h: - { - GfVec3h value; - const bool retValue = op.GetAs(&value, timeCode); - if (!retValue) - { - return false; - } - result.x = double(value[0]); - result.y = double(value[1]); - result.z = double(value[2]); - } - break; - - case UsdDataType::kVec3i: - { - GfVec3i value; - const bool retValue = op.GetAs(&value, timeCode); - if (!retValue) - { - return false; - } - result.x = double(value[0]); - result.y = double(value[1]); - result.z = double(value[2]); - } - break; - - default: - return false; - } - - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readVector %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); - return true; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readVector\n"); + const SdfValueTypeName vtn = op.GetTypeName(); + UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); + switch (attr_type) { + case UsdDataType::kVec3d: { + GfVec3d value; + const bool retValue = op.GetAs(&value, timeCode); + if (!retValue) { + return false; + } + result.x = value[0]; + result.y = value[1]; + result.z = value[2]; + } break; + + case UsdDataType::kVec3f: { + GfVec3f value; + const bool retValue = op.GetAs(&value, timeCode); + if (!retValue) { + return false; + } + result.x = double(value[0]); + result.y = double(value[1]); + result.z = double(value[2]); + } break; + + case UsdDataType::kVec3h: { + GfVec3h value; + const bool retValue = op.GetAs(&value, timeCode); + if (!retValue) { + return false; + } + result.x = double(value[0]); + result.y = double(value[1]); + result.z = double(value[2]); + } break; + + case UsdDataType::kVec3i: { + GfVec3i value; + const bool retValue = op.GetAs(&value, timeCode); + if (!retValue) { + return false; + } + result.x = double(value[0]); + result.y = double(value[1]); + result.z = double(value[2]); + } break; + + default: return false; + } + + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg( + "TransformationMatrix::readVector %f %f %f\n%s\n", + result.x, + result.y, + result.z, + op.GetOpName().GetText()); + return true; } //---------------------------------------------------------------------------------------------------------------------- -bool TransformationMatrix::pushVector(const MVector& result, UsdGeomXformOp& op, UsdTimeCode timeCode) +bool TransformationMatrix::pushVector( + const MVector& result, + UsdGeomXformOp& op, + UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushVector %f %f %f [@%f]\n%s\n", result.x, result.y, result.z, timeCode.GetValue(), op.GetOpName().GetText()); - auto attr = op.GetAttr(); - if(!attr) - { - return false; - } - - if(timeCode.IsDefault() && op.GetNumTimeSamples()) - { - if(!hasEmptyDefaultValue(op, timeCode)) - { - return false; - } - } - - TfToken typeName; - attr.GetMetadata(SdfFieldKeys->TypeName, &typeName); - SdfValueTypeName vtn = SdfSchema::GetInstance().FindType(typeName); - UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); - switch(attr_type) - { - case UsdDataType::kVec3d: - { - GfVec3d value(result.x, result.y, result.z); - GfVec3d oldValue; - op.Get(&oldValue, timeCode); - if(value != oldValue) - { - op.Set(value, timeCode); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg( + "TransformationMatrix::pushVector %f %f %f [@%f]\n%s\n", + result.x, + result.y, + result.z, + timeCode.GetValue(), + op.GetOpName().GetText()); + auto attr = op.GetAttr(); + if (!attr) { + return false; } - break; - case UsdDataType::kVec3f: - { - GfVec3f value(result.x, result.y, result.z); - GfVec3f oldValue; - op.Get(&oldValue, timeCode); - if(value != oldValue) - { - op.Set(value, timeCode); - } + if (timeCode.IsDefault() && op.GetNumTimeSamples()) { + if (!hasEmptyDefaultValue(op, timeCode)) { + return false; + } } - break; - case UsdDataType::kVec3h: - { - GfVec3h value(result.x, result.y, result.z); - GfVec3h oldValue; - op.Get(&oldValue, timeCode); - if(value != oldValue) - { - op.Set(value, timeCode); - } - } - break; + TfToken typeName; + attr.GetMetadata(SdfFieldKeys->TypeName, &typeName); + SdfValueTypeName vtn = SdfSchema::GetInstance().FindType(typeName); + UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); + switch (attr_type) { + case UsdDataType::kVec3d: { + GfVec3d value(result.x, result.y, result.z); + GfVec3d oldValue; + op.Get(&oldValue, timeCode); + if (value != oldValue) { + op.Set(value, timeCode); + } + } break; + + case UsdDataType::kVec3f: { + GfVec3f value(result.x, result.y, result.z); + GfVec3f oldValue; + op.Get(&oldValue, timeCode); + if (value != oldValue) { + op.Set(value, timeCode); + } + } break; + + case UsdDataType::kVec3h: { + GfVec3h value(result.x, result.y, result.z); + GfVec3h oldValue; + op.Get(&oldValue, timeCode); + if (value != oldValue) { + op.Set(value, timeCode); + } + } break; + + case UsdDataType::kVec3i: { + GfVec3i value(result.x, result.y, result.z); + GfVec3i oldValue; + op.Get(&oldValue, timeCode); + if (value != oldValue) { + op.Set(value, timeCode); + } + } break; - case UsdDataType::kVec3i: - { - GfVec3i value(result.x, result.y, result.z); - GfVec3i oldValue; - op.Get(&oldValue, timeCode); - if(value != oldValue) - { - op.Set(value, timeCode); - } + default: return false; } - break; - - default: - return false; - } - return true; + return true; } //---------------------------------------------------------------------------------------------------------------------- -bool TransformationMatrix::pushShear(const MVector& result, UsdGeomXformOp& op, UsdTimeCode timeCode) +bool TransformationMatrix::pushShear( + const MVector& result, + UsdGeomXformOp& op, + UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushShear %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); - - if(timeCode.IsDefault() && op.GetNumTimeSamples()) - { - if(!hasEmptyDefaultValue(op, timeCode)) - { - return false; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg( + "TransformationMatrix::pushShear %f %f %f\n%s\n", + result.x, + result.y, + result.z, + op.GetOpName().GetText()); + + if (timeCode.IsDefault() && op.GetNumTimeSamples()) { + if (!hasEmptyDefaultValue(op, timeCode)) { + return false; + } } - } - const SdfValueTypeName vtn = op.GetTypeName(); - UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); - switch(attr_type) - { - case UsdDataType::kMatrix4d: - { - GfMatrix4d m( - 1.0, 0.0, 0.0, 0.0, - result.x, 1.0, 0.0, 0.0, - result.y, result.z, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0); - GfMatrix4d oldValue; - op.Get(&oldValue, timeCode); - if(m != oldValue) - op.Set(m, timeCode); - } - break; - - default: + const SdfValueTypeName vtn = op.GetTypeName(); + UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); + switch (attr_type) { + case UsdDataType::kMatrix4d: { + GfMatrix4d m( + 1.0, + 0.0, + 0.0, + 0.0, + result.x, + 1.0, + 0.0, + 0.0, + result.y, + result.z, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0); + GfMatrix4d oldValue; + op.Get(&oldValue, timeCode); + if (m != oldValue) + op.Set(m, timeCode); + } break; + + default: return false; + } return false; - } - return false; } //---------------------------------------------------------------------------------------------------------------------- -bool TransformationMatrix::readShear(MVector& result, const UsdGeomXformOp& op, UsdTimeCode timeCode) +bool TransformationMatrix::readShear( + MVector& result, + const UsdGeomXformOp& op, + UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readShear\n"); - const SdfValueTypeName vtn = op.GetTypeName(); - UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); - switch(attr_type) - { - case UsdDataType::kMatrix4d: - { - GfMatrix4d value; - const bool retValue = op.GetAs(&value, timeCode); - if (!retValue) - { - return false; - } - result.x = value[1][0]; - result.y = value[2][0]; - result.z = value[2][1]; - } - break; - - default: - return false; - } - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readShear %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); - return true; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readShear\n"); + const SdfValueTypeName vtn = op.GetTypeName(); + UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); + switch (attr_type) { + case UsdDataType::kMatrix4d: { + GfMatrix4d value; + const bool retValue = op.GetAs(&value, timeCode); + if (!retValue) { + return false; + } + result.x = value[1][0]; + result.y = value[2][0]; + result.z = value[2][1]; + } break; + + default: return false; + } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg( + "TransformationMatrix::readShear %f %f %f\n%s\n", + result.x, + result.y, + result.z, + op.GetOpName().GetText()); + return true; } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::readPoint(MPoint& result, const UsdGeomXformOp& op, UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readPoint\n"); - const SdfValueTypeName vtn = op.GetTypeName(); - UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); - switch(attr_type) - { - case UsdDataType::kVec3d: - { - GfVec3d value; - const bool retValue = op.GetAs(&value, timeCode); - if (!retValue) - { - return false; - } - result.x = value[0]; - result.y = value[1]; - result.z = value[2]; - } - break; - - case UsdDataType::kVec3f: - { - GfVec3f value; - const bool retValue = op.GetAs(&value, timeCode); - if (!retValue) - { - return false; - } - result.x = double(value[0]); - result.y = double(value[1]); - result.z = double(value[2]); - } - break; - - case UsdDataType::kVec3h: - { - GfVec3h value; - const bool retValue = op.GetAs(&value, timeCode); - if (!retValue) - { - return false; - } - result.x = double(value[0]); - result.y = double(value[1]); - result.z = double(value[2]); - } - break; - - case UsdDataType::kVec3i: - { - GfVec3i value; - const bool retValue = op.GetAs(&value, timeCode); - if (!retValue) - { - return false; - } - result.x = double(value[0]); - result.y = double(value[1]); - result.z = double(value[2]); - } - break; - - default: - return false; - } - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readPoint %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); - - return true; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readPoint\n"); + const SdfValueTypeName vtn = op.GetTypeName(); + UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); + switch (attr_type) { + case UsdDataType::kVec3d: { + GfVec3d value; + const bool retValue = op.GetAs(&value, timeCode); + if (!retValue) { + return false; + } + result.x = value[0]; + result.y = value[1]; + result.z = value[2]; + } break; + + case UsdDataType::kVec3f: { + GfVec3f value; + const bool retValue = op.GetAs(&value, timeCode); + if (!retValue) { + return false; + } + result.x = double(value[0]); + result.y = double(value[1]); + result.z = double(value[2]); + } break; + + case UsdDataType::kVec3h: { + GfVec3h value; + const bool retValue = op.GetAs(&value, timeCode); + if (!retValue) { + return false; + } + result.x = double(value[0]); + result.y = double(value[1]); + result.z = double(value[2]); + } break; + + case UsdDataType::kVec3i: { + GfVec3i value; + const bool retValue = op.GetAs(&value, timeCode); + if (!retValue) { + return false; + } + result.x = double(value[0]); + result.y = double(value[1]); + result.z = double(value[2]); + } break; + + default: return false; + } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg( + "TransformationMatrix::readPoint %f %f %f\n%s\n", + result.x, + result.y, + result.z, + op.GetOpName().GetText()); + + return true; } //---------------------------------------------------------------------------------------------------------------------- -bool TransformationMatrix::readMatrix(MMatrix& result, const UsdGeomXformOp& op, UsdTimeCode timeCode) +bool TransformationMatrix::readMatrix( + MMatrix& result, + const UsdGeomXformOp& op, + UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readMatrix\n"); - const SdfValueTypeName vtn = op.GetTypeName(); - UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); - switch(attr_type) - { - case UsdDataType::kMatrix4d: - { - GfMatrix4d value; - const bool retValue = op.GetAs(&value, timeCode); - if (!retValue) - { - return false; - } - auto vtemp = (const void*)&value; - auto mtemp = (const MMatrix*)vtemp; - result = *mtemp; - } - break; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readMatrix\n"); + const SdfValueTypeName vtn = op.GetTypeName(); + UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); + switch (attr_type) { + case UsdDataType::kMatrix4d: { + GfMatrix4d value; + const bool retValue = op.GetAs(&value, timeCode); + if (!retValue) { + return false; + } + auto vtemp = (const void*)&value; + auto mtemp = (const MMatrix*)vtemp; + result = *mtemp; + } break; - default: - return false; - } + default: return false; + } - return true; + return true; } //---------------------------------------------------------------------------------------------------------------------- -bool TransformationMatrix::pushMatrix(const MMatrix& result, UsdGeomXformOp& op, UsdTimeCode timeCode) +bool TransformationMatrix::pushMatrix( + const MMatrix& result, + UsdGeomXformOp& op, + UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushMatrix\n"); - if(timeCode.IsDefault() && op.GetNumTimeSamples()) - { - if(!hasEmptyDefaultValue(op, timeCode)) - { - return false; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushMatrix\n"); + if (timeCode.IsDefault() && op.GetNumTimeSamples()) { + if (!hasEmptyDefaultValue(op, timeCode)) { + return false; + } } - } - const SdfValueTypeName vtn = op.GetTypeName(); - UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); - switch(attr_type) - { - case UsdDataType::kMatrix4d: - { - const GfMatrix4d& value = *(const GfMatrix4d*)(&result); - GfMatrix4d oldValue; - op.Get(&oldValue, timeCode); - if(value != oldValue) - { - const bool retValue = op.Set(value, timeCode); - if (!retValue) - { - return false; + const SdfValueTypeName vtn = op.GetTypeName(); + UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); + switch (attr_type) { + case UsdDataType::kMatrix4d: { + const GfMatrix4d& value = *(const GfMatrix4d*)(&result); + GfMatrix4d oldValue; + op.Get(&oldValue, timeCode); + if (value != oldValue) { + const bool retValue = op.Set(value, timeCode); + if (!retValue) { + return false; + } } - } - } - break; + } break; - default: - return false; - } + default: return false; + } - return true; + return true; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::setFromMatrix(MObject thisNode, const MMatrix& m) { - double S[3]; - MEulerRotation R; - double T[3]; - utils::matrixToSRT(*(const GfMatrix4d*)&m, S, R, T); - m_scaleFromUsd.x = S[0]; - m_scaleFromUsd.y = S[1]; - m_scaleFromUsd.z = S[2]; - m_rotationFromUsd.x = R.x; - m_rotationFromUsd.y = R.y; - m_rotationFromUsd.z = R.z; - m_translationFromUsd.x = T[0]; - m_translationFromUsd.y = T[1]; - m_translationFromUsd.z = T[2]; - MPlug(thisNode, MPxTransform::scaleX).setValue(m_scaleFromUsd.x); - MPlug(thisNode, MPxTransform::scaleY).setValue(m_scaleFromUsd.y); - MPlug(thisNode, MPxTransform::scaleZ).setValue(m_scaleFromUsd.z); - MPlug(thisNode, MPxTransform::rotateX).setValue(m_rotationFromUsd.x); - MPlug(thisNode, MPxTransform::rotateY).setValue(m_rotationFromUsd.y); - MPlug(thisNode, MPxTransform::rotateZ).setValue(m_rotationFromUsd.z); - MPlug(thisNode, MPxTransform::translateX).setValue(m_translationFromUsd.x); - MPlug(thisNode, MPxTransform::translateY).setValue(m_translationFromUsd.y); - MPlug(thisNode, MPxTransform::translateZ).setValue(m_translationFromUsd.z); + double S[3]; + MEulerRotation R; + double T[3]; + utils::matrixToSRT(*(const GfMatrix4d*)&m, S, R, T); + m_scaleFromUsd.x = S[0]; + m_scaleFromUsd.y = S[1]; + m_scaleFromUsd.z = S[2]; + m_rotationFromUsd.x = R.x; + m_rotationFromUsd.y = R.y; + m_rotationFromUsd.z = R.z; + m_translationFromUsd.x = T[0]; + m_translationFromUsd.y = T[1]; + m_translationFromUsd.z = T[2]; + MPlug(thisNode, MPxTransform::scaleX).setValue(m_scaleFromUsd.x); + MPlug(thisNode, MPxTransform::scaleY).setValue(m_scaleFromUsd.y); + MPlug(thisNode, MPxTransform::scaleZ).setValue(m_scaleFromUsd.z); + MPlug(thisNode, MPxTransform::rotateX).setValue(m_rotationFromUsd.x); + MPlug(thisNode, MPxTransform::rotateY).setValue(m_rotationFromUsd.y); + MPlug(thisNode, MPxTransform::rotateZ).setValue(m_rotationFromUsd.z); + MPlug(thisNode, MPxTransform::translateX).setValue(m_translationFromUsd.x); + MPlug(thisNode, MPxTransform::translateY).setValue(m_translationFromUsd.y); + MPlug(thisNode, MPxTransform::translateZ).setValue(m_translationFromUsd.z); } //---------------------------------------------------------------------------------------------------------------------- bool TransformationMatrix::pushPoint(const MPoint& result, UsdGeomXformOp& op, UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushPoint %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); - - if(timeCode.IsDefault() && op.GetNumTimeSamples()) - { - if(!hasEmptyDefaultValue(op, timeCode)) - { - return false; - } - } - - const SdfValueTypeName vtn = op.GetTypeName(); - UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); - switch(attr_type) - { - case UsdDataType::kVec3d: - { - GfVec3d value(result.x, result.y, result.z); - GfVec3d oldValue; - op.Get(&oldValue, timeCode); - if(value != oldValue) - op.Set(value, timeCode); - } - break; - - case UsdDataType::kVec3f: - { - GfVec3f value(result.x, result.y, result.z); - GfVec3f oldValue; - op.Get(&oldValue, timeCode); - if(value != oldValue) - op.Set(value, timeCode); - } - break; - - case UsdDataType::kVec3h: - { - GfVec3h value(result.x, result.y, result.z); - GfVec3h oldValue; - op.Get(&oldValue, timeCode); - if(value != oldValue) - op.Set(value, timeCode); - } - break; - - case UsdDataType::kVec3i: - { - GfVec3i value(result.x, result.y, result.z); - GfVec3i oldValue; - op.Get(&oldValue, timeCode); - if(value != oldValue) - op.Set(value, timeCode); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg( + "TransformationMatrix::pushPoint %f %f %f\n%s\n", + result.x, + result.y, + result.z, + op.GetOpName().GetText()); + + if (timeCode.IsDefault() && op.GetNumTimeSamples()) { + if (!hasEmptyDefaultValue(op, timeCode)) { + return false; + } } - break; - - default: - return false; - } - return true; + const SdfValueTypeName vtn = op.GetTypeName(); + UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(vtn); + switch (attr_type) { + case UsdDataType::kVec3d: { + GfVec3d value(result.x, result.y, result.z); + GfVec3d oldValue; + op.Get(&oldValue, timeCode); + if (value != oldValue) + op.Set(value, timeCode); + } break; + + case UsdDataType::kVec3f: { + GfVec3f value(result.x, result.y, result.z); + GfVec3f oldValue; + op.Get(&oldValue, timeCode); + if (value != oldValue) + op.Set(value, timeCode); + } break; + + case UsdDataType::kVec3h: { + GfVec3h value(result.x, result.y, result.z); + GfVec3h oldValue; + op.Get(&oldValue, timeCode); + if (value != oldValue) + op.Set(value, timeCode); + } break; + + case UsdDataType::kVec3i: { + GfVec3i value(result.x, result.y, result.z); + GfVec3i oldValue; + op.Get(&oldValue, timeCode); + if (value != oldValue) + op.Set(value, timeCode); + } break; + + default: return false; + } + + return true; } //---------------------------------------------------------------------------------------------------------------------- double TransformationMatrix::readDouble(const UsdGeomXformOp& op, UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readDouble\n"); - double result = 0; - UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(op.GetTypeName()); - switch(attr_type) - { - case UsdDataType::kHalf: - { - GfHalf value; - const bool retValue = op.Get(&value, timeCode); - if (retValue) - { - result = float(value); - } - } - break; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readDouble\n"); + double result = 0; + UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(op.GetTypeName()); + switch (attr_type) { + case UsdDataType::kHalf: { + GfHalf value; + const bool retValue = op.Get(&value, timeCode); + if (retValue) { + result = float(value); + } + } break; - case UsdDataType::kFloat: - { - float value; - const bool retValue = op.Get(&value, timeCode); - if (retValue) - { - result = double(value); - } - } - break; + case UsdDataType::kFloat: { + float value; + const bool retValue = op.Get(&value, timeCode); + if (retValue) { + result = double(value); + } + } break; - case UsdDataType::kDouble: - { - double value; - const bool retValue = op.Get(&value, timeCode); - if (retValue) - { - result = value; - } - } - break; + case UsdDataType::kDouble: { + double value; + const bool retValue = op.Get(&value, timeCode); + if (retValue) { + result = value; + } + } break; - case UsdDataType::kInt: - { - int32_t value; - const bool retValue = op.Get(&value, timeCode); - if (retValue) - { - result = double(value); - } - } - break; - - default: - break; - } - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("TransformationMatrix::readDouble %f\n%s\n", result, op.GetOpName().GetText()); - return result; + case UsdDataType::kInt: { + int32_t value; + const bool retValue = op.Get(&value, timeCode); + if (retValue) { + result = double(value); + } + } break; + + default: break; + } + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg("TransformationMatrix::readDouble %f\n%s\n", result, op.GetOpName().GetText()); + return result; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushDouble(const double value, UsdGeomXformOp& op, UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushDouble %f\n%s\n", value, op.GetOpName().GetText()); - - if(timeCode.IsDefault() && op.GetNumTimeSamples()) - { - if(!hasEmptyDefaultValue(op, timeCode)) - { - return; - } - } - - UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(op.GetTypeName()); - switch(attr_type) - { - case UsdDataType::kHalf: - { - GfHalf oldValue; - op.Get(&oldValue); - if(oldValue != GfHalf(value)) - op.Set(GfHalf(value), timeCode); - } - break; - - case UsdDataType::kFloat: - { - float oldValue; - op.Get(&oldValue); - if(oldValue != float(value)) - op.Set(float(value), timeCode); - } - break; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::pushDouble %f\n%s\n", value, op.GetOpName().GetText()); - case UsdDataType::kDouble: - { - double oldValue; - op.Get(&oldValue); - if(oldValue != double(value)) - op.Set(double(value), timeCode); + if (timeCode.IsDefault() && op.GetNumTimeSamples()) { + if (!hasEmptyDefaultValue(op, timeCode)) { + return; + } } - break; - case UsdDataType::kInt: - { - int32_t oldValue; - op.Get(&oldValue); - if(oldValue != int32_t(value)) - op.Set(int32_t(value), timeCode); + UsdDataType attr_type = AL::usdmaya::utils::getAttributeType(op.GetTypeName()); + switch (attr_type) { + case UsdDataType::kHalf: { + GfHalf oldValue; + op.Get(&oldValue); + if (oldValue != GfHalf(value)) + op.Set(GfHalf(value), timeCode); + } break; + + case UsdDataType::kFloat: { + float oldValue; + op.Get(&oldValue); + if (oldValue != float(value)) + op.Set(float(value), timeCode); + } break; + + case UsdDataType::kDouble: { + double oldValue; + op.Get(&oldValue); + if (oldValue != double(value)) + op.Set(double(value), timeCode); + } break; + + case UsdDataType::kInt: { + int32_t oldValue; + op.Get(&oldValue); + if (oldValue != int32_t(value)) + op.Set(int32_t(value), timeCode); + } break; + + default: break; } - break; - - default: - break; - } } //---------------------------------------------------------------------------------------------------------------------- -bool TransformationMatrix::readRotation(MEulerRotation& result, const UsdGeomXformOp& op, UsdTimeCode timeCode) +bool TransformationMatrix::readRotation( + MEulerRotation& result, + const UsdGeomXformOp& op, + UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::readRotation %f %f %f\n%s\n", result.x, result.y, result.z, op.GetOpName().GetText()); - const double degToRad = M_PI / 180.0; - switch(op.GetOpType()) - { - case UsdGeomXformOp::TypeRotateX: - { - result.x = readDouble(op, timeCode) * degToRad; - result.y = 0.0; - result.z = 0.0; - result.order = MEulerRotation::kXYZ; - } - break; - - case UsdGeomXformOp::TypeRotateY: - { - result.x = 0.0; - result.y = readDouble(op, timeCode) * degToRad; - result.z = 0.0; - result.order = MEulerRotation::kXYZ; - } - break; - - case UsdGeomXformOp::TypeRotateZ: - { - result.x = 0.0; - result.y = 0.0; - result.z = readDouble(op, timeCode) * degToRad; - result.order = MEulerRotation::kXYZ; - } - break; - - case UsdGeomXformOp::TypeRotateXYZ: - { - MVector v; - if(readVector(v, op, timeCode)) - { - result.x = v.x * degToRad; - result.y = v.y * degToRad; - result.z = v.z * degToRad; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg( + "TransformationMatrix::readRotation %f %f %f\n%s\n", + result.x, + result.y, + result.z, + op.GetOpName().GetText()); + const double degToRad = M_PI / 180.0; + switch (op.GetOpType()) { + case UsdGeomXformOp::TypeRotateX: { + result.x = readDouble(op, timeCode) * degToRad; + result.y = 0.0; + result.z = 0.0; result.order = MEulerRotation::kXYZ; - } - else - return false; - } - break; - - case UsdGeomXformOp::TypeRotateXZY: - { - MVector v; - if(readVector(v, op, timeCode)) - { - result.x = v.x * degToRad; - result.y = v.y * degToRad; - result.z = v.z * degToRad; - result.order = MEulerRotation::kXZY; - } - else - return false; - } - break; - - case UsdGeomXformOp::TypeRotateYXZ: - { - MVector v; - if(readVector(v, op, timeCode)) - { - result.x = v.x * degToRad; - result.y = v.y * degToRad; - result.z = v.z * degToRad; - result.order = MEulerRotation::kYXZ; - } - else - return false; - } - break; - - case UsdGeomXformOp::TypeRotateYZX: - { - MVector v; - if(readVector(v, op, timeCode)) - { - result.x = v.x * degToRad; - result.y = v.y * degToRad; - result.z = v.z * degToRad; - result.order = MEulerRotation::kYZX; - } - else - return false; - } - break; - - case UsdGeomXformOp::TypeRotateZXY: - { - MVector v; - if(readVector(v, op, timeCode)) - { - result.x = v.x * degToRad; - result.y = v.y * degToRad; - result.z = v.z * degToRad; - result.order = MEulerRotation::kZXY; - } - else - return false; - } - break; + } break; - case UsdGeomXformOp::TypeRotateZYX: - { - MVector v; - if(readVector(v, op, timeCode)) - { - result.x = v.x * degToRad; - result.y = v.y * degToRad; - result.z = v.z * degToRad; - result.order = MEulerRotation::kZYX; - } - else - return false; - } - break; + case UsdGeomXformOp::TypeRotateY: { + result.x = 0.0; + result.y = readDouble(op, timeCode) * degToRad; + result.z = 0.0; + result.order = MEulerRotation::kXYZ; + } break; - default: - return false; - } - return true; + case UsdGeomXformOp::TypeRotateZ: { + result.x = 0.0; + result.y = 0.0; + result.z = readDouble(op, timeCode) * degToRad; + result.order = MEulerRotation::kXYZ; + } break; + + case UsdGeomXformOp::TypeRotateXYZ: { + MVector v; + if (readVector(v, op, timeCode)) { + result.x = v.x * degToRad; + result.y = v.y * degToRad; + result.z = v.z * degToRad; + result.order = MEulerRotation::kXYZ; + } else + return false; + } break; + + case UsdGeomXformOp::TypeRotateXZY: { + MVector v; + if (readVector(v, op, timeCode)) { + result.x = v.x * degToRad; + result.y = v.y * degToRad; + result.z = v.z * degToRad; + result.order = MEulerRotation::kXZY; + } else + return false; + } break; + + case UsdGeomXformOp::TypeRotateYXZ: { + MVector v; + if (readVector(v, op, timeCode)) { + result.x = v.x * degToRad; + result.y = v.y * degToRad; + result.z = v.z * degToRad; + result.order = MEulerRotation::kYXZ; + } else + return false; + } break; + + case UsdGeomXformOp::TypeRotateYZX: { + MVector v; + if (readVector(v, op, timeCode)) { + result.x = v.x * degToRad; + result.y = v.y * degToRad; + result.z = v.z * degToRad; + result.order = MEulerRotation::kYZX; + } else + return false; + } break; + + case UsdGeomXformOp::TypeRotateZXY: { + MVector v; + if (readVector(v, op, timeCode)) { + result.x = v.x * degToRad; + result.y = v.y * degToRad; + result.z = v.z * degToRad; + result.order = MEulerRotation::kZXY; + } else + return false; + } break; + + case UsdGeomXformOp::TypeRotateZYX: { + MVector v; + if (readVector(v, op, timeCode)) { + result.x = v.x * degToRad; + result.y = v.y * degToRad; + result.z = v.z * degToRad; + result.order = MEulerRotation::kZYX; + } else + return false; + } break; + + default: return false; + } + return true; } //---------------------------------------------------------------------------------------------------------------------- -bool TransformationMatrix::pushRotation(const MEulerRotation& value, UsdGeomXformOp& op, UsdTimeCode timeCode) +bool TransformationMatrix::pushRotation( + const MEulerRotation& value, + UsdGeomXformOp& op, + UsdTimeCode timeCode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotation %f %f %f\n%s\n", value.x, value.y, value.z, op.GetOpName().GetText()); - - if(timeCode.IsDefault() && op.GetNumTimeSamples()) - { - if(!hasEmptyDefaultValue(op, timeCode)) - { - return false; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg( + "TransformationMatrix::pushRotation %f %f %f\n%s\n", + value.x, + value.y, + value.z, + op.GetOpName().GetText()); + + if (timeCode.IsDefault() && op.GetNumTimeSamples()) { + if (!hasEmptyDefaultValue(op, timeCode)) { + return false; + } } - } - const double radToDeg = 180.0 / M_PI; - switch(op.GetOpType()) - { - case UsdGeomXformOp::TypeRotateX: - { - pushDouble(value.x * radToDeg, op, timeCode); - } - break; + const double radToDeg = 180.0 / M_PI; + switch (op.GetOpType()) { + case UsdGeomXformOp::TypeRotateX: { + pushDouble(value.x * radToDeg, op, timeCode); + } break; - case UsdGeomXformOp::TypeRotateY: - { - pushDouble(value.y * radToDeg, op, timeCode); - } - break; + case UsdGeomXformOp::TypeRotateY: { + pushDouble(value.y * radToDeg, op, timeCode); + } break; - case UsdGeomXformOp::TypeRotateZ: - { - pushDouble(value.z * radToDeg, op, timeCode); - } - break; + case UsdGeomXformOp::TypeRotateZ: { + pushDouble(value.z * radToDeg, op, timeCode); + } break; - case UsdGeomXformOp::TypeRotateXYZ: - case UsdGeomXformOp::TypeRotateXZY: - case UsdGeomXformOp::TypeRotateYXZ: - case UsdGeomXformOp::TypeRotateYZX: - case UsdGeomXformOp::TypeRotateZYX: - case UsdGeomXformOp::TypeRotateZXY: - { - MVector v(value.x, value.y, value.z); - v *= radToDeg; - return pushVector(v, op, timeCode); - } - break; + case UsdGeomXformOp::TypeRotateXYZ: + case UsdGeomXformOp::TypeRotateXZY: + case UsdGeomXformOp::TypeRotateYXZ: + case UsdGeomXformOp::TypeRotateYZX: + case UsdGeomXformOp::TypeRotateZYX: + case UsdGeomXformOp::TypeRotateZXY: { + MVector v(value.x, value.y, value.z); + v *= radToDeg; + return pushVector(v, op, timeCode); + } break; - default: - return false; - } - return true; + default: return false; + } + return true; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::initialiseToPrim(bool readFromPrim, Scope* transformNode) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::initialiseToPrim\n"); - - // if not yet initialized, do not execute this code! (It will crash!). - if(!m_prim) - return; - - bool resetsXformStack = false; - m_xformops = m_xform.GetOrderedXformOps(&resetsXformStack); - m_orderedOps.resize(m_xformops.size()); - - if(!resetsXformStack) - { - m_flags |= kInheritsTransform; - } - - if(matchesMayaProfile(m_xformops.begin(), m_xformops.end(), m_orderedOps.begin())) - { - m_flags |= kFromMayaSchema; - } - else - { - } - - { - // We want to disable push to prim if enabled, otherwise MPlug value queries - // and setting in the switch statement below will trigger pushing to the prim, - // which creates undesirable "over"s. To accomplish this, we create an object - // which disables push to prim when created and resets that state back to what - // it was originally when it goes out of scope. - // - // (Note that, because of m_flags processing at the end of this method, we need - // to create a scope for disableNow which ends before that processing happens - // instead of simply letting disableNow go out of scope when the function - // exits.) - // - Scoped_DisablePushToPrim disableNow(*this); - - auto opIt = m_orderedOps.begin(); - for(std::vector::const_iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - const UsdGeomXformOp& op = *it; - switch(*opIt) - { - case kTranslate: - { - m_flags |= kPrimHasTranslation; - if(op.GetNumTimeSamples() > 1) - { - m_flags |= kAnimatedTranslation; - } - if(readFromPrim) - { - MVector tempTranslation; - internal_readVector(tempTranslation, op); - if(transformNode) - { - MPlug(transformNode->thisMObject(), MPxTransform::translateX).setValue(tempTranslation.x); - MPlug(transformNode->thisMObject(), MPxTransform::translateY).setValue(tempTranslation.y); - MPlug(transformNode->thisMObject(), MPxTransform::translateZ).setValue(tempTranslation.z); - m_translationTweak[0] = m_translationTweak[1] = m_translationTweak[2] = 0; - m_translationFromUsd = tempTranslation; - } - } - } - break; - - case kPivot: - { - m_flags |= kPrimHasPivot; - if(readFromPrim) - { - internal_readPoint(m_scalePivotFromUsd, op); - m_rotatePivotFromUsd = m_scalePivotFromUsd; - if(transformNode) - { - MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotX).setValue(m_rotatePivotFromUsd.x); - MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotY).setValue(m_rotatePivotFromUsd.y); - MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotZ).setValue(m_rotatePivotFromUsd.z); - MPlug(transformNode->thisMObject(), MPxTransform::scalePivotX).setValue(m_scalePivotFromUsd.x); - MPlug(transformNode->thisMObject(), MPxTransform::scalePivotY).setValue(m_scalePivotFromUsd.y); - MPlug(transformNode->thisMObject(), MPxTransform::scalePivotZ).setValue(m_scalePivotFromUsd.z); - } - } - } - break; - - case kRotatePivotTranslate: - { - m_flags |= kPrimHasRotatePivotTranslate; - if(readFromPrim) - { - internal_readVector(m_rotatePivotTranslationFromUsd, op); - if(transformNode) - { - MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotTranslateX).setValue(m_rotatePivotTranslationFromUsd.x); - MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotTranslateY).setValue(m_rotatePivotTranslationFromUsd.y); - MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotTranslateZ).setValue(m_rotatePivotTranslationFromUsd.z); - } - } - } - break; - - case kRotatePivot: - { - m_flags |= kPrimHasRotatePivot; - if(readFromPrim) - { - internal_readPoint(m_rotatePivotFromUsd, op); - if(transformNode) - { - MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotX).setValue(m_rotatePivotFromUsd.x); - MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotY).setValue(m_rotatePivotFromUsd.y); - MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotZ).setValue(m_rotatePivotFromUsd.z); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::initialiseToPrim\n"); + + // if not yet initialized, do not execute this code! (It will crash!). + if (!m_prim) + return; + + bool resetsXformStack = false; + m_xformops = m_xform.GetOrderedXformOps(&resetsXformStack); + m_orderedOps.resize(m_xformops.size()); + + if (!resetsXformStack) { + m_flags |= kInheritsTransform; + } + + if (matchesMayaProfile(m_xformops.begin(), m_xformops.end(), m_orderedOps.begin())) { + m_flags |= kFromMayaSchema; + } else { + } + + { + // We want to disable push to prim if enabled, otherwise MPlug value queries + // and setting in the switch statement below will trigger pushing to the prim, + // which creates undesirable "over"s. To accomplish this, we create an object + // which disables push to prim when created and resets that state back to what + // it was originally when it goes out of scope. + // + // (Note that, because of m_flags processing at the end of this method, we need + // to create a scope for disableNow which ends before that processing happens + // instead of simply letting disableNow go out of scope when the function + // exits.) + // + Scoped_DisablePushToPrim disableNow(*this); + + auto opIt = m_orderedOps.begin(); + for (std::vector::const_iterator it = m_xformops.begin(), + e = m_xformops.end(); + it != e; + ++it, ++opIt) { + const UsdGeomXformOp& op = *it; + switch (*opIt) { + case kTranslate: { + m_flags |= kPrimHasTranslation; + if (op.GetNumTimeSamples() > 1) { + m_flags |= kAnimatedTranslation; + } + if (readFromPrim) { + MVector tempTranslation; + internal_readVector(tempTranslation, op); + if (transformNode) { + MPlug(transformNode->thisMObject(), MPxTransform::translateX) + .setValue(tempTranslation.x); + MPlug(transformNode->thisMObject(), MPxTransform::translateY) + .setValue(tempTranslation.y); + MPlug(transformNode->thisMObject(), MPxTransform::translateZ) + .setValue(tempTranslation.z); + m_translationTweak[0] = m_translationTweak[1] = m_translationTweak[2] = 0; + m_translationFromUsd = tempTranslation; + } + } + } break; + + case kPivot: { + m_flags |= kPrimHasPivot; + if (readFromPrim) { + internal_readPoint(m_scalePivotFromUsd, op); + m_rotatePivotFromUsd = m_scalePivotFromUsd; + if (transformNode) { + MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotX) + .setValue(m_rotatePivotFromUsd.x); + MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotY) + .setValue(m_rotatePivotFromUsd.y); + MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotZ) + .setValue(m_rotatePivotFromUsd.z); + MPlug(transformNode->thisMObject(), MPxTransform::scalePivotX) + .setValue(m_scalePivotFromUsd.x); + MPlug(transformNode->thisMObject(), MPxTransform::scalePivotY) + .setValue(m_scalePivotFromUsd.y); + MPlug(transformNode->thisMObject(), MPxTransform::scalePivotZ) + .setValue(m_scalePivotFromUsd.z); + } + } + } break; + + case kRotatePivotTranslate: { + m_flags |= kPrimHasRotatePivotTranslate; + if (readFromPrim) { + internal_readVector(m_rotatePivotTranslationFromUsd, op); + if (transformNode) { + MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotTranslateX) + .setValue(m_rotatePivotTranslationFromUsd.x); + MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotTranslateY) + .setValue(m_rotatePivotTranslationFromUsd.y); + MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotTranslateZ) + .setValue(m_rotatePivotTranslationFromUsd.z); + } + } + } break; + + case kRotatePivot: { + m_flags |= kPrimHasRotatePivot; + if (readFromPrim) { + internal_readPoint(m_rotatePivotFromUsd, op); + if (transformNode) { + MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotX) + .setValue(m_rotatePivotFromUsd.x); + MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotY) + .setValue(m_rotatePivotFromUsd.y); + MPlug(transformNode->thisMObject(), MPxTransform::rotatePivotZ) + .setValue(m_rotatePivotFromUsd.z); + } + } + } break; + + case kRotate: { + m_flags |= kPrimHasRotation; + if (op.GetNumTimeSamples() > 1) { + m_flags |= kAnimatedRotation; + } + if (readFromPrim) { + internal_readRotation(m_rotationFromUsd, op); + if (transformNode) { + m_rotationTweak[0] = m_rotationTweak[1] = m_rotationTweak[2] = 0; + // attempting to set the rotation via the attributes can end up failing when + // using zxy rotation orders. The only reliable way to set this value would + // appeear to be via MFnTransform :( + MFnTransform fn(m_transformNode.object()); + fn.setRotation(m_rotationFromUsd); + } + } + } break; + + case kRotateAxis: { + m_flags |= kPrimHasRotateAxes; + if (readFromPrim) { + MEulerRotation eulers; + internal_readRotation(eulers, op); + m_rotateOrientationFromUsd = eulers.asQuaternion(); + if (transformNode) { + MPlug(transformNode->thisMObject(), MPxTransform::rotateAxisX) + .setValue(eulers.x); + MPlug(transformNode->thisMObject(), MPxTransform::rotateAxisY) + .setValue(eulers.y); + MPlug(transformNode->thisMObject(), MPxTransform::rotateAxisZ) + .setValue(eulers.z); + } + } + } break; + + case kRotatePivotInv: { + } break; + + case kScalePivotTranslate: { + m_flags |= kPrimHasScalePivotTranslate; + if (readFromPrim) { + internal_readVector(m_scalePivotTranslationFromUsd, op); + if (transformNode) { + MPlug(transformNode->thisMObject(), MPxTransform::scalePivotTranslateX) + .setValue(m_scalePivotTranslationFromUsd.x); + MPlug(transformNode->thisMObject(), MPxTransform::scalePivotTranslateY) + .setValue(m_scalePivotTranslationFromUsd.y); + MPlug(transformNode->thisMObject(), MPxTransform::scalePivotTranslateZ) + .setValue(m_scalePivotTranslationFromUsd.z); + } + } + } break; + + case kScalePivot: { + m_flags |= kPrimHasScalePivot; + if (readFromPrim) { + internal_readPoint(m_scalePivotFromUsd, op); + if (transformNode) { + MPlug(transformNode->thisMObject(), MPxTransform::scalePivotX) + .setValue(m_scalePivotFromUsd.x); + MPlug(transformNode->thisMObject(), MPxTransform::scalePivotY) + .setValue(m_scalePivotFromUsd.y); + MPlug(transformNode->thisMObject(), MPxTransform::scalePivotZ) + .setValue(m_scalePivotFromUsd.z); + } + } + } break; + + case kShear: { + m_flags |= kPrimHasShear; + if (op.GetNumTimeSamples() > 1) { + m_flags |= kAnimatedShear; + } + if (readFromPrim) { + MVector tempShear; + internal_readShear(tempShear, op); + if (transformNode) { + MPlug(transformNode->thisMObject(), MPxTransform::shearXY) + .setValue(tempShear.x); + MPlug(transformNode->thisMObject(), MPxTransform::shearXZ) + .setValue(tempShear.y); + MPlug(transformNode->thisMObject(), MPxTransform::shearYZ) + .setValue(tempShear.z); + m_shearTweak[0] = m_shearTweak[1] = m_shearTweak[2] = 0; + m_shearFromUsd = tempShear; + } + } + } break; + + case kScale: { + m_flags |= kPrimHasScale; + if (op.GetNumTimeSamples() > 1) { + m_flags |= kAnimatedScale; + } + if (readFromPrim) { + MVector tempScale(1.0, 1.0, 1.0); + internal_readVector(tempScale, op); + if (transformNode) { + MPlug(transformNode->thisMObject(), MPxTransform::scaleX) + .setValue(tempScale.x); + MPlug(transformNode->thisMObject(), MPxTransform::scaleY) + .setValue(tempScale.y); + MPlug(transformNode->thisMObject(), MPxTransform::scaleZ) + .setValue(tempScale.z); + m_scaleTweak[0] = m_scaleTweak[1] = m_scaleTweak[2] = 0; + m_scaleFromUsd = tempScale; + } + } + } break; + + case kScalePivotInv: { + } break; + + case kPivotInv: { + } break; + + case kTransform: { + m_flags |= kPrimHasTransform; + m_flags |= kFromMatrix; + m_flags |= kPushPrimToMatrix; + if (op.GetNumTimeSamples() > 1) { + m_flags |= kAnimatedMatrix; + } + + if (readFromPrim) { + MMatrix m; + internal_readMatrix(m, op); + setFromMatrix(transformNode->thisMObject(), m); + } + } break; + + case kUnknownOp: { + } break; } - } - } - break; - - case kRotate: - { - m_flags |= kPrimHasRotation; - if(op.GetNumTimeSamples() > 1) - { - m_flags |= kAnimatedRotation; - } - if(readFromPrim) - { - internal_readRotation(m_rotationFromUsd, op); - if(transformNode) - { - m_rotationTweak[0] = m_rotationTweak[1] = m_rotationTweak[2] = 0; - // attempting to set the rotation via the attributes can end up failing when using zxy rotation orders. - // The only reliable way to set this value would appeear to be via MFnTransform :( - MFnTransform fn(m_transformNode.object()); - fn.setRotation(m_rotationFromUsd); - } - } - } - break; - - case kRotateAxis: - { - m_flags |= kPrimHasRotateAxes; - if(readFromPrim) { - MEulerRotation eulers; - internal_readRotation(eulers, op); - m_rotateOrientationFromUsd = eulers.asQuaternion(); - if(transformNode) - { - MPlug(transformNode->thisMObject(), MPxTransform::rotateAxisX).setValue(eulers.x); - MPlug(transformNode->thisMObject(), MPxTransform::rotateAxisY).setValue(eulers.y); - MPlug(transformNode->thisMObject(), MPxTransform::rotateAxisZ).setValue(eulers.z); - } - } - } - break; - - case kRotatePivotInv: - { - } - break; - - case kScalePivotTranslate: - { - m_flags |= kPrimHasScalePivotTranslate; - if(readFromPrim) - { - internal_readVector(m_scalePivotTranslationFromUsd, op); - if(transformNode) - { - MPlug(transformNode->thisMObject(), MPxTransform::scalePivotTranslateX).setValue(m_scalePivotTranslationFromUsd.x); - MPlug(transformNode->thisMObject(), MPxTransform::scalePivotTranslateY).setValue(m_scalePivotTranslationFromUsd.y); - MPlug(transformNode->thisMObject(), MPxTransform::scalePivotTranslateZ).setValue(m_scalePivotTranslationFromUsd.z); - } - } - } - break; - - case kScalePivot: - { - m_flags |= kPrimHasScalePivot; - if(readFromPrim) - { - internal_readPoint(m_scalePivotFromUsd, op); - if(transformNode) - { - MPlug(transformNode->thisMObject(), MPxTransform::scalePivotX).setValue(m_scalePivotFromUsd.x); - MPlug(transformNode->thisMObject(), MPxTransform::scalePivotY).setValue(m_scalePivotFromUsd.y); - MPlug(transformNode->thisMObject(), MPxTransform::scalePivotZ).setValue(m_scalePivotFromUsd.z); - } - } - } - break; - - case kShear: - { - m_flags |= kPrimHasShear; - if(op.GetNumTimeSamples() > 1) - { - m_flags |= kAnimatedShear; - } - if(readFromPrim) - { - MVector tempShear; - internal_readShear(tempShear, op); - if(transformNode) - { - MPlug(transformNode->thisMObject(), MPxTransform::shearXY).setValue(tempShear.x); - MPlug(transformNode->thisMObject(), MPxTransform::shearXZ).setValue(tempShear.y); - MPlug(transformNode->thisMObject(), MPxTransform::shearYZ).setValue(tempShear.z); - m_shearTweak[0] = m_shearTweak[1] = m_shearTweak[2] = 0; - m_shearFromUsd = tempShear; - } - } - } - break; - - case kScale: - { - m_flags |= kPrimHasScale; - if(op.GetNumTimeSamples() > 1) - { - m_flags |= kAnimatedScale; - } - if(readFromPrim) - { - MVector tempScale(1.0, 1.0, 1.0); - internal_readVector(tempScale, op); - if(transformNode) - { - MPlug(transformNode->thisMObject(), MPxTransform::scaleX).setValue(tempScale.x); - MPlug(transformNode->thisMObject(), MPxTransform::scaleY).setValue(tempScale.y); - MPlug(transformNode->thisMObject(), MPxTransform::scaleZ).setValue(tempScale.z); - m_scaleTweak[0] = m_scaleTweak[1] = m_scaleTweak[2] = 0; - m_scaleFromUsd = tempScale; - } - } - } - break; - - case kScalePivotInv: - { - } - break; - - case kPivotInv: - { - } - break; - - case kTransform: - { - m_flags |= kPrimHasTransform; - m_flags |= kFromMatrix; - m_flags |= kPushPrimToMatrix; - if(op.GetNumTimeSamples() > 1) - { - m_flags |= kAnimatedMatrix; - } - - if(readFromPrim) - { - MMatrix m; - internal_readMatrix(m, op); - setFromMatrix(transformNode->thisMObject(), m); - } } - break; - case kUnknownOp: - { - } - break; - } + // Push to prim will now be reset to its original state as the + // disableNow variable goes out of scope here... } - // Push to prim will now be reset to its original state as the - // disableNow variable goes out of scope here... - } - - if(m_flags & kAnimationMask) - { - m_flags &= ~kPushToPrimEnabled; - m_flags |= kReadAnimatedValues; - } + if (m_flags & kAnimationMask) { + m_flags &= ~kPushToPrimEnabled; + m_flags |= kReadAnimatedValues; + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::updateToTime(const UsdTimeCode& time) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::updateToTime %f\n", time.GetValue()); - // if not yet initialized, do not execute this code! (It will crash!). - if(!m_prim) - { - return; - } - if(m_time != time) - { - m_time = time; - { - auto opIt = m_orderedOps.begin(); - for(std::vector::const_iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - const UsdGeomXformOp& op = *it; - switch(*opIt) + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::updateToTime %f\n", time.GetValue()); + // if not yet initialized, do not execute this code! (It will crash!). + if (!m_prim) { + return; + } + if (m_time != time) { + m_time = time; { - case kTranslate: - { - if(op.GetNumTimeSamples() >= 1) - { - m_flags |= kAnimatedTranslation; - internal_readVector(m_translationFromUsd, op); - MPxTransformationMatrix::translationValue = m_translationFromUsd + m_translationTweak; - } - } - break; - - case kRotate: - { - if(op.GetNumTimeSamples() >= 1) - { - m_flags |= kAnimatedRotation; - internal_readRotation(m_rotationFromUsd, op); - MPxTransformationMatrix::rotationValue = m_rotationFromUsd; - MPxTransformationMatrix::rotationValue.x += m_rotationTweak.x; - MPxTransformationMatrix::rotationValue.y += m_rotationTweak.y; - MPxTransformationMatrix::rotationValue.z += m_rotationTweak.z; + auto opIt = m_orderedOps.begin(); + for (std::vector::const_iterator it = m_xformops.begin(), + e = m_xformops.end(); + it != e; + ++it, ++opIt) { + const UsdGeomXformOp& op = *it; + switch (*opIt) { + case kTranslate: { + if (op.GetNumTimeSamples() >= 1) { + m_flags |= kAnimatedTranslation; + internal_readVector(m_translationFromUsd, op); + MPxTransformationMatrix::translationValue + = m_translationFromUsd + m_translationTweak; + } + } break; + + case kRotate: { + if (op.GetNumTimeSamples() >= 1) { + m_flags |= kAnimatedRotation; + internal_readRotation(m_rotationFromUsd, op); + MPxTransformationMatrix::rotationValue = m_rotationFromUsd; + MPxTransformationMatrix::rotationValue.x += m_rotationTweak.x; + MPxTransformationMatrix::rotationValue.y += m_rotationTweak.y; + MPxTransformationMatrix::rotationValue.z += m_rotationTweak.z; + } + } break; + + case kScale: { + if (op.GetNumTimeSamples() >= 1) { + m_flags |= kAnimatedScale; + internal_readVector(m_scaleFromUsd, op); + MPxTransformationMatrix::scaleValue = m_scaleFromUsd + m_scaleTweak; + } + } break; + + case kShear: { + if (op.GetNumTimeSamples() >= 1) { + m_flags |= kAnimatedShear; + internal_readShear(m_shearFromUsd, op); + MPxTransformationMatrix::shearValue = m_shearFromUsd + m_shearTweak; + } + } break; + + case kTransform: { + if (op.GetNumTimeSamples() >= 1) { + m_flags |= kAnimatedMatrix; + GfMatrix4d matrix; + op.Get(&matrix, getTimeCode()); + double T[3], S[3]; + AL::usdmaya::utils::matrixToSRT(matrix, S, m_rotationFromUsd, T); + m_scaleFromUsd.x = S[0]; + m_scaleFromUsd.y = S[1]; + m_scaleFromUsd.z = S[2]; + m_translationFromUsd.x = T[0]; + m_translationFromUsd.y = T[1]; + m_translationFromUsd.z = T[2]; + MPxTransformationMatrix::rotationValue.x + = m_rotationFromUsd.x + m_rotationTweak.x; + MPxTransformationMatrix::rotationValue.y + = m_rotationFromUsd.y + m_rotationTweak.y; + MPxTransformationMatrix::rotationValue.z + = m_rotationFromUsd.z + m_rotationTweak.z; + MPxTransformationMatrix::translationValue + = m_translationFromUsd + m_translationTweak; + MPxTransformationMatrix::scaleValue = m_scaleFromUsd + m_scaleTweak; + } + } break; + + default: break; + } } - } - break; - - case kScale: - { - if(op.GetNumTimeSamples() >= 1) - { - m_flags |= kAnimatedScale; - internal_readVector(m_scaleFromUsd, op); - MPxTransformationMatrix::scaleValue = m_scaleFromUsd + m_scaleTweak; - } - } - break; - - case kShear: - { - if(op.GetNumTimeSamples() >= 1) - { - m_flags |= kAnimatedShear; - internal_readShear(m_shearFromUsd, op); - MPxTransformationMatrix::shearValue = m_shearFromUsd + m_shearTweak; - } - } - break; - - case kTransform: - { - if(op.GetNumTimeSamples() >= 1) - { - m_flags |= kAnimatedMatrix; - GfMatrix4d matrix; - op.Get(&matrix, getTimeCode()); - double T[3], S[3]; - AL::usdmaya::utils::matrixToSRT(matrix, S, m_rotationFromUsd, T); - m_scaleFromUsd.x = S[0]; - m_scaleFromUsd.y = S[1]; - m_scaleFromUsd.z = S[2]; - m_translationFromUsd.x = T[0]; - m_translationFromUsd.y = T[1]; - m_translationFromUsd.z = T[2]; - MPxTransformationMatrix::rotationValue.x = m_rotationFromUsd.x + m_rotationTweak.x; - MPxTransformationMatrix::rotationValue.y = m_rotationFromUsd.y + m_rotationTweak.y; - MPxTransformationMatrix::rotationValue.z = m_rotationFromUsd.z + m_rotationTweak.z; - MPxTransformationMatrix::translationValue = m_translationFromUsd + m_translationTweak; - MPxTransformationMatrix::scaleValue = m_scaleFromUsd + m_scaleTweak; - } - } - break; - - default: - break; } - } } - } } //---------------------------------------------------------------------------------------------------------------------- @@ -1314,50 +1204,44 @@ void TransformationMatrix::updateToTime(const UsdTimeCode& time) //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertTranslateOp() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertTranslateOp\n"); - // generate our translate op, and insert into the correct stack location - UsdGeomXformOp op = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionDouble); - m_xformops.insert(m_xformops.begin(), op); - m_orderedOps.insert(m_orderedOps.begin(), kTranslate); - m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); - m_flags |= kPrimHasTranslation; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertTranslateOp\n"); + // generate our translate op, and insert into the correct stack location + UsdGeomXformOp op = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionDouble); + m_xformops.insert(m_xformops.begin(), op); + m_orderedOps.insert(m_orderedOps.begin(), kTranslate); + m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); + m_flags |= kPrimHasTranslation; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::translateTo(const MVector& vector, MSpace::Space space) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::translateTo %f %f %f\n", vector.x, vector.y, vector.z); - if(isTranslateLocked()) - return MPxTransformationMatrix::translateTo(vector, space); - - MStatus status = MPxTransformationMatrix::translateTo(vector, space); - if(status) - { - m_translationTweak = MPxTransformationMatrix::translationValue - m_translationFromUsd; - } - - if(pushToPrimAvailable()) - { - // if the prim does not contain a translation, make sure we insert a transform op for that. - if(primHasTranslation()) - { - // helping the branch predictor - } - else - if(!pushPrimToMatrix() && vector != MVector(0.0, 0.0, 0.0)) - { - insertTranslateOp(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::translateTo %f %f %f\n", vector.x, vector.y, vector.z); + if (isTranslateLocked()) + return MPxTransformationMatrix::translateTo(vector, space); + + MStatus status = MPxTransformationMatrix::translateTo(vector, space); + if (status) { + m_translationTweak = MPxTransformationMatrix::translationValue - m_translationFromUsd; + } + + if (pushToPrimAvailable()) { + // if the prim does not contain a translation, make sure we insert a transform op for that. + if (primHasTranslation()) { + // helping the branch predictor + } else if (!pushPrimToMatrix() && vector != MVector(0.0, 0.0, 0.0)) { + insertTranslateOp(); + } - // Push new value to prim, but only if it's changing, otherwise extra work and unintended - // side effects will happen. - // - if (!vector.isEquivalent(m_translationFromUsd)) - { - pushTranslateToPrim(); + // Push new value to prim, but only if it's changing, otherwise extra work and unintended + // side effects will happen. + // + if (!vector.isEquivalent(m_translationFromUsd)) { + pushTranslateToPrim(); + } } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- @@ -1365,51 +1249,45 @@ MStatus TransformationMatrix::translateTo(const MVector& vector, MSpace::Space s //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertScaleOp() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertScaleOp\n"); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertScaleOp\n"); - // generate our translate op, and insert into the correct stack location - UsdGeomXformOp op = m_xform.AddScaleOp(UsdGeomXformOp::PrecisionFloat); + // generate our translate op, and insert into the correct stack location + UsdGeomXformOp op = m_xform.AddScaleOp(UsdGeomXformOp::PrecisionFloat); - auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScale); - auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); + auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScale); + auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); - m_xformops.insert(posInXfm, op); - m_orderedOps.insert(posInOps, kScale); - m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); - m_flags |= kPrimHasScale; + m_xformops.insert(posInXfm, op); + m_orderedOps.insert(posInOps, kScale); + m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); + m_flags |= kPrimHasScale; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::scaleTo(const MVector& scale, MSpace::Space space) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::scaleTo %f %f %f\n", scale.x, scale.y, scale.z); - if(isScaleLocked()) - return MPxTransformationMatrix::scaleTo(scale, space); - - MStatus status = MPxTransformationMatrix::scaleTo(scale, space); - if(status) - { - m_scaleTweak = MPxTransformationMatrix::scaleValue - m_scaleFromUsd; - } - if(pushToPrimAvailable()) - { - if(primHasScale()) - { - // helping the branch predictor - } - else - if(!pushPrimToMatrix() && scale != MVector(1.0, 1.0, 1.0)) - { - // rare case: add a new scale op into the prim - insertScaleOp(); - } - // Push new value to prim, but only if it's changing. - if (!scale.isEquivalent(m_scaleFromUsd)) - { - pushScaleToPrim(); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::scaleTo %f %f %f\n", scale.x, scale.y, scale.z); + if (isScaleLocked()) + return MPxTransformationMatrix::scaleTo(scale, space); + + MStatus status = MPxTransformationMatrix::scaleTo(scale, space); + if (status) { + m_scaleTweak = MPxTransformationMatrix::scaleValue - m_scaleFromUsd; + } + if (pushToPrimAvailable()) { + if (primHasScale()) { + // helping the branch predictor + } else if (!pushPrimToMatrix() && scale != MVector(1.0, 1.0, 1.0)) { + // rare case: add a new scale op into the prim + insertScaleOp(); + } + // Push new value to prim, but only if it's changing. + if (!scale.isEquivalent(m_scaleFromUsd)) { + pushScaleToPrim(); + } } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- @@ -1417,1122 +1295,1036 @@ MStatus TransformationMatrix::scaleTo(const MVector& scale, MSpace::Space space) //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertShearOp() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertShearOp\n"); - // generate our translate op, and insert into the correct stack location - UsdGeomXformOp op = m_xform.AddTransformOp(UsdGeomXformOp::PrecisionDouble, TfToken("shear")); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertShearOp\n"); + // generate our translate op, and insert into the correct stack location + UsdGeomXformOp op = m_xform.AddTransformOp(UsdGeomXformOp::PrecisionDouble, TfToken("shear")); - auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kShear); - auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); + auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kShear); + auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); - m_xformops.insert(posInXfm, op); - m_orderedOps.insert(posInOps, kShear); - m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); - m_flags |= kPrimHasShear; + m_xformops.insert(posInXfm, op); + m_orderedOps.insert(posInOps, kShear); + m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); + m_flags |= kPrimHasShear; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::shearTo(const MVector& shear, MSpace::Space space) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::shearTo %f %f %f\n", shear.x, shear.y, shear.z); - if(isShearLocked()) - return MPxTransformationMatrix::shearTo(shear, space); - MStatus status = MPxTransformationMatrix::shearTo(shear, space); - if(status) - { - m_shearTweak = MPxTransformationMatrix::shearValue - m_shearFromUsd; - } - if(pushToPrimAvailable()) - { - if(primHasShear()) - { - // helping the branch predictor - } - else - if(!pushPrimToMatrix() && shear != MVector(0.0, 0.0, 0.0)) - { - // rare case: add a new scale op into the prim - insertShearOp(); - } - // Push new value to prim, but only if it's changing. - if (!shear.isEquivalent(m_shearFromUsd)) - { - pushShearToPrim(); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::shearTo %f %f %f\n", shear.x, shear.y, shear.z); + if (isShearLocked()) + return MPxTransformationMatrix::shearTo(shear, space); + MStatus status = MPxTransformationMatrix::shearTo(shear, space); + if (status) { + m_shearTweak = MPxTransformationMatrix::shearValue - m_shearFromUsd; + } + if (pushToPrimAvailable()) { + if (primHasShear()) { + // helping the branch predictor + } else if (!pushPrimToMatrix() && shear != MVector(0.0, 0.0, 0.0)) { + // rare case: add a new scale op into the prim + insertShearOp(); + } + // Push new value to prim, but only if it's changing. + if (!shear.isEquivalent(m_shearFromUsd)) { + pushShearToPrim(); + } } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertScalePivotOp() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertScalePivotOp\n"); - // generate our translate op, and insert into the correct stack location - UsdGeomXformOp op = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("scalePivot")); - UsdGeomXformOp opinv = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("scalePivot"), true); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertScalePivotOp\n"); + // generate our translate op, and insert into the correct stack location + UsdGeomXformOp op + = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("scalePivot")); + UsdGeomXformOp opinv + = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("scalePivot"), true); - { - auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScalePivot); - auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); - m_xformops.insert(posInXfm, op); - m_orderedOps.insert(posInOps, kScalePivot); - } - { - auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScalePivotInv); - auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); - m_xformops.insert(posInXfm, opinv); - m_orderedOps.insert(posInOps, kScalePivotInv); - } - m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); - m_flags |= kPrimHasScalePivot; + { + auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScalePivot); + auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); + m_xformops.insert(posInXfm, op); + m_orderedOps.insert(posInOps, kScalePivot); + } + { + auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScalePivotInv); + auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); + m_xformops.insert(posInXfm, opinv); + m_orderedOps.insert(posInOps, kScalePivotInv); + } + m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); + m_flags |= kPrimHasScalePivot; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::setScalePivot(const MPoint& sp, MSpace::Space space, bool balance) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setScalePivot %f %f %f\n", sp.x, sp.y, sp.z); - MStatus status = MPxTransformationMatrix::setScalePivot(sp, space, balance); - if(status) - { - m_scalePivotTweak = MPxTransformationMatrix::scalePivotValue - m_scalePivotFromUsd; - } - if(pushToPrimAvailable()) - { - // Do not insert a scale pivot op if the input prim has a generic pivot. - if(primHasScalePivot() || primHasPivot()) - { - } - else - if(!pushPrimToMatrix() && sp != MPoint(0.0, 0.0, 0.0)) - { - insertScalePivotOp(); - } - // Push new value to prim, but only if it's changing. - if (!sp.isEquivalent(m_scalePivotFromUsd)) - { - pushScalePivotToPrim(); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::setScalePivot %f %f %f\n", sp.x, sp.y, sp.z); + MStatus status = MPxTransformationMatrix::setScalePivot(sp, space, balance); + if (status) { + m_scalePivotTweak = MPxTransformationMatrix::scalePivotValue - m_scalePivotFromUsd; + } + if (pushToPrimAvailable()) { + // Do not insert a scale pivot op if the input prim has a generic pivot. + if (primHasScalePivot() || primHasPivot()) { + } else if (!pushPrimToMatrix() && sp != MPoint(0.0, 0.0, 0.0)) { + insertScalePivotOp(); + } + // Push new value to prim, but only if it's changing. + if (!sp.isEquivalent(m_scalePivotFromUsd)) { + pushScalePivotToPrim(); + } } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertScalePivotTranslationOp() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertScalePivotTranslationOp\n"); - // generate our translate op, and insert into the correct stack location - UsdGeomXformOp op = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("scalePivotTranslate")); - - auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScalePivotTranslate); - auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::insertScalePivotTranslationOp\n"); + // generate our translate op, and insert into the correct stack location + UsdGeomXformOp op + = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("scalePivotTranslate")); + + auto posInOps + = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kScalePivotTranslate); + auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); - m_xformops.insert(posInXfm, op); - m_orderedOps.insert(posInOps, kScalePivotTranslate); - m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); - m_flags |= kPrimHasScalePivotTranslate; + m_xformops.insert(posInXfm, op); + m_orderedOps.insert(posInOps, kScalePivotTranslate); + m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); + m_flags |= kPrimHasScalePivotTranslate; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::setScalePivotTranslation(const MVector& sp, MSpace::Space space) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setScalePivotTranslation %f %f %f\n", sp.x, sp.y, sp.z); - MStatus status = MPxTransformationMatrix::setScalePivotTranslation(sp, space); - if(status) - { - m_scalePivotTranslationTweak = MPxTransformationMatrix::scalePivotTranslationValue - m_scalePivotTranslationFromUsd; - } - if(pushToPrimAvailable()) - { - if(primHasScalePivotTranslate()) - { - } - else - if(!pushPrimToMatrix() && sp != MVector(0.0, 0.0, 0.0)) - { - insertScalePivotTranslationOp(); - } - // Push new value to prim, but only if it's changing. - if (!sp.isEquivalent(m_scalePivotTranslationFromUsd)) - { - pushScalePivotTranslateToPrim(); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::setScalePivotTranslation %f %f %f\n", sp.x, sp.y, sp.z); + MStatus status = MPxTransformationMatrix::setScalePivotTranslation(sp, space); + if (status) { + m_scalePivotTranslationTweak + = MPxTransformationMatrix::scalePivotTranslationValue - m_scalePivotTranslationFromUsd; + } + if (pushToPrimAvailable()) { + if (primHasScalePivotTranslate()) { + } else if (!pushPrimToMatrix() && sp != MVector(0.0, 0.0, 0.0)) { + insertScalePivotTranslationOp(); + } + // Push new value to prim, but only if it's changing. + if (!sp.isEquivalent(m_scalePivotTranslationFromUsd)) { + pushScalePivotTranslateToPrim(); + } } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertRotatePivotOp() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotatePivotOp\n"); - // generate our translate op, and insert into the correct stack location - UsdGeomXformOp op = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotatePivot")); - UsdGeomXformOp opinv = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotatePivot"), true); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotatePivotOp\n"); + // generate our translate op, and insert into the correct stack location + UsdGeomXformOp op + = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotatePivot")); + UsdGeomXformOp opinv + = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotatePivot"), true); - { - auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotatePivot); - auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); - m_xformops.insert(posInXfm, op); - m_orderedOps.insert(posInOps, kRotatePivot); - } - { - auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotatePivotInv); - auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); - m_xformops.insert(posInXfm, opinv); - m_orderedOps.insert(posInOps, kRotatePivotInv); - } - m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); - m_flags |= kPrimHasRotatePivot; + { + auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotatePivot); + auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); + m_xformops.insert(posInXfm, op); + m_orderedOps.insert(posInOps, kRotatePivot); + } + { + auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotatePivotInv); + auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); + m_xformops.insert(posInXfm, opinv); + m_orderedOps.insert(posInOps, kRotatePivotInv); + } + m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); + m_flags |= kPrimHasRotatePivot; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::setRotatePivot(const MPoint& pivot, MSpace::Space space, bool balance) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setRotatePivot %f %f %f\n", pivot.x, pivot.y, pivot.z); - MStatus status = MPxTransformationMatrix::setRotatePivot(pivot, space, balance); - if(status) - { - m_rotatePivotTweak = MPxTransformationMatrix::rotatePivotValue - m_rotatePivotFromUsd; - } - if(pushToPrimAvailable()) - { - // Do not insert a rotate pivot op if the input prim has a generic pivot. - if(primHasRotatePivot() || primHasPivot()) - { - } - else - if(!pushPrimToMatrix() && pivot != MPoint(0.0, 0.0, 0.0)) - { - insertRotatePivotOp(); - } - // Push new value to prim, but only if it's changing. - if (!pivot.isEquivalent(m_rotatePivotFromUsd)) - { - pushRotatePivotToPrim(); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::setRotatePivot %f %f %f\n", pivot.x, pivot.y, pivot.z); + MStatus status = MPxTransformationMatrix::setRotatePivot(pivot, space, balance); + if (status) { + m_rotatePivotTweak = MPxTransformationMatrix::rotatePivotValue - m_rotatePivotFromUsd; + } + if (pushToPrimAvailable()) { + // Do not insert a rotate pivot op if the input prim has a generic pivot. + if (primHasRotatePivot() || primHasPivot()) { + } else if (!pushPrimToMatrix() && pivot != MPoint(0.0, 0.0, 0.0)) { + insertRotatePivotOp(); + } + // Push new value to prim, but only if it's changing. + if (!pivot.isEquivalent(m_rotatePivotFromUsd)) { + pushRotatePivotToPrim(); + } } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertRotatePivotTranslationOp() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotatePivotTranslationOp\n"); - // generate our translate op, and insert into the correct stack location - UsdGeomXformOp op = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotatePivotTranslate")); - - auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotatePivotTranslate); - auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::insertRotatePivotTranslationOp\n"); + // generate our translate op, and insert into the correct stack location + UsdGeomXformOp op + = m_xform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotatePivotTranslate")); + + auto posInOps + = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotatePivotTranslate); + auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); - m_xformops.insert(posInXfm, op); - m_orderedOps.insert(posInOps, kRotatePivotTranslate); - m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); - m_flags |= kPrimHasRotatePivotTranslate; + m_xformops.insert(posInXfm, op); + m_orderedOps.insert(posInOps, kRotatePivotTranslate); + m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); + m_flags |= kPrimHasRotatePivotTranslate; } //---------------------------------------------------------------------------------------------------------------------- -MStatus TransformationMatrix::setRotatePivotTranslation(const MVector &vector, MSpace::Space space) +MStatus TransformationMatrix::setRotatePivotTranslation(const MVector& vector, MSpace::Space space) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setRotatePivotTranslation %f %f %f\n", vector.x, vector.y, vector.z); - MStatus status = MPxTransformationMatrix::setRotatePivotTranslation(vector, space); - if(status) - { - m_rotatePivotTranslationTweak = MPxTransformationMatrix::rotatePivotTranslationValue - m_rotatePivotTranslationFromUsd; - } - if(pushToPrimAvailable()) - { - if(primHasRotatePivotTranslate()) - { - } - else - if(!pushPrimToMatrix() && vector != MVector(0.0, 0.0, 0.0)) - { - insertRotatePivotTranslationOp(); - } - // Push new value to prim, but only if it's changing. - if (!vector.isEquivalent(m_rotatePivotTranslationFromUsd)) - { - pushRotatePivotTranslateToPrim(); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg( + "TransformationMatrix::setRotatePivotTranslation %f %f %f\n", + vector.x, + vector.y, + vector.z); + MStatus status = MPxTransformationMatrix::setRotatePivotTranslation(vector, space); + if (status) { + m_rotatePivotTranslationTweak = MPxTransformationMatrix::rotatePivotTranslationValue + - m_rotatePivotTranslationFromUsd; + } + if (pushToPrimAvailable()) { + if (primHasRotatePivotTranslate()) { + } else if (!pushPrimToMatrix() && vector != MVector(0.0, 0.0, 0.0)) { + insertRotatePivotTranslationOp(); + } + // Push new value to prim, but only if it's changing. + if (!vector.isEquivalent(m_rotatePivotTranslationFromUsd)) { + pushRotatePivotTranslateToPrim(); + } } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertRotateOp() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotateOp\n"); - // generate our translate op, and insert into the correct stack location - UsdGeomXformOp op; - - switch(rotationOrder()) - { - case MTransformationMatrix::kXYZ: - op = m_xform.AddRotateXYZOp(UsdGeomXformOp::PrecisionFloat); - break; - - case MTransformationMatrix::kXZY: - op = m_xform.AddRotateXZYOp(UsdGeomXformOp::PrecisionFloat); - break; - - case MTransformationMatrix::kYXZ: - op = m_xform.AddRotateYXZOp(UsdGeomXformOp::PrecisionFloat); - break; - - case MTransformationMatrix::kYZX: - op = m_xform.AddRotateYZXOp(UsdGeomXformOp::PrecisionFloat); - break; - - case MTransformationMatrix::kZXY: - op = m_xform.AddRotateZXYOp(UsdGeomXformOp::PrecisionFloat); - break; - - case MTransformationMatrix::kZYX: - op = m_xform.AddRotateZYXOp(UsdGeomXformOp::PrecisionFloat); - break; - - default: - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotateOp - got invalid rotation order; assuming XYZ"); - op = m_xform.AddRotateXYZOp(UsdGeomXformOp::PrecisionFloat); - break; - } - - auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotate); - auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); - - m_xformops.insert(posInXfm, op); - m_orderedOps.insert(posInOps, kRotate); - m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); - m_flags |= kPrimHasRotation; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotateOp\n"); + // generate our translate op, and insert into the correct stack location + UsdGeomXformOp op; + + switch (rotationOrder()) { + case MTransformationMatrix::kXYZ: + op = m_xform.AddRotateXYZOp(UsdGeomXformOp::PrecisionFloat); + break; + + case MTransformationMatrix::kXZY: + op = m_xform.AddRotateXZYOp(UsdGeomXformOp::PrecisionFloat); + break; + case MTransformationMatrix::kYXZ: + op = m_xform.AddRotateYXZOp(UsdGeomXformOp::PrecisionFloat); + break; + + case MTransformationMatrix::kYZX: + op = m_xform.AddRotateYZXOp(UsdGeomXformOp::PrecisionFloat); + break; + + case MTransformationMatrix::kZXY: + op = m_xform.AddRotateZXYOp(UsdGeomXformOp::PrecisionFloat); + break; + + case MTransformationMatrix::kZYX: + op = m_xform.AddRotateZYXOp(UsdGeomXformOp::PrecisionFloat); + break; + + default: + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::insertRotateOp - got invalid rotation order; assuming XYZ"); + op = m_xform.AddRotateXYZOp(UsdGeomXformOp::PrecisionFloat); + break; + } + + auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotate); + auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); + + m_xformops.insert(posInXfm, op); + m_orderedOps.insert(posInOps, kRotate); + m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); + m_flags |= kPrimHasRotation; } //---------------------------------------------------------------------------------------------------------------------- -MStatus TransformationMatrix::rotateTo(const MQuaternion &q, MSpace::Space space) +MStatus TransformationMatrix::rotateTo(const MQuaternion& q, MSpace::Space space) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::rotateTo %f %f %f %f\n", q.x, q.y, q.z, q.w); - if(isRotateLocked()) - return MPxTransformationMatrix::rotateTo(q, space);; - MStatus status = MPxTransformationMatrix::rotateTo(q, space); - if(status) - { - m_rotationTweak.x = MPxTransformationMatrix::rotationValue.x - m_rotationFromUsd.x; - m_rotationTweak.y = MPxTransformationMatrix::rotationValue.y - m_rotationFromUsd.y; - m_rotationTweak.z = MPxTransformationMatrix::rotationValue.z - m_rotationFromUsd.z; - } - if(pushToPrimAvailable()) - { - if(primHasRotation()) - { - } - else - if(!pushPrimToMatrix() && q != MQuaternion(0.0, 0.0, 0.0, 1.0)) - { - insertRotateOp(); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::rotateTo %f %f %f %f\n", q.x, q.y, q.z, q.w); + if (isRotateLocked()) + return MPxTransformationMatrix::rotateTo(q, space); + ; + MStatus status = MPxTransformationMatrix::rotateTo(q, space); + if (status) { + m_rotationTweak.x = MPxTransformationMatrix::rotationValue.x - m_rotationFromUsd.x; + m_rotationTweak.y = MPxTransformationMatrix::rotationValue.y - m_rotationFromUsd.y; + m_rotationTweak.z = MPxTransformationMatrix::rotationValue.z - m_rotationFromUsd.z; + } + if (pushToPrimAvailable()) { + if (primHasRotation()) { + } else if (!pushPrimToMatrix() && q != MQuaternion(0.0, 0.0, 0.0, 1.0)) { + insertRotateOp(); + } + if (m_enableUsdWriteback) { + // Push new value to prim, but only if it's changing. + if (!MPxTransformationMatrix::rotationValue.isEquivalent(m_rotationFromUsd)) { + pushRotateQuatToPrim(); + } + } } - if(m_enableUsdWriteback) - { - // Push new value to prim, but only if it's changing. - if (!MPxTransformationMatrix::rotationValue.isEquivalent(m_rotationFromUsd)) - { - pushRotateQuatToPrim(); - } - } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- -MStatus TransformationMatrix::rotateTo(const MEulerRotation &e, MSpace::Space space) +MStatus TransformationMatrix::rotateTo(const MEulerRotation& e, MSpace::Space space) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::rotateTo %f %f %f\n", e.x, e.y, e.z); - if(isRotateLocked()) - return MPxTransformationMatrix::rotateTo(e, space);; - MStatus status = MPxTransformationMatrix::rotateTo(e, space); - if(status) - { - m_rotationTweak.x = MPxTransformationMatrix::rotationValue.x - m_rotationFromUsd.x; - m_rotationTweak.y = MPxTransformationMatrix::rotationValue.y - m_rotationFromUsd.y; - m_rotationTweak.z = MPxTransformationMatrix::rotationValue.z - m_rotationFromUsd.z; - } - if(pushToPrimAvailable()) - { - if(primHasRotation()) - { - } - else - if(!pushPrimToMatrix() && e != MEulerRotation(0.0, 0.0, 0.0, MEulerRotation::kXYZ)) - { - insertRotateOp(); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::rotateTo %f %f %f\n", e.x, e.y, e.z); + if (isRotateLocked()) + return MPxTransformationMatrix::rotateTo(e, space); + ; + MStatus status = MPxTransformationMatrix::rotateTo(e, space); + if (status) { + m_rotationTweak.x = MPxTransformationMatrix::rotationValue.x - m_rotationFromUsd.x; + m_rotationTweak.y = MPxTransformationMatrix::rotationValue.y - m_rotationFromUsd.y; + m_rotationTweak.z = MPxTransformationMatrix::rotationValue.z - m_rotationFromUsd.z; + } + if (pushToPrimAvailable()) { + if (primHasRotation()) { + } else if ( + !pushPrimToMatrix() && e != MEulerRotation(0.0, 0.0, 0.0, MEulerRotation::kXYZ)) { + insertRotateOp(); + } + if (m_enableUsdWriteback) { + // Push new value to prim, but only if it's changing. + if (!e.isEquivalent(m_rotationFromUsd)) { + pushRotateToPrim(); + } + } } - if(m_enableUsdWriteback) - { - // Push new value to prim, but only if it's changing. - if (!e.isEquivalent(m_rotationFromUsd)) - { - pushRotateToPrim(); - } - } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus TransformationMatrix::setRotationOrder(MTransformationMatrix::RotationOrder, bool) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setRotationOrder\n"); - // do not allow people to change the rotation order here. - // It's too hard for my feeble brain to figure out how to remap that to the USD data. - return MS::kFailure; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setRotationOrder\n"); + // do not allow people to change the rotation order here. + // It's too hard for my feeble brain to figure out how to remap that to the USD data. + return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::insertRotateAxesOp() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotateAxesOp\n"); - // generate our translate op, and insert into the correct stack location - UsdGeomXformOp op = m_xform.AddRotateXYZOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotateAxis")); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::insertRotateAxesOp\n"); + // generate our translate op, and insert into the correct stack location + UsdGeomXformOp op + = m_xform.AddRotateXYZOp(UsdGeomXformOp::PrecisionFloat, TfToken("rotateAxis")); - auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotateAxis); - auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); + auto posInOps = std::lower_bound(m_orderedOps.begin(), m_orderedOps.end(), kRotateAxis); + auto posInXfm = m_xformops.begin() + (posInOps - m_orderedOps.begin()); - m_xformops.insert(posInXfm, op); - m_orderedOps.insert(posInOps, kRotateAxis); - m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); - m_flags |= kPrimHasRotateAxes; + m_xformops.insert(posInXfm, op); + m_orderedOps.insert(posInOps, kRotateAxis); + m_xform.SetXformOpOrder(m_xformops, (m_flags & kInheritsTransform) == 0); + m_flags |= kPrimHasRotateAxes; } //---------------------------------------------------------------------------------------------------------------------- -MStatus TransformationMatrix::setRotateOrientation(const MQuaternion &q, MSpace::Space space, bool balance) +MStatus +TransformationMatrix::setRotateOrientation(const MQuaternion& q, MSpace::Space space, bool balance) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setRotateOrientation %f %f %f %f\n", q.x, q.y, q.z, q.w); - MStatus status = MPxTransformationMatrix::setRotateOrientation(q, space, balance); - if(status) - { - m_rotateOrientationFromUsd = MPxTransformationMatrix::rotateOrientationValue * m_rotateOrientationTweak.inverse(); - } - if(pushToPrimAvailable()) - { - if(primHasRotateAxes()) - { - } - else - if(!pushPrimToMatrix() && q != MQuaternion(0.0, 0.0, 0.0, 1.0)) - { - insertRotateAxesOp(); - } - if(m_enableUsdWriteback) - { - pushRotateAxisToPrim(); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::setRotateOrientation %f %f %f %f\n", q.x, q.y, q.z, q.w); + MStatus status = MPxTransformationMatrix::setRotateOrientation(q, space, balance); + if (status) { + m_rotateOrientationFromUsd + = MPxTransformationMatrix::rotateOrientationValue * m_rotateOrientationTweak.inverse(); + } + if (pushToPrimAvailable()) { + if (primHasRotateAxes()) { + } else if (!pushPrimToMatrix() && q != MQuaternion(0.0, 0.0, 0.0, 1.0)) { + insertRotateAxesOp(); + } + if (m_enableUsdWriteback) { + pushRotateAxisToPrim(); + } } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- -MStatus TransformationMatrix::setRotateOrientation(const MEulerRotation& euler, MSpace::Space space, bool balance) +MStatus TransformationMatrix::setRotateOrientation( + const MEulerRotation& euler, + MSpace::Space space, + bool balance) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::setRotateOrientation %f %f %f\n", euler.x, euler.y, euler.z); - MStatus status = MPxTransformationMatrix::setRotateOrientation(euler, space, balance); - if(status) - { - m_rotateOrientationFromUsd = MPxTransformationMatrix::rotateOrientationValue * m_rotateOrientationTweak.inverse(); - } - if(pushToPrimAvailable()) - { - if(primHasRotateAxes()) - { - } - else - if(!pushPrimToMatrix() && euler != MEulerRotation(0.0, 0.0, 0.0, MEulerRotation::kXYZ)) - { - insertRotateAxesOp(); - } - if(m_enableUsdWriteback) - { - pushRotateAxisToPrim(); + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::setRotateOrientation %f %f %f\n", euler.x, euler.y, euler.z); + MStatus status = MPxTransformationMatrix::setRotateOrientation(euler, space, balance); + if (status) { + m_rotateOrientationFromUsd + = MPxTransformationMatrix::rotateOrientationValue * m_rotateOrientationTweak.inverse(); + } + if (pushToPrimAvailable()) { + if (primHasRotateAxes()) { + } else if ( + !pushPrimToMatrix() && euler != MEulerRotation(0.0, 0.0, 0.0, MEulerRotation::kXYZ)) { + insertRotateAxesOp(); + } + if (m_enableUsdWriteback) { + pushRotateAxisToPrim(); + } } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::notifyProxyShapeOfRedraw() { - // Anytime we update the xform, we need to tell the proxy shape that it - // needs to redraw itself - MObject tn(m_transformNode.object()); - if (!tn.isNull()) - { - MStatus status; - MFnDependencyNode mfn(tn, &status); - if (status && mfn.typeId() == Transform::kTypeId) - { - auto xform = static_cast(mfn.userNode()); - MObject proxyObj = xform->getProxyShape(); - if (!proxyObj.isNull()) - { - MFnDependencyNode proxyMfn(proxyObj); - if (proxyMfn.typeId() == ProxyShape::kTypeId) - { - GfMatrix4d oldMatrix; - bool oldResetsStack; - m_xform.GetLocalTransformation(&oldMatrix, &oldResetsStack, getTimeCode()); - - // We check that the matrix actually HAS changed, as this function will be - // called when, ie, pushToPrim is toggled, which often happens on node - // creation, when nothing has actually changed - GfMatrix4d newMatrix; - bool newResetsStack; - m_xform.GetLocalTransformation(&newMatrix, &newResetsStack, getTimeCode()); - if (newMatrix != oldMatrix || newResetsStack != oldResetsStack) - { - MHWRender::MRenderer::setGeometryDrawDirty(proxyObj); - } - } - } - } - } + // Anytime we update the xform, we need to tell the proxy shape that it + // needs to redraw itself + MObject tn(m_transformNode.object()); + if (!tn.isNull()) { + MStatus status; + MFnDependencyNode mfn(tn, &status); + if (status && mfn.typeId() == Transform::kTypeId) { + auto xform = static_cast(mfn.userNode()); + MObject proxyObj = xform->getProxyShape(); + if (!proxyObj.isNull()) { + MFnDependencyNode proxyMfn(proxyObj); + if (proxyMfn.typeId() == ProxyShape::kTypeId) { + GfMatrix4d oldMatrix; + bool oldResetsStack; + m_xform.GetLocalTransformation(&oldMatrix, &oldResetsStack, getTimeCode()); + + // We check that the matrix actually HAS changed, as this function will be + // called when, ie, pushToPrim is toggled, which often happens on node + // creation, when nothing has actually changed + GfMatrix4d newMatrix; + bool newResetsStack; + m_xform.GetLocalTransformation(&newMatrix, &newResetsStack, getTimeCode()); + if (newMatrix != oldMatrix || newResetsStack != oldResetsStack) { + MHWRender::MRenderer::setGeometryDrawDirty(proxyObj); + } + } + } + } + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushTranslateToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushTranslateToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kTranslate) - { - UsdGeomXformOp& op = *it; - MVector tempTranslation; - internal_readVector(tempTranslation, op); - // only write back if data has changed significantly - if(!tempTranslation.isEquivalent(MPxTransformationMatrix::translationValue)) - { - internal_pushVector(MPxTransformationMatrix::translationValue, op); - m_translationFromUsd = MPxTransformationMatrix::translationValue; - m_translationTweak = MVector(0, 0, 0); - } - return; - } - } - if(m_enableUsdWriteback) - { - pushTransformToPrim(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushTranslateToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kTranslate) { + UsdGeomXformOp& op = *it; + MVector tempTranslation; + internal_readVector(tempTranslation, op); + // only write back if data has changed significantly + if (!tempTranslation.isEquivalent(MPxTransformationMatrix::translationValue)) { + internal_pushVector(MPxTransformationMatrix::translationValue, op); + m_translationFromUsd = MPxTransformationMatrix::translationValue; + m_translationTweak = MVector(0, 0, 0); + } + return; + } + } + if (m_enableUsdWriteback) { + pushTransformToPrim(); + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushPivotToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushPivotToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kPivot) - { - UsdGeomXformOp& op = *it; - MPoint tempPivot; - internal_readPoint(tempPivot, op); - - // only write back if data has changed significantly - if(!tempPivot.isEquivalent(MPxTransformationMatrix::rotatePivotValue)) - { - internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); - m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; - m_rotatePivotTweak = MPoint(0, 0, 0); - m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; - m_scalePivotTweak = MVector(0, 0, 0); - } - return; - } - } - if(m_enableUsdWriteback) - { - pushTransformToPrim(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushPivotToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kPivot) { + UsdGeomXformOp& op = *it; + MPoint tempPivot; + internal_readPoint(tempPivot, op); + + // only write back if data has changed significantly + if (!tempPivot.isEquivalent(MPxTransformationMatrix::rotatePivotValue)) { + internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); + m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; + m_rotatePivotTweak = MPoint(0, 0, 0); + m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; + m_scalePivotTweak = MVector(0, 0, 0); + } + return; + } + } + if (m_enableUsdWriteback) { + pushTransformToPrim(); + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushRotatePivotToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotatePivotToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kRotatePivot) - { - UsdGeomXformOp& op = *it; - MPoint tempPivot; - internal_readPoint(tempPivot, op); - // only write back if data has changed significantly - if(!tempPivot.isEquivalent(MPxTransformationMatrix::rotatePivotValue)) - { - internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); - m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; - m_rotatePivotTweak = MVector(0, 0, 0); - } - return; - } - } - if(m_enableUsdWriteback) - { - pushTransformToPrim(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotatePivotToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kRotatePivot) { + UsdGeomXformOp& op = *it; + MPoint tempPivot; + internal_readPoint(tempPivot, op); + // only write back if data has changed significantly + if (!tempPivot.isEquivalent(MPxTransformationMatrix::rotatePivotValue)) { + internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); + m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; + m_rotatePivotTweak = MVector(0, 0, 0); + } + return; + } + } + if (m_enableUsdWriteback) { + pushTransformToPrim(); + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushRotatePivotTranslateToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotatePivotTranslateToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kRotatePivotTranslate) - { - UsdGeomXformOp& op = *it; - MVector tempPivotTranslation; - internal_readVector(tempPivotTranslation, op); - // only write back if data has changed significantly - if(!tempPivotTranslation.isEquivalent(MPxTransformationMatrix::rotatePivotTranslationValue)) - { - internal_pushPoint(MPxTransformationMatrix::rotatePivotTranslationValue, op); - m_rotatePivotTranslationFromUsd = MPxTransformationMatrix::rotatePivotTranslationValue; - m_rotatePivotTranslationTweak = MVector(0, 0, 0); - } - return; - } - } - if(m_enableUsdWriteback) - { - pushTransformToPrim(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::pushRotatePivotTranslateToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kRotatePivotTranslate) { + UsdGeomXformOp& op = *it; + MVector tempPivotTranslation; + internal_readVector(tempPivotTranslation, op); + // only write back if data has changed significantly + if (!tempPivotTranslation.isEquivalent( + MPxTransformationMatrix::rotatePivotTranslationValue)) { + internal_pushPoint(MPxTransformationMatrix::rotatePivotTranslationValue, op); + m_rotatePivotTranslationFromUsd + = MPxTransformationMatrix::rotatePivotTranslationValue; + m_rotatePivotTranslationTweak = MVector(0, 0, 0); + } + return; + } + } + if (m_enableUsdWriteback) { + pushTransformToPrim(); + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushRotateToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotateToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kRotate) - { - UsdGeomXformOp& op = *it; - MEulerRotation tempRotate; - internal_readRotation(tempRotate, op); - - // only write back if data has changed significantly - if(!tempRotate.isEquivalent(MPxTransformationMatrix::rotationValue)) - { - internal_pushRotation(MPxTransformationMatrix::rotationValue, op); - m_rotationFromUsd = MPxTransformationMatrix::rotationValue; - m_rotationTweak = MEulerRotation(0, 0, 0); - } - return; - } - } - if(m_enableUsdWriteback) - { - pushTransformToPrim(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotateToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kRotate) { + UsdGeomXformOp& op = *it; + MEulerRotation tempRotate; + internal_readRotation(tempRotate, op); + + // only write back if data has changed significantly + if (!tempRotate.isEquivalent(MPxTransformationMatrix::rotationValue)) { + internal_pushRotation(MPxTransformationMatrix::rotationValue, op); + m_rotationFromUsd = MPxTransformationMatrix::rotationValue; + m_rotationTweak = MEulerRotation(0, 0, 0); + } + return; + } + } + if (m_enableUsdWriteback) { + pushTransformToPrim(); + } } - //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushRotateQuatToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotateQuatToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kRotate) - { - UsdGeomXformOp& op = *it; - MEulerRotation tempRotate; - internal_readRotation(tempRotate, op); - - // only write back if data has changed significantly - if(!tempRotate.asQuaternion().isEquivalent(MPxTransformationMatrix::rotationValue.asQuaternion())) - { - internal_pushRotation(MPxTransformationMatrix::rotationValue, op); - m_rotationFromUsd = MPxTransformationMatrix::rotationValue; - m_rotationTweak = MEulerRotation(0, 0, 0); - } - return; - } - } - if(m_enableUsdWriteback) - { - pushTransformToPrim(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotateQuatToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kRotate) { + UsdGeomXformOp& op = *it; + MEulerRotation tempRotate; + internal_readRotation(tempRotate, op); + + // only write back if data has changed significantly + if (!tempRotate.asQuaternion().isEquivalent( + MPxTransformationMatrix::rotationValue.asQuaternion())) { + internal_pushRotation(MPxTransformationMatrix::rotationValue, op); + m_rotationFromUsd = MPxTransformationMatrix::rotationValue; + m_rotationTweak = MEulerRotation(0, 0, 0); + } + return; + } + } + if (m_enableUsdWriteback) { + pushTransformToPrim(); + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushRotateAxisToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotateAxisToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kRotateAxis) - { - UsdGeomXformOp& op = *it; - MVector tempRotateAxis; - internal_readVector(tempRotateAxis, op); - tempRotateAxis *= (M_PI / 180.0); - - MEulerRotation temp(tempRotateAxis.x, tempRotateAxis.y, tempRotateAxis.z); - - // only write back if data has changed significantly - if(!(temp.asQuaternion()).isEquivalent(m_rotateOrientationFromUsd)) - { - const double radToDeg = 180.0 / M_PI; - MEulerRotation e = m_rotateOrientationFromUsd.asEulerRotation(); - MVector vec(e.x * radToDeg, e.y * radToDeg, e.z * radToDeg); - internal_pushVector(vec, op); - } - return; - } - } - if(m_enableUsdWriteback) - { - pushTransformToPrim(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushRotateAxisToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kRotateAxis) { + UsdGeomXformOp& op = *it; + MVector tempRotateAxis; + internal_readVector(tempRotateAxis, op); + tempRotateAxis *= (M_PI / 180.0); + + MEulerRotation temp(tempRotateAxis.x, tempRotateAxis.y, tempRotateAxis.z); + + // only write back if data has changed significantly + if (!(temp.asQuaternion()).isEquivalent(m_rotateOrientationFromUsd)) { + const double radToDeg = 180.0 / M_PI; + MEulerRotation e = m_rotateOrientationFromUsd.asEulerRotation(); + MVector vec(e.x * radToDeg, e.y * radToDeg, e.z * radToDeg); + internal_pushVector(vec, op); + } + return; + } + } + if (m_enableUsdWriteback) { + pushTransformToPrim(); + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushScalePivotTranslateToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushScalePivotTranslateToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kScalePivotTranslate) - { - UsdGeomXformOp& op = *it; - MVector tempPivotTranslation; - internal_readVector(tempPivotTranslation, op); - // only write back if data has changed significantly - if(!tempPivotTranslation.isEquivalent(MPxTransformationMatrix::scalePivotTranslationValue)) - { - internal_pushVector(MPxTransformationMatrix::scalePivotTranslationValue, op); - m_scalePivotTranslationFromUsd = MPxTransformationMatrix::scalePivotTranslationValue; - m_scalePivotTranslationTweak = MVector(0, 0, 0); - } - return; - } - } - if(m_enableUsdWriteback) - { - pushTransformToPrim(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX) + .Msg("TransformationMatrix::pushScalePivotTranslateToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kScalePivotTranslate) { + UsdGeomXformOp& op = *it; + MVector tempPivotTranslation; + internal_readVector(tempPivotTranslation, op); + // only write back if data has changed significantly + if (!tempPivotTranslation.isEquivalent( + MPxTransformationMatrix::scalePivotTranslationValue)) { + internal_pushVector(MPxTransformationMatrix::scalePivotTranslationValue, op); + m_scalePivotTranslationFromUsd + = MPxTransformationMatrix::scalePivotTranslationValue; + m_scalePivotTranslationTweak = MVector(0, 0, 0); + } + return; + } + } + if (m_enableUsdWriteback) { + pushTransformToPrim(); + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushScalePivotToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushScalePivotToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kScalePivot) - { - UsdGeomXformOp& op = *it; - MPoint tempPivot; - internal_readPoint(tempPivot, op); - // only write back if data has changed significantly - if(!tempPivot.isEquivalent(MPxTransformationMatrix::scalePivotValue)) - { - internal_pushPoint(MPxTransformationMatrix::scalePivotValue, op); - m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; - m_scalePivotTweak = MPoint(0, 0, 0); - } - return; - } - } - if(m_enableUsdWriteback) - { - pushTransformToPrim(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushScalePivotToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kScalePivot) { + UsdGeomXformOp& op = *it; + MPoint tempPivot; + internal_readPoint(tempPivot, op); + // only write back if data has changed significantly + if (!tempPivot.isEquivalent(MPxTransformationMatrix::scalePivotValue)) { + internal_pushPoint(MPxTransformationMatrix::scalePivotValue, op); + m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; + m_scalePivotTweak = MPoint(0, 0, 0); + } + return; + } + } + if (m_enableUsdWriteback) { + pushTransformToPrim(); + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushScaleToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushScaleToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kScale) - { - UsdGeomXformOp& op = *it; - MVector tempScale(1.0, 1.0, 1.0); - internal_readVector(tempScale, op); - // only write back if data has changed significantly - if(!tempScale.isEquivalent(MPxTransformationMatrix::scaleValue)) - { - internal_pushVector(MPxTransformationMatrix::scaleValue, op); - m_scaleFromUsd = MPxTransformationMatrix::scaleValue; - m_scaleTweak = MVector(0, 0, 0); - } - return; - } - } - if(m_enableUsdWriteback) - { - pushTransformToPrim(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushScaleToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kScale) { + UsdGeomXformOp& op = *it; + MVector tempScale(1.0, 1.0, 1.0); + internal_readVector(tempScale, op); + // only write back if data has changed significantly + if (!tempScale.isEquivalent(MPxTransformationMatrix::scaleValue)) { + internal_pushVector(MPxTransformationMatrix::scaleValue, op); + m_scaleFromUsd = MPxTransformationMatrix::scaleValue; + m_scaleTweak = MVector(0, 0, 0); + } + return; + } + } + if (m_enableUsdWriteback) { + pushTransformToPrim(); + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushShearToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushShearToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kShear) - { - UsdGeomXformOp& op = *it; - internal_pushShear(MPxTransformationMatrix::shearValue, op); - m_shearFromUsd = MPxTransformationMatrix::shearValue; - m_shearTweak = MVector(0, 0, 0); - return; - } - } - if(m_enableUsdWriteback) - { - pushTransformToPrim(); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushShearToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kShear) { + UsdGeomXformOp& op = *it; + internal_pushShear(MPxTransformationMatrix::shearValue, op); + m_shearFromUsd = MPxTransformationMatrix::shearValue; + m_shearTweak = MVector(0, 0, 0); + return; + } + } + if (m_enableUsdWriteback) { + pushTransformToPrim(); + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushTransformToPrim() { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushTransformToPrim\n"); - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - if(*opIt == kTransform) - { - UsdGeomXformOp& op = *it; - if(pushPrimToMatrix()) - { - internal_pushMatrix(asMatrix(), op); - } - return; - } - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushTransformToPrim\n"); + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + if (*opIt == kTransform) { + UsdGeomXformOp& op = *it; + if (pushPrimToMatrix()) { + internal_pushMatrix(asMatrix(), op); + } + return; + } + } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::pushToPrim() { - // if not yet intiaialised, do not execute this code! (It will crash!). - if(!m_prim) - return; - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushToPrim\n"); - - GfMatrix4d oldMatrix; - bool oldResetsStack; - m_xform.GetLocalTransformation(&oldMatrix, &oldResetsStack, getTimeCode()); - - auto opIt = m_orderedOps.begin(); - for(std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); it != e; ++it, ++opIt) - { - UsdGeomXformOp& op = *it; - switch(*opIt) - { - case kTranslate: - { - internal_pushVector(MPxTransformationMatrix::translationValue, op); - m_translationFromUsd = MPxTransformationMatrix::translationValue; - m_translationTweak = MVector(0, 0, 0); - } - break; - - case kPivot: - { - // is this a bug? - internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); - m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; - m_rotatePivotTweak = MPoint(0, 0, 0); - m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; - m_scalePivotTweak = MVector(0, 0, 0); - } - break; - - case kRotatePivotTranslate: - { - internal_pushPoint(MPxTransformationMatrix::rotatePivotTranslationValue, op); - m_rotatePivotTranslationFromUsd = MPxTransformationMatrix::rotatePivotTranslationValue; - m_rotatePivotTranslationTweak = MVector(0, 0, 0); - } - break; - - case kRotatePivot: - { - internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); - m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; - m_rotatePivotTweak = MPoint(0, 0, 0); - } - break; - - case kRotate: - { - internal_pushRotation(MPxTransformationMatrix::rotationValue, op); - m_rotationFromUsd = MPxTransformationMatrix::rotationValue; - m_rotationTweak = MEulerRotation(0, 0, 0); - } - break; - - case kRotateAxis: - { - const double radToDeg = 180.0 / M_PI; - MEulerRotation e = m_rotateOrientationFromUsd.asEulerRotation(); - MVector vec(e.x * radToDeg, e.y * radToDeg, e.z * radToDeg); - internal_pushVector(vec, op); - } - break; - - case kRotatePivotInv: - { - } - break; - - case kScalePivotTranslate: - { - internal_pushVector(MPxTransformationMatrix::scalePivotTranslationValue, op); - m_scalePivotTranslationFromUsd = MPxTransformationMatrix::scalePivotTranslationValue; - m_scalePivotTranslationTweak = MVector(0, 0, 0); - } - break; - - case kScalePivot: - { - internal_pushPoint(MPxTransformationMatrix::scalePivotValue, op); - m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; - m_scalePivotTweak = MPoint(0, 0, 0); - } - break; - - case kShear: - { - internal_pushShear(MPxTransformationMatrix::shearValue, op); - m_shearFromUsd = MPxTransformationMatrix::shearValue; - m_shearTweak = MVector(0, 0, 0); - } - break; - - case kScale: - { - internal_pushVector(MPxTransformationMatrix::scaleValue, op); - m_scaleFromUsd = MPxTransformationMatrix::scaleValue; - m_scaleTweak = MVector(0, 0, 0); - } - break; - - case kScalePivotInv: - { - } - break; - - case kPivotInv: - { - } - break; - - case kTransform: - { - if(pushPrimToMatrix()) - { - internal_pushMatrix(asMatrix(), op); - } - } - break; + // if not yet intiaialised, do not execute this code! (It will crash!). + if (!m_prim) + return; + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::pushToPrim\n"); - case kUnknownOp: - { - } - break; + GfMatrix4d oldMatrix; + bool oldResetsStack; + m_xform.GetLocalTransformation(&oldMatrix, &oldResetsStack, getTimeCode()); + + auto opIt = m_orderedOps.begin(); + for (std::vector::iterator it = m_xformops.begin(), e = m_xformops.end(); + it != e; + ++it, ++opIt) { + UsdGeomXformOp& op = *it; + switch (*opIt) { + case kTranslate: { + internal_pushVector(MPxTransformationMatrix::translationValue, op); + m_translationFromUsd = MPxTransformationMatrix::translationValue; + m_translationTweak = MVector(0, 0, 0); + } break; + + case kPivot: { + // is this a bug? + internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); + m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; + m_rotatePivotTweak = MPoint(0, 0, 0); + m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; + m_scalePivotTweak = MVector(0, 0, 0); + } break; + + case kRotatePivotTranslate: { + internal_pushPoint(MPxTransformationMatrix::rotatePivotTranslationValue, op); + m_rotatePivotTranslationFromUsd = MPxTransformationMatrix::rotatePivotTranslationValue; + m_rotatePivotTranslationTweak = MVector(0, 0, 0); + } break; + + case kRotatePivot: { + internal_pushPoint(MPxTransformationMatrix::rotatePivotValue, op); + m_rotatePivotFromUsd = MPxTransformationMatrix::rotatePivotValue; + m_rotatePivotTweak = MPoint(0, 0, 0); + } break; + + case kRotate: { + internal_pushRotation(MPxTransformationMatrix::rotationValue, op); + m_rotationFromUsd = MPxTransformationMatrix::rotationValue; + m_rotationTweak = MEulerRotation(0, 0, 0); + } break; + + case kRotateAxis: { + const double radToDeg = 180.0 / M_PI; + MEulerRotation e = m_rotateOrientationFromUsd.asEulerRotation(); + MVector vec(e.x * radToDeg, e.y * radToDeg, e.z * radToDeg); + internal_pushVector(vec, op); + } break; + + case kRotatePivotInv: { + } break; + + case kScalePivotTranslate: { + internal_pushVector(MPxTransformationMatrix::scalePivotTranslationValue, op); + m_scalePivotTranslationFromUsd = MPxTransformationMatrix::scalePivotTranslationValue; + m_scalePivotTranslationTweak = MVector(0, 0, 0); + } break; + + case kScalePivot: { + internal_pushPoint(MPxTransformationMatrix::scalePivotValue, op); + m_scalePivotFromUsd = MPxTransformationMatrix::scalePivotValue; + m_scalePivotTweak = MPoint(0, 0, 0); + } break; + + case kShear: { + internal_pushShear(MPxTransformationMatrix::shearValue, op); + m_shearFromUsd = MPxTransformationMatrix::shearValue; + m_shearTweak = MVector(0, 0, 0); + } break; + + case kScale: { + internal_pushVector(MPxTransformationMatrix::scaleValue, op); + m_scaleFromUsd = MPxTransformationMatrix::scaleValue; + m_scaleTweak = MVector(0, 0, 0); + } break; + + case kScalePivotInv: { + } break; + + case kPivotInv: { + } break; + + case kTransform: { + if (pushPrimToMatrix()) { + internal_pushMatrix(asMatrix(), op); + } + } break; + + case kUnknownOp: { + } break; + } } - } - notifyProxyShapeOfRedraw(); + notifyProxyShapeOfRedraw(); } //---------------------------------------------------------------------------------------------------------------------- MMatrix TransformationMatrix::asMatrix() const { - MMatrix m = MPxTransformationMatrix::asMatrix(); - - const double x = m_localTranslateOffset.x; - const double y = m_localTranslateOffset.y; - const double z = m_localTranslateOffset.z; - - m[3][0] += m[0][0] * x; - m[3][1] += m[0][1] * x; - m[3][2] += m[0][2] * x; - m[3][0] += m[1][0] * y; - m[3][1] += m[1][1] * y; - m[3][2] += m[1][2] * y; - m[3][0] += m[2][0] * z; - m[3][1] += m[2][1] * z; - m[3][2] += m[2][2] * z; - - // Let Maya know what the matrix should be - return m; + MMatrix m = MPxTransformationMatrix::asMatrix(); + + const double x = m_localTranslateOffset.x; + const double y = m_localTranslateOffset.y; + const double z = m_localTranslateOffset.z; + + m[3][0] += m[0][0] * x; + m[3][1] += m[0][1] * x; + m[3][2] += m[0][2] * x; + m[3][0] += m[1][0] * y; + m[3][1] += m[1][1] * y; + m[3][2] += m[1][2] * y; + m[3][0] += m[2][0] * z; + m[3][1] += m[2][1] * z; + m[3][2] += m[2][2] * z; + + // Let Maya know what the matrix should be + return m; } //---------------------------------------------------------------------------------------------------------------------- MMatrix TransformationMatrix::asMatrix(double percent) const { - MMatrix m = MPxTransformationMatrix::asMatrix(percent); - - const double x = m_localTranslateOffset.x * percent; - const double y = m_localTranslateOffset.y * percent; - const double z = m_localTranslateOffset.z * percent; - - m[3][0] += m[0][0] * x; - m[3][1] += m[0][1] * x; - m[3][2] += m[0][2] * x; - m[3][0] += m[1][0] * y; - m[3][1] += m[1][1] * y; - m[3][2] += m[1][2] * y; - m[3][0] += m[2][0] * z; - m[3][1] += m[2][1] * z; - m[3][2] += m[2][2] * z; - - return m; + MMatrix m = MPxTransformationMatrix::asMatrix(percent); + + const double x = m_localTranslateOffset.x * percent; + const double y = m_localTranslateOffset.y * percent; + const double z = m_localTranslateOffset.z * percent; + + m[3][0] += m[0][0] * x; + m[3][1] += m[0][1] * x; + m[3][2] += m[0][2] * x; + m[3][0] += m[1][0] * y; + m[3][1] += m[1][1] * y; + m[3][2] += m[1][2] * y; + m[3][0] += m[2][0] * z; + m[3][1] += m[2][1] * z; + m[3][2] += m[2][2] * z; + + return m; } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::enableReadAnimatedValues(bool enabled) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::enableReadAnimatedValues\n"); - if(enabled) m_flags |= kReadAnimatedValues; - else m_flags &= ~kReadAnimatedValues; - - // if not yet intiaialised, do not execute this code! (It will crash!). - if(!m_prim) - return; - - // if we are enabling push to prim, we need to see if anything has changed on the transform since the last time - // the values were synced. I'm assuming that if a given transform attribute is not the same as the default, or - // the prim already has a transform op for that attribute, then just call a method to make a minor adjustment - // of nothing. This will call my code that will magically construct the transform ops in the right order. - if(enabled) - { - const MVector nullVec(0, 0, 0); - const MVector oneVec(1.0, 1.0, 1.0); - const MPoint nullPoint(0, 0, 0); - const MQuaternion nullQuat(0, 0, 0, 1.0); - - if(!pushPrimToMatrix()) - { - if(primHasTranslation() || translation() != nullVec) - translateBy(nullVec); - - if(primHasScale() || scale() != oneVec) - scaleBy(oneVec); - - if(primHasShear() || shear() != nullVec) - shearBy(nullVec); - - if(primHasScalePivot() || scalePivot() != nullPoint) - setScalePivot(scalePivot(), MSpace::kTransform, false); - - if(primHasScalePivotTranslate() || scalePivotTranslation() != nullVec) - setScalePivotTranslation(scalePivotTranslation(), MSpace::kTransform); - - if(primHasRotatePivot() || rotatePivot() != nullPoint) - setRotatePivot(rotatePivot(), MSpace::kTransform, false); - - if(primHasRotatePivotTranslate() || rotatePivotTranslation() != nullVec) - setRotatePivotTranslation(rotatePivotTranslation(), MSpace::kTransform); - - if(primHasRotation() || rotation() != nullQuat) - rotateBy(nullQuat); - - if(primHasRotateAxes() || rotateOrientation() != nullQuat) - setRotateOrientation(rotateOrientation(), MSpace::kTransform, false); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::enableReadAnimatedValues\n"); + if (enabled) + m_flags |= kReadAnimatedValues; else - if(primHasTransform()) - { - auto transformIt = std::find(m_orderedOps.begin(), m_orderedOps.end(), kTransform); - if (transformIt != m_orderedOps.end() ) - { - internal_pushMatrix(asMatrix(), m_xformops[std::distance(m_orderedOps.begin(), transformIt)]); - } + m_flags &= ~kReadAnimatedValues; + + // if not yet intiaialised, do not execute this code! (It will crash!). + if (!m_prim) + return; + + // if we are enabling push to prim, we need to see if anything has changed on the transform + // since the last time the values were synced. I'm assuming that if a given transform attribute + // is not the same as the default, or the prim already has a transform op for that attribute, + // then just call a method to make a minor adjustment of nothing. This will call my code that + // will magically construct the transform ops in the right order. + if (enabled) { + const MVector nullVec(0, 0, 0); + const MVector oneVec(1.0, 1.0, 1.0); + const MPoint nullPoint(0, 0, 0); + const MQuaternion nullQuat(0, 0, 0, 1.0); + + if (!pushPrimToMatrix()) { + if (primHasTranslation() || translation() != nullVec) + translateBy(nullVec); + + if (primHasScale() || scale() != oneVec) + scaleBy(oneVec); + + if (primHasShear() || shear() != nullVec) + shearBy(nullVec); + + if (primHasScalePivot() || scalePivot() != nullPoint) + setScalePivot(scalePivot(), MSpace::kTransform, false); + + if (primHasScalePivotTranslate() || scalePivotTranslation() != nullVec) + setScalePivotTranslation(scalePivotTranslation(), MSpace::kTransform); + + if (primHasRotatePivot() || rotatePivot() != nullPoint) + setRotatePivot(rotatePivot(), MSpace::kTransform, false); + + if (primHasRotatePivotTranslate() || rotatePivotTranslation() != nullVec) + setRotatePivotTranslation(rotatePivotTranslation(), MSpace::kTransform); + + if (primHasRotation() || rotation() != nullQuat) + rotateBy(nullQuat); + + if (primHasRotateAxes() || rotateOrientation() != nullQuat) + setRotateOrientation(rotateOrientation(), MSpace::kTransform, false); + } else if (primHasTransform()) { + auto transformIt = std::find(m_orderedOps.begin(), m_orderedOps.end(), kTransform); + if (transformIt != m_orderedOps.end()) { + internal_pushMatrix( + asMatrix(), m_xformops[std::distance(m_orderedOps.begin(), transformIt)]); + } + } } - } } //---------------------------------------------------------------------------------------------------------------------- void TransformationMatrix::enablePushToPrim(bool enabled) { - TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::enablePushToPrim\n"); - if(enabled) m_flags |= kPushToPrimEnabled; - else m_flags &= ~kPushToPrimEnabled; - - // if not yet intiaialised, do not execute this code! (It will crash!). - if(!m_prim) - return; - - // if we are enabling push to prim, we need to see if anything has changed on the transform since the last time - // the values were synced. I'm assuming that if a given transform attribute is not the same as the default, or - // the prim already has a transform op for that attribute, then just call a method to make a minor adjustment - // of nothing. This will call my code that will magically construct the transform ops in the right order. - if(enabled && getTimeCode() == UsdTimeCode::Default()) - { - const MVector nullVec(0, 0, 0); - const MVector oneVec(1.0, 1.0, 1.0); - const MPoint nullPoint(0, 0, 0); - const MQuaternion nullQuat(0, 0, 0, 1.0); - - if(!pushPrimToMatrix()) - { - if(primHasTranslation() || translation() != nullVec) - translateTo(translation()); - - if(primHasScale() || scale() != oneVec) - scaleTo(scale()); - - if(primHasShear() || shear() != nullVec) - shearTo(shear()); - - if(primHasScalePivot() || scalePivot() != nullPoint) - setScalePivot(scalePivot(), MSpace::kTransform, false); - - if(primHasScalePivotTranslate() || scalePivotTranslation() != nullVec) - setScalePivotTranslation(scalePivotTranslation(), MSpace::kTransform); - - if(primHasRotatePivot() || rotatePivot() != nullPoint) - setRotatePivot(rotatePivot(), MSpace::kTransform, false); - - if(primHasRotatePivotTranslate() || rotatePivotTranslation() != nullVec) - setRotatePivotTranslation(rotatePivotTranslation(), MSpace::kTransform); - - if(primHasRotation() || rotation() != nullQuat) - rotateTo(rotation()); - - if(primHasRotateAxes() || rotateOrientation() != nullQuat) - setRotateOrientation(rotateOrientation(), MSpace::kTransform, false); - } + TF_DEBUG(ALUSDMAYA_TRANSFORM_MATRIX).Msg("TransformationMatrix::enablePushToPrim\n"); + if (enabled) + m_flags |= kPushToPrimEnabled; else - if(primHasTransform()) - { - auto transformIt = std::find(m_orderedOps.begin(), m_orderedOps.end(), kTransform); - if (transformIt != m_orderedOps.end() ) - { - internal_pushMatrix(asMatrix(), m_xformops[std::distance(m_orderedOps.begin(), transformIt)]); - } + m_flags &= ~kPushToPrimEnabled; + + // if not yet intiaialised, do not execute this code! (It will crash!). + if (!m_prim) + return; + + // if we are enabling push to prim, we need to see if anything has changed on the transform + // since the last time the values were synced. I'm assuming that if a given transform attribute + // is not the same as the default, or the prim already has a transform op for that attribute, + // then just call a method to make a minor adjustment of nothing. This will call my code that + // will magically construct the transform ops in the right order. + if (enabled && getTimeCode() == UsdTimeCode::Default()) { + const MVector nullVec(0, 0, 0); + const MVector oneVec(1.0, 1.0, 1.0); + const MPoint nullPoint(0, 0, 0); + const MQuaternion nullQuat(0, 0, 0, 1.0); + + if (!pushPrimToMatrix()) { + if (primHasTranslation() || translation() != nullVec) + translateTo(translation()); + + if (primHasScale() || scale() != oneVec) + scaleTo(scale()); + + if (primHasShear() || shear() != nullVec) + shearTo(shear()); + + if (primHasScalePivot() || scalePivot() != nullPoint) + setScalePivot(scalePivot(), MSpace::kTransform, false); + + if (primHasScalePivotTranslate() || scalePivotTranslation() != nullVec) + setScalePivotTranslation(scalePivotTranslation(), MSpace::kTransform); + + if (primHasRotatePivot() || rotatePivot() != nullPoint) + setRotatePivot(rotatePivot(), MSpace::kTransform, false); + + if (primHasRotatePivotTranslate() || rotatePivotTranslation() != nullVec) + setRotatePivotTranslation(rotatePivotTranslation(), MSpace::kTransform); + + if (primHasRotation() || rotation() != nullQuat) + rotateTo(rotation()); + + if (primHasRotateAxes() || rotateOrientation() != nullQuat) + setRotateOrientation(rotateOrientation(), MSpace::kTransform, false); + } else if (primHasTransform()) { + auto transformIt = std::find(m_orderedOps.begin(), m_orderedOps.end(), kTransform); + if (transformIt != m_orderedOps.end()) { + internal_pushMatrix( + asMatrix(), m_xformops[std::distance(m_orderedOps.begin(), transformIt)]); + } + } } - } } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/TransformationMatrix.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/TransformationMatrix.h index b71a00247f..a7cda27c65 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/TransformationMatrix.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/TransformationMatrix.h @@ -19,12 +19,11 @@ #include "AL/usdmaya/TransformOperation.h" #include "AL/usdmaya/nodes/BasicTransformationMatrix.h" -#include -#include - -#include #include +#include +#include +#include PXR_NAMESPACE_USING_DIRECTIVE @@ -35,502 +34,558 @@ namespace nodes { class Transform; //---------------------------------------------------------------------------------------------------------------------- -/// \brief This class provides a transformation matrix that allows you to apply tweaks over some read only -/// transformation information extracted from a UsdPrim. Currently each tweak is a simple offset over the values -/// contained within the UsdPrim. +/// \brief This class provides a transformation matrix that allows you to apply tweaks over some +/// read only +/// transformation information extracted from a UsdPrim. Currently each tweak is a simple +/// offset over the values contained within the UsdPrim. /// \ingroup nodes //---------------------------------------------------------------------------------------------------------------------- -class TransformationMatrix - : public BasicTransformationMatrix +class TransformationMatrix : public BasicTransformationMatrix { - friend class Transform; - - UsdGeomXformable m_xform; - UsdTimeCode m_time; - std::vector m_xformops; - std::vector m_orderedOps; - - // tweak values. These are applied on top of the USD transform values to produce the final result. - MVector m_scaleTweak; - MEulerRotation m_rotationTweak; - MVector m_translationTweak; - MVector m_shearTweak; - MPoint m_scalePivotTweak; - MVector m_scalePivotTranslationTweak; - MPoint m_rotatePivotTweak; - MVector m_rotatePivotTranslationTweak; - MQuaternion m_rotateOrientationTweak; - - // values read in from USD - MVector m_scaleFromUsd; - MEulerRotation m_rotationFromUsd; - MVector m_translationFromUsd; - MVector m_shearFromUsd; - MPoint m_scalePivotFromUsd; - MVector m_scalePivotTranslationFromUsd; - MPoint m_rotatePivotFromUsd; - MVector m_rotatePivotTranslationFromUsd; - MQuaternion m_rotateOrientationFromUsd; - - // post-transform translation value applied in object space after all other transformations - MVector m_localTranslateOffset; - bool m_enableUsdWriteback = true; - - void print() const - { - std::cout << "m_scaleTweak " << m_scaleTweak << '\n'; - std::cout << "m_rotationTweak " << m_rotationTweak << '\n'; - std::cout << "m_translationTweak " << m_translationTweak << '\n'; - std::cout << "m_shearTweak " << m_shearTweak << '\n'; - std::cout << "m_scalePivotTweak " << m_scalePivotTweak << '\n'; - std::cout << "m_scalePivotTranslationTweak " << m_scalePivotTranslationTweak << '\n'; - std::cout << "m_rotatePivotTweak " << m_rotatePivotTweak << '\n'; - std::cout << "m_rotatePivotTranslationTweak " << m_rotatePivotTranslationTweak << '\n'; - std::cout << "m_rotateOrientationTweak " << m_rotateOrientationTweak << '\n'; - std::cout << "m_scaleFromUsd " << m_scaleFromUsd << '\n'; - std::cout << "m_rotationFromUsd " << m_rotationFromUsd << '\n'; - std::cout << "m_translationFromUsd " << m_translationFromUsd << '\n'; - std::cout << "m_shearFromUsd " << m_shearFromUsd << '\n'; - std::cout << "m_scalePivotFromUsd " << m_scalePivotFromUsd << '\n'; - std::cout << "m_scalePivotTranslationFromUsd " << m_scalePivotTranslationFromUsd << '\n'; - std::cout << "m_rotatePivotFromUsd " << m_rotatePivotFromUsd << '\n'; - std::cout << "m_rotatePivotTranslationFromUsd " << m_rotatePivotTranslationFromUsd << '\n'; - std::cout << "m_rotateOrientationFromUsd " << m_rotateOrientationFromUsd << '\n' << std::endl; - } - - // methods that will insert a transform op into the ordered queue of operations, if for some. - void insertTranslateOp(); - void insertScaleOp(); - void insertShearOp(); - void insertScalePivotOp(); - void insertScalePivotTranslationOp(); - void insertRotateOp(); - void insertRotatePivotOp(); - void insertRotatePivotTranslationOp(); - void insertRotateAxesOp(); - - enum Flags - { - // describe which components are animated - kAnimatedScale = 1 << 0, - kAnimatedRotation = 1 << 1, - kAnimatedTranslation = 1 << 2, - kAnimatedMatrix = 1 << 3, - kAnimatedShear = 1 << 4, - - // are the transform ops coming from a matrix, the PXR schema, or from the maya schema (no flags set) - kFromMatrix = 1 << 8, - kFromMayaSchema = 1 << 9, - - // which transform components are present in the prim? - kPrimHasScale = 1 << 16, - kPrimHasRotation = 1 << 17, - kPrimHasTranslation = 1 << 18, - kPrimHasShear = 1 << 19, - kPrimHasScalePivot = 1 << 20, - kPrimHasScalePivotTranslate = 1 << 21, - kPrimHasRotatePivot = 1 << 22, - kPrimHasRotatePivotTranslate = 1 << 23, - kPrimHasRotateAxes = 1 << 24, - kPrimHasPivot = 1 << 25, - kPrimHasTransform = 1 << 26, - - kPushToPrimEnabled = 1 << 28, - kInheritsTransform = 1 << 29, - - kPushPrimToMatrix = 1 << 30, - kReadAnimatedValues = 1 << 31, - - kAnimationMask = kAnimatedShear | kAnimatedScale | kAnimatedRotation | kAnimatedTranslation | kAnimatedMatrix, - - // Most of these flags are calculated based on reading the usd prim; however, a few are driven - // "externally" (ie, from attributes on the controlling transform node), and should NOT be reset - // when we're re-initializing (ie, in setPrim) - kPreservationMask = kPushToPrimEnabled | kReadAnimatedValues - }; - uint32_t m_flags = kReadAnimatedValues; - - bool internal_readVector(MVector& result, const UsdGeomXformOp& op) { return readVector(result, op, getTimeCode()); } - bool internal_readShear(MVector& result, const UsdGeomXformOp& op) { return readShear(result, op, getTimeCode()); } - bool internal_readPoint(MPoint& result, const UsdGeomXformOp& op) { return readPoint(result, op, getTimeCode()); } - bool internal_readRotation(MEulerRotation& result, const UsdGeomXformOp& op) { return readRotation(result, op, getTimeCode()); } - double internal_readDouble(const UsdGeomXformOp& op) { return readDouble(op, getTimeCode()); } - bool internal_readMatrix(MMatrix& result, const UsdGeomXformOp& op) { return readMatrix(result, op, getTimeCode()); } - - bool internal_pushVector(const MVector& result, UsdGeomXformOp& op) { return pushVector(result, op, getTimeCode()); } - bool internal_pushPoint(const MPoint& result, UsdGeomXformOp& op) { return pushPoint(result, op, getTimeCode()); } - bool internal_pushRotation(const MEulerRotation& result, UsdGeomXformOp& op) { return pushRotation(result, op, getTimeCode()); } - void internal_pushDouble(const double result, UsdGeomXformOp& op) { pushDouble(result, op, getTimeCode()); } - bool internal_pushShear(const MVector& result, UsdGeomXformOp& op) { return pushShear(result, op, getTimeCode()); } - bool internal_pushMatrix(const MMatrix& result, UsdGeomXformOp& op) { return pushMatrix(result, op, getTimeCode()); } - - /// \brief checks to see whether the transform attribute is locked - /// \return true if the translate attribute is locked - bool isTranslateLocked() + friend class Transform; + + UsdGeomXformable m_xform; + UsdTimeCode m_time; + std::vector m_xformops; + std::vector m_orderedOps; + + // tweak values. These are applied on top of the USD transform values to produce the final + // result. + MVector m_scaleTweak; + MEulerRotation m_rotationTweak; + MVector m_translationTweak; + MVector m_shearTweak; + MPoint m_scalePivotTweak; + MVector m_scalePivotTranslationTweak; + MPoint m_rotatePivotTweak; + MVector m_rotatePivotTranslationTweak; + MQuaternion m_rotateOrientationTweak; + + // values read in from USD + MVector m_scaleFromUsd; + MEulerRotation m_rotationFromUsd; + MVector m_translationFromUsd; + MVector m_shearFromUsd; + MPoint m_scalePivotFromUsd; + MVector m_scalePivotTranslationFromUsd; + MPoint m_rotatePivotFromUsd; + MVector m_rotatePivotTranslationFromUsd; + MQuaternion m_rotateOrientationFromUsd; + + // post-transform translation value applied in object space after all other transformations + MVector m_localTranslateOffset; + bool m_enableUsdWriteback = true; + + void print() const + { + std::cout << "m_scaleTweak " << m_scaleTweak << '\n'; + std::cout << "m_rotationTweak " << m_rotationTweak << '\n'; + std::cout << "m_translationTweak " << m_translationTweak << '\n'; + std::cout << "m_shearTweak " << m_shearTweak << '\n'; + std::cout << "m_scalePivotTweak " << m_scalePivotTweak << '\n'; + std::cout << "m_scalePivotTranslationTweak " << m_scalePivotTranslationTweak << '\n'; + std::cout << "m_rotatePivotTweak " << m_rotatePivotTweak << '\n'; + std::cout << "m_rotatePivotTranslationTweak " << m_rotatePivotTranslationTweak << '\n'; + std::cout << "m_rotateOrientationTweak " << m_rotateOrientationTweak << '\n'; + std::cout << "m_scaleFromUsd " << m_scaleFromUsd << '\n'; + std::cout << "m_rotationFromUsd " << m_rotationFromUsd << '\n'; + std::cout << "m_translationFromUsd " << m_translationFromUsd << '\n'; + std::cout << "m_shearFromUsd " << m_shearFromUsd << '\n'; + std::cout << "m_scalePivotFromUsd " << m_scalePivotFromUsd << '\n'; + std::cout << "m_scalePivotTranslationFromUsd " << m_scalePivotTranslationFromUsd << '\n'; + std::cout << "m_rotatePivotFromUsd " << m_rotatePivotFromUsd << '\n'; + std::cout << "m_rotatePivotTranslationFromUsd " << m_rotatePivotTranslationFromUsd << '\n'; + std::cout << "m_rotateOrientationFromUsd " << m_rotateOrientationFromUsd << '\n' + << std::endl; + } + + // methods that will insert a transform op into the ordered queue of operations, if for some. + void insertTranslateOp(); + void insertScaleOp(); + void insertShearOp(); + void insertScalePivotOp(); + void insertScalePivotTranslationOp(); + void insertRotateOp(); + void insertRotatePivotOp(); + void insertRotatePivotTranslationOp(); + void insertRotateAxesOp(); + + enum Flags + { + // describe which components are animated + kAnimatedScale = 1 << 0, + kAnimatedRotation = 1 << 1, + kAnimatedTranslation = 1 << 2, + kAnimatedMatrix = 1 << 3, + kAnimatedShear = 1 << 4, + + // are the transform ops coming from a matrix, the PXR schema, or from the maya schema (no + // flags set) + kFromMatrix = 1 << 8, + kFromMayaSchema = 1 << 9, + + // which transform components are present in the prim? + kPrimHasScale = 1 << 16, + kPrimHasRotation = 1 << 17, + kPrimHasTranslation = 1 << 18, + kPrimHasShear = 1 << 19, + kPrimHasScalePivot = 1 << 20, + kPrimHasScalePivotTranslate = 1 << 21, + kPrimHasRotatePivot = 1 << 22, + kPrimHasRotatePivotTranslate = 1 << 23, + kPrimHasRotateAxes = 1 << 24, + kPrimHasPivot = 1 << 25, + kPrimHasTransform = 1 << 26, + + kPushToPrimEnabled = 1 << 28, + kInheritsTransform = 1 << 29, + + kPushPrimToMatrix = 1 << 30, + kReadAnimatedValues = 1 << 31, + + kAnimationMask = kAnimatedShear | kAnimatedScale | kAnimatedRotation | kAnimatedTranslation + | kAnimatedMatrix, + + // Most of these flags are calculated based on reading the usd prim; however, a few are + // driven "externally" (ie, from attributes on the controlling transform node), and should + // NOT be reset when we're re-initializing (ie, in setPrim) + kPreservationMask = kPushToPrimEnabled | kReadAnimatedValues + }; + uint32_t m_flags = kReadAnimatedValues; + + bool internal_readVector(MVector& result, const UsdGeomXformOp& op) + { + return readVector(result, op, getTimeCode()); + } + bool internal_readShear(MVector& result, const UsdGeomXformOp& op) + { + return readShear(result, op, getTimeCode()); + } + bool internal_readPoint(MPoint& result, const UsdGeomXformOp& op) + { + return readPoint(result, op, getTimeCode()); + } + bool internal_readRotation(MEulerRotation& result, const UsdGeomXformOp& op) + { + return readRotation(result, op, getTimeCode()); + } + double internal_readDouble(const UsdGeomXformOp& op) { return readDouble(op, getTimeCode()); } + bool internal_readMatrix(MMatrix& result, const UsdGeomXformOp& op) + { + return readMatrix(result, op, getTimeCode()); + } + + bool internal_pushVector(const MVector& result, UsdGeomXformOp& op) + { + return pushVector(result, op, getTimeCode()); + } + bool internal_pushPoint(const MPoint& result, UsdGeomXformOp& op) + { + return pushPoint(result, op, getTimeCode()); + } + bool internal_pushRotation(const MEulerRotation& result, UsdGeomXformOp& op) + { + return pushRotation(result, op, getTimeCode()); + } + void internal_pushDouble(const double result, UsdGeomXformOp& op) + { + pushDouble(result, op, getTimeCode()); + } + bool internal_pushShear(const MVector& result, UsdGeomXformOp& op) + { + return pushShear(result, op, getTimeCode()); + } + bool internal_pushMatrix(const MMatrix& result, UsdGeomXformOp& op) + { + return pushMatrix(result, op, getTimeCode()); + } + + /// \brief checks to see whether the transform attribute is locked + /// \return true if the translate attribute is locked + bool isTranslateLocked() { - MPlug plug(m_transformNode.object(), MPxTransform::translate); - return plug.isLocked() || - plug.child(0).isLocked() || - plug.child(1).isLocked() || - plug.child(2).isLocked(); + MPlug plug(m_transformNode.object(), MPxTransform::translate); + return plug.isLocked() || plug.child(0).isLocked() || plug.child(1).isLocked() + || plug.child(2).isLocked(); } - /// \brief checks to see whether the rotate attribute is locked - /// \return true if the rotate attribute is locked - bool isRotateLocked() + /// \brief checks to see whether the rotate attribute is locked + /// \return true if the rotate attribute is locked + bool isRotateLocked() { - MPlug plug(m_transformNode.object(), MPxTransform::rotate); - return plug.isLocked() || - plug.child(0).isLocked() || - plug.child(1).isLocked() || - plug.child(2).isLocked(); + MPlug plug(m_transformNode.object(), MPxTransform::rotate); + return plug.isLocked() || plug.child(0).isLocked() || plug.child(1).isLocked() + || plug.child(2).isLocked(); } - /// \brief checks to see whether the scale attribute is locked - /// \return true if the scale attribute is locked - bool isScaleLocked() + /// \brief checks to see whether the scale attribute is locked + /// \return true if the scale attribute is locked + bool isScaleLocked() { - MPlug plug(m_transformNode.object(), MPxTransform::scale); - return plug.isLocked() || - plug.child(0).isLocked() || - plug.child(1).isLocked() || - plug.child(2).isLocked(); + MPlug plug(m_transformNode.object(), MPxTransform::scale); + return plug.isLocked() || plug.child(0).isLocked() || plug.child(1).isLocked() + || plug.child(2).isLocked(); } - /// \brief checks to see whether the shear attribute is locked - /// \return true if the shear attribute is locked - bool isShearLocked() + /// \brief checks to see whether the shear attribute is locked + /// \return true if the shear attribute is locked + bool isShearLocked() { - MPlug plug(m_transformNode.object(), MPxTransform::shear); - return plug.isLocked() || - plug.child(0).isLocked() || - plug.child(1).isLocked() || - plug.child(2).isLocked(); + MPlug plug(m_transformNode.object(), MPxTransform::shear); + return plug.isLocked() || plug.child(0).isLocked() || plug.child(1).isLocked() + || plug.child(2).isLocked(); } - /// \brief helper method. Reads a vector from the transform op specified at the requested timecode - /// \param result the returned result - /// \param op the transformation op to read from - /// \param timeCode the time at which to query the transform value - /// return true if read ok - static bool readVector(MVector& result, const UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); - - /// \brief helper method. Reads a shear value from the transform op specified at the requested timecode - /// \param result the returned result - /// \param op the transformation op to read from - /// \param timeCode the time at which to query the transform value - /// return true if read ok - static bool readShear(MVector& result, const UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); - - /// \brief helper method. Reads a point from the transform op specified at the requested timecode - /// \param result the returned result - /// \param op the transformation op to read from - /// \param timeCode the time at which to query the transform value - /// return true if read ok - static bool readPoint(MPoint& result, const UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); - - /// \brief helper method. Reads an euler rotation from the transform op specified at the requested timecode - /// \param result the returned result - /// \param op the transformation op to read from - /// \param timeCode the time at which to query the transform value - /// return true if read ok - static bool readRotation(MEulerRotation& result, const UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); - - /// \brief helper method. Reads a double from the transform op specified at the requested timecode (typically RotateX / rotateY values) - /// \param op the transformation op to read from - /// \param timeCode the time at which to query the transform value - /// return the returned value - static double readDouble(const UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); - - /// \brief helper method. Reads a matrix from the transform op specified at the requested timecode - /// \param result the returned result - /// \param op the transformation op to read from - /// \param timeCode the time at which to query the transform value - /// return true if read ok - static bool readMatrix(MMatrix& result, const UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); - - /// \brief helper method. Pushes a vector into the transform op specified at the requested timecode - /// \param input the new value to insert into the transform operation - /// \param op the transformation op to write into - /// \param timeCode the time at which to set the transform value - /// return true if written ok - static bool pushVector(const MVector& input, UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::Default()); - - /// \brief helper method. Pushes a point into the transform op specified at the requested timecode - /// \param input the new value to insert into the transform operation - /// \param op the transformation op to write into - /// \param timeCode the time at which to set the transform value - /// return true if written ok - static bool pushPoint(const MPoint& input, UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::Default()); - - /// \brief helper method. Pushes a vector into the transform op specified at the requested timecode - /// \param input the new value to insert into the transform operation - /// \param op the transformation op to write into - /// \param timeCode the time at which to set the transform value - /// return true if written ok - static bool pushRotation(const MEulerRotation& input, UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::Default()); - - /// \brief helper method. Pushes a double into the transform op specified at the requested timecode (typically for RotateX / RotateY) - /// \param input the new value to insert into the transform operation - /// \param op the transformation op to write into - /// \param timeCode the time at which to set the transform value - /// return true if written ok - static void pushDouble(const double input, UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::Default()); - - /// \brief helper method. Pushes a shear into the transform op specified at the requested timecode - /// \param input the new value to insert into the transform operation - /// \param op the transformation op to write into - /// \param timeCode the time at which to set the transform value - /// return true if written ok - static bool pushShear(const MVector& input, UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::Default()); - - /// \brief helper method. Pushes a matrix into the transform op specified at the requested timecode - /// \param input the new value to insert into the transform operation - /// \param op the transformation op to write into - /// \param timeCode the time at which to set the transform value - /// return true if written ok - static bool pushMatrix(const MMatrix& input, UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::Default()); - - /// \brief If set to true, transform values will target the animated key-frame values in the prim. If set to false, - /// the transform values will target the default attribute values. - /// \param enabled true to target animated values, false to target the default. - void enableReadAnimatedValues(bool enabled); - - /// \brief Applies a local space translation offset to the computed matrix. Useful for positioning objects on a - /// table. - /// \param localTranslateOffset the local space offset to apply to the transform. - inline void setLocalTranslationOffset(const MVector& localTranslateOffset) - { m_localTranslateOffset = localTranslateOffset; } - - /// \brief this method updates the internal transformation components to the given time. Only the Transform node - /// should need to call this method - /// \param time the new timecode - void updateToTime(const UsdTimeCode& time); - - /// \brief pushes any modifications on the matrix back onto the UsdPrim - void pushToPrim(); - - void notifyProxyShapeOfRedraw(); - - /// \brief sets the SRT values from a matrix - void setFromMatrix(MObject thisNode, const MMatrix& m); - - // Translation methods: - MStatus translateTo(const MVector &vector, MSpace::Space = MSpace::kTransform) override; - - // Scale methods: - MStatus scaleTo(const MVector &, MSpace::Space = MSpace::kTransform) override; - - // Shear methods: - MStatus shearTo(const MVector& shear, MSpace::Space = MSpace::kTransform) override; - - // Scale pivot methods: - MStatus setScalePivot(const MPoint &, MSpace::Space = MSpace::kTransform, bool balance = true) override; - MStatus setScalePivotTranslation(const MVector &vector, MSpace::Space = MSpace::kTransform) override; - - // Rotate pivot methods: - MStatus setRotatePivot(const MPoint &, MSpace::Space = MSpace::kTransform, bool balance = true) override; - MStatus setRotatePivotTranslation(const MVector &vector, MSpace::Space = MSpace::kTransform) override; - - // Rotate order methods: - MStatus setRotationOrder(MTransformationMatrix::RotationOrder, bool preserve = true) override; - - // Rotation methods: - MStatus rotateTo(const MQuaternion &q, MSpace::Space = MSpace::kTransform) override; - MStatus rotateTo(const MEulerRotation &e, MSpace::Space = MSpace::kTransform) override; - MStatus setRotateOrientation(const MQuaternion &q, MSpace::Space = MSpace::kTransform, bool balance = true) override; - MStatus setRotateOrientation(const MEulerRotation &euler, MSpace::Space = MSpace::kTransform, bool balance = true) override; - - /// \brief If set to true, modifications to these transform attributes will be pushed back onto the original prim. - /// \param enabled true will cause changes to this transform update the values on the USD prim. False will mean that - /// the changes are simply cached internally. - /// \param enabled true to write values to the usd prim when changed, false to treat the usd prim as read only. - void enablePushToPrim(bool enabled); - - // Compute matrix result - MMatrix asMatrix() const override; - MMatrix asMatrix(double percent) const override; + /// \brief helper method. Reads a vector from the transform op specified at the requested + /// timecode \param result the returned result \param op the transformation op to read from + /// \param timeCode the time at which to query the transform value + /// return true if read ok + static bool readVector( + MVector& result, + const UsdGeomXformOp& op, + UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); + + /// \brief helper method. Reads a shear value from the transform op specified at the requested + /// timecode \param result the returned result \param op the transformation op to read from + /// \param timeCode the time at which to query the transform value + /// return true if read ok + static bool readShear( + MVector& result, + const UsdGeomXformOp& op, + UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); + + /// \brief helper method. Reads a point from the transform op specified at the requested + /// timecode \param result the returned result \param op the transformation op to read from + /// \param timeCode the time at which to query the transform value + /// return true if read ok + static bool readPoint( + MPoint& result, + const UsdGeomXformOp& op, + UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); + + /// \brief helper method. Reads an euler rotation from the transform op specified at the + /// requested timecode \param result the returned result \param op the transformation op to + /// read from \param timeCode the time at which to query the transform value return true if + /// read ok + static bool readRotation( + MEulerRotation& result, + const UsdGeomXformOp& op, + UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); + + /// \brief helper method. Reads a double from the transform op specified at the requested + /// timecode (typically RotateX / rotateY values) \param op the transformation op to read from + /// \param timeCode the time at which to query the transform value + /// return the returned value + static double + readDouble(const UsdGeomXformOp& op, UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); + + /// \brief helper method. Reads a matrix from the transform op specified at the requested + /// timecode \param result the returned result \param op the transformation op to read from + /// \param timeCode the time at which to query the transform value + /// return true if read ok + static bool readMatrix( + MMatrix& result, + const UsdGeomXformOp& op, + UsdTimeCode timeCode = UsdTimeCode::EarliestTime()); + + /// \brief helper method. Pushes a vector into the transform op specified at the requested + /// timecode \param input the new value to insert into the transform operation \param op the + /// transformation op to write into \param timeCode the time at which to set the transform + /// value return true if written ok + static bool pushVector( + const MVector& input, + UsdGeomXformOp& op, + UsdTimeCode timeCode = UsdTimeCode::Default()); + + /// \brief helper method. Pushes a point into the transform op specified at the requested + /// timecode \param input the new value to insert into the transform operation \param op the + /// transformation op to write into \param timeCode the time at which to set the transform + /// value return true if written ok + static bool pushPoint( + const MPoint& input, + UsdGeomXformOp& op, + UsdTimeCode timeCode = UsdTimeCode::Default()); + + /// \brief helper method. Pushes a vector into the transform op specified at the requested + /// timecode \param input the new value to insert into the transform operation \param op the + /// transformation op to write into \param timeCode the time at which to set the transform + /// value return true if written ok + static bool pushRotation( + const MEulerRotation& input, + UsdGeomXformOp& op, + UsdTimeCode timeCode = UsdTimeCode::Default()); + + /// \brief helper method. Pushes a double into the transform op specified at the requested + /// timecode (typically for RotateX / RotateY) \param input the new value to insert into the + /// transform operation \param op the transformation op to write into \param timeCode the time + /// at which to set the transform value return true if written ok + static void pushDouble( + const double input, + UsdGeomXformOp& op, + UsdTimeCode timeCode = UsdTimeCode::Default()); + + /// \brief helper method. Pushes a shear into the transform op specified at the requested + /// timecode \param input the new value to insert into the transform operation \param op the + /// transformation op to write into \param timeCode the time at which to set the transform + /// value return true if written ok + static bool pushShear( + const MVector& input, + UsdGeomXformOp& op, + UsdTimeCode timeCode = UsdTimeCode::Default()); + + /// \brief helper method. Pushes a matrix into the transform op specified at the requested + /// timecode \param input the new value to insert into the transform operation \param op the + /// transformation op to write into \param timeCode the time at which to set the transform + /// value return true if written ok + static bool pushMatrix( + const MMatrix& input, + UsdGeomXformOp& op, + UsdTimeCode timeCode = UsdTimeCode::Default()); + + /// \brief If set to true, transform values will target the animated key-frame values in the + /// prim. If set to false, + /// the transform values will target the default attribute values. + /// \param enabled true to target animated values, false to target the default. + void enableReadAnimatedValues(bool enabled); + + /// \brief Applies a local space translation offset to the computed matrix. Useful for + /// positioning objects on a + /// table. + /// \param localTranslateOffset the local space offset to apply to the transform. + inline void setLocalTranslationOffset(const MVector& localTranslateOffset) + { + m_localTranslateOffset = localTranslateOffset; + } -public: + /// \brief this method updates the internal transformation components to the given time. Only + /// the Transform node + /// should need to call this method + /// \param time the new timecode + void updateToTime(const UsdTimeCode& time); + + /// \brief pushes any modifications on the matrix back onto the UsdPrim + void pushToPrim(); + + void notifyProxyShapeOfRedraw(); + + /// \brief sets the SRT values from a matrix + void setFromMatrix(MObject thisNode, const MMatrix& m); + + // Translation methods: + MStatus translateTo(const MVector& vector, MSpace::Space = MSpace::kTransform) override; + + // Scale methods: + MStatus scaleTo(const MVector&, MSpace::Space = MSpace::kTransform) override; + + // Shear methods: + MStatus shearTo(const MVector& shear, MSpace::Space = MSpace::kTransform) override; + + // Scale pivot methods: + MStatus + setScalePivot(const MPoint&, MSpace::Space = MSpace::kTransform, bool balance = true) override; + MStatus + setScalePivotTranslation(const MVector& vector, MSpace::Space = MSpace::kTransform) override; + + // Rotate pivot methods: + MStatus + setRotatePivot(const MPoint&, MSpace::Space = MSpace::kTransform, bool balance = true) override; + MStatus + setRotatePivotTranslation(const MVector& vector, MSpace::Space = MSpace::kTransform) override; + + // Rotate order methods: + MStatus setRotationOrder(MTransformationMatrix::RotationOrder, bool preserve = true) override; + + // Rotation methods: + MStatus rotateTo(const MQuaternion& q, MSpace::Space = MSpace::kTransform) override; + MStatus rotateTo(const MEulerRotation& e, MSpace::Space = MSpace::kTransform) override; + MStatus setRotateOrientation( + const MQuaternion& q, + MSpace::Space = MSpace::kTransform, + bool balance = true) override; + MStatus setRotateOrientation( + const MEulerRotation& euler, + MSpace::Space = MSpace::kTransform, + bool balance = true) override; + + /// \brief If set to true, modifications to these transform attributes will be pushed back onto + /// the original prim. \param enabled true will cause changes to this transform update the + /// values on the USD prim. False will mean that + /// the changes are simply cached internally. + /// \param enabled true to write values to the usd prim when changed, false to treat the usd + /// prim as read only. + void enablePushToPrim(bool enabled); + + // Compute matrix result + MMatrix asMatrix() const override; + MMatrix asMatrix(double percent) const override; - /// \brief the type ID of the transformation matrix - AL_USDMAYA_PUBLIC - static const MTypeId kTypeId; - - /// \brief create an instance of this transformation matrix - /// \return a new instance of this transformation matrix - AL_USDMAYA_PUBLIC - static MPxTransformationMatrix* creator(); - - /// \brief ctor - TransformationMatrix(); - - /// \brief ctor - /// \param prim the USD prim that this matrix should represent - TransformationMatrix(const UsdPrim& prim); - - /// \brief set the prim that this transformation matrix will read/write to. - /// \param prim the prim - /// \param transformNode the owning transform node - void setPrim(const UsdPrim& prim, Scope* transformNode) override; - - /// \brief Returns the timecode to use when pushing the transform values to the USD prim. If readFromTimeline flag - /// is set to true, then the timecode will be read from the incoming time attribute on the transform node. - /// If readFromTimeline is false, then the timecode will be the magic 'modify default values' timecode, - /// and animation data will not be affected (only the default values found in the USD prim) - /// \return the timecode to use when pushing transform values to the USD prim - inline UsdTimeCode getTimeCode() - { return readAnimatedValues() ? m_time : UsdTimeCode::Default(); } - - //-------------------------------------------------------------------------------------------------------------------- - /// \name Query flags - //-------------------------------------------------------------------------------------------------------------------- - - /// \brief does the prim have animated scale? - inline bool hasAnimation() const - { return (kAnimationMask & m_flags) != 0; } - - /// \brief does the prim have animated scale? - inline bool hasAnimatedScale() const - { return (kAnimatedScale & m_flags) != 0; } - - /// \brief does the prim have animated shear? - inline bool hasAnimatedShear() const - { return (kAnimatedShear & m_flags) != 0; } - - /// \brief does the prim have animated translation? - inline bool hasAnimatedTranslation() const - { return (kAnimatedTranslation & m_flags) != 0; } - - /// \brief does the prim have animated rotation? - inline bool hasAnimatedRotation() const - { return (kAnimatedRotation & m_flags) != 0; } - - /// \brief does the prim have an animated matrix only? - inline bool hasAnimatedMatrix() const - { return (kAnimatedMatrix & m_flags) != 0; } - - /// \brief does the UsdGeomXform have a scale transform op? - inline bool primHasScale() const - { return (kPrimHasScale & m_flags) != 0; } - - /// \brief does the UsdGeomXform have a rotation transform op? - inline bool primHasRotation() const - { return (kPrimHasRotation & m_flags) != 0; } - - /// \brief does the UsdGeomXform have a translation transform op? - inline bool primHasTranslation() const - { return (kPrimHasTranslation & m_flags) != 0; } - - /// \brief does the UsdGeomXform have a shear transform op? - inline bool primHasShear() const - { return (kPrimHasShear & m_flags) != 0; } - - /// \brief does the UsdGeomXform have a scale pivot op? - inline bool primHasScalePivot() const - { return (kPrimHasScalePivot & m_flags) != 0; } - - /// \brief does the UsdGeomXform have a scale pivot translate op? - inline bool primHasScalePivotTranslate() const - { return (kPrimHasScalePivotTranslate & m_flags) != 0; } - - /// \brief does the UsdGeomXform have a rotate pivot op? - inline bool primHasRotatePivot() const - { return (kPrimHasRotatePivot & m_flags) != 0; } - - /// \brief does the UsdGeomXform have a rotate pivot translate op? - inline bool primHasRotatePivotTranslate() const - { return (kPrimHasRotatePivotTranslate & m_flags) != 0; } - - /// \brief does the UsdGeomXform have a rotation axes op? - inline bool primHasRotateAxes() const - { return (kPrimHasRotateAxes & m_flags) != 0; } - - /// \brief does the UsdGeomXform have a pixar pivot op? - inline bool primHasPivot() const - { return (kPrimHasPivot & m_flags) != 0; } - - /// \brief does the UsdGeomXform have a transform matrix op? - inline bool primHasTransform() const - { return (kPrimHasTransform & m_flags) != 0; } - - /// \brief should we read the animated keyframes or the defaults? - inline bool readAnimatedValues() const - { return (kReadAnimatedValues & m_flags) != 0; } - - /// \brief Is this transform set to write back onto the USD prim - inline bool pushToPrimEnabled() const - { return (kPushToPrimEnabled & m_flags) != 0; } - - /// \brief Is this prim writing back to a matrix (true) or to components (false) - inline bool pushPrimToMatrix() const - { return (kPushPrimToMatrix & m_flags) != 0; } - - /// \brief Is this transform set to write back onto the USD prim, and is it currently possible? - bool pushToPrimAvailable() const override - { return pushToPrimEnabled() && m_prim.IsValid(); } - - //-------------------------------------------------------------------------------------------------------------------- - /// \name Convert To-From USD primitive - //-------------------------------------------------------------------------------------------------------------------- - - - /// \brief this method inspects the UsdGeomXform to find out: - /// -# what schema is being used (Maya, Pxr, or just a matrix) - /// -# which transformation components are present (e.g. scale, rotate, etc). - /// -# which, if any, of those components are animated. - /// \param readFromPrim if true, the maya attribute values will be updated from those found on the USD prim - /// \param node the transform node to which this matrix belongs (and where the USD prim will be extracted from) - void initialiseToPrim(bool readFromPrim = true, Scope* node = 0) override; - - void pushTranslateToPrim(); - void pushPivotToPrim(); - void pushRotatePivotTranslateToPrim(); - void pushRotatePivotToPrim(); - void pushRotateToPrim(); - void pushRotateQuatToPrim(); - void pushRotateAxisToPrim(); - void pushScalePivotTranslateToPrim(); - void pushScalePivotToPrim(); - void pushScaleToPrim(); - void pushShearToPrim(); - void pushTransformToPrim(); - - // Helper class. Creating a variable of this class temporarily disables - // push to prim after saving its original state. When the variable goes - // out of scope, the original push to prim state is restored by the - // destructor. - // - class Scoped_DisablePushToPrim - { - public: - Scoped_DisablePushToPrim(TransformationMatrix& tm) : m_transformationMatrix(tm) +public: + /// \brief the type ID of the transformation matrix + AL_USDMAYA_PUBLIC + static const MTypeId kTypeId; + + /// \brief create an instance of this transformation matrix + /// \return a new instance of this transformation matrix + AL_USDMAYA_PUBLIC + static MPxTransformationMatrix* creator(); + + /// \brief ctor + TransformationMatrix(); + + /// \brief ctor + /// \param prim the USD prim that this matrix should represent + TransformationMatrix(const UsdPrim& prim); + + /// \brief set the prim that this transformation matrix will read/write to. + /// \param prim the prim + /// \param transformNode the owning transform node + void setPrim(const UsdPrim& prim, Scope* transformNode) override; + + /// \brief Returns the timecode to use when pushing the transform values to the USD prim. If + /// readFromTimeline flag + /// is set to true, then the timecode will be read from the incoming time attribute on + /// the transform node. If readFromTimeline is false, then the timecode will be the + /// magic 'modify default values' timecode, and animation data will not be affected + /// (only the default values found in the USD prim) + /// \return the timecode to use when pushing transform values to the USD prim + inline UsdTimeCode getTimeCode() { - m_IsPushToPrimEnabled = m_transformationMatrix.pushToPrimEnabled(); - m_transformationMatrix.m_flags &= ~TransformationMatrix::kPushToPrimEnabled; + return readAnimatedValues() ? m_time : UsdTimeCode::Default(); } - ~Scoped_DisablePushToPrim() + //-------------------------------------------------------------------------------------------------------------------- + /// \name Query flags + //-------------------------------------------------------------------------------------------------------------------- + + /// \brief does the prim have animated scale? + inline bool hasAnimation() const { return (kAnimationMask & m_flags) != 0; } + + /// \brief does the prim have animated scale? + inline bool hasAnimatedScale() const { return (kAnimatedScale & m_flags) != 0; } + + /// \brief does the prim have animated shear? + inline bool hasAnimatedShear() const { return (kAnimatedShear & m_flags) != 0; } + + /// \brief does the prim have animated translation? + inline bool hasAnimatedTranslation() const { return (kAnimatedTranslation & m_flags) != 0; } + + /// \brief does the prim have animated rotation? + inline bool hasAnimatedRotation() const { return (kAnimatedRotation & m_flags) != 0; } + + /// \brief does the prim have an animated matrix only? + inline bool hasAnimatedMatrix() const { return (kAnimatedMatrix & m_flags) != 0; } + + /// \brief does the UsdGeomXform have a scale transform op? + inline bool primHasScale() const { return (kPrimHasScale & m_flags) != 0; } + + /// \brief does the UsdGeomXform have a rotation transform op? + inline bool primHasRotation() const { return (kPrimHasRotation & m_flags) != 0; } + + /// \brief does the UsdGeomXform have a translation transform op? + inline bool primHasTranslation() const { return (kPrimHasTranslation & m_flags) != 0; } + + /// \brief does the UsdGeomXform have a shear transform op? + inline bool primHasShear() const { return (kPrimHasShear & m_flags) != 0; } + + /// \brief does the UsdGeomXform have a scale pivot op? + inline bool primHasScalePivot() const { return (kPrimHasScalePivot & m_flags) != 0; } + + /// \brief does the UsdGeomXform have a scale pivot translate op? + inline bool primHasScalePivotTranslate() const { - if(m_IsPushToPrimEnabled) - { - m_transformationMatrix.m_flags |= TransformationMatrix::kPushToPrimEnabled; - } + return (kPrimHasScalePivotTranslate & m_flags) != 0; } - private: - // The TransformationMatrix whose push to prim state is being affected. - TransformationMatrix& m_transformationMatrix; + /// \brief does the UsdGeomXform have a rotate pivot op? + inline bool primHasRotatePivot() const { return (kPrimHasRotatePivot & m_flags) != 0; } - // Holder for the original value of push to prim state. - bool m_IsPushToPrimEnabled; - }; + /// \brief does the UsdGeomXform have a rotate pivot translate op? + inline bool primHasRotatePivotTranslate() const + { + return (kPrimHasRotatePivotTranslate & m_flags) != 0; + } + /// \brief does the UsdGeomXform have a rotation axes op? + inline bool primHasRotateAxes() const { return (kPrimHasRotateAxes & m_flags) != 0; } + + /// \brief does the UsdGeomXform have a pixar pivot op? + inline bool primHasPivot() const { return (kPrimHasPivot & m_flags) != 0; } + + /// \brief does the UsdGeomXform have a transform matrix op? + inline bool primHasTransform() const { return (kPrimHasTransform & m_flags) != 0; } + + /// \brief should we read the animated keyframes or the defaults? + inline bool readAnimatedValues() const { return (kReadAnimatedValues & m_flags) != 0; } + + /// \brief Is this transform set to write back onto the USD prim + inline bool pushToPrimEnabled() const { return (kPushToPrimEnabled & m_flags) != 0; } + + /// \brief Is this prim writing back to a matrix (true) or to components (false) + inline bool pushPrimToMatrix() const { return (kPushPrimToMatrix & m_flags) != 0; } + + /// \brief Is this transform set to write back onto the USD prim, and is it currently possible? + bool pushToPrimAvailable() const override { return pushToPrimEnabled() && m_prim.IsValid(); } + + //-------------------------------------------------------------------------------------------------------------------- + /// \name Convert To-From USD primitive + //-------------------------------------------------------------------------------------------------------------------- + + /// \brief this method inspects the UsdGeomXform to find out: + /// -# what schema is being used (Maya, Pxr, or just a matrix) + /// -# which transformation components are present (e.g. scale, rotate, etc). + /// -# which, if any, of those components are animated. + /// \param readFromPrim if true, the maya attribute values will be updated from those found on + /// the USD prim \param node the transform node to which this matrix belongs (and where the USD + /// prim will be extracted from) + void initialiseToPrim(bool readFromPrim = true, Scope* node = 0) override; + + void pushTranslateToPrim(); + void pushPivotToPrim(); + void pushRotatePivotTranslateToPrim(); + void pushRotatePivotToPrim(); + void pushRotateToPrim(); + void pushRotateQuatToPrim(); + void pushRotateAxisToPrim(); + void pushScalePivotTranslateToPrim(); + void pushScalePivotToPrim(); + void pushScaleToPrim(); + void pushShearToPrim(); + void pushTransformToPrim(); + + // Helper class. Creating a variable of this class temporarily disables + // push to prim after saving its original state. When the variable goes + // out of scope, the original push to prim state is restored by the + // destructor. + // + class Scoped_DisablePushToPrim + { + public: + Scoped_DisablePushToPrim(TransformationMatrix& tm) + : m_transformationMatrix(tm) + { + m_IsPushToPrimEnabled = m_transformationMatrix.pushToPrimEnabled(); + m_transformationMatrix.m_flags &= ~TransformationMatrix::kPushToPrimEnabled; + } + + ~Scoped_DisablePushToPrim() + { + if (m_IsPushToPrimEnabled) { + m_transformationMatrix.m_flags |= TransformationMatrix::kPushToPrimEnabled; + } + } + + private: + // The TransformationMatrix whose push to prim state is being affected. + TransformationMatrix& m_transformationMatrix; + + // Holder for the original value of push to prim state. + bool m_IsPushToPrimEnabled; + }; }; //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/LockManager.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/LockManager.cpp index 0203542791..5edac4aa57 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/LockManager.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/LockManager.cpp @@ -23,228 +23,193 @@ namespace proxy { //---------------------------------------------------------------------------------------------------------------------- void LockManager::removeEntries(const SdfPathVector& entries) { - auto lockIt = m_lockedPrims.begin(); - auto lockEnd = m_lockedPrims.end(); - - auto unlockIt = m_unlockedPrims.begin(); - auto unlockEnd = m_unlockedPrims.end(); - - for(auto it = entries.begin(), end = entries.end(); lockIt != lockEnd && it != end; ++it) - { - const SdfPath path = *it; - lockIt = std::lower_bound(lockIt, lockEnd, path); - if(lockIt != lockEnd && *lockIt == path) - { - lockIt = m_lockedPrims.erase(lockIt); + auto lockIt = m_lockedPrims.begin(); + auto lockEnd = m_lockedPrims.end(); + + auto unlockIt = m_unlockedPrims.begin(); + auto unlockEnd = m_unlockedPrims.end(); + + for (auto it = entries.begin(), end = entries.end(); lockIt != lockEnd && it != end; ++it) { + const SdfPath path = *it; + lockIt = std::lower_bound(lockIt, lockEnd, path); + if (lockIt != lockEnd && *lockIt == path) { + lockIt = m_lockedPrims.erase(lockIt); + } } - } - for(auto it = entries.begin(), end = entries.end(); unlockIt != unlockEnd && it != end; ++it) - { - const SdfPath path = *it; - unlockIt = std::lower_bound(unlockIt, unlockEnd, path); - if(unlockIt != unlockEnd && *unlockIt == path) - { - unlockIt = m_unlockedPrims.erase(unlockIt); + for (auto it = entries.begin(), end = entries.end(); unlockIt != unlockEnd && it != end; ++it) { + const SdfPath path = *it; + unlockIt = std::lower_bound(unlockIt, unlockEnd, path); + if (unlockIt != unlockEnd && *unlockIt == path) { + unlockIt = m_unlockedPrims.erase(unlockIt); + } } - } } //---------------------------------------------------------------------------------------------------------------------- void LockManager::removeFromRootPath(const SdfPath& path) { - { - // find the start of the entries for this path - auto lb = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); - auto ub = lb; - - // keep walking forwards until we hit a new branch in the tree - while(ub != m_lockedPrims.end()) { - if(ub->HasPrefix(path)) - { - ++ub; - } - else - { - break; - } + // find the start of the entries for this path + auto lb = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); + auto ub = lb; + + // keep walking forwards until we hit a new branch in the tree + while (ub != m_lockedPrims.end()) { + if (ub->HasPrefix(path)) { + ++ub; + } else { + break; + } + } + + // if we find a valid range, erase the previous entries + if (lb != ub) { + m_lockedPrims.erase(lb, ub); + } } - // if we find a valid range, erase the previous entries - if(lb != ub) + // remove all previous prims from m_lockInheritedPrims that are children of the current prim. { - m_lockedPrims.erase(lb, ub); + // find the start of the entries for this path + auto lb = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); + auto ub = lb; + + // keep walking forwards until we hit a new branch in the tree + while (ub != m_unlockedPrims.end()) { + if (ub->HasPrefix(path)) { + ++ub; + } else { + break; + } + } + + // if we find a valid range, erase the previous entries + if (lb != ub) { + m_unlockedPrims.erase(lb, ub); + } } - } - - // remove all previous prims from m_lockInheritedPrims that are children of the current prim. - { - // find the start of the entries for this path - auto lb = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); - auto ub = lb; - - // keep walking forwards until we hit a new branch in the tree - while(ub != m_unlockedPrims.end()) - { - if(ub->HasPrefix(path)) - { - ++ub; - } - else - { - break; - } - } - - // if we find a valid range, erase the previous entries - if(lb != ub) - { - m_unlockedPrims.erase(lb, ub); - } - } } //---------------------------------------------------------------------------------------------------------------------- void LockManager::setLocked(const SdfPath& path) { - auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); - if(lockIter != m_lockedPrims.end()) - { - // lock already in the locked array, so return - if(*lockIter == path) - return; - } - m_lockedPrims.insert(lockIter, path); - - auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); - if(unlockIter != m_unlockedPrims.end()) - { - if(*unlockIter == path) - { - m_unlockedPrims.erase(unlockIter); + auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); + if (lockIter != m_lockedPrims.end()) { + // lock already in the locked array, so return + if (*lockIter == path) + return; + } + m_lockedPrims.insert(lockIter, path); + + auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); + if (unlockIter != m_unlockedPrims.end()) { + if (*unlockIter == path) { + m_unlockedPrims.erase(unlockIter); + } } - } } //---------------------------------------------------------------------------------------------------------------------- void LockManager::setUnlocked(const SdfPath& path) { - auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); - if(unlockIter != m_unlockedPrims.end()) - { - // lock already in the locked array, so return - if(*unlockIter == path) - return; - } - m_unlockedPrims.insert(unlockIter, path); - - auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); - if(lockIter != m_lockedPrims.end()) - { - if(*lockIter == path) - { - m_lockedPrims.erase(lockIter); + auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); + if (unlockIter != m_unlockedPrims.end()) { + // lock already in the locked array, so return + if (*unlockIter == path) + return; + } + m_unlockedPrims.insert(unlockIter, path); + + auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); + if (lockIter != m_lockedPrims.end()) { + if (*lockIter == path) { + m_lockedPrims.erase(lockIter); + } } - } } //---------------------------------------------------------------------------------------------------------------------- void LockManager::setInherited(const SdfPath& path) { - if(!m_unlockedPrims.empty()) - { - auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); - if(unlockIter != m_unlockedPrims.end()) - { - // lock already in the locked array, so return - if(*unlockIter == path) - { - m_unlockedPrims.erase(unlockIter); - } + if (!m_unlockedPrims.empty()) { + auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); + if (unlockIter != m_unlockedPrims.end()) { + // lock already in the locked array, so return + if (*unlockIter == path) { + m_unlockedPrims.erase(unlockIter); + } + } } - } - if(!m_lockedPrims.empty()) - { - auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); - if(lockIter != m_lockedPrims.end()) - { - // lock already in the locked array, so return - if(*lockIter == path) - { - m_lockedPrims.erase(lockIter); - } + if (!m_lockedPrims.empty()) { + auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); + if (lockIter != m_lockedPrims.end()) { + // lock already in the locked array, so return + if (*lockIter == path) { + m_lockedPrims.erase(lockIter); + } + } } - } } //---------------------------------------------------------------------------------------------------------------------- bool LockManager::isLocked(const SdfPath& path) const { - if(m_lockedPrims.empty()) - return false; + if (m_lockedPrims.empty()) + return false; - auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); + auto lockIter = std::lower_bound(m_lockedPrims.begin(), m_lockedPrims.end(), path); - // first check the edge case where this path is in the locked set - if(lockIter != m_lockedPrims.end() && *lockIter == path) - { - return true; - } + // first check the edge case where this path is in the locked set + if (lockIter != m_lockedPrims.end() && *lockIter == path) { + return true; + } - // now attempt to see if a parent of this path is in the locked set - bool hasLockedParent = false; - if(lockIter != m_lockedPrims.begin()) - { - --lockIter; - { - if(path.HasPrefix(*lockIter)) - { - hasLockedParent = true; - } + // now attempt to see if a parent of this path is in the locked set + bool hasLockedParent = false; + if (lockIter != m_lockedPrims.begin()) { + --lockIter; + { + if (path.HasPrefix(*lockIter)) { + hasLockedParent = true; + } + } } - } - // now attempt to see if a parent of this path is in the unlocked set - bool hasUnlockedParent = false; - auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); + // now attempt to see if a parent of this path is in the unlocked set + bool hasUnlockedParent = false; + auto unlockIter = std::lower_bound(m_unlockedPrims.begin(), m_unlockedPrims.end(), path); - // first check the edge case where this path is in the locked set - if(unlockIter != m_unlockedPrims.end() && *unlockIter == path) - { - return false; - } + // first check the edge case where this path is in the locked set + if (unlockIter != m_unlockedPrims.end() && *unlockIter == path) { + return false; + } - if(unlockIter != m_unlockedPrims.begin()) - { - --unlockIter; - { - if(path.HasPrefix(*unlockIter)) - { - hasUnlockedParent = true; - } + if (unlockIter != m_unlockedPrims.begin()) { + --unlockIter; + { + if (path.HasPrefix(*unlockIter)) { + hasUnlockedParent = true; + } + } } - } - - // if we have entries in both the locked and unlocked set..... - if(hasLockedParent && hasUnlockedParent) - { - // if the locked path is longer than the unlocked path, the closest parent to path is locked. - return (lockIter->GetString().size() >= unlockIter->GetString().size()); - } - else - if(hasLockedParent) - { - return true; - } - - // either the parent is unlocked, or no entry exists at all (treat as unlocked). - return false; + + // if we have entries in both the locked and unlocked set..... + if (hasLockedParent && hasUnlockedParent) { + // if the locked path is longer than the unlocked path, the closest parent to path is + // locked. + return (lockIter->GetString().size() >= unlockIter->GetString().size()); + } else if (hasLockedParent) { + return true; + } + + // either the parent is unlocked, or no entry exists at all (treat as unlocked). + return false; } //---------------------------------------------------------------------------------------------------------------------- -} // proxy -} // nodes -} // usdmaya -} // AL +} // namespace proxy +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/LockManager.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/LockManager.h index 6286cd4e94..2945ba04c3 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/LockManager.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/LockManager.h @@ -31,68 +31,73 @@ namespace proxy { //---------------------------------------------------------------------------------------------------------------------- struct LockManager { - /// \brief removes the specified paths from the locked and unlocked sets - /// \param entries the array of entires to remove. - AL_USDMAYA_PUBLIC - void removeEntries(const SdfPathVector& entries); + /// \brief removes the specified paths from the locked and unlocked sets + /// \param entries the array of entires to remove. + AL_USDMAYA_PUBLIC + void removeEntries(const SdfPathVector& entries); - /// \brief removes all entries from the locked and unlocked sets that are a child of the specified path - /// \param path the root path to remove - AL_USDMAYA_PUBLIC - void removeFromRootPath(const SdfPath& path); + /// \brief removes all entries from the locked and unlocked sets that are a child of the + /// specified path \param path the root path to remove + AL_USDMAYA_PUBLIC + void removeFromRootPath(const SdfPath& path); - /// \brief sets the specified path as locked (and any paths that inherit their state from their parent). - /// If the path exists within the unlocked set, it will be removed. - /// \param path the path to insert into the locked set - AL_USDMAYA_PUBLIC - void setLocked(const SdfPath& path); + /// \brief sets the specified path as locked (and any paths that inherit their state from their + /// parent). + /// If the path exists within the unlocked set, it will be removed. + /// \param path the path to insert into the locked set + AL_USDMAYA_PUBLIC + void setLocked(const SdfPath& path); - /// \brief sets the specified path as unlocked (and any paths that inherit their state from their parent). - /// If the path exists within the locked set, it will be removed. - /// \param path the path to insert into the unlocked set - AL_USDMAYA_PUBLIC - void setUnlocked(const SdfPath& path); + /// \brief sets the specified path as unlocked (and any paths that inherit their state from + /// their parent). + /// If the path exists within the locked set, it will be removed. + /// \param path the path to insert into the unlocked set + AL_USDMAYA_PUBLIC + void setUnlocked(const SdfPath& path); - /// \brief adds the specified path to the locked prims list. No checking is done by this method to see whether - /// the path is part of the locked or unlocked sets. The intention for this method is to quickly - /// build up changes in the set of lock prims, and having done that, later sort them by calling sort() - /// \param path the path to insert into the locked set - inline void addLocked(const SdfPath& path) - { m_lockedPrims.emplace_back(path); } + /// \brief adds the specified path to the locked prims list. No checking is done by this method + /// to see whether + /// the path is part of the locked or unlocked sets. The intention for this method is to + /// quickly build up changes in the set of lock prims, and having done that, later sort + /// them by calling sort() + /// \param path the path to insert into the locked set + inline void addLocked(const SdfPath& path) { m_lockedPrims.emplace_back(path); } - /// \brief adds the specified path to the unlocked prims list. No checking is done by this method to see whether - /// the path is part of the locked or unlocked sets. The intention for this method is to quickly - /// build up changes in the set of lock prims, and having done that, later sort them by calling sort() - /// \param path the path to insert into the unlocked set - inline void addUnlocked(const SdfPath& path) - { m_unlockedPrims.emplace_back(path); } + /// \brief adds the specified path to the unlocked prims list. No checking is done by this + /// method to see whether + /// the path is part of the locked or unlocked sets. The intention for this method is to + /// quickly build up changes in the set of lock prims, and having done that, later sort + /// them by calling sort() + /// \param path the path to insert into the unlocked set + inline void addUnlocked(const SdfPath& path) { m_unlockedPrims.emplace_back(path); } - /// \brief sorts the two sets of locked and unlocked prims for fast lookup - inline void sort() + /// \brief sorts the two sets of locked and unlocked prims for fast lookup + inline void sort() { - std::sort(m_lockedPrims.begin(), m_lockedPrims.end()); - std::sort(m_unlockedPrims.begin(), m_unlockedPrims.end()); + std::sort(m_lockedPrims.begin(), m_lockedPrims.end()); + std::sort(m_unlockedPrims.begin(), m_unlockedPrims.end()); } - /// \brief Will remove the path from both the locked and unlocked sets. The lock status will now be inherited. - /// \param path the path to set as inherited - AL_USDMAYA_PUBLIC - void setInherited(const SdfPath& path); + /// \brief Will remove the path from both the locked and unlocked sets. The lock status will + /// now be inherited. \param path the path to set as inherited + AL_USDMAYA_PUBLIC + void setInherited(const SdfPath& path); - /// \brief a query function to determine whether the specified path is locked or not. - /// \param path the path to query the lock status for - /// \return true if the prim is locked (either by explicitly being set as locked, or by inheriting a lock status) - AL_USDMAYA_PUBLIC - bool isLocked(const SdfPath& path) const; + /// \brief a query function to determine whether the specified path is locked or not. + /// \param path the path to query the lock status for + /// \return true if the prim is locked (either by explicitly being set as locked, or by + /// inheriting a lock status) + AL_USDMAYA_PUBLIC + bool isLocked(const SdfPath& path) const; private: - SdfPathVector m_lockedPrims; - SdfPathVector m_unlockedPrims; + SdfPathVector m_lockedPrims; + SdfPathVector m_unlockedPrims; }; //---------------------------------------------------------------------------------------------------------------------- -} // proxy -} // nodes -} // usdmaya -} // AL +} // namespace proxy +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/PrimFilter.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/PrimFilter.cpp index 6414eb88bc..031853beb9 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/PrimFilter.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/PrimFilter.cpp @@ -13,9 +13,10 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/nodes/ProxyShape.h" #include "AL/usdmaya/nodes/proxy/PrimFilter.h" + #include "AL/usdmaya/fileio/SchemaPrims.h" +#include "AL/usdmaya/nodes/ProxyShape.h" namespace AL { namespace usdmaya { @@ -24,110 +25,113 @@ namespace proxy { //---------------------------------------------------------------------------------------------------------------------- PrimFilter::PrimFilter( - const SdfPathVector& previousPrims, - const std::vector& newPrimSet, - PrimFilterInterface* proxy, - bool forceImport) - : m_newPrimSet(newPrimSet), m_transformsToCreate(), m_updatablePrimSet(), m_removedPrimSet() + const SdfPathVector& previousPrims, + const std::vector& newPrimSet, + PrimFilterInterface* proxy, + bool forceImport) + : m_newPrimSet(newPrimSet) + , m_transformsToCreate() + , m_updatablePrimSet() + , m_removedPrimSet() { - // copy over original prims - m_removedPrimSet.assign(previousPrims.begin(), previousPrims.end()); - std::sort(m_removedPrimSet.begin(), m_removedPrimSet.end(), [](const SdfPath& a, const SdfPath& b){ return b < a; } ); + // copy over original prims + m_removedPrimSet.assign(previousPrims.begin(), previousPrims.end()); + std::sort( + m_removedPrimSet.begin(), m_removedPrimSet.end(), [](const SdfPath& a, const SdfPath& b) { + return b < a; + }); - for(auto it = m_newPrimSet.begin(); it != m_newPrimSet.end(); ) - { - UsdPrim prim = *it; - auto lastIt = it; - ++it; + for (auto it = m_newPrimSet.begin(); it != m_newPrimSet.end();) { + UsdPrim prim = *it; + auto lastIt = it; + ++it; - SdfPath path = prim.GetPath(); + SdfPath path = prim.GetPath(); - // check previous prim type (if it exists at all?) - std::string existingTranslatorId = proxy->getTranslatorIdForPath(path); - - std::string newTranslatorId = proxy->generateTranslatorId(prim); + // check previous prim type (if it exists at all?) + std::string existingTranslatorId = proxy->getTranslatorIdForPath(path); - // inactive prims should be removed - if (!prim.IsActive()) - { - it = m_newPrimSet.erase(lastIt); - continue; - } + std::string newTranslatorId = proxy->generateTranslatorId(prim); - bool supportsUpdate = false; - bool requiresParent = false; - bool importableByDefault = false; - proxy->getTranslatorInfo(newTranslatorId, supportsUpdate, requiresParent, importableByDefault); - - if(importableByDefault || forceImport) - { - // if the type remains the same, and the type supports update - if(existingTranslatorId == newTranslatorId) - { - // locate the path and delete from the removed set (we do not want to delete this prim! - // Note that m_removedPrimSet is reverse sorted - auto iter = std::lower_bound(m_removedPrimSet.begin(), m_removedPrimSet.end(), path, [](const SdfPath& a, const SdfPath& b){ return b < a; } ); - if(iter != removedPrimSet().end() && *iter == path) - { - if (supportsUpdate) - { - m_removedPrimSet.erase(iter); - if (proxy->isPrimDirty(prim)) - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg( - "PrimFilter::PrimFilter %s prim will be updated.\n", path.GetText()); - m_updatablePrimSet.push_back(prim); - } - else - { - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg( - "PrimFilter::PrimFilter %s prim remains unchanged.\n", path.GetText()); - } - // supporting update means it's not a new prim, - // otherwise we still want the prim to be re-created. + // inactive prims should be removed + if (!prim.IsActive()) { it = m_newPrimSet.erase(lastIt); + continue; + } - // skip creating transforms in this case. - requiresParent = false; - } - else - { - if (proxy->isPrimDirty(prim)) - { - // prim has been added in "remove prim set", nothing to do here - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg( - "PrimFilter::PrimFilter %s prim will be removed and recreated.\n", path.GetText()); - } - else - { - // prim is clean, no need to remove nor recreate - TF_DEBUG(ALUSDMAYA_TRANSLATORS).Msg( - "PrimFilter::PrimFilter %s prim remains unchanged.\n", path.GetText()); + bool supportsUpdate = false; + bool requiresParent = false; + bool importableByDefault = false; + proxy->getTranslatorInfo( + newTranslatorId, supportsUpdate, requiresParent, importableByDefault); + + if (importableByDefault || forceImport) { + // if the type remains the same, and the type supports update + if (existingTranslatorId == newTranslatorId) { + // locate the path and delete from the removed set (we do not want to delete this + // prim! Note that m_removedPrimSet is reverse sorted + auto iter = std::lower_bound( + m_removedPrimSet.begin(), + m_removedPrimSet.end(), + path, + [](const SdfPath& a, const SdfPath& b) { return b < a; }); + if (iter != removedPrimSet().end() && *iter == path) { + if (supportsUpdate) { + m_removedPrimSet.erase(iter); + if (proxy->isPrimDirty(prim)) { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "PrimFilter::PrimFilter %s prim will be updated.\n", + path.GetText()); + m_updatablePrimSet.push_back(prim); + } else { + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "PrimFilter::PrimFilter %s prim remains unchanged.\n", + path.GetText()); + } + // supporting update means it's not a new prim, + // otherwise we still want the prim to be re-created. + it = m_newPrimSet.erase(lastIt); + + // skip creating transforms in this case. + requiresParent = false; + } else { + if (proxy->isPrimDirty(prim)) { + // prim has been added in "remove prim set", nothing to do here + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "PrimFilter::PrimFilter %s prim will be removed and " + "recreated.\n", + path.GetText()); + } else { + // prim is clean, no need to remove nor recreate + TF_DEBUG(ALUSDMAYA_TRANSLATORS) + .Msg( + "PrimFilter::PrimFilter %s prim remains unchanged.\n", + path.GetText()); - m_removedPrimSet.erase(iter); - it = m_newPrimSet.erase(lastIt); - // skip creating transforms in this case. - requiresParent = false; + m_removedPrimSet.erase(iter); + it = m_newPrimSet.erase(lastIt); + // skip creating transforms in this case. + requiresParent = false; + } + } + } } - } + // if we need a transform, make a note of it now + if (requiresParent) { + m_transformsToCreate.push_back(prim); + } + } else { + it = m_newPrimSet.erase(lastIt); } - } - // if we need a transform, make a note of it now - if(requiresParent) - { - m_transformsToCreate.push_back(prim); - } - } - else - { - it = m_newPrimSet.erase(lastIt); } - } } //---------------------------------------------------------------------------------------------------------------------- -} // proxy -} // nodes -} // usdmaya -} // AL +} // namespace proxy +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/PrimFilter.h b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/PrimFilter.h index 2bc2b38daa..eebcc92625 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/PrimFilter.h +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/PrimFilter.h @@ -16,11 +16,12 @@ #pragma once #include -#include #include #include +#include + #include PXR_NAMESPACE_USING_DIRECTIVE @@ -31,36 +32,45 @@ namespace nodes { namespace proxy { //---------------------------------------------------------------------------------------------------------------------- -/// \brief The prim filter needs to know about some state provided in the proxy shape node. In order to maintain a -/// separation between the filter and the proxy (so that it's easy to test!), this class acts as a bridge between -/// the two. +/// \brief The prim filter needs to know about some state provided in the proxy shape node. In +/// order to maintain a +/// separation between the filter and the proxy (so that it's easy to test!), this class +/// acts as a bridge between the two. //---------------------------------------------------------------------------------------------------------------------- struct PrimFilterInterface { - /// \brief Given a path to a prim, this method will return some translator type information for the prim found at that path, - /// which the proxy shape has previously cached (i.e. the old state of the prim prior to a variant switch). - /// If the proxy shape is aware of the prim, and the returned info is valid, true will be returned. If the - /// proxy shape is unaware of the prim (i.e. a variant switch has created it), then false will be returned. - /// \param path the path to the prim we are querying - /// \return the translatorId string, or an empty string if unknown type - virtual std::string getTranslatorIdForPath(const SdfPath& path) = 0; - - /// \brief for a specific translator, this method should return whether it supports update, and if that translator requires a - /// DAG path to be created. - /// \param translatorId the translator to query - /// \param supportsUpdate returned value that indicates if the translator in question can be updated - /// \param requiresParent returned value that indicates whether the translator in question needs a DAG path to be created - /// \param importableByDefault returned value that indicates whether the prim needs to be forced into being - /// \return returns false if the translator is unknown, true otherwise - virtual bool getTranslatorInfo(const std::string& translatorId, bool& supportsUpdate, bool& requiresParent, bool& importableByDefault) = 0; - - - virtual std::string generateTranslatorId(UsdPrim prim) = 0; - - /// \brief check if a prim is dirty. - /// \param prim the prim to check. - /// \return returns true if yes, false otherwise. - virtual bool isPrimDirty(const UsdPrim& prim) = 0; + /// \brief Given a path to a prim, this method will return some translator type information for + /// the prim found at that path, + /// which the proxy shape has previously cached (i.e. the old state of the prim prior to + /// a variant switch). If the proxy shape is aware of the prim, and the returned info is + /// valid, true will be returned. If the proxy shape is unaware of the prim (i.e. a + /// variant switch has created it), then false will be returned. + /// \param path the path to the prim we are querying + /// \return the translatorId string, or an empty string if unknown type + virtual std::string getTranslatorIdForPath(const SdfPath& path) = 0; + + /// \brief for a specific translator, this method should return whether it supports update, and + /// if that translator requires a + /// DAG path to be created. + /// \param translatorId the translator to query + /// \param supportsUpdate returned value that indicates if the translator in question can be + /// updated \param requiresParent returned value that indicates whether the translator in + /// question needs a DAG path to be created \param importableByDefault returned value that + /// indicates whether the prim needs to be forced into being \return returns false if the + /// translator is unknown, true otherwise + virtual bool getTranslatorInfo( + const std::string& translatorId, + bool& supportsUpdate, + bool& requiresParent, + bool& importableByDefault) + = 0; + + virtual std::string generateTranslatorId(UsdPrim prim) = 0; + + /// \brief check if a prim is dirty. + /// \param prim the prim to check. + /// \return returns true if yes, false otherwise. + virtual bool isPrimDirty(const UsdPrim& prim) = 0; }; //---------------------------------------------------------------------------------------------------------------------- @@ -69,42 +79,40 @@ struct PrimFilterInterface class PrimFilter { public: - - /// \brief constructor constructs the prim filter - /// \param previousPrims the previous set of prims that existed in the stage - /// \param newPrimSet the new set of prims that have been created - /// \param proxy the proxy shape - /// \param forceImport mirrors the status of the -fi flag - AL_USDMAYA_PUBLIC - PrimFilter(const SdfPathVector& previousPrims, const MayaUsdUtils::UsdPrimVector& newPrimSet, PrimFilterInterface* proxy, bool forceImport = false); - - /// \brief returns the set of prims to create - inline const std::vector& newPrimSet() const - { return m_newPrimSet; } - - /// \brief returns the set of prims that require created transforms - inline const std::vector& transformsToCreate() const - { return m_transformsToCreate; } - - /// \brief returns the list of prims that needs to be updated - inline const std::vector& updatablePrimSet() const - { return m_updatablePrimSet; } - - /// \brief returns the list of prims that have been removed from the stage - inline const SdfPathVector& removedPrimSet() const - { return m_removedPrimSet; } + /// \brief constructor constructs the prim filter + /// \param previousPrims the previous set of prims that existed in the stage + /// \param newPrimSet the new set of prims that have been created + /// \param proxy the proxy shape + /// \param forceImport mirrors the status of the -fi flag + AL_USDMAYA_PUBLIC + PrimFilter( + const SdfPathVector& previousPrims, + const MayaUsdUtils::UsdPrimVector& newPrimSet, + PrimFilterInterface* proxy, + bool forceImport = false); + + /// \brief returns the set of prims to create + inline const std::vector& newPrimSet() const { return m_newPrimSet; } + + /// \brief returns the set of prims that require created transforms + inline const std::vector& transformsToCreate() const { return m_transformsToCreate; } + + /// \brief returns the list of prims that needs to be updated + inline const std::vector& updatablePrimSet() const { return m_updatablePrimSet; } + + /// \brief returns the list of prims that have been removed from the stage + inline const SdfPathVector& removedPrimSet() const { return m_removedPrimSet; } private: - std::vector m_newPrimSet; - std::vector m_transformsToCreate; - std::vector m_updatablePrimSet; - SdfPathVector m_removedPrimSet; + std::vector m_newPrimSet; + std::vector m_transformsToCreate; + std::vector m_updatablePrimSet; + SdfPathVector m_removedPrimSet; }; //---------------------------------------------------------------------------------------------------------------------- -} // proxy -} // nodes -} // usdmaya -} // AL +} // namespace proxy +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/ProxyShapeMetaData.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/ProxyShapeMetaData.cpp index a95ce0b1f3..975b044baa 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/ProxyShapeMetaData.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/ProxyShapeMetaData.cpp @@ -14,384 +14,331 @@ // limitations under the License. // -#include "AL/usdmaya/nodes/ProxyShape.h" -#include "AL/usdmaya/nodes/Transform.h" #include "AL/usdmaya/Metadata.h" #include "AL/usdmaya/fileio/SchemaPrims.h" #include "AL/usdmaya/fileio/TransformIterator.h" +#include "AL/usdmaya/nodes/ProxyShape.h" +#include "AL/usdmaya/nodes/Transform.h" namespace AL { namespace usdmaya { namespace nodes { - //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::removeMetaData(const SdfPathVector& removedPaths) { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::removeMetaData"); + TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::removeMetaData"); - m_selectabilityDB.removePathsAsUnselectable(removedPaths); - m_lockManager.removeEntries(removedPaths); + m_selectabilityDB.removePathsAsUnselectable(removedPaths); + m_lockManager.removeEntries(removedPaths); } //---------------------------------------------------------------------------------------------------------------------- -void ProxyShape::processChangedMetaData(const SdfPathVector& resyncedPaths, const SdfPathVector& changedOnlyPaths) +void ProxyShape::processChangedMetaData( + const SdfPathVector& resyncedPaths, + const SdfPathVector& changedOnlyPaths) { - TF_DEBUG(ALUSDMAYA_EVENTS).Msg("ProxyShape::processChangedMetaData - processing changes %lu %lu\n", resyncedPaths.size(), changedOnlyPaths.size()); - - // if this is just a data change (rather than a variant switch), check for any meta data changes - if(m_variantSwitchedPrims.empty()) - { - // figure out whether selectability has changed. - for(const SdfPath& path : changedOnlyPaths) - { - UsdPrim changedPrim = m_stage->GetPrimAtPath(path); - if(!changedPrim) - { - continue; - } - - TfToken selectabilityPropertyToken; - if(changedPrim.GetMetadata(Metadata::selectability, &selectabilityPropertyToken)) - { - bool hasPath = m_selectabilityDB.containsPath(path); - //Check if this prim is unselectable - if(selectabilityPropertyToken == Metadata::unselectable) - { - if(!hasPath) - { - m_selectabilityDB.addPathAsUnselectable(path); - } - } - if(hasPath) - { - m_selectabilityDB.removePathAsUnselectable(path); - } - } - - // build up new lock-prim list - TfToken lockPropertyToken; - if (changedPrim.GetMetadata(Metadata::locked, & lockPropertyToken)) - { - if (lockPropertyToken == Metadata::lockTransform) - { - m_lockManager.setLocked(path); - } - else - if (lockPropertyToken == Metadata::lockUnlocked) - { - m_lockManager.setUnlocked(path); - } - else - { - m_lockManager.setInherited(path); - } - } - else - { - m_lockManager.setInherited(path); - } - } - m_lockManager.sort(); - } - else - { - auto& unselectablePaths = m_selectabilityDB.m_unselectablePaths; - - // figure out whether selectability has changed. - for(const SdfPath& path : resyncedPaths) - { - UsdPrim syncPrimRoot = m_stage->GetPrimAtPath(path); - if(!syncPrimRoot) - { - // TODO : Ensure elements have been removed from selectabilityDB, excludeGeom, and lock prims - continue; - } - - // determine range of selectable prims we need to replace in the selectability DB - auto lb = std::lower_bound(unselectablePaths.begin(), unselectablePaths.end(), path); - auto ub = lb; - if(lb != unselectablePaths.end()) - { - while(ub != unselectablePaths.end() && ub->HasPrefix(*lb)) - { - ++ub; - } - } - - m_lockManager.removeFromRootPath(path); - - // sort the excluded tagged geom to help searching - std::sort(m_excludedTaggedGeometry.begin(), m_excludedTaggedGeometry.end()); - - // fill these lists as we traverse - SdfPathVector newUnselectables; - SdfPathVector newExcludeGeom; - - // keep track of where the last item in the original set of prims is. - // As we traverse, lookups will be performed on the first elements in the array, so that - // will remain sorted. Items appended to the end of the array will not be sorted. - // In order to do this without using a 2nd vector, I'm using the lastTaggedPrim to denote - // the boundary between the sorted and unsorted prims - size_t lastTaggedPrim = m_excludedTaggedGeometry.size(); - - // from the resync prim, traverse downwards through the child prims - for(fileio::TransformIterator it(syncPrimRoot, parentTransform(), true); !it.done(); it.next()) - { - auto prim = it.prim(); - auto path = prim.GetPath(); - - // first check to see if the excluded geom has changed - { - bool excludeGeo = false; - if(prim.GetMetadata(Metadata::excludeFromProxyShape, &excludeGeo) && excludeGeo) - { - auto last = m_excludedTaggedGeometry.begin() + lastTaggedPrim; - auto it = std::lower_bound(m_excludedTaggedGeometry.begin(), last, path); - if(it != last && *it == path) - { - // we already have an entry for this prim + TF_DEBUG(ALUSDMAYA_EVENTS) + .Msg( + "ProxyShape::processChangedMetaData - processing changes %lu %lu\n", + resyncedPaths.size(), + changedOnlyPaths.size()); + + // if this is just a data change (rather than a variant switch), check for any meta data changes + if (m_variantSwitchedPrims.empty()) { + // figure out whether selectability has changed. + for (const SdfPath& path : changedOnlyPaths) { + UsdPrim changedPrim = m_stage->GetPrimAtPath(path); + if (!changedPrim) { + continue; } - else - { - // add to back of list - m_excludedTaggedGeometry.emplace_back(path); - } - } - else - { - // if we aren't excluding the geom, but have an existing entry, remove it. - auto last = m_excludedTaggedGeometry.begin() + lastTaggedPrim; - auto it = std::lower_bound(m_excludedTaggedGeometry.begin(), last, path); - if(it != last && *it == path) - { - m_excludedTaggedGeometry.erase(it); - --lastTaggedPrim; - } - } - - // If prim has exclusion tag or is a descendent of a prim with it, create as Maya geo - if (excludeGeo || primHasExcludedParent(prim)) - { - VtValue schemaName(fileio::ALExcludedPrimSchema.GetString()); - prim.SetCustomDataByKey(fileio::ALSchemaType, schemaName); - } - } - // build up new unselectable list - TfToken selectabilityPropertyToken; - if(prim.GetMetadata(Metadata::selectability, &selectabilityPropertyToken)) - { - if(selectabilityPropertyToken == Metadata::unselectable) - { - newUnselectables.emplace_back(path); - } - } + TfToken selectabilityPropertyToken; + if (changedPrim.GetMetadata( + Metadata::selectability, &selectabilityPropertyToken)) { + bool hasPath = m_selectabilityDB.containsPath(path); + // Check if this prim is unselectable + if (selectabilityPropertyToken == Metadata::unselectable) { + if (!hasPath) { + m_selectabilityDB.addPathAsUnselectable(path); + } + } + if (hasPath) { + m_selectabilityDB.removePathAsUnselectable(path); + } + } - // build up new lock-prim list - TfToken lockPropertyToken; - if (prim.GetMetadata(Metadata::locked, &lockPropertyToken)) - { - if (lockPropertyToken == Metadata::lockTransform) - { - m_lockManager.addLocked(path); - } - else - if (lockPropertyToken == Metadata::lockUnlocked) - { - m_lockManager.addUnlocked(path); - } + // build up new lock-prim list + TfToken lockPropertyToken; + if (changedPrim.GetMetadata(Metadata::locked, &lockPropertyToken)) { + if (lockPropertyToken == Metadata::lockTransform) { + m_lockManager.setLocked(path); + } else if (lockPropertyToken == Metadata::lockUnlocked) { + m_lockManager.setUnlocked(path); + } else { + m_lockManager.setInherited(path); + } + } else { + m_lockManager.setInherited(path); + } } - } + m_lockManager.sort(); + } else { + auto& unselectablePaths = m_selectabilityDB.m_unselectablePaths; + + // figure out whether selectability has changed. + for (const SdfPath& path : resyncedPaths) { + UsdPrim syncPrimRoot = m_stage->GetPrimAtPath(path); + if (!syncPrimRoot) { + // TODO : Ensure elements have been removed from selectabilityDB, excludeGeom, and + // lock prims + continue; + } - m_lockManager.sort(); + // determine range of selectable prims we need to replace in the selectability DB + auto lb = std::lower_bound(unselectablePaths.begin(), unselectablePaths.end(), path); + auto ub = lb; + if (lb != unselectablePaths.end()) { + while (ub != unselectablePaths.end() && ub->HasPrefix(*lb)) { + ++ub; + } + } - // sort and merge into previous selectable database - std::sort(newUnselectables.begin(), newUnselectables.end()); + m_lockManager.removeFromRootPath(path); + + // sort the excluded tagged geom to help searching + std::sort(m_excludedTaggedGeometry.begin(), m_excludedTaggedGeometry.end()); + + // fill these lists as we traverse + SdfPathVector newUnselectables; + SdfPathVector newExcludeGeom; + + // keep track of where the last item in the original set of prims is. + // As we traverse, lookups will be performed on the first elements in the array, so that + // will remain sorted. Items appended to the end of the array will not be sorted. + // In order to do this without using a 2nd vector, I'm using the lastTaggedPrim to + // denote the boundary between the sorted and unsorted prims + size_t lastTaggedPrim = m_excludedTaggedGeometry.size(); + + // from the resync prim, traverse downwards through the child prims + for (fileio::TransformIterator it(syncPrimRoot, parentTransform(), true); !it.done(); + it.next()) { + auto prim = it.prim(); + auto path = prim.GetPath(); + + // first check to see if the excluded geom has changed + { + bool excludeGeo = false; + if (prim.GetMetadata(Metadata::excludeFromProxyShape, &excludeGeo) + && excludeGeo) { + auto last = m_excludedTaggedGeometry.begin() + lastTaggedPrim; + auto it = std::lower_bound(m_excludedTaggedGeometry.begin(), last, path); + if (it != last && *it == path) { + // we already have an entry for this prim + } else { + // add to back of list + m_excludedTaggedGeometry.emplace_back(path); + } + } else { + // if we aren't excluding the geom, but have an existing entry, remove it. + auto last = m_excludedTaggedGeometry.begin() + lastTaggedPrim; + auto it = std::lower_bound(m_excludedTaggedGeometry.begin(), last, path); + if (it != last && *it == path) { + m_excludedTaggedGeometry.erase(it); + --lastTaggedPrim; + } + } + + // If prim has exclusion tag or is a descendent of a prim with it, create as + // Maya geo + if (excludeGeo || primHasExcludedParent(prim)) { + VtValue schemaName(fileio::ALExcludedPrimSchema.GetString()); + prim.SetCustomDataByKey(fileio::ALSchemaType, schemaName); + } + } + + // build up new unselectable list + TfToken selectabilityPropertyToken; + if (prim.GetMetadata( + Metadata::selectability, &selectabilityPropertyToken)) { + if (selectabilityPropertyToken == Metadata::unselectable) { + newUnselectables.emplace_back(path); + } + } + + // build up new lock-prim list + TfToken lockPropertyToken; + if (prim.GetMetadata(Metadata::locked, &lockPropertyToken)) { + if (lockPropertyToken == Metadata::lockTransform) { + m_lockManager.addLocked(path); + } else if (lockPropertyToken == Metadata::lockUnlocked) { + m_lockManager.addUnlocked(path); + } + } + } - if(lb == unselectablePaths.end()) - { - if(!newUnselectables.empty()) - { - unselectablePaths.insert(unselectablePaths.end(), newUnselectables.begin(), newUnselectables.end()); - } - } - else - { - // TODO: could probably overwrite some of old paths here, and then insert the remaining new elements. - lb = unselectablePaths.erase(lb, ub); - if(!newUnselectables.empty()) - { - unselectablePaths.insert(lb, newUnselectables.begin(), newUnselectables.end()); + m_lockManager.sort(); + + // sort and merge into previous selectable database + std::sort(newUnselectables.begin(), newUnselectables.end()); + + if (lb == unselectablePaths.end()) { + if (!newUnselectables.empty()) { + unselectablePaths.insert( + unselectablePaths.end(), newUnselectables.begin(), newUnselectables.end()); + } + } else { + // TODO: could probably overwrite some of old paths here, and then insert the + // remaining new elements. + lb = unselectablePaths.erase(lb, ub); + if (!newUnselectables.empty()) { + unselectablePaths.insert(lb, newUnselectables.begin(), newUnselectables.end()); + } + } } - } } - } - // reconstruct the lock prims - { - constructLockPrims(); - } + // reconstruct the lock prims + { + constructLockPrims(); + } } - //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::constructExcludedPrims() { - auto excludedPaths = getExcludePrimPaths(); - if (m_excludedGeometry != excludedPaths) - { - std::swap(m_excludedGeometry, excludedPaths); - constructGLImagingEngine(); - } + auto excludedPaths = getExcludePrimPaths(); + if (m_excludedGeometry != excludedPaths) { + std::swap(m_excludedGeometry, excludedPaths); + constructGLImagingEngine(); + } } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::constructLockPrims() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::constructLockPrims\n"); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::constructLockPrims\n"); - // iterate over the - for(auto it : m_requiredPaths) - { - Scope* s = it.second.getTransformNode(); - if(!s) - { - continue; - } + // iterate over the + for (auto it : m_requiredPaths) { + Scope* s = it.second.getTransformNode(); + if (!s) { + continue; + } - const UsdPrim& prim = s->transform()->prim(); - if(prim) - { - bool is_locked = m_lockManager.isLocked(prim.GetPath()); + const UsdPrim& prim = s->transform()->prim(); + if (prim) { + bool is_locked = m_lockManager.isLocked(prim.GetPath()); - MObject lockObject = s->thisMObject(); + MObject lockObject = s->thisMObject(); - MPlug t(lockObject, m_transformTranslate); - MPlug r(lockObject, m_transformRotate); - MPlug s(lockObject, m_transformScale); + MPlug t(lockObject, m_transformTranslate); + MPlug r(lockObject, m_transformRotate); + MPlug s(lockObject, m_transformScale); - t.setLocked(is_locked); - r.setLocked(is_locked); - s.setLocked(is_locked); + t.setLocked(is_locked); + r.setLocked(is_locked); + s.setLocked(is_locked); - if(is_locked) - { - MFnDependencyNode fn(lockObject); - Transform* transformNode = dynamic_cast(fn.userNode()); - if (transformNode) - { - MPlug plug(lockObject, Transform::pushToPrim()); - if(plug.asBool()) plug.setBool(false); + if (is_locked) { + MFnDependencyNode fn(lockObject); + Transform* transformNode = dynamic_cast(fn.userNode()); + if (transformNode) { + MPlug plug(lockObject, Transform::pushToPrim()); + if (plug.asBool()) + plug.setBool(false); + } + } } - } } - } } //---------------------------------------------------------------------------------------------------------------------- bool ProxyShape::primHasExcludedParent(UsdPrim prim) { - if(prim.IsValid()) - { - SdfPath primPath = prim.GetPrimPath(); - TF_FOR_ALL(excludedPath, m_excludedTaggedGeometry) - { - if (primPath.HasPrefix(*excludedPath)) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::primHasExcludedParent %s=true\n", primPath.GetText()); - return true; - } + if (prim.IsValid()) { + SdfPath primPath = prim.GetPrimPath(); + TF_FOR_ALL(excludedPath, m_excludedTaggedGeometry) + { + if (primPath.HasPrefix(*excludedPath)) { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg("ProxyShape::primHasExcludedParent %s=true\n", primPath.GetText()); + return true; + } + } } - } - return false; + return false; } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::findPrimsWithMetaData() { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::findPrimsWithMetaData\n"); - if(!m_stage) - return; - - if(isLockPrimFeatureActive()) - { - SdfPathVector newUnselectables; - for(fileio::TransformIterator it(m_stage, parentTransform(), true); !it.done(); it.next()) - { - auto prim = it.prim(); - bool excludeGeo = false; - if(prim.GetMetadata(Metadata::excludeFromProxyShape, &excludeGeo)) - { - if (excludeGeo) - { - m_excludedTaggedGeometry.push_back(prim.GetPrimPath()); - } - } - - // If prim has exclusion tag or is a descendent of a prim with it, create as Maya geo - if (excludeGeo || primHasExcludedParent(prim)) - { - VtValue schemaName(fileio::ALExcludedPrimSchema.GetString()); - prim.SetCustomDataByKey(fileio::ALSchemaType, schemaName); - } - - TfToken selectabilityPropertyToken; - if(prim.GetMetadata(Metadata::selectability, &selectabilityPropertyToken)) - { - //Check if this prim is unselectable - if(selectabilityPropertyToken == Metadata::unselectable) - { - newUnselectables.push_back(prim.GetPath()); - } - } + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::findPrimsWithMetaData\n"); + if (!m_stage) + return; + + if (isLockPrimFeatureActive()) { + SdfPathVector newUnselectables; + for (fileio::TransformIterator it(m_stage, parentTransform(), true); !it.done(); + it.next()) { + auto prim = it.prim(); + bool excludeGeo = false; + if (prim.GetMetadata(Metadata::excludeFromProxyShape, &excludeGeo)) { + if (excludeGeo) { + m_excludedTaggedGeometry.push_back(prim.GetPrimPath()); + } + } + // If prim has exclusion tag or is a descendent of a prim with it, create as Maya geo + if (excludeGeo || primHasExcludedParent(prim)) { + VtValue schemaName(fileio::ALExcludedPrimSchema.GetString()); + prim.SetCustomDataByKey(fileio::ALSchemaType, schemaName); + } - // build up new lock-prim list - TfToken lockPropertyToken; - if (prim.GetMetadata(Metadata::locked, & lockPropertyToken)) - { - if (lockPropertyToken == Metadata::lockTransform) - { - m_lockManager.setLocked(prim.GetPath()); - } - else - if (lockPropertyToken == Metadata::lockUnlocked) - { - m_lockManager.setUnlocked(prim.GetPath()); - } - else - if (lockPropertyToken == Metadata::lockInherited) - { - m_lockManager.setInherited(prim.GetPath()); + TfToken selectabilityPropertyToken; + if (prim.GetMetadata(Metadata::selectability, &selectabilityPropertyToken)) { + // Check if this prim is unselectable + if (selectabilityPropertyToken == Metadata::unselectable) { + newUnselectables.push_back(prim.GetPath()); + } + } + + // build up new lock-prim list + TfToken lockPropertyToken; + if (prim.GetMetadata(Metadata::locked, &lockPropertyToken)) { + if (lockPropertyToken == Metadata::lockTransform) { + m_lockManager.setLocked(prim.GetPath()); + } else if (lockPropertyToken == Metadata::lockUnlocked) { + m_lockManager.setUnlocked(prim.GetPath()); + } else if (lockPropertyToken == Metadata::lockInherited) { + m_lockManager.setInherited(prim.GetPath()); + } + } else { + m_lockManager.setInherited(prim.GetPath()); + } } - } - else - { - m_lockManager.setInherited(prim.GetPath()); - } - } - constructLockPrims(); - constructExcludedPrims(); - m_selectabilityDB.setPathsAsUnselectable(newUnselectables); - } + constructLockPrims(); + constructExcludedPrims(); + m_selectabilityDB.setPathsAsUnselectable(newUnselectables); + } } //---------------------------------------------------------------------------------------------------------------------- SdfPathVector ProxyShape::getExcludePrimPaths() const { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::getExcludePrimPaths\n"); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("ProxyShape::getExcludePrimPaths\n"); - SdfPathVector paths = getPrimPathsFromCommaJoinedString(excludePrimPathsPlug().asString()); - SdfPathVector temp = getPrimPathsFromCommaJoinedString(excludedTranslatedGeometryPlug().asString()); - paths.insert(paths.end(), temp.begin(), temp.end()); - return paths; + SdfPathVector paths = getPrimPathsFromCommaJoinedString(excludePrimPathsPlug().asString()); + SdfPathVector temp + = getPrimPathsFromCommaJoinedString(excludedTranslatedGeometryPlug().asString()); + paths.insert(paths.end(), temp.begin(), temp.end()); + return paths; } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/ProxyShapeVariantFallbacks.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/ProxyShapeVariantFallbacks.cpp index b570ba0de2..9152d2da5f 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/ProxyShapeVariantFallbacks.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/proxy/ProxyShapeVariantFallbacks.cpp @@ -23,118 +23,111 @@ namespace AL { namespace usdmaya { namespace nodes { - //---------------------------------------------------------------------------------------------------------------------- PcpVariantFallbackMap ProxyShape::convertVariantFallbackFromStr(const MString& fallbacksStr) const { - if (!fallbacksStr.length()) - { - return {}; - } + if (!fallbacksStr.length()) { + return {}; + } - JsParseError parseError; - JsValue jsValue(JsParseString(fallbacksStr.asChar(), &parseError)); - if (parseError.line || !jsValue.IsObject()) - { - MGlobal::displayError(MString(parseError.reason.c_str())); - MGlobal::displayError( - MString("ProxyShape attribute \"") + name() + ".variantFallbacks\" " - "contains incorrect variant fallbacks, value must be a string form of JSON data."); - return {}; - } + JsParseError parseError; + JsValue jsValue(JsParseString(fallbacksStr.asChar(), &parseError)); + if (parseError.line || !jsValue.IsObject()) { + MGlobal::displayError(MString(parseError.reason.c_str())); + MGlobal::displayError( + MString("ProxyShape attribute \"") + name() + + ".variantFallbacks\" " + "contains incorrect variant fallbacks, value must be a string form of JSON data."); + return {}; + } - JsObject jsObject(jsValue.GetJsObject()); - PcpVariantFallbackMap result; - for (const auto& variantSet: jsObject) - { - const std::string& variantName = variantSet.first; - if (!variantSet.second.IsArray()) - { - MGlobal::displayError( - MString("ProxyShape attribute \"") + name() + ".variantFallbacks\" " - "contains unexpected data: variant value for \"" + variantName.c_str() + "\" must be an array."); - continue; + JsObject jsObject(jsValue.GetJsObject()); + PcpVariantFallbackMap result; + for (const auto& variantSet : jsObject) { + const std::string& variantName = variantSet.first; + if (!variantSet.second.IsArray()) { + MGlobal::displayError( + MString("ProxyShape attribute \"") + name() + + ".variantFallbacks\" " + "contains unexpected data: variant value for \"" + + variantName.c_str() + "\" must be an array."); + continue; + } + result[variantName] = variantSet.second.GetArrayOf(); } - result[variantName] = variantSet.second.GetArrayOf(); - } - return result; + return result; } //---------------------------------------------------------------------------------------------------------------------- MString ProxyShape::convertVariantFallbacksToStr(const PcpVariantFallbackMap& fallbacks) const { - if (fallbacks.empty()) - { - return {}; - } + if (fallbacks.empty()) { + return {}; + } - JsObject jsObject; - for (const auto& variantSet: fallbacks) - { - jsObject[variantSet.first] = JsArray(variantSet.second.cbegin(), variantSet.second.cend()); - } + JsObject jsObject; + for (const auto& variantSet : fallbacks) { + jsObject[variantSet.first] = JsArray(variantSet.second.cbegin(), variantSet.second.cend()); + } - return JsWriteToString(jsObject).c_str(); + return JsWriteToString(jsObject).c_str(); } //---------------------------------------------------------------------------------------------------------------------- MString ProxyShape::getVariantFallbacksFromLayer(const SdfLayerRefPtr& layer) const { - if (!layer) - { - return {}; - } + if (!layer) { + return {}; + } - static const std::string kVariantFallbacksToken = "variant_fallbacks"; - const VtDictionary& data(layer->GetCustomLayerData()); - const auto& valIt(data.find(kVariantFallbacksToken)); - if (valIt == data.end()) - { - return {}; - } + static const std::string kVariantFallbacksToken = "variant_fallbacks"; + const VtDictionary& data(layer->GetCustomLayerData()); + const auto& valIt(data.find(kVariantFallbacksToken)); + if (valIt == data.end()) { + return {}; + } - const VtValue& customFallbacksVal(valIt->second); - if (!customFallbacksVal.IsHolding()) - { - TF_WARN( - "Session layer has wrong \"%s\" data type, value must be a string.", - kVariantFallbacksToken.c_str()); - return {}; - } - auto result = customFallbacksVal.Get(); - if (result.empty()) - { - return {}; - } - return result.c_str(); + const VtValue& customFallbacksVal(valIt->second); + if (!customFallbacksVal.IsHolding()) { + TF_WARN( + "Session layer has wrong \"%s\" data type, value must be a string.", + kVariantFallbacksToken.c_str()); + return {}; + } + auto result = customFallbacksVal.Get(); + if (result.empty()) { + return {}; + } + return result.c_str(); } //---------------------------------------------------------------------------------------------------------------------- -PcpVariantFallbackMap ProxyShape::updateVariantFallbacks(PcpVariantFallbackMap& defaultVariantFallbacks, MDataBlock& dataBlock) const +PcpVariantFallbackMap ProxyShape::updateVariantFallbacks( + PcpVariantFallbackMap& defaultVariantFallbacks, + MDataBlock& dataBlock) const { - auto fallbacks(convertVariantFallbackFromStr(inputStringValue(dataBlock, m_variantFallbacks))); - if (!fallbacks.empty()) - { - defaultVariantFallbacks = UsdStage::GetGlobalVariantFallbacks(); - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Setting global variant fallback"); - UsdStage::SetGlobalVariantFallbacks(fallbacks); - return fallbacks; - } - return {}; + auto fallbacks(convertVariantFallbackFromStr(inputStringValue(dataBlock, m_variantFallbacks))); + if (!fallbacks.empty()) { + defaultVariantFallbacks = UsdStage::GetGlobalVariantFallbacks(); + TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Setting global variant fallback"); + UsdStage::SetGlobalVariantFallbacks(fallbacks); + return fallbacks; + } + return {}; } //---------------------------------------------------------------------------------------------------------------------- void ProxyShape::saveVariantFallbacks(const MString& fallbacksStr, MDataBlock& dataBlock) const { - if (fallbacksStr != inputStringValue(dataBlock, m_variantFallbacks)) - { - TF_DEBUG(ALUSDMAYA_EVALUATION).Msg("Saving global variant fallbacks: \n\"%s\"\n", fallbacksStr.asChar()); - outputStringValue(dataBlock, m_variantFallbacks, fallbacksStr); - } + if (fallbacksStr != inputStringValue(dataBlock, m_variantFallbacks)) { + TF_DEBUG(ALUSDMAYA_EVALUATION) + .Msg("Saving global variant fallbacks: \n\"%s\"\n", fallbacksStr.asChar()); + outputStringValue(dataBlock, m_variantFallbacks, fallbacksStr); + } } //---------------------------------------------------------------------------------------------------------------------- -} // nodes -} // usdmaya -} // AL +} // namespace nodes +} // namespace usdmaya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/wrapLayerManager.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/wrapLayerManager.cpp index 45b30c8612..a3243fc6b6 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/wrapLayerManager.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/wrapLayerManager.cpp @@ -23,12 +23,12 @@ // boost includes. Disabling those warnings for the specific includes // for now instead of disabling the strict settings at a higher level. #ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable : 4275 ) +#pragma warning(push) +#pragma warning(disable : 4275) #endif - #include +#include #ifdef _MSC_VER -#pragma warning( pop ) +#pragma warning(pop) #endif #include @@ -38,65 +38,68 @@ #include using AL::usdmaya::nodes::LayerManager; -using boost::python::reference_existing_object; using boost::python::object; +using boost::python::reference_existing_object; namespace { - struct PyLayerManager - { +struct PyLayerManager +{ //------------------------------------------------------------------------------------------------------------------ /// \brief Python-wrappable version of LayerManager::findOrCreateManager - /// \param returnWasCreated boolean controlling whether the return result includes whether a new + /// \param returnWasCreated boolean controlling whether the return result includes whether a + /// new /// LayerManager node was created or not - /// \return if returnCreateCount is false, then will return the string name of the parent transform node for the - /// usdPrim; if returnCreateCount is true, the return will be a 2-tuple, the first item of which is the - /// name of the parent transform node, and the second is the number of transforms created - static object findOrCreate( - bool returnWasCreated=false) + /// \return if returnCreateCount is false, then will return the string name of the parent + /// transform node for the + /// usdPrim; if returnCreateCount is true, the return will be a 2-tuple, the first item + /// of which is the name of the parent transform node, and the second is the number of + /// transforms created + static object findOrCreate(bool returnWasCreated = false) { - bool wasCreated; - LayerManager* managerPtr = LayerManager::findOrCreateManager(nullptr, &wasCreated); - typename boost::python::reference_existing_object::apply::type converter; - boost::python::handle<> handle(converter(managerPtr)); - object managerPyObj(handle); - if (returnWasCreated) - { - return boost::python::make_tuple(managerPyObj, wasCreated); - } - return managerPyObj; + bool wasCreated; + LayerManager* managerPtr = LayerManager::findOrCreateManager(nullptr, &wasCreated); + typename boost::python::reference_existing_object::apply::type converter; + boost::python::handle<> handle(converter(managerPtr)); + object managerPyObj(handle); + if (returnWasCreated) { + return boost::python::make_tuple(managerPyObj, wasCreated); + } + return managerPyObj; } - static boost::python::list getLayerIdentifiers( - LayerManager& manager) + static boost::python::list getLayerIdentifiers(LayerManager& manager) { - MStringArray mstrings; - manager.getLayerIdentifiers(mstrings); - boost::python::list pyList; - for (unsigned int i = 0; i < mstrings.length(); ++i) - { - pyList.append(mstrings[i].asChar()); - } - return pyList; + MStringArray mstrings; + manager.getLayerIdentifiers(mstrings); + boost::python::list pyList; + for (unsigned int i = 0; i < mstrings.length(); ++i) { + pyList.append(mstrings[i].asChar()); + } + return pyList; } - }; -} +}; +} // namespace void wrapLayerManager() { - boost::python::class_("LayerManager", boost::python::no_init) - .def("find", &LayerManager::findManager, - boost::python::return_value_policy()) + boost::python::class_("LayerManager", boost::python::no_init) + .def( + "find", + &LayerManager::findManager, + boost::python::return_value_policy()) .staticmethod("find") - .def("findOrCreate", PyLayerManager::findOrCreate, - (boost::python::arg("returnWasCreated")=false)) + .def( + "findOrCreate", + PyLayerManager::findOrCreate, + (boost::python::arg("returnWasCreated") = false)) .staticmethod("findOrCreate") - .def("addLayer", &LayerManager::addLayer, - (boost::python::arg("layer"), - boost::python::arg("identifier")="")) - .def("removeLayer", &LayerManager::removeLayer) - .def("findLayer", &LayerManager::findLayer) - .def("getLayerIdentifiers", PyLayerManager::getLayerIdentifiers) - ; + .def( + "addLayer", + &LayerManager::addLayer, + (boost::python::arg("layer"), boost::python::arg("identifier") = "")) + .def("removeLayer", &LayerManager::removeLayer) + .def("findLayer", &LayerManager::findLayer) + .def("getLayerIdentifiers", PyLayerManager::getLayerIdentifiers); } TF_REFPTR_CONST_VOLATILE_GET(LayerManager) diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/wrapProxyShape.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/wrapProxyShape.cpp index c9756b807d..070f40dddb 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/wrapProxyShape.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/nodes/wrapProxyShape.cpp @@ -13,47 +13,47 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include "AL/usdmaya/nodes/ProxyShape.h" -#include "AL/usdmaya/nodes/Transform.h" #include "AL/maya/utils/MayaHelperMacros.h" #include "AL/maya/utils/Utils.h" +#include "AL/usdmaya/nodes/ProxyShape.h" +#include "AL/usdmaya/nodes/Transform.h" #include -#include -#include -#include +#include +#include +#include #include +#include +#include #include -#include #include +#include #include -#include -#include #include #include -#include -#include -#include +#include +#include +#include #include using AL::usdmaya::nodes::ProxyShape; -using boost::python::reference_existing_object; using boost::python::object; +using boost::python::reference_existing_object; namespace { - struct MBoundingBoxConverter - { +struct MBoundingBoxConverter +{ // to-python conversion of const MBoundingBox. // Decided NOT to register this using boost::python::to_python_converter, // in case pxr registers one at some point static PyObject* convert(const MBoundingBox& bbox) { TfPyLock lock; - object OpenMaya = boost::python::import("maya.OpenMaya"); + object OpenMaya = boost::python::import("maya.OpenMaya"); // Considered grabbing the raw pointer to the MBoundingBox // from the swig wrapper, but this seems sketchy, so I'm // just re-constructing "in python" @@ -66,101 +66,88 @@ namespace { object pyBbox = PyMBoundingBox(pyMin, pyMax); return boost::python::incref(pyBbox.ptr()); } - }; - - //---------------------------------------------------------------------------------------------------------------------- - /// \brief Helper func to convert mobj for a dag or depend node into it's a python string for it's name - /// \param mobj an MObject for a dependency graph node - /// \param description A string used in error messages to describe what this node was - /// \return a boost::python::object holding the string name for the node - object MobjToName(const MObject& mobj, MString description) - { - MStatus status; +}; + +//---------------------------------------------------------------------------------------------------------------------- +/// \brief Helper func to convert mobj for a dag or depend node into it's a python string for it's +/// name \param mobj an MObject for a dependency graph node \param description A string used in +/// error messages to describe what this node was \return a boost::python::object holding the string +/// name for the node +object MobjToName(const MObject& mobj, MString description) +{ + MStatus status; TfPyLock lock; - if (mobj.isNull()) - { - return object(); //None + if (mobj.isNull()) { + return object(); // None } - if (mobj.hasFn(MFn::kDagNode)) - { - MFnDagNode requiredDagNode(mobj, &status); - if (!status) { - MGlobal::displayError( - MString("Error converting MObject to dagNode: ") - + description); - return object(); //None - } - return boost::python::str(requiredDagNode.fullPathName().asChar()); - } - else if (mobj.hasFn(MFn::kDependencyNode)) - { - MFnDependencyNode requiredDepNode(mobj, &status); - if (!status) { + if (mobj.hasFn(MFn::kDagNode)) { + MFnDagNode requiredDagNode(mobj, &status); + if (!status) { + MGlobal::displayError(MString("Error converting MObject to dagNode: ") + description); + return object(); // None + } + return boost::python::str(requiredDagNode.fullPathName().asChar()); + } else if (mobj.hasFn(MFn::kDependencyNode)) { + MFnDependencyNode requiredDepNode(mobj, &status); + if (!status) { + MGlobal::displayError( + MString("Error converting MObject to dependNode: ") + description); + return object(); // None + } + return boost::python::str(requiredDepNode.name().asChar()); + } else { MGlobal::displayError( - MString("Error converting MObject to dependNode: ") - + description); - return object(); //None - } - return boost::python::str(requiredDepNode.name().asChar()); - } - else - { - MGlobal::displayError( - MString("MObject did not appear to be a dependency node: ") - + description); - return object(); //None + MString("MObject did not appear to be a dependency node: ") + description); + return object(); // None } - } +} - struct PyProxyShape - { +struct PyProxyShape +{ //------------------------------------------------------------------------------------------------------------------ /// \brief Find Usd prim associated with Maya node. /// \param dagPath Dag path of AL_usdmaya_Transform node. /// \return The Usd prim if found, else an invalid prim. static UsdPrim getUsdPrimFromMayaPath(const std::string& dagPath) { - MStatus status; - MSelectionList sel; - status = sel.add(MString(dagPath.c_str())); - if (status) - { - MObject node; - status = sel.getDependNode(0, node); - if (status) - { - MFnDependencyNode depNode(node); - if (depNode.typeId() == AL::usdmaya::nodes::Transform::kTypeId || - depNode.typeId() == AL::usdmaya::nodes::Scope::kTypeId) - { - // Get proxy shape - auto transform = static_cast(depNode.userNode()); - MPlug stageDataPlug(transform->getProxyShape(), AL::usdmaya::nodes::ProxyShape::outStageData()); - - // Get stage data - MObject stageObject; - status = stageDataPlug.getValue(stageObject); - MFnPluginData fnData(stageObject); - auto* stageData = static_cast(fnData.data()); - - // Validate stage - if (stageData && stageData->stage) - { - - // Lookup prim path in stage - MPlug primPathPlug(node, AL::usdmaya::nodes::Transform::primPath()); - MString primPath; - status = primPathPlug.getValue(primPath); - if (status) - { - return stageData->stage->GetPrimAtPath(SdfPath(primPath.asChar())); - } + MStatus status; + MSelectionList sel; + status = sel.add(MString(dagPath.c_str())); + if (status) { + MObject node; + status = sel.getDependNode(0, node); + if (status) { + MFnDependencyNode depNode(node); + if (depNode.typeId() == AL::usdmaya::nodes::Transform::kTypeId + || depNode.typeId() == AL::usdmaya::nodes::Scope::kTypeId) { + // Get proxy shape + auto transform + = static_cast(depNode.userNode()); + MPlug stageDataPlug( + transform->getProxyShape(), AL::usdmaya::nodes::ProxyShape::outStageData()); + + // Get stage data + MObject stageObject; + status = stageDataPlug.getValue(stageObject); + MFnPluginData fnData(stageObject); + auto* stageData = static_cast(fnData.data()); + + // Validate stage + if (stageData && stageData->stage) { + + // Lookup prim path in stage + MPlug primPathPlug(node, AL::usdmaya::nodes::Transform::primPath()); + MString primPath; + status = primPathPlug.getValue(primPath); + if (status) { + return stageData->stage->GetPrimAtPath(SdfPath(primPath.asChar())); + } + } + } } - } } - } - return UsdPrim(); + return UsdPrim(); } //------------------------------------------------------------------------------------------------------------------ @@ -169,41 +156,41 @@ namespace { /// \return The full dag path of the Maya node if found, else an empty string. static std::string getMayaPathFromUsdPrim(const ProxyShape& proxyShape, const UsdPrim& prim) { - return prim.IsValid() ? AL::maya::utils::convert(proxyShape.getMayaPathFromUsdPrim(prim)) : std::string(); + return prim.IsValid() ? AL::maya::utils::convert(proxyShape.getMayaPathFromUsdPrim(prim)) + : std::string(); } //------------------------------------------------------------------------------------------------------------------ /// \brief Returns a python bounding box for the given proxy shape /// - /// Used because we opted NOT to register auto-conversion of c++ MBoundingBoxes to python MBoundingBoxes, - /// with boost::python::to_python_converter, as if pixar ever does so in the future, the double registration would - /// be a problem + /// Used because we opted NOT to register auto-conversion of c++ MBoundingBoxes to python + /// MBoundingBoxes, with boost::python::to_python_converter, as if pixar ever does so in the + /// future, the double registration would be a problem static PyObject* boundingBox(const ProxyShape& proxyShape) { - return MBoundingBoxConverter::convert(proxyShape.boundingBox()); + return MBoundingBoxConverter::convert(proxyShape.boundingBox()); } //------------------------------------------------------------------------------------------------------------------ /// \brief Python-wrappable version of ProxyShape::findRequiredPath - static object findRequiredPath( - const ProxyShape& proxyShape, const SdfPath& path) + static object findRequiredPath(const ProxyShape& proxyShape, const SdfPath& path) { - MObject obj = proxyShape.findRequiredPath(path); - MString desc = MString("from SdfPath '") + path.GetText() + "'"; - return MobjToName(obj, desc); + MObject obj = proxyShape.findRequiredPath(path); + MString desc = MString("from SdfPath '") + path.GetText() + "'"; + return MobjToName(obj, desc); } //------------------------------------------------------------------------------------------------------------------ - /// \brief Utility method, for better readability, that returns whether given MObject is a ProxyShape + /// \brief Utility method, for better readability, that returns whether given MObject is a + /// ProxyShape static bool isProxyShape(MObject mobj) { - MStatus status; - MFnDependencyNode mfnDep(mobj, &status); - if (!status) - { - return false; - } - return mfnDep.typeId() == ProxyShape::kTypeId; + MStatus status; + MFnDependencyNode mfnDep(mobj, &status); + if (!status) { + return false; + } + return mfnDep.typeId() == ProxyShape::kTypeId; } //------------------------------------------------------------------------------------------------------------------ @@ -217,298 +204,288 @@ namespace { /// None will be returned in python). static ProxyShape* getProxyShapeByName(std::string name) { - MStatus status; - MSelectionList sel; - status = sel.add(AL::maya::utils::convert(name)); - if (!status) - { - return nullptr; - } - MDagPath dag; - status = sel.getDagPath(0, dag); - if (!status) - { - return nullptr; - } - - MObject proxyMObj = dag.node(); - if (!isProxyShape(proxyMObj)) - { - // Try extending to shapes below... - if (!dag.hasFn(MFn::kTransform)) - { - return nullptr; + MStatus status; + MSelectionList sel; + status = sel.add(AL::maya::utils::convert(name)); + if (!status) { + return nullptr; + } + MDagPath dag; + status = sel.getDagPath(0, dag); + if (!status) { + return nullptr; } - bool foundProxy = false; - unsigned int numShapes; - if (!dag.numberOfShapesDirectlyBelow(numShapes)) - { - return nullptr; + MObject proxyMObj = dag.node(); + if (!isProxyShape(proxyMObj)) { + // Try extending to shapes below... + if (!dag.hasFn(MFn::kTransform)) { + return nullptr; + } + + bool foundProxy = false; + unsigned int numShapes; + if (!dag.numberOfShapesDirectlyBelow(numShapes)) { + return nullptr; + } + for (uint32_t i = 0; i < numShapes; ++i) { + dag.extendToShapeDirectlyBelow(i); + if (isProxyShape(dag.node())) { + foundProxy = true; + proxyMObj = dag.node(); + break; + } + dag.pop(); + } + if (!foundProxy) { + return nullptr; + } } - for (uint32_t i = 0; i < numShapes; ++i) - { - dag.extendToShapeDirectlyBelow(i); - if (isProxyShape(dag.node())) - { - foundProxy = true; - proxyMObj = dag.node(); - break; - } - dag.pop(); + + MFnDependencyNode mfnDep(proxyMObj, &status); + if (!status) { + return nullptr; } - if (!foundProxy) - { - return nullptr; + auto proxyShapePtr = static_cast(mfnDep.userNode(&status)); + if (!status) { + return nullptr; } - } - - MFnDependencyNode mfnDep(proxyMObj, &status); - if (!status) - { - return nullptr; - } - auto proxyShapePtr = static_cast(mfnDep.userNode(&status)); - if (!status) - { - return nullptr; - } - return proxyShapePtr; + return proxyShapePtr; } //------------------------------------------------------------------------------------------------------------------ /// \brief Python-wrappable version of ProxyShape::makeUsdTransformChain /// \param proxyShape the ProxyShape we're making transforms for - /// \param usdPrim the leaf of the prim we wish to create (same as for ProxyShape::makeUsdTransformChain) - /// \param reason the reason why this path is being generated. (same as for ProxyShape::makeUsdTransformChain) - /// \param pushToPrim boolean controlling whether or not to set pushToPrim to true; in the wrapped function, this + /// \param usdPrim the leaf of the prim we wish to create (same as for + /// ProxyShape::makeUsdTransformChain) \param reason the reason why this path is being + /// generated. (same as for ProxyShape::makeUsdTransformChain) \param pushToPrim boolean + /// controlling whether or not to set pushToPrim to true; in the wrapped function, this /// is essentially controlled by whether or not the modifier2 param is passed. - /// \param returnCreateCount boolean controlling whether the return result includes the transforms that were + /// \param returnCreateCount boolean controlling whether the return result includes the + /// transforms that were /// created - /// \return if returnCreateCount is false, then will return the string name of the parent transform node for the - /// usdPrim; if returnCreateCount is true, the return will be a 2-tuple, the first item of which is the - /// name of the parent transform node, and the second is the number of transforms created + /// \return if returnCreateCount is false, then will return the string name of the parent + /// transform node for the + /// usdPrim; if returnCreateCount is true, the return will be a 2-tuple, the first item + /// of which is the name of the parent transform node, and the second is the number of + /// transforms created static object makeUsdTransformChain( - ProxyShape& proxyShape, - const UsdPrim& usdPrim, - ProxyShape::TransformReason reason=ProxyShape::kRequested, - bool pushToPrim=false, - bool returnCreateCount=false) + ProxyShape& proxyShape, + const UsdPrim& usdPrim, + ProxyShape::TransformReason reason = ProxyShape::kRequested, + bool pushToPrim = false, + bool returnCreateCount = false) { - // Note - this current doesn't support undo, but right now, neither - // does the AL_usdmaya_ProxyShapeImportAllTransforms command - MDagModifier modifier; - MDGModifier modifier2; - uint32_t createCount = 0; - - MDGModifier* mod2Ptr = nullptr; - if (pushToPrim) - { - mod2Ptr = &modifier2; - } - MObject resultObj = proxyShape.makeUsdTransformChain( - usdPrim, - modifier, - reason, - mod2Ptr, - &createCount); - modifier.doIt(); - if (pushToPrim) - { - modifier2.doIt(); - } - MString objDesc("maya transform chain root for '"); - objDesc += usdPrim.GetPath().GetText(); - objDesc += "'"; - object resultPyObj = MobjToName(resultObj, objDesc); - if (returnCreateCount) - { - return boost::python::make_tuple(resultPyObj, createCount); - } - return resultPyObj; + // Note - this current doesn't support undo, but right now, neither + // does the AL_usdmaya_ProxyShapeImportAllTransforms command + MDagModifier modifier; + MDGModifier modifier2; + uint32_t createCount = 0; + + MDGModifier* mod2Ptr = nullptr; + if (pushToPrim) { + mod2Ptr = &modifier2; + } + MObject resultObj + = proxyShape.makeUsdTransformChain(usdPrim, modifier, reason, mod2Ptr, &createCount); + modifier.doIt(); + if (pushToPrim) { + modifier2.doIt(); + } + MString objDesc("maya transform chain root for '"); + objDesc += usdPrim.GetPath().GetText(); + objDesc += "'"; + object resultPyObj = MobjToName(resultObj, objDesc); + if (returnCreateCount) { + return boost::python::make_tuple(resultPyObj, createCount); + } + return resultPyObj; } //------------------------------------------------------------------------------------------------------------------ /// \brief Python-wrappable version of ProxyShape::makeUsdTransforms /// \param proxyShape the ProxyShape we're making transforms for - /// \param usdPrim the root for the transforms to be created (same as for ProxyShape::makeUsdTransforms) - /// \param reason the reason for creating the transforms (use with selection, etc). (same as for + /// \param usdPrim the root for the transforms to be created (same as for + /// ProxyShape::makeUsdTransforms) \param reason the reason for creating the transforms (use + /// with selection, etc). (same as for /// ProxyShape::makeUsdTransforms) - /// \param pushToPrim boolean controlling whether or not to set pushToPrim to true; in the wrapped function, this + /// \param pushToPrim boolean controlling whether or not to set pushToPrim to true; in the + /// wrapped function, this /// is essentially controlled by whether or not the modifier2 param is passed. /// \return the string name of the parent transform node for the usdPrim static object makeUsdTransforms( - ProxyShape& proxyShape, - const UsdPrim& usdPrim, - ProxyShape::TransformReason reason=ProxyShape::kRequested, - bool pushToPrim=false) + ProxyShape& proxyShape, + const UsdPrim& usdPrim, + ProxyShape::TransformReason reason = ProxyShape::kRequested, + bool pushToPrim = false) { - MDagModifier modifier; - MDGModifier modifier2; - - MDGModifier* mod2Ptr = nullptr; - if (pushToPrim) - { - mod2Ptr = &modifier2; - } - - MObject resultObj = proxyShape.makeUsdTransforms( - usdPrim, - modifier, - reason, - mod2Ptr); - modifier.doIt(); - if (pushToPrim) - { - modifier2.doIt(); - } - MString objDesc("maya transform for '"); - objDesc += usdPrim.GetPath().GetText(); - objDesc += "'"; - return MobjToName(resultObj, objDesc); + MDagModifier modifier; + MDGModifier modifier2; + + MDGModifier* mod2Ptr = nullptr; + if (pushToPrim) { + mod2Ptr = &modifier2; + } + + MObject resultObj = proxyShape.makeUsdTransforms(usdPrim, modifier, reason, mod2Ptr); + modifier.doIt(); + if (pushToPrim) { + modifier2.doIt(); + } + MString objDesc("maya transform for '"); + objDesc += usdPrim.GetPath().GetText(); + objDesc += "'"; + return MobjToName(resultObj, objDesc); } //------------------------------------------------------------------------------------------------------------------ - /// \brief Python-wrappable version of ProxyShape::removeUsdTransformChain (that takes a UsdPrim object) - /// \param proxyShape the ProxyShape we're removing transforms from - /// \param usdPrim the leaf node in the chain of transforms we wish to remove (same as for + /// \brief Python-wrappable version of ProxyShape::removeUsdTransformChain (that takes a + /// UsdPrim object) \param proxyShape the ProxyShape we're removing transforms from \param + /// usdPrim the leaf node in the chain of transforms we wish to remove (same as for /// ProxyShape::removeUsdTransformChain) - /// \param reason the reason why this path is being removed. (same as for ProxyShape::removeUsdTransformChain) + /// \param reason the reason why this path is being removed. (same as for + /// ProxyShape::removeUsdTransformChain) static void removeUsdTransformChain( - ProxyShape& proxyShape, - const UsdPrim& usdPrim, - ProxyShape::TransformReason reason=ProxyShape::kRequested) + ProxyShape& proxyShape, + const UsdPrim& usdPrim, + ProxyShape::TransformReason reason = ProxyShape::kRequested) { - MDagModifier modifier; - proxyShape.removeUsdTransformChain( - usdPrim, - modifier, - reason); - modifier.doIt(); + MDagModifier modifier; + proxyShape.removeUsdTransformChain(usdPrim, modifier, reason); + modifier.doIt(); } //------------------------------------------------------------------------------------------------------------------ - /// \brief Python-wrappable version of ProxyShape::removeUsdTransformChain (that takes an SdfPath) - /// \param proxyShape the ProxyShape we're removing transforms from - /// \param path the leaf node in the chain of transforms we wish to remove (same as for + /// \brief Python-wrappable version of ProxyShape::removeUsdTransformChain (that takes an + /// SdfPath) \param proxyShape the ProxyShape we're removing transforms from \param path the + /// leaf node in the chain of transforms we wish to remove (same as for /// ProxyShape::removeUsdTransformChain) - /// \param reason the reason why this path is being removed. (same as for ProxyShape::removeUsdTransformChain) + /// \param reason the reason why this path is being removed. (same as for + /// ProxyShape::removeUsdTransformChain) static void removeUsdTransformChain( - ProxyShape& proxyShape, - const SdfPath& path, - ProxyShape::TransformReason reason=ProxyShape::kRequested) + ProxyShape& proxyShape, + const SdfPath& path, + ProxyShape::TransformReason reason = ProxyShape::kRequested) { - MDagModifier modifier; - proxyShape.removeUsdTransformChain( - path, - modifier, - reason); - modifier.doIt(); + MDagModifier modifier; + proxyShape.removeUsdTransformChain(path, modifier, reason); + modifier.doIt(); } //------------------------------------------------------------------------------------------------------------------ /// \brief Python-wrappable version of ProxyShape::removeUsdTransforms /// \param proxyShape the ProxyShape we're removing transforms from - /// \param path all AL_usdmaya_Transform nodes found underneath this path will be destroyed (unless those nodes are + /// \param path all AL_usdmaya_Transform nodes found underneath this path will be destroyed + /// (unless those nodes are /// required for another purpose). (same as for ProxyShape::removeUsdTransforms) - /// \param reason Are we deleting selected transforms, or those that are required, or requested? (same as for + /// \param reason Are we deleting selected transforms, or those that are required, or + /// requested? (same as for /// ProxyShape::removeUsdTransforms) static void removeUsdTransforms( - ProxyShape& proxyShape, - const UsdPrim& usdPrim, - ProxyShape::TransformReason reason=ProxyShape::kRequested) + ProxyShape& proxyShape, + const UsdPrim& usdPrim, + ProxyShape::TransformReason reason = ProxyShape::kRequested) { - MDagModifier modifier; - proxyShape.removeUsdTransforms( - usdPrim, - modifier, - reason); - modifier.doIt(); + MDagModifier modifier; + proxyShape.removeUsdTransforms(usdPrim, modifier, reason); + modifier.doIt(); } - }; -} +}; +} // namespace void wrapProxyShape() { - void (*removeUsdTransformChain_prim)(ProxyShape& proxyShape, - const UsdPrim& usdPrim, ProxyShape::TransformReason) = PyProxyShape::removeUsdTransformChain; + void (*removeUsdTransformChain_prim)( + ProxyShape & proxyShape, const UsdPrim& usdPrim, ProxyShape::TransformReason) + = PyProxyShape::removeUsdTransformChain; - void (*removeUsdTransformChain_path)(ProxyShape& proxyShape, - const SdfPath& path, ProxyShape::TransformReason) = PyProxyShape::removeUsdTransformChain; + void (*removeUsdTransformChain_path)( + ProxyShape & proxyShape, const SdfPath& path, ProxyShape::TransformReason) + = PyProxyShape::removeUsdTransformChain; - boost::python::class_ - proxyShapeCls("ProxyShape", boost::python::no_init); + boost::python::class_ proxyShapeCls( + "ProxyShape", boost::python::no_init); - boost::python::scope proxyShapeScope = proxyShapeCls; + boost::python::scope proxyShapeScope = proxyShapeCls; - boost::python::enum_("TransformReason") - .value("kSelection", ProxyShape::kSelection) - .value("kRequested", ProxyShape::kRequested) - .value("kRequired", ProxyShape::kRequired) - ; + boost::python::enum_("TransformReason") + .value("kSelection", ProxyShape::kSelection) + .value("kRequested", ProxyShape::kRequested) + .value("kRequired", ProxyShape::kRequired); - proxyShapeCls - .def("getByName", PyProxyShape::getProxyShapeByName, - boost::python::return_value_policy()) + proxyShapeCls + .def( + "getByName", + PyProxyShape::getProxyShapeByName, + boost::python::return_value_policy()) .staticmethod("getByName") - .def("getUsdStage", &ProxyShape::getUsdStage) - .def("getUsdPrimFromMayaPath", PyProxyShape::getUsdPrimFromMayaPath, - ("Find Usd prim associated with Maya node.\n" - "Args:\n" - "\tdagPath (str): Dag path of AL_usdmaya_Transform node.\n" - "Returns:\n" - "\tThe Usd prim if found, else an invalid prim.\n"), - (boost::python::arg("dagPath"))) + .def("getUsdStage", &ProxyShape::getUsdStage) + .def( + "getUsdPrimFromMayaPath", + PyProxyShape::getUsdPrimFromMayaPath, + ("Find Usd prim associated with Maya node.\n" + "Args:\n" + "\tdagPath (str): Dag path of AL_usdmaya_Transform node.\n" + "Returns:\n" + "\tThe Usd prim if found, else an invalid prim.\n"), + (boost::python::arg("dagPath"))) .staticmethod("getUsdPrimFromMayaPath") - .def("getMayaPathFromUsdPrim", &PyProxyShape::getMayaPathFromUsdPrim, - ("Find Maya node associated with Usd prim in Proxy's stage.\n" - "Args:\n" - "\tprim (pxr.Usd.Prim): A valid Usd prim.\n" - "Returns:\n" - "\tThe full dag path of the Maya node if found, else an empty string.\n"), - (boost::python::arg("prim"))) - .def("resync", &ProxyShape::resync, - (boost::python::arg("path"))) - .def("boundingBox", PyProxyShape::boundingBox) - .def("isRequiredPath", &ProxyShape::isRequiredPath) - .def("findRequiredPath", PyProxyShape::findRequiredPath) - .def("makeUsdTransformChain", PyProxyShape::makeUsdTransformChain, - (boost::python::arg("usdPrim"), - boost::python::arg("reason")=ProxyShape::kRequested, - boost::python::arg("pushToPrim")=false, - boost::python::arg("returnCreateCount")=false)) - .def("makeUsdTransforms", PyProxyShape::makeUsdTransforms, - (boost::python::arg("usdPrim"), - boost::python::arg("reason")=ProxyShape::kRequested, - boost::python::arg("pushToPrim")=false)) - .def("removeUsdTransformChain", removeUsdTransformChain_prim, - (boost::python::arg("usdPrim"), - boost::python::arg("reason")=ProxyShape::kRequested)) - .def("removeUsdTransformChain", removeUsdTransformChain_path, - (boost::python::arg("path"), - boost::python::arg("reason")=ProxyShape::kRequested)) - .def("removeUsdTransforms", PyProxyShape::removeUsdTransforms, - (boost::python::arg("usdPrim"), - boost::python::arg("reason")=ProxyShape::kRequested)) - .def("destroyTransformReferences", &ProxyShape::destroyTransformReferences) - ; + .def( + "getMayaPathFromUsdPrim", + &PyProxyShape::getMayaPathFromUsdPrim, + ("Find Maya node associated with Usd prim in Proxy's stage.\n" + "Args:\n" + "\tprim (pxr.Usd.Prim): A valid Usd prim.\n" + "Returns:\n" + "\tThe full dag path of the Maya node if found, else an empty string.\n"), + (boost::python::arg("prim"))) + .def("resync", &ProxyShape::resync, (boost::python::arg("path"))) + .def("boundingBox", PyProxyShape::boundingBox) + .def("isRequiredPath", &ProxyShape::isRequiredPath) + .def("findRequiredPath", PyProxyShape::findRequiredPath) + .def( + "makeUsdTransformChain", + PyProxyShape::makeUsdTransformChain, + (boost::python::arg("usdPrim"), + boost::python::arg("reason") = ProxyShape::kRequested, + boost::python::arg("pushToPrim") = false, + boost::python::arg("returnCreateCount") = false)) + .def( + "makeUsdTransforms", + PyProxyShape::makeUsdTransforms, + (boost::python::arg("usdPrim"), + boost::python::arg("reason") = ProxyShape::kRequested, + boost::python::arg("pushToPrim") = false)) + .def( + "removeUsdTransformChain", + removeUsdTransformChain_prim, + (boost::python::arg("usdPrim"), boost::python::arg("reason") = ProxyShape::kRequested)) + .def( + "removeUsdTransformChain", + removeUsdTransformChain_path, + (boost::python::arg("path"), boost::python::arg("reason") = ProxyShape::kRequested)) + .def( + "removeUsdTransforms", + PyProxyShape::removeUsdTransforms, + (boost::python::arg("usdPrim"), boost::python::arg("reason") = ProxyShape::kRequested)) + .def("destroyTransformReferences", &ProxyShape::destroyTransformReferences); // Decided NOT to register this using boost::python::to_python_converter, // in case pxr registers one at some point -// boost::python::to_python_converter(); + // boost::python::to_python_converter(); } -// This workaround for a VS compiler bug where we need to explicitly specify -// the conversion to pointer of your our class seems no longer needed for VS2017. +// This workaround for a VS compiler bug where we need to explicitly specify +// the conversion to pointer of your our class seems no longer needed for VS2017. // What it means, is that compiler will properly generate this conversion -// implicitly and cause linker error LNK2005. +// implicitly and cause linker error LNK2005. // -// In this particular case we got wrapTranslatorContext.obj generating error for +// In this particular case we got wrapTranslatorContext.obj generating error for // already defined conversion to a pointer for ProxyShape in wrapProxyShape.obj // // The best place to put this fix would be in pxr/base/lib/tf/refPtr.h -// where TF_REFPTR_CONST_VOLATILE_GET is defined, but for now we are +// where TF_REFPTR_CONST_VOLATILE_GET is defined, but for now we are // patching it locally. -#if defined(ARCH_COMPILER_MSVC) && ARCH_COMPILER_MSVC_VERSION <= 1910 - TF_REFPTR_CONST_VOLATILE_GET(ProxyShape) +#if defined(ARCH_COMPILER_MSVC) && ARCH_COMPILER_MSVC_VERSION <= 1910 +TF_REFPTR_CONST_VOLATILE_GET(ProxyShape) #endif diff --git a/plugin/al/lib/AL_USDMaya/AL/usdmaya/wrapStageCache.cpp b/plugin/al/lib/AL_USDMaya/AL/usdmaya/wrapStageCache.cpp index 47b32fa9d5..0eb2c88399 100644 --- a/plugin/al/lib/AL_USDMaya/AL/usdmaya/wrapStageCache.cpp +++ b/plugin/al/lib/AL_USDMaya/AL/usdmaya/wrapStageCache.cpp @@ -15,23 +15,25 @@ // #include "AL/usdmaya/StageCache.h" +#include + +#include #include #include -#include - -#include -//using namespace std; -//using namespace boost::python; -//using namespace boost; +// using namespace std; +// using namespace boost::python; +// using namespace boost; void wrapStageCache() { - boost::python::class_("StageCache") + boost::python::class_("StageCache") - .def("Get", &AL::usdmaya::StageCache::Get, - boost::python::return_value_policy()) - .staticmethod("Get") - .def("Clear", &AL::usdmaya::StageCache::Clear) - .staticmethod("Clear"); + .def( + "Get", + &AL::usdmaya::StageCache::Get, + boost::python::return_value_policy()) + .staticmethod("Get") + .def("Clear", &AL::usdmaya::StageCache::Clear) + .staticmethod("Clear"); } diff --git a/plugin/al/mayatest/AL/maya/test/Api.h b/plugin/al/mayatest/AL/maya/test/Api.h index 028a76f864..34859a10db 100644 --- a/plugin/al/mayatest/AL/maya/test/Api.h +++ b/plugin/al/mayatest/AL/maya/test/Api.h @@ -15,26 +15,26 @@ // #if defined _WIN32 || defined __CYGWIN__ - #ifdef AL_MAYA_TEST_EXPORT - #ifdef __GNUC__ - #define AL_MAYA_TEST_PUBLIC __attribute__ ((dllexport)) - #else - #define AL_MAYA_TEST_PUBLIC __declspec(dllexport) - #endif - #else - #ifdef __GNUC__ - #define AL_MAYA_TEST_PUBLIC __attribute__ ((dllimport)) - #else - #define AL_MAYA_TEST_PUBLIC __declspec(dllimport) - #endif - #endif - #define AL_MAYA_TEST_LOCAL +#ifdef AL_MAYA_TEST_EXPORT +#ifdef __GNUC__ +#define AL_MAYA_TEST_PUBLIC __attribute__((dllexport)) #else - #if __GNUC__ >= 4 - #define AL_MAYA_TEST_PUBLIC __attribute__ ((visibility ("default"))) - #define AL_MAYA_TEST_LOCAL __attribute__ ((visibility ("hidden"))) - #else - #define AL_MAYA_TEST_PUBLIC - #define AL_MAYA_TEST_LOCAL - #endif +#define AL_MAYA_TEST_PUBLIC __declspec(dllexport) +#endif +#else +#ifdef __GNUC__ +#define AL_MAYA_TEST_PUBLIC __attribute__((dllimport)) +#else +#define AL_MAYA_TEST_PUBLIC __declspec(dllimport) +#endif +#endif +#define AL_MAYA_TEST_LOCAL +#else +#if __GNUC__ >= 4 +#define AL_MAYA_TEST_PUBLIC __attribute__((visibility("default"))) +#define AL_MAYA_TEST_LOCAL __attribute__((visibility("hidden"))) +#else +#define AL_MAYA_TEST_PUBLIC +#define AL_MAYA_TEST_LOCAL +#endif #endif diff --git a/plugin/al/mayatest/AL/maya/test/testHarness.cpp b/plugin/al/mayatest/AL/maya/test/testHarness.cpp index 97fc04cb14..c913a372b3 100644 --- a/plugin/al/mayatest/AL/maya/test/testHarness.cpp +++ b/plugin/al/mayatest/AL/maya/test/testHarness.cpp @@ -13,55 +13,51 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include #include "testHarness.h" + #include "testHelpers.h" -#include + #include #include +#include +#include namespace AL { namespace maya { namespace test { #ifdef _WIN32 -# define RESET_COLOUR +#define RESET_COLOUR #else -# define RESET_COLOUR "\e[39m" +#define RESET_COLOUR "\e[39m" #endif -const char* happy_dino = -" __\n" -" /\"_)\n" -" _.----._/ /\n" -" / /\n" -" __/ ( | ( |\n" -"/__.-'|_|--|_|\n" RESET_COLOUR; - -const char* angry_dino = -" __\n" -" /x_)\n" -" _/\\/\\/\\_/ /\n" -" _| /\n" -" _| ( | ( |\n" -"/__.-'|_|--|_|\n" RESET_COLOUR; - -const char* happy_cat = -"\n" -" \\ /\\ \n" -" ) ( ^)\n" -" ( / )\n" -" \\(__)|\n" -RESET_COLOUR; - -const char* angry_cat = -"\n" -" // \n" -" ( >)\n" -" /\\ / )\n" -" / \\(__)|\n" -RESET_COLOUR; +const char* happy_dino = " __\n" + " /\"_)\n" + " _.----._/ /\n" + " / /\n" + " __/ ( | ( |\n" + "/__.-'|_|--|_|\n" RESET_COLOUR; + +const char* angry_dino = " __\n" + " /x_)\n" + " _/\\/\\/\\_/ /\n" + " _| /\n" + " _| ( | ( |\n" + "/__.-'|_|--|_|\n" RESET_COLOUR; + +const char* happy_cat = "\n" + " \\ /\\ \n" + " ) ( ^)\n" + " ( / )\n" + " \\(__)|\n" RESET_COLOUR; + +const char* angry_cat = "\n" + " // \n" + " ( >)\n" + " /\\ / )\n" + " / \\(__)|\n" RESET_COLOUR; //---------------------------------------------------------------------------------------------------------------------- const MString UnitTestHarness::kName = "AL_maya_test_UnitTestHarness"; @@ -69,175 +65,159 @@ const MString UnitTestHarness::kName = "AL_maya_test_UnitTestHarness"; //---------------------------------------------------------------------------------------------------------------------- MSyntax UnitTestHarness::createSyntax() { - MSyntax syn; - syn.addFlag("-f", "-filter", MSyntax::kString); - syn.addFlag("-o", "-output", MSyntax::kString); - syn.addFlag("-ff", "-flag_file", MSyntax::kString); - syn.addFlag("-l", "-list"); - syn.addFlag("-bof", "-break_on_failure"); - syn.addFlag("-ne", "-no_catch_exceptions"); - syn.addFlag("-nc", "-no_colour"); - syn.addFlag("-nt", "-no_time"); - syn.addFlag("-rs", "-random_seed", MSyntax::kLong); - syn.addFlag("-rp", "-repeat", MSyntax::kLong); - syn.addFlag("-std", "-stack_trace_depth", MSyntax::kLong); - syn.addFlag("-tof", "-throw_on_failure"); - syn.addFlag("-ktf", "-keep_temp_files"); - return syn; + MSyntax syn; + syn.addFlag("-f", "-filter", MSyntax::kString); + syn.addFlag("-o", "-output", MSyntax::kString); + syn.addFlag("-ff", "-flag_file", MSyntax::kString); + syn.addFlag("-l", "-list"); + syn.addFlag("-bof", "-break_on_failure"); + syn.addFlag("-ne", "-no_catch_exceptions"); + syn.addFlag("-nc", "-no_colour"); + syn.addFlag("-nt", "-no_time"); + syn.addFlag("-rs", "-random_seed", MSyntax::kLong); + syn.addFlag("-rp", "-repeat", MSyntax::kLong); + syn.addFlag("-std", "-stack_trace_depth", MSyntax::kLong); + syn.addFlag("-tof", "-throw_on_failure"); + syn.addFlag("-ktf", "-keep_temp_files"); + return syn; } //---------------------------------------------------------------------------------------------------------------------- std::vector constructGoogleTestArgs(MArgDatabase& database) { - std::vector args; - args.emplace_back("maya_tests"); - - MString filter = "*"; - MString output = ""; - MString color = "yes"; - int rs = 0; - int rp = 1; - int sd = 100; - - if(database.isFlagSet("-ff")) - { - MString flag_file; - if(database.getFlagArgument("-ff", 0, flag_file)) - { - std::string str("--gtest_flagfile="); - str += flag_file.asChar(); - args.emplace_back(std::move(str)); + std::vector args; + args.emplace_back("maya_tests"); + + MString filter = "*"; + MString output = ""; + MString color = "yes"; + int rs = 0; + int rp = 1; + int sd = 100; + + if (database.isFlagSet("-ff")) { + MString flag_file; + if (database.getFlagArgument("-ff", 0, flag_file)) { + std::string str("--gtest_flagfile="); + str += flag_file.asChar(); + args.emplace_back(std::move(str)); + } } - } - - if(database.isFlagSet("-nc")) - { - color = "no"; - } - - if(database.isFlagSet("-f")) - { - if(database.getFlagArgument("-f", 0, filter)) {} - } - - if(database.isFlagSet("-o")) - { - if(database.getFlagArgument("-o", 0, output)) {} - } - - if(database.isFlagSet("-rs")) - { - if(database.getFlagArgument("-rs", 0, rs)) {} - } - - if(database.isFlagSet("-rp")) - { - if(database.getFlagArgument("-rp", 0, rp)) {} - } - - if(database.isFlagSet("-std")) - { - if(database.getFlagArgument("-std", 0, sd)) {} - } - - ::testing::GTEST_FLAG(catch_exceptions) = !database.isFlagSet("-ne"); - ::testing::GTEST_FLAG(print_time) = !database.isFlagSet("-nt"); - ::testing::GTEST_FLAG(list_tests) = database.isFlagSet("-l"); - ::testing::GTEST_FLAG(throw_on_failure) = database.isFlagSet("-tof"); - ::testing::GTEST_FLAG(filter) = filter.asChar(); - ::testing::GTEST_FLAG(output) = output.asChar(); - ::testing::GTEST_FLAG(color) = color.asChar(); - ::testing::GTEST_FLAG(random_seed) = rs; - ::testing::GTEST_FLAG(repeat) = rp; - ::testing::GTEST_FLAG(stack_trace_depth) = sd; - - return args; -} + if (database.isFlagSet("-nc")) { + color = "no"; + } -//---------------------------------------------------------------------------------------------------------------------- -void* UnitTestHarness::creator() -{ - return new UnitTestHarness; + if (database.isFlagSet("-f")) { + if (database.getFlagArgument("-f", 0, filter)) { } + } + + if (database.isFlagSet("-o")) { + if (database.getFlagArgument("-o", 0, output)) { } + } + + if (database.isFlagSet("-rs")) { + if (database.getFlagArgument("-rs", 0, rs)) { } + } + + if (database.isFlagSet("-rp")) { + if (database.getFlagArgument("-rp", 0, rp)) { } + } + + if (database.isFlagSet("-std")) { + if (database.getFlagArgument("-std", 0, sd)) { } + } + + ::testing::GTEST_FLAG(catch_exceptions) = !database.isFlagSet("-ne"); + ::testing::GTEST_FLAG(print_time) = !database.isFlagSet("-nt"); + ::testing::GTEST_FLAG(list_tests) = database.isFlagSet("-l"); + ::testing::GTEST_FLAG(throw_on_failure) = database.isFlagSet("-tof"); + ::testing::GTEST_FLAG(filter) = filter.asChar(); + ::testing::GTEST_FLAG(output) = output.asChar(); + ::testing::GTEST_FLAG(color) = color.asChar(); + ::testing::GTEST_FLAG(random_seed) = rs; + ::testing::GTEST_FLAG(repeat) = rp; + ::testing::GTEST_FLAG(stack_trace_depth) = sd; + + return args; } +//---------------------------------------------------------------------------------------------------------------------- +void* UnitTestHarness::creator() { return new UnitTestHarness; } + //---------------------------------------------------------------------------------------------------------------------- MStatus UnitTestHarness::doIt(const MArgList& args) { - MStatus status; - MArgDatabase database(syntax(), args, &status); - if(!status) - return status; + MStatus status; + MArgDatabase database(syntax(), args, &status); + if (!status) + return status; + + // the unit tests cycle manipulate the timeline quite a bit. Disable GL refresh to speed them up + // a bit. + if (MGlobal::kInteractive == MGlobal::mayaState()) + MGlobal::executeCommand("refresh -suspend true"); + + std::vector arguments = constructGoogleTestArgs(database); + + char** argv = new char*[arguments.size()]; + int32_t argc(arguments.size()); + for (int32_t i = 0; i < argc; ++i) { + argv[i] = (char*)arguments[i].c_str(); + } + + ::testing::InitGoogleTest(&argc, argv); + int error_code = -1; + if (RUN_ALL_TESTS() == 0 && ::testing::UnitTest::GetInstance()->test_to_run_count() > 0) { + error_code = 0; + } + delete[] argv; + setResult(error_code); + + if (!database.isFlagSet("-ktf")) { + cleanTemporaryFiles(); + } - // the unit tests cycle manipulate the timeline quite a bit. Disable GL refresh to speed them up a bit. - if(MGlobal::kInteractive == MGlobal::mayaState()) - MGlobal::executeCommand("refresh -suspend true"); - - std::vector arguments = constructGoogleTestArgs(database); - - char** argv = new char*[arguments.size()]; - int32_t argc(arguments.size()); - for(int32_t i = 0; i < argc; ++i) - { - argv[i] = (char*)arguments[i].c_str(); - } - - ::testing::InitGoogleTest(&argc, argv); - int error_code = -1; - if(RUN_ALL_TESTS() == 0 && ::testing::UnitTest::GetInstance()->test_to_run_count() > 0) - { - error_code = 0; - } - delete [] argv; - setResult(error_code); - - if(!database.isFlagSet("-ktf")) - { - cleanTemporaryFiles(); - } - - if(MGlobal::kInteractive == MGlobal::mayaState()) - MGlobal::executeCommand("refresh -suspend false"); - - if(error_code) - { - #ifndef _WIN32 - if(::testing::GTEST_FLAG(color) != "no") std::cout << "\e[31m"; - #endif - std::cout << angry_dino; - } - else - { - #ifndef _WIN32 - if(::testing::GTEST_FLAG(color) != "no") std::cout << "\e[32m"; - #endif - std::cout << happy_dino; - } - // return the status based on the error code - status = (error_code == 0) ? MS::kSuccess : MS::kFailure; - return status; + if (MGlobal::kInteractive == MGlobal::mayaState()) + MGlobal::executeCommand("refresh -suspend false"); + + if (error_code) { +#ifndef _WIN32 + if (::testing::GTEST_FLAG(color) != "no") + std::cout << "\e[31m"; +#endif + std::cout << angry_dino; + } else { +#ifndef _WIN32 + if (::testing::GTEST_FLAG(color) != "no") + std::cout << "\e[32m"; +#endif + std::cout << happy_dino; + } + // return the status based on the error code + status = (error_code == 0) ? MS::kSuccess : MS::kFailure; + return status; } //------------------------------------------------------------------------------ void UnitTestHarness::cleanTemporaryFiles() const { - const MString temp_path = buildTempPath("AL_USDMayaTests*.*"); - MString cmd( - "import glob;" - "import os;" - "[os.remove(x) for x in glob.glob('" + temp_path + "')];" - ); - - MStatus stat = MGlobal::executePythonCommand(cmd); - - if(stat != MStatus::kSuccess) { - MGlobal::displayWarning("Unable to remove temporary test files"); - } + const MString temp_path = buildTempPath("AL_USDMayaTests*.*"); + MString cmd( + "import glob;" + "import os;" + "[os.remove(x) for x in glob.glob('" + + temp_path + "')];"); + + MStatus stat = MGlobal::executePythonCommand(cmd); + + if (stat != MStatus::kSuccess) { + MGlobal::displayWarning("Unable to remove temporary test files"); + } } //---------------------------------------------------------------------------------------------------------------------- -} // test -} // maya -} // AL +} // namespace test +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/mayatest/AL/maya/test/testHarness.h b/plugin/al/mayatest/AL/maya/test/testHarness.h index 58907a3dcd..d7df6ca997 100644 --- a/plugin/al/mayatest/AL/maya/test/testHarness.h +++ b/plugin/al/mayatest/AL/maya/test/testHarness.h @@ -14,9 +14,9 @@ // limitations under the License. // #pragma once -#include #include "AL/maya/test/Api.h" +#include namespace AL { namespace maya { @@ -25,19 +25,17 @@ namespace test { class UnitTestHarness : public MPxCommand { public: - - AL_MAYA_TEST_PUBLIC static void* creator(); - AL_MAYA_TEST_PUBLIC static MSyntax createSyntax(); - AL_MAYA_TEST_PUBLIC static const MString kName; - AL_MAYA_TEST_PUBLIC MStatus doIt(const MArgList& args) override; + AL_MAYA_TEST_PUBLIC static void* creator(); + AL_MAYA_TEST_PUBLIC static MSyntax createSyntax(); + AL_MAYA_TEST_PUBLIC static const MString kName; + AL_MAYA_TEST_PUBLIC MStatus doIt(const MArgList& args) override; private: - void cleanTemporaryFiles() const; - + void cleanTemporaryFiles() const; }; //---------------------------------------------------------------------------------------------------------------------- -} // test -} // maya -} // AL +} // namespace test +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/mayatest/AL/maya/test/testHelpers.cpp b/plugin/al/mayatest/AL/maya/test/testHelpers.cpp index fc86f03f92..4c8ada14c7 100644 --- a/plugin/al/mayatest/AL/maya/test/testHelpers.cpp +++ b/plugin/al/mayatest/AL/maya/test/testHelpers.cpp @@ -15,9 +15,15 @@ // #include "testHelpers.h" +#include +#include + +#include #include +#include #include #include +#include #include #include #include @@ -26,18 +32,11 @@ #include #include #include -#include #include -#include -#include +#include #include - -#include -#include - #include -#include PXR_NAMESPACE_USING_DIRECTIVE @@ -45,716 +44,638 @@ namespace AL { namespace maya { namespace test { - //---------------------------------------------------------------------------------------------------------------------- const char* buildTempPath(const char* const filename) { - static std::string _temp_subdir; - if(_temp_subdir.empty()) - { - _temp_subdir = ArchMakeTmpSubdir(TfRealPath(ArchGetTmpDir()), "AL_USDMaya"); - - if(_temp_subdir.empty()) - { - return nullptr; - } + static std::string _temp_subdir; + if (_temp_subdir.empty()) { + _temp_subdir = ArchMakeTmpSubdir(TfRealPath(ArchGetTmpDir()), "AL_USDMaya"); - _temp_subdir += AL_PATH_CHAR; - } + if (_temp_subdir.empty()) { + return nullptr; + } + + _temp_subdir += AL_PATH_CHAR; + } - std::string full_path = _temp_subdir + filename; - std::replace(full_path.begin(), full_path.end(), '\\', '/'); + std::string full_path = _temp_subdir + filename; + std::replace(full_path.begin(), full_path.end(), '\\', '/'); - static char temp_file[512]; - std::strcpy(temp_file, full_path.data()); + static char temp_file[512]; + std::strcpy(temp_file, full_path.data()); - return temp_file; + return temp_file; } //---------------------------------------------------------------------------------------------------------------------- void compareTempPaths(std::string pathA, std::string pathB) { - std::replace(pathA.begin(), pathA.end(), '\\', '/'); - std::replace(pathB.begin(), pathB.end(), '\\', '/'); + std::replace(pathA.begin(), pathA.end(), '\\', '/'); + std::replace(pathB.begin(), pathB.end(), '\\', '/'); - EXPECT_EQ(pathA, pathB); + EXPECT_EQ(pathA, pathB); } //---------------------------------------------------------------------------------------------------------------------- void comparePlugs(const MPlug& plugA, const MPlug& plugB, bool usdTesting) { - SCOPED_TRACE(MString("plugA: ") + plugA.name() + " - plugB: " + plugB.name()); - EXPECT_EQ(plugA.isArray(), plugB.isArray()); - EXPECT_EQ(plugA.isElement(), plugB.isElement()); - EXPECT_EQ(plugA.isCompound(), plugB.isCompound()); - EXPECT_EQ(plugA.isChild(), plugB.isChild()); - EXPECT_EQ(plugA.partialName(false, true, true, true, true, true), plugB.partialName(false, true, true, true, true, true)); - - /// I need to special case the testing of the Time, Angle, and Distance attribute types. These are converted to doubles in USD, - /// so if plugA is one of those types, plugB should be a double. - /// \TODO I would have thought that there would be a way to flag the units used in the USD attributes? - if(usdTesting && (plugA.attribute().apiType() != plugB.attribute().apiType())) - { - if(plugA.attribute().apiType() == MFn::kTimeAttribute || - plugA.attribute().apiType() == MFn::kDoubleAngleAttribute || - plugA.attribute().apiType() == MFn::kDoubleLinearAttribute) - { - if(plugA.isArray()) - { - EXPECT_EQ(plugA.numElements(), plugB.numElements()); - for(uint32_t i = 0; i < plugA.numElements(); ++i) - { - EXPECT_NEAR(plugA.elementByLogicalIndex(i).asDouble(), plugB.elementByLogicalIndex(i).asDouble(), 1e-5f); + SCOPED_TRACE(MString("plugA: ") + plugA.name() + " - plugB: " + plugB.name()); + EXPECT_EQ(plugA.isArray(), plugB.isArray()); + EXPECT_EQ(plugA.isElement(), plugB.isElement()); + EXPECT_EQ(plugA.isCompound(), plugB.isCompound()); + EXPECT_EQ(plugA.isChild(), plugB.isChild()); + EXPECT_EQ( + plugA.partialName(false, true, true, true, true, true), + plugB.partialName(false, true, true, true, true, true)); + + /// I need to special case the testing of the Time, Angle, and Distance attribute types. These + /// are converted to doubles in USD, so if plugA is one of those types, plugB should be a + /// double. \TODO I would have thought that there would be a way to flag the units used in the + /// USD attributes? + if (usdTesting && (plugA.attribute().apiType() != plugB.attribute().apiType())) { + if (plugA.attribute().apiType() == MFn::kTimeAttribute + || plugA.attribute().apiType() == MFn::kDoubleAngleAttribute + || plugA.attribute().apiType() == MFn::kDoubleLinearAttribute) { + if (plugA.isArray()) { + EXPECT_EQ(plugA.numElements(), plugB.numElements()); + for (uint32_t i = 0; i < plugA.numElements(); ++i) { + EXPECT_NEAR( + plugA.elementByLogicalIndex(i).asDouble(), + plugB.elementByLogicalIndex(i).asDouble(), + 1e-5f); + } + } else { + EXPECT_NEAR(plugA.asDouble(), plugB.asDouble(), 1e-5f); + } } - } - else - { - EXPECT_NEAR(plugA.asDouble(), plugB.asDouble(), 1e-5f); - } - } - return; - } - - // make sure the unit types match - EXPECT_EQ(plugA.attribute().apiType(), plugB.attribute().apiType()); - if(plugB.isArray()) - { - // for arrays, just make sure the array sizes match, and then compare each of the element plugs - EXPECT_EQ(plugA.numElements(), plugB.numElements()); - for(uint32_t i = 0; i < plugA.numElements(); ++i) - { - comparePlugs(plugA.elementByLogicalIndex(i), plugB.elementByLogicalIndex(i)); - } - } - else - if(plugB.isCompound()) - { - // for compound attrs, make sure child counts match, and then compare each of the child plugs - EXPECT_EQ(plugA.numChildren(), plugB.numChildren()); - for(uint32_t i = 0; i < plugA.numChildren(); ++i) - { - comparePlugs(plugA.child(i), plugB.child(i)); + return; } - } - else - { - switch(plugA.attribute().apiType()) - { - case MFn::kTypedAttribute: - { - MFnTypedAttribute fnA(plugA.attribute()); - MFnTypedAttribute fnB(plugB.attribute()); - EXPECT_EQ(fnA.attrType(), fnB.attrType()); - switch(fnA.attrType()) - { - case MFnData::kString: - EXPECT_EQ(plugA.asString(), plugB.asString()); - break; - default: - std::cout << ("Unknown typed attribute type \"") << plugA.name().asChar() << "\" " << fnA.attrType() << std::endl; - break; + // make sure the unit types match + EXPECT_EQ(plugA.attribute().apiType(), plugB.attribute().apiType()); + if (plugB.isArray()) { + // for arrays, just make sure the array sizes match, and then compare each of the element + // plugs + EXPECT_EQ(plugA.numElements(), plugB.numElements()); + for (uint32_t i = 0; i < plugA.numElements(); ++i) { + comparePlugs(plugA.elementByLogicalIndex(i), plugB.elementByLogicalIndex(i)); } - } - break; - case MFn::kNumericAttribute: - { - // when we get here, the attributes represent a single value - // make sure the types match, and compare the values to make sure they - // are the same. - MFnNumericAttribute unAttrA(plugA.attribute()); - MFnNumericAttribute unAttrB(plugB.attribute()); - EXPECT_EQ(unAttrA.unitType(), unAttrB.unitType()); - - switch(unAttrA.unitType()) - { - case MFnNumericData::kBoolean: - EXPECT_EQ(plugA.asBool(), plugB.asBool()); - break; - - case MFnNumericData::kByte: - EXPECT_EQ(plugA.asChar(), plugB.asChar()); - break; - - case MFnNumericData::kChar: - EXPECT_EQ(plugA.asChar(), plugB.asChar()); - break; - - case MFnNumericData::kShort: - EXPECT_EQ(plugA.asShort(), plugB.asShort()); - break; - - case MFnNumericData::k2Short: - EXPECT_EQ(plugA.child(0).asShort(), plugB.child(0).asShort()); - EXPECT_EQ(plugA.child(1).asShort(), plugB.child(1).asShort()); - break; - - case MFnNumericData::k3Short: - EXPECT_EQ(plugA.child(0).asShort(), plugB.child(0).asShort()); - EXPECT_EQ(plugA.child(1).asShort(), plugB.child(1).asShort()); - EXPECT_EQ(plugA.child(2).asShort(), plugB.child(2).asShort()); - break; - - case MFnNumericData::kLong: - EXPECT_EQ(plugA.asInt(), plugB.asInt()); - break; - - case MFnNumericData::kInt64: - EXPECT_EQ(plugA.asInt64(), plugB.asInt64()); - break; - - case MFnNumericData::k2Long: - EXPECT_EQ(plugA.child(0).asInt(), plugB.child(0).asInt()); - EXPECT_EQ(plugA.child(1).asInt(), plugB.child(1).asInt()); - break; - - case MFnNumericData::k3Long: - EXPECT_EQ(plugA.child(0).asInt(), plugB.child(0).asInt()); - EXPECT_EQ(plugA.child(1).asInt(), plugB.child(1).asInt()); - EXPECT_EQ(plugA.child(2).asInt(), plugB.child(2).asInt()); - break; - - case MFnNumericData::kFloat: - EXPECT_NEAR(plugA.asFloat(), plugB.asFloat(), 1e-5f); - break; - - case MFnNumericData::k2Float: - EXPECT_NEAR(plugA.child(0).asFloat(), plugB.child(0).asFloat(), 1e-5f); - EXPECT_NEAR(plugA.child(1).asFloat(), plugB.child(1).asFloat(), 1e-5f); - break; - - case MFnNumericData::k3Float: - EXPECT_NEAR(plugA.child(0).asFloat(), plugB.child(0).asFloat(), 1e-5f); - EXPECT_NEAR(plugA.child(1).asFloat(), plugB.child(1).asFloat(), 1e-5f); - EXPECT_NEAR(plugA.child(2).asFloat(), plugB.child(2).asFloat(), 1e-5f); - break; - - case MFnNumericData::kDouble: - EXPECT_NEAR(plugA.asDouble(), plugB.asDouble(), 1e-5f); - break; - - case MFnNumericData::k2Double: - EXPECT_NEAR(plugA.child(0).asDouble(), plugB.child(0).asDouble(), 1e-5f); - EXPECT_NEAR(plugA.child(1).asDouble(), plugB.child(1).asDouble(), 1e-5f); - break; - - case MFnNumericData::k3Double: - EXPECT_NEAR(plugA.child(0).asDouble(), plugB.child(0).asDouble(), 1e-5f); - EXPECT_NEAR(plugA.child(1).asDouble(), plugB.child(1).asDouble(), 1e-5f); - EXPECT_NEAR(plugA.child(2).asDouble(), plugB.child(2).asDouble(), 1e-5f); - break; - - case MFnNumericData::k4Double: - EXPECT_NEAR(plugA.child(0).asDouble(), plugB.child(0).asDouble(), 1e-5f); - EXPECT_NEAR(plugA.child(1).asDouble(), plugB.child(1).asDouble(), 1e-5f); - EXPECT_NEAR(plugA.child(2).asDouble(), plugB.child(2).asDouble(), 1e-5f); - EXPECT_NEAR(plugA.child(3).asDouble(), plugB.child(3).asDouble(), 1e-5f); - break; - - default: - std::cout << ("Unknown numeric attribute type \"") << plugA.name().asChar() << "\" " << std::endl; - break; + } else if (plugB.isCompound()) { + // for compound attrs, make sure child counts match, and then compare each of the child + // plugs + EXPECT_EQ(plugA.numChildren(), plugB.numChildren()); + for (uint32_t i = 0; i < plugA.numChildren(); ++i) { + comparePlugs(plugA.child(i), plugB.child(i)); } - } - break; - - case MFn::kUnitAttribute: - { - MFnUnitAttribute unAttrA(plugA.attribute()); - MFnUnitAttribute unAttrB(plugB.attribute()); - EXPECT_EQ(unAttrA.unitType(), unAttrB.unitType()); - switch(unAttrA.unitType()) - { - case MFnUnitAttribute::kAngle: - EXPECT_NEAR(plugA.asMAngle().as(MAngle::kRadians), plugB.asMAngle().as(MAngle::kRadians), 1e-5f); - break; - - case MFnUnitAttribute::kDistance: - EXPECT_NEAR(plugA.asMDistance().as(MDistance::kFeet), plugB.asMDistance().as(MDistance::kFeet), 1e-5f); - break; - - case MFnUnitAttribute::kTime: - EXPECT_NEAR(plugA.asMTime().as(MTime::kSeconds), plugB.asMTime().as(MTime::kSeconds), 1e-5f); - break; + } else { + switch (plugA.attribute().apiType()) { + case MFn::kTypedAttribute: { + MFnTypedAttribute fnA(plugA.attribute()); + MFnTypedAttribute fnB(plugB.attribute()); + EXPECT_EQ(fnA.attrType(), fnB.attrType()); + switch (fnA.attrType()) { + case MFnData::kString: EXPECT_EQ(plugA.asString(), plugB.asString()); break; + + default: + std::cout << ("Unknown typed attribute type \"") << plugA.name().asChar() << "\" " + << fnA.attrType() << std::endl; + break; + } + } break; + case MFn::kNumericAttribute: { + // when we get here, the attributes represent a single value + // make sure the types match, and compare the values to make sure they + // are the same. + MFnNumericAttribute unAttrA(plugA.attribute()); + MFnNumericAttribute unAttrB(plugB.attribute()); + EXPECT_EQ(unAttrA.unitType(), unAttrB.unitType()); + + switch (unAttrA.unitType()) { + case MFnNumericData::kBoolean: EXPECT_EQ(plugA.asBool(), plugB.asBool()); break; + + case MFnNumericData::kByte: EXPECT_EQ(plugA.asChar(), plugB.asChar()); break; + + case MFnNumericData::kChar: EXPECT_EQ(plugA.asChar(), plugB.asChar()); break; + + case MFnNumericData::kShort: EXPECT_EQ(plugA.asShort(), plugB.asShort()); break; + + case MFnNumericData::k2Short: + EXPECT_EQ(plugA.child(0).asShort(), plugB.child(0).asShort()); + EXPECT_EQ(plugA.child(1).asShort(), plugB.child(1).asShort()); + break; + + case MFnNumericData::k3Short: + EXPECT_EQ(plugA.child(0).asShort(), plugB.child(0).asShort()); + EXPECT_EQ(plugA.child(1).asShort(), plugB.child(1).asShort()); + EXPECT_EQ(plugA.child(2).asShort(), plugB.child(2).asShort()); + break; + + case MFnNumericData::kLong: EXPECT_EQ(plugA.asInt(), plugB.asInt()); break; + + case MFnNumericData::kInt64: EXPECT_EQ(plugA.asInt64(), plugB.asInt64()); break; + + case MFnNumericData::k2Long: + EXPECT_EQ(plugA.child(0).asInt(), plugB.child(0).asInt()); + EXPECT_EQ(plugA.child(1).asInt(), plugB.child(1).asInt()); + break; + + case MFnNumericData::k3Long: + EXPECT_EQ(plugA.child(0).asInt(), plugB.child(0).asInt()); + EXPECT_EQ(plugA.child(1).asInt(), plugB.child(1).asInt()); + EXPECT_EQ(plugA.child(2).asInt(), plugB.child(2).asInt()); + break; + + case MFnNumericData::kFloat: + EXPECT_NEAR(plugA.asFloat(), plugB.asFloat(), 1e-5f); + break; + + case MFnNumericData::k2Float: + EXPECT_NEAR(plugA.child(0).asFloat(), plugB.child(0).asFloat(), 1e-5f); + EXPECT_NEAR(plugA.child(1).asFloat(), plugB.child(1).asFloat(), 1e-5f); + break; + + case MFnNumericData::k3Float: + EXPECT_NEAR(plugA.child(0).asFloat(), plugB.child(0).asFloat(), 1e-5f); + EXPECT_NEAR(plugA.child(1).asFloat(), plugB.child(1).asFloat(), 1e-5f); + EXPECT_NEAR(plugA.child(2).asFloat(), plugB.child(2).asFloat(), 1e-5f); + break; + + case MFnNumericData::kDouble: + EXPECT_NEAR(plugA.asDouble(), plugB.asDouble(), 1e-5f); + break; + + case MFnNumericData::k2Double: + EXPECT_NEAR(plugA.child(0).asDouble(), plugB.child(0).asDouble(), 1e-5f); + EXPECT_NEAR(plugA.child(1).asDouble(), plugB.child(1).asDouble(), 1e-5f); + break; + + case MFnNumericData::k3Double: + EXPECT_NEAR(plugA.child(0).asDouble(), plugB.child(0).asDouble(), 1e-5f); + EXPECT_NEAR(plugA.child(1).asDouble(), plugB.child(1).asDouble(), 1e-5f); + EXPECT_NEAR(plugA.child(2).asDouble(), plugB.child(2).asDouble(), 1e-5f); + break; + + case MFnNumericData::k4Double: + EXPECT_NEAR(plugA.child(0).asDouble(), plugB.child(0).asDouble(), 1e-5f); + EXPECT_NEAR(plugA.child(1).asDouble(), plugB.child(1).asDouble(), 1e-5f); + EXPECT_NEAR(plugA.child(2).asDouble(), plugB.child(2).asDouble(), 1e-5f); + EXPECT_NEAR(plugA.child(3).asDouble(), plugB.child(3).asDouble(), 1e-5f); + break; + + default: + std::cout << ("Unknown numeric attribute type \"") << plugA.name().asChar() << "\" " + << std::endl; + break; + } + } break; + + case MFn::kUnitAttribute: { + MFnUnitAttribute unAttrA(plugA.attribute()); + MFnUnitAttribute unAttrB(plugB.attribute()); + EXPECT_EQ(unAttrA.unitType(), unAttrB.unitType()); + switch (unAttrA.unitType()) { + case MFnUnitAttribute::kAngle: + EXPECT_NEAR( + plugA.asMAngle().as(MAngle::kRadians), + plugB.asMAngle().as(MAngle::kRadians), + 1e-5f); + break; + + case MFnUnitAttribute::kDistance: + EXPECT_NEAR( + plugA.asMDistance().as(MDistance::kFeet), + plugB.asMDistance().as(MDistance::kFeet), + 1e-5f); + break; + + case MFnUnitAttribute::kTime: + EXPECT_NEAR( + plugA.asMTime().as(MTime::kSeconds), + plugB.asMTime().as(MTime::kSeconds), + 1e-5f); + break; + + default: + std::cout << ("Unknown unit attribute type \"") << plugA.name().asChar() << "\" " + << std::endl; + break; + } + } break; + + case MFn::kGenericAttribute: + case MFn::kMessageAttribute: { + } break; + + case MFn::kMatrixAttribute: + case MFn::kFloatMatrixAttribute: { + MFnMatrixData fnA(plugA.asMObject()); + MFnMatrixData fnB(plugB.asMObject()); + MMatrix vA = fnA.matrix(); + MMatrix vB = fnB.matrix(); + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 4; ++j) { + EXPECT_NEAR(vA[i][j], vB[i][j], 1e-5f); + } + } + } break; + + case MFn::kEnumAttribute: EXPECT_EQ(plugA.asShort(), plugB.asShort()); break; + + case MFn::kTimeAttribute: + EXPECT_NEAR( + plugA.asMTime().as(MTime::kSeconds), plugB.asMTime().as(MTime::kSeconds), 1e-5f); + break; + + case MFn::kFloatAngleAttribute: + case MFn::kDoubleAngleAttribute: + EXPECT_NEAR( + plugA.asMAngle().as(MAngle::kRadians), + plugB.asMAngle().as(MAngle::kRadians), + 1e-5f); + break; + + case MFn::kFloatLinearAttribute: + case MFn::kDoubleLinearAttribute: + EXPECT_NEAR( + plugA.asMDistance().as(MDistance::kFeet), + plugB.asMDistance().as(MDistance::kFeet), + 1e-5f); + break; default: - std::cout << ("Unknown unit attribute type \"") << plugA.name().asChar() << "\" " << std::endl; - break; - } - } - break; - - case MFn::kGenericAttribute: - case MFn::kMessageAttribute: - { - } - break; - - case MFn::kMatrixAttribute: - case MFn::kFloatMatrixAttribute: - { - MFnMatrixData fnA(plugA.asMObject()); - MFnMatrixData fnB(plugB.asMObject()); - MMatrix vA = fnA.matrix(); - MMatrix vB = fnB.matrix(); - for(int i = 0; i < 4; ++i) - { - for(int j = 0; j < 4; ++j) - { - EXPECT_NEAR(vA[i][j], vB[i][j], 1e-5f); - } + std::cout << ("Unknown attribute type \"") << plugA.name().asChar() << "\" " + << plugA.attribute().apiTypeStr() << std::endl; + break; } - } - break; - - case MFn::kEnumAttribute: - EXPECT_EQ(plugA.asShort(), plugB.asShort()); - break; - - case MFn::kTimeAttribute: - EXPECT_NEAR(plugA.asMTime().as(MTime::kSeconds), plugB.asMTime().as(MTime::kSeconds), 1e-5f); - break; - - case MFn::kFloatAngleAttribute: - case MFn::kDoubleAngleAttribute: - EXPECT_NEAR(plugA.asMAngle().as(MAngle::kRadians), plugB.asMAngle().as(MAngle::kRadians), 1e-5f); - break; - - case MFn::kFloatLinearAttribute: - case MFn::kDoubleLinearAttribute: - EXPECT_NEAR(plugA.asMDistance().as(MDistance::kFeet), plugB.asMDistance().as(MDistance::kFeet), 1e-5f); - break; - - default: - std::cout << ("Unknown attribute type \"") << plugA.name().asChar() << "\" " << plugA.attribute().apiTypeStr() << std::endl; - break; } - } } //---------------------------------------------------------------------------------------------------------------------- -void compareNodes(const MObject& nodeA, const MObject& nodeB, bool includeDefaultAttrs, bool includeDynamicAttrs, bool usdTesting) +void compareNodes( + const MObject& nodeA, + const MObject& nodeB, + bool includeDefaultAttrs, + bool includeDynamicAttrs, + bool usdTesting) { - MFnDependencyNode fnA(nodeA); - MFnDependencyNode fnB(nodeB); - for(uint32_t i = 0; i < fnA.attributeCount(); ++i) - { - MPlug plugA(nodeA, fnA.attribute(i)), plugB; - - // we only want to process high level attributes, e.g. translate, and not it's kids translateX, translateY, translateZ - if(plugA.isChild()) - { - continue; - } + MFnDependencyNode fnA(nodeA); + MFnDependencyNode fnB(nodeB); + for (uint32_t i = 0; i < fnA.attributeCount(); ++i) { + MPlug plugA(nodeA, fnA.attribute(i)), plugB; + + // we only want to process high level attributes, e.g. translate, and not it's kids + // translateX, translateY, translateZ + if (plugA.isChild()) { + continue; + } - if(plugA.isDynamic()) - { - if(!includeDynamicAttrs) - continue; - } - else - { - if(!includeDefaultAttrs) - continue; - } + if (plugA.isDynamic()) { + if (!includeDynamicAttrs) + continue; + } else { + if (!includeDefaultAttrs) + continue; + } - // can we find the attribute on the second node? - MStatus status; - plugB = fnB.findPlug(plugA.partialName(false, true, true, true, true, true), true, &status); - EXPECT_EQ(MStatus(MS::kSuccess), status); + // can we find the attribute on the second node? + MStatus status; + plugB = fnB.findPlug(plugA.partialName(false, true, true, true, true, true), true, &status); + EXPECT_EQ(MStatus(MS::kSuccess), status); - // compare the plug values to be ensure they match - comparePlugs(plugA, plugB, usdTesting); - } + // compare the plug values to be ensure they match + comparePlugs(plugA, plugB, usdTesting); + } } //---------------------------------------------------------------------------------------------------------------------- -void compareNodes(const MObject& nodeA, const MObject& nodeB, const char* const attributes[], uint32_t attributeCount, bool usdTesting) +void compareNodes( + const MObject& nodeA, + const MObject& nodeB, + const char* const attributes[], + uint32_t attributeCount, + bool usdTesting) { - MFnDependencyNode fnA(nodeA); - MFnDependencyNode fnB(nodeB); - for(uint32_t i = 0; i < attributeCount; ++i) - { - MPlug plugA = fnA.findPlug(attributes[i]); - MPlug plugB = fnB.findPlug(attributes[i]); - - // compare the plug values to be ensure they match - comparePlugs(plugA, plugB, usdTesting); - } + MFnDependencyNode fnA(nodeA); + MFnDependencyNode fnB(nodeB); + for (uint32_t i = 0; i < attributeCount; ++i) { + MPlug plugA = fnA.findPlug(attributes[i]); + MPlug plugB = fnB.findPlug(attributes[i]); + + // compare the plug values to be ensure they match + comparePlugs(plugA, plugB, usdTesting); + } } //---------------------------------------------------------------------------------------------------------------------- void randomPlug(MPlug plug) { - // make sure the unit types match - if(plug.isArray()) - { - if(plug.attribute().apiType() == MFn::kMatrixAttribute || - plug.attribute().apiType() == MFn::kFloatMatrixAttribute) - { - for(int i = 0; i < 511; ++i) - { - char tempStr[2048]; - snprintf(tempStr, 2048, "setAttr \"%s[%d]\" -type \"matrix\" %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf;", - plug.name().asChar(), - i, - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble(), - randDouble()); - MGlobal::executeCommand(tempStr); - } - } - else - { - // for arrays, just make sure the array sizes match, and then compare each of the element plugs - plug.setNumElements(511); - for(uint32_t i = 0; i < plug.numElements(); ++i) - { - randomPlug(plug.elementByLogicalIndex(i)); - } - } - } - else - if(plug.isCompound()) - { - // for compound attrs, make sure child counts match, and then compare each of the child plugs - for(uint32_t i = 0; i < plug.numChildren(); ++i) - { - randomPlug(plug.child(i)); - } - } - else - { - switch(plug.attribute().apiType()) - { - case MFn::kTypedAttribute: - { - MFnTypedAttribute fn(plug.attribute()); - switch(fn.attrType()) - { - case MFnData::kString: - randomString(plug); - break; - - default: - std::cout << ("Unknown typed attribute type") << std::endl; - break; + // make sure the unit types match + if (plug.isArray()) { + if (plug.attribute().apiType() == MFn::kMatrixAttribute + || plug.attribute().apiType() == MFn::kFloatMatrixAttribute) { + for (int i = 0; i < 511; ++i) { + char tempStr[2048]; + snprintf( + tempStr, + 2048, + "setAttr \"%s[%d]\" -type \"matrix\" %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf " + "%lf %lf %lf %lf %lf %lf;", + plug.name().asChar(), + i, + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble(), + randDouble()); + MGlobal::executeCommand(tempStr); + } + } else { + // for arrays, just make sure the array sizes match, and then compare each of the + // element plugs + plug.setNumElements(511); + for (uint32_t i = 0; i < plug.numElements(); ++i) { + randomPlug(plug.elementByLogicalIndex(i)); + } } - } - break; - - case MFn::kNumericAttribute: - { - // when we get here, the attributes represent a single value - // make sure the types match, and compare the values to make sure they - // are the same. - MFnNumericAttribute unAttr(plug.attribute()); - switch(unAttr.unitType()) - { - case MFnNumericData::kBoolean: - randomBool(plug); - break; - - case MFnNumericData::kByte: - randomInt8(plug); - break; - - case MFnNumericData::kChar: - randomInt8(plug); - break; - - case MFnNumericData::kShort: - randomInt16(plug); - break; - - case MFnNumericData::k2Short: - randomInt16(plug.child(0)); - randomInt16(plug.child(1)); - break; - - case MFnNumericData::k3Short: - randomInt16(plug.child(0)); - randomInt16(plug.child(1)); - randomInt16(plug.child(2)); - break; - - case MFnNumericData::kLong: - randomInt32(plug); - break; - - case MFnNumericData::kInt64: - randomInt64(plug); - break; - - case MFnNumericData::k2Long: - randomInt32(plug.child(0)); - randomInt32(plug.child(1)); - break; - - case MFnNumericData::k3Long: - randomInt32(plug.child(0)); - randomInt32(plug.child(1)); - randomInt32(plug.child(2)); - break; - - case MFnNumericData::kFloat: - randomFloat(plug); - break; - - case MFnNumericData::k2Float: - randomFloat(plug.child(0)); - randomFloat(plug.child(1)); - break; - - case MFnNumericData::k3Float: - randomFloat(plug.child(0)); - randomFloat(plug.child(1)); - randomFloat(plug.child(2)); - break; - - case MFnNumericData::kDouble: - randomDouble(plug); - break; - - case MFnNumericData::k2Double: - randomDouble(plug.child(0)); - randomDouble(plug.child(1)); - break; - - case MFnNumericData::k3Double: - randomDouble(plug.child(0)); - randomDouble(plug.child(1)); - randomDouble(plug.child(2)); - break; - - case MFnNumericData::k4Double: - randomDouble(plug.child(0)); - randomDouble(plug.child(1)); - randomDouble(plug.child(2)); - randomDouble(plug.child(3)); - break; - - default: - std::cout << ("Unknown numeric attribute type") << std::endl; - break; + } else if (plug.isCompound()) { + // for compound attrs, make sure child counts match, and then compare each of the child + // plugs + for (uint32_t i = 0; i < plug.numChildren(); ++i) { + randomPlug(plug.child(i)); } - } - break; - - case MFn::kUnitAttribute: - { - MFnUnitAttribute unAttr(plug.attribute()); - switch(unAttr.unitType()) - { - case MFnUnitAttribute::kAngle: - randomAngle(plug); - break; - - case MFnUnitAttribute::kDistance: - randomDistance(plug); - break; - - case MFnUnitAttribute::kTime: - randomTime(plug); - break; + } else { + switch (plug.attribute().apiType()) { + case MFn::kTypedAttribute: { + MFnTypedAttribute fn(plug.attribute()); + switch (fn.attrType()) { + case MFnData::kString: randomString(plug); break; + + default: std::cout << ("Unknown typed attribute type") << std::endl; break; + } + } break; + + case MFn::kNumericAttribute: { + // when we get here, the attributes represent a single value + // make sure the types match, and compare the values to make sure they + // are the same. + MFnNumericAttribute unAttr(plug.attribute()); + switch (unAttr.unitType()) { + case MFnNumericData::kBoolean: randomBool(plug); break; + + case MFnNumericData::kByte: randomInt8(plug); break; + + case MFnNumericData::kChar: randomInt8(plug); break; + + case MFnNumericData::kShort: randomInt16(plug); break; + + case MFnNumericData::k2Short: + randomInt16(plug.child(0)); + randomInt16(plug.child(1)); + break; + + case MFnNumericData::k3Short: + randomInt16(plug.child(0)); + randomInt16(plug.child(1)); + randomInt16(plug.child(2)); + break; + + case MFnNumericData::kLong: randomInt32(plug); break; + + case MFnNumericData::kInt64: randomInt64(plug); break; + + case MFnNumericData::k2Long: + randomInt32(plug.child(0)); + randomInt32(plug.child(1)); + break; + + case MFnNumericData::k3Long: + randomInt32(plug.child(0)); + randomInt32(plug.child(1)); + randomInt32(plug.child(2)); + break; + + case MFnNumericData::kFloat: randomFloat(plug); break; + + case MFnNumericData::k2Float: + randomFloat(plug.child(0)); + randomFloat(plug.child(1)); + break; + + case MFnNumericData::k3Float: + randomFloat(plug.child(0)); + randomFloat(plug.child(1)); + randomFloat(plug.child(2)); + break; + + case MFnNumericData::kDouble: randomDouble(plug); break; + + case MFnNumericData::k2Double: + randomDouble(plug.child(0)); + randomDouble(plug.child(1)); + break; + + case MFnNumericData::k3Double: + randomDouble(plug.child(0)); + randomDouble(plug.child(1)); + randomDouble(plug.child(2)); + break; + + case MFnNumericData::k4Double: + randomDouble(plug.child(0)); + randomDouble(plug.child(1)); + randomDouble(plug.child(2)); + randomDouble(plug.child(3)); + break; + + default: std::cout << ("Unknown numeric attribute type") << std::endl; break; + } + } break; + + case MFn::kUnitAttribute: { + MFnUnitAttribute unAttr(plug.attribute()); + switch (unAttr.unitType()) { + case MFnUnitAttribute::kAngle: randomAngle(plug); break; + + case MFnUnitAttribute::kDistance: randomDistance(plug); break; + + case MFnUnitAttribute::kTime: randomTime(plug); break; + + default: std::cout << ("Unknown unit attribute type") << std::endl; break; + } + } break; + + case MFn::kMatrixAttribute: + case MFn::kFloatMatrixAttribute: { + } break; + + case MFn::kMessageAttribute: { + } break; + + case MFn::kEnumAttribute: { + MFnEnumAttribute unAttr(plug.attribute()); + short minVal; + unAttr.getMin(minVal); + short maxVal; + unAttr.getMax(maxVal); + short random = 0; + MStatus status = MS::kFailure; + while (!status) { + random = (rand() % (maxVal - minVal + 1)) + minVal; + unAttr.fieldName(random, &status); + } + EXPECT_EQ(MStatus(MS::kSuccess), plug.setShort(random)); + } break; + + case MFn::kGenericAttribute: { + } break; + + case MFn::kTimeAttribute: randomTime(plug); break; + + case MFn::kFloatAngleAttribute: + case MFn::kDoubleAngleAttribute: randomAngle(plug); break; + + case MFn::kFloatLinearAttribute: + case MFn::kDoubleLinearAttribute: randomDistance(plug); break; default: - std::cout << ("Unknown unit attribute type") << std::endl; - break; - } - } - break; - - case MFn::kMatrixAttribute: - case MFn::kFloatMatrixAttribute: - { - } - break; - - case MFn::kMessageAttribute: - { - } - break; - - case MFn::kEnumAttribute: - { - MFnEnumAttribute unAttr(plug.attribute()); - short minVal; unAttr.getMin(minVal); - short maxVal; unAttr.getMax(maxVal); - short random = 0; - MStatus status = MS::kFailure; - while(!status) - { - random = (rand() % (maxVal - minVal + 1)) + minVal; - unAttr.fieldName(random, &status); + std::cout << ("Unknown attribute type \"") << plug.name().asChar() << "\" " + << plug.attribute().apiTypeStr() << std::endl; + break; } - EXPECT_EQ(MStatus(MS::kSuccess), plug.setShort(random)); - } - break; - - case MFn::kGenericAttribute: - { - } - break; - - case MFn::kTimeAttribute: - randomTime(plug); - break; - - case MFn::kFloatAngleAttribute: - case MFn::kDoubleAngleAttribute: - randomAngle(plug); - break; - - case MFn::kFloatLinearAttribute: - case MFn::kDoubleLinearAttribute: - randomDistance(plug); - break; - - default: - std::cout << ("Unknown attribute type \"") << plug.name().asChar() << "\" " << plug.attribute().apiTypeStr() << std::endl; - break; } - } } //---------------------------------------------------------------------------------------------------------------------- void randomNode(MObject node, const char* const attributeNames[], const uint32_t attributeCount) { - MFnDependencyNode fn(node); - for(uint32_t i = 0; i < attributeCount; ++i) - { - MStatus status; - MPlug plug = fn.findPlug(attributeNames[i], &status); - EXPECT_EQ(MStatus(MS::kSuccess), status); - randomPlug(plug); - } + MFnDependencyNode fn(node); + for (uint32_t i = 0; i < attributeCount; ++i) { + MStatus status; + MPlug plug = fn.findPlug(attributeNames[i], &status); + EXPECT_EQ(MStatus(MS::kSuccess), status); + randomPlug(plug); + } } //---------------------------------------------------------------------------------------------------------------------- void randomAnimatedValue(MPlug plug, double startFrame, double endFrame, bool forceKeyframe) { - // If value is not keyable, set it to be a random value - if (!forceKeyframe && !plug.isKeyable()) - { - randomPlug(plug); - return; - } - - MStatus status; - // Create animation curve and set keys for current attribute in time range - MFnAnimCurve fnCurve; - fnCurve.create(plug, NULL, &status); - EXPECT_EQ(MStatus(MS::kSuccess), status); - - for(double t = startFrame, e = endFrame + 1e-3f; t < e; t += 1.0) - { - MTime tm(t, MTime::kFilm); - - switch (fnCurve.animCurveType()) - { - case MFnAnimCurve::kAnimCurveTL: - case MFnAnimCurve::kAnimCurveTA: - case MFnAnimCurve::kAnimCurveTU: - { - double value = randDouble(); - fnCurve.addKey(tm, value, MFnAnimCurve::kTangentGlobal, MFnAnimCurve::kTangentGlobal, NULL, &status); - EXPECT_EQ(MStatus(MS::kSuccess), status); - break; - } - default: - { - std::cout << "[DgNodeTranslator::setAngleAnim] Unexpected anim curve type: " << fnCurve.animCurveType() << std::endl; - break; - } + // If value is not keyable, set it to be a random value + if (!forceKeyframe && !plug.isKeyable()) { + randomPlug(plug); + return; + } + + MStatus status; + // Create animation curve and set keys for current attribute in time range + MFnAnimCurve fnCurve; + fnCurve.create(plug, NULL, &status); + EXPECT_EQ(MStatus(MS::kSuccess), status); + + for (double t = startFrame, e = endFrame + 1e-3f; t < e; t += 1.0) { + MTime tm(t, MTime::kFilm); + + switch (fnCurve.animCurveType()) { + case MFnAnimCurve::kAnimCurveTL: + case MFnAnimCurve::kAnimCurveTA: + case MFnAnimCurve::kAnimCurveTU: { + double value = randDouble(); + fnCurve.addKey( + tm, + value, + MFnAnimCurve::kTangentGlobal, + MFnAnimCurve::kTangentGlobal, + NULL, + &status); + EXPECT_EQ(MStatus(MS::kSuccess), status); + break; + } + default: { + std::cout << "[DgNodeTranslator::setAngleAnim] Unexpected anim curve type: " + << fnCurve.animCurveType() << std::endl; + break; + } + } } - } } //---------------------------------------------------------------------------------------------------------------------- -void randomAnimatedNode(MObject node, const char* const attributeNames[], const uint32_t attributeCount, double startFrame, double endFrame, bool forceKeyframe) +void randomAnimatedNode( + MObject node, + const char* const attributeNames[], + const uint32_t attributeCount, + double startFrame, + double endFrame, + bool forceKeyframe) { - MStatus status; - MFnDependencyNode fn(node); + MStatus status; + MFnDependencyNode fn(node); - for(uint32_t i = 0; i < attributeCount; ++i) - { - MPlug plug = fn.findPlug(attributeNames[i], &status); - EXPECT_EQ(MStatus(MS::kSuccess), status); + for (uint32_t i = 0; i < attributeCount; ++i) { + MPlug plug = fn.findPlug(attributeNames[i], &status); + EXPECT_EQ(MStatus(MS::kSuccess), status); - switch(plug.attribute().apiType()) - { - case MFn::kNumericAttribute: - { - MFnNumericAttribute unAttr(plug.attribute()); - switch(unAttr.unitType()) - { - case MFnNumericData::kDouble: - case MFnNumericData::kBoolean: - { + switch (plug.attribute().apiType()) { + case MFn::kNumericAttribute: { + MFnNumericAttribute unAttr(plug.attribute()); + switch (unAttr.unitType()) { + case MFnNumericData::kDouble: + case MFnNumericData::kBoolean: { + randomAnimatedValue(plug, startFrame, endFrame, forceKeyframe); + break; + } + case MFnNumericData::k3Float: + case MFnNumericData::k3Double: { + randomAnimatedValue(plug.child(0), startFrame, endFrame, forceKeyframe); + randomAnimatedValue(plug.child(1), startFrame, endFrame, forceKeyframe); + randomAnimatedValue(plug.child(2), startFrame, endFrame, forceKeyframe); + break; + } + default: { + std::cout << ("Unknown numeric attribute type") << std::endl; + break; + } + } + break; + } + case MFn::kFloatLinearAttribute: + case MFn::kDoubleLinearAttribute: { randomAnimatedValue(plug, startFrame, endFrame, forceKeyframe); break; - } - case MFnNumericData::k3Float: - case MFnNumericData::k3Double: - { + } + case MFn::kAttribute3Double: + case MFn::kAttribute3Float: { randomAnimatedValue(plug.child(0), startFrame, endFrame, forceKeyframe); randomAnimatedValue(plug.child(1), startFrame, endFrame, forceKeyframe); randomAnimatedValue(plug.child(2), startFrame, endFrame, forceKeyframe); break; - } - default: - { - std::cout << ("Unknown numeric attribute type") << std::endl; + } + case MFn::kEnumAttribute: + case MFn::kMessageAttribute: { break; - } } - break; - } - case MFn::kFloatLinearAttribute: - case MFn::kDoubleLinearAttribute: - { - randomAnimatedValue(plug, startFrame, endFrame, forceKeyframe); - break; - } - case MFn::kAttribute3Double: - case MFn::kAttribute3Float: - { - randomAnimatedValue(plug.child(0), startFrame, endFrame, forceKeyframe); - randomAnimatedValue(plug.child(1), startFrame, endFrame, forceKeyframe); - randomAnimatedValue(plug.child(2), startFrame, endFrame, forceKeyframe); - break; - } - case MFn::kEnumAttribute: - case MFn::kMessageAttribute: - { - break; - } - default: - { - std::cout << ("Unknown attribute type \"") << plug.name().asChar() << "\" " << plug.attribute().apiTypeStr() << std::endl; - break; - } + default: { + std::cout << ("Unknown attribute type \"") << plug.name().asChar() << "\" " + << plug.attribute().apiTypeStr() << std::endl; + break; + } + } } - } } //---------------------------------------------------------------------------------------------------------------------- -} // test -} // maya -} // AL +} // namespace test +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/mayatest/AL/maya/test/testHelpers.h b/plugin/al/mayatest/AL/maya/test/testHelpers.h index 599f9b73ec..659582f068 100644 --- a/plugin/al/mayatest/AL/maya/test/testHelpers.h +++ b/plugin/al/mayatest/AL/maya/test/testHelpers.h @@ -15,7 +15,7 @@ // #pragma once -#include +#include "AL/maya/test/Api.h" #include #include @@ -24,53 +24,51 @@ #include #include +#include + #include -#include #include - -#include "AL/maya/test/Api.h" +#include namespace AL { namespace maya { namespace test { - #ifdef TRACE_ASSIGNMENT -# define TRACE(X) X; +#define TRACE(X) X; #else -# define TRACE(X) +#define TRACE(X) #endif #if 0 -# define AL_OUTPUT_TEST_NAME(X) std::cerr << X << std::endl; +#define AL_OUTPUT_TEST_NAME(X) std::cerr << X << std::endl; #else -# define AL_OUTPUT_TEST_NAME(X) +#define AL_OUTPUT_TEST_NAME(X) #endif - #if 0 -# define AL_USDMAYA_UNTESTED EXPECT_TRUE(false) +#define AL_USDMAYA_UNTESTED EXPECT_TRUE(false) #else -# define AL_USDMAYA_UNTESTED +#define AL_USDMAYA_UNTESTED #endif - // comparisons between MPlugs require stream operators for cpp unit -inline std::ostream& operator << (std::ostream& os, const MPlug& plug) +inline std::ostream& operator<<(std::ostream& os, const MPlug& plug) { - return os << plug.name().asChar(); + return os << plug.name().asChar(); } // comparisons between MPlugs require stream operators for cpp unit -inline std::ostream& operator << (std::ostream& os, const MObject& obj) +inline std::ostream& operator<<(std::ostream& os, const MObject& obj) { - if(obj == MObject::kNullObj) os << "kNullObj"; - else - os << obj.apiTypeStr(); - return os; + if (obj == MObject::kNullObj) + os << "kNullObj"; + else + os << obj.apiTypeStr(); + return os; } -# define AL_PATH_CHAR "/" +#define AL_PATH_CHAR "/" /// \brief Used to generate a temporary filepath from the given filename. /// \param filename the filename to append to the end of the OS temp dir @@ -87,39 +85,57 @@ AL_MAYA_TEST_PUBLIC void compareTempPaths(std::string pathA, std::string pathB); /// \param plugA the first plug to compare /// \param plugB the second plug to compare /// \param usdTesting if true, when plugA refers to a Time, Angle, or Distance attribute, then -/// plugB is assumed to be a double. This is to work around the inability of USD attributes to understand -/// time values. In most cases you should be able to leave this value as false. -AL_MAYA_TEST_PUBLIC void comparePlugs(const MPlug& plugA, const MPlug& plugB, bool usdTesting = false); - -/// \brief Compares all of the attributes contained on the two nodes to see if the values and types match. This is -/// a way to help test the importers / exporters. i.e. Create a node of a given type, assign random attribute -/// values to it, export, re-import, and then see if the imported matches the exported. +/// plugB is assumed to be a double. This is to work around the inability of USD attributes +/// to understand time values. In most cases you should be able to leave this value as +/// false. +AL_MAYA_TEST_PUBLIC void +comparePlugs(const MPlug& plugA, const MPlug& plugB, bool usdTesting = false); + +/// \brief Compares all of the attributes contained on the two nodes to see if the values and types +/// match. This is +/// a way to help test the importers / exporters. i.e. Create a node of a given type, assign +/// random attribute values to it, export, re-import, and then see if the imported matches +/// the exported. /// \param nodeA the first node to test /// \param nodeB the second node to test /// \param includeDefaultAttrs if true attributes on the node will be tested /// \param includeDynamicAttrs if true dynamically added attributes on the node will be tested /// \param usdTesting if true, when plugA refers to a Time, Angle, or Distance attribute, then -/// plugB is assumed to be a double. This is to work around the inability of USD attributes to understand -/// time values. In most cases you should be able to leave this value as false. -AL_MAYA_TEST_PUBLIC void compareNodes(const MObject& nodeA, const MObject& nodeB, bool includeDefaultAttrs, bool includeDynamicAttrs, bool usdTesting = false); - -/// \brief Compares all of the attributes contained on the two nodes to see if the values and types match. This is -/// a way to help test the importers / exporters. i.e. Create a node of a given type, assign random attribute -/// values to it, export, re-import, and then see if the imported matches the exported. +/// plugB is assumed to be a double. This is to work around the inability of USD attributes +/// to understand time values. In most cases you should be able to leave this value as +/// false. +AL_MAYA_TEST_PUBLIC void compareNodes( + const MObject& nodeA, + const MObject& nodeB, + bool includeDefaultAttrs, + bool includeDynamicAttrs, + bool usdTesting = false); + +/// \brief Compares all of the attributes contained on the two nodes to see if the values and types +/// match. This is +/// a way to help test the importers / exporters. i.e. Create a node of a given type, assign +/// random attribute values to it, export, re-import, and then see if the imported matches +/// the exported. /// \param nodeA the first node to test /// \param nodeB the second node to test /// \param includeDefaultAttrs if true attributes on the node will be tested /// \param includeDynamicAttrs if true dynamically added attributes on the node will be tested /// \param usdTesting if true, when plugA refers to a Time, Angle, or Distance attribute, then -/// plugB is assumed to be a double. This is to work around the inability of USD attributes to understand -/// time values. In most cases you should be able to leave this value as false. -AL_MAYA_TEST_PUBLIC void compareNodes(const MObject& nodeA, const MObject& nodeB, const char* const attributes[], uint32_t attributeCount, bool usdTesting = false); +/// plugB is assumed to be a double. This is to work around the inability of USD attributes +/// to understand time values. In most cases you should be able to leave this value as +/// false. +AL_MAYA_TEST_PUBLIC void compareNodes( + const MObject& nodeA, + const MObject& nodeB, + const char* const attributes[], + uint32_t attributeCount, + bool usdTesting = false); // some random number generators -inline bool randBool() { return (rand() % 2) ? true : false; } -inline float randFloat() { return float(rand()) / RAND_MAX; } -inline double randDouble() { return double(rand()) / RAND_MAX; } -inline int8_t randInt8() { return int8_t(rand()); } +inline bool randBool() { return (rand() % 2) ? true : false; } +inline float randFloat() { return float(rand()) / RAND_MAX; } +inline double randDouble() { return double(rand()) / RAND_MAX; } +inline int8_t randInt8() { return int8_t(rand()); } inline int16_t randInt16() { return int16_t(rand()); } inline int32_t randInt32() { return int32_t(rand()); } inline int64_t randInt64() { return int64_t(rand()); } @@ -129,69 +145,73 @@ inline int64_t randInt64() { return int64_t(rand()); } //---------------------------------------------------------------------------------------------------------------------- inline void randomBool(MPlug plug) { - EXPECT_EQ(MStatus(MS::kSuccess), plug.setBool(randBool())); - TRACE(std::cout << "randomBool " << plug.name().asChar() << " " << plug.asBool() << std::endl); + EXPECT_EQ(MStatus(MS::kSuccess), plug.setBool(randBool())); + TRACE(std::cout << "randomBool " << plug.name().asChar() << " " << plug.asBool() << std::endl); } inline void randomInt8(MPlug plug) { - EXPECT_EQ(MStatus(MS::kSuccess), plug.setChar(randInt8())); - TRACE(std::cout << "randomInt8 " << plug.name().asChar() << " " << plug.asChar() << std::endl); + EXPECT_EQ(MStatus(MS::kSuccess), plug.setChar(randInt8())); + TRACE(std::cout << "randomInt8 " << plug.name().asChar() << " " << plug.asChar() << std::endl); } inline void randomInt16(MPlug plug) { - EXPECT_EQ(MStatus(MS::kSuccess), plug.setShort(randInt16())); - TRACE(std::cout << "randomInt16 " << plug.name().asChar() << " " << plug.asShort() << std::endl); + EXPECT_EQ(MStatus(MS::kSuccess), plug.setShort(randInt16())); + TRACE( + std::cout << "randomInt16 " << plug.name().asChar() << " " << plug.asShort() << std::endl); } inline void randomInt32(MPlug plug) { - EXPECT_EQ(MStatus(MS::kSuccess), plug.setInt(randInt32())); - TRACE(std::cout << "randomInt32 " << plug.name().asChar() << " " << plug.asInt() << std::endl); + EXPECT_EQ(MStatus(MS::kSuccess), plug.setInt(randInt32())); + TRACE(std::cout << "randomInt32 " << plug.name().asChar() << " " << plug.asInt() << std::endl); } inline void randomInt64(MPlug plug) { - EXPECT_EQ(MStatus(MS::kSuccess), plug.setInt(randInt64())); - TRACE(std::cout << "randomInt64 " << plug.name().asChar() << " " << plug.asInt64() << std::endl); + EXPECT_EQ(MStatus(MS::kSuccess), plug.setInt(randInt64())); + TRACE( + std::cout << "randomInt64 " << plug.name().asChar() << " " << plug.asInt64() << std::endl); } inline void randomFloat(MPlug plug) { - EXPECT_EQ(MStatus(MS::kSuccess), plug.setFloat(randFloat())); - TRACE(std::cout << "randomFloat " << plug.name().asChar() << " " << plug.asFloat() << std::endl); + EXPECT_EQ(MStatus(MS::kSuccess), plug.setFloat(randFloat())); + TRACE( + std::cout << "randomFloat " << plug.name().asChar() << " " << plug.asFloat() << std::endl); } inline void randomDouble(MPlug plug) { - EXPECT_EQ(MStatus(MS::kSuccess), plug.setDouble(randDouble())); - TRACE(std::cout << "randomDouble " << plug.name().asChar() << " " << plug.asDouble() << std::endl); + EXPECT_EQ(MStatus(MS::kSuccess), plug.setDouble(randDouble())); + TRACE( + std::cout << "randomDouble " << plug.name().asChar() << " " << plug.asDouble() + << std::endl); } inline void randomAngle(MPlug plug) { - MAngle angle(randDouble(), MAngle::kRadians); - EXPECT_EQ(MStatus(MS::kSuccess), plug.setMAngle(angle)); - TRACE(std::cout << "randomAngle " << plug.name().asChar() << " " << plug.asDouble() << std::endl); + MAngle angle(randDouble(), MAngle::kRadians); + EXPECT_EQ(MStatus(MS::kSuccess), plug.setMAngle(angle)); + TRACE( + std::cout << "randomAngle " << plug.name().asChar() << " " << plug.asDouble() << std::endl); } inline void randomTime(MPlug plug) { - MTime mtime(randDouble(), MTime::kSeconds); - EXPECT_EQ(MStatus(MS::kSuccess), plug.setMTime(mtime)); - TRACE(std::cout << "randomTime " << plug.name().asChar() << " " << plug.asDouble() << std::endl); + MTime mtime(randDouble(), MTime::kSeconds); + EXPECT_EQ(MStatus(MS::kSuccess), plug.setMTime(mtime)); + TRACE( + std::cout << "randomTime " << plug.name().asChar() << " " << plug.asDouble() << std::endl); } inline void randomDistance(MPlug plug) { - MDistance dist(randFloat(), MDistance::kInches); - EXPECT_EQ(MStatus(MS::kSuccess), plug.setMDistance(dist)); - TRACE(std::cout << "randomDistance " << plug.name().asChar() << " " << plug.asDouble() << std::endl); + MDistance dist(randFloat(), MDistance::kInches); + EXPECT_EQ(MStatus(MS::kSuccess), plug.setMDistance(dist)); + TRACE( + std::cout << "randomDistance " << plug.name().asChar() << " " << plug.asDouble() + << std::endl); } inline void randomString(MPlug plug) { - const char* const strings[] = { - "dinosaurs", - "rock", - "and", - "so", - "do", - "cats" - }; - EXPECT_EQ(MStatus(MS::kSuccess), plug.setString(strings[rand() % 6])); - TRACE(std::cout << "randomString " << plug.name().asChar() << " " << plug.asString() << std::endl); + const char* const strings[] = { "dinosaurs", "rock", "and", "so", "do", "cats" }; + EXPECT_EQ(MStatus(MS::kSuccess), plug.setString(strings[rand() % 6])); + TRACE( + std::cout << "randomString " << plug.name().asChar() << " " << plug.asString() + << std::endl); } //---------------------------------------------------------------------------------------------------------------------- @@ -202,17 +222,24 @@ AL_MAYA_TEST_PUBLIC void randomPlug(MPlug plug); //---------------------------------------------------------------------------------------------------------------------- // make a random plug full of random data //---------------------------------------------------------------------------------------------------------------------- -AL_MAYA_TEST_PUBLIC void randomNode(MObject node, const char* const attributeNames[], const uint32_t attributeCount); +AL_MAYA_TEST_PUBLIC void +randomNode(MObject node, const char* const attributeNames[], const uint32_t attributeCount); //---------------------------------------------------------------------------------------------------------------------- // make a random plug full of random data that is animated in the range startFrame -> endFrame //---------------------------------------------------------------------------------------------------------------------- -AL_MAYA_TEST_PUBLIC void randomAnimatedNode(MObject node, const char* const attributeNames[], const uint32_t attributeCount, double startFrame, double endFrame, bool forceKeyframe=false); -AL_MAYA_TEST_PUBLIC void randomAnimatedValue(MPlug plug, double startFrame, double endFrame, bool forceKeyframe=false); - +AL_MAYA_TEST_PUBLIC void randomAnimatedNode( + MObject node, + const char* const attributeNames[], + const uint32_t attributeCount, + double startFrame, + double endFrame, + bool forceKeyframe = false); +AL_MAYA_TEST_PUBLIC void +randomAnimatedValue(MPlug plug, double startFrame, double endFrame, bool forceKeyframe = false); //---------------------------------------------------------------------------------------------------------------------- -} // test -} // maya -} // AL +} // namespace test +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/mayautils/AL/maya/event/Api.h b/plugin/al/mayautils/AL/maya/event/Api.h index 1983fa8acf..1734902867 100644 --- a/plugin/al/mayautils/AL/maya/event/Api.h +++ b/plugin/al/mayautils/AL/maya/event/Api.h @@ -15,26 +15,26 @@ // #if defined _WIN32 || defined __CYGWIN__ - #ifdef AL_MAYA_EVENTS_EXPORT - #ifdef __GNUC__ - #define AL_MAYA_EVENTS_PUBLIC __attribute__ ((dllexport)) - #else - #define AL_MAYA_EVENTS_PUBLIC __declspec(dllexport) - #endif - #else - #ifdef __GNUC__ - #define AL_MAYA_EVENTS_PUBLIC __attribute__ ((dllimport)) - #else - #define AL_MAYA_EVENTS_PUBLIC __declspec(dllimport) - #endif - #endif - #define AL_MAYA_EVENTS_LOCAL +#ifdef AL_MAYA_EVENTS_EXPORT +#ifdef __GNUC__ +#define AL_MAYA_EVENTS_PUBLIC __attribute__((dllexport)) #else - #if __GNUC__ >= 4 - #define AL_MAYA_EVENTS_PUBLIC __attribute__ ((visibility ("default"))) - #define AL_MAYA_EVENTS_LOCAL __attribute__ ((visibility ("hidden"))) - #else - #define AL_MAYA_EVENTS_PUBLIC - #define AL_MAYA_EVENTS_LOCAL - #endif +#define AL_MAYA_EVENTS_PUBLIC __declspec(dllexport) +#endif +#else +#ifdef __GNUC__ +#define AL_MAYA_EVENTS_PUBLIC __attribute__((dllimport)) +#else +#define AL_MAYA_EVENTS_PUBLIC __declspec(dllimport) +#endif +#endif +#define AL_MAYA_EVENTS_LOCAL +#else +#if __GNUC__ >= 4 +#define AL_MAYA_EVENTS_PUBLIC __attribute__((visibility("default"))) +#define AL_MAYA_EVENTS_LOCAL __attribute__((visibility("hidden"))) +#else +#define AL_MAYA_EVENTS_PUBLIC +#define AL_MAYA_EVENTS_LOCAL +#endif #endif \ No newline at end of file diff --git a/plugin/al/mayautils/AL/maya/event/MayaEventManager.cpp b/plugin/al/mayautils/AL/maya/event/MayaEventManager.cpp index 590f7ebedc..6e80521a0d 100644 --- a/plugin/al/mayautils/AL/maya/event/MayaEventManager.cpp +++ b/plugin/al/mayautils/AL/maya/event/MayaEventManager.cpp @@ -19,8 +19,8 @@ #include #include #include -#include #include +#include #include @@ -31,274 +31,281 @@ namespace event { //---------------------------------------------------------------------------------------------------------------------- static void bindBasicFunction(void* ptr) { - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId); } //---------------------------------------------------------------------------------------------------------------------- static void bindCheckFunction(bool* retCode, void* ptr) { - bool result = true; - auto binder = [&result](void* ud, const void* cb) - { - MMessage::MCheckFunction cf = (MMessage::MCheckFunction)cb; - bool temp = true; - cf(&temp, ud); - result = result && temp; - }; + bool result = true; + auto binder = [&result](void* ud, const void* cb) { + MMessage::MCheckFunction cf = (MMessage::MCheckFunction)cb; + bool temp = true; + cf(&temp, ud); + result = result && temp; + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- static void bindCheckPlugFunction(bool* retCode, MPlug& plug, void* ptr) { - bool result = true; - auto binder = [&result, &plug](void* ud, const void* cb) - { - MMessage::MCheckPlugFunction cf = (MMessage::MCheckPlugFunction)cb; - bool temp = true; - cf(&temp, plug, ud); - result = result && temp; - }; + bool result = true; + auto binder = [&result, &plug](void* ud, const void* cb) { + MMessage::MCheckPlugFunction cf = (MMessage::MCheckPlugFunction)cb; + bool temp = true; + cf(&temp, plug, ud); + result = result && temp; + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- static void bindNodeFunction(MObject& node, void* ptr) { - auto binder = [&node](void* ud, const void* cb) - { - MMessage::MNodeFunction cf = (MMessage::MNodeFunction)cb; - cf(node, ud); - }; + auto binder = [&node](void* ud, const void* cb) { + MMessage::MNodeFunction cf = (MMessage::MNodeFunction)cb; + cf(node, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- static void bindStringFunction(const MString& str, void* ptr) { - auto binder = [str](void* ud, const void* cb) - { - MMessage::MStringFunction cf = (MMessage::MStringFunction)cb; - cf(str, ud); - }; + auto binder = [str](void* ud, const void* cb) { + MMessage::MStringFunction cf = (MMessage::MStringFunction)cb; + cf(str, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- -static void bindStringIntBoolIntFunction(const MString& str, uint32_t index, bool flag, uint32_t type, void* ptr) +static void bindStringIntBoolIntFunction( + const MString& str, + uint32_t index, + bool flag, + uint32_t type, + void* ptr) { - auto binder = [str, index, flag, type](void* ud, const void* cb) - { - MMessage::MStringIntBoolIntFunction cf = (MMessage::MStringIntBoolIntFunction)cb; - cf(str, index, flag, type, ud); - }; + auto binder = [str, index, flag, type](void* ud, const void* cb) { + MMessage::MStringIntBoolIntFunction cf = (MMessage::MStringIntBoolIntFunction)cb; + cf(str, index, flag, type, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- static void bindNodeStringBoolFunction(MObject& node, const MString& str, bool flag, void* ptr) { - auto binder = [&node, str, flag](void* ud, const void* cb) - { - MMessage::MNodeStringBoolFunction cf = (MMessage::MNodeStringBoolFunction)cb; - cf(node, str, flag, ud); - }; + auto binder = [&node, str, flag](void* ud, const void* cb) { + MMessage::MNodeStringBoolFunction cf = (MMessage::MNodeStringBoolFunction)cb; + cf(node, str, flag, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- static void bindTimeFunction(MTime& time, void* ptr) { - auto binder = [&time](void* ud, const void* cb) - { - MMessage::MTimeFunction cf = (MMessage::MTimeFunction)cb; - cf(time, ud); - }; + auto binder = [&time](void* ud, const void* cb) { + MMessage::MTimeFunction cf = (MMessage::MTimeFunction)cb; + cf(time, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- static void bindPlugFunction(MPlug& src, MPlug& dst, bool made, void* ptr) { - auto binder = [&src, &dst, made](void* ud, const void* cb) - { - MMessage::MPlugFunction cf = (MMessage::MPlugFunction)cb; - cf(src, dst, made, ud); - }; + auto binder = [&src, &dst, made](void* ud, const void* cb) { + MMessage::MPlugFunction cf = (MMessage::MPlugFunction)cb; + cf(src, dst, made, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- static void bindParentChildFunction(MDagPath& child, MDagPath& parent, void* ptr) { - auto binder = [&child, &parent](void* ud, const void* cb) - { - MMessage::MParentChildFunction cf = (MMessage::MParentChildFunction)cb; - cf(child, parent, ud); - }; + auto binder = [&child, &parent](void* ud, const void* cb) { + MMessage::MParentChildFunction cf = (MMessage::MParentChildFunction)cb; + cf(child, parent, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- static void bindStringArrayFunction(const MStringArray& strs, void* ptr) { - auto binder = [strs](void* ud, const void* cb) - { - MMessage::MStringArrayFunction cf = (MMessage::MStringArrayFunction)cb; - cf(strs, ud); - }; + auto binder = [strs](void* ud, const void* cb) { + MMessage::MStringArrayFunction cf = (MMessage::MStringArrayFunction)cb; + cf(strs, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- static void bindObjArrayFunction(MObjectArray& objects, void* ptr) { - auto binder = [&objects](void* ud, const void* cb) - { - MMessage::MObjArray cf = (MMessage::MObjArray)cb; - cf(objects, ud); - }; + auto binder = [&objects](void* ud, const void* cb) { + MMessage::MObjArray cf = (MMessage::MObjArray)cb; + cf(objects, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- static void bindCameraLayerFunction(MObject& cameraSetNode, uint32_t index, bool added, void* ptr) { - auto binder = [&cameraSetNode, index, added](void* ud, const void* cb) - { - MMessage::MCameraLayerFunction cf = (MMessage::MCameraLayerFunction)cb; - cf(cameraSetNode, index, added, ud); - }; + auto binder = [&cameraSetNode, index, added](void* ud, const void* cb) { + MMessage::MCameraLayerFunction cf = (MMessage::MCameraLayerFunction)cb; + cf(cameraSetNode, index, added, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- -static void bindCameraLayerCameraFunction(MObject& cameraSetNode, uint32_t index, MObject& oldCamera, MObject& newCamera, void* ptr) +static void bindCameraLayerCameraFunction( + MObject& cameraSetNode, + uint32_t index, + MObject& oldCamera, + MObject& newCamera, + void* ptr) { - auto binder = [&cameraSetNode, index, &oldCamera, &newCamera](void* ud, const void* cb) - { - MMessage::MCameraLayerCameraFunction cf = (MMessage::MCameraLayerCameraFunction)cb; - cf(cameraSetNode, index, oldCamera, newCamera, ud); - }; + auto binder = [&cameraSetNode, index, &oldCamera, &newCamera](void* ud, const void* cb) { + MMessage::MCameraLayerCameraFunction cf = (MMessage::MCameraLayerCameraFunction)cb; + cf(cameraSetNode, index, oldCamera, newCamera, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- static void bindPlugsDGModFunction(MPlugArray& plugs, MDGModifier& modifier, void* ptr) { - auto binder = [&plugs, &modifier](void* ud, const void* cb) - { - MMessage::MPlugsDGModFunction cf = (MMessage::MPlugsDGModFunction)cb; - cf(plugs, modifier, ud); - }; + auto binder = [&plugs, &modifier](void* ud, const void* cb) { + MMessage::MPlugsDGModFunction cf = (MMessage::MPlugsDGModFunction)cb; + cf(plugs, modifier, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- -static void bindMessageFunction(const MString& message, MCommandMessage::MessageType messageType, void* ptr) +static void +bindMessageFunction(const MString& message, MCommandMessage::MessageType messageType, void* ptr) { - auto binder = [message, messageType](void* ud, const void* cb) - { - MCommandMessage::MMessageFunction cf = (MCommandMessage::MMessageFunction)cb; - cf(message, messageType, ud); - }; + auto binder = [message, messageType](void* ud, const void* cb) { + MCommandMessage::MMessageFunction cf = (MCommandMessage::MMessageFunction)cb; + cf(message, messageType, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- -static void bindMessageFilterFunction(const MString& message, MCommandMessage::MessageType messageType, bool& filterOutput, void* ptr) +static void bindMessageFilterFunction( + const MString& message, + MCommandMessage::MessageType messageType, + bool& filterOutput, + void* ptr) { - filterOutput = false; - auto binder = [&filterOutput, message, messageType](void* ud, const void* cb) - { - bool temp = false; - MCommandMessage::MMessageFilterFunction cf = (MCommandMessage::MMessageFilterFunction)cb; - cf(message, messageType, temp, ud); - filterOutput = filterOutput || temp; - }; + filterOutput = false; + auto binder = [&filterOutput, message, messageType](void* ud, const void* cb) { + bool temp = false; + MCommandMessage::MMessageFilterFunction cf = (MCommandMessage::MMessageFilterFunction)cb; + cf(message, messageType, temp, ud); + filterOutput = filterOutput || temp; + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- -static void bindMessageParentChildFunction(MDagMessage::DagMessage msgType, MDagPath& child, MDagPath& parent, void* ptr) +static void bindMessageParentChildFunction( + MDagMessage::DagMessage msgType, + MDagPath& child, + MDagPath& parent, + void* ptr) { - auto binder = [msgType, &child, &parent](void* ud, const void* cb) - { - MDagMessage::MMessageParentChildFunction cf = (MDagMessage::MMessageParentChildFunction)cb; - cf(msgType, child, parent, ud); - }; + auto binder = [msgType, &child, &parent](void* ud, const void* cb) { + MDagMessage::MMessageParentChildFunction cf = (MDagMessage::MMessageParentChildFunction)cb; + cf(msgType, child, parent, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } //---------------------------------------------------------------------------------------------------------------------- -static void bindPathObjectPlugColoursFunction(MDagPath& path, MObject& object, MPlug& plug, MColorArray& colors, void* ptr) +static void bindPathObjectPlugColoursFunction( + MDagPath& path, + MObject& object, + MPlug& plug, + MColorArray& colors, + void* ptr) { - auto binder = [&path, &object, &plug, &colors](void* ud, const void* cb) - { - MPaintMessage::MPathObjectPlugColorsFunction cf = (MPaintMessage::MPathObjectPlugColorsFunction)cb; - cf(path, object, plug, colors, ud); - }; + auto binder = [&path, &object, &plug, &colors](void* ud, const void* cb) { + MPaintMessage::MPathObjectPlugColorsFunction cf + = (MPaintMessage::MPathObjectPlugColorsFunction)cb; + cf(path, object, plug, colors, ud); + }; - MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; - auto& scheduler = AL::event::EventScheduler::getScheduler(); - scheduler.triggerEvent(cbi->eventId, binder); + MayaEventHandler::MayaCallbackInfo* cbi = (MayaEventHandler::MayaCallbackInfo*)ptr; + auto& scheduler = AL::event::EventScheduler::getScheduler(); + scheduler.triggerEvent(cbi->eventId, binder); } -// these are functions we will probably want in the long term, however to ensure the OpenSource build does not -// complain about unused symbols, they are hidden behind a #if 0 for now. +// these are functions we will probably want in the long term, however to ensure the OpenSource +// build does not complain about unused symbols, they are hidden behind a #if 0 for now. #if 0 //---------------------------------------------------------------------------------------------------------------------- static void bindElapsedTimeFunction(float elapsed, float last, void* ptr) @@ -561,640 +568,1212 @@ static void bindWorldMatrixModifiedFunction(MObject& transform, MDagMessage::Mat #endif //---------------------------------------------------------------------------------------------------------------------- -MayaEventHandler::MayaEventHandler(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) -{ - m_scheduler = scheduler; - registerAnimMessages(scheduler, eventType); - registerCameraSetMessages(scheduler, eventType); - registerCommandMessages(scheduler, eventType); - registerConditionMessages(scheduler, eventType); - registerContainerMessages(scheduler, eventType); - registerDagMessages(scheduler, eventType); - registerDGMessages(scheduler, eventType); - registerEventMessages(scheduler, eventType); - registerLockMessages(scheduler, eventType); - registerModelMessages(scheduler, eventType); - registerNodeMessages(scheduler, eventType); - registerObjectSetMessages(scheduler, eventType); - registerPaintMessages(scheduler, eventType); - registerPolyMessages(scheduler, eventType); - registerSceneMessages(scheduler, eventType); - registerTimerMessages(scheduler, eventType); - registerUiMessages(scheduler, eventType); - scheduler->registerHandler(eventType, this); +MayaEventHandler::MayaEventHandler( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) +{ + m_scheduler = scheduler; + registerAnimMessages(scheduler, eventType); + registerCameraSetMessages(scheduler, eventType); + registerCommandMessages(scheduler, eventType); + registerConditionMessages(scheduler, eventType); + registerContainerMessages(scheduler, eventType); + registerDagMessages(scheduler, eventType); + registerDGMessages(scheduler, eventType); + registerEventMessages(scheduler, eventType); + registerLockMessages(scheduler, eventType); + registerModelMessages(scheduler, eventType); + registerNodeMessages(scheduler, eventType); + registerObjectSetMessages(scheduler, eventType); + registerPaintMessages(scheduler, eventType); + registerPolyMessages(scheduler, eventType); + registerSceneMessages(scheduler, eventType); + registerTimerMessages(scheduler, eventType); + registerUiMessages(scheduler, eventType); + scheduler->registerHandler(eventType, this); } //---------------------------------------------------------------------------------------------------------------------- bool MayaEventHandler::registerEvent( - AL::event::EventScheduler* scheduler, - const char* eventName, - AL::event::EventType eventType, - MayaMessageType messageType, - MayaCallbackType callbackType, - uint32_t mmessageEnum) -{ - // first register the new event with the scheduler - AL::event::EventId id = scheduler->registerEvent(eventName, eventType); - if(!id) - { - std::cout << "failed to register event " << eventName << std::endl; - return false; - } - - auto index = m_callbacks.size(); - MayaCallbackInfo cb = { - id, - 0, - messageType, - callbackType, - mmessageEnum, - 0 - }; - m_callbacks.push_back(cb); - m_eventMapping[id] = index; + AL::event::EventScheduler* scheduler, + const char* eventName, + AL::event::EventType eventType, + MayaMessageType messageType, + MayaCallbackType callbackType, + uint32_t mmessageEnum) +{ + // first register the new event with the scheduler + AL::event::EventId id = scheduler->registerEvent(eventName, eventType); + if (!id) { + std::cout << "failed to register event " << eventName << std::endl; + return false; + } + + auto index = m_callbacks.size(); + MayaCallbackInfo cb = { id, 0, messageType, callbackType, mmessageEnum, 0 }; + m_callbacks.push_back(cb); + m_eventMapping[id] = index; - return true; + return true; } //---------------------------------------------------------------------------------------------------------------------- void MayaEventHandler::onCallbackCreated(const AL::event::CallbackId callbackId) { - AL::event::EventId id = AL::event::extractEventId(callbackId); - - EventToMaya::iterator it = m_eventMapping.find(id); - if(it != m_eventMapping.end()) - { - const uint32_t index = it->second; - auto& event = m_callbacks[index]; - // if ref count is zero, register callback with maya - if(!event.refCount) - { - initEvent(event); + AL::event::EventId id = AL::event::extractEventId(callbackId); + + EventToMaya::iterator it = m_eventMapping.find(id); + if (it != m_eventMapping.end()) { + const uint32_t index = it->second; + auto& event = m_callbacks[index]; + // if ref count is zero, register callback with maya + if (!event.refCount) { + initEvent(event); + } + ++event.refCount; } - ++event.refCount; - } } //---------------------------------------------------------------------------------------------------------------------- void MayaEventHandler::onCallbackDestroyed(const AL::event::CallbackId callbackId) { - AL::event::EventId id = AL::event::extractEventId(callbackId); - EventToMaya::iterator it = m_eventMapping.find(id); - if(it != m_eventMapping.end()) - { - const uint32_t index = it->second; - auto& event = m_callbacks[index]; - --event.refCount; - - // if reduced callback count has hit zero, destroy maya callback - if(!event.refCount) - { - MMessage::removeCallback(event.mayaCallback); - event.mayaCallback = 0; + AL::event::EventId id = AL::event::extractEventId(callbackId); + EventToMaya::iterator it = m_eventMapping.find(id); + if (it != m_eventMapping.end()) { + const uint32_t index = it->second; + auto& event = m_callbacks[index]; + --event.refCount; + + // if reduced callback count has hit zero, destroy maya callback + if (!event.refCount) { + MMessage::removeCallback(event.mayaCallback); + event.mayaCallback = 0; + } } - } } - //---------------------------------------------------------------------------------------------------------------------- void MayaEventHandler::initAnimMessage(MayaCallbackInfo& cbi) { - switch(cbi.mmessageEnum) - { - case AnimMessage::kAnimCurveEdited: cbi.mayaCallback = MAnimMessage::addAnimCurveEditedCallback(bindObjArrayFunction, &cbi); break; - case AnimMessage::kAnimKeyFrameEdited: cbi.mayaCallback = MAnimMessage::addAnimKeyframeEditedCallback(bindObjArrayFunction, &cbi); break; - case AnimMessage::kNodeAnimKeyframeEdited: /* unsupported */ break; - case AnimMessage::kAnimKeyframeEditCheck: cbi.mayaCallback = MAnimMessage::addAnimKeyframeEditCheckCallback(bindCheckPlugFunction, &cbi); break; - case AnimMessage::kPreBakeResults: cbi.mayaCallback = MAnimMessage::addPreBakeResultsCallback(bindPlugsDGModFunction, &cbi); break; - case AnimMessage::kPostBakeResults: cbi.mayaCallback = MAnimMessage::addPostBakeResultsCallback(bindPlugsDGModFunction, &cbi); break; - case AnimMessage::kDisableImplicitControl: cbi.mayaCallback = MAnimMessage::addDisableImplicitControlCallback(bindPlugsDGModFunction, &cbi); break; - default: break; - } + switch (cbi.mmessageEnum) { + case AnimMessage::kAnimCurveEdited: + cbi.mayaCallback = MAnimMessage::addAnimCurveEditedCallback(bindObjArrayFunction, &cbi); + break; + case AnimMessage::kAnimKeyFrameEdited: + cbi.mayaCallback = MAnimMessage::addAnimKeyframeEditedCallback(bindObjArrayFunction, &cbi); + break; + case AnimMessage::kNodeAnimKeyframeEdited: /* unsupported */ break; + case AnimMessage::kAnimKeyframeEditCheck: + cbi.mayaCallback + = MAnimMessage::addAnimKeyframeEditCheckCallback(bindCheckPlugFunction, &cbi); + break; + case AnimMessage::kPreBakeResults: + cbi.mayaCallback = MAnimMessage::addPreBakeResultsCallback(bindPlugsDGModFunction, &cbi); + break; + case AnimMessage::kPostBakeResults: + cbi.mayaCallback = MAnimMessage::addPostBakeResultsCallback(bindPlugsDGModFunction, &cbi); + break; + case AnimMessage::kDisableImplicitControl: + cbi.mayaCallback + = MAnimMessage::addDisableImplicitControlCallback(bindPlugsDGModFunction, &cbi); + break; + default: break; + } } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerAnimMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) -{ - registerEvent(scheduler, "AnimCurveEdited", eventType, MayaMessageType::kAnimMessage, MayaCallbackType::kObjArrayFunction, AnimMessage::kAnimCurveEdited); - registerEvent(scheduler, "AnimKeyFrameEdited", eventType, MayaMessageType::kAnimMessage, MayaCallbackType::kObjArrayFunction, AnimMessage::kAnimKeyFrameEdited); - //registerEvent(scheduler, "NodeAnimKeyframeEdited", eventType, MayaMessageType::kAnimMessage, MayaCallbackType::kNodeObjArrayFunction, AnimMessage::kNodeAnimKeyframeEdited); - registerEvent(scheduler, "AnimKeyframeEditCheck", eventType, MayaMessageType::kAnimMessage, MayaCallbackType::kCheckPlugFunction, AnimMessage::kAnimKeyframeEditCheck); - registerEvent(scheduler, "PreBakeResults", eventType, MayaMessageType::kAnimMessage, MayaCallbackType::kPlugsDGModFunction, AnimMessage::kPreBakeResults); - registerEvent(scheduler, "PostBakeResults", eventType, MayaMessageType::kAnimMessage, MayaCallbackType::kPlugsDGModFunction, AnimMessage::kPostBakeResults); - registerEvent(scheduler, "DisableImplicitControl", eventType, MayaMessageType::kAnimMessage, MayaCallbackType::kPlugsDGModFunction, AnimMessage::kDisableImplicitControl); +void MayaEventHandler::registerAnimMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) +{ + registerEvent( + scheduler, + "AnimCurveEdited", + eventType, + MayaMessageType::kAnimMessage, + MayaCallbackType::kObjArrayFunction, + AnimMessage::kAnimCurveEdited); + registerEvent( + scheduler, + "AnimKeyFrameEdited", + eventType, + MayaMessageType::kAnimMessage, + MayaCallbackType::kObjArrayFunction, + AnimMessage::kAnimKeyFrameEdited); + // registerEvent(scheduler, "NodeAnimKeyframeEdited", eventType, MayaMessageType::kAnimMessage, + // MayaCallbackType::kNodeObjArrayFunction, AnimMessage::kNodeAnimKeyframeEdited); + registerEvent( + scheduler, + "AnimKeyframeEditCheck", + eventType, + MayaMessageType::kAnimMessage, + MayaCallbackType::kCheckPlugFunction, + AnimMessage::kAnimKeyframeEditCheck); + registerEvent( + scheduler, + "PreBakeResults", + eventType, + MayaMessageType::kAnimMessage, + MayaCallbackType::kPlugsDGModFunction, + AnimMessage::kPreBakeResults); + registerEvent( + scheduler, + "PostBakeResults", + eventType, + MayaMessageType::kAnimMessage, + MayaCallbackType::kPlugsDGModFunction, + AnimMessage::kPostBakeResults); + registerEvent( + scheduler, + "DisableImplicitControl", + eventType, + MayaMessageType::kAnimMessage, + MayaCallbackType::kPlugsDGModFunction, + AnimMessage::kDisableImplicitControl); } //---------------------------------------------------------------------------------------------------------------------- void MayaEventHandler::initCameraSetMessage(MayaCallbackInfo& cbi) { - switch(cbi.mmessageEnum) - { - case CameraSetMessage::kCameraLayer: cbi.mayaCallback = MCameraSetMessage::addCameraLayerCallback(bindCameraLayerFunction, &cbi); break; - case CameraSetMessage::kCameraChanged: cbi.mayaCallback = MCameraSetMessage::addCameraChangedCallback(bindCameraLayerCameraFunction, &cbi); break; - default: break; - } + switch (cbi.mmessageEnum) { + case CameraSetMessage::kCameraLayer: + cbi.mayaCallback = MCameraSetMessage::addCameraLayerCallback(bindCameraLayerFunction, &cbi); + break; + case CameraSetMessage::kCameraChanged: + cbi.mayaCallback + = MCameraSetMessage::addCameraChangedCallback(bindCameraLayerCameraFunction, &cbi); + break; + default: break; + } } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerCameraSetMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) +void MayaEventHandler::registerCameraSetMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) { - registerEvent(scheduler, "CameraLayer", eventType, MayaMessageType::kCameraSetMessage, MayaCallbackType::kCameraLayerFunction, CameraSetMessage::kCameraLayer); - registerEvent(scheduler, "CameraChanged", eventType, MayaMessageType::kCameraSetMessage, MayaCallbackType::kCameraLayerCameraFunction, CameraSetMessage::kCameraChanged); + registerEvent( + scheduler, + "CameraLayer", + eventType, + MayaMessageType::kCameraSetMessage, + MayaCallbackType::kCameraLayerFunction, + CameraSetMessage::kCameraLayer); + registerEvent( + scheduler, + "CameraChanged", + eventType, + MayaMessageType::kCameraSetMessage, + MayaCallbackType::kCameraLayerCameraFunction, + CameraSetMessage::kCameraChanged); } - //---------------------------------------------------------------------------------------------------------------------- void MayaEventHandler::initCommandMessage(MayaCallbackInfo& cbi) { - switch(cbi.mmessageEnum) - { - case CommandMessage::kCommand: cbi.mayaCallback = MCommandMessage::addCommandCallback(bindStringFunction, &cbi); break; - case CommandMessage::kCommandOuptut: cbi.mayaCallback = MCommandMessage::addCommandOutputCallback(bindMessageFunction, &cbi); break; - case CommandMessage::kCommandOutputFilter: cbi.mayaCallback = MCommandMessage::addCommandOutputFilterCallback(bindMessageFilterFunction, &cbi); break; - case CommandMessage::kProc: cbi.mayaCallback = MCommandMessage::addProcCallback(bindStringIntBoolIntFunction, &cbi, 0); break; - default: break; - } + switch (cbi.mmessageEnum) { + case CommandMessage::kCommand: + cbi.mayaCallback = MCommandMessage::addCommandCallback(bindStringFunction, &cbi); + break; + case CommandMessage::kCommandOuptut: + cbi.mayaCallback = MCommandMessage::addCommandOutputCallback(bindMessageFunction, &cbi); + break; + case CommandMessage::kCommandOutputFilter: + cbi.mayaCallback + = MCommandMessage::addCommandOutputFilterCallback(bindMessageFilterFunction, &cbi); + break; + case CommandMessage::kProc: + cbi.mayaCallback = MCommandMessage::addProcCallback(bindStringIntBoolIntFunction, &cbi, 0); + break; + default: break; + } } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerCommandMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) +void MayaEventHandler::registerCommandMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) { - registerEvent(scheduler, "Command", eventType, MayaMessageType::kCommandMessage, MayaCallbackType::kStringFunction, CommandMessage::kCommand); - registerEvent(scheduler, "CommandOuptut", eventType, MayaMessageType::kCommandMessage, MayaCallbackType::kMessageFunction, CommandMessage::kCommandOuptut); - registerEvent(scheduler, "CommandOutputFilter", eventType, MayaMessageType::kCommandMessage, MayaCallbackType::kMessageFilterFunction, CommandMessage::kCommandOutputFilter); - registerEvent(scheduler, "Proc", eventType, MayaMessageType::kCommandMessage, MayaCallbackType::kStringIntBoolIntFunction, CommandMessage::kProc); + registerEvent( + scheduler, + "Command", + eventType, + MayaMessageType::kCommandMessage, + MayaCallbackType::kStringFunction, + CommandMessage::kCommand); + registerEvent( + scheduler, + "CommandOuptut", + eventType, + MayaMessageType::kCommandMessage, + MayaCallbackType::kMessageFunction, + CommandMessage::kCommandOuptut); + registerEvent( + scheduler, + "CommandOutputFilter", + eventType, + MayaMessageType::kCommandMessage, + MayaCallbackType::kMessageFilterFunction, + CommandMessage::kCommandOutputFilter); + registerEvent( + scheduler, + "Proc", + eventType, + MayaMessageType::kCommandMessage, + MayaCallbackType::kStringIntBoolIntFunction, + CommandMessage::kProc); } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::initConditionMessage(MayaCallbackInfo& cbi) -{ -} +void MayaEventHandler::initConditionMessage(MayaCallbackInfo& cbi) { } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerConditionMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) +void MayaEventHandler::registerConditionMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) { } //---------------------------------------------------------------------------------------------------------------------- void MayaEventHandler::initContainerMessage(MayaCallbackInfo& cbi) { - switch(cbi.mmessageEnum) - { - case ContainerMessage::kPublishAttr: cbi.mayaCallback = MContainerMessage::addPublishAttrCallback(bindNodeStringBoolFunction, &cbi); break; - case ContainerMessage::kBoundAttr: cbi.mayaCallback = MContainerMessage::addBoundAttrCallback(bindNodeStringBoolFunction, &cbi); break; - default: break; - } + switch (cbi.mmessageEnum) { + case ContainerMessage::kPublishAttr: + cbi.mayaCallback + = MContainerMessage::addPublishAttrCallback(bindNodeStringBoolFunction, &cbi); + break; + case ContainerMessage::kBoundAttr: + cbi.mayaCallback + = MContainerMessage::addBoundAttrCallback(bindNodeStringBoolFunction, &cbi); + break; + default: break; + } } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerContainerMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) +void MayaEventHandler::registerContainerMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) { - registerEvent(scheduler, "PublishAttr", eventType, MayaMessageType::kContainerMessage, MayaCallbackType::kNodeStringBoolFunction, ContainerMessage::kPublishAttr); - registerEvent(scheduler, "BoundAttr", eventType, MayaMessageType::kContainerMessage, MayaCallbackType::kNodeStringBoolFunction, ContainerMessage::kBoundAttr); + registerEvent( + scheduler, + "PublishAttr", + eventType, + MayaMessageType::kContainerMessage, + MayaCallbackType::kNodeStringBoolFunction, + ContainerMessage::kPublishAttr); + registerEvent( + scheduler, + "BoundAttr", + eventType, + MayaMessageType::kContainerMessage, + MayaCallbackType::kNodeStringBoolFunction, + ContainerMessage::kBoundAttr); } //---------------------------------------------------------------------------------------------------------------------- void MayaEventHandler::initDagMessage(MayaCallbackInfo& cbi) { - switch(cbi.mmessageEnum) - { - case DagMessage::kParentAdded: cbi.mayaCallback = MDagMessage::addParentAddedCallback(bindParentChildFunction, &cbi); break; - case DagMessage::kParentAddedDagPath: /* cbi.mayaCallback = MDagMessage::addParentAddedDagPathCallback(bindNodeStringBoolFunc, &cbi); */ break; - case DagMessage::kParentRemoved: cbi.mayaCallback = MDagMessage::addParentRemovedCallback(bindParentChildFunction, &cbi); break; - case DagMessage::kParentRemovedDagPath: /* cbi.mayaCallback = MDagMessage::addParentRemovedDagPathCallback(bindNodeStringBoolFunc, &cbi); */ break; - case DagMessage::kChildAdded: cbi.mayaCallback = MDagMessage::addChildAddedCallback(bindParentChildFunction, &cbi); break; - case DagMessage::kChildAddedDagPath: /* cbi.mayaCallback = MContainerMessage::addChildAddedDagPathCallback(bindNodeStringBoolFunc, &cbi); */ break; - case DagMessage::kChildRemoved: cbi.mayaCallback = MDagMessage::addChildRemovedCallback(bindParentChildFunction, &cbi); break; - case DagMessage::kChildRemovedDagPath: /* cbi.mayaCallback = MDagMessage::addChildRemovedDagPathCallback(bindNodeStringBoolFunc, &cbi); */ break; - case DagMessage::kChildReordered: cbi.mayaCallback = MDagMessage::addChildReorderedCallback(bindParentChildFunction, &cbi); break; - case DagMessage::kChildReorderedDagPath: /* cbi.mayaCallback = MDagMessage::addChildReorderedDagPathCallback(bindNodeStringBoolFunc, &cbi); */ break; - case DagMessage::kDag: /* cbi.mayaCallback = MDagMessage::addDagCallback(bindMessageParentChildFunction, &cbi); */ break; - case DagMessage::kDagDagPath: /* cbi.mayaCallback = MDagMessage::addDagDagPathCallback(bindNodeStringBoolFunc, &cbi); */ break; - case DagMessage::kAllDagChanges: cbi.mayaCallback = MDagMessage::addAllDagChangesCallback(bindMessageParentChildFunction, &cbi); break; - case DagMessage::kAllDagChangesDagPath: /* cbi.mayaCallback = MDagMessage::addAllDagChangesDagPathCallback(bindNodeStringBoolFunc, &cbi); */ break; - case DagMessage::kInstanceAdded: cbi.mayaCallback = MDagMessage::addInstanceAddedCallback(bindParentChildFunction, &cbi); break; - case DagMessage::kInstanceAddedDagPath: /* cbi.mayaCallback = MDagMessage::addInstanceAddedDagPathCallback(bindNodeStringBoolFunc, &cbi); */ break; - case DagMessage::kInstanceRemoved: cbi.mayaCallback = MDagMessage::addInstanceRemovedCallback(bindParentChildFunction, &cbi); break; - case DagMessage::kInstanceRemovedDagPath: /* cbi.mayaCallback = MDagMessage::addInstanceRemovedDagPathCallback(bindNodeStringBoolFunc, &cbi); */ break; - case DagMessage::kWorldMatrixModified: /* cbi.mayaCallback = MDagMessage::addWorldMatrixModifiedCallback(bindNodeStringBoolFunc, &cbi); */ break; - default: break; - } -} - -//---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerDagMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) -{ - registerEvent(scheduler, "ParentAdded", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kParentChildFunction, DagMessage::kParentAdded); - registerEvent(scheduler, "ParentRemoved", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kParentChildFunction, DagMessage::kParentRemoved); - registerEvent(scheduler, "ChildAdded", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kParentChildFunction, DagMessage::kChildAdded); - registerEvent(scheduler, "ChildRemoved", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kParentChildFunction, DagMessage::kChildRemoved); - registerEvent(scheduler, "ChildReordered", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kParentChildFunction, DagMessage::kChildReordered); - //registerEvent(scheduler, "Dag", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kMessageParentChildFunction, DagMessage::kDag); - registerEvent(scheduler, "AllDagChanges", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kMessageParentChildFunction, DagMessage::kAllDagChanges); - registerEvent(scheduler, "InstanceAdded", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kParentChildFunction, DagMessage::kInstanceAdded); - registerEvent(scheduler, "InstanceRemoved", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kParentChildFunction, DagMessage::kInstanceRemoved); -} - -//---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::initDGMessage(MayaCallbackInfo& cbi) -{ - switch(cbi.mmessageEnum) - { - case DGMessage::kTimeChange: cbi.mayaCallback = MDGMessage::addTimeChangeCallback(bindTimeFunction, &cbi); break; - case DGMessage::kDelayedTimeChange: cbi.mayaCallback = MDGMessage::addDelayedTimeChangeCallback(bindTimeFunction, &cbi); break; - case DGMessage::kDelayedTimeChangeRunup: cbi.mayaCallback = MDGMessage::addDelayedTimeChangeRunupCallback(bindTimeFunction, &cbi); break; - case DGMessage::kForceUpdate: cbi.mayaCallback = MDGMessage::addForceUpdateCallback(bindTimeFunction, &cbi); break; - case DGMessage::kNodeAdded: cbi.mayaCallback = MDGMessage::addNodeAddedCallback(bindNodeFunction, kDefaultNodeType, &cbi); break; - case DGMessage::kNodeRemoved: cbi.mayaCallback = MDGMessage::addNodeRemovedCallback(bindNodeFunction, kDefaultNodeType, &cbi); break; - case DGMessage::kConnection: cbi.mayaCallback = MDGMessage::addConnectionCallback(bindPlugFunction, &cbi); break; - case DGMessage::kPreConnection: cbi.mayaCallback = MDGMessage::addPreConnectionCallback(bindPlugFunction, &cbi); break; - default: break; - } -} - -//---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerDGMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) -{ - registerEvent(scheduler, "TimeChange", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kTimeFunction, DGMessage::kTimeChange); - registerEvent(scheduler, "DelayedTimeChange", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kTimeFunction, DGMessage::kDelayedTimeChange); - registerEvent(scheduler, "DelayedTimeChangeRunup", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kTimeFunction, DGMessage::kDelayedTimeChangeRunup); - registerEvent(scheduler, "ForceUpdate", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kTimeFunction, DGMessage::kForceUpdate); - registerEvent(scheduler, "NodeAdded", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kNodeFunction, DGMessage::kNodeAdded); - registerEvent(scheduler, "NodeRemoved", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kNodeFunction, DGMessage::kNodeRemoved); - registerEvent(scheduler, "Connection", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kPlugFunction, DGMessage::kConnection); - registerEvent(scheduler, "PreConnection", eventType, MayaMessageType::kDagMessage, MayaCallbackType::kPlugFunction, DGMessage::kPreConnection); -} - -//---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::initEventMessage(MayaCallbackInfo& cbi) -{ + switch (cbi.mmessageEnum) { + case DagMessage::kParentAdded: + cbi.mayaCallback = MDagMessage::addParentAddedCallback(bindParentChildFunction, &cbi); + break; + case DagMessage::kParentAddedDagPath: /* cbi.mayaCallback = + MDagMessage::addParentAddedDagPathCallback(bindNodeStringBoolFunc, + &cbi); */ + break; + case DagMessage::kParentRemoved: + cbi.mayaCallback = MDagMessage::addParentRemovedCallback(bindParentChildFunction, &cbi); + break; + case DagMessage::kParentRemovedDagPath: /* cbi.mayaCallback = + MDagMessage::addParentRemovedDagPathCallback(bindNodeStringBoolFunc, + &cbi); */ + break; + case DagMessage::kChildAdded: + cbi.mayaCallback = MDagMessage::addChildAddedCallback(bindParentChildFunction, &cbi); + break; + case DagMessage::kChildAddedDagPath: /* cbi.mayaCallback = + MContainerMessage::addChildAddedDagPathCallback(bindNodeStringBoolFunc, + &cbi); */ + break; + case DagMessage::kChildRemoved: + cbi.mayaCallback = MDagMessage::addChildRemovedCallback(bindParentChildFunction, &cbi); + break; + case DagMessage::kChildRemovedDagPath: /* cbi.mayaCallback = + MDagMessage::addChildRemovedDagPathCallback(bindNodeStringBoolFunc, + &cbi); */ + break; + case DagMessage::kChildReordered: + cbi.mayaCallback = MDagMessage::addChildReorderedCallback(bindParentChildFunction, &cbi); + break; + case DagMessage::kChildReorderedDagPath: /* cbi.mayaCallback = + MDagMessage::addChildReorderedDagPathCallback(bindNodeStringBoolFunc, + &cbi); */ + break; + case DagMessage::kDag: /* cbi.mayaCallback = + MDagMessage::addDagCallback(bindMessageParentChildFunction, &cbi); */ + break; + case DagMessage::kDagDagPath: /* cbi.mayaCallback = + MDagMessage::addDagDagPathCallback(bindNodeStringBoolFunc, + &cbi); */ + break; + case DagMessage::kAllDagChanges: + cbi.mayaCallback + = MDagMessage::addAllDagChangesCallback(bindMessageParentChildFunction, &cbi); + break; + case DagMessage::kAllDagChangesDagPath: /* cbi.mayaCallback = + MDagMessage::addAllDagChangesDagPathCallback(bindNodeStringBoolFunc, + &cbi); */ + break; + case DagMessage::kInstanceAdded: + cbi.mayaCallback = MDagMessage::addInstanceAddedCallback(bindParentChildFunction, &cbi); + break; + case DagMessage::kInstanceAddedDagPath: /* cbi.mayaCallback = + MDagMessage::addInstanceAddedDagPathCallback(bindNodeStringBoolFunc, + &cbi); */ + break; + case DagMessage::kInstanceRemoved: + cbi.mayaCallback = MDagMessage::addInstanceRemovedCallback(bindParentChildFunction, &cbi); + break; + case DagMessage::kInstanceRemovedDagPath: /* cbi.mayaCallback = + MDagMessage::addInstanceRemovedDagPathCallback(bindNodeStringBoolFunc, + &cbi); */ + break; + case DagMessage::kWorldMatrixModified: /* cbi.mayaCallback = + MDagMessage::addWorldMatrixModifiedCallback(bindNodeStringBoolFunc, + &cbi); */ + break; + default: break; + } } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerEventMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) -{ +void MayaEventHandler::registerDagMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) +{ + registerEvent( + scheduler, + "ParentAdded", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kParentChildFunction, + DagMessage::kParentAdded); + registerEvent( + scheduler, + "ParentRemoved", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kParentChildFunction, + DagMessage::kParentRemoved); + registerEvent( + scheduler, + "ChildAdded", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kParentChildFunction, + DagMessage::kChildAdded); + registerEvent( + scheduler, + "ChildRemoved", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kParentChildFunction, + DagMessage::kChildRemoved); + registerEvent( + scheduler, + "ChildReordered", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kParentChildFunction, + DagMessage::kChildReordered); + // registerEvent(scheduler, "Dag", eventType, MayaMessageType::kDagMessage, + // MayaCallbackType::kMessageParentChildFunction, DagMessage::kDag); + registerEvent( + scheduler, + "AllDagChanges", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kMessageParentChildFunction, + DagMessage::kAllDagChanges); + registerEvent( + scheduler, + "InstanceAdded", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kParentChildFunction, + DagMessage::kInstanceAdded); + registerEvent( + scheduler, + "InstanceRemoved", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kParentChildFunction, + DagMessage::kInstanceRemoved); } - //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::initLockMessage(MayaCallbackInfo& cbi) +void MayaEventHandler::initDGMessage(MayaCallbackInfo& cbi) { + switch (cbi.mmessageEnum) { + case DGMessage::kTimeChange: + cbi.mayaCallback = MDGMessage::addTimeChangeCallback(bindTimeFunction, &cbi); + break; + case DGMessage::kDelayedTimeChange: + cbi.mayaCallback = MDGMessage::addDelayedTimeChangeCallback(bindTimeFunction, &cbi); + break; + case DGMessage::kDelayedTimeChangeRunup: + cbi.mayaCallback = MDGMessage::addDelayedTimeChangeRunupCallback(bindTimeFunction, &cbi); + break; + case DGMessage::kForceUpdate: + cbi.mayaCallback = MDGMessage::addForceUpdateCallback(bindTimeFunction, &cbi); + break; + case DGMessage::kNodeAdded: + cbi.mayaCallback + = MDGMessage::addNodeAddedCallback(bindNodeFunction, kDefaultNodeType, &cbi); + break; + case DGMessage::kNodeRemoved: + cbi.mayaCallback + = MDGMessage::addNodeRemovedCallback(bindNodeFunction, kDefaultNodeType, &cbi); + break; + case DGMessage::kConnection: + cbi.mayaCallback = MDGMessage::addConnectionCallback(bindPlugFunction, &cbi); + break; + case DGMessage::kPreConnection: + cbi.mayaCallback = MDGMessage::addPreConnectionCallback(bindPlugFunction, &cbi); + break; + default: break; + } } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerLockMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) +void MayaEventHandler::registerDGMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) +{ + registerEvent( + scheduler, + "TimeChange", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kTimeFunction, + DGMessage::kTimeChange); + registerEvent( + scheduler, + "DelayedTimeChange", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kTimeFunction, + DGMessage::kDelayedTimeChange); + registerEvent( + scheduler, + "DelayedTimeChangeRunup", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kTimeFunction, + DGMessage::kDelayedTimeChangeRunup); + registerEvent( + scheduler, + "ForceUpdate", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kTimeFunction, + DGMessage::kForceUpdate); + registerEvent( + scheduler, + "NodeAdded", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kNodeFunction, + DGMessage::kNodeAdded); + registerEvent( + scheduler, + "NodeRemoved", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kNodeFunction, + DGMessage::kNodeRemoved); + registerEvent( + scheduler, + "Connection", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kPlugFunction, + DGMessage::kConnection); + registerEvent( + scheduler, + "PreConnection", + eventType, + MayaMessageType::kDagMessage, + MayaCallbackType::kPlugFunction, + DGMessage::kPreConnection); +} + +//---------------------------------------------------------------------------------------------------------------------- +void MayaEventHandler::initEventMessage(MayaCallbackInfo& cbi) { } + +//---------------------------------------------------------------------------------------------------------------------- +void MayaEventHandler::registerEventMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) +{ +} + +//---------------------------------------------------------------------------------------------------------------------- +void MayaEventHandler::initLockMessage(MayaCallbackInfo& cbi) { } + +//---------------------------------------------------------------------------------------------------------------------- +void MayaEventHandler::registerLockMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) { } //---------------------------------------------------------------------------------------------------------------------- void MayaEventHandler::initModelMessage(MayaCallbackInfo& cbi) { - switch(cbi.mmessageEnum) - { - case ModelMessage::kCallback: cbi.mayaCallback = MModelMessage::addCallback(MModelMessage::kActiveListModified, bindBasicFunction, &cbi); break; - case ModelMessage::kBeforeDuplicate: cbi.mayaCallback = MModelMessage::addBeforeDuplicateCallback(bindBasicFunction, &cbi); break; - case ModelMessage::kAfterDuplicate: cbi.mayaCallback = MModelMessage::addAfterDuplicateCallback(bindBasicFunction, &cbi); break; - case ModelMessage::kNodeAddedToModel: /* cbi.mayaCallback = MModelMessage::addNodeAddedToModelCallback(bindTimeFunction, &cbi); */ break; - case ModelMessage::kNodeRemovedFromModel: /* cbi.mayaCallback = MModelMessage::addNodeRemovedFromModelCallback(bindTimeFunction, &cbi); */ break; - default: break; - } + switch (cbi.mmessageEnum) { + case ModelMessage::kCallback: + cbi.mayaCallback = MModelMessage::addCallback( + MModelMessage::kActiveListModified, bindBasicFunction, &cbi); + break; + case ModelMessage::kBeforeDuplicate: + cbi.mayaCallback = MModelMessage::addBeforeDuplicateCallback(bindBasicFunction, &cbi); + break; + case ModelMessage::kAfterDuplicate: + cbi.mayaCallback = MModelMessage::addAfterDuplicateCallback(bindBasicFunction, &cbi); + break; + case ModelMessage::kNodeAddedToModel: /* cbi.mayaCallback = + MModelMessage::addNodeAddedToModelCallback(bindTimeFunction, + &cbi); */ + break; + case ModelMessage::kNodeRemovedFromModel: /* cbi.mayaCallback = + MModelMessage::addNodeRemovedFromModelCallback(bindTimeFunction, + &cbi); */ + break; + default: break; + } } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerModelMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) +void MayaEventHandler::registerModelMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) { - registerEvent(scheduler, "Callback", eventType, MayaMessageType::kModelMessage, MayaCallbackType::kBasicFunction, ModelMessage::kCallback); - registerEvent(scheduler, "BeforeDuplicate", eventType, MayaMessageType::kModelMessage, MayaCallbackType::kBasicFunction, ModelMessage::kBeforeDuplicate); - registerEvent(scheduler, "AfterDuplicate", eventType, MayaMessageType::kModelMessage, MayaCallbackType::kBasicFunction, ModelMessage::kAfterDuplicate); + registerEvent( + scheduler, + "Callback", + eventType, + MayaMessageType::kModelMessage, + MayaCallbackType::kBasicFunction, + ModelMessage::kCallback); + registerEvent( + scheduler, + "BeforeDuplicate", + eventType, + MayaMessageType::kModelMessage, + MayaCallbackType::kBasicFunction, + ModelMessage::kBeforeDuplicate); + registerEvent( + scheduler, + "AfterDuplicate", + eventType, + MayaMessageType::kModelMessage, + MayaCallbackType::kBasicFunction, + ModelMessage::kAfterDuplicate); } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::initNodeMessage(MayaCallbackInfo& cbi) -{ -} +void MayaEventHandler::initNodeMessage(MayaCallbackInfo& cbi) { } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerNodeMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) +void MayaEventHandler::registerNodeMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) { } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::initObjectSetMessage(MayaCallbackInfo& cbi) -{ -} +void MayaEventHandler::initObjectSetMessage(MayaCallbackInfo& cbi) { } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerObjectSetMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) +void MayaEventHandler::registerObjectSetMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) { } //---------------------------------------------------------------------------------------------------------------------- void MayaEventHandler::initPaintMessage(MayaCallbackInfo& cbi) { - switch(cbi.mmessageEnum) - { - case PaintMessage::kVertexColor: cbi.mayaCallback = MPaintMessage::addVertexColorCallback(bindPathObjectPlugColoursFunction, &cbi); break; - default: break; - } + switch (cbi.mmessageEnum) { + case PaintMessage::kVertexColor: + cbi.mayaCallback + = MPaintMessage::addVertexColorCallback(bindPathObjectPlugColoursFunction, &cbi); + break; + default: break; + } } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerPaintMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) +void MayaEventHandler::registerPaintMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) { - registerEvent(scheduler, "VertexColor", eventType, MayaMessageType::kModelMessage, MayaCallbackType::kPathObjectPlugColoursFunction, PaintMessage::kVertexColor); + registerEvent( + scheduler, + "VertexColor", + eventType, + MayaMessageType::kModelMessage, + MayaCallbackType::kPathObjectPlugColoursFunction, + PaintMessage::kVertexColor); } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::initPolyMessage(MayaCallbackInfo& cbi) -{ -} +void MayaEventHandler::initPolyMessage(MayaCallbackInfo& cbi) { } //---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerPolyMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) +void MayaEventHandler::registerPolyMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) { } //---------------------------------------------------------------------------------------------------------------------- void MayaEventHandler::initSceneMessage(MayaCallbackInfo& cbi) { - switch(cbi.mmessageEnum) - { - case SceneMessage::kSceneUpdate: - case SceneMessage::kBeforeNew: - case SceneMessage::kAfterNew: - case SceneMessage::kBeforeImport: - case SceneMessage::kAfterImport: - case SceneMessage::kBeforeOpen: - case SceneMessage::kAfterOpen: - case SceneMessage::kBeforeFileRead: - case SceneMessage::kAfterFileRead: - case SceneMessage::kAfterSceneReadAndRecordEdits: - case SceneMessage::kBeforeExport: - case SceneMessage::kExportStarted: - case SceneMessage::kAfterExport: - case SceneMessage::kBeforeSave: - case SceneMessage::kAfterSave: - case SceneMessage::kBeforeCreateReference: - case SceneMessage::kBeforeLoadReferenceAndRecordEdits: - case SceneMessage::kAfterCreateReference: - case SceneMessage::kAfterCreateReferenceAndRecordEdits: - case SceneMessage::kBeforeRemoveReference: - case SceneMessage::kAfterRemoveReference: - case SceneMessage::kBeforeImportReference: - case SceneMessage::kAfterImportReference: - case SceneMessage::kBeforeExportReference: - case SceneMessage::kAfterExportReference: - case SceneMessage::kBeforeUnloadReference: - case SceneMessage::kAfterUnloadReference: - case SceneMessage::kBeforeLoadReference: - case SceneMessage::kBeforeCreateReferenceAndRecordEdits: - case SceneMessage::kAfterLoadReference: - case SceneMessage::kAfterLoadReferenceAndRecordEdits: - case SceneMessage::kBeforeSoftwareRender: - case SceneMessage::kAfterSoftwareRender: - case SceneMessage::kBeforeSoftwareFrameRender: - case SceneMessage::kAfterSoftwareFrameRender: - case SceneMessage::kSoftwareRenderInterrupted: - case SceneMessage::kMayaInitialized: - case SceneMessage::kMayaExiting: - cbi.mayaCallback = MSceneMessage::addCallback(MSceneMessage::Message(cbi.mmessageEnum), bindBasicFunction, &cbi, 0); - break; - - case SceneMessage::kBeforeNewCheck: - case SceneMessage::kBeforeImportCheck: - case SceneMessage::kBeforeOpenCheck: - case SceneMessage::kBeforeExportCheck: - case SceneMessage::kBeforeSaveCheck: - case SceneMessage::kBeforeCreateReferenceCheck: - case SceneMessage::kBeforeLoadReferenceCheck: - cbi.mayaCallback = MSceneMessage::addCheckCallback(MSceneMessage::Message(cbi.mmessageEnum), bindCheckFunction, &cbi, 0); - break; - - case SceneMessage::kBeforePluginLoad: - case SceneMessage::kAfterPluginLoad: - case SceneMessage::kBeforePluginUnload: - case SceneMessage::kAfterPluginUnload: - cbi.mayaCallback = MSceneMessage::addStringArrayCallback(MSceneMessage::Message(cbi.mmessageEnum), bindStringArrayFunction, &cbi, 0); - break; - } -} - -//---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerSceneMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) -{ - registerEvent(scheduler, "SceneUpdate", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kSceneUpdate); - registerEvent(scheduler, "BeforeNew", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeNew); - registerEvent(scheduler, "AfterNew", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterNew); - registerEvent(scheduler, "BeforeImport", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeImport); - registerEvent(scheduler, "AfterImport", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterImport); - registerEvent(scheduler, "BeforeOpen", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeOpen); - registerEvent(scheduler, "AfterOpen", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterOpen); - registerEvent(scheduler, "BeforeFileRead", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeFileRead); - registerEvent(scheduler, "AfterFileRead", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterFileRead); - registerEvent(scheduler, "AfterSceneReadAndRecordEdits", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterSceneReadAndRecordEdits); - registerEvent(scheduler, "BeforeExport", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeExport); - registerEvent(scheduler, "ExportStarted", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kExportStarted); - registerEvent(scheduler, "AfterExport", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterExport); - registerEvent(scheduler, "BeforeSave", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeSave); - registerEvent(scheduler, "AfterSave", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterSave); - registerEvent(scheduler, "BeforeCreateReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeCreateReference); - registerEvent(scheduler, "BeforeLoadReferenceAndRecordEdits", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeLoadReferenceAndRecordEdits); - registerEvent(scheduler, "AfterCreateReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterCreateReference); - registerEvent(scheduler, "AfterCreateReferenceAndRecordEdits", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterCreateReferenceAndRecordEdits); - registerEvent(scheduler, "BeforeRemoveReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeRemoveReference); - registerEvent(scheduler, "AfterRemoveReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterRemoveReference); - registerEvent(scheduler, "BeforeImportReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeImportReference); - registerEvent(scheduler, "AfterImportReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterImportReference); - registerEvent(scheduler, "BeforeExportReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeExportReference); - registerEvent(scheduler, "AfterExportReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterExportReference); - registerEvent(scheduler, "BeforeUnloadReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeUnloadReference); - registerEvent(scheduler, "AfterUnloadReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterUnloadReference); - registerEvent(scheduler, "BeforeLoadReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeLoadReference); - registerEvent(scheduler, "BeforeCreateReferenceAndRecordEdits", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeCreateReferenceAndRecordEdits); - registerEvent(scheduler, "AfterLoadReference", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterLoadReference); - registerEvent(scheduler, "AfterLoadReferenceAndRecordEdits", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterLoadReferenceAndRecordEdits); - registerEvent(scheduler, "BeforeSoftwareRender", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeSoftwareRender); - registerEvent(scheduler, "AfterSoftwareRender", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterSoftwareRender); - registerEvent(scheduler, "BeforeSoftwareFrameRender", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kBeforeSoftwareFrameRender); - registerEvent(scheduler, "AfterSoftwareFrameRender", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kAfterSoftwareFrameRender); - registerEvent(scheduler, "SoftwareRenderInterrupted", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kSoftwareRenderInterrupted); - registerEvent(scheduler, "MayaInitialized", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kMayaInitialized); - registerEvent(scheduler, "MayaExiting", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kBasicFunction, MSceneMessage::kMayaExiting); - registerEvent(scheduler, "BeforeNewCheck", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kCheckFunction, MSceneMessage::kBeforeNewCheck); - registerEvent(scheduler, "BeforeImportCheck", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kCheckFunction, MSceneMessage::kBeforeImportCheck); - registerEvent(scheduler, "BeforeOpenCheck", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kCheckFunction, MSceneMessage::kBeforeOpenCheck); - registerEvent(scheduler, "BeforeExportCheck", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kCheckFunction, MSceneMessage::kBeforeExportCheck); - registerEvent(scheduler, "BeforeSaveCheck", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kCheckFunction, MSceneMessage::kBeforeSaveCheck); - registerEvent(scheduler, "BeforeCreateReferenceCheck", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kCheckFunction, MSceneMessage::kBeforeCreateReferenceCheck); - registerEvent(scheduler, "BeforeLoadReferenceCheck", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kCheckFunction, MSceneMessage::kBeforeLoadReferenceCheck); - registerEvent(scheduler, "BeforePluginLoad", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kStringArrayFunction, MSceneMessage::kBeforePluginLoad); - registerEvent(scheduler, "AfterPluginLoad", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kStringArrayFunction, MSceneMessage::kAfterPluginLoad); - registerEvent(scheduler, "BeforePluginUnload", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kStringArrayFunction, MSceneMessage::kBeforePluginUnload); - registerEvent(scheduler, "AfterPluginUnload", eventType, MayaMessageType::kSceneMessage, MayaCallbackType::kStringArrayFunction, MSceneMessage::kAfterPluginUnload); -} - -//---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::initTimerMessage(MayaCallbackInfo& cbi) -{ -} - -//---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerTimerMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) -{ -} - -//---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::initUiMessage(MayaCallbackInfo& cbi) -{ -} - -//---------------------------------------------------------------------------------------------------------------------- -void MayaEventHandler::registerUiMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType) + switch (cbi.mmessageEnum) { + case SceneMessage::kSceneUpdate: + case SceneMessage::kBeforeNew: + case SceneMessage::kAfterNew: + case SceneMessage::kBeforeImport: + case SceneMessage::kAfterImport: + case SceneMessage::kBeforeOpen: + case SceneMessage::kAfterOpen: + case SceneMessage::kBeforeFileRead: + case SceneMessage::kAfterFileRead: + case SceneMessage::kAfterSceneReadAndRecordEdits: + case SceneMessage::kBeforeExport: + case SceneMessage::kExportStarted: + case SceneMessage::kAfterExport: + case SceneMessage::kBeforeSave: + case SceneMessage::kAfterSave: + case SceneMessage::kBeforeCreateReference: + case SceneMessage::kBeforeLoadReferenceAndRecordEdits: + case SceneMessage::kAfterCreateReference: + case SceneMessage::kAfterCreateReferenceAndRecordEdits: + case SceneMessage::kBeforeRemoveReference: + case SceneMessage::kAfterRemoveReference: + case SceneMessage::kBeforeImportReference: + case SceneMessage::kAfterImportReference: + case SceneMessage::kBeforeExportReference: + case SceneMessage::kAfterExportReference: + case SceneMessage::kBeforeUnloadReference: + case SceneMessage::kAfterUnloadReference: + case SceneMessage::kBeforeLoadReference: + case SceneMessage::kBeforeCreateReferenceAndRecordEdits: + case SceneMessage::kAfterLoadReference: + case SceneMessage::kAfterLoadReferenceAndRecordEdits: + case SceneMessage::kBeforeSoftwareRender: + case SceneMessage::kAfterSoftwareRender: + case SceneMessage::kBeforeSoftwareFrameRender: + case SceneMessage::kAfterSoftwareFrameRender: + case SceneMessage::kSoftwareRenderInterrupted: + case SceneMessage::kMayaInitialized: + case SceneMessage::kMayaExiting: + cbi.mayaCallback = MSceneMessage::addCallback( + MSceneMessage::Message(cbi.mmessageEnum), bindBasicFunction, &cbi, 0); + break; + + case SceneMessage::kBeforeNewCheck: + case SceneMessage::kBeforeImportCheck: + case SceneMessage::kBeforeOpenCheck: + case SceneMessage::kBeforeExportCheck: + case SceneMessage::kBeforeSaveCheck: + case SceneMessage::kBeforeCreateReferenceCheck: + case SceneMessage::kBeforeLoadReferenceCheck: + cbi.mayaCallback = MSceneMessage::addCheckCallback( + MSceneMessage::Message(cbi.mmessageEnum), bindCheckFunction, &cbi, 0); + break; + + case SceneMessage::kBeforePluginLoad: + case SceneMessage::kAfterPluginLoad: + case SceneMessage::kBeforePluginUnload: + case SceneMessage::kAfterPluginUnload: + cbi.mayaCallback = MSceneMessage::addStringArrayCallback( + MSceneMessage::Message(cbi.mmessageEnum), bindStringArrayFunction, &cbi, 0); + break; + } +} + +//---------------------------------------------------------------------------------------------------------------------- +void MayaEventHandler::registerSceneMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) +{ + registerEvent( + scheduler, + "SceneUpdate", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kSceneUpdate); + registerEvent( + scheduler, + "BeforeNew", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeNew); + registerEvent( + scheduler, + "AfterNew", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterNew); + registerEvent( + scheduler, + "BeforeImport", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeImport); + registerEvent( + scheduler, + "AfterImport", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterImport); + registerEvent( + scheduler, + "BeforeOpen", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeOpen); + registerEvent( + scheduler, + "AfterOpen", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterOpen); + registerEvent( + scheduler, + "BeforeFileRead", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeFileRead); + registerEvent( + scheduler, + "AfterFileRead", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterFileRead); + registerEvent( + scheduler, + "AfterSceneReadAndRecordEdits", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterSceneReadAndRecordEdits); + registerEvent( + scheduler, + "BeforeExport", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeExport); + registerEvent( + scheduler, + "ExportStarted", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kExportStarted); + registerEvent( + scheduler, + "AfterExport", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterExport); + registerEvent( + scheduler, + "BeforeSave", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeSave); + registerEvent( + scheduler, + "AfterSave", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterSave); + registerEvent( + scheduler, + "BeforeCreateReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeCreateReference); + registerEvent( + scheduler, + "BeforeLoadReferenceAndRecordEdits", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeLoadReferenceAndRecordEdits); + registerEvent( + scheduler, + "AfterCreateReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterCreateReference); + registerEvent( + scheduler, + "AfterCreateReferenceAndRecordEdits", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterCreateReferenceAndRecordEdits); + registerEvent( + scheduler, + "BeforeRemoveReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeRemoveReference); + registerEvent( + scheduler, + "AfterRemoveReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterRemoveReference); + registerEvent( + scheduler, + "BeforeImportReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeImportReference); + registerEvent( + scheduler, + "AfterImportReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterImportReference); + registerEvent( + scheduler, + "BeforeExportReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeExportReference); + registerEvent( + scheduler, + "AfterExportReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterExportReference); + registerEvent( + scheduler, + "BeforeUnloadReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeUnloadReference); + registerEvent( + scheduler, + "AfterUnloadReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterUnloadReference); + registerEvent( + scheduler, + "BeforeLoadReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeLoadReference); + registerEvent( + scheduler, + "BeforeCreateReferenceAndRecordEdits", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeCreateReferenceAndRecordEdits); + registerEvent( + scheduler, + "AfterLoadReference", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterLoadReference); + registerEvent( + scheduler, + "AfterLoadReferenceAndRecordEdits", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterLoadReferenceAndRecordEdits); + registerEvent( + scheduler, + "BeforeSoftwareRender", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeSoftwareRender); + registerEvent( + scheduler, + "AfterSoftwareRender", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterSoftwareRender); + registerEvent( + scheduler, + "BeforeSoftwareFrameRender", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kBeforeSoftwareFrameRender); + registerEvent( + scheduler, + "AfterSoftwareFrameRender", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kAfterSoftwareFrameRender); + registerEvent( + scheduler, + "SoftwareRenderInterrupted", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kSoftwareRenderInterrupted); + registerEvent( + scheduler, + "MayaInitialized", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kMayaInitialized); + registerEvent( + scheduler, + "MayaExiting", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kBasicFunction, + MSceneMessage::kMayaExiting); + registerEvent( + scheduler, + "BeforeNewCheck", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kCheckFunction, + MSceneMessage::kBeforeNewCheck); + registerEvent( + scheduler, + "BeforeImportCheck", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kCheckFunction, + MSceneMessage::kBeforeImportCheck); + registerEvent( + scheduler, + "BeforeOpenCheck", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kCheckFunction, + MSceneMessage::kBeforeOpenCheck); + registerEvent( + scheduler, + "BeforeExportCheck", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kCheckFunction, + MSceneMessage::kBeforeExportCheck); + registerEvent( + scheduler, + "BeforeSaveCheck", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kCheckFunction, + MSceneMessage::kBeforeSaveCheck); + registerEvent( + scheduler, + "BeforeCreateReferenceCheck", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kCheckFunction, + MSceneMessage::kBeforeCreateReferenceCheck); + registerEvent( + scheduler, + "BeforeLoadReferenceCheck", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kCheckFunction, + MSceneMessage::kBeforeLoadReferenceCheck); + registerEvent( + scheduler, + "BeforePluginLoad", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kStringArrayFunction, + MSceneMessage::kBeforePluginLoad); + registerEvent( + scheduler, + "AfterPluginLoad", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kStringArrayFunction, + MSceneMessage::kAfterPluginLoad); + registerEvent( + scheduler, + "BeforePluginUnload", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kStringArrayFunction, + MSceneMessage::kBeforePluginUnload); + registerEvent( + scheduler, + "AfterPluginUnload", + eventType, + MayaMessageType::kSceneMessage, + MayaCallbackType::kStringArrayFunction, + MSceneMessage::kAfterPluginUnload); +} + +//---------------------------------------------------------------------------------------------------------------------- +void MayaEventHandler::initTimerMessage(MayaCallbackInfo& cbi) { } + +//---------------------------------------------------------------------------------------------------------------------- +void MayaEventHandler::registerTimerMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) +{ +} + +//---------------------------------------------------------------------------------------------------------------------- +void MayaEventHandler::initUiMessage(MayaCallbackInfo& cbi) { } + +//---------------------------------------------------------------------------------------------------------------------- +void MayaEventHandler::registerUiMessages( + AL::event::EventScheduler* scheduler, + AL::event::EventType eventType) { } //---------------------------------------------------------------------------------------------------------------------- void MayaEventHandler::initEvent(MayaCallbackInfo& cbi) { - switch(cbi.mayaMessageType) - { - case MayaMessageType::kAnimMessage: - initAnimMessage(cbi); - break; - case MayaMessageType::kCameraSetMessage: - initCameraSetMessage(cbi); - break; - case MayaMessageType::kCommandMessage: - initCommandMessage(cbi); - break; - case MayaMessageType::kConditionMessage: - initConditionMessage(cbi); - break; - case MayaMessageType::kContainerMessage: - initContainerMessage(cbi); - break; - case MayaMessageType::kDagMessage: - initDagMessage(cbi); - break; - case MayaMessageType::kDGMessage: - initDGMessage(cbi); - break; - case MayaMessageType::kEventMessage: - initEventMessage(cbi); - break; - case MayaMessageType::kLockMessage: - initLockMessage(cbi); - break; - case MayaMessageType::kModelMessage: - initModelMessage(cbi); - break; - case MayaMessageType::kNodeMessage: - initNodeMessage(cbi); - break; - case MayaMessageType::kObjectSetMessage: - initObjectSetMessage(cbi); - break; - case MayaMessageType::kPaintMessage: - initPaintMessage(cbi); - break; - case MayaMessageType::kPolyMessage: - initPolyMessage(cbi); - break; - case MayaMessageType::kSceneMessage: - initSceneMessage(cbi); - break; - case MayaMessageType::kTimerMessage: - initTimerMessage(cbi); - break; - case MayaMessageType::kUiMessage: - initUiMessage(cbi); - break; - } + switch (cbi.mayaMessageType) { + case MayaMessageType::kAnimMessage: initAnimMessage(cbi); break; + case MayaMessageType::kCameraSetMessage: initCameraSetMessage(cbi); break; + case MayaMessageType::kCommandMessage: initCommandMessage(cbi); break; + case MayaMessageType::kConditionMessage: initConditionMessage(cbi); break; + case MayaMessageType::kContainerMessage: initContainerMessage(cbi); break; + case MayaMessageType::kDagMessage: initDagMessage(cbi); break; + case MayaMessageType::kDGMessage: initDGMessage(cbi); break; + case MayaMessageType::kEventMessage: initEventMessage(cbi); break; + case MayaMessageType::kLockMessage: initLockMessage(cbi); break; + case MayaMessageType::kModelMessage: initModelMessage(cbi); break; + case MayaMessageType::kNodeMessage: initNodeMessage(cbi); break; + case MayaMessageType::kObjectSetMessage: initObjectSetMessage(cbi); break; + case MayaMessageType::kPaintMessage: initPaintMessage(cbi); break; + case MayaMessageType::kPolyMessage: initPolyMessage(cbi); break; + case MayaMessageType::kSceneMessage: initSceneMessage(cbi); break; + case MayaMessageType::kTimerMessage: initTimerMessage(cbi); break; + case MayaMessageType::kUiMessage: initUiMessage(cbi); break; + } } //---------------------------------------------------------------------------------------------------------------------- AL::event::CallbackId MayaEventManager::registerCallbackInternal( - const void* func, + const void* func, const MayaCallbackType type, - const char* const eventName, - const char* const tag, - const uint32_t weight, - void* const userData) -{ - AL::event::EventScheduler* scheduler = m_mayaEvents->scheduler(); - const AL::event::EventDispatcher* event = scheduler->event(eventName); - if(!event) - return 0; - const AL::event::EventId id = event->eventId(); - - const MayaEventHandler::MayaCallbackInfo* info = m_mayaEvents->getEventInfo(id); - if(!info) - return 0; - - if(info->mayaCallbackType != type) - { - std::cerr << "unable to register maya event " << eventName << " - incorrect function prototype specified" << std::endl; - return 0; - } - return scheduler->registerCallback(id, tag, func, weight, userData); + const char* const eventName, + const char* const tag, + const uint32_t weight, + void* const userData) +{ + AL::event::EventScheduler* scheduler = m_mayaEvents->scheduler(); + const AL::event::EventDispatcher* event = scheduler->event(eventName); + if (!event) + return 0; + const AL::event::EventId id = event->eventId(); + + const MayaEventHandler::MayaCallbackInfo* info = m_mayaEvents->getEventInfo(id); + if (!info) + return 0; + + if (info->mayaCallbackType != type) { + std::cerr << "unable to register maya event " << eventName + << " - incorrect function prototype specified" << std::endl; + return 0; + } + return scheduler->registerCallback(id, tag, func, weight, userData); } //---------------------------------------------------------------------------------------------------------------------- MayaEventHandler::~MayaEventHandler() { - for(auto& r : m_callbacks) - { - if(r.refCount) - { - MMessage::removeCallback(r.mayaCallback); - r.mayaCallback = 0; - r.refCount = 0; + for (auto& r : m_callbacks) { + if (r.refCount) { + MMessage::removeCallback(r.mayaCallback); + r.mayaCallback = 0; + r.refCount = 0; + } + m_scheduler->unregisterEvent(r.eventId); } - m_scheduler->unregisterEvent(r.eventId); - } } //---------------------------------------------------------------------------------------------------------------------- MayaEventManager* MayaEventManager::g_instance = 0; //---------------------------------------------------------------------------------------------------------------------- -static const char* const eventTypeStrings[] = -{ - "unknown", - "custom", - "schema", - "coremaya", - "usdmaya" -}; +static const char* const eventTypeStrings[] + = { "unknown", "custom", "schema", "coremaya", "usdmaya" }; //---------------------------------------------------------------------------------------------------------------------- -class MayaEventSystemBinding - : public AL::event::EventSystemBinding +class MayaEventSystemBinding : public AL::event::EventSystemBinding { public: + MayaEventSystemBinding() + : EventSystemBinding(eventTypeStrings, sizeof(eventTypeStrings) / sizeof(const char*)) + { + } - MayaEventSystemBinding() - : EventSystemBinding(eventTypeStrings, sizeof(eventTypeStrings) / sizeof(const char*)) {} - - bool executePython(const char* const code) override - { - return MGlobal::executePythonCommand(code, false, true); - } + bool executePython(const char* const code) override + { + return MGlobal::executePythonCommand(code, false, true); + } - bool executeMEL(const char* const code) override - { - return MGlobal::executeCommand(code, false, true); - } + bool executeMEL(const char* const code) override + { + return MGlobal::executeCommand(code, false, true); + } - void writeLog(EventSystemBinding::Type severity, const char* const text) override - { - switch(severity) + void writeLog(EventSystemBinding::Type severity, const char* const text) override { - case kInfo: MGlobal::displayInfo(text); break; - case kWarning: MGlobal::displayWarning(text); break; - case kError: MGlobal::displayError(text); break; + switch (severity) { + case kInfo: MGlobal::displayInfo(text); break; + case kWarning: MGlobal::displayWarning(text); break; + case kError: MGlobal::displayError(text); break; + } } - } }; static MayaEventSystemBinding g_eventSystem; @@ -1202,18 +1781,17 @@ static MayaEventSystemBinding g_eventSystem; //---------------------------------------------------------------------------------------------------------------------- MayaEventManager& MayaEventManager::instance() { - if(!g_instance) - { - AL::event::EventScheduler::initScheduler(&g_eventSystem); - auto ptr = new AL::maya::event::MayaEventHandler(&AL::event::EventScheduler::getScheduler(), AL::event::kMayaEventType); - new AL::maya::event::MayaEventManager(ptr); - } - return *g_instance; + if (!g_instance) { + AL::event::EventScheduler::initScheduler(&g_eventSystem); + auto ptr = new AL::maya::event::MayaEventHandler( + &AL::event::EventScheduler::getScheduler(), AL::event::kMayaEventType); + new AL::maya::event::MayaEventManager(ptr); + } + return *g_instance; } - //---------------------------------------------------------------------------------------------------------------------- -} // event -} // maya -} // AL +} // namespace event +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/mayautils/AL/maya/event/MayaEventManager.h b/plugin/al/mayautils/AL/maya/event/MayaEventManager.h index 87d4dedd94..b08a306190 100644 --- a/plugin/al/mayautils/AL/maya/event/MayaEventManager.h +++ b/plugin/al/mayautils/AL/maya/event/MayaEventManager.h @@ -15,6 +15,7 @@ // #pragma once +#include "AL/event/EventHandler.h" #include "AL/maya/event/Api.h" #include @@ -22,8 +23,6 @@ #include #include -#include "AL/event/EventHandler.h" - namespace AL { namespace maya { namespace event { @@ -34,72 +33,172 @@ namespace event { //---------------------------------------------------------------------------------------------------------------------- enum class MayaMessageType { - kAnimMessage, ///< messages from the MAnimMessage class - kCameraSetMessage, ///< messages from the MCameraSetMessage class - kCommandMessage, ///< messages from the MCommandMessage class - kConditionMessage, ///< messages from the MConditionMessage class - kContainerMessage, ///< messages from the MContainerMessage class - kDagMessage, ///< messages from the MDagMessage class - kDGMessage, ///< messages from the MDGMessage class - kEventMessage, ///< messages from the MEventMessage class - kLockMessage, ///< messages from the MLockMessage class - kModelMessage, ///< messages from the MModelMessage class - kNodeMessage, ///< messages from the MNodeMessage class - kObjectSetMessage, ///< messages from the MObjectSetMessage class - kPaintMessage, ///< messages from the MPaintMessage class - kPolyMessage, ///< messages from the MPolyMessage class - kSceneMessage, ///< messages from the MSceneMessage class - kTimerMessage, ///< messages from the MTimerMessage class - kUiMessage ///< messages from the MUiMessage class + kAnimMessage, ///< messages from the MAnimMessage class + kCameraSetMessage, ///< messages from the MCameraSetMessage class + kCommandMessage, ///< messages from the MCommandMessage class + kConditionMessage, ///< messages from the MConditionMessage class + kContainerMessage, ///< messages from the MContainerMessage class + kDagMessage, ///< messages from the MDagMessage class + kDGMessage, ///< messages from the MDGMessage class + kEventMessage, ///< messages from the MEventMessage class + kLockMessage, ///< messages from the MLockMessage class + kModelMessage, ///< messages from the MModelMessage class + kNodeMessage, ///< messages from the MNodeMessage class + kObjectSetMessage, ///< messages from the MObjectSetMessage class + kPaintMessage, ///< messages from the MPaintMessage class + kPolyMessage, ///< messages from the MPolyMessage class + kSceneMessage, ///< messages from the MSceneMessage class + kTimerMessage, ///< messages from the MTimerMessage class + kUiMessage ///< messages from the MUiMessage class }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief An enum describing which of the standard maya callback functions are to be used for a given callback. This -/// is primarily used as a runtime check to ensure the function prototype you are binding to a given event is -/// of the correct type. +/// \brief An enum describing which of the standard maya callback functions are to be used for a +/// given callback. This +/// is primarily used as a runtime check to ensure the function prototype you are binding to +/// a given event is of the correct type. /// \ingroup mayaevents //---------------------------------------------------------------------------------------------------------------------- enum class MayaCallbackType { - kBasicFunction, ///< \brief describes the maya callback type \b MMessage::MBasicFunction \code typedef void (*MBasicFunction) (void* userData) \endcode - kElapsedTimeFunction, ///< \brief describes the maya callback type \b MMessage::MElapsedTimeFunction \code typedef void (*MElapsedTimeFunction) (float elapsedTime, float lastTime, void* userData); \endcode - kCheckFunction, ///< \brief describes the maya callback type \b MMessage::MCheckFunction \code typedef void (*MCheckFunction) (bool* retCode, void* userData); \endcode - kCheckFileFunction, ///< \brief describes the maya callback type \b MMessage::MCheckFileFunction \code typedef void (*MCheckFileFunction) (bool* retCode, MFileObject& file, void* userData); \endcode - kCheckPlugFunction, ///< \brief describes the maya callback type \b MMessage::MCheckPlugFunction \code typedef void (*MCheckPlugFunction) (bool* retCode, MPlug& plug, void* userData); \endcode - kComponentFunction, ///< \brief describes the maya callback type \b MMessage::MComponentFunction \code typedef void (*MComponentFunction) (MUintArray componentIds[], unsigned int count, void* userData); \endcode - kNodeFunction, ///< \brief describes the maya callback type \b MMessage::MNodeFunction \code typedef void (*MNodeFunction) (MObject& node, void* userData); \endcode - kStringFunction, ///< \brief describes the maya callback type \b MMessage::MStringFunction \code typedef void (*MStringFunction) (const MString& str, void* userData); \endcode - kTwoStringFunction, ///< \brief describes the maya callback type \b MMessage::MTwoStringFunction \code typedef void (*MTwoStringFunction) (const MString& str1, const MString& str2, void* userData); \endcode - kThreeStringFunction, ///< \brief describes the maya callback type \b MMessage::MThreeStringFunction \code typedef void (*MThreeStringFunction) (const MString& str1, const MString& str2, const MString& str2, void* userData); \endcode - kStringIntBoolIntFunction, ///< \brief describes the maya callback type \b MMessage::MStringIntBoolIntFunction \code typedef void (*MStringIntBoolIntFunction) (const MString& str, unsigned index, bool flag, unsigned type, void* userData); \endcode - kStringIndexFunction, ///< \brief describes the maya callback type \b MMessage::MStringIndexFunction \code typedef void (*MStringIndexFunction) (const MString& str, unsigned int index, void* userData); \endcode - kStateFunction, ///< \brief describes the maya callback type \b MMessage::MStateFunction \code typedef void (*MStateFunction) (bool state, void* userData); \endcode - kTimeFunction, ///< \brief describes the maya callback type \b MMessage::MTimeFunction \code typedef void (*MTimeFunction) (MTime& time, void* userData); \endcode - kPlugFunction, ///< \brief describes the maya callback type \b MMessage::MPlugFunction \code typedef void (*MPlugFunction) (MPlug& srcPlug, MPlug& destPlug, bool made, void* userData); \endcode - kNodePlugFunction, ///< \brief describes the maya callback type \b MMessage::MNodePlugFunction \code typedef void (*MNodePlugFunction) (MObject& node, MPlug& plug, void* userData); \endcode - kNodeStringFunction, ///< \brief describes the maya callback type \b MMessage::MNodeStringFunction \code typedef void (*MNodeStringFunction) (MObject& node, const MString& str, void* userData); \endcode - kNodeStringBoolFunction, ///< \brief describes the maya callback type \b MMessage::MNodeStringBoolFunction \code typedef void (*MNodeStringBoolFunction) (MObject& node, const MString& str, bool flag, void* userData); \endcode - kParentChildFunction, ///< \brief describes the maya callback type \b MMessage::MParentChildFunction \code typedef void (*MParentChildFunction) (MDagPath& child, MDagPath& parent, void* userData); \endcode - kModifierFunction, ///< \brief describes the maya callback type \b MMessage::MModifierFunction \code typedef void (*MModifierFunction) (MDGModifier& modifier, void* userData); \endcode - kStringArrayFunction, ///< \brief describes the maya callback type \b MMessage::MStringArrayFunction \code typedef void (*MStringArrayFunction) (const MStringArray& strs, void* userData); \endcode - kNodeModifierFunction, ///< \brief describes the maya callback type \b MMessage::MNodeModifierFunction \code typedef void (*MNodeModifierFunction) (MObject& node, MDGModifier& modifier, void* userData); \endcode - kObjArrayFunction, ///< \brief describes the maya callback type \b MMessage::MObjArray \code typedef void (*MObjArray) (MObjectArray& objects, void* userData); \endcode - kNodeObjArrayFunction, ///< \brief describes the maya callback type \b MMessage::MNodeObjArray \code typedef void (*MNodeObjArray) (MObject& node, MObjectArray& objects, void* userData); \endcode - kStringNodeFunction, ///< \brief describes the maya callback type \b MMessage::MStringNode \code typedef void (*MStringNode) (const MString& str, MObject& node, void* userData); \endcode - kCameraLayerFunction, ///< \brief describes the maya callback type \b MMessage::MCameraLayerFunction \code typedef void (*MCameraLayerFunction) (MObject& cameraSetNode, unsigned multiIndex, bool added, void* userData); \endcode - kCameraLayerCameraFunction, ///< \brief describes the maya callback type \b MMessage::MCameraLayerCameraFunction \code typedef void (*MCameraLayerCameraFunction) (MObject& cameraSetNode, unsigned multiIndex, MObject& oldCamera, MObject& newCamera, void* userData); \endcode - kConnFailFunction, ///< \brief describes the maya callback type \b MMessage::MConnFailFunction \code typedef void (*MConnFailFunction) (MPlug& srcPlug, MPlug& destPlug, const MString& srcPlugName, const MString& dstPlugName, void* userData); \endcode - kPlugsDGModFunction, ///< \brief describes the maya callback type \b MMessage::MPlugsDGModFunction \code typedef void (*MPlugsDGModFunction) (MPlugArray& plugs, MDGModifier& modifier, void* userData); \endcode - kNodeUuidFunction, ///< \brief describes the maya callback type \b MMessage::MNodeUuidFunction \code typedef void (*MNodeUuidFunction) (MObject& node, const MUuid& uuid, void* userData); \endcode - kCheckNodeUuidFunction, ///< \brief describes the maya callback type \b MMessage::MCheckNodeUuidFunction \code typedef Action (*MCheckNodeUuidFunction) (bool doAction, MObject& node, MUuid& uuid, void* userData); \endcode - kObjectFileFunction, ///< \brief describes the maya callback type \b MMessage::MObjectFileFunction \code typedef void (*MObjectFileFunction) (const MObject& object, const MFileObject& file, void* userData); \endcode - kCheckObjectFileFunction, ///< \brief describes the maya callback type \b MMessage::MCheckObjectFileFunction \code typedef void (*MCheckObjectFileFunction) (bool* retCode, const MObject& referenceNode, MFileObject& file, void* userData); \endcode - kRenderTileFunction, ///< \brief describes the maya callback type \b MMessage::MRenderTileFunction \code typedef void (*MRenderTileFunction) (int originX, int originY, int tileMaxX, int tileMaxY, void* userData); \endcode - kMessageFunction, ///< \brief describes the maya callback type \b MMessage::MMessageFunction \code typedef void (*MMessageFunction) (const MString& message, MCommandMessage::MessageType messageType, void* userData); \endcode - kMessageFilterFunction, ///< \brief describes the maya callback type \b MMessage::MMessageFilterFunction \code typedef void (*MMessageFilterFunction) (const MString& message, MCommandMessage::MessageType messageType, bool& filterOutput, void* userData); \endcode - kMessageParentChildFunction, ///< \brief describes the maya callback type \b MMessage::MMessageParentChildFunction \code typedef void (*MMessageParentChildFunction) (MDagMessage::DagMessage msgType, MDagPath& child, MDagPath& parent, void* userData); \endcode - kPathObjectPlugColoursFunction, ///< \brief describes the maya callback type \b MMessage::MPathObjectPlugColorsFunction \code typedef void (*MPathObjectPlugColorsFunction) (MDagPath& path, MObject& object, MPlug& plug, MColorArray& colors, void* userData); \endcode - kWorldMatrixModifiedFunction ///< \brief describes the maya callback type \b MMessage::MWorldMatrixModifiedFunction \code typedef void (*MWorldMatrixModifiedFunction) (MObject& transformNode, MDagMessage::MatrixModifiedFlags& modified, void* userData); \endcode + kBasicFunction, ///< \brief describes the maya callback type \b MMessage::MBasicFunction \code + ///< typedef void (*MBasicFunction) (void* userData) \endcode + kElapsedTimeFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MElapsedTimeFunction \code typedef void + ///< (*MElapsedTimeFunction) (float elapsedTime, float lastTime, void* + ///< userData); \endcode + kCheckFunction, ///< \brief describes the maya callback type \b MMessage::MCheckFunction \code + ///< typedef void (*MCheckFunction) (bool* retCode, void* userData); \endcode + kCheckFileFunction, ///< \brief describes the maya callback type \b MMessage::MCheckFileFunction + ///< \code typedef void (*MCheckFileFunction) (bool* retCode, MFileObject& + ///< file, void* userData); \endcode + kCheckPlugFunction, ///< \brief describes the maya callback type \b MMessage::MCheckPlugFunction + ///< \code typedef void (*MCheckPlugFunction) (bool* retCode, MPlug& plug, + ///< void* userData); \endcode + kComponentFunction, ///< \brief describes the maya callback type \b MMessage::MComponentFunction + ///< \code typedef void (*MComponentFunction) (MUintArray componentIds[], + ///< unsigned int count, void* userData); \endcode + kNodeFunction, ///< \brief describes the maya callback type \b MMessage::MNodeFunction \code + ///< typedef void (*MNodeFunction) (MObject& node, void* userData); \endcode + kStringFunction, ///< \brief describes the maya callback type \b MMessage::MStringFunction \code + ///< typedef void (*MStringFunction) (const MString& str, void* userData); + ///< \endcode + kTwoStringFunction, ///< \brief describes the maya callback type \b MMessage::MTwoStringFunction + ///< \code typedef void (*MTwoStringFunction) (const MString& str1, const + ///< MString& str2, void* userData); \endcode + kThreeStringFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MThreeStringFunction \code typedef void + ///< (*MThreeStringFunction) (const MString& str1, const MString& str2, + ///< const MString& str2, void* userData); \endcode + kStringIntBoolIntFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MStringIntBoolIntFunction \code typedef void + ///< (*MStringIntBoolIntFunction) (const MString& str, unsigned + ///< index, bool flag, unsigned type, void* userData); \endcode + kStringIndexFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MStringIndexFunction \code typedef void + ///< (*MStringIndexFunction) (const MString& str, unsigned int index, + ///< void* userData); \endcode + kStateFunction, ///< \brief describes the maya callback type \b MMessage::MStateFunction \code + ///< typedef void (*MStateFunction) (bool state, void* userData); \endcode + kTimeFunction, ///< \brief describes the maya callback type \b MMessage::MTimeFunction \code + ///< typedef void (*MTimeFunction) (MTime& time, void* userData); \endcode + kPlugFunction, ///< \brief describes the maya callback type \b MMessage::MPlugFunction \code + ///< typedef void (*MPlugFunction) (MPlug& srcPlug, MPlug& destPlug, bool made, + ///< void* userData); \endcode + kNodePlugFunction, ///< \brief describes the maya callback type \b MMessage::MNodePlugFunction + ///< \code typedef void (*MNodePlugFunction) (MObject& node, MPlug& plug, + ///< void* userData); \endcode + kNodeStringFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MNodeStringFunction \code typedef void + ///< (*MNodeStringFunction) (MObject& node, const MString& str, void* + ///< userData); \endcode + kNodeStringBoolFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MNodeStringBoolFunction \code typedef void + ///< (*MNodeStringBoolFunction) (MObject& node, const MString& str, + ///< bool flag, void* userData); \endcode + kParentChildFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MParentChildFunction \code typedef void + ///< (*MParentChildFunction) (MDagPath& child, MDagPath& parent, void* + ///< userData); \endcode + kModifierFunction, ///< \brief describes the maya callback type \b MMessage::MModifierFunction + ///< \code typedef void (*MModifierFunction) (MDGModifier& modifier, void* + ///< userData); \endcode + kStringArrayFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MStringArrayFunction \code typedef void + ///< (*MStringArrayFunction) (const MStringArray& strs, void* userData); + ///< \endcode + kNodeModifierFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MNodeModifierFunction \code typedef void + ///< (*MNodeModifierFunction) (MObject& node, MDGModifier& modifier, + ///< void* userData); \endcode + kObjArrayFunction, ///< \brief describes the maya callback type \b MMessage::MObjArray \code + ///< typedef void (*MObjArray) (MObjectArray& objects, void* userData); + ///< \endcode + kNodeObjArrayFunction, ///< \brief describes the maya callback type \b MMessage::MNodeObjArray + ///< \code typedef void (*MNodeObjArray) (MObject& node, MObjectArray& + ///< objects, void* userData); \endcode + kStringNodeFunction, ///< \brief describes the maya callback type \b MMessage::MStringNode \code + ///< typedef void (*MStringNode) (const MString& str, MObject& node, void* + ///< userData); \endcode + kCameraLayerFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MCameraLayerFunction \code typedef void + ///< (*MCameraLayerFunction) (MObject& cameraSetNode, unsigned multiIndex, + ///< bool added, void* userData); \endcode + kCameraLayerCameraFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MCameraLayerCameraFunction \code typedef void + ///< (*MCameraLayerCameraFunction) (MObject& cameraSetNode, unsigned + ///< multiIndex, MObject& oldCamera, MObject& newCamera, void* + ///< userData); \endcode + kConnFailFunction, ///< \brief describes the maya callback type \b MMessage::MConnFailFunction + ///< \code typedef void (*MConnFailFunction) (MPlug& srcPlug, MPlug& + ///< destPlug, const MString& srcPlugName, const MString& dstPlugName, void* + ///< userData); \endcode + kPlugsDGModFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MPlugsDGModFunction \code typedef void + ///< (*MPlugsDGModFunction) (MPlugArray& plugs, MDGModifier& modifier, + ///< void* userData); \endcode + kNodeUuidFunction, ///< \brief describes the maya callback type \b MMessage::MNodeUuidFunction + ///< \code typedef void (*MNodeUuidFunction) (MObject& node, const MUuid& + ///< uuid, void* userData); \endcode + kCheckNodeUuidFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MCheckNodeUuidFunction \code typedef Action + ///< (*MCheckNodeUuidFunction) (bool doAction, MObject& node, MUuid& + ///< uuid, void* userData); \endcode + kObjectFileFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MObjectFileFunction \code typedef void + ///< (*MObjectFileFunction) (const MObject& object, const MFileObject& + ///< file, void* userData); \endcode + kCheckObjectFileFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MCheckObjectFileFunction \code typedef void + ///< (*MCheckObjectFileFunction) (bool* retCode, const MObject& + ///< referenceNode, MFileObject& file, void* userData); \endcode + kRenderTileFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MRenderTileFunction \code typedef void + ///< (*MRenderTileFunction) (int originX, int originY, int tileMaxX, int + ///< tileMaxY, void* userData); \endcode + kMessageFunction, ///< \brief describes the maya callback type \b MMessage::MMessageFunction + ///< \code typedef void (*MMessageFunction) (const MString& message, + ///< MCommandMessage::MessageType messageType, void* userData); \endcode + kMessageFilterFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MMessageFilterFunction \code typedef void + ///< (*MMessageFilterFunction) (const MString& message, + ///< MCommandMessage::MessageType messageType, bool& filterOutput, void* + ///< userData); \endcode + kMessageParentChildFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MMessageParentChildFunction \code typedef void + ///< (*MMessageParentChildFunction) (MDagMessage::DagMessage + ///< msgType, MDagPath& child, MDagPath& parent, void* userData); + ///< \endcode + kPathObjectPlugColoursFunction, ///< \brief describes the maya callback type \b + ///< MMessage::MPathObjectPlugColorsFunction \code typedef void + ///< (*MPathObjectPlugColorsFunction) (MDagPath& path, MObject& + ///< object, MPlug& plug, MColorArray& colors, void* userData); + ///< \endcode + kWorldMatrixModifiedFunction ///< \brief describes the maya callback type \b + ///< MMessage::MWorldMatrixModifiedFunction \code typedef void + ///< (*MWorldMatrixModifiedFunction) (MObject& transformNode, + ///< MDagMessage::MatrixModifiedFlags& modified, void* userData); + ///< \endcode }; //---------------------------------------------------------------------------------------------------------------------- @@ -108,15 +207,15 @@ namespace AnimMessage { /// \brief Maya events defined in the \b MAnimMessage class enum AnimMessage { - kAnimCurveEdited, ///< MAnimMessage::addAnimCurveEditedCallback - kAnimKeyFrameEdited, ///< MAnimMessage::addAnimKeyframeEditedCallback - kNodeAnimKeyframeEdited, ///< MAnimMessage::addNodeAnimKeyframeEditedCallback - \b unsupported - kAnimKeyframeEditCheck, ///< MAnimMessage::addAnimKeyframeEditCheckCallback - kPreBakeResults, ///< MAnimMessage::addPreBakeResultsCallback - kPostBakeResults, ///< MAnimMessage::addPostBakeResultsCallback - kDisableImplicitControl ///< MAnimMessage::addDisableImplicitControlCallback + kAnimCurveEdited, ///< MAnimMessage::addAnimCurveEditedCallback + kAnimKeyFrameEdited, ///< MAnimMessage::addAnimKeyframeEditedCallback + kNodeAnimKeyframeEdited, ///< MAnimMessage::addNodeAnimKeyframeEditedCallback - \b unsupported + kAnimKeyframeEditCheck, ///< MAnimMessage::addAnimKeyframeEditCheckCallback + kPreBakeResults, ///< MAnimMessage::addPreBakeResultsCallback + kPostBakeResults, ///< MAnimMessage::addPostBakeResultsCallback + kDisableImplicitControl ///< MAnimMessage::addDisableImplicitControlCallback }; -} +} // namespace AnimMessage //---------------------------------------------------------------------------------------------------------------------- namespace CameraSetMessage { @@ -124,10 +223,10 @@ namespace CameraSetMessage { /// \brief Maya events defined in the \b MCameraSetMessage class enum CameraSetMessage { - kCameraLayer, ///< MCamerSetMessage::addCameraLayerCallback - kCameraChanged ///< MCamerSetMessage::addCameraChangedCallback + kCameraLayer, ///< MCamerSetMessage::addCameraLayerCallback + kCameraChanged ///< MCamerSetMessage::addCameraChangedCallback }; -} +} // namespace CameraSetMessage //---------------------------------------------------------------------------------------------------------------------- namespace CommandMessage { @@ -135,12 +234,12 @@ namespace CommandMessage { /// \brief Maya events defined in the \b MCommandMessage class enum CommandMessage { - kCommand, ///< MCommandMessage::addCommandCallback - kCommandOuptut, ///< MCommandMessage::addCommandOutputCallback - kCommandOutputFilter, ///< MCommandMessage::addCommandOutputFilterCallback - kProc ///< MCommandMessage::addProcCallback + kCommand, ///< MCommandMessage::addCommandCallback + kCommandOuptut, ///< MCommandMessage::addCommandOutputCallback + kCommandOutputFilter, ///< MCommandMessage::addCommandOutputFilterCallback + kProc ///< MCommandMessage::addProcCallback }; -} +} // namespace CommandMessage //---------------------------------------------------------------------------------------------------------------------- namespace ConditionMessage { @@ -148,9 +247,9 @@ namespace ConditionMessage { /// \brief Maya events defined in the \b MConditionMessage class enum ConditionMessage { - kCondition ///< unsupported + kCondition ///< unsupported }; -} +} // namespace ConditionMessage //---------------------------------------------------------------------------------------------------------------------- namespace ContainerMessage { @@ -158,10 +257,10 @@ namespace ContainerMessage { /// \brief Maya events defined in the \b MContainerMessage class enum ContainerMessage { - kPublishAttr, ///< MContainerMessage::addPublishAttrCallback - kBoundAttr ///< MContainerMessage::addBoundAttrCallback + kPublishAttr, ///< MContainerMessage::addPublishAttrCallback + kBoundAttr ///< MContainerMessage::addBoundAttrCallback }; -} +} // namespace ContainerMessage //---------------------------------------------------------------------------------------------------------------------- namespace DagMessage { @@ -169,27 +268,27 @@ namespace DagMessage { /// \brief Maya events defined in the \b MDagMessage class enum DagMessage { - kParentAdded, ///< MDagMessage::addParentAddedCallback - kParentAddedDagPath, ///< MDagMessage::addParentAddedDagPathCallback - \b unsupported - kParentRemoved, ///< MDagMessage::addParentRemovedCallback - kParentRemovedDagPath, ///< MDagMessage::addParentRemovedDagPathCallback - \b unsupported - kChildAdded, ///< MDagMessage::addChildAddedCallback - kChildAddedDagPath, ///< MDagMessage::addChildAddedDagPathCallback - \b unsupported - kChildRemoved, ///< MDagMessage::addChildRemovedCallback - kChildRemovedDagPath, ///< MDagMessage::addChildRemovedDagPathCallback - \b unsupported - kChildReordered, ///< MDagMessage::addChildReorderedCallback - kChildReorderedDagPath, ///< MDagMessage::addChildReorderedDagPathCallback - \b unsupported - kDag, ///< MDagMessage::addDagCallback - \b unsupported - kDagDagPath, ///< MDagMessage::addDagDagPathCallback - \b unsupported - kAllDagChanges, ///< MDagMessage::addAllDagChangesCallback - kAllDagChangesDagPath, ///< MDagMessage::addAllDagChangesDagPathCallback - \b unsupported - kInstanceAdded, ///< MDagMessage::addInstanceAddedCallback - kInstanceAddedDagPath, ///< MDagMessage::addInstanceAddedDagPathCallback - \b unsupported - kInstanceRemoved, ///< MDagMessage::addInstanceRemovedCallback - kInstanceRemovedDagPath, ///< MDagMessage::addInstanceRemovedDagPathCallback - \b unsupported - kWorldMatrixModified, ///< MDagMessage::addWorldMatrixModifiedCallback - \b unsupported + kParentAdded, ///< MDagMessage::addParentAddedCallback + kParentAddedDagPath, ///< MDagMessage::addParentAddedDagPathCallback - \b unsupported + kParentRemoved, ///< MDagMessage::addParentRemovedCallback + kParentRemovedDagPath, ///< MDagMessage::addParentRemovedDagPathCallback - \b unsupported + kChildAdded, ///< MDagMessage::addChildAddedCallback + kChildAddedDagPath, ///< MDagMessage::addChildAddedDagPathCallback - \b unsupported + kChildRemoved, ///< MDagMessage::addChildRemovedCallback + kChildRemovedDagPath, ///< MDagMessage::addChildRemovedDagPathCallback - \b unsupported + kChildReordered, ///< MDagMessage::addChildReorderedCallback + kChildReorderedDagPath, ///< MDagMessage::addChildReorderedDagPathCallback - \b unsupported + kDag, ///< MDagMessage::addDagCallback - \b unsupported + kDagDagPath, ///< MDagMessage::addDagDagPathCallback - \b unsupported + kAllDagChanges, ///< MDagMessage::addAllDagChangesCallback + kAllDagChangesDagPath, ///< MDagMessage::addAllDagChangesDagPathCallback - \b unsupported + kInstanceAdded, ///< MDagMessage::addInstanceAddedCallback + kInstanceAddedDagPath, ///< MDagMessage::addInstanceAddedDagPathCallback - \b unsupported + kInstanceRemoved, ///< MDagMessage::addInstanceRemovedCallback + kInstanceRemovedDagPath, ///< MDagMessage::addInstanceRemovedDagPathCallback - \b unsupported + kWorldMatrixModified, ///< MDagMessage::addWorldMatrixModifiedCallback - \b unsupported }; -} +} // namespace DagMessage //---------------------------------------------------------------------------------------------------------------------- namespace DGMessage { @@ -197,17 +296,17 @@ namespace DGMessage { /// \brief Maya events defined in the \b MDGMessage class enum DGMessage { - kTimeChange, ///< DGMessage::addTimeChangeCallback - kDelayedTimeChange, ///< DGMessage::addDelayedTimeChangeCallback - kDelayedTimeChangeRunup, ///< DGMessage::addDelayedTimeChangeRunupCallback - kForceUpdate, ///< DGMessage::addForceUpdateCallback - kNodeAdded, ///< DGMessage::addNodeAddedCallback - kNodeRemoved, ///< DGMessage::addNodeRemovedCallback - kConnection, ///< DGMessage::addConnectionCallback - kPreConnection, ///< DGMessage::addPreConnectionCallback - kNodeChangeUuidCheck, ///< DGMessage::addNodeChangeUuidCheckCallback - \b unsupported + kTimeChange, ///< DGMessage::addTimeChangeCallback + kDelayedTimeChange, ///< DGMessage::addDelayedTimeChangeCallback + kDelayedTimeChangeRunup, ///< DGMessage::addDelayedTimeChangeRunupCallback + kForceUpdate, ///< DGMessage::addForceUpdateCallback + kNodeAdded, ///< DGMessage::addNodeAddedCallback + kNodeRemoved, ///< DGMessage::addNodeRemovedCallback + kConnection, ///< DGMessage::addConnectionCallback + kPreConnection, ///< DGMessage::addPreConnectionCallback + kNodeChangeUuidCheck, ///< DGMessage::addNodeChangeUuidCheckCallback - \b unsupported }; -} +} // namespace DGMessage //---------------------------------------------------------------------------------------------------------------------- namespace EventMessage { @@ -216,7 +315,7 @@ namespace EventMessage { enum EventMessage { }; -} +} // namespace EventMessage //---------------------------------------------------------------------------------------------------------------------- namespace LockMessage { @@ -225,7 +324,7 @@ namespace LockMessage { enum LockMessage { }; -} +} // namespace LockMessage //---------------------------------------------------------------------------------------------------------------------- namespace ModelMessage { @@ -233,13 +332,13 @@ namespace ModelMessage { /// \brief Maya events defined in the \b MModelMessage class enum ModelMessage { - kCallback, ///< MModelMessage::addCallback - kBeforeDuplicate, ///< MModelMessage::addBeforeDuplicateCallback - kAfterDuplicate, ///< MModelMessage::addAfterDuplicateCallback - kNodeAddedToModel, ///< MModelMessage::addNodeAddedToModelCallback - \b upsupported - kNodeRemovedFromModel, ///< MModelMessage::addNodeRemovedFromModelCallback - \b upsupported + kCallback, ///< MModelMessage::addCallback + kBeforeDuplicate, ///< MModelMessage::addBeforeDuplicateCallback + kAfterDuplicate, ///< MModelMessage::addAfterDuplicateCallback + kNodeAddedToModel, ///< MModelMessage::addNodeAddedToModelCallback - \b upsupported + kNodeRemovedFromModel, ///< MModelMessage::addNodeRemovedFromModelCallback - \b upsupported }; -} +} // namespace ModelMessage //---------------------------------------------------------------------------------------------------------------------- namespace NodeMessage { @@ -248,7 +347,7 @@ namespace NodeMessage { enum NodeMessage { }; -} +} // namespace NodeMessage //---------------------------------------------------------------------------------------------------------------------- namespace ObjectSetMessage { @@ -257,7 +356,7 @@ namespace ObjectSetMessage { enum ObjectSetMessage { }; -} +} // namespace ObjectSetMessage //---------------------------------------------------------------------------------------------------------------------- namespace PaintMessage { @@ -265,9 +364,9 @@ namespace PaintMessage { /// \brief Maya events defined in the \b MPaintMessage class enum PaintMessage { - kVertexColor, ///< MPaintMessage::addVertexColorCallback + kVertexColor, ///< MPaintMessage::addVertexColorCallback }; -} +} // namespace PaintMessage //---------------------------------------------------------------------------------------------------------------------- namespace PolyMessage { @@ -276,7 +375,7 @@ namespace PolyMessage { enum PolyMessage { }; -} +} // namespace PolyMessage //---------------------------------------------------------------------------------------------------------------------- namespace SceneMessage { @@ -284,57 +383,105 @@ namespace SceneMessage { /// \brief Maya events defined in the \b MSceneMessage class enum SceneMessage { - kSceneUpdate = MSceneMessage::kSceneUpdate, ///< MSceneMessage::addCallback(MSceneMessage::kSceneUpdate) - kBeforeNew = MSceneMessage::kBeforeNew, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeNew) - kAfterNew = MSceneMessage::kAfterNew, ///< MSceneMessage::addCallback(MSceneMessage::kAfterNew) - kBeforeImport = MSceneMessage::kBeforeImport, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeImport) - kAfterImport = MSceneMessage::kAfterImport, ///< MSceneMessage::addCallback(MSceneMessage::kAfterImport) - kBeforeOpen = MSceneMessage::kBeforeOpen, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeOpen) - kAfterOpen = MSceneMessage::kAfterOpen, ///< MSceneMessage::addCallback(MSceneMessage::kAfterOpen) - kBeforeFileRead = MSceneMessage::kBeforeFileRead, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeFileRead) - kAfterFileRead = MSceneMessage::kAfterFileRead, ///< MSceneMessage::addCallback(MSceneMessage::kAfterFileRead) - kAfterSceneReadAndRecordEdits = MSceneMessage::kAfterSceneReadAndRecordEdits, ///< MSceneMessage::addCallback(MSceneMessage::kAfterSceneReadAndRecordEdits) - kBeforeExport = MSceneMessage::kBeforeExport, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeExport) - kExportStarted = MSceneMessage::kExportStarted, ///< MSceneMessage::addCallback(MSceneMessage::kExportStarted) - kAfterExport = MSceneMessage::kAfterExport, ///< MSceneMessage::addCallback(MSceneMessage::kAfterExport) - kBeforeSave = MSceneMessage::kBeforeSave, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeSave) - kAfterSave = MSceneMessage::kAfterSave, ///< MSceneMessage::addCallback(MSceneMessage::kAfterSave) - kBeforeCreateReference = MSceneMessage::kBeforeCreateReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeCreateReference) - kBeforeLoadReferenceAndRecordEdits = MSceneMessage::kBeforeLoadReferenceAndRecordEdits, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeLoadReferenceAndRecordEdits) - kAfterCreateReference = MSceneMessage::kAfterCreateReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterCreateReference) - kAfterCreateReferenceAndRecordEdits = MSceneMessage::kAfterCreateReferenceAndRecordEdits, ///< MSceneMessage::addCallback(MSceneMessage::kAfterCreateReferenceAndRecordEdits) - kBeforeRemoveReference = MSceneMessage::kBeforeRemoveReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeRemoveReference) - kAfterRemoveReference = MSceneMessage::kAfterRemoveReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterRemoveReference) - kBeforeImportReference = MSceneMessage::kBeforeImportReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeImportReference) - kAfterImportReference = MSceneMessage::kAfterImportReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterImportReference) - kBeforeExportReference = MSceneMessage::kBeforeExportReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeExportReference) - kAfterExportReference = MSceneMessage::kAfterExportReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterExportReference) - kBeforeUnloadReference = MSceneMessage::kBeforeUnloadReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeUnloadReference) - kAfterUnloadReference = MSceneMessage::kAfterUnloadReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterUnloadReference) - kBeforeLoadReference = MSceneMessage::kBeforeLoadReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeLoadReference) - kBeforeCreateReferenceAndRecordEdits = MSceneMessage::kBeforeCreateReferenceAndRecordEdits, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeCreateReferenceAndRecordEdits) - kAfterLoadReference = MSceneMessage::kAfterLoadReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterLoadReference) - kAfterLoadReferenceAndRecordEdits = MSceneMessage::kAfterLoadReferenceAndRecordEdits, ///< MSceneMessage::addCallback(MSceneMessage::kAfterLoadReferenceAndRecordEdits) - kBeforeSoftwareRender = MSceneMessage::kBeforeSoftwareRender, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeSoftwareRender) - kAfterSoftwareRender = MSceneMessage::kAfterSoftwareRender, ///< MSceneMessage::addCallback(MSceneMessage::kAfterSoftwareRender) - kBeforeSoftwareFrameRender = MSceneMessage::kBeforeSoftwareFrameRender, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeSoftwareFrameRender) - kAfterSoftwareFrameRender = MSceneMessage::kAfterSoftwareFrameRender, ///< MSceneMessage::addCallback(MSceneMessage::kAfterSoftwareFrameRender) - kSoftwareRenderInterrupted = MSceneMessage::kSoftwareRenderInterrupted, ///< MSceneMessage::addCallback(MSceneMessage::kSoftwareRenderInterrupted) - kMayaInitialized = MSceneMessage::kMayaInitialized, ///< MSceneMessage::addCallback(MSceneMessage::kMayaInitialized) - kMayaExiting = MSceneMessage::kMayaExiting, ///< MSceneMessage::addCallback(MSceneMessage::kMayaExiting) - kBeforeNewCheck = MSceneMessage::kBeforeNewCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeNewCheck) - kBeforeImportCheck = MSceneMessage::kBeforeImportCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeImportCheck) - kBeforeOpenCheck = MSceneMessage::kBeforeOpenCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeOpenCheck) - kBeforeExportCheck = MSceneMessage::kBeforeExportCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeExportCheck) - kBeforeSaveCheck = MSceneMessage::kBeforeSaveCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeSaveCheck) - kBeforeCreateReferenceCheck = MSceneMessage::kBeforeCreateReferenceCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeCreateReferenceCheck) - kBeforeLoadReferenceCheck = MSceneMessage::kBeforeLoadReferenceCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeLoadReferenceCheck) - kBeforePluginLoad = MSceneMessage::kBeforePluginLoad, ///< MSceneMessage::addStringArrayCallback(MSceneMessage::kBeforePluginLoad) - kAfterPluginLoad = MSceneMessage::kAfterPluginLoad, ///< MSceneMessage::addStringArrayCallback(MSceneMessage::kAfterPluginLoad) - kBeforePluginUnload = MSceneMessage::kBeforePluginUnload, ///< MSceneMessage::addStringArrayCallback(MSceneMessage::kBeforePluginUnload) - kAfterPluginUnload = MSceneMessage::kAfterPluginUnload, ///< MSceneMessage::addStringArrayCallback(MSceneMessage::kAfterPluginUnload) + kSceneUpdate + = MSceneMessage::kSceneUpdate, ///< MSceneMessage::addCallback(MSceneMessage::kSceneUpdate) + kBeforeNew + = MSceneMessage::kBeforeNew, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeNew) + kAfterNew = MSceneMessage::kAfterNew, ///< MSceneMessage::addCallback(MSceneMessage::kAfterNew) + kBeforeImport + = MSceneMessage::kBeforeImport, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeImport) + kAfterImport + = MSceneMessage::kAfterImport, ///< MSceneMessage::addCallback(MSceneMessage::kAfterImport) + kBeforeOpen + = MSceneMessage::kBeforeOpen, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeOpen) + kAfterOpen + = MSceneMessage::kAfterOpen, ///< MSceneMessage::addCallback(MSceneMessage::kAfterOpen) + kBeforeFileRead = MSceneMessage:: + kBeforeFileRead, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeFileRead) + kAfterFileRead + = MSceneMessage::kAfterFileRead, ///< MSceneMessage::addCallback(MSceneMessage::kAfterFileRead) + kAfterSceneReadAndRecordEdits = MSceneMessage:: + kAfterSceneReadAndRecordEdits, ///< MSceneMessage::addCallback(MSceneMessage::kAfterSceneReadAndRecordEdits) + kBeforeExport + = MSceneMessage::kBeforeExport, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeExport) + kExportStarted + = MSceneMessage::kExportStarted, ///< MSceneMessage::addCallback(MSceneMessage::kExportStarted) + kAfterExport + = MSceneMessage::kAfterExport, ///< MSceneMessage::addCallback(MSceneMessage::kAfterExport) + kBeforeSave + = MSceneMessage::kBeforeSave, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeSave) + kAfterSave + = MSceneMessage::kAfterSave, ///< MSceneMessage::addCallback(MSceneMessage::kAfterSave) + kBeforeCreateReference = MSceneMessage:: + kBeforeCreateReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeCreateReference) + kBeforeLoadReferenceAndRecordEdits = MSceneMessage:: + kBeforeLoadReferenceAndRecordEdits, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeLoadReferenceAndRecordEdits) + kAfterCreateReference = MSceneMessage:: + kAfterCreateReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterCreateReference) + kAfterCreateReferenceAndRecordEdits = MSceneMessage:: + kAfterCreateReferenceAndRecordEdits, ///< MSceneMessage::addCallback(MSceneMessage::kAfterCreateReferenceAndRecordEdits) + kBeforeRemoveReference = MSceneMessage:: + kBeforeRemoveReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeRemoveReference) + kAfterRemoveReference = MSceneMessage:: + kAfterRemoveReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterRemoveReference) + kBeforeImportReference = MSceneMessage:: + kBeforeImportReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeImportReference) + kAfterImportReference = MSceneMessage:: + kAfterImportReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterImportReference) + kBeforeExportReference = MSceneMessage:: + kBeforeExportReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeExportReference) + kAfterExportReference = MSceneMessage:: + kAfterExportReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterExportReference) + kBeforeUnloadReference = MSceneMessage:: + kBeforeUnloadReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeUnloadReference) + kAfterUnloadReference = MSceneMessage:: + kAfterUnloadReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterUnloadReference) + kBeforeLoadReference = MSceneMessage:: + kBeforeLoadReference, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeLoadReference) + kBeforeCreateReferenceAndRecordEdits = MSceneMessage:: + kBeforeCreateReferenceAndRecordEdits, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeCreateReferenceAndRecordEdits) + kAfterLoadReference = MSceneMessage:: + kAfterLoadReference, ///< MSceneMessage::addCallback(MSceneMessage::kAfterLoadReference) + kAfterLoadReferenceAndRecordEdits = MSceneMessage:: + kAfterLoadReferenceAndRecordEdits, ///< MSceneMessage::addCallback(MSceneMessage::kAfterLoadReferenceAndRecordEdits) + kBeforeSoftwareRender = MSceneMessage:: + kBeforeSoftwareRender, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeSoftwareRender) + kAfterSoftwareRender = MSceneMessage:: + kAfterSoftwareRender, ///< MSceneMessage::addCallback(MSceneMessage::kAfterSoftwareRender) + kBeforeSoftwareFrameRender = MSceneMessage:: + kBeforeSoftwareFrameRender, ///< MSceneMessage::addCallback(MSceneMessage::kBeforeSoftwareFrameRender) + kAfterSoftwareFrameRender = MSceneMessage:: + kAfterSoftwareFrameRender, ///< MSceneMessage::addCallback(MSceneMessage::kAfterSoftwareFrameRender) + kSoftwareRenderInterrupted = MSceneMessage:: + kSoftwareRenderInterrupted, ///< MSceneMessage::addCallback(MSceneMessage::kSoftwareRenderInterrupted) + kMayaInitialized = MSceneMessage:: + kMayaInitialized, ///< MSceneMessage::addCallback(MSceneMessage::kMayaInitialized) + kMayaExiting + = MSceneMessage::kMayaExiting, ///< MSceneMessage::addCallback(MSceneMessage::kMayaExiting) + kBeforeNewCheck = MSceneMessage:: + kBeforeNewCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeNewCheck) + kBeforeImportCheck = MSceneMessage:: + kBeforeImportCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeImportCheck) + kBeforeOpenCheck = MSceneMessage:: + kBeforeOpenCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeOpenCheck) + kBeforeExportCheck = MSceneMessage:: + kBeforeExportCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeExportCheck) + kBeforeSaveCheck = MSceneMessage:: + kBeforeSaveCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeSaveCheck) + kBeforeCreateReferenceCheck = MSceneMessage:: + kBeforeCreateReferenceCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeCreateReferenceCheck) + kBeforeLoadReferenceCheck = MSceneMessage:: + kBeforeLoadReferenceCheck, ///< MSceneMessage::addCheckCallback(MSceneMessage::kBeforeLoadReferenceCheck) + kBeforePluginLoad = MSceneMessage:: + kBeforePluginLoad, ///< MSceneMessage::addStringArrayCallback(MSceneMessage::kBeforePluginLoad) + kAfterPluginLoad = MSceneMessage:: + kAfterPluginLoad, ///< MSceneMessage::addStringArrayCallback(MSceneMessage::kAfterPluginLoad) + kBeforePluginUnload = MSceneMessage:: + kBeforePluginUnload, ///< MSceneMessage::addStringArrayCallback(MSceneMessage::kBeforePluginUnload) + kAfterPluginUnload = MSceneMessage:: + kAfterPluginUnload, ///< MSceneMessage::addStringArrayCallback(MSceneMessage::kAfterPluginUnload) }; -} +} // namespace SceneMessage //---------------------------------------------------------------------------------------------------------------------- namespace TimerMessage { @@ -343,7 +490,7 @@ namespace TimerMessage { enum TimerMessage { }; -} +} // namespace TimerMessage //---------------------------------------------------------------------------------------------------------------------- namespace UiMessage { @@ -352,580 +499,957 @@ namespace UiMessage { enum UiMessage { }; -} +} // namespace UiMessage //---------------------------------------------------------------------------------------------------------------------- -/// \brief An interface that provides the event system with some utilities from the underlying DCC application. -/// This class is responsible for keeping track of the number of maya events registered, and creating/destroying -/// the MMessage callbacks. +/// \brief An interface that provides the event system with some utilities from the underlying DCC +/// application. +/// This class is responsible for keeping track of the number of maya events registered, and +/// creating/destroying the MMessage callbacks. /// \ingroup mayaevents //---------------------------------------------------------------------------------------------------------------------- -class MayaEventHandler - : public AL::event::CustomEventHandler +class MayaEventHandler : public AL::event::CustomEventHandler { - typedef std::unordered_map EventToMaya; + typedef std::unordered_map EventToMaya; + public: + /// \brief a structure to store some binding info for the MMessage event info + struct MayaCallbackInfo + { + AL::event::EventId eventId; ///< the event id from the event scheduler + uint32_t refCount; ///< the ref count for this callback + MayaMessageType mayaMessageType; ///< the maya MMessage class that defines the message + MayaCallbackType + mayaCallbackType; ///< the type of C callback function needed to execute the callback + uint32_t mmessageEnum; ///< the enum value from one of the MSceneMessage / MEventMessage etc + ///< classes. + MCallbackId mayaCallback; ///< the maya callback ID + }; + + /// \brief constructor function + /// \param scheduler the event scheduler + /// \param eventType the event type + AL_MAYA_EVENTS_PUBLIC + MayaEventHandler(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + + /// \brief dtor + ~MayaEventHandler(); + + /// \brief returns the event type string + /// \return "maya" + const char* eventTypeString() const override { return "maya"; } + + /// \brief returns the event scheduler + /// \return the event scheduler used for these maya events + AL::event::EventScheduler* scheduler() const { return m_scheduler; } + + /// \brief queries the maya event information for the specified maya event + /// \param event the event ID + /// \return a pointer to the maya event information (or null for an invalid event) + const MayaCallbackInfo* getEventInfo(const AL::event::EventId event) const + { + const auto it = m_eventMapping.find(event); + if (it == m_eventMapping.end()) + return 0; + return m_callbacks.data() + it->second; + } + + /// \brief queries whether the event has an associated MCallbackId (indicating the callback is + /// active with maya) \param event the event to query \return true if callback is active with + /// maya, false otherwise + bool isMayaCallbackRegistered(const AL::event::EventId event) const + { + const MayaCallbackInfo* cbi = getEventInfo(event); + return cbi ? cbi->refCount != 0 : false; + } - /// \brief a structure to store some binding info for the MMessage event info - struct MayaCallbackInfo - { - AL::event::EventId eventId; ///< the event id from the event scheduler - uint32_t refCount; ///< the ref count for this callback - MayaMessageType mayaMessageType; ///< the maya MMessage class that defines the message - MayaCallbackType mayaCallbackType; ///< the type of C callback function needed to execute the callback - uint32_t mmessageEnum; ///< the enum value from one of the MSceneMessage / MEventMessage etc classes. - MCallbackId mayaCallback; ///< the maya callback ID - }; - - /// \brief constructor function - /// \param scheduler the event scheduler - /// \param eventType the event type - AL_MAYA_EVENTS_PUBLIC - MayaEventHandler(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - - /// \brief dtor - ~MayaEventHandler(); - - /// \brief returns the event type string - /// \return "maya" - const char* eventTypeString() const override - { return "maya"; } - - /// \brief returns the event scheduler - /// \return the event scheduler used for these maya events - AL::event::EventScheduler* scheduler() const - { return m_scheduler; } - - /// \brief queries the maya event information for the specified maya event - /// \param event the event ID - /// \return a pointer to the maya event information (or null for an invalid event) - const MayaCallbackInfo* getEventInfo(const AL::event::EventId event) const - { - const auto it = m_eventMapping.find(event); - if(it == m_eventMapping.end()) return 0; - return m_callbacks.data() + it->second; - } - - /// \brief queries whether the event has an associated MCallbackId (indicating the callback is active with maya) - /// \param event the event to query - /// \return true if callback is active with maya, false otherwise - bool isMayaCallbackRegistered(const AL::event::EventId event) const - { - const MayaCallbackInfo* cbi = getEventInfo(event); - return cbi ? cbi->refCount != 0 : false; - } - - /// \brief queries the maya event information for the specified maya event - /// \param eventName the event name - /// \return a pointer to the maya event information (or null for an invalid event) - const MayaCallbackInfo* getEventInfo(const char* const eventName) const - { - const AL::event::EventDispatcher* const dispatcher = m_scheduler->event(eventName); - if(dispatcher) - { - return getEventInfo(dispatcher->eventId()); - } - return 0; - } - - /// \brief queries whether the event has an associated MCallbackId (indicating the callback is active with maya) - /// \param eventName the event to query - /// \return true if callback is active with maya, false otherwise - bool isMayaCallbackRegistered(const char* const eventName) const - { - const MayaCallbackInfo* cbi = getEventInfo(eventName); - return cbi ? cbi->refCount != 0 : false; - } + /// \brief queries the maya event information for the specified maya event + /// \param eventName the event name + /// \return a pointer to the maya event information (or null for an invalid event) + const MayaCallbackInfo* getEventInfo(const char* const eventName) const + { + const AL::event::EventDispatcher* const dispatcher = m_scheduler->event(eventName); + if (dispatcher) { + return getEventInfo(dispatcher->eventId()); + } + return 0; + } + + /// \brief queries whether the event has an associated MCallbackId (indicating the callback is + /// active with maya) \param eventName the event to query \return true if callback is active + /// with maya, false otherwise + bool isMayaCallbackRegistered(const char* const eventName) const + { + const MayaCallbackInfo* cbi = getEventInfo(eventName); + return cbi ? cbi->refCount != 0 : false; + } private: - void onCallbackCreated(const AL::event::CallbackId callbackId) override; - void onCallbackDestroyed(const AL::event::CallbackId callbackId) override; - bool registerEvent( - AL::event::EventScheduler* scheduler, - const char* eventName, - AL::event::EventType eventType, - MayaMessageType messageType, - MayaCallbackType callbackType, - uint32_t mmessageEnum); - void initEvent(MayaCallbackInfo& cbi); - void initAnimMessage(MayaCallbackInfo& cbi); - void initCameraSetMessage(MayaCallbackInfo& cbi); - void initCommandMessage(MayaCallbackInfo& cbi); - void initConditionMessage(MayaCallbackInfo& cbi); - void initContainerMessage(MayaCallbackInfo& cbi); - void initDagMessage(MayaCallbackInfo& cbi); - void initDGMessage(MayaCallbackInfo& cbi); - void initEventMessage(MayaCallbackInfo& cbi); - void initLockMessage(MayaCallbackInfo& cbi); - void initModelMessage(MayaCallbackInfo& cbi); - void initNodeMessage(MayaCallbackInfo& cbi); - void initObjectSetMessage(MayaCallbackInfo& cbi); - void initPaintMessage(MayaCallbackInfo& cbi); - void initPolyMessage(MayaCallbackInfo& cbi); - void initSceneMessage(MayaCallbackInfo& cbi); - void initTimerMessage(MayaCallbackInfo& cbi); - void initUiMessage(MayaCallbackInfo& cbi); - void registerAnimMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerCameraSetMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerCommandMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerConditionMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerContainerMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerDagMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerDGMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerEventMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerLockMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerModelMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerNodeMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerObjectSetMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerPaintMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerPolyMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerSceneMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerTimerMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - void registerUiMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); - std::vector m_callbacks; - EventToMaya m_eventMapping; - AL::event::EventScheduler* m_scheduler; + void onCallbackCreated(const AL::event::CallbackId callbackId) override; + void onCallbackDestroyed(const AL::event::CallbackId callbackId) override; + bool registerEvent( + AL::event::EventScheduler* scheduler, + const char* eventName, + AL::event::EventType eventType, + MayaMessageType messageType, + MayaCallbackType callbackType, + uint32_t mmessageEnum); + void initEvent(MayaCallbackInfo& cbi); + void initAnimMessage(MayaCallbackInfo& cbi); + void initCameraSetMessage(MayaCallbackInfo& cbi); + void initCommandMessage(MayaCallbackInfo& cbi); + void initConditionMessage(MayaCallbackInfo& cbi); + void initContainerMessage(MayaCallbackInfo& cbi); + void initDagMessage(MayaCallbackInfo& cbi); + void initDGMessage(MayaCallbackInfo& cbi); + void initEventMessage(MayaCallbackInfo& cbi); + void initLockMessage(MayaCallbackInfo& cbi); + void initModelMessage(MayaCallbackInfo& cbi); + void initNodeMessage(MayaCallbackInfo& cbi); + void initObjectSetMessage(MayaCallbackInfo& cbi); + void initPaintMessage(MayaCallbackInfo& cbi); + void initPolyMessage(MayaCallbackInfo& cbi); + void initSceneMessage(MayaCallbackInfo& cbi); + void initTimerMessage(MayaCallbackInfo& cbi); + void initUiMessage(MayaCallbackInfo& cbi); + void registerAnimMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void + registerCameraSetMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void + registerCommandMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void + registerConditionMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void + registerContainerMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void registerDagMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void registerDGMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void + registerEventMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void registerLockMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void + registerModelMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void registerNodeMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void + registerObjectSetMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void + registerPaintMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void registerPolyMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void + registerSceneMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void + registerTimerMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + void registerUiMessages(AL::event::EventScheduler* scheduler, AL::event::EventType eventType); + std::vector m_callbacks; + EventToMaya m_eventMapping; + AL::event::EventScheduler* m_scheduler; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief A class that replaces the MMessage (and derived message classes) in order to provide a level of scheduling -/// and debugability across multiple plugins, which is not possible in the standard maya API. Effectively the -/// class wraps the core EventScheduler API to provide a little bit of additional type safety on the callback -/// type provided. +/// \brief A class that replaces the MMessage (and derived message classes) in order to provide a +/// level of scheduling +/// and debugability across multiple plugins, which is not possible in the standard maya +/// API. Effectively the class wraps the core EventScheduler API to provide a little bit of +/// additional type safety on the callback type provided. /// \ingroup mayaevents //---------------------------------------------------------------------------------------------------------------------- class MayaEventManager { - AL_MAYA_EVENTS_PUBLIC - static MayaEventManager* g_instance; + AL_MAYA_EVENTS_PUBLIC + static MayaEventManager* g_instance; + public: + /// \brief returns the global maya event manager instance + AL_MAYA_EVENTS_PUBLIC + static MayaEventManager& instance(); + + /// \brief returns the global maya event manager instance + static void freeInstance() + { + delete g_instance; + g_instance = 0; + } + + /// \brief constructor + /// \param mayaEvents the custom event handler + MayaEventManager(MayaEventHandler* mayaEvents) + : m_mayaEvents(mayaEvents) + { + g_instance = this; + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MBasicFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kBasicFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MElapsedTimeFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kElapsedTimeFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MCheckFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kCheckFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MCheckFileFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kCheckFileFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MCheckPlugFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kCheckPlugFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MComponentFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kComponentFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MNodeFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kNodeFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MStringFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kStringFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MTwoStringFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kTwoStringFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MThreeStringFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kThreeStringFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MStringIntBoolIntFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, + MayaCallbackType::kStringIntBoolIntFunction, + eventName, + tag, + weight, + userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MStringIndexFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kStringIndexFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MNodeStringBoolFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, + MayaCallbackType::kNodeStringBoolFunction, + eventName, + tag, + weight, + userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MStateFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kStateFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MTimeFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kTimeFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MPlugFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kPlugFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MNodePlugFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kNodePlugFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MNodeStringFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kNodeStringFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MParentChildFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kParentChildFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MModifierFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kModifierFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MStringArrayFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kStringArrayFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MNodeModifierFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kNodeModifierFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MObjArray func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kObjArrayFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MNodeObjArray func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kNodeObjArrayFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MStringNode func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kStringNodeFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MCameraLayerFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kCameraLayerFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MCameraLayerCameraFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, + MayaCallbackType::kCameraLayerCameraFunction, + eventName, + tag, + weight, + userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MConnFailFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kConnFailFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MPlugsDGModFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kPlugsDGModFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MNodeUuidFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kNodeUuidFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MCheckNodeUuidFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, + MayaCallbackType::kCheckNodeUuidFunction, + eventName, + tag, + weight, + userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MObjectFileFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kObjectFileFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MCheckObjectFileFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, + MayaCallbackType::kCheckObjectFileFunction, + eventName, + tag, + weight, + userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MMessage::MRenderTileFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kRenderTileFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MCommandMessage::MMessageFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, MayaCallbackType::kMessageFunction, eventName, tag, weight, userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MCommandMessage::MMessageFilterFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, + MayaCallbackType::kMessageFilterFunction, + eventName, + tag, + weight, + userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MDagMessage::MMessageParentChildFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, + MayaCallbackType::kMessageParentChildFunction, + eventName, + tag, + weight, + userData); + } + + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MDagMessage::MWorldMatrixModifiedFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, + MayaCallbackType::kWorldMatrixModifiedFunction, + eventName, + tag, + weight, + userData); + } - /// \brief returns the global maya event manager instance - AL_MAYA_EVENTS_PUBLIC - static MayaEventManager& instance(); - - /// \brief returns the global maya event manager instance - static void freeInstance() - { delete g_instance; g_instance = 0; } - - /// \brief constructor - /// \param mayaEvents the custom event handler - MayaEventManager(MayaEventHandler* mayaEvents) - : m_mayaEvents(mayaEvents) { g_instance = this; } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MBasicFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kBasicFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MElapsedTimeFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kElapsedTimeFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MCheckFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kCheckFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MCheckFileFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kCheckFileFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MCheckPlugFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kCheckPlugFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MComponentFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kComponentFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MNodeFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kNodeFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MStringFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kStringFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MTwoStringFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kTwoStringFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MThreeStringFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kThreeStringFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MStringIntBoolIntFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kStringIntBoolIntFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MStringIndexFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kStringIndexFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MNodeStringBoolFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kNodeStringBoolFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MStateFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kStateFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MTimeFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kTimeFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MPlugFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kPlugFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MNodePlugFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kNodePlugFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MNodeStringFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kNodeStringFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MParentChildFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kParentChildFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MModifierFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kModifierFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MStringArrayFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kStringArrayFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MNodeModifierFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kNodeModifierFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MObjArray func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kObjArrayFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MNodeObjArray func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kNodeObjArrayFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MStringNode func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kStringNodeFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MCameraLayerFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kCameraLayerFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MCameraLayerCameraFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kCameraLayerCameraFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MConnFailFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kConnFailFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MPlugsDGModFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kPlugsDGModFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MNodeUuidFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kNodeUuidFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MCheckNodeUuidFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kCheckNodeUuidFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MObjectFileFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kObjectFileFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MCheckObjectFileFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kCheckObjectFileFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MMessage::MRenderTileFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kRenderTileFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MCommandMessage::MMessageFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kMessageFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MCommandMessage::MMessageFilterFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kMessageFilterFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MDagMessage::MMessageParentChildFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kMessageParentChildFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MDagMessage::MWorldMatrixModifiedFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kWorldMatrixModifiedFunction, eventName, tag, weight, userData); } - - /// \brief registers a C++ callback against a maya event - /// \param func the C++ function - /// \param eventName the event - /// \param tag the unique tag for the callback - /// \param weight the weight (lower weights at executed before higher weights) - /// \param userData custom user data pointer - /// \return the callback id - AL::event::CallbackId registerCallback(MPaintMessage::MPathObjectPlugColorsFunction func, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0) - { return registerCallbackInternal((void*)func, MayaCallbackType::kPathObjectPlugColoursFunction, eventName, tag, weight, userData); } - - /// \brief unregisters the callback id - /// \param id the callback id to unregister - bool unregisterCallback(AL::event::CallbackId id) - { - AL::event::EventScheduler* scheduler = m_mayaEvents->scheduler(); - return scheduler->unregisterCallback(id); - } - - /// \brief returns the custom maya event handler - /// \return the event handler in charge of registering and unregistering maya events - MayaEventHandler* mayaEventsHandler() const - { return m_mayaEvents; } + /// \brief registers a C++ callback against a maya event + /// \param func the C++ function + /// \param eventName the event + /// \param tag the unique tag for the callback + /// \param weight the weight (lower weights at executed before higher weights) + /// \param userData custom user data pointer + /// \return the callback id + AL::event::CallbackId registerCallback( + MPaintMessage::MPathObjectPlugColorsFunction func, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0) + { + return registerCallbackInternal( + (void*)func, + MayaCallbackType::kPathObjectPlugColoursFunction, + eventName, + tag, + weight, + userData); + } + + /// \brief unregisters the callback id + /// \param id the callback id to unregister + bool unregisterCallback(AL::event::CallbackId id) + { + AL::event::EventScheduler* scheduler = m_mayaEvents->scheduler(); + return scheduler->unregisterCallback(id); + } + + /// \brief returns the custom maya event handler + /// \return the event handler in charge of registering and unregistering maya events + MayaEventHandler* mayaEventsHandler() const { return m_mayaEvents; } private: - AL_MAYA_EVENTS_PUBLIC - AL::event::CallbackId registerCallbackInternal(const void* func, MayaCallbackType type, const char* const eventName, const char* const tag, uint32_t weight, void* userData = 0); - MayaEventHandler* m_mayaEvents; + AL_MAYA_EVENTS_PUBLIC + AL::event::CallbackId registerCallbackInternal( + const void* func, + MayaCallbackType type, + const char* const eventName, + const char* const tag, + uint32_t weight, + void* userData = 0); + MayaEventHandler* m_mayaEvents; }; - //---------------------------------------------------------------------------------------------------------------------- -} // utils -} // event -} // AL +} // namespace event +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- - diff --git a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/plugin.cpp b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/plugin.cpp index 165d0f8982..24a5fa5fb6 100644 --- a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/plugin.cpp +++ b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/plugin.cpp @@ -13,42 +13,42 @@ // See the License for the specific language governing permissions and // limitations under the License. // +#include "AL/maya/test/testHarness.h" +#include "AL/maya/tests/mayaplugintest/utils/CommandGuiHelperTest.h" +#include "AL/maya/tests/mayaplugintest/utils/NodeHelperUnitTest.h" +#include "AL/maya/utils/CommandGuiHelper.h" +#include "AL/maya/utils/MayaHelperMacros.h" +#include "AL/maya/utils/MenuBuilder.h" + #include #include #include -#include "AL/maya/utils/MayaHelperMacros.h" -#include "AL/maya/utils/CommandGuiHelper.h" -#include "AL/maya/utils/MenuBuilder.h" -#include "AL/maya/test/testHarness.h" -#include "AL/maya/tests/mayaplugintest/utils/NodeHelperUnitTest.h" -#include "AL/maya/tests/mayaplugintest/utils/CommandGuiHelperTest.h" using AL::maya::test::UnitTestHarness; MStatus initializePlugin(MObject obj) { - MStatus status; - MFnPlugin plugin(obj, "Animal Logic", "1.0", "Any"); + MStatus status; + MFnPlugin plugin(obj, "Animal Logic", "1.0", "Any"); - AL_REGISTER_DEPEND_NODE(plugin, AL::maya::tests::utils::NodeHelperUnitTest); - AL_REGISTER_COMMAND(plugin, AL::maya::tests::utils::CommandGuiHelperTestCMD); - AL_REGISTER_COMMAND(plugin, UnitTestHarness); - AL::maya::tests::utils::CommandGuiHelperTestCMD::makeGUI(); + AL_REGISTER_DEPEND_NODE(plugin, AL::maya::tests::utils::NodeHelperUnitTest); + AL_REGISTER_COMMAND(plugin, AL::maya::tests::utils::CommandGuiHelperTestCMD); + AL_REGISTER_COMMAND(plugin, UnitTestHarness); + AL::maya::tests::utils::CommandGuiHelperTestCMD::makeGUI(); - AL_REGISTER_COMMAND(plugin, AL::maya::utils::CommandGuiListGen); - CHECK_MSTATUS(AL::maya::utils::MenuBuilder::generatePluginUI(plugin, "mayaplugintest")); - return status; + AL_REGISTER_COMMAND(plugin, AL::maya::utils::CommandGuiListGen); + CHECK_MSTATUS(AL::maya::utils::MenuBuilder::generatePluginUI(plugin, "mayaplugintest")); + return status; } MStatus uninitializePlugin(MObject obj) { - MFnPlugin plugin(obj); - AL_UNREGISTER_NODE(plugin, AL::maya::tests::utils::NodeHelperUnitTest); - AL_UNREGISTER_COMMAND(plugin, AL::maya::tests::utils::CommandGuiHelperTestCMD); - AL_UNREGISTER_COMMAND(plugin, UnitTestHarness); + MFnPlugin plugin(obj); + AL_UNREGISTER_NODE(plugin, AL::maya::tests::utils::NodeHelperUnitTest); + AL_UNREGISTER_COMMAND(plugin, AL::maya::tests::utils::CommandGuiHelperTestCMD); + AL_UNREGISTER_COMMAND(plugin, UnitTestHarness); - MStatus status; - AL_UNREGISTER_COMMAND(plugin, AL::maya::utils::CommandGuiListGen); - return status; + MStatus status; + AL_UNREGISTER_COMMAND(plugin, AL::maya::utils::CommandGuiListGen); + return status; } - diff --git a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_maya_MenuBuilder.cpp b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_maya_MenuBuilder.cpp index b46c116c5d..b8aeaae16e 100644 --- a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_maya_MenuBuilder.cpp +++ b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_maya_MenuBuilder.cpp @@ -15,6 +15,7 @@ // //#include "test_usdmaya.h" #include "AL/maya/utils/MenuBuilder.h" + #include //---------------------------------------------------------------------------------------------------------------------- @@ -22,54 +23,21 @@ //---------------------------------------------------------------------------------------------------------------------- TEST(maya_MenuBuilder, simplePath) { - AL::maya::utils::MenuBuilder::clearRootMenus(); - EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI", "sphere", "sphereOB")); - EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu0 = *AL::maya::utils::MenuBuilder::rootMenus().begin(); - EXPECT_EQ(std::string("FOO"), menu0.name()); - EXPECT_EQ(size_t(1), menu0.childMenus().size()); - EXPECT_EQ(size_t(0), menu0.menuItems().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); - EXPECT_EQ(std::string("BAR"), menu1.name()); - EXPECT_EQ(size_t(1), menu1.childMenus().size()); - EXPECT_EQ(size_t(0), menu1.menuItems().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu2 = *menu1.childMenus().begin(); - EXPECT_EQ(std::string("MOO"), menu2.name()); - EXPECT_EQ(size_t(0), menu2.childMenus().size()); - EXPECT_EQ(size_t(1), menu2.menuItems().size()); - - const AL::maya::utils::MenuBuilder::MenuItem& item = menu2.menuItems()[0]; - EXPECT_EQ(std::string("HI"), item.label); - EXPECT_EQ(std::string("sphere"), item.command); - EXPECT_EQ(std::string("sphereOB"), item.optionBox); - EXPECT_FALSE(item.checkBox); - EXPECT_FALSE(item.checkBoxValue); - - AL::maya::utils::MenuBuilder::clearRootMenus(); -} + AL::maya::utils::MenuBuilder::clearRootMenus(); + EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI", "sphere", "sphereOB")); + EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu0 + = *AL::maya::utils::MenuBuilder::rootMenus().begin(); + EXPECT_EQ(std::string("FOO"), menu0.name()); + EXPECT_EQ(size_t(1), menu0.childMenus().size()); + EXPECT_EQ(size_t(0), menu0.menuItems().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); + EXPECT_EQ(std::string("BAR"), menu1.name()); + EXPECT_EQ(size_t(1), menu1.childMenus().size()); + EXPECT_EQ(size_t(0), menu1.menuItems().size()); -// Make sure that when we add menu item paths, the entries get added into the correct menu paths. -TEST(maya_MenuBuilder, sharedPath) -{ - AL::maya::utils::MenuBuilder::clearRootMenus(); - EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI", "sphere", "sphereOB")); - EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/OINK/HI", "cube", "cubeOB")); - EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu0 = *AL::maya::utils::MenuBuilder::rootMenus().begin(); - EXPECT_EQ(std::string("FOO"), menu0.name()); - EXPECT_EQ(size_t(1), menu0.childMenus().size()); - EXPECT_EQ(size_t(0), menu0.menuItems().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); - EXPECT_EQ(std::string("BAR"), menu1.name()); - EXPECT_EQ(size_t(2), menu1.childMenus().size()); - EXPECT_EQ(size_t(0), menu1.menuItems().size()); - - { const AL::maya::utils::MenuBuilder::Menu& menu2 = *menu1.childMenus().begin(); EXPECT_EQ(std::string("MOO"), menu2.name()); EXPECT_EQ(size_t(0), menu2.childMenus().size()); @@ -81,64 +49,101 @@ TEST(maya_MenuBuilder, sharedPath) EXPECT_EQ(std::string("sphereOB"), item.optionBox); EXPECT_FALSE(item.checkBox); EXPECT_FALSE(item.checkBoxValue); - } - { - auto it = menu1.childMenus().begin(); - ++it; - const AL::maya::utils::MenuBuilder::Menu& menu2 = *it; - EXPECT_EQ(std::string("OINK"), menu2.name()); - EXPECT_EQ(size_t(0), menu2.childMenus().size()); - EXPECT_EQ(size_t(1), menu2.menuItems().size()); + AL::maya::utils::MenuBuilder::clearRootMenus(); +} - const AL::maya::utils::MenuBuilder::MenuItem& item = menu2.menuItems()[0]; - EXPECT_EQ(std::string("HI"), item.label); - EXPECT_EQ(std::string("cube"), item.command); - EXPECT_EQ(std::string("cubeOB"), item.optionBox); - EXPECT_FALSE(item.checkBox); - EXPECT_FALSE(item.checkBoxValue); - } - AL::maya::utils::MenuBuilder::clearRootMenus(); +// Make sure that when we add menu item paths, the entries get added into the correct menu paths. +TEST(maya_MenuBuilder, sharedPath) +{ + AL::maya::utils::MenuBuilder::clearRootMenus(); + EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI", "sphere", "sphereOB")); + EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/OINK/HI", "cube", "cubeOB")); + EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu0 + = *AL::maya::utils::MenuBuilder::rootMenus().begin(); + EXPECT_EQ(std::string("FOO"), menu0.name()); + EXPECT_EQ(size_t(1), menu0.childMenus().size()); + EXPECT_EQ(size_t(0), menu0.menuItems().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); + EXPECT_EQ(std::string("BAR"), menu1.name()); + EXPECT_EQ(size_t(2), menu1.childMenus().size()); + EXPECT_EQ(size_t(0), menu1.menuItems().size()); + + { + const AL::maya::utils::MenuBuilder::Menu& menu2 = *menu1.childMenus().begin(); + EXPECT_EQ(std::string("MOO"), menu2.name()); + EXPECT_EQ(size_t(0), menu2.childMenus().size()); + EXPECT_EQ(size_t(1), menu2.menuItems().size()); + + const AL::maya::utils::MenuBuilder::MenuItem& item = menu2.menuItems()[0]; + EXPECT_EQ(std::string("HI"), item.label); + EXPECT_EQ(std::string("sphere"), item.command); + EXPECT_EQ(std::string("sphereOB"), item.optionBox); + EXPECT_FALSE(item.checkBox); + EXPECT_FALSE(item.checkBoxValue); + } + + { + auto it = menu1.childMenus().begin(); + ++it; + const AL::maya::utils::MenuBuilder::Menu& menu2 = *it; + EXPECT_EQ(std::string("OINK"), menu2.name()); + EXPECT_EQ(size_t(0), menu2.childMenus().size()); + EXPECT_EQ(size_t(1), menu2.menuItems().size()); + + const AL::maya::utils::MenuBuilder::MenuItem& item = menu2.menuItems()[0]; + EXPECT_EQ(std::string("HI"), item.label); + EXPECT_EQ(std::string("cube"), item.command); + EXPECT_EQ(std::string("cubeOB"), item.optionBox); + EXPECT_FALSE(item.checkBox); + EXPECT_FALSE(item.checkBoxValue); + } + AL::maya::utils::MenuBuilder::clearRootMenus(); } -// Make sure that when we add menu item paths under the same menu path, the entries get added correctly +// Make sure that when we add menu item paths under the same menu path, the entries get added +// correctly TEST(maya_MenuBuilder, sharedPath2) { - AL::maya::utils::MenuBuilder::clearRootMenus(); - EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI", "sphere", "sphereOB")); - EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/BYE", "cube", "cubeOB")); - EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu0 = *AL::maya::utils::MenuBuilder::rootMenus().begin(); - EXPECT_EQ(std::string("FOO"), menu0.name()); - EXPECT_EQ(size_t(1), menu0.childMenus().size()); - EXPECT_EQ(size_t(0), menu0.menuItems().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); - EXPECT_EQ(std::string("BAR"), menu1.name()); - EXPECT_EQ(size_t(1), menu1.childMenus().size()); - EXPECT_EQ(size_t(0), menu1.menuItems().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu2 = *menu1.childMenus().begin(); - EXPECT_EQ(std::string("MOO"), menu2.name()); - EXPECT_EQ(size_t(0), menu2.childMenus().size()); - EXPECT_EQ(size_t(2), menu2.menuItems().size()); - - const AL::maya::utils::MenuBuilder::MenuItem& item1 = menu2.menuItems()[0]; - EXPECT_EQ(std::string("HI"), item1.label); - EXPECT_EQ(std::string("sphere"), item1.command); - EXPECT_EQ(std::string("sphereOB"), item1.optionBox); - EXPECT_FALSE(item1.checkBox); - EXPECT_FALSE(item1.checkBoxValue); - - const AL::maya::utils::MenuBuilder::MenuItem& item2 = menu2.menuItems()[1]; - EXPECT_EQ(std::string("BYE"), item2.label); - EXPECT_EQ(std::string("cube"), item2.command); - EXPECT_EQ(std::string("cubeOB"), item2.optionBox); - EXPECT_FALSE(item2.checkBox); - EXPECT_FALSE(item2.checkBoxValue); - - AL::maya::utils::MenuBuilder::clearRootMenus(); + AL::maya::utils::MenuBuilder::clearRootMenus(); + EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI", "sphere", "sphereOB")); + EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/BYE", "cube", "cubeOB")); + EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu0 + = *AL::maya::utils::MenuBuilder::rootMenus().begin(); + EXPECT_EQ(std::string("FOO"), menu0.name()); + EXPECT_EQ(size_t(1), menu0.childMenus().size()); + EXPECT_EQ(size_t(0), menu0.menuItems().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); + EXPECT_EQ(std::string("BAR"), menu1.name()); + EXPECT_EQ(size_t(1), menu1.childMenus().size()); + EXPECT_EQ(size_t(0), menu1.menuItems().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu2 = *menu1.childMenus().begin(); + EXPECT_EQ(std::string("MOO"), menu2.name()); + EXPECT_EQ(size_t(0), menu2.childMenus().size()); + EXPECT_EQ(size_t(2), menu2.menuItems().size()); + + const AL::maya::utils::MenuBuilder::MenuItem& item1 = menu2.menuItems()[0]; + EXPECT_EQ(std::string("HI"), item1.label); + EXPECT_EQ(std::string("sphere"), item1.command); + EXPECT_EQ(std::string("sphereOB"), item1.optionBox); + EXPECT_FALSE(item1.checkBox); + EXPECT_FALSE(item1.checkBoxValue); + + const AL::maya::utils::MenuBuilder::MenuItem& item2 = menu2.menuItems()[1]; + EXPECT_EQ(std::string("BYE"), item2.label); + EXPECT_EQ(std::string("cube"), item2.command); + EXPECT_EQ(std::string("cubeOB"), item2.optionBox); + EXPECT_FALSE(item2.checkBox); + EXPECT_FALSE(item2.checkBoxValue); + + AL::maya::utils::MenuBuilder::clearRootMenus(); } // make sure we can't add a duplicate entry. @@ -147,112 +152,123 @@ TEST(maya_MenuBuilder, sharedPath2) // is probably going to confuse petest_alUsdMayaople TEST(maya_MenuBuilder, duplicatePath) { - AL::maya::utils::MenuBuilder::clearRootMenus(); - EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI", "sphere", "sphereOB")); - EXPECT_FALSE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI", "cube", "cubeOB")); - EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu0 = *AL::maya::utils::MenuBuilder::rootMenus().begin(); - EXPECT_EQ(std::string("FOO"), menu0.name()); - EXPECT_EQ(size_t(1), menu0.childMenus().size()); - EXPECT_EQ(size_t(0), menu0.menuItems().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); - EXPECT_EQ(std::string("BAR"), menu1.name()); - EXPECT_EQ(size_t(1), menu1.childMenus().size()); - EXPECT_EQ(size_t(0), menu1.menuItems().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu2 = *menu1.childMenus().begin(); - EXPECT_EQ(std::string("MOO"), menu2.name()); - EXPECT_EQ(size_t(0), menu2.childMenus().size()); - EXPECT_EQ(size_t(1), menu2.menuItems().size()); - - const AL::maya::utils::MenuBuilder::MenuItem& item = menu2.menuItems()[0]; - EXPECT_EQ(std::string("HI"), item.label); - EXPECT_EQ(std::string("sphere"), item.command); - EXPECT_EQ(std::string("sphereOB"), item.optionBox); - EXPECT_FALSE(item.checkBox); - EXPECT_FALSE(item.checkBoxValue); - - AL::maya::utils::MenuBuilder::clearRootMenus(); + AL::maya::utils::MenuBuilder::clearRootMenus(); + EXPECT_TRUE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI", "sphere", "sphereOB")); + EXPECT_FALSE(AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI", "cube", "cubeOB")); + EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu0 + = *AL::maya::utils::MenuBuilder::rootMenus().begin(); + EXPECT_EQ(std::string("FOO"), menu0.name()); + EXPECT_EQ(size_t(1), menu0.childMenus().size()); + EXPECT_EQ(size_t(0), menu0.menuItems().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); + EXPECT_EQ(std::string("BAR"), menu1.name()); + EXPECT_EQ(size_t(1), menu1.childMenus().size()); + EXPECT_EQ(size_t(0), menu1.menuItems().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu2 = *menu1.childMenus().begin(); + EXPECT_EQ(std::string("MOO"), menu2.name()); + EXPECT_EQ(size_t(0), menu2.childMenus().size()); + EXPECT_EQ(size_t(1), menu2.menuItems().size()); + + const AL::maya::utils::MenuBuilder::MenuItem& item = menu2.menuItems()[0]; + EXPECT_EQ(std::string("HI"), item.label); + EXPECT_EQ(std::string("sphere"), item.command); + EXPECT_EQ(std::string("sphereOB"), item.optionBox); + EXPECT_FALSE(item.checkBox); + EXPECT_FALSE(item.checkBoxValue); + + AL::maya::utils::MenuBuilder::clearRootMenus(); } // make sure the checkbox values are correctly assigned TEST(maya_MenuBuilder, simpleCheckbox) { - AL::maya::utils::MenuBuilder::clearRootMenus(); - EXPECT_TRUE(0 != AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI1", "Checky", true, false)); - EXPECT_TRUE(0 != AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI2", "McCheckFace", true, true)); - EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu0 = *AL::maya::utils::MenuBuilder::rootMenus().begin(); - EXPECT_EQ(std::string("FOO"), menu0.name()); - EXPECT_EQ(size_t(1), menu0.childMenus().size()); - EXPECT_EQ(size_t(0), menu0.menuItems().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); - EXPECT_EQ(std::string("BAR"), menu1.name()); - EXPECT_EQ(size_t(1), menu1.childMenus().size()); - EXPECT_EQ(size_t(0), menu1.menuItems().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu2 = *menu1.childMenus().begin(); - EXPECT_EQ(std::string("MOO"), menu2.name()); - EXPECT_EQ(size_t(0), menu2.childMenus().size()); - EXPECT_EQ(size_t(2), menu2.menuItems().size()); - - const AL::maya::utils::MenuBuilder::MenuItem& item1 = menu2.menuItems()[0]; - EXPECT_EQ(std::string("HI1"), item1.label); - EXPECT_EQ(std::string("Checky"), item1.command); - EXPECT_EQ(std::string(""), item1.optionBox); - EXPECT_TRUE(item1.checkBox); - EXPECT_FALSE(item1.checkBoxValue); - - const AL::maya::utils::MenuBuilder::MenuItem& item2 = menu2.menuItems()[1]; - EXPECT_EQ(std::string("HI2"), item2.label); - EXPECT_EQ(std::string("McCheckFace"), item2.command); - EXPECT_EQ(std::string(""), item2.optionBox); - EXPECT_TRUE(item2.checkBox); - EXPECT_TRUE(item2.checkBoxValue); - - AL::maya::utils::MenuBuilder::clearRootMenus(); + AL::maya::utils::MenuBuilder::clearRootMenus(); + EXPECT_TRUE( + 0 != AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI1", "Checky", true, false)); + EXPECT_TRUE( + 0 != AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI2", "McCheckFace", true, true)); + EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu0 + = *AL::maya::utils::MenuBuilder::rootMenus().begin(); + EXPECT_EQ(std::string("FOO"), menu0.name()); + EXPECT_EQ(size_t(1), menu0.childMenus().size()); + EXPECT_EQ(size_t(0), menu0.menuItems().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); + EXPECT_EQ(std::string("BAR"), menu1.name()); + EXPECT_EQ(size_t(1), menu1.childMenus().size()); + EXPECT_EQ(size_t(0), menu1.menuItems().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu2 = *menu1.childMenus().begin(); + EXPECT_EQ(std::string("MOO"), menu2.name()); + EXPECT_EQ(size_t(0), menu2.childMenus().size()); + EXPECT_EQ(size_t(2), menu2.menuItems().size()); + + const AL::maya::utils::MenuBuilder::MenuItem& item1 = menu2.menuItems()[0]; + EXPECT_EQ(std::string("HI1"), item1.label); + EXPECT_EQ(std::string("Checky"), item1.command); + EXPECT_EQ(std::string(""), item1.optionBox); + EXPECT_TRUE(item1.checkBox); + EXPECT_FALSE(item1.checkBoxValue); + + const AL::maya::utils::MenuBuilder::MenuItem& item2 = menu2.menuItems()[1]; + EXPECT_EQ(std::string("HI2"), item2.label); + EXPECT_EQ(std::string("McCheckFace"), item2.command); + EXPECT_EQ(std::string(""), item2.optionBox); + EXPECT_TRUE(item2.checkBox); + EXPECT_TRUE(item2.checkBoxValue); + + AL::maya::utils::MenuBuilder::clearRootMenus(); } // Test radio button values are correctly assigned TEST(maya_MenuBuilder, simpleRadioButton) { - AL::maya::utils::MenuBuilder::clearRootMenus(); - EXPECT_TRUE(0 != AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI1", "Radio", false, false, true, false)); - EXPECT_TRUE(0 != AL::maya::utils::MenuBuilder::addEntry("FOO/BAR/MOO/HI2", "McRadioFace", false, false, true, true)); - EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu0 = *AL::maya::utils::MenuBuilder::rootMenus().begin(); - EXPECT_EQ(std::string("FOO"), menu0.name()); - EXPECT_EQ(size_t(1), menu0.childMenus().size()); - EXPECT_EQ(size_t(0), menu0.menuItems().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); - EXPECT_EQ(std::string("BAR"), menu1.name()); - EXPECT_EQ(size_t(1), menu1.childMenus().size()); - EXPECT_EQ(size_t(0), menu1.menuItems().size()); - - const AL::maya::utils::MenuBuilder::Menu& menu2 = *menu1.childMenus().begin(); - EXPECT_EQ(std::string("MOO"), menu2.name()); - EXPECT_EQ(size_t(0), menu2.childMenus().size()); - EXPECT_EQ(size_t(2), menu2.menuItems().size()); - - const AL::maya::utils::MenuBuilder::MenuItem& item1 = menu2.menuItems()[0]; - EXPECT_EQ(std::string("HI1"), item1.label); - EXPECT_EQ(std::string("Radio"), item1.command); - EXPECT_EQ(std::string(""), item1.optionBox); - EXPECT_TRUE(item1.radioButton); - EXPECT_FALSE(item1.radioButtonValue); - - const AL::maya::utils::MenuBuilder::MenuItem& item2 = menu2.menuItems()[1]; - EXPECT_EQ(std::string("HI2"), item2.label); - EXPECT_EQ(std::string("McRadioFace"), item2.command); - EXPECT_EQ(std::string(""), item2.optionBox); - EXPECT_TRUE(item2.radioButton); - EXPECT_TRUE(item2.radioButtonValue); - - AL::maya::utils::MenuBuilder::clearRootMenus(); + AL::maya::utils::MenuBuilder::clearRootMenus(); + EXPECT_TRUE( + 0 + != AL::maya::utils::MenuBuilder::addEntry( + "FOO/BAR/MOO/HI1", "Radio", false, false, true, false)); + EXPECT_TRUE( + 0 + != AL::maya::utils::MenuBuilder::addEntry( + "FOO/BAR/MOO/HI2", "McRadioFace", false, false, true, true)); + EXPECT_EQ(size_t(1), AL::maya::utils::MenuBuilder::rootMenus().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu0 + = *AL::maya::utils::MenuBuilder::rootMenus().begin(); + EXPECT_EQ(std::string("FOO"), menu0.name()); + EXPECT_EQ(size_t(1), menu0.childMenus().size()); + EXPECT_EQ(size_t(0), menu0.menuItems().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu1 = *menu0.childMenus().begin(); + EXPECT_EQ(std::string("BAR"), menu1.name()); + EXPECT_EQ(size_t(1), menu1.childMenus().size()); + EXPECT_EQ(size_t(0), menu1.menuItems().size()); + + const AL::maya::utils::MenuBuilder::Menu& menu2 = *menu1.childMenus().begin(); + EXPECT_EQ(std::string("MOO"), menu2.name()); + EXPECT_EQ(size_t(0), menu2.childMenus().size()); + EXPECT_EQ(size_t(2), menu2.menuItems().size()); + + const AL::maya::utils::MenuBuilder::MenuItem& item1 = menu2.menuItems()[0]; + EXPECT_EQ(std::string("HI1"), item1.label); + EXPECT_EQ(std::string("Radio"), item1.command); + EXPECT_EQ(std::string(""), item1.optionBox); + EXPECT_TRUE(item1.radioButton); + EXPECT_FALSE(item1.radioButtonValue); + + const AL::maya::utils::MenuBuilder::MenuItem& item2 = menu2.menuItems()[1]; + EXPECT_EQ(std::string("HI2"), item2.label); + EXPECT_EQ(std::string("McRadioFace"), item2.command); + EXPECT_EQ(std::string(""), item2.optionBox); + EXPECT_TRUE(item2.radioButton); + EXPECT_TRUE(item2.radioButtonValue); + + AL::maya::utils::MenuBuilder::clearRootMenus(); } \ No newline at end of file diff --git a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_maya_NodeHelper.cpp b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_maya_NodeHelper.cpp index 9043dcc3e0..1b3b577a2b 100644 --- a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_maya_NodeHelper.cpp +++ b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_maya_NodeHelper.cpp @@ -27,11 +27,11 @@ #include #include #include +#include #include #include #include #include -#include #include @@ -41,678 +41,770 @@ namespace { MObject m_node = MObject::kNullObj; -void setUp() +void setUp() { - MFnDependencyNode fn; - m_node = fn.create("transform"); + MFnDependencyNode fn; + m_node = fn.create("transform"); } void tearDown() { - MDGModifier mod; - mod.deleteNode(m_node); - mod.doIt(); + MDGModifier mod; + mod.deleteNode(m_node); + mod.doIt(); } MPlug findPlug(const char* name) { - MStatus status; - MFnDependencyNode fn(m_node, &status); - EXPECT_EQ(MStatus(MS::kSuccess), status); - MPlug plug = fn.findPlug(name, true, &status); - EXPECT_EQ(MStatus(MS::kSuccess), status); - return plug; + MStatus status; + MFnDependencyNode fn(m_node, &status); + EXPECT_EQ(MStatus(MS::kSuccess), status); + MPlug plug = fn.findPlug(name, true, &status); + EXPECT_EQ(MStatus(MS::kSuccess), status); + return plug; } /// \brief A set of bit flags you can apply to an attribute enum AttributeFlags { - kCached = AL::maya::utils::NodeHelper::kCached, - kReadable = AL::maya::utils::NodeHelper::kReadable, - kWritable = AL::maya::utils::NodeHelper::kWritable, - kStorable = AL::maya::utils::NodeHelper::kStorable, - kAffectsAppearance = AL::maya::utils::NodeHelper::kAffectsAppearance, - kKeyable = AL::maya::utils::NodeHelper::kKeyable, - kConnectable = AL::maya::utils::NodeHelper::kConnectable, - kArray = AL::maya::utils::NodeHelper::kArray, - kColour = AL::maya::utils::NodeHelper::kColour, - kHidden = AL::maya::utils::NodeHelper::kHidden, - kInternal = AL::maya::utils::NodeHelper::kInternal, - kAffectsWorldSpace = AL::maya::utils::NodeHelper::kAffectsWorldSpace, - kUsesArrayDataBuilder = AL::maya::utils::NodeHelper::kUsesArrayDataBuilder, - kDontAddToNode = AL::maya::utils::NodeHelper::kDontAddToNode, - kDynamic = AL::maya::utils::NodeHelper::kDynamic + kCached = AL::maya::utils::NodeHelper::kCached, + kReadable = AL::maya::utils::NodeHelper::kReadable, + kWritable = AL::maya::utils::NodeHelper::kWritable, + kStorable = AL::maya::utils::NodeHelper::kStorable, + kAffectsAppearance = AL::maya::utils::NodeHelper::kAffectsAppearance, + kKeyable = AL::maya::utils::NodeHelper::kKeyable, + kConnectable = AL::maya::utils::NodeHelper::kConnectable, + kArray = AL::maya::utils::NodeHelper::kArray, + kColour = AL::maya::utils::NodeHelper::kColour, + kHidden = AL::maya::utils::NodeHelper::kHidden, + kInternal = AL::maya::utils::NodeHelper::kInternal, + kAffectsWorldSpace = AL::maya::utils::NodeHelper::kAffectsWorldSpace, + kUsesArrayDataBuilder = AL::maya::utils::NodeHelper::kUsesArrayDataBuilder, + kDontAddToNode = AL::maya::utils::NodeHelper::kDontAddToNode, + kDynamic = AL::maya::utils::NodeHelper::kDynamic }; void checkAttributeFlags(MPlug attr, const uint32_t flags) { - MFnAttribute fn(attr.attribute()); - EXPECT_EQ((flags & kCached) != 0, fn.isCached()); - EXPECT_EQ((flags & kReadable) != 0, fn.isReadable()); - EXPECT_EQ((flags & kStorable) != 0, fn.isStorable()); - EXPECT_EQ((flags & kWritable) != 0, fn.isWritable()); - EXPECT_EQ((flags & kAffectsAppearance) != 0, fn.affectsAppearance()); - EXPECT_EQ((flags & kKeyable) != 0, fn.isKeyable()); - EXPECT_EQ((flags & kConnectable) != 0, fn.isConnectable()); - EXPECT_EQ((flags & kArray) != 0, fn.isArray()); - EXPECT_EQ((flags & kColour) != 0, fn.isUsedAsColor()); - EXPECT_EQ((flags & kHidden) != 0, fn.isHidden()); - EXPECT_EQ((flags & kInternal) != 0, fn.internal()); - EXPECT_EQ((flags & kAffectsWorldSpace) != 0, fn.isAffectsWorldSpace()); - EXPECT_EQ((flags & kUsesArrayDataBuilder) != 0, fn.usesArrayDataBuilder()); -} - + MFnAttribute fn(attr.attribute()); + EXPECT_EQ((flags & kCached) != 0, fn.isCached()); + EXPECT_EQ((flags & kReadable) != 0, fn.isReadable()); + EXPECT_EQ((flags & kStorable) != 0, fn.isStorable()); + EXPECT_EQ((flags & kWritable) != 0, fn.isWritable()); + EXPECT_EQ((flags & kAffectsAppearance) != 0, fn.affectsAppearance()); + EXPECT_EQ((flags & kKeyable) != 0, fn.isKeyable()); + EXPECT_EQ((flags & kConnectable) != 0, fn.isConnectable()); + EXPECT_EQ((flags & kArray) != 0, fn.isArray()); + EXPECT_EQ((flags & kColour) != 0, fn.isUsedAsColor()); + EXPECT_EQ((flags & kHidden) != 0, fn.isHidden()); + EXPECT_EQ((flags & kInternal) != 0, fn.internal()); + EXPECT_EQ((flags & kAffectsWorldSpace) != 0, fn.isAffectsWorldSpace()); + EXPECT_EQ((flags & kUsesArrayDataBuilder) != 0, fn.usesArrayDataBuilder()); } +} // namespace TEST(maya_NodeHelper, addStringAttr) { - setUp(); - const char* const longName = "longStringName"; - const char* const shortName = "lsn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addStringAttr(m_node, longName, shortName, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - tearDown(); + setUp(); + const char* const longName = "longStringName"; + const char* const shortName = "lsn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addStringAttr(m_node, longName, shortName, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + tearDown(); } TEST(maya_NodeHelper, addFilePathAttr) { - setUp(); - const char* const longName = "longFileName"; - const char* const shortName = "lfn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addFilePathAttr(m_node, longName, shortName, flags, AL::maya::utils::NodeHelper::kSave, "All files (*.*) (*.*)")); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - tearDown(); + setUp(); + const char* const longName = "longFileName"; + const char* const shortName = "lfn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addFilePathAttr( + m_node, + longName, + shortName, + flags, + AL::maya::utils::NodeHelper::kSave, + "All files (*.*) (*.*)")); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + tearDown(); } TEST(maya_NodeHelper, addInt8Attr) { - setUp(); - const char* const longName = "longInt8Name"; - const char* const shortName = "li8n"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const int8_t defaultValue = 19; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt8Attr(m_node, longName, shortName, defaultValue, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_EQ(char(defaultValue), findPlug(longName).asChar()); - - // This test will always fail, so don't run it. It turns out that if you create a char attribute type in Maya, - // it will always set a min value of 0, and a max value of 255 (which is pretty dumb given that char is a signed type) - if(0) - { - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_FALSE(fn.hasMin()); - EXPECT_FALSE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - double minMax[2]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - EXPECT_EQ(4.0, minMax[0]); - EXPECT_EQ(40.0, minMax[1]); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40, 5, 39); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_TRUE(fn.hasSoftMax()); - EXPECT_TRUE(fn.hasSoftMin()); - double minMax[4]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - fn.getSoftMin(minMax[2]); - fn.getSoftMax(minMax[3]); - EXPECT_NEAR(4.0, minMax[0], 1e-5f); - EXPECT_NEAR(40.0, minMax[1], 1e-5f); - EXPECT_NEAR(5, minMax[2], 1e-5f); - EXPECT_NEAR(39.0, minMax[3], 1e-5f); - } - tearDown(); + setUp(); + const char* const longName = "longInt8Name"; + const char* const shortName = "li8n"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const int8_t defaultValue = 19; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt8Attr(m_node, longName, shortName, defaultValue, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_EQ(char(defaultValue), findPlug(longName).asChar()); + + // This test will always fail, so don't run it. It turns out that if you create a char attribute + // type in Maya, it will always set a min value of 0, and a max value of 255 (which is pretty + // dumb given that char is a signed type) + if (0) { + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_FALSE(fn.hasMin()); + EXPECT_FALSE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + } + { + AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + double minMax[2]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + EXPECT_EQ(4.0, minMax[0]); + EXPECT_EQ(40.0, minMax[1]); + } + { + AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40, 5, 39); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_TRUE(fn.hasSoftMax()); + EXPECT_TRUE(fn.hasSoftMin()); + double minMax[4]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + fn.getSoftMin(minMax[2]); + fn.getSoftMax(minMax[3]); + EXPECT_NEAR(4.0, minMax[0], 1e-5f); + EXPECT_NEAR(40.0, minMax[1], 1e-5f); + EXPECT_NEAR(5, minMax[2], 1e-5f); + EXPECT_NEAR(39.0, minMax[3], 1e-5f); + } + tearDown(); } TEST(maya_NodeHelper, addInt16Attr) { - setUp(); - const char* const longName = "longInt16Name"; - const char* const shortName = "li16n"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const int defaultValue = 67; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt16Attr(m_node, longName, shortName, defaultValue, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_EQ(defaultValue, findPlug(longName).asInt()); - { - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_FALSE(fn.hasMin()); - EXPECT_FALSE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - double minMax[2]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - EXPECT_EQ(4.0, minMax[0]); - EXPECT_EQ(40.0, minMax[1]); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40, 5, 39); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_TRUE(fn.hasSoftMax()); - EXPECT_TRUE(fn.hasSoftMin()); - double minMax[4]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - fn.getSoftMin(minMax[2]); - fn.getSoftMax(minMax[3]); - EXPECT_NEAR(4.0, minMax[0], 1e-5f); - EXPECT_NEAR(40.0, minMax[1], 1e-5f); - EXPECT_NEAR(5, minMax[2], 1e-5f); - EXPECT_NEAR(39.0, minMax[3], 1e-5f); - } - tearDown(); + setUp(); + const char* const longName = "longInt16Name"; + const char* const shortName = "li16n"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const int defaultValue = 67; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt16Attr( + m_node, longName, shortName, defaultValue, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_EQ(defaultValue, findPlug(longName).asInt()); + { + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_FALSE(fn.hasMin()); + EXPECT_FALSE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + } + { + AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + double minMax[2]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + EXPECT_EQ(4.0, minMax[0]); + EXPECT_EQ(40.0, minMax[1]); + } + { + AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40, 5, 39); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_TRUE(fn.hasSoftMax()); + EXPECT_TRUE(fn.hasSoftMin()); + double minMax[4]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + fn.getSoftMin(minMax[2]); + fn.getSoftMax(minMax[3]); + EXPECT_NEAR(4.0, minMax[0], 1e-5f); + EXPECT_NEAR(40.0, minMax[1], 1e-5f); + EXPECT_NEAR(5, minMax[2], 1e-5f); + EXPECT_NEAR(39.0, minMax[3], 1e-5f); + } + tearDown(); } - TEST(maya_NodeHelper, addInt32Attr) { - setUp(); - const char* const longName = "longInt32Name"; - const char* const shortName = "li32n"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const int defaultValue = 23; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, defaultValue, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_EQ(defaultValue, findPlug(longName).asInt()); - { - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_FALSE(fn.hasMin()); - EXPECT_FALSE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - double minMax[2]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - EXPECT_EQ(4.0, minMax[0]); - EXPECT_EQ(40.0, minMax[1]); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40, 5, 39); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_TRUE(fn.hasSoftMax()); - EXPECT_TRUE(fn.hasSoftMin()); - double minMax[4]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - fn.getSoftMin(minMax[2]); - fn.getSoftMax(minMax[3]); - EXPECT_NEAR(4.0, minMax[0], 1e-5f); - EXPECT_NEAR(40.0, minMax[1], 1e-5f); - EXPECT_NEAR(5, minMax[2], 1e-5f); - EXPECT_NEAR(39.0, minMax[3], 1e-5f); - } - tearDown(); + setUp(); + const char* const longName = "longInt32Name"; + const char* const shortName = "li32n"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const int defaultValue = 23; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt32Attr( + m_node, longName, shortName, defaultValue, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_EQ(defaultValue, findPlug(longName).asInt()); + { + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_FALSE(fn.hasMin()); + EXPECT_FALSE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + } + { + AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + double minMax[2]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + EXPECT_EQ(4.0, minMax[0]); + EXPECT_EQ(40.0, minMax[1]); + } + { + AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40, 5, 39); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_TRUE(fn.hasSoftMax()); + EXPECT_TRUE(fn.hasSoftMin()); + double minMax[4]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + fn.getSoftMin(minMax[2]); + fn.getSoftMax(minMax[3]); + EXPECT_NEAR(4.0, minMax[0], 1e-5f); + EXPECT_NEAR(40.0, minMax[1], 1e-5f); + EXPECT_NEAR(5, minMax[2], 1e-5f); + EXPECT_NEAR(39.0, minMax[3], 1e-5f); + } + tearDown(); } - TEST(maya_NodeHelper, addInt64Attr) { - setUp(); - const char* const longName = "longInt64Name"; - const char* const shortName = "li64n"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const int64_t defaultValue = 23; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt64Attr(m_node, longName, shortName, defaultValue, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_EQ(defaultValue, findPlug(longName).asInt64()); - { - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_FALSE(fn.hasMin()); - EXPECT_FALSE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - double minMax[2]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - EXPECT_EQ(4.0, minMax[0]); - EXPECT_EQ(40.0, minMax[1]); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40, 5, 39); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_TRUE(fn.hasSoftMax()); - EXPECT_TRUE(fn.hasSoftMin()); - double minMax[4]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - fn.getSoftMin(minMax[2]); - fn.getSoftMax(minMax[3]); - EXPECT_NEAR(4.0, minMax[0], 1e-5f); - EXPECT_NEAR(40.0, minMax[1], 1e-5f); - EXPECT_NEAR(5, minMax[2], 1e-5f); - EXPECT_NEAR(39.0, minMax[3], 1e-5f); - } - tearDown(); + setUp(); + const char* const longName = "longInt64Name"; + const char* const shortName = "li64n"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const int64_t defaultValue = 23; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt64Attr( + m_node, longName, shortName, defaultValue, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_EQ(defaultValue, findPlug(longName).asInt64()); + { + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_FALSE(fn.hasMin()); + EXPECT_FALSE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + } + { + AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + double minMax[2]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + EXPECT_EQ(4.0, minMax[0]); + EXPECT_EQ(40.0, minMax[1]); + } + { + AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4, 40, 5, 39); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_TRUE(fn.hasSoftMax()); + EXPECT_TRUE(fn.hasSoftMin()); + double minMax[4]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + fn.getSoftMin(minMax[2]); + fn.getSoftMax(minMax[3]); + EXPECT_NEAR(4.0, minMax[0], 1e-5f); + EXPECT_NEAR(40.0, minMax[1], 1e-5f); + EXPECT_NEAR(5, minMax[2], 1e-5f); + EXPECT_NEAR(39.0, minMax[3], 1e-5f); + } + tearDown(); } - TEST(maya_NodeHelper, addFloatAttr) { - setUp(); - const char* const longName = "longFloatName"; - const char* const shortName = "lFn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const float defaultValue = 23.1f; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addFloatAttr(m_node, longName, shortName, defaultValue, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_NEAR(defaultValue, findPlug(longName).asFloat(), 1e-5f); - { - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_FALSE(fn.hasMin()); - EXPECT_FALSE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4.0f, 40.0f); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - double minMax[2]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - EXPECT_NEAR(4.0f, minMax[0], 1e-5f); - EXPECT_NEAR(40.0f, minMax[1], 1e-5f); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4.0f, 40.0f, 4.1f, 39.0f); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_TRUE(fn.hasSoftMax()); - EXPECT_TRUE(fn.hasSoftMin()); - double minMax[4]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - fn.getSoftMin(minMax[2]); - fn.getSoftMax(minMax[3]); - EXPECT_NEAR(4.0f, minMax[0], 1e-5f); - EXPECT_NEAR(40.0f, minMax[1], 1e-5f); - EXPECT_NEAR(4.1f, minMax[2], 1e-5f); - EXPECT_NEAR(39.0f, minMax[3], 1e-5f); - } - tearDown(); + setUp(); + const char* const longName = "longFloatName"; + const char* const shortName = "lFn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const float defaultValue = 23.1f; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addFloatAttr( + m_node, longName, shortName, defaultValue, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_NEAR(defaultValue, findPlug(longName).asFloat(), 1e-5f); + { + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_FALSE(fn.hasMin()); + EXPECT_FALSE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + } + { + AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4.0f, 40.0f); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + double minMax[2]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + EXPECT_NEAR(4.0f, minMax[0], 1e-5f); + EXPECT_NEAR(40.0f, minMax[1], 1e-5f); + } + { + AL::maya::utils::NodeHelper::setMinMax( + findPlug(longName).attribute(), 4.0f, 40.0f, 4.1f, 39.0f); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_TRUE(fn.hasSoftMax()); + EXPECT_TRUE(fn.hasSoftMin()); + double minMax[4]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + fn.getSoftMin(minMax[2]); + fn.getSoftMax(minMax[3]); + EXPECT_NEAR(4.0f, minMax[0], 1e-5f); + EXPECT_NEAR(40.0f, minMax[1], 1e-5f); + EXPECT_NEAR(4.1f, minMax[2], 1e-5f); + EXPECT_NEAR(39.0f, minMax[3], 1e-5f); + } + tearDown(); } TEST(maya_NodeHelper, addDoubleAttr) { - setUp(); - const char* const longName = "longDoubleName"; - const char* const shortName = "lDn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const double defaultValue = 23.2f; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addDoubleAttr(m_node, longName, shortName, defaultValue, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_NEAR(defaultValue, findPlug(longName).asDouble(), 1e-5f); - { - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_FALSE(fn.hasMin()); - EXPECT_FALSE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4.0f, 40.0f); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_FALSE(fn.hasSoftMax()); - EXPECT_FALSE(fn.hasSoftMin()); - double minMax[2]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - EXPECT_NEAR(4.0f, minMax[0], 1e-5f); - EXPECT_NEAR(40.0f, minMax[1], 1e-5f); - } - { - AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4.0f, 40.0f, 4.1f, 39.0f); - MFnNumericAttribute fn(findPlug(longName).attribute()); - EXPECT_TRUE(fn.hasMin()); - EXPECT_TRUE(fn.hasMax()); - EXPECT_TRUE(fn.hasSoftMax()); - EXPECT_TRUE(fn.hasSoftMin()); - double minMax[4]; - fn.getMin(minMax[0]); - fn.getMax(minMax[1]); - fn.getSoftMin(minMax[2]); - fn.getSoftMax(minMax[3]); - EXPECT_NEAR(4.0f, minMax[0], 1e-5f); - EXPECT_NEAR(40.0f, minMax[1], 1e-5f); - EXPECT_NEAR(4.1f, minMax[2], 1e-5f); - EXPECT_NEAR(39.0f, minMax[3], 1e-5f); - } - tearDown(); + setUp(); + const char* const longName = "longDoubleName"; + const char* const shortName = "lDn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const double defaultValue = 23.2f; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addDoubleAttr( + m_node, longName, shortName, defaultValue, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_NEAR(defaultValue, findPlug(longName).asDouble(), 1e-5f); + { + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_FALSE(fn.hasMin()); + EXPECT_FALSE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + } + { + AL::maya::utils::NodeHelper::setMinMax(findPlug(longName).attribute(), 4.0f, 40.0f); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_FALSE(fn.hasSoftMax()); + EXPECT_FALSE(fn.hasSoftMin()); + double minMax[2]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + EXPECT_NEAR(4.0f, minMax[0], 1e-5f); + EXPECT_NEAR(40.0f, minMax[1], 1e-5f); + } + { + AL::maya::utils::NodeHelper::setMinMax( + findPlug(longName).attribute(), 4.0f, 40.0f, 4.1f, 39.0f); + MFnNumericAttribute fn(findPlug(longName).attribute()); + EXPECT_TRUE(fn.hasMin()); + EXPECT_TRUE(fn.hasMax()); + EXPECT_TRUE(fn.hasSoftMax()); + EXPECT_TRUE(fn.hasSoftMin()); + double minMax[4]; + fn.getMin(minMax[0]); + fn.getMax(minMax[1]); + fn.getSoftMin(minMax[2]); + fn.getSoftMax(minMax[3]); + EXPECT_NEAR(4.0f, minMax[0], 1e-5f); + EXPECT_NEAR(40.0f, minMax[1], 1e-5f); + EXPECT_NEAR(4.1f, minMax[2], 1e-5f); + EXPECT_NEAR(39.0f, minMax[3], 1e-5f); + } + tearDown(); } TEST(maya_NodeHelper, addTimeAttr) { - setUp(); - const char* const longName = "longTimeName"; - const char* const shortName = "lTn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const MTime defaultValue = 23.3; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addTimeAttr(m_node, longName, shortName, defaultValue, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_NEAR(defaultValue.value(), findPlug(longName).asMTime().value(), 1e-5f); - tearDown(); + setUp(); + const char* const longName = "longTimeName"; + const char* const shortName = "lTn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const MTime defaultValue = 23.3; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addTimeAttr(m_node, longName, shortName, defaultValue, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_NEAR(defaultValue.value(), findPlug(longName).asMTime().value(), 1e-5f); + tearDown(); } TEST(maya_NodeHelper, addBoolAttr) { - setUp(); - const char* const longName = "longBoolName"; - const char* const shortName = "lBn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const bool defaultValue = true; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addBoolAttr(m_node, longName, shortName, defaultValue, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_EQ(defaultValue, findPlug(longName).asBool()); - tearDown(); + setUp(); + const char* const longName = "longBoolName"; + const char* const shortName = "lBn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const bool defaultValue = true; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addBoolAttr(m_node, longName, shortName, defaultValue, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_EQ(defaultValue, findPlug(longName).asBool()); + tearDown(); } TEST(maya_NodeHelper, addFloat3Attr) { - setUp(); - const char* const longName = "longFloat3Name"; - const char* const shortName = "lf3n"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const float defaultValueX = 31.1f; - const float defaultValueY = 31.2f; - const float defaultValueZ = 31.3f; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addFloat3Attr(m_node, longName, shortName, defaultValueX, defaultValueY, defaultValueZ, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asFloat(), 1e-5f); - EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asFloat(), 1e-5f); - EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asFloat(), 1e-5f); - tearDown(); + setUp(); + const char* const longName = "longFloat3Name"; + const char* const shortName = "lf3n"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const float defaultValueX = 31.1f; + const float defaultValueY = 31.2f; + const float defaultValueZ = 31.3f; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addFloat3Attr( + m_node, longName, shortName, defaultValueX, defaultValueY, defaultValueZ, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asFloat(), 1e-5f); + EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asFloat(), 1e-5f); + EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asFloat(), 1e-5f); + tearDown(); } TEST(maya_NodeHelper, addAngle3Attr) { - setUp(); - const char* const longName = "longAngle3Name"; - const char* const shortName = "la3n"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const float defaultValueX = 33.1f; - const float defaultValueY = 33.2f; - const float defaultValueZ = 33.3f; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addAngle3Attr(m_node, longName, shortName, defaultValueX, defaultValueY, defaultValueZ, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asFloat(), 1e-5f); - EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asFloat(), 1e-5f); - EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asFloat(), 1e-5f); - tearDown(); + setUp(); + const char* const longName = "longAngle3Name"; + const char* const shortName = "la3n"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const float defaultValueX = 33.1f; + const float defaultValueY = 33.2f; + const float defaultValueZ = 33.3f; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addAngle3Attr( + m_node, longName, shortName, defaultValueX, defaultValueY, defaultValueZ, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asFloat(), 1e-5f); + EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asFloat(), 1e-5f); + EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asFloat(), 1e-5f); + tearDown(); } TEST(maya_NodeHelper, addPointAttr) { - setUp(); - const char* const longName = "longPointName"; - const char* const shortName = "lpn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const double defaultValueX = 41.1; - const double defaultValueY = 41.2; - const double defaultValueZ = 41.3; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addPointAttr(m_node, longName, shortName, MPoint(defaultValueX, defaultValueY, defaultValueZ), flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asDouble(), 1e-5f); - EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asDouble(), 1e-5f); - EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asDouble(), 1e-5f); - tearDown(); + setUp(); + const char* const longName = "longPointName"; + const char* const shortName = "lpn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const double defaultValueX = 41.1; + const double defaultValueY = 41.2; + const double defaultValueZ = 41.3; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addPointAttr( + m_node, + longName, + shortName, + MPoint(defaultValueX, defaultValueY, defaultValueZ), + flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asDouble(), 1e-5f); + EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asDouble(), 1e-5f); + EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asDouble(), 1e-5f); + tearDown(); } TEST(maya_NodeHelper, addVectorAttr) { - setUp(); - const char* const longName = "longVectorName"; - const char* const shortName = "lVn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const double defaultValueX = 51.1; - const double defaultValueY = 51.2; - const double defaultValueZ = 51.3; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addVectorAttr(m_node, longName, shortName, MVector(defaultValueX, defaultValueY, defaultValueZ), flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asDouble(), 1e-5f); - EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asDouble(), 1e-5f); - EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asDouble(), 1e-5f); - tearDown(); + setUp(); + const char* const longName = "longVectorName"; + const char* const shortName = "lVn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const double defaultValueX = 51.1; + const double defaultValueY = 51.2; + const double defaultValueZ = 51.3; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addVectorAttr( + m_node, + longName, + shortName, + MVector(defaultValueX, defaultValueY, defaultValueZ), + flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asDouble(), 1e-5f); + EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asDouble(), 1e-5f); + EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asDouble(), 1e-5f); + tearDown(); } TEST(maya_NodeHelper, addFloatPointAttr) { - setUp(); - const char* const longName = "longFPointName"; - const char* const shortName = "lFpn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const float defaultValueX = 61.1; - const float defaultValueY = 61.2; - const float defaultValueZ = 61.3; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addFloatPointAttr(m_node, longName, shortName, MFloatPoint(defaultValueX, defaultValueY, defaultValueZ), flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asFloat(), 1e-5f); - EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asFloat(), 1e-5f); - EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asFloat(), 1e-5f); - tearDown(); + setUp(); + const char* const longName = "longFPointName"; + const char* const shortName = "lFpn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const float defaultValueX = 61.1; + const float defaultValueY = 61.2; + const float defaultValueZ = 61.3; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addFloatPointAttr( + m_node, + longName, + shortName, + MFloatPoint(defaultValueX, defaultValueY, defaultValueZ), + flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asFloat(), 1e-5f); + EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asFloat(), 1e-5f); + EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asFloat(), 1e-5f); + tearDown(); } TEST(maya_NodeHelper, addFloatVectorAttr) { - setUp(); - const char* const longName = "longFVectorName"; - const char* const shortName = "lFVn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - const float defaultValueX = 71.1; - const float defaultValueY = 71.2; - const float defaultValueZ = 71.3; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addFloatVectorAttr(m_node, longName, shortName, MFloatVector(defaultValueX, defaultValueY, defaultValueZ), flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asFloat(), 1e-5f); - EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asFloat(), 1e-5f); - EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asFloat(), 1e-5f); - tearDown(); + setUp(); + const char* const longName = "longFVectorName"; + const char* const shortName = "lFVn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + const float defaultValueX = 71.1; + const float defaultValueY = 71.2; + const float defaultValueZ = 71.3; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addFloatVectorAttr( + m_node, + longName, + shortName, + MFloatVector(defaultValueX, defaultValueY, defaultValueZ), + flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asFloat(), 1e-5f); + EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asFloat(), 1e-5f); + EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asFloat(), 1e-5f); + tearDown(); } TEST(maya_NodeHelper, addColourAttr) { - setUp(); - const char* const longName = "longColourName"; - const char* const shortName = "lCn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable | kColour; - const float defaultValueX = 0.441; - const float defaultValueY = 0.442; - const float defaultValueZ = 0.443; - const float defaultValueW = 0.444; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addColourAttr(m_node, longName, shortName, MColor(defaultValueX, defaultValueY, defaultValueZ, defaultValueW), flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asFloat(), 1e-5f); - EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asFloat(), 1e-5f); - EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asFloat(), 1e-5f); - tearDown(); + setUp(); + const char* const longName = "longColourName"; + const char* const shortName = "lCn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable | kColour; + const float defaultValueX = 0.441; + const float defaultValueY = 0.442; + const float defaultValueZ = 0.443; + const float defaultValueW = 0.444; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addColourAttr( + m_node, + longName, + shortName, + MColor(defaultValueX, defaultValueY, defaultValueZ, defaultValueW), + flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + EXPECT_NEAR(defaultValueX, findPlug(longName).child(0).asFloat(), 1e-5f); + EXPECT_NEAR(defaultValueY, findPlug(longName).child(1).asFloat(), 1e-5f); + EXPECT_NEAR(defaultValueZ, findPlug(longName).child(2).asFloat(), 1e-5f); + tearDown(); } TEST(maya_NodeHelper, addMatrixAttr) { - setUp(); - double D[4][4] = { - {1.0, 2.0, 3.0, 4.0f}, - {11.0, 12.0, 13.0, 14.0f}, - {21.0, 22.0, 23.0, 24.0f}, - {31.0, 32.0, 33.0, 34.0f} - }; - MMatrix MM(D); - const char* const longName = "longMatrixName"; - const char* const shortName = "lMn"; - const uint32_t flags = kCached | kReadable | kWritable | kStorable; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addMatrixAttr(m_node, longName, shortName, MM, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - MObject attrData; - findPlug(longName).getValue(attrData); - MFnMatrixData fnData(attrData); - EXPECT_EQ(MM, fnData.matrix()); - tearDown(); + setUp(); + double D[4][4] = { { 1.0, 2.0, 3.0, 4.0f }, + { 11.0, 12.0, 13.0, 14.0f }, + { 21.0, 22.0, 23.0, 24.0f }, + { 31.0, 32.0, 33.0, 34.0f } }; + MMatrix MM(D); + const char* const longName = "longMatrixName"; + const char* const shortName = "lMn"; + const uint32_t flags = kCached | kReadable | kWritable | kStorable; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addMatrixAttr(m_node, longName, shortName, MM, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + MObject attrData; + findPlug(longName).getValue(attrData); + MFnMatrixData fnData(attrData); + EXPECT_EQ(MM, fnData.matrix()); + tearDown(); } TEST(maya_NodeHelper, addDataAttr) { - setUp(); - const uint32_t flags = kCached | kReadable | kWritable | kHidden | kStorable; - { - const char* const longName = "longDataName1"; - const char* const shortName = "lDDn1"; - MFnAttribute::DisconnectBehavior behaviour = MFnAttribute::kNothing; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addDataAttr(m_node, longName, shortName, MFnData::kVectorArray, flags, behaviour)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - MFnAttribute fn(findPlug(longName).attribute()); - EXPECT_EQ(behaviour, fn.disconnectBehavior()); - EXPECT_EQ(true, fn.accepts(MFnData::kVectorArray)); - } - { - const char* const longName = "longDataName2"; - const char* const shortName = "lDDn2"; - MFnAttribute::DisconnectBehavior behaviour = MFnAttribute::kDelete; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addDataAttr(m_node, longName, shortName, MFnData::kMesh, flags, behaviour)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - MFnAttribute fn(findPlug(longName).attribute()); - EXPECT_EQ(behaviour, fn.disconnectBehavior()); - EXPECT_EQ(true, fn.accepts(MFnData::kMesh)); - } - { - const char* const longName = "longDataName3"; - const char* const shortName = "lDDn3"; - MFnAttribute::DisconnectBehavior behaviour = MFnAttribute::kReset; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addDataAttr(m_node, longName, shortName, MFnData::kLattice, flags, behaviour)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - MFnAttribute fn(findPlug(longName).attribute()); - EXPECT_EQ(behaviour, fn.disconnectBehavior()); - EXPECT_EQ(true, fn.accepts(MFnData::kLattice)); - } - tearDown(); + setUp(); + const uint32_t flags = kCached | kReadable | kWritable | kHidden | kStorable; + { + const char* const longName = "longDataName1"; + const char* const shortName = "lDDn1"; + MFnAttribute::DisconnectBehavior behaviour = MFnAttribute::kNothing; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addDataAttr( + m_node, longName, shortName, MFnData::kVectorArray, flags, behaviour)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + MFnAttribute fn(findPlug(longName).attribute()); + EXPECT_EQ(behaviour, fn.disconnectBehavior()); + EXPECT_EQ(true, fn.accepts(MFnData::kVectorArray)); + } + { + const char* const longName = "longDataName2"; + const char* const shortName = "lDDn2"; + MFnAttribute::DisconnectBehavior behaviour = MFnAttribute::kDelete; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addDataAttr( + m_node, longName, shortName, MFnData::kMesh, flags, behaviour)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + MFnAttribute fn(findPlug(longName).attribute()); + EXPECT_EQ(behaviour, fn.disconnectBehavior()); + EXPECT_EQ(true, fn.accepts(MFnData::kMesh)); + } + { + const char* const longName = "longDataName3"; + const char* const shortName = "lDDn3"; + MFnAttribute::DisconnectBehavior behaviour = MFnAttribute::kReset; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addDataAttr( + m_node, longName, shortName, MFnData::kLattice, flags, behaviour)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + MFnAttribute fn(findPlug(longName).attribute()); + EXPECT_EQ(behaviour, fn.disconnectBehavior()); + EXPECT_EQ(true, fn.accepts(MFnData::kLattice)); + } + tearDown(); } TEST(maya_NodeHelper, addMessageAttr) { - setUp(); - const char* const longName = "longMessageName"; - const char* const shortName = "lMNn"; - const uint32_t flags = kCached | kReadable | kWritable | kHidden; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addMessageAttr(m_node, longName, shortName, flags)); - EXPECT_EQ(findPlug(longName), findPlug(shortName)); - checkAttributeFlags(findPlug(longName), flags); - tearDown(); + setUp(); + const char* const longName = "longMessageName"; + const char* const shortName = "lMNn"; + const uint32_t flags = kCached | kReadable | kWritable | kHidden; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addMessageAttr(m_node, longName, shortName, flags)); + EXPECT_EQ(findPlug(longName), findPlug(shortName)); + checkAttributeFlags(findPlug(longName), flags); + tearDown(); } TEST(maya_NodeHelper, testAttributeFlags) { - setUp(); - { - const char* const longName = "testAttrFlags1"; - const char* const shortName = "taf1"; - const uint32_t flags = kReadable | kWritable | kCached; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); - checkAttributeFlags(findPlug(longName), flags); - } - { - const char* const longName = "testAttrFlags2"; - const char* const shortName = "taf2"; - const uint32_t flags = kReadable | kWritable | kStorable; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); - checkAttributeFlags(findPlug(longName), flags); - } - { - const char* const longName = "testAttrFlags3"; - const char* const shortName = "taf3"; - const uint32_t flags = kReadable | kWritable | kAffectsAppearance; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); - checkAttributeFlags(findPlug(longName), flags); - } - { - const char* const longName = "testAttrFlags4"; - const char* const shortName = "taf4"; - const uint32_t flags = kReadable | kWritable | kKeyable; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); - checkAttributeFlags(findPlug(longName), flags); - } - { - const char* const longName = "testAttrFlags5"; - const char* const shortName = "taf5"; - const uint32_t flags = kReadable | kWritable | kConnectable; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); - checkAttributeFlags(findPlug(longName), flags); - } - /// \todo Investigate. - /// So when I'm *not* setting kUsesArrayDataBuilder, kUsesArrayDataBuilder gets set anyway whenever you use kArray? WAT? - #if 0 + setUp(); + { + const char* const longName = "testAttrFlags1"; + const char* const shortName = "taf1"; + const uint32_t flags = kReadable | kWritable | kCached; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); + checkAttributeFlags(findPlug(longName), flags); + } + { + const char* const longName = "testAttrFlags2"; + const char* const shortName = "taf2"; + const uint32_t flags = kReadable | kWritable | kStorable; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); + checkAttributeFlags(findPlug(longName), flags); + } + { + const char* const longName = "testAttrFlags3"; + const char* const shortName = "taf3"; + const uint32_t flags = kReadable | kWritable | kAffectsAppearance; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); + checkAttributeFlags(findPlug(longName), flags); + } + { + const char* const longName = "testAttrFlags4"; + const char* const shortName = "taf4"; + const uint32_t flags = kReadable | kWritable | kKeyable; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); + checkAttributeFlags(findPlug(longName), flags); + } + { + const char* const longName = "testAttrFlags5"; + const char* const shortName = "taf5"; + const uint32_t flags = kReadable | kWritable | kConnectable; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); + checkAttributeFlags(findPlug(longName), flags); + } +/// \todo Investigate. +/// So when I'm *not* setting kUsesArrayDataBuilder, kUsesArrayDataBuilder gets set anyway +/// whenever you use kArray? WAT? +#if 0 { const char* const longName = "testAttrFlags6"; const char* const shortName = "taf6"; @@ -720,41 +812,51 @@ TEST(maya_NodeHelper, testAttributeFlags) EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); checkAttributeFlags(findPlug(longName), flags); } - #endif - { - const char* const longName = "testAttrFlags7"; - const char* const shortName = "taf7"; - const uint32_t flags = kReadable | kWritable | kColour; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); - checkAttributeFlags(findPlug(longName), flags); - } - { - const char* const longName = "testAttrFlags8"; - const char* const shortName = "taf8"; - const uint32_t flags = kReadable | kWritable | kHidden; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); - checkAttributeFlags(findPlug(longName), flags); - } - { - const char* const longName = "testAttrFlags9"; - const char* const shortName = "taf9"; - const uint32_t flags = kReadable | kWritable | kInternal; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); - checkAttributeFlags(findPlug(longName), flags); - } - { - const char* const longName = "testAttrFlags10"; - const char* const shortName = "taf10"; - const uint32_t flags = kReadable | kWritable | kAffectsWorldSpace; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); - checkAttributeFlags(findPlug(longName), flags); - } - { - const char* const longName = "testAttrFlags11"; - const char* const shortName = "taf11"; - const uint32_t flags = kReadable | kWritable | kUsesArrayDataBuilder | kArray; - EXPECT_EQ(MStatus(MS::kSuccess), AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); - checkAttributeFlags(findPlug(longName), flags); - } - tearDown(); +#endif + { + const char* const longName = "testAttrFlags7"; + const char* const shortName = "taf7"; + const uint32_t flags = kReadable | kWritable | kColour; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); + checkAttributeFlags(findPlug(longName), flags); + } + { + const char* const longName = "testAttrFlags8"; + const char* const shortName = "taf8"; + const uint32_t flags = kReadable | kWritable | kHidden; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); + checkAttributeFlags(findPlug(longName), flags); + } + { + const char* const longName = "testAttrFlags9"; + const char* const shortName = "taf9"; + const uint32_t flags = kReadable | kWritable | kInternal; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); + checkAttributeFlags(findPlug(longName), flags); + } + { + const char* const longName = "testAttrFlags10"; + const char* const shortName = "taf10"; + const uint32_t flags = kReadable | kWritable | kAffectsWorldSpace; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); + checkAttributeFlags(findPlug(longName), flags); + } + { + const char* const longName = "testAttrFlags11"; + const char* const shortName = "taf11"; + const uint32_t flags = kReadable | kWritable | kUsesArrayDataBuilder | kArray; + EXPECT_EQ( + MStatus(MS::kSuccess), + AL::maya::utils::NodeHelper::addInt32Attr(m_node, longName, shortName, 0, flags)); + checkAttributeFlags(findPlug(longName), flags); + } + tearDown(); } diff --git a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_mobjectmap.cpp b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_mobjectmap.cpp index f7eef2b18b..62ce258155 100644 --- a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_mobjectmap.cpp +++ b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/test_mobjectmap.cpp @@ -16,6 +16,7 @@ //#include "AL/maya/utils/Utils.h" #include "AL/maya/utils/MObjectMap.h" + #include using namespace AL; @@ -28,52 +29,47 @@ TEST(extraMaya_Utils, guid_compare) { #if AL_UTILS_ENABLE_SIMD - guid_compare gcmp; - i128 a = set16i8(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); - i128 b = set16i8(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + guid_compare gcmp; + i128 a = set16i8(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + i128 b = set16i8(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); - // identical guids should always return false - EXPECT_EQ(true, !gcmp(a, b) && !gcmp(b, a)); + // identical guids should always return false + EXPECT_EQ(true, !gcmp(a, b) && !gcmp(b, a)); - for(uint32_t i = 0; i < 16; ++i) - { - ALIGN16(uint8_t values[]) = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; - values[i] += 1; + for (uint32_t i = 0; i < 16; ++i) { + ALIGN16(uint8_t values[]) = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; + values[i] += 1; - i128 c = load4i(values); - EXPECT_EQ(true, gcmp(a, c) && !gcmp(c, a)); - } + i128 c = load4i(values); + EXPECT_EQ(true, gcmp(a, c) && !gcmp(c, a)); + } - for(uint32_t i = 0; i < 16; ++i) - { - ALIGN16(uint8_t values[]) = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; - values[i] -= 1; + for (uint32_t i = 0; i < 16; ++i) { + ALIGN16(uint8_t values[]) = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; + values[i] -= 1; - i128 c = load4i(values); - EXPECT_EQ(true, !gcmp(a, c) && gcmp(c, a)); - } + i128 c = load4i(values); + EXPECT_EQ(true, !gcmp(a, c) && gcmp(c, a)); + } #else - guid_compare gcmp; - guid a = {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}}; - guid b = {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}}; + guid_compare gcmp; + guid a = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } }; + guid b = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } }; - // identical guids should always return false - EXPECT_EQ(true, !gcmp(a, b) && !gcmp(b, a)); + // identical guids should always return false + EXPECT_EQ(true, !gcmp(a, b) && !gcmp(b, a)); - for(uint32_t i = 0; i < 16; ++i) - { - guid values = {{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }}; - values.uuid[i] += 1; + for (uint32_t i = 0; i < 16; ++i) { + guid values = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } }; + values.uuid[i] += 1; - EXPECT_EQ(true, gcmp(a, values) && !gcmp(values, a)); - } + EXPECT_EQ(true, gcmp(a, values) && !gcmp(values, a)); + } - for(uint32_t i = 0; i < 16; ++i) - { - guid values = {{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }}; - values.uuid[i] -= 1; - EXPECT_EQ(true, !gcmp(a, values) && gcmp(values, a)); - } + for (uint32_t i = 0; i < 16; ++i) { + guid values = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 } }; + values.uuid[i] -= 1; + EXPECT_EQ(true, !gcmp(a, values) && gcmp(values, a)); + } #endif } - diff --git a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/CommandGuiHelperTest.cpp b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/CommandGuiHelperTest.cpp index f93c0756e3..9cbea6a469 100644 --- a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/CommandGuiHelperTest.cpp +++ b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/CommandGuiHelperTest.cpp @@ -14,12 +14,13 @@ // limitations under the License. // #include "AL/maya/utils/CommandGuiHelper.h" + #include "AL/maya/tests/mayaplugintest/utils/CommandGuiHelperTest.h" -#include +#include #include +#include #include -#include #include #include @@ -33,460 +34,448 @@ const MString CommandGuiHelperTestCMD::kName = "AL_usdmaya_CommandGuiHelperTest" //---------------------------------------------------------------------------------------------------------------------- void CommandGuiHelperTestCMD::makeGUI() { - // Currently this tests all of the individual data types, all using the 'persist' parameter to ensure they get added - // into the optionVars correctly, and can be retrieved and set by the gui. There aren't exactly loads of tests regarding - // the non-persistent command args. I will need to go test those at some point. - AL::maya::utils::CommandGuiHelper commandOpts("AL_usdmaya_CommandGuiHelperTest", "Unit Testy Stuff", "Test", "USD/Tests/CommandGuiHelperTest"); - commandOpts.addFlagOption("qflag", "Flag", false, true); - commandOpts.addBoolOption("qbool", "Bool", false, true); - commandOpts.addIntOption("qint", "Int", 42, true); - commandOpts.addIntSliderOption("qintSlider", "Int Slider", -42, 69, 42, true); - commandOpts.addInt2Option("qint2", "Int2", 1, 2, true); - commandOpts.addInt3Option("qint3", "Int3", 3, 4, 5, true); - commandOpts.addInt4Option("qint4", "Int4", 6, 7, 8, 9, true); - commandOpts.addDoubleOption("qdouble", "Double", 2.3, true); - commandOpts.addDoubleSliderOption("qdoubleSlider", "Double Slider", -1.2, 4.5, 2.3, true); - commandOpts.addVec2Option("qdouble2", "Double2", 0.1, 0.4, true); - commandOpts.addVec3Option("qdouble3", "Double3", 0.5, 0.6, 0.9, true); - commandOpts.addVec4Option("qdouble4", "Double4", 0.8, 0.5, 0.6, 0.9, true); - commandOpts.addColourOption("qcolour", "Colour", 0.15, 0.16, 0.19, true); - - const int32_t values[4] = { - 4, 3, 2, 1 - }; - const char* const strings[5] = { - "never", "eat", "shredded", "wheat", 0 - }; - commandOpts.addEnumOption("qenum1", "Enum Passed as Index", 0, strings, 0, true, false); - commandOpts.addEnumOption("qenum2", "Enum Passed as String", 0, strings, 0, true, true); - commandOpts.addEnumOption("qenum3", "Enum Passed as Mutated Index", 0, strings, values, true, false); - commandOpts.addRadioButtonGroupOption("qradio1", "Radio Passed as Index", 0, strings, 0, true, false); - commandOpts.addRadioButtonGroupOption("qradio2", "Radio Passed as String", 0, strings, 0, true, true); - commandOpts.addRadioButtonGroupOption("qradio3", "Radio Passed as Mutated Index", 0, strings, values, true, false); - commandOpts.addStringOption("qstring", "String", "hello", true, AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); - commandOpts.addFilePathOption("fp1", "File Path Load", AL::maya::utils::CommandGuiHelper::kLoad, "All Files (*.*) (*.*)", AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); - commandOpts.addFilePathOption("fp2", "File Path Save", AL::maya::utils::CommandGuiHelper::kSave, "All Files (*.*) (*.*)", AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); - commandOpts.addFilePathOption("fp3", "File Path Dir", AL::maya::utils::CommandGuiHelper::kDirectory, "All Files (*.*) (*.*)", AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); - commandOpts.addFilePathOption("fp4", "File Path Dir + File", AL::maya::utils::CommandGuiHelper::kDirectoryWithFiles, "All Files (*.*) (*.*)", AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); - commandOpts.addFilePathOption("fp5", "File Path Multi File", AL::maya::utils::CommandGuiHelper::kMultiLoad, "All Files (*.*) (*.*)", AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); + // Currently this tests all of the individual data types, all using the 'persist' parameter to + // ensure they get added into the optionVars correctly, and can be retrieved and set by the gui. + // There aren't exactly loads of tests regarding the non-persistent command args. I will need to + // go test those at some point. + AL::maya::utils::CommandGuiHelper commandOpts( + "AL_usdmaya_CommandGuiHelperTest", + "Unit Testy Stuff", + "Test", + "USD/Tests/CommandGuiHelperTest"); + commandOpts.addFlagOption("qflag", "Flag", false, true); + commandOpts.addBoolOption("qbool", "Bool", false, true); + commandOpts.addIntOption("qint", "Int", 42, true); + commandOpts.addIntSliderOption("qintSlider", "Int Slider", -42, 69, 42, true); + commandOpts.addInt2Option("qint2", "Int2", 1, 2, true); + commandOpts.addInt3Option("qint3", "Int3", 3, 4, 5, true); + commandOpts.addInt4Option("qint4", "Int4", 6, 7, 8, 9, true); + commandOpts.addDoubleOption("qdouble", "Double", 2.3, true); + commandOpts.addDoubleSliderOption("qdoubleSlider", "Double Slider", -1.2, 4.5, 2.3, true); + commandOpts.addVec2Option("qdouble2", "Double2", 0.1, 0.4, true); + commandOpts.addVec3Option("qdouble3", "Double3", 0.5, 0.6, 0.9, true); + commandOpts.addVec4Option("qdouble4", "Double4", 0.8, 0.5, 0.6, 0.9, true); + commandOpts.addColourOption("qcolour", "Colour", 0.15, 0.16, 0.19, true); + + const int32_t values[4] = { 4, 3, 2, 1 }; + const char* const strings[5] = { "never", "eat", "shredded", "wheat", 0 }; + commandOpts.addEnumOption("qenum1", "Enum Passed as Index", 0, strings, 0, true, false); + commandOpts.addEnumOption("qenum2", "Enum Passed as String", 0, strings, 0, true, true); + commandOpts.addEnumOption( + "qenum3", "Enum Passed as Mutated Index", 0, strings, values, true, false); + commandOpts.addRadioButtonGroupOption( + "qradio1", "Radio Passed as Index", 0, strings, 0, true, false); + commandOpts.addRadioButtonGroupOption( + "qradio2", "Radio Passed as String", 0, strings, 0, true, true); + commandOpts.addRadioButtonGroupOption( + "qradio3", "Radio Passed as Mutated Index", 0, strings, values, true, false); + commandOpts.addStringOption( + "qstring", + "String", + "hello", + true, + AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); + commandOpts.addFilePathOption( + "fp1", + "File Path Load", + AL::maya::utils::CommandGuiHelper::kLoad, + "All Files (*.*) (*.*)", + AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); + commandOpts.addFilePathOption( + "fp2", + "File Path Save", + AL::maya::utils::CommandGuiHelper::kSave, + "All Files (*.*) (*.*)", + AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); + commandOpts.addFilePathOption( + "fp3", + "File Path Dir", + AL::maya::utils::CommandGuiHelper::kDirectory, + "All Files (*.*) (*.*)", + AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); + commandOpts.addFilePathOption( + "fp4", + "File Path Dir + File", + AL::maya::utils::CommandGuiHelper::kDirectoryWithFiles, + "All Files (*.*) (*.*)", + AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); + commandOpts.addFilePathOption( + "fp5", + "File Path Multi File", + AL::maya::utils::CommandGuiHelper::kMultiLoad, + "All Files (*.*) (*.*)", + AL::maya::utils::CommandGuiHelper::kStringMustHaveValue); } //---------------------------------------------------------------------------------------------------------------------- MSyntax CommandGuiHelperTestCMD::createSyntax() { - MSyntax syn; - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wfg", "-qflag", MSyntax::kNoArg), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wb", "-qbool", MSyntax::kBoolean), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wi", "-qint", MSyntax::kLong), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wis", "-qintSlider", MSyntax::kLong), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wi2", "-qint2", MSyntax::kLong, MSyntax::kLong), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wi3", "-qint3", MSyntax::kLong, MSyntax::kLong, MSyntax::kLong), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wi4", "-qint4", MSyntax::kLong, MSyntax::kLong, MSyntax::kLong, MSyntax::kLong), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wd", "-qdouble", MSyntax::kDouble), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wds", "-qdoubleSlider", MSyntax::kDouble), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wd2", "-qdouble2", MSyntax::kDouble, MSyntax::kDouble), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wd3", "-qdouble3", MSyntax::kDouble, MSyntax::kDouble, MSyntax::kDouble), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wd4", "-qdouble4", MSyntax::kDouble, MSyntax::kDouble, MSyntax::kDouble, MSyntax::kDouble), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wc", "-qcolour", MSyntax::kDouble, MSyntax::kDouble, MSyntax::kDouble), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-we1", "-qenum1", MSyntax::kLong), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-we2", "-qenum2", MSyntax::kString), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-we3", "-qenum3", MSyntax::kLong), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wr1", "-qradio1", MSyntax::kLong), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wr2", "-qradio2", MSyntax::kString), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-wr3", "-qradio3", MSyntax::kLong), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-ws", "-qstring", MSyntax::kString), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-fp1", "-fap1", MSyntax::kString), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-fp2", "-fap2", MSyntax::kString), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-fp3", "-fap3", MSyntax::kString), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-fp4", "-fap4", MSyntax::kString), "syntaxError"); - AL_MAYA_CHECK_ERROR2(syn.addFlag("-fp5", "-fap5", MSyntax::kString), "syntaxError"); - return syn; + MSyntax syn; + AL_MAYA_CHECK_ERROR2(syn.addFlag("-wfg", "-qflag", MSyntax::kNoArg), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-wb", "-qbool", MSyntax::kBoolean), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-wi", "-qint", MSyntax::kLong), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-wis", "-qintSlider", MSyntax::kLong), "syntaxError"); + AL_MAYA_CHECK_ERROR2( + syn.addFlag("-wi2", "-qint2", MSyntax::kLong, MSyntax::kLong), "syntaxError"); + AL_MAYA_CHECK_ERROR2( + syn.addFlag("-wi3", "-qint3", MSyntax::kLong, MSyntax::kLong, MSyntax::kLong), + "syntaxError"); + AL_MAYA_CHECK_ERROR2( + syn.addFlag( + "-wi4", "-qint4", MSyntax::kLong, MSyntax::kLong, MSyntax::kLong, MSyntax::kLong), + "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-wd", "-qdouble", MSyntax::kDouble), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-wds", "-qdoubleSlider", MSyntax::kDouble), "syntaxError"); + AL_MAYA_CHECK_ERROR2( + syn.addFlag("-wd2", "-qdouble2", MSyntax::kDouble, MSyntax::kDouble), "syntaxError"); + AL_MAYA_CHECK_ERROR2( + syn.addFlag("-wd3", "-qdouble3", MSyntax::kDouble, MSyntax::kDouble, MSyntax::kDouble), + "syntaxError"); + AL_MAYA_CHECK_ERROR2( + syn.addFlag( + "-wd4", + "-qdouble4", + MSyntax::kDouble, + MSyntax::kDouble, + MSyntax::kDouble, + MSyntax::kDouble), + "syntaxError"); + AL_MAYA_CHECK_ERROR2( + syn.addFlag("-wc", "-qcolour", MSyntax::kDouble, MSyntax::kDouble, MSyntax::kDouble), + "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-we1", "-qenum1", MSyntax::kLong), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-we2", "-qenum2", MSyntax::kString), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-we3", "-qenum3", MSyntax::kLong), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-wr1", "-qradio1", MSyntax::kLong), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-wr2", "-qradio2", MSyntax::kString), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-wr3", "-qradio3", MSyntax::kLong), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-ws", "-qstring", MSyntax::kString), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-fp1", "-fap1", MSyntax::kString), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-fp2", "-fap2", MSyntax::kString), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-fp3", "-fap3", MSyntax::kString), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-fp4", "-fap4", MSyntax::kString), "syntaxError"); + AL_MAYA_CHECK_ERROR2(syn.addFlag("-fp5", "-fap5", MSyntax::kString), "syntaxError"); + return syn; } //---------------------------------------------------------------------------------------------------------------------- -void* CommandGuiHelperTestCMD::creator() -{ - return new CommandGuiHelperTestCMD; -} +void* CommandGuiHelperTestCMD::creator() { return new CommandGuiHelperTestCMD; } //---------------------------------------------------------------------------------------------------------------------- MStatus CommandGuiHelperTestCMD::doIt(const MArgList& args) { - MStatus status; - MArgDatabase argData(syntax(), args, &status); - - // Check that all flags were valid - if(status != MS::kSuccess) - { - return status; - } - - bool b; - int i; - int i2[2]; - int i3[3]; - int i4[4]; - double d; - double d2[2]; - double d3[3]; - double d4[4]; - double c[3]; - int e1; - MString e2; - int e3; - int r1; - MString r2; - int r3; - MString s; - - const char* const testFail = "test fail"; - if(argData.isFlagSet("qbool")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qbool", 0, b), testFail); - std::cout << "qbool " << b << std::endl; - } - else - { - std::cout << "qbool not set" << std::endl; - } - - if(argData.isFlagSet("qint")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint", 0, i), testFail); - std::cout << "qint " << i << std::endl; - } - else - { - std::cout << "qint not set" << std::endl; - } - - if(argData.isFlagSet("qint2")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint2", 0, i2[0]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint2", 1, i2[1]), testFail); - std::cout << "qint2 " << i2[0] << " " << i2[1] << std::endl; - } - else - { - std::cout << "int2 not set" << std::endl; - } - - if(argData.isFlagSet("qint3")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint3", 0, i3[0]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint3", 1, i3[1]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint3", 2, i3[2]), testFail); - std::cout << "qint3 " << i3[0] << " " << i3[1] << " " << i3[2] << std::endl; - } - else - { - std::cout << "qint3 not set" << std::endl; - } - - if(argData.isFlagSet("qint4")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint4", 0, i4[0]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint4", 1, i4[1]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint4", 2, i4[2]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint4", 3, i4[3]), testFail); - std::cout << "qint4 " << i4[0] << " " << i4[1] << " " << i4[2] << " " << i4[3] << std::endl; - } - else - { - std::cout << "qint4 not set" << std::endl; - } - - if(argData.isFlagSet("qdouble")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble", 0, d), testFail); - std::cout << "qdouble " << i << std::endl; - } - else - { - std::cout << "qdouble not set" << std::endl; - } - - if(argData.isFlagSet("qdouble2")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble2", 0, d2[0]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble2", 1, d2[1]), testFail); - std::cout << "qdouble2 " << d2[0] << " " << d2[1] << std::endl; - } - else - { - std::cout << "qdouble2 not set" << std::endl; - } - - if(argData.isFlagSet("qdouble3")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble3", 0, d3[0]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble3", 1, d3[1]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble3", 2, d3[2]), testFail); - std::cout << "qdouble3 " << d3[0] << " " << d3[1] << " " << d3[2] << std::endl; - } - else - { - std::cout << "qdouble3 not set" << std::endl; - } - - if(argData.isFlagSet("qdouble4")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble4", 0, d4[0]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble4", 1, d4[1]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble4", 2, d4[2]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble4", 3, d4[3]), testFail); - std::cout << "qdouble4 " << d4[0] << " " << d4[1] << " " << d4[2] << " " << d4[3] << std::endl; - } - else - { - std::cout << "qdouble4 not set" << std::endl; - } - - if(argData.isFlagSet("qcolour")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qcolour", 0, c[0]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qcolour", 1, c[1]), testFail); - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qcolour", 2, c[2]), testFail); - std::cout << "qcolour " << c[0] << " " << c[1] << " " << c[2] << std::endl; - } - else - { - std::cout << "qcolour not set" << std::endl; - } - - if(argData.isFlagSet("qenum1")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qenum1", 0, e1), testFail); - std::cout << "qenum1 " << e1 << std::endl; - } - else - { - std::cout << "qenum1 not set" << std::endl; - } - - if(argData.isFlagSet("qenum2")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qenum2", 0, e2), testFail); - std::cout << "qenum2 " << e2.asChar() << std::endl; - } - else - { - std::cout << "qenum2 not set" << std::endl; - } - - if(argData.isFlagSet("qenum3")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qenum3", 0, e3), testFail); - std::cout << "qenum3 " << e3 << std::endl; - } - else - { - std::cout << "qenum3 not set" << std::endl; - } - - if(argData.isFlagSet("qradio1")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qradio1", 0, r1), testFail); - std::cout << "qradio1 " << r1 << std::endl; - } - else - { - std::cout << "qradio1 not set" << std::endl; - } - - if(argData.isFlagSet("qradio2")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qradio2", 0, r2), testFail); - std::cout << "qradio2 " << r2.asChar() << std::endl; - } - else - { - std::cout << "qradio2 not set" << std::endl; - } - - if(argData.isFlagSet("qradio3")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qradio3", 0, r3), testFail); - std::cout << "qradio3 " << r3 << std::endl; - } - else - { - std::cout << "qradio3 not set" << std::endl; - } - - if(argData.isFlagSet("qstring")) - { - AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qstring", 0, s), testFail); - std::cout << "qstring " << s.asChar() << std::endl; - } - else - { - std::cout << "qstring not set" << std::endl; - } - - return MS::kSuccess; + MStatus status; + MArgDatabase argData(syntax(), args, &status); + + // Check that all flags were valid + if (status != MS::kSuccess) { + return status; + } + + bool b; + int i; + int i2[2]; + int i3[3]; + int i4[4]; + double d; + double d2[2]; + double d3[3]; + double d4[4]; + double c[3]; + int e1; + MString e2; + int e3; + int r1; + MString r2; + int r3; + MString s; + + const char* const testFail = "test fail"; + if (argData.isFlagSet("qbool")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qbool", 0, b), testFail); + std::cout << "qbool " << b << std::endl; + } else { + std::cout << "qbool not set" << std::endl; + } + + if (argData.isFlagSet("qint")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint", 0, i), testFail); + std::cout << "qint " << i << std::endl; + } else { + std::cout << "qint not set" << std::endl; + } + + if (argData.isFlagSet("qint2")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint2", 0, i2[0]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint2", 1, i2[1]), testFail); + std::cout << "qint2 " << i2[0] << " " << i2[1] << std::endl; + } else { + std::cout << "int2 not set" << std::endl; + } + + if (argData.isFlagSet("qint3")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint3", 0, i3[0]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint3", 1, i3[1]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint3", 2, i3[2]), testFail); + std::cout << "qint3 " << i3[0] << " " << i3[1] << " " << i3[2] << std::endl; + } else { + std::cout << "qint3 not set" << std::endl; + } + + if (argData.isFlagSet("qint4")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint4", 0, i4[0]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint4", 1, i4[1]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint4", 2, i4[2]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qint4", 3, i4[3]), testFail); + std::cout << "qint4 " << i4[0] << " " << i4[1] << " " << i4[2] << " " << i4[3] << std::endl; + } else { + std::cout << "qint4 not set" << std::endl; + } + + if (argData.isFlagSet("qdouble")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble", 0, d), testFail); + std::cout << "qdouble " << i << std::endl; + } else { + std::cout << "qdouble not set" << std::endl; + } + + if (argData.isFlagSet("qdouble2")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble2", 0, d2[0]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble2", 1, d2[1]), testFail); + std::cout << "qdouble2 " << d2[0] << " " << d2[1] << std::endl; + } else { + std::cout << "qdouble2 not set" << std::endl; + } + + if (argData.isFlagSet("qdouble3")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble3", 0, d3[0]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble3", 1, d3[1]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble3", 2, d3[2]), testFail); + std::cout << "qdouble3 " << d3[0] << " " << d3[1] << " " << d3[2] << std::endl; + } else { + std::cout << "qdouble3 not set" << std::endl; + } + + if (argData.isFlagSet("qdouble4")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble4", 0, d4[0]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble4", 1, d4[1]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble4", 2, d4[2]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qdouble4", 3, d4[3]), testFail); + std::cout << "qdouble4 " << d4[0] << " " << d4[1] << " " << d4[2] << " " << d4[3] + << std::endl; + } else { + std::cout << "qdouble4 not set" << std::endl; + } + + if (argData.isFlagSet("qcolour")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qcolour", 0, c[0]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qcolour", 1, c[1]), testFail); + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qcolour", 2, c[2]), testFail); + std::cout << "qcolour " << c[0] << " " << c[1] << " " << c[2] << std::endl; + } else { + std::cout << "qcolour not set" << std::endl; + } + + if (argData.isFlagSet("qenum1")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qenum1", 0, e1), testFail); + std::cout << "qenum1 " << e1 << std::endl; + } else { + std::cout << "qenum1 not set" << std::endl; + } + + if (argData.isFlagSet("qenum2")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qenum2", 0, e2), testFail); + std::cout << "qenum2 " << e2.asChar() << std::endl; + } else { + std::cout << "qenum2 not set" << std::endl; + } + + if (argData.isFlagSet("qenum3")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qenum3", 0, e3), testFail); + std::cout << "qenum3 " << e3 << std::endl; + } else { + std::cout << "qenum3 not set" << std::endl; + } + + if (argData.isFlagSet("qradio1")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qradio1", 0, r1), testFail); + std::cout << "qradio1 " << r1 << std::endl; + } else { + std::cout << "qradio1 not set" << std::endl; + } + + if (argData.isFlagSet("qradio2")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qradio2", 0, r2), testFail); + std::cout << "qradio2 " << r2.asChar() << std::endl; + } else { + std::cout << "qradio2 not set" << std::endl; + } + + if (argData.isFlagSet("qradio3")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qradio3", 0, r3), testFail); + std::cout << "qradio3 " << r3 << std::endl; + } else { + std::cout << "qradio3 not set" << std::endl; + } + + if (argData.isFlagSet("qstring")) { + AL_MAYA_CHECK_ERROR(argData.getFlagArgument("qstring", 0, s), testFail); + std::cout << "qstring " << s.asChar() << std::endl; + } else { + std::cout << "qstring not set" << std::endl; + } + + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- bool test_CommandGuiHelper() { - const MString polyCube_constructionHistory = MString("polyCube_constructionHistory"); - const MString polyCube_width = MString("polyCube_width"); - const MString polyCube_height = MString("polyCube_height"); - const MString polyCube_depth = MString("polyCube_depth"); - const MString polyCube_subdivisionsX = MString("polyCube_subdivisionsX"); - const MString polyCube_subdivisionsY = MString("polyCube_subdivisionsY"); - const MString polyCube_subdivisionsZ = MString("polyCube_subdivisionsZ"); - const MString polyCube_name = MString("polyCube_name"); - const MString polyCube_axis = MString("polyCube_axis"); - - // make sure these don't already exist (messing with our tests) - { - if(MGlobal::optionVarExists(polyCube_constructionHistory)) MGlobal::removeOptionVar(polyCube_constructionHistory); - if(MGlobal::optionVarExists(polyCube_width)) MGlobal::removeOptionVar(polyCube_width); - if(MGlobal::optionVarExists(polyCube_height)) MGlobal::removeOptionVar(polyCube_height); - if(MGlobal::optionVarExists(polyCube_depth)) MGlobal::removeOptionVar(polyCube_depth); - if(MGlobal::optionVarExists(polyCube_subdivisionsX)) MGlobal::removeOptionVar(polyCube_subdivisionsX); - if(MGlobal::optionVarExists(polyCube_subdivisionsY)) MGlobal::removeOptionVar(polyCube_subdivisionsY); - if(MGlobal::optionVarExists(polyCube_subdivisionsZ)) MGlobal::removeOptionVar(polyCube_subdivisionsZ); - if(MGlobal::optionVarExists(polyCube_name)) MGlobal::removeOptionVar(polyCube_name); - if(MGlobal::optionVarExists(polyCube_axis)) MGlobal::removeOptionVar(polyCube_name); - } - - // generate the GUI. - { - // see: http://help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/Commands/polyCube.html - AL::maya::utils::CommandGuiHelper options("polyCube", "Create Polygon Cube", "Create", "USD/polygons/Create Cube"); - options.addBoolOption("constructionHistory", "Construction History", true, true); - options.addDoubleOption("width", "Width", 1.0f, true); - options.addDoubleOption("height", "Height", 1.1f, true); - options.addDoubleOption("depth", "Depth", 1.2f, true); - options.addIntOption("subdivisionsX", "Subdivisions in X", 1, true); - options.addIntOption("subdivisionsY", "Subdivisions in Y", 2, true); - options.addIntOption("subdivisionsZ", "Subdivisions in Z", 3, true); - options.addStringOption("name", "Name", "", false); - const double defaultAxis[3] = {1, 0, 0}; - options.addVec3Option("axis", "Axis", defaultAxis, true); - const char* enumStrings[] = + const MString polyCube_constructionHistory = MString("polyCube_constructionHistory"); + const MString polyCube_width = MString("polyCube_width"); + const MString polyCube_height = MString("polyCube_height"); + const MString polyCube_depth = MString("polyCube_depth"); + const MString polyCube_subdivisionsX = MString("polyCube_subdivisionsX"); + const MString polyCube_subdivisionsY = MString("polyCube_subdivisionsY"); + const MString polyCube_subdivisionsZ = MString("polyCube_subdivisionsZ"); + const MString polyCube_name = MString("polyCube_name"); + const MString polyCube_axis = MString("polyCube_axis"); + + // make sure these don't already exist (messing with our tests) + { + if (MGlobal::optionVarExists(polyCube_constructionHistory)) + MGlobal::removeOptionVar(polyCube_constructionHistory); + if (MGlobal::optionVarExists(polyCube_width)) + MGlobal::removeOptionVar(polyCube_width); + if (MGlobal::optionVarExists(polyCube_height)) + MGlobal::removeOptionVar(polyCube_height); + if (MGlobal::optionVarExists(polyCube_depth)) + MGlobal::removeOptionVar(polyCube_depth); + if (MGlobal::optionVarExists(polyCube_subdivisionsX)) + MGlobal::removeOptionVar(polyCube_subdivisionsX); + if (MGlobal::optionVarExists(polyCube_subdivisionsY)) + MGlobal::removeOptionVar(polyCube_subdivisionsY); + if (MGlobal::optionVarExists(polyCube_subdivisionsZ)) + MGlobal::removeOptionVar(polyCube_subdivisionsZ); + if (MGlobal::optionVarExists(polyCube_name)) + MGlobal::removeOptionVar(polyCube_name); + if (MGlobal::optionVarExists(polyCube_axis)) + MGlobal::removeOptionVar(polyCube_name); + } + + // generate the GUI. { - "No UVs", - "No normalization", - "Each face separately", - "Normalized UVs", - "Non distorted UVs", - 0 - }; - const int32_t enumValues[] = + // see: http://help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/Commands/polyCube.html + AL::maya::utils::CommandGuiHelper options( + "polyCube", "Create Polygon Cube", "Create", "USD/polygons/Create Cube"); + options.addBoolOption("constructionHistory", "Construction History", true, true); + options.addDoubleOption("width", "Width", 1.0f, true); + options.addDoubleOption("height", "Height", 1.1f, true); + options.addDoubleOption("depth", "Depth", 1.2f, true); + options.addIntOption("subdivisionsX", "Subdivisions in X", 1, true); + options.addIntOption("subdivisionsY", "Subdivisions in Y", 2, true); + options.addIntOption("subdivisionsZ", "Subdivisions in Z", 3, true); + options.addStringOption("name", "Name", "", false); + const double defaultAxis[3] = { 1, 0, 0 }; + options.addVec3Option("axis", "Axis", defaultAxis, true); + const char* enumStrings[] = { "No UVs", "No normalization", "Each face separately", + "Normalized UVs", "Non distorted UVs", 0 }; + const int32_t enumValues[] = { 0, 1, 2, 3, 4 }; + options.addEnumOption("createUVs", "Create UVs", 4, enumStrings, enumValues, true, false); + } + + // generate a GUI for a light (to test colour params). { - 0, 1, 2, 3, 4 - }; - options.addEnumOption("createUVs", "Create UVs", 4, enumStrings, enumValues, true, false); - } - - // generate a GUI for a light (to test colour params). - { - AL::maya::utils::CommandGuiHelper options("pointLight", "Create Point Light", "Create", "USD/lights/Create Point Light"); - double colour[3] = {1, 1, 1}; - options.addColourOption("rgb", "Colour", colour, true); - double shadowColour[3] = {0, 0, 0}; - options.addColourOption("sc", "Shadow Colour", shadowColour, true); - } - - // Does load set our option vars correctly? - bool result = true; - - result = MGlobal::executeCommand("init_polyCube_optionGUI;") && result; - bool exists = false; - - if(MGlobal::optionVarIntValue(polyCube_constructionHistory, &exists)) - { - result = exists && result; - } - else - { - result = false; - std::cout << "polyCube_constructionHistory failed" << std::endl; - } - - if(fabs(1.0f - MGlobal::optionVarDoubleValue(polyCube_width, &exists)) < 1e-5f) - { - result = exists && result; - } - else - { - result = false; - std::cout << "polyCube_width failed" << std::endl; - } - - if(fabs(1.1f - MGlobal::optionVarDoubleValue(polyCube_height, &exists)) < 1e-5f) - { - result = exists && result; - } - else - { - result = false; - std::cout << "polyCube_height failed" << std::endl; - } - - if(fabs(1.2f - MGlobal::optionVarDoubleValue(polyCube_depth, &exists)) < 1e-5f) - { - result = exists && result; - } - else - { - result = false; - std::cout << "polyCube_depth failed" << std::endl; - } - - if(1 == MGlobal::optionVarIntValue(polyCube_subdivisionsX, &exists)) - { - result = exists && result; - } - else - { - result = false; - std::cout << "polyCube_subdivisionsX failed" << std::endl; - } - - if(2 == MGlobal::optionVarIntValue(polyCube_subdivisionsY, &exists)) - { - result = exists && result; - } - else - { - result = false; - std::cout << "polyCube_subdivisionsY failed" << std::endl; - } - - if(3 == MGlobal::optionVarIntValue(polyCube_subdivisionsZ, &exists)) - { - result = exists && result; - } - else - { - result = false; - std::cout << "polyCube_subdivisionsZ failed" << std::endl; - } - - // create up after ourselves - if(0) - { - if(MGlobal::optionVarExists(polyCube_constructionHistory)) MGlobal::removeOptionVar(polyCube_constructionHistory); - if(MGlobal::optionVarExists(polyCube_width)) MGlobal::removeOptionVar(polyCube_width); - if(MGlobal::optionVarExists(polyCube_height)) MGlobal::removeOptionVar(polyCube_height); - if(MGlobal::optionVarExists(polyCube_depth)) MGlobal::removeOptionVar(polyCube_depth); - if(MGlobal::optionVarExists(polyCube_subdivisionsX)) MGlobal::removeOptionVar(polyCube_subdivisionsX); - if(MGlobal::optionVarExists(polyCube_subdivisionsY)) MGlobal::removeOptionVar(polyCube_subdivisionsY); - if(MGlobal::optionVarExists(polyCube_subdivisionsZ)) MGlobal::removeOptionVar(polyCube_subdivisionsZ); - if(MGlobal::optionVarExists(polyCube_name)) MGlobal::removeOptionVar(polyCube_name); - if(MGlobal::optionVarExists(polyCube_axis)) MGlobal::removeOptionVar(polyCube_axis); - } - return result; + AL::maya::utils::CommandGuiHelper options( + "pointLight", "Create Point Light", "Create", "USD/lights/Create Point Light"); + double colour[3] = { 1, 1, 1 }; + options.addColourOption("rgb", "Colour", colour, true); + double shadowColour[3] = { 0, 0, 0 }; + options.addColourOption("sc", "Shadow Colour", shadowColour, true); + } + + // Does load set our option vars correctly? + bool result = true; + + result = MGlobal::executeCommand("init_polyCube_optionGUI;") && result; + bool exists = false; + + if (MGlobal::optionVarIntValue(polyCube_constructionHistory, &exists)) { + result = exists && result; + } else { + result = false; + std::cout << "polyCube_constructionHistory failed" << std::endl; + } + + if (fabs(1.0f - MGlobal::optionVarDoubleValue(polyCube_width, &exists)) < 1e-5f) { + result = exists && result; + } else { + result = false; + std::cout << "polyCube_width failed" << std::endl; + } + + if (fabs(1.1f - MGlobal::optionVarDoubleValue(polyCube_height, &exists)) < 1e-5f) { + result = exists && result; + } else { + result = false; + std::cout << "polyCube_height failed" << std::endl; + } + + if (fabs(1.2f - MGlobal::optionVarDoubleValue(polyCube_depth, &exists)) < 1e-5f) { + result = exists && result; + } else { + result = false; + std::cout << "polyCube_depth failed" << std::endl; + } + + if (1 == MGlobal::optionVarIntValue(polyCube_subdivisionsX, &exists)) { + result = exists && result; + } else { + result = false; + std::cout << "polyCube_subdivisionsX failed" << std::endl; + } + + if (2 == MGlobal::optionVarIntValue(polyCube_subdivisionsY, &exists)) { + result = exists && result; + } else { + result = false; + std::cout << "polyCube_subdivisionsY failed" << std::endl; + } + + if (3 == MGlobal::optionVarIntValue(polyCube_subdivisionsZ, &exists)) { + result = exists && result; + } else { + result = false; + std::cout << "polyCube_subdivisionsZ failed" << std::endl; + } + + // create up after ourselves + if (0) { + if (MGlobal::optionVarExists(polyCube_constructionHistory)) + MGlobal::removeOptionVar(polyCube_constructionHistory); + if (MGlobal::optionVarExists(polyCube_width)) + MGlobal::removeOptionVar(polyCube_width); + if (MGlobal::optionVarExists(polyCube_height)) + MGlobal::removeOptionVar(polyCube_height); + if (MGlobal::optionVarExists(polyCube_depth)) + MGlobal::removeOptionVar(polyCube_depth); + if (MGlobal::optionVarExists(polyCube_subdivisionsX)) + MGlobal::removeOptionVar(polyCube_subdivisionsX); + if (MGlobal::optionVarExists(polyCube_subdivisionsY)) + MGlobal::removeOptionVar(polyCube_subdivisionsY); + if (MGlobal::optionVarExists(polyCube_subdivisionsZ)) + MGlobal::removeOptionVar(polyCube_subdivisionsZ); + if (MGlobal::optionVarExists(polyCube_name)) + MGlobal::removeOptionVar(polyCube_name); + if (MGlobal::optionVarExists(polyCube_axis)) + MGlobal::removeOptionVar(polyCube_axis); + } + return result; } //---------------------------------------------------------------------------------------------------------------------- -} // utils -} // tests -} // maya -} // AL +} // namespace utils +} // namespace tests +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/CommandGuiHelperTest.h b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/CommandGuiHelperTest.h index ae95997655..c04de4e166 100644 --- a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/CommandGuiHelperTest.h +++ b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/CommandGuiHelperTest.h @@ -24,25 +24,24 @@ namespace tests { namespace utils { //---------------------------------------------------------------------------------------------------------------------- -// A very simple test command that adds in all combinations of command argument, used to test the CommandGuiHelper class. +// A very simple test command that adds in all combinations of command argument, used to test the +// CommandGuiHelper class. //---------------------------------------------------------------------------------------------------------------------- #ifndef AL_GENERATING_DOCS -class CommandGuiHelperTestCMD - : public MPxCommand +class CommandGuiHelperTestCMD : public MPxCommand { public: - - static const MString kName; - static MSyntax createSyntax(); - static void makeGUI(); - static void* creator(); - MStatus doIt(const MArgList& args) override; + static const MString kName; + static MSyntax createSyntax(); + static void makeGUI(); + static void* creator(); + MStatus doIt(const MArgList& args) override; }; #endif //---------------------------------------------------------------------------------------------------------------------- -} // utils -} // tests -} // maya -} // AL +} // namespace utils +} // namespace tests +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/NodeHelperUnitTest.cpp b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/NodeHelperUnitTest.cpp index 001ef2603f..a050f4b6d3 100644 --- a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/NodeHelperUnitTest.cpp +++ b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/NodeHelperUnitTest.cpp @@ -15,14 +15,14 @@ // #include "AL/maya/tests/mayaplugintest/utils/NodeHelperUnitTest.h" -#include -#include +#include +#include #include +#include +#include #include -#include -#include #include -#include +#include #include @@ -34,330 +34,376 @@ namespace utils { //---------------------------------------------------------------------------------------------------------------------- const MString NodeHelperUnitTest::kTypeName = "AL_usdmaya_NodeHelperUnitTest"; const MTypeId NodeHelperUnitTest::kTypeId(0x4321); -MObject NodeHelperUnitTest::loadFilename; -MObject NodeHelperUnitTest::saveFilename; -MObject NodeHelperUnitTest::directoryWithFile; -MObject NodeHelperUnitTest::directory; -MObject NodeHelperUnitTest::multiFile; -MObject NodeHelperUnitTest::inPreFrame; -MObject NodeHelperUnitTest::inBool; -MObject NodeHelperUnitTest::inInt8; -MObject NodeHelperUnitTest::inInt16; -MObject NodeHelperUnitTest::inInt32; -MObject NodeHelperUnitTest::inInt64; -MObject NodeHelperUnitTest::inFloat; -MObject NodeHelperUnitTest::inDouble; -MObject NodeHelperUnitTest::inPoint; -MObject NodeHelperUnitTest::inFloatPoint; -MObject NodeHelperUnitTest::inVector; -MObject NodeHelperUnitTest::inFloatVector; -MObject NodeHelperUnitTest::inString; -MObject NodeHelperUnitTest::inColour; -MObject NodeHelperUnitTest::inMatrix; -MObject NodeHelperUnitTest::inBoolHidden; -MObject NodeHelperUnitTest::inInt8Hidden; -MObject NodeHelperUnitTest::inInt16Hidden; -MObject NodeHelperUnitTest::inInt32Hidden; -MObject NodeHelperUnitTest::inInt64Hidden; -MObject NodeHelperUnitTest::inFloatHidden; -MObject NodeHelperUnitTest::inDoubleHidden; -MObject NodeHelperUnitTest::inPointHidden; -MObject NodeHelperUnitTest::inFloatPointHidden; -MObject NodeHelperUnitTest::inVectorHidden; -MObject NodeHelperUnitTest::inFloatVectorHidden; -MObject NodeHelperUnitTest::inStringHidden; -MObject NodeHelperUnitTest::inColourHidden; -MObject NodeHelperUnitTest::inMatrixHidden; -MObject NodeHelperUnitTest::outBool; -MObject NodeHelperUnitTest::outInt8; -MObject NodeHelperUnitTest::outInt16; -MObject NodeHelperUnitTest::outInt32; -MObject NodeHelperUnitTest::outInt64; -MObject NodeHelperUnitTest::outFloat; -MObject NodeHelperUnitTest::outDouble; -MObject NodeHelperUnitTest::outPoint; -MObject NodeHelperUnitTest::outFloatPoint; -MObject NodeHelperUnitTest::outVector; -MObject NodeHelperUnitTest::outFloatVector; -MObject NodeHelperUnitTest::outString; -MObject NodeHelperUnitTest::outColour; -MObject NodeHelperUnitTest::outMatrix; +MObject NodeHelperUnitTest::loadFilename; +MObject NodeHelperUnitTest::saveFilename; +MObject NodeHelperUnitTest::directoryWithFile; +MObject NodeHelperUnitTest::directory; +MObject NodeHelperUnitTest::multiFile; +MObject NodeHelperUnitTest::inPreFrame; +MObject NodeHelperUnitTest::inBool; +MObject NodeHelperUnitTest::inInt8; +MObject NodeHelperUnitTest::inInt16; +MObject NodeHelperUnitTest::inInt32; +MObject NodeHelperUnitTest::inInt64; +MObject NodeHelperUnitTest::inFloat; +MObject NodeHelperUnitTest::inDouble; +MObject NodeHelperUnitTest::inPoint; +MObject NodeHelperUnitTest::inFloatPoint; +MObject NodeHelperUnitTest::inVector; +MObject NodeHelperUnitTest::inFloatVector; +MObject NodeHelperUnitTest::inString; +MObject NodeHelperUnitTest::inColour; +MObject NodeHelperUnitTest::inMatrix; +MObject NodeHelperUnitTest::inBoolHidden; +MObject NodeHelperUnitTest::inInt8Hidden; +MObject NodeHelperUnitTest::inInt16Hidden; +MObject NodeHelperUnitTest::inInt32Hidden; +MObject NodeHelperUnitTest::inInt64Hidden; +MObject NodeHelperUnitTest::inFloatHidden; +MObject NodeHelperUnitTest::inDoubleHidden; +MObject NodeHelperUnitTest::inPointHidden; +MObject NodeHelperUnitTest::inFloatPointHidden; +MObject NodeHelperUnitTest::inVectorHidden; +MObject NodeHelperUnitTest::inFloatVectorHidden; +MObject NodeHelperUnitTest::inStringHidden; +MObject NodeHelperUnitTest::inColourHidden; +MObject NodeHelperUnitTest::inMatrixHidden; +MObject NodeHelperUnitTest::outBool; +MObject NodeHelperUnitTest::outInt8; +MObject NodeHelperUnitTest::outInt16; +MObject NodeHelperUnitTest::outInt32; +MObject NodeHelperUnitTest::outInt64; +MObject NodeHelperUnitTest::outFloat; +MObject NodeHelperUnitTest::outDouble; +MObject NodeHelperUnitTest::outPoint; +MObject NodeHelperUnitTest::outFloatPoint; +MObject NodeHelperUnitTest::outVector; +MObject NodeHelperUnitTest::outFloatVector; +MObject NodeHelperUnitTest::outString; +MObject NodeHelperUnitTest::outColour; +MObject NodeHelperUnitTest::outMatrix; //---------------------------------------------------------------------------------------------------------------------- -void* NodeHelperUnitTest::creator() -{ - return new NodeHelperUnitTest; -} +void* NodeHelperUnitTest::creator() { return new NodeHelperUnitTest; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelperUnitTest::initialise() { - try - { - setNodeType(kTypeName); + try { + setNodeType(kTypeName); - addFrame("Fabrice"); - // just for fabrice :) - inPreFrame = addBoolAttr("perFrameAttr", "pfaattrh", true, kReadable | kWritable | kStorable | kKeyable | kHidden); + addFrame("Fabrice"); + // just for fabrice :) + inPreFrame = addBoolAttr( + "perFrameAttr", + "pfaattrh", + true, + kReadable | kWritable | kStorable | kKeyable | kHidden); - addFrame("file"); - loadFilename = addFilePathAttr("loadFilename", "lfp", kReadable | kWritable | kStorable, kLoad, "USD Files (*.usd*) (*.usd*);;Alembic Files (*.abc) (*.abc);;All files (*.*) (*.*)"); - saveFilename = addFilePathAttr("saveFilename", "sfp", kReadable | kWritable | kStorable, kSave, "USD Files (*.usd*) (*.usd*);;Alembic Files (*.abc) (*.abc)"); - directoryWithFile = addFilePathAttr("directoryWithFile", "dwf", kReadable | kWritable | kStorable, kDirectoryWithFiles); - directory = addFilePathAttr("directory", "dir", kReadable | kWritable | kStorable, kDirectory); - multiFile = addFilePathAttr("multiFile", "mf", kReadable | kWritable | kStorable, kMultiLoad); + addFrame("file"); + loadFilename = addFilePathAttr( + "loadFilename", + "lfp", + kReadable | kWritable | kStorable, + kLoad, + "USD Files (*.usd*) (*.usd*);;Alembic Files (*.abc) (*.abc);;All files (*.*) (*.*)"); + saveFilename = addFilePathAttr( + "saveFilename", + "sfp", + kReadable | kWritable | kStorable, + kSave, + "USD Files (*.usd*) (*.usd*);;Alembic Files (*.abc) (*.abc)"); + directoryWithFile = addFilePathAttr( + "directoryWithFile", "dwf", kReadable | kWritable | kStorable, kDirectoryWithFiles); + directory + = addFilePathAttr("directory", "dir", kReadable | kWritable | kStorable, kDirectory); + multiFile + = addFilePathAttr("multiFile", "mf", kReadable | kWritable | kStorable, kMultiLoad); - addFrame("hello"); - inBool = addBoolAttr("boolAttr", "battr", true, kReadable | kWritable | kStorable | kKeyable); - inBoolHidden = addBoolAttr("boolAttrHidden", "battrh", true, kReadable | kWritable | kStorable | kKeyable | kHidden); - inInt8 = addInt8Attr("int8Attr", "i8attr", 69, kReadable | kWritable | kStorable | kKeyable); - inInt8Hidden = addInt8Attr("int8AttrHidden", "i8attrh", 69, kReadable | kWritable | kStorable | kKeyable | kHidden); - inInt16 = addInt16Attr("int16Attr", "i16attr", 69, kReadable | kWritable | kStorable | kKeyable); - inInt16Hidden = addInt16Attr("int16AttrHidden", "i16attrh", 69, kReadable | kWritable | kStorable | kKeyable | kHidden); - inInt32 = addInt32Attr("int32Attr", "i32attr", 69, kReadable | kWritable | kStorable | kKeyable); - inInt32Hidden = addInt32Attr("int32AttrHidden", "i32attrh", 69, kReadable | kWritable | kStorable | kKeyable | kHidden); - inInt64 = addInt64Attr("int64Attr", "i64attr", 69, kReadable | kWritable | kStorable | kKeyable); - inInt64Hidden = addInt64Attr("int64AttrHidden", "i64attrh", 69, kReadable | kWritable | kStorable | kKeyable | kHidden); - inFloat = addFloatAttr("floatAttr", "fattr", 42.0f, kReadable | kWritable | kStorable | kKeyable); - inFloatHidden = addFloatAttr("floatAttrHidden", "fattrh", 42.0f, kReadable | kWritable | kStorable | kKeyable | kHidden); - inDouble = addDoubleAttr("doubleAttr", "dattr", 21.0f, kReadable | kWritable | kStorable | kKeyable); - inDoubleHidden = addDoubleAttr("doubleAttrHidden", "dattrh", 21.0f, kReadable | kWritable | kStorable | kKeyable | kHidden); + addFrame("hello"); + inBool + = addBoolAttr("boolAttr", "battr", true, kReadable | kWritable | kStorable | kKeyable); + inBoolHidden = addBoolAttr( + "boolAttrHidden", + "battrh", + true, + kReadable | kWritable | kStorable | kKeyable | kHidden); + inInt8 + = addInt8Attr("int8Attr", "i8attr", 69, kReadable | kWritable | kStorable | kKeyable); + inInt8Hidden = addInt8Attr( + "int8AttrHidden", + "i8attrh", + 69, + kReadable | kWritable | kStorable | kKeyable | kHidden); + inInt16 = addInt16Attr( + "int16Attr", "i16attr", 69, kReadable | kWritable | kStorable | kKeyable); + inInt16Hidden = addInt16Attr( + "int16AttrHidden", + "i16attrh", + 69, + kReadable | kWritable | kStorable | kKeyable | kHidden); + inInt32 = addInt32Attr( + "int32Attr", "i32attr", 69, kReadable | kWritable | kStorable | kKeyable); + inInt32Hidden = addInt32Attr( + "int32AttrHidden", + "i32attrh", + 69, + kReadable | kWritable | kStorable | kKeyable | kHidden); + inInt64 = addInt64Attr( + "int64Attr", "i64attr", 69, kReadable | kWritable | kStorable | kKeyable); + inInt64Hidden = addInt64Attr( + "int64AttrHidden", + "i64attrh", + 69, + kReadable | kWritable | kStorable | kKeyable | kHidden); + inFloat = addFloatAttr( + "floatAttr", "fattr", 42.0f, kReadable | kWritable | kStorable | kKeyable); + inFloatHidden = addFloatAttr( + "floatAttrHidden", + "fattrh", + 42.0f, + kReadable | kWritable | kStorable | kKeyable | kHidden); + inDouble = addDoubleAttr( + "doubleAttr", "dattr", 21.0f, kReadable | kWritable | kStorable | kKeyable); + inDoubleHidden = addDoubleAttr( + "doubleAttrHidden", + "dattrh", + 21.0f, + kReadable | kWritable | kStorable | kKeyable | kHidden); - addFrame("world"); - inPoint = addPointAttr("pointAttr", "pattr", MPoint(2,3,4), kReadable | kWritable | kStorable | kKeyable); - inPointHidden = addPointAttr("pointAttrHidden", "pattrh", MPoint(2,3,4), kReadable | kWritable | kStorable | kKeyable | kHidden); - inFloatPoint = addFloatPointAttr("floatPointAttr", "fpattr", MFloatPoint(1,2,3), kReadable | kWritable | kStorable | kKeyable); - inFloatPointHidden = addFloatPointAttr("floatPointAttrHidden", "fpattrh", MFloatPoint(1,2,3), kReadable | kWritable | kStorable | kKeyable | kHidden); - inVector = addVectorAttr("vecAttr", "vattr", MPoint(2,3,4), kReadable | kWritable | kStorable | kKeyable); - inVectorHidden = addVectorAttr("vecAttrHidden", "vattrh", MPoint(2,3,4), kReadable | kWritable | kStorable | kKeyable | kHidden); - inFloatVector = addFloatVectorAttr("floatVecAttr", "fvattr", MFloatPoint(1,2,3), kReadable | kWritable | kStorable | kKeyable); - inFloatVectorHidden = addFloatVectorAttr("floatVecAttrHidden", "fvattrh", MFloatPoint(1,2,3), kReadable | kWritable | kStorable | kKeyable | kHidden); - inString = addStringAttr("stringAttr", "sattr", kReadable | kWritable | kStorable | kKeyable); - inStringHidden = addStringAttr("stringAttrHidden", "sattrh", kReadable | kWritable | kStorable | kKeyable | kHidden); - inColour = addColourAttr("colourAttr", "cattr", MColor(0.1f, 0.2f, 0.9f), kReadable | kWritable | kStorable | kKeyable); - inColourHidden = addColourAttr("colourAttrHidden", "cattrh", MColor(0.1f, 0.2f, 0.9f), kReadable | kWritable | kStorable | kKeyable | kHidden); - double fm[4][4] = { - {1, 2, 3, 4}, - {5, 6, 7, 8}, - {9, 10, 11, 12}, - {13, 14, 15, 16} - }; - MMatrix m(fm); - inMatrix = addMatrixAttr("matrixAttr", "mattr", m, kReadable | kWritable | kStorable | kKeyable); - inMatrixHidden = addMatrixAttr("matrixAttrHidden", "mattrh", m, kReadable | kWritable | kStorable | kKeyable | kHidden); + addFrame("world"); + inPoint = addPointAttr( + "pointAttr", "pattr", MPoint(2, 3, 4), kReadable | kWritable | kStorable | kKeyable); + inPointHidden = addPointAttr( + "pointAttrHidden", + "pattrh", + MPoint(2, 3, 4), + kReadable | kWritable | kStorable | kKeyable | kHidden); + inFloatPoint = addFloatPointAttr( + "floatPointAttr", + "fpattr", + MFloatPoint(1, 2, 3), + kReadable | kWritable | kStorable | kKeyable); + inFloatPointHidden = addFloatPointAttr( + "floatPointAttrHidden", + "fpattrh", + MFloatPoint(1, 2, 3), + kReadable | kWritable | kStorable | kKeyable | kHidden); + inVector = addVectorAttr( + "vecAttr", "vattr", MPoint(2, 3, 4), kReadable | kWritable | kStorable | kKeyable); + inVectorHidden = addVectorAttr( + "vecAttrHidden", + "vattrh", + MPoint(2, 3, 4), + kReadable | kWritable | kStorable | kKeyable | kHidden); + inFloatVector = addFloatVectorAttr( + "floatVecAttr", + "fvattr", + MFloatPoint(1, 2, 3), + kReadable | kWritable | kStorable | kKeyable); + inFloatVectorHidden = addFloatVectorAttr( + "floatVecAttrHidden", + "fvattrh", + MFloatPoint(1, 2, 3), + kReadable | kWritable | kStorable | kKeyable | kHidden); + inString + = addStringAttr("stringAttr", "sattr", kReadable | kWritable | kStorable | kKeyable); + inStringHidden = addStringAttr( + "stringAttrHidden", "sattrh", kReadable | kWritable | kStorable | kKeyable | kHidden); + inColour = addColourAttr( + "colourAttr", + "cattr", + MColor(0.1f, 0.2f, 0.9f), + kReadable | kWritable | kStorable | kKeyable); + inColourHidden = addColourAttr( + "colourAttrHidden", + "cattrh", + MColor(0.1f, 0.2f, 0.9f), + kReadable | kWritable | kStorable | kKeyable | kHidden); + double fm[4][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; + MMatrix m(fm); + inMatrix + = addMatrixAttr("matrixAttr", "mattr", m, kReadable | kWritable | kStorable | kKeyable); + inMatrixHidden = addMatrixAttr( + "matrixAttrHidden", + "mattrh", + m, + kReadable | kWritable | kStorable | kKeyable | kHidden); - outBool = addBoolAttr("boolAttrOut", "obattr", false, kReadable); - outInt8 = addInt8Attr("int8AttrOut", "oi8attr", 0, kReadable); - outInt16 = addInt16Attr("int16AttrOut", "oi16attr", 0, kReadable); - outInt32 = addInt32Attr("int32AttrOut", "oi32attr", 0, kReadable); - outInt64 = addInt64Attr("int64AttrOut", "oi64attr", 0, kReadable); - outFloat = addFloatAttr("floatAttrOut", "ofattr", 0, kReadable); - outDouble = addDoubleAttr("doubleAttrOut", "odattr", 0, kReadable); - outPoint = addPointAttr("pointAttrOut", "opattr", MPoint(), kReadable); - outFloatPoint = addFloatPointAttr("floatPointAttrOut", "ofpattr", MFloatPoint(), kReadable); - outVector = addVectorAttr("vecAttrOut", "ovattr", MPoint(), kReadable); - outFloatVector = addFloatVectorAttr("floatVecAttrOut", "ofvattr", MFloatPoint(), kReadable); - outString = addStringAttr("stringAttrOut", "osattr", kReadable); - outColour = addColourAttr("colourAttrOut", "ocattr", MColor(), kReadable); - outMatrix = addMatrixAttr("matrixAttrOut", "omattr", MMatrix(), kReadable); - } - catch(const MStatus& status) - { - return status; - } + outBool = addBoolAttr("boolAttrOut", "obattr", false, kReadable); + outInt8 = addInt8Attr("int8AttrOut", "oi8attr", 0, kReadable); + outInt16 = addInt16Attr("int16AttrOut", "oi16attr", 0, kReadable); + outInt32 = addInt32Attr("int32AttrOut", "oi32attr", 0, kReadable); + outInt64 = addInt64Attr("int64AttrOut", "oi64attr", 0, kReadable); + outFloat = addFloatAttr("floatAttrOut", "ofattr", 0, kReadable); + outDouble = addDoubleAttr("doubleAttrOut", "odattr", 0, kReadable); + outPoint = addPointAttr("pointAttrOut", "opattr", MPoint(), kReadable); + outFloatPoint = addFloatPointAttr("floatPointAttrOut", "ofpattr", MFloatPoint(), kReadable); + outVector = addVectorAttr("vecAttrOut", "ovattr", MPoint(), kReadable); + outFloatVector = addFloatVectorAttr("floatVecAttrOut", "ofvattr", MFloatPoint(), kReadable); + outString = addStringAttr("stringAttrOut", "osattr", kReadable); + outColour = addColourAttr("colourAttrOut", "ocattr", MColor(), kReadable); + outMatrix = addMatrixAttr("matrixAttrOut", "omattr", MMatrix(), kReadable); + } catch (const MStatus& status) { + return status; + } - attributeAffects(inBool, outBool); - attributeAffects(inInt8, outInt8); - attributeAffects(inInt16, outInt16); - attributeAffects(inInt32, outInt32); - attributeAffects(inInt64, outInt64); - attributeAffects(inFloat, outFloat); - attributeAffects(inDouble, outDouble); - attributeAffects(inPoint, outPoint); - attributeAffects(inFloatPoint, outFloatPoint); - attributeAffects(inVector, outVector); - attributeAffects(inFloatVector, outFloatVector); - attributeAffects(inString, outString); - attributeAffects(inColour, outColour); - attributeAffects(inMatrix, outMatrix); + attributeAffects(inBool, outBool); + attributeAffects(inInt8, outInt8); + attributeAffects(inInt16, outInt16); + attributeAffects(inInt32, outInt32); + attributeAffects(inInt64, outInt64); + attributeAffects(inFloat, outFloat); + attributeAffects(inDouble, outDouble); + attributeAffects(inPoint, outPoint); + attributeAffects(inFloatPoint, outFloatPoint); + attributeAffects(inVector, outVector); + attributeAffects(inFloatVector, outFloatVector); + attributeAffects(inString, outString); + attributeAffects(inColour, outColour); + attributeAffects(inMatrix, outMatrix); - generateAETemplate(); - return MS::kSuccess; + generateAETemplate(); + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus NodeHelperUnitTest::compute(const MPlug& plug, MDataBlock& datablock) { - if(plug == outBool) - { - return outputBoolValue(datablock, outBool, inputBoolValue(datablock, inBool)); - } - else - if(plug == outInt8) - { - return outputInt8Value(datablock, outInt8, inputInt8Value(datablock, inInt8)); - } - else - if(plug == outInt16) - { - return outputInt16Value(datablock, outInt16, inputInt16Value(datablock, inInt16)); - } - else - if(plug == outInt32) - { - return outputInt32Value(datablock, outInt32, inputInt32Value(datablock, inInt32)); - } - else - if(plug == outInt64) - { - return outputInt64Value(datablock, outInt64, inputInt64Value(datablock, inInt64)); - } - else - if(plug == outFloat) - { - return outputFloatValue(datablock, outFloat, inputFloatValue(datablock, inFloat)); - } - else - if(plug == outDouble) - { - return outputDoubleValue(datablock, outDouble, inputDoubleValue(datablock, inDouble)); - } - else - if(plug == outPoint) - { - return outputPointValue(datablock, outPoint, inputPointValue(datablock, inPoint)); - } - else - if(plug == outFloatPoint) - { - return outputFloatPointValue(datablock, outFloatPoint, inputFloatPointValue(datablock, inFloatPoint)); - } - else - if(plug == outVector) - { - return outputVectorValue(datablock, outVector, inputVectorValue(datablock, inVector)); - } - else - if(plug == outFloatVector) - { - return outputFloatVectorValue(datablock, outFloatVector, inputFloatVectorValue(datablock, inFloatVector)); - } - else - if(plug == outString) - { - return outputStringValue(datablock, outString, inputStringValue(datablock, inString)); - } - else - if(plug == outColour) - { - return outputColourValue(datablock, outColour, inputColourValue(datablock, inColour)); - } - else - if(plug == outMatrix) - { - return outputMatrixValue(datablock, outMatrix, inputMatrixValue(datablock, inMatrix)); - } - return MS::kInvalidParameter; + if (plug == outBool) { + return outputBoolValue(datablock, outBool, inputBoolValue(datablock, inBool)); + } else if (plug == outInt8) { + return outputInt8Value(datablock, outInt8, inputInt8Value(datablock, inInt8)); + } else if (plug == outInt16) { + return outputInt16Value(datablock, outInt16, inputInt16Value(datablock, inInt16)); + } else if (plug == outInt32) { + return outputInt32Value(datablock, outInt32, inputInt32Value(datablock, inInt32)); + } else if (plug == outInt64) { + return outputInt64Value(datablock, outInt64, inputInt64Value(datablock, inInt64)); + } else if (plug == outFloat) { + return outputFloatValue(datablock, outFloat, inputFloatValue(datablock, inFloat)); + } else if (plug == outDouble) { + return outputDoubleValue(datablock, outDouble, inputDoubleValue(datablock, inDouble)); + } else if (plug == outPoint) { + return outputPointValue(datablock, outPoint, inputPointValue(datablock, inPoint)); + } else if (plug == outFloatPoint) { + return outputFloatPointValue( + datablock, outFloatPoint, inputFloatPointValue(datablock, inFloatPoint)); + } else if (plug == outVector) { + return outputVectorValue(datablock, outVector, inputVectorValue(datablock, inVector)); + } else if (plug == outFloatVector) { + return outputFloatVectorValue( + datablock, outFloatVector, inputFloatVectorValue(datablock, inFloatVector)); + } else if (plug == outString) { + return outputStringValue(datablock, outString, inputStringValue(datablock, inString)); + } else if (plug == outColour) { + return outputColourValue(datablock, outColour, inputColourValue(datablock, inColour)); + } else if (plug == outMatrix) { + return outputMatrixValue(datablock, outMatrix, inputMatrixValue(datablock, inMatrix)); + } + return MS::kInvalidParameter; } //---------------------------------------------------------------------------------------------------------------------- #define MEL_SCRIPT(TEXT) #TEXT -static const char* const testScript = MEL_SCRIPT( -proc string compareAttributes() -{ - string $result = ""; - string $n = `createNode "NodeHelperUnitTest"`; - $boolIn = `getAttr ($n + ".boolAttr")`; - $boolOut = `getAttr ($n + ".boolAttrOut")`; - if($boolIn != $boolOut) $result += "boolAttr failed\n"; +static const char* const testScript = MEL_SCRIPT(proc string compareAttributes() { + string $result = ""; + string $n = `createNode "NodeHelperUnitTest"`; + $boolIn = `getAttr($n + ".boolAttr")`; + $boolOut = `getAttr($n + ".boolAttrOut")`; + if ($boolIn != $boolOut) + $result += "boolAttr failed\n"; - $intIn8 = `getAttr ($n + ".int8Attr")`; - $intOut8 = `getAttr ($n + ".int8AttrOut")`; - if($intIn8 != $intOut8) $result += "int8Attr failed\n"; + $intIn8 = `getAttr($n + ".int8Attr")`; + $intOut8 = `getAttr($n + ".int8AttrOut")`; + if ($intIn8 != $intOut8) + $result += "int8Attr failed\n"; - $intIn16 = `getAttr ($n + ".int16Attr")`; - $intOut16 = `getAttr ($n + ".int16AttrOut")`; - if($intIn16 != $intOut16) $result += "int16Attr failed\n"; + $intIn16 = `getAttr($n + ".int16Attr")`; + $intOut16 = `getAttr($n + ".int16AttrOut")`; + if ($intIn16 != $intOut16) + $result += "int16Attr failed\n"; - $intIn32 = `getAttr ($n + ".int32Attr")`; - $intOut32 = `getAttr ($n + ".int32AttrOut")`; - if($intIn32 != $intOut32) $result += "intAttr32 failed\n"; + $intIn32 = `getAttr($n + ".int32Attr")`; + $intOut32 = `getAttr($n + ".int32AttrOut")`; + if ($intIn32 != $intOut32) + $result += "intAttr32 failed\n"; - $intIn64 = `getAttr ($n + ".intAttr64")`; - $intOut64 = `getAttr ($n + ".intAttr64Out")`; - if($intIn64 != $intOut64) $result += "intAttr64 failed\n"; + $intIn64 = `getAttr($n + ".intAttr64")`; + $intOut64 = `getAttr($n + ".intAttr64Out")`; + if ($intIn64 != $intOut64) + $result += "intAttr64 failed\n"; - $floatIn = `getAttr ($n + ".floatAttr")`; - $floatOut = `getAttr ($n + ".floatAttrOut")`; - if($floatIn != $floatOut) $result += "floatAttr failed\n"; + $floatIn = `getAttr($n + ".floatAttr")`; + $floatOut = `getAttr($n + ".floatAttrOut")`; + if ($floatIn != $floatOut) + $result += "floatAttr failed\n"; - $doubleIn = `getAttr ($n + ".doubleAttr")`; - $doubleOut = `getAttr ($n + ".doubleAttrOut")`; - if($doubleIn != $doubleOut) $result += "doubleAttr failed\n"; + $doubleIn = `getAttr($n + ".doubleAttr")`; + $doubleOut = `getAttr($n + ".doubleAttrOut")`; + if ($doubleIn != $doubleOut) + $result += "doubleAttr failed\n"; - $pointAttrIn = `getAttr ($n + ".pointAttr")`; - $pointAttrOut = `getAttr ($n + ".pointAttrOut")`; - if($pointAttrIn[0] != $pointAttrOut[0] || - $pointAttrIn[1] != $pointAttrOut[1] || - $pointAttrIn[2] != $pointAttrOut[2]) $result += "pointAttr failed\n"; + $pointAttrIn = `getAttr($n + ".pointAttr")`; + $pointAttrOut = `getAttr($n + ".pointAttrOut")`; + if ($pointAttrIn[0] != $pointAttrOut[0] || $pointAttrIn[1] != $pointAttrOut[1] + || $pointAttrIn[2] != $pointAttrOut[2]) + $result += "pointAttr failed\n"; - $fpointAttrIn = `getAttr ($n + ".floatPointAttr")`; - $fpointAttrOut = `getAttr ($n + ".floatPointAttrOut")`; - if($fpointAttrIn[0] != $fpointAttrOut[0] || - $fpointAttrIn[1] != $fpointAttrOut[1] || - $fpointAttrIn[2] != $fpointAttrOut[2]) $result += "floatPointAttr failed\n"; + $fpointAttrIn = `getAttr($n + ".floatPointAttr")`; + $fpointAttrOut = `getAttr($n + ".floatPointAttrOut")`; + if ($fpointAttrIn[0] != $fpointAttrOut[0] || $fpointAttrIn[1] != $fpointAttrOut[1] + || $fpointAttrIn[2] != $fpointAttrOut[2]) + $result += "floatPointAttr failed\n"; - $fpointAttrIn = `getAttr ($n + ".vecAttr")`; - $fpointAttrOut = `getAttr ($n + ".vecAttrOut")`; - if($fpointAttrIn[0] != $fpointAttrOut[0] || - $fpointAttrIn[1] != $fpointAttrOut[1] || - $fpointAttrIn[2] != $fpointAttrOut[2]) $result += "vecAttr failed\n"; + $fpointAttrIn = `getAttr($n + ".vecAttr")`; + $fpointAttrOut = `getAttr($n + ".vecAttrOut")`; + if ($fpointAttrIn[0] != $fpointAttrOut[0] || $fpointAttrIn[1] != $fpointAttrOut[1] + || $fpointAttrIn[2] != $fpointAttrOut[2]) + $result += "vecAttr failed\n"; - $fpointAttrIn = `getAttr ($n + ".floatVecAttr")`; - $fpointAttrOut = `getAttr ($n + ".floatVecAttrOut")`; - if($fpointAttrIn[0] != $fpointAttrOut[0] || - $fpointAttrIn[1] != $fpointAttrOut[1] || - $fpointAttrIn[2] != $fpointAttrOut[2]) $result += "floatVecAttr failed\n"; + $fpointAttrIn = `getAttr($n + ".floatVecAttr")`; + $fpointAttrOut = `getAttr($n + ".floatVecAttrOut")`; + if ($fpointAttrIn[0] != $fpointAttrOut[0] || $fpointAttrIn[1] != $fpointAttrOut[1] + || $fpointAttrIn[2] != $fpointAttrOut[2]) + $result += "floatVecAttr failed\n"; - setAttr -type "string" ($n + ".stringAttr") "someText"; - $stringAttrIn = `getAttr ($n + ".stringAttr")`; - $stringAttrOut = `getAttr ($n + ".stringAttrOut")`; - if($stringAttrIn != $stringAttrOut) $result += "stringAttr failed\n"; + setAttr - type "string"($n + ".stringAttr") "someText"; + $stringAttrIn = `getAttr($n + ".stringAttr")`; + $stringAttrOut = `getAttr($n + ".stringAttrOut")`; + if ($stringAttrIn != $stringAttrOut) + $result += "stringAttr failed\n"; - $fpointAttrIn = `getAttr ($n + ".colourAttr")`; - $fpointAttrOut = `getAttr ($n + ".colourAttrOut")`; - if($fpointAttrIn[0] != $fpointAttrOut[0] || - $fpointAttrIn[1] != $fpointAttrOut[1] || - $fpointAttrIn[2] != $fpointAttrOut[2]) $result += "colourAttr failed\n"; + $fpointAttrIn = `getAttr($n + ".colourAttr")`; + $fpointAttrOut = `getAttr($n + ".colourAttrOut")`; + if ($fpointAttrIn[0] != $fpointAttrOut[0] || $fpointAttrIn[1] != $fpointAttrOut[1] + || $fpointAttrIn[2] != $fpointAttrOut[2]) + $result += "colourAttr failed\n"; - $mIn = `getAttr ($n + ".matrixAttr")`; - $mOut = `getAttr ($n + ".matrixAttrOut")`; - for($i = 0; $i < 16; $i++) - { - if($mIn[$i] != $mOut[$i]) { - $result += "matrixAttr Failed\n"; + $mIn = `getAttr($n + ".matrixAttr")`; + $mOut = `getAttr($n + ".matrixAttrOut")`; + for ($i = 0; $i < 16; $i++) { + if ($mIn[$i] != $mOut[$i]) { + $result += "matrixAttr Failed\n"; + } } - } - delete $n; - return $result; -} -compareAttributes(); -); + delete $n; + return $result; +} compareAttributes();); //---------------------------------------------------------------------------------------------------------------------- void NodeHelperUnitTest::runUnitTest() { - MString result; - MGlobal::executeCommand(testScript, result); - if(result.length()) - { - std::cout << "NodeHelperUnitTest failed\n" << result.length() << "\n"; - } + MString result; + MGlobal::executeCommand(testScript, result); + if (result.length()) { + std::cout << "NodeHelperUnitTest failed\n" << result.length() << "\n"; + } } //---------------------------------------------------------------------------------------------------------------------- -} // utils -} // tests -} // maya -} // AL +} // namespace utils +} // namespace tests +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/NodeHelperUnitTest.h b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/NodeHelperUnitTest.h index f88fcf79df..67f2b7b033 100644 --- a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/NodeHelperUnitTest.h +++ b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/NodeHelperUnitTest.h @@ -27,74 +27,72 @@ namespace utils { //---------------------------------------------------------------------------------------------------------------------- #ifndef AL_GENERATING_DOCS class NodeHelperUnitTest -: public AL::maya::utils::NodeHelper, - public MPxNode + : public AL::maya::utils::NodeHelper + , public MPxNode { public: - - static void* creator(); - static MStatus initialise(); - static const MString kTypeName; - static const MTypeId kTypeId; - static void runUnitTest(); + static void* creator(); + static MStatus initialise(); + static const MString kTypeName; + static const MTypeId kTypeId; + static void runUnitTest(); private: + MStatus compute(const MPlug& plug, MDataBlock& datablock) override; - MStatus compute(const MPlug &plug, MDataBlock &datablock) override; - - static MObject loadFilename; - static MObject saveFilename; - static MObject directoryWithFile; - static MObject directory; - static MObject multiFile; - static MObject inPreFrame; - static MObject inBool; - static MObject inBoolHidden; - static MObject inInt8; - static MObject inInt8Hidden; - static MObject inInt16; - static MObject inInt16Hidden; - static MObject inInt32; - static MObject inInt32Hidden; - static MObject inInt64; - static MObject inInt64Hidden; - static MObject inFloat; - static MObject inFloatHidden; - static MObject inDouble; - static MObject inDoubleHidden; - static MObject inPoint; - static MObject inPointHidden; - static MObject inFloatPoint; - static MObject inFloatPointHidden; - static MObject inVector; - static MObject inVectorHidden; - static MObject inFloatVector; - static MObject inFloatVectorHidden; - static MObject inString; - static MObject inStringHidden; - static MObject inColour; - static MObject inColourHidden; - static MObject inMatrix; - static MObject inMatrixHidden; - static MObject outBool; - static MObject outInt8; - static MObject outInt16; - static MObject outInt32; - static MObject outInt64; - static MObject outFloat; - static MObject outDouble; - static MObject outPoint; - static MObject outFloatPoint; - static MObject outVector; - static MObject outFloatVector; - static MObject outString; - static MObject outColour; - static MObject outMatrix; + static MObject loadFilename; + static MObject saveFilename; + static MObject directoryWithFile; + static MObject directory; + static MObject multiFile; + static MObject inPreFrame; + static MObject inBool; + static MObject inBoolHidden; + static MObject inInt8; + static MObject inInt8Hidden; + static MObject inInt16; + static MObject inInt16Hidden; + static MObject inInt32; + static MObject inInt32Hidden; + static MObject inInt64; + static MObject inInt64Hidden; + static MObject inFloat; + static MObject inFloatHidden; + static MObject inDouble; + static MObject inDoubleHidden; + static MObject inPoint; + static MObject inPointHidden; + static MObject inFloatPoint; + static MObject inFloatPointHidden; + static MObject inVector; + static MObject inVectorHidden; + static MObject inFloatVector; + static MObject inFloatVectorHidden; + static MObject inString; + static MObject inStringHidden; + static MObject inColour; + static MObject inColourHidden; + static MObject inMatrix; + static MObject inMatrixHidden; + static MObject outBool; + static MObject outInt8; + static MObject outInt16; + static MObject outInt32; + static MObject outInt64; + static MObject outFloat; + static MObject outDouble; + static MObject outPoint; + static MObject outFloatPoint; + static MObject outVector; + static MObject outFloatVector; + static MObject outString; + static MObject outColour; + static MObject outMatrix; }; #endif //---------------------------------------------------------------------------------------------------------------------- -} // utils -} // tests -} // maya -} // AL +} // namespace utils +} // namespace tests +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/PluginTranslatorOptionsTest.cpp b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/PluginTranslatorOptionsTest.cpp index cc3222db14..e0c96db91b 100644 --- a/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/PluginTranslatorOptionsTest.cpp +++ b/plugin/al/mayautils/AL/maya/tests/mayaplugintest/utils/PluginTranslatorOptionsTest.cpp @@ -1,224 +1,228 @@ #include "AL/maya/utils/PluginTranslatorOptions.h" + #include #include + #include using namespace AL::maya::utils; //---------------------------------------------------------------------------------------------------------------------- -// void PluginTranslatorOptionsContext::registerPluginTranslatorOptions(PluginTranslatorOptions* options); -// void PluginTranslatorOptionsContext::unregisterPluginTranslatorOptions(const char* const pluginTranslatorGrouping); -// bool PluginTranslatorOptionsContext::isRegistered(const char* const pluginTranslatorGrouping) const; -// const MString& PluginTranslatorOptions::grouping() const; +// void PluginTranslatorOptionsContext::registerPluginTranslatorOptions(PluginTranslatorOptions* +// options); void PluginTranslatorOptionsContext::unregisterPluginTranslatorOptions(const char* +// const pluginTranslatorGrouping); bool PluginTranslatorOptionsContext::isRegistered(const char* +// const pluginTranslatorGrouping) const; const MString& PluginTranslatorOptions::grouping() const; //---------------------------------------------------------------------------------------------------------------------- TEST(maya_PluginTranslatorOptionsContext, registerPluginTranslatorOptions) { - PluginTranslatorOptionsContext ctx; - EXPECT_FALSE(ctx.isRegistered("testOptions")); - { - PluginTranslatorOptions options(ctx, "testOptions"); - EXPECT_TRUE(ctx.isRegistered("testOptions")); - EXPECT_EQ(MString("testOptions"), options.grouping()); - } - EXPECT_FALSE(ctx.isRegistered("testOptions")); + PluginTranslatorOptionsContext ctx; + EXPECT_FALSE(ctx.isRegistered("testOptions")); + { + PluginTranslatorOptions options(ctx, "testOptions"); + EXPECT_TRUE(ctx.isRegistered("testOptions")); + EXPECT_EQ(MString("testOptions"), options.grouping()); + } + EXPECT_FALSE(ctx.isRegistered("testOptions")); } //---------------------------------------------------------------------------------------------------------------------- -// bool PluginTranslatorOptions::addBool(const char* optionName, bool defaultValue = false, Mode mode = kBoth); +// bool PluginTranslatorOptions::addBool(const char* optionName, bool defaultValue = false, Mode +// mode = kBoth); TEST(maya_PluginTranslatorOptionsContext, addBool) { - PluginTranslatorOptionsContext ctx; - PluginTranslatorOptions options(ctx, "testOptions"); - - // check we can register the option - EXPECT_TRUE(options.addBool("option1", true)); - - // make sure it fails if we try to register the same option again - EXPECT_FALSE(options.addBool("option1", true)); - EXPECT_TRUE(options.isOption("option1")); - EXPECT_EQ(true, options.defaultBool("option1")); - EXPECT_EQ(OptionType::kBool, options.optionType("option1")); - - // register a second option to validate alternate values - EXPECT_TRUE(options.addBool("option2", false)); - EXPECT_TRUE(options.isOption("option1")); - EXPECT_TRUE(options.isOption("option2")); - EXPECT_FALSE(options.defaultBool("option2")); - - PluginTranslatorOptionsInstance instance(ctx); - EXPECT_TRUE(instance.getBool("option1")); - EXPECT_FALSE(instance.getBool("option2")); - instance.setBool("option1", true); - EXPECT_TRUE(instance.getBool("option1")); - instance.setBool("option1", false); - EXPECT_FALSE(instance.getBool("option1")); + PluginTranslatorOptionsContext ctx; + PluginTranslatorOptions options(ctx, "testOptions"); + + // check we can register the option + EXPECT_TRUE(options.addBool("option1", true)); + + // make sure it fails if we try to register the same option again + EXPECT_FALSE(options.addBool("option1", true)); + EXPECT_TRUE(options.isOption("option1")); + EXPECT_EQ(true, options.defaultBool("option1")); + EXPECT_EQ(OptionType::kBool, options.optionType("option1")); + + // register a second option to validate alternate values + EXPECT_TRUE(options.addBool("option2", false)); + EXPECT_TRUE(options.isOption("option1")); + EXPECT_TRUE(options.isOption("option2")); + EXPECT_FALSE(options.defaultBool("option2")); + + PluginTranslatorOptionsInstance instance(ctx); + EXPECT_TRUE(instance.getBool("option1")); + EXPECT_FALSE(instance.getBool("option2")); + instance.setBool("option1", true); + EXPECT_TRUE(instance.getBool("option1")); + instance.setBool("option1", false); + EXPECT_FALSE(instance.getBool("option1")); } //---------------------------------------------------------------------------------------------------------------------- -// bool PluginTranslatorOptions::addInt(const char* optionName, int defaultValue = 0, Mode mode = kBoth); +// bool PluginTranslatorOptions::addInt(const char* optionName, int defaultValue = 0, Mode mode = +// kBoth); TEST(maya_PluginTranslatorOptionsContext, addInt) { - PluginTranslatorOptionsContext ctx; - PluginTranslatorOptions options(ctx, "testOptions"); - - // check we can register the option - EXPECT_TRUE(options.addInt("option1", 42)); - - // make sure it fails if we try to register the same option again - EXPECT_FALSE(options.addInt("option1", 42)); - EXPECT_TRUE(options.isOption("option1")); - EXPECT_EQ(OptionType::kInt, options.optionType("option1")); - EXPECT_EQ(42, options.defaultInt("option1")); - - // register a second option to validate alternate values - EXPECT_TRUE(options.addInt("option2", 44)); - EXPECT_TRUE(options.isOption("option1")); - EXPECT_TRUE(options.isOption("option2")); - EXPECT_EQ(44, options.defaultInt("option2")); - - PluginTranslatorOptionsInstance instance(ctx); - EXPECT_EQ(42, instance.getInt("option1")); - EXPECT_EQ(44, instance.getInt("option2")); - instance.setInt("option1", 52); - EXPECT_EQ(52, instance.getInt("option1")); - instance.setInt("option1", 54); - EXPECT_EQ(54, instance.getInt("option1")); + PluginTranslatorOptionsContext ctx; + PluginTranslatorOptions options(ctx, "testOptions"); + + // check we can register the option + EXPECT_TRUE(options.addInt("option1", 42)); + + // make sure it fails if we try to register the same option again + EXPECT_FALSE(options.addInt("option1", 42)); + EXPECT_TRUE(options.isOption("option1")); + EXPECT_EQ(OptionType::kInt, options.optionType("option1")); + EXPECT_EQ(42, options.defaultInt("option1")); + + // register a second option to validate alternate values + EXPECT_TRUE(options.addInt("option2", 44)); + EXPECT_TRUE(options.isOption("option1")); + EXPECT_TRUE(options.isOption("option2")); + EXPECT_EQ(44, options.defaultInt("option2")); + + PluginTranslatorOptionsInstance instance(ctx); + EXPECT_EQ(42, instance.getInt("option1")); + EXPECT_EQ(44, instance.getInt("option2")); + instance.setInt("option1", 52); + EXPECT_EQ(52, instance.getInt("option1")); + instance.setInt("option1", 54); + EXPECT_EQ(54, instance.getInt("option1")); } //---------------------------------------------------------------------------------------------------------------------- -// bool PluginTranslatorOptions::addFloat(const char* optionName, float defaultValue = 0.0f, Mode mode = kBoth); +// bool PluginTranslatorOptions::addFloat(const char* optionName, float defaultValue = 0.0f, Mode +// mode = kBoth); TEST(maya_PluginTranslatorOptionsContext, addFloat) { - PluginTranslatorOptionsContext ctx; - PluginTranslatorOptions options(ctx, "testOptions"); - - // check we can register the option - EXPECT_TRUE(options.addFloat("option1", 13.24f)); - - // make sure it fails if we try to register the same option again - EXPECT_FALSE(options.addFloat("option1", 13.25f)); - EXPECT_TRUE(options.isOption("option1")); - EXPECT_EQ(OptionType::kFloat, options.optionType("option1")); - EXPECT_EQ(13.24f, options.defaultFloat("option1")); - - // register a second option to validate alternate values - EXPECT_TRUE(options.addFloat("option2", 23.24f)); - EXPECT_TRUE(options.isOption("option1")); - EXPECT_TRUE(options.isOption("option2")); - EXPECT_EQ(23.24f, options.defaultFloat("option2")); - - PluginTranslatorOptionsInstance instance(ctx); - EXPECT_EQ(13.24f, instance.getFloat("option1")); - EXPECT_EQ(23.24f, instance.getFloat("option2")); - instance.setFloat("option1", 12.24f); - EXPECT_EQ(12.24f, instance.getFloat("option1")); - instance.setFloat("option1", 11.24f); - EXPECT_EQ(11.24f, instance.getFloat("option1")); + PluginTranslatorOptionsContext ctx; + PluginTranslatorOptions options(ctx, "testOptions"); + + // check we can register the option + EXPECT_TRUE(options.addFloat("option1", 13.24f)); + + // make sure it fails if we try to register the same option again + EXPECT_FALSE(options.addFloat("option1", 13.25f)); + EXPECT_TRUE(options.isOption("option1")); + EXPECT_EQ(OptionType::kFloat, options.optionType("option1")); + EXPECT_EQ(13.24f, options.defaultFloat("option1")); + + // register a second option to validate alternate values + EXPECT_TRUE(options.addFloat("option2", 23.24f)); + EXPECT_TRUE(options.isOption("option1")); + EXPECT_TRUE(options.isOption("option2")); + EXPECT_EQ(23.24f, options.defaultFloat("option2")); + + PluginTranslatorOptionsInstance instance(ctx); + EXPECT_EQ(13.24f, instance.getFloat("option1")); + EXPECT_EQ(23.24f, instance.getFloat("option2")); + instance.setFloat("option1", 12.24f); + EXPECT_EQ(12.24f, instance.getFloat("option1")); + instance.setFloat("option1", 11.24f); + EXPECT_EQ(11.24f, instance.getFloat("option1")); } //---------------------------------------------------------------------------------------------------------------------- -// bool PluginTranslatorOptions::addString(const char* optionName, const char* const defaultValue = "", Mode mode = kBoth); +// bool PluginTranslatorOptions::addString(const char* optionName, const char* const defaultValue = +// "", Mode mode = kBoth); TEST(maya_PluginTranslatorOptionsContext, addString) { - PluginTranslatorOptionsContext ctx; - PluginTranslatorOptions options(ctx, "testOptions"); - - // check we can register the option - EXPECT_TRUE(options.addString("option1", "hello")); - - // make sure it fails if we try to register the same option again - EXPECT_FALSE(options.addString("option1", "hel2lo")); - EXPECT_TRUE(options.isOption("option1")); - EXPECT_EQ(OptionType::kString, options.optionType("option1")); - EXPECT_EQ(MString("hello"), options.defaultString("option1")); - - // register a second option to validate alternate values - EXPECT_TRUE(options.addString("option2", "byebye")); - EXPECT_TRUE(options.isOption("option1")); - EXPECT_TRUE(options.isOption("option2")); - EXPECT_EQ(MString("byebye"), options.defaultString("option2")); - - PluginTranslatorOptionsInstance instance(ctx); - EXPECT_EQ(MString("hello"), instance.getString("option1")); - EXPECT_EQ(MString("byebye"), instance.getString("option2")); - instance.setString("option1", "hello"); - EXPECT_EQ(MString("hello"), instance.getString("option1")); - instance.setString("option1", "hello2"); - EXPECT_EQ(MString("hello2"), instance.getString("option1")); + PluginTranslatorOptionsContext ctx; + PluginTranslatorOptions options(ctx, "testOptions"); + + // check we can register the option + EXPECT_TRUE(options.addString("option1", "hello")); + + // make sure it fails if we try to register the same option again + EXPECT_FALSE(options.addString("option1", "hel2lo")); + EXPECT_TRUE(options.isOption("option1")); + EXPECT_EQ(OptionType::kString, options.optionType("option1")); + EXPECT_EQ(MString("hello"), options.defaultString("option1")); + + // register a second option to validate alternate values + EXPECT_TRUE(options.addString("option2", "byebye")); + EXPECT_TRUE(options.isOption("option1")); + EXPECT_TRUE(options.isOption("option2")); + EXPECT_EQ(MString("byebye"), options.defaultString("option2")); + + PluginTranslatorOptionsInstance instance(ctx); + EXPECT_EQ(MString("hello"), instance.getString("option1")); + EXPECT_EQ(MString("byebye"), instance.getString("option2")); + instance.setString("option1", "hello"); + EXPECT_EQ(MString("hello"), instance.getString("option1")); + instance.setString("option1", "hello2"); + EXPECT_EQ(MString("hello2"), instance.getString("option1")); } //---------------------------------------------------------------------------------------------------------------------- -// bool PluginTranslatorOptions::addEnum(const char* optionName, const char* const enumValues[], int defaultValue = 0, Mode mode = kBoth); +// bool PluginTranslatorOptions::addEnum(const char* optionName, const char* const enumValues[], +// int defaultValue = 0, Mode mode = kBoth); TEST(maya_PluginTranslatorOptionsContext, addEnum) { - PluginTranslatorOptionsContext ctx; - PluginTranslatorOptions options(ctx, "testOptions"); - - const char* const enumVals[] = { - "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", 0 - }; - - // check we can register the option - EXPECT_TRUE(options.addEnum("option1", enumVals, 3)); - - // make sure it fails if we try to register the same option again - EXPECT_FALSE(options.addEnum("option1", enumVals, 2)); - EXPECT_TRUE(options.isOption("option1")); - EXPECT_EQ(OptionType::kEnum, options.optionType("option1")); - EXPECT_EQ(3, options.defaultInt("option1")); - - // register a second option to validate alternate values - EXPECT_TRUE(options.addEnum("option2", enumVals, 4)); - EXPECT_TRUE(options.isOption("option1")); - EXPECT_TRUE(options.isOption("option2")); - EXPECT_EQ(4, options.defaultInt("option2")); - - PluginTranslatorOptionsInstance instance(ctx); - EXPECT_EQ(3, instance.getEnum("option1")); - EXPECT_EQ(4, instance.getEnum("option2")); - instance.setEnum("option1", 2); - EXPECT_EQ(2, instance.getEnum("option1")); - instance.setEnum("option1", 3); - EXPECT_EQ(3, instance.getEnum("option1")); + PluginTranslatorOptionsContext ctx; + PluginTranslatorOptions options(ctx, "testOptions"); + + const char* const enumVals[] + = { "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", 0 }; + + // check we can register the option + EXPECT_TRUE(options.addEnum("option1", enumVals, 3)); + + // make sure it fails if we try to register the same option again + EXPECT_FALSE(options.addEnum("option1", enumVals, 2)); + EXPECT_TRUE(options.isOption("option1")); + EXPECT_EQ(OptionType::kEnum, options.optionType("option1")); + EXPECT_EQ(3, options.defaultInt("option1")); + + // register a second option to validate alternate values + EXPECT_TRUE(options.addEnum("option2", enumVals, 4)); + EXPECT_TRUE(options.isOption("option1")); + EXPECT_TRUE(options.isOption("option2")); + EXPECT_EQ(4, options.defaultInt("option2")); + + PluginTranslatorOptionsInstance instance(ctx); + EXPECT_EQ(3, instance.getEnum("option1")); + EXPECT_EQ(4, instance.getEnum("option2")); + instance.setEnum("option1", 2); + EXPECT_EQ(2, instance.getEnum("option1")); + instance.setEnum("option1", 3); + EXPECT_EQ(3, instance.getEnum("option1")); } - //---------------------------------------------------------------------------------------------------------------------- // void PluginTranslatorOptionsInstance::toOptionVars(const char* const prefix); // void PluginTranslatorOptionsInstance::fromOptionVars(const char* const prefix); TEST(maya_PluginTranslatorOptionsInstance, toOptionVars) { - const char* const enumVals[] = { - "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", 0 - }; - - PluginTranslatorOptionsContext ctx; - PluginTranslatorOptions options(ctx, "testOptions"); - EXPECT_TRUE(options.addBool("bval", true)); - EXPECT_TRUE(options.addInt("ival", 22)); - EXPECT_TRUE(options.addFloat("fval", 23.4f)); - EXPECT_TRUE(options.addString("sval", "HALLO")); - EXPECT_TRUE(options.addEnum("eval", enumVals, 3)); - - PluginTranslatorOptionsInstance instance(ctx); - instance.setBool("bval", false); - instance.setInt("ival", 23); - instance.setFloat("fval", 34.2f); - instance.setString("sval", "bye"); - instance.setEnum("eval", 4); - - instance.toOptionVars("dave"); - MString optVarValue = MGlobal::optionVarStringValue(MString("dave") + "testOptions"); - EXPECT_TRUE(optVarValue.length() != 0); - - // now check to see if options were read back in - PluginTranslatorOptionsInstance instance2(ctx); - instance2.fromOptionVars("dave"); - EXPECT_FALSE(instance2.getBool("bval")); - EXPECT_EQ(23, instance2.getInt("ival")); - EXPECT_EQ(34.2f, instance2.getFloat("fval")); - EXPECT_EQ(MString("bye"), instance2.getString("sval")); - EXPECT_EQ(4, instance2.getEnum("eval")); + const char* const enumVals[] + = { "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", 0 }; + + PluginTranslatorOptionsContext ctx; + PluginTranslatorOptions options(ctx, "testOptions"); + EXPECT_TRUE(options.addBool("bval", true)); + EXPECT_TRUE(options.addInt("ival", 22)); + EXPECT_TRUE(options.addFloat("fval", 23.4f)); + EXPECT_TRUE(options.addString("sval", "HALLO")); + EXPECT_TRUE(options.addEnum("eval", enumVals, 3)); + + PluginTranslatorOptionsInstance instance(ctx); + instance.setBool("bval", false); + instance.setInt("ival", 23); + instance.setFloat("fval", 34.2f); + instance.setString("sval", "bye"); + instance.setEnum("eval", 4); + + instance.toOptionVars("dave"); + MString optVarValue = MGlobal::optionVarStringValue(MString("dave") + "testOptions"); + EXPECT_TRUE(optVarValue.length() != 0); + + // now check to see if options were read back in + PluginTranslatorOptionsInstance instance2(ctx); + instance2.fromOptionVars("dave"); + EXPECT_FALSE(instance2.getBool("bval")); + EXPECT_EQ(23, instance2.getInt("ival")); + EXPECT_EQ(34.2f, instance2.getFloat("fval")); + EXPECT_EQ(MString("bye"), instance2.getString("sval")); + EXPECT_EQ(4, instance2.getEnum("eval")); } //---------------------------------------------------------------------------------------------------------------------- @@ -226,27 +230,26 @@ TEST(maya_PluginTranslatorOptionsInstance, toOptionVars) // void PluginTranslatorOptionsInstance::fromOptionVars(const char* const prefix); TEST(maya_PluginTranslatorOptionsInstance, generateGUI) { - const char* const enumVals[] = { - "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", 0 - }; - - PluginTranslatorOptionsContext ctx; - PluginTranslatorOptions options(ctx, "testOptions"); - EXPECT_TRUE(options.addBool("bval", true)); - EXPECT_TRUE(options.addInt("ival", 22)); - EXPECT_TRUE(options.addFloat("fval", 23.4f)); - EXPECT_TRUE(options.addString("sval", "HALLO")); - EXPECT_TRUE(options.addEnum("eval", enumVals, 3)); - - PluginTranslatorOptions options2(ctx, "moreOptions"); - EXPECT_TRUE(options2.addBool("bval2", true)); - EXPECT_TRUE(options2.addInt("ival2", 22)); - EXPECT_TRUE(options2.addFloat("fval2", 23.4f)); - EXPECT_TRUE(options2.addString("sval2", "HALLO")); - EXPECT_TRUE(options2.addEnum("eval2", enumVals, 3)); - - MString code; - PluginTranslatorOptionsInstance instance(ctx); - ctx.generateGUI("dave", code); - std::cout << '\n' << code << '\n'; + const char* const enumVals[] + = { "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", 0 }; + + PluginTranslatorOptionsContext ctx; + PluginTranslatorOptions options(ctx, "testOptions"); + EXPECT_TRUE(options.addBool("bval", true)); + EXPECT_TRUE(options.addInt("ival", 22)); + EXPECT_TRUE(options.addFloat("fval", 23.4f)); + EXPECT_TRUE(options.addString("sval", "HALLO")); + EXPECT_TRUE(options.addEnum("eval", enumVals, 3)); + + PluginTranslatorOptions options2(ctx, "moreOptions"); + EXPECT_TRUE(options2.addBool("bval2", true)); + EXPECT_TRUE(options2.addInt("ival2", 22)); + EXPECT_TRUE(options2.addFloat("fval2", 23.4f)); + EXPECT_TRUE(options2.addString("sval2", "HALLO")); + EXPECT_TRUE(options2.addEnum("eval2", enumVals, 3)); + + MString code; + PluginTranslatorOptionsInstance instance(ctx); + ctx.generateGUI("dave", code); + std::cout << '\n' << code << '\n'; } diff --git a/plugin/al/mayautils/AL/maya/utils/Api.h b/plugin/al/mayautils/AL/maya/utils/Api.h index f19c0a325c..1eacc3eaac 100644 --- a/plugin/al/mayautils/AL/maya/utils/Api.h +++ b/plugin/al/mayautils/AL/maya/utils/Api.h @@ -15,47 +15,47 @@ // #if defined _WIN32 || defined __CYGWIN__ - #ifdef AL_MAYA_UTILS_EXPORT - #ifdef __GNUC__ - #define AL_MAYA_UTILS_PUBLIC __attribute__ ((dllexport)) - #else - #define AL_MAYA_UTILS_PUBLIC __declspec(dllexport) - #endif - #else - #ifdef __GNUC__ - #define AL_MAYA_UTILS_PUBLIC __attribute__ ((dllimport)) - #else - #define AL_MAYA_UTILS_PUBLIC __declspec(dllimport) - #endif - #endif - #define AL_MAYA_UTILS_LOCAL +#ifdef AL_MAYA_UTILS_EXPORT +#ifdef __GNUC__ +#define AL_MAYA_UTILS_PUBLIC __attribute__((dllexport)) +#else +#define AL_MAYA_UTILS_PUBLIC __declspec(dllexport) +#endif +#else +#ifdef __GNUC__ +#define AL_MAYA_UTILS_PUBLIC __attribute__((dllimport)) +#else +#define AL_MAYA_UTILS_PUBLIC __declspec(dllimport) +#endif +#endif +#define AL_MAYA_UTILS_LOCAL - #ifdef AL_MAYA_MACROS_EXPORT - #ifdef __GNUC__ - #define AL_MAYA_MACROS_PUBLIC __attribute__ ((dllexport)) - #else - #define AL_MAYA_MACROS_PUBLIC __declspec(dllexport) - #endif - #else - #ifdef __GNUC__ - #define AL_MAYA_MACROS_PUBLIC __attribute__ ((dllimport)) - #else - #define AL_MAYA_MACROS_PUBLIC __declspec(dllimport) - #endif - #endif - #define AL_MAYA_MACROS_LOCAL -#else - #if __GNUC__ >= 4 - #define AL_MAYA_UTILS_PUBLIC __attribute__ ((visibility ("default"))) - #define AL_MAYA_UTILS_LOCAL __attribute__ ((visibility ("hidden"))) +#ifdef AL_MAYA_MACROS_EXPORT +#ifdef __GNUC__ +#define AL_MAYA_MACROS_PUBLIC __attribute__((dllexport)) +#else +#define AL_MAYA_MACROS_PUBLIC __declspec(dllexport) +#endif +#else +#ifdef __GNUC__ +#define AL_MAYA_MACROS_PUBLIC __attribute__((dllimport)) +#else +#define AL_MAYA_MACROS_PUBLIC __declspec(dllimport) +#endif +#endif +#define AL_MAYA_MACROS_LOCAL +#else +#if __GNUC__ >= 4 +#define AL_MAYA_UTILS_PUBLIC __attribute__((visibility("default"))) +#define AL_MAYA_UTILS_LOCAL __attribute__((visibility("hidden"))) - #define AL_MAYA_MACROS_PUBLIC __attribute__ ((visibility ("default"))) - #define AL_MAYA_MACROS_LOCAL __attribute__ ((visibility ("hidden"))) - #else - #define AL_MAYA_UTILS_PUBLIC - #define AL_MAYA_UTILS_LOCAL +#define AL_MAYA_MACROS_PUBLIC __attribute__((visibility("default"))) +#define AL_MAYA_MACROS_LOCAL __attribute__((visibility("hidden"))) +#else +#define AL_MAYA_UTILS_PUBLIC +#define AL_MAYA_UTILS_LOCAL - #define AL_MAYA_MACROS_PUBLIC - #define AL_MAYA_MACROS_LOCAL - #endif +#define AL_MAYA_MACROS_PUBLIC +#define AL_MAYA_MACROS_LOCAL +#endif #endif diff --git a/plugin/al/mayautils/AL/maya/utils/CommandGuiHelper.cpp b/plugin/al/mayautils/AL/maya/utils/CommandGuiHelper.cpp index b22a471b9b..63ac3d8cfd 100644 --- a/plugin/al/mayautils/AL/maya/utils/CommandGuiHelper.cpp +++ b/plugin/al/mayautils/AL/maya/utils/CommandGuiHelper.cpp @@ -14,18 +14,19 @@ // limitations under the License. // #include "AL/maya/utils/CommandGuiHelper.h" + #include "AL/maya/utils/MenuBuilder.h" #include "AL/maya/utils/Utils.h" +#include +#include #include #include -#include -#include -#include #include +#include -#include #include +#include namespace AL { namespace maya { @@ -36,1247 +37,1284 @@ std::vector> CommandGuiListGen::m_funcs; AL_MAYA_DEFINE_COMMAND(CommandGuiListGen, AL_usdmaya); //---------------------------------------------------------------------------------------------------------------------- -int32_t CommandGuiListGen::registerListFunc(GenerateListFn generateListFunc, const MString& menuName) +int32_t +CommandGuiListGen::registerListFunc(GenerateListFn generateListFunc, const MString& menuName) { - int32_t n = (m_funcs.size()); - m_funcs.emplace_back(menuName, generateListFunc); - return n; + int32_t n = (m_funcs.size()); + m_funcs.emplace_back(menuName, generateListFunc); + return n; } - //---------------------------------------------------------------------------------------------------------------------- MSyntax CommandGuiListGen::createSyntax() { - MSyntax syn; - syn.addArg(MSyntax::kLong); - return syn; + MSyntax syn; + syn.addArg(MSyntax::kLong); + return syn; } //---------------------------------------------------------------------------------------------------------------------- MStatus CommandGuiListGen::doIt(const MArgList& args) { - MString context; - int32_t genListId = 0; - - MStatus status; - MArgDatabase database(syntax(), args, &status); - if(status) - { - // extract the list ID - if(!database.getCommandArgument(0, genListId)) - { - return MS::kFailure; - } - - // ensure the list id is valid - if(genListId < 0 || size_t(genListId) >= m_funcs.size()) - { - MGlobal::displayError("Invalid gen list ID for the GUI"); - return MS::kFailure; - } - - MStringArray strings = m_funcs[genListId].second(m_funcs[genListId].first); - - MString result; - const MString append_begin("menuItem -l \""); - const MString append_mid("\" -p "); - const MString append_end(";"); - for(uint32_t i = 0, n = strings.length(); i != n; ++i) - { - result += append_begin + strings[i] + append_mid + m_funcs[genListId].first + append_end; + MString context; + int32_t genListId = 0; + + MStatus status; + MArgDatabase database(syntax(), args, &status); + if (status) { + // extract the list ID + if (!database.getCommandArgument(0, genListId)) { + return MS::kFailure; + } + + // ensure the list id is valid + if (genListId < 0 || size_t(genListId) >= m_funcs.size()) { + MGlobal::displayError("Invalid gen list ID for the GUI"); + return MS::kFailure; + } + + MStringArray strings = m_funcs[genListId].second(m_funcs[genListId].first); + + MString result; + const MString append_begin("menuItem -l \""); + const MString append_mid("\" -p "); + const MString append_end(";"); + for (uint32_t i = 0, n = strings.length(); i != n; ++i) { + result + += append_begin + strings[i] + append_mid + m_funcs[genListId].first + append_end; + } + setResult(result); } - setResult(result); - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- -CommandGuiHelper::CommandGuiHelper(const char* commandName, const char* menuItemPath, bool checkBoxValue) : m_checkBoxCommand(true) +CommandGuiHelper::CommandGuiHelper( + const char* commandName, + const char* menuItemPath, + bool checkBoxValue) + : m_checkBoxCommand(true) { - m_hasFilePath = false; + m_hasFilePath = false; - // insert into the main menu - MenuBuilder::addEntry(menuItemPath, commandName, true, checkBoxValue); + // insert into the main menu + MenuBuilder::addEntry(menuItemPath, commandName, true, checkBoxValue); } //---------------------------------------------------------------------------------------------------------------------- -CommandGuiHelper::CommandGuiHelper(const char* commandName, const char* windowTitle, const char* doitLabel, const char* menuItemPath, bool hasOptionBox) : m_checkBoxCommand(false) +CommandGuiHelper::CommandGuiHelper( + const char* commandName, + const char* windowTitle, + const char* doitLabel, + const char* menuItemPath, + bool hasOptionBox) + : m_checkBoxCommand(false) { - m_hasFilePath = false; - m_commandName = commandName; - // generate and execute the main option box routine - std::string mycmd_optionGUI = commandName; - mycmd_optionGUI += "_optionGUI"; - - // insert into the main menu - if(hasOptionBox) - { - MenuBuilder::addEntry(menuItemPath, (std::string("execute_") + mycmd_optionGUI).c_str(), (std::string("build_") + mycmd_optionGUI).c_str()); - } - else - { - MenuBuilder::addEntry(menuItemPath, (std::string("build_") + mycmd_optionGUI).c_str()); - } - - std::ostringstream ui; - ui << "global proc build_" << mycmd_optionGUI << "()\n" - "{\n" - " if(`window -q -ex \"" << mycmd_optionGUI << "\"`)\n" - " {\n" - " if(`window -q -visible \"" << mycmd_optionGUI << "\"`) return;\n" - // If there was an error building the window, the window may exist, but not be shown. - // We assume that if it's not visible, there was an error, so we delete it and try again. - " deleteUI \"" << mycmd_optionGUI << "\";\n" - " }\n" - " $window = `window -title \"" << windowTitle << "\" -w 550 -h 350 \"" << mycmd_optionGUI << "\"`;\n" - " $menuBarLayout = `menuBarLayout`;\n" - " $menu = `menu -label \"Edit\"`;\n" - " menuItem -label \"Save Settings\" -c \"save_" << mycmd_optionGUI << "\";\n" - " menuItem -label \"Reset Settings\" -c \"reset_" << mycmd_optionGUI << "\";\n" - " setParent $window;\n" - " $form = `formLayout -numberOfDivisions 100`;\n" - " $columnLayout = `frameLayout -cll 0 -bv 1 -lv 0`;\n" - " rowLayout -cw 1 170 -nc 2 -ct2 \"left\" \"right\" -adj 2 -rat 1 \"top\" 0 -rat 2 \"top\" 0;\n" - " columnLayout -adj 1 -cat \"both\" 1 -rs 2;\n" - " build_" << commandName << "_labels();\n" - " setParent ..;\n" - " columnLayout -adj 1 -cat \"both\" 1 -rs 2;\n" - " build_" << commandName << "_controls();\n" - " setParent ..;\n" - " setParent ..;\n" - " setParent ..;\n" - // Create / Apply / Cancel - " $rowLayout = `paneLayout -cn \"vertical3\"`;\n" - " $doit = `button -label \"" << doitLabel << "\" -c (\"save_" << mycmd_optionGUI << ";execute_" << mycmd_optionGUI << ";deleteUI \" + $window)`;\n" - " $saveit = `button -label \"Apply\" -c \"save_" << mycmd_optionGUI << "\"`;\n" - " $close = `button -label \"Close\" -c (\"deleteUI \" + $window)`;\n" - " setParent ..;\n" - " formLayout -e\n" - " -attachForm $columnLayout \"top\" 1\n" - " -attachForm $columnLayout \"left\" 1\n" - " -attachForm $columnLayout \"right\" 1\n" - " -attachControl $columnLayout \"bottom\" 5 $rowLayout\n" - " -attachForm $rowLayout \"left\" 5\n" - " -attachForm $rowLayout \"right\" 5\n" - " -attachForm $rowLayout \"bottom\" 5\n" - " -attachNone $rowLayout \"top\"\n" - " $form;\n" - " init_" << mycmd_optionGUI << "();\n" - " load_" << mycmd_optionGUI << "();\n" - " showWindow;\n" - "}\n"; - - MGlobal::executeCommand(MString(ui.str().data(), ui.str().length())); - - // if you want to validate the output code - if (AL_MAYAUTILS_DEBUG) - { - std::cout << ui.str() + "\n" << std::endl; - } - - // begin construction of the 6 utils functions for this dialog - m_init << "global proc init_" << mycmd_optionGUI << "()\n{\n"; - m_save << "global proc save_" << mycmd_optionGUI << "()\n{\n"; - m_load << "global proc load_" << mycmd_optionGUI << "()\n{\n"; - m_reset << "global proc reset_" << mycmd_optionGUI << "()\n{\n"; - m_execute << "global proc execute_" << mycmd_optionGUI << "()\n{\n string $str = \"" << commandName << " \";\n"; - m_labels << "global proc build_" << commandName << "_labels()\n{\n"; - m_controls << "global proc build_" << commandName << "_controls()\n{\n"; + m_hasFilePath = false; + m_commandName = commandName; + // generate and execute the main option box routine + std::string mycmd_optionGUI = commandName; + mycmd_optionGUI += "_optionGUI"; + + // insert into the main menu + if (hasOptionBox) { + MenuBuilder::addEntry( + menuItemPath, + (std::string("execute_") + mycmd_optionGUI).c_str(), + (std::string("build_") + mycmd_optionGUI).c_str()); + } else { + MenuBuilder::addEntry(menuItemPath, (std::string("build_") + mycmd_optionGUI).c_str()); + } + + std::ostringstream ui; + ui << "global proc build_" << mycmd_optionGUI + << "()\n" + "{\n" + " if(`window -q -ex \"" + << mycmd_optionGUI + << "\"`)\n" + " {\n" + " if(`window -q -visible \"" + << mycmd_optionGUI + << "\"`) return;\n" + // If there was an error building the window, the window may exist, but not be shown. + // We assume that if it's not visible, there was an error, so we delete it and try again. + " deleteUI \"" + << mycmd_optionGUI + << "\";\n" + " }\n" + " $window = `window -title \"" + << windowTitle << "\" -w 550 -h 350 \"" << mycmd_optionGUI + << "\"`;\n" + " $menuBarLayout = `menuBarLayout`;\n" + " $menu = `menu -label \"Edit\"`;\n" + " menuItem -label \"Save Settings\" -c \"save_" + << mycmd_optionGUI + << "\";\n" + " menuItem -label \"Reset Settings\" -c \"reset_" + << mycmd_optionGUI + << "\";\n" + " setParent $window;\n" + " $form = `formLayout -numberOfDivisions 100`;\n" + " $columnLayout = `frameLayout -cll 0 -bv 1 -lv 0`;\n" + " rowLayout -cw 1 170 -nc 2 -ct2 \"left\" \"right\" -adj 2 -rat 1 \"top\" 0 -rat 2 " + "\"top\" 0;\n" + " columnLayout -adj 1 -cat \"both\" 1 -rs 2;\n" + " build_" + << commandName + << "_labels();\n" + " setParent ..;\n" + " columnLayout -adj 1 -cat \"both\" 1 -rs 2;\n" + " build_" + << commandName + << "_controls();\n" + " setParent ..;\n" + " setParent ..;\n" + " setParent ..;\n" + // Create / Apply / Cancel + " $rowLayout = `paneLayout -cn \"vertical3\"`;\n" + " $doit = `button -label \"" + << doitLabel << "\" -c (\"save_" << mycmd_optionGUI << ";execute_" << mycmd_optionGUI + << ";deleteUI \" + $window)`;\n" + " $saveit = `button -label \"Apply\" -c \"save_" + << mycmd_optionGUI + << "\"`;\n" + " $close = `button -label \"Close\" -c (\"deleteUI \" + $window)`;\n" + " setParent ..;\n" + " formLayout -e\n" + " -attachForm $columnLayout \"top\" 1\n" + " -attachForm $columnLayout \"left\" 1\n" + " -attachForm $columnLayout \"right\" 1\n" + " -attachControl $columnLayout \"bottom\" 5 $rowLayout\n" + " -attachForm $rowLayout \"left\" 5\n" + " -attachForm $rowLayout \"right\" 5\n" + " -attachForm $rowLayout \"bottom\" 5\n" + " -attachNone $rowLayout \"top\"\n" + " $form;\n" + " init_" + << mycmd_optionGUI + << "();\n" + " load_" + << mycmd_optionGUI + << "();\n" + " showWindow;\n" + "}\n"; + + MGlobal::executeCommand(MString(ui.str().data(), ui.str().length())); + + // if you want to validate the output code + if (AL_MAYAUTILS_DEBUG) { + std::cout << ui.str() + "\n" << std::endl; + } + + // begin construction of the 6 utils functions for this dialog + m_init << "global proc init_" << mycmd_optionGUI << "()\n{\n"; + m_save << "global proc save_" << mycmd_optionGUI << "()\n{\n"; + m_load << "global proc load_" << mycmd_optionGUI << "()\n{\n"; + m_reset << "global proc reset_" << mycmd_optionGUI << "()\n{\n"; + m_execute << "global proc execute_" << mycmd_optionGUI << "()\n{\n string $str = \"" + << commandName << " \";\n"; + m_labels << "global proc build_" << commandName << "_labels()\n{\n"; + m_controls << "global proc build_" << commandName << "_controls()\n{\n"; } //---------------------------------------------------------------------------------------------------------------------- CommandGuiHelper::~CommandGuiHelper() { - if (m_checkBoxCommand) - { - return; - } - - // close off our util functions - m_init << "}\n"; - m_save << "}\n"; - m_load << "}\n"; - m_reset << "}\n"; - m_execute << " eval $str;\n}\n"; - m_labels << "}\n"; - m_controls << "}\n"; - - // if you want to validate the output code - if (AL_MAYAUTILS_DEBUG) - { - std::cout << m_global.str() + "\n" << std::endl; - std::cout << m_init.str() + "\n" << std::endl; - std::cout << m_save.str() + "\n" << std::endl; - std::cout << m_load.str() + "\n" << std::endl; - std::cout << m_reset.str() + "\n" << std::endl; - std::cout << m_execute.str() + "\n" << std::endl; - std::cout << m_labels.str() + "\n" << std::endl; - std::cout << m_controls.str() + "\n" << std::endl; - } - - static const char* const alFileDialogHandler = - "global proc alFileDialogHandler(string $filter, string $control, int $mode)\n" - "{\n" - " string $result[] = `fileDialog2 -ff $filter -ds 2 -fm $mode`;\n" - " if(size($result))\n" - " {\n" - " string $r = $result[0];\n" - " for($i = 1; $i < size($result); ++$i)\n" - " $r += (\";\" + $result[$i]);\n" - " textFieldButtonGrp -e -fi $r $control;\n" - " }\n" - "}\n"; - - // if we happen to have a file dialog knocking about in our GUI, ensure the handler is available. - if(m_hasFilePath) - { - MGlobal::executeCommand(alFileDialogHandler); - } - - // and execute them - MGlobal::executeCommand(MString(m_global.str().data(), m_global.str().size())); - MGlobal::executeCommand(MString(m_init.str().data(), m_init.str().size())); - MGlobal::executeCommand(MString(m_save.str().data(), m_save.str().size())); - MGlobal::executeCommand(MString(m_load.str().data(), m_load.str().size())); - MGlobal::executeCommand(MString(m_reset.str().data(), m_reset.str().size())); - MGlobal::executeCommand(MString(m_execute.str().data(), m_execute.str().size())); - MGlobal::executeCommand(MString(m_labels.str().data(), m_labels.str().size())); - MGlobal::executeCommand(MString(m_controls.str().data(), m_controls.str().size())); + if (m_checkBoxCommand) { + return; + } + + // close off our util functions + m_init << "}\n"; + m_save << "}\n"; + m_load << "}\n"; + m_reset << "}\n"; + m_execute << " eval $str;\n}\n"; + m_labels << "}\n"; + m_controls << "}\n"; + + // if you want to validate the output code + if (AL_MAYAUTILS_DEBUG) { + std::cout << m_global.str() + "\n" << std::endl; + std::cout << m_init.str() + "\n" << std::endl; + std::cout << m_save.str() + "\n" << std::endl; + std::cout << m_load.str() + "\n" << std::endl; + std::cout << m_reset.str() + "\n" << std::endl; + std::cout << m_execute.str() + "\n" << std::endl; + std::cout << m_labels.str() + "\n" << std::endl; + std::cout << m_controls.str() + "\n" << std::endl; + } + + static const char* const alFileDialogHandler + = "global proc alFileDialogHandler(string $filter, string $control, int $mode)\n" + "{\n" + " string $result[] = `fileDialog2 -ff $filter -ds 2 -fm $mode`;\n" + " if(size($result))\n" + " {\n" + " string $r = $result[0];\n" + " for($i = 1; $i < size($result); ++$i)\n" + " $r += (\";\" + $result[$i]);\n" + " textFieldButtonGrp -e -fi $r $control;\n" + " }\n" + "}\n"; + + // if we happen to have a file dialog knocking about in our GUI, ensure the handler is + // available. + if (m_hasFilePath) { + MGlobal::executeCommand(alFileDialogHandler); + } + + // and execute them + MGlobal::executeCommand(MString(m_global.str().data(), m_global.str().size())); + MGlobal::executeCommand(MString(m_init.str().data(), m_init.str().size())); + MGlobal::executeCommand(MString(m_save.str().data(), m_save.str().size())); + MGlobal::executeCommand(MString(m_load.str().data(), m_load.str().size())); + MGlobal::executeCommand(MString(m_reset.str().data(), m_reset.str().size())); + MGlobal::executeCommand(MString(m_execute.str().data(), m_execute.str().size())); + MGlobal::executeCommand(MString(m_labels.str().data(), m_labels.str().size())); + MGlobal::executeCommand(MString(m_controls.str().data(), m_controls.str().size())); } //---------------------------------------------------------------------------------------------------------------------- void CommandGuiHelper::addExecuteText(const char* toAdd) { - // TODO: write a proper string encoder for MEL (tricky, because can't represent - // all 256 character-bytes using mel string literals - would have to resort to - // calling out to python for a truly string rerpr encoder. - // (note that even mel's builtin "encodeString" command doesn't actually always - // return a mel string that will evaluate to the input - ie, it will return - // "\004", but that isn't a valid mel escape sequence, and will just result in "004" - - // for now, just check to make sure we have printable characters... only need to - // implement a full MEL-string-encoder if we really have a need... - m_execute << " $str += \""; - bool printedError = false; - - for(size_t i = 0; toAdd[i] != '\0'; ++i) - { - if(toAdd[i] < 32 || toAdd[i] > 126) - { - if (toAdd[i] == '\b') m_execute << "\\b"; - else if (toAdd[i] == '\t') m_execute << "\\t"; - else if (toAdd[i] == '\n') m_execute << "\\n"; - else if (toAdd[i] == '\r') m_execute << "\\r"; - // Just throwing, if we ever need to use a string with weird chars, need to - // update this function... - else if (!printedError) - { - // Make our own stream (instead of steaming straigt to cerr) - // both because we also want to output to maya, and - // because we need to set a flag (ie, std::hex) - std::ostringstream err; - err << "CommandGuiHelper::addExecuteText encountered bad character at index "; - err << i; - err << ": 0x"; - err << std::hex; - // if you just reinterpret_cast as uint8_t, it still treats as a char - err << static_cast(reinterpret_cast(toAdd)[i]); - std::string errStr = err.str(); - MGlobal::displayError(errStr.c_str()); - std::cerr << errStr; - printedError = true; - } + // TODO: write a proper string encoder for MEL (tricky, because can't represent + // all 256 character-bytes using mel string literals - would have to resort to + // calling out to python for a truly string rerpr encoder. + // (note that even mel's builtin "encodeString" command doesn't actually always + // return a mel string that will evaluate to the input - ie, it will return + // "\004", but that isn't a valid mel escape sequence, and will just result in "004" + + // for now, just check to make sure we have printable characters... only need to + // implement a full MEL-string-encoder if we really have a need... + m_execute << " $str += \""; + bool printedError = false; + + for (size_t i = 0; toAdd[i] != '\0'; ++i) { + if (toAdd[i] < 32 || toAdd[i] > 126) { + if (toAdd[i] == '\b') + m_execute << "\\b"; + else if (toAdd[i] == '\t') + m_execute << "\\t"; + else if (toAdd[i] == '\n') + m_execute << "\\n"; + else if (toAdd[i] == '\r') + m_execute << "\\r"; + // Just throwing, if we ever need to use a string with weird chars, need to + // update this function... + else if (!printedError) { + // Make our own stream (instead of steaming straigt to cerr) + // both because we also want to output to maya, and + // because we need to set a flag (ie, std::hex) + std::ostringstream err; + err << "CommandGuiHelper::addExecuteText encountered bad character at index "; + err << i; + err << ": 0x"; + err << std::hex; + // if you just reinterpret_cast as uint8_t, it still treats as a char + err << static_cast(reinterpret_cast(toAdd)[i]); + std::string errStr = err.str(); + MGlobal::displayError(errStr.c_str()); + std::cerr << errStr; + printedError = true; + } + } else if (toAdd[i] == '"') + m_execute << "\\\""; + else if (toAdd[i] == '\\') + m_execute << "\\\\"; + else + m_execute << toAdd[i]; } - else if (toAdd[i] == '"') m_execute << "\\\""; - else if (toAdd[i] == '\\') m_execute << "\\\\"; - else m_execute << toAdd[i]; - } - m_execute << "\";\n"; + m_execute << "\";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addFlagOption(const char* commandFlag, const char* label, const bool defaultVal, bool persist) +void CommandGuiHelper::addFlagOption( + const char* commandFlag, + const char* label, + const bool defaultVal, + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " checkBox -l \"\" -h 20 " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal << ";\n"; - m_load << " checkBox -e -v " << getOptionVar << " " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -iv \"" << optionVar << "\" `checkBox -q -v " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " if(" << getOptionVar << ") $str += \" -" << commandFlag << " \";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " checkBox -e -v " << defaultVal << " " << optionVar << ";\n"; - - // pull the value from the checkbox when executing - m_execute << " if(`checkBox -ex " << optionVar << "` && `checkBox -q -v " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \";\n"; - } + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " checkBox -l \"\" -h 20 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal << ";\n"; + m_load << " checkBox -e -v " << getOptionVar << " " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -iv \"" << optionVar << "\" `checkBox -q -v " << optionVar << "`;\n"; + + // build up command string using optionVar value + m_execute << " if(" << getOptionVar << ") $str += \" -" << commandFlag << " \";\n"; + } else { + // just set the checkbox to the default value + m_load << " checkBox -e -v " << defaultVal << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`checkBox -ex " << optionVar << "` && `checkBox -q -v " << optionVar + << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \";\n"; + } - // reset checkbox back to the default value - m_reset << " checkBox -e -v " << defaultVal << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " checkBox -e -v " << defaultVal << " " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addBoolOption(const char* commandFlag, const char* label, const bool defaultVal, bool persist) +void CommandGuiHelper::addBoolOption( + const char* commandFlag, + const char* label, + const bool defaultVal, + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " checkBox -l \"\" -h 20 " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal << ";\n"; - m_load << " checkBox -e -v " << getOptionVar << " " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -iv \"" << optionVar << "\" `checkBox -q -v " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " checkBox -e -v " << defaultVal << " " << optionVar << ";\n"; - - // pull the value from the checkbox when executing - m_execute << " if(`checkBox -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `checkBox -q -v " << optionVar << "`;\n"; - } + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " checkBox -l \"\" -h 20 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal << ";\n"; + m_load << " checkBox -e -v " << getOptionVar << " " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -iv \"" << optionVar << "\" `checkBox -q -v " << optionVar << "`;\n"; + + // build up command string using optionVar value + m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; + } else { + // just set the checkbox to the default value + m_load << " checkBox -e -v " << defaultVal << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`checkBox -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `checkBox -q -v " << optionVar + << "`;\n"; + } - // reset checkbox back to the default value - m_reset << " checkBox -e -v " << defaultVal << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " checkBox -e -v " << defaultVal << " " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addListOption(const char* commandFlag, const char* label, GenerateListFn generateList, bool isMandatory) +void CommandGuiHelper::addListOption( + const char* commandFlag, + const char* label, + GenerateListFn generateList, + bool isMandatory) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q -sl \"") + optionVar + "\"`"; - - m_global << "global proc " << optionVar << "_handle(string $sl) {\n" - " global string $" << optionVar << "_sl; $" << optionVar << "_sl = $sl;\n}\n"; - - // Use `optionMenu -q -value` instead of "#1" because there's no good way to do string-escaping - // with "#1" - m_controls << " optionMenu -h 20 -cc \"" << optionVar << "_handle `optionMenu -q -value " << optionVar << "`\" " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // register callback - const int32_t id = CommandGuiListGen::registerListFunc(generateList, AL::maya::utils::convert(optionVar)); - - // call into command to build up menu items for optionMenu control - m_load << " $temp_str = `AL_usdmaya_CommandGuiListGen " << id << "`;\n"; - m_load << " eval($temp_str);\n"; - - // - m_execute << " global string $" << optionVar << "_sl;" - << " $str += \" "; - if (!isMandatory) { - m_execute << "-" << commandFlag << " "; - } - m_execute << "$" << optionVar << "_sl \";\n"; + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q -sl \"") + optionVar + "\"`"; + + m_global << "global proc " << optionVar + << "_handle(string $sl) {\n" + " global string $" + << optionVar << "_sl; $" << optionVar << "_sl = $sl;\n}\n"; + + // Use `optionMenu -q -value` instead of "#1" because there's no good way to do string-escaping + // with "#1" + m_controls << " optionMenu -h 20 -cc \"" << optionVar << "_handle `optionMenu -q -value " + << optionVar << "`\" " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // register callback + const int32_t id + = CommandGuiListGen::registerListFunc(generateList, AL::maya::utils::convert(optionVar)); + + // call into command to build up menu items for optionMenu control + m_load << " $temp_str = `AL_usdmaya_CommandGuiListGen " << id << "`;\n"; + m_load << " eval($temp_str);\n"; + + // + m_execute << " global string $" << optionVar << "_sl;" + << " $str += \" "; + if (!isMandatory) { + m_execute << "-" << commandFlag << " "; + } + m_execute << "$" << optionVar << "_sl \";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addIntOption(const char* commandFlag, const char* label, const int defaultVal, bool persist) +void CommandGuiHelper::addIntOption( + const char* commandFlag, + const char* label, + const int defaultVal, + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " intField -h 20 " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal << ";\n"; - m_load << " intField -e -v " << getOptionVar << " " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -iv \"" << optionVar << "\" `intField -q -v " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " intField -e -v " << defaultVal << " " << optionVar << ";\n"; - - // pull the value from the checkbox when executing - m_execute << " if(`intField -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `intField -q -v " << optionVar << "`;\n"; - } + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " intField -h 20 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal << ";\n"; + m_load << " intField -e -v " << getOptionVar << " " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -iv \"" << optionVar << "\" `intField -q -v " << optionVar << "`;\n"; + + // build up command string using optionVar value + m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; + } else { + // just set the checkbox to the default value + m_load << " intField -e -v " << defaultVal << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`intField -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `intField -q -v " << optionVar + << "`;\n"; + } - // reset checkbox back to the default value - m_reset << " intField -e -v " << defaultVal << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " intField -e -v " << defaultVal << " " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addIntSliderOption(const char* commandFlag, const char* label, const int minVal, const int maxVal, const int defaultVal, bool persist) +void CommandGuiHelper::addIntSliderOption( + const char* commandFlag, + const char* label, + const int minVal, + const int maxVal, + const int defaultVal, + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " intSlider -h 20 -min " << minVal << " -max " << maxVal << " " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal << ";\n"; - m_load << " intSlider -e -v " << getOptionVar << " " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -iv \"" << optionVar << "\" `intSlider -q -v " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " intSlider -e -v " << defaultVal << " " << optionVar << ";\n"; - - // pull the value from the checkbox when executing - m_execute << " if(`intSlider -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `intSlider -q -v " << optionVar << "`;\n"; - } + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " intSlider -h 20 -min " << minVal << " -max " << maxVal << " " << optionVar + << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal << ";\n"; + m_load << " intSlider -e -v " << getOptionVar << " " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -iv \"" << optionVar << "\" `intSlider -q -v " << optionVar + << "`;\n"; + + // build up command string using optionVar value + m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; + } else { + // just set the checkbox to the default value + m_load << " intSlider -e -v " << defaultVal << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`intSlider -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `intSlider -q -v " << optionVar + << "`;\n"; + } - // reset checkbox back to the default value - m_reset << " intSlider -e -v " << defaultVal << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " intSlider -e -v " << defaultVal << " " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addInt2Option(const char* commandFlag, const char* label, const int32_t defaultVal[2], bool persist) +void CommandGuiHelper::addInt2Option( + const char* commandFlag, + const char* label, + const int32_t defaultVal[2], + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " intFieldGrp -h 20 -nf 2 " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal[0] - << " -iva \"" << optionVar << "\" " << defaultVal[1] << ";\n"; - - m_load << " $iv = " << getOptionVar << ";\n"; - m_load << " intFieldGrp -e -v1 $iv[0] -v2 $iv[1] " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -iv \"" << optionVar << "\" `intFieldGrp -q -v1 " << optionVar - << "` -iva \"" << optionVar << "\" `intFieldGrp -q -v2 " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " $iv = " << getOptionVar << ";\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $iv[0] + \" \" + $iv[1] + \" \";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " intFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] - << " -v3 " << defaultVal[2] << " " << optionVar << ";\n"; + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " intFieldGrp -h 20 -nf 2 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal[0] << " -iva \"" + << optionVar << "\" " << defaultVal[1] << ";\n"; + + m_load << " $iv = " << getOptionVar << ";\n"; + m_load << " intFieldGrp -e -v1 $iv[0] -v2 $iv[1] " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -iv \"" << optionVar << "\" `intFieldGrp -q -v1 " << optionVar + << "` -iva \"" << optionVar << "\" `intFieldGrp -q -v2 " << optionVar << "`;\n"; + + // build up command string using optionVar value + m_execute << " $iv = " << getOptionVar << ";\n"; + m_execute << " $str += \" -" << commandFlag << " \" + $iv[0] + \" \" + $iv[1] + \" \";\n"; + } else { + // just set the checkbox to the default value + m_load << " intFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " -v3 " + << defaultVal[2] << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`intFieldGrp -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `intFieldGrp -q -v1 " << optionVar + << "` + \" \" + `intFieldGrp -q -v2 " << optionVar << "`;\n"; + } - // pull the value from the checkbox when executing - m_execute << " if(`intFieldGrp -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `intFieldGrp -q -v1 " << optionVar - << "` + \" \" + `intFieldGrp -q -v2 " << optionVar << "`;\n"; - } - - // reset checkbox back to the default value - m_reset << " intFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " intFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " " + << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addInt3Option(const char* commandFlag, const char* label, const int32_t defaultVal[3], bool persist) +void CommandGuiHelper::addInt3Option( + const char* commandFlag, + const char* label, + const int32_t defaultVal[3], + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " intFieldGrp -h 20 -nf 3 " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal[0] - << " -iva \"" << optionVar << "\" " << defaultVal[1] - << " -iva \"" << optionVar << "\" " << defaultVal[2] << ";\n"; - - m_load << " $iv = " << getOptionVar << ";\n"; - m_load << " intFieldGrp -e -v1 $iv[0] -v2 $iv[1] -v3 $iv[2] " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -iv \"" << optionVar << "\" `intFieldGrp -q -v1 " << optionVar - << "` -iva \"" << optionVar << "\" `intFieldGrp -q -v2 " << optionVar - << "` -iva \"" << optionVar << "\" `intFieldGrp -q -v3 " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " $iv = " << getOptionVar << ";\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $iv[0] + \" \" + $iv[1] + \" \" + $iv[2] + \" \";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " intFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] - << " -v3 " << defaultVal[2] << " " << optionVar << ";\n"; + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " intFieldGrp -h 20 -nf 3 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal[0] << " -iva \"" + << optionVar << "\" " << defaultVal[1] << " -iva \"" << optionVar << "\" " + << defaultVal[2] << ";\n"; + + m_load << " $iv = " << getOptionVar << ";\n"; + m_load << " intFieldGrp -e -v1 $iv[0] -v2 $iv[1] -v3 $iv[2] " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -iv \"" << optionVar << "\" `intFieldGrp -q -v1 " << optionVar + << "` -iva \"" << optionVar << "\" `intFieldGrp -q -v2 " << optionVar << "` -iva \"" + << optionVar << "\" `intFieldGrp -q -v3 " << optionVar << "`;\n"; + + // build up command string using optionVar value + m_execute << " $iv = " << getOptionVar << ";\n"; + m_execute << " $str += \" -" << commandFlag + << " \" + $iv[0] + \" \" + $iv[1] + \" \" + $iv[2] + \" \";\n"; + } else { + // just set the checkbox to the default value + m_load << " intFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " -v3 " + << defaultVal[2] << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`intFieldGrp -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `intFieldGrp -q -v1 " << optionVar + << "` + \" \" + `intFieldGrp -q -v2 " << optionVar + << "` + \" \" + `intFieldGrp -q -v3 " << optionVar << "`;\n"; + } - // pull the value from the checkbox when executing - m_execute << " if(`intFieldGrp -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `intFieldGrp -q -v1 " << optionVar - << "` + \" \" + `intFieldGrp -q -v2 " << optionVar - << "` + \" \" + `intFieldGrp -q -v3 " << optionVar << "`;\n"; - } - - // reset checkbox back to the default value - m_reset << " intFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] - << " -v3 " << defaultVal[2] << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " intFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " -v3 " + << defaultVal[2] << " " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addInt4Option(const char* commandFlag, const char* label, const int32_t defaultVal[4], bool persist) +void CommandGuiHelper::addInt4Option( + const char* commandFlag, + const char* label, + const int32_t defaultVal[4], + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " intFieldGrp -h 20 -nf 4 " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal[0] - << " -iva \"" << optionVar << "\" " << defaultVal[1] - << " -iva \"" << optionVar << "\" " << defaultVal[2] - << " -iva \"" << optionVar << "\" " << defaultVal[3] << ";\n"; - - m_load << " $iv = " << getOptionVar << ";\n"; - m_load << " intFieldGrp -e -v1 $iv[0] -v2 $iv[1] -v3 $iv[2] -v4 $iv[3] " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -iv \"" << optionVar << "\" `intFieldGrp -q -v1 " << optionVar - << "` -iva \"" << optionVar << "\" `intFieldGrp -q -v2 " << optionVar - << "` -iva \"" << optionVar << "\" `intFieldGrp -q -v3 " << optionVar - << "` -iva \"" << optionVar << "\" `intFieldGrp -q -v4 " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " $iv = " << getOptionVar << ";\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $iv[0] + \" \" + $iv[1] + \" \" + $iv[2] + \" \" + $iv[3] + \" \";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " intFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] - << " -v3 " << defaultVal[2] - << " -v4 " << defaultVal[3] << " " << optionVar << ";\n"; + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " intFieldGrp -h 20 -nf 4 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -iv \"" << optionVar << "\" " << defaultVal[0] << " -iva \"" + << optionVar << "\" " << defaultVal[1] << " -iva \"" << optionVar << "\" " + << defaultVal[2] << " -iva \"" << optionVar << "\" " << defaultVal[3] << ";\n"; + + m_load << " $iv = " << getOptionVar << ";\n"; + m_load << " intFieldGrp -e -v1 $iv[0] -v2 $iv[1] -v3 $iv[2] -v4 $iv[3] " << optionVar + << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -iv \"" << optionVar << "\" `intFieldGrp -q -v1 " << optionVar + << "` -iva \"" << optionVar << "\" `intFieldGrp -q -v2 " << optionVar << "` -iva \"" + << optionVar << "\" `intFieldGrp -q -v3 " << optionVar << "` -iva \"" << optionVar + << "\" `intFieldGrp -q -v4 " << optionVar << "`;\n"; + + // build up command string using optionVar value + m_execute << " $iv = " << getOptionVar << ";\n"; + m_execute << " $str += \" -" << commandFlag + << " \" + $iv[0] + \" \" + $iv[1] + \" \" + $iv[2] + \" \" + $iv[3] + \" \";\n"; + } else { + // just set the checkbox to the default value + m_load << " intFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " -v3 " + << defaultVal[2] << " -v4 " << defaultVal[3] << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`intFieldGrp -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `intFieldGrp -q -v1 " << optionVar + << "` + \" \" + `intFieldGrp -q -v2 " << optionVar + << "` + \" \" + `intFieldGrp -q -v3 " << optionVar + << "` + \" \" + `intFieldGrp -q -v4 " << optionVar << "`;\n"; + } - // pull the value from the checkbox when executing - m_execute << " if(`intFieldGrp -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `intFieldGrp -q -v1 " << optionVar - << "` + \" \" + `intFieldGrp -q -v2 " << optionVar - << "` + \" \" + `intFieldGrp -q -v3 " << optionVar - << "` + \" \" + `intFieldGrp -q -v4 " << optionVar << "`;\n"; - } - - // reset checkbox back to the default value - m_reset << " intFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] - << " -v3 " << defaultVal[2] - << " -v4 " << defaultVal[3] << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " intFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " -v3 " + << defaultVal[2] << " -v4 " << defaultVal[3] << " " << optionVar << ";\n"; } - //---------------------------------------------------------------------------------------------------------------------- void CommandGuiHelper::addEnumOption( - const char* commandFlag, - const char* label, - int defaultIndex, + const char* commandFlag, + const char* label, + int defaultIndex, const char* const enumNames[], - const int32_t enumValues[], - bool persist, - bool passAsString) + const int32_t enumValues[], + bool persist, + bool passAsString) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - std::ostringstream enumValuesAsString; - if(passAsString) - { - enumValuesAsString << "$evs = {\"" << enumNames[0] << "\""; - for(int i = 1; enumNames[i]; ++i) - { - enumValuesAsString << ",\"" << enumNames[i] << "\""; - } - enumValuesAsString << "};"; - } - else - if(enumValues) - { - enumValuesAsString << "$ev = {" << enumValues[0]; - for(int i = 1; enumNames[i]; ++i) - { - enumValuesAsString << "," << enumValues[i]; - } - enumValuesAsString << "};"; - } - - // generate checkbox control for boolean argument - m_controls << " optionMenu -h 20 " << optionVar << ";\n"; - for(int i = 0; enumNames[i]; ++i) - { - m_controls << " menuItem -label \"" << enumNames[i] << "\";\n"; - } - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -iv \"" << optionVar << "\" " << defaultIndex << ";\n"; - m_load << " optionMenu -e -sl (" << getOptionVar << " + 1) " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -iv \"" << optionVar << "\" (`optionMenu -q -sl " << optionVar << "` - 1);\n"; - - // build up command string using optionVar value - if(passAsString) - { - m_execute << " {\n"; - m_execute << " " << enumValuesAsString.str() << "\n"; - m_execute << " int $__index = " << getOptionVar << ";\n"; - m_execute << " $str += \" -" << commandFlag << " \\\"\" + $evs[ $__index ] + \"\\\"\";\n"; - m_execute << " }\n"; - } - else - if(enumValues) - { - m_execute << " {\n"; - m_execute << " " << enumValuesAsString.str() << "\n"; - m_execute << " int $__index = " << getOptionVar << ";\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $ev[ $__index ];\n"; - m_execute << " }\n"; - } - else - { - m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + std::ostringstream enumValuesAsString; + if (passAsString) { + enumValuesAsString << "$evs = {\"" << enumNames[0] << "\""; + for (int i = 1; enumNames[i]; ++i) { + enumValuesAsString << ",\"" << enumNames[i] << "\""; + } + enumValuesAsString << "};"; + } else if (enumValues) { + enumValuesAsString << "$ev = {" << enumValues[0]; + for (int i = 1; enumNames[i]; ++i) { + enumValuesAsString << "," << enumValues[i]; + } + enumValuesAsString << "};"; } - } - else - { - // just set the checkbox to the default value - m_load << " optionMenu -e -sl (" << defaultIndex << " + 1) " << optionVar << ";\n"; - if(passAsString) - { - m_execute << " if(`intField -ex " << optionVar << "`)\n"; - m_execute << " {\n"; - m_execute << " " << enumValuesAsString.str() << "\n"; - m_execute << " int $__index = (`optionMenu -q -sl " << optionVar << "` - 1);\n"; - m_execute << " $str += \" -" << commandFlag << " \\\"\" + $evs[ $__index ] + \"\\\"\";\n"; - m_execute << " }\n"; - } - else - if(enumValues) - { - m_execute << " if(`intField -ex " << optionVar << "`)\n"; - m_execute << " {\n"; - m_execute << " " << enumValuesAsString.str() << "\n"; - m_execute << " int $__index = (`optionMenu -q -sl " << optionVar << "` - 1);\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $ev[ $__index ];\n"; - m_execute << " }\n"; + // generate checkbox control for boolean argument + m_controls << " optionMenu -h 20 " << optionVar << ";\n"; + for (int i = 0; enumNames[i]; ++i) { + m_controls << " menuItem -label \"" << enumNames[i] << "\";\n"; } - else - { - m_execute << " if(`intField -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `optionMenu -q -sl " << optionVar << "` - 1);\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -iv \"" << optionVar << "\" " << defaultIndex << ";\n"; + m_load << " optionMenu -e -sl (" << getOptionVar << " + 1) " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -iv \"" << optionVar << "\" (`optionMenu -q -sl " << optionVar + << "` - 1);\n"; + + // build up command string using optionVar value + if (passAsString) { + m_execute << " {\n"; + m_execute << " " << enumValuesAsString.str() << "\n"; + m_execute << " int $__index = " << getOptionVar << ";\n"; + m_execute << " $str += \" -" << commandFlag + << " \\\"\" + $evs[ $__index ] + \"\\\"\";\n"; + m_execute << " }\n"; + } else if (enumValues) { + m_execute << " {\n"; + m_execute << " " << enumValuesAsString.str() << "\n"; + m_execute << " int $__index = " << getOptionVar << ";\n"; + m_execute << " $str += \" -" << commandFlag << " \" + $ev[ $__index ];\n"; + m_execute << " }\n"; + } else { + m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; + } + } else { + // just set the checkbox to the default value + m_load << " optionMenu -e -sl (" << defaultIndex << " + 1) " << optionVar << ";\n"; + + if (passAsString) { + m_execute << " if(`intField -ex " << optionVar << "`)\n"; + m_execute << " {\n"; + m_execute << " " << enumValuesAsString.str() << "\n"; + m_execute << " int $__index = (`optionMenu -q -sl " << optionVar << "` - 1);\n"; + m_execute << " $str += \" -" << commandFlag + << " \\\"\" + $evs[ $__index ] + \"\\\"\";\n"; + m_execute << " }\n"; + } else if (enumValues) { + m_execute << " if(`intField -ex " << optionVar << "`)\n"; + m_execute << " {\n"; + m_execute << " " << enumValuesAsString.str() << "\n"; + m_execute << " int $__index = (`optionMenu -q -sl " << optionVar << "` - 1);\n"; + m_execute << " $str += \" -" << commandFlag << " \" + $ev[ $__index ];\n"; + m_execute << " }\n"; + } else { + m_execute << " if(`intField -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `optionMenu -q -sl " + << optionVar << "` - 1);\n"; + } } - } - // reset checkbox back to the default value - m_reset << " optionMenu -e -sl (" << defaultIndex << " + 1) " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " optionMenu -e -sl (" << defaultIndex << " + 1) " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- void CommandGuiHelper::addRadioButtonGroupOption( - const char* commandFlag, - const char* label, - int defaultIndex, + const char* commandFlag, + const char* label, + int defaultIndex, const char* const enumNames[], - const int32_t enumValues[], - bool persist, - bool passAsString) + const int32_t enumValues[], + bool persist, + bool passAsString) { - // do we have 4 or less options? - int32_t optionCount = 0; - { - while(enumNames[optionCount++]) + // do we have 4 or less options? + int32_t optionCount = 0; { - // if for some reason this is being called with more than 4 options, just use a combo box instead. - if(optionCount > 4) - { - addEnumOption(commandFlag, label, defaultIndex, enumNames, enumValues, persist, passAsString); - return; - } + while (enumNames[optionCount++]) { + // if for some reason this is being called with more than 4 options, just use a combo + // box instead. + if (optionCount > 4) { + addEnumOption( + commandFlag, label, defaultIndex, enumNames, enumValues, persist, passAsString); + return; + } + } + --optionCount; } - --optionCount; - } - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - std::ostringstream enumValuesAsString; - if(passAsString) - { - enumValuesAsString << "$evs = {\"" << enumNames[0] << "\""; - for(int i = 1; enumNames[i]; ++i) - { - enumValuesAsString << ",\"" << enumNames[i] << "\""; - } - enumValuesAsString << "};"; - } - else - if(enumValues) - { - enumValuesAsString << "$ev = {" << enumValues[0]; - for(int i = 1; enumNames[i]; ++i) - { - enumValuesAsString << "," << enumValues[i]; - } - enumValuesAsString << "};"; - } - - // generate checkbox control for boolean argument - m_controls << " radioButtonGrp -h 20 -nrb " << optionCount << " "; - for(int i = 0; enumNames[i]; ++i) - { - m_controls << "-l" << (i+1) << " \"" << enumNames[i] << "\" "; - } - m_controls << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -iv \"" << optionVar << "\" " << defaultIndex << ";\n"; - m_load << " radioButtonGrp -e -sl (" << getOptionVar << " + 1) " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -iv \"" << optionVar << "\" (`radioButtonGrp -q -sl " << optionVar << "` - 1);\n"; - - // build up command string using optionVar value - if(passAsString) - { - m_execute << " {\n"; - m_execute << " " << enumValuesAsString.str() << "\n"; - m_execute << " int $__index = " << getOptionVar << ";\n"; - m_execute << " $str += \" -" << commandFlag << " \\\"\" + $evs[ $__index ] + \"\\\"\";\n"; - m_execute << " }\n"; - } - else - if(enumValues) - { - m_execute << " {\n"; - m_execute << " " << enumValuesAsString.str() << "\n"; - m_execute << " int $__index = " << getOptionVar << ";\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $ev[ $__index ];\n"; - m_execute << " }\n"; - } - else - { - m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + std::ostringstream enumValuesAsString; + if (passAsString) { + enumValuesAsString << "$evs = {\"" << enumNames[0] << "\""; + for (int i = 1; enumNames[i]; ++i) { + enumValuesAsString << ",\"" << enumNames[i] << "\""; + } + enumValuesAsString << "};"; + } else if (enumValues) { + enumValuesAsString << "$ev = {" << enumValues[0]; + for (int i = 1; enumNames[i]; ++i) { + enumValuesAsString << "," << enumValues[i]; + } + enumValuesAsString << "};"; } - } - else - { - // just set the checkbox to the default value - m_load << " radioButtonGrp -e -sl (" << defaultIndex << " + 1) " << optionVar << ";\n"; - if(passAsString) - { - m_execute << " if(`radioButtonGrp -ex " << optionVar << "`)\n"; - m_execute << " {\n"; - m_execute << " " << enumValuesAsString.str() << "\n"; - m_execute << " int $__index = (`radioButtonGrp -q -sl " << optionVar << "` - 1);\n"; - m_execute << " $str += \" -" << commandFlag << " \\\"\" + $evs[ $__index ] + \"\\\"\";\n"; - m_execute << " }\n"; - } - else - if(enumValues) - { - m_execute << " if(`radioButtonGrp -ex " << optionVar << "`)\n"; - m_execute << " {\n"; - m_execute << " " << enumValuesAsString.str() << "\n"; - m_execute << " int $__index = (`radioButtonGrp -q -sl " << optionVar << "` - 1);\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $ev[ $__index ];\n"; - m_execute << " }\n"; + // generate checkbox control for boolean argument + m_controls << " radioButtonGrp -h 20 -nrb " << optionCount << " "; + for (int i = 0; enumNames[i]; ++i) { + m_controls << "-l" << (i + 1) << " \"" << enumNames[i] << "\" "; } - else - { - m_execute << " if(`radioButtonGrp -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `radioButtonGrp -q -sl " << optionVar << "` - 1);\n"; + m_controls << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -iv \"" << optionVar << "\" " << defaultIndex << ";\n"; + m_load << " radioButtonGrp -e -sl (" << getOptionVar << " + 1) " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -iv \"" << optionVar << "\" (`radioButtonGrp -q -sl " << optionVar + << "` - 1);\n"; + + // build up command string using optionVar value + if (passAsString) { + m_execute << " {\n"; + m_execute << " " << enumValuesAsString.str() << "\n"; + m_execute << " int $__index = " << getOptionVar << ";\n"; + m_execute << " $str += \" -" << commandFlag + << " \\\"\" + $evs[ $__index ] + \"\\\"\";\n"; + m_execute << " }\n"; + } else if (enumValues) { + m_execute << " {\n"; + m_execute << " " << enumValuesAsString.str() << "\n"; + m_execute << " int $__index = " << getOptionVar << ";\n"; + m_execute << " $str += \" -" << commandFlag << " \" + $ev[ $__index ];\n"; + m_execute << " }\n"; + } else { + m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; + } + } else { + // just set the checkbox to the default value + m_load << " radioButtonGrp -e -sl (" << defaultIndex << " + 1) " << optionVar << ";\n"; + + if (passAsString) { + m_execute << " if(`radioButtonGrp -ex " << optionVar << "`)\n"; + m_execute << " {\n"; + m_execute << " " << enumValuesAsString.str() << "\n"; + m_execute << " int $__index = (`radioButtonGrp -q -sl " << optionVar << "` - 1);\n"; + m_execute << " $str += \" -" << commandFlag + << " \\\"\" + $evs[ $__index ] + \"\\\"\";\n"; + m_execute << " }\n"; + } else if (enumValues) { + m_execute << " if(`radioButtonGrp -ex " << optionVar << "`)\n"; + m_execute << " {\n"; + m_execute << " " << enumValuesAsString.str() << "\n"; + m_execute << " int $__index = (`radioButtonGrp -q -sl " << optionVar << "` - 1);\n"; + m_execute << " $str += \" -" << commandFlag << " \" + $ev[ $__index ];\n"; + m_execute << " }\n"; + } else { + m_execute << " if(`radioButtonGrp -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `radioButtonGrp -q -sl " + << optionVar << "` - 1);\n"; + } } - } - // reset checkbox back to the default value - m_reset << " radioButtonGrp -e -sl (" << defaultIndex << " + 1) " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " radioButtonGrp -e -sl (" << defaultIndex << " + 1) " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addDoubleOption(const char* commandFlag, const char* label, const double defaultVal, bool persist) +void CommandGuiHelper::addDoubleOption( + const char* commandFlag, + const char* label, + const double defaultVal, + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " floatField -h 20 " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal << ";\n"; - m_load << " floatField -e -v " << getOptionVar << " " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -fv \"" << optionVar << "\" `floatField -q -v " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " floatField -e -v " << defaultVal << " " << optionVar << ";\n"; - - // pull the value from the checkbox when executing - m_execute << " if(`floatField -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `floatField -q -v " << optionVar << "`;\n"; - } + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " floatField -h 20 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal << ";\n"; + m_load << " floatField -e -v " << getOptionVar << " " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -fv \"" << optionVar << "\" `floatField -q -v " << optionVar + << "`;\n"; + + // build up command string using optionVar value + m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; + } else { + // just set the checkbox to the default value + m_load << " floatField -e -v " << defaultVal << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`floatField -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `floatField -q -v " << optionVar + << "`;\n"; + } - // reset checkbox back to the default value - m_reset << " floatField -e -v " << defaultVal << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " floatField -e -v " << defaultVal << " " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addDoubleSliderOption(const char* commandFlag, const char* label, const double minVal, const double maxVal, const double defaultVal, bool persist) +void CommandGuiHelper::addDoubleSliderOption( + const char* commandFlag, + const char* label, + const double minVal, + const double maxVal, + const double defaultVal, + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " floatSlider -h 20 -min " << minVal << " -max " << maxVal << " " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal << ";\n"; - m_load << " floatSlider -e -v " << getOptionVar << " " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -fv \"" << optionVar << "\" `floatSlider -q -v " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " floatSlider -e -v " << defaultVal << " " << optionVar << ";\n"; - - // pull the value from the checkbox when executing - m_execute << " if(`floatSlider -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `floatSlider -q -v " << optionVar << "`;\n"; - } + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " floatSlider -h 20 -min " << minVal << " -max " << maxVal << " " << optionVar + << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal << ";\n"; + m_load << " floatSlider -e -v " << getOptionVar << " " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -fv \"" << optionVar << "\" `floatSlider -q -v " << optionVar + << "`;\n"; + + // build up command string using optionVar value + m_execute << " $str += \" -" << commandFlag << " \" + " << getOptionVar << ";\n"; + } else { + // just set the checkbox to the default value + m_load << " floatSlider -e -v " << defaultVal << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`floatSlider -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `floatSlider -q -v " << optionVar + << "`;\n"; + } - // reset checkbox back to the default value - m_reset << " floatSlider -e -v " << defaultVal << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " floatSlider -e -v " << defaultVal << " " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addVec2Option(const char* commandFlag, const char* label, const double defaultVal[2], bool persist) +void CommandGuiHelper::addVec2Option( + const char* commandFlag, + const char* label, + const double defaultVal[2], + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " floatFieldGrp -h 20 -nf 2 " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal[0] - << " -fva \"" << optionVar << "\" " << defaultVal[1] << ";\n"; - - m_load << " $fv = " << getOptionVar << ";\n"; - m_load << " floatFieldGrp -e -v1 $fv[0] -v2 $fv[1] " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -fv \"" << optionVar << "\" `floatFieldGrp -q -v1 " << optionVar - << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v2 " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " $fv = " << getOptionVar << ";\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $fv[0] + \" \" + $fv[1] + \" \";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " floatFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] << " " << optionVar << ";\n"; + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " floatFieldGrp -h 20 -nf 2 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal[0] << " -fva \"" + << optionVar << "\" " << defaultVal[1] << ";\n"; + + m_load << " $fv = " << getOptionVar << ";\n"; + m_load << " floatFieldGrp -e -v1 $fv[0] -v2 $fv[1] " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -fv \"" << optionVar << "\" `floatFieldGrp -q -v1 " << optionVar + << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v2 " << optionVar << "`;\n"; + + // build up command string using optionVar value + m_execute << " $fv = " << getOptionVar << ";\n"; + m_execute << " $str += \" -" << commandFlag << " \" + $fv[0] + \" \" + $fv[1] + \" \";\n"; + } else { + // just set the checkbox to the default value + m_load << " floatFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " " + << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`floatFieldGrp -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `floatFieldGrp -q -v1 " << optionVar + << "` + \" \" + `floatFieldGrp -q -v2 " << optionVar << "`;\n"; + } - // pull the value from the checkbox when executing - m_execute << " if(`floatFieldGrp -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `floatFieldGrp -q -v1 " << optionVar - << "` + \" \" + `floatFieldGrp -q -v2 " << optionVar << "`;\n"; - } - - // reset checkbox back to the default value - m_reset << " floatFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " floatFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " " + << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addVec3Option(const char* commandFlag, const char* label, const double defaultVal[3], bool persist) +void CommandGuiHelper::addVec3Option( + const char* commandFlag, + const char* label, + const double defaultVal[3], + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " floatFieldGrp -h 20 -nf 3 " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal[0] - << " -fva \"" << optionVar << "\" " << defaultVal[1] - << " -fva \"" << optionVar << "\" " << defaultVal[2] << ";\n"; - - m_load << " $fv = " << getOptionVar << ";\n"; - m_load << " floatFieldGrp -e -v1 $fv[0] -v2 $fv[1] -v3 $fv[2] " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -fv \"" << optionVar << "\" `floatFieldGrp -q -v1 " << optionVar - << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v2 " << optionVar - << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v3 " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " $fv = " << getOptionVar << ";\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $fv[0] + \" \" + $fv[1] + \" \" + $fv[2] + \" \";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " floatFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] - << " -v3 " << defaultVal[2] << " " << optionVar << ";\n"; + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " floatFieldGrp -h 20 -nf 3 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal[0] << " -fva \"" + << optionVar << "\" " << defaultVal[1] << " -fva \"" << optionVar << "\" " + << defaultVal[2] << ";\n"; + + m_load << " $fv = " << getOptionVar << ";\n"; + m_load << " floatFieldGrp -e -v1 $fv[0] -v2 $fv[1] -v3 $fv[2] " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -fv \"" << optionVar << "\" `floatFieldGrp -q -v1 " << optionVar + << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v2 " << optionVar + << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v3 " << optionVar << "`;\n"; + + // build up command string using optionVar value + m_execute << " $fv = " << getOptionVar << ";\n"; + m_execute << " $str += \" -" << commandFlag + << " \" + $fv[0] + \" \" + $fv[1] + \" \" + $fv[2] + \" \";\n"; + } else { + // just set the checkbox to the default value + m_load << " floatFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " -v3 " + << defaultVal[2] << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`floatFieldGrp -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `floatFieldGrp -q -v1 " << optionVar + << "` + \" \" + `floatFieldGrp -q -v2 " << optionVar + << "` + \" \" + `floatFieldGrp -q -v3 " << optionVar << "`;\n"; + } - // pull the value from the checkbox when executing - m_execute << " if(`floatFieldGrp -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `floatFieldGrp -q -v1 " << optionVar - << "` + \" \" + `floatFieldGrp -q -v2 " << optionVar - << "` + \" \" + `floatFieldGrp -q -v3 " << optionVar << "`;\n"; - } - - // reset checkbox back to the default value - m_reset << " floatFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] - << " -v3 " << defaultVal[2] << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " floatFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " -v3 " + << defaultVal[2] << " " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addVec4Option(const char* commandFlag, const char* label, const double defaultVal[4], bool persist) +void CommandGuiHelper::addVec4Option( + const char* commandFlag, + const char* label, + const double defaultVal[4], + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " floatFieldGrp -h 20 -nf 4 " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal[0] - << " -fva \"" << optionVar << "\" " << defaultVal[1] - << " -fva \"" << optionVar << "\" " << defaultVal[2] - << " -fva \"" << optionVar << "\" " << defaultVal[3] << ";\n"; - - m_load << " $fv = " << getOptionVar << ";\n"; - m_load << " floatFieldGrp -e -v1 $fv[0] -v2 $fv[1] -v3 $fv[2] -v4 $fv[3] " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -fv \"" << optionVar << "\" `floatFieldGrp -q -v1 " << optionVar - << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v2 " << optionVar - << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v3 " << optionVar - << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v4 " << optionVar << "`;\n"; - - // build up command string using optionVar value - m_execute << " $fv = " << getOptionVar << ";\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $fv[0] + \" \" + $fv[1] + \" \" + $fv[2] + \" \" + $fv[3] + \" \";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " floatFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] - << " -v3 " << defaultVal[2] - << " -v4 " << defaultVal[3] << " " << optionVar << ";\n"; + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " floatFieldGrp -h 20 -nf 4 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal[0] << " -fva \"" + << optionVar << "\" " << defaultVal[1] << " -fva \"" << optionVar << "\" " + << defaultVal[2] << " -fva \"" << optionVar << "\" " << defaultVal[3] << ";\n"; + + m_load << " $fv = " << getOptionVar << ";\n"; + m_load << " floatFieldGrp -e -v1 $fv[0] -v2 $fv[1] -v3 $fv[2] -v4 $fv[3] " << optionVar + << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -fv \"" << optionVar << "\" `floatFieldGrp -q -v1 " << optionVar + << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v2 " << optionVar + << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v3 " << optionVar + << "` -fva \"" << optionVar << "\" `floatFieldGrp -q -v4 " << optionVar << "`;\n"; + + // build up command string using optionVar value + m_execute << " $fv = " << getOptionVar << ";\n"; + m_execute << " $str += \" -" << commandFlag + << " \" + $fv[0] + \" \" + $fv[1] + \" \" + $fv[2] + \" \" + $fv[3] + \" \";\n"; + } else { + // just set the checkbox to the default value + m_load << " floatFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " -v3 " + << defaultVal[2] << " -v4 " << defaultVal[3] << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`floatFieldGrp -ex " << optionVar << "`)\n"; + m_execute << " $str += \" -" << commandFlag << " \" + `floatFieldGrp -q -v1 " << optionVar + << "` + \" \" + `floatFieldGrp -q -v2 " << optionVar + << "` + \" \" + `floatFieldGrp -q -v3 " << optionVar + << "` + \" \" + `floatFieldGrp -q -v4 " << optionVar << "`;\n"; + } - // pull the value from the checkbox when executing - m_execute << " if(`floatFieldGrp -ex " << optionVar << "`)\n"; - m_execute << " $str += \" -" << commandFlag << " \" + `floatFieldGrp -q -v1 " << optionVar - << "` + \" \" + `floatFieldGrp -q -v2 " << optionVar - << "` + \" \" + `floatFieldGrp -q -v3 " << optionVar - << "` + \" \" + `floatFieldGrp -q -v4 " << optionVar << "`;\n"; - } - - // reset checkbox back to the default value - m_reset << " floatFieldGrp -e -v1 " << defaultVal[0] - << " -v2 " << defaultVal[1] - << " -v3 " << defaultVal[2] - << " -v4 " << defaultVal[3] << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " floatFieldGrp -e -v1 " << defaultVal[0] << " -v2 " << defaultVal[1] << " -v3 " + << defaultVal[2] << " -v4 " << defaultVal[3] << " " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addColourOption(const char* commandFlag, const char* label, const double defaultVal[3], bool persist) +void CommandGuiHelper::addColourOption( + const char* commandFlag, + const char* label, + const double defaultVal[3], + bool persist) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " colorSliderGrp -h 20 " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal[0] - << " -fva \"" << optionVar << "\" " << defaultVal[1] - << " -fva \"" << optionVar << "\" " << defaultVal[2] << ";\n"; - - m_load << " $fv = " << getOptionVar << ";\n"; - m_load << " colorSliderGrp -e -rgb $fv[0] $fv[1] $fv[2] " << optionVar << ";\n"; - - // pull value from checkbox, and insert into the optionVar - m_save << " $cv = `colorSliderGrp -q -rgb " << optionVar << "`;\n"; - m_save << " optionVar -fv \"" << optionVar << "\" $cv[0] " - << " -fva \"" << optionVar << "\" $cv[1] " - << " -fva \"" << optionVar << "\" $cv[2];\n"; - - // build up command string using optionVar value - m_execute << " $cv = " << getOptionVar << ";\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $cv[0] + \" \" + $cv[1] + \" \" + $cv[2] + \" \";\n"; - } - else - { - // just set the checkbox to the default value - m_load << " colorSliderGrp -e -rgb " << defaultVal[0] - << " " << defaultVal[1] - << " " << defaultVal[2] << " " << optionVar << ";\n"; + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " colorSliderGrp -h 20 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -fv \"" << optionVar << "\" " << defaultVal[0] << " -fva \"" + << optionVar << "\" " << defaultVal[1] << " -fva \"" << optionVar << "\" " + << defaultVal[2] << ";\n"; + + m_load << " $fv = " << getOptionVar << ";\n"; + m_load << " colorSliderGrp -e -rgb $fv[0] $fv[1] $fv[2] " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " $cv = `colorSliderGrp -q -rgb " << optionVar << "`;\n"; + m_save << " optionVar -fv \"" << optionVar << "\" $cv[0] " + << " -fva \"" << optionVar << "\" $cv[1] " + << " -fva \"" << optionVar << "\" $cv[2];\n"; + + // build up command string using optionVar value + m_execute << " $cv = " << getOptionVar << ";\n"; + m_execute << " $str += \" -" << commandFlag + << " \" + $cv[0] + \" \" + $cv[1] + \" \" + $cv[2] + \" \";\n"; + } else { + // just set the checkbox to the default value + m_load << " colorSliderGrp -e -rgb " << defaultVal[0] << " " << defaultVal[1] << " " + << defaultVal[2] << " " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + m_execute << " if(`colorSliderGrp -ex " << optionVar << "`) {\n"; + m_execute << " $cv = `colorSliderGrp -q -rgb " << optionVar << "`;\n"; + m_execute << " $str += \" -" << commandFlag << " \" + $cv[0] " + << "+ \" \" + $cv[1] " + << "+ \" \" + $cv[2];\n"; + m_execute << " }\n"; + } - // pull the value from the checkbox when executing - m_execute << " if(`colorSliderGrp -ex " << optionVar << "`) {\n"; - m_execute << " $cv = `colorSliderGrp -q -rgb " << optionVar << "`;\n"; - m_execute << " $str += \" -" << commandFlag << " \" + $cv[0] " - << "+ \" \" + $cv[1] " - << "+ \" \" + $cv[2];\n"; - m_execute << " }\n"; - } - - // reset checkbox back to the default value - m_reset << " colorSliderGrp -e -rgb " << defaultVal[0] - << " " << defaultVal[1] - << " " << defaultVal[2] << " " << optionVar << ";\n"; + // reset checkbox back to the default value + m_reset << " colorSliderGrp -e -rgb " << defaultVal[0] << " " << defaultVal[1] << " " + << defaultVal[2] << " " << optionVar << ";\n"; } //---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addStringOption(const char* commandFlag, const char* label, MString defaultVal, bool persist, StringPolicy policy) +void CommandGuiHelper::addStringOption( + const char* commandFlag, + const char* label, + MString defaultVal, + bool persist, + StringPolicy policy) { - const std::string optionVar = m_commandName + "_" + commandFlag; - const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; - - // generate checkbox control for boolean argument - m_controls << " textField -h 20 " << optionVar << ";\n"; + const std::string optionVar = m_commandName + "_" + commandFlag; + const std::string getOptionVar = std::string("`optionVar -q \"") + optionVar + "\"`"; + + // generate checkbox control for boolean argument + m_controls << " textField -h 20 " << optionVar << ";\n"; + + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + + // if the default value does not exist, force it to exist using the default value. Then set the + // control value + if (persist) { + m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; + m_init << " optionVar -sv \"" << optionVar << "\" " << defaultVal << ";\n"; + m_load << " textField -e -tx " << getOptionVar << " " << optionVar << ";\n"; + + // pull value from checkbox, and insert into the optionVar + m_save << " optionVar -sv \"" << optionVar << "\" `textField -q -tx " << optionVar + << "`;\n"; + + // build up command string using optionVar value + if (policy == kStringOptional) { + m_execute << " if(size(" << getOptionVar << "))\n"; + m_execute << " $str += \" -" << commandFlag << " \\\"\" + " << getOptionVar + << " + \"\\\"\";\n"; + } else if (policy == kStringMustHaveValue) { + m_execute << " if(!size(" << getOptionVar << ")) {\n"; + m_execute << " error \"" << label << " must be specified\";\n return;\n }\n"; + m_execute << " $str += \" -" << commandFlag << " \\\"\" + " << getOptionVar + << " + \"\\\"\";\n"; + } else { + std::cerr << "unknown string policy" << std::endl; + } + } else { + // just set the checkbox to the default value + m_load << " textField -e -tx \"" << defaultVal << "\" " << optionVar << ";\n"; + + // pull the value from the checkbox when executing + if (policy == kStringOptional) { + m_execute << " if(`textField -ex " << optionVar << "`)\n"; + m_execute << " if(size(`textField -q -tx " << optionVar << "`))\n"; + m_execute << " $str += \" -" << commandFlag << " \\\"\" + `textField -q -tx " + << optionVar << "` + \"\\\"\";\n"; + } else if (policy == kStringMustHaveValue) { + m_execute << " if(`textField -ex " << optionVar << "`)\n"; + m_execute << " if(!size(`textField -q -tx " << optionVar << "`)) {\n"; + m_execute << " error \"" << label + << " must be specified\";\n return;\n }\n else\n"; + m_execute << " $str += \" -" << commandFlag << " \\\"\" + `textField -q -tx " + << optionVar << "` + \"\\\"\";\n"; + } else { + std::cerr << "unknown string policy" << std::endl; + } + } - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; + // reset checkbox back to the default value + m_reset << " textField -e -tx \"" << defaultVal << "\" " << optionVar << ";\n"; +} - // if the default value does not exist, force it to exist using the default value. Then set the control value - if(persist) - { - m_init << " if(!`optionVar -ex \"" << optionVar << "\"`)\n"; - m_init << " optionVar -sv \"" << optionVar << "\" " << defaultVal << ";\n"; - m_load << " textField -e -tx " << getOptionVar << " " << optionVar << ";\n"; +//---------------------------------------------------------------------------------------------------------------------- +void CommandGuiHelper::addFilePathOption( + const char* commandFlag, + const char* label, + FileMode fileMode, + const char* filter, + StringPolicy policy) +{ + const std::string optionVar = m_commandName + "_" + commandFlag; - // pull value from checkbox, and insert into the optionVar - m_save << " optionVar -sv \"" << optionVar << "\" `textField -q -tx " << optionVar << "`;\n"; + // generate checkbox control for boolean argument + m_controls << " textFieldButtonGrp -h 20 -bl \"...\" -bc \"alFileDialogHandler(\\\"" << filter + << "\\\", \\\"" << optionVar << "\\\", " << fileMode << ")\" " << optionVar << ";\n"; - // build up command string using optionVar value - if(policy == kStringOptional) - { - m_execute << " if(size(" << getOptionVar << "))\n"; - m_execute << " $str += \" -" << commandFlag << " \\\"\" + " << getOptionVar << " + \"\\\"\";\n"; - } - else - if(policy == kStringMustHaveValue) - { - m_execute << " if(!size(" << getOptionVar << ")) {\n"; - m_execute << " error \"" << label << " must be specified\";\n return;\n }\n"; - m_execute << " $str += \" -" << commandFlag << " \\\"\" + " << getOptionVar << " + \"\\\"\";\n"; - } - else - { - std::cerr << "unknown string policy" << std::endl; - } - } - else - { - // just set the checkbox to the default value - m_load << " textField -e -tx \"" << defaultVal << "\" " << optionVar << ";\n"; + // add label + m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; // pull the value from the checkbox when executing - if(policy == kStringOptional) - { - m_execute << " if(`textField -ex " << optionVar << "`)\n"; - m_execute << " if(size(`textField -q -tx " << optionVar << "`))\n"; - m_execute << " $str += \" -" << commandFlag << " \\\"\" + `textField -q -tx " << optionVar << "` + \"\\\"\";\n"; - } - else - if(policy == kStringMustHaveValue) - { - m_execute << " if(`textField -ex " << optionVar << "`)\n"; - m_execute << " if(!size(`textField -q -tx " << optionVar << "`)) {\n"; - m_execute << " error \"" << label << " must be specified\";\n return;\n }\n else\n"; - m_execute << " $str += \" -" << commandFlag << " \\\"\" + `textField -q -tx " << optionVar << "` + \"\\\"\";\n"; + if (policy == kStringOptional) { + m_execute << " if(`textFieldButtonGrp -ex " << optionVar << "`)\n"; + m_execute << " if(size(`textFieldButtonGrp -q -fi " << optionVar << "`))\n"; + m_execute << " $str += \" -" << commandFlag << " \\\"\" + `textFieldButtonGrp -q -fi " + << optionVar << "` + \"\\\"\";\n"; + } else if (policy == kStringMustHaveValue) { + m_execute << " if(`textFieldButtonGrp -ex " << optionVar << "`)\n"; + m_execute << " if(!size(`textFieldButtonGrp -q -fi " << optionVar << "`)) {\n"; + m_execute << " error \"" << label << " must be specified\";\n return;\n }\n"; + m_execute << " $str += \" -" << commandFlag << " \\\"\" + `textFieldButtonGrp -q -fi " + << optionVar << "` + \"\\\"\";\n"; + } else { + std::cerr << "unknown string policy" << std::endl; } - else - { - std::cerr << "unknown string policy" << std::endl; - } - } - // reset checkbox back to the default value - m_reset << " textField -e -tx \"" << defaultVal << "\" " << optionVar << ";\n"; -} + // reset checkbox back to the default value + m_reset << " textFieldButtonGrp -e -fi \"\" " << optionVar << ";\n"; -//---------------------------------------------------------------------------------------------------------------------- -void CommandGuiHelper::addFilePathOption(const char* commandFlag, const char* label, FileMode fileMode, const char* filter, StringPolicy policy) -{ - const std::string optionVar = m_commandName + "_" + commandFlag; - - // generate checkbox control for boolean argument - m_controls << " textFieldButtonGrp -h 20 -bl \"...\" -bc \"alFileDialogHandler(\\\"" << filter << "\\\", \\\"" << optionVar << "\\\", " << fileMode << ")\" " << optionVar << ";\n"; - - // add label - m_labels << " text -al \"right\" -h 20 -w 160 -l \"" << label << ":\";\n"; - - // pull the value from the checkbox when executing - if(policy == kStringOptional) - { - m_execute << " if(`textFieldButtonGrp -ex " << optionVar << "`)\n"; - m_execute << " if(size(`textFieldButtonGrp -q -fi " << optionVar << "`))\n"; - m_execute << " $str += \" -" << commandFlag << " \\\"\" + `textFieldButtonGrp -q -fi " << optionVar << "` + \"\\\"\";\n"; - } - else - if(policy == kStringMustHaveValue) - { - m_execute << " if(`textFieldButtonGrp -ex " << optionVar << "`)\n"; - m_execute << " if(!size(`textFieldButtonGrp -q -fi " << optionVar << "`)) {\n"; - m_execute << " error \"" << label << " must be specified\";\n return;\n }\n"; - m_execute << " $str += \" -" << commandFlag << " \\\"\" + `textFieldButtonGrp -q -fi " << optionVar << "` + \"\\\"\";\n"; - } - else - { - std::cerr << "unknown string policy" << std::endl; - } - - // reset checkbox back to the default value - m_reset << " textFieldButtonGrp -e -fi \"\" " << optionVar << ";\n"; - - m_hasFilePath = true; + m_hasFilePath = true; } //---------------------------------------------------------------------------------------------------------------------- -} // utils -} // maya -} // AL +} // namespace utils +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/mayautils/AL/maya/utils/CommandGuiHelper.h b/plugin/al/mayautils/AL/maya/utils/CommandGuiHelper.h index 6050a4ff53..a711447176 100644 --- a/plugin/al/mayautils/AL/maya/utils/CommandGuiHelper.h +++ b/plugin/al/mayautils/AL/maya/utils/CommandGuiHelper.h @@ -17,7 +17,6 @@ #pragma once #include "AL/maya/utils/Api.h" - #include "AL/maya/utils/MayaHelperMacros.h" #include @@ -29,56 +28,60 @@ namespace AL { namespace maya { namespace utils { -/// \brief Callback type used to provide a list of *things* to an optionMenu control in an option box GUI +/// \brief Callback type used to provide a list of *things* to an optionMenu control in an option +/// box GUI typedef MStringArray (*GenerateListFn)(const MString& context); //---------------------------------------------------------------------------------------------------------------------- /// \brief A method used by the generated command GUI code to retrieve a list of items from C++. /// \ingroup mayagui //---------------------------------------------------------------------------------------------------------------------- -class CommandGuiListGen - : public MPxCommand +class CommandGuiListGen : public MPxCommand { public: - AL_MAYA_DECLARE_COMMAND(); - - /// \brief Internal method. Registers a custom list function with this command so that MEL can request a custom C++ - /// command to generate a list of items, which are then displayed within a MEL GUI. - /// \param generateListFunc a C++ function that can take an optional user specified 'context', and return a list of - /// items to display within the GUI. - /// \param menuName the GUI control to which the menu items will be appended. - /// \return the unique ID for this generator - AL_MAYA_UTILS_PUBLIC - static int32_t registerListFunc(GenerateListFn generateListFunc, const MString& menuName); + AL_MAYA_DECLARE_COMMAND(); + + /// \brief Internal method. Registers a custom list function with this command so that MEL can + /// request a custom C++ + /// command to generate a list of items, which are then displayed within a MEL GUI. + /// \param generateListFunc a C++ function that can take an optional user specified 'context', + /// and return a list of + /// items to display within the GUI. + /// \param menuName the GUI control to which the menu items will be appended. + /// \return the unique ID for this generator + AL_MAYA_UTILS_PUBLIC + static int32_t registerListFunc(GenerateListFn generateListFunc, const MString& menuName); private: - bool isUndoable() const override { return false; } - MStatus doIt(const MArgList& args) override; - static std::vector> m_funcs; + bool isUndoable() const override { return false; } + MStatus doIt(const MArgList& args) override; + static std::vector> m_funcs; }; //---------------------------------------------------------------------------------------------------------------------- -/// \brief This class isn't really a wrapper around command options as such, it's mainly just a helper +/// \brief This class isn't really a wrapper around command options as such, it's mainly just a +/// helper /// to auto generate some GUI code to create a menu item + option box dialog. /// \note -/// The following example code demonstrates how to use the CommandGuiHelper class to autogenerate a menu item, -/// which will be available in the menu path "USD" -> "polygons" -> "Create Cube"; This will call the mel command "polyCube". -/// The total command called will be something akin to: +/// The following example code demonstrates how to use the CommandGuiHelper class to autogenerate a +/// menu item, which will be available in the menu path "USD" -> "polygons" -> "Create Cube"; This +/// will call the mel command "polyCube". The total command called will be something akin to: /// -/// polyCube -constructionHistory true -width 1 -height 1.1 -depth 1.2 -subdivisionsX 1 subdivisionsY 2 -subdivisionsZ 3 -name "pCube" +/// polyCube -constructionHistory true -width 1 -height 1.1 -depth 1.2 -subdivisionsX 1 +/// subdivisionsY 2 -subdivisionsZ 3 -name "pCube" /// -/// However all of the numeric values will actually be stored as optionVar's. (see the optionVar mel command, or MGlobal class) -/// If the command is "polyCube", and the flag is "constructionHistory", then the optionVar used to store the preference -/// will be "polyCube_constructionHistory". +/// However all of the numeric values will actually be stored as optionVar's. (see the optionVar mel +/// command, or MGlobal class) If the command is "polyCube", and the flag is "constructionHistory", +/// then the optionVar used to store the preference will be "polyCube_constructionHistory". /// -/// Whilst I'm using "polyCube" as an example of how to use this class, you'd probably want to use this for your own -/// MPxCommand derived classes. +/// Whilst I'm using "polyCube" as an example of how to use this class, you'd probably want to use +/// this for your own MPxCommand derived classes. /// /// \code /// { -/// AL::maya::CommandGuiHelper options("polyCube", "Create Polygon Cube", "Create", "USD/polygons/Create Cube"); -/// options.addBoolOption("constructionHistory", "Construction History", true, true); -/// options.addDoubleOption("width", "Width", 1.0, true); +/// AL::maya::CommandGuiHelper options("polyCube", "Create Polygon Cube", "Create", +/// "USD/polygons/Create Cube"); options.addBoolOption("constructionHistory", "Construction +/// History", true, true); options.addDoubleOption("width", "Width", 1.0, true); /// options.addDoubleOption("height", "Height", 1.1, true); /// options.addDoubleOption("depth", "Depth", 1.2, true); /// options.addIntOption("subdivisionsX", "Subdivisions in X", 1, true); @@ -89,366 +92,490 @@ class CommandGuiListGen /// } /// \endcode /// -/// If the above code is called somewhere within your initialisePlugin method, and you end up calling -/// AL::maya::MenuBuilder::generatePluginUI() at the end of your initialise method, then that command (+optionBox) will -/// be available on the main maya menu. -/// \ingroup mayagui +/// If the above code is called somewhere within your initialisePlugin method, and you end up +/// calling AL::maya::MenuBuilder::generatePluginUI() at the end of your initialise method, then +/// that command (+optionBox) will be available on the main maya menu. \ingroup mayagui //---------------------------------------------------------------------------------------------------------------------- class CommandGuiHelper { public: - - /// \brief Used to describe the type of file dialog that should be used for a file path attribute - enum FileMode - { - kSave = 0, ///< a save file dialog - kLoad = 1, ///< a load file dialog - kDirectoryWithFiles = 2, ///< a directory dialog, but displays files. - kDirectory = 3, ///< a directory dialog - kMultiLoad = 4 ///< multiple input files - }; - - /// \brief determines if a text string argument is optional (e.g. a name of the object if specified, but falls back - /// to a default if not), or whether it must exist (e.g. for a file to open) - enum StringPolicy - { - kStringOptional, ///< if the string value is empty, the flag will be omitted. - kStringMustHaveValue ///< if the string is empty, it is an error. - }; - - /// \brief ctor - /// \param commandName the name of the mel command to execute - /// \param windowTitle the title to display at the top of the option box. - /// \param doitLabel The label that will appear on the 'Create/Yes/DoIt' button on the left hand side of the dialog - /// \param menuItemPath determines the path to the menu item from the main menu. - /// \param hasOptionBox If true, the dialog will only be executed when the option box button is clicked. - /// If false, there will be no option box, and the GUI will always be displayed. - AL_MAYA_UTILS_PUBLIC - CommandGuiHelper(const char* commandName, const char* windowTitle, const char* doitLabel, const char* menuItemPath, bool hasOptionBox = true); - - /// \brief ctor - /// \brief add a menu item with a checkbox - /// \param commandName the name of the mel command to execute - /// \param menuItemPath determines the path to the menu item from the main menu. - /// \param checkBoxValue the default value for the checkbox - AL_MAYA_UTILS_PUBLIC - CommandGuiHelper(const char* commandName, const char* menuItemPath, bool checkBoxValue = false); - - /// \brief dtor - auto generates, and executes the GUI code. - AL_MAYA_UTILS_PUBLIC - ~CommandGuiHelper(); - - /// \brief add some text to the execute command, unconditionally - /// Useful if, ie, you always want to set a non-default command flag - /// \param toAdd extra flags / text to add to the execution command - AL_MAYA_UTILS_PUBLIC - void addExecuteText(const char* toAdd); - - /// \brief add a boolean option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addFlagOption(const char* commandFlag, const char* label, bool defaultVal, bool persist = true); - - /// \brief add a boolean option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addBoolOption(const char* commandFlag, const char* label, bool defaultVal, bool persist = true); - - /// \brief add an integer option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addIntOption(const char* commandFlag, const char* label, int32_t defaultVal, bool persist = true); - - /// \brief add an integer option value to the GUI (with min/max, displayed as a slider) - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param minVal the minimum value for the slider range - /// \param maxVal the maximum value for the slider range - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addIntSliderOption(const char* commandFlag, const char* label, int32_t minVal, int32_t maxVal, int32_t defaultVal, bool persist = true); - - /// \brief add a 2D integer option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addInt2Option(const char* commandFlag, const char* label, const int32_t defaultVal[2], bool persist = true); - - /// \brief add a 2D integer option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param a the default value for the 1st value of the flag - /// \param b the default value for the 2st value of the flag - /// \param persist if true, the GUI option will be persisted as an optionVar - void addInt2Option(const char* commandFlag, const char* label, const int32_t a, const int32_t b, bool persist = true) + /// \brief Used to describe the type of file dialog that should be used for a file path + /// attribute + enum FileMode + { + kSave = 0, ///< a save file dialog + kLoad = 1, ///< a load file dialog + kDirectoryWithFiles = 2, ///< a directory dialog, but displays files. + kDirectory = 3, ///< a directory dialog + kMultiLoad = 4 ///< multiple input files + }; + + /// \brief determines if a text string argument is optional (e.g. a name of the object if + /// specified, but falls back + /// to a default if not), or whether it must exist (e.g. for a file to open) + enum StringPolicy + { + kStringOptional, ///< if the string value is empty, the flag will be omitted. + kStringMustHaveValue ///< if the string is empty, it is an error. + }; + + /// \brief ctor + /// \param commandName the name of the mel command to execute + /// \param windowTitle the title to display at the top of the option box. + /// \param doitLabel The label that will appear on the 'Create/Yes/DoIt' button on the left + /// hand side of the dialog \param menuItemPath determines the path to the menu item from the + /// main menu. \param hasOptionBox If true, the dialog will only be executed when the option + /// box button is clicked. + /// If false, there will be no option box, and the GUI will always be + /// displayed. + AL_MAYA_UTILS_PUBLIC + CommandGuiHelper( + const char* commandName, + const char* windowTitle, + const char* doitLabel, + const char* menuItemPath, + bool hasOptionBox = true); + + /// \brief ctor + /// \brief add a menu item with a checkbox + /// \param commandName the name of the mel command to execute + /// \param menuItemPath determines the path to the menu item from the main menu. + /// \param checkBoxValue the default value for the checkbox + AL_MAYA_UTILS_PUBLIC + CommandGuiHelper(const char* commandName, const char* menuItemPath, bool checkBoxValue = false); + + /// \brief dtor - auto generates, and executes the GUI code. + AL_MAYA_UTILS_PUBLIC + ~CommandGuiHelper(); + + /// \brief add some text to the execute command, unconditionally + /// Useful if, ie, you always want to set a non-default command flag + /// \param toAdd extra flags / text to add to the execution command + AL_MAYA_UTILS_PUBLIC + void addExecuteText(const char* toAdd); + + /// \brief add a boolean option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void + addFlagOption(const char* commandFlag, const char* label, bool defaultVal, bool persist = true); + + /// \brief add a boolean option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void + addBoolOption(const char* commandFlag, const char* label, bool defaultVal, bool persist = true); + + /// \brief add an integer option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void addIntOption( + const char* commandFlag, + const char* label, + int32_t defaultVal, + bool persist = true); + + /// \brief add an integer option value to the GUI (with min/max, displayed as a slider) + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param minVal the minimum value for the slider range + /// \param maxVal the maximum value for the slider range + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void addIntSliderOption( + const char* commandFlag, + const char* label, + int32_t minVal, + int32_t maxVal, + int32_t defaultVal, + bool persist = true); + + /// \brief add a 2D integer option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void addInt2Option( + const char* commandFlag, + const char* label, + const int32_t defaultVal[2], + bool persist = true); + + /// \brief add a 2D integer option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param a the default value for the 1st value of the flag + /// \param b the default value for the 2st value of the flag + /// \param persist if true, the GUI option will be persisted as an optionVar + void addInt2Option( + const char* commandFlag, + const char* label, + const int32_t a, + const int32_t b, + bool persist = true) { - const int32_t temp[] = {a, b}; - addInt2Option(commandFlag, label, temp, persist); + const int32_t temp[] = { a, b }; + addInt2Option(commandFlag, label, temp, persist); } - /// \brief add a 3D integer option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addInt3Option(const char* commandFlag, const char* label, const int32_t defaultVal[3], bool persist = true); - - /// \brief add a 3D integer option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param a the default value for the 1st value of the flag - /// \param b the default value for the 2st value of the flag - /// \param c the default value for the 3rd value of the flag - /// \param persist if true, the GUI option will be persisted as an optionVar - void addInt3Option(const char* commandFlag, const char* label, const int32_t a, const int32_t b, const int32_t c, bool persist = true) + /// \brief add a 3D integer option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void addInt3Option( + const char* commandFlag, + const char* label, + const int32_t defaultVal[3], + bool persist = true); + + /// \brief add a 3D integer option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param a the default value for the 1st value of the flag + /// \param b the default value for the 2st value of the flag + /// \param c the default value for the 3rd value of the flag + /// \param persist if true, the GUI option will be persisted as an optionVar + void addInt3Option( + const char* commandFlag, + const char* label, + const int32_t a, + const int32_t b, + const int32_t c, + bool persist = true) { - const int32_t temp[] = {a, b, c}; - addInt3Option(commandFlag, label, temp, persist); + const int32_t temp[] = { a, b, c }; + addInt3Option(commandFlag, label, temp, persist); } - /// \brief add a 4D integer option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addInt4Option(const char* commandFlag, const char* label, const int32_t defaultVal[4], bool persist = true); - - /// \brief add a 4D integer option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param a the default value for the 1st value of the flag - /// \param b the default value for the 2st value of the flag - /// \param c the default value for the 3rd value of the flag - /// \param d the default value for the 4th value of the flag - /// \param persist if true, the GUI option will be persisted as an optionVar - void addInt4Option(const char* commandFlag, const char* label, const int32_t a, const int32_t b, const int32_t c, const int32_t d, bool persist = true) + /// \brief add a 4D integer option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void addInt4Option( + const char* commandFlag, + const char* label, + const int32_t defaultVal[4], + bool persist = true); + + /// \brief add a 4D integer option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param a the default value for the 1st value of the flag + /// \param b the default value for the 2st value of the flag + /// \param c the default value for the 3rd value of the flag + /// \param d the default value for the 4th value of the flag + /// \param persist if true, the GUI option will be persisted as an optionVar + void addInt4Option( + const char* commandFlag, + const char* label, + const int32_t a, + const int32_t b, + const int32_t c, + const int32_t d, + bool persist = true) { - const int32_t temp[] = {a, b, c, d}; - addInt4Option(commandFlag, label, temp, persist); + const int32_t temp[] = { a, b, c, d }; + addInt4Option(commandFlag, label, temp, persist); } - /// \brief adds a dynamic drop down list of items that will be displayed within an optionMenu control. - /// The list of text strings will be generated within C++ by the custom generateList function, which will then - /// be chosen to represent the list of options available for this command. When the command is executed, the - /// selected item will be passed to the command as a text string. - /// \note Only string command options are supported for this control type, and the command GUI must be created with - /// the 'hasOptionBox' option of the constructor set to false. - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param generateList The C++ command to build up a list of text strings for the GUI to display - /// \param isMandatory If true, our commandFlag is actually a mandatory argument, not a option / flag - AL_MAYA_UTILS_PUBLIC - void addListOption(const char* commandFlag, const char* label, GenerateListFn generateList, bool isMandatory=false); - - /// \brief add an enum option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultIndex the default index into the enumNames/enumValues for the enum - /// \param enumNames an array of text string names (last string must be NULL) for the enum entries. e.g. - /// \code - /// const char* const enumStrings[] = { - /// "up", - /// "down", - /// "left", - /// "right", - /// 0 - /// }; - /// \endcode - /// \param enumValues an array of integer values that match up to the enumNames. This array can be NULL, - /// in which case it is assumed that the enum values are 0, 1, 2, 3, etc. - /// \param persist if true, the GUI option will be persisted as an optionVar - /// \param passAsString if true, the command will be passed the text string value of the enum. If false, - /// a numeric value will be passed instead. - AL_MAYA_UTILS_PUBLIC - void addEnumOption( - const char* commandFlag, - const char* label, - int defaultIndex, - const char* const enumNames[], - const int32_t enumValues[], - bool persist = true, - bool passAsString = false); - - /// \brief Similar to the enum option, but this time with radio buttons. THE MAXIMUM NUMBER OF OPTIONS IS 4. - /// If you exceed this, the code will default to using a combo box for display. - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultIndex the default index into the enumNames/enumValues for the enum - /// \param enumNames an array of text string names (last string must be NULL) for the enum entries. e.g. - /// \code - /// const char* const enumStrings[] = { - /// "up", - /// "down", - /// "left", - /// "right", - /// 0 - /// }; - /// \endcode - /// \param enumValues - an array of integer values that match up to the enumNames. This array can be NULL, - /// in which case it is assumed that the enum values are 0, 1, 2, 3, etc. - /// \param persist if true, the GUI option will be persisted as an optionVar - /// \param passAsString - if true, the command will be passed the text string value of the enum. If false, - /// a numeric value will be passed instead. - AL_MAYA_UTILS_PUBLIC - void addRadioButtonGroupOption( - const char* commandFlag, - const char* label, - int defaultIndex, - const char* const enumNames[], - const int32_t enumValues[], - bool persist = true, - bool passAsString = false); - - /// \brief add a double precision option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addDoubleOption(const char* commandFlag, const char* label, double defaultVal, bool persist = true); - - /// \brief add a double precision option value to the GUI (with min/max, displayed as a slider) - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not setoption - /// \param minVal the minimum value for the slider range - /// \param maxVal the maximum value for the slider range - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addDoubleSliderOption(const char* commandFlag, const char* label, double minVal, double maxVal, double defaultVal, bool persist = true); - - /// \brief add a 2D vector option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addVec2Option(const char* commandFlag, const char* label, const double defaultVal[2], bool persist = true); - - /// \brief add a 2D vector option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param a the default value for the 1st value of the flag - /// \param b the default value for the 2st value of the flag - /// \param persist if true, the GUI option will be persisted as an optionVar - void addVec2Option(const char* commandFlag, const char* label, const double a, const double b, bool persist = true) + /// \brief adds a dynamic drop down list of items that will be displayed within an optionMenu + /// control. + /// The list of text strings will be generated within C++ by the custom generateList + /// function, which will then be chosen to represent the list of options available for + /// this command. When the command is executed, the selected item will be passed to the + /// command as a text string. + /// \note Only string command options are supported for this control type, and the command GUI + /// must be created with + /// the 'hasOptionBox' option of the constructor set to false. + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param generateList The C++ command to build up a list of text strings for the GUI to + /// display \param isMandatory If true, our commandFlag is actually a mandatory argument, not + /// a option / flag + AL_MAYA_UTILS_PUBLIC + void addListOption( + const char* commandFlag, + const char* label, + GenerateListFn generateList, + bool isMandatory = false); + + /// \brief add an enum option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultIndex the default index into the enumNames/enumValues for the enum + /// \param enumNames an array of text string names (last string must be NULL) for the enum + /// entries. e.g. \code + /// const char* const enumStrings[] = { + /// "up", + /// "down", + /// "left", + /// "right", + /// 0 + /// }; + /// \endcode + /// \param enumValues an array of integer values that match up to the enumNames. This array + /// can be NULL, + /// in which case it is assumed that the enum values are 0, 1, 2, 3, etc. + /// \param persist if true, the GUI option will be persisted as an optionVar + /// \param passAsString if true, the command will be passed the text string value of the + /// enum. If false, + /// a numeric value will be passed instead. + AL_MAYA_UTILS_PUBLIC + void addEnumOption( + const char* commandFlag, + const char* label, + int defaultIndex, + const char* const enumNames[], + const int32_t enumValues[], + bool persist = true, + bool passAsString = false); + + /// \brief Similar to the enum option, but this time with radio buttons. THE MAXIMUM NUMBER OF + /// OPTIONS IS 4. + /// If you exceed this, the code will default to using a combo box for display. + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultIndex the default index into the enumNames/enumValues for the enum + /// \param enumNames an array of text string names (last string must be NULL) for the enum + /// entries. e.g. \code + /// const char* const enumStrings[] = { + /// "up", + /// "down", + /// "left", + /// "right", + /// 0 + /// }; + /// \endcode + /// \param enumValues - an array of integer values that match up to the enumNames. This array + /// can be NULL, + /// in which case it is assumed that the enum values are 0, 1, 2, 3, etc. + /// \param persist if true, the GUI option will be persisted as an optionVar + /// \param passAsString - if true, the command will be passed the text string value of the + /// enum. If false, + /// a numeric value will be passed instead. + AL_MAYA_UTILS_PUBLIC + void addRadioButtonGroupOption( + const char* commandFlag, + const char* label, + int defaultIndex, + const char* const enumNames[], + const int32_t enumValues[], + bool persist = true, + bool passAsString = false); + + /// \brief add a double precision option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void addDoubleOption( + const char* commandFlag, + const char* label, + double defaultVal, + bool persist = true); + + /// \brief add a double precision option value to the GUI (with min/max, displayed as a slider) + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not setoption + /// \param minVal the minimum value for the slider range + /// \param maxVal the maximum value for the slider range + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void addDoubleSliderOption( + const char* commandFlag, + const char* label, + double minVal, + double maxVal, + double defaultVal, + bool persist = true); + + /// \brief add a 2D vector option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void addVec2Option( + const char* commandFlag, + const char* label, + const double defaultVal[2], + bool persist = true); + + /// \brief add a 2D vector option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param a the default value for the 1st value of the flag + /// \param b the default value for the 2st value of the flag + /// \param persist if true, the GUI option will be persisted as an optionVar + void addVec2Option( + const char* commandFlag, + const char* label, + const double a, + const double b, + bool persist = true) { - const double temp[] = {a, b}; - addVec2Option(commandFlag, label, temp, persist); + const double temp[] = { a, b }; + addVec2Option(commandFlag, label, temp, persist); } - /// \brief add a 3D vector option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addVec3Option(const char* commandFlag, const char* label, const double defaultVal[3], bool persist = true); - - /// \brief add a 3D vector option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param a the default value for the 1st value of the flag - /// \param b the default value for the 2st value of the flag - /// \param c the default value for the 3rd value of the flag - /// \param persist if true, the GUI option will be persisted as an optionVar - void addVec3Option(const char* commandFlag, const char* label, const double a, const double b, const double c, bool persist = true) + /// \brief add a 3D vector option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void addVec3Option( + const char* commandFlag, + const char* label, + const double defaultVal[3], + bool persist = true); + + /// \brief add a 3D vector option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param a the default value for the 1st value of the flag + /// \param b the default value for the 2st value of the flag + /// \param c the default value for the 3rd value of the flag + /// \param persist if true, the GUI option will be persisted as an optionVar + void addVec3Option( + const char* commandFlag, + const char* label, + const double a, + const double b, + const double c, + bool persist = true) { - const double temp[] = {a, b, c}; - addVec3Option(commandFlag, label, temp, persist); + const double temp[] = { a, b, c }; + addVec3Option(commandFlag, label, temp, persist); } - /// \brief add a 4D vector option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addVec4Option(const char* commandFlag, const char* label, const double defaultVal[4], bool persist = true); - - /// \brief add a 4D vector option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param a the default value for the 1st value of the flag - /// \param b the default value for the 2st value of the flag - /// \param c the default value for the 3rd value of the flag - /// \param d the default value for the 4th value of the flag - /// \param persist if true, the GUI option will be persisted as an optionVar - void addVec4Option(const char* commandFlag, const char* label, const double a, const double b, const double c, const double d, bool persist = true) + /// \brief add a 4D vector option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void addVec4Option( + const char* commandFlag, + const char* label, + const double defaultVal[4], + bool persist = true); + + /// \brief add a 4D vector option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param a the default value for the 1st value of the flag + /// \param b the default value for the 2st value of the flag + /// \param c the default value for the 3rd value of the flag + /// \param d the default value for the 4th value of the flag + /// \param persist if true, the GUI option will be persisted as an optionVar + void addVec4Option( + const char* commandFlag, + const char* label, + const double a, + const double b, + const double c, + const double d, + bool persist = true) { - const double temp[] = {a, b, c, d}; - addVec4Option(commandFlag, label, temp, persist); + const double temp[] = { a, b, c, d }; + addVec4Option(commandFlag, label, temp, persist); } - /// \brief add a colour option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - AL_MAYA_UTILS_PUBLIC - void addColourOption(const char* commandFlag, const char* label, const double defaultVal[3], bool persist = true); - - /// \brief add a colour option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param a the default value for the 1st value of the flag - /// \param b the default value for the 2st value of the flag - /// \param c the default value for the 3rd value of the flag - /// \param persist if true, the GUI option will be persisted as an optionVar - void addColourOption(const char* commandFlag, const char* label, const double a, const double b, const double c, bool persist = true) + /// \brief add a colour option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + AL_MAYA_UTILS_PUBLIC + void addColourOption( + const char* commandFlag, + const char* label, + const double defaultVal[3], + bool persist = true); + + /// \brief add a colour option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param a the default value for the 1st value of the flag + /// \param b the default value for the 2st value of the flag + /// \param c the default value for the 3rd value of the flag + /// \param persist if true, the GUI option will be persisted as an optionVar + void addColourOption( + const char* commandFlag, + const char* label, + const double a, + const double b, + const double c, + bool persist = true) { - const double temp[] = {a, b, c}; - addColourOption(commandFlag, label, temp, persist); + const double temp[] = { a, b, c }; + addColourOption(commandFlag, label, temp, persist); } - /// \brief add a string option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param defaultVal the default value for the flag if not set - /// \param persist if true, the GUI option will be persisted as an optionVar - /// \param policy is the string optional (kStringOptional), or required? (kStringMustHaveValue) - AL_MAYA_UTILS_PUBLIC - void addStringOption(const char* commandFlag, const char* label, MString defaultVal, bool persist = true, StringPolicy policy = kStringOptional); - - /// \brief add a file path option value to the GUI - /// \param commandFlag the flag for the command - /// \param label human readable GUI label for the option - /// \param fileMode the type of file dialog you wish to have present - /// \param filter the file extension filter for the file dialog - /// \param policy is the file path optional (kStringOptional), or required? (kStringMustHaveValue) - AL_MAYA_UTILS_PUBLIC - void addFilePathOption(const char* commandFlag, const char* label, FileMode fileMode, const char* filter = "All files (*) (*)", StringPolicy policy = kStringOptional); + /// \brief add a string option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param defaultVal the default value for the flag if not set + /// \param persist if true, the GUI option will be persisted as an optionVar + /// \param policy is the string optional (kStringOptional), or required? + /// (kStringMustHaveValue) + AL_MAYA_UTILS_PUBLIC + void addStringOption( + const char* commandFlag, + const char* label, + MString defaultVal, + bool persist = true, + StringPolicy policy = kStringOptional); + + /// \brief add a file path option value to the GUI + /// \param commandFlag the flag for the command + /// \param label human readable GUI label for the option + /// \param fileMode the type of file dialog you wish to have present + /// \param filter the file extension filter for the file dialog + /// \param policy is the file path optional (kStringOptional), or required? + /// (kStringMustHaveValue) + AL_MAYA_UTILS_PUBLIC + void addFilePathOption( + const char* commandFlag, + const char* label, + FileMode fileMode, + const char* filter = "All files (*) (*)", + StringPolicy policy = kStringOptional); private: - std::ostringstream m_global; - std::ostringstream m_init; - std::ostringstream m_save; - std::ostringstream m_load; - std::ostringstream m_reset; - std::ostringstream m_execute; - std::ostringstream m_labels; - std::ostringstream m_controls; - std::string m_commandName; - bool m_hasFilePath; - bool m_checkBoxCommand; + std::ostringstream m_global; + std::ostringstream m_init; + std::ostringstream m_save; + std::ostringstream m_load; + std::ostringstream m_reset; + std::ostringstream m_execute; + std::ostringstream m_labels; + std::ostringstream m_controls; + std::string m_commandName; + bool m_hasFilePath; + bool m_checkBoxCommand; }; //---------------------------------------------------------------------------------------------------------------------- -} // utils -} // maya -} // AL +} // namespace utils +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/mayautils/AL/maya/utils/DebugCodes.h b/plugin/al/mayautils/AL/maya/utils/DebugCodes.h index aca5b68629..3d4067d7ea 100644 --- a/plugin/al/mayautils/AL/maya/utils/DebugCodes.h +++ b/plugin/al/mayautils/AL/maya/utils/DebugCodes.h @@ -16,5 +16,5 @@ #pragma once #ifndef AL_MAYAUTILS_DEBUG -# define AL_MAYAUTILS_DEBUG 0 +#define AL_MAYAUTILS_DEBUG 0 #endif diff --git a/plugin/al/mayautils/AL/maya/utils/FileTranslatorBase.h b/plugin/al/mayautils/AL/maya/utils/FileTranslatorBase.h index 7d13a75e42..618e0a1cdc 100644 --- a/plugin/al/mayautils/AL/maya/utils/FileTranslatorBase.h +++ b/plugin/al/mayautils/AL/maya/utils/FileTranslatorBase.h @@ -16,7 +16,8 @@ #pragma once //---------------------------------------------------------------------------------------------------------------------- /// \file FileTranslatorBase.h -/// \brief This file contains a few macros and templates to help automate the tedious boiler plate setup of +/// \brief This file contains a few macros and templates to help automate the tedious boiler plate +/// setup of /// Maya import/export plugins. /// \code /// MAYA_TRANSLATOR_BEGIN(MyExporter, "My Exporter", true, true, "*.my", "*.my"); @@ -43,7 +44,8 @@ /// /// MAYA_TRANSLATOR_END(); /// -/// MStatus MyExporter::reader(const MFileObject& file, const OptionsParser& options, FileAccessMode mode) +/// MStatus MyExporter::reader(const MFileObject& file, const OptionsParser& options, FileAccessMode +/// mode) /// { /// // query your options /// bool someBoolValue = options.getBool(kSomeBoolValue); @@ -56,7 +58,8 @@ /// return MS::kSuccess; // done! /// } /// -/// MStatus MyExporter::writer(const MFileObject& file, const OptionsParser& options, FileAccessMode mode) +/// MStatus MyExporter::writer(const MFileObject& file, const OptionsParser& options, FileAccessMode +/// mode) /// { /// // query your options /// bool someBoolValue = options.getBool(kSomeBoolValue); @@ -88,159 +91,160 @@ //---------------------------------------------------------------------------------------------------------------------- #include "AL/maya/utils/FileTranslatorOptions.h" -#include #include +#include namespace AL { namespace maya { namespace utils { /// \brief Macro to wrap some boiler plate creation of a file translator -#define AL_MAYA_TRANSLATOR_BEGIN(ClassName, TranslatorName, HaveRead, HaveWrite, DefaultExtension, FilterString) \ - class ClassName : public AL::maya::utils::FileTranslatorBase { \ - public: \ - static constexpr const char* const kTranslatorName = TranslatorName; \ - static constexpr const char* const kClassName = #ClassName; \ - static void* creator() { return new ClassName; } \ - private: \ - bool haveReadMethod() const override { return HaveRead; } \ - bool haveWriteMethod() const override { return HaveWrite; } \ - MString defaultExtension() const override { return DefaultExtension; } \ - MString filter() const override { return FilterString; } \ - public: +#define AL_MAYA_TRANSLATOR_BEGIN( \ + ClassName, TranslatorName, HaveRead, HaveWrite, DefaultExtension, FilterString) \ + class ClassName : public AL::maya::utils::FileTranslatorBase \ + { \ + public: \ + static constexpr const char* const kTranslatorName = TranslatorName; \ + static constexpr const char* const kClassName = #ClassName; \ + static void* creator() { return new ClassName; } \ + \ + private: \ + bool haveReadMethod() const override { return HaveRead; } \ + bool haveWriteMethod() const override { return HaveWrite; } \ + MString defaultExtension() const override { return DefaultExtension; } \ + MString filter() const override { return FilterString; } \ + \ + public: /// \brief Macro to wrap some boiler plate creation of a file translator -#define AL_MAYA_TRANSLATOR_END() }; +#define AL_MAYA_TRANSLATOR_END() \ + } \ + ; //---------------------------------------------------------------------------------------------------------------------- /// \brief A utility class that provides a 'unique' base class to derive new translator from. //---------------------------------------------------------------------------------------------------------------------- -template -class FileTranslatorBase - : public MPxFileTranslator +template class FileTranslatorBase : public MPxFileTranslator { public: + /// \brief unregister the file translator + /// \param plugin the MFnPlugin function set + template static MStatus registerTranslator(FnPlugin& plugin) + { + if (MS::kSuccess == T::specifyOptions(m_options)) { + m_options.generateScript(m_optionParser, m_defaultOptionString); + + MStatus status = plugin.registerFileTranslator( + T::kTranslatorName, "", T::creator, T::kClassName, m_defaultOptionString.asChar()); + + if (!status) { + MGlobal::displayError( + MString("Failed to register translator: ") + T::kTranslatorName); + } + return status; + } + MGlobal::displayError( + MString("Failed to generate options for translator: ") + T::kTranslatorName); + return MS::kFailure; + } - /// \brief unregister the file translator - /// \param plugin the MFnPlugin function set - template - static MStatus registerTranslator(FnPlugin& plugin) + /// \brief unregister the file translator + /// \param plugin the MFnPlugin function set + template static MStatus deregisterTranslator(FnPlugin& plugin) { - if(MS::kSuccess == T::specifyOptions(m_options)) - { - m_options.generateScript(m_optionParser, m_defaultOptionString); - - MStatus status = plugin.registerFileTranslator( - T::kTranslatorName, - "", - T::creator, - T::kClassName, - m_defaultOptionString.asChar()); - - if(!status) { - MGlobal::displayError(MString("Failed to register translator: ") + T::kTranslatorName); + if (MS::kSuccess == T::cleanupOptions(m_options)) { + MStatus status = plugin.deregisterFileTranslator(T::kTranslatorName); + if (!status) { + MGlobal::displayError( + MString("Failed to deregister translator: ") + T::kTranslatorName); + } + return status; } - return status; - } - MGlobal::displayError(MString("Failed to generate options for translator: ") + T::kTranslatorName); - return MS::kFailure; + MGlobal::displayError( + MString("Failed to remove options for translator: ") + T::kTranslatorName); + return MS::kFailure; + } + + /// \brief default fall back in case no options are needed in the derived translator + /// \param options the file translator options + /// \return MS::kSuccess if options were correctly specified + static MStatus specifyOptions(FileTranslatorOptions& options) { return MS::kSuccess; } + + /// \brief default fall back in case no options are needed in the derived translator + /// \param options the file translator options + /// \return MS::kSuccess if options were correctly cleaned up + static MStatus cleanupOptions(FileTranslatorOptions& options) { return MS::kSuccess; } + + /// \brief Override this method to read your files (do not use the version from + /// MPxFileTranslator!) \param file the file to read into maya \param options a set of + /// Key/Value pair options passed through from the MEL GUI \param mode does this actually serve + /// any purpose? \return a failure in this case (because you need to override to import the + /// file) + virtual MStatus + reader(const MFileObject& file, const OptionsParser& options, FileAccessMode mode) + { + return MS::kFailure; } - /// \brief unregister the file translator - /// \param plugin the MFnPlugin function set - template - static MStatus deregisterTranslator(FnPlugin& plugin) - { - if(MS::kSuccess == T::cleanupOptions(m_options)) + /// \brief Override this method to write your files (do not use the version from + /// MPxFileTranslator!) \param file information about the file to export \param options a set + /// of Key/Value pair options passed through from the MEL GUI \param mode are we exporting + /// everything, or only the selected objects \return a failure in this case (because you need to + /// override to import the file) + virtual MStatus + writer(const MFileObject& file, const OptionsParser& options, FileAccessMode mode) { - MStatus status = plugin.deregisterFileTranslator(T::kTranslatorName); - if(!status) - { - MGlobal::displayError(MString("Failed to deregister translator: ") + T::kTranslatorName); - } - return status; + return MS::kFailure; } - MGlobal::displayError(MString("Failed to remove options for translator: ") + T::kTranslatorName); - return MS::kFailure; - } - - /// \brief default fall back in case no options are needed in the derived translator - /// \param options the file translator options - /// \return MS::kSuccess if options were correctly specified - static MStatus specifyOptions(FileTranslatorOptions& options) - { return MS::kSuccess; } - - /// \brief default fall back in case no options are needed in the derived translator - /// \param options the file translator options - /// \return MS::kSuccess if options were correctly cleaned up - static MStatus cleanupOptions(FileTranslatorOptions& options) - { return MS::kSuccess; } - - /// \brief Override this method to read your files (do not use the version from MPxFileTranslator!) - /// \param file the file to read into maya - /// \param options a set of Key/Value pair options passed through from the MEL GUI - /// \param mode does this actually serve any purpose? - /// \return a failure in this case (because you need to override to import the file) - virtual MStatus reader(const MFileObject& file, const OptionsParser& options, FileAccessMode mode) - { return MS::kFailure; } - - /// \brief Override this method to write your files (do not use the version from MPxFileTranslator!) - /// \param file information about the file to export - /// \param options a set of Key/Value pair options passed through from the MEL GUI - /// \param mode are we exporting everything, or only the selected objects - /// \return a failure in this case (because you need to override to import the file) - virtual MStatus writer(const MFileObject& file, const OptionsParser& options, FileAccessMode mode) - { return MS::kFailure; } - - /// \brief access the registered translator options - /// \return the options - static FileTranslatorOptions& options() - { return m_options; } + + /// \brief access the registered translator options + /// \return the options + static FileTranslatorOptions& options() { return m_options; } protected: - static void setPluginOptionsContext(PluginTranslatorOptionsInstance* pluginOptions) - { - m_optionParser.setPluginOptionsContext(pluginOptions); - } -private: + static void setPluginOptionsContext(PluginTranslatorOptionsInstance* pluginOptions) + { + m_optionParser.setPluginOptionsContext(pluginOptions); + } - MStatus reader(const MFileObject &file, const MString &optionsString, FileAccessMode mode) override +private: + MStatus + reader(const MFileObject& file, const MString& optionsString, FileAccessMode mode) override { - prepPluginOptions(); - MStatus status = m_optionParser.parse(optionsString); - if(MS::kSuccess == status) - { - return reader(file, m_optionParser, mode); - } - MGlobal::displayError("Unable to parse the file translator options"); - return status; + prepPluginOptions(); + MStatus status = m_optionParser.parse(optionsString); + if (MS::kSuccess == status) { + return reader(file, m_optionParser, mode); + } + MGlobal::displayError("Unable to parse the file translator options"); + return status; } - MStatus writer(const MFileObject &file, const MString &optionsString, FileAccessMode mode) override + MStatus + writer(const MFileObject& file, const MString& optionsString, FileAccessMode mode) override { - prepPluginOptions(); - MStatus status = m_optionParser.parse(optionsString); - if(MS::kSuccess == status) - { - return writer(file, m_optionParser, mode); - } - MGlobal::displayError("Unable to parse the file translator options"); - return status; + prepPluginOptions(); + MStatus status = m_optionParser.parse(optionsString); + if (MS::kSuccess == status) { + return writer(file, m_optionParser, mode); + } + MGlobal::displayError("Unable to parse the file translator options"); + return status; } - virtual void prepPluginOptions() {} + virtual void prepPluginOptions() { } - static MString m_defaultOptionString; - static OptionsParser m_optionParser; - static FileTranslatorOptions m_options; + static MString m_defaultOptionString; + static OptionsParser m_optionParser; + static FileTranslatorOptions m_options; }; -template MString FileTranslatorBase::m_defaultOptionString; -template OptionsParser FileTranslatorBase::m_optionParser; -template FileTranslatorOptions FileTranslatorBase::m_options(T::kClassName); +template MString FileTranslatorBase::m_defaultOptionString; +template OptionsParser FileTranslatorBase::m_optionParser; +template FileTranslatorOptions FileTranslatorBase::m_options(T::kClassName); //---------------------------------------------------------------------------------------------------------------------- -} // utils -} // maya -} // AL +} // namespace utils +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/mayautils/AL/maya/utils/FileTranslatorOptions.cpp b/plugin/al/mayautils/AL/maya/utils/FileTranslatorOptions.cpp index 57307f235f..d627cbeccb 100644 --- a/plugin/al/mayautils/AL/maya/utils/FileTranslatorOptions.cpp +++ b/plugin/al/mayautils/AL/maya/utils/FileTranslatorOptions.cpp @@ -13,11 +13,12 @@ // See the License for the specific language governing permissions and // limitations under the License. // -#include #include "AL/maya/utils/FileTranslatorOptions.h" #include +#include + namespace AL { namespace maya { namespace utils { @@ -26,632 +27,649 @@ const MString OptionsParser::kNullString; //---------------------------------------------------------------------------------------------------------------------- OptionsParser::OptionsParser(PluginTranslatorOptionsInstance* const pluginOptions) - : m_optionNameToValue(), m_niceNameToValue(), m_pluginOptions(pluginOptions) + : m_optionNameToValue() + , m_niceNameToValue() + , m_pluginOptions(pluginOptions) { } //---------------------------------------------------------------------------------------------------------------------- OptionsParser::~OptionsParser() { - auto it = m_optionNameToValue.begin(); - auto end = m_optionNameToValue.end(); - for(; it != end; ++it) - delete it->second; - m_optionNameToValue.clear(); - m_niceNameToValue.clear(); + auto it = m_optionNameToValue.begin(); + auto end = m_optionNameToValue.end(); + for (; it != end; ++it) + delete it->second; + m_optionNameToValue.clear(); + m_niceNameToValue.clear(); } //---------------------------------------------------------------------------------------------------------------------- void OptionsParser::construct(MString& optionString) { - optionString.clear(); - - for(auto& r : m_optionNameToValue) - { - optionString += r.first.c_str(); - optionString += "="; - switch(r.second->m_type) - { - case kBool: - optionString += r.second->m_bool; - break; - case kEnum: - case kInt: - optionString += r.second->m_int; - break; - case kFloat: - optionString += r.second->m_float; - break; - case kString: - optionString += r.second->m_string.c_str(); - break; + optionString.clear(); + + for (auto& r : m_optionNameToValue) { + optionString += r.first.c_str(); + optionString += "="; + switch (r.second->m_type) { + case kBool: optionString += r.second->m_bool; break; + case kEnum: + case kInt: optionString += r.second->m_int; break; + case kFloat: optionString += r.second->m_float; break; + case kString: optionString += r.second->m_string.c_str(); break; + } + optionString += ";"; } - optionString += ";"; - } } //---------------------------------------------------------------------------------------------------------------------- MStatus OptionsParser::parse(const MString& optionString) { - MStatus status = MS::kSuccess; - { - auto it = m_niceNameToValue.begin(); - auto end = m_niceNameToValue.end(); - for(; it != end; ++it) + MStatus status = MS::kSuccess; { - it->second->init(); + auto it = m_niceNameToValue.begin(); + auto end = m_niceNameToValue.end(); + for (; it != end; ++it) { + it->second->init(); + } } - } - - if (optionString.length() > 0) - { - int i, length; - // Start parsing. - MStringArray optionList; - MStringArray theOption; - optionString.split(';', optionList); // break out all the options. - - length = optionList.length(); - for(i = 0; i < length; ++i) - { - theOption.clear(); - optionList[i].split('=', theOption); - - auto it = m_optionNameToValue.find(theOption[0].asChar()); - if(it != m_optionNameToValue.end()) - { - it->second->parse(theOption[1]); - } - else - if(m_pluginOptions) - { - m_pluginOptions->parse(theOption[0], theOption[1]); - } - else - { - MGlobal::displayError(MString("Unknown option: ") + theOption[0] + " { " + theOption[1] + " }"); - status = MS::kFailure; - } + + if (optionString.length() > 0) { + int i, length; + // Start parsing. + MStringArray optionList; + MStringArray theOption; + optionString.split(';', optionList); // break out all the options. + + length = optionList.length(); + for (i = 0; i < length; ++i) { + theOption.clear(); + optionList[i].split('=', theOption); + + auto it = m_optionNameToValue.find(theOption[0].asChar()); + if (it != m_optionNameToValue.end()) { + it->second->parse(theOption[1]); + } else if (m_pluginOptions) { + m_pluginOptions->parse(theOption[0], theOption[1]); + } else { + MGlobal::displayError( + MString("Unknown option: ") + theOption[0] + " { " + theOption[1] + " }"); + status = MS::kFailure; + } + } } - } - return status; + return status; } //---------------------------------------------------------------------------------------------------------------------- FileTranslatorOptions::FileTranslatorOptions(const char* fileTranslatorName) - : m_frames(), m_visibility(), m_translatorName(fileTranslatorName), m_code() + : m_frames() + , m_visibility() + , m_translatorName(fileTranslatorName) + , m_code() { } //---------------------------------------------------------------------------------------------------------------------- bool FileTranslatorOptions::addFrame(const char* frameName) { - m_frames.push_back(FrameLayout(frameName)); - /// \todo need error checking here - return true; + m_frames.push_back(FrameLayout(frameName)); + /// \todo need error checking here + return true; } //---------------------------------------------------------------------------------------------------------------------- bool FileTranslatorOptions::removeFrame(const char* frameName) { - auto iter = std::find_if(m_frames.begin(), - m_frames.end(), - [&](FrameLayout& frame) { - return frame.m_frameName == frameName; - }); - if (iter != m_frames.end()) - { - m_frames.erase(iter); - return true; - } - MGlobal::displayError((std::string("FileTranslatorOptions: failed to remove frame: ") + frameName).c_str()); - return false; + auto iter = std::find_if(m_frames.begin(), m_frames.end(), [&](FrameLayout& frame) { + return frame.m_frameName == frameName; + }); + if (iter != m_frames.end()) { + m_frames.erase(iter); + return true; + } + MGlobal::displayError( + (std::string("FileTranslatorOptions: failed to remove frame: ") + frameName).c_str()); + return false; } //---------------------------------------------------------------------------------------------------------------------- MString niceNameToOptionString(MString n) { - char* str = (char*)n.asChar(); - for(uint32_t i = 0, len = n.length(); i < len; ++i) - { - const char c = str[i]; - if(!isalnum(c) && c != '_') - { - str[i] = '_'; + char* str = (char*)n.asChar(); + for (uint32_t i = 0, len = n.length(); i < len; ++i) { + const char c = str[i]; + if (!isalnum(c) && c != '_') { + str[i] = '_'; + } } - } - return n; + return n; } //---------------------------------------------------------------------------------------------------------------------- -bool FileTranslatorOptions::boolControlsVisibility(const char* controller, const char* controlled, bool invertBehaviour) +bool FileTranslatorOptions::boolControlsVisibility( + const char* controller, + const char* controlled, + bool invertBehaviour) { - MString opt_controller = niceNameToOptionString(controller); - MString opt_controlled = niceNameToOptionString(controlled); - if(hasOption(opt_controller) && hasOption(opt_controlled)) - { - MString controllerControl = m_translatorName + "_" + opt_controller; - MString controlledControl = m_translatorName + "_" + opt_controlled; - m_visibility.emplace_back(controllerControl, controlledControl); - return true; - } - MGlobal::displayError("FileTranslatorOptions: unknown option name"); - return false; + MString opt_controller = niceNameToOptionString(controller); + MString opt_controlled = niceNameToOptionString(controlled); + if (hasOption(opt_controller) && hasOption(opt_controlled)) { + MString controllerControl = m_translatorName + "_" + opt_controller; + MString controlledControl = m_translatorName + "_" + opt_controlled; + m_visibility.emplace_back(controllerControl, controlledControl); + return true; + } + MGlobal::displayError("FileTranslatorOptions: unknown option name"); + return false; } //---------------------------------------------------------------------------------------------------------------------- bool FileTranslatorOptions::addBool(const char* niceName, bool defaultValue) { - if(m_frames.empty()) - return false; + if (m_frames.empty()) + return false; + + FrameLayout& frame = lastFrame(); + FrameLayout::Option option; + + option.optionName = niceNameToOptionString(niceName); + option.niceName = niceName; + option.type = kBool; + option.defaultBool = defaultValue; + option.enumValues = 0; + if (hasOption(option.optionName)) { + MString msg("FileTranslatorOptions: cannot register the same bool option twice: ^1"); + msg.format(option.optionName); + MGlobal::displayError(msg); + return false; + } - FrameLayout& frame = lastFrame(); - FrameLayout::Option option; - - option.optionName = niceNameToOptionString(niceName); - option.niceName = niceName; - option.type = kBool; - option.defaultBool = defaultValue; - option.enumValues = 0; - if(hasOption(option.optionName)) - { - MString msg("FileTranslatorOptions: cannot register the same bool option twice: ^1"); - msg.format(option.optionName); - MGlobal::displayError(msg); return false; - } - - frame.m_options.push_back(option); - return true; + frame.m_options.push_back(option); + return true; } //---------------------------------------------------------------------------------------------------------------------- bool FileTranslatorOptions::addInt(const char* niceName, int defaultValue) { - if(m_frames.empty()) - return false; - - FrameLayout& frame = lastFrame(); - FrameLayout::Option option; - - option.optionName = niceNameToOptionString(niceName); - option.niceName = niceName; - option.type = kInt; - option.defaultInt = defaultValue; - option.enumValues = 0; - if(hasOption(option.optionName)) - { - MString msg("FileTranslatorOptions: cannot register the same int option twice: ^1"); - msg.format(option.optionName); - MGlobal::displayError(msg); return false; - } - frame.m_options.push_back(option); - return true; + if (m_frames.empty()) + return false; + + FrameLayout& frame = lastFrame(); + FrameLayout::Option option; + + option.optionName = niceNameToOptionString(niceName); + option.niceName = niceName; + option.type = kInt; + option.defaultInt = defaultValue; + option.enumValues = 0; + if (hasOption(option.optionName)) { + MString msg("FileTranslatorOptions: cannot register the same int option twice: ^1"); + msg.format(option.optionName); + MGlobal::displayError(msg); + return false; + } + frame.m_options.push_back(option); + return true; } //---------------------------------------------------------------------------------------------------------------------- bool FileTranslatorOptions::addFloat(const char* niceName, float defaultValue) { - if(m_frames.empty()) - return false; - - FrameLayout& frame = lastFrame(); - FrameLayout::Option option; - - option.optionName = niceNameToOptionString(niceName); - option.niceName = niceName; - option.type = kFloat; - option.defaultFloat = defaultValue; - option.enumValues = 0; - if(hasOption(option.optionName)) - { - MString msg("FileTranslatorOptions: cannot register the same float option twice: ^1"); - msg.format(option.optionName); - MGlobal::displayError(msg); return false; - } - frame.m_options.push_back(option); - return true; + if (m_frames.empty()) + return false; + + FrameLayout& frame = lastFrame(); + FrameLayout::Option option; + + option.optionName = niceNameToOptionString(niceName); + option.niceName = niceName; + option.type = kFloat; + option.defaultFloat = defaultValue; + option.enumValues = 0; + if (hasOption(option.optionName)) { + MString msg("FileTranslatorOptions: cannot register the same float option twice: ^1"); + msg.format(option.optionName); + MGlobal::displayError(msg); + return false; + } + frame.m_options.push_back(option); + return true; } //---------------------------------------------------------------------------------------------------------------------- bool FileTranslatorOptions::addString(const char* niceName, const char* const defaultValue) { - if(m_frames.empty()) - return false; - - FrameLayout& frame = lastFrame(); - FrameLayout::Option option; - - option.optionName = niceNameToOptionString(niceName); - option.niceName = niceName; - option.type = kString; - option.defaultString = defaultValue; - option.enumValues = 0; - if(hasOption(option.optionName)) - { - MString msg("FileTranslatorOptions: cannot register the same string option twice: ^1"); - msg.format(option.optionName); - MGlobal::displayError(msg); return false; - } - frame.m_options.push_back(option); - return true; + if (m_frames.empty()) + return false; + + FrameLayout& frame = lastFrame(); + FrameLayout::Option option; + + option.optionName = niceNameToOptionString(niceName); + option.niceName = niceName; + option.type = kString; + option.defaultString = defaultValue; + option.enumValues = 0; + if (hasOption(option.optionName)) { + MString msg("FileTranslatorOptions: cannot register the same string option twice: ^1"); + msg.format(option.optionName); + MGlobal::displayError(msg); + return false; + } + frame.m_options.push_back(option); + return true; } //---------------------------------------------------------------------------------------------------------------------- -bool FileTranslatorOptions::addEnum(const char* niceName, const char* const enumValues[], const int defaultValue) +bool FileTranslatorOptions::addEnum( + const char* niceName, + const char* const enumValues[], + const int defaultValue) { - if(m_frames.empty()) - return false; - - FrameLayout& frame = lastFrame(); - FrameLayout::Option option; - - option.optionName = niceNameToOptionString(niceName); - option.niceName = niceName; - option.type = kEnum; - option.defaultInt = defaultValue; - option.enumValues = enumValues; - - if(hasOption(option.optionName)) - { - MString msg("FileTranslatorOptions: cannot register the same enum option twice: ^1"); - msg.format(option.optionName); - MGlobal::displayError(msg); - return false; - } - frame.m_options.push_back(option); - return true; + if (m_frames.empty()) + return false; + + FrameLayout& frame = lastFrame(); + FrameLayout::Option option; + + option.optionName = niceNameToOptionString(niceName); + option.niceName = niceName; + option.type = kEnum; + option.defaultInt = defaultValue; + option.enumValues = enumValues; + + if (hasOption(option.optionName)) { + MString msg("FileTranslatorOptions: cannot register the same enum option twice: ^1"); + msg.format(option.optionName); + MGlobal::displayError(msg); + return false; + } + frame.m_options.push_back(option); + return true; } //---------------------------------------------------------------------------------------------------------------------- -void FileTranslatorOptions::generateBoolGlobals(const MString& niceName, const MString& optionName, bool defaultValue) +void FileTranslatorOptions::generateBoolGlobals( + const MString& niceName, + const MString& optionName, + bool defaultValue) { - MString controlName = m_translatorName + "_" + optionName; - MString createCommand = MString("global proc create_") + controlName + "() {" + MString("checkBox -l \"") + niceName + "\" -v " + defaultValue + " " + controlName + ";}\n"; - MString postCommand = MString("global proc post_") + controlName + "(string $value){ eval (\"checkBox -e -v \" + $value + \" " + controlName + "\");}\n"; - MString buildCommand = MString("global proc string build_") + controlName + "(){ string $str = \"" + optionName + "=\"; if(` checkBox -q -v " + controlName + "`) $str = $str + \"1;\"; else $str = $str + \"0;\"; return $str;}\n"; - - m_code += createCommand; - m_code += postCommand; - m_code += buildCommand; - m_code += "\n"; + MString controlName = m_translatorName + "_" + optionName; + MString createCommand = MString("global proc create_") + controlName + "() {" + + MString("checkBox -l \"") + niceName + "\" -v " + defaultValue + " " + controlName + + ";}\n"; + MString postCommand = MString("global proc post_") + controlName + + "(string $value){ eval (\"checkBox -e -v \" + $value + \" " + controlName + "\");}\n"; + MString buildCommand = MString("global proc string build_") + controlName + + "(){ string $str = \"" + optionName + "=\"; if(` checkBox -q -v " + controlName + + "`) $str = $str + \"1;\"; else $str = $str + \"0;\"; return $str;}\n"; + + m_code += createCommand; + m_code += postCommand; + m_code += buildCommand; + m_code += "\n"; } //---------------------------------------------------------------------------------------------------------------------- -void FileTranslatorOptions::generateIntGlobals(const MString& niceName, const MString& optionName, int defaultValue) +void FileTranslatorOptions::generateIntGlobals( + const MString& niceName, + const MString& optionName, + int defaultValue) { - MString controlName = m_translatorName + "_" + optionName; - MString createCommand = MString("global proc create_") + controlName + "() {" + MString("intFieldGrp -l \"") + niceName + "\" -v1 " + defaultValue + " " + controlName + ";}\n"; - MString postCommand = MString("global proc post_") + controlName + "(string $value){ eval (\"intFieldGrp -e -v1 \" + $value + \" " + controlName + "\");}\n"; - MString buildCommand = MString("global proc string build_") + controlName + "(){ string $str = \"" + optionName + "=\" + `intFieldGrp -q -v1 " + controlName + "` + \";\"; return $str;}\n"; - - m_code += createCommand; - m_code += postCommand; - m_code += buildCommand; - m_code += "\n"; + MString controlName = m_translatorName + "_" + optionName; + MString createCommand = MString("global proc create_") + controlName + "() {" + + MString("intFieldGrp -l \"") + niceName + "\" -v1 " + defaultValue + " " + controlName + + ";}\n"; + MString postCommand = MString("global proc post_") + controlName + + "(string $value){ eval (\"intFieldGrp -e -v1 \" + $value + \" " + controlName + "\");}\n"; + MString buildCommand = MString("global proc string build_") + controlName + + "(){ string $str = \"" + optionName + "=\" + `intFieldGrp -q -v1 " + controlName + + "` + \";\"; return $str;}\n"; + + m_code += createCommand; + m_code += postCommand; + m_code += buildCommand; + m_code += "\n"; } //---------------------------------------------------------------------------------------------------------------------- -void FileTranslatorOptions::generateFloatGlobals(const MString& niceName, const MString& optionName, float defaultValue) +void FileTranslatorOptions::generateFloatGlobals( + const MString& niceName, + const MString& optionName, + float defaultValue) { - MString controlName = m_translatorName + "_" + optionName; - MString createCommand = MString("global proc create_") + controlName + "() {" + MString("floatFieldGrp -l \"") + niceName + "\" -v1 " + defaultValue + " " + controlName + ";}\n"; - MString postCommand = MString("global proc post_") + controlName + "(string $value){ eval (\"floatFieldGrp -e -v1 \" + $value + \" " + controlName + "\");}\n"; - MString buildCommand = MString("global proc string build_") + controlName + "(){ string $str = \"" + optionName + "=\" + `floatFieldGrp -q -v1 " + controlName + "` + \";\"; return $str;}\n"; - - m_code += createCommand; - m_code += postCommand; - m_code += buildCommand; - m_code += "\n"; + MString controlName = m_translatorName + "_" + optionName; + MString createCommand = MString("global proc create_") + controlName + "() {" + + MString("floatFieldGrp -l \"") + niceName + "\" -v1 " + defaultValue + " " + controlName + + ";}\n"; + MString postCommand = MString("global proc post_") + controlName + + "(string $value){ eval (\"floatFieldGrp -e -v1 \" + $value + \" " + controlName + + "\");}\n"; + MString buildCommand = MString("global proc string build_") + controlName + + "(){ string $str = \"" + optionName + "=\" + `floatFieldGrp -q -v1 " + controlName + + "` + \";\"; return $str;}\n"; + + m_code += createCommand; + m_code += postCommand; + m_code += buildCommand; + m_code += "\n"; } //---------------------------------------------------------------------------------------------------------------------- -void FileTranslatorOptions::generateStringGlobals(const MString& niceName, const MString& optionName, MString defaultValue) +void FileTranslatorOptions::generateStringGlobals( + const MString& niceName, + const MString& optionName, + MString defaultValue) { - MString controlName = m_translatorName + "_" + optionName; - MString createCommand = MString("global proc create_") + controlName + "() {" + MString("textFieldGrp -l \"") + niceName + "\" " + controlName + ";}\n"; - MString postCommand = MString("global proc post_") + controlName + "(string $value){ eval (\"textFieldGrp -e -tx \" + $value + \" " + controlName + "\");}\n"; - MString buildCommand = MString("global proc string build_") + controlName + "(){ string $str = \"" + optionName + "=\" + `textFieldGrp -q -tx " + controlName + "` + \";\"; return $str;}\n"; - - m_code += createCommand; - m_code += postCommand; - m_code += buildCommand; - m_code += "\n"; + MString controlName = m_translatorName + "_" + optionName; + MString createCommand = MString("global proc create_") + controlName + "() {" + + MString("textFieldGrp -l \"") + niceName + "\" " + controlName + ";}\n"; + MString postCommand = MString("global proc post_") + controlName + + "(string $value){ eval (\"textFieldGrp -e -tx \" + $value + \" " + controlName + + "\");}\n"; + MString buildCommand = MString("global proc string build_") + controlName + + "(){ string $str = \"" + optionName + "=\" + `textFieldGrp -q -tx " + controlName + + "` + \";\"; return $str;}\n"; + + m_code += createCommand; + m_code += postCommand; + m_code += buildCommand; + m_code += "\n"; } //---------------------------------------------------------------------------------------------------------------------- -void FileTranslatorOptions::generateEnumGlobals(const MString& niceName, const MString& optionName, const char* const enumValues[], int defaultValue) +void FileTranslatorOptions::generateEnumGlobals( + const MString& niceName, + const MString& optionName, + const char* const enumValues[], + int defaultValue) { - MString controlName = m_translatorName + "_" + optionName; - MString createCommand = MString("global proc create_") + controlName + "() {" + MString("optionMenuGrp -l \"") + niceName + "\" " + controlName + ";"; - - for(int i = 0; enumValues && enumValues[i]; ++i) - { - createCommand += MString("menuItem -l \"") + enumValues[i] + "\";"; - } - - createCommand += "}\n"; - MString postCommand = MString("global proc post_") + controlName + "(string $value){ int $v=$value; eval (\"optionMenuGrp -e -sl \" + ($v + 1) + \" " + controlName + "\");}\n"; - MString buildCommand = MString("global proc string build_") + controlName + "(){ string $str = \"" + optionName + "=\" + (`optionMenuGrp -q -sl " + controlName + "` -1) + \";\"; return $str;}\n"; - - m_code += createCommand; - m_code += postCommand; - m_code += buildCommand; - m_code += "\n"; + MString controlName = m_translatorName + "_" + optionName; + MString createCommand = MString("global proc create_") + controlName + "() {" + + MString("optionMenuGrp -l \"") + niceName + "\" " + controlName + ";"; + + for (int i = 0; enumValues && enumValues[i]; ++i) { + createCommand += MString("menuItem -l \"") + enumValues[i] + "\";"; + } + + createCommand += "}\n"; + MString postCommand = MString("global proc post_") + controlName + + "(string $value){ int $v=$value; eval (\"optionMenuGrp -e -sl \" + ($v + 1) + \" " + + controlName + "\");}\n"; + MString buildCommand = MString("global proc string build_") + controlName + + "(){ string $str = \"" + optionName + "=\" + (`optionMenuGrp -q -sl " + controlName + + "` -1) + \";\"; return $str;}\n"; + + m_code += createCommand; + m_code += postCommand; + m_code += buildCommand; + m_code += "\n"; } //---------------------------------------------------------------------------------------------------------------------- bool FileTranslatorOptions::hasOption(const char* const optionName) const { - for(auto frame : m_frames) - { - for(auto option : frame.m_options) - { - if(option.optionName == optionName) - return true; + for (auto frame : m_frames) { + for (auto option : frame.m_options) { + if (option.optionName == optionName) + return true; + } } - } - return false; + return false; } //---------------------------------------------------------------------------------------------------------------------- std::string stringify(const char* str) { - std::string new_str; - while(*str) - { - switch(*str) - { - case '\'': new_str += "\\\'"; break; - case '\"': new_str += "\\\""; break; - case '\\': new_str += "\\\\"; break; - case '\n': new_str += "\\n"; break; - case '\t': new_str += "\\t"; break; - case '\r': new_str += "\\r"; break; - case '\a': new_str += "\\a"; break; - default: new_str += *str; break; + std::string new_str; + while (*str) { + switch (*str) { + case '\'': new_str += "\\\'"; break; + case '\"': new_str += "\\\""; break; + case '\\': new_str += "\\\\"; break; + case '\n': new_str += "\\n"; break; + case '\t': new_str += "\\t"; break; + case '\r': new_str += "\\r"; break; + case '\a': new_str += "\\a"; break; + default: new_str += *str; break; + } + ++str; } - ++str; - } - return new_str; + return new_str; } //---------------------------------------------------------------------------------------------------------------------- MStatus FileTranslatorOptions::initParser(OptionsParser& optionParser) { - // first generate a collection of methods to create, edit, and query each separate option. For each exporter/importer - // option, we will generate three methods: - // - // proc create_myOptionName(); ///< creates the GUI control for the option - // proc post_myOptionName(string $value); ///< set the value in the control from the parsed option string - // proc string build_myOptionName(); ///< get the value from the control, and return it as a text string "myOptionName=" - // - // We will also add in some entries into the optionParser, which will be used later on when using the exporter. - // This option parser will know about the option names (both the 'nice' names and the actual option name), as well as - // the associated data type. This will be able to split apart the option string of the form "option1=10;option2=hello;option3=true" - // - auto itf = m_frames.begin(); - auto endf = m_frames.end(); - for(; itf != endf; ++itf) - { - auto ito = itf->m_options.begin(); - auto endo = itf->m_options.end(); - for(; ito != endo; ++ito) - { - switch(ito->type) - { - case kBool: - { - OptionsParser::OptionValue* value = new OptionsParser::OptionValue; - value->m_type = OptionsParser::kBool; - value->m_defaultBool = ito->defaultBool; - optionParser.m_niceNameToValue.insert(std::make_pair(ito->niceName.asChar(), value)); - optionParser.m_optionNameToValue.insert(std::make_pair(ito->optionName.asChar(), value)); - } - break; - - case kInt: - { - OptionsParser::OptionValue* value = new OptionsParser::OptionValue; - value->m_type = OptionsParser::kInt; - value->m_defaultInt = ito->defaultInt; - optionParser.m_niceNameToValue.insert(std::make_pair(ito->niceName.asChar(), value)); - optionParser.m_optionNameToValue.insert(std::make_pair(ito->optionName.asChar(), value)); - } - break; - - case kFloat: - { - OptionsParser::OptionValue* value = new OptionsParser::OptionValue; - value->m_type = OptionsParser::kFloat; - value->m_defaultFloat = ito->defaultFloat; - optionParser.m_niceNameToValue.insert(std::make_pair(ito->niceName.asChar(), value)); - optionParser.m_optionNameToValue.insert(std::make_pair(ito->optionName.asChar(), value)); - } - break; - - case kString: - { - OptionsParser::OptionValue* value = new OptionsParser::OptionValue; - value->m_type = OptionsParser::kString; - value->m_defaultString = ito->defaultString; - optionParser.m_niceNameToValue.insert(std::make_pair(ito->niceName.asChar(), value)); - optionParser.m_optionNameToValue.insert(std::make_pair(ito->optionName.asChar(), value)); - } - break; - - case kEnum: - { - OptionsParser::OptionValue* value = new OptionsParser::OptionValue; - value->m_type = OptionsParser::kEnum; - value->m_defaultInt = ito->defaultInt; - optionParser.m_niceNameToValue.insert(std::make_pair(ito->niceName.asChar(), value)); - optionParser.m_optionNameToValue.insert(std::make_pair(ito->optionName.asChar(), value)); + // first generate a collection of methods to create, edit, and query each separate option. For + // each exporter/importer option, we will generate three methods: + // + // proc create_myOptionName(); ///< creates the GUI control for the option + // proc post_myOptionName(string $value); ///< set the value in the control from the parsed + // option string proc string build_myOptionName(); ///< get the value from the control, + // and return it as a text string "myOptionName=" + // + // We will also add in some entries into the optionParser, which will be used later on when + // using the exporter. This option parser will know about the option names (both the 'nice' + // names and the actual option name), as well as the associated data type. This will be able to + // split apart the option string of the form "option1=10;option2=hello;option3=true" + // + auto itf = m_frames.begin(); + auto endf = m_frames.end(); + for (; itf != endf; ++itf) { + auto ito = itf->m_options.begin(); + auto endo = itf->m_options.end(); + for (; ito != endo; ++ito) { + switch (ito->type) { + case kBool: { + OptionsParser::OptionValue* value = new OptionsParser::OptionValue; + value->m_type = OptionsParser::kBool; + value->m_defaultBool = ito->defaultBool; + optionParser.m_niceNameToValue.insert( + std::make_pair(ito->niceName.asChar(), value)); + optionParser.m_optionNameToValue.insert( + std::make_pair(ito->optionName.asChar(), value)); + } break; + + case kInt: { + OptionsParser::OptionValue* value = new OptionsParser::OptionValue; + value->m_type = OptionsParser::kInt; + value->m_defaultInt = ito->defaultInt; + optionParser.m_niceNameToValue.insert( + std::make_pair(ito->niceName.asChar(), value)); + optionParser.m_optionNameToValue.insert( + std::make_pair(ito->optionName.asChar(), value)); + } break; + + case kFloat: { + OptionsParser::OptionValue* value = new OptionsParser::OptionValue; + value->m_type = OptionsParser::kFloat; + value->m_defaultFloat = ito->defaultFloat; + optionParser.m_niceNameToValue.insert( + std::make_pair(ito->niceName.asChar(), value)); + optionParser.m_optionNameToValue.insert( + std::make_pair(ito->optionName.asChar(), value)); + } break; + + case kString: { + OptionsParser::OptionValue* value = new OptionsParser::OptionValue; + value->m_type = OptionsParser::kString; + value->m_defaultString = ito->defaultString; + optionParser.m_niceNameToValue.insert( + std::make_pair(ito->niceName.asChar(), value)); + optionParser.m_optionNameToValue.insert( + std::make_pair(ito->optionName.asChar(), value)); + } break; + + case kEnum: { + OptionsParser::OptionValue* value = new OptionsParser::OptionValue; + value->m_type = OptionsParser::kEnum; + value->m_defaultInt = ito->defaultInt; + optionParser.m_niceNameToValue.insert( + std::make_pair(ito->niceName.asChar(), value)); + optionParser.m_optionNameToValue.insert( + std::make_pair(ito->optionName.asChar(), value)); + } break; + } } - break; - } } - } - return MS::kSuccess; + return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- -MStatus FileTranslatorOptions::generateScript(OptionsParser& optionParser, MString& defaultOptionString) +MStatus +FileTranslatorOptions::generateScript(OptionsParser& optionParser, MString& defaultOptionString) { - initParser(optionParser); - - // first generate a collection of methods to create, edit, and query each separate option. For each exporter/importer - // option, we will generate three methods: - // - // proc create_myOptionName(); ///< creates the GUI control for the option - // proc post_myOptionName(string $value); ///< set the value in the control from the parsed option string - // proc string build_myOptionName(); ///< get the value from the control, and return it as a text string "myOptionName=" - // - // We will also add in some entries into the optionParser, which will be used later on when using the exporter. - // This option parser will know about the option names (both the 'nice' names and the actual option name), as well as - // the associated data type. This will be able to split apart the option string of the form "option1=10;option2=hello;option3=true" - // - auto itf = m_frames.begin(); - auto endf = m_frames.end(); - for(; itf != endf; ++itf) - { - auto ito = itf->m_options.begin(); - auto endo = itf->m_options.end(); - for(; ito != endo; ++ito) - { - switch(ito->type) - { - case kBool: - { - generateBoolGlobals(ito->niceName, ito->optionName, ito->defaultBool); - defaultOptionString += ito->optionName + "="; - if(ito->defaultBool) - defaultOptionString += "1;"; - else - defaultOptionString += "0;"; - } - break; - - case kInt: - { - generateIntGlobals(ito->niceName, ito->optionName, ito->defaultInt); - defaultOptionString += ito->optionName + "=" + (MString() + ito->defaultInt) + ";"; + initParser(optionParser); + + // first generate a collection of methods to create, edit, and query each separate option. For + // each exporter/importer option, we will generate three methods: + // + // proc create_myOptionName(); ///< creates the GUI control for the option + // proc post_myOptionName(string $value); ///< set the value in the control from the parsed + // option string proc string build_myOptionName(); ///< get the value from the control, + // and return it as a text string "myOptionName=" + // + // We will also add in some entries into the optionParser, which will be used later on when + // using the exporter. This option parser will know about the option names (both the 'nice' + // names and the actual option name), as well as the associated data type. This will be able to + // split apart the option string of the form "option1=10;option2=hello;option3=true" + // + auto itf = m_frames.begin(); + auto endf = m_frames.end(); + for (; itf != endf; ++itf) { + auto ito = itf->m_options.begin(); + auto endo = itf->m_options.end(); + for (; ito != endo; ++ito) { + switch (ito->type) { + case kBool: { + generateBoolGlobals(ito->niceName, ito->optionName, ito->defaultBool); + defaultOptionString += ito->optionName + "="; + if (ito->defaultBool) + defaultOptionString += "1;"; + else + defaultOptionString += "0;"; + } break; + + case kInt: { + generateIntGlobals(ito->niceName, ito->optionName, ito->defaultInt); + defaultOptionString += ito->optionName + "=" + (MString() + ito->defaultInt) + ";"; + } break; + + case kFloat: { + generateFloatGlobals(ito->niceName, ito->optionName, ito->defaultFloat); + defaultOptionString + += ito->optionName + "=" + (MString() + ito->defaultFloat) + ";"; + } break; + + case kString: { + generateStringGlobals(ito->niceName, ito->optionName, ito->defaultString); + defaultOptionString += ito->optionName + "=" + ito->defaultString + ";"; + } break; + + case kEnum: { + generateEnumGlobals( + ito->niceName, ito->optionName, ito->enumValues, ito->defaultInt); + defaultOptionString += ito->optionName + "=" + (MString() + ito->defaultInt) + ";"; + } break; + } } - break; + } - case kFloat: - { - generateFloatGlobals(ito->niceName, ito->optionName, ito->defaultFloat); - defaultOptionString += ito->optionName + "=" + (MString() + ito->defaultFloat) + ";"; + m_code += "global proc fromOptionVars_"; + m_code += m_translatorName; + m_code += "() {}\n"; + + m_code += "global proc create_"; + m_code += m_translatorName; + m_code += "(string $parent) {}\n"; + + m_code += "global proc post_"; + m_code += m_translatorName; + m_code += "(string $name, string $value) {}\n"; + + m_code += "global proc string query_"; + m_code += m_translatorName; + m_code += "() { return \"\"; }\n"; + + // generate the actual entry point for our option dialog, e.g. + // + // global proc int myExporterName(string $parent, string $action, string $initialSettings, + // string $resultCallback) + // + m_code += MString("global proc int ") + m_translatorName + + "(string $parent, string $action, string $initialSettings, string $resultCallback)\n{\n"; + m_code += " int $result = 1;\n" + " string $currentOptions;\n" + " string $optionList[];\n" + " string $optionBreakDown[];\n" + " int $index;\n" + " if ($action == \"post\")\n {\n" //< start of the 'post' section of the script (set + //control values from option string) + " setParent $parent;\n" + " columnLayout -adj true;\n" + " AL_usdmaya_SyncFileIOGui \"" + + m_translatorName + "\";\n"; + + itf = m_frames.begin(); + for (; itf != endf; ++itf) { + auto ito = itf->m_options.begin(); + auto endo = itf->m_options.end(); + for (; ito != endo; ++ito) { + MString controlName = m_translatorName + "_" + ito->optionName; + m_code += MString(" create_") + controlName + "();\n"; } - break; + } - case kString: - { - generateStringGlobals(ito->niceName, ito->optionName, ito->defaultString); - defaultOptionString += ito->optionName + "=" + ito->defaultString + ";"; + m_code += " create_"; + m_code += m_translatorName; + m_code += "($parent);\n"; + + // generate the code to split apart the key-value pairs of options. + m_code += " if (size($initialSettings) > 0) {\n" + " tokenize($initialSettings, \";\", $optionList);\n" + " for ($index = 0; $index < size($optionList); $index++) {\n" + " tokenize($optionList[$index], \"=\", $optionBreakDown);\n" + " if(size($optionBreakDown) < 2) continue;\n"; + + itf = m_frames.begin(); + for (; itf != endf; ++itf) { + auto ito = itf->m_options.begin(); + auto endo = itf->m_options.end(); + for (; ito != endo; ++ito) { + MString controlName = m_translatorName + "_" + ito->optionName; + m_code += MString(" if ($optionBreakDown[0] == \"") + ito->optionName + "\")\n"; + m_code += MString(" post_") + controlName + "($optionBreakDown[1]); else\n"; } - break; + } - case kEnum: - { - generateEnumGlobals(ito->niceName, ito->optionName, ito->enumValues, ito->defaultInt); - defaultOptionString += ito->optionName + "=" + (MString() + ito->defaultInt) + ";"; + m_code += " {\n post_"; + m_code += m_translatorName + + "($optionBreakDown[0], $optionBreakDown[1]);\n }\n" + " }\n }\n" + " }\n else\n if ($action == \"query\")\n {\n"; //< start of 'query' section - return + //all control values as key-value pairs + //in an option string. + + itf = m_frames.begin(); + for (; itf != endf; ++itf) { + auto ito = itf->m_options.begin(); + auto endo = itf->m_options.end(); + for (; ito != endo; ++ito) { + MString controlName = m_translatorName + "_" + ito->optionName; + m_code += MString(" $currentOptions = $currentOptions + `build_") + controlName + + "`;\n"; } - break; - } - } - } - - m_code += "global proc fromOptionVars_"; - m_code += m_translatorName; - m_code += "() {}\n"; - - m_code += "global proc create_"; - m_code += m_translatorName; - m_code += "(string $parent) {}\n"; - - m_code += "global proc post_"; - m_code += m_translatorName; - m_code += "(string $name, string $value) {}\n"; - - m_code += "global proc string query_"; - m_code += m_translatorName; - m_code += "() { return \"\"; }\n"; - - - // generate the actual entry point for our option dialog, e.g. - // - // global proc int myExporterName(string $parent, string $action, string $initialSettings, string $resultCallback) - // - m_code += MString("global proc int ") + m_translatorName + "(string $parent, string $action, string $initialSettings, string $resultCallback)\n{\n"; - m_code += " int $result = 1;\n" - " string $currentOptions;\n" - " string $optionList[];\n" - " string $optionBreakDown[];\n" - " int $index;\n" - " if ($action == \"post\")\n {\n" //< start of the 'post' section of the script (set control values from option string) - " setParent $parent;\n" - " columnLayout -adj true;\n" - " AL_usdmaya_SyncFileIOGui \"" + m_translatorName + "\";\n"; - - itf = m_frames.begin(); - for(; itf != endf; ++itf) - { - auto ito = itf->m_options.begin(); - auto endo = itf->m_options.end(); - for(; ito != endo; ++ito) - { - MString controlName = m_translatorName + "_" + ito->optionName; - m_code += MString(" create_") + controlName + "();\n"; - } - } - - m_code += " create_"; - m_code += m_translatorName; - m_code += "($parent);\n"; - - // generate the code to split apart the key-value pairs of options. - m_code += " if (size($initialSettings) > 0) {\n" - " tokenize($initialSettings, \";\", $optionList);\n" - " for ($index = 0; $index < size($optionList); $index++) {\n" - " tokenize($optionList[$index], \"=\", $optionBreakDown);\n" - " if(size($optionBreakDown) < 2) continue;\n"; - - itf = m_frames.begin(); - for(; itf != endf; ++itf) - { - auto ito = itf->m_options.begin(); - auto endo = itf->m_options.end(); - for(; ito != endo; ++ito) - { - MString controlName = m_translatorName + "_" + ito->optionName; - m_code += MString(" if ($optionBreakDown[0] == \"") + ito->optionName + "\")\n"; - m_code += MString(" post_") + controlName + "($optionBreakDown[1]); else\n"; - } - } - - m_code += " {\n post_"; - m_code += m_translatorName + "($optionBreakDown[0], $optionBreakDown[1]);\n }\n" - " }\n }\n" - " }\n else\n if ($action == \"query\")\n {\n"; //< start of 'query' section - return all control values as key-value pairs in an option string. - - itf = m_frames.begin(); - for(; itf != endf; ++itf) - { - auto ito = itf->m_options.begin(); - auto endo = itf->m_options.end(); - for(; ito != endo; ++ito) - { - MString controlName = m_translatorName + "_" + ito->optionName; - m_code += MString(" $currentOptions = $currentOptions + `build_") + controlName + "`;\n"; } - } - m_code += MString(" $currentOptions = $currentOptions + `query_") + m_translatorName + "`;\n"; - m_code += " eval($resultCallback+\" \\\"\"+$currentOptions+\"\\\"\");\n" - " }\n else\n {\n" - " $result = 0;\n }\n" - " return $result;\n}\n"; + m_code + += MString(" $currentOptions = $currentOptions + `query_") + m_translatorName + "`;\n"; + m_code += " eval($resultCallback+\" \\\"\"+$currentOptions+\"\\\"\");\n" + " }\n else\n {\n" + " $result = 0;\n }\n" + " return $result;\n}\n"; #if 0 std::cout << "--------------------------------------------------------\n"; @@ -663,11 +681,11 @@ MStatus FileTranslatorOptions::generateScript(OptionsParser& optionParser, MStri std::cout << "--------------------------------------------------------\n"; #endif - return MGlobal::executeCommand(m_code, false, false); + return MGlobal::executeCommand(m_code, false, false); } //---------------------------------------------------------------------------------------------------------------------- -} // utils -} // maya -} // AL +} // namespace utils +} // namespace maya +} // namespace AL //---------------------------------------------------------------------------------------------------------------------- diff --git a/plugin/al/mayautils/AL/maya/utils/FileTranslatorOptions.h b/plugin/al/mayautils/AL/maya/utils/FileTranslatorOptions.h index 14e69b5177..5ead51131e 100644 --- a/plugin/al/mayautils/AL/maya/utils/FileTranslatorOptions.h +++ b/plugin/al/mayautils/AL/maya/utils/FileTranslatorOptions.h @@ -16,7 +16,6 @@ #pragma once #include "AL/maya/utils/Api.h" - #include "AL/maya/utils/PluginTranslatorOptions.h" #include @@ -25,417 +24,404 @@ namespace AL { namespace maya { namespace utils { - //---------------------------------------------------------------------------------------------------------------------- /// \brief Utility class that parses the file translator options passed through by Maya /// \ingroup mayagui //---------------------------------------------------------------------------------------------------------------------- class OptionsParser { - friend class FileTranslatorOptions; -public: + friend class FileTranslatorOptions; - /// \brief ctor - AL_MAYA_UTILS_PUBLIC - OptionsParser(PluginTranslatorOptionsInstance* pluginOptions = 0); - - /// \brief dtor - AL_MAYA_UTILS_PUBLIC - ~OptionsParser(); - - /// \brief Given a string containing a semi-colon separated list of options passed to a file translator plugin, - /// this function will parse and extract all of the option values. - /// \param optionString the option string to parse - /// \return MS::kSuccess if the parsing was successful, false otherwise. - AL_MAYA_UTILS_PUBLIC - MStatus parse(const MString& optionString); - - /// \brief Given a string containing a semi-colon separated list of options passed to a file translator plugin, - /// this function will parse and extract all of the option values. - /// \param optionString the option string to parse - /// \return MS::kSuccess if the parsing was successful, false otherwise. - AL_MAYA_UTILS_PUBLIC - void construct(MString& optionString); - - /// \brief Given the text name of an option, returns the boolean value for that option. - /// \param str the name of the option - /// \return the option value - bool getBool(const char* const str) const - { - auto it = m_niceNameToValue.find(str); - if(it != m_niceNameToValue.end()) - { - return it->second->m_bool; - } - else - if(m_pluginOptions) - { - return m_pluginOptions->getBool(str); - } - else - std::cout << "no plugin options" << std::endl; - return false; - } - - /// \brief Given the text name of an option, returns the integer value for that option. - /// \param str the name of the option - /// \return the option value - int getInt(const char* const str) const - { - auto it = m_niceNameToValue.find(str); - if(it != m_niceNameToValue.end()) - { - return it->second->m_int; - } - else - if(m_pluginOptions) - { - return m_pluginOptions->getInt(str); - } - return 0; - } - - /// \brief Given the text name of an option, returns the floating point value for that option. - /// \param str the name of the option - /// \return the option value - float getFloat(const char* const str) const - { - auto it = m_niceNameToValue.find(str); - if(it != m_niceNameToValue.end()) - { - return it->second->m_float; - } - else - if(m_pluginOptions) - { - return m_pluginOptions->getFloat(str); - } - return 0.0f; - } - - /// \brief Given the text name of an option, returns the string value for that option. - /// \param str the name of the option - /// \return the option value - MString getString(const char* const str) const - { - auto it = m_niceNameToValue.find(str); - if(it != m_niceNameToValue.end()) - { - return it->second->m_string.c_str(); - } - else - if(m_pluginOptions) +public: + /// \brief ctor + AL_MAYA_UTILS_PUBLIC + OptionsParser(PluginTranslatorOptionsInstance* pluginOptions = 0); + + /// \brief dtor + AL_MAYA_UTILS_PUBLIC + ~OptionsParser(); + + /// \brief Given a string containing a semi-colon separated list of options passed to a file + /// translator plugin, + /// this function will parse and extract all of the option values. + /// \param optionString the option string to parse + /// \return MS::kSuccess if the parsing was successful, false otherwise. + AL_MAYA_UTILS_PUBLIC + MStatus parse(const MString& optionString); + + /// \brief Given a string containing a semi-colon separated list of options passed to a file + /// translator plugin, + /// this function will parse and extract all of the option values. + /// \param optionString the option string to parse + /// \return MS::kSuccess if the parsing was successful, false otherwise. + AL_MAYA_UTILS_PUBLIC + void construct(MString& optionString); + + /// \brief Given the text name of an option, returns the boolean value for that option. + /// \param str the name of the option + /// \return the option value + bool getBool(const char* const str) const { - return m_pluginOptions->getString(str); + auto it = m_niceNameToValue.find(str); + if (it != m_niceNameToValue.end()) { + return it->second->m_bool; + } else if (m_pluginOptions) { + return m_pluginOptions->getBool(str); + } else + std::cout << "no plugin options" << std::endl; + return false; } - return kNullString; - } - - /// \brief Given the text name of an option, returns the boolean value for that option. - /// \param str the name of the option - /// \return the option value - void setBool(const char* const str, bool value) - { - auto it = m_niceNameToValue.find(str); - if(it != m_niceNameToValue.end()) + + /// \brief Given the text name of an option, returns the integer value for that option. + /// \param str the name of the option + /// \return the option value + int getInt(const char* const str) const { - it->second->m_bool = value; + auto it = m_niceNameToValue.find(str); + if (it != m_niceNameToValue.end()) { + return it->second->m_int; + } else if (m_pluginOptions) { + return m_pluginOptions->getInt(str); + } + return 0; } - else - if(m_pluginOptions) + + /// \brief Given the text name of an option, returns the floating point value for that option. + /// \param str the name of the option + /// \return the option value + float getFloat(const char* const str) const { - m_pluginOptions->setBool(str, value); + auto it = m_niceNameToValue.find(str); + if (it != m_niceNameToValue.end()) { + return it->second->m_float; + } else if (m_pluginOptions) { + return m_pluginOptions->getFloat(str); + } + return 0.0f; } - } - - /// \brief Given the text name of an option, returns the integer value for that option. - /// \param str the name of the option - /// \return the option value - void setInt(const char* const str, int value) - { - auto it = m_niceNameToValue.find(str); - if(it != m_niceNameToValue.end()) + + /// \brief Given the text name of an option, returns the string value for that option. + /// \param str the name of the option + /// \return the option value + MString getString(const char* const str) const { - it->second->m_int = value; + auto it = m_niceNameToValue.find(str); + if (it != m_niceNameToValue.end()) { + return it->second->m_string.c_str(); + } else if (m_pluginOptions) { + return m_pluginOptions->getString(str); + } + return kNullString; } - else - if(m_pluginOptions) + + /// \brief Given the text name of an option, returns the boolean value for that option. + /// \param str the name of the option + /// \return the option value + void setBool(const char* const str, bool value) { - m_pluginOptions->setInt(str, value); + auto it = m_niceNameToValue.find(str); + if (it != m_niceNameToValue.end()) { + it->second->m_bool = value; + } else if (m_pluginOptions) { + m_pluginOptions->setBool(str, value); + } } - } - - /// \brief Given the text name of an option, returns the floating point value for that option. - /// \param str the name of the option - /// \return the option value - void setFloat(const char* const str, float value) - { - auto it = m_niceNameToValue.find(str); - if(it != m_niceNameToValue.end()) + + /// \brief Given the text name of an option, returns the integer value for that option. + /// \param str the name of the option + /// \return the option value + void setInt(const char* const str, int value) { - it->second->m_float = value; + auto it = m_niceNameToValue.find(str); + if (it != m_niceNameToValue.end()) { + it->second->m_int = value; + } else if (m_pluginOptions) { + m_pluginOptions->setInt(str, value); + } } - else - if(m_pluginOptions) + + /// \brief Given the text name of an option, returns the floating point value for that option. + /// \param str the name of the option + /// \return the option value + void setFloat(const char* const str, float value) { - m_pluginOptions->setFloat(str, value); + auto it = m_niceNameToValue.find(str); + if (it != m_niceNameToValue.end()) { + it->second->m_float = value; + } else if (m_pluginOptions) { + m_pluginOptions->setFloat(str, value); + } } - } - - /// \brief Given the text name of an option, returns the string value for that option. - /// \param str the name of the option - /// \return the option value - void setString(const char* const str, const MString& value) - { - auto it = m_niceNameToValue.find(str); - if(it != m_niceNameToValue.end()) + + /// \brief Given the text name of an option, returns the string value for that option. + /// \param str the name of the option + /// \return the option value + void setString(const char* const str, const MString& value) { - it->second->m_string = std::string(value.asChar(), value.length()); + auto it = m_niceNameToValue.find(str); + if (it != m_niceNameToValue.end()) { + it->second->m_string = std::string(value.asChar(), value.length()); + } else if (m_pluginOptions) { + m_pluginOptions->setString(str, value.asChar()); + } } - else - if(m_pluginOptions) + + void setPluginOptionsContext(PluginTranslatorOptionsInstance* pluginOptions) { - m_pluginOptions->setString(str, value.asChar()); + m_pluginOptions = pluginOptions; } - } - - void setPluginOptionsContext(PluginTranslatorOptionsInstance* pluginOptions) - { - m_pluginOptions = pluginOptions; - } private: #ifndef AL_GENERATING_DOCS - enum OptionType - { - kBool, - kInt, - kFloat, - kString, - kEnum - }; - - AL_MAYA_UTILS_PUBLIC - static const MString kNullString; - struct OptionValue - { - void init() + enum OptionType { - switch(m_type) - { - case kBool: m_bool = m_defaultBool; break; - case kInt: m_int = m_defaultInt; break; - case kFloat: m_float = m_defaultFloat; break; - case kString: m_string = m_defaultString; break; - case kEnum: m_int = m_defaultInt; break; - default: break; - } - } + kBool, + kInt, + kFloat, + kString, + kEnum + }; - void parse(MString& str) + AL_MAYA_UTILS_PUBLIC + static const MString kNullString; + struct OptionValue { - switch(m_type) - { - case kBool: m_bool = str.asInt() ? true : false; break; - case kInt: m_int = str.asInt(); break; - case kFloat: m_float = str.asFloat(); break; - case kString: m_string = str.asChar(); break; - case kEnum: m_int = str.asInt(); break; - default: break; - } - } + void init() + { + switch (m_type) { + case kBool: m_bool = m_defaultBool; break; + case kInt: m_int = m_defaultInt; break; + case kFloat: m_float = m_defaultFloat; break; + case kString: m_string = m_defaultString; break; + case kEnum: m_int = m_defaultInt; break; + default: break; + } + } - OptionType m_type; - union - { - bool m_defaultBool; - int m_defaultInt; - float m_defaultFloat; - }; - std::string m_defaultString; - union - { - bool m_bool; - int m_int; - float m_float; + void parse(MString& str) + { + switch (m_type) { + case kBool: m_bool = str.asInt() ? true : false; break; + case kInt: m_int = str.asInt(); break; + case kFloat: m_float = str.asFloat(); break; + case kString: m_string = str.asChar(); break; + case kEnum: m_int = str.asInt(); break; + default: break; + } + } + + OptionType m_type; + union + { + bool m_defaultBool; + int m_defaultInt; + float m_defaultFloat; + }; + std::string m_defaultString; + union + { + bool m_bool; + int m_int; + float m_float; + }; + std::string m_string; }; - std::string m_string; - }; - std::map m_optionNameToValue; - std::map m_niceNameToValue; - PluginTranslatorOptionsInstance* m_pluginOptions; + std::map m_optionNameToValue; + std::map m_niceNameToValue; + PluginTranslatorOptionsInstance* m_pluginOptions; #endif }; - //---------------------------------------------------------------------------------------------------------------------- -/// \brief Utility class that constructs the file translator export GUI from the export options you want to support. +/// \brief Utility class that constructs the file translator export GUI from the export options you +/// want to support. //---------------------------------------------------------------------------------------------------------------------- class FileTranslatorOptions { public: - - /// \brief ctor - /// \param fileTranslatorName the name of the file translator - AL_MAYA_UTILS_PUBLIC - FileTranslatorOptions(const char* fileTranslatorName); - - /// \name High Level Layout - /// \brief A collection of file translator options can be grouped into 1 or more GUI frames within the GUI. - /// At a minimum, there must be at least 1 frame added to the GUI prior to any options being added. - - /// \brief add a new frame layout under which to group a set of controls. There must be at least 1 frame created - /// before you create any options (otherwise the controls will not have a location in which to live) - /// \param frameName the name of the high level frame to add into the GUI - AL_MAYA_UTILS_PUBLIC - bool addFrame(const char* frameName); - - /// \brief remove frame layout and it's set of controls - /// \param frameName the name of the high level frame to remove - AL_MAYA_UTILS_PUBLIC - bool removeFrame(const char* frameName); - - /// \name Add Exporter Options - /// \brief Add custom export/import options using the following methods. There must be at least 1 frame layout - /// created prior to creating any new controls. - - /// \brief Add a boolean value to the translator options - /// \param optionName the name of the option - /// \param defaultValue the default value for the option - /// \return true if the option was successfully added. False if the option is a duplicate - AL_MAYA_UTILS_PUBLIC - bool addBool(const char* optionName, bool defaultValue = false); - - /// \brief Add an integer value to the translator options - /// \param optionName the name of the option - /// \param defaultValue the default value for the option - /// \return true if the option was successfully added. False if the option is a duplicate - AL_MAYA_UTILS_PUBLIC - bool addInt(const char* optionName, int defaultValue = 0); - - /// \brief Add a float value to the translator options - /// \param optionName the name of the option - /// \param defaultValue the default value for the option - /// \return true if the option was successfully added. False if the option is a duplicate - AL_MAYA_UTILS_PUBLIC - bool addFloat(const char* optionName, float defaultValue = 0.0f); - - /// \brief Add a string value to the translator options - /// \param optionName the name of the option - /// \param defaultValue the default value for the option - /// \return true if the option was successfully added. False if the option is a duplicate - AL_MAYA_UTILS_PUBLIC - bool addString(const char* optionName, const char* const defaultValue = ""); - - /// \brief Add an integer value to the translator options - /// \param optionName the name of the option - /// \param enumValues a null terminated list of strings for each enum entry - /// \param defaultValue the default value for the option - /// \return true if the option was successfully added. False if the option is a duplicate - AL_MAYA_UTILS_PUBLIC - bool addEnum(const char* optionName, const char* const enumValues[], int defaultValue = 0); - - /// \brief For a given boolean option (the controller), if enabled the 'controlled' option will be editable. If - /// the checkbox is uncecked, the controlled option will be disabled in the GUI. The invertBehaviour - /// param reverses this behaviour (i.e. if controller is true, controlled will be disabled). - /// \param controller the name of the option that controls the enabled state of the controlled option. - /// \param controlled the name of the option to enable/disable based on the state of the controlled attribute. - /// \param invertBehaviour if true, controlled will be disabled when controller is enabled. - /// if false, controlled will be enabled when controller is enabled. - /// \return true if the visibility relationship could be created. May return false if the controller or - /// controlled options are invalid. - AL_MAYA_UTILS_PUBLIC - bool boolControlsVisibility(const char* controller, const char* controlled, bool invertBehaviour = false); - - /// \name MEL script code generation - /// \brief Once all of the options have been added for the file translator, then you can easily generate the - /// MEL script code via the generateScript method. - - /// \brief This method generates the MEL script for the import/export GUI, and evaluates it behind the scenes. - /// It also configure the option parser for use by the MPxFileTranslator object, and generates the - /// defaultOptionString required when registering the function. - /// \param optionParser the option parser in which the options for the file translator have been specified - /// \param defaultOptionString the returned default option string for the file translator (which can be used - /// when registering your file translator with the MFnPlugin) - /// \return MS::kSuccess if ok - AL_MAYA_UTILS_PUBLIC - MStatus generateScript(OptionsParser& optionParser, MString& defaultOptionString); - - /// \brief This method initialises all of the options stored within the option parser - /// \param optionParser the option parser in which the options for the file translator have been specified - /// \return MS::kSuccess if ok - AL_MAYA_UTILS_PUBLIC - MStatus initParser(OptionsParser& optionParser); + /// \brief ctor + /// \param fileTranslatorName the name of the file translator + AL_MAYA_UTILS_PUBLIC + FileTranslatorOptions(const char* fileTranslatorName); + + /// \name High Level Layout + /// \brief A collection of file translator options can be grouped into 1 or more GUI frames + /// within the GUI. + /// At a minimum, there must be at least 1 frame added to the GUI prior to any options + /// being added. + + /// \brief add a new frame layout under which to group a set of controls. There must be at + /// least 1 frame created + /// before you create any options (otherwise the controls will not have a location in + /// which to live) + /// \param frameName the name of the high level frame to add into the GUI + AL_MAYA_UTILS_PUBLIC + bool addFrame(const char* frameName); + + /// \brief remove frame layout and it's set of controls + /// \param frameName the name of the high level frame to remove + AL_MAYA_UTILS_PUBLIC + bool removeFrame(const char* frameName); + + /// \name Add Exporter Options + /// \brief Add custom export/import options using the following methods. There must be at least + /// 1 frame layout + /// created prior to creating any new controls. + + /// \brief Add a boolean value to the translator options + /// \param optionName the name of the option + /// \param defaultValue the default value for the option + /// \return true if the option was successfully added. False if the option is a duplicate + AL_MAYA_UTILS_PUBLIC + bool addBool(const char* optionName, bool defaultValue = false); + + /// \brief Add an integer value to the translator options + /// \param optionName the name of the option + /// \param defaultValue the default value for the option + /// \return true if the option was successfully added. False if the option is a duplicate + AL_MAYA_UTILS_PUBLIC + bool addInt(const char* optionName, int defaultValue = 0); + + /// \brief Add a float value to the translator options + /// \param optionName the name of the option + /// \param defaultValue the default value for the option + /// \return true if the option was successfully added. False if the option is a duplicate + AL_MAYA_UTILS_PUBLIC + bool addFloat(const char* optionName, float defaultValue = 0.0f); + + /// \brief Add a string value to the translator options + /// \param optionName the name of the option + /// \param defaultValue the default value for the option + /// \return true if the option was successfully added. False if the option is a duplicate + AL_MAYA_UTILS_PUBLIC + bool addString(const char* optionName, const char* const defaultValue = ""); + + /// \brief Add an integer value to the translator options + /// \param optionName the name of the option + /// \param enumValues a null terminated list of strings for each enum entry + /// \param defaultValue the default value for the option + /// \return true if the option was successfully added. False if the option is a duplicate + AL_MAYA_UTILS_PUBLIC + bool addEnum(const char* optionName, const char* const enumValues[], int defaultValue = 0); + + /// \brief For a given boolean option (the controller), if enabled the 'controlled' option will + /// be editable. If + /// the checkbox is uncecked, the controlled option will be disabled in the GUI. The + /// invertBehaviour param reverses this behaviour (i.e. if controller is true, + /// controlled will be disabled). + /// \param controller the name of the option that controls the enabled state of the controlled + /// option. \param controlled the name of the option to enable/disable based on the state of + /// the controlled attribute. \param invertBehaviour if true, controlled will be disabled when + /// controller is enabled. + /// if false, controlled will be enabled when controller is enabled. + /// \return true if the visibility relationship could be created. May return false if the + /// controller or + /// controlled options are invalid. + AL_MAYA_UTILS_PUBLIC + bool boolControlsVisibility( + const char* controller, + const char* controlled, + bool invertBehaviour = false); + + /// \name MEL script code generation + /// \brief Once all of the options have been added for the file translator, then you can easily + /// generate the + /// MEL script code via the generateScript method. + + /// \brief This method generates the MEL script for the import/export GUI, and evaluates it + /// behind the scenes. + /// It also configure the option parser for use by the MPxFileTranslator object, and + /// generates the defaultOptionString required when registering the function. + /// \param optionParser the option parser in which the options for the file translator have + /// been specified \param defaultOptionString the returned default option string for the file + /// translator (which can be used + /// when registering your file translator with the MFnPlugin) + /// \return MS::kSuccess if ok + AL_MAYA_UTILS_PUBLIC + MStatus generateScript(OptionsParser& optionParser, MString& defaultOptionString); + + /// \brief This method initialises all of the options stored within the option parser + /// \param optionParser the option parser in which the options for the file translator have + /// been specified \return MS::kSuccess if ok + AL_MAYA_UTILS_PUBLIC + MStatus initParser(OptionsParser& optionParser); protected: #ifndef AL_GENERATING_DOCS - bool hasOption(const char* const optionName) const; - bool hasOption(const MString& optionName) const { return hasOption(optionName.asChar()); } - void generateBoolGlobals(const MString& niceName, const MString& optionName, bool defaultValue); - void generateIntGlobals(const MString& niceName, const MString& optionName, int defaultValue); - void generateFloatGlobals(const MString& niceName, const MString& optionName, float defaultValue); - void generateStringGlobals(const MString& niceName, const MString& optionName, MString defaultValue); - void generateEnumGlobals(const MString& niceName, const MString& optionName, const char* const enumVals[], int defaultValue); + bool hasOption(const char* const optionName) const; + bool hasOption(const MString& optionName) const { return hasOption(optionName.asChar()); } + void generateBoolGlobals(const MString& niceName, const MString& optionName, bool defaultValue); + void generateIntGlobals(const MString& niceName, const MString& optionName, int defaultValue); + void + generateFloatGlobals(const MString& niceName, const MString& optionName, float defaultValue); + void + generateStringGlobals(const MString& niceName, const MString& optionName, MString defaultValue); + void generateEnumGlobals( + const MString& niceName, + const MString& optionName, + const char* const enumVals[], + int defaultValue); #endif private: #ifndef AL_GENERATING_DOCS - enum OptionType - { - kBool, - kInt, - kFloat, - kString, - kEnum - }; - struct FrameLayout - { - FrameLayout(const char* frameName) - : m_frameName(frameName), m_options() - {} - MString m_frameName; - struct Option + enum OptionType { - MString optionName; - MString niceName; - OptionType type; - union - { - bool defaultBool; - int defaultInt; - float defaultFloat; - const char* defaultString; - }; - const char* const* enumValues; - - Option() = default; - Option(const Option& opt) - : optionName(opt.optionName), niceName(opt.niceName), type(opt.type), enumValues(opt.enumValues) - { - switch(type) + kBool, + kInt, + kFloat, + kString, + kEnum + }; + struct FrameLayout + { + FrameLayout(const char* frameName) + : m_frameName(frameName) + , m_options() { - case kBool: defaultBool = opt.defaultBool; break; - case kInt: - case kEnum: defaultInt = opt.defaultInt; break; - case kFloat: defaultFloat = opt.defaultFloat; break; - case kString: defaultString = opt.defaultString; break; } - } + MString m_frameName; + struct Option + { + MString optionName; + MString niceName; + OptionType type; + union + { + bool defaultBool; + int defaultInt; + float defaultFloat; + const char* defaultString; + }; + const char* const* enumValues; + + Option() = default; + Option(const Option& opt) + : optionName(opt.optionName) + , niceName(opt.niceName) + , type(opt.type) + , enumValues(opt.enumValues) + { + switch (type) { + case kBool: defaultBool = opt.defaultBool; break; + case kInt: + case kEnum: defaultInt = opt.defaultInt; break; + case kFloat: defaultFloat = opt.defaultFloat; break; + case kString: defaultString = opt.defaultString; break; + } + } + }; + std::vector