file_path
stringlengths
21
224
content
stringlengths
0
80.8M
ashleygoldstein/LWM-Warehouse-Scene/README.md
# LWM-Warehouse-Scene This Sample was developed during the Learn With Me livestream Series. Learn With Me streams every Monday and Wednesday at 1pm EST on the NVIDIA Omniverse Twitch and YouTube channels https://www.youtube.com/@NVIDIAOmniverse/streams Playlist of the previously recorded streams: https://youtube.com/playlist?list=PLPR2h_elPvVKH9HLtdgfXNUxGeN6QAlc7 This USD works in Omniverse USD Composer (fka Create) and Isaac Sim 2022.2.0 and later versions. Check out the Tests folder for simple test scenes. Contributors/Inspired Authors: Alberto Arenas / Omniverse Ambassador- Camera Constraint ActionGraph Mathew Schwartz / NJIT - Behavior Scripts for Detecting Collision Eric Craft / Mead & Hunt - Collision Detection OmniGraph ____________________________________________ Notes: For the full sample scene to work, please download all of the .usd files in that folder as the main scene, Warehouse_Detect_Coll_OG, uses payloads of the graphs. If the graphs are not working, please ensure they are connected to the payload. You must have Physx Graph enabled from the Extension Manager in order for the Counter graph to work. If you add more packages to the scene, a Rigidbody with Colliders preset must be added, if not already on the package, then remove the Colliders from the Decal Mesh and the Scotch Mesh. Questions? Join me on Discord at discord.gg/nvidiaomniverse or email me at agoldstein@nvidia.com
ashleygoldstein/LWM-Warehouse-Scene/Scripts/pallet_collision.py
from omni.kit.scripting import BehaviorScript import omni import omni.physx from pxr import Gf, Sdf, PhysxSchema, UsdGeom, Usd from omni.physx.scripts import utils from omni.physx import get_physx_scene_query_interface from omni.physx import get_physx_interface, get_physx_simulation_interface from omni.physx.scripts.physicsUtils import * import carb class CollisionTest(BehaviorScript): def on_init(self): self.ignore_objects = [] self.pallet_collection = 0 self.collected_attr = self.prim.CreateAttribute('Collected', Sdf.ValueTypeNames.Int) self.collected_attr.Set(0) self.reset_character() def on_play(self): '''' Called on runtime ''' self.reset_character() self._contact_report_sub = get_physx_simulation_interface().subscribe_contact_report_events(self._on_contact_report_event) contactReportAPI = PhysxSchema.PhysxContactReportAPI.Apply(self.prim) contactReportAPI.CreateThresholdAttr().Set(self.contact_thresh) def on_stop(self): self.on_destroy() def on_destroy(self): self.pallet = None self.collected_attr.Set(0) self._contact_report_sub.unsubscribe() self._contact_report_sub = None def reset_character(self): self.contact_thresh = 1 self.collected_attr.Set(0) self.pallet_collection = 0 self.ignore_objects = [] # Assign this pallet as agent instance self.pallet = str(self.prim_path) # parent_prim = self.stage.GetPrimAtPath(self.package_path) # if parent_prim.IsValid(): # children = parent_prim.GetAllChildren() # self.package = [str(child.GetPath()) for child in children] def on_update(self, current_time: float, delta_time: float): """ Called on every update. Initializes character at start, publishes character positions and executes character commands. :param float current_time: current time in seconds. :param float delta_time: time elapsed since last update. """ return def subscribe_to_contact(self): # apply contact report ### This would be an example of each object managing their own collision self._contact_report_sub = get_physx_simulation_interface().subscribe_contact_report_events(self._on_contact_report_event) contactReportAPI = PhysxSchema.PhysxContactReportAPI.Apply(self.prim) contactReportAPI.CreateThresholdAttr().Set(self.contact_thresh) def _on_contact_report_event(self, contact_headers, contact_data): # Check if a collision was because of a player for contact_header in contact_headers: collider_1 = str(PhysicsSchemaTools.intToSdfPath(contact_header.actor0)) collider_2 = str(PhysicsSchemaTools.intToSdfPath(contact_header.actor1)) contacts = [collider_1, collider_2] if self.prim_path in contacts: self.object_path = "" if self.prim_path == collider_1: self.object_path = collider_2 else: self.object_path = collider_1 print(collider_2) if self.object_path in self.ignore_objects: continue else: self.ignore_objects.append(self.object_path) self.pallet_collection += 1 print(f'Collected: {self.pallet_collection}') self.collected_attr.Set(self.pallet_collection)
dantreble/a2f/README.md
# a2f Unreal plugin to import json blendshape animations generated by audio2face in Nvidia Omniverse It can convert a blend shape channel to a bone transform: ![Import settings example](/Resources/importsettings.png) It supports reimport and batch import.
dantreble/a2f/Source/a2fEditor/Private/a2fOptionWindow.cpp
// Copyright Epic Games, Inc. All Rights Reserved. #include "a2fOptionWindow.h" #include "Modules/ModuleManager.h" #include "Widgets/Layout/SBorder.h" #include "Widgets/Text/STextBlock.h" #include "Widgets/Layout/SBox.h" #include "Widgets/Layout/SUniformGridPanel.h" #include "Widgets/Input/SButton.h" #include "EditorStyleSet.h" #include "Factories/FbxAnimSequenceImportData.h" #include "IDocumentation.h" #include "PropertyEditorModule.h" #include "IDetailsView.h" #define LOCTEXT_NAMESPACE "Fa2fEditorModule" void Sa2fOptionWindow::Construct(const FArguments& InArgs) { ImportUI = InArgs._ImportUI; WidgetWindow = InArgs._WidgetWindow; check (ImportUI); TSharedPtr<SBox> ImportTypeDisplay; TSharedPtr<SHorizontalBox> FbxHeaderButtons; TSharedPtr<SBox> InspectorBox; this->ChildSlot [ SNew(SBox) .MaxDesiredHeight(InArgs._MaxWindowHeight) .MaxDesiredWidth(InArgs._MaxWindowWidth) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .Padding(2) [ SAssignNew(ImportTypeDisplay, SBox) ] +SVerticalBox::Slot() .AutoHeight() .Padding(2) [ SNew(SBorder) .Padding(FMargin(3)) .BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder")) [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .AutoWidth() [ SNew(STextBlock) .Font(FEditorStyle::GetFontStyle("CurveEd.LabelFont")) .Text(LOCTEXT("Import_CurrentFileTitle", "Current Asset: ")) ] +SHorizontalBox::Slot() .Padding(5, 0, 0, 0) .AutoWidth() .VAlign(VAlign_Center) [ SNew(STextBlock) .Font(FEditorStyle::GetFontStyle("CurveEd.InfoFont")) .Text(InArgs._FullPath) .ToolTipText(InArgs._FullPath) ] ] ] + SVerticalBox::Slot() .AutoHeight() .Padding(2) [ SAssignNew(InspectorBox, SBox) .MaxDesiredHeight(650.0f) .WidthOverride(400.0f) ] + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Right) .Padding(2) [ SNew(SUniformGridPanel) .SlotPadding(2) + SUniformGridPanel::Slot(0, 0) [ IDocumentation::Get()->CreateAnchor(FString("Engine/Content/FBX/ImportOptions")) ] + SUniformGridPanel::Slot(1, 0) [ SNew(SButton) .HAlign(HAlign_Center) .Text(LOCTEXT("FbxOptionWindow_ImportAll", "Import All")) .ToolTipText(LOCTEXT("FbxOptionWindow_ImportAll_ToolTip", "Import all files with these same settings")) .IsEnabled(this, &Sa2fOptionWindow::CanImport) .OnClicked(this, &Sa2fOptionWindow::OnImportAll) ] + SUniformGridPanel::Slot(2, 0) [ SAssignNew(ImportButton, SButton) .HAlign(HAlign_Center) .Text(LOCTEXT("FbxOptionWindow_Import", "Import")) .IsEnabled(this, &Sa2fOptionWindow::CanImport) .OnClicked(this, &Sa2fOptionWindow::OnImport) ] + SUniformGridPanel::Slot(3, 0) [ SNew(SButton) .HAlign(HAlign_Center) .Text(LOCTEXT("FbxOptionWindow_Cancel", "Cancel")) .ToolTipText(LOCTEXT("FbxOptionWindow_Cancel_ToolTip", "Cancels importing this FBX file")) .OnClicked(this, &Sa2fOptionWindow::OnCancel) ] ] ] ]; FPropertyEditorModule& PropertyEditorModule = FModuleManager::GetModuleChecked<FPropertyEditorModule>("PropertyEditor"); FDetailsViewArgs DetailsViewArgs; DetailsViewArgs.bAllowSearch = false; DetailsViewArgs.NameAreaSettings = FDetailsViewArgs::HideNameArea; DetailsView = PropertyEditorModule.CreateDetailView(DetailsViewArgs); InspectorBox->SetContent(DetailsView->AsShared()); ImportTypeDisplay->SetContent( SNew(SBorder) .Padding(FMargin(3)) .BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder")) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .VAlign(VAlign_Center) [ SNew(STextBlock) .Text(this, &Sa2fOptionWindow::GetImportTypeDisplayText) ] + SHorizontalBox::Slot() [ SNew(SBox) .HAlign(HAlign_Right) [ SAssignNew(FbxHeaderButtons, SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(FMargin(2.0f, 0.0f)) [ SNew(SButton) .Text(LOCTEXT("FbxOptionWindow_ResetOptions", "Reset to Default")) .OnClicked(this, &Sa2fOptionWindow::OnResetToDefaultClick) ] ] ] ] ); DetailsView->SetObject(ImportUI); } FReply Sa2fOptionWindow::OnImport() { bShouldImport = true; if ( WidgetWindow.IsValid() ) { WidgetWindow.Pin()->RequestDestroyWindow(); } return FReply::Handled(); } FReply Sa2fOptionWindow::OnCancel() { bShouldImport = false; bShouldImportAll = false; if ( WidgetWindow.IsValid() ) { WidgetWindow.Pin()->RequestDestroyWindow(); } return FReply::Handled(); } FReply Sa2fOptionWindow::OnKeyDown(const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent) { if( InKeyEvent.GetKey() == EKeys::Escape ) { return OnCancel(); } return FReply::Unhandled(); } bool Sa2fOptionWindow::ShouldImport() const { return bShouldImport; } FReply Sa2fOptionWindow::OnResetToDefaultClick() const { ImportUI->ResetToDefault(); //Refresh the view to make sure the custom UI are updating correctly DetailsView->SetObject(ImportUI, true); return FReply::Handled(); } FText Sa2fOptionWindow::GetImportTypeDisplayText() const { return ImportUI->bIsReimport ? LOCTEXT("FbxOptionWindow_ReImportTypeAnim", "Reimport Animation") : LOCTEXT("FbxOptionWindow_ImportTypeAnim", "Import Animation"); } bool Sa2fOptionWindow::CanImport() const { // do test to see if we are ready to import if (ImportUI->Skeleton == NULL) { return false; } //if (ImportUI->AnimSequenceImportData->AnimationLength == FBXALIT_SetRange) //{ // if (ImportUI->AnimSequenceImportData->FrameImportRange.Min > ImportUI->AnimSequenceImportData->FrameImportRange.Max) // { // return false; // } //} return true; } #undef LOCTEXT_NAMESPACE
dantreble/a2f/Source/a2fEditor/Private/a2fEditor.cpp
// Copyright Spitfire Interactive Pty Ltd. All Rights Reserved. #include "a2fEditor.h" #define LOCTEXT_NAMESPACE "Fa2fEditorModule" void Fa2fEditorModule::StartupModule() { // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module } void Fa2fEditorModule::ShutdownModule() { // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading, // we call this function before unloading the module. } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(Fa2fEditorModule, a2f)
dantreble/a2f/Source/a2fEditor/Private/a2fImportUI.cpp
// Copyright Spitfire Interactive Pty Ltd. All Rights Reserved. #include "a2fImportUI.h" #include "a2fAssetImportData.h" #include "AnimationUtils.h" Ua2fImportUI::Ua2fImportUI() { ResetToDefault(); } void Ua2fImportUI::ResetToDefault() { AnimSequenceImportData = CreateDefaultSubobject<Ua2fAssetImportData>(TEXT("AnimSequenceImportData"), true); BoneCompressionSettings = FAnimationUtils::GetDefaultAnimationBoneCompressionSettings(); CurveCompressionSettings = FAnimationUtils::GetDefaultAnimationCurveCompressionSettings(); }
dantreble/a2f/Source/a2fEditor/Private/a2fAssetImportData.cpp
// Copyright Spitfire Interactive Pty Ltd. All Rights Reserved. #include "a2fAssetImportData.h" void Ua2fAssetImportData::GetCurvesToStrip(TSet<FString> &CurvesToStrip) const { for (const FCurveDrivenBoneTransform &CurveDrivenBoneTransform : CurveDrivenBoneTransforms) { for (const FCurveDrivenTransform &CurveDrivenTransform : CurveDrivenBoneTransform.CurveDrivenTransforms) { if(CurveDrivenTransform.StripCurveTrack) { CurvesToStrip.Add(CurveDrivenTransform.Curve); } } } }
dantreble/a2f/Source/a2fEditor/Private/a2fFactory.cpp
// Copyright Spitfire Interactive Pty Ltd. All Rights Reserved. #include "a2fFactory.h" #include "a2fAssetImportData.h" #include "a2fImportUI.h" #include "a2fOptionWindow.h" #include "AnimationUtils.h" #include "EditorFramework/AssetImportData.h" #include "Interfaces/IMainFrameModule.h" #include "Misc/FileHelper.h" #include "Serialization/JsonSerializer.h" #include "HAL/PlatformApplicationMisc.h" Ua2fFactory::Ua2fFactory(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { bCreateNew = false; bEditorImport = true; bText = true; bShowOption = true; bOperationCanceled = false; ImportUI = nullptr; SupportedClass = UAnimSequence::StaticClass(); Formats.Add("json;JavaScript Object Notation"); } void Ua2fFactory::PostInitProperties() { ImportUI = NewObject<Ua2fImportUI>(this, NAME_None, RF_NoFlags); Super::PostInitProperties(); } bool Ua2fFactory::FactoryCanImport(const FString& Filename) { return true; } inline UObject* Ua2fFactory::FactoryCreateText(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, UObject* Context, const TCHAR* Type, const TCHAR*& Buffer, const TCHAR* BufferEnd, FFeedbackContext* Warn, bool& bOutOperationCanceled) { //We are not re-importing ImportUI->bIsReimport = false; //ImportUI->ReimportMesh = nullptr; //ImportUI->bAllowContentTypeImport = true; // Show the import dialog only when not in a "yes to all" state or when automating import bool bIsAutomated = IsAutomatedImport(); bool bShowImportDialog = bShowOption && !bIsAutomated; bool bImportAll = false; //Only try and read the old data on individual imports if(bShowImportDialog) { if (const UAnimSequence* ExistingAnimSequence = FindObject<UAnimSequence>(InParent, *InName.ToString())) { ImportUI->Skeleton = ExistingAnimSequence->GetSkeleton(); ImportUI->BoneCompressionSettings = ExistingAnimSequence->BoneCompressionSettings; ImportUI->CurveCompressionSettings = ExistingAnimSequence->CurveCompressionSettings; if (Ua2fAssetImportData* ExistingImportData = Cast<Ua2fAssetImportData>(ExistingAnimSequence->AssetImportData)) { ImportUI->AnimSequenceImportData = ExistingImportData; } } } if(bShowImportDialog) { TSharedPtr<SWindow> ParentWindow; if (FModuleManager::Get().IsModuleLoaded("MainFrame")) { IMainFrameModule& MainFrame = FModuleManager::LoadModuleChecked<IMainFrameModule>("MainFrame"); ParentWindow = MainFrame.GetParentWindow(); } // Compute centered window position based on max window size, which include when all categories are expanded const float ImportWindowWidth = 410.0f; const float ImportWindowHeight = 750.0f; FVector2D ImportWindowSize = FVector2D(ImportWindowWidth, ImportWindowHeight); // Max window size it can get based on current slate const FSlateRect WorkAreaRect = FSlateApplicationBase::Get().GetPreferredWorkArea(); const FVector2D DisplayTopLeft(WorkAreaRect.Left, WorkAreaRect.Top); const FVector2D DisplaySize(WorkAreaRect.Right - WorkAreaRect.Left, WorkAreaRect.Bottom - WorkAreaRect.Top); const float ScaleFactor = FPlatformApplicationMisc::GetDPIScaleFactorAtPoint(DisplayTopLeft.X, DisplayTopLeft.Y); ImportWindowSize *= ScaleFactor; const FVector2D WindowPosition = (DisplayTopLeft + (DisplaySize - ImportWindowSize) / 2.0f) / ScaleFactor; TSharedRef<SWindow> Window = SNew(SWindow) .Title(NSLOCTEXT("UnrealEd", "a2fImportOpionsTitle", "a2f Import Options")) .SizingRule(ESizingRule::Autosized) .AutoCenter(EAutoCenter::None) .ClientSize(ImportWindowSize) .ScreenPosition(WindowPosition); TSharedPtr<Sa2fOptionWindow> A2FOptionWindow; Window->SetContent ( SAssignNew(A2FOptionWindow, Sa2fOptionWindow) .ImportUI(ImportUI) .WidgetWindow(Window) .FullPath(FText::FromString(InParent->GetPathName())) .MaxWindowHeight(ImportWindowHeight) .MaxWindowWidth(ImportWindowWidth) ); FSlateApplication::Get().AddModalWindow(Window, ParentWindow, false); bImportAll = A2FOptionWindow->ShouldImportAll(); bOperationCanceled |= !A2FOptionWindow->ShouldImport(); } if(bOperationCanceled) { bOutOperationCanceled = true; return nullptr; } if(bImportAll) { // If the user chose to import all, we don't show the dialog again and use the same settings for each object until importing another set of files bShowOption = false; } UAnimSequence* AnimSequence = CastChecked<UAnimSequence>(CreateOrOverwriteAsset(InClass, InParent, InName, Flags)); if( AnimSequence == nullptr) { return nullptr; } USkeleton* Skeleton = ImportUI->Skeleton; AnimSequence->SetSkeleton(Skeleton); Ua2fAssetImportData* ImportData = Cast<Ua2fAssetImportData>(AnimSequence->AssetImportData); if (!ImportData) { ImportData = NewObject<Ua2fAssetImportData>(AnimSequence, NAME_None, RF_NoFlags, ImportUI->AnimSequenceImportData); // Try to preserve the source file data if possible if (AnimSequence->AssetImportData != nullptr) { ImportData->SourceData = AnimSequence->AssetImportData->SourceData; } AnimSequence->AssetImportData = ImportData; } AnimSequence->AssetImportData->AddFileName(UFactory::GetCurrentFilename(), 0); TSharedPtr<FJsonObject> JsonObject = MakeShareable(new FJsonObject()); const TSharedRef<TJsonReader<>> JsonReader = TJsonReaderFactory<>::Create(Buffer); if (!(JsonObject.IsValid() && FJsonSerializer::Deserialize(JsonReader, JsonObject))) { return nullptr; } int32 NumPoses; JsonObject->TryGetNumberField(TEXT("numPoses"), NumPoses); int32 NumFrames; JsonObject->TryGetNumberField(TEXT("numFrames"), NumFrames); TArray<FString> CurveNames; JsonObject->TryGetStringArrayField(TEXT("facsNames"), CurveNames); const TArray<TSharedPtr<FJsonValue>>* WeightMat; JsonObject->TryGetArrayField(TEXT("weightMat"), WeightMat); const int32 FPS = ImportUI->AnimSequenceImportData->FrameRate; if (CurveNames.Num() == 0 || WeightMat == nullptr) { return nullptr; } bool bIsAdditiveAnim = ImportUI->AnimSequenceImportData->AdditiveAnimType == AAT_LocalSpaceBase || ImportUI->AnimSequenceImportData->AdditiveAnimType == AAT_RotationOffsetMeshSpace; const int32 Frames = WeightMat->Num(); TSet<FString> CurvesToStrip; ImportUI->AnimSequenceImportData->GetCurvesToStrip(CurvesToStrip); for(int32 CurveIndex = 0; CurveIndex < CurveNames.Num(); ++CurveIndex) { const FString& CurveName = CurveNames[CurveIndex]; if(CurvesToStrip.Contains(CurveName)) { continue; } const USkeleton::AnimCurveUID CurveUID = Skeleton->GetUIDByName(USkeleton::AnimCurveMappingName, *CurveName); if (CurveUID == SmartName::MaxUID) { continue; } TArray<FRichCurveKey> Keys; Keys.Reserve(Frames); float WeightMin = FLT_MAX; float WeightMax = FLT_MIN; for (int32 FrameIndex = 0; FrameIndex < Frames; ++FrameIndex) { const TSharedPtr<FJsonValue>& WeightRow = (*WeightMat)[FrameIndex]; const float Time = static_cast<float>(FrameIndex) / FPS; const TArray<TSharedPtr<FJsonValue>>& WeightValues = WeightRow->AsArray(); const float Weight = WeightValues[CurveIndex]->AsNumber(); WeightMin = FMath::Min(WeightMin, Weight); WeightMax = FMath::Max(WeightMax, Weight); Keys.Add(FRichCurveKey(Time, Weight)); } //If the anim is additive and all the values are zero, don't bother adding a track if(bIsAdditiveAnim && FMath::IsNearlyEqual(WeightMin,0.0f) && FMath::IsNearlyEqual(WeightMax, 0.0f)) { continue; } FSmartName SmartName; Skeleton->GetSmartNameByUID(USkeleton::AnimCurveMappingName, CurveUID, SmartName); AnimSequence->RawCurveData.AddCurveData(SmartName); FFloatCurve* FloatCurveData = static_cast<FFloatCurve*>(AnimSequence->RawCurveData.GetCurveData(CurveUID)); FloatCurveData->FloatCurve.SetKeys(Keys); } for (FCurveDrivenBoneTransform &CurveDrivenBoneTransform : ImportUI->AnimSequenceImportData->CurveDrivenBoneTransforms) { FRawAnimSequenceTrack RawTrack; RawTrack.PosKeys.Empty(); RawTrack.RotKeys.Empty(); RawTrack.ScaleKeys.Empty(); TArray<int32> CurveIndices; for (const FCurveDrivenTransform &CurveDrivenTransform : CurveDrivenBoneTransform.CurveDrivenTransforms) { CurveIndices.Add(CurveNames.Find(CurveDrivenTransform.Curve)); } const FReferenceSkeleton &ReferenceSkeleton = Skeleton->GetReferenceSkeleton(); const TArray<FTransform> &RawRefBonePose = ReferenceSkeleton.GetRawRefBonePose(); int32 RawBoneIndex = ReferenceSkeleton.FindRawBoneIndex(CurveDrivenBoneTransform.Bone); FTransform RawBonePose = RawBoneIndex != INDEX_NONE ? RawRefBonePose[RawBoneIndex] : FTransform::Identity; for (int32 FrameIndex = 0; FrameIndex < Frames; ++FrameIndex) { FTransform LocalTransform; const TSharedPtr<FJsonValue>& WeightRow = (*WeightMat)[FrameIndex]; const TArray<TSharedPtr<FJsonValue>>& WeightValues = WeightRow->AsArray(); for (int32 CurveDrivenIndex = 0; CurveDrivenIndex < CurveDrivenBoneTransform.CurveDrivenTransforms.Num(); ++CurveDrivenIndex) { int32 CurveIndex = CurveIndices[CurveDrivenIndex]; if(CurveIndex == INDEX_NONE) { continue; } FCurveDrivenTransform &CurveDrivenTransform = CurveDrivenBoneTransform.CurveDrivenTransforms[CurveDrivenIndex]; FTransform::BlendFromIdentityAndAccumulate(LocalTransform, CurveDrivenTransform.Transform, ScalarRegister(WeightValues[CurveIndex]->AsNumber())); } FTransform CombinedTransform = RawBonePose* LocalTransform; RawTrack.ScaleKeys.Add(CombinedTransform.GetScale3D()); RawTrack.PosKeys.Add(CombinedTransform.GetTranslation()); RawTrack.RotKeys.Add(CombinedTransform.GetRotation()); } AnimSequence->AddNewRawTrack(CurveDrivenBoneTransform.Bone, &RawTrack); } AnimSequence->SetRawNumberOfFrame(Frames); AnimSequence->SequenceLength = static_cast<float>(FMath::Max(Frames - 1, 1)) / FPS; AnimSequence->ImportFileFramerate = FPS; AnimSequence->BoneCompressionSettings = ImportUI->BoneCompressionSettings; AnimSequence->CurveCompressionSettings = ImportUI->CurveCompressionSettings; AnimSequence->AdditiveAnimType = ImportUI->AnimSequenceImportData->AdditiveAnimType; return AnimSequence; } void Ua2fFactory::CleanUp() { bShowOption = true; bOperationCanceled = false; Super::CleanUp(); } int32 Ua2fFactory::GetPriority() const { return INT32_MAX; } bool Ua2fFactory::CanReimport(UObject* Obj, TArray<FString>& OutFilenames) { if(const UAnimSequence* AnimSequence = Cast<UAnimSequence>(Obj)) { if(const UAssetImportData* AssetImportData = AnimSequence->AssetImportData) { AssetImportData->ExtractFilenames(OutFilenames); return true; } } return false; } void Ua2fFactory::SetReimportPaths(UObject* Obj, const TArray<FString>& NewReimportPaths) { if (const UAnimSequence* AnimSequence = Cast<UAnimSequence>(Obj)) { if(NewReimportPaths.Num() == 1) { if(UAssetImportData* AssetImportData = AnimSequence->AssetImportData) { AssetImportData->UpdateFilenameOnly(NewReimportPaths[0]); } } } } EReimportResult::Type Ua2fFactory::Reimport(UObject* Obj) { const UAnimSequence* AnimSequence = Cast<UAnimSequence>(Obj); if (AnimSequence == nullptr) { return EReimportResult::Failed; } const FString ResolvedSourceFilePath = AnimSequence->AssetImportData->GetFirstFilename(); if (ResolvedSourceFilePath.IsEmpty()) { return EReimportResult::Failed; } if (IFileManager::Get().FileSize(*ResolvedSourceFilePath) == INDEX_NONE) { return EReimportResult::Failed; } bool bOutCanceled = false; if (ImportObject(AnimSequence->GetClass(), AnimSequence->GetOuter(), *AnimSequence->GetName(), RF_Public | RF_Standalone, ResolvedSourceFilePath, nullptr, bOutCanceled)) { return EReimportResult::Succeeded; } if (bOutCanceled) { return EReimportResult::Cancelled; } return EReimportResult::Failed; }
dantreble/a2f/Source/a2fEditor/Public/a2fEditor.h
// Copyright Spitfire Interactive Pty Ltd. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Modules/ModuleManager.h" class Fa2fEditorModule : public IModuleInterface { public: /** IModuleInterface implementation */ virtual void StartupModule() override; virtual void ShutdownModule() override; };
dantreble/a2f/Source/a2fEditor/Public/a2fAssetImportData.h
// Copyright Spitfire Interactive Pty Ltd. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "EditorFramework/AssetImportData.h" #include "a2fAssetImportData.generated.h" /** * */ USTRUCT(BlueprintType) struct FCurveDrivenTransform { GENERATED_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite) FString Curve; UPROPERTY(EditAnywhere, BlueprintReadWrite) bool StripCurveTrack = true; UPROPERTY(EditAnywhere, BlueprintReadWrite) FTransform Transform; }; USTRUCT(BlueprintType) struct FCurveDrivenBoneTransform { GENERATED_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite) FName Bone; UPROPERTY(EditAnywhere, BlueprintReadWrite) TArray<FCurveDrivenTransform> CurveDrivenTransforms; }; UCLASS(BlueprintType) class A2FEDITOR_API Ua2fAssetImportData : public UAssetImportData { GENERATED_BODY() public: UFUNCTION() void GetCurvesToStrip(TSet<FString>& CurvesToStrip) const; /** Use this option to specify a sample rate for the imported animation*/ UPROPERTY(EditAnywhere, BlueprintReadWrite, meta = (ToolTip = "Animation frames per second", ClampMin = 0, UIMin = 0, ClampMax = 48000, UIMax = 60)) int32 FrameRate = 30; UPROPERTY(EditAnywhere, BlueprintReadWrite) TEnumAsByte<enum EAdditiveAnimationType> AdditiveAnimType = AAT_LocalSpaceBase; UPROPERTY(EditAnywhere,BlueprintReadWrite) TArray<FCurveDrivenBoneTransform> CurveDrivenBoneTransforms; };
dantreble/a2f/Source/a2fEditor/Public/a2fFactory.h
// Copyright Spitfire Interactive Pty Ltd. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Factories/Factory.h" #include "EditorReimportHandler.h" #include "a2fFactory.generated.h" /** * */ UCLASS() class A2FEDITOR_API Ua2fFactory : public UFactory, public FReimportHandler { GENERATED_UCLASS_BODY() public: Ua2fFactory(); virtual void PostInitProperties() override; virtual bool FactoryCanImport(const FString& Filename) override; virtual UObject* FactoryCreateText(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, UObject* Context, const TCHAR* Type, const TCHAR*& Buffer, const TCHAR* BufferEnd, FFeedbackContext* Warn, bool& bOutOperationCanceled) override; virtual void CleanUp() override; // FReimportHandler virtual int32 GetPriority() const override; virtual bool CanReimport(UObject* Obj, TArray<FString>& OutFilenames) override; virtual void SetReimportPaths(UObject* Obj, const TArray<FString>& NewReimportPaths) override; virtual EReimportResult::Type Reimport(UObject* Obj) override; private: UPROPERTY() class Ua2fImportUI* ImportUI; bool bShowOption; /** true if the import operation was canceled. */ bool bOperationCanceled; };
dantreble/a2f/Source/a2fEditor/Public/a2fImportUI.h
// Copyright Spitfire Interactive Pty Ltd. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "a2fImportUI.generated.h" /** * */ UCLASS(BlueprintType, HideCategories = Object, MinimalAPI) class Ua2fImportUI : public UObject { public: Ua2fImportUI(); private: GENERATED_BODY() public: void ResetToDefault(); /** Skeleton to use for imported asset. When importing a mesh, leaving this as "None" will create a new skeleton. When importing an animation this MUST be specified to import the asset. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = ImportSettings, meta = (ImportType = "SkeletalMesh|Animation")) class USkeleton* Skeleton; /** The bone compression settings used to compress bones in this sequence. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = ImportSettings) class UAnimBoneCompressionSettings* BoneCompressionSettings; /** The curve compression settings used to compress curves in this sequence. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = ImportSettings) class UAnimCurveCompressionSettings* CurveCompressionSettings; UPROPERTY(EditAnywhere, BlueprintReadWrite, Transient, Instanced, Category = ImportSettings) class Ua2fAssetImportData* AnimSequenceImportData; bool bIsReimport; };
dantreble/a2f/Source/a2fEditor/Public/a2fOptionWindow.h
// Copyright Spitfire Interactive Pty Ltd. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "InputCoreTypes.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Input/Reply.h" #include "Widgets/SCompoundWidget.h" #include "Widgets/SWindow.h" #include "a2fImportUI.h" class SButton; class A2FEDITOR_API Sa2fOptionWindow : public SCompoundWidget { public: SLATE_BEGIN_ARGS( Sa2fOptionWindow ) : _ImportUI(NULL) , _WidgetWindow() , _FullPath() , _MaxWindowHeight(0.0f) , _MaxWindowWidth(0.0f) {} SLATE_ARGUMENT( Ua2fImportUI*, ImportUI ) SLATE_ARGUMENT( TSharedPtr<SWindow>, WidgetWindow ) SLATE_ARGUMENT( FText, FullPath ) SLATE_ARGUMENT( float, MaxWindowHeight) SLATE_ARGUMENT(float, MaxWindowWidth) SLATE_END_ARGS() public: void Construct(const FArguments& InArgs); virtual bool SupportsKeyboardFocus() const override { return true; } FReply OnImport(); FReply OnImportAll() { bShouldImportAll = true; return OnImport(); } FReply OnCancel(); virtual FReply OnKeyDown( const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent ) override; bool ShouldImport() const; bool ShouldImportAll() const { return bShouldImportAll; } Sa2fOptionWindow() : ImportUI(NULL) , bShouldImport(false) , bShouldImportAll(false) {} private: bool CanImport() const; FReply OnResetToDefaultClick() const; FText GetImportTypeDisplayText() const; Ua2fImportUI* ImportUI; TSharedPtr<class IDetailsView> DetailsView; TWeakPtr< SWindow > WidgetWindow; TSharedPtr< SButton > ImportButton; bool bShouldImport; bool bShouldImportAll; };
Vadim-Karpenko/omniverse-material-manager-extended/CHANGELOG.md
# Change Log All notable changes to this project will be documented in this file. ## [1.1.1] - 2022-12-26 ### Fixed Support of Create 2022.3.1 ## [1.1.1] - 2022-10-04 ### Fixed Convert icon and preview_image to png format ## [1.1.0] - 2022-09-26 ### Added #### Roaming mode (settings tab) Allowing you to automatically select an object just by looking at it. Note that this can cause difficulty when creating new objects with variants, so it's best to only enable this mode when your scene is ready for demonstration. ### Fixed - Fixed possible crash caused by iterating through history of commands. ## [1.0.1] - 2022-08-26 ### Added - Support of a new version of viewport (Next viewport). ## [1.0.0] - 2022-08-18 Initial release.
Vadim-Karpenko/omniverse-material-manager-extended/link_app.sh
#!/bin/bash set -e SCRIPT_DIR=$(dirname ${BASH_SOURCE}) cd "$SCRIPT_DIR" exec "tools/packman/python.sh" tools/scripts/link_app.py $@
Vadim-Karpenko/omniverse-material-manager-extended/link_app.bat
@echo off call "%~dp0tools\packman\python.bat" %~dp0tools\scripts\link_app.py %* if %errorlevel% neq 0 ( goto Error ) :Success exit /b 0 :Error exit /b %errorlevel%
Vadim-Karpenko/omniverse-material-manager-extended/README.md
# Material Manager Extended ![welcome](readme_media/welcome.jpg) ### About This extension will let you quickly toggle between different materials for the static objects in your scene. ## Quick links * [Installation](#installation) * [Restrictions](#restrictions) * [How to use](#how-to-use) * [Linking with an Omniverse app](#linking-with-an-omniverse-app) * [Contributing](#contributing) * [Changelog](CHANGELOG.md) ## Installation To add a this extension to your Omniverse app: ### From Community tab 1. Go to **Extension Manager** (Window - Extensions) — Community tab 2. Search for **Material Manager** extension and enable it ### Manual 1. Go to **Extension Manager** (Window - Extensions) — **Gear Icon** — **Extension Search Path** 2. Add this as a search path: `git://github.com/Vadim-Karpenko/omniverse-material-manager-extended?branch=main&dir=exts` 3. Search for **Material Manager** extension and enable it A new window will appear alongside the Property tab: ![start window](readme_media/start_window.jpg) ## Restrictions - Some vegetation can cause problems, but most should work just fine. - Currently has no support of instanced meshes (they usually greyed out and aren't accessible). - Your object needs to have the following structure: ![Structure example](readme_media/structure_example.svg) Most objects already have this structure, especially from **Nvidia Assets** tab, but in some custom cases, you might need to change your object so it corresponds to the structure from above. Note: Looks folder can be empty, and your original textures located somewhere else, it just tells the extension that this is a separate object. #### Example: ![Structure example 2](readme_media/structure_example2.jpg) - It will not work with the primitives, because it does not corresponds to the structure from above. ## How to use - Navigate to your viewport and select any static object on your scene - Once an object is selected and is valid (see restrictions), the window will be changed into something similar to this: ![step 1](readme_media/step1.jpg) - Click **Add new variant** at the bottom of the window. A new variant called _Look_1_ will appear in the list. You can create as many as you need, and if you need to rename your variant you can do it by renaming appropriate folder in **Looks/MME/your_variant** ![step 2](readme_media/step2.jpg) - You will see a viewport window on top of your model. Change material or replace it completely while your variant is active ![step 3](readme_media/step3.jpg) ![step 4](readme_media/step4.jpg) - Now you can toggle between those variants ![step 5](readme_media/step5.jpg) ![step 6](readme_media/step6.jpg) - More complex Xform's are also supported. This means that the extension will toggle all the materials for every mesh at once under this Xform. ![step 7](readme_media/step7.jpg) ## Linking with an Omniverse app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` There is also an analogous `link_app.sh` for Linux. If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app code ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3" ``` ## Contributing Feel free to create a new issue if you run into any problems. Pull requests are welcomed.
Vadim-Karpenko/omniverse-material-manager-extended/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
Vadim-Karpenko/omniverse-material-manager-extended/tools/packman/python.sh
#!/bin/bash # Copyright 2019-2020 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -e PACKMAN_CMD="$(dirname "${BASH_SOURCE}")/packman" if [ ! -f "$PACKMAN_CMD" ]; then PACKMAN_CMD="${PACKMAN_CMD}.sh" fi source "$PACKMAN_CMD" init export PYTHONPATH="${PM_MODULE_DIR}:${PYTHONPATH}" export PYTHONNOUSERSITE=1 # workaround for our python not shipping with certs if [[ -z ${SSL_CERT_DIR:-} ]]; then export SSL_CERT_DIR=/etc/ssl/certs/ fi "${PM_PYTHON}" -u "$@"
Vadim-Karpenko/omniverse-material-manager-extended/tools/packman/python.bat
:: Copyright 2019-2020 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: http://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. @echo off setlocal call "%~dp0\packman" init set "PYTHONPATH=%PM_MODULE_DIR%;%PYTHONPATH%" set PYTHONNOUSERSITE=1 "%PM_PYTHON%" -u %*
Vadim-Karpenko/omniverse-material-manager-extended/tools/packman/packman.cmd
:: Reset errorlevel status (don't inherit from caller) [xxxxxxxxxxx] @call :ECHO_AND_RESET_ERROR :: You can remove the call below if you do your own manual configuration of the dev machines call "%~dp0\bootstrap\configure.bat" if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Everything below is mandatory if not defined PM_PYTHON goto :PYTHON_ENV_ERROR if not defined PM_MODULE goto :MODULE_ENV_ERROR :: Generate temporary path for variable file for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile ^ -File "%~dp0bootstrap\generate_temp_file_name.ps1"') do set PM_VAR_PATH=%%a if %1.==. ( set PM_VAR_PATH_ARG= ) else ( set PM_VAR_PATH_ARG=--var-path="%PM_VAR_PATH%" ) "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" %* %PM_VAR_PATH_ARG% if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Marshall environment variables into the current environment if they have been generated and remove temporary file if exist "%PM_VAR_PATH%" ( for /F "usebackq tokens=*" %%A in ("%PM_VAR_PATH%") do set "%%A" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) if exist "%PM_VAR_PATH%" ( del /F "%PM_VAR_PATH%" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) set PM_VAR_PATH= goto :eof :: Subroutines below :PYTHON_ENV_ERROR @echo User environment variable PM_PYTHON is not set! Please configure machine for packman or call configure.bat. exit /b 1 :MODULE_ENV_ERROR @echo User environment variable PM_MODULE is not set! Please configure machine for packman or call configure.bat. exit /b 1 :VAR_ERROR @echo Error while processing and setting environment variables! exit /b 1 :ECHO_AND_RESET_ERROR @echo off if /I "%PM_VERBOSITY%"=="debug" ( @echo on ) exit /b 0
Vadim-Karpenko/omniverse-material-manager-extended/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
Vadim-Karpenko/omniverse-material-manager-extended/tools/packman/bootstrap/generate_temp_file_name.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> $out = [System.IO.Path]::GetTempFileName() Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAK+Ewup1N0/mdf # 1l4R58rxyumHgZvTmEhrYTb2Zf0zd6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh # PJcf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Hw6UVDANBgkqhkiG # 9w0BAQEFAASCAQCdefEKh6Qmwx7xGCkrYi/A+/Cla6LdnYJp38eMs3fqTTvjhyDw # HffXrwdqWy5/fgW3o3qJXqa5o7hLxYIoWSULOCpJRGdt+w7XKPAbZqHrN9elAhWJ # vpBTCEaj7dVxr1Ka4NsoPSYe0eidDBmmvGvp02J4Z1j8+ImQPKN6Hv/L8Ixaxe7V # mH4VtXIiBK8xXdi4wzO+A+qLtHEJXz3Gw8Bp3BNtlDGIUkIhVTM3Q1xcSEqhOLqo # PGdwCw9acxdXNWWPjOJkNH656Bvmkml+0p6MTGIeG4JCeRh1Wpqm1ZGSoEcXNaof # wOgj48YzI+dNqBD9i7RSWCqJr2ygYKRTxnuU # SIG # End signature block
Vadim-Karpenko/omniverse-material-manager-extended/tools/packman/bootstrap/configure.bat
:: Copyright 2019 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: http://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. set PM_PACKMAN_VERSION=6.33.2 :: Specify where packman command is rooted set PM_INSTALL_PATH=%~dp0.. :: The external root may already be configured and we should do minimal work in that case if defined PM_PACKAGES_ROOT goto ENSURE_DIR :: If the folder isn't set we assume that the best place for it is on the drive that we are currently :: running from set PM_DRIVE=%CD:~0,2% set PM_PACKAGES_ROOT=%PM_DRIVE%\packman-repo :: We use *setx* here so that the variable is persisted in the user environment echo Setting user environment variable PM_PACKAGES_ROOT to %PM_PACKAGES_ROOT% setx PM_PACKAGES_ROOT %PM_PACKAGES_ROOT% if %errorlevel% neq 0 ( goto ERROR ) :: The above doesn't work properly from a build step in VisualStudio because a separate process is :: spawned for it so it will be lost for subsequent compilation steps - VisualStudio must :: be launched from a new process. We catch this odd-ball case here: if defined PM_DISABLE_VS_WARNING goto ENSURE_DIR if not defined VSLANG goto ENSURE_DIR echo The above is a once-per-computer operation. Unfortunately VisualStudio cannot pick up environment change echo unless *VisualStudio is RELAUNCHED*. echo If you are launching VisualStudio from command line or command line utility make sure echo you have a fresh launch environment (relaunch the command line or utility). echo If you are using 'linkPath' and referring to packages via local folder links you can safely ignore this warning. echo You can disable this warning by setting the environment variable PM_DISABLE_VS_WARNING. echo. :: Check for the directory that we need. Note that mkdir will create any directories :: that may be needed in the path :ENSURE_DIR if not exist "%PM_PACKAGES_ROOT%" ( echo Creating directory %PM_PACKAGES_ROOT% mkdir "%PM_PACKAGES_ROOT%" ) if %errorlevel% neq 0 ( goto ERROR_MKDIR_PACKAGES_ROOT ) :: The Python interpreter may already be externally configured if defined PM_PYTHON_EXT ( set PM_PYTHON=%PM_PYTHON_EXT% goto PACKMAN ) set PM_PYTHON_VERSION=3.7.9-windows-x86_64 set PM_PYTHON_BASE_DIR=%PM_PACKAGES_ROOT%\python set PM_PYTHON_DIR=%PM_PYTHON_BASE_DIR%\%PM_PYTHON_VERSION% set PM_PYTHON=%PM_PYTHON_DIR%\python.exe if exist "%PM_PYTHON%" goto PACKMAN if not exist "%PM_PYTHON_BASE_DIR%" call :CREATE_PYTHON_BASE_DIR set PM_PYTHON_PACKAGE=python@%PM_PYTHON_VERSION%.cab for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME%.zip call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_PYTHON_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching python from CDN !!! goto ERROR ) for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_folder.ps1" -parentPath "%PM_PYTHON_BASE_DIR%"') do set TEMP_FOLDER_NAME=%%a echo Unpacking Python interpreter ... "%SystemRoot%\system32\expand.exe" -F:* "%TARGET%" "%TEMP_FOLDER_NAME%" 1> nul del "%TARGET%" :: Failure during extraction to temp folder name, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error unpacking python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :: If python has now been installed by a concurrent process we need to clean up and then continue if exist "%PM_PYTHON%" ( call :CLEAN_UP_TEMP_FOLDER goto PACKMAN ) else ( if exist "%PM_PYTHON_DIR%" ( rd /s /q "%PM_PYTHON_DIR%" > nul ) ) :: Perform atomic rename rename "%TEMP_FOLDER_NAME%" "%PM_PYTHON_VERSION%" 1> nul :: Failure during move, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error renaming python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :PACKMAN :: The packman module may already be externally configured if defined PM_MODULE_DIR_EXT ( set PM_MODULE_DIR=%PM_MODULE_DIR_EXT% ) else ( set PM_MODULE_DIR=%PM_PACKAGES_ROOT%\packman-common\%PM_PACKMAN_VERSION% ) set PM_MODULE=%PM_MODULE_DIR%\packman.py if exist "%PM_MODULE%" goto ENSURE_7ZA set PM_MODULE_PACKAGE=packman-common@%PM_PACKMAN_VERSION%.zip for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME% call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_MODULE_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching packman from CDN !!! goto ERROR ) echo Unpacking ... "%PM_PYTHON%" -S -s -u -E "%~dp0\install_package.py" "%TARGET%" "%PM_MODULE_DIR%" if %errorlevel% neq 0 ( echo !!! Error unpacking packman !!! goto ERROR ) del "%TARGET%" :ENSURE_7ZA set PM_7Za_VERSION=16.02.4 set PM_7Za_PATH=%PM_PACKAGES_ROOT%\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END set PM_7Za_PATH=%PM_PACKAGES_ROOT%\chk\7za\%PM_7ZA_VERSION% if exist "%PM_7Za_PATH%" goto END "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" pull "%PM_MODULE_DIR%\deps.packman.xml" if %errorlevel% neq 0 ( echo !!! Error fetching packman dependencies !!! goto ERROR ) goto END :ERROR_MKDIR_PACKAGES_ROOT echo Failed to automatically create packman packages repo at %PM_PACKAGES_ROOT%. echo Please set a location explicitly that packman has permission to write to, by issuing: echo. echo setx PM_PACKAGES_ROOT {path-you-choose-for-storing-packman-packages-locally} echo. echo Then launch a new command console for the changes to take effect and run packman command again. exit /B %errorlevel% :ERROR echo !!! Failure while configuring local machine :( !!! exit /B %errorlevel% :CLEAN_UP_TEMP_FOLDER rd /S /Q "%TEMP_FOLDER_NAME%" exit /B :CREATE_PYTHON_BASE_DIR :: We ignore errors and clean error state - if two processes create the directory one will fail which is fine md "%PM_PYTHON_BASE_DIR%" > nul 2>&1 exit /B 0 :END
Vadim-Karpenko/omniverse-material-manager-extended/tools/packman/bootstrap/fetch_file_from_packman_bootstrap.cmd
:: Copyright 2019 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: http://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. :: You need to specify <package-name> <target-path> as input to this command @setlocal @set PACKAGE_NAME=%1 @set TARGET_PATH=%2 @echo Fetching %PACKAGE_NAME% ... @powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0download_file_from_url.ps1" ^ -source "http://bootstrap.packman.nvidia.com/%PACKAGE_NAME%" -output %TARGET_PATH% :: A bug in powershell prevents the errorlevel code from being set when using the -File execution option :: We must therefore do our own failure analysis, basically make sure the file exists and is larger than 0 bytes: @if not exist %TARGET_PATH% goto ERROR_DOWNLOAD_FAILED @if %~z2==0 goto ERROR_DOWNLOAD_FAILED @endlocal @exit /b 0 :ERROR_DOWNLOAD_FAILED @echo Failed to download file from S3 @echo Most likely because endpoint cannot be reached or file %PACKAGE_NAME% doesn't exist @endlocal @exit /b 1
Vadim-Karpenko/omniverse-material-manager-extended/tools/packman/bootstrap/download_file_from_url.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> param( [Parameter(Mandatory=$true)][string]$source=$null, [string]$output="out.exe" ) $filename = $output $triesLeft = 3 do { $triesLeft -= 1 try { Write-Host "Downloading from bootstrap.packman.nvidia.com ..." $wc = New-Object net.webclient $wc.Downloadfile($source, $fileName) $triesLeft = 0 } catch { Write-Host "Error downloading $source!" Write-Host $_.Exception|format-list -force } } while ($triesLeft -gt 0)
Vadim-Karpenko/omniverse-material-manager-extended/tools/packman/bootstrap/generate_temp_folder.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> param( [Parameter(Mandatory=$true)][string]$parentPath=$null ) [string] $name = [System.Guid]::NewGuid() $out = Join-Path $parentPath $name New-Item -ItemType Directory -Path ($out) | Out-Null Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgB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ZgwGgYJKoZIhvcNAQkDMQ0G # CyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG # SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3 # DQEJBDEiBCDvFxQ6lYLr8vB+9czUl19rjCw1pWhhUXw/SqOmvIa/VDANBgkqhkiG # 9w0BAQEFAASCAQB9ox2UrcUXQsBI4Uycnhl4AMpvhVXJME62tygFMppW1l7QftDy # LvfPKRYm2YUioak/APxAS6geRKpeMkLvXuQS/Jlv0kY3BjxkeG0eVjvyjF4SvXbZ # 3JCk9m7wLNE+xqOo0ICjYlIJJgRLudjWkC5Skpb1NpPS8DOaIYwRV+AWaSOUPd9P # O5yVcnbl7OpK3EAEtwDrybCVBMPn2MGhAXybIHnth3+MFp1b6Blhz3WlReQyarjq # 1f+zaFB79rg6JswXoOTJhwICBP3hO2Ua3dMAswbfl+QNXF+igKLJPYnaeSVhBbm6 # VCu2io27t4ixqvoD0RuPObNX/P3oVA38afiM # SIG # End signature block
Vadim-Karpenko/omniverse-material-manager-extended/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
Vadim-Karpenko/omniverse-material-manager-extended/exts/karpenko.materialsmanager.ext/karpenko/materialsmanager/ext/prim_serializer.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["update_property_paths", "get_prim_as_text", "text_to_stage"] from omni.kit.commands import execute from pxr import Sdf from pxr import Tf from pxr import Usd from typing import List from typing import Optional def _to_layer(text: str) -> Optional[Sdf.Layer]: """Create an sdf layer from the given text""" if not text.startswith("#usda 1.0\n"): text = "#usda 1.0\n" + text anonymous_layer = Sdf.Layer.CreateAnonymous("clipboard.usda") try: if not anonymous_layer.ImportFromString(text): return except Tf.ErrorException: return return anonymous_layer def update_property_paths(prim_spec, old_path, new_path): if not prim_spec: return for rel in prim_spec.relationships: rel.targetPathList.explicitItems = [path.ReplacePrefix(old_path, new_path) for path in rel.targetPathList.explicitItems] for attr in prim_spec.attributes: attr.connectionPathList.explicitItems = [path.ReplacePrefix(old_path, new_path) for path in attr.connectionPathList.explicitItems] for child in prim_spec.nameChildren: update_property_paths(child, old_path, new_path) def get_prim_as_text(stage: Usd.Stage, prim_paths: List[Sdf.Path]) -> Optional[str]: """Generate a text from the stage and prim path""" if not prim_paths: return # TODO: It can be slow in large scenes. Ideally we need to flatten specific prims. flatten_layer = stage.Flatten() anonymous_layer = Sdf.Layer.CreateAnonymous(prim_paths[0].name + ".usda") paths_map = {} for i in range(0, len(prim_paths)): item_name = str.format("Item_{:02d}", i) Sdf.PrimSpec(anonymous_layer, item_name, Sdf.SpecifierDef) prim_path = prim_paths[i] anonymous_path = Sdf.Path.absoluteRootPath.AppendChild(item_name).AppendChild(prim_path.name) # Copy Sdf.CopySpec(flatten_layer, prim_path, anonymous_layer, anonymous_path) paths_map[prim_path] = anonymous_path for prim in anonymous_layer.rootPrims: for source_path, target_path in paths_map.items(): update_property_paths(prim, source_path, target_path) return anonymous_layer.ExportToString() def text_to_stage(stage: Usd.Stage, text: str, root: Sdf.Path = Sdf.Path.absoluteRootPath) -> bool: """ Convert the given text to the prim and place it to the stage under the given root. """ source_layer = _to_layer(text) if not source_layer: return False execute("ImportLayer", layer=source_layer, stage=stage, root=root) return True
Vadim-Karpenko/omniverse-material-manager-extended/exts/karpenko.materialsmanager.ext/karpenko/materialsmanager/ext/style.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["materialsmanager_window_style"] import omni.kit.app import omni.ui as ui import pathlib from omni.ui import color as cl EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) # The main style dict materialsmanager_window_style = { "Image::material_preview": { "image_url": f"{EXTENSION_FOLDER_PATH}/data/icons/material@3x.png", }, "Label::main_label": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl("#a1a1a1"), "font_size": 24, }, "Label::main_hint": { "alignment": ui.Alignment.CENTER, "margin_height": 1, "margin_width": 10, "font_size": 16, }, "Label::main_hint_small": { "alignment": ui.Alignment.CENTER, "color": cl("#a1a1a1"), }, "Label::material_name": { "alignment": ui.Alignment.LEFT_CENTER, "font_size": 14, }, "Label::secondary_label": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl("#a1a1a1"), "font_size": 18, }, "Label::material_counter": { "alignment": ui.Alignment.CENTER, "margin_height": 1, "margin_width": 10, "font_size": 14, }, } # The style dict for the viewport widget ui viewport_widget_style = { "Button.Label": { "font_size": 30, }, "Button.Label:disabled": { "color": cl("#a1a1a1") }, "Button:disabled": { "background_color": cl("#4d4d4d"), }, "Button": { "alignment": ui.Alignment.BOTTOM, "background_color": cl("#666666"), }, "Label::name_label": { "alignment": ui.Alignment.CENTER_BOTTOM, "font_size": 34, } }
Vadim-Karpenko/omniverse-material-manager-extended/exts/karpenko.materialsmanager.ext/karpenko/materialsmanager/ext/extension.py
import asyncio import base64 import json import math import carb import omni.ext import omni.kit.commands import omni.ui as ui import omni.usd from omni.kit.viewport.utility import (get_active_viewport_camera_path, get_active_viewport_window, get_ui_position_for_prim) from pxr import Sdf from .prim_serializer import get_prim_as_text, text_to_stage from .style import materialsmanager_window_style as _style from .viewport_ui.widget_info_scene import WidgetInfoScene class MaterialManagerExtended(omni.ext.IExt): WINDOW_NAME = "Material Manager Extended" SCENE_SETTINGS_WINDOW_NAME = "Material Manager Settings" MENU_PATH = "Window/" + WINDOW_NAME def on_startup(self, ext_id): print("[karpenko.materialsmanager.ext] MaterialManagerExtended startup") self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self.latest_selected_prim = None self.variants_frame_original = None self.variants_frame = None self.active_objects_frame = None self._window = None self._window_scenemanager = None self.materials_frame = None self.main_frame = None self.ignore_change = False self.ignore_settings_update = False self.roaming_timer = None self.ext_id = ext_id self._widget_info_viewport = None self.current_ui = "default" self.is_settings_open = False self.ignore_next_select = False self.last_roaming_prim = None self.reticle = None self.stage = self._usd_context.get_stage() self.allowed_commands = [ "SelectPrimsCommand", "SelectPrims", "CreatePrimCommand", "DeletePrims", "TransformPrimCommand", "Undo", "BindMaterial", "BindMaterialCommand", "MovePrims", "MovePrim", ] self.is_settings_window_open = False self.render_default_layout() # show the window in the usual way if the stage is loaded if self.stage: self._window.deferred_dock_in("Property") else: # otherwise, show the window after the stage is loaded self._setup_window_task = asyncio.ensure_future(self._dock_window()) omni.kit.commands.subscribe_on_change(self.on_change) self.roaming_timer = asyncio.ensure_future(self.enable_roaming_timer()) def on_shutdown(self): """ This function is called when the addon is disabled """ omni.kit.commands.unsubscribe_on_change(self.on_change) if self.roaming_timer: self.disable_roaming_timer() # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(self.WINDOW_NAME, None) if self._window: self._window.destroy() self._window = None self._selection = None self._usd_context = None self.latest_selected_prim = None self.variants_frame_original = None self.variants_frame = None self.materials_frame = None self.main_frame = None if self._widget_info_viewport: self._widget_info_viewport.destroy() self._widget_info_viewport = None if self.reticle: self.reticle.destroy() self.reticle = None print("[karpenko.materialsmanager.ext] MaterialManagerExtended shutdown") async def _dock_window(self): """ It waits for the property window to appear, then docks the window to it """ property_win = None frames = 3 while frames > 0: if not property_win: property_win = ui.Workspace.get_window("Property") if property_win: break # early out frames = frames - 1 await omni.kit.app.get_app().next_update_async() # Dock to property window after 5 frames. It's enough for window to appear. for _ in range(5): await omni.kit.app.get_app().next_update_async() if property_win: self._window.deferred_dock_in("Property") self._setup_window_task = None async def enable_roaming_timer(self): while True: await asyncio.sleep(1.0) self.get_closest_mme_object() def disable_roaming_timer(self): self.roaming_timer = None def get_latest_version(self, looks): """ It takes a list of looks, and returns the next available version number :param looks: The parent folder of the looks :return: The latest version of the look. """ latest_version = 1 versions = [] for look in looks.GetChildren(): look_path = look.GetPath() if look_path.name.startswith("Look_"): version = int(look_path.name.split("_")[-1]) versions.append(version) versions.sort() for version in versions: if version != latest_version: return latest_version else: latest_version += 1 return latest_version def add_variant(self, looks, parent_prim): """ It creates a new folder under the Looks folder, copies all materials attached to the meshes and re-binds them so the user can tweak copies instead of the original ones. :param looks: The looks folder :param parent_prim: The prim that contains the meshes that need to be assigned the new materials """ looks = parent_prim.GetPrimAtPath("Looks") looks_path = looks.GetPath() self.ignore_change = True # group all commands so it can be undone at once with omni.kit.undo.group(): all_meshes = self.get_meshes_from_prim(parent_prim) all_materials = self.get_data_from_meshes(all_meshes) # Check if folder (prim, Scope) MME already exist if not looks.GetPrimAtPath("MME"): # Create a folder called MME under the looks folder, it will contain all the materials for all variants omni.kit.commands.execute( "CreatePrim", prim_path=f"{looks_path}/MME", prim_type="Scope", attributes={}, select_new_prim=False ) is_active_attr_path = Sdf.Path(f"{looks_path}/MME.MMEisActive") omni.kit.commands.execute( 'CreateUsdAttributeOnPath', attr_path=is_active_attr_path, attr_type=Sdf.ValueTypeNames.Bool, custom=True, attr_value=False, variability=Sdf.VariabilityVarying ) self.set_mesh_data(all_materials, looks_path, None) # Generate a new name for the variant based on the quantity of previous ones folder_name = f"Look_{self.get_latest_version(looks.GetPrimAtPath('MME'))}" # Create a folder for the new variant omni.kit.commands.execute( "CreatePrim", prim_path=f"{looks_path}/MME/{folder_name}", prim_type="Scope", attributes={}, select_new_prim=False ) is_active_attr_path = Sdf.Path(f"{looks_path}/MME/{folder_name}.MMEisActive") omni.kit.commands.execute( 'CreateUsdAttributeOnPath', attr_path=is_active_attr_path, attr_type=Sdf.ValueTypeNames.Bool, custom=True, variability=Sdf.VariabilityVarying ) if folder_name is None: new_looks_folder = looks else: new_looks_folder = looks.GetPrimAtPath(f"MME/{folder_name}") new_looks_folder_path = new_looks_folder.GetPath() materials_to_copy = [mat_data["path"] for mat_data in all_materials] # remove duplicates materials_to_copy = list(set(materials_to_copy)) # Copy material's prim as text usd_code = get_prim_as_text(self.stage, materials_to_copy) # put the clone material into the scene text_to_stage(self.stage, usd_code, new_looks_folder_path) self.bind_materials(all_materials, new_looks_folder_path) self.set_mesh_data(all_materials, looks_path, folder_name) self.deactivate_all_variants(looks) # Set current variant as active omni.kit.commands.execute( 'ChangeProperty', prop_path=is_active_attr_path, value=True, prev=False, ) self.ignore_change = False if not self.ignore_settings_update: self.render_active_objects_frame() self.render_variants_frame(looks, parent_prim) def get_meshes_from_prim(self, parent_prim): """ It takes a parent prim and returns a list of all the meshes that are children of that prim :param parent_prim: The parent prim of the mesh you want to get :return: A list of all meshes in the scene. """ all_meshes = [] for mesh in self.get_all_children_of_prim(parent_prim): if mesh.GetTypeName() == "Mesh": all_meshes.append(mesh) return all_meshes def get_data_from_meshes(self, all_meshes): """ It loops through all passed meshes, gets the materials that are bound to them, and returns a list of dictionaries containing the material name, path, and the mesh it's bound to :param all_meshes: a list of all the meshes in the scene :return: A list of dictionaries. """ result = [] # loop through all meshes for mesh_data in all_meshes: # Get currently binded materials for the current mesh current_material_prims = mesh_data.GetRelationship('material:binding').GetTargets() # Loop through all binded materials paths for original_material_prim_path in current_material_prims: original_material_prim = self.stage.GetPrimAtPath(original_material_prim_path) if not original_material_prim: continue result.append({ "name": original_material_prim.GetName(), "path": original_material_prim_path, "mesh": mesh_data.GetPath(), }) return result def bind_materials(self, all_materials, variant_folder_path): """ Look through all the materials and bind them to the meshes. If variant_folder_path is empty, then just binds passed materials. If not, looks for the materials in the variant folder and binds them instead using all_materials as a reference. :param all_materials: A list of dictionaries containing the material path and the mesh path :param variant_folder_path: The path to the variant folder """ # Check if there is a variant folder where new materials are stored if variant_folder_path: variant_materials_prim = self.stage.GetPrimAtPath(variant_folder_path) with omni.kit.undo.group(): # loop through all passed materials for mat_data in all_materials: if variant_folder_path and variant_materials_prim: # loop throug all materials in the variant folder for var_mat in variant_materials_prim.GetChildren(): # If found material matches with the one in the all_materials list, bind it to the mesh if var_mat.GetName() == str(mat_data["path"]).split("/")[-1]: omni.kit.commands.execute( "BindMaterialCommand", prim_path=mat_data["mesh"], material_path=var_mat.GetPath(), strength=['weakerThanDescendants'] ) break else: if mat_data["mesh"] and mat_data["path"]: # If there's no variant folder, then just bind passed material to the mesh omni.kit.commands.execute( 'BindMaterialCommand', material_path=mat_data["path"], prim_path=mat_data["mesh"], strength=['weakerThanDescendants'] ) def deactivate_all_variants(self, looks): """ It deactivates all variants in a given looks prim :param looks: The looks prim """ looks_path = looks.GetPath() mme_folder = looks.GetPrimAtPath("MME") # Check if mme folder exists if mme_folder: # MMEisActive also present in MME folder, so we need to set it to False as well. mme_folder_prop_path = Sdf.Path(f"{looks_path}/MME.MMEisActive") mme_is_active = self.stage.GetAttributeAtPath(mme_folder_prop_path).Get() if mme_is_active: omni.kit.commands.execute( 'ChangeProperty', prop_path=mme_folder_prop_path, value=False, prev=True, ) # Loop through all variants in the MME folder and deactivate them for look in mme_folder.GetChildren(): p_type = look.GetTypeName() if p_type == "Scope": look_is_active_path = Sdf.Path(f"{looks_path}/MME/{look.GetName()}.MMEisActive") look_is_active = self.stage.GetAttributeAtPath(look_is_active_path).Get() if look_is_active: omni.kit.commands.execute( 'ChangeProperty', prop_path=look_is_active_path, value=False, prev=True, ) def get_parent_from_mesh(self, mesh_prim): """ It takes a mesh prim as an argument and returns the first Xform prim it finds in the prim's ancestry :param mesh_prim: The mesh prim you want to get the parent of :return: The parent of the mesh_prim. """ parent_prim = mesh_prim.GetParent() default_prim = self.stage.GetDefaultPrim() if not default_prim: return default_prim_name = default_prim.GetName() rootname = f"/{default_prim_name}" while True: if parent_prim is None or parent_prim.IsPseudoRoot(): return parent_prim if str(parent_prim.GetPath()) == "/" or str(parent_prim.GetPath()) == rootname: return None if parent_prim.GetPrimAtPath("Looks") and str(parent_prim.GetPath()) != rootname: return parent_prim parent_prim = parent_prim.GetParent() return parent_prim def get_looks_folder(self, parent_prim): """ If the parent_prim has a child prim named "Looks", return that found prim. Otherwise, return None :param parent_prim: The parent prim of the looks folder :return: The looks folder if it exists, otherwise None. """ if not parent_prim: return None looks_folder = parent_prim.GetPrimAtPath("Looks") return looks_folder if looks_folder else None def check_if_original_active(self, mme_folder): """ If the folder has an attribute called "MMEisActive" and it's value is True, return the folder and True. Otherwise, return the folder and False :param mme_folder: The folder that contains the MME data :return: the mme_folder and a boolean value. """ if mme_folder: mme_is_active_attr = mme_folder.GetAttribute("MMEisActive") if mme_is_active_attr and mme_is_active_attr.Get(): return mme_folder, True return mme_folder, False def get_currently_active_folder(self, looks): """ It looks for a folder called "MME" in the "Looks" folder, and if it finds it, it search for a folder inside with an attribute MMEisActive set to True and returns it if it finds one. If it doesn't find one, it returns None. :param looks: The looks node :return: The currently active folder. """ mme_folder = looks.GetPrimAtPath("MME") if mme_folder: if mme_folder.GetTypeName() == "Scope": for look in mme_folder.GetChildren(): if look.GetTypeName() == "Scope": is_active_attr = look.GetAttribute("MMEisActive") if is_active_attr and is_active_attr.Get(): return look return None def update_material_data(self, latest_action): """ It updates the material data in the looks folder when a material is changed using data from the latest action. All data is converted into string and encrypted into base64 to prevent it from being seen or modified by the user. :param latest_action: The latest action that was performed in the scene :return: The return value is a list of dictionaries. """ if "prim_path" not in latest_action.kwargs or "material_path" not in latest_action.kwargs: return prim_path = latest_action.kwargs["prim_path"] if not prim_path: return if type(prim_path) == list: prim_path = prim_path[0] new_material_path = latest_action.kwargs["material_path"] if not new_material_path: return if type(new_material_path) == list: new_material_path = new_material_path[0] parent_mesh = self.get_parent_from_mesh(self.stage.GetPrimAtPath(prim_path)) looks = self.get_looks_folder(parent_mesh) if looks: looks_path = looks.GetPath() mme_folder, is_original_active = self.check_if_original_active(looks.GetPrimAtPath("MME")) if is_original_active: folder_name = None else: active_folder = self.get_currently_active_folder(looks) if not active_folder: return folder_name = active_folder.GetName() mesh_data = self.get_mesh_data(looks_path, folder_name) mesh_data_to_update = [] previous_mats = [] unique_mats = [] mesh_mats = {} if mesh_data: for mat_data in mesh_data: material_prim = self.stage.GetPrimAtPath(new_material_path) mat_name = material_prim.GetName() if mat_data["mesh"] == prim_path and mat_data["path"] != new_material_path: carb.log_warn("Material changes detected. Updating material data...") if mat_data["path"] in previous_mats: unique_mats.append(mat_data["path"]) mesh_mats[mat_name] = True else: mesh_mats[mat_name] = False previous_mats.append(mat_data["path"]) mat_data["path"] = new_material_path mesh_data_to_update.append(mat_data) else: mesh_mats[mat_name] = False if not is_original_active and folder_name: active_folder_path = active_folder.GetPath() # Copy material's prim as text usd_code = get_prim_as_text( self.stage, [Sdf.Path(i["path"]) for i in mesh_data if i["path"] not in unique_mats] ) mats_to_delete = [i.GetPath() for i in active_folder.GetChildren() if str(i.GetPath()) not in unique_mats and not mesh_mats.get(i.GetName(), False)] if mats_to_delete: omni.kit.commands.execute( 'DeletePrims', paths=mats_to_delete, ) # put the clone material into the scene text_to_stage(self.stage, usd_code, active_folder_path) self.ignore_change = True self.bind_materials(mesh_data_to_update, active_folder_path) self.ignore_change = False self.set_mesh_data(mesh_data, looks_path, folder_name) self.render_current_materials_frame(parent_mesh) def on_change(self): """ Everytime the user changes the scene, this method is called. Method does the following: It checks if the user has changed the material, and if so, it updates the material data in the apropriate variant folder or save it into the MME folder if the variant is set to \"original\". It checks if the selected object has a material, and if it does, it renders a new window with the material's properties of the selected object. If the selected object doesn't have a material, it renders a new window with a prompt to select an object with a material. :return: None """ if not self.stage: self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self.stage = self._usd_context.get_stage() # Get history of commands current_history = reversed(omni.kit.undo.get_history().values()) # Get the latest one try: latest_action = next(current_history) except StopIteration: return if latest_action.name == "ChangePrimVarCommand" and latest_action.level == 1: latest_action = next(current_history) if self.ignore_next_select and latest_action.name == "SelectPrimsCommand": self.ignore_next_select = False omni.kit.commands.execute('Undo') else: self.ignore_next_select = False if latest_action.name not in self.allowed_commands: return # To skip the changes made by the addon if self.ignore_change: return show_default_layout = True if latest_action.name in ["BindMaterial", "BindMaterialCommand"]: self.update_material_data(latest_action) return # Get the top-level prim (World) default_prim = self.stage.GetDefaultPrim() if not default_prim: return default_prim_name = default_prim.GetName() rootname = f"/{default_prim_name}" # Get currently selected prim paths = self._selection.get_selected_prim_paths() if paths: # Get path of the first selected prim base_path = paths[0] if len(paths) > 0 else None base_path = Sdf.Path(base_path) if base_path else None if base_path: # Skip if the prim is the root of the stage to avoid unwanted errors if base_path == rootname: return # Skip if this object was already selected previously. Protection from infinite loop. if base_path == self.latest_selected_prim: return # Save the path of the currently selected prim for the next iteration self.latest_selected_prim = base_path # Get prim from path prim = self.stage.GetPrimAtPath(base_path) if prim: p_type = prim.GetTypeName() # This is needed to successfully get the prim even if it's child was selected if p_type == "Mesh" or p_type == "Scope" or p_type == "Material": prim = self.get_parent_from_mesh(prim) elif p_type == "Xform": # Current prim is already parental one, so we don't need to do anything. pass else: # In case if something unexpected is selected, we just return None carb.log_warn(f"Selected {prim} does not has any materials or has invalid type.") return if not prim: self.render_scenelevel_frame() return if prim.GetPrimAtPath("Looks") and prim != self.latest_selected_prim: # Save the type of the rendered window self.current_ui = "object" # Render new window for the selected prim self.render_objectlevel_frame(prim) if not self.ignore_settings_update: self.render_active_objects_frame() show_default_layout = False if show_default_layout and self.current_ui != "default": self.current_ui = "default" self.render_scenelevel_frame() if not self.ignore_settings_update: self.render_active_objects_frame() self.latest_selected_prim = None def _get_looks(self, path): """ It gets the prim at the path, checks if it's a mesh, scope, or material, and if it is, it gets the parent prim. If it's an xform, it does nothing. If it's something else, it returns None :param path: The path to the prim you want to get the looks from :return: The prim and the looks. """ prim = self.stage.GetPrimAtPath(path) p_type = prim.GetTypeName() # User could select not the prim directly but sub-items of it, so we need to make sure in any scenario # we will get the parent prim. if p_type == "Mesh" or p_type == "Scope" or p_type == "Material": prim = self.get_parent_from_mesh(prim) elif p_type == "Xform": # Current prim is already parental one, so we don't need to do anything. pass else: # In case if something unexpected is selected, we just return None carb.log_error("No selected prim") return None, None # Get all looks (a.k.a. materials) looks = prim.GetPrimAtPath("Looks").GetChildren() # return a parental prim object and its looks return prim, looks def get_all_materials_variants(self, looks_prim): """ It returns a list of all the variants in the MME folder :param looks_prim: The prim that contains the MME folder :return: A list of all the variants in the MME folder. """ variants = [] mme_folder = looks_prim.GetPrimAtPath("MME") if mme_folder: for child in mme_folder.GetChildren(): if child.GetTypeName() == "Scope": variants.append(child) return variants def get_mesh_data(self, looks_path, folder_name): """ It gets the mesh data from the folder you pass as a parameter. It does decode it back from base64 and returns it as a dictionary. :param looks_path: The path to the looks prim :param folder_name: The name of the folder that contains the mesh data :return: A list of dictionaries. """ if folder_name: data_attr_path = Sdf.Path(f"{looks_path}/MME/{folder_name}.MMEMeshData") else: data_attr_path = Sdf.Path(f"{looks_path}/MME.MMEMeshData") data_attr = self.stage.GetAttributeAtPath(data_attr_path) if data_attr: attr_value = data_attr.Get() if attr_value: result = [] # decode base64 string and load json for item in attr_value: result.append(json.loads(base64.b64decode(item).decode("utf-8"))) return result def set_mesh_data(self, mesh_materials, looks_path, folder_name): """ It creates a custom attribute on a USD prim, and sets the value of that attribute to a list of base64 encoded JSON strings :param mesh_materials: A list of dictionaries containing the following keys: path, mesh :param looks_path: The path to the looks prim :param folder_name: The name of the folder that contains the mesh data """ # Convert every Path to string in mesh_materials to be able to pass it into JSON all_materials = [{ "path": str(mat_data["path"]), "mesh": str(mat_data["mesh"]), } for mat_data in mesh_materials] if folder_name: data_attr_path = Sdf.Path(f"{looks_path}/MME/{folder_name}.MMEMeshData") else: data_attr_path = Sdf.Path(f"{looks_path}/MME.MMEMeshData") omni.kit.commands.execute( 'CreateUsdAttributeOnPath', attr_path=data_attr_path, attr_type=Sdf.ValueTypeNames.StringArray, custom=True, variability=Sdf.VariabilityVarying, attr_value=[base64.b64encode(json.dumps(i).encode()) for i in all_materials], ) def delete_variant(self, prim_path, looks, parent_prim): """ It deletes the variant prim and then re-renders the variants frame :param prim_path: The path to the variant prim you want to delete :param looks: a list of all the looks in the current scene :param parent_prim: The prim path of the parent prim of the variant set """ omni.kit.commands.execute('DeletePrims', paths=[prim_path, ]) self.render_variants_frame(looks, parent_prim) def enable_variant(self, folder_name, looks, parent_prim, ignore_changes=True, ignore_select=False): """ It takes a folder name, a looks prim, and a parent prim, and then it activates the variant in the folder, binds the materials in the variant, and renders the variant and current materials frames :param folder_name: The name of the folder that contains the materials you want to enable :param looks: the looks prim :param parent_prim: The prim that contains the variant sets """ if ignore_changes: self.ignore_change = True if folder_name is None: new_looks_folder = looks.GetPrimAtPath("MME") else: new_looks_folder = looks.GetPrimAtPath(f"MME/{folder_name}") new_looks_folder_path = new_looks_folder.GetPath() all_materials = self.get_mesh_data(looks.GetPath(), folder_name) self.deactivate_all_variants(looks) is_active_attr_path = Sdf.Path(f"{new_looks_folder_path}.MMEisActive") omni.kit.commands.execute( 'ChangeProperty', prop_path=is_active_attr_path, value=True, prev=False, ) self.bind_materials(all_materials, None if folder_name is None else new_looks_folder_path) if ignore_select: self.ignore_next_select = True self.render_variants_frame(looks, parent_prim, ignore_widget=True) self.render_current_materials_frame(parent_prim) if ignore_changes: self.ignore_change = False def select_material(self, associated_mesh): """ It selects the material of the mesh that is currently selected in the viewport :param associated_mesh: The path to the mesh you want to select the material for """ if associated_mesh: mesh = self.stage.GetPrimAtPath(associated_mesh) if mesh: current_material_prims = mesh.GetRelationship('material:binding').GetTargets() if current_material_prims: omni.usd.get_context().get_selection().set_prim_path_selected( str(current_material_prims[0]), True, True, True, True) ui.Workspace.show_window("Property", True) property_window = ui.Workspace.get_window("Property") ui.WindowHandle.focus(property_window) def render_variants_frame(self, looks, parent_prim, ignore_widget=False): """ It renders the variants frame, it contains all the variants of the current prim :param parent_prim: The prim that contains the variants """ # Checking if any of the variants are active. is_variants_active = False all_variants = self.get_all_materials_variants(looks) for variant_prim in all_variants: is_active_attr = variant_prim.GetAttribute("MMEisActive") if is_active_attr: if is_active_attr.Get(): is_variants_active = True break # Checking if the is_variants_active variable is True or False. If it is True, then the active_status variable # is set to an empty string. If it is False, then the active_status variable is set to ' (Active)'. active_status = '' if is_variants_active else ' (Active)' # Creating a frame in the UI. if not self.variants_frame_original: self.variants_frame_original = ui.Frame( name="variants_frame_original", identifier="variants_frame_original" ) with self.variants_frame_original: with ui.CollapsableFrame(f"Original{active_status}", height=ui.Pixel(10), collapsed=is_variants_active): with ui.VStack(): ui.Label("Your original, unmodified materials. Cannot be deleted.", name="variant_label", height=40) if is_variants_active: with ui.HStack(): ui.Button( "Enable", name="variant_button", clicked_fn=lambda: self.enable_variant(None, looks, parent_prim)) if not self.variants_frame: self.variants_frame = ui.Frame(name="variants_frame", identifier="variants_frame") with self.variants_frame: with ui.VStack(height=ui.Pixel(10)): for variant_prim in all_variants: # Creating a functions that will be called later in this loop. prim_name = variant_prim.GetName() prim_path = variant_prim.GetPath() is_active_attr = variant_prim.GetAttribute("MMEisActive") if is_active_attr: # Checking if the attribute is_active_attr is active. is_active = is_active_attr.Get() active_status = ' (Active)' if is_active else '' with ui.CollapsableFrame(f"{variant_prim.GetName()}{active_status}", height=ui.Pixel(10), collapsed=not is_active): with ui.VStack(height=ui.Pixel(10)): with ui.HStack(): if not active_status: ui.Button( "Enable", name="variant_button", clicked_fn=lambda p_name=prim_name: self.enable_variant( p_name, looks, parent_prim )) ui.Button( "Delete", name="variant_button", clicked_fn=lambda p_path=prim_path: self.delete_variant( p_path, looks, parent_prim )) else: label_text = "This variant is enabled.\nMake changes to the active materials" \ "from above to edit this variant.\nAll changes will be saved automatically." ui.Label(label_text, name="variant_label", height=40) if not ignore_widget and self.get_setting("MMEEnableViewportUI"): if hasattr(self, "_widget_info_viewport") and self._widget_info_viewport: self._widget_info_viewport.destroy() self._widget_info_viewport = None if len(all_variants) > 0: # Get the active viewport (which at startup is the default Viewport) viewport_window = get_active_viewport_window() # Issue an error if there is no Viewport if not viewport_window: carb.log_warn(f"No Viewport Window to add {self.ext_id} scene to") self._widget_info_viewport = None return if hasattr(self, "ext_id"): print("ext_id", self.ext_id) # Build out the scene self._widget_info_viewport = WidgetInfoScene( viewport_window, self.ext_id, all_variants=all_variants, enable_variant=self.enable_variant, looks=looks, check_visibility=self.get_setting, parent_prim=parent_prim ) return self.variants_frame_original, self.variants_frame def get_closest_mme_object(self): """ If the user has enabled the roaming mode, then we get the camera position and the list of all visible MME objects. We then find the closest MME object to the camera and render the widget for that object. :return: The closest prim to the currently active camera. """ if not self.get_setting("MMEEnableRoamingMode", False): return False camera_prim = self.stage.GetPrimAtPath(get_active_viewport_camera_path()) camera_position = camera_prim.GetAttribute("xformOp:translate").Get() window = get_active_viewport_window() mme_objects = self.get_mme_valid_objects_on_stage() all_visible_prims = [] for prim in mme_objects: ui_position, is_visible = get_ui_position_for_prim(window, prim.GetPath()) if is_visible: all_visible_prims.append(prim) closest_prim = None closest_distance = 0 for prim in all_visible_prims: prim_position = prim.GetAttribute("xformOp:translate").Get() distance = math.sqrt( (prim_position[0] - camera_position[0]) ** 2 + (prim_position[1] - camera_position[1]) ** 2 + (prim_position[2] - camera_position[2]) ** 2 ) if closest_distance > self.get_setting("MMEMaxVisibleDistance", 500): closest_prim = None continue if not closest_prim: closest_prim = prim closest_distance = distance elif distance < closest_distance: closest_prim = prim closest_distance = distance if not hasattr(self, "last_roaming_prim"): self.last_roaming_prim = closest_prim return if closest_distance > 0 and closest_prim and self.last_roaming_prim != closest_prim: self.last_roaming_prim = closest_prim self.render_objectlevel_frame(closest_prim) if hasattr(self, "_widget_info_viewport") and self._widget_info_viewport: self._widget_info_viewport.info_manipulator.model._on_kit_selection_changed() elif not closest_prim: if hasattr(self, "latest_selected_prim") and self.latest_selected_prim: return self.last_roaming_prim = None self.render_scenelevel_frame() if hasattr(self, "_widget_info_viewport") and self._widget_info_viewport: self._widget_info_viewport.destroy() return closest_prim def get_all_children_of_prim(self, prim): """ It takes a prim as an argument and returns a list of all the prims that are children of that prim :param prim: The prim you want to get the children of :return: A list of all the children of the prim. """ children = [] for child in prim.GetChildren(): children.append(child) children.extend(self.get_all_children_of_prim(child)) return children def render_current_materials_frame(self, prim): """ It loops through all meshes of the selected prim, gets all materials that are binded to the mesh, and then loops through all materials and renders a button for each material :param prim: The prim to get all children of :return: The return value is a ui.Frame object. """ all_meshes = [] all_mat_paths = [] # Get all meshes for mesh in self.get_all_children_of_prim(prim): if mesh.GetTypeName() == "Mesh": material_paths = mesh.GetRelationship('material:binding').GetTargets() all_meshes.append({"mesh": mesh, "material_paths": material_paths}) for original_material_prim_path in material_paths: all_mat_paths.append(original_material_prim_path) materials_quantity = len(list(dict.fromkeys(all_mat_paths))) processed_materials = [] scrolling_frame_height = ui.Percent(80) materials_column_count = 1 if materials_quantity < 2: scrolling_frame_height = ui.Percent(50) elif materials_quantity < 4: scrolling_frame_height = ui.Percent(70) elif materials_quantity > 6: materials_column_count = 2 scrolling_frame_height = ui.Percent(100) if not self.materials_frame: self.materials_frame = ui.Frame(name="materials_frame", identifier="materials_frame") with self.materials_frame: with ui.ScrollingFrame(height=scrolling_frame_height): with ui.VGrid(column_count=materials_column_count, height=ui.Pixel(10)): material_counter = 1 # loop through all meshes for mesh_data in all_meshes: def sl_mat_fn(mesh_path=mesh_data["mesh"].GetPath()): return self.select_material(mesh_path) # Get currently binded materials for the current mesh current_material_prims = mesh_data["material_paths"] # Loop through all binded materials paths for original_material_prim_path in current_material_prims: if original_material_prim_path in processed_materials: continue # Get the material prim from path original_material_prim = self.stage.GetPrimAtPath(original_material_prim_path) if not original_material_prim: continue with ui.HStack(): if materials_column_count == 1: ui.Spacer(height=10, width=10) ui.Label( f"{material_counter}.", name="material_counter", width=20 if materials_column_count == 1 else 50, ) ui.Image( height=24, width=24, name="material_preview", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT ) if materials_column_count == 1: ui.Spacer(height=10, width=10) ui.Label( original_material_prim.GetName(), elided_text=True, name="material_name" ) ui.Button( "Select", name="variant_button", width=ui.Percent(30), clicked_fn=sl_mat_fn, ) material_counter += 1 processed_materials.append(original_material_prim_path) if len(all_mat_paths) == 0: ui.Label( "No materials were found. Please make sure that the selected model is valid.", name="main_hint", height=30 ) ui.Spacer(height=10) return self.materials_frame def render_objectlevel_frame(self, prim): """ It renders a frame with a list of all the variants of a given object, and a list of all the materials of the currently active variant. :param prim: The prim that is currently selected in the viewport :return: The main_frame is being returned. """ if not prim: return looks = prim.GetPrimAtPath("Looks") if not hasattr(self, "variants_frame") or self.variants_frame: self.variants_frame = None if not hasattr(self, "variants_frame_original") or self.variants_frame_original: self.variants_frame_original = None if not hasattr(self, "materials_frame") or self.materials_frame: self.materials_frame = None if not hasattr(self, "main_frame") or not self.main_frame: self.main_frame = ui.Frame(name="main_frame", identifier="main_frame") with self.main_frame: with ui.VStack(style=_style): with ui.HStack(height=ui.Pixel(10), name="label_container"): ui.Spacer(width=10) ui.Label(prim.GetName(), name="main_label", height=ui.Pixel(10)) ui.Spacer(height=6) ui.Separator(height=6) ui.Spacer(height=10) with ui.HStack(height=ui.Pixel(30)): ui.Spacer(width=10) ui.Label("Active materials", name="secondary_label") self.render_current_materials_frame(prim) with ui.HStack(height=ui.Pixel(30)): ui.Spacer(width=10) ui.Label("All variants", name="secondary_label") with ui.ScrollingFrame(): with ui.VStack(): self.render_variants_frame(looks, prim) ui.Spacer(height=10) ui.Button( "Add new variant", height=30, clicked_fn=lambda: self.add_variant(looks, prim), alignment=ui.Alignment.CENTER_BOTTOM, tooltip="Create a new variant, based on the current look", ) def open_scene_settings(self): """ If the settings window is not open, render the settings layout, set the settings window to open, and then show the settings window. If the settings window is open, render the active objects frame, and then show the settings window """ if not self.is_settings_open: self.render_scene_settings_layout(dock_in=True) self.is_settings_open = True else: self.render_active_objects_frame() ui.Workspace.show_window(self.SCENE_SETTINGS_WINDOW_NAME, True) scene_settings_window = ui.Workspace.get_window(self.SCENE_SETTINGS_WINDOW_NAME) ui.WindowHandle.focus(scene_settings_window) def render_scenelevel_frame(self): """ It creates a frame with a hint and a button to open the settings window. :return: The main_frame is being returned. """ if not hasattr(self, "main_frame") or not self.main_frame: self.main_frame = ui.Frame(name="main_frame", identifier="main_frame") with self.main_frame: with ui.VStack(style=_style): ui.Spacer() with ui.VStack(): ui.Label("Please select any object to see its materials", name="main_hint", height=30) ui.Label("or", name="main_hint_small", height=10) ui.Spacer(height=5) with ui.HStack(height=ui.Pixel(10)): ui.Spacer() ui.Button( "Open settings", height=20, width=150, name="open_mme_settings", clicked_fn=self.open_scene_settings, ) ui.Spacer() ui.Spacer() return self.main_frame def render_default_layout(self, prim=None): """ It's a function that renders a default layout for the UI :param prim: The prim that is selected in the viewport """ if self.main_frame: self.main_frame = None if self.variants_frame: self.variants_frame = None if self.variants_frame_original: self.variants_frame_original = None if self._window: self._window.destroy() self._window = None self._window = ui.Window(self.WINDOW_NAME, width=300, height=300) with self._window.frame: if not prim: self.render_scenelevel_frame() else: self.render_objectlevel_frame(prim) # SCENE SETTINGS def is_MME_exists(self, prim): """ A recursive method that checks if the prim has a MME prim in its hierarchy :param prim: The prim to check :return: A boolean value. """ for child in prim.GetChildren(): if child.GetName() == "Looks": if child.GetPrimAtPath("MME"): return True else: return False if self.is_MME_exists(child): return True return False def get_mme_valid_objects_on_stage(self): """ Returns a list of valid objects on the stage. """ if not self.stage: return [] valid_objects = [] default_prim = self.stage.GetDefaultPrim() # Get all objects and check if it has Looks folder for obj in default_prim.GetAllChildren(): if obj: if self.is_MME_exists(obj): valid_objects.append(obj) return valid_objects def select_prim(self, prim_path): """ It selects the prim at the given path, shows the property window, and focuses it :param prim_path: The path to the prim you want to select """ self.ignore_settings_update = True omni.kit.commands.execute( 'SelectPrimsCommand', old_selected_paths=[], new_selected_paths=[str(prim_path), ], expand_in_stage=True ) ui.Workspace.show_window(self.WINDOW_NAME, True) property_window = ui.Workspace.get_window(self.WINDOW_NAME) ui.WindowHandle.focus(property_window) self.ignore_settings_update = False def check_stage(self): """ It gets the current stage from the USD context """ if not hasattr(self, "stage") or not self.stage: self._usd_context = omni.usd.get_context() self.stage = self._usd_context.get_stage() def set_setting(self, value, attribute_name, create_only=False): """ It checks if the attribute for showing viewport ui exists, under the DefaultPrim if it doesn't, it creates it, but if it does, it changes the value instead :param value: True or False :param create_only: If True, the attribute will only be created if it doesn't exist, defaults to False (optional) :return: The return value is the value of the attribute. """ self.check_stage() if not self.stage: return # Get DefaultPrim from Stage default_prim = self.stage.GetDefaultPrim() # Get attribute from DefaultPrim if it exists attribute = default_prim.GetAttribute(attribute_name) attribute_path = attribute.GetPath() # check if attribute exists if not attribute: # if not, create it omni.kit.commands.execute( 'CreateUsdAttributeOnPath', attr_path=attribute_path, attr_type=Sdf.ValueTypeNames.Bool, custom=True, attr_value=value, variability=Sdf.VariabilityVarying ) else: if attribute.Get() == value or create_only: return omni.kit.commands.execute( 'ChangeProperty', prop_path=attribute_path, value=value, prev=not value, ) def get_setting(self, attribute_name, default_value=True): """ It gets the value of an attribute from the default prim of the stage :param attribute_name: The name of the attribute you want to get :param default_value: The value to return if the attribute doesn't exist, defaults to True (optional) :return: The value of the attribute. """ self.check_stage() if not self.stage: return # Get DefaultPrim from Stage default_prim = self.stage.GetDefaultPrim() # Get attribute from DefaultPrim called attribute = default_prim.GetAttribute(attribute_name) if attribute: return attribute.Get() else: return default_value # Attribute was not created yet, so we return default_value def render_active_objects_frame(self, valid_objects=None): """ It creates a UI frame with a list of buttons that select objects in the scene :param valid_objects: a list of objects that have variants :return: The active_objects_frame is being returned. """ if not valid_objects: valid_objects = self.get_mme_valid_objects_on_stage() objects_quantity = len(valid_objects) objects_column_count = 1 if objects_quantity > 6: objects_column_count = 2 if not self.active_objects_frame: self.active_objects_frame = ui.Frame(name="active_objects_frame", identifier="active_objects_frame") with self.active_objects_frame: with ui.VGrid(column_count=objects_column_count): material_counter = 1 # loop through all meshes for prim in valid_objects: if not prim: continue with ui.HStack(): if objects_column_count == 1: ui.Spacer(height=10, width=10) ui.Label( f"{material_counter}.", name="material_counter", width=20 if objects_column_count == 1 else 50, ) if objects_column_count == 1: ui.Spacer(height=10, width=10) ui.Label( prim.GetName(), elided_text=True, name="material_name" ) ui.Button( "Select", name="variant_button", width=ui.Percent(30), clicked_fn=lambda mesh_path=prim.GetPath(): self.select_prim(mesh_path), ) material_counter += 1 if objects_quantity == 0: ui.Label( "No models with variants were found.", name="main_hint", height=30 ) ui.Spacer(height=10) return self.active_objects_frame def render_scene_settings_layout(self, dock_in=False): """ It renders a window with a list of objects in the scene that have variants and some settings. Called only once, all interactive elements are updated through the frames. """ valid_objects = self.get_mme_valid_objects_on_stage() if self._window_scenemanager: self._window_scenemanager.destroy() self._window_scenemanager = None self._window_scenemanager = ui.Window(self.SCENE_SETTINGS_WINDOW_NAME, width=300, height=300) if dock_in: self._window_scenemanager.deferred_dock_in(self.WINDOW_NAME) if self.active_objects_frame: self.active_objects_frame = None with self._window_scenemanager.frame: with ui.VStack(style=_style): with ui.HStack(height=ui.Pixel(10), name="label_container"): ui.Spacer(width=10) ui.Label(self.SCENE_SETTINGS_WINDOW_NAME, name="main_label", height=ui.Pixel(10)) ui.Spacer(height=6) ui.Separator(height=6) ui.Spacer(height=10) with ui.HStack(height=ui.Pixel(30)): ui.Spacer(width=10) ui.Label("Models with variants in your scene", name="secondary_label") ui.Spacer(height=40) with ui.ScrollingFrame(height=ui.Pixel(100)): self.render_active_objects_frame(valid_objects) ui.Spacer(height=10) with ui.HStack(height=ui.Pixel(30)): ui.Spacer(width=10) ui.Label("Settings", name="secondary_label") ui.Spacer(height=10) ui.Separator(height=6) with ui.ScrollingFrame(): with ui.VStack(): ui.Spacer(height=5) with ui.HStack(height=20): ui.Spacer(width=ui.Percent(5)) ui.Label("Enable viewport widget rendering:", width=ui.Percent(70)) ui.Spacer(width=ui.Percent(10)) # Creating a checkbox and setting the value to the value of the get_setting() # function. self.enable_viewport_ui = ui.CheckBox(width=ui.Percent(15)) self.enable_viewport_ui.model.set_value(self.get_setting("MMEEnableViewportUI")) self.enable_viewport_ui.model.add_value_changed_fn( lambda value: self.set_setting(value.get_value_as_bool(), "MMEEnableViewportUI") ) ui.Spacer(height=10) ui.Separator(height=6) with ui.HStack(height=20): # Window will appear if you look at the object in the viewport, instead of clicking on it ui.Spacer(width=ui.Percent(5)) ui.Label("Roaming mode:", width=ui.Percent(70)) ui.Spacer(width=ui.Percent(10)) self.enable_roaming_mode = ui.CheckBox(width=ui.Percent(15)) self.enable_roaming_mode.model.set_value(self.get_setting("MMEEnableRoamingMode", False)) self.enable_roaming_mode.model.add_value_changed_fn( lambda value: self.set_setting(value.get_value_as_bool(), "MMEEnableRoamingMode") ) ui.Spacer(height=10) ui.Separator(height=6)
Vadim-Karpenko/omniverse-material-manager-extended/exts/karpenko.materialsmanager.ext/karpenko/materialsmanager/ext/__init__.py
from .extension import *
Vadim-Karpenko/omniverse-material-manager-extended/exts/karpenko.materialsmanager.ext/karpenko/materialsmanager/ext/viewport_ui/widget_info_manipulator.py
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WidgetInfoManipulator"] from omni.ui import color as cl from omni.ui import scene as sc import omni.ui as ui from ..style import viewport_widget_style class _ViewportLegacyDisableSelection: """Disables selection in the Viewport Legacy""" def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact is the focused window! # And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) except Exception: pass class _DragPrioritize(sc.GestureManager): """Refuses preventing _DragGesture.""" def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: return True class _DragGesture(sc.DragGesture): """"Gesture to disable rectangle selection in the viewport legacy""" def __init__(self): super().__init__(manager=_DragPrioritize()) def on_began(self): # When the user drags the slider, we don't want to see the selection # rect. In Viewport Next, it works well automatically because the # selection rect is a manipulator with its gesture, and we add the # slider manipulator to the same SceneView. # In Viewport Legacy, the selection rect is not a manipulator. Thus it's # not disabled automatically, and we need to disable it with the code. self.__disable_selection = _ViewportLegacyDisableSelection() def on_ended(self): # This re-enables the selection in the Viewport Legacy self.__disable_selection = None class WidgetInfoManipulator(sc.Manipulator): def __init__(self, all_variants, enable_variant, looks, parent_prim, check_visibility, **kwargs): super().__init__(**kwargs) self.destroy() self.all_variants = all_variants self.enable_variant = enable_variant self.looks = looks self.parent_prim = parent_prim self.check_visibility = check_visibility self._radius = 2 self._distance_to_top = 5 self._thickness = 2 self._radius_hovered = 20 self.prev_button = None self.next_button = None def destroy(self): self._root = None self._slider_subscription = None self._slider_model = None self._name_label = None self.prev_button = None self.next_button = None self.all_variants = None self.enable_variant = None self.looks = None self.parent_prim = None def _on_build_widgets(self): with ui.ZStack(height=70, style=viewport_widget_style): ui.Rectangle( style={ "background_color": cl(0.2), "border_color": cl(0.7), "border_width": 2, "border_radius": 4, } ) with ui.VStack(): ui.Spacer(height=4) with ui.HStack(): ui.Spacer(width=10) self.prev_button = ui.Button("Prev", width=100) self._name_label = ui.Label( "", elided_text=True, name="name_label", height=0, alignment=ui.Alignment.CENTER_BOTTOM ) self.next_button = ui.Button("Next", width=100) ui.Spacer(width=10) # setup some model, just for simple demonstration here self._slider_model = ui.SimpleIntModel() ui.Spacer(height=5) with ui.HStack(style={"font_size": 26}): ui.Spacer(width=5) ui.IntSlider(self._slider_model, min=0, max=len(self.all_variants)) ui.Spacer(width=5) ui.Spacer(height=24) ui.Spacer() self.on_model_updated(None) # Additional gesture that prevents Viewport Legacy selection self._widget.gestures += [_DragGesture()] def on_build(self): """Called when the model is changed and rebuilds the whole slider""" self._root = sc.Transform(visible=False) with self._root: with sc.Transform(scale_to=sc.Space.SCREEN): with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 100, 0)): # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): self._widget = sc.Widget(500, 130, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED) self._widget.frame.set_build_fn(self._on_build_widgets) # Update the slider def update_variant(self, value): if not self._root or not self._root.visible or not self.looks or not self.parent_prim: return if value == 0: self.enable_variant(None, self.looks, self.parent_prim, ignore_select=True) else: selected_variant = self.all_variants[value - 1] if not selected_variant: return prim_name = selected_variant.GetName() self.enable_variant(prim_name, self.looks, self.parent_prim, ignore_select=True) def on_model_updated(self, _): if not self._root: return # if we don't have selection then show nothing if not self.model or not self.model.get_item("name") or not self.check_visibility("MMEEnableViewportUI"): self._root.visible = False return # Update the shapes position = self.model.get_as_floats(self.model.get_item("position")) self._root.transform = sc.Matrix44.get_translation_matrix(*position) self._root.visible = True active_index = 0 for variant_prim in self.all_variants: is_active_attr = variant_prim.GetAttribute("MMEisActive") if is_active_attr: # Checking if the attribute is_active_attr is active. is_active = is_active_attr.Get() if is_active: active_index = self.all_variants.index(variant_prim) + 1 break if self._slider_model: if self._slider_subscription: self._slider_subscription.unsubscribe() self._slider_subscription = None self._slider_model.as_int = active_index self._slider_subscription = self._slider_model.subscribe_value_changed_fn( lambda m: self.update_variant(m.as_int) ) if self.prev_button and self.next_button: self.prev_button.enabled = active_index > 0 self.next_button.enabled = active_index < len(self.all_variants) self.prev_button.set_clicked_fn(lambda: self.update_variant(active_index - 1)) self.next_button.set_clicked_fn(lambda: self.update_variant(active_index + 1)) # Update the shape name if self._name_label: if active_index == 0: self._name_label.text = "Orginal" else: self._name_label.text = f"{self.all_variants[active_index - 1].GetName()}"
Vadim-Karpenko/omniverse-material-manager-extended/exts/karpenko.materialsmanager.ext/karpenko/materialsmanager/ext/viewport_ui/__init__.py
Vadim-Karpenko/omniverse-material-manager-extended/exts/karpenko.materialsmanager.ext/karpenko/materialsmanager/ext/viewport_ui/widget_info_scene.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WidgetInfoScene"] from omni.ui import scene as sc from .widget_info_model import WidgetInfoModel from .widget_info_manipulator import WidgetInfoManipulator class WidgetInfoScene(): """The Object Info Manupulator, placed into a Viewport""" def __init__(self, viewport_window, ext_id: str, all_variants: list, enable_variant, looks, parent_prim, check_visibility): self._scene_view = None self._viewport_window = viewport_window # Create a unique frame for our SceneView with self._viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self._scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self._scene_view.scene: self.info_manipulator = WidgetInfoManipulator( model=WidgetInfoModel(parent_prim=parent_prim, get_setting=check_visibility), all_variants=all_variants, enable_variant=enable_variant, looks=looks, parent_prim=parent_prim, check_visibility=check_visibility, ) # Register the SceneView with the Viewport to get projection and view updates self._viewport_window.viewport_api.add_scene_view(self._scene_view) def __del__(self): self.destroy() def destroy(self): if self.info_manipulator: self.info_manipulator.destroy() if self._scene_view: # Empty the SceneView of any elements it may have self._scene_view.scene.clear() # Be a good citizen, and un-register the SceneView from Viewport updates if self._viewport_window: self._viewport_window.viewport_api.remove_scene_view(self._scene_view) # Remove our references to these objects self._viewport_window = None self._scene_view = None self.info_manipulator = None
Vadim-Karpenko/omniverse-material-manager-extended/exts/karpenko.materialsmanager.ext/karpenko/materialsmanager/ext/viewport_ui/widget_info_model.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WidgetInfoModel"] from omni.ui import scene as sc from pxr import UsdGeom from pxr import Usd from pxr import UsdShade from pxr import Tf from pxr import UsdLux import omni.usd import omni.kit.commands class WidgetInfoModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and info of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because we take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] class ValueItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value about some attibute""" def __init__(self, value=0): super().__init__() self.value = [value] def __init__(self, parent_prim, get_setting): super().__init__() self.material_name = "" self.position = WidgetInfoModel.PositionItem() # The distance from the bounding box to the position the model returns self._offset = 0 # Current selection self._prim = parent_prim self.get_setting = get_setting self._current_path = "" self._stage_listener = None # Save the UsdContext name (we currently only work with single Context) self._usd_context_name = '' usd_context = self._get_context() # Track selection self._events = usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="Object Info Selection Update" ) def _get_context(self) -> Usd.Stage: # Get the UsdContext we are attached to return omni.usd.get_context(self._usd_context_name) def _notice_changed(self, notice, stage): """Called by Tf.Notice""" if self.get_setting("MMEEnableRoamingMode", False): self._item_changed(self.position) return for p in notice.GetChangedInfoOnlyPaths(): if self._current_path in str(p.GetPrimPath()): self._item_changed(self.position) def get_item(self, identifier): if identifier == "position": return self.position if identifier == "name": return self._current_path if identifier == "material": return self.material_name def get_as_floats(self, item): if item == self.position: # Requesting position return self._get_position() if item: # Get the value directly from the item return item.value return [] def set_floats(self, item, value): if not self._current_path: return if not value or not item or item.value == value: return # Set directly to the item item.value = value # This makes the manipulator updated self._item_changed(item) def _on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_kit_selection_changed() def _on_kit_selection_changed(self): # selection change, reset it for now self._current_path = "" usd_context = self._get_context() stage = usd_context.get_stage() if not stage: return if not self.get_setting("MMEEnableRoamingMode", False): prim_paths = usd_context.get_selection().get_selected_prim_paths() if not prim_paths or len(prim_paths) > 1 or len(prim_paths) == 0 or str(self._prim.GetPath()) not in prim_paths[0]: self._item_changed(self.position) # Revoke the Tf.Notice listener, we don't need to update anything if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None return prim = self._prim if prim.GetTypeName() == "Light": self.material_name = "I am a Light" elif prim.IsA(UsdGeom.Imageable): material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() if material: self.material_name = str(material.GetPath()) else: self.material_name = "N/A" else: self._prim = None return self._current_path = str(self._prim.GetPath()) # Add a Tf.Notice listener to update the position if not self._stage_listener: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage) (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim) # Position is changed self._item_changed(self.position) def find_child_mesh_with_position(self, prim): """ A recursive method to find a child with a valid position. """ if prim.IsA(UsdGeom.Mesh): self._current_path = str(prim.GetPath()) prim_position = self._get_position(non_recursive=True) if prim_position[0] == 0.0 or prim_position[1] == 0.0 or prim_position[2] == 0.0: pass else: return prim for child in prim.GetChildren(): result = self.find_child_mesh_with_position(child) if result: return result return None def _get_position(self, non_recursive=False): """Returns position of currently selected object""" stage = self._get_context().get_stage() if not stage or not self._current_path: return [0, 0, 0] # Get position directly from USD if non_recursive: prim = stage.GetPrimAtPath(self._current_path) else: prim = self.find_child_mesh_with_position(stage.GetPrimAtPath(self._current_path)) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1] + self._offset, (bboxMin[2] + bboxMax[2]) * 0.5] return position
Vadim-Karpenko/omniverse-material-manager-extended/exts/karpenko.materialsmanager.ext/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.1.4" # The title and description fields are primarily for displaying extension info in UI title = "Material Manager" description="Allows you to quickly toggle between different materials" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "https://github.com/Vadim-Karpenko/omniverse-material-manager-extended" # One of categories for UI. category = "Material" # Keywords for the extension keywords = ["material", "materials", "manager", ] authors = ["Vadim Karpenko"] preview_image = "data/preview_image.png" icon = "data/icons/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.stage.copypaste" = {} "omni.kit.uiapp" = {} "omni.kit.viewport.utility" = { } "omni.ui.scene" = { } "omni.ui" = { } "omni.usd" = { } "omni.kit.usd_undo" = {} # Main python module this extension provides, it will be publicly available as "import karpenko.materialsmanager.ext". [[python.module]] name = "karpenko.materialsmanager.ext" dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
Vadim-Karpenko/omniverse-material-manager-extended/exts/karpenko.materialsmanager.ext/docs/README.md
## Material Manager Extended This extension will let you quickly toggle between different materials for the static objects in your scene.
zslrmhb/Omniverse-Virtual-Assisstant/nlp.py
# natural language processing module utilizing the Riva SDK import wikipedia as wiki import wikipediaapi as wiki_api import riva.client from config import URI class NLPService: def __init__(self, max_wiki_articles): """ :param max_wiki_articles: max wiki articles to search """ self.max_wiki_articles = max_wiki_articles self.wiki_summary = " " self.input_query = " " self.auth = riva.client.Auth(uri=URI) self.service = riva.client.NLPService(self.auth) self.wiki_wiki = wiki_api.Wikipedia('en') def wiki_query(self, input_query) -> None: """ :param input_query: word to search :return: None """ self.wiki_summary = " " self.input_query = input_query wiki_articles = wiki.search(input_query) for article in wiki_articles[:min(len(wiki_articles), self.max_wiki_articles)]: print(f"Getting summary for: {article}") page = self.wiki_wiki.page(article) self.wiki_summary += "\n" + page.summary def nlp_query(self) -> None: """ :return: Response from the NLP model """ resp = self.service.natural_query(self.input_query, self.wiki_summary) if len(resp.results[0].answer) == 0: return "Sorry, I don't understand, may you speak again?" else: return resp.results[0].answer
zslrmhb/Omniverse-Virtual-Assisstant/tts.py
# text-to-speech module utilizting the Riva SDK import riva.client import riva.client.audio_io from config import URI class TTSService: def __init__(self, language='en-US', sample_rate_hz=44100): """ :param language: language code :param sample_rate_hz: sample rate herz """ self.auth = riva.client.Auth(uri=URI) self.service = riva.client.SpeechSynthesisService(self.auth) self.langauge = language self.voice = "English-US.Male-1" self.sample_rate_hz = sample_rate_hz def speak(self, text) -> None: """ :param text: text to speak :return: None """ sound_stream = riva.client.audio_io.SoundCallBack( 3, nchannels=1, sampwidth=2, framerate=self.sample_rate_hz ) responses = self.service.synthesize_online( text, None, self.langauge, sample_rate_hz=self.sample_rate_hz ) for resp in responses: sound_stream(resp.audio) sound_stream.close() def get_audio_bytes(self, text) -> bytes: """ :param text: text to speak :return: speech audio """ resp = self.service.synthesize(text, self.voice, self.langauge, sample_rate_hz=self.sample_rate_hz) return resp.audio
zslrmhb/Omniverse-Virtual-Assisstant/audio2face_streaming_utils.py
""" This demo script shows how to send audio data to Audio2Face Streaming Audio Player via gRPC requests. There are two options: * Send the whole track at once using PushAudioRequest() * Send the audio chunks seuqntially in a stream using PushAudioStreamRequest() For the second option this script emulates the stream of chunks, generated by splitting an input WAV audio file. But in a real application such stream of chunks may be aquired from some other streaming source: * streaming audio via internet, streaming Text-To-Speech, etc gRPC protocol details could be find in audio2face.proto """ import sys import grpc import time import numpy as np import soundfile import audio2face_pb2 import audio2face_pb2_grpc def push_audio_track(url, audio_data, samplerate, instance_name): """ This function pushes the whole audio track at once via PushAudioRequest() PushAudioRequest parameters: * audio_data: bytes, containing audio data for the whole track, where each sample is encoded as 4 bytes (float32) * samplerate: sampling rate for the audio data * instance_name: prim path of the Audio2Face Streaming Audio Player on the stage, were to push the audio data * block_until_playback_is_finished: if True, the gRPC request will be blocked until the playback of the pushed track is finished The request is passed to PushAudio() """ block_until_playback_is_finished = True # ADJUST with grpc.insecure_channel(url) as channel: stub = audio2face_pb2_grpc.Audio2FaceStub(channel) request = audio2face_pb2.PushAudioRequest() request.audio_data = audio_data.astype(np.float32).tobytes() request.samplerate = samplerate request.instance_name = instance_name request.block_until_playback_is_finished = block_until_playback_is_finished print("Sending audio data...") response = stub.PushAudio(request) if response.success: print("SUCCESS") else: print(f"ERROR: {response.message}") print("Closed channel") def push_audio_track_stream(url, audio_data, samplerate, instance_name): """ This function pushes audio chunks sequentially via PushAudioStreamRequest() The function emulates the stream of chunks, generated by splitting input audio track. But in a real application such stream of chunks may be aquired from some other streaming source. The first message must contain start_marker field, containing only meta information (without audio data): * samplerate: sampling rate for the audio data * instance_name: prim path of the Audio2Face Streaming Audio Player on the stage, were to push the audio data * block_until_playback_is_finished: if True, the gRPC request will be blocked until the playback of the pushed track is finished (after the last message) Second and other messages must contain audio_data field: * audio_data: bytes, containing audio data for an audio chunk, where each sample is encoded as 4 bytes (float32) All messages are packed into a Python generator and passed to PushAudioStream() """ chunk_size = samplerate // 10 # ADJUST sleep_between_chunks = 0.04 # ADJUST block_until_playback_is_finished = True # ADJUST with grpc.insecure_channel(url) as channel: print("Channel creadted") stub = audio2face_pb2_grpc.Audio2FaceStub(channel) def make_generator(): start_marker = audio2face_pb2.PushAudioRequestStart( samplerate=samplerate, instance_name=instance_name, block_until_playback_is_finished=block_until_playback_is_finished, ) # At first, we send a message with start_marker yield audio2face_pb2.PushAudioStreamRequest(start_marker=start_marker) # Then we send messages with audio_data for i in range(len(audio_data) // chunk_size + 1): time.sleep(sleep_between_chunks) chunk = audio_data[i * chunk_size : i * chunk_size + chunk_size] yield audio2face_pb2.PushAudioStreamRequest(audio_data=chunk.astype(np.float32).tobytes()) request_generator = make_generator() print("Sending audio data...") response = stub.PushAudioStream(request_generator) if response.success: print("SUCCESS") else: print(f"ERROR: {response.message}") print("Channel closed") def main(): """ This demo script shows how to send audio data to Audio2Face Streaming Audio Player via gRPC requests. There two options: * Send the whole track at once using PushAudioRequest() * Send the audio chunks seuqntially in a stream using PushAudioStreamRequest() For the second option this script emulates the stream of chunks, generated by splitting an input WAV audio file. But in a real application such stream of chunks may be aquired from some other streaming source: * streaming audio via internet, streaming Text-To-Speech, etc gRPC protocol details could be find in audio2face.proto """ if len(sys.argv) < 3: print("Format: python test_client.py PATH_TO_WAV INSTANCE_NAME") return # Sleep time emulates long latency of the request sleep_time = 2.0 # ADJUST # URL of the Audio2Face Streaming Audio Player server (where A2F App is running) url = "localhost:50051" # ADJUST # Local input WAV file path audio_fpath = sys.argv[1] # Prim path of the Audio2Face Streaming Audio Player on the stage (were to push the audio data) instance_name = sys.argv[2] data, samplerate = soundfile.read(audio_fpath, dtype="float32") # Only Mono audio is supported if len(data.shape) > 1: data = np.average(data, axis=1) print(f"Sleeping for {sleep_time} seconds") time.sleep(sleep_time) if 0: # ADJUST # Push the whole audio track at once push_audio_track(url, data, samplerate, instance_name) else: # Emulate audio stream and push audio chunks sequentially push_audio_track_stream(url, data, samplerate, instance_name) if __name__ == "__main__": main()
zslrmhb/Omniverse-Virtual-Assisstant/asr.py
# Audio to Speech Module utilizing the Riva SDK import riva.client import riva.client.audio_io from typing import Iterable import riva.client.proto.riva_asr_pb2 as rasr from config import URI config = riva.client.StreamingRecognitionConfig( config=riva.client.RecognitionConfig( encoding=riva.client.AudioEncoding.LINEAR_PCM, language_code='en-US', max_alternatives=1, profanity_filter=False, enable_automatic_punctuation=True, verbatim_transcripts=True, sample_rate_hertz=16000 ), interim_results=False, ) class ASRService: def __init__(self): """ """ self.auth = riva.client.Auth(uri=URI) self.service = riva.client.ASRService(self.auth) self.sample_rate_hz = 16000 self.file_streaming_chunk = 1600 self.transcript = "" self.default_device_info = riva.client.audio_io.get_default_input_device_info() self.default_device_index = None if self.default_device_info is None else self.default_device_info['index'] def run(self) -> None: """ :return: None """ with riva.client.audio_io.MicrophoneStream( rate=self.sample_rate_hz, chunk=self.file_streaming_chunk, device=1, ) as audio_chunk_iterator: self.print_response(responses=self.service.streaming_response_generator( audio_chunks=audio_chunk_iterator, streaming_config=config)) def print_response(self, responses: Iterable[rasr.StreamingRecognizeResponse]) -> None: """ :param responses: Streaming Response :return: None """ self.transcript = "" for response in responses: if not response.results: continue for result in response.results: if not result.alternatives: continue if result.is_final: partial_transcript = result.alternatives[0].transcript self.transcript += partial_transcript # print(self.transcript) return # key = input("Press 'q' to finished recording\n" # "Press 'r' to redo\n" # "Press 'c' to continue record\n") # # micStream.closed = True # while key not in ['q', 'r', 'c']: # print("Please input the correct key!\n") # key = input() # micStream.closed = False # if key == "q": return # elif key == "r": self.transcript = "" # else: continue
zslrmhb/Omniverse-Virtual-Assisstant/main.py
# Running the Demo from asr import ASRService from nlp import NLPService from tts import TTSService from audio2face import Audio2FaceService asr_service = ASRService() nlp_service = NLPService(max_wiki_articles=5) tts_service = TTSService() audio2face_service = Audio2FaceService() while True: # speech recognition asr_service.run() print(asr_service.transcript) # natural language processing with the help of Wikipedia API nlp_service.wiki_query(asr_service.transcript) output = nlp_service.nlp_query() print(output) # text-to-speech audio_bytes = tts_service.get_audio_bytes(output) # Audio2Face Animation audio2face_service.make_avatar_speaks(audio_bytes)
zslrmhb/Omniverse-Virtual-Assisstant/config.py
# configuration for accessing the remote local host on the Google Cloud Server URI = "" # This will be in the syntax of external ip of your Riva Server:Port of your Riva Server # Example: 12.34.56.789:50050
zslrmhb/Omniverse-Virtual-Assisstant/audio2face_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import audio2face_pb2 as audio2face__pb2 class Audio2FaceStub(object): """Missing associated documentation comment in .proto file.""" def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.PushAudio = channel.unary_unary( "/nvidia.audio2face.Audio2Face/PushAudio", request_serializer=audio2face__pb2.PushAudioRequest.SerializeToString, response_deserializer=audio2face__pb2.PushAudioResponse.FromString, ) self.PushAudioStream = channel.stream_unary( "/nvidia.audio2face.Audio2Face/PushAudioStream", request_serializer=audio2face__pb2.PushAudioStreamRequest.SerializeToString, response_deserializer=audio2face__pb2.PushAudioStreamResponse.FromString, ) class Audio2FaceServicer(object): """Missing associated documentation comment in .proto file.""" def PushAudio(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def PushAudioStream(self, request_iterator, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def add_Audio2FaceServicer_to_server(servicer, server): rpc_method_handlers = { "PushAudio": grpc.unary_unary_rpc_method_handler( servicer.PushAudio, request_deserializer=audio2face__pb2.PushAudioRequest.FromString, response_serializer=audio2face__pb2.PushAudioResponse.SerializeToString, ), "PushAudioStream": grpc.stream_unary_rpc_method_handler( servicer.PushAudioStream, request_deserializer=audio2face__pb2.PushAudioStreamRequest.FromString, response_serializer=audio2face__pb2.PushAudioStreamResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler("nvidia.audio2face.Audio2Face", rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class Audio2Face(object): """Missing associated documentation comment in .proto file.""" @staticmethod def PushAudio( request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None, ): return grpc.experimental.unary_unary( request, target, "/nvidia.audio2face.Audio2Face/PushAudio", audio2face__pb2.PushAudioRequest.SerializeToString, audio2face__pb2.PushAudioResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, ) @staticmethod def PushAudioStream( request_iterator, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None, ): return grpc.experimental.stream_unary( request_iterator, target, "/nvidia.audio2face.Audio2Face/PushAudioStream", audio2face__pb2.PushAudioStreamRequest.SerializeToString, audio2face__pb2.PushAudioStreamResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata, )
zslrmhb/Omniverse-Virtual-Assisstant/audio2face.py
# speech to Audio2Face module utilizing the gRPC protocal from audio2face_streaming_utils import riva.client import io from pydub import AudioSegment from scipy.io.wavfile import read import numpy as np from audio2face_streaming_utils import push_audio_track class Audio2FaceService: def __init__(self, sample_rate=44100): """ :param sample_rate: sample rate """ self.a2f_url = 'localhost:50051' # Set it to the port of your local host self.sample_rate = 44100 self.avatar_instance = '/World/audio2face/PlayerStreaming' # Set it to the name of your Audio2Face Streaming Instance def tts_to_wav(self, tts_byte, framerate=22050) -> str: """ :param tts_byte: tts data in byte :param framerate: framerate :return: wav byte """ seg = AudioSegment.from_raw(io.BytesIO(tts_byte), sample_width=2, frame_rate=22050, channels=1) wavIO = io.BytesIO() seg.export(wavIO, format="wav") rate, wav = read(io.BytesIO(wavIO.getvalue())) return wav def wav_to_numpy_float32(self, wav_byte) -> float: """ :param wav_byte: wav byte :return: float32 """ return wav_byte.astype(np.float32, order='C') / 32768.0 def get_tts_numpy_audio(self, audio) -> float: """ :param audio: audio from tts_to_wav :return: float32 of the audio """ wav_byte = self.tts_to_wav(audio) return self.wav_to_numpy_float32(wav_byte) def make_avatar_speaks(self, audio) -> None: """ :param audio: tts audio :return: None """ push_audio_track(self.a2f_url, self.get_tts_numpy_audio(audio), self.sample_rate, self.avatar_instance)
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
1
Edit dataset card