file_path
stringlengths
20
202
content
stringlengths
9
3.85M
size
int64
9
3.85M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
8
993
alphanum_fraction
float64
0.26
0.93
omniverse-code/kit/include/omni/kit/ui/Popup.h
// Copyright (c) 2019-2020, 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. // #pragma once #include "ColumnLayout.h" #include <omni/ui/windowmanager/IWindowCallbackManager.h> #include <cstdint> #include <functional> #include <memory> #include <string> namespace omni { namespace kit { namespace ui { class Container; /** * Defines a popup. */ class OMNI_KIT_UI_CLASS_API Popup { public: /** * Constructor */ OMNI_KIT_UI_API explicit Popup( const std::string& title, bool modal = false, float width = 0, float height = 0, bool autoResize = false); /** * Destructor. */ OMNI_KIT_UI_API ~Popup(); OMNI_KIT_UI_API void show(); OMNI_KIT_UI_API void hide(); OMNI_KIT_UI_API bool isVisible() const; OMNI_KIT_UI_API void setVisible(bool visible); OMNI_KIT_UI_API const char* getTitle() const; OMNI_KIT_UI_API void setTitle(const char* title); OMNI_KIT_UI_API carb::Float2 getPos() const; OMNI_KIT_UI_API void setPos(const carb::Float2& pos); OMNI_KIT_UI_API float getWidth() const; OMNI_KIT_UI_API void setWidth(float width); OMNI_KIT_UI_API float getHeight() const; OMNI_KIT_UI_API void setHeight(float height); OMNI_KIT_UI_API std::shared_ptr<Container> getLayout() const; OMNI_KIT_UI_API void setLayout(std::shared_ptr<Container> layout); OMNI_KIT_UI_API void setUpdateFn(const std::function<void(float)>& fn); OMNI_KIT_UI_API void setCloseFn(const std::function<void()>& fn); private: void _draw(float dt); std::string m_popupId; bool m_modal; bool m_autoResize; std::string m_title; float m_width; float m_height; carb::Float2 m_pos; std::shared_ptr<Container> m_layout; omni::ui::windowmanager::IWindowCallbackPtr m_handle; omni::kit::SubscriptionId m_updateSubId; bool m_visible = false; bool m_pendingVisiblityUpdate = false; bool m_pendingPositionUpdate = false; std::function<void(float)> m_updateFn; std::function<void()> m_closeFn; }; } } }
2,407
C
22.841584
114
0.688409
omniverse-code/kit/include/omni/kit/ui/Model.h
// Copyright (c) 2019-2020, 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. // #pragma once #include "Api.h" #include "Common.h" #include <carb/events/IEvents.h> #include <memory> #include <string> #include <unordered_map> namespace omni { namespace kit { namespace ui { enum class ModelNodeType { eUnknown, eObject, eArray, eString, eBool, eNumber }; enum class ModelEventType { eNodeAdd, eNodeRemove, eNodeTypeChange, eNodeValueChange }; struct ModelChangeInfo { carb::events::SenderId sender = carb::events::kGlobalSenderId; bool transient = false; }; template <class T> struct ModelValue { T value; bool ambiguous; }; class OMNI_KIT_UI_CLASS_API Model { public: Model() = default; // PART 1: Get OMNI_KIT_UI_API virtual ModelNodeType getType(const char* path, const char* meta = "") = 0; OMNI_KIT_UI_API virtual ModelValue<std::string> getValueAsString( const char* path, const char* meta = "", size_t index = 0, bool isTimeSampled = false, double time = -1.0) = 0; OMNI_KIT_UI_API virtual ModelValue<bool> getValueAsBool( const char* path, const char* meta = "", size_t index = 0, bool isTimeSampled = false, double time = -1.0) = 0; OMNI_KIT_UI_API virtual ModelValue<double> getValueAsNumber( const char* path, const char* meta = "", size_t index = 0, bool isTimeSampled = false, double time = -1.0) = 0; virtual size_t getKeyCount(const char* path, const char* meta = "") { return 0; } virtual std::string getKey(const char* path, const char* meta, size_t index) { return ""; } virtual size_t getArraySize(const char* path, const char* meta = "") { return 0; } // PART 2: Set virtual void beginChangeGroup() { } virtual void endChangeGroup() { } virtual void setType(const char* path, const char* meta, ModelNodeType type, const ModelChangeInfo& info = {}) { } OMNI_KIT_UI_API virtual void setValueString(const char* path, const char* meta, std::string value, size_t index = 0, bool isTimeSampled = false, double time = -1.0, const ModelChangeInfo& info = {}) = 0; OMNI_KIT_UI_API virtual void setValueBool(const char* path, const char* meta, bool value, size_t index = 0, bool isTimeSampled = false, double time = -1.0, const ModelChangeInfo& info = {}) = 0; OMNI_KIT_UI_API virtual void setValueNumber(const char* path, const char* meta, double value, size_t index = 0, bool isTimeSampled = false, double time = -1.0, const ModelChangeInfo& info = {}) = 0; OMNI_KIT_UI_API virtual void setArraySize(const char* path, const char* meta, size_t size, bool isTimeSampled = false, double time = -1.0, const ModelChangeInfo& info = {}) { } // PART 3: signals OMNI_KIT_UI_API void signalChange(const char* path, const char* meta, ModelEventType type, const ModelChangeInfo& info); virtual void onSubscribeToChange(const char* path, const char* meta, carb::events::IEventStream*) { } virtual void onUnsubscribeToChange(const char* path, const char* meta, carb::events::IEventStream*) { } OMNI_KIT_UI_API void subscribeToChange(const char* path, const char* meta, carb::events::IEventStream*); OMNI_KIT_UI_API void unsubscribeToChange(const char* path, const char* meta, carb::events::IEventStream*); // HELPERS: template <class T> OMNI_KIT_UI_API ModelValue<T> getValue( const char* path, const char* meta, size_t index = 0, bool isTimeSampled = false, double time = -1.0); template <class T> OMNI_KIT_UI_API void setValue(const char* path, const char* meta, T value, size_t index = 00, bool isTimeSampled = false, double time = -1.0, const ModelChangeInfo& info = {}); template <class T> OMNI_KIT_UI_API static ModelNodeType getNodeTypeForT(); OMNI_KIT_UI_API virtual ~Model(){}; private: std::unordered_map<std::string, std::vector<carb::events::IEventStream*>> m_pathChangeListeners; }; template <> inline ModelValue<bool> Model::getValue(const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { return getValueAsBool(path, meta, index, isTimeSampled, time); } template <> inline ModelValue<std::string> Model::getValue( const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { return getValueAsString(path, meta, index, isTimeSampled, time); } template <> inline ModelValue<double> Model::getValue(const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { return getValueAsNumber(path, meta, index, isTimeSampled, time); } template <> inline ModelValue<float> Model::getValue(const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { auto v = getValue<double>(path, meta, index, isTimeSampled, time); return { static_cast<float>(v.value), v.ambiguous }; } template <> inline ModelValue<int32_t> Model::getValue(const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { auto v = getValue<double>(path, meta, index, isTimeSampled, time); return { static_cast<int32_t>(v.value), v.ambiguous }; } template <> inline ModelValue<uint32_t> Model::getValue(const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { auto v = getValue<double>(path, meta, index, isTimeSampled, time); return { static_cast<uint32_t>(v.value), v.ambiguous }; } template <> inline ModelValue<carb::Int2> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<int32_t>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<int32_t>(path, meta, 1, isTimeSampled, time); return { carb::Int2{ v0.value, v1.value }, v0.ambiguous || v1.ambiguous }; } template <> inline ModelValue<carb::Double2> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<double>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<double>(path, meta, 1, isTimeSampled, time); return { carb::Double2{ v0.value, v1.value }, v0.ambiguous || v1.ambiguous }; } template <> inline ModelValue<carb::Double3> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<double>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<double>(path, meta, 1, isTimeSampled, time); auto v2 = getValue<double>(path, meta, 2, isTimeSampled, time); return { carb::Double3{ v0.value, v1.value, v2.value }, v0.ambiguous || v1.ambiguous || v2.ambiguous }; } template <> inline ModelValue<carb::Double4> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<double>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<double>(path, meta, 1, isTimeSampled, time); auto v2 = getValue<double>(path, meta, 2, isTimeSampled, time); auto v3 = getValue<double>(path, meta, 3, isTimeSampled, time); return { carb::Double4{ v0.value, v1.value, v2.value, v3.value }, v0.ambiguous || v1.ambiguous || v2.ambiguous || v3.ambiguous }; } template <> inline ModelValue<carb::ColorRgb> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<float>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<float>(path, meta, 1, isTimeSampled, time); auto v2 = getValue<float>(path, meta, 2, isTimeSampled, time); return { carb::ColorRgb{ v0.value, v1.value, v2.value }, v0.ambiguous || v1.ambiguous || v2.ambiguous }; } template <> inline ModelValue<carb::ColorRgba> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<float>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<float>(path, meta, 1, isTimeSampled, time); auto v2 = getValue<float>(path, meta, 2, isTimeSampled, time); auto v3 = getValue<float>(path, meta, 3, isTimeSampled, time); return { carb::ColorRgba{ v0.value, v1.value, v2.value, v3.value }, v0.ambiguous || v1.ambiguous || v2.ambiguous || v3.ambiguous }; } template <> inline ModelValue<Mat44> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { ModelValue<Mat44> res; res.ambiguous = false; for (size_t i = 0; i < 16; i++) { auto v = getValue<double>(path, meta, i, isTimeSampled, time); *(&res.value.rows[0].x + i) = v.value; res.ambiguous |= v.ambiguous; } return res; } template <> inline void Model::setValue(const char* path, const char* meta, bool value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueBool(path, meta, value, index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, std::string value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueString(path, meta, value, index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, double value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueNumber(path, meta, value, index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, float value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueNumber(path, meta, static_cast<double>(value), index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, int32_t value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueNumber(path, meta, static_cast<double>(value), index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, uint32_t value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueNumber(path, meta, static_cast<double>(value), index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::Int2 value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 2); this->setValue(path, meta, value.x, 0, isTimeSampled, time, info); this->setValue(path, meta, value.y, 1, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::Double2 value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 2, isTimeSampled, time); this->setValue(path, meta, value.x, 0, isTimeSampled, time, info); this->setValue(path, meta, value.y, 1, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::Double3 value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 3, isTimeSampled, time); this->setValue(path, meta, value.x, 0, isTimeSampled, time, info); this->setValue(path, meta, value.y, 1, isTimeSampled, time, info); this->setValue(path, meta, value.z, 2, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::Double4 value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 4, isTimeSampled, time); this->setValue(path, meta, value.x, 0, isTimeSampled, time, info); this->setValue(path, meta, value.y, 1, isTimeSampled, time, info); this->setValue(path, meta, value.z, 2, isTimeSampled, time, info); this->setValue(path, meta, value.w, 3, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::ColorRgb value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 3, isTimeSampled, time); this->setValue(path, meta, value.r, 0, isTimeSampled, time, info); this->setValue(path, meta, value.g, 1, isTimeSampled, time, info); this->setValue(path, meta, value.b, 2, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::ColorRgba value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 4, isTimeSampled, time); this->setValue(path, meta, value.r, 0, isTimeSampled, time, info); this->setValue(path, meta, value.g, 1, isTimeSampled, time, info); this->setValue(path, meta, value.b, 2, isTimeSampled, time, info); this->setValue(path, meta, value.a, 3, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, ui::Mat44 value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 16, isTimeSampled, time); for (size_t i = 0; i < 16; i++) this->setValue(path, meta, *(&value.rows[0].x + i), i, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline ModelNodeType Model::getNodeTypeForT<std::string>() { return ModelNodeType::eString; } template <> inline ModelNodeType Model::getNodeTypeForT<bool>() { return ModelNodeType::eBool; } template <> inline ModelNodeType Model::getNodeTypeForT<double>() { return ModelNodeType::eNumber; } template <> inline ModelNodeType Model::getNodeTypeForT<float>() { return ModelNodeType::eNumber; } template <> inline ModelNodeType Model::getNodeTypeForT<int32_t>() { return ModelNodeType::eNumber; } template <> inline ModelNodeType Model::getNodeTypeForT<uint32_t>() { return ModelNodeType::eNumber; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::Int2>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::Double2>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::Double3>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::Double4>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::ColorRgb>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::ColorRgba>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<Mat44>() { return ModelNodeType::eArray; } // Default Value Model std::unique_ptr<Model> createSimpleValueModel(ModelNodeType valueType); } } }
19,326
C
32.966608
127
0.572441
omniverse-code/kit/include/omni/kit/ui/Menu.h
// Copyright (c) 2019-2020, 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. // #pragma once #include "Widget.h" #include <omni/kit/KitTypes.h> #include <functional> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace carb { namespace imgui { struct ImGui; } } namespace omni { namespace kit { namespace ui { struct MenuItemImpl; enum class MenuEventType : uint32_t { eActivate, }; /** * Menu System allows to register menu items based on path like: "File/Preferences/Foo". * The item can be either a toggle (2 state, with a check) or just a command. * Menu items in the same sub menu a sorted based on priority value. If priority differs more than 10 inbetween items - * separator is added. */ class OMNI_KIT_UI_CLASS_API Menu : public Widget { public: OMNI_KIT_UI_API Menu(); OMNI_KIT_UI_API ~Menu() override; static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Menu); WidgetType getType() override { return kType; } /** * Checks if a menu item is already registered. * * @param menuPath The path to the menu (e.g. "File/Open"). * @return true if it's existed, or false otherwise. */ OMNI_KIT_UI_API bool hasItem(const char* menuPath); /** * Adds a menu item. * * @param menuPath The path to the menu (e.g. "File/Open"). * @param onMenuItemClicked The callback function called when menu item is clicked. * @param toggle If the menu item is a toggle (i.e. checkable). * @param priority Priority of the menu. Menu with smaller priority will be placed at top. If priority differs more * @param toggle value (if toggle). * @param enabled. * @param draw glyph char with origin color defined in svg. * then 10 in between items separator is added. */ OMNI_KIT_UI_API bool addItem(const char* menuPath, const std::function<void(const char* menuPath, bool value)>& onClick, bool toggle, int priority, bool value, bool enabled, bool originSvgColor = false); OMNI_KIT_UI_API void setOnClick(const char* menuPath, const std::function<void(const char* menuPath, bool value)>& onClick); OMNI_KIT_UI_API void setOnRightClick(const char* menuPath, const std::function<void(const char* menuPath, bool value)>& onClick); /** * Removes a menu item. * * @param menuPath The path of the menu item to be removed. */ OMNI_KIT_UI_API void removeItem(const char* menuPath); OMNI_KIT_UI_API size_t getItemCount() const; OMNI_KIT_UI_API std::vector<std::string> getItems() const; /** * Sets the priority of a menu item. * * @param menuPath The path of the menu to set priority. * @param priority The priority to be set to. */ OMNI_KIT_UI_API void setPriority(const char* menuPath, int priority); /** * Sets the hotkey for a menu item. * * @param menuPath The path of the menu to set hotkey to. * @param mod The modifier key flags for the hotkey. * @param key The key for the hotkey. */ OMNI_KIT_UI_API void setHotkey(const char* menuPath, carb::input::KeyboardModifierFlags mod, carb::input::KeyboardInput key); /** * Sets the input action for a menu item. * * @param menuPath The path of the menu to set hotkey to. * @param actionName The action name. */ OMNI_KIT_UI_API void setActionName(const char* menuPath, const char* actionMappingSetPath, const char* actionPath); /** * Sets the toggle value for a menu item. The menu must be a "toggle" when being created. * * @param value The toggle value of the menu item. */ OMNI_KIT_UI_API void setValue(const char* menuPath, bool value); /** * Gets the toggle value for a menu item. The menu must be a "toggle" when being created. * * @return The toggle value of the menu item. */ OMNI_KIT_UI_API bool getValue(const char* menuPath) const; /** * Sets the enabled state of a menu item. * * @param menuPath The path of the menu to set enabled state to. * @param enabled true to enabled the menu. false to disable it. */ OMNI_KIT_UI_API void setEnabled(const char* menuPath, bool value); /** * For non "toggle" menu items, invoke the onClick function handler * * @param menuPath The path of the menu to activate. */ OMNI_KIT_UI_API void executeOnClick(const char* menuPath); void draw(float elapsedTime) override; private: void _update(float elapsedTime); std::unique_ptr<MenuItemImpl> m_root; std::unordered_map<std::string, MenuItemImpl*> m_pathToMenu; carb::events::ISubscriptionPtr m_updateEvtSub; bool m_needUpdate = false; carb::input::Keyboard* m_keyboard = nullptr; bool m_warning_silence = false; }; // Temporary hook up to the Editor main menu bar OMNI_KIT_UI_API std::shared_ptr<Menu> getEditorMainMenu(); // Temporary hook to enable scripting a menu item via python OMNI_KIT_UI_API void activateMenuItem(const char* menuPath); } } }
5,785
C
29.452631
119
0.638894
omniverse-code/kit/include/omni/kit/ui/UI.h
// Copyright (c) 2019-2020, 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. // #pragma once #include "BroadcastModel.h" #include "Button.h" #include "CheckBox.h" #include "CollapsingFrame.h" #include "Color.h" #include "ColumnLayout.h" #include "ComboBox.h" #include "ContentWindow.h" #include "Drag.h" #include "Field.h" #include "FilePicker.h" #include "Image.h" #include "Label.h" #include "Library.h" #include "ListBox.h" #include "Menu.h" #include "Model.h" #include "ModelMeta.h" #include "Popup.h" #include "ProgressBar.h" #include "RowColumnLayout.h" #include "RowLayout.h" #include "ScalarXYZ.h" #include "ScalarXYZW.h" #include "ScrollingFrame.h" #include "Separator.h" #include "SimpleTreeView.h" #include "Slider.h" #include "Spacer.h" #include "TextBox.h" #include "Transform.h" #include "ViewCollapsing.h" #include "Window.h"
1,202
C
26.340908
77
0.757072
omniverse-code/kit/include/omni/kit/ui/Widget.h
// Copyright (c) 2019-2020, 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. // #pragma once #include "Api.h" #include "Common.h" #include <carb/Defines.h> #include <omni/ui/Font.h> #include <omni/ui/IGlyphManager.h> #include <functional> #include <memory> #include <string> namespace omni { namespace kit { namespace ui { class Container; class Window; typedef uint64_t WidgetType; /** * Parent this class it to asscoiate your own data with a Widget. */ class WidgetUserData { public: virtual ~WidgetUserData() = default; }; /** * Defines a widget. */ class OMNI_KIT_UI_CLASS_API Widget : public std::enable_shared_from_this<Widget> { friend class Container; friend class Window; public: /** * Constructor. */ OMNI_KIT_UI_API Widget(); /** * Destructor. */ OMNI_KIT_UI_API virtual ~Widget(); /** * Determines if the widget is enabled. * * @return true if the widget is enabled, false if disabled. */ OMNI_KIT_UI_API bool isEnabled() const; /** * Set the widget to enabled. */ OMNI_KIT_UI_API void setEnabled(bool enable); /** * Gets the layout this widget is within. * * A nullptr indicates the widget is not in a layout but directly in window. * * @return The layout this widget is within. */ OMNI_KIT_UI_API Container* getLayout() const; /** * Gets the type of widget. * * @return The type of widget. */ OMNI_KIT_UI_API virtual WidgetType getType() = 0; /** * Draws the widget. * * @param elapsedTime The time elapsed (in seconds) */ OMNI_KIT_UI_API virtual void draw(float elapsedTime) = 0; /** * set the font * * @param font The font to use */ OMNI_KIT_UI_API void setFontStyle(omni::ui::FontStyle fontStyle); /** * get the font * * @return The font in use */ OMNI_KIT_UI_API omni::ui::FontStyle getFontStyle() const; /** * Get the font size (height in pixels) of the current font style with the current scaling applied. * * @return The font size. */ OMNI_KIT_UI_API float getFontSize() const; /** * Sets the callback function when the widget recieves a dragdrop payload * * @param fn The callback function when the widget recieves a dragdrop payload * @param payloadName the name of acceptable payload */ OMNI_KIT_UI_API void setDragDropFn(const std::function<void(WidgetRef, const char*)>& fn, const char* payloadName); /** * Sets the callback function when the widget is dragged. * * @param fn The callback function when the widget is dragged. */ void setDraggingFn(const std::function<void(WidgetRef, DraggingType)>& fn) { m_draggedFn = fn; } /** * A way to associate arbitrary user data with it. */ std::shared_ptr<WidgetUserData> userData; /** * Determines if the widget is visible. * * @return true if the widget is visible, false if hidden. */ OMNI_KIT_UI_API bool isVisible() const; /** * Set the widget visibility state. */ OMNI_KIT_UI_API void setVisible(bool visible); Length width = Pixel(0); Length height = Pixel(0); static constexpr size_t kUniqueIdSize = 4; protected: bool m_enabled = true; bool m_visible = true; bool m_isDragging; Container* m_layout = nullptr; char m_uniqueId[kUniqueIdSize + 1]; std::string m_label; omni::ui::FontStyle m_fontStyle; carb::imgui::Font* m_font; std::function<void(WidgetRef, const char*)> m_dragDropFn; std::function<void(WidgetRef, DraggingType)> m_draggedFn; std::string m_dragDropPayloadName; }; } } }
4,127
C
22.191011
119
0.642113
omniverse-code/kit/include/omni/kit/ui/NativeFileDialog.h
// Copyright (c) 2019-2020, 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. // #pragma once #include <carb/extras/Unicode.h> #include <carb/logging/Log.h> #include <string> #include <utility> #include <vector> #if CARB_PLATFORM_WINDOWS # ifndef NOMINMAX # define NOMINMAX # endif # include <ShObjIdl_core.h> #endif #ifdef _MSC_VER # pragma warning(disable : 4996) #endif namespace omni { namespace kit { namespace ui { /** * Defines an NativeFileDialog class that handles file/folder selection using OS specific implementation. */ class NativeFileDialog { public: enum class Mode { eOpen, ///! OpenFileDialog. eSave, ///! SaveFileDialog. }; enum class Type { eFile, ///! Select file. eDirectory, ///! Select directory. }; /** * Constructor. * * @param mode Open or Save dialog. * @param type Choose File or Directory. * @param title Title text. * @param multiSelction If supporting selecting more than one file/directory. */ NativeFileDialog(Mode mode, Type type, const std::string& title, bool multiSelection); /** * Add file type filter. * * @param name Name of the file type. * @param spec Specification of the file type. */ void addFilter(const std::string& name, const std::string& spec); /** * Shows the open file dialog. */ bool show(); /** * Gets the selected path(s). * * @param urls The vector to write selected path(s) to. * @return True if the result is valid. */ bool getFileUrls(std::vector<std::string>& urls) const; private: struct FileTypeFilter { std::string name; std::string spec; }; Mode m_mode; Type m_type; std::string m_title; std::vector<FileTypeFilter> m_filters; std::vector<std::string> m_fileUrls; bool m_multiSel; }; inline NativeFileDialog::NativeFileDialog(Mode mode, Type type, const std::string& title, bool multiSelection) : m_mode(mode), m_type(type), m_title(title), m_multiSel(multiSelection) { } inline void NativeFileDialog::addFilter(const std::string& name, const std::string& spec) { m_filters.emplace_back(FileTypeFilter{ name, spec }); } inline bool NativeFileDialog::show() { bool ret = false; #if CARB_PLATFORM_WINDOWS auto prepareDialogCommon = [this](::IFileDialog* fileDialog, std::vector<std::wstring>& wstrs) { // Set filters std::vector<COMDLG_FILTERSPEC> rgFilterSpec; rgFilterSpec.reserve(m_filters.size()); wstrs.reserve(m_filters.size() * 2); for (auto& filter : m_filters) { wstrs.push_back(carb::extras::convertUtf8ToWide(filter.name)); std::wstring& nameWstr = wstrs.back(); wstrs.push_back(carb::extras::convertUtf8ToWide(filter.spec)); std::wstring& specWstr = wstrs.back(); rgFilterSpec.emplace_back(COMDLG_FILTERSPEC{ nameWstr.c_str(), specWstr.c_str() }); } fileDialog->SetFileTypes(static_cast<UINT>(rgFilterSpec.size()), rgFilterSpec.data()); std::wstring title = carb::extras::convertUtf8ToWide(m_title); fileDialog->SetTitle(title.c_str()); }; switch (m_mode) { case Mode::eOpen: { IFileOpenDialog* fileDialog; auto hr = CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&fileDialog)); if (SUCCEEDED(hr)) { DWORD options; fileDialog->GetOptions(&options); if (m_multiSel) { options |= OFN_ALLOWMULTISELECT; } if (m_type == Type::eDirectory) { options |= FOS_PICKFOLDERS; } fileDialog->SetOptions(options); std::vector<std::wstring> wstrs; // keep a reference of the converted string around prepareDialogCommon(fileDialog, wstrs); hr = fileDialog->Show(nullptr); if (SUCCEEDED(hr)) { IShellItemArray* pItemArray; hr = fileDialog->GetResults(&pItemArray); if (SUCCEEDED(hr)) { DWORD dwNumItems = 0; pItemArray->GetCount(&dwNumItems); for (DWORD i = 0; i < dwNumItems; i++) { IShellItem* pItem = nullptr; hr = pItemArray->GetItemAt(i, &pItem); if (SUCCEEDED(hr)) { PWSTR pszFilePath; hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath); if (SUCCEEDED(hr)) { std::string path = carb::extras::convertWideToUtf8(pszFilePath); m_fileUrls.emplace_back(std::move(path)); CoTaskMemFree(pszFilePath); } pItem->Release(); } } ret = true; pItemArray->Release(); } } fileDialog->Release(); } break; } case Mode::eSave: { IFileSaveDialog* fileDialog; auto hr = CoCreateInstance(CLSID_FileSaveDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&fileDialog)); if (SUCCEEDED(hr)) { std::vector<std::wstring> wstrs; // keep a reference of the converted string around prepareDialogCommon(fileDialog, wstrs); fileDialog->SetFileName(L"Untitled"); hr = fileDialog->Show(nullptr); if (SUCCEEDED(hr)) { IShellItem* pItem = nullptr; hr = fileDialog->GetResult(&pItem); if (SUCCEEDED(hr)) { PWSTR pszFilePath; hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath); if (SUCCEEDED(hr)) { std::string path = carb::extras::convertWideToUtf8(pszFilePath); UINT fileTypeIndex; hr = fileDialog->GetFileTypeIndex(&fileTypeIndex); fileTypeIndex--; // One based index. Convert it to zero based if (SUCCEEDED(hr)) { std::string& fileType = m_filters[fileTypeIndex].spec; size_t extPos = path.rfind(".stage.usd"); path = path.substr(0, extPos) + fileType.substr(1); m_fileUrls.emplace_back(std::move(path)); } CoTaskMemFree(pszFilePath); } pItem->Release(); ret = true; } } fileDialog->Release(); } break; } } #endif return ret; } inline bool NativeFileDialog::getFileUrls(std::vector<std::string>& urls) const { if (m_fileUrls.size()) { urls = m_fileUrls; return true; } return false; } } } }
7,695
C
29.0625
115
0.540481
omniverse-code/kit/include/omni/kit/ui/ComboBox.h
// Copyright (c) 2019-2020, 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. // #pragma once #include "ValueWidget.h" #include <string> #include <vector> namespace omni { namespace kit { namespace ui { /** * Defines a combo box. */ template <class T> class OMNI_KIT_UI_CLASS_API ComboBox : public SimpleValueWidget<T> { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ComboBox<T>); OMNI_KIT_UI_API explicit ComboBox(const char* text, const std::vector<T>& items = {}, const std::vector<std::string>& displayNames = {}); OMNI_KIT_UI_API ~ComboBox() override; OMNI_KIT_UI_API size_t getItemCount() const; OMNI_KIT_UI_API const T& getItemAt(size_t index) const; OMNI_KIT_UI_API void addItem(const T& item, const std::string& displayName = ""); OMNI_KIT_UI_API void removeItem(size_t index); OMNI_KIT_UI_API void clearItems(); OMNI_KIT_UI_API void setItems(const std::vector<T>& items, const std::vector<std::string>& displayNames = {}); OMNI_KIT_UI_API int64_t getSelectedIndex() const; OMNI_KIT_UI_API void setSelectedIndex(int64_t index); OMNI_KIT_UI_API WidgetType getType() override; protected: virtual bool _isTransientChangeSupported() const override { return false; } bool _drawImGuiWidget(carb::imgui::ImGui* imgui, T& value) override; private: struct Element { T value; std::string displayName; }; std::vector<Element> m_items; int64_t m_selectedIndex = -1; }; using ComboBoxString = ComboBox<std::string>; using ComboBoxInt = ComboBox<int>; } } }
2,044
C
23.939024
114
0.674658
omniverse-code/kit/include/omni/kit/ui/FilterGroupWidget.h
// Copyright (c) 2019-2020, 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. // #include <omni/kit/FilterGroup.h> #include <omni/kit/ui/ColorScheme.h> #include <omni/ui/IGlyphManager.h> namespace omni { namespace kit { namespace ui { template <typename FilterGroupT> class FilterGroupWidget { public: explicit FilterGroupWidget(FilterGroupT& filterGroup) : m_filterGroup(filterGroup) { m_glyphManager = carb::getFramework()->acquireInterface<omni::ui::IGlyphManager>(); } void draw(carb::imgui::ImGui* imgui, float elapsedTime) { using namespace carb::imgui; const float kFontSize = imgui->getFontSize(); const carb::Float2 kItemSpacing = imgui->getStyle()->itemSpacing; bool filterEnabled = m_filterGroup.isFilterGroupEnabled(); if (filterEnabled) { imgui->pushStyleColor(StyleColor::eText, kAssetExplorerFilterIconEnabledColor); } auto filterGlyph = m_glyphManager->getGlyphInfo("${glyphs}/filter.svg"); bool filterIconClicked = imgui->selectable(filterGlyph.code, false, 0, { kFontSize, kFontSize }); if (filterEnabled) { imgui->popStyleColor(); } // (RMB / hold LMB / Click LMB & No filter is enabled) to open filter list bool showFilterList = imgui->isItemClicked(1) || (imgui->isItemClicked(0) && !m_filterGroup.isAnyFilterEnabled()); m_mouseHeldOnFilterIconTime += elapsedTime; if (!(imgui->isItemHovered(0) && imgui->isMouseDown(0))) { m_mouseHeldOnFilterIconTime = 0.f; } const float kMouseHoldTime = 0.3f; if (showFilterList || m_mouseHeldOnFilterIconTime >= kMouseHoldTime) { imgui->openPopup("FilterList"); } else { if (filterIconClicked) { m_filterGroup.setFilterGroupEnabled(!filterEnabled); } } if (imgui->beginPopup("FilterList", 0)) { imgui->text("Filter"); imgui->sameLineEx(0.f, kFontSize * 3); imgui->textColored(kAssetExplorerClearFilterColor, "Clear Filters"); bool clearFilters = imgui->isItemClicked(0); imgui->separator(); std::vector<std::string> filterNames; m_filterGroup.getFilterNames(filterNames); for (auto& name : filterNames) { if (clearFilters) { m_filterGroup.setFilterEnabled(name, false); } bool enabled = m_filterGroup.isFilterEnabled(name); imgui->pushIdString(name.c_str()); auto checkGlyph = enabled ? m_glyphManager->getGlyphInfo("${glyphs}/check_square.svg") : m_glyphManager->getGlyphInfo("${glyphs}/square.svg"); if (imgui->selectable((std::string(checkGlyph.code) + " ").c_str(), false, kSelectableFlagDontClosePopups, { 0.f, 0.f })) { m_filterGroup.setFilterEnabled(name, !enabled); } imgui->popId(); imgui->sameLine(); imgui->text(name.c_str()); } imgui->endPopup(); } // Draw the tiny triangle at corner of the filter icon { imgui->sameLine(); auto cursorPos = imgui->getCursorScreenPos(); auto drawList = imgui->getWindowDrawList(); carb::Float2 points[3]; points[0] = { cursorPos.x - kItemSpacing.x, cursorPos.y + kFontSize * 0.75f + kItemSpacing.y * 0.5f }; points[1] = { cursorPos.x - kItemSpacing.x, cursorPos.y + kFontSize + kItemSpacing.y * 0.5f }; points[2] = { cursorPos.x - kItemSpacing.x - kFontSize * 0.25f, cursorPos.y + kFontSize + kItemSpacing.y * 0.5f }; imgui->addTriangleFilled( drawList, points[0], points[1], points[2], imgui->getColorU32StyleColor(StyleColor::eText, 1.f)); imgui->newLine(); } } private: FilterGroupT& m_filterGroup; omni::ui::IGlyphManager* m_glyphManager = nullptr; float m_mouseHeldOnFilterIconTime = 0.f; }; } } }
4,671
C
34.938461
122
0.588739
omniverse-code/kit/include/omni/kit/ui/SimpleTreeView.h
// Copyright (c) 2019-2020, 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. // #pragma once #include "Widget.h" #include <functional> #include <memory> #include <string> namespace omni { namespace kit { namespace ui { /** * Defines a SimpleTreeView. */ class OMNI_KIT_UI_CLASS_API SimpleTreeView : public Widget { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::SimpleTreeView); /** * Constructor. * * @param treeData A list of strings to construct the data of the TreeView * @param separator */ OMNI_KIT_UI_API explicit SimpleTreeView(const std::vector<std::string>& treeData, char separator = '/'); /** * Destructor. */ OMNI_KIT_UI_API ~SimpleTreeView() override; /** * Gets the text of the treeNode. * * @return The text of the treeNode. */ OMNI_KIT_UI_API const std::string getSelectedItemName() const; /** * Clears the currently selected tree node */ OMNI_KIT_UI_API void clearSelection(); /** * Sets the text of the tree nodes. * * @param text The text of the tree nodes. */ OMNI_KIT_UI_API void setTreeData(const std::vector<std::string>& treeData); /** * Sets the callback function when any tree node is clicked. * * fn The callback function when any tree node is clicked. */ OMNI_KIT_UI_API void setClickedFn(const std::function<void(WidgetRef)>& fn); /** * @see Widget::getType */ OMNI_KIT_UI_API WidgetType getType() override; /** * @see Widget::draw */ void draw(float elapsedTime) override; protected: // Clicked Function callback std::function<void(WidgetRef)> m_clickedFn; protected: struct TreeDataNode; using TreeDataNodePtr = std::shared_ptr<TreeDataNode>; // An internal structure to accomodate the Hierachical tree data struct TreeDataNode : public std::enable_shared_from_this<TreeDataNode> { // The text of the current node std::string m_text; // Pointer to the parent node std::weak_ptr<TreeDataNode> m_parentNode; // List of child nodes std::vector<TreeDataNodePtr> m_children; // Single Node's constructor/destructor explicit TreeDataNode(const std::string& data); ~TreeDataNode(); // Helper functions // Add a child TreeDataNodePtr& addChild(TreeDataNodePtr& node); // Recursively delete all childrens(decendents) void deleteChildren(); // Stack up the node text to construct the full path from root to the current node const std::string getFullPath(const char& separator) const; }; // The root node of the entire tree TreeDataNodePtr m_rootNode; // Pointer to the currently selected Node, for the rendering purpose std::weak_ptr<TreeDataNode> m_selectedNode; // A customized separator, default as '/' char m_separator; protected: // Helper function to build the entire data tree, return false if build fail bool buildDataTree(const std::vector<std::string>& inputStrings); // Helper function to split the string into a list of string tokens // example, "root/parent/child" ==> ["root","parent","child"] std::vector<std::string> split(const std::string& s, char seperator); // A core function to hierachically, node as the root, visualize the tree data using into the SimpleTreeView void drawTreeNode(carb::imgui::ImGui* imgui, const std::shared_ptr<SimpleTreeView::TreeDataNode>& node); }; } } }
3,948
C
27.007092
112
0.6692
omniverse-code/kit/include/omni/kit/ui/ScalarXYZW.h
// Copyright (c) 2019-2020, 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. // #pragma once #include "Image.h" #include "ScalarXYZ.h" #include "ValueWidget.h" namespace omni { namespace kit { namespace ui { /** * Defines a ScalarXYZW widget. */ class OMNI_KIT_UI_CLASS_API ScalarXYZW : public ValueWidget<carb::Double4> { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ScalarXYZW); /** * Constructor. * */ OMNI_KIT_UI_API ScalarXYZW( const char* displayFormat, float speed, float wrapValue, float minValue, float maxValue, carb::Double4 value = {}); /** * Destructor. */ OMNI_KIT_UI_API ~ScalarXYZW(); /** * @see Widget::getType */ OMNI_KIT_UI_API WidgetType getType() override; void draw(float elapsedTime) override; private: std::shared_ptr<ScalarXYZ> m_scalar; bool m_edited; bool m_init; }; } } }
1,282
C
21.508772
123
0.690328
omniverse-code/kit/include/omni/kit/ui/ListBox.h
// Copyright (c) 2019-2020, 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. // #pragma once #include "Label.h" #include <functional> #include <string> #include <utility> #include <vector> namespace omni { namespace kit { namespace ui { /** * Defines a list box. */ class OMNI_KIT_UI_CLASS_API ListBox : public Label { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ListBox); OMNI_KIT_UI_API explicit ListBox(const char* text, bool multiSelect = true, int visibleItemCount = -1, const std::vector<std::string>& items = {}); OMNI_KIT_UI_API ~ListBox() override; OMNI_KIT_UI_API bool isMultiSelect() const; OMNI_KIT_UI_API void setMultiSelect(bool multiSelect); OMNI_KIT_UI_API int getItemHeightCount() const; OMNI_KIT_UI_API void setItemHeightCount(int itemHeightCount); OMNI_KIT_UI_API size_t getItemCount() const; OMNI_KIT_UI_API const char* getItemAt(size_t index) const; OMNI_KIT_UI_API void addItem(const char* item); OMNI_KIT_UI_API void removeItem(size_t index); OMNI_KIT_UI_API void clearItems(); OMNI_KIT_UI_API std::vector<int> getSelected() const; OMNI_KIT_UI_API void setSelected(int index, bool selected); OMNI_KIT_UI_API void clearSelection(); OMNI_KIT_UI_API void setSelectionChangedFn(const std::function<void(WidgetRef)>& fn); OMNI_KIT_UI_API WidgetType getType() override; void draw(float elapsedTime) override; private: int m_itemHeightCount = -1; bool m_multiSelect = false; int m_selectedIndex = -1; std::vector<std::pair<std::string, bool>> m_items; std::function<void(WidgetRef)> m_selectionChangedFn; }; } } }
2,144
C
25.481481
89
0.680504
omniverse-code/kit/include/omni/kit/ui/ScalarXYZ.h
// Copyright (c) 2019-2020, 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. // #pragma once #include "Image.h" #include "ValueWidget.h" namespace omni { namespace kit { namespace ui { /** * Defines a ScalarXYZ widget. */ class OMNI_KIT_UI_CLASS_API ScalarXYZ : public ValueWidget<carb::Double3> { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ScalarXYZ); OMNI_KIT_UI_API ScalarXYZ(const char* displayFormat, float speed, double wrapValue, double minValue, double maxValue, double deadZone = 0.0, carb::Double3 value = {}); OMNI_KIT_UI_API ~ScalarXYZ(); /** * @see Widget::getType */ OMNI_KIT_UI_API WidgetType getType() override; /** * Draws the scalar, used for drawing when allocated by other classes * * @param v x,y,z to draw * @return true if dirty */ OMNI_KIT_UI_API bool drawScalar(carb::Double3& v, bool& afterEdit, bool hasX = true, bool hasY = true, bool hasZ = true); OMNI_KIT_UI_API double wrapScalar(double value) const; OMNI_KIT_UI_API double deadzoneScalar(double value) const; std::string displayFormat; float dragSpeed; double wrapValue; double deadZone; double minVal; double maxVal; void draw(float elapsedTime) override; void setSkipYposUpdate(bool skip) { m_skipYposUpdate = skip; } private: enum class Images { eX, eY, eZ, eCount }; std::shared_ptr<Image> m_images[static_cast<size_t>(Images::eCount)]; std::string m_labelY; std::string m_labelZ; bool m_skipYposUpdate = false; const char* m_filenames[static_cast<size_t>(Images::eCount)] = { "/resources/icons/transform_x.png", "/resources/icons/transform_y.png", "/resources/icons/transform_z.png" }; }; } } }
2,487
C
26.340659
125
0.593888
omniverse-code/kit/include/omni/kit/usd/layers/LayerTypes.h
// 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. // #pragma once #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> #include <carb/events/IEvents.h> namespace omni { namespace kit { namespace usd { namespace layers { /** * Regards of edit mode, it's extended by Kit to support customized workflow. * USD supports to switch edit target so that all authoring will take place in * that layer. When it's working with multiple sublayers, this kind of freedom * may cause experience issues. User has to be aware the changes he/she made are * not overrided in any stronger layer. We extend a new mode called "auto authoring" * is to improve this. In this mode, all changes will firstly go into a middle delegate * layer and it will distribute them into their corresponding layers where it has the strongest * opinions. So it cannot switch edit target freely, and user does not need to be * aware of existence of multi-sublayers and how USD will compose the changes. * Besides, there is one more extended mode called "spec linking", which is based on * auto authoring. In this mode, user can customize the target layer of specific specs. */ enum class LayerEditMode { eNormal, // Normal USD mode that user can freely switch edit target and creates deltas. eAutoAuthoring, // Auto authoring mode that user cannot switch authoring layer freely. And all // deltas will be merged to its original layer where the prim specs have strongest opinions. // @see IWorkflowAutoAuthoring for interfaces about auto authoring. eSpecsLinking, // Spec linking mode will support to link specified spec changes into specific layers, // including forwarding changes of whole prim, or specific group of attributes. }; enum class LayerEventType { eInfoChanged, // Layer info changed, which includes: // PXR_NS::UsdGeomTokens->upAxis PXR_NS::UsdGeomTokens->metersPerUnit // PXR_NS::SdfFieldKeys->StartTimeCode PXR_NS::SdfFieldKeys->EndTimeCode // PXR_NS::SdfFieldKeys->FramesPerSecond PXR_NS::SdfFieldKeys->TimeCodesPerSecond // PXR_NS::SdfFieldKeys->SubLayerOffsets PXR_NS::SdfFieldKeys->Comment // PXR_NS::SdfFieldKeys->Documentation eMutenessScopeChanged, // For vallina USD, muteness is only local and not persistent. Omniverse extends // it so it could be persistent and sharable with other users. The muteness scope // is a concept about this that supports to switch between local and global scope. // In local scope, muteness will not be persistent In contract, global scope will // save muteness across sessions. This event is to notify change of muteness scope. eMutenessStateChanged, // Change of muteness state. eLockStateChanged, // Change of lock state. Lock is a customized concept in Omniverse that supports to // lock a layer it's not editable and savable. eDirtyStateChanged, // Change of dirtiness state. eOutdateStateChanged, // Change of outdate state. This is only emitted for layer in Nucleus when layer content // is out of sync with server one. ePrimSpecsChanged, // Change of layer. It will be emitted along with changed paths of prim specs. eSublayersChanged, // Change of sublayers. eSpecsLockingChanged, // Change of lock states of specs. It will be emitted along with the changed paths. eSpecsLinkingChanged, // Change of linking states of specs. It will be emitted along with the changed paths. eEditTargetChanged, // Change of edit target. eEditModeChanged, // Change of edit mode. @see LayerEditMode for details. eDefaultLayerChanged, // Change default layer. Default layer is an extended concept that's only available in auto // authornig mode. It's to host all new created prims from auto authoring layer. eLiveSessionStateChanged, // Live session started or stopped eLiveSessionListChanged, // List of live sessions refreshed, which may because of a session is created or removed. eLiveSessionUserJoined, // User joined. eLiveSessionUserLeft, // User left. eLiveSessionMergeStarted, // Starting to merge live session. eLiveSessionMergeEnded, // Finished to merge live session. eUsedLayersChanged, // Used layers changed in stage. Used layers includes all sublayers, references, payloads or any external layers loaded into stage. // If eSublayersChanged is sent, this event will be sent also. eLiveSessionJoining, // The event will be sent before Live Session is joined. eLayerFilePermissionChanged, // The event will be sent when file write/read permission is changed. }; enum class LayerErrorType { eSuccess, eReadOnly, // Destination folder or file is read-only eNotFound, // File/folder/live session is not found, or layer is not in the local layer stack. eAlreadyExists, // File/folder/layer/live session already existes. eInvalidStage, // No stage is attached to the UsdContext. eInvalidParam, // Invalid param passed to API. eLiveSessionInvalid, // The live session does not match the base layer. Or The live session exists, // but it is broken on disk, for example, toml file is corrupted. eLiveSessionVersionMismatch, eLiveSessionBaseLayerMismatch, // The base layer of thie live session does not match the specified one. // It's normally because user wants to join session of layer B for layer A. eLiveSessionAlreadyJoined, eLiveSessionNoMergePermission, eLiveSessionNotSupported, // Live session is not supported for the layer if layer is not in Nucleus or already has .live as extension. // Or it's reported for joining a live session for a reference or payload prim if prim is invalid, or it has // no references or payloads. eLiveSessionNotJoined, eUnkonwn }; class ILayersInstance : public carb::IObject { public: virtual carb::events::IEventStream* getEventStream() const = 0; virtual LayerEditMode getEditMode() const = 0; virtual void setEditMode(LayerEditMode editMode) = 0; virtual LayerErrorType getLastErrorType() const = 0; virtual const char* getLastErrorString() const = 0; }; } } } }
7,077
C
45.565789
160
0.693232
omniverse-code/kit/include/omni/kit/usd/layers/IWorkflowSpecsLocking.h
// 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. // #pragma once #include "LayerTypes.h" #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> namespace omni { namespace kit { namespace usd { namespace layers { struct IWorkflowSpecsLocking { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::IWorkflowSpecsLocking", 1, 0) carb::dictionary::Item*(CARB_ABI* lockSpec)(ILayersInstance* layersIntance, const char* specPath, bool hierarchy); carb::dictionary::Item*(CARB_ABI* unlockSpec)(ILayersInstance* layersIntance, const char* specPath, bool hierarchy); void(CARB_ABI* unlockAllSpecs)(ILayersInstance* layersIntance); bool(CARB_ABI* isSpecLocked)(ILayersInstance* layersInstance, const char* specPath); carb::dictionary::Item*(CARB_ABI* getAllLockedSpecs)(ILayersInstance* layersIntance); }; } } } }
1,230
C
25.760869
120
0.765041
omniverse-code/kit/include/omni/kit/usd/layers/IWorkflowAutoAuthoring.h
// 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. // #pragma once #include "LayerTypes.h" #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> namespace omni { namespace kit { namespace usd { namespace layers { struct IWorkflowAutoAuthoring { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::IWorkflowAutoAuthoring", 1, 0) bool(CARB_ABI* isEnabled)(ILayersInstance* layersIntance); void(CARB_ABI* suspend)(ILayersInstance* layersIntance); void(CARB_ABI* resume)(ILayersInstance* layersIntance); void(CARB_ABI* setDefaultLayer)(ILayersInstance* layersIntance, const char* layerIdentifier); const char*(CARB_ABI* getDefaultLayer)(ILayersInstance* layersIntance); bool(CARB_ABI* isAutoAuthoringLayer)(ILayersInstance* layersIntance, const char* layerIdentifier); }; } } } }
1,207
C
24.166666
102
0.767191
omniverse-code/kit/include/omni/kit/usd/layers/LayersHelper.hpp
// Copyright (c) 2019-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. // #pragma once // clang-format off #include "UsdPCH.h" // clang-format on #include <omni/kit/usd/layers/ILayers.h> #include <omni/usd/UsdContext.h> #if defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif namespace omni { namespace kit { namespace usd { namespace layers { namespace internal { static carb::dictionary::IDictionary* getDictInterface() { static auto staticInterface = carb::getCachedInterface<carb::dictionary::IDictionary>(); return staticInterface; } } static ILayers* getLayersInterface() { static auto staticInterface = carb::getCachedInterface<omni::kit::usd::layers::ILayers>(); return staticInterface; } static ILayersState* getLayersStateInterface() { static auto staticInterface = carb::getCachedInterface<omni::kit::usd::layers::ILayersState>(); return staticInterface; } static IWorkflowAutoAuthoring* getAutoAuthoringInterface() { static auto staticInterface = carb::getCachedInterface<omni::kit::usd::layers::IWorkflowAutoAuthoring>(); return staticInterface; } static IWorkflowLiveSyncing* getLiveSyncingInterface() { static auto staticInterface = carb::getCachedInterface<omni::kit::usd::layers::IWorkflowLiveSyncing>(); return staticInterface; } static IWorkflowSpecsLocking* getSpecsLockingInterface() { static auto staticInterface = carb::getCachedInterface<omni::kit::usd::layers::IWorkflowSpecsLocking>(); return staticInterface; } static ILayersInstance* getLayersInstanceByName(const std::string& name) { auto layers = getLayersInterface(); return layers->getLayersInstanceByName(name.c_str()); } static ILayersInstance* getLayersInstanceByUsdContext(omni::usd::UsdContext* usdContext) { auto layers = getLayersInterface(); return layers->getLayersInstanceByContext(usdContext); } static carb::events::IEventStream* getEventStream(omni::usd::UsdContext* usdContext) { auto layerInstance = getLayersInstanceByUsdContext(usdContext); return layerInstance->getEventStream(); } static LayerEditMode getEditMode(omni::usd::UsdContext* usdContext) { auto layerInstance = getLayersInstanceByUsdContext(usdContext); return layerInstance->getEditMode(); } static void setEditMode(omni::usd::UsdContext* usdContext, LayerEditMode editMode) { auto layerInstance = getLayersInstanceByUsdContext(usdContext); layerInstance->setEditMode(editMode); } static std::vector<std::string> getLocalLayerIdentifiers( omni::usd::UsdContext* usdContext, bool includeSessionLayer = true, bool includeAnonymous = true, bool includeInvalid = true) { std::vector<std::string> layerIdentifiers; auto layerInstance = getLayersInstanceByUsdContext(usdContext); auto layersState = getLayersStateInterface(); auto item = layersState->getLocalLayerIdentifiers(layerInstance, includeSessionLayer, includeAnonymous, includeInvalid); if (item) { auto dict = internal::getDictInterface(); size_t length = dict->getArrayLength(item); for (size_t i = 0; i < length; i++) { layerIdentifiers.push_back(dict->getStringBufferAt(item, i)); } dict->destroyItem(item); } return layerIdentifiers; } static std::vector<std::string> getDirtyLayerIdentifiers(omni::usd::UsdContext* usdContext) { std::vector<std::string> layerIdentifiers; auto layerInstance = getLayersInstanceByUsdContext(usdContext); auto layersState = getLayersStateInterface(); auto item = layersState->getDirtyLayerIdentifiers(layerInstance); if (item) { auto dict = internal::getDictInterface(); size_t length = dict->getArrayLength(item); for (size_t i = 0; i < length; i++) { layerIdentifiers.push_back(dict->getStringBufferAt(item, i)); } dict->destroyItem(item); } return layerIdentifiers; } static std::string getLayerName(omni::usd::UsdContext* usdContext, const std::string& layerIdentifier) { std::vector<std::string> layerIdentifiers; auto layerInstance = getLayersInstanceByUsdContext(usdContext); auto layersState = getLayersStateInterface(); const std::string& name = layersState->getLayerName(layerInstance, layerIdentifier.c_str()); if (name.empty()) { if (PXR_NS::SdfLayer::IsAnonymousLayerIdentifier(layerIdentifier)) { return layerIdentifier; } else { return PXR_NS::SdfLayer::GetDisplayNameFromIdentifier(layerIdentifier); } } else { return name; } } static void suspendAutoAuthoring(omni::usd::UsdContext* usdContext) { auto autoAuthoring = getAutoAuthoringInterface(); auto layerInstance = getLayersInstanceByUsdContext(usdContext); autoAuthoring->suspend(layerInstance); } static void resumeAutoAuthoring(omni::usd::UsdContext* usdContext) { auto autoAuthoring = getAutoAuthoringInterface(); auto layerInstance = getLayersInstanceByUsdContext(usdContext); autoAuthoring->resume(layerInstance); } static std::string getDefaultLayerIdentifier(omni::usd::UsdContext* usdContext) { auto autoAuthoring = getAutoAuthoringInterface(); auto layerInstance = getLayersInstanceByUsdContext(usdContext); return autoAuthoring->getDefaultLayer(layerInstance); } } } } } #if defined(__GNUC__) # pragma GCC diagnostic pop #endif
5,871
C++
26.568075
124
0.731903
omniverse-code/kit/include/omni/kit/usd/layers/ILayersState.h
// 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. // #pragma once #include "LayerTypes.h" #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> namespace omni { namespace kit { namespace usd { namespace layers { /** * ILayersState works for managing all layers states of the corresponding stage. Not all layer states can be queried through ILayersState, * but only those ones that are not easily accessed from USD APIs or extended in Omniverse. All the following interfaces work for the used * layers in the bound UsdContext. */ struct ILayersState { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::ILayersState", 1, 1) // Gets all sublayers rooted from root layer, or session layer if includeSessionLayer is true. It's sorted from // strongest to weakest. If includeAnonymous is false, it will exclude anonymous ones. If includeInvalid is true, it // will include invalid sublayers. Invalid sublayers are those ones that in the layers list but its layer handle // cannot be found. carb::dictionary::Item*(CARB_ABI* getLocalLayerIdentifiers)(ILayersInstance* layerInstance, bool includeSessionLayer, bool includeAnonymous, bool includeInvalid); // Gets all dirty used layers excluding anonymous ones. carb::dictionary::Item*(CARB_ABI* getDirtyLayerIdentifiers)(ILayersInstance* layerInstance); /** * Muteness scope is a concept extended by Omniverse. It includes two modes: global and local. When it's in global mode, * muteness will be serialized and will broadcasted during live session, while local mode means they are transient and will * not be broadcasted during live session. */ void(CARB_ABI* setMutenessScope)(ILayersInstance* layersInstance, bool global); bool(CARB_ABI* isMutenessGlobal)(ILayersInstance* layersInstance); bool(CARB_ABI* isLayerGloballyMuted)(ILayersInstance* layersInstance, const char* layerIdentifier); bool(CARB_ABI* isLayerLocallyMuted)(ILayersInstance* layersInstance, const char* layerIdentifier); // If layer is writable means it can be set as edit target, it should satisfy: // 1. It's not read-only on disk. // 2. It's not muted. // 3. It's not locked by setLayerLockState. // You can still set it as edit target forcely if it's not writable, while this is useful for guardrails. bool(CARB_ABI* isLayerWritable)(ILayersInstance* layersInstance, const char* layerIdentifier); // If layer is savable means it can be saved to disk, it should satisfy: // 1. It's writable checked by isLayerWritable. // 2. It's not anonymous. // You can still save the layer forcely even it's locally locked or muted, while this is useful for guardrails. bool(CARB_ABI* isLayerSavable)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Layer is a lock extended in Omniverse. It's not real ACL control to lock the layer for accessing, but a bool * flag that's checked by all applications to access it for UX purpose so it cannot be set as edit target. * Currently, only sublayers in the local layer stack can be locked. */ void(CARB_ABI* setLayerLockState)(ILayersInstance* layersInstance, const char* layerIdentifier, bool locked); bool(CARB_ABI* isLayerLocked)(ILayersInstance* layersInstance, const char* layerIdentifier); void(CARB_ABI* setLayerName)(ILayersInstance* layersInstance, const char* layerIdentifier, const char* name); const char*(CARB_ABI* getLayerName)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * If layer is outdated, it means it has updates on-disk. Currently, only layers in Nucleus can be watched * for updates. */ bool(CARB_ABI* isLayerOutdated)(ILayersInstance* layersInstance, const char* layerIdentifier); // If layer is read-only on disk, this is used to check file permission only. // It's only useful when layer is not anonymous. bool(CARB_ABI* isLayerReadOnlyOnDisk)(ILayersInstance* layersInstance, const char* layerIdentifier); // Gets all outdated layers. carb::dictionary::Item*(CARB_ABI* getAllOutdatedLayerIdentifiers)(ILayersInstance* layerInstance); // Gets all outdated sublayers in the stage's local layer stack. carb::dictionary::Item*(CARB_ABI* getOutdatedSublayerIdentifiers)(ILayersInstance* layerInstance); // Gets all outdated layers except those ones in the sublayers list, like those reference or payload layers. // If a layer is both inserted as sublayer, or reference, it will be treated as sublayer only. carb::dictionary::Item*(CARB_ABI* getOutdatedNonSublayerIdentifiers)(ILayersInstance* layerInstance); // Reload all outdated layers. void(CARB_ABI* reloadAllOutdatedLayers)(ILayersInstance* layerInstance); // Reload all outdated sublayers. void(CARB_ABI* reloadOutdatedSublayers)(ILayersInstance* layerInstance); // Reload all outdated layers except sublayers. If a layer is both inserted as sublayer, or reference, it will // be treated as sublayer only. void(CARB_ABI* reloadOutdatedNonSublayers)(ILayersInstance* layerInstance); // Gets the file owner. It's empty if file system does not support it. const char* (CARB_ABI* getLayerOwner)(ILayersInstance* layersInstance, const char* layerIdentifier); }; } } } }
5,905
C
46.248
138
0.725826
omniverse-code/kit/include/omni/kit/usd/layers/IWorkflowSpecsLinking.h
// 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. // #pragma once #include "LayerTypes.h" #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> namespace omni { namespace kit { namespace usd { namespace layers { struct IWorkflowSpecsLinking { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::IWorkflowSpecsLinking", 1, 0) bool(CARB_ABI* isEnabled)(ILayersInstance* layersIntance); void(CARB_ABI* suspend)(ILayersInstance* layersIntance); void(CARB_ABI* resume)(ILayersInstance* layersIntance); /** * Links spec to specific layer. * * @param specPath The spec path to be linked to layer, which can be prim or property path. If it's prim path, * all of its properties will be linked also. * @param layerIdentifier The layer that the spec is linked to. * @param hierarchy If it's true, all descendants of this spec will be linked to the specified layer also. * * @return Array of specs that are successfully linked. */ carb::dictionary::Item*(CARB_ABI* linkSpec)(ILayersInstance* layersIntance, const char* specPath, const char* layerIdentifier, bool hierarchy); /** * Unlinks spec from layer. * * @param specPath The spec path to be unlinked. * @param layerIdentifier The layer that the spec is unlinked from. * @param hierarchy If it's true, it means all of its descendants will be unlinked also. False otherwise. * @return Array of specs that are successfully unlinked. */ carb::dictionary::Item*(CARB_ABI* unlinkSpec)(ILayersInstance* layersIntance, const char* specPath, const char* layerIdentifier, bool hierarchy); /** * Unlinks spec from all linked layers. * * @param specPath The spec path to be unlinked. * @param hierarchy If it's true, it means all of its descendants will be unlinked also. False otherwise. * * @return Array of specs that are successfully unlinked. */ carb::dictionary::Item*(CARB_ABI* unlinkSpecFromAllLayers)(ILayersInstance* layersIntance, const char* specPath, bool hierarchy); /** * Unlinks specs that are linked to specific layer. * * @param layerIdentifier The layer identifier to unlink all specs from. * * @return array of specs that are successfully unlinked. */ carb::dictionary::Item*(CARB_ABI* unlinkSpecsToLayer)(ILayersInstance* layersIntance, const char* layerIdentifier); /** * Clears all spec links. */ void(CARB_ABI* unlinkAllSpecs)(ILayersInstance* layersIntance); /** * Gets all layer identifiers that specs are linked to. * * @param hierarchy If it's true, it means all of its descendants will be unlinked also. False otherwise. * @return Map of specs that are linked, of which key is the spec path, and value is list of layers that spec is * linked to. */ carb::dictionary::Item*(CARB_ABI* getSpecLayerLinks)(ILayersInstance* layersIntance, const char* specPath, bool hierarchy); /** * Gets all spec paths that link to this layer. */ carb::dictionary::Item*(CARB_ABI* getSpecLinksForLayer)(ILayersInstance* layersIntance, const char* layerIdentifier); /** * Gets all spec links. * * @return Map of spec links, of which key is the spec path, and value is layers that spec is linked to. */ carb::dictionary::Item*(CARB_ABI* getAllSpecLinks)(ILayersInstance* layersIntance); /** * Checkes if spec is linked or not. * * @param specPath The spec path. * @param layerIdentifier Layer identifier. If it's empty or null, it will return true if it's linked to any layers. * If it's not null and not empty, it will return true only when spec is linked to the specific layer. */ bool(CARB_ABI* isSpecLinked)(ILayersInstance* layersIntance, const char* specPath, const char* layerIdentifier); }; } } } }
4,823
C
36.6875
121
0.623886
omniverse-code/kit/include/omni/kit/usd/layers/ILayers.h
// 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. // #pragma once #include "ILayersState.h" #include "IWorkflowAutoAuthoring.h" #include "IWorkflowLiveSyncing.h" #include "IWorkflowSpecsLinking.h" #include "IWorkflowSpecsLocking.h" namespace omni { namespace kit { namespace usd { namespace layers { struct ILayers { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::ILayers", 1, 0) ILayersInstance*(CARB_ABI* getLayersInstanceByName)(const char* usdContextName); ILayersInstance*(CARB_ABI* getLayersInstanceByContext)(void* usdContext); }; } } } }
947
C
22.121951
84
0.771911
omniverse-code/kit/include/omni/kit/usd/layers/IWorkflowLiveSyncing.h
// 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. // #pragma once #include "LayerTypes.h" #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> #define LIVE_SYNCING_MAJOR_VER 1 #define LIVE_SYNCING_MINOR_VER 0 namespace omni { namespace kit { namespace usd { namespace layers { typedef void(*OnStageResultFn)(bool result, const char* err, void* userData); /** * A Live Session is a concept that extends live workflow for USD layers. * Users who join the same Live Session can see live updates with each other. * A Live Session is physically defined as follows: * 1. It has an unique URL to identify the location. * 2. It has a toml file to include the session configuration. * 3. It includes a Live Session layer that has extension .live for users to cooperate together. * 4. It includes a channel for users to send instant messages. * 5. It's bound to a base layer. A base layer is a USD file that your Live Session will be based on. */ class LiveSession; /** * LiveSyncing interfaces work to create/stop/manage Live Sessions. It supports to join a Live Session * for sublayer, or prim with references or payloads. If a layer is in the local sublayer list, and it's * added as reference or payload also. The Live Session can only be joined for the sublayer or reference/payload, * but cannot be joined for both. For layer that is added to multiple prims as reference/payload, it supports to * join the same Live Session for multiple prims that references the same layer. */ struct IWorkflowLiveSyncing { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::IWorkflowLiveSyncing", 2, 2) /** * Gets the count of Live Sessions for a specific layer. The layer must be in the layer stack of current UsdContext * that layerInstance is bound to. It's possible that getTotalLiveSessions will return 0 even there are Live Sessions * on the server as Live Sessions' finding is asynchronous, and this function only returns the count that's discovered * currently. * * @param layerIdentifier The base layer of Live Sessions. */ size_t(CARB_ABI* getTotalLiveSessions)(ILayersInstance* layerInstance, const char* layerIdentifier); /** * Gets the Live Session at index. The index must be less than the total Live Sessions got from getTotalLiveSessions. * Also, the index is not promised to be valid always as it's possible the Live Session is removed. * @param layerIdentifier The base layer of Live Sessions. * @param index The index to access. REMINDER: The same index may be changed to different Live Session as * it does not promise the list of Live Sessions will not be changed or re-ordered. */ LiveSession*(CARB_ABI* getLiveSessionAtIndex)(ILayersInstance* layerInstance, const char* layerIdentifier, size_t index); /** * The name of this Live Session. It's possible that session is invalid and it will return empty. * * @param session The Live Session instance. */ const char*(CARB_ABI* getLiveSessionName)(ILayersInstance* layerInstance, LiveSession* session); /** * The unique URL of this Live Session. It's possible that session is invalid and it will return empty. */ const char*(CARB_ABI* getLiveSessionUrl)(ILayersInstance* layerInstance, LiveSession* session); /** * The owner name of this session. The owner of the session is the one that has the permission to merge session changes back to * base layers. It's possible that session is invalid and it will return empty. REMEMBER: You should not use this * function to check if the local instance is the session owner as it's possible multiple instances with the same user join * in the Live Session. But only one of them is the real session owner. This funciton is only to check the static ownership * that tells you whom the session belongs to. In order to tell the runtime ownership, you should see permissionToMergeSessionChanges. * * @param session The Live Session instance. */ const char*(CARB_ABI* getLiveSessionOwner)(ILayersInstance* layersInstance, LiveSession* session); /** * The communication channel of this session. Channel is a concept in Nucleus to pub/sub transient messages * so all clients connected to it can communicate with each other. It's possible that session is invalid and it will return empty. * * @param session The Live Session instance. */ const char*(CARB_ABI* getLiveSessionChannelUrl)(ILayersInstance* layerInstance, LiveSession* session); /** * A session consists a root layer that's suffixed with .live extension. All live edits are done inside that * .live layer during a Live Session. It's possible that session is invalid and it will return empty. * * @param session The Live Session instance. */ const char*(CARB_ABI* getLiveSessionRootIdentifier)(ILayersInstance* layerInstance, LiveSession* session); /** * The base layer identifier for this Live Session. It's possible that session is invalid and it will return empty. * * @param session The Live Session instance. */ const char*(CARB_ABI* getLiveSessionBaseLayerIdentifier)(ILayersInstance* layerInstance, LiveSession* session); /** * Whether the local user has the permission to merge the Live Session or not. It's possible that the local user is * the owner of the Live Session but it returns false as if there are multiple instances with the same user join * the same session, only one of them has the merge permission to satisfy the requirement of unique ownership. * If the session is not joined, it will return the static ownership based on the owner name. * * @param session The Live Session instance. */ bool(CARB_ABI* permissionToMergeSessionChanges)(ILayersInstance* layersInstance, LiveSession* session); /** * If the session is valid. A valid session means it's not removed from disk. It's possible that this session * is removed during runtime. This function can be used to check if it's still valid before accessing it. * * @param session The Live Session instance. */ bool(CARB_ABI* isValidLiveSession)(ILayersInstance* layersInstance, LiveSession* session); /** * Creates a Live Session for specific sublayer. * * @param layerIdentifier The base layer. * @param sessionName The name of the Live Session. Name can only be alphanumerical characters with hyphens and underscores, * and should be prefixed with letter. * @see ILayersInstance::get_last_error_type() for more error details if it returns nullptr. */ LiveSession*(CARB_ABI* createLiveSession)(ILayersInstance* layersInstance, const char* layerIdentifier, const char* sessionName); /** * Joins the Live Session. The base layer of the Live Session must be in the local layer stack of current stage. * * @param session The Live Session instance. * @see ILayersInstance::get_last_error_type() for more error details if it returns false. */ bool(CARB_ABI* joinLiveSession)(ILayersInstance* layersInstance, LiveSession* session); /** * Joins Live Session by url for specified sublayer. The url must point to a valid Live Session for this layer or it can be created if it does not exist. * * @param layerIdentifier The base layer identifier of a sublayer. * @param liveSessionUrl The Live Session URL to join. * @param createIfNotExisted If it's true, it will create the Live Session under the URL specified if no Live Session is found. * @see ILayersInstance::get_last_error_type() for more error details if it returns false. */ bool(CARB_ABI* joinLiveSessionByURL)(ILayersInstance* layersInstance, const char* layerIdentifier, const char* liveSessionUrl, bool createIfNotExisted); /** * Stops the Live Session of base layer if it's in Live Session already. If this layer is added as reference/payload to multiple prims, and some of * them are in the Live Session of this layer, it will stop the Live Session for all the prims that reference this layer and in the Live Session. * @see stopLiveSessionForPrim to stop Live Session for specific prim. * * @param layerIdentifier The base layer. */ void(CARB_ABI* stopLiveSession)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Stops all Live Sessions in this stage for all layers. */ void(CARB_ABI* stopAllLiveSessions)(ILayersInstance* layersInstance); /** * If the current stage has any active Live Sessions for all used layers. */ bool(CARB_ABI* isStageInLiveSession)(ILayersInstance* layersInstance); /** * If a base layer is in any Live Sessions. It includes both Live Sessions for sublayer or reference/payload prims. * @see isLayerInPrimLiveSession to check if a layer is in any Live Sessions that are bound to reference/payload prims. * * @param layerIdentifier The base layer. */ bool(CARB_ABI* isLayerInLiveSession)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Gets the current Live Session of the base layer. A layer can only have one Live Session enabled at a time. * * @param layerIdentifier The base layer. */ LiveSession*(CARB_ABI* getCurrentLiveSession)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Checkes if this layer is a Live Session layer. A Live Session layer must be managed by a session, and with extension .live. * * @param layerIdentifier The base layer. */ bool(CARB_ABI* isLiveSessionLayer)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Merge changes of the Live Session to base layer specified by layerIdentifier. If layer is not in the Live Session currently, * it will return false directly. Live Session for prim is not supported to be merged. * * @param layerIdentifier The base layer to merge. * @param stopSession If it needs to stop the Live Session after merging. * @see ILayersInstance::get_last_error_type() for more error details if it returns false. */ bool(CARB_ABI* mergeLiveSessionChanges)(ILayersInstance* layersInstance, const char* layerIdentifier, bool stopSession); /** * Merge changes of the Live Session to target layer specified by targetLayerIdentifier. If base layer is not in the Live Session currently, * it will return false directly. Live Session for prim is not supported to be merged. * * @param layersInstance Layer instance. * @param layerIdentifier The base layer of the Live Session. * @param targetLayerIdentifier Target layer identifier. * @param stopSession If it's to stop Live Session after merge. * @param clearTargetLayer If it's to clear target layer before merge. * @see ILayersInstance::get_last_error_type() for more error details if it returns false. */ bool(CARB_ABI* mergeLiveSessionChangesToSpecificLayer)(ILayersInstance* layersInstance, const char* layerIdentifier, const char* targetLayerIdentifier, bool stopSession, bool clearTargetLayer); /** * Given the layer identifier of a .live layer, it's to find its corresponding session. * * @param liveLayerIdentifier The live layer of the Live Session. */ LiveSession*(CARB_ABI* getLiveSessionForLiveLayer)(ILayersInstance* layersInstance, const char* liveLayerIdentifier); /** * Gets the Live Session by url. It can only find the Live Session that belongs to one of the sublayer in the current stage. * * @param liveSessionURL The URL of the Live Session. */ LiveSession*(CARB_ABI* getLiveSessionByURL)(ILayersInstance* layersInstance, const char* liveSessionURL); /** * Gets the logged-in user name for this layer. The layer must be in the used layers of current opened stage, from Nucleus, * and not a live layer. As client library supports multiple Nucleus servers, the logged-in user for each layer may be different. * * @param layerIdentifier The base layer. */ const char*(CARB_ABI* getLoggedInUserNameForLayer)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Gets the logged-in user id for this layer. The layer must be in the used layers of current opened stage, from Nucleus, * and not a live layer. As client library supports multiple Nucleus servers, the logged-in user for each layer may be different. * * @param layerIdentifier The base layer. */ const char*(CARB_ABI* getLoggedInUserIdForLayer)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Opens stage with specified Live Session asynchronously. * * @param stageUrl The stageUrl to open. * @param sessionName The session to open. * @param stageResultFn Callback of stage open. This function will call omni::usd::UsdContext::openStage * * @return false if no session name is provided or other open issues. */ bool(CARB_ABI* openStageWithLiveSession)( ILayersInstance* layersInstance, const char* stageUrl, const char* sessionName, OnStageResultFn stageResultFn, void* userData); /** * Joins the Live Session for prim. The prim must include references or payloads. If it includes multiple references or payloads, an index * is provided to decide which reference or payload layer to join the Live Session. * @param layersInstance Layer instance. * @param session The Live Session to join. It must be the Live Session of the references or payloads of the specified prim. * @param primPath The prim to join the Live Session. * @see ILayersInstance::get_last_error_type() for more error details if it returns false. */ bool(CARB_ABI* joinLiveSessionForPrim)(ILayersInstance* layersInstance, LiveSession* session, const char* primPath); /** * Finds the Live Session by name. It will return the first one that matches the name. * @param layerIdentifier The base layer to find the Live Session. * @param sessionName The name to search. */ LiveSession*(CARB_ABI* findLiveSessionByName)(ILayersInstance* layersInstance, const char* layerIdentifier, const char* sessionName); /** * Whether the prim is in any Live Sessions or not. * * @param primPath The prim path to check. * @param layerIdentifier The optional layer identifier to check. If it's not specified, it will return true if it's in any Live Sessions. * Otherwise, it will only return true if the prim is in the Live Session specified by the layer identifier. * @param fromReferenceOrPayloadOnly If it's true, it will check only references and payloads to see if the same * Live Session is enabled already in any references or payloads. Otherwise, it checkes both the prim specificed by primPath and its references * and payloads. This is normally used to check if the Live Session can be stopped as prim that is in a Live Session may not own the Live Session, * which is owned by its references or payloads, so it cannot stop the Live Session with the prim. */ bool(CARB_ABI* isPrimInLiveSession)(ILayersInstance* layersInstance, const char* primPath, const char* layerIdentifier, bool fromReferenceOrPayloadOnly); /** * Whether the layer is in the Live Session that's bound to any prims. */ bool(CARB_ABI* isLayerInPrimLiveSession)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Returns all prim paths that this Live Session is currently bound to, or nullptr if no prims are in this Live Session. * * @param session The session handle. */ carb::dictionary::Item*(CARB_ABI* getLiveSessionPrimPaths)(ILayersInstance* layersInstance, LiveSession* session); /** * Stops all the Live Sessions that the prim joins to, or the specified Live Session if layerIdentifier is provided. */ void(CARB_ABI* stopLiveSessionForPrim)(ILayersInstance* layersInstance, const char* primPath, const char* layerIdentifier); /** * It provides option to cancel joining to a Live Session if layer is in joining state. * This function only works when it's called during handling eLiveSessionJoining event as all interfaces * to join a Live Session is synchronous currently. * TODO: Supports asynchronous interface to join a session to avoid blocking main thread. */ LiveSession*(CARB_ABI* tryCancellingLiveSessionJoin)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Nanoseconds since the Unix epoch (1 January 1970) of the last time the file was modified. This time is not real time * in the filesystem. Joining a session will modify its modified time also. * * @param session The Live Session instance. */ uint64_t (CARB_ABI* getLiveSessionLastModifiedTimeNs)(ILayersInstance* layerInstance, LiveSession* session); }; } } } }
17,655
C
50.028902
157
0.721609
omniverse-code/kit/include/omni/kit/commands/ICommand.h
// 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. // #pragma once #include <carb/IObject.h> #include <carb/dictionary/IDictionary.h> namespace omni { namespace kit { namespace commands { /** * Pure virtual command interface. */ class ICommand : public carb::IObject { public: /** * Factory function prototype to create a new command instance. * * @param extensionId The id of the source extension registering the command. * @param commandName The command name, unique to the extension registering it. * @param kwargs Arbitrary keyword arguments the command will be executed with. * * @return The command object that was created. */ using CreateFunctionType = carb::ObjectPtr<ICommand> (*)(const char* /*extensionId*/, const char* /*commandName*/, const carb::dictionary::Item* /*kwargs*/); /** * Function prototype to populate keyword arguments expected by a command along with default values. * * @param defaultKwargs Dictionary item to fill with all keyword arguments that have default values. * @param optionalKwargs Dictionary item to fill with all other keyword arguments that are optional. * @param requiredKwargs Dictionary item to fill with all other keyword arguments that are required. */ using PopulateKeywordArgsFunctionType = void (*)(carb::dictionary::Item* /*defaultKwargs*/, carb::dictionary::Item* /*optionalKwargs*/, carb::dictionary::Item* /*requiredKwargs*/); /** * Get the id of the source extension which registered this command. * * @return Id of the source extension which registered this command. */ virtual const char* getExtensionId() const = 0; /** * Get the name of this command, unique to the extension that registered it. * * @return Name of this command, unique to the extension that registered it. */ virtual const char* getName() const = 0; /** * Called when this command object is being executed, * either originally or in response to a redo request. */ virtual void doCommand() = 0; /** * Called when this command object is being undone. */ virtual void undoCommand() = 0; }; using ICommandPtr = carb::ObjectPtr<ICommand>; } } }
2,870
C
34.012195
104
0.64878
omniverse-code/kit/include/omni/kit/commands/ICommandBridge.h
// 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. // #pragma once #include <omni/kit/commands/ICommand.h> #include <carb/dictionary/IDictionary.h> #include <carb/Interface.h> namespace omni { namespace kit { namespace commands { /** * Defines the interface for the CommandBridge. Commands were originally * written in (and only available to use from) Python, so this interface * acts as a bridge allowing them to be registered and executed from C++ */ class ICommandBridge { public: CARB_PLUGIN_INTERFACE("omni::kit::commands::ICommandBridge", 1, 0); using RegisterFunctionType = void (*)(const char*, const char*, const carb::dictionary::Item*, const carb::dictionary::Item*, const carb::dictionary::Item*); using DeregisterFunctionType = void (*)(const char*, const char*); using ExecuteFunctionType = bool (*)(const char*, const char*, const carb::dictionary::Item*); using UndoFunctionType = bool (*)(); using RedoFunctionType = bool (*)(); using RepeatFunctionType = bool (*)(); using VoidFunctionType = void (*)(); /** * Enable the command bridge so that new command types can be registered and deregistered from C++, * and so that existing command types can be executed in Python (where commands are held) from C++. * * @param registerFunction Function responsible for registering new C++ command types with Python. * @param deregisterFunction Function responsible for deregistering C++ command types from Python. * @param executeFunction Function responsible for executing existing commands in Python from C++. * @param undoFunction Function responsible for calling undo on past commands in Python from C++. * @param redoFunction Function responsible for calling redo on past commands in Python from C++. * @param repeatFunction Function responsible for calling repeat on past commands in Python from C++. * @param beginUndoGroupFunction Function responsible for opening an undo group in Python from C++. * @param endUndoGroupFunction Function responsible for closing an undo group in Python from C++. * @param beginUndoDisabledFunction Function responsible for disabling undo in Python from C++. * @param endUndoDisabledFunction Function responsible for re-enabling undo in Python from C++. */ virtual void enableBridge(RegisterFunctionType registerFunction, DeregisterFunctionType deregisterFunction, ExecuteFunctionType executeFunction, UndoFunctionType undoFunction, RedoFunctionType redoFunction, RepeatFunctionType repeatFunction, VoidFunctionType beginUndoGroupFunction, VoidFunctionType endUndoGroupFunction, VoidFunctionType beginUndoDisabledFunction, VoidFunctionType endUndoDisabledFunction) = 0; /** * Disable the command bridge so that new command types can no longer be registered and deregistered from C++, * and so that existing command types can no longer be executed in Python (where commands are held) from C++. * Calling this will also cause any remaining command types previously registered in C++ to be deregistered. */ virtual void disableBridge() = 0; /** * Bridge function to call from C++ to register a C++ command type with Python. * * @param extensionId The id of the source extension registering the command. * @param commandName The command name, unique to the registering extension. * @param factory Factory function used to create instances of the command. * @param populateKeywordArgs Function called to populate the keyword args. */ virtual void registerCommand(const char* extensionId, const char* commandName, ICommand::CreateFunctionType factory, ICommand::PopulateKeywordArgsFunctionType populateKeywordArgs) = 0; /** * Bridge function to call from C++ to deregister a C++ command type from Python. * * @param extensionId The id of the source extension that registered the command. * @param commandName Command name, unique to the extension that registered it. */ virtual void deregisterCommand(const char* extensionId, const char* commandName) = 0; /** * Deregister all C++ command types that were registered by the specified extension. * * @param extensionId The id of the source extension that registered the commands. */ virtual void deregisterAllCommandsForExtension(const char* extensionId) = 0; /** * Bridge function to call from C++ to execute any existing command type in Python. * * @param commandName Command name, unique to the extension that registered it. * @param kwargs Arbitrary keyword arguments the command will be executed with. * * @return True if the command object was created and executed, false otherwise. */ virtual bool executeCommand(const char* commandName, const carb::dictionary::Item* kwargs = nullptr) const = 0; /** * Bridge function to call from C++ to execute any existing command type in Python. * * @param extensionId The id of the source extension that registered the command. * @param commandName Command name, unique to the extension that registered it. * @param kwargs Arbitrary keyword arguments the command will be executed with. * * @return True if the command object was created and executed, false otherwise. */ virtual bool executeCommand(const char* extensionId, const char* commandName, const carb::dictionary::Item* kwargs = nullptr) const = 0; /** * Bridge function to call from Python to create a new instance of a C++ command. * * @param extensionId The id of the source extension that registered the command. * @param commandName The command name, unique to the extension that registered it. * @param kwargs Arbitrary keyword arguments that the command will be executed with. * * @return A command object if it was created, or an empty ObjectPtr otherwise. */ virtual carb::ObjectPtr<ICommand> createCommandObject(const char* extensionId, const char* commandName, const carb::dictionary::Item* kwargs = nullptr) const = 0; /** * Bridge function to call from C++ to undo the last command that was executed. * * @return True if the last command was successfully undone, false otherwise. */ virtual bool undoCommand() const = 0; /** * Bridge function to call from C++ to redo the last command that was undone. * * @return True if the last command was successfully redone, false otherwise. */ virtual bool redoCommand() const = 0; /** * Bridge function to call from C++ to repeat the last command that was executed or redone. * * @return True if the last command was successfully repeated, false otherwise. */ virtual bool repeatCommand() const = 0; /** * Bridge function to call from C++ to begin a new group of commands to be undone together. */ virtual void beginUndoGroup() const = 0; /** * Bridge function to call from C++ to end a new group of commands to be undone together. */ virtual void endUndoGroup() const = 0; /** * Bridge function to call from C++ to begin disabling undo for subsequent commands. */ virtual void beginUndoDisabled() const = 0; /** * Bridge function to call from C++ to end disabling undo for subsequent commands. */ virtual void endUndoDisabled() const = 0; /** * RAII class used to begin and end a new undo group within a specific scope. */ class ScopedUndoGroup { public: ScopedUndoGroup() { if (ICommandBridge* commandBridge = carb::getCachedInterface<ICommandBridge>()) { commandBridge->beginUndoGroup(); } } ~ScopedUndoGroup() { if (ICommandBridge* commandBridge = carb::getCachedInterface<ICommandBridge>()) { commandBridge->endUndoGroup(); } } }; /** * RAII class used to begin and end disabling undo within a specific scope. */ class ScopedUndoDisabled { public: ScopedUndoDisabled() { if (ICommandBridge* commandBridge = carb::getCachedInterface<ICommandBridge>()) { commandBridge->beginUndoDisabled(); } } ~ScopedUndoDisabled() { if (ICommandBridge* commandBridge = carb::getCachedInterface<ICommandBridge>()) { commandBridge->endUndoDisabled(); } } }; }; } } }
9,730
C
40.763948
116
0.643063
omniverse-code/kit/include/omni/kit/commands/Command.h
// 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. // #pragma once #include <omni/kit/commands/ICommand.h> #include <carb/ObjectUtils.h> #include <omni/String.h> namespace omni { namespace kit { namespace commands { /** * Abstract command base class providing the core functionaly common to all commands. */ class Command : public ICommand { public: /** * Constructor. * * @param extensionId The id of the source extension registering the command. * @param commandName The command name, unique to the registering extension. */ Command(const char* extensionId, const char* commandName) : m_extensionId(extensionId ? extensionId : ""), m_commandName(commandName ? commandName : "") { } /** * Destructor. */ ~Command() override = default; /** * @ref ICommand::getExtensionId */ const char* getExtensionId() const override { return m_extensionId.c_str(); } /** * @ref ICommand::getName */ const char* getName() const override { return m_commandName.c_str(); } protected: omni::string m_extensionId; //!< The id of the source extension that registered the command. omni::string m_commandName; //!< Name of the command, unique to the registering extension. private: CARB_IOBJECT_IMPL }; } } }
1,728
C
22.684931
102
0.680556
omniverse-code/kit/include/omni/str/IReadOnlyCString.gen.h
// Copyright (c) 2020-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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL //! Reference counted read-only C-style (i.e. null-terminated) string. template <> class omni::core::Generated<omni::str::IReadOnlyCString_abi> : public omni::str::IReadOnlyCString_abi { public: OMNI_PLUGIN_INTERFACE("omni::str::IReadOnlyCString") //! Returns a pointer to the null-terminated string. //! //! The returned pointer is valid for the lifetime of this object. //! //! This method is thread safe. const char* getBuffer() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline const char* omni::core::Generated<omni::str::IReadOnlyCString_abi>::getBuffer() noexcept { return getBuffer_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
1,537
C
26.963636
101
0.72674
omniverse-code/kit/include/omni/str/IReadOnlyCString.h
// Copyright (c) 2020-2023, 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. // //! @file //! @brief Interface to manage access to a read-only string. #pragma once #include "../core/IObject.h" #include "../../carb/Defines.h" namespace omni { //! Namespace for various string helper classes, interfaces, and functions. namespace str { //! Forward declaration of the IReadOnlyCString. OMNI_DECLARE_INTERFACE(IReadOnlyCString); //! Reference counted read-only C-style (i.e. null-terminated) string. class IReadOnlyCString_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.str.IReadOnlyCString")> { protected: //! Returns a pointer to the null-terminated string. //! //! The returned pointer is valid for the lifetime of this object. //! //! This method is thread safe. virtual OMNI_ATTR("c_str, not_null") const char* getBuffer_abi() noexcept = 0; }; } // namespace str } // namespace omni #include "IReadOnlyCString.gen.h" namespace omni { namespace str { //! Concrete implementation of the IReadOnlyCString interface. class ReadOnlyCString : public omni::core::Implements<omni::str::IReadOnlyCString> { public: //! Creates a read-only string. The given string is copied and must not be nullptr. static omni::core::ObjectPtr<IReadOnlyCString> create(const char* str) { OMNI_ASSERT(str, "ReadOnlyCString: the given string must not be nullptr"); return { new ReadOnlyCString{ str }, omni::core::kSteal }; } private: ReadOnlyCString(const char* str) : m_buffer{ str } { } const char* getBuffer_abi() noexcept override { return m_buffer.c_str(); } CARB_PREVENT_COPY_AND_MOVE(ReadOnlyCString); std::string m_buffer; }; } // namespace str } // namespace omni
2,144
C
27.6
120
0.712687
omniverse-code/kit/include/omni/str/Wildcard.h
// Copyright (c) 2020-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. // /** @file * @brief Helper functions to handle matching wildcard patterns. */ #pragma once #include <stddef.h> #include <cstdint> namespace omni { /** Namespace for various string helper functions. */ namespace str { /** Checks if a string matches a wildcard pattern. * * @param[in] str The string to attempt to match to the pattern @p pattern. * This may not be `nullptr`. * @param[in] pattern The wildcard pattern to match against. This may not be * `nullptr`. The wildcard pattern may contain '?' to match * exactly one character (any character), or '*' to match * zero or more characters. * @returns `true` if the string @p str matches the pattern. Returns `false` if * the pattern does not match the pattern. */ inline bool matchWildcard(const char* str, const char* pattern) { const char* star = nullptr; const char* s0 = str; const char* s1 = s0; const char* p = pattern; while (*s0) { // Advance both pointers when both characters match or '?' found in pattern if ((*p == '?') || (*p == *s0)) { s0++; p++; continue; } // * found in pattern, save index of *, advance a pattern pointer if (*p == '*') { star = p++; s1 = s0; continue; } // Current characters didn't match, consume character in string and rewind to star pointer in the pattern if (star) { p = star + 1; s0 = ++s1; continue; } // Characters do not match and current pattern pointer is not star return false; } // Skip remaining stars in pattern while (*p == '*') { p++; } return !*p; // Was whole pattern matched? } /** Attempts to match a string to a set of wildcard patterns. * * @param[in] str The string to attempt to match to the pattern @p pattern. * This may not be `nullptr`. * @param[in] patterns An array of patterns to attempt to match the string @p str * to. Each pattern in this array has the same format as the * pattern in @ref matchWildcard(). This may not be `nullptr`. * @param[in] patternsCount The total number of wildcard patterns in @p patterns. * @returns The pattern that the test string @p str matched to if successful. Returns * `nullptr` if the test string did not match any of the patterns. */ inline const char* matchWildcards(const char* str, const char* const* patterns, size_t patternsCount) { for (size_t i = 0; i < patternsCount; ++i) { if (matchWildcard(str, patterns[i])) { return patterns[i]; } } return nullptr; } /** Tests whether a string is potentially a wildcard pattern. * * @param[in] pattern The pattern to test as a wildcard. This will be considered a wildcard * if it contains the special wildcard characters '*' or '?'. This may not * be nullptr. * @returns `true` if the pattern is likely a wildcard string. Returns `false` if the pattern * does not contain any of the special wildcard characters. */ inline bool isWildcardPattern(const char* pattern) { for (const char* p = pattern; p[0] != 0; p++) { if (*p == '*' || *p == '?') return true; } return false; } } // namespace str } // namespace omni
4,056
C
31.717742
113
0.589744
usnuni/isaac-sim/README.md
# isaac-sim ## 코드 실행 - 아나콘다(python==3.7.16) 환경에서 아래 코드 실행 후 동일 터미널에서 경로 변경 및 py 파일 실행해야 정상 작동(새 터미널창으로 하면 작동 안 됨) ``` cd ~/.local/share/ov/pkg/isaac_sim-2022.2.1 source setup_conda_env.sh #cd ~/{py_file_path} cd ~/isaac_sample ``` ## 환경 설정 ### 1 NVIDIA-SMI, Driver Version 535.54.03 / CUDA Version: 12.2 #### 1.1 Nvidia driver (version: 535-server) ``` sudo add-apt-repository ppa:graphics-drivers/ppa sudo apt update sudo apt-get install nvidia-driver-535-server sudo reboot nvidia-smi ``` #### 1.2 CUDA toolkit - E: Unable to locate package nvidia-docker2 (아래 코드로 해결) ``` wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-keyring_1.1-1_all.deb sudo dpkg -i cuda-keyring_1.1-1_all.deb sudo apt update sudo apt -y install cuda # install packages sudo apt install nvidia-docker2 sudo apt install nvidia-container-toolkit ``` ### 2 Anaconda python ver=3.10 <pre> <code> sudo apt install curl bzip2 -y curl --output anaconda.sh https://repo.anaconda.com/archive/Anaconda3-2023.03-0-Linux-x86_64.sh sha256sum anaconda.sh bash anaconda.sh </code> </pre> ### 3 Isaac Sim 2022.2.1 [link](https://www.nvidia.com/en-us/omniverse/download/#ov-download) - E: AppImages require FUSE to run. ``` apt install fuse libfuse2 ``` ### 4 ROS2 humble [link](https://docs.ros.org/en/humble/Installation/Ubuntu-Install-Debians.html) - have to run this code every time start ROS ``` source /opt/ros/humble/setup.bash ``` ### 5 Docker [link](https://docs.docker.com/engine/install/ubuntu) #### 5.1 Nvidia drivers for Docker ``` sudo apt install nvidia-container-toolkit ``` #### 5.2 Docker compose [link](https://docs.docker.com/compose/install/linux/#install-using-the-repository) ``` sudo apt install docker-compose-plugin # verify docker compose version > Docker Compose version v2.21.0 ``` ### 6 Moveit #### 6.1 Docker MoveIt2 설치 [link](https://moveit.picknik.ai/main/doc/how_to_guides/how_to_setup_docker_containers_in_ubuntu.html) ``` wget https://raw.githubusercontent.com/ros-planning/moveit2_tutorials/main/.docker/docker-compose.yml DOCKER_IMAGE=rolling-tutorial docker compose run --rm --name moveit2_container gpu ``` - E: Failed to initialize NVML: Driver/library version mismatch > reboot - enter the container through another terminal ``` docker exec -it moveit2_container /bin/bash ``` ##### 6.1.1 moveit tutorial [link](https://github.com/ros-planning/moveit2_tutorials) [getting started](https://moveit.picknik.ai/main/doc/tutorials/getting_started/getting_started.html) ``` source /opt/ros/humble/setup.bash # same as link ``` https://docs.omniverse.nvidia.com/isaacsim/latest/install_ros.html#isaac-sim-app-install-ros To start using the ROS2 packages built within this workspace, open a new terminal and source the workspace with the following commands: ``` source /opt/ros/foxy/setup.bash cd foxy_ws source install/local_setup.bash ``` # Errors 1. sudo apt update ``` W: https://nvidia.github.io/libnvidia-container/stable/ubuntu18.04/amd64/InRelease: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details. ``` 2. colcon build --mixin release ``` ModuleNotFoundError: No module named 'catkin_pkg' CMake Error at /opt/ros/humble/share/ament_cmake_core/cmake/core/ament_package_xml.cmake:95 (message): execute_process(/home/ari/anaconda3/bin/python3.10 /opt/ros/humble/share/ament_cmake_core/cmake/core/package_xml_2_cmake.py /home/ari/ws_moveit/src/moveit2/moveit_common/package.xml /home/ari/ws_moveit/build/moveit_common/ament_cmake_core/package.cmake) returned error code 1 Call Stack (most recent call first): /opt/ros/humble/share/ament_cmake_core/cmake/core/ament_package_xml.cmake:49 (_ament_package_xml) /opt/ros/humble/share/ament_lint_auto/cmake/ament_lint_auto_find_test_dependencies.cmake:31 (ament_package_xml) CMakeLists.txt:8 (ament_lint_auto_find_test_dependencies) ``` ``` conda install -c auto catkin_pkg <failed ``` ``` sudo cp -r /home/ari/anaconda3/envs/isaac/lib/python2.7/site-packages/catkin_pkg /opt/ros/humble/lib/python3.10/site-packages/ < failed ``` 3. 1 package had stderr output: isaac_ros_navigation_goal > ignoreed.. 4. ros2 bridge connect error ``` unset LD_LIBRARY_PATH export FASTRTPS_DEFAULT_PROFILES_FILE=~/.ros/fastdds.xml ```
4,340
Markdown
28.732877
206
0.737097
usnuni/isaac-sim/pick-n-place/README.md
# isaac-sim-pick-place ## Environment Setup ### 1. Download Isaac Sim - Dependency check - Ubuntu - Recommanded: 20.04 / 22.04 - Tested on: 20.04 - NVIDIA Driver version - Recommanded: 525.60.11 - Minimum: 510.73.05 - Tested on: 510.108.03 / - [Download Omniverse](https://developer.nvidia.com/isaac-sim) - [Workstation Setup](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_basic.html) - [Python Environment Installation](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_python.html#advanced-running-with-anaconda) ### 2. Environment Setup ## 2-1. Conda Check [Python Environment Installation](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_python.html#advanced-running-with-anaconda) - Create env create ``` conda env create -f environment.yml conda activate isaac-sim ``` - Setup environment variables so that Isaac Sim python packages are located correctly ``` source setup_conda_env.sh ``` - Install requirment pakages ``` pip install -r requirements.txt ``` ## 2-2. Docker (recommended) - Install Init file ``` wget https://raw.githubusercontent.com/gist-ailab/AILAB-isaac-sim-pick-place/main/dockers/init_script.sh zsh init_script.sh ```
1,312
Markdown
26.93617
152
0.696646
usnuni/isaac-sim/pick-n-place/dockers/extension.toml
[core] reloadable = true order = 0 [package] version = "1.5.1" category = "Simulation" title = "Isaac Sim Samples" description = "Sample extensions for Isaac Sim" authors = ["NVIDIA"] repository = "" keywords = ["isaac", "samples", "manipulation"] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" preview_image = "data/preview.png" icon = "data/icon.png" writeTarget.kit = true [dependencies] "omni.kit.uiapp" = {} "omni.physx" = {} "omni.physx.vehicle" = {} "omni.isaac.dynamic_control" = {} "omni.isaac.motion_planning" = {} "omni.isaac.synthetic_utils" = {} "omni.isaac.ui" = {} "omni.isaac.core" = {} "omni.isaac.franka" = {} "omni.isaac.manipulators" = {} "omni.isaac.dofbot" = {} "omni.isaac.universal_robots" = {} "omni.isaac.motion_generation" = {} "omni.graph.action" = {} "omni.graph.nodes" = {} "omni.graph.core" = {} "omni.isaac.quadruped" = {} "omni.isaac.wheeled_robots" = {} [[python.module]] name = "omni.isaac.examples.tests" [[python.module]] name = "omni.isaac.examples.kaya_gamepad" [[python.module]] name = "omni.isaac.examples.omnigraph_keyboard" [[python.module]] name = "omni.isaac.examples.follow_target" [[python.module]] name = "omni.isaac.examples.path_planning" [[python.module]] name = "omni.isaac.examples.simple_stack" [[python.module]] name = "omni.isaac.examples.bin_filling" [[python.module]] name = "omni.isaac.examples.robo_factory" [[python.module]] name = "omni.isaac.examples.robo_party" [[python.module]] name = "omni.isaac.examples.hello_world" [[python.module]] name = "omni.isaac.examples.franka_nut_and_bolt" [[python.module]] name = "omni.isaac.examples.replay_follow_target" [[python.module]] name = "omni.isaac.examples.surface_gripper" [[python.module]] name = "omni.isaac.examples.unitree_quadruped" [[python.module]] name = "omni.isaac.examples.user_examples" [[python.module]] name = "omni.isaac.examples.ailab_examples" [[test]] timeout = 960
1,927
TOML
20.186813
49
0.693306
usnuni/isaac-sim/pick-n-place/dockers/BUILD.md
# Install Container ```bash docker login nvcr.io id : $oauthtoken pwd : Njc5dHR0b2QwZTh0dTFtNW5ydXI4Y3JtNm46MGVkM2VjODctZTk1Ni00NmNjLTkxNDEtYTdmMjNlNjllMjNj ``` # Build ```bash docker build --pull -t \ registry.ark.svc.ops.openark/library/isaac-sim:2022.2.1-ubuntu22.04_v3 \ --build-arg ISAACSIM_VERSION=2022.2.1 \ --build-arg BASE_DIST=ubuntu20.04 \ --build-arg CUDA_VERSION=11.4.2 \ --build-arg VULKAN_SDK_VERSION=1.3.224.1 \ --file Dockerfile.2022.2.1-ubuntu22.04 . ``` ```bash docker push --tls-verify=false registry.ark.svc.ops.openark/library/isaac-sim:2022.2.1-ubuntu22.04_v3 ``` # Container Usage ```bash docker pull --tls-verify=false registry.ark.svc.ops.openark/library/isaac-sim:2022.2.1-ubuntu22.04_v3 ``` ```bash podman run -it --entrypoint bash --name isaac-sim --device nvidia.com/gpu=all -e "ACCEPT_EULA=Y" --rm --network=host \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -e DISPLAY \ -v /home:/home \ -v ~/docker/isaac-sim/cache/kit:/isaac-sim/kit/cache/Kit:rw \ -v ~/docker/isaac-sim/cache/ov:/root/.cache/ov:rw \ -v ~/docker/isaac-sim/cache/pip:/root/.cache/pip:rw \ -v ~/docker/isaac-sim/cache/glcache:/root/.cache/nvidia/GLCache:rw \ -v ~/docker/isaac-sim/cache/computecache:/root/.nv/ComputeCache:rw \ -v ~/docker/isaac-sim/logs:/root/.nvidia-omniverse/logs:rw \ -v ~/docker/isaac-sim/data:/root/.local/share/ov/data:rw \ -v ~/docker/isaac-sim/documents:/root/Documents:rw \ registry.ark.svc.ops.openark/library/isaac-sim:2022.2.1-ubuntu22.04_v3 ``` # In a docker container (Deprecated) ```bash alias code="code --no-sandbox --user-data-dir=/root" alias chrome="google-chrome --no-sandbox" ln -sf /usr/lib64/libcuda.so.1 /usr/lib64/libcuda.so export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib64 ```
1,737
Markdown
29.491228
118
0.716753
usnuni/isaac-sim/pick-n-place/dockers/README.md
# Install Init file wget https://raw.githubusercontent.com/gist-ailab/AILAB-isaac-sim-pick-place/main/dockers/init_script.sh zsh init_script.sh # VScode
155
Markdown
21.285711
104
0.787097
usnuni/isaac-sim/pick-n-place/dockers/ailab_examples/ailab_extension.py
# Copyright (c) 2020-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. import os from omni.isaac.examples.ailab_script import AILabExtension from omni.isaac.examples.ailab_examples import AILab class AILabExtension(AILabExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="AILab extension", title="AILab extension Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=AILab(), ) return
1,191
Python
41.571427
135
0.702771
usnuni/isaac-sim/pick-n-place/dockers/ailab_examples/ailab.py
# Copyright (c) 2020-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. from omni.isaac.examples.base_sample import BaseSample # Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html class AILab(BaseSample): def __init__(self) -> None: super().__init__() return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() return async def setup_post_load(self): return async def setup_pre_reset(self): return async def setup_post_reset(self): return def world_cleanup(self): return
1,035
Python
27.777777
116
0.707246
usnuni/isaac-sim/pick-n-place/dockers/ailab_script/ailab_extension_old.py
# ailabktw # from abc import abstractmethod import omni.ext import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription import weakref from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder import asyncio from omni.isaac.examples.ailab_script import AILab from omni.isaac.core import World import os # ---- # class AILabExtension(omni.ext.IExt): def __init__(self): super().__init__() self._ext_id= 'omni.isaac.examples-1.5.1' self.use_custom_updated = False pass def on_startup(self, ext_id: str='omni.isaac.examples-1.5.1'): self._menu_items = None self._buttons = None self._ext_id = ext_id self._sample = None self._extra_frames = [] return def on_custom_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="AILab extension", title="AILab extension Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=AILab(), ) return def start_extension( self, menu_name: str, submenu_name: str, name: str, title: str, doc_link: str, overview: str, file_path: str, sample=None, number_of_extra_frames=1, window_width=420, keep_window_open=False, ): if sample is None: self._sample = AILab() else: self._sample = sample menu_items = [MenuItemDescription(name=name, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())] if menu_name == "" or menu_name is None: self._menu_items = menu_items elif submenu_name == "" or submenu_name is None: self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)] else: self._menu_items = [ MenuItemDescription( name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)] ) ] add_menu_items(self._menu_items, "Isaac Examples") self._buttons = dict() self._build_ui( name=name, title=title, doc_link=doc_link, overview=overview, file_path=file_path, number_of_extra_frames=number_of_extra_frames, window_width=window_width, keep_window_open=keep_window_open, ) return @property def sample(self): return self._sample def get_frame(self, index): if index >= len(self._extra_frames): raise Exception("there were {} extra frames created only".format(len(self._extra_frames))) return self._extra_frames[index] def get_world(self): return World.instance() def get_buttons(self): return self._buttons def _build_ui( self, name, title, doc_link, overview, file_path, # number_of_extra_frames, window_width, keep_window_open, number_of_extra_frames=1, window_width=420, keep_window_open=False, # use_custom_update=False, **args ): self._window = omni.ui.Window( name, width=window_width, height=0, visible=keep_window_open, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): setup_ui_headers(self._ext_id, file_path, title, doc_link, overview) self._controls_frame = ui.CollapsableFrame( title="Object Picking", width=ui.Fraction(1), height=0, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with ui.VStack(style=get_style(), spacing=5, height=0): for i in range(number_of_extra_frames): self._extra_frames.append( ui.CollapsableFrame( title="", width=ui.Fraction(0.33), height=0, visible=False, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) ) with self._controls_frame: # = ++ if use_custom_update: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Check Objects", "type": "button", "text": "Check", "tooltip": "Check object to pick", "on_clicked_fn": self._on_check, } self._buttons["Check Objects"] = btn_builder(**dict) self._buttons["Check Objects"].enabled = True dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = True dict = { "label": "Object No.0", "type": "button", "text": "000_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.0"] = btn_builder(**dict) self._buttons["Object No.0"].enabled = True dict = { "label": "Object No.1", "type": "button", "text": "001_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.1"] = btn_builder(**dict) self._buttons["Object No.1"].enabled = True dict = { "label": "Object No.2", "type": "button", "text": "002_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.2"] = btn_builder(**dict) self._buttons["Object No.2"].enabled = True else: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Check Objects", "type": "button", "text": "Check", "tooltip": "Check object to pick", "on_clicked_fn": self._on_check, } self._buttons["Check Objects"] = btn_builder(**dict) self._buttons["Check Objects"].enabled = True # dict = { # "label": "Pick Object", # "type": "button", # "text": "Pick", # "tooltip": "Pick object and move", # "on_clicked_fn": self._on_load_world, # } # self._buttons["Pick Object"] = btn_builder(**dict) # self._buttons["Pick Object"].enabled = False dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = False dict = { "label": "Object No.0", "type": "button", "text": "000_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.0"] = btn_builder(**dict) self._buttons["Object No.0"].enabled = False dict = { "label": "Object No.1", "type": "button", "text": "001_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.1"] = btn_builder(**dict) self._buttons["Object No.1"].enabled = False dict = { "label": "Object No.2", "type": "button", "text": "002_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.2"] = btn_builder(**dict) self._buttons["Object No.2"].enabled = False return def _set_button_tooltip(self, button_name, tool_tip): self._buttons[button_name].set_tooltip(tool_tip) return def _on_load_world(self): async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load World"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_reset(self): async def _on_reset_async(): await self._sample.reset_async() await omni.kit.app.get_app().next_update_async() self.post_reset_button_event() asyncio.ensure_future(_on_reset_async()) return # ++ def _on_check(self): async def _on_check(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(True) self._buttons["Check Objects"].enabled = False self.use_custom_updated = False self.post_reset_button_event() asyncio.ensure_future(_on_check()) return def _on_selected_button(self): async def _on_selected_button(): # await self._sample.selected_button_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(False) self._buttons["Check Objects"].enabled = True self.use_custom_updated = True self.post_reset_button_event() asyncio.ensure_future(_on_selected_button()) return # def _on_check(self): # async def _on_check(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() # self.post_reset_button_event() # asyncio.ensure_future(_on_check()) # return @abstractmethod def post_reset_button_event(self): return @abstractmethod def post_load_button_event(self): return @abstractmethod def post_clear_button_event(self): return def _enable_all_buttons(self, flag): for btn_name, btn in self._buttons.items(): if isinstance(btn, omni.ui._ui.Button): btn.enabled = flag return def _menu_callback(self): self._window.visible = not self._window.visible return def _on_window(self, status): # if status: return def on_shutdown(self): self._extra_frames = [] if self._sample._world is not None: self._sample._world_cleanup() if self._menu_items is not None: self._sample_window_cleanup() if self._buttons is not None: self._buttons["Load World"].enabled = True self._enable_all_buttons(False) self.shutdown_cleanup() return def shutdown_cleanup(self): return def _sample_window_cleanup(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None self._menu_items = None self._buttons = None return def on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.CLOSED): if World.instance() is not None: self.sample._world_cleanup() self.sample._world.clear_instance() if hasattr(self, "_buttons"): if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load World"].enabled = True return def _reset_on_stop_event(self, e): if e.type == int(omni.timeline.TimelineEventType.STOP): self._buttons["Load World"].enabled = False self._buttons["Reset"].enabled = True self.post_clear_button_event() return
15,356
Python
37.878481
135
0.456108
usnuni/isaac-sim/pick-n-place/dockers/ailab_script/ailab.py
# ailabktw # import gc from abc import abstractmethod from omni.isaac.core import World from omni.isaac.core.scenes.scene import Scene from omni.isaac.core.utils.stage import create_new_stage_async, update_stage_async # ---- # class AILab(object): def __init__(self) -> None: self._world = None self._current_tasks = None self._world_settings = {"physics_dt": 1.0 / 60.0, "stage_units_in_meters": 1.0, "rendering_dt": 1.0 / 60.0} # self._logging_info = "" return def get_world(self): return self._world def set_world_settings(self, physics_dt=None, stage_units_in_meters=None, rendering_dt=None): if physics_dt is not None: self._world_settings["physics_dt"] = physics_dt if stage_units_in_meters is not None: self._world_settings["stage_units_in_meters"] = stage_units_in_meters if rendering_dt is not None: self._world_settings["rendering_dt"] = rendering_dt return async def load_world_async(self): """Function called when clicking load buttton """ if World.instance() is None: await create_new_stage_async() self._world = World(**self._world_settings) await self._world.initialize_simulation_context_async() self.setup_scene() else: self._world = World.instance() self._current_tasks = self._world.get_current_tasks() await self._world.reset_async() await self._world.pause_async() await self.setup_post_load() if len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return async def reset_async(self): """Function called when clicking reset buttton """ if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.remove_physics_callback("tasks_step") await self._world.play_async() await update_stage_async() await self.setup_pre_reset() await self._world.reset_async() await self._world.pause_async() await self.setup_post_reset() if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return # ++ async def check_async(self): """Function called when clicking reset buttton """ if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.remove_physics_callback("tasks_step") await self._world.play_async() await update_stage_async() await self.setup_pre_reset() await self._world.reset_async() await self._world.pause_async() await self.setup_post_reset() if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return async def selected_button_async(self): """Function called when clicking reset buttton """ if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.remove_physics_callback("tasks_step") await self._world.play_async() await update_stage_async() await self.setup_pre_reset() await self._world.reset_async() await self._world.pause_async() await self.setup_post_reset() if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return @abstractmethod def setup_scene(self, scene: Scene) -> None: """used to setup anything in the world, adding tasks happen here for instance. Args: scene (Scene): [description] """ return @abstractmethod async def setup_post_load(self): """called after first reset of the world when pressing load, intializing provate variables happen here. """ return @abstractmethod async def setup_pre_reset(self): """ called in reset button before resetting the world to remove a physics callback for instance or a controller reset """ return @abstractmethod async def setup_post_reset(self): """ called in reset button after resetting the world which includes one step with rendering """ return @abstractmethod async def setup_post_clear(self): """called after clicking clear button or after creating a new stage and clearing the instance of the world with its callbacks """ return # def log_info(self, info): # self._logging_info += str(info) + "\n" # return def _world_cleanup(self): self._world.stop() self._world.clear_all_callbacks() self._current_tasks = None self.world_cleanup() return def world_cleanup(self): """Function called when extension shutdowns and starts again, (hot reloading feature) """ return async def clear_async(self): """Function called when clicking clear buttton """ await create_new_stage_async() if self._world is not None: self._world_cleanup() self._world.clear_instance() self._world = None gc.collect() await self.setup_post_clear() return
5,568
Python
33.165644
115
0.604346
usnuni/isaac-sim/pick-n-place/lecture/1-1/debug_example.py
a =1 b=1 print(a+b) b=2 print(a+b)
36
Python
4.285714
10
0.555556
stephenT0/funkyboy-anamorphic-effects/README.md
# Anamorphic Effects An extension that emulates camera effects associated with anamorphic lenses. Download this sample scene to demo the extension: https://drive.google.com/file/d/1ZYNbhNenNNl2WTJeKibXuf8S1eJVl4Cy/view?usp=share_link ## Adding This Extension To add this extension to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com/stephenT0/funkyboy-anamorphic-effects?branch=main&dir=exts` Manual installation: 1. Download Zip 2. Extract and place into a directory of your choice 3. Go into: Extension Manager -> Gear Icon -> Extension Search Path 4. Add a custom search path ending with: \funkyboy-anamorphic-effects-master\exts
728
Markdown
35.449998
135
0.788462
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/extension.py
import omni.ext import omni.ui as ui from .window import AnamorphicEffectsWindow, WINDOW_TITLE class FunkyboyAnamorphicEffectsExtension(omni.ext.IExt): def on_startup(self, ext_id): self._menu_path = f"Window/{WINDOW_TITLE}" self._window = AnamorphicEffectsWindow(WINDOW_TITLE, self._menu_path) self._menu = omni.kit.ui.get_editor_menu().add_item(self._menu_path, self._on_menu_click, True) def on_shutdown(self): omni.kit.ui.get_editor_menu().remove_item(self._menu) if self._window is not None: self._window.destroy() self._window = None def _on_menu_click(self, menu, toggled): if toggled: if self._window is None: self._window = AnamorphicEffectsWindow(WINDOW_TITLE, self._menu_path) else: self._window.show() else: if self._window is not None: self._window.hide()
952
Python
31.862068
103
0.611345
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/style1.py
import omni.ui as ui from omni.ui import color as cl style1 = { # "RadioButton": { # "border_width": 0.5, # "border_radius": 0.0, # "margin": 5.0, # "padding": 5.0 # }, "RadioButton::On:checked": { "background_color": 0xFF00B976, "border_color": 0xFF272727, }, "RadioButton.Label::On": { "color": 0xFFFFFFFF, }, "RadioButton::Off1:checked": { "background_color": 0xFF0000FF, "border_color": 0xFF00B976 }, "Button.Label::Off": { "color": 0xFFFFFFFF }}
573
Python
21.076922
39
0.52007
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/custom_slider_widget.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__ = ["CustomSliderWidget"] from typing import Optional import carb.settings from omni.kit.viewport.window import ViewportWindow import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl from .custom_base_widget import CustomBaseWidget NUM_FIELD_WIDTH = 500 SLIDER_WIDTH = ui.Percent(100) FIELD_HEIGHT = 22 # TODO: Once Field padding is fixed, this should be 18 SPACING = 4 TEXTURE_NAME = "slider_bg_texture" class CustomSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=1.0, default_val=0.0, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls( height=FIELD_HEIGHT, min=self.__min, max=self.__max, name="attr_slider" ) if self.__display_range: self._build_display_range() with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=2) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class AnaBokehSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=1.0, default_val=0.5, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_anisotropy = ui.SimpleFloatModel() current_anisotropy = 0.5 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_anisotropy, min=0.0, max=1.0, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_anisotropy(value): current_anisotropy = value settings = carb.settings.get_settings() settings.set("/rtx/post/dof/anisotropy", float(current_anisotropy)) if self._slider_model_anisotropy: self._slider_subscription_anisotropy = None self._slider_model_anisotropy.as_float = current_anisotropy self._slider_subscription_anisotropy = self._slider_model_anisotropy.subscribe_value_changed_fn( lambda model: update_anisotropy(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class LFlareSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=135.0, default_val=60, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_sensor_size = ui.SimpleFloatModel() current_sensor_size = 60.0 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_sensor_size, min=0.0, max=135.0, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_sensor_size(value): current_sensor_size = value settings = carb.settings.get_settings() settings.set("/rtx/post/lensFlares/sensorDiagonal", float(current_sensor_size)) if self._slider_model_sensor_size: self._slider_subscription_sensor_size = None self._slider_model_sensor_size.as_float = current_sensor_size self._slider_subscription_sensor_size = self._slider_model_sensor_size.subscribe_value_changed_fn( lambda model: update_sensor_size(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class FlareStretchSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.01, max=15.0, default_val=1.5, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_flare = ui.SimpleFloatModel() current_flare = 1.5 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_flare, min=0.01, max=15.0, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_flare(value): current_flare = value settings = carb.settings.get_settings() settings.set("/rtx/post/lensFlares/sensorAspectRatio", float(current_flare)) if self._slider_model_flare: self._slider_subscription_flare = None self._slider_model_flare.as_float = current_flare self._slider_subscription_flare = self._slider_model_flare.subscribe_value_changed_fn( lambda model: update_flare(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class BloomIntensitySliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=0.5, default_val=0.1, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_bloom = ui.SimpleFloatModel() current_bloom = 0.1 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_bloom, min=0.0, max=0.5, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_bloom(value): current_bloom = value settings = carb.settings.get_settings() settings.set("/rtx/post/lensFlares/flareScale", float(current_bloom)) if self._slider_model_bloom: self._slider_subscription_bloom = None self._slider_model_bloom.as_float = current_bloom self._slider_subscription_bloom = self._slider_model_bloom.subscribe_value_changed_fn( lambda model: update_bloom(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class LensBladesSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=3, max=11, default_val=6, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_blades = ui.SimpleIntModel() current_blades = 6 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.IntSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_blades, min=3, max=11, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_blades(value): current_blades = value settings = carb.settings.get_settings() settings.set("/rtx/post/lensFlares/blades", int(current_blades)) if self._slider_model_blades: self._slider_subscription_blades = None self._slider_model_blades.as_float = current_blades self._slider_subscription_blades = self._slider_model_blades.subscribe_value_changed_fn( lambda model: update_blades(model.as_int)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class BladeRotationWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=100.0, default_val=50.0, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_blade_rotation = ui.SimpleFloatModel() current_blade_rotation = 50.0 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_blade_rotation, min=0.0, max=100.0, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_blade_rotation(value): current_blade_rotation = value settings = carb.settings.get_settings() settings.set("/rtx/post/lensFlares/apertureRotation", float(current_blade_rotation)) if self._slider_model_blade_rotation: self._slider_subscription_blade_rotation = None self._slider_model_blade_rotation.as_float = current_blade_rotation self._slider_subscription_blade_rotatation = self._slider_model_blade_rotation.subscribe_value_changed_fn( lambda model: update_blade_rotation(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class CustomRatioSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.5, max=4.5, default_val=2.39, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._model_ratio_width = ui.SimpleFloatModel() current_ratio_width = 2.39 with ui.ZStack(): field = ui.FloatField(self._model_ratio_width, height=15, width=35) # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(5): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(model=field.model, min=0.5, max=4.5, name="attr_slider") if self.__display_range: self._build_display_range() def update_ratio_width(value): self.current_ratio_width = value active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/self.current_ratio_width viewport_api.resolution = (width,height) if self._model_ratio_width: self._slider_subscription_ratio_width = None self._model_ratio_width.as_float = current_ratio_width self._slider_subscription_ratio_width = self._model_ratio_width.subscribe_value_changed_fn( lambda model: update_ratio_width(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed)
53,968
Python
42.664239
142
0.510951
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/window.py
import omni.ui as ui import carb.settings from omni.kit.viewport.window import ViewportWindow from pathlib import Path from .custom_slider_widget import AnaBokehSliderWidget, LFlareSliderWidget, FlareStretchSliderWidget, BloomIntensitySliderWidget, LensBladesSliderWidget, BladeRotationWidget from .style import julia_modeler_style, ATTR_LABEL_WIDTH, BLOCK_HEIGHT from .style1 import style1 WINDOW_TITLE = "Anamorphic Effects" MY_IMAGE = Path(__file__).parent.parent.parent.parent / "data" / "AE.png" LABEL_WIDTH = 120 SPACING = 4 options = ["2.39:1 Cinemascope", "2.35:1 Scope", "2.20:1 Todd-AO", "2.76:1 Panavision Ultra-70", "2:1 2x Anamorphic", "1.77:1 Standard Widescreen (16x9)", "1.33:1 Standard Television (4x3)", "0.56:1 Mobile (9x16)", "1:1 Square"] NUM_FIELD_WIDTH = 500 SLIDER_WIDTH = ui.Percent(100) FIELD_HEIGHT = 22 SPACING = 4 TEXTURE_NAME = "slider_bg_texture" class AnamorphicEffectsWindow(ui.Window): def __init__(self, title: str, delegate=None, **kwargs,): self.__label_width = ATTR_LABEL_WIDTH super().__init__(title, **kwargs, width=375, height=425) self.frame.style = julia_modeler_style self.frame.set_build_fn(self._build_fn) ui.dock_window_in_window("Anamorphic Effects", "Property", ui.DockPosition.SAME, 0.3) def destroy(self): super().destroy() def label_width(self): return self.__label_width def _build_collapsable_header(self, collapsed, title): """Build a custom title of CollapsableFrame""" with ui.VStack(): ui.Spacer(height=8) with ui.HStack(): ui.Label(title, name="collapsable_name") if collapsed: image_name = "collapsable_opened" else: image_name = "collapsable_closed" ui.Image(name=image_name, width=10, height=10) ui.Spacer(height=8) ui.Line(style_type_name_override="HeaderLine") def _build_fn(self): def effect_off(): active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = ((width/16)*9) viewport_api.resolution = (width,height) settings = carb.settings.get_settings() settings.set("/rtx/post/dof/anisotropy", 0.0) settings.set("/rtx/post/lensFlares/enabled", False) self.aspect_frame.collapsed = True self.lens_frame.collapsed = True def effect_on(): active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() first = texture_res[0] height = first/2.39 viewport_api.resolution = (first,height) settings = carb.settings.get_settings() settings.set("/rtx/post/dof/anisotropy", 0.5) settings.set("/rtx/post/lensFlares/flareScale", 0.1) settings.set("/rtx/post/lensFlares/enabled", True) settings.set("/rtx/post/lensFlares/sensorAspectRatio", 1.5) settings.set("/rtx/post/lensFlares/blades", 3) self.aspect_frame.collapsed = False self.lens_frame.collapsed = False def combo_changed(item_model: ui.AbstractItemModel, item: ui.AbstractItem): value_model = item_model.get_item_value_model(item) current_index = value_model.as_int option = options[current_index] if option == "2.39:1 Cinemascope": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/2.39 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(2.39) if option == "2.35:1 Scope": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/2.35 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(2.35) if option == "2.20:1 Todd-AO": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/2.20 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(2.20) if option == "2.76:1 Panavision Ultra-70": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/1.76 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(2.76) if option == "2:1 2x Anamorphic": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/2 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(2.1) if option == "1.77:1 Standard Widescreen (16x9)": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = ((width/16)*9) viewport_api.resolution = (width,height) self._model_ratio_width.set_value(1.77) if option == "1.33:1 Standard Television (4x3)": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/1.33 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(1.33) if option == "0.56:1 Mobile (9x16)": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = ((width/9)*16) viewport_api.resolution = (width,height) self._model_ratio_width.set_value(0.56) if option == "1:1 Square": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width viewport_api.resolution = (width,height) self._model_ratio_width.set_value(1.0) with ui.ScrollingFrame(): with ui.VStack(height=0): with ui.HStack(): ui.Spacer(width=55) ui.Image(str(MY_IMAGE), fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.CENTER, height=45,) collection = ui.RadioCollection() with ui.HStack(style=style1): ui.Label("Activate:", width=10, style={"font_size":16}) ui.RadioButton(text ="Off", radio_collection=collection, clicked_fn=effect_off, name="Off") ui.RadioButton(text ="On", radio_collection=collection, clicked_fn=effect_on, name="On") self.aspect_frame = ui.CollapsableFrame("Aspect Ratio".upper(), name="group", build_header_fn=self._build_collapsable_header, collapsed=True) with self.aspect_frame: with ui.VStack(height=0): with ui.HStack(): ui.Label(" Aspect Ratio Preset: ", height=0, width=0) with ui.ZStack(): ui.Rectangle(name="combobox", height=BLOCK_HEIGHT) option_list = options combo_model: ui.AbstractItemModel = ui.ComboBox( 0, *option_list, name="dropdown_menu", height=10 ).model ui.Spacer(width=ui.Percent(10)) self.combo_sub = combo_model.subscribe_item_changed_fn(combo_changed) self._model_ratio_width = ui.SimpleFloatModel() current_ratio_width = 2.39 with ui.HStack(height=0): ui.Spacer(width=5) ui.Label("Custom Ratio: ", height=0, width=0) ui.Spacer(width=10) field = ui.FloatField(self._model_ratio_width, height=15, width=35) ui.Label(":1", height=15, width=15, style={"font_size": 20}) with ui.ZStack(): ui.Rectangle(name="combobox2", height=BLOCK_HEIGHT) ui.FloatSlider(model=field.model, min=0.5, max=4.5, name="attr_slider",) def update_ratio_width(value): self.current_ratio_width = value active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/self.current_ratio_width viewport_api.resolution = (width,height) if self._model_ratio_width: self._slider_subscription_ratio_width = None self._model_ratio_width.as_float = current_ratio_width self._slider_subscription_ratio_width = self._model_ratio_width.subscribe_value_changed_fn( lambda model: update_ratio_width(model.as_float)) self.lens_frame = ui.CollapsableFrame("Lens Effects".upper(), name="group", build_header_fn=self._build_collapsable_header, collapsed=True) with self.lens_frame: with ui.VStack(height=0): with ui.HStack(): ui.Spacer(width=5) ui.Label("Anamorphic Bokeh", height=0, width=0, tooltip="Controls Aniostropy value in Depth of Field Overrides located in the Post Processing menu") ui.Spacer(width=8) AnaBokehSliderWidget() with ui.HStack(): ui.Spacer(width=5) ui.Label("Lens Flare Intensity", height=0, width=0, tooltip="Controls Sensor Diagonal value in FFT Bloom located in the Post Processing menu") ui.Spacer(width=4) LFlareSliderWidget() with ui.HStack(): ui.Spacer(width=5) ui.Label("Lens Flare Stretch", height=0, width=0, tooltip="Controls Sensor Aspect Ratio value in FFT Bloom located in the Post Processing menu") ui.Spacer(width=13) FlareStretchSliderWidget() with ui.HStack(): ui.Spacer(width=5) ui.Label("Bloom Intensity", height=0, width=0, tooltip="Controls Bloom Intensity value in FFT Bloom located in the Post Processing menu") ui.Spacer(width=27) BloomIntensitySliderWidget() with ui.HStack(): ui.Spacer(width=5) ui.Label("Lens Blades", height=0, width=0, tooltip="Controls Lens Blades value in FFT Bloom located in the Post Processing menu") ui.Spacer(width=49) LensBladesSliderWidget() with ui.HStack(): ui.Spacer(width=5) ui.Label("Blade Rotation", height=0, width=0, tooltip="Controls Aperture Rotation value in FFT Bloom located in the Post Processing menu") ui.Spacer(width=34) BladeRotationWidget()
13,636
Python
50.851711
228
0.520387
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2023-03-02 - Initial version of anamorphic camera ## [1.1.0] - 2023-05-08 - added quality of life updates
215
Markdown
20.599998
80
0.683721
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/docs/README.md
# Anamorphic Effects An extension that emulates camera effects associated with anamorphic lenses
99
Markdown
18.999996
75
0.838384
stephenT0/funkyboy-exts-CornellBoxmaker/README.md
# Cornell Box Maker Make a Cornell Box that is customizable in real time. ## Adding This Extension To add this extension to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com/stephenT0/funkyboy-exts-CornellBoxmaker?branch=main&dir=exts` Manual installation: 1. Download Zip 2. Extract and place into a directory of your choice 3. Go into: Extension Manager -> Gear Icon -> Extension Search Path 4. Add a custom search path ending with: \funkyboy-exts-CornellBoxmaker-master\exts ## Acknowledgments Thanks to the Nvidia Omniverse Discord for helping me make this extension. In particular AshleyG and Mati.
698
Markdown
35.789472
109
0.776504
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/funkyboy/cornell/box/extension.py
import omni.ext import omni.kit.ui from .window import CornellBoxWindow, WINDOW_TITLE class CornellBoxExtension(omni.ext.IExt): def on_startup(self, ext_id): self._menu_path = f"Window/{WINDOW_TITLE}" self._window = CornellBoxWindow(WINDOW_TITLE, self._menu_path) self._menu = omni.kit.ui.get_editor_menu().add_item(self._menu_path, self._on_menu_click, True) def on_shutdown(self): omni.kit.ui.get_editor_menu().remove_item(self._menu) if self._window is not None: self._window.destroy() self._window = None def _on_menu_click(self, menu, toggled): if toggled: if self._window is None: self._window = CornellBoxWindow(WINDOW_TITLE, self._menu_path) else: self._window.show() else: if self._window is not None: self._window.hide()
922
Python
29.766666
103
0.591106
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/funkyboy/cornell/box/box_maker.py
import omni.kit.commands import omni.usd import omni.kit.undo from pxr import Gf, Sdf, Usd class BoxMaker: def __init__(self) -> None: self._stage:Usd.Stage = omni.usd.get_context().get_stage() omni.kit.commands.execute('DeletePrims', paths=["/World/CB_Looks", "/World/Cornell_Box", "/World/defaultLight", "/Environment"]) self.Create_Box() def Create_Panel(self): plane_prim_path = omni.usd.get_stage_next_free_path(self._stage, self.geom_xform_path.AppendPath("Plane"), False) omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',prim_type='Plane') omni.kit.commands.execute('MovePrim', path_from='/World/Plane', path_to=plane_prim_path) mtl_path = Sdf.Path(omni.usd.get_stage_next_free_path(self._stage, self.looks_scope_path.AppendPath("OmniPBR"), False)) omni.kit.commands.execute('CreateMdlMaterialPrim', mtl_url='OmniPBR.mdl', mtl_name='OmniPBR', mtl_path=str(mtl_path)) omni.kit.commands.execute('BindMaterial', prim_path=plane_prim_path, material_path=str(mtl_path), strength=['strongerThanDescendants']) plane_prim = self._stage.GetPrimAtPath(plane_prim_path) plane_prim.GetAttribute("xformOp:scale").Set(Gf.Vec3d(4,4,4)) shader_prim = self._stage.GetPrimAtPath(mtl_path.AppendPath("Shader")) mtl_color_attr = shader_prim.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr.Set((0.9, 0.9, 0.9)) return plane_prim def Create_Box(self): with omni.kit.undo.group(): self.geom_xform_path = Sdf.Path(omni.usd.get_stage_next_free_path(self._stage, "/World/Cornell_Box", False)) self.looks_scope_path = Sdf.Path(omni.usd.get_stage_next_free_path(self._stage, "/World/CB_Looks", False)) self.geom_xform_path2 = Sdf.Path(omni.usd.get_stage_next_free_path(self._stage, "/World/Cornell_Box/Panels", False)) omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Xform', prim_path=str(self.geom_xform_path)) omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Xform', prim_path=str(self.geom_xform_path2)) omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Scope', prim_path=str(self.looks_scope_path)) #create floor panel = self.Create_Panel() panel.GetAttribute("xformOp:scale").Set(Gf.Vec3d( 4, 4, 15)) #create back wall panel = self.Create_Panel() panel.GetAttribute("xformOp:rotateXYZ").Set(Gf.Vec3d(90, 0, 90)) panel.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0, 200, -400)) #create front wall # panel = self.Create_Panel() # panel.GetAttribute("xformOp:rotateXYZ").Set(Gf.Vec3d(90, 0, 90)) # panel.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0, 100, 100)) #create ceiling panel = self.Create_Panel() panel.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0, 400, 0)) panel.GetAttribute("xformOp:scale").Set(Gf.Vec3d(4, 4, 15)) #create colored wall 1 panel = self.Create_Panel() panel.GetAttribute("xformOp:rotateXYZ").Set(Gf.Vec3d(0, 0, 90)) panel.GetAttribute("xformOp:translate").Set(Gf.Vec3d(-200, 200, 0)) panel.GetAttribute("xformOp:scale").Set(Gf.Vec3d(4, 4, 15)) #create colored wall 2 panel = self.Create_Panel() panel.GetAttribute("xformOp:rotateXYZ").Set(Gf.Vec3d(0, 0, 90)) panel.GetAttribute("xformOp:translate").Set(Gf.Vec3d(200, 200, 0)) panel.GetAttribute("xformOp:scale").Set(Gf.Vec3d(4, 4, 15)) #move panels omni.kit.commands.execute('MovePrim', path_from='/World/Cornell_Box/Plane', path_to='/World/Cornell_Box/Panels/Plane') omni.kit.commands.execute('MovePrim', path_from='/World/Cornell_Box/Plane_01', path_to='/World/Cornell_Box/Panels/Plane_01') omni.kit.commands.execute('MovePrim', path_from='/World/Cornell_Box/Plane_02', path_to='/World/Cornell_Box/Panels/Plane_02') omni.kit.commands.execute('MovePrim', path_from='/World/Cornell_Box/Plane_03', path_to='/World/Cornell_Box/Panels/Plane_03') omni.kit.commands.execute('MovePrim', path_from='/World/Cornell_Box/Plane_04', path_to='/World/Cornell_Box/Panels/Plane_04') #make wall red omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/CB_Looks/OmniPBR_03/Shader.inputs:diffuse_color_constant'), value=Gf.Vec3f(1.0, 0.0, 0.0), prev=Gf.Vec3f(0.9, 0.9, 0.9)) #make wall green omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/CB_Looks/OmniPBR_04/Shader.inputs:diffuse_color_constant'), value=Gf.Vec3f(0.0, 0.9, 0.2), prev=Gf.Vec3f(0.9, 0.9, 0.9)) #create rectangle light light_prim_path = omni.usd.get_stage_next_free_path(self._stage, self.geom_xform_path.AppendPath("RectLight"), False) omni.kit.commands.execute('CreatePrim',prim_type='RectLight', attributes={'width': 150, 'height': 100, 'intensity': 17500}) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/RectLight.xformOp:translate'), value=Gf.Vec3d(0.0, 399.9000, 125), prev=Gf.Vec3d(0.0, 0.0, 0.0)) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/RectLight.xformOp:rotateXYZ'), value=Gf.Vec3d(0.0, -90.0, -90.0), prev=Gf.Vec3d(0.0, 0.0, 0.0)) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/RectLight.visibleInPrimaryRay'), value=True, prev=None) omni.kit.commands.execute('MovePrim', path_from='/World/RectLight', path_to='/World/Cornell_Box/RectLight') light_prim = self._stage.GetPrimAtPath(light_prim_path) #Visible light #light_prim.GetAttribute("xformOp:scale").Set(Gf.Vec3d(4,4,4)) light_prim.CreateAttribute("visibleInPrimaryRay", Sdf.ValueTypeNames.Bool).Set(True) #Create Camera omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Camera', attributes={'focusDistance': 400, 'focalLength': 27.5}) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/Camera.xformOp:translate'), value=Gf.Vec3d(0.0, 200.0, 1180.10002), prev=Gf.Vec3d(0.0, 200.0, 1200.0)) omni.kit.commands.execute('MovePrim', path_from='/World/Camera', path_to='/World/Cornell_Box/Camera') #Create Cubes omni.kit.commands.execute('CreateMeshPrimWithDefaultXform', prim_type='Cube') omni.kit.commands.execute('TransformPrimSRT', path=Sdf.Path('/World/Cube'), new_translation=Gf.Vec3d(0.0, 50.0, 100.0), new_rotation_euler=Gf.Vec3d(0.0, 0.0, 0.0), new_rotation_order=Gf.Vec3i(0, 1, 2), new_scale=Gf.Vec3d(1.0, 1.0, 1.0), old_translation=Gf.Vec3d(0.0, 0.0, 0.0), old_rotation_euler=Gf.Vec3d(0.0, 0.0, 0.0), old_rotation_order=Gf.Vec3i(0, 1, 2), old_scale=Gf.Vec3d(1.0, 1.0, 1.0)) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/Cube.xformOp:rotateXYZ'), value=Gf.Vec3d(0.0, -45, 0.0), prev=Gf.Vec3d(0.0, 0.0, 0.0)) omni.kit.commands.execute('BindMaterial', material_path='/World/CB_Looks/OmniPBR', prim_path=['/World/Cube'], strength=['weakerThanDescendants']) omni.kit.commands.execute('CopyPrims', paths_from=['/World/Cube'], duplicate_layers=False, combine_layers=False, flatten_references=False) omni.kit.commands.execute('TransformPrimSRT', path=Sdf.Path('/World/Cube_01'), new_translation=Gf.Vec3d(99.8525344330427, 49.99999999997604, -83.82421861450064), new_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), new_rotation_order=Gf.Vec3i(0, 1, 2), new_scale=Gf.Vec3d(1.0, 1.0, 1.0), old_translation=Gf.Vec3d(0.0, 50.0, 100.0), old_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), old_rotation_order=Gf.Vec3i(0, 1, 2), old_scale=Gf.Vec3d(1.0, 1.0, 1.0)) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/Cube_01.xformOp:scale'), value=Gf.Vec3d(1.0, 1.5, 1.0), prev=Gf.Vec3d(1.0, 1.598320722579956, 1.0)) omni.kit.commands.execute('TransformPrimSRT', path=Sdf.Path('/World/Cube_01'), new_translation=Gf.Vec3d(99.85253443304272, 74.75868843615456, -100.0), new_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), new_rotation_order=Gf.Vec3i(0, 1, 2), new_scale=Gf.Vec3d(1.0, 1.5, 1.0), old_translation=Gf.Vec3d(99.8525344330427, 49.99999999997604, -83.82421861450064), old_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), old_rotation_order=Gf.Vec3i(0, 1, 2), old_scale=Gf.Vec3d(1.0, 1.5, 1.0)) omni.kit.commands.execute('CopyPrims', paths_from=['/World/Cube_01'], duplicate_layers=False, combine_layers=False, flatten_references=False) omni.kit.commands.execute('TransformPrimSRT', path=Sdf.Path('/World/Cube_02'), new_translation=Gf.Vec3d(-100.31094017767478, 74.75868843615382, -200.65476487048673), new_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), new_rotation_order=Gf.Vec3i(0, 1, 2), new_scale=Gf.Vec3d(1.0, 1.5, 1.0), old_translation=Gf.Vec3d(99.85253443304272, 74.75868843615456, -100.0), old_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), old_rotation_order=Gf.Vec3i(0, 1, 2), old_scale=Gf.Vec3d(1.0, 1.5, 1.0)) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/Cube_02.xformOp:scale'), value=Gf.Vec3d(1.0, 2.0, 1.0), prev=Gf.Vec3d(1.0, 1.5, 1.0)) omni.kit.commands.execute('TransformPrimSRT', path=Sdf.Path('/World/Cube_02'), new_translation=Gf.Vec3d(-100.31094017767478, 100.0, -200.65476487048673), new_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), new_rotation_order=Gf.Vec3i(0, 1, 2), new_scale=Gf.Vec3d(1.0, 2.0, 1.0), old_translation=Gf.Vec3d(-100.31094017767478, 74.75868843615382, -200.65476487048673), old_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), old_rotation_order=Gf.Vec3i(0, 1, 2), old_scale=Gf.Vec3d(1.0, 2.0, 1.0)) omni.kit.commands.execute('MovePrim', path_from='/World/Cube', path_to='/World/Cornell_Box/Cube') omni.kit.commands.execute('MovePrim', path_from='/World/Cube_01', path_to='/World/Cornell_Box/Cube_01') omni.kit.commands.execute('MovePrim', path_from='/World/Cube_02', path_to='/World/Cornell_Box/Cube_02')
12,213
Python
39.849498
136
0.563089
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/funkyboy/cornell/box/window.py
import omni.ext import omni.ui as ui import omni.kit.commands import omni.usd from pxr import Gf, Sdf from .box_maker import BoxMaker from omni.ui import color as cl from omni.ui import constant as fl WINDOW_TITLE = "Cornell Box Maker" SPACING = 4 combo_sub = None options = ["Classic", "SIGGRAPH 1984", "NVIDIA Omniverse"] class CornellBoxWindow(ui.Window): def __init__(self, title, menu_path): super().__init__(title, width=450, height=280) self._menu_path = menu_path self.set_visibility_changed_fn(self._on_visibility_changed) self.frame.set_build_fn(self._build_window) #color widget variables self._color_model = None self._color_model_2 = None self._color_changed_subs = [] self._color_changed_subs_2 = [] self._path_model = None self._path_model_2 = None self._change_info_path_subscription = None self._change_info_path_subscription_2 = None self._stage = omni.usd.get_context().get_stage() self._OmniPBR_Path_03 = "/World/CB_Looks/OmniPBR_03/Shader.inputs:diffuse_color_constant" self._OmniPBR_Path_04 = "/World/CB_Looks/OmniPBR_04/Shader.inputs:diffuse_color_constant" #subscribe mat 1 attr_path = self._OmniPBR_Path_03 color_attr = self._stage.GetAttributeAtPath(attr_path) if color_attr: self._change_info_path_subscription = omni.usd.get_watcher().subscribe_to_change_info_path( attr_path, self._on_mtl_attr_changed) #subscribe mat 2 attr_path_2 = self._OmniPBR_Path_04 color_attr_2 = self._stage.GetAttributeAtPath(attr_path_2) if color_attr_2: self._change_info_path_subscription_2 = omni.usd.get_watcher().subscribe_to_change_info_path( attr_path_2, self._on_mtl_attr_changed_2) #combox group variables self.combo_sub = None #main ui Window def _build_window(self): #with self.frame: with ui.ScrollingFrame(): with ui.VStack(height=0): def on_click(): BoxMaker() with ui.HStack(height=0, spacing=SPACING): ui.Label("Start Here: ", height=40, width=0) ui.Button("Make Box", clicked_fn=lambda: on_click()) with ui.CollapsableFrame("Color", name="group", height=50): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(height=0, spacing=SPACING): ui.Label("Colored Wall #1: ", height=0, width=0) self._color_model = ui.ColorWidget(0.9, 0.0, 0.0, height=0).model for item in self._color_model.get_item_children(): component = self._color_model.get_item_value_model(item) self._color_changed_subs.append(component.subscribe_value_changed_fn(self._on_color_changed)) #ui.FloatDrag(component) self._path_model = self._OmniPBR_Path_03 with ui.HStack(height=0, spacing=SPACING): ui.Label("Colored Wall #2: ", height=0, width=0) self._color_model_2 = ui.ColorWidget(0.0, 0.9, 0.2, height=0).model for item in self._color_model_2.get_item_children(): component = self._color_model_2.get_item_value_model(item) self._color_changed_subs_2.append(component.subscribe_value_changed_fn(self._on_color_changed_2)) #ui.FloatDrag(component) self._path_model_2 = self._OmniPBR_Path_04 #combobox group with ui.HStack(height=0, spacing=SPACING): ui.Label("Select Preset Style:", height=0, width=0) combo_model: ui.AbstractItemModel = ui.ComboBox(0, *options).model def combo_changed(item_model: ui.AbstractItemModel, item: ui.AbstractItem): value_model = item_model.get_item_value_model(item) current_index = value_model.as_int option = options[current_index] #print(f"Selected '{option}' at index {current_index}.") if option == "Classic": mtl_path_1 = "/World/CB_Looks/OmniPBR_03/Shader" shader_prim_1 = self._stage.GetPrimAtPath(mtl_path_1) mtl_color_attr_1 = shader_prim_1.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_1.Set((0.9, 0.0, 0.0)) mtl_path_2 = "/World/CB_Looks/OmniPBR_04/Shader" shader_prim_2 = self._stage.GetPrimAtPath(mtl_path_2) mtl_color_attr_2 = shader_prim_2.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_2.Set((0.0, 0.9, 0.2)) if option == "SIGGRAPH 1984": mtl_path_1 = "/World/CB_Looks/OmniPBR_03/Shader" shader_prim_1 = self._stage.GetPrimAtPath(mtl_path_1) mtl_color_attr_1 = shader_prim_1.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_1.Set((0.9, 0.0, 0.0)) mtl_path_2 = "/World/CB_Looks/OmniPBR_04/Shader" shader_prim_2 = self._stage.GetPrimAtPath(mtl_path_2) mtl_color_attr_2 = shader_prim_2.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_2.Set((0.0, 0.0, 0.9)) if option == "NVIDIA Omniverse": mtl_path_1 = "/World/CB_Looks/OmniPBR_03/Shader" shader_prim_1 = self._stage.GetPrimAtPath(mtl_path_1) mtl_color_attr_1 = shader_prim_1.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_1.Set((0.069, 0.069, 0.069)) # self._color_model.Set((0.069, 0.069, 0.069)) mtl_path_2 = "/World/CB_Looks/OmniPBR_04/Shader" shader_prim_2 = self._stage.GetPrimAtPath(mtl_path_2) mtl_color_attr_2 = shader_prim_2.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_2.Set((0.4, 0.8, 0.0)) self.combo_sub = combo_model.subscribe_item_changed_fn(combo_changed) ui.Spacer(width=1) ui.Spacer(width=0,height=0) #scale sliders for cornell box xform self._slider_model_x = ui.SimpleFloatModel() self._slider_model_y = ui.SimpleFloatModel() self._slider_model_z = ui.SimpleFloatModel() self._source_prim_model = ui.SimpleStringModel() with ui.CollapsableFrame("Scale", name="group", height=100,): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Spacer(width=5) ui.Label("Box Width: ", height=0, width=0) #ui.Spacer(width=5) #ui.FloatDrag(self._slider_model, min=0.1, max=5) ui.FloatSlider(self._slider_model_x, min=0.1, max=10, step=0.05) #ui.Spacer(width=10) def update_scale_x(prim_name, value): usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cornell_Box/Panels") scale_attr = cube_prim.GetAttribute("xformOp:scale") scale = scale_attr.Get() scale_attr.Set(Gf.Vec3d(value, scale[1], scale[2])) if self._slider_model_x: self._slider_subscription_x = None self._slider_model_x.as_float = 1.0 self._slider_subscription_x = self._slider_model_x.subscribe_value_changed_fn( lambda m, #the following is where we change from self.model to self._source_prim_model p=self._source_prim_model: update_scale_x(p, m.as_float) ) with ui.HStack(): ui.Spacer(width=5) ui.Label("Box Height: ", height=0, width=0) #ui.Spacer(width=5) ui.FloatSlider(self._slider_model_y, min=0.1, max=10, step=0.05) #ui.Spacer(width=10) def update_scale_y(prim_name, value): usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cornell_Box/Panels") scale_attr = cube_prim.GetAttribute("xformOp:scale") scale = scale_attr.Get() scale_attr.Set(Gf.Vec3d(scale[0], value, scale[2])) #usd_context = omni.usd.get_context() #stage = usd_context.get_stage() light_prim = stage.GetPrimAtPath("/World/Cornell_Box/RectLight") trans_attr = light_prim.GetAttribute("xformOp:translate") trans = trans_attr.Get() trans_attr.Set(Gf.Vec3d(trans[0], ((399.9) * value), trans[2])) if self._slider_model_y: self._slider_subscription_y = None self._slider_model_y.as_float = 1.0 self._slider_subscription = self._slider_model_y.subscribe_value_changed_fn( lambda m, #the following is where we change from self.model to self._source_prim_model p=self._source_prim_model: update_scale_y(p, m.as_float) ) with ui.HStack(): ui.Spacer(width=5) ui.Label("Box Length: ", height=0, width=0) #ui.Spacer(width=5) ui.FloatSlider(self._slider_model_z, min=0.1, max=10, step=0.05) #ui.Spacer(width=10) def update_scale_z(prim_name, value): usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cornell_Box/Panels") scale_attr = cube_prim.GetAttribute("xformOp:scale") scale = scale_attr.Get() scale_attr.Set(Gf.Vec3d(scale[0], scale[1], value)) if self._slider_model_z: self._slider_subscription_z = None self._slider_model_z.as_float = 1.0 self._slider_subscription_z = self._slider_model_z.subscribe_value_changed_fn( lambda m, #the following is where we change from self.model to self._source_prim_model p=self._source_prim_model: update_scale_z(p, m.as_float)) #dock super().dock_in_window("Environments", ui.DockPosition.SAME) #functions for color picker def _on_mtl_attr_changed(self, path): color_attr = self._stage.GetAttributeAtPath(path) color_model_items = self._color_model.get_item_children() if color_attr: color = color_attr.Get() for i in range(len(color)): component = self._color_model.get_item_value_model(color_model_items[i]) component.set_value(color[i]) def _on_mtl_attr_changed_2(self, path): color_attr = self._stage.GetAttributeAtPath(path) color_model_items = self._color_model_2.get_item_children() if color_attr: color = color_attr.Get() for i in range(len(color)): component = self._color_model_2.get_item_value_model(color_model_items[i]) component.set_value(color[i]) def _on_color_changed(self, model): values = [] for item in self._color_model.get_item_children(): component = self._color_model.get_item_value_model(item) values.append(component.as_float) if Sdf.Path.IsValidPathString(self._path_model): attr_path = Sdf.Path(self._path_model) color_attr = self._stage.GetAttributeAtPath(attr_path) if color_attr: color_attr.Set(Gf.Vec3f(*values[0:3])) def _on_color_changed_2(self, model): values = [] for item in self._color_model_2.get_item_children(): component = self._color_model_2.get_item_value_model(item) values.append(component.as_float) if Sdf.Path.IsValidPathString(self._path_model_2): attr_path = Sdf.Path(self._path_model_2) color_attr = self._stage.GetAttributeAtPath(attr_path) if color_attr: color_attr.Set(Gf.Vec3f(*values[0:3])) def _on_visibility_changed(self, visible): omni.kit.ui.get_editor_menu().set_value(self._menu_path, visible) def destroy(self) -> None: self._change_info_path_subscription = None self._color_changed_subs = None return super().destroy() def on_shutdown(self): self._win = None def show(self): self.visible = True self.focus() def hide(self): self.visible = False
15,194
Python
47.701923
146
0.490325
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.2.1" # The title and description fields are primarily for displaying extension info in UI title = "Cornell Box Maker" description="Make a cornell box and customize its appearance and dimensions" icon = "data/icon.png" preview_image = "data/preview.png" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Modeling" # Keywords for the extension keywords = ["Box", "Cornell", "Maker"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import funkyboy.cornell.box". [[python.module]] name = "funkyboy.cornell.box"
840
TOML
26.129031
109
0.736905
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/docs/CHANGELOG.md
# Changelog ## [0.1.0] 2022-08-18 -Initial version of Cornell Box Maker ## [0.1.1] 2022-09-21 -Color widget working ## [0.1.2] 2022-10-02 -Added Combo Box Widget -Added Docking
177
Markdown
18.777776
37
0.689266
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/docs/README.md
Make a Cornell Box that is customizable in real time. Extension works best from a new scene. -extension currently works best started from a new scene with the extension freshly loaded To do: -Lots of small issues to reslove -overall stability and usability -improve UI issues: -takes 3 clicks to close window -reliant on a World xform to work -color widgets not reliable after a new scene is created
405
Markdown
30.230767
92
0.790123
stephenT0/funkyboy-camera-speed/README.md
# Tea Time 10 Camera speed presets for scene navigation ## Adding This Extension To add this extension to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com//stephenT0/funkyboy-exts-camera-speed-selector?branch=main&dir=exts` Manual installation: 1. Download Zip 2. Extract and place into a directory of your choice 3. Go into: Extension Manager -> Gear Icon -> Extension Search Path 4. Add a custom search path ending with: \funkyboy-exts-camera-speed-selector-master\exts ## Acknowledgments Thanks to the Nvidia Omniverse Discord for helping me make this extension. In particular Jen, Mati, and @ericcraft-mh.
705
Markdown
36.157893
119
0.771631
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/_window_copy.py
import omni.ext import omni.ui as ui import carb.settings import carb import omni.kit.commands from .style import style1 LABEL_WIDTH = 120 SPACING = 4 class SimpleCamWindow(ui.Window): def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ CAMERA_VEL = "/persistent/app/viewport/camMoveVelocity" # Camera velocity setting self._settings = carb.settings.get_settings() # Grab carb settings with self.frame: with ui.VStack(): ui.Button("Select a Camera Speed", style={"background_color":0xFF6FF, "color":0xFF00B976, "font_size":20,}, tooltip=" right click + WASD to fly ") def on_click(): self._settings.set(CAMERA_VEL, 0.01) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click2(): self._settings.set(CAMERA_VEL, 0.1) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click3(): self._settings.set(CAMERA_VEL, 0.5) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click4(): self._settings.set(CAMERA_VEL, 2.5) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click5(): self._settings.set(CAMERA_VEL, 5.0) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click6(): self._settings.set(CAMERA_VEL, 7.5) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click7(): self._settings.set(CAMERA_VEL, 10.0) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click8(): self._settings.set(CAMERA_VEL, 20.0) carb.log_info(f"Camera velocity set to: {self._settings.get_as_float(CAMERA_VEL)}") def on_click9(): self._settings.set(CAMERA_VEL, 30.0) carb.log_info(f"Camera velocity set to: {self._settings.get_as_float(CAMERA_VEL)}") def on_click10(): self._settings.set(CAMERA_VEL, 50.0) carb.log_info(f"Camera velocity set to: {self._settings.get_as_float(CAMERA_VEL)}") def on_click11(): omni.kit.commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='Viewport') # Added a clicked function to handle the click call def call_clicked(val:int): if val == 0: radbt0.call_clicked_fn() if val == 1: radbt1.call_clicked_fn() if val == 2: radbt2.call_clicked_fn() if val == 3: radbt3.call_clicked_fn() if val == 4: radbt4.call_clicked_fn() if val == 5: radbt5.call_clicked_fn() if val == 6: radbt6.call_clicked_fn() if val == 7: radbt7.call_clicked_fn() if val == 8: radbt8.call_clicked_fn() if val == 9: radbt9.call_clicked_fn() #the slider collection = ui.RadioCollection() intSlider = ui.IntSlider( collection.model, min=0, max=9, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": 0xFF00B976, "color": 0xFF00B976, "font_size": 14.0, }) intSlider.model.add_value_changed_fn(lambda val:call_clicked(val.get_value_as_int())) #the buttons with ui.HStack(style=style1): radbt0 = ui.RadioButton(text ="1", name="one", radio_collection=collection, clicked_fn=lambda: on_click()) radbt1 = ui.RadioButton(text ="2", name="two", radio_collection=collection, clicked_fn=lambda: on_click2()) radbt2 = ui.RadioButton(text ="3", name="three", radio_collection=collection, clicked_fn=lambda: on_click3()) radbt3 = ui.RadioButton(text ="4", name="four", radio_collection=collection, clicked_fn=lambda: on_click4()) radbt4 = ui.RadioButton(text ="5", name="five", radio_collection=collection, clicked_fn=lambda: on_click5()) radbt5 = ui.RadioButton(text ="6", name="six", radio_collection=collection, clicked_fn=lambda: on_click6()) radbt6 = ui.RadioButton(text ="7", name="seven", radio_collection=collection, clicked_fn=lambda: on_click7()) radbt7 = ui.RadioButton(text ="8", name="eight", radio_collection=collection, clicked_fn=lambda: on_click8()) radbt8 = ui.RadioButton(text ="9", name="nine", radio_collection=collection, clicked_fn=lambda: on_click9()) radbt9 = ui.RadioButton(text ="10", name="ten", radio_collection=collection, clicked_fn=lambda: on_click10())
6,418
Python
47.263158
165
0.509037
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/style.py
import omni.ui as ui style1 = { # "RadioButton": { # "border_width": 0.5, # "border_radius": 0.0, # "margin": 5.0, # "padding": 5.0 # }, "RadioButton::one": { "background_color": 0xFF00B976, "border_color": 0xFF272727, }, "RadioButton.Label::one": { "color": 0xFFFFFFFF, }, "RadioButton::two": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::two": { "color": 0xFFFFFFFF }, "RadioButton::three": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::three": { "color": 0xFFFFFFFF }, "RadioButton::four": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::four": { "color": 0xFFFFFFFF }, "RadioButton::five": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::five": { "color": 0xFFFFFFFF }, "RadioButton::six": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::six": { "color": 0xFFFFFFFF }, "RadioButton::seven": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::seven": { "color": 0xFFFFFFFF }, "RadioButton::eight": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::eight": { "color": 0xFFFFFFFF }, "RadioButton::nine": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::nine": { "color": 0xFFFFFFFF }, "RadioButton::ten": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::ten": { "color": 0xFFFFFFFF },}
2,514
Python
29.670731
47
0.393795
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/extension.py
#__all__ = ["ExampleWindowExtension"] from .window import SimpleCamWindow, WINDOW_TITLE import omni.ext import omni.kit.ui class SimpleCamExtension(omni.ext.IExt): def on_startup(self, ext_id): self._menu_path = f"Window/{WINDOW_TITLE}" self._window = SimpleCamWindow(WINDOW_TITLE, self._menu_path) self._menu = omni.kit.ui.get_editor_menu().add_item(self._menu_path, self._on_menu_click, True) def on_shutdown(self): omni.kit.ui.get_editor_menu().remove_item(self._menu) if self._window is not None: self._window.destroy() self._window = None def _on_menu_click(self, menu, toggled): if toggled: if self._window is None: self._window = SimpleCamWindow(WINDOW_TITLE, self._menu_path) else: self._window.show() else: if self._window is not None: self._window.hide()
957
Python
25.61111
103
0.591432
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/sample_code_for_cam_speed.py
import omni.ext import omni.ui as ui import carb.settings import carb class MyExtension(omni.ext.IExt): def on_startup(self, ext_id): CAMERA_VEL = "/persistent/app/viewport/camMoveVelocity" # Camera velocity setting self._settings = carb.settings.get_settings() # Grab carb settings self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): ui.Label("Some Label") def on_click(): carb.log_info(f"Camera velocity before: {self._settings.get_as_string(CAMERA_VEL)}") # Here is the function we use to set setting values. Setting values are stored inside of carb # so we have to give it the path for that setting, hence why we have CAMERA_VEL # 100 is the new camera speed that is hard coded in, you could put any number there self._settings.set(CAMERA_VEL, 100) carb.log_info(f"Camera velocity after: {self._settings.get_as_string(CAMERA_VEL)}") ui.Button("Click Me", clicked_fn=lambda: on_click()) def on_shutdown(self): print("[omni.code.snippets] MyExtension shutdown") #Thank you Jen from Nvidia Omniverse Discord
1,292
Python
46.888887
113
0.623065
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/sample_code_for_slider.py
import omni.ext import omni.ui as ui class MyExtension(omni.ext.IExt): radbt0 = ui.RadioButton radbt1 = ui.RadioButton def on_startup(self, ext_id): print("[funkyboy.hello.world.1] MyExtension startup") self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): def on_click(): print("clicked!") def on_click2(): print("clicked!2") # Added a clicked function to handle the click call def call_clicked(val:int): if val == 0: radbt0.call_clicked_fn() if val == 1: radbt1.call_clicked_fn() collection = ui.RadioCollection() intSlider = ui.IntSlider( collection.model, min=0, max=1, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": 0xFF00B976, "color": 0xFF00B976, "font_size": 18.0, }) # pass lambda arg.get_value_as_int() to call_Clicked(arg.get_value_as_int()) intSlider.model.add_value_changed_fn(lambda val:call_clicked(val.get_value_as_int())) with ui.HStack(): radbt0 = ui.RadioButton(text ="1",radio_collection=collection, clicked_fn=lambda: on_click()) radbt1 = ui.RadioButton(text ="2", radio_collection=collection, clicked_fn=lambda: on_click2()) def on_shutdown(self): print("[funkyboy.hello.world.1] MyExtension shutdown") #Here is the version with the dictionary. # import omni.ext # import omni.ui as ui # class MyExtension(omni.ext.IExt): # radbt0 = ui.RadioButton # radbt1 = ui.RadioButton # def on_startup(self, ext_id): # print("[funkyboy.hello.world.1] MyExtension startup") # self._window = ui.Window("My Window", width=300, height=300) # with self._window.frame: # with ui.VStack(): # def on_click(): # print("clicked!") # def on_click2(): # print("clicked!2") # collection = ui.RadioCollection() # intSlider = ui.IntSlider( # collection.model, # min=0, # max=1, # style={ # "draw_mode": ui.SliderDrawMode.HANDLE, # "background_color": 0xFF00B976, # "color": 0xFF00B976, # "font_size": 18.0, # }) # # pass lambda arg.get_value_as_int() to call_clicked[(]arg.get_value_as_int()]() # intSlider.model.add_value_changed_fn(lambda val:call_clicked[val.get_value_as_int()]()) # with ui.HStack(): # radbt0 = ui.RadioButton(text ="1",radio_collection=collection, clicked_fn=lambda: on_click()) # radbt1 = ui.RadioButton(text ="2", radio_collection=collection, clicked_fn=lambda: on_click2()) # # call_clicked ditionary approach # # NOTE: no () at the end of the line, instead it is at the end of the add_value_changed_fn call # call_clicked = { # 0:radbt0.call_clicked_fn, # 1:radbt1.call_clicked_fn # } # def on_shutdown(self): # print("[funkyboy.hello.world.1] MyExtension shutdown") #Thank you @ericcraft-mh from Nvidia Omniverse Discord
3,820
Python
46.172839
117
0.491099
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.2" # The title and description fields are primarily for displaying extension info in UI title = "Simple Camera Speed Selector" description="10 presets for camera speed. Use right click + WASD to fly around" icon = "data/icon.png" preview_image = "data/preview.png" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "UI, Camera" # Keywords for the extension keywords = ["Camera", "Speed", "Scene Navigation"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import Funkyboy.cameraspeed". [[python.module]] name = "Funkyboy.cameraspeed"
866
TOML
26.967741
109
0.737875
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/docs/CHANGELOG.md
# Changelog ## [0.1.0] 2022-08-18 -Initial version of Simple Camera Speed Selector ## [0.1.1] 2022-09-27 -test for omniverse community tab ## [0.1.2] 2022-10-03 -added Docking
176
Markdown
21.124997
48
0.698864
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/docs/README.md
10 Camera speed presets for scene navigation
49
Markdown
8.999998
45
0.77551
Helbling-Technik/orbit.maze/scripts/create_env.py
from __future__ import annotations import argparse from omni.isaac.orbit.app import AppLauncher # add argparse arguments parser = argparse.ArgumentParser(description="Test adding sensors on a robot.") parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to spawn.") parser.add_argument("--num_cams", type=int, default=1, help="Number of cams per env (2 Max)") parser.add_argument("--save", action="store_true", default=False, help="Save the obtained data to disk.") # parser.add_argument("--livestream", type=int, default="1", help="stream remotely") # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) # parse the arguments args_cli = parser.parse_args() args_cli.num_cams = min(2, args_cli.num_cams) args_cli.num_cams = max(0, args_cli.num_cams) args_cli.num_envs = max(1, args_cli.num_envs) # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app import math from PIL import Image import torch import traceback import carb import os import omni.isaac.orbit.sim as sim_utils from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg from omni.isaac.orbit.scene import InteractiveScene, InteractiveSceneCfg from omni.isaac.orbit.sensors import CameraCfg, ContactSensorCfg, RayCasterCfg, patterns from omni.isaac.orbit.actuators import ImplicitActuatorCfg from omni.isaac.orbit.utils import configclass from omni.isaac.orbit.utils.timer import Timer import omni.replicator.core as rep from omni.isaac.orbit.utils import convert_dict_to_backend from tqdm import tqdm current_script_path = os.path.abspath(__file__) # Absolute path of the project root (assuming it's three levels up from the current script) project_root = os.path.join(current_script_path, "../..") MAZE_CFG = ArticulationCfg( spawn=sim_utils.UsdFileCfg( # usd_path=f"{ISAAC_ORBIT_NUCLEUS_DIR}/Robots/Classic/Cartpole/cartpole.usd", # Path to the USD file relative to the project root usd_path=os.path.join(project_root, "usds/Maze_Simple.usd"), # usd_path=f"../../../../usds/Maze_Simple.usd", rigid_props=sim_utils.RigidBodyPropertiesCfg( rigid_body_enabled=True, max_linear_velocity=1000.0, max_angular_velocity=1000.0, max_depenetration_velocity=100.0, enable_gyroscopic_forces=True, ), articulation_props=sim_utils.ArticulationRootPropertiesCfg( enabled_self_collisions=False, solver_position_iteration_count=4, solver_velocity_iteration_count=0, sleep_threshold=0.005, stabilization_threshold=0.001, ), ), init_state=ArticulationCfg.InitialStateCfg( pos=(0.0, 0.0, 0.0), joint_pos={"OuterDOF_RevoluteJoint": 0.0, "InnerDOF_RevoluteJoint": 0.0} ), actuators={ "outer_actuator": ImplicitActuatorCfg( joint_names_expr=["OuterDOF_RevoluteJoint"], effort_limit=0.01, velocity_limit=1.0 / math.pi, stiffness=0.0, damping=10.0, ), "inner_actuator": ImplicitActuatorCfg( joint_names_expr=["InnerDOF_RevoluteJoint"], effort_limit=0.01, velocity_limit=1.0 / math.pi, stiffness=0.0, damping=10.0, ), }, ) @configclass class SensorsSceneCfg(InteractiveSceneCfg): """Design the scene with sensors on the robot.""" # ground plane ground = AssetBaseCfg( prim_path="/World/ground", spawn=sim_utils.GroundPlaneCfg(size=(100.0, 100.0)), ) # cartpole robot: ArticulationCfg = MAZE_CFG.replace(prim_path="{ENV_REGEX_NS}/Labyrinth") # Sphere with collision enabled but not actuated sphere = RigidObjectCfg( prim_path="{ENV_REGEX_NS}/sphere", spawn=sim_utils.SphereCfg( radius=0.005, # Define the radius of the sphere mass_props=sim_utils.MassPropertiesCfg(density=7850), # Density of steel in kg/m^3) rigid_props=sim_utils.RigidBodyPropertiesCfg(rigid_body_enabled=True), collision_props=sim_utils.CollisionPropertiesCfg(collision_enabled=True), visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.9, 0.9, 0.9), metallic=0.8), ), init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 0.11)), ) # sensors camera_1 = CameraCfg( prim_path="{ENV_REGEX_NS}/top_cam", update_period=0.1, height=8, width=8, data_types=["rgb"],#, "distance_to_image_plane"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5) ), offset=CameraCfg.OffsetCfg(pos=(0.0, 0.0, 0.5), rot=(0,1,0,0), convention="ros"), ) # sphere_object = RigidObject(cfg=sphere_cfg) # lights dome_light = AssetBaseCfg( prim_path="/World/DomeLight", spawn=sim_utils.DomeLightCfg(color=(0.9, 0.9, 0.9), intensity=500.0), ) distant_light = AssetBaseCfg( prim_path="/World/DistantLight", spawn=sim_utils.DistantLightCfg(color=(0.9, 0.9, 0.9), intensity=2500.0), init_state=AssetBaseCfg.InitialStateCfg(rot=(0.738, 0.477, 0.477, 0.0)), ) def run_simulator( sim: sim_utils.SimulationContext, scene: InteractiveScene, ): """Run the simulator.""" # Define simulation stepping sim_dt = sim.get_physics_dt() sim_time = 0.0 def reset(): # reset the scene entities # root state # we offset the root state by the origin since the states are written in simulation world frame # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world root_state = scene["robot"].data.default_root_state.clone() root_state[:, :3] += scene.env_origins scene["robot"].write_root_state_to_sim(root_state) # set joint positions with some noise joint_pos, joint_vel = ( scene["robot"].data.default_joint_pos.clone(), scene["robot"].data.default_joint_vel.clone(), ) joint_pos += torch.rand_like(joint_pos) * 0.1 scene["robot"].write_joint_state_to_sim(joint_pos, joint_vel) # clear internal buffers scene.reset() print("[INFO]: Resetting robot state...") output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output", "camera") rep_writer = rep.BasicWriter(output_dir=output_dir, frame_padding=3) episode_steps = 500 while simulation_app.is_running(): reset() with Timer(f"Time taken for {episode_steps} steps with {args_cli.num_envs} envs"): with tqdm(range(episode_steps*args_cli.num_envs)) as pbar: for count in range(episode_steps): # Apply default actions to the robot # -- generate actions/commands targets = scene["robot"].data.default_joint_pos # -- apply action to the robot scene["robot"].set_joint_position_target(targets) # -- write data to sim scene.write_data_to_sim() # perform step sim.step() # update sim-time sim_time += sim_dt count += 1 # update buffers scene.update(sim_dt) pbar.update(args_cli.num_envs) # Extract camera data if args_cli.save: for i in range(args_cli.num_envs): for j in range(args_cli.num_cams): single_cam_data = convert_dict_to_backend(scene[f"camera_{j+1}"].data.output, backend="numpy") #single_cam_info = scene[f"camera_{j+1}"].data.info # Pack data back into replicator format to save them using its writer rep_output = dict() for key, data in zip(single_cam_data.keys(), single_cam_data.values()):#, single_cam_info): # if info is not None: # rep_output[key] = {"data": data, "info": info} # else: rep_output[key] = data[i] # Save images # Note: We need to provide On-time data for Replicator to save the images. rep_output["trigger_outputs"] = {"on_time":f"{count}_{i}_{j}"}#{"on_time": scene["camera_1"].frame} rep_writer.write(rep_output) if args_cli.num_cams > 0: cam1_rgb = scene["camera_1"].data.output["rgb"] squeezed_img = cam1_rgb.squeeze(0).cpu().numpy().astype('uint8') image = Image.fromarray(squeezed_img) # image.save('test_cam'+str(count)+'.png') if args_cli.num_cams > 1: cam2_rgb = scene["camera_2"].data.output["rgb"] def main(): """Main function.""" # Initialize the simulation context sim_cfg = sim_utils.SimulationCfg(dt=0.005, substeps=1) sim = sim_utils.SimulationContext(sim_cfg) # Set main camera sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0]) # design scene scene_cfg = SensorsSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0) scene = InteractiveScene(scene_cfg) # Play the simulator sim.reset() # Now we are ready! print("[INFO]: Setup complete...") # Run the simulator run_simulator(sim, scene) if __name__ == "__main__": try: # run the main execution main() except Exception as err: carb.log_error(err) carb.log_error(traceback.format_exc()) raise finally: # close sim app simulation_app.close()
10,261
Python
38.929961
131
0.587467
Helbling-Technik/orbit.maze/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.0" # Description title = "Maze" # TODO: Please adapt to your title. description="Maze Task for RL Learning" #TODO: Please adapt to your description. repository = "https://github.com/kevchef/orbit.maze.git" # TODO: Please adapt to your repository. keywords = ["extension", "maze","task","RL", "orbit"] # TODO: Please adapt to your keywords. category = "orbit" readme = "README.md" [dependencies] "omni.kit.uiapp" = {} "omni.isaac.orbit" = {} "omni.isaac.orbit_assets" = {} "omni.isaac.orbit_tasks" = {} "omni.isaac.core" = {} "omni.isaac.gym" = {} "omni.replicator.isaac" = {} # Note: You can add additional dependencies here for your extension. # For example, if you want to use the omni.kit module, you can add it as a dependency: # "omni.kit" = {} [[python.module]] name = "orbit.maze" # TODO: Please adapt to your package name.
917
TOML
31.785713
98
0.688113
Helbling-Technik/orbit.maze/orbit/maze/tasks/maze/maze_env_cfg.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause import math import torch import omni.isaac.orbit.sim as sim_utils from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg, RigidObjectCfg from omni.isaac.orbit.envs import RLTaskEnvCfg from omni.isaac.orbit.sensors import CameraCfg from omni.isaac.orbit.managers import EventTermCfg as EventTerm from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm from omni.isaac.orbit.managers import RewardTermCfg as RewTerm from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm from omni.isaac.orbit.scene import InteractiveSceneCfg from omni.isaac.orbit.actuators import ImplicitActuatorCfg from omni.isaac.orbit.utils import configclass import orbit.maze.tasks.maze.mdp as mdp import os ## # Pre-defined configs ## # from omni.isaac.orbit_assets.maze import MAZE_CFG # isort:skip # from maze import MAZE_CFG # isort:skip # Absolute path of the current script current_script_path = os.path.abspath(__file__) # Absolute path of the project root (assuming it's three levels up from the current script) project_root = os.path.join(current_script_path, "../../../../..") MAZE_CFG = ArticulationCfg( spawn=sim_utils.UsdFileCfg( usd_path=os.path.join(project_root, "usds/Maze_Simple.usd"), rigid_props=sim_utils.RigidBodyPropertiesCfg( rigid_body_enabled=True, max_linear_velocity=1000.0, max_angular_velocity=1000.0, max_depenetration_velocity=100.0, enable_gyroscopic_forces=True, ), articulation_props=sim_utils.ArticulationRootPropertiesCfg( enabled_self_collisions=False, solver_position_iteration_count=4, solver_velocity_iteration_count=0, sleep_threshold=0.005, stabilization_threshold=0.001, ), ), init_state=ArticulationCfg.InitialStateCfg( pos=(0.0, 0.0, 0.0), joint_pos={"OuterDOF_RevoluteJoint": 0.0, "InnerDOF_RevoluteJoint": 0.0} ), actuators={ "outer_actuator": ImplicitActuatorCfg( joint_names_expr=["OuterDOF_RevoluteJoint"], effort_limit=0.01, # 5g * 9.81 * 0.15m = 0.007357 velocity_limit=1.0 / math.pi, stiffness=0.0, damping=10.0, ), "inner_actuator": ImplicitActuatorCfg( joint_names_expr=["InnerDOF_RevoluteJoint"], effort_limit=0.01, # 5g * 9.81 * 0.15m = 0.007357 velocity_limit=1.0 / math.pi, stiffness=0.0, damping=10.0, ), }, ) # Scene definition ## @configclass class MazeSceneCfg(InteractiveSceneCfg): """Configuration for a cart-pole scene.""" # ground plane ground = AssetBaseCfg( prim_path="/World/ground", spawn=sim_utils.GroundPlaneCfg(size=(100.0, 100.0)), ) # cartpole robot: ArticulationCfg = MAZE_CFG.replace(prim_path="{ENV_REGEX_NS}/Labyrinth") # Sphere with collision enabled but not actuated sphere = RigidObjectCfg( prim_path="{ENV_REGEX_NS}/sphere", spawn=sim_utils.SphereCfg( radius=0.005, mass_props=sim_utils.MassPropertiesCfg(density=7850), rigid_props=sim_utils.RigidBodyPropertiesCfg(rigid_body_enabled=True), collision_props=sim_utils.CollisionPropertiesCfg(collision_enabled=True), visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.9, 0.9, 0.9), metallic=0.8), ), init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 0.11)), ) dome_light = AssetBaseCfg( prim_path="/World/DomeLight", spawn=sim_utils.DomeLightCfg(color=(0.9, 0.9, 0.9), intensity=1000.0), ) ## # MDP settings ## @configclass class CommandsCfg: """Command terms for the MDP.""" # no commands for this MDP null = mdp.NullCommandCfg() # sphere_cmd_pos = mdp.UniformPose2dCommandCfg( # asset_name="sphere", # simple_heading=True, # resampling_time_range=(10000000000, 10000000000), # debug_vis=False, # ranges=mdp.UniformPose2dCommandCfg.Ranges(pos_x=(-0.05, 0.05), pos_y=(-0.05, 0.05)), # ) @configclass class ActionsCfg: """Action specifications for the MDP.""" outer_joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=["OuterDOF_RevoluteJoint"], scale=0.1) inner_joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=["InnerDOF_RevoluteJoint"], scale=0.1) @configclass class ObservationsCfg: """Observation specifications for the MDP.""" @configclass class PolicyCfg(ObsGroup): """Observations for policy group.""" # observation terms (order preserved) joint_pos = ObsTerm(func=mdp.joint_pos_rel) joint_vel = ObsTerm(func=mdp.joint_vel_rel) sphere_pos = ObsTerm( func=mdp.root_pos_w, params={"asset_cfg": SceneEntityCfg("sphere")}, ) sphere_lin_vel = ObsTerm( func=mdp.root_lin_vel_w, params={"asset_cfg": SceneEntityCfg("sphere")}, ) target_pos_rel = ObsTerm( func=mdp.get_target_pos, params={ "asset_cfg": SceneEntityCfg("sphere"), "target": {"x": 0.0, "y": 0.0}, }, ) # target_sphere_pos = ObsTerm( # func=mdp.get_generated_commands_xy, # params={"command_name": "sphere_cmd_pos"}, # ) def __post_init__(self) -> None: self.enable_corruption = False self.concatenate_terms = True # observation groups policy: PolicyCfg = PolicyCfg() @configclass class EventCfg: """Configuration for events.""" # reset reset_outer_joint = EventTerm( func=mdp.reset_joints_by_offset, mode="reset", params={ "asset_cfg": SceneEntityCfg("robot", joint_names=["OuterDOF_RevoluteJoint"]), "position_range": (-0.01 * math.pi, 0.01 * math.pi), "velocity_range": (-0.01 * math.pi, 0.01 * math.pi), }, ) reset_inner_joint = EventTerm( func=mdp.reset_joints_by_offset, mode="reset", params={ "asset_cfg": SceneEntityCfg("robot", joint_names=["InnerDOF_RevoluteJoint"]), "position_range": (-0.01 * math.pi, 0.01 * math.pi), "velocity_range": (-0.01 * math.pi, 0.01 * math.pi), }, ) reset_sphere_pos = EventTerm( func=mdp.reset_root_state_uniform, mode="reset", params={ "asset_cfg": SceneEntityCfg("sphere"), "pose_range": {"x": (-0.05, 0.05), "y": (-0.05, 0.05)}, "velocity_range": {}, }, ) @configclass class RewardsCfg: """Reward terms for the MDP.""" # (1) Constant running reward alive = RewTerm(func=mdp.is_alive, weight=0.1) # (2) Failure penalty terminating = RewTerm(func=mdp.is_terminated, weight=-2.0) # (3) Primary task: keep sphere in center sphere_pos = RewTerm( func=mdp.root_xypos_target_l2, weight=-5000.0, params={ "asset_cfg": SceneEntityCfg("sphere"), "target": {"x": 0.0, "y": 0.0}, }, ) # sphere_to_target = RewTerm( # func=mdp.object_goal_distance_l2, # params={"command_name": "sphere_cmd_pos", "object_cfg": SceneEntityCfg("sphere")}, # weight=-5000.0, # ) outer_joint_vel = RewTerm( func=mdp.joint_vel_l1, weight=-0.01, params={"asset_cfg": SceneEntityCfg("robot", joint_names=["OuterDOF_RevoluteJoint"])}, ) inner_joint_vel = RewTerm( func=mdp.joint_vel_l1, weight=-0.01, params={"asset_cfg": SceneEntityCfg("robot", joint_names=["InnerDOF_RevoluteJoint"])}, ) @configclass class TerminationsCfg: """Termination terms for the MDP.""" # (1) Time out time_out = DoneTerm(func=mdp.time_out, time_out=True) # (2) Sphere off maze sphere_on_ground = DoneTerm( func=mdp.root_height_below_minimum, params={"asset_cfg": SceneEntityCfg("sphere"), "minimum_height": 0.01}, ) @configclass class CurriculumCfg: """Configuration for the curriculum.""" pass ## # Environment configuration ## @configclass class MazeEnvCfg(RLTaskEnvCfg): """Configuration for the locomotion velocity-tracking environment.""" # Scene settings scene: MazeSceneCfg = MazeSceneCfg(num_envs=16, env_spacing=0.5) # Basic settings observations: ObservationsCfg = ObservationsCfg() actions: ActionsCfg = ActionsCfg() events: EventCfg = EventCfg() # MDP settings curriculum: CurriculumCfg = CurriculumCfg() rewards: RewardsCfg = RewardsCfg() terminations: TerminationsCfg = TerminationsCfg() # No command generator commands: CommandsCfg = CommandsCfg() # Post initialization def __post_init__(self) -> None: """Post initialization.""" # general settings self.decimation = 2 self.episode_length_s = 10 # viewer settings self.viewer.eye = (1, 1, 1.5) # simulation settings self.sim.dt = 1 / 200
9,410
Python
30.162252
120
0.623273
Helbling-Technik/orbit.maze/orbit/maze/tasks/maze/mdp/rewards.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations import torch from typing import TYPE_CHECKING from omni.isaac.orbit.assets import Articulation, RigidObject from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.utils.math import wrap_to_pi if TYPE_CHECKING: from omni.isaac.orbit.envs import RLTaskEnv def joint_pos_target_l2(env: RLTaskEnv, target: float, asset_cfg: SceneEntityCfg) -> torch.Tensor: """Penalize joint position deviation from a target value.""" # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] # wrap the joint positions to (-pi, pi) joint_pos = wrap_to_pi(asset.data.joint_pos[:, asset_cfg.joint_ids]) # compute the reward # print("joint pos reward: ", torch.sum(torch.square(joint_pos - target), dim=1)) return torch.sum(torch.square(joint_pos - target), dim=1) def root_pos_target_l2(env: RLTaskEnv, target: dict[str, float], asset_cfg: SceneEntityCfg) -> torch.Tensor: """Penalize joint position deviation from a target value.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] target_list = torch.tensor([target.get(key, 0.0) for key in ["x", "y", "z"]], device=asset.data.root_pos_w.device) root_pos = asset.data.root_pos_w - env.scene.env_origins # compute the reward return torch.sum(torch.square(root_pos - target_list), dim=1) def root_xypos_target_l2(env: RLTaskEnv, target: dict[str, float], asset_cfg: SceneEntityCfg) -> torch.Tensor: """Penalize joint position deviation from a target value.""" # extract the used quantities (to enable type-hinting) asset: RigidObject = env.scene[asset_cfg.name] target_tensor = torch.tensor([target.get(key, 0.0) for key in ["x", "y"]], device=asset.data.root_pos_w.device) root_pos = asset.data.root_pos_w - env.scene.env_origins # compute the reward # xy_reward_l2 = (torch.sum(torch.square(root_pos[:,:2] - target_tensor), dim=1) <= 0.0025).float()*2 - 1 xy_reward_l2 = torch.sum(torch.square(root_pos[:, :2] - target_tensor), dim=1) # print("sphere_xypos_rewards: ", xy_reward_l2.tolist()) return xy_reward_l2 def object_goal_distance_l2( env: RLTaskEnv, command_name: str, object_cfg: SceneEntityCfg = SceneEntityCfg("sphere"), ) -> torch.Tensor: """Reward the agent for tracking the goal pose using L2-kernel.""" # extract the used quantities (to enable type-hinting) object: RigidObject = env.scene[object_cfg.name] command = env.command_manager.get_command(command_name) # command_pos is difference between target in env frame and object in env frame command_pos = command[:, :2] object_pos = object.data.root_pos_w - env.scene.env_origins # print("target_pos: ", command_pos) # print("object_pos: ", object_pos[:, :2]) # distance of the target to the object: (num_envs,) distance = torch.norm(command_pos, dim=1) # print("distance: ", distance) # rewarded if the object is closest to the target return distance
3,207
Python
43.555555
118
0.696913
Helbling-Technik/orbit.maze/orbit/maze/tasks/maze/mdp/events.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations import torch from typing import TYPE_CHECKING import omni.isaac.orbit.utils.math as math_utils from omni.isaac.orbit.assets import Articulation, RigidObject from omni.isaac.orbit.managers import SceneEntityCfg if TYPE_CHECKING: from omni.isaac.orbit.envs import RLTaskEnv def set_random_target_pos( env: RLTaskEnv, env_ids: torch.Tensor, pose_range: dict[str, tuple[float, float]], asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), ): # extract the used quantities (to enable type-hinting) asset: RigidObject | Articulation = env.scene[asset_cfg.name] # poses range_list = [pose_range.get(key, (0.0, 0.0)) for key in ["x", "y"]] ranges = torch.tensor(range_list, device=asset.device) rand_samples = math_utils.sample_uniform(ranges[:, 0], ranges[:, 1], (len(env_ids), 6), device=asset.device) target_positions = env.scene.env_origins[env_ids] + rand_samples[:, 0:3] return target_positions
1,111
Python
29.888888
112
0.713771
Helbling-Technik/orbit.maze/orbit/maze/tasks/maze/mdp/observations.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations import torch from typing import TYPE_CHECKING from omni.isaac.orbit.sensors import Camera from omni.isaac.orbit.assets import Articulation, RigidObject from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.utils.math import wrap_to_pi if TYPE_CHECKING: from omni.isaac.orbit.envs import RLTaskEnv def camera_image(env: RLTaskEnv, asset_cfg: SceneEntityCfg) -> torch.Tensor: """Camera image from top camera.""" # Extract the used quantities (to enable type-hinting) asset: Camera = env.scene[asset_cfg.name] # Get the RGBA image tensor rgba_tensor = asset.data.output["rgb"] # Check the shape of the input tensor assert rgba_tensor.dim() == 4 and rgba_tensor.size(-1) == 4, "Expected tensor of shape (n, 128, 128, 4)" # Ensure the tensor is on the correct device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") rgba_tensor = rgba_tensor.to(device) # Convert the RGBA tensor to grayscale # Using the weights for R, G, and B, and ignoring the Alpha channel weights = torch.tensor([0.2989, 0.5870, 0.1140, 0.0], device=device).view(1, 1, 1, 4) grayscale_tensor = (rgba_tensor * weights).sum(dim=-1) # Flatten each image to a 1D tensor n_envs = grayscale_tensor.size(0) n_pixels = grayscale_tensor.size(1) * grayscale_tensor.size(2) grayscale_tensor_flattened = grayscale_tensor.view(n_envs, n_pixels) return grayscale_tensor_flattened def get_target_pos(env: RLTaskEnv, target: dict[str, float], asset_cfg: SceneEntityCfg) -> torch.Tensor: """Penalize joint position deviation from a target value.""" # extract the used quantities (to enable type-hinting) # asset: RigidObject = env.scene[asset_cfg.name] # target_tensor = torch.tensor([target.get(key, 0.0) for key in ["x", "y"]], device=asset.data.root_pos_w.device) # root_pos = asset.data.root_pos_w - env.scene.env_origins zeros_tensor = torch.zeros_like(env.scene.env_origins) # return (zeros_tensor - root_pos)[:, :2].to(dtype=torch.float16) return zeros_tensor[:, :2] def get_env_pos_of_command(env: RLTaskEnv, object_cfg: SceneEntityCfg, command_name: str) -> torch.Tensor: """The generated command from command term in the command manager with the given name.""" """The env frame target position can not fully be recovered as one of the terms is updated less frequently""" object: RigidObject = env.scene[object_cfg.name] object_pos = object.data.root_pos_w - env.scene.env_origins commanded = env.command_manager.get_command(command_name) target_pos_env = commanded[:, :2] + object_pos[:, :2] print("target_pos_env_observation: ", target_pos_env[:, :2]) return target_pos_env def get_generated_commands_xy(env: RLTaskEnv, command_name: str) -> torch.Tensor: """The generated command from command term in the command manager with the given name.""" commanded = env.command_manager.get_command(command_name) return commanded[:, :2]
3,161
Python
41.729729
117
0.707371
ashleygoldstein/kit-exts-joints/README.md
# Create Joints in Omniverse ![](https://github.com/ashleygoldstein/kit-exts-joints/blob/main/images/createJointext.PNG) This extension allows you to create any joint easily and efficiently between two prims in your Omniverse USD stage! ## Get Started This extension is available in Omniverse Kit and can be installed via the Extensions manager tab. Once you are in the Extensions tab, navigate to the Community tab and search `Joint Connection`. Install and Enable the extension and the Joint Connection window will appear. ## How to Use To use this extension once enabled select your first Prim in the stage and click the `S` button in the Joint Connection window for `Prim A`. Then select your second Prim in the stage that you want the joint to be connected with and click the `S` button for `Prim B`. In the `Joints` drop down menu, select which joint you want to create. Then, click `Create Joint` button. :tada: Congratulations! :tada: You now have a joint! Click the `play` button in Omniverse to test it out. > :exclamation: You must have rigidbodies added to your prims for joint physics to work properly
1,144
Markdown
38.482757
141
0.765734
ashleygoldstein/kit-exts-joints/exts/goldstein.joint.connection/goldstein/joint/connection/extension.py
import omni.ext import omni.ui as ui from .window import JointWindow # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class JointCreationExt(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[Joint.Creation.Ext] startup") self._window = JointWindow("Joint Creation", width=300, height=300) def on_shutdown(self): self._window.destroy() print("[Joint.Creation.Ext] shutdown")
805
Python
39.299998
119
0.720497
ashleygoldstein/kit-exts-joints/exts/goldstein.joint.connection/goldstein/joint/connection/utils.py
from typing import List import omni.usd import omni.kit.commands def get_selection() -> List[str]: """Get the list of currently selected prims""" return omni.usd.get_context().get_selection().get_selected_prim_paths()
227
Python
27.499997
75
0.726872
ashleygoldstein/kit-exts-joints/exts/goldstein.joint.connection/goldstein/joint/connection/window.py
import omni.ui as ui from .utils import get_selection import omni.kit.commands import omni.usd JOINTS = ("D6", "Revolute", "Fixed", "Spherical", "Prismatic", "Distance", "Gear", "Rack and Pinion") class JointWindow(ui.Window): def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self._source_prim_model_a = ui.SimpleStringModel() self._source_prim_model_b = ui.SimpleStringModel() self._stage = omni.usd.get_context().get_stage() self.frame.set_build_fn(self._build_fn) self.combo_model = None self.current_joint = None def _on_get_selection_a(self): """Called when the user presses the "Get From Selection" button""" self._source_prim_model_a.as_string = ", ".join(get_selection()) def _on_get_selection_b(self): """Called when the user presses the "Get From Selection" button""" self._source_prim_model_b.as_string = ", ".join(get_selection()) def _build_window(self): with self.frame: with ui.VStack(): with ui.CollapsableFrame("Source"): with ui.VStack(height=20, spacing=4): with ui.HStack(): ui.Label("Prim A") ui.StringField(model = self._source_prim_model_a) ui.Button("S", clicked_fn=self._on_get_selection_a) ui.Spacer() with ui.HStack(): ui.Label("Prim B") ui.StringField(model = self._source_prim_model_b) ui.Button("S", clicked_fn=self._on_get_selection_b) with ui.CollapsableFrame("Joints"): with ui.VStack(): ui.Label self.combo_model = ui.ComboBox(0,*JOINTS).model def combo_changed(item_model, item): value_model = item_model.get_item_value_model(item) self.current_joint = JOINTS[value_model.as_int] # self.current_index = value_model.as_int self._combo_changed_sub = self.combo_model.subscribe_item_changed_fn(combo_changed) def on_click(): print("clicked!") omni.kit.commands.execute('CreateJointCommand', stage = self._stage, joint_type=self.current_joint, from_prim = self._stage.GetPrimAtPath(self._source_prim_model_a.as_string), to_prim = self._stage.GetPrimAtPath(self._source_prim_model_b.as_string)) ui.Button("Create Joint", clicked_fn=lambda: on_click()) def _build_fn(self): with ui.ScrollingFrame(): with ui.VStack(height=10): self._build_window() def destroy(self) -> None: self._combo_changed_sub = None return super().destroy()
3,350
Python
42.51948
127
0.477313
gist-ailab/AILAB-isaac-sim-pick-place/lecture/3-4/pick_place.py
from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core import World from omni.kit.viewport.utility import get_active_viewport import sys, os from pathlib import Path import numpy as np import random sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from utils.controllers.pick_place_controller_robotiq import PickPlaceController from utils.tasks.pick_place_task import UR5ePickPlace # YCB Dataset 물체들에 대한 정보 취득 working_dir = os.path.dirname(os.path.realpath(__file__)) ycb_path = os.path.join(Path(working_dir).parent, 'dataset/ycb') obj_dirs = [os.path.join(ycb_path, obj_name) for obj_name in os.listdir(ycb_path)] obj_dirs.sort() object_info = {} label2name = {} total_object_num = len(obj_dirs) for obj_idx, obj_dir in enumerate(obj_dirs): usd_file = os.path.join(obj_dir, 'final.usd') object_info[obj_idx] = { 'name': os.path.basename(obj_dir), 'usd_file': usd_file, 'label': obj_idx, } label2name[obj_idx]=os.path.basename(obj_dir) # 랜덤한 물체에 대한 usd file path 선택 obje_info = random.sample(list(object_info.values()), 1) objects_usd = obje_info[0]['usd_file'] # Random하게 생성된 물체들의 ​번호와 카테고리 출력 print("object: {}".format(obje_info[0]['name'])) # 물체를 생성할 위치 지정(너무 멀어지는 경우 로봇이 닿지 않을 수 있음, 물체 사이의 거리가 가까울 경우 충돌이 발생할 수 있음) objects_position = np.array([[0.5, 0, 0.1]]) offset = np.array([0, 0, 0.1]) # 물체를 놓을 위치(place position) 지정 target_position = np.array([0.4, -0.33, 0.55]) target_orientation = np.array([0, 0, 0, 1]) # World 생성 my_world = World(stage_units_in_meters=1.0) # Task 생성 my_task = UR5ePickPlace(objects_list = [objects_usd], objects_position = objects_position, offset=offset) # World에 Task 추가 my_world.add_task(my_task) my_world.reset() # Task로부터 ur5e 획득 task_params = my_task.get_params() my_ur5e = my_world.scene.get_object(task_params["robot_name"]["value"]) # PickPlace controller 생성 my_controller = PickPlaceController( name="pick_place_controller", gripper=my_ur5e.gripper, robot_articulation=my_ur5e ) # robot control(PD control)을 위한 instance 선언 articulation_controller = my_ur5e.get_articulation_controller() # GUI 상에서 보는 view point 지정(Depth 카메라 view에서 Perspective view로 변환시, 전체적으로 보기 편함) viewport = get_active_viewport() viewport.set_active_camera('/World/ur5e/realsense/Depth') viewport.set_active_camera('/OmniverseKit_Persp') # 생성한 world 에서 physics simulation step​ while simulation_app.is_running(): my_world.step(render=True) if my_world.is_playing(): # step이 0일때, world와 controller를 reset if my_world.current_time_step_index == 0: my_world.reset() my_controller.reset() # my_world로 부터 observation 값들 획득​ observations = my_world.get_observations() # 획득한 observation을 pick place controller에 전달 actions = my_controller.forward( picking_position=observations[task_params["task_object_name_0"]["value"]]["position"], placing_position=observations[task_params["task_object_name_0"]["value"]]["target_position"], current_joint_positions=observations[task_params["robot_name"]["value"]]["joint_positions"], end_effector_offset=np.array([0, 0, 0.14]) ) # controller의 동작이 끝났음을 출력 if my_controller.is_done(): print("done picking and placing") break # 선언한 action을 입력받아 articulation_controller를 통해 action 수행. # Controller 내부에서 계산된 joint position값을 통해 action을 수행함​ articulation_controller.apply_action(actions) # simulation 종료​ simulation_app.close()
3,733
Python
32.044248
105
0.669167
gist-ailab/AILAB-isaac-sim-pick-place/lecture/3-4/0_practice_task_generation.py
from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core import World from omni.kit.viewport.utility import get_active_viewport import sys, os from pathlib import Path import numpy as np import random sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from utils.controllers.pick_place_controller_robotiq import PickPlaceController from utils.tasks.pick_place_task import UR5ePickPlace ############### Random한 YCB 물체 생성을 포함하는 Task 생성 ###################### # YCB Dataset 물체들에 대한 정보 취득 # 랜덤한 물체에 대한 usd file path 선택 # Random하게 생성된 물체들의 ​번호와 카테고리 출력 # 물체를 생성할 위치 지정(너무 멀어지는 경우 로봇이 닿지 않을 수 있음, 물체 사이의 거리가 가까울 경우 충돌이 발생할 수 있음) # 물체를 놓을 위치(place position) 지정 # World 생성 my_world = World(stage_units_in_meters=1.0) # Task 생성 # World에 Task 추가 ######################################################################## # GUI 상에서 보는 view point 지정(Depth 카메라 view에서 Perspective view로 변환시, 전체적으로 보기 편함) viewport = get_active_viewport() viewport.set_active_camera('/World/ur5e/realsense/Depth') viewport.set_active_camera('/OmniverseKit_Persp') # 생성한 world 에서 physics simulation step​ while simulation_app.is_running(): my_world.step(render=True) # simulation 종료​ simulation_app.close()
1,280
Python
25.687499
79
0.689844
gist-ailab/AILAB-isaac-sim-pick-place/lecture/3-2/0_position_control.py
from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core import World from omni.kit.viewport.utility import get_active_viewport import numpy as np import sys, os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from utils.tasks.pick_place_task import UR5ePickPlace from utils.controllers.RMPFflow_pickplace import RMPFlowController from utils.controllers.basic_manipulation_controller import BasicManipulationController # World 생성 my_world = World(stage_units_in_meters=1.0) # Task 생성 my_task = UR5ePickPlace() my_world.add_task(my_task) my_world.reset() # Controller 생성 task_params = my_task.get_params() my_ur5e = my_world.scene.get_object(task_params["robot_name"]["value"]) my_controller = BasicManipulationController( # Controller의 이름 설정 name='basic_manipulation_controller', # 로봇 모션 controller 설정 cspace_controller=RMPFlowController( name="end_effector_controller_cspace_controller", robot_articulation=my_ur5e, attach_gripper=True ), # 로봇의 gripper 설정 gripper=my_ur5e.gripper, # phase의 진행 속도 설정 events_dt=[0.008], ) # robot control(PD control)을 위한 instance 선언 articulation_controller = my_ur5e.get_articulation_controller() my_controller.reset() # GUI 상에서 보는 view point 지정(Depth 카메라 view에서 Perspective view로 변환시, 전체적으로 보기 편함) viewport = get_active_viewport() viewport.set_active_camera('/World/ur5e/realsense/Depth') viewport.set_active_camera('/OmniverseKit_Persp') # 시뮬레이션 앱 실행 후 dalay를 위한 변수 max_step = 150 # 시뮬레이션 앱이 실행 중이면 동작 ee_target_position = np.array([0.25, -0.23, 0.4]) while simulation_app.is_running(): # 생성한 world 에서 physics simulation step​ my_world.step(render=True) if my_world.is_playing(): if my_world.current_time_step_index > max_step: # my_world로 부터 observation 값들 획득​ observations = my_world.get_observations() # 획득한 observation을 pick place controller에 전달 actions = my_controller.forward( target_position=ee_target_position, current_joint_positions=observations[task_params["robot_name"]["value"]]["joint_positions"], end_effector_offset = np.array([0, 0, 0.14]) ) # controller의 동작이 끝났음을 출력 if my_controller.is_done(): print("done position control of end-effector") break # 컨트롤러 내부에서 계산된 타겟 joint position값을 # articulation controller에 전달하여 action 수행 articulation_controller.apply_action(actions) # 시뮬레이션 종료 simulation_app.close()
2,648
Python
32.1125
108
0.686934
gist-ailab/AILAB-isaac-sim-pick-place/lecture/3-2/1_look_around.py
from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core import World from omni.kit.viewport.utility import get_active_viewport from omni.isaac.core.utils.rotations import euler_angles_to_quat import numpy as np import sys, os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from utils.tasks.pick_place_task import UR5ePickPlace from utils.controllers.RMPFflow_pickplace import RMPFlowController from utils.controllers.basic_manipulation_controller import BasicManipulationController # World 생성 my_world = World(stage_units_in_meters=1.0) # Task 생성 my_task = UR5ePickPlace() # World에 Task 추가 및 World 리셋 my_world.add_task(my_task) my_world.reset() # Task로부터 로봇과 카메라 획득 task_params = my_task.get_params() my_ur5e = my_world.scene.get_object(task_params["robot_name"]["value"]) # Controller 생성 my_controller = BasicManipulationController( name='basic_manipulation_controller', cspace_controller=RMPFlowController( name="basic_manipulation_controller_cspace_controller", robot_articulation=my_ur5e, attach_gripper=True ), gripper=my_ur5e.gripper, events_dt=[0.008], ) # robot control(PD control)을 위한 instance 선언 articulation_controller = my_ur5e.get_articulation_controller() # GUI 상에서 보는 view point 지정(Depth 카메라 view에서 Perspective view로 변환시, 전체적으로 보기 편함) viewport = get_active_viewport() viewport.set_active_camera('/World/ur5e/realsense/Depth') viewport.set_active_camera('/OmniverseKit_Persp') # target object를 찾기 위한 예제 코드 # end effector가 반지름 4를 가지며 theta가 45도씩 360도를 회전 수행 for theta in range(0, 360, 45): # theta 값에 따라서 end effector의 위치를 지정(x, y, z) r, z = 4, 0.35 x, y = r/10 * np.cos(theta/360*2*np.pi), r/10 * np.sin(theta/360*2*np.pi) while simulation_app.is_running(): # 생성한 world 에서 physics simulation step​ my_world.step(render=True) if my_world.is_playing(): # step이 0일때, World와 Controller를 reset if my_world.current_time_step_index == 0: my_world.reset() my_controller.reset() # 획득한 observation을 pick place controller에 전달 actions = my_controller.forward( target_position=np.array([x, y, z]), current_joint_positions=my_ur5e.get_joint_positions(), end_effector_offset = np.array([0, 0, 0.14]), end_effector_orientation=euler_angles_to_quat(np.array([0, np.pi, theta * 2 * np.pi / 360])) ) # end effector가 원하는 위치에 도달하면 # controller reset 및 while문 나가기 if my_controller.is_done(): my_controller.reset() break # 선언한 action을 입력받아 articulation_controller를 통해 action 수행 # Controller에서 계산된 joint position값을 통해 action을 수행함 articulation_controller.apply_action(actions) simulation_app.close()
3,016
Python
32.522222
108
0.656499
gist-ailab/AILAB-isaac-sim-pick-place/lecture/3-2/2_gripper_control.py
from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core import World from omni.kit.viewport.utility import get_active_viewport import numpy as np import sys, os sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) from utils.tasks.pick_place_task import UR5ePickPlace from utils.controllers.RMPFflow_pickplace import RMPFlowController from utils.controllers.basic_manipulation_controller import BasicManipulationController # if you don't declare objects_position, the objects will be placed randomly objects_position = np.array([0.4, 0.4, 0.1]) target_position = np.array([0.4, -0.33, 0.05]) # 0.55 for considering the length of the gripper tip target_orientation = np.array([0, 0, 0, 1]) offset = np.array([0, 0, 0.1]) # releasing offset at the target position my_world = World(stage_units_in_meters=1.0) my_task = UR5ePickPlace() my_world.add_task(my_task) my_world.reset() task_params = my_task.get_params() my_ur5e = my_world.scene.get_object(task_params["robot_name"]["value"]) my_controller = BasicManipulationController( name='basic_manipulation_controller', cspace_controller=RMPFlowController( name="end_effector_controller_cspace_controller", robot_articulation=my_ur5e, attach_gripper=True ), gripper=my_ur5e.gripper, events_dt=[0.008], ) articulation_controller = my_ur5e.get_articulation_controller() my_controller.reset() viewport = get_active_viewport() viewport.set_active_camera('/World/ur5e/realsense/Depth') viewport.set_active_camera('/OmniverseKit_Persp') # 그리퍼 열기 / 닫기 명령어 입력받음 while True: instruction = input('Enter the instruction [open/close]:') if instruction in ["o", "open", "c", "close"]: break else: print("wrong instruction") print('instruction : ', instruction) while simulation_app.is_running(): my_world.step(render=True) if my_world.is_playing(): observations = my_world.get_observations() if instruction == "o" or instruction == "open": actions = my_controller.open( current_joint_positions=observations[task_params["robot_name"]["value"]]["joint_positions"], ) elif instruction == "c" or instruction == "close": actions = my_controller.close( current_joint_positions=observations[task_params["robot_name"]["value"]]["joint_positions"], ) articulation_controller.apply_action(actions) # 컨트롤러가 끝나면 새로운 명령어 입력 받음 if my_controller.is_done(): if instruction == "o" or instruction == "open": print("done opening the gripper\n") elif instruction == "c" or instruction == "close": print("done closing the gripper\n") while True: instruction = input('Enter the instruction [open/close/quit]:') if instruction in ["o", "open", "c", "close", "q", "quit"]: break else: print("wrong instruction") print('instruction : ', instruction) print() if instruction == 'q' or instruction == 'quit': break my_controller.reset() simulation_app.close()
3,281
Python
37.16279
108
0.650716
gist-ailab/AILAB-isaac-sim-pick-place/lecture/dataset/origin_YCB/044_flat_screwdriver/poisson/nontextured.xml
<KinBody name="044_flat_screwdriver"> <Body type="static" name="044_flat_screwdriver"> <Geom type="trimesh"> <Render>./nontextured.stl</Render> <Data>./nontextured.stl</Data> </Geom> </Body> </KinBody>
226
XML
24.22222
50
0.632743
gist-ailab/AILAB-isaac-sim-pick-place/lecture/dataset/origin_YCB/035_power_drill/google_16k/kinbody.xml
<KinBody name="power_drill"> <Body type="static" name="power_drill"> <Geom type="trimesh"> <Render>textured.dae</Render> <Data>textured.dae</Data> </Geom> </Body> </KinBody>
198
XML
21.111109
41
0.611111
gist-ailab/AILAB-isaac-sim-pick-place/lecture/checkpoint/1.py
https://drive.google.com/file/d/1MbkrrGytk8aqzOBoVs11tUyhMoGgQnKs/view?usp=sharing
83
Python
40.99998
82
0.855422
rosklyar/omniverse_extensions/exts/playtika.eyedarts.export/playtika/eyedarts/export/extension.py
import omni.ext import carb.events import omni.kit.app import omni.ui as ui import omni.kit.window.filepicker as fp from pxr import Usd, UsdGeom, Gf import omni.usd import os from os.path import exists import asyncio import json # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): async def export_eyedarts(): output_folder = "C:/Users/rskliar/ue-projects/test_folder" progress_window = ui.Window("Export eye darts to json...", width=750, height=100) with progress_window.frame: with ui.VStack(): file_label = ui.StringField() pb = ui.ProgressBar() pb.model.set_value(0) stage = omni.usd.get_context().get_stage() manager = omni.audio2face.player.get_ext().player_manager() instance = manager.get_instance("/World/LazyGraph/Player") l_eye = stage.GetPrimAtPath("/World/male_fullface/char_male_model_hi/l_eye_grp_hi") r_eye = stage.GetPrimAtPath("/World/male_fullface/char_male_model_hi/r_eye_grp_hi") wav_files_folder = instance.get_abs_track_root_path() files_to_process = getWavFiles(wav_files_folder) for f in files_to_process: instance.set_track_name(f) pb.model.set_value(0) print("Processing file:" + f) file_label.model.set_value(f) fileLengthInSeconds = instance.get_range_end() time = 0.0 result = [] while(time < fileLengthInSeconds): e = await omni.kit.app.get_app().next_update_async() time += 1.0 / 60 instance.set_time(time) pose_l = omni.usd.utils.get_world_transform_matrix(l_eye) pose_r = omni.usd.utils.get_world_transform_matrix(r_eye) l_rx, l_ry, l_rz = pose_l.ExtractRotation().Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) r_rx, r_ry, r_rz = pose_r.ExtractRotation().Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) frame = [l_rx, l_ry, l_rz, r_rx, r_ry, r_rz] result.append(frame) pb.model.set_value(time / fileLengthInSeconds) result_json = { "numPoses": 6, "numFrames": len(result), "facsNames" : ["l_rx", "l_ry", "l_rz", "r_rx", "r_ry", "r_rz"], "weightMat": result } with open(output_folder + "/" + f[:-3] + "json", 'w') as outfile: json.dump(result_json, outfile) progress_window.destroy() progress_window.visible = False def on_change(event): if(event.type == 8): asyncio.ensure_future(export_eyedarts()) pass print("[playtika.eyedarts.export] ExportEyeDarts startup") self.output_folder = "" self.fps = 60 self._window = ui.Window("Export eye darts", width=750, height=300) self.filePicker = None self.folder_label = None print("Stream=" + str(omni.kit.app.get_app().get_message_bus_event_stream())) print("Update Stream=" + str(omni.kit.app.get_app().get_update_event_stream())) self._subscription = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(on_change) print("[playtika.eyedarts.export] ExportEyeDarts subscription created") with self._window.frame: with ui.VStack(): def getWavFiles(json_files_folder): files = [] if json_files_folder and not exists(json_files_folder): raise Exception("Please, select existed folder with JSON files!") for file in os.listdir(json_files_folder): if file.endswith('.wav'): files.append(file) return files def on_combobox_changed(model, item): self.fps = model.get_item_value_model(model.get_item_children()[model.get_item_value_model().as_int]).as_int def on_click(): asyncio.ensure_future(export()) async def export(): progress_window = ui.Window("Export eye darts to json...", width=750, height=100) with progress_window.frame: with ui.VStack(): file_label = ui.StringField() pb = ui.ProgressBar() pb.model.set_value(0) if(self.output_folder): stage = omni.usd.get_context().get_stage() manager = omni.audio2face.player.get_ext().player_manager() instance = manager.get_instance("/World/LazyGraph/Player") l_eye = stage.GetPrimAtPath("/World/male_fullface/char_male_model_hi/l_eye_grp_hi") r_eye = stage.GetPrimAtPath("/World/male_fullface/char_male_model_hi/r_eye_grp_hi") wav_files_folder = instance.get_abs_track_root_path() files_to_process = getWavFiles(wav_files_folder) for f in files_to_process: instance.set_track_name(f) pb.model.set_value(0) print("Processing file:" + f) file_label.model.set_value(f) fileLengthInSeconds = instance.get_range_end() time = 0.0 result = [] while(time < fileLengthInSeconds): e = await omni.kit.app.get_app().next_update_async() time += 1.0 / self.fps instance.set_time(time) pose_l = omni.usd.utils.get_world_transform_matrix(l_eye) pose_r = omni.usd.utils.get_world_transform_matrix(r_eye) l_rx, l_ry, l_rz = pose_l.ExtractRotation().Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) r_rx, r_ry, r_rz = pose_r.ExtractRotation().Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) frame = [l_rx, l_ry, l_rz, r_rx, r_ry, r_rz] result.append(frame) pb.model.set_value(time / fileLengthInSeconds) result_json = { "numPoses": 6, "numFrames": len(result), "facsNames" : ["l_rx", "l_ry", "l_rz", "r_rx", "r_ry", "r_rz"], "weightMat": result } with open(self.output_folder + "/" + f[:-3] + "json", 'w') as outfile: json.dump(result_json, outfile) progress_window.destroy() progress_window.visible = False def on_click_open(file_name, dir_name): print("File name: " + dir_name) self.output_folder = dir_name self.folder_label.text = "Output folder: " + self.output_folder self.filePicker.hide() def show_file_picker(): print("show file picker") self.filePicker = fp.FilePickerDialog("Select output folder", apply_button_label="Select", click_apply_handler=on_click_open) self.filePicker.show() with ui.HStack(): self.folder_label = ui.Label("Output folder: " + self.output_folder, height=20) ui.Button("Select", clicked_fn=lambda: show_file_picker(), width = 20, height=20) with ui.HStack(): ui.Label("FPS: ", height=20) fpsCombobox = ui.ComboBox(0, "60", "24") fpsCombobox.model.add_item_changed_fn(lambda model, item: on_combobox_changed(model, item)) ui.Button("Export", clicked_fn=lambda: on_click()) def on_shutdown(self): print("[playtika.eyedarts.export] ExportEyeDarts shutdown") def getWavFiles(json_files_folder): files = [] if json_files_folder and not exists(json_files_folder): raise Exception("Please, select existed folder with JSON files!") for file in os.listdir(json_files_folder): if file.endswith('.wav'): files.append(file) return files
9,417
Python
50.747252
145
0.511946
MatthewDZane/XArmFollowTarget/README.md
<a name="readme-top"></a> <!-- PROJECT SHIELDS --> <!-- *** I'm using markdown "reference style" links for readability. *** Reference links are enclosed in brackets [ ] instead of parentheses ( ). *** See the bottom of this document for the declaration of the reference variables *** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use. *** https://www.markdownguide.org/basic-syntax/#reference-style-links --> [![Contributors][contributors-shield]][contributors-url] [![Forks][forks-shield]][forks-url] [![Stargazers][stars-shield]][stars-url] [![Issues][issues-shield]][issues-url] [![LinkedIn][linkedin-shield]][linkedin-url] <!-- PROJECT LOGO --> <br /> <div align="center"> <a href="https://github/MatthewDZane/XArmFollowTarget/images/IsaacSim.png"> <img src="images/IsaacSim.png" alt="IsaacSim" width="700" height="400"> </a> <h3 align="center">XArm Follow Target</h3> <p align="center"> An Autonomous Camera Controller Robot <br /> <a href="https://github/MatthewDZane/XArmFollowTarget"><strong>Explore the docs »</strong></a> <br /> </a> </p> </div> <!-- TABLE OF CONTENTS --> <details> <summary>Table of Contents</summary> <ol> <li> <a href="#about-the-project">About The Project</a> <ul> <li><a href="#built-with">Built With</a></li> </ul> </li> <li> <a href="#using-xarm-follow-target-as-a-third-party-extension">Using Xarm Follow Target as a Third Party Extension</a> </li> </ol> </details> <!-- ABOUT THE PROJECT --> ## About The Project This project autonomously controls a RealSense Camera mounted to an [XArm Robot](https://www.ufactory.cc/xarm-collaborative-robot). The repo is comprised of several scripts, which are designed to run synchronously across several different machines (XArm Robot, Local RealSense Camera Machine, and Remote Nautilus Cluster Machine), which utilize NVidia's [Isaac Sim](https://developer.nvidia.com/isaac-sim) and Intel's [RealSense Camera](https://www.intelrealsense.com/). First the RealSense Camera script sends positional data to the remote machine, using OpenCV and the Camera's depth sensors. Then, the custom Isaac Sim Extension runs a Follow Target task, solving the Kinematic equations, to calculate the correct orientation of the XArm. Finally, these new orientations are sent back to the XArm itself to then update the robot is real life. This project was headed by Professor Robert Twomey at the University of Nebraska Lincoln and is intented for educational and experimental use. <p align="right">(<a href="#readme-top">back to top</a>)</p> ### Built With This project was built using the following. * [XArm](https://www.ufactory.cc/xarm-collaborative-robot) * [Isaac Sim](https://developer.nvidia.com/isaac-sim) * [RealSense Camera](https://www.intelrealsense.com/) <div align="center"> <a href="https://gitlab.nrp-nautilus.io/MatthewZane/XArmFollowTarget/images/RealSenseCamera.png"> <img src="images/RealSenseCamera.png" alt="RealSenseCamera" width="500" height="410"> </a> </div> # Using XArm Follow Target as a Third Party Extension 1. Clone the repo into the directory where you would like to store Isaac Sim Extensions 2. Open Isaac Sim and go to Windows->Extensions 3. Click the Settings Icon (Gear) and add the path to the parent directory of the repo (not XArm or XArmFollowTarget). Now the XArm Follow Target Extention should show up under the Third Party Extensions. 4. Enable the XArm Follow Target Extension and check the Autoload setting. The XArm Follow Target Extension will now appear on the top menu bar of the Isaac Sim Application. 5. Click the XArm Follow Target to use the Extension Port Forward local ports to the Container for the realsense camera client. - once you have a XGL container running you will need to use the kubernetes CLI to get the specific pod name. This can be done with ``` kubectl get pods -n <your namespace> ``` once you have your pod name we can now prot forward the local ports to the container for communication, Run ``` kubectl port-forward <running XGL pod> 12345:12345 12346:12346 -n <your namespace> ``` We use these ports by default <!-- MARKDOWN LINKS & IMAGES --> <!-- https://www.markdownguide.org/basic-syntax/#reference-style-links --> [contributors-shield]: https://img.shields.io/github/contributors/MatthewDZane/XArmFollowTarget.svg?style=for-the-badge [contributors-url]: https://gitlab.nrp-nautilus.io/MatthewZane/XArmFollowTarget/graphs/contributors [forks-shield]: https://img.shields.io/github/forks/MatthewDZane/XArmFollowTarget.svg?style=for-the-badge [forks-url]: https://gitlab.nrp-nautilus.io/MatthewZane/XArmFollowTarget/network/members [stars-shield]: https://img.shields.io/github/stars/MatthewDZane/XArmFollowTarget.svg?style=for-the-badge [stars-url]: https://gitlab.nrp-nautilus.io/MatthewZane/XArmFollowTarget/stargazers [issues-shield]: https://img.shields.io/github/issues/MatthewDZane/XArmFollowTarget.svg?style=for-the-badge [issues-url]: https://gitlab.nrp-nautilus.io/MatthewZane/XArmFollowTarget/issues [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555 [linkedin-url]: https://linkedin.com/in/matthewdzane
5,280
Markdown
44.525862
471
0.743371
MatthewDZane/XArmFollowTarget/scripts/scenario.py
# This software contains source code provided by NVIDIA Corporation. # Copyright (c) 2022-2023, 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. # class ScenarioTemplate: def __init__(self): pass def setup_scenario(self): pass def teardown_scenario(self): pass def update_scenario(self): pass import numpy as np from omni.isaac.core.utils.types import ArticulationAction """ This scenario takes in a robot Articulation and makes it move through its joint DOFs. Additionally, it adds a cuboid prim to the stage that moves in a circle around the robot. The particular framework under which this scenario operates should not be taken as a direct recomendation to the user about how to structure their code. In the simple example put together in this template, this particular structure served to improve code readability and separate the logic that runs the example from the UI design. """ class ExampleScenario(ScenarioTemplate): def __init__(self): self._object = None self._articulation = None self._running_scenario = False self._time = 0.0 # s self._object_radius = 0.5 # m self._object_height = 0.5 # m self._object_frequency = 0.25 # Hz self._joint_index = 0 self._max_joint_speed = 4 # rad/sec self._lower_joint_limits = None self._upper_joint_limits = None self._joint_time = 0 self._path_duration = 0 self._calculate_position = lambda t, x: 0 self._calculate_velocity = lambda t, x: 0 def setup_scenario(self, articulation, object_prim): self._articulation = articulation self._object = object_prim self._initial_object_position = self._object.get_world_pose()[0] self._initial_object_phase = np.arctan2(self._initial_object_position[1], self._initial_object_position[0]) self._object_radius = np.linalg.norm(self._initial_object_position[:2]) self._running_scenario = True self._joint_index = 0 self._lower_joint_limits = articulation.dof_properties["lower"] self._upper_joint_limits = articulation.dof_properties["upper"] # teleport robot to lower joint range epsilon = 0.001 articulation.set_joint_positions(self._lower_joint_limits + epsilon) self._derive_sinusoid_params(0) def teardown_scenario(self): self._time = 0.0 self._object = None self._articulation = None self._running_scenario = False self._joint_index = 0 self._lower_joint_limits = None self._upper_joint_limits = None self._joint_time = 0 self._path_duration = 0 self._calculate_position = lambda t, x: 0 self._calculate_velocity = lambda t, x: 0 def update_scenario(self, step: float): if not self._running_scenario: return self._time += step x = self._object_radius * np.cos(self._initial_object_phase + self._time * self._object_frequency * 2 * np.pi) y = self._object_radius * np.sin(self._initial_object_phase + self._time * self._object_frequency * 2 * np.pi) z = self._initial_object_position[2] self._object.set_world_pose(np.array([x, y, z])) self._update_sinusoidal_joint_path(step) def _derive_sinusoid_params(self, joint_index: int): # Derive the parameters of the joint target sinusoids for joint {joint_index} start_position = self._lower_joint_limits[joint_index] P_max = self._upper_joint_limits[joint_index] - start_position V_max = self._max_joint_speed T = P_max * np.pi / V_max # T is the expected time of the joint path self._path_duration = T self._calculate_position = ( lambda time, path_duration: start_position + -P_max / 2 * np.cos(time * 2 * np.pi / path_duration) + P_max / 2 ) self._calculate_velocity = lambda time, path_duration: V_max * np.sin(2 * np.pi * time / path_duration) def _update_sinusoidal_joint_path(self, step): # Update the target for the robot joints self._joint_time += step if self._joint_time > self._path_duration: self._joint_time = 0 self._joint_index = (self._joint_index + 1) % self._articulation.num_dof self._derive_sinusoid_params(self._joint_index) joint_position_target = self._calculate_position(self._joint_time, self._path_duration) joint_velocity_target = self._calculate_velocity(self._joint_time, self._path_duration) action = ArticulationAction( np.array([joint_position_target]), np.array([joint_velocity_target]), joint_indices=np.array([self._joint_index]), ) self._articulation.apply_action(action)
5,251
Python
34.486486
118
0.645972
MatthewDZane/XArmFollowTarget/scripts/extension.py
# This software contains source code provided by NVIDIA Corporation. # Copyright (c) 2022-2023, 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. # import weakref import asyncio import gc import omni import omni.ui as ui import omni.usd import omni.timeline import omni.kit.commands from omni.kit.menu.utils import add_menu_items, remove_menu_items from omni.isaac.ui.menu import make_menu_item_description from omni.usd import StageEventType import omni.physx as _physx from .global_variables import EXTENSION_TITLE, EXTENSION_DESCRIPTION from .ui_builder import UIBuilder """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(omni.ext.IExt): def on_startup(self, ext_id: str): """Initialize extension and UI elements""" # Events self._usd_context = omni.usd.get_context() # Build Window self._window = ui.Window( title=EXTENSION_TITLE, width=600, height=500, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM ) self._window.set_visibility_changed_fn(self._on_window) # UI self._models = {} self._ext_id = ext_id self._menu_items = [ make_menu_item_description(ext_id, EXTENSION_TITLE, lambda a=weakref.proxy(self): a._menu_callback()) ] add_menu_items(self._menu_items, EXTENSION_TITLE) # Filled in with User Functions self.ui_builder = UIBuilder() # Events self._usd_context = omni.usd.get_context() self._physxIFace = _physx.acquire_physx_interface() self._physx_subscription = None self._stage_event_sub = None self._timeline = omni.timeline.get_timeline_interface() def on_shutdown(self): self._models = {} remove_menu_items(self._menu_items, EXTENSION_TITLE) if self._window: self._window = None self.ui_builder.cleanup() gc.collect() def _on_window(self, visible): if self._window.visible: # Subscribe to Stage and Timeline Events self._usd_context = omni.usd.get_context() events = self._usd_context.get_stage_event_stream() self._stage_event_sub = events.create_subscription_to_pop(self._on_stage_event) stream = self._timeline.get_timeline_event_stream() self._timeline_event_sub = stream.create_subscription_to_pop(self._on_timeline_event) self._build_ui() else: self._usd_context = None self._stage_event_sub = None self._timeline_event_sub = None self.ui_builder.cleanup() def _build_ui(self): with self._window.frame: with ui.VStack(spacing=5, height=0): self._build_extension_ui() async def dock_window(): await omni.kit.app.get_app().next_update_async() def dock(space, name, location, pos=0.5): window = omni.ui.Workspace.get_window(name) if window and space: window.dock_in(space, location, pos) return window tgt = ui.Workspace.get_window("Viewport") dock(tgt, EXTENSION_TITLE, omni.ui.DockPosition.LEFT, 0.33) await omni.kit.app.get_app().next_update_async() self._task = asyncio.ensure_future(dock_window()) ################################################################# # Functions below this point call user functions ################################################################# def _menu_callback(self): self._window.visible = not self._window.visible self.ui_builder.on_menu_callback() def _on_timeline_event(self, event): if event.type == int(omni.timeline.TimelineEventType.PLAY): if not self._physx_subscription: self._physx_subscription = self._physxIFace.subscribe_physics_step_events(self._on_physics_step) elif event.type == int(omni.timeline.TimelineEventType.STOP): self._physx_subscription = None self.ui_builder.on_timeline_event(event) def _on_physics_step(self, step): self.ui_builder.on_physics_step(step) def _on_stage_event(self, event): if event.type == int(StageEventType.OPENED) or event.type == int(StageEventType.CLOSED): # stage was opened or closed, cleanup self._physx_subscription = None self.ui_builder.cleanup() self.ui_builder.on_stage_event(event) def _build_extension_ui(self): # Call user function for building UI self.ui_builder.build_ui()
5,777
Python
36.764706
117
0.647395
MatthewDZane/XArmFollowTarget/scripts/ui_builder.py
# This software contains source code provided by NVIDIA Corporation. # Copyright (c) 2022-2023, 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. # import sys import os SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR)) import omni.ui as ui import omni.timeline from omni.isaac.core.world import World from omni.isaac.ui.ui_utils import get_style, btn_builder, state_btn_builder, cb_builder, float_builder from omni.usd import StageEventType from .XArm.xarm_sample import XArmSample import asyncio class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper instance self.wrapped_ui_elements = [] self._buttons = None self._task_ui_elements = None # Get access to the timeline to control stop/pause/play programmatically self._timeline = omni.timeline.get_timeline_interface() self._sample = XArmSample() ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step: float): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ if self._sample._world is not None: self._sample._world_cleanup() if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load XArm5"].enabled = True self._buttons["Load XArm7"].enabled = True self.shutdown_cleanup() return def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ self._buttons = {} self._task_ui_elements = {} world_controls_frame = ui.CollapsableFrame(title="World Controls", collapsed=False) with world_controls_frame: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Load XArm5", "type": "button", "text": "Load", "tooltip": "Load XArm5 and Task", "on_clicked_fn": self._on_load_xarm5, } self._buttons["Load XArm5"] = btn_builder(**dict) self._buttons["Load XArm5"].enabled = True dict = { "label": "Load XArm7", "type": "button", "text": "Load", "tooltip": "Load XArm7 and Task", "on_clicked_fn": self._on_load_xarm7, } self._buttons["Load XArm7"] = btn_builder(**dict) self._buttons["Load XArm7"].enabled = True dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = False task_controls_frame = ui.CollapsableFrame(title="Task Controls", collapsed=False) with task_controls_frame: with ui.VStack(spacing=5): task_controls_frame.visible = True dict = { "label": "Follow Target", "type": "button", "a_text": "START", "b_text": "STOP", "tooltip": "Follow Target", "on_clicked_fn": self._on_follow_target_button_event, } self._task_ui_elements["Follow Target"] = state_btn_builder(**dict) self._task_ui_elements["Follow Target"].enabled = False dict = { "label": "Add Obstacle", "type": "button", "text": "ADD", "tooltip": "Add Obstacle", "on_clicked_fn": self._on_add_obstacle_button_event, } self._task_ui_elements["Add Obstacle"] = btn_builder(**dict) self._task_ui_elements["Add Obstacle"].enabled = False dict = { "label": "Remove Obstacle", "type": "button", "text": "REMOVE", "tooltip": "Remove Obstacle", "on_clicked_fn": self._on_remove_obstacle_button_event, } self._task_ui_elements["Remove Obstacle"] = btn_builder(**dict) self._task_ui_elements["Remove Obstacle"].enabled = False dict = { "label": "Random Target Enabled", "type": "checkbox", "default_val": True, "tooltip": "Random Target Enabled", "on_clicked_fn": self._on_random_target_enabled_event } self._task_ui_elements["Random Target Checkbox"] = cb_builder(**dict) args = { "label": "Min Face Range", "default_val": .3, "tooltip": "Min Range in Meters", } self._task_ui_elements["Min Face Range"] = float_builder(**args) self._task_ui_elements["Min Face Range"].add_value_changed_fn(self._on_min_face_range_changed_event) args = { "label": "Max Face Range", "default_val": 10, "tooltip": "Max Range in Meters", } self._task_ui_elements["Max Face Range"] = float_builder(**args) self._task_ui_elements["Max Face Range"].add_value_changed_fn(self._on_max_face_range_changed_event) def _on_load_xarm5(self): self._sample.set_xarm_version(5) self._on_random_target_enabled_event(False) self._on_min_face_range_changed_event(self._task_ui_elements["Min Face Range"].get_value_as_float()) self._on_max_face_range_changed_event(self._task_ui_elements["Max Face Range"].get_value_as_float()) async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load XArm5"].enabled = False self._buttons["Load XArm7"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_load_xarm7(self): self._sample.set_xarm_version(7) self._on_random_target_enabled_event(False) self._on_min_face_range_changed_event(self._task_ui_elements["Min Face Range"].get_value_as_float()) self._on_max_face_range_changed_event(self._task_ui_elements["Max Face Range"].get_value_as_float()) async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load XArm7"].enabled = False self._buttons["Load XArm5"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_reset(self): async def _on_reset_async(): await self._sample.reset_async() await omni.kit.app.get_app().next_update_async() self.post_reset_button_event() asyncio.ensure_future(_on_reset_async()) return def _on_follow_target_button_event(self, val): asyncio.ensure_future(self._sample._on_follow_target_event_async(val)) return def _on_add_obstacle_button_event(self): self._sample._on_add_obstacle_event() self._task_ui_elements["Remove Obstacle"].enabled = True return def _on_remove_obstacle_button_event(self): self._sample._on_remove_obstacle_event() world = self._sample.get_world() current_task = list(world.get_current_tasks().values())[0] if not current_task.obstacles_exist(): self._task_ui_elements["Remove Obstacle"].enabled = False return def _on_random_target_enabled_event(self, val): self._sample.rand_target_enabled = self._task_ui_elements["Random Target Checkbox"].get_value_as_bool() def _on_min_face_range_changed_event(self, val): self._sample.min_detection_range = self._task_ui_elements["Min Face Range"].get_value_as_float() def _on_max_face_range_changed_event(self, val): self._sample.max_detection_range = self._task_ui_elements["Max Face Range"].get_value_as_float() def _enable_all_buttons(self, flag): for btn_name, btn in self._buttons.items(): if isinstance(btn, omni.ui._ui.Button): btn.enabled = flag return def _on_follow_target_button_event(self, val): asyncio.ensure_future(self._sample._on_follow_target_event_async(val)) return def _on_save_data_button_event(self): self._sample._on_save_data_event(self._task_ui_elements["Output Directory"].get_value_as_string()) return def post_reset_button_event(self): self._task_ui_elements["Follow Target"].enabled = True self._task_ui_elements["Remove Obstacle"].enabled = False self._task_ui_elements["Add Obstacle"].enabled = True if self._task_ui_elements["Follow Target"].text == "STOP": self._task_ui_elements["Follow Target"].text = "START" return def post_load_button_event(self): self._task_ui_elements["Follow Target"].enabled = True self._task_ui_elements["Add Obstacle"].enabled = True return def post_clear_button_event(self): self._task_ui_elements["Follow Target"].enabled = False self._task_ui_elements["Remove Obstacle"].enabled = False self._task_ui_elements["Add Obstacle"].enabled = False if self._task_ui_elements["Follow Target"].text == "STOP": self._task_ui_elements["Follow Target"].text = "START" return def shutdown_cleanup(self): return def on_stage_event(self, event): if event.type == int(StageEventType.OPENED): # If the user opens a new stage, the extension should completely reset self._task_ui_elements["Follow Target"].enabled = False self._task_ui_elements["Remove Obstacle"].enabled = False self._task_ui_elements["Add Obstacle"].enabled = False if self._task_ui_elements["Follow Target"].text == "STOP": self._task_ui_elements["Follow Target"].text = "START" elif event.type == int(omni.usd.StageEventType.CLOSED): if World.instance() is not None: self._sample._world_cleanup() self._sample._world.clear_instance() if hasattr(self, "_buttons"): if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load XArm5"].enabled = True self._buttons["Load XArm7"].enabled = True return def _reset_on_stop_event(self, e): if e.type == int(omni.timeline.TimelineEventType.STOP): #self._buttons["Load XArm5"].enabled = False #self._buttons["Load XArm7"].enabled = False self._buttons["Reset"].enabled = True self.post_clear_button_event() return
13,492
Python
40.516923
116
0.561073
MatthewDZane/XArmFollowTarget/scripts/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template extension creates a basic tool for interacting with a robot Articulation through the UI by changing its joint position targets. This format is generally useful for building UI tools to help with robot configuration or inspection. To use the template as written, the user must load a robot Articulation onto the stage, and press the PLAY button on the left-hand toolbar. Then, in the extension UI, they can select their Articulation from a drop-down menu and start controlling the robot joint position targets. The extension only functions while the timeline is running because robot Articulation objects only function while the timeline is playing (physics does not run while the timeline is stopped stopped). # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
2,057
Markdown
61.363635
132
0.79825
MatthewDZane/XArmFollowTarget/scripts/XArm/xarm_socket.py
import ast import socket import threading import carb class XArmSocket(): def __init__(self) -> None: # sending position data to arm self.txsocket = None self.txconn = None # tracking info self.rxsocket = None self.rxconn = None self.cam_to_nose = None self.face_direction = None self.dx = None self.dy = None # threads self.txsocket_thread = None self.rxsocket_thread = None def start_txsocket(self): self.txsocket_thread = threading.Thread(target=self.setup_txsocket) self.txsocket_thread.start() def start_rxsocket(self): self.rxsocket_thread = threading.Thread(target=self.setup_rxsocket) self.rxsocket_thread.start() def setup_txsocket(self): if self.txsocket is None: self.txsocket = socket.socket() # allow socket to reuse address self.txsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) txport = 12345 self.txsocket.bind(('', txport)) # https://docs.python.org/3/library/socket.html#socket.socket.listen self.txsocket.listen(5) # number of unaccepted connections allow (backlog) while True: self.txconn, self.txaddr = self.txsocket.accept() print("accepted tx connection from:",str(self.txaddr[0]), ":", str(self.txaddr[1])) def setup_rxsocket(self): if self.rxsocket is None: self.rxsocket = socket.socket() # allow socket to reuse address self.rxsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) rxport = 12346 self.rxsocket.bind(('', rxport)) # https://docs.python.org/3/library/socket.html#socket.socket.listen self.rxsocket.listen(5) # number of unaccepted connections allow (backlog) while True: self.rxconn, self.rxaddr = self.rxsocket.accept() print("accepted rx connection from:",str(self.rxaddr[0]), ":", str(self.rxaddr[1])) while True: data = self.rxconn.recv(1024) if data: message = data.decode() # carb.log_error("received:" + str(type(message)) + message) cam_to_nose = [0, 0, 0] face_direction = [0, 0, 0] try: cam_to_nose[0], cam_to_nose[1], cam_to_nose[2], face_direction[0], face_direction[1], face_direction[2], dx, dy = ast.literal_eval(message) except ValueError: self.cam_to_nose = None self.face_direction = None self.dx = None self.dy = None else: # print("received:", x, y, z, dx, dy, dist) weight = 0.1 self.cam_to_nose = cam_to_nose self.face_direction = face_direction self.dx = weight*dx self.dy = weight*dy else: self.cam_to_nose = None self.face_direction = None self.dx = None self.dy = None def shut_down_socket(self): if self.txconn: try: # self._conn.send("Done".encode()) self.txsocket.shutdown(socket.SHUT_RDWR) self.txsocket.close() self.txsocket = None except socket.error as e: pass if self.rxconn: try: # self._conn.send("Done".encode()) self.rxsocket.shutdown(socket.SHUT_RDWR) self.rxsocket.close() self.rxsocket = None except socket.error as e: pass
3,939
Python
35.82243
163
0.513074
MatthewDZane/XArmFollowTarget/scripts/XArm/xarm_rmpflow_controller.py
import omni.isaac.motion_generation as mg from omni.isaac.core.articulations import Articulation import pathlib class XArmRMPFlowController(mg.MotionPolicyController): """[summary] Args: name (str): [description] robot_articulation (Articulation): [description] physics_dt (float, optional): [description]. Defaults to 1.0/60.0. attach_gripper (bool, optional): [description]. Defaults to False. """ def __init__( self, name: str, robot_articulation: Articulation, physics_dt: float = 1.0 / 60.0, xarm_version: int = 7 ) -> None: current_directory = str(pathlib.Path(__file__).parent.resolve()).replace("\\", "/") if xarm_version == 5: relative_robot_description_path = "/XArm/XArm5/xarm5_descriptor.yaml" relative_urdf_path = "/XArm/XArm5/xarm5.urdf" relative_rmpflow_config_path = "/XArm/XArm5/xarm5_rmpflow_common.yaml" end_effector_frame_name = "link5" elif xarm_version == 7: relative_robot_description_path = "/XArm/XArm7/xarm7_descriptor.yaml" relative_urdf_path = "/XArm/XArm7/xarm7.urdf" relative_rmpflow_config_path = "/XArm/XArm7/xarm7_rmpflow_common.yaml" end_effector_frame_name = "link7" self.rmp_flow = mg.lula.motion_policies.RmpFlow( robot_description_path=current_directory + relative_robot_description_path, urdf_path=current_directory + relative_urdf_path, rmpflow_config_path=current_directory + relative_rmpflow_config_path, end_effector_frame_name=end_effector_frame_name, maximum_substep_size=0.0334, ignore_robot_state_updates=False, ) self.articulation_rmp = mg.ArticulationMotionPolicy(robot_articulation, self.rmp_flow, physics_dt) mg.MotionPolicyController.__init__(self, name=name, articulation_motion_policy=self.articulation_rmp) self._default_position, self._default_orientation = ( self._articulation_motion_policy._robot_articulation.get_world_pose() ) self._motion_policy.set_robot_base_pose( robot_position=self._default_position, robot_orientation=self._default_orientation ) return def reset(self): mg.MotionPolicyController.reset(self) self._motion_policy.set_robot_base_pose( robot_position=self._default_position, robot_orientation=self._default_orientation )
2,559
Python
40.967212
109
0.638531
MatthewDZane/XArmFollowTarget/scripts/XArm/xarm5_follow_target_with_standalone.py
import sys import os SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR)) from omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) from omni.isaac.core.utils.extensions import enable_extension enable_extension("omni.isaac.examples") from omni.isaac.core import World from XArm.xarm_follow_target import XArmFollowTarget from XArm.xarm_rmpflow_controller import XArmRMPFlowController from XArm.xarm_socket import XArmSocket import numpy as np import time def get_new_target_orientation(position): direction_vector = np.array([0, 0, 0]) - position normalized_direction = direction_vector / np.linalg.norm(direction_vector) rotation_axis = np.cross(np.array([0, 0, -1]), normalized_direction) rotation_axis /= np.linalg.norm(rotation_axis) rotation_angle = np.arccos(np.dot(np.array([0, 0, -1]), normalized_direction)) half_angle = 0.5 * rotation_angle sin_half_angle = np.sin(half_angle) cos_half_angle = np.cos(half_angle) quaternion = np.array([ cos_half_angle, sin_half_angle * rotation_axis[0], sin_half_angle * rotation_axis[1], sin_half_angle * rotation_axis[2] ]) return quaternion def main(): xarm_version = 5 world = World(stage_units_in_meters=1.0) xarm_task = XArmFollowTarget(xarm_version=xarm_version) world.add_task(xarm_task) world.reset() task_params = world.get_task("xarm_follow_target_task").get_params() xarm_name = task_params["robot_name"]["value"] target_name = task_params["target_name"]["value"] xarm = world.scene.get_object(xarm_name) cube = world.scene.get_object(target_name) xarm_controller = XArmRMPFlowController( name="target_follower_controller", robot_articulation=xarm, xarm_version=xarm_version ) articulation_controller = xarm.get_articulation_controller() xarm_socket = XArmSocket() xarm_socket.start_txsocket() xarm_socket.start_rxsocket() max_range = 0.6 min_range = 0.4 min_height = 0.2 last_face_seen_timeout = 1 last_face_seen_time = 0 last_rand_target_timeout = 5 last_rand_target_time = 0 start_time = time.time() wait_time = 1 while simulation_app.is_running() and time.time() < start_time + wait_time: world.step(render=True) if world.is_playing(): if world.current_time_step_index == 0: world.reset() xarm_controller.reset() while simulation_app.is_running(): world.step(render=True) if world.is_playing(): observations = world.get_observations() actions = xarm_controller.forward( target_end_effector_position=observations[task_params["target_name"]["value"]]["position"], target_end_effector_orientation=observations[task_params["target_name"]["value"]]["orientation"], ) gains = 1e15*np.ones(5), 1e14*np.ones(5) articulation_controller.set_gains(gains[0], gains[1]) # Solution from Nvidia Live Session 1:23:00 articulation_controller.apply_action(actions) if xarm_socket.txconn: try: sendData = str(xarm.get_joint_positions().tolist()) res = xarm_socket.txconn.send(sendData.encode()) if res == 0: print("channel is closed...") except: # if sending failed, recreate the socket and reconnect print("sending failed... closing connection") xarm_socket.txconn.close() xarm_socket.txconn = None current_time = time.time() if xarm_socket.dx and xarm_socket.dy: # update position of target from camera feed cube = world.scene.get_object("target") pos, _ = cube.get_world_pose() newpose = [pos[0], pos[1] + xarm_socket.dx, pos[2] + xarm_socket.dy] range = np.linalg.norm(newpose) if range < min_range: newpose = newpose / np.linalg.norm(newpose) * min_range elif range > max_range: newpose = newpose / np.linalg.norm(newpose) * max_range newpose = [newpose[0], newpose[1], max(newpose[2], min_height)] updated_quaternion = get_new_target_orientation(newpose) print("pose", pos, "->", newpose, end="") cube.set_world_pose(np.array(newpose), updated_quaternion) print("set.") xarm_socket.dx = None xarm_socket.dy = None last_face_seen_time = current_time elif ( \ xarm_task.task_achieved or \ current_time > last_rand_target_time + last_rand_target_timeout \ ) and current_time > last_face_seen_time + last_face_seen_timeout: # set random location cube = world.scene.get_object("target") randpos = [ np.random.uniform(-1, 1), np.random.uniform(-1, 1), np.random.uniform(0, 1) ] range = np.linalg.norm(randpos) if range < min_range: randpos = randpos / np.linalg.norm(randpos) * min_range elif range > max_range: randpos = randpos / np.linalg.norm(randpos) * max_range randpos = [randpos[0], randpos[1], max(randpos[2], min_height)] updated_quaternion = get_new_target_orientation(randpos) print("Setting new target pos:"+str(randpos)) cube.set_world_pose(np.array(randpos), updated_quaternion) last_rand_target_time = time.time() xarm_socket.shut_down_socket() simulation_app.close() if __name__ == '__main__': main()
6,120
Python
35.218935
113
0.577124
MatthewDZane/XArmFollowTarget/scripts/XArm/xarm_sample.py
from omni.isaac.examples.base_sample import BaseSample from .xarm_follow_target import XArmFollowTarget from .xarm_rmpflow_controller import XArmRMPFlowController from .xarm_socket import XArmSocket import numpy as np import time import carb import omni.kit.pipapi omni.kit.pipapi.install("pyquaternion") from pyquaternion import Quaternion class XArmSample(BaseSample): def __init__(self) -> None: super().__init__() self._controller = None self._articulation_controller = None self._xarm_version = None # sending position data to arm self.xarm_socket = XArmSocket() self._max_range = None self._min_range = None self._min_height = None self._last_face_seen_timeout = 1 self._last_face_seen_time = 0 self.rand_target_enabled = True self._last_rand_target_timeout = 5 self._last_rand_target_time = 0 self.min_detection_range = None self.max_detection_range = None def set_xarm_version(self, xarm_version): self._xarm_version = xarm_version if self._xarm_version == 5: self._max_range = 0.7 self._min_range = 0.3 self._min_height = 0.1 elif self._xarm_version == 7: self._max_range = 0.7 self._min_range = 0.3 self._min_height = 0.1 def setup_scene(self): world = self.get_world() world.add_task(XArmFollowTarget(self._xarm_version)) return async def setup_pre_reset(self): world = self.get_world() if world.physics_callback_exists("sim_step"): world.remove_physics_callback("sim_step") self._controller.reset() return def world_cleanup(self): self._controller = None self.xarm_socket.shut_down_socket() return async def setup_post_load(self): self._xarm_task = list(self._world.get_current_tasks().values())[0] self._task_params = self._xarm_task.get_params() self._xarm = self._world.scene.get_object(self._task_params["robot_name"]["value"]) self._controller = XArmRMPFlowController( name="target_follower_controller", robot_articulation=self._xarm, xarm_version=self._xarm_version ) self._articulation_controller = self._xarm.get_articulation_controller() self.xarm_socket.start_txsocket() self.xarm_socket.start_rxsocket() return async def _on_follow_target_event_async(self, val): world = self.get_world() if val: await world.play_async() world.add_physics_callback("sim_step", self._on_follow_target_simulation_step) else: world.remove_physics_callback("sim_step") return def _on_follow_target_simulation_step(self, step_size): observations = self._world.get_observations() actions = self._controller.forward( target_end_effector_position=observations[self._task_params["target_name"]["value"]]["position"], target_end_effector_orientation=observations[self._task_params["target_name"]["value"]]["orientation"], ) self._articulation_controller.set_gains( 1e15*np.ones(self._xarm_version), 1e14*np.ones(self._xarm_version) ) # Solution from Nvidia Live Session 1:23:00 self._articulation_controller.apply_action(actions) if self.xarm_socket.txconn: try: sendData = str(self._xarm.get_joint_positions().tolist()) #print("joints:", sendData) res = self.xarm_socket.txconn.send(sendData.encode()) if res == 0: print("channel is closed...") except Exception as e: print(e) # if sending failed, recreate the socket and reconnect print("sending failed... closing connection") self.xarm_socket.txconn.close() self.xarm_socket.txconn = None face_in_range = False if self.xarm_socket.cam_to_nose and self.xarm_socket.face_direction: cam_position, cam_orientation = self._xarm.end_effector.get_world_pose() nose_distance_from_camera = np.linalg.norm(self.xarm_socket.cam_to_nose) carb.log_error(str(self.min_detection_range) + " " + str(self.max_detection_range) + " " + str(nose_distance_from_camera)) face_in_range = nose_distance_from_camera >= self.min_detection_range and nose_distance_from_camera <= self.max_detection_range current_time = time.time() if face_in_range: carb.log_error("here") cam_orientation = Quaternion(cam_orientation) nose_position = cam_orientation.rotate(self.xarm_socket.cam_to_nose) + cam_position nose_direction = cam_orientation.rotate(self.xarm_socket.face_direction) nose_direction /= np.linalg.norm(nose_direction) # update position of target from camera feed cube = self._world.scene.get_object("target") if nose_distance_from_camera < self.min_detection_range: newpose = nose_position + nose_direction * self.min_detection_range elif nose_distance_from_camera > self.max_detection_range: newpose = nose_position + nose_direction * self.max_detection_range else: newpose = nose_position + nose_direction * nose_distance_from_camera range = np.linalg.norm(newpose) if range < self._min_range: newpose = newpose / np.linalg.norm(newpose) * self._min_range elif range > self._max_range: newpose = newpose / np.linalg.norm(newpose) * self._max_range newpose = [newpose[0], newpose[1], max(newpose[2], self._min_height)] updated_quaternion = self._get_new_target_orientation(newpose) cube.set_world_pose(np.array(newpose), updated_quaternion) self.xarm_socket.dx = None self.xarm_socket.dy = None self._last_face_seen_time = current_time elif self.rand_target_enabled and ( \ self._xarm_task.task_achieved or \ current_time > self._last_rand_target_time + self._last_rand_target_timeout \ ) and current_time > self._last_face_seen_time + self._last_face_seen_timeout: # set random location cube = self._world.scene.get_object("target") randpos = [ np.random.uniform(-1, 1), np.random.uniform(-1, 1), np.random.uniform(0, 1) ] range = np.linalg.norm(randpos) if range < self._min_range: randpos = randpos / np.linalg.norm(randpos) * self._min_range elif range > self._max_range: randpos = randpos / np.linalg.norm(randpos) * self._max_range randpos = [randpos[0], randpos[1], max(randpos[2], self._min_height)] updated_quaternion = self._get_new_target_orientation(randpos) print("Setting new target pos:"+str(randpos)) cube.set_world_pose(np.array(randpos), updated_quaternion) self._last_rand_target_time = time.time() self.xarm_socket.cam_to_nose=None self.xarm_socket.face_direction=None return def _on_add_obstacle_event(self): world = self.get_world() current_task = list(world.get_current_tasks().values())[0] cube = current_task.add_obstacle() self._controller.add_obstacle(cube) return def _on_remove_obstacle_event(self): world = self.get_world() current_task = list(world.get_current_tasks().values())[0] obstacle_to_delete = current_task.get_obstacle_to_delete() self._controller.remove_obstacle(obstacle_to_delete) current_task.remove_obstacle() return def _on_logging_event(self, val): world = self.get_world() data_logger = world.get_data_logger() if not world.get_data_logger().is_started(): robot_name = self._task_params["robot_name"]["value"] target_name = self._task_params["target_name"]["value"] def frame_logging_func(tasks, scene): return { "joint_positions": scene.get_object(robot_name).get_joint_positions().tolist(), "applied_joint_positions": scene.get_object(robot_name) .get_applied_action() .joint_positions.tolist(), "target_position": scene.get_object(target_name).get_world_pose()[0].tolist(), } data_logger.add_data_frame_logging_func(frame_logging_func) if val: data_logger.start() else: data_logger.pause() return def _on_save_data_event(self, log_path): world = self.get_world() data_logger = world.get_data_logger() data_logger.save(log_path=log_path) data_logger.reset() return def _get_new_target_orientation(self, position): direction_vector = np.array([0, 0, 0.3]) - position normalized_direction = direction_vector / np.linalg.norm(direction_vector) rotation_axis = np.cross(np.array([0, 0, -1]), normalized_direction) rotation_axis /= np.linalg.norm(rotation_axis) rotation_angle = np.arccos(np.dot(np.array([0, 0, -1]), normalized_direction)) half_angle = 0.5 * rotation_angle sin_half_angle = np.sin(half_angle) cos_half_angle = np.cos(half_angle) quaternion = np.array([ cos_half_angle, sin_half_angle * rotation_axis[0], sin_half_angle * rotation_axis[1], sin_half_angle * rotation_axis[2] ]) return quaternion
10,092
Python
38.89328
139
0.586504
MatthewDZane/XArmFollowTarget/scripts/XArm/xarm_follow_target.py
from .xarm import XArm import numpy as np import omni.isaac.core.tasks as tasks from omni.isaac.core.utils.stage import get_stage_units import carb class XArmFollowTarget(tasks.FollowTarget): """[summary] Args: name (str, optional): [description]. Defaults to "ur10_follow_target". target_prim_path (Optional[str], optional): [description]. Defaults to None. target_name (Optional[str], optional): [description]. Defaults to None. target_position (Optional[np.ndarray], optional): [description]. Defaults to None. target_orientation (Optional[np.ndarray], optional): [description]. Defaults to None. """ def __init__(self, xarm_version: int = 7): super().__init__(name="xarm_follow_target_task", target_position=np.array([0.3, 0.0, 0.5]) / get_stage_units(), offset=None) self._goal_position = np.array([0, 0, 0]) self.task_achieved = False self.xarm_version = xarm_version return def set_up_scene(self, scene): super().set_up_scene(scene) scene.add_default_ground_plane() self._cube = scene.get_object("target") # cpose, crot = self._cube.get_world_pose() # self._cube.set_world_pose(cpose, np.Array([180.0, 90, -180])) return def pre_step(self, control_index, simulation_time): self._goal_position, orient = self._cube.get_world_pose() end_effector_position, _ = self._xarm.end_effector.get_world_pose() # print("orientation"+str(orient)) dist = np.mean(np.abs(self._goal_position - end_effector_position)) if not self.task_achieved is bool(dist < 0.02): self.task_achieved = bool(dist < 0.02) if self.task_achieved: print("Target Reached") self._cube.get_applied_visual_material().set_color(color=np.array([0, 1.0, 0])) else: self._cube.get_applied_visual_material().set_color(color=np.array([1.0, 0, 0])) return def set_robot(self) -> XArm: """[summary] Returns: XArm: [description] """ if self.xarm_version == 5: prim_path = "/World/XArm5" name = "xarm5" positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0]) elif self.xarm_version == 7: prim_path = "/World/XArm7" name = "xarm7" positions=np.array([-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2, np.pi / 2, 0]) self._xarm = XArm(prim_path=prim_path, name=name, version=self.xarm_version) self._xarm.set_joints_default_state( positions=positions ) return self._xarm
2,758
Python
38.414285
132
0.577592
MatthewDZane/XArmFollowTarget/scripts/XArm/xarm.py
from typing import Optional import numpy as np from omni.isaac.core.robots.robot import Robot from omni.isaac.core.prims.rigid_prim import RigidPrim from omni.isaac.core.utils.stage import add_reference_to_stage import pathlib class XArm(Robot): """[summary] Args: prim_path (str): [description] name (str, optional): [description]. Defaults to "ur10_robot". usd_path (Optional[str], optional): [description]. Defaults to None. position (Optional[np.ndarray], optional): [description]. Defaults to None. orientation (Optional[np.ndarray], optional): [description]. Defaults to None. """ def __init__( self, prim_path: str, name: str = "xarm_robot", version: Optional[int] = 7, position: Optional[np.ndarray] = None, orientation: Optional[np.ndarray] = None ) -> None: self._end_effector = None current_directory = str(pathlib.Path(__file__).parent.resolve()).replace("\\", "/") if version == 5: relative_usd_path = "/XArm/XArm5/xarm5.usd" end_link = "/link5" elif version == 7: relative_usd_path = "/XArm/XArm7/xarm7.usd" end_link = "/link7" add_reference_to_stage(usd_path=current_directory + relative_usd_path, prim_path=prim_path) self._end_effector_prim_path = prim_path + end_link super().__init__( prim_path=prim_path, name=name, position=position, orientation=orientation, articulation_controller=None ) return @property def end_effector(self) -> RigidPrim: """[summary] Returns: RigidPrim: [description] """ return self._end_effector def initialize(self, physics_sim_view=None) -> None: """[summary] """ super().initialize(physics_sim_view) self._end_effector = RigidPrim(prim_path=self._end_effector_prim_path, name=self.name + "_end_effector") self.disable_gravity() self._end_effector.initialize(physics_sim_view) return def post_reset(self) -> None: """[summary] """ Robot.post_reset(self) self._end_effector.post_reset() return
2,275
Python
30.178082
116
0.593846
MatthewDZane/XArmFollowTarget/scripts/XArm/README.md
# Using XArm Follow Target as an Isaac Example 1. cd into the Isaac Sim User examples directory. ``` /home/user/.local/share/ov/pkg/isaac_sim-2022.2.1/exts/omni.isaac.examples/omni/isaac/examples/user_examples/ ``` 2. Clone the repo as XArmFollowTarget. ``` git clone https://gitlab.nrp-nautilus.io/isaac/xarm.git XArmFollowTarget ``` 3. Add the following lines to the .../user_examples/__init__.py file (not in the repo directory): ``` from omni.isaac.examples.user_examples.XArmFollowTarget.scripts.XArm.xarm_sample import XArmSample from omni.isaac.examples.user_examples.XArmFollowTarget.scripts.XArm.xarm_extension import XArmExtension ``` 4. After this runs you should see the XArm extension in the Example drop down in the Isaac-sim gui 5. To recieve the position output run the **client.py** script found in the folder, the **server.py** runs by default once the example is loaded.
896
Markdown
41.714284
146
0.767857
MatthewDZane/XArmFollowTarget/scripts/XArm/xarm_extension.py
import asyncio import os import omni import omni.ui as ui from omni.usd import StageEventType from omni.isaac.core import World from omni.isaac.examples.base_sample import BaseSampleExtension from omni.isaac.ui.ui_utils import btn_builder, get_style, state_btn_builder, setup_ui_headers, cb_builder, float_builder from .xarm_sample import XArmSample class XArmExtension(BaseSampleExtension): def on_startup(self, ext_id: str): self._buttons = {} self._task_ui_elements = {} super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="XArm", title="XArm", doc_link="", overview="", sample=XArmSample(), file_path=os.path.abspath(__file__), number_of_extra_frames=0, ) return def shutdown_cleanup(self): if self._sample._world is not None: self._sample._world_cleanup() if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load XArm5"].enabled = True self._buttons["Load XArm7"].enabled = True return def _build_ui( self, name, title, doc_link, overview, file_path, number_of_extra_frames, window_width, keep_window_open ): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ self._window = omni.ui.Window( name, width=window_width, height=0, visible=keep_window_open, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): setup_ui_headers(self._ext_id, file_path, title, doc_link, overview) self._controls_frame = ui.CollapsableFrame( title="World Controls", width=ui.Fraction(1), height=0, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with self._controls_frame: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Load XArm5", "type": "button", "text": "Load", "tooltip": "Load XArm5 and Task", "on_clicked_fn": self._on_load_xarm5, } self._buttons["Load XArm5"] = btn_builder(**dict) self._buttons["Load XArm5"].enabled = True dict = { "label": "Load XArm7", "type": "button", "text": "Load", "tooltip": "Load XArm7 and Task", "on_clicked_fn": self._on_load_xarm7, } self._buttons["Load XArm7"] = btn_builder(**dict) self._buttons["Load XArm7"].enabled = True dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = False task_controls_frame = ui.CollapsableFrame( title="Task Controls", collapsed=False ) with task_controls_frame: with ui.VStack(spacing=5): task_controls_frame.visible = True dict = { "label": "Follow Target", "type": "button", "a_text": "START", "b_text": "STOP", "tooltip": "Follow Target", "on_clicked_fn": self._on_follow_target_button_event, } self._task_ui_elements["Follow Target"] = state_btn_builder(**dict) self._task_ui_elements["Follow Target"].enabled = False dict = { "label": "Add Obstacle", "type": "button", "text": "ADD", "tooltip": "Add Obstacle", "on_clicked_fn": self._on_add_obstacle_button_event, } self._task_ui_elements["Add Obstacle"] = btn_builder(**dict) self._task_ui_elements["Add Obstacle"].enabled = False dict = { "label": "Remove Obstacle", "type": "button", "text": "REMOVE", "tooltip": "Remove Obstacle", "on_clicked_fn": self._on_remove_obstacle_button_event, } self._task_ui_elements["Remove Obstacle"] = btn_builder(**dict) self._task_ui_elements["Remove Obstacle"].enabled = False dict = { "label": "Random Target Enabled", "type": "checkbox", "default_val": False, "tooltip": "Random Target Enabled", "on_clicked_fn": self._on_random_target_enabled_event } self._task_ui_elements["Random Target Checkbox"] = cb_builder(**dict) args = { "label": "Min Face Range", "default_val": .3, "tooltip": "Min Range in Meters", } self._task_ui_elements["Min Face Range"] = float_builder(**args) self._task_ui_elements["Min Face Range"].add_value_changed_fn(self._on_min_face_range_changed_event) args = { "label": "Max Face Range", "default_val": 10, "tooltip": "Max Range in Meters", } self._task_ui_elements["Max Face Range"] = float_builder(**args) self._task_ui_elements["Max Face Range"].add_value_changed_fn(self._on_max_face_range_changed_event) def _on_load_xarm5(self): self._sample.set_xarm_version(5) self._on_random_target_enabled_event(False) self._on_min_face_range_changed_event(self._task_ui_elements["Min Face Range"].get_value_as_float()) self._on_max_face_range_changed_event(self._task_ui_elements["Max Face Range"].get_value_as_float()) async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load XArm5"].enabled = False self._buttons["Load XArm7"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_load_xarm7(self): self._sample.set_xarm_version(7) self._on_random_target_enabled_event(False) self._on_min_face_range_changed_event(self._task_ui_elements["Min Face Range"].get_value_as_float()) self._on_max_face_range_changed_event(self._task_ui_elements["Max Face Range"].get_value_as_float()) async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load XArm5"].enabled = False self._buttons["Load XArm7"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_reset(self): async def _on_reset_async(): await self._sample.reset_async() await omni.kit.app.get_app().next_update_async() self.post_reset_button_event() asyncio.ensure_future(_on_reset_async()) return def _on_follow_target_button_event(self, val): asyncio.ensure_future(self._sample._on_follow_target_event_async(val)) return def _on_add_obstacle_button_event(self): self._sample._on_add_obstacle_event() self._task_ui_elements["Remove Obstacle"].enabled = True return def _on_remove_obstacle_button_event(self): self._sample._on_remove_obstacle_event() world = self._sample.get_world() current_task = list(world.get_current_tasks().values())[0] if not current_task.obstacles_exist(): self._task_ui_elements["Remove Obstacle"].enabled = False return def _on_random_target_enabled_event(self, val): self._sample.rand_target_enabled = self._task_ui_elements["Random Target Checkbox"].get_value_as_bool() def _on_min_face_range_changed_event(self, val): self._sample.min_detection_range = self._task_ui_elements["Min Face Range"].get_value_as_float() def _on_max_face_range_changed_event(self, val): self._sample.min_detection_range = self._task_ui_elements["Max Face Range"].get_value_as_float() def _enable_all_buttons(self, flag): for btn_name, btn in self._buttons.items(): if isinstance(btn, omni.ui._ui.Button): btn.enabled = flag return def _on_follow_target_button_event(self, val): asyncio.ensure_future(self._sample._on_follow_target_event_async(val)) return def _on_save_data_button_event(self): self._sample._on_save_data_event(self._task_ui_elements["Output Directory"].get_value_as_string()) return def post_reset_button_event(self): self._task_ui_elements["Follow Target"].enabled = True self._task_ui_elements["Remove Obstacle"].enabled = False self._task_ui_elements["Add Obstacle"].enabled = True if self._task_ui_elements["Follow Target"].text == "STOP": self._task_ui_elements["Follow Target"].text = "START" return def post_load_button_event(self): self._task_ui_elements["Follow Target"].enabled = True self._task_ui_elements["Add Obstacle"].enabled = True return def post_clear_button_event(self): self._task_ui_elements["Follow Target"].enabled = False self._task_ui_elements["Remove Obstacle"].enabled = False self._task_ui_elements["Add Obstacle"].enabled = False if self._task_ui_elements["Follow Target"].text == "STOP": self._task_ui_elements["Follow Target"].text = "START" return def on_stage_event(self, event): if event.type == int(StageEventType.OPENED): # If the user opens a new stage, the extension should completely reset self._task_ui_elements["Follow Target"].enabled = False self._task_ui_elements["Remove Obstacle"].enabled = False self._task_ui_elements["Add Obstacle"].enabled = False if self._task_ui_elements["Follow Target"].text == "STOP": self._task_ui_elements["Follow Target"].text = "START" elif event.type == int(omni.usd.StageEventType.CLOSED): if World.instance() is not None: self._sample._world_cleanup() self._sample._world.clear_instance() if hasattr(self, "_buttons"): if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load XArm5"].enabled = True self._buttons["Load XArm7"].enabled = True return def _reset_on_stop_event(self, e): if e.type == int(omni.timeline.TimelineEventType.STOP): #self._buttons["Load XArm5"].enabled = False #self._buttons["Load XArm7"].enabled = False self._buttons["Reset"].enabled = True self.post_clear_button_event() return
13,233
Python
44.013605
124
0.516058
MatthewDZane/XArmFollowTarget/scripts/XArm/client/Test_ContainerServer.py
# server.py import socket HOST = "localhost" PORT = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) while True: conn, addr = s.accept() with conn: data = conn.recv(1024) if not data: break print("Received:", data) conn.sendall(data)
332
Python
17.499999
53
0.596386
MatthewDZane/XArmFollowTarget/scripts/XArm/client/Cont_clientTest.py
# server.py import socket HOST = "localhost" PORT = 8211 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) while True: conn, addr = s.accept() with conn: data = conn.recv(1024) if not data: break print("Received:", data) conn.sendall(data) # client.py import socket HOST = "localhost" PORT = 50000 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.sendall("Hello, world!".encode()) data = s.recv(1024) print("Received:", data.decode()) s.close()
573
Python
15.882352
53
0.631763
MatthewDZane/XArmFollowTarget/scripts/XArm/client/local-xarm-client.py
import socket import math import time mysocket = socket.socket() # mysocket.connect(('127.0.0.1',12345)) mysocket.connect(('192.168.4.206',12345)) """ # xArm-Python-SDK: https://github.com/xArm-Developer/xArm-Python-SDK # git clone [email protected]:xArm-Developer/xArm-Python-SDK.git # cd xArm-Python-SDK # python setup.py install """ try: from xarm.tools import utils except: pass from xarm import version from xarm.wrapper import XArmAPI arm = XArmAPI('192.168.4.15') arm.motion_enable(enable=True) arm.set_mode(0) arm.set_state(state=0) # arm.reset(wait=True) arm.set_mode(1) arm.set_state(0) time.sleep(0.1) variables = {} params = {'speed': 100, 'acc': 2000, 'angle_speed': 20, 'angle_acc': 500, 'events': {}, 'variables': variables, 'callback_in_thread': True, 'quit': False} # Register error/warn changed callback def error_warn_change_callback(data):# if data and data['error_code'] != 0: params['quit'] = True pprint('err={}, quit'.format(data['error_code'])) arm.release_error_warn_changed_callback(error_warn_change_callback) arm.register_error_warn_changed_callback(error_warn_change_callback) # Register state changed callback def state_changed_callback(data): if data and data['state'] == 4: if arm.version_number[0] >= 1 and arm.version_number[1] >= 1 and arm.version_number[2] > 0: params['quit'] = True pprint('state=4, quit') arm.release_state_changed_callback(state_changed_callback) arm.register_state_changed_callback(state_changed_callback) # Register counter value changed callback if hasattr(arm, 'register_count_changed_callback'): def count_changed_callback(data): if not params['quit']: pprint('counter val: {}'.format(data['count'])) arm.register_count_changed_callback(count_changed_callback) # Register connect changed callback def connect_changed_callback(data): if data and not data['connected']: params['quit'] = True pprint('disconnect, connected={}, reported={}, quit'.format(data['connected'], data['reported'])) arm.release_connect_changed_callback(error_warn_change_callback) arm.register_connect_changed_callback(connect_changed_callback) def close_socket(thissocket): try: thissocket.shutdown(socket.SHUT_RDWR) thissocket.close() thissocket = None except socket.error as e: pass print("socket is closed") try: while True: data = mysocket.recv(1024) message = data.decode() if message == "Done": break # print(message) try: joints = eval(message) except: continue # print(joints) joints_deg = [math.degrees(joint) for joint in joints] if arm.connected and arm.state != 4: arm.set_servo_angle_j(joints, is_radian=True) # print("moved to", joints_deg) except KeyboardInterrupt: print("closing socket...") close_socket(mysocket) print("Isaac Sim Connection Stopped") if hasattr(arm, 'release_count_changed_callback'): arm.release_count_changed_callback(count_changed_callback) arm.release_error_warn_changed_callback(state_changed_callback) arm.release_state_changed_callback(state_changed_callback) arm.release_connect_changed_callback(error_warn_change_callback)
3,384
Python
28.692982
154
0.668735
MatthewDZane/XArmFollowTarget/scripts/XArm/client/go-home.py
#!/usr/bin/env python3 # Software License Agreement (BSD License) # # Copyright (c) 2022, UFACTORY, Inc. # All rights reserved. # # Author: Vinman <[email protected]> <[email protected]> """ # Notice # 1. Changes to this file on Studio will not be preserved # 2. The next conversion will overwrite the file with the same name """ import sys import math import time import datetime import random import traceback import threading """ # xArm-Python-SDK: https://github.com/xArm-Developer/xArm-Python-SDK # git clone [email protected]:xArm-Developer/xArm-Python-SDK.git # cd xArm-Python-SDK # python setup.py install """ try: from xarm.tools import utils except: pass from xarm import version from xarm.wrapper import XArmAPI def pprint(*args, **kwargs): try: stack_tuple = traceback.extract_stack(limit=2)[0] print('[{}][{}] {}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), stack_tuple[1], ' '.join(map(str, args)))) except: print(*args, **kwargs) pprint('xArm-Python-SDK Version:{}'.format(version.__version__)) arm = XArmAPI('192.168.4.15') arm.clean_warn() arm.clean_error() arm.motion_enable(True) arm.set_mode(0) arm.set_state(0) time.sleep(1) variables = {} params = {'speed': 100, 'acc': 2000, 'angle_speed': 20, 'angle_acc': 500, 'events': {}, 'variables': variables, 'callback_in_thread': True, 'quit': False} # Register error/warn changed callback def error_warn_change_callback(data): if data and data['error_code'] != 0: params['quit'] = True pprint('err={}, quit'.format(data['error_code'])) arm.release_error_warn_changed_callback(error_warn_change_callback) arm.register_error_warn_changed_callback(error_warn_change_callback) # Register state changed callback def state_changed_callback(data): if data and data['state'] == 4: if arm.version_number[0] >= 1 and arm.version_number[1] >= 1 and arm.version_number[2] > 0: params['quit'] = True pprint('state=4, quit') arm.release_state_changed_callback(state_changed_callback) arm.register_state_changed_callback(state_changed_callback) # Register counter value changed callback if hasattr(arm, 'register_count_changed_callback'): def count_changed_callback(data): if not params['quit']: pprint('counter val: {}'.format(data['count'])) arm.register_count_changed_callback(count_changed_callback) # Register connect changed callback def connect_changed_callback(data): if data and not data['connected']: params['quit'] = True pprint('disconnect, connected={}, reported={}, quit'.format(data['connected'], data['reported'])) arm.release_connect_changed_callback(error_warn_change_callback) arm.register_connect_changed_callback(connect_changed_callback) # Rotation if not params['quit']: params['angle_acc'] = 1145 if not params['quit']: params['angle_speed'] = 80 # if params['quit']: if arm.error_code == 0 and not params['quit']: code = arm.set_servo_angle(angle=[0.0, 0, 0.0, 0.0, 0.0, 0.0, 0.0], speed=params['angle_speed'], mvacc=params['angle_acc'], wait=True, radius=-1.0) if code != 0: params['quit'] = True pprint('set_servo_angle, code={}'.format(code)) # release all event if hasattr(arm, 'release_count_changed_callback'): arm.release_count_changed_callback(count_changed_callback) arm.release_error_warn_changed_callback(state_changed_callback) arm.release_state_changed_callback(state_changed_callback) arm.release_connect_changed_callback(error_warn_change_callback)
3,630
Python
32.009091
155
0.680716
MatthewDZane/XArmFollowTarget/scripts/XArm/client/realsense_facePoseClient.py
# ====== Sample Code for Smart Design Technology Blog ====== # Intel Realsense D435 cam has RGB camera with 1920×1080 resolution # Depth camera is 1280x720 # FOV is limited to 69deg x 42deg (H x V) - the RGB camera FOV # If you run this on a non-Intel CPU, explore other options for rs.align # On the NVIDIA Jetson AGX we build the pyrealsense lib with CUDA import pyrealsense2 as rs import mediapipe as mp import cv2 import numpy as np import datetime as dt import socket import sys from itertools import combinations font = cv2.FONT_HERSHEY_SIMPLEX org = (20, 100) fontScale = .5 color = (0,50,255) thickness = 1 # ====== Realsense ====== realsense_ctx = rs.context() connected_devices = [] # List of serial numbers for present cameras for i in range(len(realsense_ctx.devices)): detected_camera = realsense_ctx.devices[i].get_info(rs.camera_info.serial_number) print(f"{detected_camera}") connected_devices.append(detected_camera) device = connected_devices[0] # In this example we are only using one camera pipeline = rs.pipeline() config = rs.config() background_removed_color = 153 # Grey # ====== Mediapipe ====== mp_face_mesh = mp.solutions.face_mesh face_mesh = mp_face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5) mp_drawing = mp.solutions.drawing_utils drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1) # ====== Socket ====== bSocket = True if (len(sys.argv) > 1): print(sys.argv) if sys.argv[1] == "--no-socket": bSocket = False if bSocket: # open socket to omniverse machine mysocket = socket.socket() # mysocket.connect(('192.168.1.62',12346)) mysocket.connect(('192.168.4.206',12346)) # mysocket.connect(('127.0.0.1',12346)) def close_socket(thissocket): try: thissocket.shutdown(socket.SHUT_RDWR) thissocket.close() thissocket = None except socket.error as e: pass print("socket is closed") def get_pixel_depth(depth_image_flipped, pixel_coodinate, img_w, img_h): #calculate distance to end of the nose x_pixel = pixel_coodinate[0] y_pixel = pixel_coodinate[1] if x_pixel >= img_w: x_pixel = img_w - 1 if y_pixel >= img_h: y_pixel = img_h - 1 return depth_image_flipped[y_pixel, x_pixel] * depth_scale def get_camera_to_pixel_vector(pixel_coodinate, inv_cam_matrix, distance_from_camera): homogeneous_nose_coordinates = np.array([ [pixel_coodinate[0]], [pixel_coodinate[1]], [1] ]) homogeneous_nose_coordinates = homogeneous_nose_coordinates / np.linalg.norm(homogeneous_nose_coordinates) cam_to_pixel = inv_cam_matrix @ homogeneous_nose_coordinates # Normalize the input vectors cam_to_pixel = cam_to_pixel / np.linalg.norm(cam_to_pixel) #print(vector_to_nose.flatten()) return cam_to_pixel * distance_from_camera def estimate_plane_normal(points): planes = list(combinations(points, 3)) #print(points) normals = [] for points in planes: a = points[1] - points[0] b = points[2] - points[0] #print (a,b) normal = np.cross(a, b) if normal[2] > 0: normal = -1 * normal normals.append(normal) plane_normal = np.mean(normals, axis=0) plane_normal = plane_normal / np.linalg.norm(plane_normal) return plane_normal # ====== Enable Streams ====== config.enable_device(device) # # For worse FPS, but better resolution: # stream_res_x = 1280 # stream_res_y = 720 # # For better FPS. but worse resolution: stream_res_x = 640 stream_res_y = 480 stream_fps = 30 config.enable_stream(rs.stream.depth, stream_res_x, stream_res_y, rs.format.z16, stream_fps) config.enable_stream(rs.stream.color, stream_res_x, stream_res_y, rs.format.bgr8, stream_fps) profile = pipeline.start(config) align_to = rs.stream.color align = rs.align(align_to) # ====== Get depth Scale ====== depth_sensor = profile.get_device().first_depth_sensor() depth_scale = depth_sensor.get_depth_scale() print(f"\tDepth Scale for Camera SN {device} is: {depth_scale}") # ====== Set clipping distance ====== clipping_distance_in_meters = 2 clipping_distance = clipping_distance_in_meters / depth_scale print(f"\tConfiguration Successful for SN {device}") # ====== Get and process images ====== print(f"Starting to capture images on SN: {device}") while True: start_time = dt.datetime.today().timestamp() # Get and align frames frames = pipeline.wait_for_frames() aligned_frames = align.process(frames) aligned_depth_frame = aligned_frames.get_depth_frame() color_frame = aligned_frames.get_color_frame() if not aligned_depth_frame or not color_frame: continue # Process images depth_image = np.asanyarray(aligned_depth_frame.get_data()) depth_image_flipped = cv2.flip(depth_image,1) color_image = np.asanyarray(color_frame.get_data()) depth_image_3d = np.dstack((depth_image,depth_image,depth_image)) #Depth image is 1 channel, while color image is 3 background_removed = np.where((depth_image_3d > clipping_distance) | (depth_image_3d <= 0), background_removed_color, color_image) depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.03), cv2.COLORMAP_JET) images = cv2.flip(background_removed,1) # images = background_removed color_image = cv2.flip(color_image,1) color_images_rgb = cv2.cvtColor(color_image, cv2.COLOR_BGR2RGB) #added from face-pose client img_h, img_w, img_c = color_images_rgb.shape # calculate intrinsic values focal_length = 1 * img_w intrinsics = aligned_frames.get_profile().as_video_stream_profile().get_intrinsics() cam_matrix = np.array( [ [intrinsics.fx, 0, img_w/2], [0, intrinsics.fy, img_h/2], [0, 0, 1] ]) inv_cam_matrix = np.linalg.inv(cam_matrix) # the distortion paramaters dist_matrix = np.zeros((4, 1), dtype=np.float64) face_3d = [] face_2d = [] # Process face results = face_mesh.process(color_images_rgb) if results.multi_face_landmarks: i=0 for face_landmarks in results.multi_face_landmarks: for idx, lm in enumerate(face_landmarks.landmark): if idx in [1, 33, 61, 199, 263, 291]: x, y = int(lm.x * img_w), int(lm.y * img_h) cv2.circle(color_images_rgb, (x, y), 10, (0, 0, 255), -1) face_2d.append([x, y]) landmark_distance = get_pixel_depth( depth_image_flipped, [x, y], img_w, img_h ) cam_to_landmark = get_camera_to_pixel_vector( [x, y], inv_cam_matrix, landmark_distance ) face_3d.append(cam_to_landmark.flatten()) if idx == 1: nose_pixel = (x, y) cam_to_nose = cam_to_landmark nose_distance = landmark_distance face_2d = np.array(face_2d, dtype=np.float64) face_3d = np.array(face_3d, dtype=np.float64) nose_landmark = face_landmarks.landmark[1] # solve PnP success, rot_vec, trans_vec = cv2.solvePnP(face_3d, face_2d, cam_matrix, dist_matrix) # get rotatinal matrix rmat, jac = cv2.Rodrigues(rot_vec) # get angles angles, mtxR, mtxQ, Qx, Qy, Qz = cv2.RQDecomp3x3(rmat) # get the y rotation degree x_degrees = angles[0] * 360 y_degrees = angles[1] * 360 z_degrees = angles[2] * 360 # see where the user's head is tilting if y < -10: text = "Looking Left" elif y > 10: text = "Looking Right" elif x < -10: text = "Looking Down" elif x > 10: text = "Looking Up" else: text = "Looking Forward" # display the nose direction p2 = (int(nose_pixel[0] + y_degrees * 10), int(nose_pixel[1] - x_degrees * 10)) cv2.line(color_images_rgb, (int(nose_pixel[0]), int(nose_pixel[1])), p2, (255, 0, 0), 3) # cv2.line(images, (int(nose_pixel[0]), int(nose_pixel[1])), p2, (255, 0, 0), 3) face_direction = estimate_plane_normal(face_3d) print(nose_distance, end="\t") ##vector of Nose in camera local space print(cam_to_nose.flatten(), end="\t") ##Normal of the face in camera local space print(face_direction.flatten(), end="\t") print(nose_pixel) # add the text on the image cv2.putText(color_images_rgb, text, (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) cv2.putText(color_images_rgb, "x: "+str(np.round(x_degrees, 2)), (500, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) cv2.putText(color_images_rgb, "y: "+str(np.round(y_degrees, 2)), (500, 100), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) cv2.putText(color_images_rgb, "z: "+str(np.round(z_degrees, 2)), (500, 150), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) cv2.putText(color_images_rgb, "Distance: "+ str(np.round(nose_distance, 2)), (500, 200), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) xdiff = 0.5-nose_landmark.x ydiff = 0.5-nose_landmark.y cv2.putText(color_images_rgb, "xdiff: "+str(np.round(xdiff, 2)), (500, 250), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) images = cv2.putText(color_images_rgb, "ydiff: "+str(np.round(ydiff, 2)), (500, 300), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) # mp_drawing.draw_landmarks( # image=color_images_rgb, # landmark_list=face_landmarks, # connections=mp_face_mesh.FACEMESH_CONTOURS, # landmark_drawing_spec = drawing_spec, # connection_drawing_spec=drawing_spec) if bSocket: cam_to_nose = cam_to_nose.flatten() try: #print("sending:", [cam_to_nose[0], cam_to_nose[1], cam_to_nose[2], face_direction[0], face_direction[1], face_direction[2], xdiff, ydiff]) sendData = str([ cam_to_nose[0], cam_to_nose[1], cam_to_nose[2], face_direction[0], face_direction[1], face_direction[2], xdiff, ydiff] ) mysocket.send(sendData.encode()) except: pass # Display FPS time_diff = dt.datetime.today().timestamp() - start_time fps = int(1 / time_diff) org3 = (20, org[1] + 60) images = cv2.putText(images, f"FPS: {fps}", org3, font, fontScale, color, thickness, cv2.LINE_AA) name_of_window = 'SN: ' + str(device) # Display images cv2.namedWindow(name_of_window, cv2.WINDOW_AUTOSIZE) output_bgr = cv2.cvtColor(color_images_rgb, cv2.COLOR_RGB2BGR) cv2.imshow(name_of_window, output_bgr) # cv2.imshow(name_of_window, images) # cv2.imshow(name_of_window, color_image) key = cv2.waitKey(1) # Press esc or 'q' to close the image window if key & 0xFF == ord('q') or key == 27: print(f"User pressed break key for SN: {device}") break print(f"Application Closing") pipeline.stop() print(f"Application Closed.")
11,623
Python
33.906907
155
0.593564
MatthewDZane/XArmFollowTarget/scripts/XArm/client/look-forward.py
#!/usr/bin/env python3 # Software License Agreement (BSD License) # # Copyright (c) 2022, UFACTORY, Inc. # All rights reserved. # # Author: Vinman <[email protected]> <[email protected]> """ # Notice # 1. Changes to this file on Studio will not be preserved # 2. The next conversion will overwrite the file with the same name """ import sys import math import time import datetime import random import traceback import threading # IKFast for xarm 7 import pyikfast import numpy as np """ # xArm-Python-SDK: https://github.com/xArm-Developer/xArm-Python-SDK # git clone [email protected]:xArm-Developer/xArm-Python-SDK.git # cd xArm-Python-SDK # python setup.py install """ try: from xarm.tools import utils except: pass from xarm import version from xarm.wrapper import XArmAPI def pprint(*args, **kwargs): try: stack_tuple = traceback.extract_stack(limit=2)[0] print('[{}][{}] {}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), stack_tuple[1], ' '.join(map(str, args)))) except: print(*args, **kwargs) frontForwardAngle = [0, 2.5, 0, 37.3, 0, -57.3, 0] frontBackAngle = [0.0,-45.0,0.0,0.0,0.0,-45.0,0.0] pprint('xArm-Python-SDK Version:{}'.format(version.__version__)) arm = XArmAPI('192.168.4.15') arm.clean_warn() arm.clean_error() arm.motion_enable(True) arm.set_mode(0) arm.set_state(0) time.sleep(1) variables = {} params = {'speed': 50, 'acc': 2000, 'angle_speed': 20, 'angle_acc': 500, 'events': {}, 'variables': variables, 'callback_in_thread': True, 'quit': False} params['angle_acc'] = 50 params['angle_speed'] = 1000 # Register error/warn changed callback def error_warn_change_callback(data): if data and data['error_code'] != 0: params['quit'] = True pprint('err={}, quit'.format(data['error_code'])) arm.release_error_warn_changed_callback(error_warn_change_callback) arm.register_error_warn_changed_callback(error_warn_change_callback) # Register state changed callback def state_changed_callback(data): if data and data['state'] == 4: if arm.version_number[0] >= 1 and arm.version_number[1] >= 1 and arm.version_number[2] > 0: params['quit'] = True pprint('state=4, quit') arm.release_state_changed_callback(state_changed_callback) arm.register_state_changed_callback(state_changed_callback) # Register counter value changed callback if hasattr(arm, 'register_count_changed_callback'): def count_changed_callback(data): if not params['quit']: pprint('counter val: {}'.format(data['count'])) arm.register_count_changed_callback(count_changed_callback) # Register connect changed callback def connect_changed_callback(data): if data and not data['connected']: params['quit'] = True pprint('disconnect, connected={}, reported={}, quit'.format(data['connected'], data['reported'])) arm.release_connect_changed_callback(error_warn_change_callback) arm.register_connect_changed_callback(connect_changed_callback) # Rotation if not params['quit']: # params['angle_acc'] = 1145 # params['angle_speed'] = 80 # if params['quit']: if arm.error_code == 0 and not params['quit']: # code = arm.set_servo_angle(angle=[0.1, -34.9, -0.1, 1.6, 0, -63.5, 0.1], speed=params['angle_speed'], mvacc=params['angle_acc'], wait=True, radius=-1.0) code = arm.set_servo_angle(angle=frontForwardAngle, speed=params['angle_speed'], mvacc=params['angle_acc'], wait=True, radius=-1.0) if code != 0: params['quit'] = True pprint('set_servo_angle, code={}'.format(code)) # look forward but retracted code = arm.set_servo_angle(angle=frontBackAngle, peed=params['angle_speed'], mvacc=params['angle_acc'], wait=True, radius=-1.0) # print(arm.get_position(), arm.get_position(is_radian=True)) # angles = list(np.radians(frontForwardAngle)) # angles = list(np.radians(frontBackAngle)) # print("start (joints): ", angles) # translate, rotate = pyikfast.forward(angles) # print("start pos (translate, rotate): ", translate, rotate, "\n") # translate = [0.400, 0.0, 0.400] # results = pyikfast.inverse(translate, rotate) # for result in results: # theseangles = list(result) # print("final angles (IK joints): ", theseangles) # finalangles = list(np.degrees(results[3])) # arm.set_servo_angle(angle=finalangles, speed=params['angle_speed'], mvacc=params['angle_acc'], wait=True, radius=-1.0) # translate, rotate = pyikfast.forward(angles) # print("final FK (translate, rotate): ", translate, rotate, "\n") # frontBackAngle = [0.0,-45.0,0.0,0.0,0.0,-45.0,0.0] # angles = np.radians(frontBackAngle) # print("start (joints): ", angles) # translate, rotate = pyikfast.forward(list(angles)) # print("FK (translate, rotate): ", translate, rotate, "\n") # joints = pyikfast.inverse(translate, rotate) # look down # code = arm.set_servo_angle(angle=[0.0, 0, 0.0, 0.0, 0.0, 0.0, 0.0], speed=params['angle_speed'], mvacc=params['angle_acc'], wait=True, radius=-1.0) # relative moves # arm.set_position(pitch=-88.0, relative=False, wait=True) # arm.set_position(pitch=-10.0, relative=True, wait=True) # print(arm.get_position(), arm.get_position(is_radian=True)) # arm.set_position(pitch=-10.0, relative=True, wait=True) # testing face tracking # arm.set_tool_position(pitch=10.0, wait=True) # arm.set_tool_position(pitch=-20.0, wait=True) # arm.set_tool_position(pitch=10.0, wait=True) # arm.set_servo_angle(servo_id=1, angle=3, relative=True, is_radian=False, wait=True) # arm.set_servo_angle(servo_id=1, angle=-6, relative=True, is_radian=False, wait=True) # arm.set_servo_angle(servo_id=1, angle=3, relative=True, is_radian=False, wait=True) # arm.set_position(pitch=-20.0, relative=True, wait=True) # print(arm.get_position(), arm.get_position(is_radian=True)) # arm.set_position(pitch=-10.0, relative=True, wait=True) # print(arm.get_position(), arm.get_position(is_radian=True)) # arm.set_position(roll=-10.0, relative=True, wait=True) # print(arm.get_position(), arm.get_position(is_radian=True)) # arm.set_position(roll=20.0, relative=True, wait=True) # print(arm.get_position(), arm.get_position(is_radian=True)) # arm.set_position(roll=-10, relative=True, wait=True) # print(arm.get_position(), arm.get_position(is_radian=True)) # back to forward # arm.set_servo_angle(angle=[0.0, -45.0, 0.0, 0.0, 0.0, -45.0, 0.0], speed=params['angle_speed'], mvacc=params['angle_acc'], wait=True, radius=-1.0) # release all event if hasattr(arm, 'release_count_changed_callback'): arm.release_count_changed_callback(count_changed_callback) arm.release_error_warn_changed_callback(state_changed_callback) arm.release_state_changed_callback(state_changed_callback) arm.release_connect_changed_callback(error_warn_change_callback)
6,835
Python
32.674877
162
0.685296
MatthewDZane/XArmFollowTarget/scripts/XArm/client/face-pose-client.py
# from this video: # https://www.youtube.com/watch?v=-toNMaS4SeQ import cv2 import mediapipe as mp import numpy as np import time import socket import sys bSocket = True if (len(sys.argv) > 1): print(sys.argv) if sys.argv[1] == "--no-socket": bSocket = False if bSocket: # open socket to omniverse machine mysocket = socket.socket() mysocket.connect(('192.168.4.206',12346)) # robert's local machine # mysocket.connect(('192.168.1.62',12346)) # mysocket.connect(('127.0.0.1',12346)) def close_socket(thissocket): try: thissocket.shutdown(socket.SHUT_RDWR) thissocket.close() thissocket = None except socket.error as e: pass print("socket is closed") mp_face_mesh = mp.solutions.face_mesh face_mesh = mp_face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5) mp_drawing = mp.solutions.drawing_utils drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1) # cap = cv2.VideoCapture(0) cap = cv2.VideoCapture(1) try: while cap.isOpened(): success, image = cap.read() start = time.time() image = cv2.cvtColor(cv2.flip(image, -1), cv2.COLOR_BGR2RGB) # image = cv2.cvtColor(cv2.flip(image, -2), cv2.COLOR_BGR2RGB) # improve performance image.flags.writeable = False # get the results results = face_mesh.process(image) # improve performance image.flags.writeable = True # convert colorspace image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) img_h, img_w, img_c = image.shape face_3d = [] face_2d = [] nose_norm = [] if results.multi_face_landmarks: for face_landmarks in results.multi_face_landmarks: for idx, lm in enumerate(face_landmarks.landmark): if idx == 33 or idx == 263 or idx == 1 or idx == 61 or idx == 291 or idx == 199: if idx == 1: nose_2d = (lm.x * img_w, lm.y * img_h) nose_norm = (lm.x, lm.y) nose_3d = (lm.x * img_w, lm.y * img_h, lm.z * 3000) x, y = int(lm.x * img_w), int(lm.y * img_h) cv2.circle(image, (x, y), 10, (0, 0, 255), -1) face_2d.append([x, y]) face_3d.append([x, y, lm.z]) # convert to numpy array face_2d = np.array(face_2d, dtype=np.float64) # convert to np array face_3d = np.array(face_3d, dtype=np.float64) # the camera matrix focal length focal_length = 1 * img_w cam_matrix = np.array( [ [focal_length, 0, img_h/2], [0, focal_length, img_w/2], [0, 0, 1] ]) # the distortion paramaters dist_matrix = np.zeros((4, 1), dtype=np.float64) # solve PnP success, rot_vec, trans_vec = cv2.solvePnP(face_3d, face_2d, cam_matrix, dist_matrix) # get rotatinal matrix rmat, jac = cv2.Rodrigues(rot_vec) # get angles angles, mtxR, mtxQ, Qx, Qy, Qz = cv2.RQDecomp3x3(rmat) # get the y rotation degree x = angles[0] * 360 y = angles[1] * 360 z = angles[2] * 360 # see where the user's head is tilting if y < -10: text = "Looking Left" elif y > 10: text = "Looking Right" elif x < -10: text = "Looking Down" elif x > 10: text = "Looking Up" else: text = "Looking Forward" # display the nose direction nose_3d_projection, jacobian = cv2.projectPoints(nose_3d, rot_vec, trans_vec, cam_matrix, dist_matrix) p1 = (int(nose_2d[0]), int(nose_2d[1])) p2 = (int(nose_2d[0] + y * 10), int(nose_2d[1] - x * 10)) cv2.line(image, p1, p2, (255, 0, 0), 3) # add the text on the image cv2.putText(image, text, (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) cv2.putText(image, "x: "+str(np.round(x, 2)), (500, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) cv2.putText(image, "y: "+str(np.round(y, 2)), (500, 100), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) cv2.putText(image, "z: "+str(np.round(z, 2)), (500, 150), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) xdiff = 0.5-nose_norm[0] ydiff = 0.5-nose_norm[1] cv2.putText(image, "xdiff: "+str(np.round(xdiff, 2)), (500, 250), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) cv2.putText(image, "ydiff: "+str(np.round(ydiff, 2)), (500, 300), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) end = time.time() totalTime = end-start fps = 1/totalTime # print("FPS: ", fps) cv2.putText(image, f'FPS: {int(fps)}', (20, 450), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2) mp_drawing.draw_landmarks( image=image, landmark_list=face_landmarks, connections=mp_face_mesh.FACEMESH_CONTOURS, landmark_drawing_spec = drawing_spec, connection_drawing_spec=drawing_spec) if bSocket: try: print("sending:", [x, y, z, xdiff, ydiff]) sendData = str([x, y, z, xdiff, ydiff]) mysocket.send(sendData.encode()) except: pass cv2.imshow('Head Pose Estimation', image) if cv2.waitKey(5) & 0xFF == 27: break except KeyboardInterrupt: print("quitting") if bSocket: close_socket(mysocket) cap.release()
4,957
Python
24.958115
114
0.616905
MatthewDZane/XArmFollowTarget/scripts/XArm/XArm/XArm7/xarm7_rmpflow_common.yaml
# Copyright (c) 2019-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. joint_limit_buffers: [.01, .03, .01, .01, .01, .01, .01] rmp_params: cspace_target_rmp: metric_scalar: 50. position_gain: 100. damping_gain: 50. robust_position_term_thresh: .5 inertia: 1. cspace_trajectory_rmp: p_gain: 100. d_gain: 10. ff_gain: .25 weight: 50. cspace_affine_rmp: final_handover_time_std_dev: .25 weight: 2000. joint_limit_rmp: metric_scalar: 1000. metric_length_scale: .01 metric_exploder_eps: 1e-3 metric_velocity_gate_length_scale: .01 accel_damper_gain: 200. accel_potential_gain: 1. accel_potential_exploder_length_scale: .1 accel_potential_exploder_eps: 1e-2 joint_velocity_cap_rmp: max_velocity: 2. # 4. # max_xd velocity_damping_region: 1.5 damping_gain: 1000.0 metric_weight: 100. # metric_scalar target_rmp: accel_p_gain: 50. #100. accel_d_gain: 85. accel_norm_eps: .075 metric_alpha_length_scale: .05 min_metric_alpha: .01 max_metric_scalar: 10000 min_metric_scalar: 2500 proximity_metric_boost_scalar: 20. proximity_metric_boost_length_scale: .02 xi_estimator_gate_std_dev: 20000. accept_user_weights: false # Values >= .5 are true and < .5 are false axis_target_rmp: accel_p_gain: 210. accel_d_gain: 60. metric_scalar: 10 proximity_metric_boost_scalar: 3000. proximity_metric_boost_length_scale: .08 xi_estimator_gate_std_dev: 20000. accept_user_weights: false collision_rmp: damping_gain: 50. damping_std_dev: .04 damping_robustness_eps: 1e-2 damping_velocity_gate_length_scale: .01 repulsion_gain: 800. repulsion_std_dev: .01 metric_modulation_radius: .5 metric_scalar: 10000. # Real value should be this. #metric_scalar: 0. # Turns off collision avoidance. metric_exploder_std_dev: .02 metric_exploder_eps: .001 damping_rmp: accel_d_gain: 30. metric_scalar: 50. inertia: 100. canonical_resolve: max_acceleration_norm: 50. projection_tolerance: .01 verbose: false body_cylinders: - name: base_stem pt1: [0,0,.333] pt2: [0,0,0.] radius: .05 # Each arm is approx. 1m from (arm) base to gripper center. # .1661 between links (approx .15) body_collision_controllers: - name: link7 radius: .05 - name: link5 radius: .05
3,017
YAML
30.768421
78
0.618827
MatthewDZane/XArmFollowTarget/scripts/XArm/XArm/XArm7/xarm7_descriptor.yaml
api_version: 1.0 cspace: - joint1 - joint2 - joint3 - joint4 - joint5 - joint6 - joint7 root_link: world default_q: [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ] cspace_to_urdf_rules: [] composite_task_spaces: [] #collision_spheres: # - panda_link0: # - "center": [0.0, 0.0, 0.05] # "radius": 0.08
348
YAML
16.449999
44
0.534483