file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/include/omni/geometry/Geometry.h | // Copyright (c) 2018-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/Defines.h>
#include <carb/Types.h>
#include <list>
#include <string>
namespace omni
{
namespace geometry
{
struct Geometry
{
CARB_PLUGIN_INTERFACE("omni::geometry::Geometry", 0, 1)
/*
ABI Definitions
*/
bool(CARB_ABI* triangulate)(long int stageId, const char* inputPath, const char* outputPath);
/**
* @param stageId Identfier for stage to work in
* @param layerPath The path of the layer in which to create the collision representation. If NULL or zero-length,
* the root layer is used
* @param inputPath The path of the original graphics mesh
* @param outputRoot The path of the new collision grouping
* @param proxyName If not NULL or zero-length, the root name of the collision meshes
* @param maxConvexHulls How many convex hulls can be used in the decomposition. If set to 1, the convex hull of
* the mesh vertices is used
* @param maxNumVerticesPerCH Maximum number of vertices per convex hull
* @param usePlaneShifting Whether or not to use plane shifting when building the hull
* @param resolution Voxel resolution for VHACD when convex decomposition is performed (maxConvexHulls > 1)
* @param visible Whether or not to make the collision hulls visible
* @return number of convex hulls, return 0 in case of failure
*/
int(CARB_ABI* createConvexHull)(long int stageId,
const char* layerPath,
const char* inputPath,
const char* outputRoot,
const char* proxyName,
const int maxConvexHulls,
const int maxNumVerticesPerCH,
const bool usePlaneShifting,
const int resolution,
const bool visible);
bool(CARB_ABI* createConvexHullFromSkeletalMesh)(long int stageId,
const char* inputMeshPath,
const char* proxyName,
const int maxConvexHulls,
const int maxNumVerticesPerCH,
const int resolution,
const bool makeConvexHullsVisible);
// It applies for all proxy prims, such as triangle proxy prim as well as convex proxy prim
bool(CARB_ABI* removeConvexHull)(long int stageId, const char* outputPath);
// Return a UsdGeomCube at path outputPath
bool(CARB_ABI* computeAABB)(long int stageId, const char* inputPath, const char* outputPath);
// Return a UsdGeomSphere at path outputPath
bool(CARB_ABI* computeBoundingSphere)(long int stageId, const char* inputPath, const char* outputPath);
};
}
}
| 3,440 | C | 44.879999 | 119 | 0.609012 |
omniverse-code/kit/include/omni/kit/EditorUsd.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/Defines.h>
namespace omni
{
namespace kit
{
/**
* Defines a Kit specific usd metadata set.
* The python counterpart is at source/extensions/omni.usd/bindings/python/omni.usd/impl/editor.py
*/
class EditorUsd
{
public:
/**
* Sets if to hide the prim in Stage Window.
*
* @param prim The prim to set metadata value to.
* @param hide true to hide prim in Stage Window, false to show in Stage Window.
*/
static void setHideInStageWindow(const pxr::UsdPrim& prim, bool hide)
{
static const pxr::TfToken kHideInStageWindow("hide_in_stage_window");
setMetadata(prim, kHideInStageWindow, hide);
}
/**
* Gets whether the prim should be hidden in Stage Window.
*
* @param prim The prim to get metadata value from.
* @return true if prim is hidden, false otherwise.
*/
static bool isHideInStageWindow(const pxr::UsdPrim& prim)
{
static const pxr::TfToken kHideInStageWindow("hide_in_stage_window");
return getMetadata(prim, kHideInStageWindow, false);
}
/**
* Sets if to disallow deletion of a prim.
*
* @param prim The prim to set metadata value to.
* @param noDelete true to disallow deletion, false to allow deletion.
*/
static void setNoDelete(const pxr::UsdPrim& prim, bool noDelete)
{
static const pxr::TfToken kNoDelete("no_delete");
setMetadata(prim, kNoDelete, noDelete);
}
/**
* Gets whether deletion on the prim is disallowed.
*
* @param prim The prim to get metadata value from.
* @return true if prim cannot be disabled, false otherwise.
*/
static bool isNoDelete(const pxr::UsdPrim& prim)
{
static const pxr::TfToken kNoDelete("no_delete");
return getMetadata(prim, kNoDelete, false);
}
/**
* Sets if to override the picking preference of a prim.
*
* @param prim The prim to set metadata value to.
* @param pickModel true to always pick the enclosing model regardless of editor preferences, false to follow editor
* preferences.
*/
static void setAlwaysPickModel(const pxr::UsdPrim& prim, bool pickModel)
{
static const pxr::TfToken kAlwaysPickModel("always_pick_model");
setMetadata(prim, kAlwaysPickModel, pickModel);
}
/**
* Gets whether prim overrides the picking mode to always pick model.
*
* @param prim The prim to get metadata value from.
* @return true if pick on the prim always select its enclosing model, false otherwise.
*/
static bool isAlwaysPickModel(const pxr::UsdPrim& prim)
{
static const pxr::TfToken kAlwaysPickModel("always_pick_model");
return getMetadata(prim, kAlwaysPickModel, false);
}
/**
* Sets if a prim should ignore material updates.
*
* @param prim The material prim to set metadata value to.
* @param ignore true if prim has set to ignore material updates.
*/
static void setIgnoreMaterialUpdates(const pxr::UsdPrim& prim, bool ignore)
{
static const pxr::TfToken kIgnoreMaterialUpdates("ignore_material_updates");
setMetadata(prim, kIgnoreMaterialUpdates, ignore);
}
/**
* Gets whether the prim should ignore material updates.
*
* @param prim The prim to get metadata value from.
* @return true if prim has set to ignore material updates
*/
static bool hasIgnoreMaterialUpdates(const pxr::UsdPrim& prim)
{
static const pxr::TfToken kIgnoreMaterialUpdates("ignore_material_updates");
return getMetadata(prim, kIgnoreMaterialUpdates, false);
}
/**
* Sets if a prim should show a selection outline
*
* @param prim The material prim to set metadata value to.
* @param ignore true if prim has set to not show a selection outline
*/
static void setNoSelectionOutline(const pxr::UsdPrim& prim, bool ignore)
{
static const pxr::TfToken kNoSelectionOutline("no_selection_outline");
setMetadata(prim, kNoSelectionOutline, ignore);
}
/**
* Gets whether the prim should show a selection outline
*
* @param prim The prim to get metadata value from.
* @return true if prim has set to not show a selection outline
*/
static bool hasNoSelectionOutline(const pxr::UsdPrim& prim)
{
static const pxr::TfToken kNoSelectionOutline("no_selection_outline");
return getMetadata(prim, kNoSelectionOutline, false);
}
private:
template <typename T>
static void setMetadata(const pxr::UsdPrim& prim, const pxr::TfToken& token, T value)
{
pxr::UsdEditContext context(prim.GetStage(), prim.GetStage()->GetSessionLayer());
bool ret = prim.SetMetadata(token, value);
CARB_ASSERT(ret);
}
template <typename T>
static T getMetadata(const pxr::UsdPrim& prim, const pxr::TfToken& token, T defaultVal)
{
T val = defaultVal;
prim.GetMetadata(token, &val);
return val;
}
};
}
}
| 5,517 | C | 32.646341 | 120 | 0.671198 |
omniverse-code/kit/include/omni/kit/IScriptEditor.h | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Interface.h>
namespace omni
{
namespace kit
{
/**
* Defines the interface for ScriptEditor Window.
*/
struct IScriptEditor
{
CARB_PLUGIN_INTERFACE("omni::kit::IScriptEditor", 1, 0);
void(CARB_ABI* showHideWindow)(void* window, bool visible);
};
}
}
| 725 | C | 24.928571 | 77 | 0.755862 |
omniverse-code/kit/include/omni/kit/FilterGroup.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/logging/Log.h>
#include <omni/kit/EventSubscribers.h>
#include <functional>
#include <map>
#include <regex>
namespace omni
{
namespace kit
{
/**
* Defines the filter group class
* @param ItemT Type of the item to be filtered.
* @param FilterT Type of the filter used to test item.
* @param Pred Predicate to test if an item is accepted by a filter.
*/
template <typename ItemT, typename FilterT, typename Pred>
class FilterGroup
{
public:
using SubscriptionId = uint64_t;
using OnFilterChangedFn = std::function<void()>;
/**
* Tests an item against all enabled filters.
*
* @param item The item to be tested.
* @return True if the item matches any enabled filter.
*/
bool match(const ItemT& item) const
{
if (m_enabledCount == 0 || m_groupEnabled == false)
{
return true;
}
bool accepted = false;
for (auto&& filter : m_filters)
{
if (!filter.second.enabled)
{
continue;
}
accepted |= m_pred(item, filter.second.filter);
if (accepted)
{
break;
}
}
return accepted;
}
/**
* Adds a filter to the FilterGroup.
*
* @param name The name of the filter.
* @param filter The filter to be added.
* @param enabled True to enable the filter on add.
* @return True if filter is added successfully.
*/
bool addFilter(const std::string& name, const FilterT& filter, bool enabled)
{
auto filterEntry = m_filters.find(name);
if (filterEntry == m_filters.end())
{
m_filters.emplace(name, FilterData{ filter, enabled });
m_enabledCount += enabled ? 1 : 0;
// Turn on filterGroup if not already enabled
m_groupEnabled |= enabled;
m_filterChangeSubscribers.send();
return true;
}
else
{
CARB_LOG_WARN("Failed to add filter %s. Already existed", name.c_str());
}
return false;
}
/**
* Gets names of all filters in the FilterGroup.
*
* @param filterNames The vector to store all filter names to.
*/
void getFilterNames(std::vector<std::string>& filterNames) const
{
filterNames.reserve(m_filters.size());
for (auto&& filter : m_filters)
{
filterNames.push_back(filter.first);
}
}
/**
* Checks if a filter is enabled by its name.
*
* @param name The name of the filter to be checked.
* @return True if the filter is enabled. False if filter is disabled or not exists.
*/
bool isFilterEnabled(const std::string& name) const
{
auto filterEntry = m_filters.find(name);
if (filterEntry != m_filters.end())
{
return filterEntry->second.enabled;
}
return false;
}
/**
* Enable or disable a filter by its name.
* If the filter is the first one to be enabled in the FilterGroup, the FilterGroup will be enabled.
* If the filter is the last one to be disabled in the FilterGroup, the FilterGroup will be disabled.
*
* @param name The name of the filter.
* @param enabled True to enable the filter. False to disable the filter.
*/
void setFilterEnabled(const std::string& name, bool enabled)
{
auto filterEntry = m_filters.find(name);
if (filterEntry != m_filters.end())
{
if (filterEntry->second.enabled != enabled)
{
m_enabledCount += enabled ? 1 : -1;
filterEntry->second.enabled = enabled;
if (m_groupEnabled && m_enabledCount == 0)
{
m_groupEnabled = false;
}
else if (!m_groupEnabled && enabled)
{
m_groupEnabled |= true;
}
m_filterChangeSubscribers.send();
}
}
}
/**
* Checks if the FilterGroup is enabled.
* If a FilterGroup is disabled, none of its enabled filter will filter any item.
*
* @return True if FilterGroup is enabled.
*/
bool isFilterGroupEnabled() const
{
return m_groupEnabled;
}
/**
* Enabled or disable the FilterGroup
*
* @param enabled True to enable the FilterGroup. False to disable the FilterGroup.
*/
void setFilterGroupEnabled(bool enabled)
{
if (m_groupEnabled != enabled)
{
m_groupEnabled = enabled;
m_filterChangeSubscribers.send();
}
}
/**
* Checks if any of the filter in the FilterGroup is enabled.
*
* @return True if at least one filter in the FilterGroup is enabled.
*/
bool isAnyFilterEnabled() const
{
return m_enabledCount > 0;
}
/**
* Remove all filters in the group.
*/
void clear()
{
m_filters.clear();
m_enabledCount = 0;
m_groupEnabled = false;
m_filterChangeSubscribers.send();
}
/**
* Subscribes to filter change event.
*
* @param onFilterEvent The function to be called when filter has changed.
* @return SubscriptionId to be used when unsubscribe from filter event.
*/
SubscriptionId subscribeForFilterEvent(const OnFilterChangedFn& onFilterEvent)
{
// Since we're using std::function, userData is not needed anymore.
return m_filterChangeSubscribers.subscribe([onFilterEvent](void*) { onFilterEvent(); }, nullptr);
}
/**
* Unsubscribe from filter change event.
*
* @param subId the SubscriptionId obtain when calling @ref subscribeForFilterEvent.
*/
void unsubscribeFromFilterEvent(SubscriptionId subId)
{
m_filterChangeSubscribers.unsubscribe(subId);
}
private:
using OnFilterChangedInternalFn = std::function<void(void*)>;
struct FilterData
{
FilterT filter;
bool enabled;
};
bool m_groupEnabled = false;
Pred m_pred;
std::map<std::string, FilterData> m_filters;
size_t m_enabledCount = 0;
carb::EventSubscribers<OnFilterChangedInternalFn, SubscriptionId> m_filterChangeSubscribers;
};
/**
* Defines a FilterGroup that tests string against regular expression.
*/
struct RegexPred
{
bool operator()(const std::string& str, const std::regex& regex) const
{
return std::regex_search(str, regex);
}
};
using RegexFilterGroup = FilterGroup<std::string, std::regex, RegexPred>;
}
}
| 7,123 | C | 27.047244 | 105 | 0.600309 |
omniverse-code/kit/include/omni/kit/ValueGuard.h | // Copyright (c) 2018-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/Defines.h>
namespace omni
{
namespace kit
{
template <typename T, T inVal, T outVal>
class ValueGuard
{
public:
explicit ValueGuard(T& val) : m_val(val)
{
CARB_ASSERT(m_val == outVal);
m_val = inVal;
}
~ValueGuard()
{
m_val = outVal;
}
private:
T& m_val;
};
using BoolGuard = ValueGuard<bool, true, false>;
}
}
| 839 | C | 19 | 77 | 0.693683 |
omniverse-code/kit/include/omni/kit/IExtensionWindow.h | // Copyright (c) 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 "ExtensionWindowTypes.h"
#include <carb/Interface.h>
namespace omni
{
namespace kit
{
/**
* Defines the minimal interface for an extension window.
*/
struct IExtensionWindow
{
CARB_PLUGIN_INTERFACE("omni::kit::IExtensionWindow", 1, 1);
/**
* Creates an instance of the extension window.
*
* @return created instance of extension window.
*/
ExtensionWindowHandle(CARB_ABI* createInstance)();
/**
* Destroys an instance of extension window.
*
* @param handle The window handle to be destroyed.
* @return true if window is destroyed, false if not.
*/
bool(CARB_ABI* destroyInstance)(const ExtensionWindowHandle handle);
/**
* Query if an instance of extension window is visible.
*
* @param handle The window handle to be destroyed.
*/
bool(CARB_ABI* isInstanceVisible)(const ExtensionWindowHandle handle);
/**
* Display or hide an instance of extension window.
*
* @param handle The window handle to be destroyed.
* @param visible true to show the window, false to hide the window.
*/
void(CARB_ABI* setInstanceVisible)(const ExtensionWindowHandle handle, bool visible);
/**
* Creates an instance of the viewport window with custom name and usdd stage.
*
* @param name The window name.
* @param usdContextName The usd context to show in the window.
* @param createMenu When true, the Window menu is created.
* @return created instance of extension window.
*/
ExtensionWindowHandle(CARB_ABI* createCustomizedInstance)(const char* name,
const char* usdContextName,
bool createMenu);
};
}
}
| 2,245 | C | 31.085714 | 89 | 0.664588 |
omniverse-code/kit/include/omni/kit/IStageUpdate.h | // 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
#if (!defined(PXR_USD_SDF_PATH_H))
namespace pxr
{
class SdfPath;
};
#endif
#include "KitTypes.h"
#include <carb/Interface.h>
#include <carb/InterfaceUtils.h>
#include <memory>
namespace omni
{
namespace kit
{
struct StageUpdateNode;
struct StageUpdateSettings
{
bool playSimulations;
bool playComputegraph;
bool isPlaying;
};
struct StageUpdateNodeDesc
{
const char* displayName;
void* userData;
int order;
/**
Attach usd stage to physics.
This function gets called when Kit loads a new usd file or create a new scene.
To convert stageId to stage ref, use
pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(stageId))
*/
void(CARB_ABI* onAttach)(long int stageId, double metersPerUnit, void* userData);
// detach the stage
void(CARB_ABI* onDetach)(void* userData);
// simulation was paused
void(CARB_ABI* onPause)(void* userData);
// simulation was stopped(reset)
void(CARB_ABI* onStop)(void* userData);
// simulation was resumed
void(CARB_ABI* onResume)(float currentTime, void* userData);
// this gets called in every update cycle of Kit (typically at each render frame)
void(CARB_ABI* onUpdate)(float currentTime, float elapsedSecs, const StageUpdateSettings* settings, void* userData);
/*
The following call backs are called when there is change in usd scene (e.g. user interaction, scripting, )
Each plugin should query the usd stage based on provided prim path name and sync changes related to their data
*/
// this gets called when a new Usd prim was added to the scene
void(CARB_ABI* onPrimAdd)(const pxr::SdfPath& primPath, void* userData);
// this gets called when some properties in the usd prim was changed (e.g. manipulator or script changes transform)
void(CARB_ABI* onPrimOrPropertyChange)(const pxr::SdfPath& primOrPropertyPath, void* userData);
// this gets called when the named usd prim was removed from the scene
void(CARB_ABI* onPrimRemove)(const pxr::SdfPath& primPath, void* userData);
/**
* Temporary raycast handler. This will become part of a more general user event handler.
*
* @param orig the ray origin. Set to NULL to send a stop command for grabbing.
* @param dir the ray direction (should be normalized).
* @param input whether the input control is set or reset (e.g. mouse down).
*/
void(CARB_ABI* onRaycast)(const float* orig, const float* dir, bool input, void* userData);
};
struct StageUpdateNodeDescV2 : public StageUpdateNodeDesc
{
// simulation was resumed
void(CARB_ABI* onResumeV2)(double currentTime, double absoluteSimTime, void* userData);
// this gets called in every update cycle of Kit (typically at each render frame)
void(CARB_ABI* onUpdateV2)(double currentTime,
float elapsedSecs,
double absoluteSimTime,
const StageUpdateSettings* settings,
void* userData);
};
struct StageUpdateNodeInfo
{
const char* name;
bool enabled;
int order;
};
typedef void (*OnStageUpdateNodesChangeFn)(void* userData);
struct StageUpdate
{
virtual StageUpdateNode* createStageUpdateNode(const StageUpdateNodeDesc& desc) = 0;
virtual void destroyStageUpdateNode(StageUpdateNode* node) = 0;
virtual size_t getStageUpdateNodeCount() const = 0;
virtual void getStageUpdateNodes(StageUpdateNodeInfo* nodes) const = 0;
virtual void setStageUpdateNodeOrder(size_t index, int order) = 0;
virtual void setStageUpdateNodeEnabled(size_t index, bool enabled) = 0;
virtual SubscriptionId subscribeToStageUpdateNodesChangeEvents(OnStageUpdateNodesChangeFn onChange,
void* userData) = 0;
virtual void unsubscribeToStageUpdateNodesChangeEvents(SubscriptionId subscriptionId) = 0;
virtual void attach(long int stageId) = 0;
virtual void detach() = 0;
virtual void setPlaying(float currentTime, bool isPlaying, bool isStop /*= false*/) = 0;
virtual void applyPendingEdit() = 0;
virtual void update(float currentTime, float elapsedSecs, StageUpdateSettings& settings) = 0;
virtual void handleAddedPrim(const pxr::SdfPath& primPath) = 0;
virtual void handleChangedPrimOrProperty(const pxr::SdfPath& primOrPropertyPath, bool& isTransformDirty) = 0;
virtual void handleRemovedPrim(const pxr::SdfPath& primPath) = 0;
virtual void handleRaycast(const float* orig, const float* dir, bool input) = 0;
virtual StageUpdateNode* createStageUpdateNodeV2(const StageUpdateNodeDescV2& desc) = 0;
virtual void setPlayingV2(double currentTime, double absoluteSimTime, bool isPlaying, bool isStop /*= false*/) = 0;
virtual void updateV2(double currentTime, float elapsedSecs, double absoluteSimTime, StageUpdateSettings& settings) = 0;
};
using StageUpdatePtr = std::shared_ptr<StageUpdate>;
/**
* Defines an interface for the editor stage update API part.
*/
struct IStageUpdate
{
CARB_PLUGIN_INTERFACE("omni::kit::IStageUpdate", 1, 0);
//------------------------
// Deprecated interface
//------------------------
StageUpdateNode*(CARB_ABI* createStageUpdateNode)(const StageUpdateNodeDesc& desc);
void(CARB_ABI* destroyStageUpdateNode)(StageUpdateNode* node);
size_t(CARB_ABI* getStageUpdateNodeCount)();
void(CARB_ABI* getStageUpdateNodes)(StageUpdateNodeInfo* nodes);
void(CARB_ABI* setStageUpdateNodeOrder)(size_t index, int order);
void(CARB_ABI* setStageUpdateNodeEnabled)(size_t index, bool enabled);
SubscriptionId(CARB_ABI* subscribeToStageUpdateNodesChangeEvents)(OnStageUpdateNodesChangeFn onChange,
void* userData);
void(CARB_ABI* unsubscribeToStageUpdateNodesChangeEvents)(SubscriptionId subscriptionId);
void(CARB_ABI* attach)(long int stageId);
void(CARB_ABI* detach)();
void(CARB_ABI* setPlaying)(float currentTime, bool isPlaying, bool isStop /*= false*/);
void(CARB_ABI* applyPendingEdit)();
void(CARB_ABI* update)(float currentTime, float elapsedSecs, StageUpdateSettings& settings);
void(CARB_ABI* handleAddedPrim)(const pxr::SdfPath& primPath);
void(CARB_ABI* handleChangedPrimOrProperty)(const pxr::SdfPath& primOrPropertyPath, bool& isTransformDirty);
void(CARB_ABI* handleRemovedPrim)(const pxr::SdfPath& primPath);
void(CARB_ABI* handleRaycast)(const float* orig, const float* dir, bool input);
StageUpdateNode*(CARB_ABI* createStageUpdateNodeV2)(const StageUpdateNodeDescV2& desc);
void(CARB_ABI* setPlayingV2)(double currentTime, double absoluteSimTime, bool isPlaying, bool isStop /*= false*/);
void(CARB_ABI* updateV2)(double currentTime, float elapsedSecs, double absoluteSimTime, StageUpdateSettings& settings);
//---------------
// New interface
//---------------
/**
* Gets the StageUpdate object with the given name. Creates a new one if it does not exist.
* Pass nullptr to retrieve the default StageUpdate, which is the StageUpdate object of the default UsdContext.
*
* @param name Name of the StageUpdate object.
*
* @return The StageUpdate
*/
StageUpdatePtr(CARB_ABI* getStageUpdateByName)(const char* name);
inline StageUpdatePtr getStageUpdate(const char* name)
{
return getStageUpdateByName(name);
}
inline StageUpdatePtr getStageUpdate()
{
return getStageUpdateByName(nullptr);
}
/**
* Destroys the StageUpdate with the given name if nothing references it. Does not release the default StageUpdate (name==null).
*
* @param name Name of the StageUpdate.
*
* @return True if a StageUpdate was deleted, false otherwise. The latter happens when the StageUpdate does not exist, it
* is in use, or it is the StageUpdate of the default UsdContext.
*/
bool(CARB_ABI* destroyStageUpdate)(const char* name);
};
/**
* Gets the StageUpdate object with the given name via cached IStageUpdate interface. Creates a new one if it does not exist.
* Pass nullptr to retrieve the default StageUpdate, which is the StageUpdate object of the default UsdContext.
*
* @param name Name of the StageUpdate object.
*
* @return The StageUpdate
*/
inline StageUpdatePtr getStageUpdate(const char* name = nullptr)
{
auto iface = carb::getCachedInterface<omni::kit::IStageUpdate>();
return iface == nullptr ? nullptr : iface->getStageUpdate(name);
}
}
}
| 9,131 | C | 33.722433 | 132 | 0.701566 |
omniverse-code/kit/include/omni/kit/KitTypes.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/datasource/IDataSource.h>
namespace carb
{
namespace input
{
struct Keyboard;
struct Mouse;
}
namespace imgui
{
struct ImGui;
}
}
namespace omni
{
namespace kit
{
typedef uint64_t SubscriptionId;
constexpr size_t kBackBufferCount = 3; ///< Maximum number of frames to queue up.
struct Prompt;
struct Window;
struct ContentWindowWidget;
struct ContentWindowToolButton;
typedef void (*OnUpdateEventFn)(float elapsedTime, void* userData);
typedef void (*OnConnectionEventFn)(const carb::datasource::ConnectionEventType& eventType, void* userData);
typedef void (*OnWindowDrawFn)(const char* windowName, float elapsedTime, void* userData);
typedef void (*OnWindowStateChangeFn)(const char* name, bool open, void* userData);
typedef void (*OnExtensionsChangeFn)(void* userData);
typedef void (*OnShutdownEventFn)(void* userData);
typedef void (*OnLogEventFn)(
const char* source, int32_t level, const char* filename, int lineNumber, const char* message, void* userData);
typedef void (*OnUIDrawEventFn)(carb::imgui::ImGui*,
const double* viewMatrix,
const double* projMatrix,
const carb::Float4& viewPortRect,
void* userData);
struct ExtensionInfo
{
const char* id;
bool enabled;
const char* name;
const char* description;
const char* path;
};
struct ExtensionFolderInfo
{
const char* path;
bool builtin;
};
enum class GraphicsMode
{
eVulkan,
eDirect3D12
};
enum class RendererMode
{
eRtx, ///< NVIDIA RTX renderer, a fully ray traced renderer.
eNvf ///< NVIDIA NVF renderer. reserved for internal use.
};
struct EnumClassHash
{
template <typename T>
std::size_t operator()(T t) const
{
return static_cast<std::size_t>(t);
}
};
}
}
| 2,308 | C | 24.097826 | 114 | 0.701906 |
omniverse-code/kit/include/omni/kit/IFileDialog.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 "KitTypes.h"
#include <carb/Interface.h>
namespace omni
{
namespace kit
{
struct FileDialog;
typedef void (*OnFileDialogFileSelected)(const char* realpath, void* userData);
typedef void (*OnFileDialogCancelled)(void* userData);
enum class FileDialogOpenMode
{
eOpen,
eSave
};
enum class FileDialogSelectType
{
eFile,
eDirectory,
eAll
};
enum class FileDialogDataSource
{
eLocal, ///! Show local files only
eOmniverse, ///! Show omniverse files only
eAll ///! Show files form all data sources
};
/**
* Defines an interface for the editor stage update API part.
*/
struct IFileDialog
{
CARB_PLUGIN_INTERFACE("omni::kit::IFileDialog", 0, 6);
/**
* Create file dialog that uses for file/folder picker
* @param title Window title.
* @param mode Create dialog for save or open.
* @param type Create dialog to select file or folder.
* @param onFileSelectedFn Callback for file selection.
* @param onDialogCancelled Callback for dialog cancel.
* @param width Initial window width.
* @param height Initial window height.
* @return FileDialog instance
*/
FileDialog*(CARB_ABI* createFileDialog)(const char* title,
FileDialogOpenMode mode,
FileDialogSelectType type,
OnFileDialogFileSelected onFileSelectedFn,
void* selectedFnUserData,
OnFileDialogCancelled onDialogCancelled,
void* cancelFnUserData,
float width,
float height);
/**
* Destroy file dialog
* @param dialog FileDialog instance
*/
void(CARB_ABI* destroyFileDialog)(FileDialog* dialog);
/**
* Sets file selection callback.
* @param dialog FileDialog instance.
* @param onFileSelctedFn Callback if file is selected.
*/
void(CARB_ABI* setFileSelectedFnForFileDialog)(FileDialog* dialog,
OnFileDialogFileSelected onFileSelctedFn,
void* userData);
/**
* Sets file dialog cancelled callback.
* @param dialog FileDialog instance.
* @param onDialogCancelled Callback ifdialog is cancelled.
*/
void(CARB_ABI* setCancelFnForFileDialog)(FileDialog* dialog, OnFileDialogCancelled onDialogCancelled, void* userData);
/**
* Adds filter to file dialog to filter file type
* @param dialog FileDialog instance
*/
void(CARB_ABI* addFilterToFileDialog)(FileDialog* dialog, const char* name, const char* spec);
/**
* Clear all filters of file dialog
* @param dialog FileDialog instance
*/
void(CARB_ABI* clearAllFiltersOfFileDialog)(FileDialog* dialog);
/**
* Show file dialog
*/
void(CARB_ABI* showFileDialog)(FileDialog* dialog, FileDialogDataSource dataSource);
/**
* Draw file dialog
*/
void(CARB_ABI* drawFileDialog)(FileDialog* dialog, float elapsedTime);
/**
* If file dialog is opened or not
*/
bool(CARB_ABI* isFileDialogOpened)(FileDialog* dialog);
/**
* Gets title of file dialog
*/
const char*(CARB_ABI* getTitleOfFileDialog)(FileDialog* dialog);
/**
* Sets title for file dialog
*/
void(CARB_ABI* setTitleForFileDialog)(FileDialog* dialog, const char* title);
/**
* Gets selection type for file dialog
*/
FileDialogSelectType(CARB_ABI* getSelectionType)(FileDialog* dialog);
/**
* Sets selection type for file dialog
*/
void(CARB_ABI* setSelectionType)(FileDialog* dialog, FileDialogSelectType type);
/**
* Sets the directory where the dialog will open
*/
void(CARB_ABI* setCurrentDirectory)(FileDialog* dialog, const char* dir);
/** sets the default name to use for the filename on save dialogs.
*
* @param[in] dialog the file picker dialog to set the default save name for. This
* may not be nullptr.
* @param[in] name the default filename to use for this dialog. This may be nullptr
* or an empty string to use the USD stage's default prim name. In
* this case, if the prim name cannot be retrieved, "Untitled" will
* be used instead. If a non-empty string is given here, this will
* always be used as the initial suggested filename.
* @returns no return value.
*
* @remarks This sets the default filename to be used when saving a file. This name will
* be ignored if the dialog is not in @ref FileDialogOpenMode::eSave mode. The
* given name will still be stored regardless. This default filename may omit
* the file extension to take the extension from the current filter. If an
* extension is explicitly given here, no extension will be appended regardless
* of the current filter.
*/
void(CARB_ABI* setDefaultSaveName)(FileDialog* dialog, const char* name);
};
}
}
| 5,788 | C | 33.254438 | 122 | 0.623013 |
omniverse-code/kit/include/omni/kit/SettingsUtils.h | // Copyright (c) 2019-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 Settings utilities for omni.kit.app
#pragma once
/**
* The settings prefix to indicate that a setting is persistent.
*/
#define PERSISTENT_SETTINGS_PREFIX "/persistent"
//! The separator character used by carb.settings
#define SETTING_SEP "/"
| 708 | C | 32.761903 | 77 | 0.769774 |
omniverse-code/kit/include/omni/kit/KitUtils.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/Framework.h>
#include <carb/datasource/DataSourceUtils.h>
#include <carb/datasource/IDataSource.h>
#include <carb/events/IEvents.h>
#include <carb/imgui/ImGui.h>
#include <carb/input/IInput.h>
#include <carb/input/InputUtils.h>
#include <carb/settings/SettingsUtils.h>
#include <carb/tokens/ITokens.h>
#include <omni/kit/AssetUtils.h>
#include <omni/kit/IFileDialog.h>
#include <omni/kit/SettingsUtils.h>
#include <omni/ui/IGlyphManager.h>
#include <atomic>
namespace omni
{
namespace kit
{
/**
* Set of helpers to pass std::function in Carbonite interfaces.
* This is borrowed from <carb/BindingsPythonUtils.h>.
*/
template <typename ReturnT, typename... ArgsT>
class FuncUtils
{
public:
using StdFuncT = std::function<ReturnT(ArgsT...)>;
using CallbackT = ReturnT (*)(ArgsT..., void*);
static ReturnT callbackWithUserData(ArgsT... args, void* userData)
{
StdFuncT* fn = (StdFuncT*)userData;
if (fn)
return (*fn)(args...);
else
return ReturnT();
}
static StdFuncT* createStdFuncCopy(const StdFuncT& fn)
{
return new StdFuncT(fn);
}
static void destroyStdFuncCopy(StdFuncT* fn)
{
delete fn;
}
};
template <class T>
struct StdFuncUtils;
template <class R, class... Args>
struct StdFuncUtils<std::function<R(Args...)>> : public omni::kit::FuncUtils<R, Args...>
{
};
template <class R, class... Args>
struct StdFuncUtils<const std::function<R(Args...)>> : public FuncUtils<R, Args...>
{
};
template <class R, class... Args>
struct StdFuncUtils<const std::function<R(Args...)>&> : public FuncUtils<R, Args...>
{
};
inline omni::kit::IFileDialog* getIFileDialog()
{
return carb::getCachedInterface<omni::kit::IFileDialog>();
}
inline carb::imgui::ImGui* getImGui()
{
return carb::getCachedInterface<carb::imgui::ImGui>();
}
inline carb::input::IInput* getInput()
{
return carb::getCachedInterface<carb::input::IInput>();
}
inline carb::dictionary::IDictionary* getDictionary()
{
return carb::getCachedInterface<carb::dictionary::IDictionary>();
}
inline carb::settings::ISettings* getSettings()
{
return carb::getCachedInterface<carb::settings::ISettings>();
}
inline carb::filesystem::IFileSystem* getFileSystem()
{
return carb::getCachedInterface<carb::filesystem::IFileSystem>();
}
inline omni::ui::IGlyphManager* getGlyphManager()
{
return carb::getCachedInterface<omni::ui::IGlyphManager>();
}
struct ProcessEventSkipHotkey
{
carb::input::KeyboardModifierFlags mod;
carb::input::KeyboardInput key;
};
inline void processImguiInputEvents(ProcessEventSkipHotkey* skipHotkeys = nullptr,
size_t skipHotkeysCount = 0,
carb::input::IInput* input = nullptr,
carb::imgui::ImGui* imgui = nullptr)
{
if (!imgui)
{
imgui = getImGui();
}
if (!input)
{
input = getInput();
}
carb::input::filterBufferedEvents(input, [&](carb::input::InputEvent& evt) -> carb::input::FilterResult {
if (evt.deviceType != carb::input::DeviceType::eKeyboard)
{
return carb::input::FilterResult::eRetain;
}
const carb::input::KeyboardEvent* event = &evt.keyboardEvent;
{
bool needToConsume = false;
bool needToFeed = false;
// Always pass through key release events to make sure keys do not get "stuck".
// Possibly limit the keys in the future to maintain a map of pressed keys on the widget activation.
if (event->type == carb::input::KeyboardEventType::eKeyRelease)
{
needToConsume = false;
needToFeed = true;
}
else
{
// Always consume character input events
if (event->type == carb::input::KeyboardEventType::eChar)
{
needToConsume = true;
needToFeed = true;
}
// Do not consume Tab key to allow free navigation
else if (event->key != carb::input::KeyboardInput::eTab)
{
needToConsume = true;
needToFeed = true;
}
// Check if the event hotkey is in the list of skip hotkeys, and if so, always avoid passing those to
// imgui
if (skipHotkeys)
{
for (size_t hkIdx = 0; hkIdx < skipHotkeysCount; ++hkIdx)
{
ProcessEventSkipHotkey& skipHk = skipHotkeys[hkIdx];
if (event->modifiers == skipHk.mod && event->key == skipHk.key)
{
needToConsume = false;
needToFeed = false;
break;
}
}
}
}
if (needToFeed)
{
imgui->feedKeyboardEvent(imgui->getCurrentContext(), *event);
}
if (needToConsume)
{
return carb::input::FilterResult::eConsume;
}
}
return carb::input::FilterResult::eRetain;
});
}
// Helper functions for the child windows
inline bool predictActiveProcessImguiInput(const char* widgetIdString,
ProcessEventSkipHotkey* skipHotkeys = nullptr,
size_t skipHotkeysCount = 0)
{
carb::imgui::ImGui* imgui = getImGui();
carb::input::IInput* input = getInput();
uint32_t widgetId = imgui->getIdString(widgetIdString);
bool isItemPredictedActive = imgui->isItemIdActive(widgetId);
if (isItemPredictedActive)
{
processImguiInputEvents(skipHotkeys, skipHotkeysCount, input, imgui);
}
return isItemPredictedActive;
}
inline bool isWritableUrl(const char* url)
{
bool writable = false;
auto omniClientDataSource =
carb::getFramework()->acquireInterface<carb::datasource::IDataSource>("carb.datasource-omniclient.plugin");
omniClientDataSource->isWritable(
nullptr, url,
[](carb::datasource::Response response, const char* path, bool isWritable, void* userData) {
if (response == carb::datasource::Response::eOk)
{
*reinterpret_cast<bool*>(userData) = isWritable;
}
},
&writable);
return writable;
}
// Copied from Client Library
inline const char* getDefaultUser()
{
for (auto e : { "OV_USER", "USER", "USERNAME", "LOGNAME" })
{
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4996) // 'sprintf': This function or variable may be unsafe.
#endif
auto user = getenv(e);
#ifdef _MSC_VER
# pragma warning(pop)
#endif
if (user)
{
return user;
}
}
return "";
}
}
}
| 7,492 | C | 28.042636 | 117 | 0.595168 |
omniverse-code/kit/include/omni/kit/ContentWindowUtils.h | // Copyright (c) 2018-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/InterfaceUtils.h>
#include <omni/kit/IContentUi.h>
namespace omni
{
namespace kit
{
/**
* Gets the default (first) IContentWindow
*
* @return Default IContentWindow
*/
inline IContentWindow* getDefaultContentWindow()
{
auto contentWindow = carb::getCachedInterface<omni::kit::IContentUi>();
if (contentWindow)
{
return contentWindow->getContentWindow(nullptr);
}
return nullptr;
}
}
}
| 889 | C | 23.722222 | 77 | 0.748031 |
omniverse-code/kit/include/omni/kit/IMinimal.h | // Copyright (c) 2018-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/Interface.h>
namespace omni
{
namespace kit
{
/**
* Minimal interface.
*
* It doesn't have any functions, but just implementing it and acquiring will load your plugin, trigger call of
* carbOnPluginStartup() and carbOnPluginShutdown() methods and allow you to use other Carbonite plugins. That by itself
* can get you quite far and useful as basic building block for Kit extensions. One can define their own interface with
* own python python bindings when needed and abandon that one.
*/
struct IMinimal
{
CARB_PLUGIN_INTERFACE("omni::kit::IMinimal", 1, 0);
};
}
}
| 1,048 | C | 31.781249 | 120 | 0.766221 |
omniverse-code/kit/include/omni/kit/IAppWindow.h | // Copyright (c) 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/IObject.h>
#include <carb/Interface.h>
#include <carb/events/EventsUtils.h>
#include <carb/events/IEvents.h>
#include <carb/input/IInput.h>
#include <carb/windowing/IWindowing.h>
namespace omni
{
namespace kit
{
constexpr const char* kWindowEnabledPath = "/app/window/enabled";
constexpr const char* kWindowWidthPath = "/app/window/width";
constexpr const char* kWindowHeightPath = "/app/window/height";
constexpr const char* kpWindowWidthPath = "/persistent/app/window/width";
constexpr const char* kpWindowHeightPath = "/persistent/app/window/height";
constexpr const char* kWindowMaximizedPath = "/app/window/maximized";
constexpr const char* kpWindowMaximizedPath = "/persistent/app/window/maximized";
constexpr const char* kWindowXPath = "/app/window/x";
constexpr const char* kWindowYPath = "/app/window/y";
constexpr const char* kWindowTitlePath = "/app/window/title";
constexpr const char* kWindowFullscreenPath = "/app/window/fullscreen";
constexpr const char* kWindowNoResizePath = "/app/window/noResize";
constexpr const char* kWindowScaleToMonitorPath = "/app/window/scaleToMonitor";
constexpr const char* kWindowAlwaysOnTopPath = "/app/window/alwaysOnTop";
constexpr const char* kWindowNoDecorationsPath = "/app/window/noDecorations";
constexpr const char* kWindowHideMouseInFullscreenPath = "/app/window/hideMouseInFullscreen";
constexpr const char* kWindowDpiScaleOverridePath = "/app/window/dpiScaleOverride";
constexpr const char* kWindowBlockAllInputPath = "/app/window/blockAllInput";
constexpr const char* kWindowIconPath = "/app/window/iconPath";
constexpr const char* kWindowChildWindowsOnTopPath = "/app/window/childWindowsOnTop";
constexpr const char* kWindowCursorBlinkPath = "/app/window/cursorBlink";
constexpr const uint64_t kPositionCentered = (uint64_t)-1;
constexpr const uint64_t kPositionUnset = (uint64_t)-2;
enum class Decorations
{
eFull,
eNone
};
enum class Resize
{
eAllowed,
eNotAllowed
};
enum class Floating
{
eRegular,
eAlwaysOnTop
};
enum class Scaling
{
eScaleToMonitor,
eNotScaled
};
enum class Fullscreen
{
eWindowed,
eFullscreen,
};
enum class WindowState
{
eNormal,
eMaximized,
eMinimized,
};
enum class CursorBlink
{
eBlink,
eNoBlink
};
struct WindowDesc
{
size_t structSize; // This field is needed to maintain ABI stability
uint64_t width, height;
uint64_t x, y;
const char* title;
Fullscreen fullscreen;
Decorations decorations;
Resize resize;
Floating floating;
Scaling scaling;
float dpiScaleOverride;
CursorBlink cursorBlink;
WindowState windowState;
};
inline WindowDesc getDefaultWindowDesc()
{
WindowDesc windowDesc;
windowDesc.structSize = sizeof(WindowDesc);
windowDesc.width = 1440;
windowDesc.height = 900;
windowDesc.x = kPositionUnset;
windowDesc.y = kPositionUnset;
windowDesc.title = "Application Window";
windowDesc.fullscreen = Fullscreen::eWindowed;
windowDesc.windowState = WindowState::eNormal;
windowDesc.decorations = Decorations::eFull;
windowDesc.resize = Resize::eAllowed;
windowDesc.floating = Floating::eRegular;
windowDesc.scaling = Scaling::eScaleToMonitor;
windowDesc.dpiScaleOverride = -1.0f;
windowDesc.cursorBlink = CursorBlink::eBlink;
return windowDesc;
}
const carb::events::EventType kEventTypeWindowCreated = 1;
const carb::events::EventType kEventTypeWindowDestroyed = 2;
const carb::events::EventType kEventTypeWindowStartup = 3;
const carb::events::EventType kEventTypeWindowShutdown = 4;
enum class WindowType
{
eVirtual,
eOs,
};
class IAppWindow : public carb::IObject
{
public:
/**
* Initializes the window taking parameters from carb::settings.
* @param name Name that identifies the window, can be nullptr.
* @return Whether the startup operation was completed successfully.
*/
virtual bool startup(const char* name) = 0;
/**
* Initializes the window with custom description.
* @return Whether the startup operation was completed successfully.
*/
virtual bool startupWithDesc(const char* name, const WindowDesc& desc) = 0;
/**
* Deinitializes the window.
* @return Whether the shutdown operation was completed successfully.
*/
virtual bool shutdown() = 0;
/**
* Call one update loop iteration on application.
* Normally, explicitly calling update is not required, as in presence of IApp interface,
* a subscription will be created that will be this function automatically.
*
* @ param dt Time elapsed since previous call. If <0 application ignores passed value and measures elapsed time
* automatically.
*/
virtual void update(float dt = -1.0f) = 0;
/**
* Returns the Carbonite window the editor is working with, or nullptr if headless.
* @return Carbonite window the editor is working with, or nullptr if headless.
*/
virtual carb::windowing::Window* getWindow() = 0;
/**
* @return The event stream that fires events on window resize.
*/
virtual carb::events::IEventStream* getWindowResizeEventStream() = 0;
/**
* @return The event stream that fires events on window close.
*/
virtual carb::events::IEventStream* getWindowCloseEventStream() = 0;
/**
* @return The event stream that fires events on window move.
*/
virtual carb::events::IEventStream* getWindowMoveEventStream() = 0;
/**
* @return The event stream that fires events on window DPI scale change.
* Content scale event stream provides DPI and "real DPI". The first one is affected by the DPI override, while
* the second one is raw hardware DPI induced this event.
*/
virtual carb::events::IEventStream* getWindowContentScaleEventStream() = 0;
/**
* @return The event stream that fires events on window drag-n-drop events.
*/
virtual carb::events::IEventStream* getWindowDropEventStream() = 0;
/**
* @return The event stream that fires events on window focus change.
*/
virtual carb::events::IEventStream* getWindowFocusEventStream() = 0;
/**
* @return The event stream that fires events on window minimize events.
*/
virtual carb::events::IEventStream* getWindowMinimizeEventStream() = 0;
/**
* Sets fullscreen state of editor Window.
*
* @param fullscreen true to set Editor Window to fullscreen.
*/
virtual void setFullscreen(bool fullscreen) = 0;
/**
* Gets the fullscreen state of editor Window.
*
* @return true if Editor is fullscreen.
*/
virtual bool isFullscreen() = 0;
/**
* Resizes the window.
*
* @param width The width of the window.
* @param height The height of the window.
*/
virtual void resize(uint32_t width, uint32_t height) = 0;
/**
* @return window width.
*/
virtual uint32_t getWidth() = 0;
/**
* @return window height.
*/
virtual uint32_t getHeight() = 0;
/**
* @return window size.
*/
virtual carb::Uint2 getSize() = 0;
/**
* Moves the window.
*
* @param x The x coordinate of the window.
* @param y The y coordinate of the window.
*/
virtual void move(int x, int y) = 0;
/**
* @return window position.
*/
virtual carb::Int2 getPosition() = 0;
/**
* @return UI scale multiplier that is applied on top of the OS DPI scale.
*/
virtual float getUiScaleMultiplier() const = 0;
/**
* Sets the UI scale multiplier that is applied on top of OS DPI scale.
*
* @param uiScaleCoeff UI scale coefficient.
*/
virtual void setUiScaleMultiplier(float uiScaleMultiplier) = 0;
/**
* @return UI scale. Includes UI scale multiplier and OS DPI scale.
*/
virtual float getUiScale() const = 0;
/**
* Gets current action mapping set settings path.
*
* @return action mapping set settings path.
*/
virtual const char* getActionMappingSetPath() = 0;
/**
* Gets the keyboard associated with the window.
*
* @return The window keyboard.
*/
virtual carb::input::Keyboard* getKeyboard() = 0;
/**
* Gets the mouse associated with the window.
*
* @return The window mouse.
*/
virtual carb::input::Mouse* getMouse() = 0;
/**
* Gets one of the gamepads available.
*
* @return The window gamepad or nullptr if index is invalid.
*/
virtual carb::input::Gamepad* getGamepad(size_t index) = 0;
/**
* @return Window title.
*/
virtual const char* getTitle() = 0;
/**
* @return DPI scale.
*/
virtual float getDpiScale() const = 0;
/**
* Sets the DPI scale override. Negative value means no override.
*/
virtual void setDpiScaleOverride(float dpiScaleOverride) = 0;
/**
* @return DPI scale override.
*/
virtual float getDpiScaleOverride() const = 0;
/**
* Sets the forced rejecting of all input events from a certain device type.
*/
virtual void setInputBlockingState(carb::input::DeviceType deviceType, bool shouldBlock) = 0;
/**
* @return whether the input for a certain device types is being blocked.
*/
virtual bool getInputBlockingState(carb::input::DeviceType deviceType) const = 0;
void broadcastInputBlockingState(bool shouldBlock)
{
for (size_t i = 0; i < (size_t)carb::input::DeviceType::eCount; ++i)
{
setInputBlockingState((carb::input::DeviceType)i, shouldBlock);
}
}
/**
* @brief Virtual/OS window
*/
virtual WindowType getWindowType() const = 0;
/**
* @return True if cursor (caret) blinks in input fields.
*/
virtual bool getCursorBlink() const = 0;
/**
* Gets the text from the clipboard associated with the window.
*
* @return The text in the window's clipboard.
*/
virtual const char* getClipboard() = 0;
/**
* Sets the text in the clipboard associated with the window.
*/
virtual void setClipboard(const char* text) = 0;
/**
* Maximize the editor window.
*/
virtual void maximizeWindow() = 0;
/**
* Restore the editor window (exit maximize/minimize).
*/
virtual void restoreWindow() = 0;
/**
* Gets the maxinized state of editor Window.
*
* @return true if Editor is maximized.
*/
virtual bool isMaximized() = 0;
/**
* @brief Allows to replace the keyboard.
*
* @param keyboard the keyboard this AppWindow should follow.
*/
virtual void setKeyboard(carb::input::Keyboard* keyboard) = 0;
};
using IAppWindowPtr = carb::ObjectPtr<IAppWindow>;
class IAppWindowFactory
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::IAppWindowFactory", 2, 4);
/**
* Create new application window.
*/
IAppWindowPtr createWindowFromSettings();
virtual IAppWindow* createWindowPtrFromSettings() = 0;
virtual void destroyWindowPtr(IAppWindow* appWindow) = 0;
/**
* Set and get default application window.
*/
virtual IAppWindow* getDefaultWindow() = 0;
virtual void setDefaultWindow(IAppWindow*) = 0;
virtual size_t getWindowCount() = 0;
virtual IAppWindow* getWindowAt(size_t index) = 0;
virtual void startupActionMappingSet() = 0;
virtual void shutdownActionMappingSet() = 0;
virtual carb::input::ActionMappingSet* getActionMappingSet() const = 0;
virtual bool startup() = 0;
virtual bool shutdown() = 0;
virtual carb::events::IEventStream* getWindowCreationEventStream() = 0;
virtual IAppWindow* getAppWindowFromHandle(int64_t appWindowHandle) = 0;
IAppWindowPtr createWindowByType(WindowType windowType);
virtual IAppWindow* createWindowPtrByType(WindowType windowType) = 0;
};
inline IAppWindowPtr IAppWindowFactory::createWindowFromSettings()
{
return carb::stealObject(this->createWindowPtrFromSettings());
}
inline IAppWindowPtr IAppWindowFactory::createWindowByType(WindowType windowType)
{
return carb::stealObject(this->createWindowPtrByType(windowType));
}
inline IAppWindow* getDefaultAppWindow()
{
IAppWindowFactory* factory = carb::getCachedInterface<IAppWindowFactory>();
return factory ? factory->getDefaultWindow() : nullptr;
}
}
}
| 12,891 | C | 28.10158 | 116 | 0.681949 |
omniverse-code/kit/include/omni/kit/IConsole.h | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//
#pragma once
#include <carb/Interface.h>
namespace omni
{
namespace kit
{
/**
* Defines the interface for ScriptEditor Window.
*/
struct IConsole
{
CARB_PLUGIN_INTERFACE("omni::kit::IConsole", 1, 0);
void(CARB_ABI* showHideWindow)(void* window, bool visible);
void(CARB_ABI* execCommand)(const std::string&);
};
}
}
| 768 | C | 25.51724 | 77 | 0.747396 |
omniverse-code/kit/include/omni/kit/IViewport.h | // Copyright (c) 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/Interface.h>
#include <omni/kit/IExtensionWindow.h>
#include <omni/kit/ViewportTypes.h>
namespace omni
{
namespace kit
{
/**
* Defines the interface for Viewport Window.
*/
struct IViewport
{
CARB_PLUGIN_INTERFACE("omni::kit::IViewport", 1, 0);
/**
* Gets a ViewportWindow instance from its ExtensionWindowHandle.
*
* @param handle The ExtensionWindowHandle. Pass nullptr to get the first available viewport (in creation order).
* @return ViewportWindow instance associated with the ExtensionWindowHandle.
*/
IViewportWindow*(CARB_ABI* getViewportWindow)(const ExtensionWindowHandle handle);
/**
* Creates a viewport window.
*
* TODO: add @param name (optional) The name of the viewport.
* If no name is specified the default names are Viewport, Viewport_2, etc.
* @return the viewport window count
*/
ExtensionWindowHandle(CARB_ABI* createViewportWindow)(/* TODO support: const char* name */);
/**
* Destroys a viewport window.
*
* @param handle The window handle to be destroyed.
* @return true if window is destroyed, false if not.
*/
bool(CARB_ABI* destroyViewportWindow)(const ExtensionWindowHandle viewportWindow);
/**
* Gets a ViewportWindow's ExtensionWindowHandle from its name.
*
* @param name the window name to retrieve an ExtensionWindowHandle for.
* @return ExtensionWindowHandle associated with the window name.
*/
ExtensionWindowHandle(CARB_ABI* getViewportWindowInstance)(const char* name);
/**
* Gets a ViewportWindow name from its ExtensionWindowHandle.
*
* @param handle The ExtensionWindowHandle. Pass nullptr to get the first available viewport (in creation order).
* @return ViewportWindow name associated with the ExtensionWindowHandle.
*/
const char*(CARB_ABI* getViewportWindowName)(const ExtensionWindowHandle handle);
/**
* Gets the number of viewport windows currently open
*
* @return the viewport window count
*/
size_t(CARB_ABI* getViewportWindowInstanceCount)();
/**
* Returns a list of all open viewport window handles
*
* @param viewportWindowList An array of viewport window handles
*
* @param count number of viewport window handles to retrieve
*
* @remarks It is up to the caller to allocate memory for the viewport
* list, using getViewportWindowInstanceCount() to determine the list
* size.
* The call will fail if count is larger than the number of
* viewport windows, or if viewportWindowList is NULL.
*
* @return true if successful, false otherwise
*/
bool(CARB_ABI* getViewportWindowInstances)(ExtensionWindowHandle* viewportWindowList, size_t count);
/**
* Add a viewport drop helper
* Returns the current drop helper node.
*
* @param dropHelper Specified the drop helper.
*/
DropHelperNode*(CARB_ABI* addDropHelper)(const DropHelper& dropHelper);
/**
* Remove a viewport drop helper
*
* @param node Specified the drop helper node to remove.
*/
void(CARB_ABI* removeDropHelper)(const DropHelperNode* node) = 0;
};
struct IViewportAddOn
{
CARB_PLUGIN_INTERFACE("omni::kit::IViewportAddOn", 0, 1);
void* (CARB_ABI* getCarbRendererContext)();
};
}
}
| 3,857 | C | 32.547826 | 117 | 0.693803 |
omniverse-code/kit/include/omni/kit/Wildcard.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 Wildcard utilities for omni.kit.app
#pragma once
#include <regex>
#include <string>
#include <unordered_set>
namespace omni
{
namespace kit
{
/**
* Defines the wildcard class.
*
* @warning This class uses `std::regex` which can be performance intensive. Consider using the functions in
* \ref omni::str instead.
*/
class Wildcard
{
public:
/**
* Sets the wildcard string.
*
* After this is set, call \ref isMatching() to determine if a string matches the wildcard pattern.
*
* @param pattern The wildcard pattern string to set.
*/
void setPatternString(const char* pattern)
{
// Special regex character
static const std::unordered_set<char> kSpecialCharacters = { '.', '^', '$', '|', '(', ')', '[',
']', '{', '}', '*', '+', '?', '\\' };
std::string expression = "^.*";
size_t len = strlen(pattern);
char prev_char = ' ';
for (size_t i = 0; i < len; i++)
{
const char character = pattern[i];
switch (character)
{
case '?':
expression += '.';
break;
case ' ':
expression += ' ';
break;
case '*':
if (i == 0 || prev_char != '*')
{
// make sure we don't have continuous * which will make std::regex_search super heavy, leading
// to crash
expression += ".*";
}
break;
default:
if (kSpecialCharacters.find(character) != kSpecialCharacters.end())
{
// Escape special regex characters
expression += '\\';
}
expression += character;
}
prev_char = character;
}
expression += ".*$";
m_expression = expression;
buildRegex();
}
/**
* Tests a string against the wildcard to see if they match.
*
* @param str The string to be tested.
* @retval true the string matches the wildcard
* @retval false the string does not match the wildcard
*/
bool isMatching(const char* str) const
{
return std::regex_search(str, m_wildcardRegex);
}
/**
* Sets if the wildcard should be case sensitive.
*
* The default is false (case insensitive).
*
* @param sensitive `true` if the wildcard should be case sensitive; `false` to be case insensitive
*/
void setCaseSensitive(bool sensitive)
{
if (m_caseSensitive != sensitive)
{
m_caseSensitive = sensitive;
buildRegex();
}
}
private:
void buildRegex()
{
if (m_expression.length())
{
auto flags = std::regex_constants::optimize;
if (!m_caseSensitive)
{
flags |= std::regex_constants::icase;
}
m_wildcardRegex = std::regex(m_expression, flags);
}
}
std::string m_expression;
std::regex m_wildcardRegex;
bool m_caseSensitive = false;
};
} // namespace kit
} // namespace omni
| 3,827 | C | 27.781955 | 118 | 0.51999 |
omniverse-code/kit/include/omni/kit/ISearch.h | // Copyright (c) 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/Interface.h>
#include <carb/events/IEvents.h>
namespace omni
{
namespace kit
{
const carb::events::EventType kEventSearchFinished = CARB_EVENTS_TYPE_FROM_STR("SEARCH_FINISHED");
/**
* Defines an interface for the search service plugin.
*
* This plugin handles communication between the content window and the search service python client.
*/
struct ISearch
{
CARB_PLUGIN_INTERFACE("omni::kit::search::ISearch", 1, 0);
/**
* Attempt to discover the search service
*
* @param url host url
*/
void(CARB_ABI* tryConnection)(const char* url);
/**
* Return true if we have discovered the search service at this host url
*
* @param url host url
* @return True if found
*/
bool(CARB_ABI* isConnected)(const char* url);
/**
* Set connection status (called from python)
*
* @param hostName host Name (not full url)
* @param isConnected true if connected, false if not
*/
void(CARB_ABI* setConnection)(const char* hostName, bool isConnected);
/**
* Perform a recursive file and tag search
*
* @param query The search query.
* @param parent The parent url to search, including the host name.
*/
void(CARB_ABI* recursiveSearch)(const char* query, const char* parent);
/**
* Status of search plugin connection. Returns true if connection attempt is pending.
*
* @param url The host url
* @return False if search is ready or unavailable. True if a connection attempt is pending.
*/
bool(CARB_ABI* connectionPending)(const char* url);
/**
* Status of search
*
* @return True if search is ongoing.
*/
bool(CARB_ABI* isSearching)();
/**
* Set status of search (called from python)
*
* @param isSearching True if searching.
*/
void(CARB_ABI* setSearching)(bool isSearching);
/**
* Add a search result to the internal cache.
*
* @param query The search query
* @param result The path to a file matching the query
* @param path The parent url
*/
void(CARB_ABI* addResult)(const char* query, const char* result, const char* path);
/**
* Get all the results from a query from the cache. Call clearMemory afterwards to cleanup.
*
* @param query The search query
* @param path The parent url
* @param nResults output: number of results.
* @return list of result paths
*/
char**(CARB_ABI* populateResults)(const char* query, const char* path, size_t* nResults);
/**
* clear memory from populateResults
*
* @param results Memory to clear
* @param nResults Number of results from populateResults
*/
void(CARB_ABI* clearMemory)(char** results, size_t nResults);
/**
* Search events occur when the search is finished.
*
* @return Search event stream
*/
carb::events::IEventStream*(CARB_ABI* getSearchEventStream)();
/**
* Shutdown the plugin
*
*/
void(CARB_ABI* shutdown)();
};
}
}
| 3,520 | C | 27.168 | 101 | 0.653977 |
omniverse-code/kit/include/omni/kit/IAppMessageBox.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 Message box interface for omni.kit.app
#pragma once
#include "../../carb/Interface.h"
namespace omni
{
namespace kit
{
//! Message box type.
//! @see IAppMessageBox::show()
enum class MessageBoxType
{
eInfo, //!< Informational
eWarning, //!< Warning
eError, //!< Error
eQuestion //!< Question
};
//! Buttons to place on the message box.
enum class MessageBoxButtons
{
eOk, //!< Only an "Ok" button should be presented
eOkCancel, //!< Both "Ok" and "Cancel" buttons should be presented
eYesNo //!< Both "Yes" and "No" buttons should be presented
};
//! Message box user response.
enum class MessageBoxResponse
{
eOk, //!< User pressed "Ok" button
eCancel, //!< User pressed "Cancel" button
eYes, //!< User pressed "Yes" button
eNo, //!< User pressed "No" button
eNone, //!< User pressed "Ok" button when that was the only choice
eError //!< An error occurred
};
//! Interface for producing an OS-specific modal message box.
class IAppMessageBox
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::IAppMessageBox", 1, 1);
/**
* Shows an OS specific modal message box.
*
* @note This is a blocking call that will return user response to the message box. The thread that calls it will be
* blocked until the user presses a button.
* @param message The message to display
* @param title The title of the message box
* @param type The \ref MessageBoxType to display
* @param buttons The \ref MessageBoxButtons to present
* @returns A \ref MessageBoxResponse value based on the button that the user pressed, or
* \ref MessageBoxResponse::eError if an error occurred.
*/
virtual MessageBoxResponse show(const char* message,
const char* title,
MessageBoxType type,
MessageBoxButtons buttons) = 0;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inline Functions //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace kit
} // namespace omni
| 2,790 | C | 32.22619 | 120 | 0.585305 |
omniverse-code/kit/include/omni/kit/ViewportTypes.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.
//
#pragma once
#include <carb/events/EventsUtils.h>
namespace carb
{
struct Double4x4
{
double m[16];
};
namespace renderer
{
struct Renderer;
struct Context;
}
namespace scenerenderer
{
struct SceneRenderer;
struct Context;
}
}
namespace rtx
{
namespace resourcemanager
{
class RpResource;
}
}
namespace carb
{
namespace sensors
{
enum class SensorType;
}
namespace renderer
{
enum class FrameDataType;
}
}
namespace omni
{
namespace usd
{
using TokenH = uint64_t;
typedef int32_t ViewportHandle;
namespace hydra
{
enum class EngineCreationFlags : uint32_t;
}
}
namespace kit
{
typedef uint64_t SubscriptionId;
constexpr uint64_t kInvalidSubscriptionId = 0xFFFF'FFFF'FFFF'FFFFULL;
enum class ViewportMenuAlignment
{
eTopLeft,
eTopRight,
eCount
};
typedef bool (*CheckCameraOverrideFn)(void* userdata);
typedef bool (*ApplyCameraOverrideFn)(carb::Double4x4& worldToView,
carb::Double3& translate,
carb::Double2& rotate,
void* userdata);
typedef void (*ResetCameraOverrideFn)(void* userdata);
typedef void (*OnQueriedNextPickedWorldPositionFn)(const carb::Double3* worldPos, void* userData);
struct CameraOverrideDesc
{
CheckCameraOverrideFn checkCameraOverrideActive;
ApplyCameraOverrideFn applyCameraOverride;
ResetCameraOverrideFn resetCameraOverride;
void* userdata;
};
enum class ViewportPrimReferencePoint
{
eBoundBoxCenter,
eBoundBoxLeft,
eBoundBoxRight,
eBoundBoxTop,
eBoundBoxBottom
};
struct DropHelper
{
bool pickable;
bool addOutline;
void* userPointer;
bool(CARB_ABI* onDropAccepted)(const char* url, void* userPointer);
std::string(CARB_ABI* onDrop)(
const char* url, const char* target, const char* viewport_name, const char* context_name, void* userPointer);
void(CARB_ABI* onPick)(const char* url, const char* target, const char* context_name, void* userPointer);
};
struct DropHelperNode
{
bool accepted;
DropHelper dropHelper;
};
// a temporary set of overrides to make XR's life easier
// TODO - further cleanup
struct ViewportWindowXROverrideDesc
{
bool disableGizmo;
const char* resolutionString;
const char** additionalMessages;
size_t additionalMessagesCount;
bool disableViewportResolutionOverride;
};
class IViewportWindow
{
public:
/**
* Setting path to retrieve viewport display options
*/
static const char* const kViewportDisplayOptionsPath;
/**
* Defines viewport element visibility flags
*/
using ShowFlags = uint32_t;
static const ShowFlags kShowFlagNone = 0;
static const ShowFlags kShowFlagFps = 1 << 0;
static const ShowFlags kShowFlagAxis = 1 << 1;
static const ShowFlags kShowFlagLayer = 1 << 2;
static const ShowFlags kShowFlagResolution = 1 << 3;
static const ShowFlags kShowFlagTimeline = 1 << 4;
static const ShowFlags kShowFlagCamera = 1 << 5;
static const ShowFlags kShowFlagGrid = 1 << 6;
static const ShowFlags kShowFlagSelectionOutline = 1 << 7;
static const ShowFlags kShowFlagLight = 1 << 8;
static const ShowFlags kShowFlagSkeleton = 1 << 9;
static const ShowFlags kShowFlagMesh = 1 << 10;
static const ShowFlags kShowFlagPathTracingResults = 1 << 11;
static const ShowFlags kShowFlagAudio = 1 << 12;
static const ShowFlags kShowFlagDeviceMemory = 1 << 13;
static const ShowFlags kShowFlagHostMemory = 1 << 14;
static const ShowFlags kShowFlagAll = kShowFlagFps | kShowFlagAxis | kShowFlagLayer | kShowFlagResolution |
kShowFlagPathTracingResults | kShowFlagTimeline | kShowFlagCamera |
kShowFlagGrid | kShowFlagSelectionOutline | kShowFlagLight |
kShowFlagSkeleton | kShowFlagMesh | kShowFlagAudio |
kShowFlagDeviceMemory | kShowFlagHostMemory;
/**
* Setting path to retrieve gizmo options
*/
static const char* const kViewportGizmoScalePath;
static const char* const kViewportGizmoConstantScaleEnabledPath;
static const char* const kViewportGizmoConstantScalePath;
static const char* const kViewportGizmoBillboardStyleEnabledPath;
typedef bool (*OnMenuDrawSubmenuFn)();
/**
* Destructor.
*/
virtual ~IViewportWindow() = default;
/**
* Adds a menu item to the viewport, those are currently only Top Left aligned or Top Right aligned.
* We currently only support Button type from the UI Toolkit
* Because the caller of this function might not have access to the UI Class directly a void * is used
* The function call does sanity check on the * and will handle wrong * properly.
*
* @param name is the name of the button.
* @param button is a pointer to a Button class.
* @param alignment is the alignment of the button either Left or Right.
*/
virtual void addMenuButtonItem(const char* name, void* button, ViewportMenuAlignment alignment) = 0;
/**
* Removes the bottom from the menu, the name is the Key in the named array.
*
* @param name the name of the button to remove
* @param alignment the alignment of the button, name are unique only per Menu
*/
virtual void removeMenuButtonItem(const char* name, ViewportMenuAlignment alignment) = 0;
/**
* Adds a menu to the show/hide type submenu
* @param name the name of the submenu
* @param drawMenuCallback draw menu function pointer
*/
virtual void addShowByTypeSubmenu(const char* name,
OnMenuDrawSubmenuFn drawMenuCallback,
OnMenuDrawSubmenuFn resetMenuCallback,
OnMenuDrawSubmenuFn isResetMenuCallback) = 0;
/**
* Removes a menu to the show/hide type submenu
* @param name the name of the submenu
*/
virtual void removeShowByTypeSubmenu(const char* name) = 0;
/**
* Posts a toast message to viewport.
*
* @param message The message to be posted.
*/
virtual void postToast(const char* message) = 0;
/**
* Request a picking query for the next frame.
*/
virtual void requestPicking() = 0;
/**
* Enable picking.
*
* @param enable Enable/disable picking.
*/
virtual void setEnabledPicking(bool enable) = 0;
/**
* Is picking enabled.
*
* @return True if picking is enabled.
*/
virtual bool isEnabledPicking() const = 0;
/**
* Gets the EventStream for in-viewport draw event.
*
* @return EventStream for in-viewport draw event.
*/
virtual carb::events::IEventStreamPtr getUiDrawEventStream() = 0;
/**
* Query the visibility of the window.
*
* @return visibility of the window.
*/
virtual bool isVisible() const = 0;
/**
* Sets the visibility of the window.
*
* @param visible true to show the window, false to hide the window.
*/
virtual void setVisible(bool visible) = 0;
/**
* Query the window name.
*
* @return the window name
*/
virtual const char* getWindowName() = 0;
/**
* Sets the active camera in the viewport to a USD camera.
*
* @param path Path of the camera prim on the stage.
*/
virtual void setActiveCamera(const char* path) = 0;
/**
* Gets the active camera in the viewport.
*
* @return Path of the camera prim on the stage.
*/
virtual const char* getActiveCamera() const = 0;
/**
* Sends signal to the currently activecamera controller to focus on target (either selected scene primitive,
* or the whole scene).
*/
virtual void focusOnSelected() = 0;
/**
* Gets camera's target.
*
* @param path The path of the Camera prim.
* @param target The target of the camera to be written to.
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool getCameraTarget(const char* path, carb::Double3& target) const = 0;
/**
* Gets prim's clipping pos in current active camera.
* It's calculated with prim_pos * view_matrix_of_camera * projection_matrix_of_camera.
* The x or y pos of returned value is [-1, 1]. In xy plane, y is facing up and x is facing right,
* which is unliking window coordinates that y is facing down and the range of xy is [0, 1]x[0, 1].
* and the z pos is [0, 1], where z is in reverse form that 0 is the far plane, and 1 is the near plane.
*
* @param path The path of the prim.
* @param pos The offset pos of the prim to be written to.
* @param referencePoint The reference point of prim to be calculated for clipping pos.
* By default, it's the center of the prim bound box.
* @return true on success, false if prim doesn't exist at path. Or
* prim's position is out of the active camera's view frustum.
*/
virtual bool getPrimClippingPos(
const char* path,
carb::Double3& pos,
ViewportPrimReferencePoint referencePoint = ViewportPrimReferencePoint::eBoundBoxCenter) const = 0;
/**
* Sets camera's target.
*
* @param path The path of the Camera prim.
* @param target The target of the camera to be set to.
* @param rotate true to keep position but change orientation and radius (camera rotates to look at new target).
* false to keep orientation and radius but change position (camera moves to look at new target).
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool setCameraTarget(const char* path, const carb::Double3& target, bool rotate) = 0;
/**
* Gets camera's position.
*
* @param path The path of the Camera prim.
* @param position The position of the camera to be written to.
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool getCameraPosition(const char* path, carb::Double3& position) const = 0;
/**
* Sets camera's position.
*
* @param path The path of the Camera prim.
* @param position The position of the camera to be set to.
* @param rotate true to keep position but change orientation and radius (camera moves to new position while still
* looking at the same target).
* false to keep orientation and radius but change target (camera moves to new position while keeping
the relative position of target unchanged).
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool setCameraPosition(const char* path, const carb::Double3& position, bool rotate) = 0;
/**
* Gets camera's forward vector.
*
* @param path The path of the Camera prim.
* @param vector The forward vector of the camera to be written to.
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool getCameraForward(const char* path, carb::Double3& vector) const = 0;
/**
* Gets camera's right vector.
*
* @param path The path of the Camera prim.
* @param vector The right vector of the camera to be written to.
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool getCameraRight(const char* path, carb::Double3& vector) const = 0;
/**
* Gets camera's up vector.
*
* @param path The path of the Camera prim.
* @param vector The up vector of the camera to be written to.
* @return true on success, false if camera doesn't exist at path.
*/
virtual bool getCameraUp(const char* path, carb::Double3& vector) const = 0;
/**
* Gets camera move speed when pilot in viewport with camera control.
*
* @return camera move speed.
*/
virtual double getCameraMoveVelocity() const = 0;
/**
* Sets camera move speed when pilot in viewport with camera control.
*
* @param velocity camera move speed.
*/
virtual void setCameraMoveVelocity(double velocity) = 0;
/**
* Enables or disables gamepad for camera controller.
*
* @param enabled true to enable gamepad, false to disable.
*/
virtual void setGamepadCameraControl(bool enabled) = 0;
/**
* Temporary workaround for fullscreen mode. DO NOT USE directly.
*/
virtual void draw(const char* windowName, float elapsedTime) = 0;
/**
* Toggles Visibility settings. Lights/Camera/Skeleton/Grid/HUD etc.
*/
virtual void toggleGlobalVisibilitySettings() = 0;
/**
* Gets the mouse event stream
*
* @returns The mouse event stream
*/
virtual carb::events::IEventStream* getMouseEventStream() = 0;
/**
* Gets the viewport window rect
*
* @returns The viewport window rect
*/
virtual carb::Float4 getViewportRect() const = 0;
virtual carb::Int2 getViewportRenderResolution() const = 0;
/**
* Gets if camera is being manipulated.
*
* @returns true if camera is being manipulated.
*/
virtual bool isManipulatingCamera() const = 0;
/**
* Gets if viewport is being focused.
*
* @returns true if viewport is being focused.
*/
virtual bool isFocused() const = 0;
/**
* Allow camera motion to be overriden
*
* @returns a subscriptionId to remove override with
*/
virtual SubscriptionId addCameraOverride(const CameraOverrideDesc& cameraOverride) = 0;
/**
* Remove override
*/
virtual void removeCameraOverride(SubscriptionId subscription) = 0;
/**
* Sets the hydra engine to use for rendering
*
*/
virtual void setActiveHydraEngine(const char* hydraEngine) = 0;
/**
* Sets the tick rate for hydra engine used during rendering
* -1 means unlimited
*/
virtual void setHydraEngineTickRate(uint32_t tickRate) = 0;
/**
* Gets the render product prim path
*
*/
virtual const char* getRenderProductPrimPath() = 0;
/**
* Sets the render product prim path
*
*/
virtual void setRenderProductPrimPath(const char* path) = 0;
/**
* Enables an AOV on the viewport
*
* @param aov name of the AOV to add.
* @param verifyAvailableBeforeAdd if true add the AOV only if it belong to the list of available AOVs.
* @returns true if the AOV is added or already exists.
*/
virtual bool addAOV(omni::usd::TokenH aov, bool verifyAvailableBeforeAdd) = 0;
/**
* Disables an AOV on the viewport
*
* @returns true if the AOV is removed.
*/
virtual bool removeAOV(omni::usd::TokenH aov) = 0;
/**
* Returns all the AOVs output by the viewport
*
* @returns true if the AOV is removed.
*/
virtual const omni::usd::TokenH* getAOVs(uint32_t& outNumAovs) = 0;
/**
* Sets the window size
*/
virtual void setWindowSize(uint32_t w, uint32_t h) = 0;
/**
* Sets the window position
*/
virtual void setWindowPosition(uint32_t x, uint32_t y) = 0;
/**
* Sets the texture resolution. This overrides window size when viewport resolution is selected
* Pass -1,-1 to undo override
*/
virtual void setTextureResolution(int32_t x, int32_t y) = 0;
/**
* @returns current viewport's resource specified by the AOV (null if non-existent)
*/
virtual rtx::resourcemanager::RpResource* getDrawableResource(omni::usd::TokenH aov) = 0;
/**
* @returns whether the AOV is available on the current viewport
*/
virtual bool isDrawableAvailable(omni::usd::TokenH aov) = 0;
/**
* @returns fps of viewport's drawable
*/
virtual float getFps() = 0;
/**
* @ Calls the callback on next mouse click and passes the world position under mouse.
*
* @param fn callback function when world position is fetched after mouse click. The position can be nullptr if
* clicked on black background.
* @param userData user data to be passed back to fn when callback is triggered.
*/
virtual void queryNextPickedWorldPosition(OnQueriedNextPickedWorldPositionFn fn, void* userData) = 0;
/**
* Returns the current frame data based on the requested feature, such as profiler data.
* If frame is not finished processing the data, the result of the previous frame is returned.
* For multi-GPU, query the device count and then set deviceIndex to the desired device index.
*
* @param dataType Specified the requested data type to return.
* @param deviceIndex The index of GPU device to get the frame data from. Set to zero in Single-GPU mode.
* You may query the number of devices with FrameDataType::eGpuProfilerDeviceCount.
* deviceIndex is ignored when the type is set to eGpuProfilerDeviceCount.
* @param data A pointer to the returned data. Returns nullptr for failures or eGpuProfilerDeviceCount.
* You may pass nullptr if you only need dataSize.
* @param dataSize The size of the returned data in bytes, the number of structures, or device count based on
* the dataType. For strings, it includes the null-termination.
*/
virtual void getFrameData(carb::renderer::FrameDataType dataType,
uint32_t deviceIndex,
void** data,
size_t* dataSize) = 0;
/**
* Checks if mouse is hovering over the viewport's content region, without being occluded by other UI elements.
*/
virtual bool isContentRegionHovered() const = 0;
/**
* Gets the hydra engine that is used for rendering.
*/
virtual const char* getActiveHydraEngine() = 0;
/* menu UI */
virtual void showHideWindow(bool visible) = 0;
virtual omni::usd::ViewportHandle getId() const = 0;
/**
* Get the picked world pos since last requested picking.
*
* @param outWorldPos picked world pos to be filled.
*
* @returns false if no picked pos is available.
*/
virtual bool getPickedWorldPos(carb::Double3& outWorldPos) = 0;
virtual bool getPickedGeometryHit(carb::Double3& outWorldPos, carb::Float3& outNormal) = 0;
virtual uint32_t getAvailableAovCount() const = 0;
virtual void getAvailableAovs(const char* outAovs[]) const = 0;
virtual const char* getUsdContextName() const = 0;
virtual void disableSelectionRect(bool enablePicking) = 0;
// A shim for XR until better paths for messages is ready
virtual void setXROverrideDesc(ViewportWindowXROverrideDesc xrOverrideDesc) = 0;
/**
* @returns scene renderer.
*/
virtual carb::scenerenderer::SceneRenderer* getSceneRenderer() = 0;
/**
* @ returns scene renderer context.
*/
virtual carb::scenerenderer::Context* getSceneRendererContext() = 0;
/**
* Sets the hydra engine flags for the hydra engine used to render this viewport
*/
virtual void setHydraEngineFlags(omni::usd::hydra::EngineCreationFlags flags) = 0;
};
}
}
| 19,832 | C | 31.24878 | 119 | 0.656263 |
omniverse-code/kit/include/omni/kit/ContentUiTypes.h | // Copyright (c) 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
namespace carb
{
namespace imgui
{
struct ImGui;
}
}
namespace omni
{
namespace kit
{
struct ContentWindowWidget;
class ContentExplorer;
using OnMenuItemClickedFn = void (*)(const char* menuPath, bool value, void* userData);
using OnMenuItemCheckFn = bool (*)(const char* contentUrl, void* userData);
using OnContentWindowToolButtonClickedFn = void (*)(const char* name, void* userData);
class IContentWindow
{
public:
/**
* Destructor.
*/
virtual ~IContentWindow() = default;
/**
* Query the visibility of the window.
*
* @return visibility of the window.
*/
virtual bool isVisible() const = 0;
/**
* Sets the visibility of the window.
*
* @param visible true to show the window, false to hide the window.
*/
virtual void setVisible(bool visible) = 0;
/**
* Navigates to a path.
*
* @param path The path to navigate to.
* @param changeSelection When true the path's parent directory will be expanded and leaf selected,
* when false the path itself will be expanded and nothing will be selected.
*/
virtual void navigateTo(const char* path, bool changeSelection = false) = 0;
/**
* Add context menu item to content window.
*
* @param menuItemName The name to the menu (e.g. "Open"), this name must be unique across context menu.
* @param tooltip The helper text.
* @param onMenuItemClicked The callback function called when menu item is clicked.
* @param userData The custom data to be passed back via callback function.
* @return true if success, false otherwise. When it returned with false,
* it means there is existing item that has the same name.
*/
virtual bool addContextMenu(const char* menuItemName,
const char* tooltip,
OnMenuItemClickedFn onMenuItemClicked,
void* userData) = 0;
/**
* Removes a context menu item in content window.
*
* @param menuItemName The name of the menu item to be removed.
*/
virtual void removeContextMenu(const char* menuItemName) = 0;
/**
* Add Icon menu item to content window.
* @param menuItemName The name to the menu (e.g. "Open"), this name must be unique across context menu.
* @param onMenuItemClicked The callback function called when menu item is clicked.
* @param userData The custom data to be passed back via callback function.
* @param onMenuItemCheck The callback function called when menu item is created. If the callback returns true, the
* menu item will not be created.
* @param userDataCheck The custom data to be passed back to onMenuItemCheck callback.
*/
virtual bool addIconMenu(const char* menuItemName,
OnMenuItemClickedFn onMenuItemClicked,
void* userData,
OnMenuItemCheckFn onMenuItemCheck,
void* userDataCheck) = 0;
/**
* Removes a Icon menu item in content window.
*
* @param menuItemName The name of the menu item to be removed.
*/
virtual void removeIconMenu(const char* menuItemName) = 0;
/**
* Refresh selected node of content window.
*/
virtual void refresh() = 0;
/**
* Adds tool button for content window, which locates at the left of search bar.
*
* @param name The name of the button, this name must be unique across tool bar of content window.
* @param toolTip The helper text.
* @param validDataSource If this is true, the button will only be enabled when a valid data source is selected.
* @param clickedFn The callback function called when button is clicked.
* @param userData The custom data to be passed back via callback function.
* @param priority The priority to sort tool buttons. It's sorted in ascending order.
* @return true if success, false otherwise. When it returned with false,
* it means there is existing item that has the same name.
*/
virtual bool addToolButton(const char* name,
const char* tooltip,
bool validDataSource,
OnContentWindowToolButtonClickedFn clickedFn,
void* userData,
int priority) = 0;
/**
* Removes tool button for content window.
*
* @param name Button name to be removed.
*/
virtual void removeToolButton(const char* name) = 0;
/**
* Gets current selected path protocol in content window.
*
* @return current selected path protocol in content window, (e.g. "" for local, or "omniverse:" for OV).
*/
virtual const char* getSelectedPathProtocol() const = 0;
/**
* Gets current selected directory in content window.
*
* @return current selected directory in content window, (e.g. "/Users/test/", or "E:/test/").
*/
virtual const char* getSelectedDirectoryPath() const = 0;
/**
* Gets current selected icon protocol in content window.
*
* @return current selected icon protocol in content window, (e.g. "" for local, or "omniverse:" for OV).
*/
virtual const char* getSelectedIconProtocol() const = 0;
/**
* Gets current selected icon in content window.
*
* @return current selected icon in content window, (e.g. "/Users/test/1.usd", or "E:/test/1.usd").
*/
virtual const char* getSelectedIconPath() const = 0;
};
}
}
| 6,103 | C | 35.771084 | 119 | 0.640669 |
omniverse-code/kit/include/omni/kit/IContentUi.h | // Copyright (c) 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/Interface.h>
#include <omni/kit/ContentUiTypes.h>
#include <omni/kit/IExtensionWindow.h>
namespace omni
{
namespace kit
{
/**
* Defines the interface for Content UI.
*/
class IContentUi
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::IContentUi", 0, 1);
/**
* Gets a ContentWindow instance from its ExtensionWindowHandle.
*
* @param handle The ExtensionWindowHandle. Pass nullptr to get the first available ContentWindow (in creation
* order).
* @return ContentWindow instance associated with the ExtensionWindowHandle.
*/
virtual IContentWindow* getContentWindow(const ExtensionWindowHandle handle) = 0;
/**
* Creates content window widget.
*
* @param width Width in pixel
* @param height Height in pixel
* @return ContentWindowWidget instance
*/
virtual ContentWindowWidget* createContentWindowWidget(uint32_t width, uint32_t height) = 0;
/**
* Destroys content window widget.
*
* @param widget ContentWindowWidget instance
*/
virtual void destroyContentWindowWidget(ContentWindowWidget* widget) = 0;
/**
* Refreshes content window widget.
*
* @param widget ContentWindowWidget instance
*/
virtual void refreshContentWindowWidget(ContentWindowWidget* widget) = 0;
/**
* Draws content window widget.
*
* @param widget ContentWindowWidget instance
* @param elapsedTime Time in seconds since last draw
*/
virtual void drawContentWindowWidget(ContentWindowWidget* widget, float elapsedTime) = 0;
/**
* Allocates buffer and fill buffer with selected tree node information.
*
* @param ContentWindowWidget instance
* @param protocol Path protocol (e.g., "", or "omniverse:"")
* @param realUrl Real path (e.g., e:/test for local, or /Users/test for OV)
* @param contentUrl Content path (e.g., /e/test for local, or /Users/test/ for OV)
*/
virtual void createSelectedTreeNodeBuffersFromContentWindowWidget(ContentWindowWidget* widget,
const char** protocol,
const char** realUrl,
const char** contentUrl) = 0;
/**
* Allocates buffer and fill buffer with selected file node information.
*
* @param ContentWindowWidget instance
* @param protocol Path protocol (e.g., "", or "omniverse:"")
* @param realUrl Real path (e.g., e:/test/test.txt for local, or /Users/test/test.txt for OV)
* @param contentUrl Content path (e.g., /e/test/test.txt for local, or /Users/test/test.txt for OV)
*/
virtual void createSelectedFileNodeBuffersFromContentWindowWidget(ContentWindowWidget* widget,
const char** protocol,
const char** realUrl,
const char** contentUrl) = 0;
/**
* Destroys allocated buffers.
*/
virtual void destroyBuffersFromContentWindowWidget(const char* protocol,
const char* realUrl,
const char* contentUrl) = 0;
/**
* Sets filter for content window.
*
* @param widget ContentWindowWidget instance
* @param filter File filter that supports regex (e.g., *.usd).
*/
virtual void setFilterForContentWindowWidget(ContentWindowWidget* widget, const char* filter) = 0;
/**
* Navigates to path.
*
* @param widget ContentWindowWidget instance
* @param path
*/
virtual void navigateContentWindowWidget(ContentWindowWidget* widget, const char* path) = 0;
/**
* Gets the download task status from download manager.
*
* @param[out] finishedFiles Number of finished files.
* @param[out] totalFiles Number of total files.
* @param[out] lastUrl Url of last downloaded file.
* return true if download is in progress, false if no file is being downloaded.
*/
virtual bool getDownloadTaskStatus(int32_t& finishedFiles, int32_t& totalFiles, const char*& lastUrl) = 0;
};
}
}
| 4,837 | C | 36.503876 | 114 | 0.620219 |
omniverse-code/kit/include/omni/kit/AssetUtils.h | // Copyright (c) 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/Framework.h>
#include <carb/datasource/DataSourceUtils.h>
#include <carb/datasource/IDataSource.h>
#include <carb/filesystem/IFileSystem.h>
#include <carb/logging/Log.h>
#include <vector>
namespace omni
{
namespace kit
{
/** Obtain a list of datasources for the local file system.
* @returns A vector of the local filesystem connections.
* This vector contains pairs where the first member is the first
* character of the filesystem name (on windows, this is the upper
* case DOS drive label; on Linux, this is '/') and the second member
* is the connection to that filesystem.
* None of the connections in the returned vector will be nullptr.
*
* @remarks This function is used to workaround a limitation with the datasource
* system that prevents DOS paths from being used, so each separate DOS
* drive needs to be registered as a separate connection.
* This function will be removed eventually when this deficiency is fixed.
*/
inline std::vector<std::pair<char, carb::datasource::Connection*>> getFilesystemConnections()
{
carb::filesystem::IFileSystem* fs = carb::getFramework()->acquireInterface<carb::filesystem::IFileSystem>();
carb::datasource::IDataSource* dataSource =
carb::getFramework()->acquireInterface<carb::datasource::IDataSource>("carb.datasource-omniclient.plugin");
std::vector<std::pair<char, carb::datasource::Connection*>> vec;
if (fs == nullptr || dataSource == nullptr)
return vec;
#if CARB_PLATFORM_WINDOWS
for (char drive = 'A'; drive <= 'Z'; drive++)
{
std::string drivePath = std::string(1, drive) + ":";
if (fs->exists(drivePath.c_str()))
{
carb::datasource::Connection* connection =
carb::datasource::connectAndWait(carb::datasource::ConnectionDesc{ drivePath.c_str() }, dataSource);
if (connection == nullptr)
{
CARB_LOG_ERROR("failed to get connection for drive %c", drive);
continue;
}
vec.push_back(std::make_pair(drive, connection));
}
}
#else
// Just add the root of the filesystem
carb::datasource::Connection* connection =
carb::datasource::connectAndWait(carb::datasource::ConnectionDesc{ "/" }, dataSource);
if (connection == nullptr)
CARB_LOG_ERROR("failed to get connection for the filesystem root");
else
vec.push_back(std::make_pair('/', connection));
#endif
return vec;
}
}
}
| 3,019 | C | 36.75 | 116 | 0.673733 |
omniverse-code/kit/include/omni/kit/KitUpdateOrder.h | // Copyright (c) 2019-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 Helpers for kit update ordering
*
* Kit's event subscribers order numbers, which control the execution order flow of the application were previously
* magic values scattered across dozens of extensions across multiple repositories. This centralizes it for now.
*
* This file defines a ordering that can be used to by extensions to have a deterministic execution flow.
*/
#pragma once
#include "../../carb/events/IEvents.h"
namespace omni
{
namespace kit
{
//! Namespace for kit update ordering values
namespace update
{
//! @defgroup updateorder Kit Update Ordering values
//! @todo Although it is good that these values are together, this is not the correct place for them. Many of the values
//! are specific to Omniverse applications that consume Carbonite but are not based in Carbonite. They should likely
//! be in a data-driven format such as a configuration file and instead referred to as names (i.e. using
//! \ref carb::RString) that can be mapped to a value, and/or documented somewhere central.
//! @{
//! Ordering of events within a \ref omni::kit::RunLoop::preUpdate event loop.
//! \see updateorder
enum PreUpdateOrdering : int32_t
{
eTelmetryInitialize = -50, //!< Initialize Telemetry profiling. Typically the first item in a frame.
eFabricBeginFrame = -20, //!< Initiate a Fabric frame.
eUnspecifiedPreUpdateOrder = carb::events::kDefaultOrder //!< Default pre-update order value
};
//! Ordering of events within a \ref omni::kit::RunLoop::update event loop.
//! \see updateorder
enum UpdateOrdering : int32_t
{
//! Checks for HydraEngine::render completion on GPU.
//!
//! 1. Pushes StageRenderingEvent::NewFrame
//! 2. Triggers renderingEventStream::pump
eCheckForHydraRenderComplete = -100,
//! Applies pending Timeline state changes
eUsdTimelineStateRefresh = -90,
//! asyncio.Future blocked awaiting (update loop begin)
//!
//! 1. IApp.next_pre_update_async
//! 2. UsdContext.next_frame_async / next_usd_async
ePythonAsyncFutureBeginUpdate = -50,
//! Enables execution of all python blocked by \ref ePythonAsyncFutureBeginUpdate
//!
//! Enable python execution blocked awaiting UsdContext::RenderingEventStream::Pump()
//! @see ePythonAsyncFutureBeginUpdate
ePythonExecBeginUpdate = -45,
//! Run OmniClient after python but before main simulation
eOmniClientUpdate = -30,
//! ITimeline wants to execute before \ref eUsdContextUpdate
eUsdTimelineUpdate = -20,
//! Core UsdUpdate execution
//!
//! 1. Update liveModeUpdate listeners
//! 2. triggers stageEventStream::pump
//! 3. MaterialWatcher::update
//! 4. IHydraEngine::setTime
//! 5. triggers IUsdStageUpdate::pump (see IUsdStageEventOrdering below)
//! 6. AudioManager::update
eUsdContextUpdate = -10,
//! Default update order value
//!
//! @note extras::SettingWrapper is hardcoded to \ref carb::events::kDefaultOrder which means this is when during
//! the main update cycle, event listeners for settings changes events will fire. There are a minimum of 60+ unique
//! setting subscription listeners in a default kit session.
eUnspecifiedUpdateOrder = carb::events::kDefaultOrder,
//! Trigger UI/ImGui Drawing
eUIRendering = 15,
//! Fabric Flush after eUsdContextUpdate
//! @see eUsdContextUpdate
eFabricFlush = 20,
//! Triggers HydraEngine::render
eHydraRendering = 30,
//! asyncio.Future blocked awaiting (update loop end)
//!
//! 1. IApp.next_update_async (legacy)
ePythonAsyncFutureEndUpdate = 50,
//! Enables execution of all python blocked by ePythonAsyncFutureEndUpdate and awaiting
//! UsdContext::StageEventStream::Pump.
ePythonExecEndUpdate = 100,
};
/*
* IApp.next_update_async() is the original model of python scripting kit, a preferred
* approach is either App.pre_update_async() and/or App.post_update_async(). Both can be used inside
* a single app tick, pseudo python code:
* While true:
* await omni.kit.app.get_app().pre_update_async()
* # Do a bunch of python scripting things before USD Update or hydra rendering is scheduled
* await omni.kit.app.get_app().post_update_async()
* # Do a bunch of python scripting things after USD Update & hydra rendering has been scheduled
*
* Alternatively use either just pre_update_async() or post_update_async() in python depending on whether you want your
* script to execute before USDUpdate or after.
*/
//! Ordering of events within a \ref omni::kit::RunLoop::postUpdate event loop.
//! \see updateorder
enum PostUpdateOrdering : int32_t
{
//! Release GPU resources held by previous frame.
eReleasePrevFrameGpuResources = -50,
//! asyncio.Future blocked awaiting (post update loop).
//!
//! 1. IApp.post_update_async (deprecates IApp.next_update_async).
ePythonAsyncFuturePostUpdate = -25,
//! Enables execution of all python blocked by \ref ePythonAsyncFuturePostUpdate.
ePythonExecPostUpdate = -10,
//! Default post-update order value.
eUnspecifiedPostUpdateOrder = carb::events::kDefaultOrder,
//! Kit App Factory Update.
eKitAppFactoryUpdate = eUnspecifiedPostUpdateOrder,
//! Kit App OS Update.
eKitAppOSUpdate = eUnspecifiedPostUpdateOrder,
//! Kit Internal Update.
eKitInternalUpdate = 100
};
#pragma push_macro("min")
#undef min
//! Ordering of events within a \ref omni::kit::RunLoop::postUpdate event loop.
//! \see updateorder
enum KitUsdStageEventOrdering : int32_t
{
//! USD File Operation Stage Event.
eKitUsdFileStageEvent = std::numeric_limits<carb::events::Order>::min() + 1,
//! Default File Stage event order.
eKitUnspecifiedUsdStageEventOrder = carb::events::kDefaultOrder,
};
#pragma pop_macro("min")
//! Ordering of USD Stage Update events during USD Context Update
//! \see eUsdContextUpdate, updateorder
enum IUsdStageEventOrdering : int32_t
{
eIUsdStageUpdateAnimationGraph = 0, //!< Hard-coded in separate non kit-sdk repro (gitlab)
eIUsdStageUpdatePinocchioPrePhysics = 8, //!< Hard-coded in separate non kit-sdk repro (gitlab)
eIUsdStageUpdateTensorPrePhysics = 9, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdateForceFieldsPrePhysics = 9, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysicsVehicle = 9, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysicsCCT = 9, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysicsCameraPrePhysics = 9, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysics = 10, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdateFabricPostPhysics = 11, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdateVehiclePostPhysics = 12, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdateForceFieldsPostPhysics = 12, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysicsCameraPostPhysics = 12, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePhysicsUI = 12, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdatePinocchioPostPhysics = 13, //!< Hard-coded in separate non kit-sdk repro (gitlab)
eIUsdStageUpdateOmnigraph = 100, //!< Defined inside kit-sdk
eIUsdStageUpdatePhysxFC = 102, //!< Hard-coded in separate non kit-sdk repro (perforce)
eIUsdStageUpdateDebugDraw = 1000, //!< Defined inside kit-sdk
eIUsdStageUpdateLast = 2000 //!< Must always be last when all prior StageUpdate events have been handled
};
//! @}
} // namespace update
} // namespace kit
} // namespace omni
| 8,269 | C | 39.539215 | 120 | 0.723546 |
omniverse-code/kit/include/omni/kit/ITagging.h | // Copyright (c) 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/Interface.h>
#include <carb/events/IEvents.h>
namespace carb
{
namespace datasource
{
struct IDataSource;
struct Connection;
}
}
namespace omni
{
namespace kit
{
const carb::events::EventType kEventGetTagsFinished = CARB_EVENTS_TYPE_FROM_STR("GET_TAGS_FINISHED");
const carb::events::EventType kEventTagQueryFinished = CARB_EVENTS_TYPE_FROM_STR("TAG_QUERY_FINISHED");
const carb::events::EventType kEventModifyTagFinished = CARB_EVENTS_TYPE_FROM_STR("MODIFY_TAG_FINISHED");
const carb::events::EventType kEventTagServiceConnected = CARB_EVENTS_TYPE_FROM_STR("TAG_SERVICE_CONNECTED");
/**
* Defines a tagging interface to a running tagging server.
*/
struct ITagging
{
CARB_PLUGIN_INTERFACE("omni::kit::ITagging", 2, 0);
/**
* Check connection to tagging service.
*
* @return true if connected to tagging service.
*/
bool(CARB_ABI* isConnected)(const char* host_url);
/**
* Sends a list of urls as a single query to the tagging server. Results can be found by calling getTagsForUrl.
* When the request returns, an event of type kEventGetTagsFinished will be dispatched.
*
* @param urls An array of usd file urls sent to the tagging server.
* @param nUrls The number of urls.
*/
void(CARB_ABI* getTags)(const char** urls, const size_t nUrls);
/**
* Sends a url & query as a recursive query to the tagging server. The query is a tag that will be matched
* with all the usd files in the url. If url is a folder, then all files in that folder and subfolders will
* be checked by the tagging service. Results can be found by calling getTagsForUrl.
* When the request returns, an event of type kEventTagQueryFinished will be dispatched.
*
* @param query
* @param url
*/
void(CARB_ABI* queryTags)(const char* query, const char* url);
/**
* Returns the tags for the usd file at the given url. Use getTags or queryTags before calling this function.
*
* @param url to the usd file that may have tags.
* @param nTags the number of tags as an output
* @param filterExcluded true if we should compare system tags and remove excluded ones
* @param resourceBusy set to true if we are blocked by another thread. This prevents ui blocking.
* @return A list of tags as a pointer. This must be freed with clearTagsMemory()
*/
char**(CARB_ABI* getTagsForUrl)(const char* url, size_t& nTags, bool filterExcluded, bool* resourceBusy);
/**
* See if url has the query after a recursive or normal search.
*
* @param url to the usd file that may have tags.
* @param query The query we are searching for
* @param resourceBusy set to true if we are blocked by another thread. This prevents ui blocking.
* @return true if we have found the query at the given url
*/
bool(CARB_ABI* urlHasTag)(const char* url, const char* query, bool* resourceBusy);
/**
* Frees the memory allocated in getTagsForUrl.
*
* @param tags pointer to tags that should be freed.
* @param nTags the number of tags as an output
*/
void(CARB_ABI* clearTagsMemory)(char** tags, size_t nTags);
/**
* Adds the tag to the usd file at url.
* When the request returns, an event of type kEventModifyTagFinished will be dispatched.
*
* @param url to the usd file.
* @param tag to add.
*/
void(CARB_ABI* addTag)(const char* url, const char* tag);
/**
* Removes the old tag and adds the new one.
* When the request returns, an event of type kEventModifyTagFinished will be dispatched.
*
* @param url to the usd file.
* @param oldTag to remove.
* @param newTag to add.
*/
void(CARB_ABI* updateTag)(const char* url, const char* oldTag, const char* newTag);
/**
* Removes the tag from the usd file at url.
* When the request returns, an event of type kEventModifyTagFinished will be dispatched.
*
* @param url to the usd file.
* @param tag to remove.
*/
void(CARB_ABI* removeTag)(const char* url, const char* tag);
/**
* Returns the event stream for tagging events.
*
* @return carb event stream for tagging.
*/
carb::events::IEventStream*(CARB_ABI* getTagEventStream)();
/**
* Shuts down the plugin
*
*/
void(CARB_ABI* shutdown)();
};
}
}
| 4,863 | C | 33.742857 | 115 | 0.680855 |
omniverse-code/kit/include/omni/kit/ExtensionWindowTypes.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
namespace omni
{
namespace kit
{
struct _ExtensionWindow;
using ExtensionWindowHandle = _ExtensionWindow*;
}
}
| 565 | C | 28.789472 | 77 | 0.79115 |
omniverse-code/kit/include/omni/kit/IApp.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 omni.kit.app interface definition file
#pragma once
#include "../../carb/Interface.h"
#include "../../carb/events/EventsUtils.h"
#include "../../carb/events/IEvents.h"
#include "../../carb/extras/Timer.h"
#include "../../carb/profiler/Profile.h"
#include "../String.h"
namespace omni
{
namespace ext
{
class ExtensionManager;
}
//! Namespace for kit
namespace kit
{
class IRunLoopRunner;
//! \defgroup appstruct IApp structs
//! @{
/**
* Application descriptor.
* @see IApp::startup()
*/
struct AppDesc
{
const char* carbAppName; //!< Carb application name. If `nullptr` it is derived from the executable filename.
const char* carbAppPath; //!< Carb application path. If `nullptr` it is derived from the executable folder.
int argc; //!< Number of values in `argv`
char** argv; //!< Array of arguments
};
/**
* Build information.
* @see IApp::getBuildInfo()
*/
struct BuildInfo
{
omni::string kitVersion; //!< Full kit version, e.g. `103.5+release.7032.aac30830.tc.windows-x86_64.release'
omni::string kitVersionShort; //!< Short kit version, `major.minor` e.g. `103.5`
omni::string kitVersionHash; //!< Git hash of kit build, 8 letters, e.g. `aac30830`
//! Full kernel version, e.g. `103.5+release.7032.aac30830.tc.windows-x86_64.release'
//! Note that this may be different than `kitVersion`
omni::string kernelVersion;
};
/**
* Platform information.
* @see IApp::getPlatformInfo()
*/
struct PlatformInfo
{
const char* config; //!< Build configuration e.g. "debug", "release"
//! Platform descriptor e.g. "windows-x86_64", "linux-x86_64", "linux-aarch64", "macos-universal"
const char* platform;
const char* pythonVersion; //!< Python version e.g. "cp37" for Python 3.7, "cp310" for Python 3.10
};
/**
* App information.
* @see IApp::getAppInfo(), AppDesc
*/
struct AppInfo
{
omni::string filename; //!< App filename. Name of a kit file or just 'kit'
omni::string name; //!< App name. It is app/name setting if defined, otherwise same as `filename`
omni::string version; //!< App version. Version in kit file or kit version
omni::string versionShort; //!< Short app version, currently major.minor, e.g. `2021.3`
//! Environment the application is running in, from `/app/environment/name` setting
//! e.g. "teamcity", "launcher", "etm", "default", etc.
omni::string environment;
bool isExternal; //!< Is external (public) configuration
};
/**
* Run Loop.
*
* A Run Loop is a collection of event streams that are pumped in order for each Run Loop iteration.
* @see IApp::getRunLoop(), carb::events::IEventStream, carb::events::IEvents
*/
class RunLoop
{
public:
carb::events::IEventStream* preUpdate; //!< Pre update events pushed every loop and stream is pumped.
carb::events::IEventStream* update; //!< Update events pushed every loop and stream is pumped.
carb::events::IEventStream* postUpdate; //!< Post update events pushed every loop and stream is pumped.
//! Stream for extensions to push events to, pumped every loop after postUpdate.
carb::events::IEventStream* messageBus;
};
//! @}
/**
* How to handle passed arguments when restarting an app.
* @see IApp::restart()
*/
enum class RestartArgsPolicy
{
eAppend, //!< Append to existing args
eReplace, //!< Replace existing args
};
// Few predefined run loop names. Serve as hints, doesn't have to use only those.
//! \defgroup apprunloop Run Loop Names
//! @{
//! Predefined Run Loop name
//!
//! Predefined names serve as hints for Run Loops but other names may also exist
constexpr char kRunLoopDefault[] = "main";
//! @copydoc kRunLoopDefault
constexpr char kRunLoopSimulation[] = "simulation";
//! @copydoc kRunLoopDefault
constexpr char kRunLoopRendering[] = "rendering";
//! @copydoc kRunLoopDefault
constexpr char kRunLoopUi[] = "ui";
//! @}
class IAppScripting;
//! \defgroup appevents App Events
//! @{
// App shutdown events pumped into IApp::getShutdownEventStream():
//! A shutdown event that is pushed during the next update after postQuit is called.
//!
//! Once \ref IApp::postQuit() is called, the next \ref IApp::update() call will check for shutdown requests and start
//! the shutdown sequence. The first step of this sequence is that this event (`kPostQuitEventType`) is dispatched
//! synchronously to the shutdown event stream (\ref IApp::getShutdownEventStream()) and the stream is pumped
//! immediately. During this event, any calls to \ref IApp::tryCancelShutdown() will abort this process (unless the
//! posted quit request is noncancellable). If no attempt to cancel the shutdown has been made,
//! \ref kPreShutdownEventType will be dispatched.
//! @see IApp::getShutdownEventStream(), IApp::postQuit(), IApp::tryCancelShutdown(), IApp::postUncancellableQuit()
//! \par Event Arguments
//! * "uncancellable" - boolean value indicating whether the requested type was noncancellable (`true`) or not
constexpr const carb::events::EventType kPostQuitEventType = 0;
//! A shutdown event that is pushed to indicate the start of shutdown
//! @see kPostQuitEventType, IApp::getShutdownEventStream(), IApp::postQuit(), IApp::tryCancelShutdown(),
//! IApp::postUncancellableQuit()
//! \par Event Arguments
//! * None
constexpr const carb::events::EventType kPreShutdownEventType = 1;
//! An event that is dispatched at app startup time.
//!
//! This event is dispatched to the stream returned by \ref IApp::getStartupEventStream() (and the stream is pumped)
//! immediately before \ref IApp::startup() returns.
//! \par Event Arguments
//! * None
const carb::events::EventType kEventAppStarted = CARB_EVENTS_TYPE_FROM_STR("APP_STARTED");
//! An event that is dispatched when the application becomes ready.
//!
//! After application startup (see \ref kEventAppStarted), every call to \ref IApp::update() after the first call will
//! check for readiness. Readiness can be delayed with \ref IApp::delayAppReady() which must be called during each main
//! run loop iteration to prevent readiness. Once a run loop completes with no calls to \ref IApp::delayAppReady() the
//! application is considered "ready" and this event is dispatched.
//! \par Event Arguments
//! * None
const carb::events::EventType kEventAppReady = CARB_EVENTS_TYPE_FROM_STR("APP_READY");
//! @}
/**
* Main Kit Application plugin.
*
* It runs all Kit extensions and contains necessary pieces to make them work together: settings, events, python, update
* loop. Generally an application will bootstrap *omni.kit.app* by doing the following steps:
* 1. Initialize the Carbonite \ref carb::Framework
* 2. Load the *omni.kit.app* plugin with \ref carb::Framework::loadPlugin()
* 3. Call \ref IApp::run() which will not return until the application shuts down
* 4. Shut down the Carbonite \ref carb::Framework
*
* The *kit* executable is provided by Carbonite for this purpose. It is a thin bootstrap executable around starting
* *omni.kit.app*.
*
* This interface can be acquired from Carbonite with \ref carb::Framework::acquireInterface().
*/
class IApp
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::IApp", 1, 3);
//////////// main API ////////////
/**
* Starts up the application.
* @note Typically this function is not called directly. Instead use \ref run().
* @param desc the \ref AppDesc that describes the application
*/
virtual void startup(const AppDesc& desc) = 0;
/**
* Performs one application update loop.
* @note Typically this function is not called directly. Instead use \ref run().
*/
virtual void update() = 0;
/**
* Checks whether the application is still running.
* @retval true The application is still running
* @retval false The application has requested to quit and has shut down
*/
virtual bool isRunning() = 0;
/**
* Shuts down the application.
*
* This function should be called once \ref isRunning() returns false.
* @returns The application exit code (0 indicates success)
*/
virtual int shutdown() = 0;
/**
* A helper function that starts, continually updates, and shuts down the application.
*
* This function essentially performs:
* ```cpp
* startup(desc);
* while (isRunning())
* update();
* return shutdown()
* ```
* @see startup(), isRunning(), update(), shutdown()
* @param desc the \ref AppDesc that describes the application
* @returns The application exit code (0 indicates success)
*/
int run(const AppDesc& desc);
//////////// extensions API ////////////
/**
* Requests application exit.
*
* @note This does not immediately exit the application. The next call to \ref update() will evaluate the shutdown
* process.
* @note This shutdown request is cancellable by calling \ref tryCancelShutdown().
* @see kPostQuitEventType, postUncancellableQuit()
* @param returnCode The requested return code that will be returned by \ref shutdown() once the application exits.
*/
virtual void postQuit(int returnCode = 0) = 0;
/**
* Access the log event stream.
*
* Accesses a \ref carb::events::IEventStream that receives every "error" (or higher) message.
* \par Event Arguments
* * Event ID is always 0
* * "source" - The log source, typically plugin name (string)
* * "level" - The \ref loglevel (integer)
* * "filename" - The source file name, such as by `__FILE__` (string)
* * "lineNumber" - The line in the source file, such as by `__LINE__` (integer)
* * "functionName" - The name of the function doing the logging, such as by \ref CARB_PRETTY_FUNCTION (string)
* * "message" - The log message
* @returns a \ref carb::events::IEventStream that receives every error (or higher) log message
* @see carb::events::IEventStream, carb::events::IEvents
*/
virtual carb::events::IEventStream* getLogEventStream() = 0;
/**
* Replays recorded log messages for the specified target.
*
* This function will call \ref carb::logging::Logger::handleMessage() for each log message that has been retained.
* @param target The \ref carb::logging::Logger instance to replay messages for
*/
virtual void replayLogMessages(carb::logging::Logger* target) = 0;
/**
* Toggles log message recording.
*
* By default, \ref startup() enables log message recording. Recorded log messages can be replayed on a
* \ref carb::logging::Logger with \ref replayLogMessages().
*
* @param logMessageRecordingEnabled if `true`, future log messages are recorded; if `false` the log messages are
* not recorded
*/
virtual void toggleLogMessageRecording(bool logMessageRecordingEnabled) = 0;
/**
* Access and/or creates a Run Loop by name.
*
* @param name The Run Loop to create or find; `nullptr` is interpreted as \ref kRunLoopDefault
* @returns the specified \ref RunLoop instance
*/
virtual RunLoop* getRunLoop(const char* name) = 0;
/**
* Tests whether the specified run loop exists.
* @param name The Run Loop to find; `nullptr` is interpreted as \ref kRunLoopDefault
* @retval true The specified \p name has a valid \ref RunLoop
* @retval false The specified \p name does not have a valid \ref RunLoop
*/
virtual bool isRunLoopAlive(const char* name) = 0;
/**
* Requests the run loop to terminate
*
* @note This calls \ref IRunLoopRunner::onRemoveRunLoop() but the \ref RunLoop itself is not actually removed.
* @param name The Run Loop to find; `nullptr` is interpreted as \ref kRunLoopDefault
* @param block Passed to \ref IRunLoopRunner::onRemoveRunLoop()
*/
virtual void terminateRunLoop(const char* name, bool block) = 0;
/**
* Helper function to access a Run Loop event stream.
* @see RunLoop
* @param runLoopName The name of the Run Loop; `nullptr` is interpreted as \ref kRunLoopDefault
* @returns A \ref carb::events::IEventStream instance
*/
carb::events::IEventStream* getPreUpdateEventStream(const char* runLoopName = kRunLoopDefault)
{
return getRunLoop(runLoopName)->preUpdate;
}
//! @copydoc getPreUpdateEventStream()
carb::events::IEventStream* getUpdateEventStream(const char* runLoopName = kRunLoopDefault)
{
return getRunLoop(runLoopName)->update;
}
//! @copydoc getPreUpdateEventStream()
carb::events::IEventStream* getPostUpdateEventStream(const char* runLoopName = kRunLoopDefault)
{
return getRunLoop(runLoopName)->postUpdate;
}
//! @copydoc getPreUpdateEventStream()
carb::events::IEventStream* getMessageBusEventStream(const char* runLoopName = kRunLoopDefault)
{
return getRunLoop(runLoopName)->messageBus;
}
/**
* Set particular Run Loop runner implementation. This function must be called only once during app startup. If
* no `IRunLoopRunner` was set application will quit. If `IRunLoopRunner` is set it becomes responsible for spinning
* run loops. Application will call in functions on `IRunLoopRunner` interface to communicate the intent.
*/
/**
* Sets the current Run Loop Runner instance
*
* @note The \ref IRunLoopRunner instance is retained by `*this` until destruction when the plugin is unloaded. To
* un-set the \ref IRunLoopRunner instance, call this function with `nullptr`.
*
* @see RunLoop, IRunLoopRunner
* @param runner The \ref IRunLoopRunner instance that will receive notifications about Run Loop events; `nullptr`
* to un-set the \ref IRunLoopRunner instance.
*/
virtual void setRunLoopRunner(IRunLoopRunner* runner) = 0;
/**
* Accesses the Extension Manager.
* @returns a pointer to the \ref omni::ext::ExtensionManager instance
*/
virtual omni::ext::ExtensionManager* getExtensionManager() = 0;
/**
* Accesses the Application Scripting Interface.
* @returns a pointer to the \ref IAppScripting instance
*/
virtual IAppScripting* getPythonScripting() = 0;
/**
* Access the build version string.
*
* This is effectively `getBuildInfo().kitVersion.c_str()`.
* @see getBuildInfo(), BuildInfo
* @returns The build version string
*/
virtual const char* getBuildVersion() = 0;
/**
* Reports whether the application is running 'debug' configuration.
*
* @note This is based on whether the plugin exporting the \ref IApp interface (typically *omni.kit.app.plugin*)
* that is currently running was built as a debug configuration.
*
* A debug configuration is one where \ref CARB_DEBUG was non-zero at compile time.
*
* @retval true \ref CARB_DEBUG was non-zero at compile-time
* @retval false \ref CARB_DEBUG was zero at compile-time (release build)
*/
virtual bool isDebugBuild() = 0;
/**
* Retrieves information about the currently running platform.
* @returns a @ref PlatformInfo struct describing the currently running platform.
*/
virtual PlatformInfo getPlatformInfo() = 0;
/**
* Returns the time elapsed since startup.
*
* This function returns the fractional time that has elapsed since \ref startup() was called, in the requested
* scale units.
* @param timeScale Desired time scale for the returned time interval (seconds, milliseconds, etc.)
* @return time passed since \ref startup() was most recently called
*/
virtual double getTimeSinceStart(carb::extras::Timer::Scale timeScale = carb::extras::Timer::Scale::eMilliseconds) = 0;
/**
* Returns the time elapsed since update.
*
* This function returns the fractional time that has elapsed since \ref update() was called (or if \ref update()
* has not yet been called, since \ref startup() was called), in milliseconds.
* @return time passed since \ref update() or \ref startup() (whichever is lower) in milliseconds
*/
virtual double getLastUpdateTime() = 0;
/**
* Returns the current update number.
*
* This value is initialized to zero at \ref startup(). Every time the \ref kRunLoopDefault \ref RunLoop::postUpdate
* \ref carb::events::IEventStream is pumped, this value is incremented by one.
* @returns the current update number (number of times that the \ref kRunLoopDefault \ref RunLoop has updated)
*/
virtual uint32_t getUpdateNumber() = 0;
/**
* Formats and prints a log message.
*
* The given log \p message is prepended with the time since start (as via \ref getTimeSinceStart()) and first sent
* to `CARB_LOG_INFO()`, and then outputted to `stdout` if `/app/enableStdoutOutput` is true (defaults to true).
* @param message The message to log and print to `stdout`
*/
virtual void printAndLog(const char* message) = 0;
/**
* Accesses the shutdown event stream.
* @see carb::events::IEvents, kPostQuitEventType, kPreShutdownEventType
* @returns The \ref carb::events::IEventStream that contains shutdown events
*/
virtual carb::events::IEventStream* getShutdownEventStream() = 0;
/**
* Attempts to cancel a shutdown in progress.
* @param reason The reason to interrupt shutdown; `nullptr` is interpreted as an empty string
* @retval true The shutdown process was interrupted successfully
* @retval false A noncancellable shutdown is in progress and cannot be interrupted
*/
virtual bool tryCancelShutdown(const char* reason) = 0;
/**
* Requests application exit that cannot be cancelled.
*
* @note This does not immediately exit the application. The next call to \ref update() will evaluate the shutdown
* process.
* @note This shutdown request is **not** cancellable by calling \ref tryCancelShutdown().
* @see kPostQuitEventType, postQuit()
* @param returnCode The requested return code that will be returned by \ref shutdown() once the application exits.
*/
virtual void postUncancellableQuit(int returnCode) = 0;
/**
* Accesses the startup event stream.
* @see carb::events::IEvents, kEventAppStarted, kEventAppReady
* @returns The \ref carb::events::IEventStream that contains startup events
*/
virtual carb::events::IEventStream* getStartupEventStream() = 0;
/**
* Checks whether the app is in a ready state.
* @retval true The app is in a ready state; \ref kEventAppReady has been previously dispatched
* @retval false The app is not yet ready
*/
virtual bool isAppReady() = 0;
/**
* Instructs the app to delay setting the ready state.
*
* @note This function is only useful prior to achieving the ready state. Calling it after \ref isAppReady() reports
* `true` has no effect.
*
* Every \ref update() call resets the delay request; therefore to continue delaying the ready state this function
* must be called during every update cycle.
* @param requesterName (required) The requester who is delaying the ready state, used for logging
*/
virtual void delayAppReady(const char* requesterName) = 0;
/**
* Access information about how the plugin was built.
* @returns A reference to \ref BuildInfo describing version and hash information
*/
virtual const BuildInfo& getBuildInfo() = 0;
/**
* Access information about the running application.
* @returns A reference to \ref AppInfo describing how the application was started and configured
*/
virtual const AppInfo& getAppInfo() = 0;
/**
* Restarts the application.
*
* Quits the current process and starts a new process. The command line arguments can be inherited, appended or
* replaced.
*
* To quit a regular \ref postQuit() is used, unless \p uncancellable is set to `true` in which case
* \ref postUncancellableQuit() is called.
*
* @param args Array of command line arguments for a new process; may be `nullptr`
* @param argCount Number of command line arguments in \p args
* @param argsPolicy A \ref RestartArgsPolicy value that controls replacing existing args with \p args, or appending
* \p args to the existing args
* @param uncancellable If `true` \ref postUncancellableQuit() is used to quit the current process; `false` will
* instead of postQuit().
*/
virtual void restart(const char* const* args = nullptr,
size_t argCount = 0,
RestartArgsPolicy argsPolicy = RestartArgsPolicy::eAppend,
bool uncancellable = false) = 0;
};
//! \addtogroup appevents
//! @{
// TODO(anov): switch back to using string hash when fix for IEventStream.push binding is merged in from Carbonite.
//! An event that is pushed when a scripting command is issued.
//!
//! This event is pushed to \ref IAppScripting::getEventStream().
//! @see carb::events::IEventStream, carb::events::IEvents, IAppScripting::executeString(),
//! IAppScripting::executeFile(), IAppScripting::getEventStream()
//! \par Event Arguments
//! * "text" - A human-readable text block (string)
const carb::events::EventType kScriptingEventCommand = 0; // CARB_EVENTS_TYPE_FROM_STR("SCRIPT_COMMAND");
//! \copydoc kScriptingEventCommand
//! \brief An event that is pushed when python prints to stdout
const carb::events::EventType kScriptingEventStdOut = 1; // CARB_EVENTS_TYPE_FROM_STR("SCRIPT_STDOUT");
//! \copydoc kScriptingEventCommand
//! \brief An event that is pushed when python prints to stderr
const carb::events::EventType kScriptingEventStdErr = 2; // CARB_EVENTS_TYPE_FROM_STR("SCRIPT_STDERR");
//! @}
/**
* Scripting Engine interface.
*/
class IAppScripting
{
public:
/**
* Run script from a string.
*
* A \ref kScriptingEventCommand event is always dispatched before executing the script.
* @param str Content of the script to execute
* @param commandName (optional) A command name that will logged for multi-line scripts
* @param executeAsFile If `true`, \p str is first written to a temporary file which is then executed. The file is
* not removed which allows inspecting the script at a later point.
* @retval true if execution was successful
* @retval false if an error occurs (\ref kScriptingEventStdErr was dispatched with the error message)
*/
virtual bool executeString(const char* str, const char* commandName = nullptr, bool executeAsFile = false) = 0;
/**
* Run script from a file.
*
* A \ref kScriptingEventCommand event is always dispatched before executing the script.
* @param path The path to the script file. May be a file name that exists in folders that have been added to the
* search path with \ref addSearchScriptFolder(). A ".py" suffix is optional.
* @param args An optional array of string arguments to pass to the script file
* @param argCount The number of arguments in the \p args array
* @retval true if execution was successful
* @retval false if the file was not found (an error is logged), or the script could not be loaded (an error is
* logged), or execution failed (\ref kScriptingEventStdErr was dispatched with the error message)
*/
virtual bool executeFile(const char* path, const char* const* args, size_t argCount) = 0;
/**
* Adds a folder path that will be searched for scripts.
*
* Calls to \ref executeFile() will search the paths added in the order that they were added.
* @see removeSearchScriptFolder()
* @note If the given \p path does not exist it will be created.
* @param path A relative or absolute path. If the path does not exist it will be created.
* @retval true The given \p path was added to the list of search paths
* @retval false The given \p path already exists in the list of search paths
*/
virtual bool addSearchScriptFolder(const char* path) = 0;
/**
* Removes a folder from the list of folders that will be searched for scripts.
*
* @see addSearchScriptFolder()
* @param path A relative or absolute path which was previously passed to \ref addSearchScriptFolder()
* @retval true The given \p path was found and removed from the list of script search folders
* @retval false The given \p path was not found in the list of script search folders
*/
virtual bool removeSearchScriptFolder(const char* path) = 0;
/**
* Access the scripting event stream.
* @see kScriptingEventCommand, kScriptingEventStdOut, kScriptingEventStdErr
* @returns a \ref carb::events::IEventStream that receives scripting events
*/
virtual carb::events::IEventStream* getEventStream() = 0;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inline Functions //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline int IApp::run(const AppDesc& desc)
{
this->startup(desc);
while (this->isRunning())
{
this->update();
}
return this->shutdown();
}
} // namespace kit
} // namespace omni
| 26,025 | C | 39.665625 | 123 | 0.679039 |
omniverse-code/kit/include/omni/kit/IRunLoopRunner.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 definition for IRunLoopRunner for *omni.kit.app*
#pragma once
#include "../../carb/IObject.h"
#include "../../carb/Interface.h"
namespace omni
{
namespace kit
{
class RunLoop;
/**
* Interface to implement by custom run loop runners.
*
* \ref IApp calls the functions on this interface if one was set with \ref IApp::setRunLoopRunner().
*/
class IRunLoopRunner : public carb::IObject
{
public:
/**
* Called once before starting application update.
*
* This is called by \ref IApp::startup(), and is called **after** the initial Run Loop notifications are given via
* \ref onAddRunLoop().
* @warning This function is **not** called by \ref IApp::setRunLoopRunner().
*/
virtual void startup() = 0;
/**
* Called each time a new run loop is created.
*
* This function can be called both prior to startup() (by \ref IApp::startup()), and whenever a new Run Loop is
* created by \ref IApp::getRunLoop().
*
* @thread_safety May be called from different threads simultaneously.
* @param name The run loop name; will not be `nullptr`
* @param loop The \ref RunLoop instance being added
*/
virtual void onAddRunLoop(const char* name, RunLoop* loop) = 0;
/**
* Called when IApp wants to remove a run loop.
*
* @param name The name of the run loop; will not be `nullptr`
* @param loop The \ref RunLoop instance, owned by \ref IApp
* @param block if `true`, this function should not return until the Run Loop has completed
*/
virtual void onRemoveRunLoop(const char* name, RunLoop* loop, bool block) = 0;
/**
* Called by each application update.
*
* Called by \ref IApp::update() before any work is done.
*/
virtual void update() = 0;
/**
* Called to notify of shut down.
* @warning This function is only called on the previous instance when \ref IApp::setRunLoopRunner() is called to
* switch to a different \ref IRunLoopRunner instance (or `nullptr`).
*/
virtual void shutdown() = 0;
};
//! RAII pointer type for \ref IRunLoopRunner
using IRunLoopRunnerPtr = carb::ObjectPtr<IRunLoopRunner>;
} // namespace kit
} // namespace omni
| 2,693 | C | 31.071428 | 119 | 0.67954 |
omniverse-code/kit/include/omni/kit/PythonInterOpHelper.h | // 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
#include <omni/kit/IApp.h>
#include <sstream>
namespace omni
{
namespace kit
{
/**
* Defines a helper class to build and run python command from C++.
* This class serves as a temporary solution before we can move editor completely into Python.
* Do not rely on it.
*/
class PythonInterOpHelper
{
public:
static void executeCommand(const char* command)
{
carb::getCachedInterface<omni::kit::IApp>()->getPythonScripting()->executeString(command);
}
static inline const char* pyBool(const bool value)
{
return (value ? "True" : "False");
}
template <typename T>
static inline std::ostream& addArgument(std::ostream& strm, const T& value)
{
strm << value;
return strm;
}
static inline std::ostream& addArgument(std::ostream& strm, const bool value)
{
strm << pyBool(value);
return strm;
}
template <typename T> static inline std::ostream&
addNamedArgument(std::ostream& strm, const char* name, const T& value)
{
strm << name << " = ";
return addArgument(strm, value);
}
#if defined(PXR_USD_USD_TIME_CODE_H)
static inline std::ostream& addArgument(std::ostream& strm, const pxr::UsdTimeCode& value)
{
strm << "Usd.TimeCode";
if (value == pxr::UsdTimeCode::Default())
strm << ".Default()";
else
strm << '(' << value.GetValue() << ')';
return strm;
}
template <typename T>
static inline std::ostream& addArrayArgument(std::ostream& strm, const char* pyType, const T* values, size_t N)
{
static_assert(std::is_same<double, T>::value || std::is_same<float, T>::value || std::is_same<int, T>::value, "Unsupported array type");
constexpr char typeMode = std::is_same<double, T>::value ? 'd' : (std::is_same<float, T>::value ? 'f' : 'i');
strm << pyType << typeMode << "(";
for (unsigned i = 0; i < (N-1); ++i)
{
strm << values[i] << ", ";
}
strm << values[N - 1] << ')';
return strm;
}
static inline std::ostream& addArgument(std::ostream& strm, const pxr::GfVec3i& value)
{
return addArrayArgument(strm , "Gf.Vec3", value.data(), 3);
}
static inline std::ostream& addArgument(std::ostream& strm, const pxr::GfVec3f& value)
{
return addArrayArgument(strm, "Gf.Vec3", value.data(), 3);
}
static inline std::ostream& addArgument(std::ostream& strm, const pxr::GfVec3d& value)
{
return addArrayArgument(strm, "Gf.Vec3", value.data(), 3);
}
static inline std::ostream& addArgument(std::ostream& strm, const pxr::GfMatrix4d& value)
{
return addArrayArgument(strm, "Gf.Matrix4", value.data(), 16);
}
static void runTransformPrimCommand(const std::string& path,
const pxr::GfMatrix4d& o,
const pxr::GfMatrix4d& n,
pxr::UsdTimeCode time_code = pxr::UsdTimeCode::Default(),
bool had_transform_at_key = false)
{
// Inject python command for undo/redo
std::ostringstream command;
command <<
"import omni.kit.commands\n"
"from pxr import Gf, Usd\n"
"omni.kit.commands.execute('TransformPrimCommand', path='" << path << "', ";
addNamedArgument(command, "old_transform_matrix", o) << ", ";
addNamedArgument(command, "new_transform_matrix", n) << ", ";
addNamedArgument(command, "time_code", time_code) << ", ";
addNamedArgument(command, "had_transform_at_key", had_transform_at_key) << ")\n";
executeCommand(command.str().c_str());
}
static void runTransformPrimSRTCommand(const std::string& path,
const pxr::GfVec3d o_t,
const pxr::GfVec3d o_re,
const pxr::GfVec3i o_ro,
const pxr::GfVec3d o_s,
const pxr::GfVec3d n_t,
const pxr::GfVec3d n_re,
const pxr::GfVec3i n_ro,
const pxr::GfVec3d n_s,
pxr::UsdTimeCode time_code = pxr::UsdTimeCode::Default(),
bool had_transform_at_key = false)
{
// Inject python command for undo/redo
std::ostringstream command;
command << "import omni.kit.commands\n"
"from pxr import Gf, Usd\n"
"omni.kit.commands.execute('TransformPrimSRTCommand', path='" << path << "', ";
addNamedArgument(command, "old_translation", o_t) << ", ";
addNamedArgument(command, "old_rotation_euler", o_re) << ", ";
addNamedArgument(command, "old_rotation_order", o_ro) << ", ";
addNamedArgument(command, "old_scale", o_s) << ", ";
addNamedArgument(command, "new_translation", n_t) << ", ";
addNamedArgument(command, "new_rotation_euler", n_re) << ", ";
addNamedArgument(command, "new_rotation_order", n_ro) << ", ";
addNamedArgument(command, "new_scale", n_s) << ", ";
addNamedArgument(command, "time_code", time_code) << ", ";
addNamedArgument(command, "had_transform_at_key", had_transform_at_key) << ")\n";
executeCommand(command.str().c_str());
}
struct TransformPrimsEntry
{
std::string path;
pxr::GfMatrix4d newTransform;
pxr::GfMatrix4d oldTransform;
bool hadTransformAtTime;
};
static void runTransformPrimsCommand(const std::vector<TransformPrimsEntry>& primsToTransform,
pxr::UsdTimeCode time_code)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
"from pxr import Gf, Usd\n"
"omni.kit.commands.execute('TransformPrimsCommand', prims_to_transform=[\n";
char separator = ' ';
for (auto& entry : primsToTransform)
{
command << separator << "('" << entry.path << "', ";
addArgument(command, entry.newTransform) << ", ";
addArgument(command, entry.oldTransform) << ", ";
addArgument(command, time_code) << ", ";
addArgument(command, entry.hadTransformAtTime) << ")\n";
separator = ',';
}
command << "])\n";
executeCommand(command.str().c_str());
}
struct TransformPrimsSRTEntry
{
std::string path;
pxr::GfVec3d newTranslation;
pxr::GfVec3d newRotationEuler;
pxr::GfVec3i newRotationOrder;
pxr::GfVec3d newScale;
pxr::GfVec3d oldTranslation;
pxr::GfVec3d oldRotationEuler;
pxr::GfVec3i oldRotationOrder;
pxr::GfVec3d oldScale;
bool hadTransformAtTime;
};
static void runTransformPrimsSRTCommand(const std::vector<TransformPrimsSRTEntry>& primsToTransform,
pxr::UsdTimeCode time_code)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
"from pxr import Gf, Usd\n"
"omni.kit.commands.execute('TransformPrimsSRTCommand', prims_to_transform=[\n";
char separator = ' ';
for (auto& entry : primsToTransform)
{
command << separator << "('" << entry.path << "', ";
addArgument(command, entry.newTranslation) << ", ";
addArgument(command, entry.newRotationEuler) << ", ";
addArgument(command, entry.newRotationOrder) << ", ";
addArgument(command, entry.newScale) << ", ";
addArgument(command, entry.oldTranslation) << ", ";
addArgument(command, entry.oldRotationEuler) << ", ";
addArgument(command, entry.oldRotationOrder) << ", ";
addArgument(command, entry.oldScale) << ", ";
addArgument(command, time_code) << ", ";
addArgument(command, entry.hadTransformAtTime) << ")\n";
separator = ',';
}
command << "])\n";
executeCommand(command.str().c_str());
}
template <typename StrT>
static std::string serializePrimPaths(StrT* paths, size_t count)
{
std::ostringstream out;
for (size_t i = 0; i < count; i++)
{
out << "'" << paths[i] << "'";
if (i != count - 1)
{
out << ",";
}
}
return out.str();
}
static void runSetSelectedPrimsCommand(const std::string& oldPaths, const std::string& newPaths, bool expandInStage)
{
// Inject python command for undo/redo
std::ostringstream command;
command << "import omni.kit.commands\n"
"omni.kit.commands.execute('SelectPrimsCommand'"
<< ", old_selected_paths=[" << oldPaths << "]"
<< ", new_selected_paths=[" << newPaths << "]"
<< ", expand_in_stage=" << pyBool(expandInStage)
<< ")\n";
executeCommand(command.str().c_str());
}
static void runMovePrimCommand(const std::string& pathFrom, const std::string& pathTo, bool keepWorldTransfrom)
{
// Inject python command for undo/redo
std::ostringstream command;
command << "import omni.kit.commands\n"
"omni.kit.commands.execute('MovePrimCommand', path_from='"
<< pathFrom << "', path_to='" << pathTo << "', keep_world_transform=" << pyBool(keepWorldTransfrom)
<< ")\n";
executeCommand(command.str().c_str());
}
static void runMovePrimsCommand(const std::vector<std::pair<pxr::SdfPath, pxr::SdfPath>>& pathsToMove,
bool keepWorldTransfrom)
{
// Inject python command for undo/redo
std::ostringstream command;
command << "import omni.kit.commands\n"
"omni.kit.commands.execute('MovePrimsCommand', paths_to_move={";
for (auto& entry : pathsToMove)
{
command << "'" << entry.first << "' : '" << entry.second << "',";
}
command.seekp(-1, std::ios_base::end);
command << "}, keep_world_transform=" << pyBool(keepWorldTransfrom) << ")\n";
executeCommand(command.str().c_str());
}
static void runCopyPrimCommand(const char* srcPath, const char* tarPath, bool dupLayers, bool combineLayers)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
"omni.kit.commands.execute('CopyPrimCommand', path_from='"
<< srcPath << "', path_to=" << (tarPath ? std::string("'") + tarPath + "'" : "None")
<< ", duplicate_layers=" << pyBool(dupLayers)
<< ", combine_layers=" << pyBool(combineLayers) << ")\n";
executeCommand(command.str().c_str());
}
static void runOpenStageCommand(const std::string& path)
{
std::ostringstream command;
command << "import omni.kit.window.file\n"
"omni.kit.window.file.open_stage('"
<< path << "')\n";
executeCommand(command.str().c_str());
}
// Open stage as a edit layer, that it will be a sublayer of an empty stage
// with a edit layer above this sublayer to make edits in.
static void runOpenStageAsEditLayerCommand(const std::string& path)
{
std::ostringstream command;
command << "import omni.kit.window.file\n"
"omni.kit.window.file.open_with_new_edit_layer('"
<< path << "')\n";
executeCommand(command.str().c_str());
}
static void runCreateReferenceCommand(const std::string& url, const std::string& pathTo, bool instanceable)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
<< "import omni.usd\n"
<< "omni.kit.commands.execute('CreateReferenceCommand', usd_context=omni.usd.get_context(), path_to='"
<< pathTo << "', asset_path='" << url << "',"
<< "instanceable=" << pyBool(instanceable) << ")\n";
executeCommand(command.str().c_str());
}
static void runCreatePayloadCommand(const std::string& url, const std::string& pathTo, bool instanceable)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
<< "import omni.usd\n"
<< "omni.kit.commands.execute('CreatePayloadCommand', usd_context=omni.usd.get_context(), path_to='"
<< pathTo << "', asset_path='" << url << "',"
<< "instanceable=" << pyBool(instanceable) << ")\n";
executeCommand(command.str().c_str());
}
static void runCreateAudioPrimFromAssetPathCommand(const std::string& url, const std::string& pathTo)
{
std::ostringstream command;
command
<< "import omni.kit.commands\n"
<< "import omni.usd\n"
<< "omni.kit.commands.execute('CreateAudioPrimFromAssetPathCommand', usd_context=omni.usd.get_context(), path_to='"
<< pathTo << "', asset_path='" << url << "')\n";
executeCommand(command.str().c_str());
}
static void runCreatePrimCommand(const char* primPath,
const char* primType,
const bool selectNewPrim,
const char* usdContextName = "")
{
std::ostringstream command;
command << "import omni.kit.commands\n"
<< "omni.kit.commands.execute('CreatePrimCommand', prim_path='" << primPath << "', prim_type='"
<< primType << "', select_new_prim=" << pyBool(selectNewPrim) << ", context_name='"
<< usdContextName << "' )\n";
executeCommand(command.str().c_str());
}
static void runCreateMdlMaterialPrimCommand(const std::string& mdlUrl,
const std::string& mtlName,
const std::string& mdlPrimPath,
const std::string& targetPrimPath = "$$$")
{
std::ostringstream command;
// targetPrimPath "" is valid param, use "$$$" for no parameter passed
if (targetPrimPath.compare("$$$") == 0)
{
command << "import omni.kit.commands\n"
<< "omni.kit.commands.execute('CreateMdlMaterialPrimCommand', mtl_url='" << mdlUrl
<< "', mtl_name='" << mtlName << "', mtl_path='" << mdlPrimPath << "', select_new_prim=False)\n";
}
else
{
command << "import asyncio\n"
<< "import omni.kit.commands\n"
<< "import omni.kit.material.library\n"
<< "import carb\n"
<< "async def create_material(prim_path):\n"
<< " def have_subids(subids):\n"
<< " if len(subids) > 1:\n"
<< " omni.kit.material.library.custom_material_dialog(mdl_path='" << mdlUrl
<< "', bind_prim_paths=[prim_path])\n"
<< " return\n";
if (targetPrimPath.empty())
{
command << " omni.kit.commands.execute('CreateMdlMaterialPrimCommand', mtl_url='" << mdlUrl
<< "', mtl_name='" << mtlName << "', mtl_path='" << mdlPrimPath << "', select_new_prim=True)\n";
command << " await omni.kit.material.library.get_subidentifier_from_mdl('" << mdlUrl
<< "', on_complete_fn=have_subids)\n";
command << "asyncio.ensure_future(create_material(None))\n";
}
else
{
command
<< " with omni.kit.undo.group():\n"
<< " omni.kit.commands.execute('CreateMdlMaterialPrimCommand', mtl_url='" << mdlUrl
<< "', mtl_name='" << mtlName << "', mtl_path='" << mdlPrimPath << "', select_new_prim=False)\n"
<< " omni.kit.commands.execute('BindMaterialCommand', prim_path = prim_path, material_path = '"
<< mdlPrimPath << "', strength = None )\n";
command << " await omni.kit.material.library.get_subidentifier_from_mdl('" << mdlUrl
<< "', on_complete_fn=have_subids)\n";
command << "omni.kit.material.library.multi_descendents_dialog(prim_paths=['" << targetPrimPath
<< "'], on_click_fn=lambda p: asyncio.ensure_future(create_material(prim_path=p)))\n";
}
}
executeCommand(command.str().c_str());
}
static void beginUndoGroup()
{
static constexpr char kCmd[] =
"import omni.kit.undo\n"
"omni.kit.undo.begin_group()";
executeCommand(kCmd);
}
static void endUndoGroup()
{
static constexpr char kCmd[] =
"import omni.kit.undo\n"
"omni.kit.undo.end_group()";
executeCommand(kCmd);
}
static void popLastUndoGroup()
{
static constexpr char kCmd[] =
"import omni.kit.undo\n"
"keep_going = True\n"
"undo_stack = omni.kit.undo.get_undo_stack()\n"
"while keep_going:\n"
" entry = undo_stack.pop()\n"
" if entry.level == 0:\n"
" keep_going = False\n";
executeCommand(kCmd);
}
static void createBuiltinCamera(const char* path, bool ortho, const char* usdContextName = "")
{
beginUndoGroup();
runCreatePrimCommand(path, "Camera", false, usdContextName);
std::ostringstream command;
command << "from pxr import Usd, UsdGeom, Gf, Kind\n"
"import omni.usd\n"
"import omni.kit.commands\n"
"stage = omni.usd.get_context('" << usdContextName << "').get_stage()\n"
"camera = UsdGeom.Camera.Get(stage, '" << path << "')\n"
"camera.CreateClippingRangeAttr(Gf.Vec2f(" << (ortho ? "2e4" : "1.0") << ", 1e7))\n"
"Usd.ModelAPI(camera).SetKind(Kind.Tokens.component)\n"
"camera.GetPrim().SetMetadata('no_delete', True)\n";
command << "import carb\n"
<< "cam_settings = carb.settings.get_settings().get_settings_dictionary('/persistent/app/primCreation/typedDefaults/"
<< (ortho ? "orthoCamera" : "camera") << "')\n"
<< "if cam_settings:\n"
<< " for name, value in cam_settings.get_dict().items():\n"
// Catch failures and issue an error, but continue on
<< " try:\n"
<< " attr = camera.GetPrim().GetAttribute(name)\n"
<< " if attr:\n"
<< " attr.Set(value)\n"
<< " except Exception:\n"
<< " import traceback\n"
<< " carb.log_error(traceback.format_exc())\n";
executeCommand(command.str().c_str());
endUndoGroup();
}
static void runFramePrimsCommand(const std::string& camera, const PXR_NS::SdfPathVector& paths, double aspectRatio, const pxr::UsdTimeCode& timeCode, const std::string& usdContext)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
<< "omni.kit.commands.execute('FramePrimsCommand'"
<< ", prim_to_move='" << camera << "'"
<< ", aspect_ratio=" << (std::isfinite(aspectRatio) ? aspectRatio : 1.0)
<< ", usd_context_name='" << usdContext << "'"
<< ", time_code=";
addArgument(command, timeCode);
if (!paths.empty())
{
auto pathItr = paths.begin();
command << ", prims_to_frame = [ '" << *pathItr << "'";
++pathItr;
for (auto pathEnd = paths.end(); pathItr != pathEnd; ++pathItr)
{
command << ", '" << *pathItr << "'";
}
command << "]";
}
command << ")\n";
executeCommand(command.str().c_str());
}
static void runDuplicateFromActiveViewportCameraCommand(const char* viewportName)
{
std::ostringstream command;
command << "import omni.kit.commands\n"
"omni.kit.commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='"
<< viewportName << "')\n";
executeCommand(command.str().c_str());
}
// Post notification utility from python
static void postNotification(const std::string& message, bool hide_after_timeout = true, bool info = true)
{
std::ostringstream command;
command << "try:\n"
<< " import omni.kit.notification_manager as nm\n"
<< " nm.post_notification(\"" << message << "\", hide_after_timeout=" << pyBool(hide_after_timeout);
if (!info)
{
command << ", status=nm.NotificationStatus.WARNING";
}
command << ")\n"
<< "except Exception:\n"
<< " pass\n";
executeCommand(command.str().c_str());
}
#endif // PXR_USD_USD_TIME_CODE_H
};
}
}
| 22,182 | C | 39.113924 | 184 | 0.53327 |
omniverse-code/kit/include/omni/kit/ViewportWindowUtils.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.
//
#pragma once
#include <carb/dictionary/IDictionary.h>
#include <carb/events/EventsUtils.h>
#include <omni/kit/IViewport.h>
#include <omni/kit/ViewportTypes.h>
namespace omni
{
namespace kit
{
/**
* Gets payload from UiDrawEventStream.
*
* @param e Event from UiDrawEventStream.
* @param viewMtx The array to hold the data of view matrix. It must be big enough to store 16 doubles.
* @param projMtx The array to hold the data of projection matrix. It must be big enough to store 16 doubles.
* @param viewportRect The Float4 to hold the data of viewport rect.
*/
inline void getUiDrawPayloadFromEvent(const carb::events::IEvent& e,
double* viewMtx,
double* projMtx,
carb::Float4& viewportRect)
{
auto events = carb::dictionary::getCachedDictionaryInterface();
for (size_t i = 0; i < 16; i++)
{
static const std::string viewMatrixPrefix("viewMatrix/");
viewMtx[i] = events->get<double>(e.payload, (viewMatrixPrefix + std::to_string(i)).c_str());
}
for (size_t i = 0; i < 16; i++)
{
static const std::string projMatrixPrefix("projMatrix/");
projMtx[i] = events->get<double>(e.payload, (projMatrixPrefix + std::to_string(i)).c_str());
}
for (size_t i = 0; i < 4; i++)
{
static const std::string viewportRectPrefix("viewportRect/");
(&viewportRect.x)[i] = events->get<float>(e.payload, (viewportRectPrefix + std::to_string(i)).c_str());
}
}
/**
* Gets the default (first) IViewportWindow
*
* @return Default IViewportWindow
*/
inline IViewportWindow* getDefaultViewportWindow()
{
auto viewport = carb::getCachedInterface<omni::kit::IViewport>();
if (viewport)
{
return viewport->getViewportWindow(nullptr);
}
return nullptr;
}
}
}
| 2,314 | C | 31.152777 | 111 | 0.662057 |
omniverse-code/kit/include/omni/kit/EventSubscribers.h | // Copyright (c) 2019-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 Utilities for managing EventSubscribers for omni.kit.app
#pragma once
#include "../../carb/Defines.h"
#include <vector>
namespace carb
{
/**
* A class that manages subscribers
*
* @thread_safety This class is **not** thread safe. Consider using \ref carb::delegate::Delegate which is thread-safe.
* @warning This class does not conform to Basic Callback Hygiene as described in the @rstdoc{../../../../CODING}. It's
* use should be avoided. Instead use \ref carb::delegate::Delegate. This class is also not thread-safe.
* @tparam FuncT The function pointer type to manage
* @tparam SubIdT A type that is used as the subscriber type
*/
template <class FuncT, typename SubIdT>
class EventSubscribers
{
public:
/**
* Create a subscription, returning a handle to reference it.
* @warning This class does not conform to Basic Callback Hygiene as described in the @rstdoc{../../../../CODING}.
* It's use should be avoided. Instead use \ref carb::delegate::Delegate. This class is also not thread-safe.
* @param fn The function pointer to register
* @param userData The user data that should be passed to \p fn when called
* @returns a `SubIdT` to reference the registered function. There is no invalid value, so `0` may be returned.
* Subscription IDs may also be reused as soon as they are unsubscribed. Call \ref unsubscribe() when finished
* with the subscription.
*/
SubIdT subscribe(FuncT fn, void* userData)
{
// Search for free slot
size_t index;
bool found = false;
for (size_t i = 0; i < m_subscribers.size(); i++)
{
if (!m_subscribers[i].fn)
{
index = i;
found = true;
break;
}
}
// Add new slot if haven't found a free one
if (!found)
{
m_subscribers.push_back({});
index = m_subscribers.size() - 1;
}
m_subscribers[index] = { fn, userData };
return (SubIdT)index;
}
/**
* Removes a subscriber previously subscribed with @ref subscribe().
* @warning This class does not conform to Basic Callback Hygiene as described in the @rstdoc{../../../../CODING}.
* It's use should be avoided. Instead use \ref carb::delegate::Delegate. This class is also not thread-safe.
* @warning Calling this function with an invalid Subscription ID will cause undefined behavior.
* @param id The subscriber ID previously passed to \ref subscribe().
*/
void unsubscribe(SubIdT id)
{
CARB_ASSERT(id < m_subscribers.size());
m_subscribers[id] = {};
}
/**
* Calls all subscribers.
* @warning This class does not conform to Basic Callback Hygiene as described in the @rstdoc{../../../../CODING}.
* It's use should be avoided. Instead use \ref carb::delegate::Delegate. This class is also not thread-safe.
* @param args Arguments passed to the subscribed `FuncT` functions. These arguments are passed by value prior to
* the `userData` parameter that was registered with \ref subscribe().
*/
template <typename... Ts>
void send(Ts... args)
{
// Iterate by index because subscribers can actually change during iteration (vector can grow)
const size_t kCount = m_subscribers.size();
for (size_t i = 0; i < kCount; i++)
{
auto& subsribers = m_subscribers[i];
if (subsribers.fn)
subsribers.fn(args..., subsribers.userData);
}
}
/**
* Calls a single subscriber.
* @warning This class does not conform to Basic Callback Hygiene as described in the @rstdoc{../../../../CODING}.
* It's use should be avoided. Instead use \ref carb::delegate::Delegate. This class is also not thread-safe.
* @warning Calling this function with an invalid Subscription ID will cause undefined behavior.
* @param id The subscriber ID previously passed to \ref subscribe().
* @param args Arguments passed to the subscribed `FuncT` functions. These arguments are passed by value prior to
* the `userData` parameter that was registered with \ref subscribe().
*/
template <typename... Ts>
void sendForId(uint64_t id, Ts... args)
{
CARB_ASSERT(id < m_subscribers.size());
if (m_subscribers[id].fn)
m_subscribers[id].fn(args..., m_subscribers[id].userData);
}
private:
struct EventData
{
FuncT fn;
void* userData;
};
std::vector<EventData> m_subscribers;
};
} // namespace carb
| 5,096 | C | 38.207692 | 119 | 0.645408 |
omniverse-code/kit/include/omni/kit/renderer/RendererUtils.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/logging/Log.h>
#include <omni/kit/renderer/IRenderer.h>
#include <rtx/resourcemanager/ResourceManager.h>
namespace
{
using namespace omni::kit::renderer;
using namespace rtx::resourcemanager;
static void* acquireGpuPointerReference(IRenderer::ResourceManagerState state, RpResource& rpRsrc, const carb::graphics::TextureDesc** texDesc)
{
if (!state.manager || !state.manager)
{
CARB_LOG_ERROR("ResourceManagerState doesn't have a ResourceManager or its Context");
return nullptr;
}
if (texDesc)
{
*texDesc = state.manager->getTextureDesc(*state.context, &rpRsrc);
if (!*texDesc)
{
CARB_LOG_ERROR("ResourceManager returned a null TextureDesc for the RpResource");
return nullptr;
}
}
auto texH = state.manager->getTextureHandle(*state.context, &rpRsrc);
if (!texH.ptr)
{
CARB_LOG_ERROR("ResourceManager could not retrieve a TextureHandle for the RpResource");
return nullptr;
}
state.manager->acquireResource(rpRsrc);
return texH.ptr;
}
static bool releaseGpuPointerReference(IRenderer::ResourceManagerState state, RpResource& rpRsrc)
{
if (state.manager)
{
state.manager->releaseResource(rpRsrc);
return true;
}
return false;
}
}
| 1,767 | C | 29.482758 | 143 | 0.706848 |
omniverse-code/kit/include/omni/kit/renderer/IGpuFoundation.h | // Copyright (c) 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/Interface.h>
namespace carb
{
namespace graphics
{
struct Graphics;
}
namespace graphicsmux
{
struct GraphicsMux;
}
namespace glinterop
{
struct GLInterop;
}
namespace cudainterop
{
struct CudaInterop;
}
}
namespace rtx
{
namespace resourcemanager
{
struct ResourceManager;
class Context;
typedef uint32_t SyncScopeId;
}
namespace rendergraph
{
struct RenderGraphBuilder;
class RenderGraphContext;
}
namespace shaderdb
{
struct ShaderDb;
class Context;
}
namespace psodb
{
struct PsoDb;
struct Context;
}
}
namespace gpu
{
namespace foundation
{
class IGpuFoundation;
struct GpuFoundationContext;
struct GpuDevices;
}
}
namespace omni
{
namespace kit
{
namespace renderer
{
class IGpuFoundation
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::renderer::IGpuFoundation", 1, 1);
virtual carb::graphics::Graphics* getGraphics() = 0;
virtual carb::graphicsmux::GraphicsMux* getGraphicsMux() = 0;
virtual rtx::resourcemanager::ResourceManager* getResourceManager() = 0;
virtual rtx::resourcemanager::Context* getResourceManagerContext() = 0;
virtual rtx::rendergraph::RenderGraphBuilder* getRenderGraphBuilder() = 0;
virtual rtx::shaderdb::ShaderDb* getShaderDb() = 0;
virtual rtx::shaderdb::Context* getShaderDbContext() = 0;
virtual rtx::psodb::PsoDb* getPipelineStateDb() = 0;
virtual rtx::psodb::Context* getPipelineStateDbContext() = 0;
virtual carb::glinterop::GLInterop* getOpenGlInterop() = 0;
virtual carb::cudainterop::CudaInterop* getCudaInterop() = 0;
virtual gpu::foundation::IGpuFoundation* getGpuFoundation() = 0;
virtual gpu::foundation::GpuDevices* getGpuFoundationDevices() = 0;
virtual bool isBindlessSupported() = 0;
virtual rtx::resourcemanager::SyncScopeId getSyncScopeId() = 0;
virtual bool isCompatibilityMode() = 0;
};
}
}
}
| 2,289 | C | 19.818182 | 78 | 0.753604 |
omniverse-code/kit/include/omni/kit/renderer/IImGuiRenderer.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 "IRenderer.h"
#include <carb/Interface.h>
#include <omni/ui/windowmanager/IWindowCallbackManager.h>
namespace carb
{
namespace graphics
{
struct CommandList;
struct Descriptor;
struct DescriptorSet;
}
}
namespace rtx
{
namespace resourcemanager
{
class Context;
}
}
namespace carb
{
namespace graphics
{
struct Graphics;
struct Device;
struct ResourceBindingSignature;
}
namespace windowing
{
struct Cursor;
}
namespace imgui
{
struct Context;
}
}
namespace omni
{
namespace ui
{
namespace windowmanager
{
struct WindowSet;
}
}
namespace kit
{
namespace renderer
{
class DrawDataHandler;
class IImGuiRenderer
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::renderer::IImGuiRenderer", 1, 3);
virtual void startup() = 0;
virtual void shutdown() = 0;
virtual uint32_t getResourceManagerDeviceMask() = 0;
virtual carb::graphics::ResourceBindingSignature* getResourceBindingSignature() = 0;
virtual TextureGpuReference allocateReferenceForTexture() = 0;
virtual TextureGpuReference allocateReferenceForDrawable() = 0;
virtual bool isPossibleToAttachAppWindow() = 0;
virtual bool attachAppWindow(IAppWindow* appWindow) = 0;
virtual bool attachAppWindowWithImGuiContext(IAppWindow* appWindow, carb::imgui::Context* imGuiContext) = 0;
virtual void detachAppWindow(IAppWindow* appWindow) = 0;
virtual bool isAppWindowAttached(IAppWindow* appWindow) = 0;
virtual omni::ui::windowmanager::WindowSet* getWindowSet(IAppWindow* appWindow) = 0;
virtual void setCursorShapeOverride(IAppWindow* appWindow, carb::windowing::CursorStandardShape cursor) = 0;
virtual bool hasCursorShapeOverride(IAppWindow* appWindow) const = 0;
virtual carb::windowing::CursorStandardShape getCursorShapeOverride(IAppWindow* appWindow) const = 0;
virtual void clearCursorShapeOverride(IAppWindow* appWindow) = 0;
virtual void deallocateReferenceForTexture(const TextureGpuReference& textureGpuReference) = 0;
virtual void deallocateReferenceForDrawable(const TextureGpuReference& textureGpuReference) = 0;
virtual DrawDataHandler* createDrawData() const = 0;
virtual void destroyDrawData(DrawDataHandler* drawDataHandler) const = 0;
virtual void fillDrawData(DrawDataHandler* drawDataHandler, void* data) const = 0;
virtual void renderDrawData(IAppWindow* appWindow,
carb::graphics::CommandList* commandList,
const DrawDataHandler* drawDataHandler) const = 0;
virtual void registerCursorShapeExtend(const char* shapeName, const char* imagePath) = 0;
virtual void unregisterCursorShapeExtend(const char* shapeName) = 0;
virtual void setCursorShapeOverrideExtend(IAppWindow* appWindow, const char* shapeName) = 0;
virtual omni::string getCursorShapeOverrideExtend(IAppWindow* appWindow) const = 0;
virtual void getAllCursorShapeNames(const char** names, size_t count) const = 0;
virtual size_t getAllCursorShapeNamesCount() const = 0;
};
}
}
}
| 3,465 | C | 28.12605 | 112 | 0.761616 |
omniverse-code/kit/include/omni/kit/renderer/IRenderer.h | // 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
#include "IGpuFoundation.h"
#include <carb/IObject.h>
#include <carb/Interface.h>
#include <carb/InterfaceUtils.h>
#include <carb/tasking/TaskingTypes.h>
#include <omni/kit/IAppWindow.h>
namespace carb
{
namespace events
{
class IEventStream;
}
namespace graphics
{
enum class DescriptorType : int32_t;
struct Device;
class DeviceGroup;
struct CommandList;
struct CommandQueue;
struct DescriptorPool;
struct ResourceBindingSignature;
struct TextureDesc;
// TextureGpuData
struct Texture;
struct Descriptor;
struct DescriptorSet;
}
namespace graphicsmux
{
class CommandList;
}
namespace renderer
{
struct TextureHandle;
}
}
namespace gpu
{
enum class GfResult : int32_t;
}
namespace rtx
{
namespace resourcemanager
{
class RpResource;
typedef uint32_t SyncScopeId;
}
}
namespace omni
{
namespace kit
{
namespace renderer
{
typedef int64_t CommandListHandle;
/**
* Defines a simple interface for texture GPU resources
*/
class TextureGpuData : public carb::IObject
{
public:
virtual carb::graphics::Texture* getGraphicsTexture() const = 0;
virtual carb::graphics::Descriptor* getGraphicsDescriptor() const = 0;
virtual carb::graphics::DescriptorSet* getGraphicsDescriptorSet() const = 0;
virtual rtx::resourcemanager::RpResource* getManagedResource() const = 0;
virtual uint32_t getBindlessDescriptorIndex() const = 0;
};
struct TextureGpuReference
{
union {
uint32_t gpuIndex;
void* ptr;
};
};
/**
* @brief The data for all the viewports in GUI. We use it when present thread
* is enabled to render viewport with more FPS that GUI.
*/
struct IRendererHydraViewportData
{
using Clock = ::std::chrono::high_resolution_clock;
using Duration = Clock::duration;
using TimePoint = Clock::time_point;
uint32_t viewportId;
size_t subFrameCount;
uint32_t subFrames[4];
size_t currentSubFrame;
TimePoint publishTime;
Duration frameAverageTime;
};
/**
* @brief Options for texture creation.
*/
struct IRendererTextureOptions
{
uint32_t gpuDeviceMask = 0; ///< Device mask to create texture on (0 for UI device only)
uint32_t textureUsageFlags = 0; ///< carb::graphics::TextureUsageFlags
uint32_t resourceUsageFlags = 0; ///< rtx::ResourceUsageFlags
uint32_t unusedExtPadding = 0; ///< Unused padding and expansion
};
/**
* Defines an interface for the small version of editor that provides simple GUI.
*/
class IRenderer
{
public:
CARB_PLUGIN_INTERFACE("omni::kit::renderer::IRenderer", 1, 9);
virtual void startup() = 0;
virtual void shutdown() = 0;
/**
* Render events stream. Render events and pushed and popped every frame.
*/
virtual carb::events::IEventStream* getPreBeginFrameEventStream(IAppWindow* appWindow) = 0;
virtual carb::events::IEventStream* getPreBeginRenderPassEventStream(IAppWindow* appWindow) = 0;
virtual carb::events::IEventStream* getRenderFrameEventStream(IAppWindow* appWindow) = 0;
virtual carb::events::IEventStream* getPostEndRenderPassEventStream(IAppWindow* appWindow) = 0;
virtual carb::events::IEventStream* getPostEndRenderFrameEventStream(IAppWindow* appWindow) = 0;
virtual carb::graphics::Device* getGraphicsDevice(IAppWindow* appWindow) = 0;
virtual carb::graphics::DeviceGroup* getGraphicsDeviceGroup(IAppWindow* appWindow) = 0;
virtual uint32_t getGraphicsDeviceIndex(IAppWindow* appWindow) = 0;
virtual carb::Format getGraphicsSwapchainFormat(IAppWindow* appWindow) = 0;
virtual carb::graphics::CommandQueue* getGraphicsCommandQueue(IAppWindow* appWindow) = 0;
typedef void (*UploadCompleteCbDeprecated)(void* arg,
void* textureHandle,
carb::graphics::Descriptor* textureDescriptor,
size_t width,
size_t height,
void* userData);
struct UploadTextureDescDeprecated
{
const char* assetUri;
UploadCompleteCbDeprecated callback;
void* arg;
};
// TODO: remove these functions as they are merely wrappers around GPU data creation with integrated assets
// management
virtual void uploadTextureDeprecated(const UploadTextureDescDeprecated& desc, void* userData = nullptr) = 0;
virtual void destroyTextureDeprecated(void* texture) = 0;
virtual TextureGpuData* getTextureDataFromHandle(void* textureHandle) = 0;
static constexpr uint32_t kMaxDescriptorSetCount = 8192;
virtual carb::graphics::DescriptorPool* getDescriptorPool() = 0;
/**
* These functions are needed because carb::graphics doesn't have descriptor set deallocations, we have very
* finite set of allocations - we have to track them to make sure we can emit a warning if we're reaching the limit.
*/
virtual void notifyDescriptorPoolAllocation(carb::graphics::DescriptorType descriptorType) = 0;
virtual int getFreeDescriptorPoolSlotCount(carb::graphics::DescriptorType descriptorType) = 0;
/**
* Functions that allocate id to use in shaders, given the created/imported GPU data.
*/
virtual TextureGpuReference allocateReferenceForTexture(
carb::graphics::ResourceBindingSignature* resourceBindingSignature) = 0;
virtual TextureGpuReference allocateReferenceForDrawable(
carb::graphics::ResourceBindingSignature* resourceBindingSignature) = 0;
virtual TextureGpuReference updateReferenceFromTextureData(TextureGpuReference textureGpuReference,
TextureGpuData* textureGpuData) = 0;
virtual TextureGpuReference updateReferenceFromDrawableData(TextureGpuReference* textureGpuReference,
TextureGpuData* drawableGpuData) = 0;
/**
* Functions to manipulate GPU data that was created outside of the renderer.
*/
virtual TextureGpuData* createExternalTextureGpuData() = 0;
virtual void updateExternalTextureGpuData(
TextureGpuData* externalTextureGpuData,
carb::graphics::Descriptor* externalDescriptor,
uint32_t bindlessDescriptorIndex = CARB_UINT32_MAX) = 0;
/**
* Functions to create managed GPU data.
*/
virtual TextureGpuData* createGpuResourcesForTexture(carb::Format format,
size_t mipMapCount,
size_t* mipWidths,
size_t* mipHeights,
const uint8_t** mipDatas,
size_t* mipStrides) = 0;
virtual void updateGpuResourcesForTexture(TextureGpuData* textureGpuData,
carb::Format format,
size_t mipMapCount,
size_t* mipWidths,
size_t* mipHeights,
const uint8_t** mipDatas,
size_t* mipStrides) = 0;
virtual void resetGpuResourcesForTexture(TextureGpuData* textureGpuData) = 0;
virtual void destroyGpuResourcesForTexture(TextureGpuData* textureGpuData) = 0;
/**
* Functions to extract command lists from handles.
*/
virtual carb::graphics::CommandList* getGraphicsCommandList(CommandListHandle commandListHandle) = 0;
virtual carb::graphicsmux::CommandList* getGraphicsMuxCommandList(CommandListHandle commandListHandle) = 0;
virtual uint32_t getCurrentBackBufferIndex(IAppWindow* appWindow) = 0;
virtual uint32_t getBackBufferCount(IAppWindow* appWindow) = 0;
virtual size_t getFrameCount(IAppWindow* appWindow) = 0;
/**
* Framebuffer information.
*/
virtual carb::graphics::Texture* getFramebufferTexture(IAppWindow* appWindow) = 0;
virtual uint32_t getFramebufferWidth(IAppWindow* appWindow) = 0;
virtual uint32_t getFramebufferHeight(IAppWindow* appWindow) = 0;
virtual carb::Format getFramebufferFormat(IAppWindow* appWindow) = 0;
virtual CommandListHandle getFrameCommandList(IAppWindow* appWindow) = 0;
virtual TextureGpuReference getInvalidTextureReference() = 0;
static inline IGpuFoundation* getGpuFoundation();
virtual bool attachAppWindow(IAppWindow* appWindow) = 0;
virtual void detachAppWindow(IAppWindow* appWindow) = 0;
virtual bool isAppWindowAttached(IAppWindow* appWindow) = 0;
virtual void waitIdle(IAppWindow* appWindow) = 0;
virtual void forceRenderFrame(float dt) = 0;
virtual rtx::resourcemanager::SyncScopeId getSyncScopeId() = 0;
/**
* Get a reference to the current ResourceManager and it's Context.
* IAppWindow* can currently be null.
*/
struct ResourceManagerState
{
rtx::resourcemanager::ResourceManager* manager;
rtx::resourcemanager::Context* context;
};
virtual ResourceManagerState getResourceManagerState(IAppWindow* appWindow) = 0;
virtual void setClearColor(IAppWindow* appWindow, const carb::Float4& clearColor) = 0;
virtual carb::Float4 getClearColor(IAppWindow* appWindow) = 0;
virtual bool setRenderQueue(IAppWindow* appWindow, size_t renderQueueIdx) = 0;
virtual size_t getRenderQueue(IAppWindow* appWindow) = 0;
/**
* Functions that deallocate id to use in shaders, given the created/imported GPU data.
*/
virtual void deallocateReferenceForTexture(
carb::graphics::ResourceBindingSignature* resourceBindingSignature, const TextureGpuReference& textureGpuReference) = 0;
virtual void deallocateReferenceForDrawable(
carb::graphics::ResourceBindingSignature* resourceBindingSignature, const TextureGpuReference& textureGpuReference) = 0;
/**
* Present thread streams.
*
* Called from the separate thread (present thread) to render the saved UI
* with bigger framerate than it's generated.
*/
virtual carb::events::IEventStream* getPresentRenderFrameEventStream(IAppWindow* appWindow) = 0;
/**
* @brief Should be called when the new viewport frame is ready
*
* @param dt time to render this frame in ns
* @param viewportId the id of the viewport that should be replaced to the
* given textureId
* @param subFrameCount the number of subframes
* @param subFrames the viewport subframes
*/
virtual void notifyRenderingIsReady(float dtNs,
uint32_t viewportId,
size_t subFrameCount,
const uint32_t* subFrames) = 0;
/**
* Functions to create managed GPU data with optional multiGpu and GPU source support.
*
* @param multiGpu data will be uploaded or copied to all GPUs in device group
* @param fromGpu data is a gpu memory address, not host memory
*/
virtual TextureGpuData* createGpuResourcesForTexture(carb::Format format,
size_t mipMapCount,
size_t* mipWidths,
size_t* mipHeights,
const uint8_t** mipDatas,
size_t* mipStrides,
bool multiGpu,
bool cudaBytes) = 0;
virtual void updateGpuResourcesForTexture(TextureGpuData* textureGpuData,
carb::Format format,
size_t mipMapCount,
size_t* mipWidths,
size_t* mipHeights,
const uint8_t** mipDatas,
size_t* mipStrides,
bool cudaBytes) = 0;
/**
* Add a callback to be run in the IRenderer / Graphics initialization
*
* @param eventHandler An IEventListener to be called during IRenderer/Graphics setup.
* This handler is currently invoked with a null carb::event::IEvent pointer.
*
*/
virtual void addToInitPipeline(carb::events::IEventListenerPtr eventHandler) = 0;
/**
* Block current thread until renderer (& GPU Foundation) is fully setup
*
*/
virtual void waitForInit() = 0;
/**
* @brief Called immediately after the renderer presents the current frame
* to the frame buffer. This function allows the developer to perform any
* additional operations or processing on the frame after it has been
* presented, such as sending the frame data to a CUDA memory frame for
* further processing. Additionally, the callback can be used to trigger any
* additional actions that need to be taken after the frame has been
* presented, such as updating a status or sending a notification.
*/
virtual carb::events::IEventStream* getPostPresentFrameBufferEventStream(IAppWindow* appWindow) = 0;
/**
* @brief Frozen window is skipped from the run loop and it's not updated.
*/
virtual void freezeAppWindow(IAppWindow* appWindow, bool freeze) = 0;
/*
* @brief State of the present thread
*
* @return true The present thread is enabled
* @return false The present thread is disabled
*/
virtual bool isPresentThreadEnabled() const = 0;
/**
* @brief Create or update a GPU resource.
*
* @param format The format of the texture being created
* @param mipMapResolutions An array of resolutions to use for mip-mapped data
* @param mipMapDatas An array of bytes to upload, for each mip-level
* @param mipMapStrides An array of strides on the bytes to upload, for each mip-level
* @param mipMapCount The number of elements in the mipResolutions, mipDatas, and mipStrides arguments
* @param multiGpu Data will be uploaded or copied to all GPUs in device group
* @param createShared Whether to create the texture as shareable for later use in CUDA or OpenGL
* @param cudaBytes Whether the pointers in mipDatas refer to CPU memory or CUDA memory
* @param deviceMask The devices to create the texture for
*/
virtual TextureGpuData* createGpuResourcesForTexture(carb::Format format,
const carb::Uint2* mipMapResolutions,
const uint8_t* const* mipMapDatas,
const size_t* mipMapStrides,
size_t mipMapCount,
const IRendererTextureOptions& options = {}) = 0;
virtual void updateGpuResourcesForTexture(TextureGpuData* textureGpuData,
carb::Format format,
const carb::Uint2* mipMapResolutions,
const uint8_t* const* mipMapDatas,
const size_t* mipMapStrides,
size_t mipMapCount,
const IRendererTextureOptions& options = {}) = 0;
/**
* Ensures that the resource exists on the target display device, potentially performing an asynchronous GPU copy.
* @return The pointer to the resource on the target display device. If the resource is already on the target
* device, then this pointer will be the same as the input. This function will return nullptr on failure.
* @param resource The resource to potentially copy to the target display device
* @param timeout The timeout (in milliseconds) for the copy operation. The future will return eTimeout if the
* timeout is exceeded.
* @param outTextureHandle Optional: If not nullptr, the GPU handle for the resource on the target device.
* @param outTextureDesc Optional: If not nullptr, the TextureDesc of the returned RpResource will be returned in
* outTextureDesc.
* @param outFuture Optional: If not nullptr, the receiver for a future that can be waited on for the completion of
* the potential GPU copy.
*/
virtual rtx::resourcemanager::RpResource* ensureRpResourceOnTargetDevice(
rtx::resourcemanager::RpResource* resource,
uint32_t timeout,
carb::renderer::TextureHandle* outTextureHandle,
const carb::graphics::TextureDesc** outTextureDesc,
carb::tasking::SharedFuture<gpu::GfResult>* outFuture) = 0;
/**
* @brief Draw-frozen window is not skipped from the run loop and but the
* draw list of this window is not updated.
*/
virtual void drawFreezeAppWindow(IAppWindow* appWindow, bool freeze) = 0;
};
inline IGpuFoundation* IRenderer::getGpuFoundation()
{
return carb::getCachedInterface<IGpuFoundation>();
}
}
}
}
| 17,938 | C | 40.815851 | 128 | 0.640149 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/ParallelScheduler.h | // 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.
//
//! @file ParallelScheduler.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::ParallelSpawner.
#pragma once
#include <omni/graph/exec/unstable/AtomicBackoff.h>
#include <omni/kit/exec/core/unstable/ITbbSchedulerState.h>
#include <omni/kit/exec/core/unstable/TbbSchedulerState.h>
#ifndef __TBB_ALLOW_MUTABLE_FUNCTORS
//! Allow task functors to mutate captured by value state
# define __TBB_ALLOW_MUTABLE_FUNCTORS 1
#endif
#include <tbb/task.h>
#include <tbb/task_group.h>
#include <atomic>
#include <thread>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
#ifndef DOXYGEN_BUILD
//! Parallel scheduler for task dispatch.
//!
//! Currently only needs to handle special requests, actual parallel work is enqueue directly to TBB
class ParallelScheduler
{
public:
//! Access static per-DLL singleton.
static ParallelScheduler& getSingleton()
{
// this static is per-DLL, but the actual private data (s_state) is shared across DLLs
static ParallelScheduler sScheduler;
return sScheduler;
}
//! Class wrapping lambda into serial and parallel tasks. Additionally, this class keeps a track of all
//! created tasks to allow activating isolation pass when all serial and parallel work is completed.
template <typename Fn>
class TaskBody : public tbb::task
{
public:
//! Expected function signature is void(). Increments total task count.
TaskBody(Fn&& f) : m_fn(std::forward<Fn>(f)), m_sharedState(ParallelScheduler::getSingleton().s_state)
{
++m_sharedState->totalTasksInFlight;
}
//! Decrements total task count and starts processing isolate tasks if no more tasks are running.
~TaskBody()
{
--m_sharedState->totalTasksInFlight;
}
//! TBB task execute method calling into lambda. To track nested executions, we increment and decrement
//! tasks per thread atomic counter.
task* execute() override
{
struct ExecutingCountedTaskScope
{
ExecutingCountedTaskScope(tbb::enumerable_thread_specific<int>& executingPerThread)
: _executingPerThread(executingPerThread)
{
_executingPerThread.local()++;
}
~ExecutingCountedTaskScope()
{
_executingPerThread.local()--;
}
tbb::enumerable_thread_specific<int>& _executingPerThread;
} executingScope(m_sharedState->tasksExecutingPerThread);
return m_fn(); // allow for potential continuation
};
private:
Fn m_fn; //!< Lambda function to call from the execute() function.
TbbSchedulerState* m_sharedState{ nullptr }; //!< Scheduler shared state used to track total task count.
};
//! Class wrapping lambda into an isolated TBB task. No other tasks will be running when this task executes.
template <typename Fn>
class IsolateTaskBody : public tbb::task
{
public:
//! Constructor capturing the lambda function
//!
//! Expected function signature is void()
IsolateTaskBody(Fn&& f) : m_fn(std::forward<Fn>(f))
{
}
//! TBB task execute method calling into lambda.
task* execute() override
{
// isolate tasks are not counted in total in flight tasks to allow us detect when
// all other work is finished. Once we are entering scope of isolate task, we make sure
// PauseTaskScope doesn't consider this task as taking part in totalTasksInFlight
struct ExecutingNotCountedTaskScope
{
ExecutingNotCountedTaskScope(tbb::enumerable_thread_specific<int>& executingPerThread)
: _executingPerThread(executingPerThread)
{
auto& perThreadCount = _executingPerThread.local();
_originalPerThread = perThreadCount;
perThreadCount = 0;
}
~ExecutingNotCountedTaskScope()
{
_executingPerThread.local() = _originalPerThread;
}
tbb::enumerable_thread_specific<int>& _executingPerThread;
int _originalPerThread;
} executingScope(ParallelScheduler::getSingleton().s_state->tasksExecutingPerThread);
return m_fn(); // allow for potential continuation
};
private:
Fn m_fn; //!< Lambda function to call from the execute() function
};
//! RAII class used to pause and resume total tasks in flight when thread is about to pick up new tasks to work on.
class PauseTaskScope
{
public:
PauseTaskScope()
: m_scheduler(ParallelScheduler::getSingleton()),
m_isCountedTask(m_scheduler.s_state->tasksExecutingPerThread.local() > 0)
{
if (m_isCountedTask)
{
--m_scheduler.s_state->totalTasksInFlight;
}
}
~PauseTaskScope()
{
if (m_isCountedTask)
{
++m_scheduler.s_state->totalTasksInFlight;
}
}
private:
ParallelScheduler& m_scheduler; //!< To avoid calling into getSingleton multiple times
const bool m_isCountedTask; //!< Know if we are pausing task that was scheduled by us or someone else.
};
//! Typically parallel tasks are spawned right away, but when executed from isolation tasks, we defer spawning
//! until all isolation work is completed.
void pushParallelTask(tbb::task& t, bool isExecutingThread)
{
if (!isProcessingIsolate())
{
if (isExecutingThread && (s_state->totalTasksInFlight < 2))
{
// the executing thread never joins the arena, so won't process its local queue. add the task to the
// global queue. we only do this if there aren't already tasks in flight that can pick up task if we
// spawn() it.
tbb::task::enqueue(t);
}
else
{
tbb::task::spawn(t); // add to local queue
}
}
else
{
s_state->queueParallel.push(&t);
}
}
//! Add task /p t for serial dispatch. This tasks are guaranteed to be run one after another, but other thread-safe
//! tasks are allowed to run together with them
void pushSerialTask(tbb::task& t)
{
s_state->queueSerial.push(&t);
}
//! Store isolate task for execution when no other tasks are running.
void pushIsolateTask(tbb::task& t)
{
s_state->queueIsolate.push(&t);
}
//! Called to notify completion of a serial task and acquire more work if available.
tbb::task* completedSerialTask()
{
tbb::task* serialTask = nullptr;
s_state->queueSerial.try_pop(serialTask);
return serialTask;
}
//! Called to notify completion of an isolate task and acquire more work if available.
tbb::task* completedIsolateTask()
{
tbb::task* isolateTask = nullptr;
s_state->queueIsolate.try_pop(isolateTask);
return isolateTask;
}
//! Returns true if calling thread has been tagged as the one processing serial task. If so, this thread
//! is in the middle of processing a serial task.
bool isWithinSerialTask() const
{
return (s_state->serialThreadId.load() == std::this_thread::get_id());
}
//! Returns true if calling thread has been tagged as the one processing isolate task. If so, this thread
//! is in the middle of processing a isolate task.
bool isWithinIsolateTask() const
{
return (s_state->isolateThreadId.load() == std::this_thread::get_id());
}
//! Returns true if processing of isolate tasks is in progress.
bool isProcessingIsolate() const
{
return (s_state->isolateThreadId.load() != std::thread::id());
}
void processContextThread(tbb::empty_task* rootTask)
{
// See the note in TbbSchedulerState.h as to why we need this
// mutex lock here.
std::lock_guard<tbb::recursive_mutex> lock(s_state->executingThreadMutex);
graph::exec::unstable::AtomicBackoff backoff;
if (isWithinIsolateTask())
{
while (rootTask->ref_count() > 1)
{
if (processQueuedTasks())
backoff.reset();
else
backoff.pause();
}
}
else
{
while (rootTask->ref_count() > 1)
{
if (processSerialTasks() || processIsolateTasks())
backoff.reset();
else
backoff.pause();
}
}
}
private:
//! Explicit call to execute the serial task queueSerial until empty.
//!
bool processSerialTasks()
{
tbb::task* task = nullptr;
s_state->queueSerial.try_pop(task);
// No work
if (!task)
return false;
{
// Acquire the thread that's supposed to be handling serial task evaluation. Note
// that this thread can be derived from many different execution contexts kickstarted
// by multiple different threads.
std::thread::id currentThreadId = std::this_thread::get_id();
std::thread::id originalThreadId;
if (!s_state->serialThreadId.compare_exchange_strong(originalThreadId, currentThreadId) &&
originalThreadId != currentThreadId)
{
return false;
}
// Once serial tasks evaluation is complete, we will want to restore the serial thread ID
// back to its default value; employ an RAII helper to do so.
struct ScopeRelease
{
std::thread::id _originalThreadId;
std::atomic<std::thread::id>& _serialThreadId;
~ScopeRelease()
{
_serialThreadId = _originalThreadId;
}
} threadScope = { originalThreadId, s_state->serialThreadId };
// Run the loop over tasks. We are responsible here to delete the task since it is consumed outside of TBB.
while (task)
{
tbb::task* nextTask = task->execute();
tbb::task::destroy(*task);
task = nextTask;
}
}
// Let the caller know that we had something to do
return true;
}
//! When no more work is available execute isolated tasks.
bool processIsolateTasks()
{
if (s_state->totalTasksInFlight > 0 || s_state->queueIsolate.empty())
{
return false;
}
// try acquire the right to process isolated tasks. Need to support nested executions.
{
std::thread::id currentThreadId = std::this_thread::get_id();
std::thread::id originalThreadId;
if (!s_state->isolateThreadId.compare_exchange_strong(originalThreadId, currentThreadId) &&
originalThreadId != currentThreadId)
{
return false;
}
// we acquired the thread, nothing else will be running until the end of this scope
struct ScopeRelease
{
std::thread::id _originalThreadId;
std::atomic<std::thread::id>& _isolateThreadId;
~ScopeRelease()
{
_isolateThreadId = _originalThreadId;
}
} threadScope = { originalThreadId, s_state->isolateThreadId };
// we don't count isolate tasks, so just pick up the next one
tbb::task* task = completedIsolateTask();
// Run the loop over tasks. We are responsible here to delete the task since it is consumed outside of TBB.
while (task)
{
tbb::task* nextTask = task->execute();
tbb::task::destroy(*task);
task = nextTask;
}
// here we will release this thread from processing isolate tasks.
// We don't worry about synchronization between push tasks and this operation because
// all push call can only happen from within above loop (indirectly via execute). There is no
// other concurrent execution happening when we are in here.
}
// do NOT start parallel work in nested isolate task. it has to be all consumed on this thread until we can
// exit isolation
if (!isWithinIsolateTask())
{
// restart parallel task execution
tbb::task* dispatchTask = nullptr;
while (s_state->queueParallel.try_pop(dispatchTask))
{
if (s_state->totalTasksInFlight < 2)
{
tbb::task::enqueue(*dispatchTask);
}
else
{
tbb::task::spawn(*dispatchTask);
}
}
}
return true;
}
//! This processing should be avoided as much as possible but is necessary when work is generated and executed
//! from within isolate task. We have to empty all the queues and unblock the rest of work.
bool processQueuedTasks()
{
OMNI_ASSERT(isWithinIsolateTask());
bool ret = false;
tbb::task* task = nullptr;
if (s_state->queueIsolate.try_pop(task))
{
while (task)
{
tbb::task* nextTask = task->execute();
tbb::task::destroy(*task); // We are responsible here to delete the task since it is consumed manually
task = nextTask;
}
ret |= true;
}
if (s_state->queueSerial.try_pop(task))
{
while (task)
{
tbb::task* nextTask = task->execute();
tbb::task::destroy(*task); // We are responsible here to delete the task since it is consumed manually
task = nextTask;
}
ret |= true;
}
if (s_state->queueParallel.try_pop(task))
{
do
{
task->execute();
tbb::task::destroy(*task); // We are responsible here to delete the task since it is consumed manually
// parallel tasks don't do scheduling continuation, this is why we don't pick up the next task
} while (s_state->queueParallel.try_pop(task));
ret |= true;
}
return ret;
}
//! Constructor
explicit ParallelScheduler() noexcept
{
omni::core::ObjectPtr<ITbbSchedulerState> sInterface = omni::core::createType<ITbbSchedulerState>();
OMNI_ASSERT(sInterface);
s_state = sInterface->geState();
OMNI_ASSERT(s_state);
}
TbbSchedulerState* s_state; //!< One scheduler state shared by all DLLs
};
namespace detail
{
//! Utility to construct in-place /p allocTask a task /p TaskT wrapping given lambda /p f
template <template <class...> typename TaskT, typename A, typename Fn>
TaskT<Fn>* makeTask(A&& allocTask, Fn&& f)
{
return new (allocTask) TaskT<Fn>(std::forward<Fn>(f));
}
} // namespace detail
#endif // DOXYGEN_BUILD
//! Interface executors use to talk to the scheduler
struct ParallelSpawner
{
//! Constructor
ParallelSpawner(graph::exec::unstable::IExecutionContext* context) : m_context(context)
{
m_root = new (tbb::task::allocate_root()) tbb::empty_task;
m_root->set_ref_count(1);
}
//! Destructor
~ParallelSpawner()
{
tbb::task::destroy(*m_root);
}
//! Thread-safe schedule method called by executor to enqueue generated work.
//! Supports parallel, serial and isolate scheduling constraints.
template <typename Fn>
graph::exec::unstable::Status schedule(Fn&& task, graph::exec::unstable::SchedulingInfo schedInfo)
{
using namespace detail;
if (schedInfo == graph::exec::unstable::SchedulingInfo::eParallel)
{
auto* dispatchTask = detail::makeTask<ParallelScheduler::TaskBody>(
tbb::task::allocate_additional_child_of(*m_root),
[task = graph::exec::unstable::captureScheduleFunction(task), this]() mutable
{
graph::exec::unstable::Status ret = graph::exec::unstable::invokeScheduleFunction(task);
this->accumulateStatus(ret);
return nullptr;
});
ParallelScheduler::getSingleton().pushParallelTask(*dispatchTask, m_context->isExecutingThread());
}
else if (schedInfo == graph::exec::unstable::SchedulingInfo::eIsolate)
{
auto* dispatchTask = detail::makeTask<ParallelScheduler::IsolateTaskBody>(
tbb::task::allocate_additional_child_of(*m_root),
[task = graph::exec::unstable::captureScheduleFunction(task), this]() mutable
{
graph::exec::unstable::Status ret = graph::exec::unstable::invokeScheduleFunction(task);
this->accumulateStatus(ret);
return ParallelScheduler::getSingleton().completedIsolateTask();
});
ParallelScheduler::getSingleton().pushIsolateTask(*dispatchTask);
}
else
{
auto* dispatchTask = detail::makeTask<ParallelScheduler::TaskBody>(
tbb::task::allocate_additional_child_of(*m_root),
[task = graph::exec::unstable::captureScheduleFunction(task), this]() mutable -> tbb::task*
{
graph::exec::unstable::Status ret = graph::exec::unstable::invokeScheduleFunction(task);
this->accumulateStatus(ret);
return ParallelScheduler::getSingleton().completedSerialTask();
});
ParallelScheduler::getSingleton().pushSerialTask(*dispatchTask);
}
return graph::exec::unstable::Status::eSuccess;
}
//! Thread-safe accumulation of status returned by all spawned tasks
void accumulateStatus(graph::exec::unstable::Status ret)
{
graph::exec::unstable::Status current, newValue = graph::exec::unstable::Status::eUnknown;
do
{
current = m_status.load();
newValue = ret | current;
} while (!m_status.compare_exchange_weak(current, newValue));
}
//! Blocking call to acquire accumulated status.
//! When more work is still available, this thread will join the arena and pickup some work OR
//! will be reserved to process serial tasks if we end up here from a serial task (nested scenario).
graph::exec::unstable::Status getStatus()
{
// We are about to enter nested execution. This has an effect on total tasks in flight, i.e.
// we will suspend the current task by reducing the counters. All that is done by RAII class below.
ParallelScheduler::PauseTaskScope pauseTask;
// Note that in situations where multiple different contexts are running from multiple different
// threads, just having the first check (m_context->isExecutingThread()) won't be enough because
// we may be attempting to get the status of a serial/isolate task that was originally created in
// context A running on thread 1 while context B running on thread 2 is being processed in the
// below check; this can occur if context A/thread 1 was temporarily suspended in the past after
// context B/thread 2 beat it to acquiring the s_state->executingThreadMutex, meaning that we
// are currently processing nested tasks (which can be of any scheduling type) that are derived
// from some top-level set of serial/isolate tasks in context B. In such situations, we need to
// additionally check if we are currently within a serial or isolate task scope, since otherwise
// the task originally created in context A/thread 1 will incorrectly skip processing on context B's
// thread, despite thread 2 being the only running context thread at the moment, and take a different
// code-path that leads to hangs. Serial/isolate tasks don't need to be run exclusively on the
// context thread from which they were eventually scheduled - they can be run on any such context
// thread as long as that context thread is the only one running/processing serial/isolate tasks.
if (m_context->isExecutingThread() || ParallelScheduler::getSingleton().isWithinSerialTask() ||
ParallelScheduler::getSingleton().isWithinIsolateTask())
{
ParallelScheduler::getSingleton().processContextThread(m_root);
}
else
{
if (m_root->ref_count() > 1)
{
m_root->wait_for_all();
m_root->set_ref_count(1);
}
}
return m_status;
}
private:
graph::exec::unstable::IExecutionContext* m_context; //!< Execution context used to identify executing thread
tbb::empty_task* m_root{ nullptr }; //!< Root task for all spawned tasks.
std::atomic<graph::exec::unstable::Status> m_status{ graph::exec::unstable::Status::eUnknown }; //!< Accumulated
//!< status
};
} // namespace unable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
| 22,357 | C | 36.513423 | 119 | 0.596905 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionGraphSettings.h | // 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.
//
//! @file IExecutionGraphSettings.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::IExecutionGraphSettings.
#pragma once
#include <omni/graph/exec/unstable/IBase.h>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
// forward declarations needed by interface declaration
class IExecutionGraphSettings;
class IExecutionGraphSettings_abi;
//! Interface for accessing global execution graph settings.
//!
//! This interface is a singleton. The settings are applied to all graphs.
//!
//! Access the singleton with @ref omni::kit::exec::core::unstable::getExecutionGraphSettings().
class IExecutionGraphSettings_abi
: public omni::core::Inherits<graph::exec::unstable::IBase,
OMNI_TYPE_ID("omni.kit.exec.core.unstable.IExecutionGraphSettings")>
{
protected:
//! If @c true all tasks will skip the scheduler and be executed immediately.
virtual bool shouldForceSerial_abi() noexcept = 0;
//! If @c true all tasks will be given to the scheduler and marked as being able to execute in parallel.
virtual bool shouldForceParallel_abi() noexcept = 0;
};
//! Returns the @ref omni::kit::exec::core::unstable::IExecutionGraphSettings singleton.
//!
//! May return @c nullptr if the *omni.kit.exec.core* extension has not been loaded.
//!
//! The returned pointer does not have @ref omni::core::IObject::acquire() called on it.
inline IExecutionGraphSettings* getExecutionGraphSettings() noexcept;
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/kit/exec/core/unstable/IExecutionGraphSettings.gen.h>
//! @copydoc omni::kit::exec::core::unstable::IExecutionGraphSettings_abi
//!
//! @ingroup groupOmniKitExecCoreInterfaces
class omni::kit::exec::core::unstable::IExecutionGraphSettings
: public omni::core::Generated<omni::kit::exec::core::unstable::IExecutionGraphSettings_abi>
{
};
// additional headers needed for API implementation
#include <omni/graph/exec/unstable/IDef.h>
inline omni::kit::exec::core::unstable::IExecutionGraphSettings* omni::kit::exec::core::unstable::getExecutionGraphSettings() noexcept
{
// createType() always calls acquire() and returns an ObjectPtr to make sure release() is called. we don't want
// to hold a ref here to avoid static destruction issues. here we allow the returned ObjectPtr to destruct
// (after calling get()) to release our ref. we know the DLL in which the singleton was created is maintaining a
// ref and will keep the singleton alive for the lifetime of the DLL.
static auto* sSingleton = omni::core::createType<IExecutionGraphSettings>().get();
return sSingleton;
}
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/kit/exec/core/unstable/IExecutionGraphSettings.gen.h>
| 3,376 | C | 36.522222 | 134 | 0.751777 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/Module.h | // 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.
//
//! @file Module.h
//!
//! @brief Helpers for writing modules/plugins based on @ref omni::kit::exec::core.
#pragma once
#include <omni/graph/exec/unstable/Module.h>
#include <omni/kit/exec/core/unstable/IExecutionControllerFactory.h>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
#ifndef DOXYGEN_BUILD
namespace detail
{
void _addClearCallback()
{
}
template <typename Fn>
void _addClearCallback(Fn&& fn)
{
addClearCallback(std::forward<Fn>(fn));
}
} // namespace detail
#endif
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
//! Helper macro to ensure EF features are enabled in the current module/plugin.
//!
//! This macro should be called from either @ref carbOnPluginStartup or @c onStarted.
//!
//! If your module/plugin registers EF nodes or passes, you must call this macro.
//!
//! @p moduleName_ is the name of your plugin and is used for debugging purposes.
//!
//! The second argument is optional and points to a callback that will be called when *any other plugin* that also calls
//! @ref OMNI_KIT_EXEC_CORE_ON_MODULE_STARTED is about to be unloaded. The purpose of the callback is to give *this*
//! module a chance to remove any references to objects that contain code that is about to be unloaded. The signature
//! of the callback is `void(void)`. See @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::addClearCallback for more details.
#define OMNI_KIT_EXEC_CORE_ON_MODULE_STARTED(moduleName_, ...) \
try \
{ \
OMNI_GRAPH_EXEC_ON_MODULE_STARTED(moduleName_); \
omni::kit::exec::core::unstable::detail::_addClearCallback(__VA_ARGS__); \
} \
catch (std::exception & e) \
{ \
CARB_LOG_ERROR("failed to register %s's passes: %s", moduleName_, e.what()); \
}
//! Helper macro to ensure EF features are safely disabled when the current module/plugin unloads.
//!
//! This macro should be called from either @ref carbOnPluginShutdown or @c onUnload.
//!
//! If your module/plugin registers EF nodes or passes, you must call this macro.
#define OMNI_KIT_EXEC_CORE_ON_MODULE_UNLOAD() \
do \
{ \
OMNI_GRAPH_EXEC_ON_MODULE_UNLOAD(); \
omni::kit::exec::core::unstable::getExecutionControllerFactory()->clear(); \
omni::kit::exec::core::unstable::removeClearCallbacks(); \
} while (0)
| 4,041 | C | 44.41573 | 120 | 0.501856 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IClearCallback.h | // 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.
//
//! @file IClearCallback.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::IClearCallback.
#pragma once
#include <omni/graph/exec/unstable/IBase.h>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
class IClearCallback_abi;
class IClearCallback;
//! Interface wrapping a callback (possibly with storage) called when @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::clear is executed.
class IClearCallback_abi : public omni::core::Inherits<omni::graph::exec::unstable::IBase,
OMNI_TYPE_ID("omni.kit.exec.core.unstable.IClearCallback")>
{
protected:
//! Invokes the wrapped function.
virtual void onClear_abi() noexcept = 0;
};
//! Smart pointer managing an instance of @ref IClearCallback.
using ClearCallbackPtr = omni::core::ObjectPtr<IClearCallback>;
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/kit/exec/core/unstable/IClearCallback.gen.h>
//! @copydoc omni::kit::exec::core::unstable::IClearCallback_abi
class omni::kit::exec::core::unstable::IClearCallback
: public omni::core::Generated<omni::kit::exec::core::unstable::IClearCallback_abi>
{
};
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/kit/exec/core/unstable/IClearCallback.gen.h>
| 1,855 | C | 29.426229 | 114 | 0.734771 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionController.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! @ref omni::kit::exec::core::unstable::IExecutionController encapsulates a @ref omni::graph::exec::unstable::IGraph
//! which orchestrates the computation for one of Kit's @c UsdContext.
//!
//! See @ref omni::kit::exec::core::unstable::IExecutionControllerFactory.
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::IExecutionController_abi>
: public omni::kit::exec::core::unstable::IExecutionController_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::IExecutionController")
//! Populates or updates the internal @ref omni::graph::exec::unstable::IGraph.
void compile();
//! Searches for the @ref omni::graph::exec::unstable::IDef and executes it. Useful for on-demand execution.
//!
//! @p *outExecuted is update to @c true if execution was successful, @c false otherwise.
//!
//! An exception will be thrown for all internal errors (e.g. memory allocation failures).
//!
//! This method is not thread safe, only a single thread should call this method at any given time.
bool executeDefinition(omni::core::ObjectParam<omni::graph::exec::unstable::IDef> execDef);
//! Executes the internal graph at the given time.
//!
//! @p *outExecuted is update to @c true if execution was successful, @c false otherwise.
//!
//! An exception will be thrown for all internal errors (e.g. memory allocation failures).
//!
//! This method is not thread safe, only a single thread should call this method at any given time.
bool execute(double currentTime,
float elapsedSecs,
double absoluteSimTime,
const omni::kit::StageUpdateSettings* updateSettings);
//! Returns the context owned by this controller
//!
//! The returned @ref omni::kit::exec::core::unstable::IExecutionContext will *not* have @ref
//! omni::core::IObject::acquire() called before being returned.
omni::kit::exec::core::unstable::IExecutionContext* getContext() noexcept;
//! Returns the graph owned by this controller
//!
//! The returned @ref omni::graph::exec::unstable::IGraph will *not* have @ref
//! omni::core::IObject::acquire() called before being returned.
omni::graph::exec::unstable::IGraph* getGraph() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionController_abi>::compile()
{
OMNI_THROW_IF_FAILED(compile_abi());
}
inline bool omni::core::Generated<omni::kit::exec::core::unstable::IExecutionController_abi>::executeDefinition(
omni::core::ObjectParam<omni::graph::exec::unstable::IDef> execDef)
{
OMNI_THROW_IF_ARG_NULL(execDef);
bool outExecuted;
OMNI_THROW_IF_FAILED(executeDefinition_abi(execDef.get(), &outExecuted));
return outExecuted;
}
inline bool omni::core::Generated<omni::kit::exec::core::unstable::IExecutionController_abi>::execute(
double currentTime, float elapsedSecs, double absoluteSimTime, const omni::kit::StageUpdateSettings* updateSettings)
{
bool outExecuted;
OMNI_THROW_IF_FAILED(execute_abi(currentTime, elapsedSecs, absoluteSimTime, updateSettings, &outExecuted));
return outExecuted;
}
inline omni::kit::exec::core::unstable::IExecutionContext* omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionController_abi>::getContext() noexcept
{
return getContext_abi();
}
inline omni::graph::exec::unstable::IGraph* omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionController_abi>::getGraph() noexcept
{
return getGraph_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 4,516 | C | 37.606837 | 120 | 0.711913 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionControllerFactory.h | // 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.
//
//! @file IExecutionControllerFactory.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::IExecutionControllerFactory.
#pragma once
#include <omni/graph/exec/unstable/IBase.h>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
// forward declarations needed by interface declaration
class IClearCallback;
class IExecutionController;
class IExecutionControllerFactory;
class IExecutionControllerFactory_abi;
//! Factory for creating instances of @ref omni::kit::exec::core::unstable::IExecutionController.
//!
//! This interface also stores the "default" @ref omni::kit::exec::core::unstable::IExecutionController, which is
//! associated with Kit's "default" @c UsdContext.
//!
//! The factory is a singleton. Access the singleton with @ref
//! omni::kit::exec::core::unstable::getExecutionControllerFactory().
class IExecutionControllerFactory_abi
: public omni::core::Inherits<graph::exec::unstable::IBase,
OMNI_TYPE_ID("omni.kit.exec.core.unstable.IExecutionControllerFactory")>
{
protected:
//! Creates an @ref omni::kit::exec::core::unstable::IExecutionController.
//!
//! The given name should match the name of the @c UsdContext.
//!
//! Throws an exception on all errors.
virtual OMNI_ATTR("throw_result") omni::core::Result
createExecutionController_abi(OMNI_ATTR("not_null, throw_if_null, c_str") const char* name,
OMNI_ATTR("out, *return") IExecutionController** out) noexcept = 0;
//! Sets the "default" @ref omni::kit::exec::core::unstable::IExecutionController which should be owned by Kit's
//! "default"
//! @c UsdContext.
//!
//! Throws an exception if the controller has already been set.
//!
//! Throws an exception on all errors.
virtual OMNI_ATTR("throw_result") omni::core::Result
setDefaultExecutionController_abi(OMNI_ATTR("not_null, throw_if_null")
IExecutionController* controller) noexcept = 0;
//! Returns the "default" @ref omni::kit::exec::core::unstable::IExecutionController associated with the "default"
//! @c UsdContext.
//!
//! The returned pointer may be @c nullptr.
//!
//! Prefer calling @ref getDefaultExecutionController() rather than directly calling this method.
virtual IExecutionController* getDefaultExecutionController_abi() noexcept = 0;
//! Attempts to release references to all objects when unloading DLLs.
//!
//! State managed by controllers may store references to objects emanating from many DLLs. As long as a controller
//! stores a reference to an object, it will not be destructed. This causes a problem when unloading DLLs. If a
//! controller's graph/context stores a reference to an object created by "foo.dll" and "foo.dll" is unloaded, when
//! the controller later releases its reference to the object, the object's @c release() method will call into
//! unloaded code, causing a crash.
//!
//! The fix for this disastrous scenario is ensure that no outstanding references to objects created in "foo.dll"
//! are present in the process. This method attempts to do just that by releasing *all* references stored within
//! all controllers/graphs/contexts.
//!
//! A plugin may choose to store references to execution framework objects originating from other modules. In such
//! a case, the plugin can be notified when this @c clear() method is called by invoking @ref
//! omni::kit::exec::core::unstable::addClearCallback when the plugin/module is loaded.
//!
//! Upon completion of this method, pointers to controllers created by this factory will remain valid, though
//! references within the controllers to objects potentially created by other DLLs will have been released.
//!
//! This method is not thread safe.
virtual void clear_abi() noexcept = 0;
//! Adds a callback that will be invoked when @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::clear() is called.
//!
//! @ref omni::kit::exec::core::unstable::IExecutionControllerFactory::clear() is called when a .dll/.so providing
//! execution framework functionality is unloaded (e.g. a plugin that provides a pass or node definition). The
//! purpose of the given callback is to provide the plugin calling this method an opportunity to remove pointers to
//! code that may be unloaded. For example, OmniGraph uses this callback to remove any @ref
//! omni::graph::exec::unstable::IDef pointers in its plugins.
//!
//! Do not call this method directly. Rather, call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_STARTED in either a plugin's
//! @ref carbOnPluginStartup or @c onStarted.
virtual void addClearCallback_abi(OMNI_ATTR("not_null") IClearCallback* callback) noexcept = 0;
//! Removes a callback registered with @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::addClearCallback.
//!
//! If @p callback is @c nullptr or was not registered, this function silently fails.
//!
//! This method should not be explicitly called, rather call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_UNLOAD during
//! plugin/module shutdown.
virtual void removeClearCallback_abi(OMNI_ATTR("not_null") IClearCallback* callback) noexcept = 0;
};
//! Smart pointer for @ref omni::kit::exec::core::unstable::IExecutionControllerFactory.
using ExecutionControllerFactoryPtr = omni::core::ObjectPtr<IExecutionControllerFactory>;
//! Returns the singleton @ref omni::kit::exec::core::unstable::IExecutionControllerFactory.
//!
//! May return @c nullptr if the *omni.kit.exec.core* extension has not been loaded.
//!
//! The returned pointer does not have @ref omni::core::IObject::acquire() called on it.
inline IExecutionControllerFactory* getExecutionControllerFactory() noexcept;
//! Returns the "default" @ref omni::kit::exec::core::unstable::IExecutionController associated with the "default" @c
//! UsdContext.
//!
//! The returned pointer may be @c nullptr.
inline omni::core::ObjectPtr<IExecutionController> getDefaultExecutionController() noexcept;
//! Adds a callback that will be invoked when @ref omni::kit::exec::core::unstable::IExecutionControllerFactory::clear()
//! is called.
//!
//! @ref omni::kit::exec::core::unstable::IExecutionControllerFactory::clear() is called when a .dll/.so providing
//! execution framework functionality is unloaded (e.g. a plugin that provides a pass or node definition). The purpose
//! of the given callback is to provide the plugin calling @ref addClearCallback an opportunity to remove pointers to
//! code that may be unloaded. For example, OmniGraph uses this callback to remove any @ref
//! omni::graph::exec::unstable::IDef pointers in its plugins.
//!
//! Do not call this method directly. Rather, call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_STARTED in either a plugin's
//! @ref carbOnPluginStartup or @c onStarted.
//!
//! The callback will be removed/unregistered by @ref OMNI_KIT_EXEC_CORE_ON_MODULE_UNLOAD.
template <typename Fn>
inline void addClearCallback(Fn&& fn) noexcept;
//! Removes any @ref omni::kit::exec::core::unstable::IExecutionControllerFactory clear callback registered by the
//! plugin/module. This method should not be explicitly called, rather call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_UNLOAD
//! during plugin/module shutdown.
inline void removeClearCallbacks() noexcept;
#ifndef DOXYGEN_BUILD
namespace detail
{
inline std::vector<IClearCallback*>& getClearCallbacks()
{
// we store raw pointers rather than ObjectPtr to avoid static destruction issues
static std::vector<IClearCallback*> sCallbacks;
return sCallbacks;
}
} // namespace detail
#endif // DOXYGEN_BUILD
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/kit/exec/core/unstable/IExecutionControllerFactory.gen.h>
//! @copydoc omni::kit::exec::core::unstable::IExecutionControllerFactory_abi
//!
//! @ingroup groupOmniKitExecCoreInterfaces
class omni::kit::exec::core::unstable::IExecutionControllerFactory
: public omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>
{
};
inline omni::kit::exec::core::unstable::IExecutionControllerFactory* omni::kit::exec::core::unstable::
getExecutionControllerFactory() noexcept
{
// createType() always calls acquire() and returns an ObjectPtr to make sure release() is called. we don't want to
// hold a ref here to avoid static destruction issues. here we allow the returned ObjectPtr to destruct (after
// calling get()) to release our ref. we know the DLL in which the singleton was created is maintaining a ref and
// will keep the singleton alive for the lifetime of the DLL.
static auto sSingleton = omni::core::createType<IExecutionControllerFactory>().get();
return sSingleton;
}
inline omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> omni::kit::exec::core::unstable::
getDefaultExecutionController() noexcept
{
return getExecutionControllerFactory()->getDefaultExecutionController();
}
// additional headers needed for API implementation
#include <omni/kit/exec/core/unstable/IClearCallback.h>
#include <omni/kit/exec/core/unstable/IExecutionController.h>
template <typename Fn>
inline void omni::kit::exec::core::unstable::addClearCallback(Fn&& fn) noexcept
{
class Callback : public graph::exec::unstable::Implements<IClearCallback>
{
public:
Callback(Fn&& fn) : m_fn(std::move(fn))
{
}
protected:
void onClear_abi() noexcept override
{
m_fn();
}
Fn m_fn;
};
Callback* callback = new Callback(std::forward<Fn>(fn));
detail::getClearCallbacks().emplace_back(callback);
getExecutionControllerFactory()->addClearCallback(callback);
}
inline void omni::kit::exec::core::unstable::removeClearCallbacks() noexcept
{
auto factory = getExecutionControllerFactory();
auto& callbacks = detail::getClearCallbacks();
while (!callbacks.empty())
{
auto callback = callbacks.back();
factory->removeClearCallback(callback);
callback->release();
callbacks.pop_back();
}
}
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/kit/exec/core/unstable/IExecutionControllerFactory.gen.h>
| 11,037 | C | 43.329317 | 120 | 0.721392 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IClearCallback.gen.h | // Copyright (c) 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Interface wrapping a callback (possibly with storage) called when @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::clear is executed.
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::IClearCallback_abi>
: public omni::kit::exec::core::unstable::IClearCallback_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::IClearCallback")
//! Invokes the wrapped function.
void onClear() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline void omni::core::Generated<omni::kit::exec::core::unstable::IClearCallback_abi>::onClear() noexcept
{
onClear_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 1,536 | C | 27.999999 | 106 | 0.735677 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/TbbSchedulerState.h | // 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.
//
//! @file TbbSchedulerState.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::TbbSchedulerState.
#pragma once
#include <tbb/concurrent_queue.h>
#include <tbb/enumerable_thread_specific.h>
#include <tbb/recursive_mutex.h>
#include <tbb/task.h>
#include <atomic>
#include <thread>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
//! Implementation details for the TBB based task scheduler state singleton.
//!
//! Will be replaced.
struct TbbSchedulerState
{
tbb::concurrent_queue<tbb::task*> queueParallel; //!< Queue of parallel tasks. Allows concurrent insertion.
tbb::concurrent_queue<tbb::task*> queueSerial; //!< Queue of serial tasks. Allows concurrent insertion.
tbb::concurrent_queue<tbb::task*> queueIsolate; //!< Queue of isolate tasks. Allows concurrent insertion.
std::atomic<int> totalTasksInFlight{ 0 }; //!< Track total number of serial and parallel tasks. Used for isolation.
tbb::enumerable_thread_specific<int> tasksExecutingPerThread{ 0 }; //!< Track execution per thread to know if
//!< waiting on a task contributed to a total
//!< tasks in flight.
std::atomic<std::thread::id> serialThreadId; //!< Thread currently processing serial tasks.
std::atomic<std::thread::id> isolateThreadId; //!< Thread currently processing isolate tasks.
tbb::recursive_mutex executingThreadMutex; //!< Mutex used to serialize the processing of all context threads
//!< (i.e., all threads which kickstarted execution from a any
//!< given ExecutionContexts). This ensures that up to a single context
//!< thread is computing at any given moment, regardless of the number
//!< of threads that kickstarted execution from a given context OR the
//!< number of different ExecutionContexts that began executing
//!< concurrently (assuming that the user is utilizing the provided
//!< ParallelScheduler for those contexts, otherwise they will need to
//!< manage the synchronization on their own), which is important because
//!< serial and isolate tasks are scheduled to run on a context thread,
//!< so allowing multiple context threads to evaluate concurrently would
//!< break the promise that serial and isolate tasks cannot be executed
//!< in multiple threads simultaneously.
};
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
| 3,522 | C | 48.619718 | 120 | 0.601363 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionContext.gen.h | // Copyright (c) 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! @ref omni::kit::exec::core::unstable::IExecutionContext inherits all of the functionality of @ref
//! omni::graph::exec::unstable::IExecutionContext but adds information related to Kit.
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::IExecutionContext_abi>
: public omni::kit::exec::core::unstable::IExecutionContext_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::IExecutionContext")
//! Returns Kit's timing parameters for the current execution.
const omni::kit::exec::core::unstable::ExecutionContextTime* getTime() noexcept;
//! Returns Kit's update settings for the current execution.
const omni::kit::StageUpdateSettings* getUpdateSettings() noexcept;
//! Schedule given function to execute at the end of current execution.
void schedulePostTask(omni::core::ObjectParam<graph::exec::unstable::IScheduleFunction> fn) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline const omni::kit::exec::core::unstable::ExecutionContextTime* omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionContext_abi>::getTime() noexcept
{
return getTime_abi();
}
inline const omni::kit::StageUpdateSettings* omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionContext_abi>::getUpdateSettings() noexcept
{
return getUpdateSettings_abi();
}
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionContext_abi>::schedulePostTask(
omni::core::ObjectParam<graph::exec::unstable::IScheduleFunction> fn) noexcept
{
schedulePostTask_abi(fn.get());
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
static_assert(std::is_standard_layout<omni::kit::exec::core::unstable::ExecutionContextTime>::value,
"omni::kit::exec::core::unstable::ExecutionContextTime must be standard layout to be used in ONI ABI");
| 2,703 | C | 35.54054 | 117 | 0.741028 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionControllerFactory.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Factory for creating instances of @ref omni::kit::exec::core::unstable::IExecutionController.
//!
//! This interface also stores the "default" @ref omni::kit::exec::core::unstable::IExecutionController, which is
//! associated with Kit's "default" @c UsdContext.
//!
//! The factory is a singleton. Access the singleton with @ref
//! omni::kit::exec::core::unstable::getExecutionControllerFactory().
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>
: public omni::kit::exec::core::unstable::IExecutionControllerFactory_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::IExecutionControllerFactory")
//! Creates an @ref omni::kit::exec::core::unstable::IExecutionController.
//!
//! The given name should match the name of the @c UsdContext.
//!
//! Throws an exception on all errors.
omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> createExecutionController(const char* name);
//! Sets the "default" @ref omni::kit::exec::core::unstable::IExecutionController which should be owned by Kit's
//! "default"
//! @c UsdContext.
//!
//! Throws an exception if the controller has already been set.
//!
//! Throws an exception on all errors.
void setDefaultExecutionController(
omni::core::ObjectParam<omni::kit::exec::core::unstable::IExecutionController> controller);
//! Returns the "default" @ref omni::kit::exec::core::unstable::IExecutionController associated with the "default"
//! @c UsdContext.
//!
//! The returned pointer may be @c nullptr.
//!
//! Prefer calling @ref getDefaultExecutionController() rather than directly calling this method.
omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> getDefaultExecutionController() noexcept;
//! Attempts to release references to all objects when unloading DLLs.
//!
//! State managed by controllers may store references to objects emanating from many DLLs. As long as a controller
//! stores a reference to an object, it will not be destructed. This causes a problem when unloading DLLs. If a
//! controller's graph/context stores a reference to an object created by "foo.dll" and "foo.dll" is unloaded, when
//! the controller later releases its reference to the object, the object's @c release() method will call into
//! unloaded code, causing a crash.
//!
//! The fix for this disastrous scenario is ensure that no outstanding references to objects created in "foo.dll"
//! are present in the process. This method attempts to do just that by releasing *all* references stored within
//! all controllers/graphs/contexts.
//!
//! A plugin may choose to store references to execution framework objects originating from other modules. In such
//! a case, the plugin can be notified when this @c clear() method is called by invoking @ref
//! omni::kit::exec::core::unstable::addClearCallback when the plugin/module is loaded.
//!
//! Upon completion of this method, pointers to controllers created by this factory will remain valid, though
//! references within the controllers to objects potentially created by other DLLs will have been released.
//!
//! This method is not thread safe.
void clear() noexcept;
//! Adds a callback that will be invoked when @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::clear() is called.
//!
//! @ref omni::kit::exec::core::unstable::IExecutionControllerFactory::clear() is called when a .dll/.so providing
//! execution framework functionality is unloaded (e.g. a plugin that provides a pass or node definition). The
//! purpose of the given callback is to provide the plugin calling this method an opportunity to remove pointers to
//! code that may be unloaded. For example, OmniGraph uses this callback to remove any @ref
//! omni::graph::exec::unstable::IDef pointers in its plugins.
//!
//! Do not call this method directly. Rather, call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_STARTED in either a plugin's
//! @ref carbOnPluginStartup or @c onStarted.
void addClearCallback(omni::core::ObjectParam<omni::kit::exec::core::unstable::IClearCallback> callback) noexcept;
//! Removes a callback registered with @ref
//! omni::kit::exec::core::unstable::IExecutionControllerFactory::addClearCallback.
//!
//! If @p callback is @c nullptr or was not registered, this function silently fails.
//!
//! This method should not be explicitly called, rather call @ref OMNI_KIT_EXEC_CORE_ON_MODULE_UNLOAD during
//! plugin/module shutdown.
void removeClearCallback(omni::core::ObjectParam<omni::kit::exec::core::unstable::IClearCallback> callback) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::createExecutionController(const char* name)
{
OMNI_THROW_IF_ARG_NULL(name);
omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> out;
OMNI_THROW_IF_FAILED(createExecutionController_abi(name, out.put()));
return out;
}
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::setDefaultExecutionController(
omni::core::ObjectParam<omni::kit::exec::core::unstable::IExecutionController> controller)
{
OMNI_THROW_IF_ARG_NULL(controller);
OMNI_THROW_IF_FAILED(setDefaultExecutionController_abi(controller.get()));
}
inline omni::core::ObjectPtr<omni::kit::exec::core::unstable::IExecutionController> omni::core::Generated<
omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::getDefaultExecutionController() noexcept
{
return omni::core::steal(getDefaultExecutionController_abi());
}
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::clear() noexcept
{
clear_abi();
}
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::addClearCallback(
omni::core::ObjectParam<omni::kit::exec::core::unstable::IClearCallback> callback) noexcept
{
addClearCallback_abi(callback.get());
}
inline void omni::core::Generated<omni::kit::exec::core::unstable::IExecutionControllerFactory_abi>::removeClearCallback(
omni::core::ObjectParam<omni::kit::exec::core::unstable::IClearCallback> callback) noexcept
{
removeClearCallback_abi(callback.get());
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 7,550 | C | 46.791139 | 131 | 0.726225 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionContext.h | // 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.
//
//! @file IExecutionContext.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::IExecutionContext.
#pragma once
#include <omni/graph/exec/unstable/IExecutionContext.h>
namespace omni
{
namespace kit
{
struct StageUpdateSettings;
namespace exec
{
namespace core
{
namespace unstable
{
//! ABI-safe struct containing time information for graph execution.
struct ExecutionContextTime
{
double currentTime; //!< Current execution time (within application timeline)
double absoluteSimTime; //!< Absolute simulation time (from start of simulation)
float elapsedSecs; //!< Time elapsed since last execution
bool timeChanged; //!< Is this execution triggered by a time change
char _padding; //!< Padding
char _padding1; //!< Padding
char _padding2; //!< Padding
};
static_assert(std::is_standard_layout<ExecutionContextTime>::value, "ExecutionContextTime is not ABI-safe");
static_assert(offsetof(ExecutionContextTime, currentTime) == 0, "unexpected offset");
static_assert(offsetof(ExecutionContextTime, absoluteSimTime) == 8, "unexpected offset");
static_assert(offsetof(ExecutionContextTime, elapsedSecs) == 16, "unexpected offset");
static_assert(offsetof(ExecutionContextTime, timeChanged) == 20, "unexpected offset");
static_assert(24 == sizeof(ExecutionContextTime), "unexpected size");
// forward declarations needed by interface declaration
class IExecutionContext;
class IExecutionContext_abi;
class IScheduleFunction;
//! @ref omni::kit::exec::core::unstable::IExecutionContext inherits all of the functionality of @ref
//! omni::graph::exec::unstable::IExecutionContext but adds information related to Kit.
class IExecutionContext_abi : public omni::core::Inherits<omni::graph::exec::unstable::IExecutionContext,
OMNI_TYPE_ID("omni.kit.exec.core.unstable.IExecutionContext")>
{
protected:
//! Returns Kit's timing parameters for the current execution.
virtual const ExecutionContextTime* getTime_abi() noexcept = 0;
//! Returns Kit's update settings for the current execution.
virtual const omni::kit::StageUpdateSettings* getUpdateSettings_abi() noexcept = 0;
//! Schedule given function to execute at the end of current execution.
virtual void schedulePostTask_abi(OMNI_ATTR("not_null") graph::exec::unstable::IScheduleFunction* fn) noexcept = 0;
};
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include "IExecutionContext.gen.h"
//! @copydoc omni::kit::exec::core::unstable::IExecutionContext_abi
class omni::kit::exec::core::unstable::IExecutionContext
: public omni::core::Generated<omni::kit::exec::core::unstable::IExecutionContext_abi>
{
public:
//! Schedule given function to execute at the end of current execution.
//!
//! This inline implementation wraps lambda into IScheduleFunction.
//!
//! The supplied function should have the signature of `void()`.
//!
//! Returns true if function was scheduled. False when context is currently not executing and function won't be
//! scheduled.
template <typename FN>
inline bool schedulePostTask(FN&& callback);
};
// additional headers needed for API implementation
#include <omni/graph/exec/unstable/IScheduleFunction.h>
template <typename FN>
inline bool omni::kit::exec::core::unstable::IExecutionContext::schedulePostTask(FN&& callback)
{
class Forwarder : public graph::exec::unstable::Implements<graph::exec::unstable::IScheduleFunction>
{
public:
Forwarder(FN&& fn) : m_fn(std::move(fn))
{
}
protected:
graph::exec::unstable::Status invoke_abi() noexcept override
{
m_fn();
return graph::exec::unstable::Status::eSuccess;
}
FN m_fn;
};
if (inExecute())
{
schedulePostTask_abi(omni::core::steal(new Forwarder(std::forward<FN>(callback))).get());
return true;
}
else
{
return false;
}
}
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include "IExecutionContext.gen.h"
| 4,659 | C | 33.518518 | 120 | 0.716892 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionController.h | // 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.
//
//! @file IExecutionController.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::IExecutionController.
#pragma once
#include <omni/graph/exec/unstable/IBase.h>
#include <omni/kit/IStageUpdate.h> // StageUpdateSettings
//! @defgroup groupOmniKitExecCoreInterfaces API Interfaces
//!
//! @brief Convenience interfaces backed by a stable ABI.
namespace omni
{
namespace graph
{
namespace exec
{
namespace unstable
{
class IDef;
class IGraph;
} // namespace unstable
} // namespace exec
} // namespace graph
namespace kit
{
namespace exec
{
//! Main namespace for Kit's integration of @ref omni::graph::exec.
namespace core
{
//! In-development interfaces for Kit's integration with Execution Framework.
//! Do not take dependencies on any code in this namespace.
namespace unstable
{
// forward declarations needed by interface declaration
class IExecutionContext;
class IExecutionController;
class IExecutionController_abi;
//! @ref omni::kit::exec::core::unstable::IExecutionController encapsulates a @ref omni::graph::exec::unstable::IGraph
//! which orchestrates the computation for one of Kit's @c UsdContext.
//!
//! See @ref omni::kit::exec::core::unstable::IExecutionControllerFactory.
class IExecutionController_abi
: public omni::core::Inherits<graph::exec::unstable::IBase, OMNI_TYPE_ID("omni.kit.exec.core.unstable.IExecutionController")>
{
protected:
//! Populates or updates the internal @ref omni::graph::exec::unstable::IGraph.
virtual OMNI_ATTR("throw_result") omni::core::Result compile_abi() noexcept = 0;
//! Searches for the @ref omni::graph::exec::unstable::IDef and executes it. Useful for on-demand execution.
//!
//! @p *outExecuted is update to @c true if execution was successful, @c false otherwise.
//!
//! An exception will be thrown for all internal errors (e.g. memory allocation failures).
//!
//! This method is not thread safe, only a single thread should call this method at any given time.
virtual OMNI_ATTR("throw_result") omni::core::Result
executeDefinition_abi(OMNI_ATTR("not_null, throw_if_null") omni::graph::exec::unstable::IDef* execDef,
OMNI_ATTR("out, not_null, throw_if_null, *return") bool* outExecuted) noexcept = 0;
//! Executes the internal graph at the given time.
//!
//! @p *outExecuted is update to @c true if execution was successful, @c false otherwise.
//!
//! An exception will be thrown for all internal errors (e.g. memory allocation failures).
//!
//! This method is not thread safe, only a single thread should call this method at any given time.
virtual OMNI_ATTR("throw_result") omni::core::Result
execute_abi(double currentTime,
float elapsedSecs,
double absoluteSimTime,
OMNI_ATTR("in") const omni::kit::StageUpdateSettings* updateSettings,
OMNI_ATTR("out, not_null, throw_if_null, *return") bool* outExecuted) noexcept = 0;
//! Returns the context owned by this controller
//!
//! The returned @ref omni::kit::exec::core::unstable::IExecutionContext will *not* have @ref
//! omni::core::IObject::acquire() called before being returned.
virtual OMNI_ATTR("no_acquire") IExecutionContext* getContext_abi() noexcept = 0;
//! Returns the graph owned by this controller
//!
//! The returned @ref omni::graph::exec::unstable::IGraph will *not* have @ref
//! omni::core::IObject::acquire() called before being returned.
virtual OMNI_ATTR("no_acquire") omni::graph::exec::unstable::IGraph* getGraph_abi() noexcept = 0;
};
//! Smart pointer for @ref omni::kit::exec::core::unstable::IExecutionController.
using ExecutionControllerPtr = omni::core::ObjectPtr<IExecutionController>;
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/kit/exec/core/unstable/IExecutionController.gen.h>
//! @copydoc omni::kit::exec::core::unstable::IExecutionController_abi
//!
//! @ingroup groupOmniKitExecCoreInterfaces
class omni::kit::exec::core::unstable::IExecutionController
: public omni::core::Generated<omni::kit::exec::core::unstable::IExecutionController_abi>
{
};
// additional headers needed for API implementation
#include <omni/graph/exec/unstable/IDef.h>
#include <omni/graph/exec/unstable/IGraph.h>
#include <omni/kit/exec/core/unstable/IExecutionContext.h>
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/kit/exec/core/unstable/IExecutionController.gen.h>
| 5,112 | C | 36.050724 | 129 | 0.717723 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/IExecutionGraphSettings.gen.h | // 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Interface for accessing global execution graph settings.
//!
//! This interface is a singleton. The settings are applied to all graphs.
//!
//! Access the singleton with @ref omni::kit::exec::core::unstable::getExecutionGraphSettings().
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::IExecutionGraphSettings_abi>
: public omni::kit::exec::core::unstable::IExecutionGraphSettings_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::IExecutionGraphSettings")
//! If @c true all tasks will skip the scheduler and be executed immediately.
bool shouldForceSerial() noexcept;
//! If @c true all tasks will be given to the scheduler and marked as being able to execute in parallel.
bool shouldForceParallel() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline bool omni::core::Generated<omni::kit::exec::core::unstable::IExecutionGraphSettings_abi>::shouldForceSerial() noexcept
{
return shouldForceSerial_abi();
}
inline bool omni::core::Generated<omni::kit::exec::core::unstable::IExecutionGraphSettings_abi>::shouldForceParallel() noexcept
{
return shouldForceParallel_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 2,061 | C | 31.21875 | 127 | 0.745754 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/ITbbSchedulerState.gen.h | // Copyright (c) 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.
//
// --------- Warning: This is a build system generated file. ----------
//
//! @file
//!
//! @brief This file was generated by <i>omni.bind</i>.
#include <omni/core/Interface.h>
#include <omni/core/OmniAttr.h>
#include <omni/core/ResultError.h>
#include <functional>
#include <type_traits>
#include <utility>
#ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL
//! Returns a global scheduler state based on TBB.
//!
//! This object is a singleton. Access it with @ref omni::kit::exec::core::unstable::getTbbSchedulerState().
//!
//! Use of this object should be transparent to the user as it is an implementation detail of
//! @ref omni::kit::exec::core::unstable::ParallelSpawner.
//!
//! Temporary interface. Will be replaced with something more generic.
template <>
class omni::core::Generated<omni::kit::exec::core::unstable::ITbbSchedulerState_abi>
: public omni::kit::exec::core::unstable::ITbbSchedulerState_abi
{
public:
OMNI_PLUGIN_INTERFACE("omni::kit::exec::core::unstable::ITbbSchedulerState")
//! Returns the needed data to access the serial task queue.
omni::kit::exec::core::unstable::TbbSchedulerState* geState() noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline omni::kit::exec::core::unstable::TbbSchedulerState* omni::core::Generated<
omni::kit::exec::core::unstable::ITbbSchedulerState_abi>::geState() noexcept
{
return geState_abi();
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 1,923 | C | 31.066666 | 109 | 0.733229 |
omniverse-code/kit/include/omni/kit/exec/core/unstable/ITbbSchedulerState.h | // 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.
//
//! @file ITbbSchedulerState.h
//!
//! @brief Defines @ref omni::kit::exec::core::unstable::ITbbSchedulerState.
#pragma once
#include <omni/graph/exec/unstable/IBase.h>
namespace omni
{
namespace kit
{
namespace exec
{
namespace core
{
namespace unstable
{
struct TbbSchedulerState;
// forward declarations needed by interface declaration
class ITbbSchedulerState;
class ITbbSchedulerState_abi;
//! Returns a global scheduler state based on TBB.
//!
//! This object is a singleton. Access it with @ref omni::kit::exec::core::unstable::getTbbSchedulerState().
//!
//! Use of this object should be transparent to the user as it is an implementation detail of
//! @ref omni::kit::exec::core::unstable::ParallelSpawner.
//!
//! Temporary interface. Will be replaced with something more generic.
class ITbbSchedulerState_abi
: public omni::core::Inherits<graph::exec::unstable::IBase, OMNI_TYPE_ID("omni.kit.exec.core.unstable.ITbbSchedulerState")>
{
protected:
//! Returns the needed data to access the serial task queue.
virtual TbbSchedulerState* geState_abi() noexcept = 0;
};
//! Returns the singleton @ref omni::kit::exec::core::unstable::ITbbSchedulerState.
//!
//! May return @c nullptr if the *omni.kit.exec.core* extension has not been loaded.
//!
//! The returned pointer does not have @ref omni::core::IObject::acquire() called on it.
inline ITbbSchedulerState* getTbbSchedulerState() noexcept;
} // namespace unstable
} // namespace core
} // namespace exec
} // namespace kit
} // namespace omni
// generated API declaration
#define OMNI_BIND_INCLUDE_INTERFACE_DECL
#include <omni/kit/exec/core/unstable/ITbbSchedulerState.gen.h>
//! @copydoc omni::kit::exec::core::unstable::ITbbSchedulerState_abi
class omni::kit::exec::core::unstable::ITbbSchedulerState
: public omni::core::Generated<omni::kit::exec::core::unstable::ITbbSchedulerState_abi>
{
};
inline omni::kit::exec::core::unstable::ITbbSchedulerState* omni::kit::exec::core::unstable::getTbbSchedulerState() noexcept
{
// createType() always calls acquire() and returns an ObjectPtr to make sure release() is called. we don't want to
// hold a ref here to avoid static destruction issues. here we allow the returned ObjectPtr to destruct (after
// calling get()) to release our ref. we know the DLL in which the singleton was created is maintaining a ref and
// will keep the singleton alive for the lifetime of the DLL.
static auto sSingleton = omni::core::createType<ITbbSchedulerState>().get();
return sSingleton;
}
// generated API implementation
#define OMNI_BIND_INCLUDE_INTERFACE_IMPL
#include <omni/kit/exec/core/unstable/ITbbSchedulerState.gen.h>
| 3,116 | C | 35.244186 | 127 | 0.751284 |
omniverse-code/kit/include/omni/kit/actions/core/IAction.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/variant/IVariant.h>
#include <carb/variant/VariantUtils.h>
namespace omni
{
namespace kit
{
namespace actions
{
namespace core
{
/**
* Pure virtual action interface.
*/
class IAction : public carb::IObject
{
public:
/**
* Function prototype to execute an action.
*
* @param args Variable positional argument (optional).
* Maybe a VariantArray with multiple args.
* @param kwargs Variable keyword arguments (optional).
*
* @return An arbitrary variant object (could be empty).
*/
using ExecuteFunctionType = carb::variant::Variant (*)(const carb::variant::Variant& /*args*/,
const carb::dictionary::Item* /*kwargs*/);
/**
* Called when something wants to execute this action.
*
* @param args Variable positional argument (optional).
* Maybe a VariantArray with multiple args.
* @param kwargs Variable keyword arguments (optional).
*
* @return An arbitrary variant object (could be empty).
*/
virtual carb::variant::Variant execute(const carb::variant::Variant& args = {},
const carb::dictionary::Item* kwargs = nullptr) = 0;
/**
* Invalidate this action so that executing it will not do anything.
* This can be called if it is no longer safe to execute the action,
* and by default is called when deregistering an action (optional).
*/
virtual void invalidate() = 0;
/**
* Is this an instance of the derived PythonAction class?
*
* @return True if this an instance of the derived PythonAction class, false otherwise.
*/
virtual bool isPythonAction() const = 0;
/**
* Get the id of the source extension which registered this action.
*
* @return Id of the source extension which registered this action.
*/
virtual const char* getExtensionId() const = 0;
/**
* Get the id of this action, unique to the extension that registered it.
*
* @return Id of this action, unique to the extension that registered it.
*/
virtual const char* getActionId() const = 0;
/**
* Get the display name of this action.
*
* @return Display name of this action.
*/
virtual const char* getDisplayName() const = 0;
/**
* Get the description of this action.
*
* @return Description of this action.
*/
virtual const char* getDescription() const = 0;
/**
* Get the URL of the icon used to represent this action.
*
* @return URL of the icon used to represent this action.
*/
virtual const char* getIconUrl() const = 0;
/**
* Get the tag that this action is grouped with.
*
* @return Tag that this action is grouped with.
*/
virtual const char* getTag() const = 0;
};
using IActionPtr = carb::ObjectPtr<IAction>;
inline bool operator==(const carb::ObjectPtr<IAction>& left, const carb::ObjectPtr<IAction>& right) noexcept
{
return (left.get() == right.get());
}
}
}
}
}
| 3,591 | C | 28.68595 | 108 | 0.641047 |
omniverse-code/kit/include/omni/kit/actions/core/IActionRegistry.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/actions/core/IAction.h>
#include <carb/Interface.h>
#include <vector>
namespace omni
{
namespace kit
{
namespace actions
{
namespace core
{
/**
* Defines the interface for the ActionRegistry.
*/
class IActionRegistry
{
public:
/// @private
CARB_PLUGIN_INTERFACE("omni::kit::actions::core::IActionRegistry", 1, 0);
/**
* Register an action.
*
* @param action The action to register.
*/
virtual void registerAction(carb::ObjectPtr<IAction>& action) = 0;
/**
* Create and register an action that calls a function object when executed.
*
* @param extensionId The id of the source extension registering the action.
* @param actionId Id of the action, unique to the extension registering it.
* @param function The function object to call when the action is executed.
* @param displayName The name of the action for display purposes.
* @param description A brief description of what the action does.
* @param iconUrl The URL of an image which represents the action.
* @param tag Arbitrary tag used to group sets of related actions.
*
* @return The action that was created.
*/
virtual carb::ObjectPtr<IAction> registerAction(const char* extensionId,
const char* actionId,
IAction::ExecuteFunctionType function,
const char* displayName = "",
const char* description = "",
const char* iconUrl = "",
const char* tag = "") = 0;
/**
* Deregister an action.
*
* @param action The action to deregister.
* @param invalidate Should the action be invalidated so executing does nothing?
*/
virtual void deregisterAction(carb::ObjectPtr<IAction>& action, bool invalidate = true) = 0;
/**
* Find and deregister an action.
*
* @param extensionId The id of the source extension that registered the action.
* @param actionId Id of the action, unique to the extension that registered it.
* @param invalidate Should the action be invalidated so executing does nothing?
*
* @return The action if it exists and was deregistered, an empty ObjectPtr otherwise.
*/
virtual carb::ObjectPtr<IAction> deregisterAction(const char* extensionId,
const char* actionId,
bool invalidate = true) = 0;
/**
* Deregister all actions that were registered by the specified extension.
*
* @param extensionId The id of the source extension that registered the actions.
* @param invalidate Should the actions be invalidated so executing does nothing?
*/
virtual void deregisterAllActionsForExtension(const char* extensionId, bool invalidate = true) = 0;
/**
* Find and execute an action.
*
* @param extensionId The id of the source extension that registered the action.
* @param actionId Id of the action, unique to the extension that registered it.
* @param args Variable positional argument (optional).
* Maybe a VariantArray with multiple args.
* @param kwargs Variable keyword arguments (optional).
*
* @return An arbitrary variant object (could be empty).
*/
virtual carb::variant::Variant executeAction(const char* extensionId,
const char* actionId,
const carb::variant::Variant& args = {},
const carb::dictionary::Item* kwargs = nullptr) const = 0;
/**
* Get an action.
*
* @param extensionId The id of the source extension that registered the action.
* @param actionId Id of the action, unique to the extension that registered it.
*
* @return The action if it exists, an empty ObjectPtr otherwise.
*/
virtual carb::ObjectPtr<IAction> getAction(const char* extensionId, const char* actionId) const = 0;
/**
* Get the total number of registered actions.
*
* @return Total number of registered actions.
*/
virtual size_t getActionCount() const = 0;
/**
* Callback function used by @ref IActionRegistry::walkAllActions.
*
* @param action The current action being visited by @ref IActionRegistry::walkAllActions.
* @param context Any user defined data that was passed to @ref IActionRegistry::walkAllActions.
*
* @return True if we should continue walking through all registered actions, false otherwise.
*/
using WalkActionsCallbackFn = bool(*)(carb::ObjectPtr<IAction> action, void* context);
/**
* Walks through all registered actions and calls a callback function for each.
*
* @param callbackFn The callback function to call for each registered action,
* until all actions have been visited or the callback function returns false.
* @param context User defined data that will be passed to callback function.
*
* @return The number of actions that were visited.
*/
virtual size_t walkAllActions(WalkActionsCallbackFn callbackFn, void* context) const = 0;
/**
* Walks through all actions that were registered by the specified extension.
*
* @param callbackFn The callback function to call for each registered action,
* until all actions have been visited or the callback function returns false.
* @param context User defined data that will be passed to callback function.
* @param extensionId The id of the extension which registered the actions.
*
* @return The number of actions that were visited.
*/
virtual size_t walkAllActionsRegisteredByExtension(WalkActionsCallbackFn callbackFn,
void* context,
const char* extensionId) const = 0;
/**
* Get all registered actions.
*
* @return All registered actions.
*/
std::vector<carb::ObjectPtr<IAction>> getAllActions() const
{
std::vector<carb::ObjectPtr<IAction>> actions;
const size_t numActionsWalked = walkAllActions(
[](carb::ObjectPtr<IAction> action, void* context) {
auto actionsPtr = static_cast<std::vector<carb::ObjectPtr<IAction>>*>(context);
actionsPtr->push_back(action);
return true;
},
&actions);
CARB_ASSERT(numActionsWalked == actions.size());
CARB_UNUSED(numActionsWalked);
return actions;
}
/**
* Get all actions that were registered by the specified extension.
*
* @param extensionId Id of the extension which registered the actions.
*
* @return All actions that were registered by the specified extension.
*/
std::vector<carb::ObjectPtr<IAction>> getAllActionsForExtension(const char* extensionId) const
{
std::vector<carb::ObjectPtr<IAction>> actions;
const size_t numActionsWalked = walkAllActionsRegisteredByExtension(
[](carb::ObjectPtr<IAction> action, void* context) {
auto actionsPtr = static_cast<std::vector<carb::ObjectPtr<IAction>>*>(context);
actionsPtr->push_back(action);
return true;
},
&actions, extensionId);
CARB_ASSERT(numActionsWalked == actions.size());
CARB_UNUSED(numActionsWalked);
return actions;
}
};
}
}
}
}
| 8,260 | C | 38.526316 | 107 | 0.624092 |
omniverse-code/kit/include/omni/kit/actions/core/Action.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/actions/core/IAction.h>
#include <carb/ObjectUtils.h>
#include <omni/String.h>
namespace omni
{
namespace kit
{
namespace actions
{
namespace core
{
/**
* Abstract action base class providing the core functionaly common to all actions.
*/
class Action : public IAction
{
public:
/**
* Struct containing all optional data that can be associated with any action.
*/
struct MetaData
{
omni::string displayName; //!< The name of the action for display purposes.
omni::string description; //!< A brief description of what the action does.
omni::string iconUrl; //!< The URL of an image which represents the action.
omni::string tag; //!< Arbitrary tag used to group sets of related actions.
};
/**
* Constructor.
*
* @param extensionId The id of the source extension registering the action.
* @param actionId Id of the action, unique to the extension registering it.
* @param metaData Pointer to a meta data struct associated with the action.
*/
Action(const char* extensionId, const char* actionId, const MetaData* metaData = nullptr)
: m_extensionId(extensionId ? extensionId : ""), m_actionId(actionId ? actionId : "")
{
if (metaData)
{
m_metaData = *metaData;
}
}
/**
* Destructor.
*/
~Action() override = default;
/**
* @ref IAction::isPythonAction
*/
bool isPythonAction() const override
{
return false;
}
/**
* @ref IAction::getExtensionId
*/
const char* getExtensionId() const override
{
return m_extensionId.c_str();
}
/**
* @ref IAction::getActionId
*/
const char* getActionId() const override
{
return m_actionId.c_str();
}
/**
* @ref IAction::getDisplayName
*/
const char* getDisplayName() const override
{
return m_metaData.displayName.c_str();
}
/**
* @ref IAction::getDescription
*/
const char* getDescription() const override
{
return m_metaData.description.c_str();
}
/**
* @ref IAction::getIconUrl
*/
const char* getIconUrl() const override
{
return m_metaData.iconUrl.c_str();
}
/**
* @ref IAction::getTag
*/
const char* getTag() const override
{
return m_metaData.tag.c_str();
}
protected:
omni::string m_extensionId; //!< The id of the source extension that registered the action.
omni::string m_actionId; //!< Id of the action, unique to the extension that registered it.
MetaData m_metaData; //!< Struct containing all the meta data associated with this action.
private:
CARB_IOBJECT_IMPL
};
}
}
}
}
| 3,224 | C | 23.24812 | 95 | 0.635546 |
omniverse-code/kit/include/omni/kit/actions/core/LambdaAction.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/actions/core/Action.h>
#include <carb/thread/Mutex.h>
namespace omni
{
namespace kit
{
namespace actions
{
namespace core
{
/**
* Concrete action class that can be used to create an action from C++ which calls a supplied lambda/function.
*/
class LambdaAction : public Action
{
public:
/**
* Factory.
*
* @param extensionId The id of the source extension registering the action.
* @param actionId Id of the action, unique to the extension registering it.
* @param metaData Pointer to a meta data struct associated with the action.
* @param function The function object to call when the action is executed.
*
* @return The action that was created.
*/
static carb::ObjectPtr<IAction> create(const char* extensionId,
const char* actionId,
const MetaData* metaData,
ExecuteFunctionType function)
{
// Note: It is important to construct the handler using ObjectPtr<T>::InitPolicy::eSteal,
// otherwise we end up incresing the reference count by one too many during construction,
// resulting in a carb::ObjectPtr<IAction> whose object instance will never be destroyed.
return carb::stealObject<IAction>(new LambdaAction(extensionId, actionId, metaData, function));
}
/**
* Constructor.
*
* @param extensionId The id of the source extension registering the action.
* @param actionId Id of the action, unique to the extension registering it.
* @param metaData Pointer to a meta data struct associated with the action.
* @param function The function object to call when the action is executed.
*/
LambdaAction(const char* extensionId, const char* actionId, const MetaData* metaData, ExecuteFunctionType function)
: Action(extensionId, actionId, metaData), m_function(function)
{
}
/**
* Destructor.
*/
~LambdaAction() override = default;
/**
* @ref IAction::execute
*/
carb::variant::Variant execute(const carb::variant::Variant& args = {},
const carb::dictionary::Item* kwargs = nullptr) override
{
std::lock_guard<carb::thread::mutex> lock(m_mutex);
return m_function ? m_function(args, kwargs) : carb::variant::Variant();
}
/**
* @ref IAction::invalidate
*/
void invalidate() override
{
std::lock_guard<carb::thread::mutex> lock(m_mutex);
m_function = nullptr;
}
private:
ExecuteFunctionType m_function; //!< The function object to call when the action is executed.
carb::thread::mutex m_mutex; //!< Mutex to lock for thread safety when calling the function.
};
}
}
}
}
| 3,270 | C | 32.721649 | 119 | 0.657187 |
omniverse-code/kit/include/omni/kit/xr/XRBootstrap.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/settings/ISettings.h>
#include <carb/settings/SettingsUtils.h>
#include <vector>
#include <string>
#include <set>
namespace omni
{
namespace kit
{
namespace xr
{
/**
* @brief Gets a list of (Vulkan) extensions, which is overridable and has default values
*
* @param path a settings path to store an overridable copy of this list
* @param hardCodedExtensions pre-loaded list of (vk) extensions
* @return std::vector<std::string> list of (vk) extensions to use
*/
inline std::vector<std::string> getExtensions(const char* path, const std::vector<std::string>& hardCodedExtensions)
{
CARB_PROFILE_ZONE(carb::profiler::kCaptureMaskDefault, "XRContext::getExtensions");
// This provides a way of other plugins/extensions to list additional extensions to load for
// an instance or device:
// This code scans the settings dictionaries under:
// /renderer/vulkan/deviceExtensions and /renderer/vulkan/instanceExtensions and will check if the items
// found contain an array, if they do the array is parsed and it's contents is added to the
// list of extensions to load
carb::settings::ISettings* settings = carb::getCachedInterface<carb::settings::ISettings>();
carb::dictionary::IDictionary* dictionary = carb::getCachedInterface<carb::dictionary::IDictionary>();
auto type = settings->getItemType(path);
std::set<std::string> extensions;
extensions.insert(hardCodedExtensions.begin(), hardCodedExtensions.end());
if (type == carb::dictionary::ItemType::eDictionary)
{
auto item = settings->getSettingsDictionary(path);
size_t count = dictionary->getItemChildCount(item);
for (size_t idx = 0; idx < count; idx++)
{
auto child = dictionary->getItemChildByIndex(item, idx);
auto childType = dictionary->getItemType(child);
if (childType == carb::dictionary::ItemType::eString)
{
std::string extension = dictionary->getStringBuffer(child);
extensions.insert(extension);
}
else if (childType == carb::dictionary::ItemType::eDictionary)
{
if (dictionary->isAccessibleAsArrayOf(carb::dictionary::ItemType::eString, child))
{
size_t arrLength = dictionary->getArrayLength(child);
for (size_t arrIdx = 0; arrIdx < arrLength; ++arrIdx)
{
std::string ext = dictionary->getStringBufferAt(child, arrIdx);
extensions.insert(ext);
}
}
}
}
}
std::vector<std::string> result;
result.insert(result.begin(), extensions.begin(), extensions.end());
return result;
}
/**
* @brief Ensure compatibility with XR
*
* Various XR plugins (especially SteamVR) require certain renderer options.
* Ensure those options are set before an XRSystem is initialized.
*/
inline void bootstrapXR()
{
auto settings = carb::getCachedInterface<carb::settings::ISettings>();
// If an XR extension is enabled disable the validation layer for now
if (settings->getAsBool("/xr/debug"))
{
// This one breaks openvr
settings->setBool("/renderer/debug/validation/enabled", false);
}
#if CARB_PLATFORM_WINDOWS
std::vector<std::string> instanceExtensions =
getExtensions("/persistent/xr/vulkanInstanceExtensions",
{ "VK_NV_external_memory_capabilities", "VK_KHR_external_memory_capabilities",
"VK_KHR_get_physical_device_properties2" });
std::vector<std::string> deviceExtensions = getExtensions(
"/persistent/xr/vulkanDeviceExtensions", { "VK_NV_dedicated_allocation", "VK_NV_external_memory",
"VK_NV_external_memory_win32", "VK_NV_win32_keyed_mutex" });
#elif CARB_PLATFORM_LINUX
std::vector<std::string> instanceExtensions =
getExtensions("/persistent/xr/vulkanInstanceExtensions",
{ "VK_KHR_external_memory_capabilities", "VK_KHR_get_physical_device_properties2",
"VK_KHR_external_semaphore_capabilities" });
std::vector<std::string> deviceExtensions = getExtensions(
"/persistent/xr/vulkanDeviceExtensions",
{ "VK_KHR_external_memory", "VK_KHR_external_semaphore", "VK_KHR_dedicated_allocation",
"VK_KHR_get_memory_requirements2", "VK_KHR_external_memory_fd", "VK_KHR_external_semaphore_fd" });
#elif CARB_PLATFORM_MACOS
// FIXME!! do some actual checks here. MacOS doesn't natively support Vulkan and only
// supports it by using MoltenVK. The set of available extensions may differ
// as a result so we don't want to make any assumptions here yet.
std::vector<std::string> instanceExtensions;
std::vector<std::string> deviceExtensions;
#else
CARB_UNSUPPORTED_PLATFORM();
#endif
carb::settings::setStringArray(
settings, "/renderer/vulkan/instanceExtensions/omni.kit.xr.plugin", instanceExtensions);
carb::settings::setStringArray(
settings, "/renderer/vulkan/deviceExtensions/omni.kit.xr.plugin", deviceExtensions);
}
} // namespace xr
} // namespace kit
} // namespace omni
| 5,783 | C | 39.166666 | 116 | 0.662805 |
omniverse-code/kit/include/omni/kit/raycast/query/RaycastQueryUtils.h | // Copyright (c) 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.
//
#pragma once
#include <omni/math/linalg/vec.h>
#include <carb/settings/ISettings.h>
namespace omni
{
namespace kit
{
namespace raycastquery
{
inline void adjustRayToSection(Ray& ray)
{
static constexpr char kSectionEnabledSettingPath[] = "/rtx/sectionPlane/enabled";
static constexpr char kSectionPlaneSettingPath[] = "/rtx/sectionPlane/plane";
auto settings = carb::getCachedInterface<carb::settings::ISettings>();
if (!settings->get<bool>(kSectionEnabledSettingPath))
{
return;
}
using namespace omni::math::linalg;
vec4<float> plane;
settings->getAsFloatArray(kSectionPlaneSettingPath, &plane[0], 4);
vec3 const planeNormal(plane[0], plane[1], plane[2]);
vec4 const rayOrigin4(ray.origin.x, ray.origin.y, ray.origin.z, 1.f);
vec3 const rayDir(ray.direction.x, ray.direction.y, ray.direction.z);
float const originPlaneDistance = -rayOrigin4.Dot(plane);
bool const originCulled = originPlaneDistance > 0.f;
float const dirNormalCos = rayDir.Dot(planeNormal);
bool const sameNormalDirection = dirNormalCos > 0.f;
float const rayDist = (dirNormalCos != 0) ? (originPlaneDistance / dirNormalCos) : ray.maxT;
if (originCulled)
{
if (sameNormalDirection)
{
// move minT so it's starting from the section plane.
ray.minT = ray.minT > rayDist ? ray.minT : rayDist;
}
else
{
// the entire ray is culled.
ray.minT = ray.maxT = std::numeric_limits<float>::infinity();
}
}
else
{
if (sameNormalDirection)
{
// the entire ray is within non-culled section, no adjustment needed
}
else
{
// move maxT so it ends on the section plane
ray.maxT = ray.maxT < rayDist ? ray.maxT : rayDist;
}
}
}
}
}
}
| 2,312 | C | 27.9125 | 96 | 0.66263 |
omniverse-code/kit/include/omni/kit/raycast/query/IRaycastQuery.h | // Copyright (c) 2019-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 Carbonite Interface for IRaycastQuery.
#pragma once
#include <carb/Interface.h>
#include <carb/events/IEvents.h>
#include <rtx/raytracing/RaycastQueryTypes.h>
namespace omni
{
namespace kit
{
namespace raycastquery
{
using RaycastSequenceId = uint32_t;
using Ray = rtx::raytracing::RaycastQueryRay;
using RayQueryResult = rtx::raytracing::RaycastQueryResult;
enum class Result : int32_t
{
eSuccess = 0, // No error
eInvalidParameter, // One of the given parameters is not valid
eParameterIsNull, // One of the given parameters is null, which is not expected
eRaycastSequenceDoesNotExist, // Raycast sequence requested does not exist
eRaycastQueryManagerDoesNotExist, // Raycast query manager does not exist, raycast queries disabled
eRaycastSequenceAdditionFailed, // Raycast sequence addition failed
};
struct RaycastQueryOp
{
size_t(CARB_ABI* getQueryCount)(RaycastQueryOp* op);
Ray*(CARB_ABI* getQueryRays)(RaycastQueryOp* op);
RayQueryResult*(CARB_ABI* getQueryResults)(RaycastQueryOp* op);
void(CARB_ABI* callback)(RaycastQueryOp* op);
void(CARB_ABI* destroy)(RaycastQueryOp* op);
};
class IRaycastQuery
{
public:
CARB_PLUGIN_INTERFACE("omni::rtx::IRaycastQuery", 1, 0)
/**
* @brief This function adds a raycast query operation in the current scene.
*
* @param raycastOp operation that describes a query that needs to be executed
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result submitRaycastQuery(RaycastQueryOp* raycastOp) = 0;
/**
* @brief Add a sequence of raycast queries that maintains last valid value
* and will execute raycast on current scene.
*
* @param sequenceId (out) sequence id (needed for removal)
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result addRaycastSequence(RaycastSequenceId& sequenceId) = 0;
/**
* @brief Remove a sequence of raycasts.
*
* @param sequenceId sequence id returned by addRaycastSequence
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result removeRaycastSequence(RaycastSequenceId sequence) = 0;
/**
* @brief Submit a new ray request to a sequence of raycasts.
*
* @param sequenceId sequence id returned by addRaycastSequence
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result submitRayToRaycastSequence(RaycastSequenceId sequence, const Ray& ray) = 0;
/**
* @brief Get latest result from a sequence of raycasts.
*
* @param sequenceId sequence id returned by addRaycastSequence
* @param ray latest ray that was resolved
* @param result result of the ray request
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result getLatestResultFromRaycastSequence(RaycastSequenceId sequence,
Ray& ray,
RayQueryResult& result) = 0;
/**
* @brief Set the size of the raycast sequence.
*
* @param sequenceId sequence id returned by addRaycastSequence
* @param size number of ray casts in sequence
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result setRaycastSequenceArraySize(RaycastSequenceId sequence, size_t size) = 0;
/**
* @brief Submit a new ray request to a sequence of raycasts.
*
* @param sequenceId sequence id returned by addRaycastSequence
* @param ray pointer to list of rays
* @param size length of the ray array
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result submitRayToRaycastSequenceArray(RaycastSequenceId sequence, Ray* ray, size_t size) = 0;
/**
* @brief Get latest result from a sequence of raycasts.
*
* @param sequenceId sequence id returned by addRaycastSequence
* @param ray latest ray that was resolved
* @param result result of the ray request
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
virtual Result getLatestResultFromRaycastSequenceArray(RaycastSequenceId sequence,
Ray* ray,
RayQueryResult* result,
size_t size) = 0;
};
template <typename RaycastQueryOpLambdaType>
class RaycastQueryTemplate final : public RaycastQueryOp
{
public:
RaycastQueryTemplate(const Ray& queryRay, RaycastQueryOpLambdaType&& raycastOpLambda)
: m_raycastOpLambda(static_cast<RaycastQueryOpLambdaType&&>(raycastOpLambda)), m_queryRay(queryRay)
{
m_queryResult = {};
RaycastQueryOp::getQueryCount = RaycastQueryTemplate<RaycastQueryOpLambdaType>::getQueryCount;
RaycastQueryOp::getQueryRays = RaycastQueryTemplate<RaycastQueryOpLambdaType>::getQueryRays;
RaycastQueryOp::getQueryResults = RaycastQueryTemplate<RaycastQueryOpLambdaType>::getQueryResults;
RaycastQueryOp::callback = RaycastQueryTemplate<RaycastQueryOpLambdaType>::callback;
RaycastQueryOp::destroy = RaycastQueryTemplate<RaycastQueryOpLambdaType>::destroy;
}
~RaycastQueryTemplate()
{
}
static size_t CARB_ABI getQueryCount(RaycastQueryOp* op)
{
return 1;
}
static Ray* CARB_ABI getQueryRays(RaycastQueryOp* op)
{
RaycastQueryTemplate<RaycastQueryOpLambdaType>* typedOp = (RaycastQueryTemplate<RaycastQueryOpLambdaType>*)op;
return &(typedOp->m_queryRay);
}
static RayQueryResult* CARB_ABI getQueryResults(RaycastQueryOp* op)
{
RaycastQueryTemplate<RaycastQueryOpLambdaType>* typedOp = (RaycastQueryTemplate<RaycastQueryOpLambdaType>*)op;
return &(typedOp->m_queryResult);
}
static void CARB_ABI destroy(RaycastQueryOp* op)
{
delete ((RaycastQueryTemplate<RaycastQueryOpLambdaType>*)op);
}
static void CARB_ABI callback(RaycastQueryOp* op)
{
RaycastQueryTemplate<RaycastQueryOpLambdaType>* typedOp = (RaycastQueryTemplate<RaycastQueryOpLambdaType>*)op;
typedOp->m_raycastOpLambda(typedOp->m_queryRay, typedOp->m_queryResult);
}
private:
RaycastQueryOpLambdaType m_raycastOpLambda;
Ray m_queryRay;
RayQueryResult m_queryResult;
};
/**
* @brief This function adds a raycast query operation in the current scene
*
* @param ray the ray to submit
* @param callback the callback lambda function to execute when resolved
*
* @return error code if function failed
*
* threadsafety: safe to call from any thread
*/
template <typename RaycastOpLambdaType>
inline void submitRaycastQueryLambda(IRaycastQuery* raycastQuery, const Ray& ray, RaycastOpLambdaType&& callback)
{
auto raycastOp = new RaycastQueryTemplate<RaycastOpLambdaType>(ray, static_cast<RaycastOpLambdaType&&>(callback));
raycastQuery->submitRaycastQuery(raycastOp);
}
}
}
}
| 7,988 | C | 32.426778 | 118 | 0.677266 |
omniverse-code/kit/include/omni/kit/ui/Common.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/events/EventsUtils.h>
#include <carb/imgui/ImGui.h>
#include <omni/kit/KitUtils.h>
#include <omni/ui/Font.h>
#include <omni/ui/IGlyphManager.h>
#include <cmath>
#include <functional>
#include <memory>
namespace omni
{
namespace kit
{
namespace ui
{
class Widget;
using WidgetRef = std::shared_ptr<Widget>;
struct Mat44
{
carb::Double4 rows[4];
};
enum class ClippingType
{
eNone,
eEllipsisLeft,
eEllipsisRight,
eWrap,
eCount
};
enum class DraggingType
{
eStarted,
eStopped
};
enum class UnitType
{
ePixel,
ePercent
};
struct Length
{
float value;
UnitType unit;
};
struct Percent : public Length
{
explicit Percent(float v) : Length{ v, UnitType::ePercent }
{
}
};
struct Pixel : public Length
{
explicit Pixel(float v) : Length{ v, UnitType::ePixel }
{
}
};
inline float calculateWidth(const Length& length, const float usedWidth = 0.0f)
{
if (length.unit == UnitType::ePercent)
return length.value * 0.01f * (getImGui()->getWindowContentRegionWidth() - usedWidth);
return length.value;
}
inline float calculateHeight(const Length& length)
{
if (length.unit == UnitType::ePercent)
return length.value * 0.01f * getImGui()->getWindowContentRegionWidth();
return length.value;
}
inline const char* getCustomGlyphCode(const char* glyphFilePath, omni::ui::FontStyle fontStyle)
{
return getGlyphManager()->getGlyphInfo(glyphFilePath, fontStyle).code;
}
inline bool clipText(ClippingType clipType, std::string& text, float& clippingWidth, const float itemWidth, size_t maxLength)
{
carb::imgui::ImGui* imgui = getImGui();
using OnClipText = std::function<std::string(const std::string& str, float itemWidth)>;
auto clipFn = [&text, &clippingWidth, itemWidth, imgui](OnClipText onClipText) {
// only re-build m_clippedText when the column is re-sized
if (itemWidth != clippingWidth)
{
std::string fullText = text;
carb::Float2 textWidth = imgui->calcTextSize(text.c_str(), nullptr, false, -1.0f);
if (textWidth.x > itemWidth && itemWidth > 0.0f)
{
text = onClipText(fullText, itemWidth);
}
clippingWidth = itemWidth;
return true;
}
return false;
};
switch (clipType)
{
case ClippingType::eEllipsisLeft:
return clipFn([maxLength, imgui](const std::string& fullText, float itemWidth) {
size_t index = 0;
std::string text = fullText;
while (++index < fullText.length())
{
text = "..." + fullText.substr(index);
carb::Float2 textWidth = imgui->calcTextSize(text.c_str(), nullptr, false, -1.0f);
if (textWidth.x < itemWidth || text.length() == maxLength - 1)
break;
}
return text;
});
case ClippingType::eEllipsisRight:
return clipFn([maxLength, imgui](const std::string& fullText, float itemWidth) {
int64_t index = static_cast<int64_t>(fullText.length());
std::string text = fullText;
while (--index > 0)
{
text = fullText.substr(0, index) + "...";
carb::Float2 textWidth = imgui->calcTextSize(text.c_str(), nullptr, false, -1.0f);
if (textWidth.x < itemWidth || text.length() == maxLength - 1)
break;
}
return text;
});
case ClippingType::eWrap:
// not supported
default:
break;
}
return false;
}
inline bool handleDragging(const std::function<void(WidgetRef, DraggingType)>& draggedFn, WidgetRef widget, bool isDragging)
{
carb::imgui::ImGui* imgui = getImGui();
bool dragging = imgui->isMouseDragging(0, -1.0f);
if (draggedFn != nullptr)
{
// dragging handling
if (dragging == true && isDragging == false)
draggedFn(widget, DraggingType::eStarted);
else if (dragging == false && isDragging == true)
draggedFn(widget, DraggingType::eStopped);
}
return dragging;
}
inline void handleDragDrop(std::function<void(WidgetRef, const char*)>& dragDropFn,
const char* dragDropPayloadName,
WidgetRef widget)
{
carb::imgui::ImGui* imgui = getImGui();
// handle drag-drop callback
if (dragDropFn != nullptr && (dragDropPayloadName != nullptr && dragDropPayloadName[0] != 0) &&
imgui->beginDragDropTarget())
{
const carb::imgui::Payload* payload = imgui->acceptDragDropPayload(dragDropPayloadName, 0);
if (payload && payload->isDelivery())
{
dragDropFn(widget, reinterpret_cast<const char*>(payload->data));
}
imgui->endDragDropTarget();
}
}
template <class T>
inline bool almostEqual(T a, T b)
{
return a == b;
}
static constexpr float kDefaultEpsilonF = 0.001f;
static constexpr double kDefaultEpsilonD = 0.0001;
inline bool almostEqual(double a, double b, double epsilon = kDefaultEpsilonD)
{
return std::abs(a - b) < epsilon;
}
inline bool almostEqual(float a, float b, float epsilon = std::numeric_limits<float>::epsilon())
{
return std::abs(a - b) < epsilon;
}
inline bool almostEqual(carb::ColorRgb a, carb::ColorRgb b, float epsilon = kDefaultEpsilonF)
{
return almostEqual(a.r, b.r, epsilon) && almostEqual(a.g, b.g, epsilon) && almostEqual(a.b, b.b, epsilon);
}
inline bool almostEqual(carb::ColorRgba a, carb::ColorRgba b, float epsilon = kDefaultEpsilonF)
{
return almostEqual(a.r, b.r, epsilon) && almostEqual(a.g, b.g, epsilon) && almostEqual(a.b, b.b, epsilon) &&
almostEqual(a.a, b.a, epsilon);
}
inline bool almostEqual(carb::Float3 a, carb::Float3 b, float epsilon = kDefaultEpsilonF)
{
return almostEqual(a.x, b.x, epsilon) && almostEqual(a.y, b.y, epsilon) && almostEqual(a.z, b.z, epsilon);
}
inline bool almostEqual(carb::Double2 a, carb::Double2 b, double epsilon = kDefaultEpsilonD)
{
return almostEqual(a.x, b.x, epsilon) && almostEqual(a.y, b.y, epsilon);
}
inline bool almostEqual(carb::Double3 a, carb::Double3 b, double epsilon = kDefaultEpsilonD)
{
return almostEqual(a.x, b.x, epsilon) && almostEqual(a.y, b.y, epsilon) && almostEqual(a.z, b.z, epsilon);
}
inline bool almostEqual(carb::Double4 a, carb::Double4 b, double epsilon = kDefaultEpsilonD)
{
return almostEqual(a.x, b.x, epsilon) && almostEqual(a.y, b.y, epsilon) && almostEqual(a.z, b.z, epsilon) &&
almostEqual(a.w, b.w, epsilon);
}
inline bool almostEqual(ui::Mat44 a, ui::Mat44 b, double epsilon = kDefaultEpsilonD)
{
return almostEqual(a.rows[0], b.rows[0], epsilon) && almostEqual(a.rows[1], b.rows[1], epsilon) &&
almostEqual(a.rows[2], b.rows[2], epsilon) && almostEqual(a.rows[3], b.rows[3], epsilon);
}
inline bool almostEqual(carb::Int2 a, carb::Int2 b)
{
return (a.x == b.x) && (a.y == b.y);
}
}
}
}
| 7,500 | C | 27.85 | 125 | 0.6364 |
omniverse-code/kit/include/omni/kit/ui/Drag.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"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a input drag.
*
* Usage:
* Drag<int, int>
* Drag<carb::Int2, int>
* Drag<double>
* Drag<carb::Double2>
* Drag<carb::Double3>
* Drag<carb::Double4>
*/
template <class T, class RangeT = double>
class OMNI_KIT_UI_CLASS_API Drag : public SimpleValueWidget<T>
{
public:
static const WidgetType kType;
OMNI_KIT_UI_API explicit Drag(
const char* text = "", T value = {}, RangeT min = {}, RangeT max = {}, float valueDragSpeed = 1.0f);
OMNI_KIT_UI_API ~Drag();
RangeT min;
RangeT max;
std::string format;
float dragSpeed;
OMNI_KIT_UI_API WidgetType getType() override;
protected:
bool _drawImGuiWidget(carb::imgui::ImGui* imgui, T& value) override;
};
#if CARB_POSIX && !CARB_TOOLCHAIN_CLANG
extern template class OMNI_KIT_UI_API Drag<int, int>;
extern template class OMNI_KIT_UI_API Drag<uint32_t, uint32_t>;
extern template class OMNI_KIT_UI_API Drag<carb::Int2, int>;
extern template class OMNI_KIT_UI_API Drag<double>;
extern template class OMNI_KIT_UI_API Drag<carb::Double2>;
extern template class OMNI_KIT_UI_API Drag<carb::Double3>;
extern template class OMNI_KIT_UI_API Drag<carb::Double4>;
#endif
using DragInt = Drag<int, int>;
using DragUInt = Drag<uint32_t, uint32_t>;
using DragInt2 = Drag<carb::Int2, int>;
using DragDouble = Drag<double>;
using DragDouble2 = Drag<carb::Double2>;
using DragDouble3 = Drag<carb::Double3>;
using DragDouble4 = Drag<carb::Double4>;
}
}
}
| 1,981 | C | 25.783783 | 108 | 0.717819 |
omniverse-code/kit/include/omni/kit/ui/Label.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 label.
*/
class OMNI_KIT_UI_CLASS_API Label : public Widget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Label);
/**
* Constructor.
*
* @param text The text for the label to use.
*/
OMNI_KIT_UI_API explicit Label(const char* text);
/**
* Constructor.
*
* @param text The text for the label to use.
* @param copyToClipboard when true, can be copied to clipboard via context menu
*/
OMNI_KIT_UI_API Label(const char* text, bool copyToClipboard, ClippingType clipping, omni::ui::FontStyle fontStyle);
/**
* Destructor.
*/
OMNI_KIT_UI_API ~Label() override;
/**
* Gets the text of the label.
*
* @return The text of the label.
*/
OMNI_KIT_UI_API const char* getText() const;
/**
* Sets the text of the label.
*
* @param text The text of the label.
*/
OMNI_KIT_UI_API virtual void setText(const char* text);
/**
* Sets the color of the label text.
*
* @param textColor
*/
OMNI_KIT_UI_API virtual void setTextColor(const carb::ColorRgba& textColor);
/**
* Resets the color of the label text.
*
* @param textColor
*/
OMNI_KIT_UI_API virtual void resetTextColor();
/**
* Sets the callback function when the label is clicked.
*
* fn The callback function when the label 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;
std::shared_ptr<Widget> tooltip;
void setPaddingX(float px)
{
m_paddingX = px;
}
protected:
std::string m_text;
bool m_customColor = false;
carb::ColorRgba m_textColor = { 1.f, 1.f, 1.f, 1.f };
std::function<void(WidgetRef)> m_clickedFn;
std::string m_clippedText;
float m_clippingWidth;
float m_paddingX = 0.0f;
bool m_copyToClipboard;
ClippingType m_clippingMode = ClippingType::eNone;
};
}
}
}
| 2,753 | C | 22.338983 | 120 | 0.63785 |
omniverse-code/kit/include/omni/kit/ui/BroadcastModel.h | // Copyright (c) 2018-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 "Model.h"
namespace omni
{
namespace kit
{
namespace ui
{
class OMNI_KIT_UI_CLASS_API BroadcastModel : public Model
{
public:
using TargetId = uint32_t;
OMNI_KIT_UI_API virtual TargetId addTarget(const std::shared_ptr<Model>& model,
const std::string& pathPrefixOrigin,
const std::string& pathPrefixNew) = 0;
OMNI_KIT_UI_API virtual void removeTarget(TargetId) = 0;
};
OMNI_KIT_UI_API std::unique_ptr<BroadcastModel> createBroadcastModel();
}
}
}
| 1,044 | C | 23.302325 | 85 | 0.685824 |
omniverse-code/kit/include/omni/kit/ui/RowLayout.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 "Container.h"
namespace omni
{
namespace kit
{
namespace ui
{
/**
*
*/
class OMNI_KIT_UI_CLASS_API RowLayout : public Container
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::RowLayout);
OMNI_KIT_UI_API RowLayout();
OMNI_KIT_UI_API ~RowLayout() override;
OMNI_KIT_UI_API WidgetType getType() override;
void draw(float elapsedTime) override;
};
}
}
}
| 866 | C | 21.230769 | 77 | 0.73903 |
omniverse-code/kit/include/omni/kit/ui/Api.h | // Copyright (c) 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
#if defined _WIN32
# ifdef OMNI_KIT_UI_EXPORTS
# define OMNI_KIT_UI_API __declspec(dllexport)
# define OMNI_KIT_UI_CLASS_API
# else
# define OMNI_KIT_UI_API __declspec(dllimport)
# define OMNI_KIT_UI_CLASS_API
# endif
#else
# ifdef OMNI_KIT_UI_EXPORTS
# define OMNI_KIT_UI_API __attribute__((visibility("default")))
# define OMNI_KIT_UI_CLASS_API __attribute__((visibility("default")))
# else
# define OMNI_KIT_UI_API
# define OMNI_KIT_UI_CLASS_API
# endif
#endif
| 987 | C | 34.285713 | 77 | 0.698075 |
omniverse-code/kit/include/omni/kit/ui/HotkeyUtils.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/InterfaceUtils.h>
#include <carb/imgui/ImGui.h>
#include <carb/input/IInput.h>
#include <carb/input/InputUtils.h>
#include <imgui/imgui.h>
#include <string>
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Classical keyboard Hotkey (modifier + key). Can be polled, works nicely with imgui windows.
*/
class Hotkey
{
public:
void initialize(carb::input::KeyboardModifierFlags mod, carb::input::KeyboardInput key, std::string displayName = "")
{
m_key = key;
m_mod = mod;
m_displayName = displayName;
m_shortcut = carb::input::getModifierFlagsString(mod);
if (!m_shortcut.empty())
m_shortcut += " + ";
m_shortcut += carb::input::getKeyboardInputString(key);
}
bool isPressedInCurrentWindow(carb::imgui::ImGui* imgui, carb::input::Keyboard* keyboard) const
{
return imgui->isWindowFocused(carb::imgui::kFocusedFlagRootAndChildWindows) && isPressed(keyboard, m_mod, m_key);
}
bool isPressed(carb::input::Keyboard* keyboard) const
{
return isPressed(keyboard, m_mod, m_key);
}
static bool isPressed(carb::input::Keyboard* keyboard,
carb::input::KeyboardModifierFlags mod,
carb::input::KeyboardInput key)
{
using namespace carb::input;
if ((uint32_t)key >= (uint32_t)carb::input::KeyboardInput::eCount)
{
return false;
}
// TODO: That's not correct to use ImGui directly here. It's better to add this functionality to
// carb::imgui::ImGui, but it's not possible to update it at this moment because physxui that is also using
// carb::imgui::ImGui is blocked. The only way to access WantCaptureKeyboard is using directly ImGui.
::ImGuiIO& io = ::ImGui::GetIO();
if (io.WantCaptureKeyboard)
{
// When wantCaptureKeyboard is true, ImGui is using the keyboard input exclusively, and it's not necessary
// to dispatch the input to the application. (e.g. InputText active, or an ImGui window is focused and
// navigation is enabled, etc.).
return false;
}
carb::input::IInput* input = carb::getCachedInterface<carb::input::IInput>();
const auto isKeyPressed = [input, keyboard](KeyboardInput key) {
return (input->getKeyboardButtonFlags(keyboard, key) & kButtonFlagTransitionDown);
};
const auto isUp = [input, keyboard](KeyboardInput key) {
return (input->getKeyboardButtonFlags(keyboard, key) & kButtonFlagStateUp);
};
const auto isDown = [input, keyboard](KeyboardInput key) {
return (input->getKeyboardButtonFlags(keyboard, key) & kButtonFlagStateDown);
};
if (!isKeyPressed(key))
return false;
if (!(mod & kKeyboardModifierFlagShift) &&
(isDown(KeyboardInput::eLeftShift) || isDown(KeyboardInput::eRightShift)))
return false;
if (!(mod & kKeyboardModifierFlagControl) &&
(isDown(KeyboardInput::eLeftControl) || isDown(KeyboardInput::eRightControl)))
return false;
if (!(mod & kKeyboardModifierFlagAlt) && (isDown(KeyboardInput::eLeftAlt) || isDown(KeyboardInput::eRightAlt)))
return false;
if ((mod & kKeyboardModifierFlagShift) && isUp(KeyboardInput::eLeftShift) && isUp(KeyboardInput::eRightShift))
return false;
if ((mod & kKeyboardModifierFlagControl) && isUp(KeyboardInput::eLeftControl) &&
isUp(KeyboardInput::eRightControl))
return false;
if ((mod & kKeyboardModifierFlagAlt) && isUp(KeyboardInput::eLeftAlt) && isUp(KeyboardInput::eRightAlt))
return false;
if ((mod & kKeyboardModifierFlagSuper) && isUp(KeyboardInput::eLeftSuper) && isUp(KeyboardInput::eRightSuper))
return false;
if ((mod & kKeyboardModifierFlagCapsLock) && isUp(KeyboardInput::eCapsLock))
return false;
if ((mod & kKeyboardModifierFlagNumLock) && isUp(KeyboardInput::eNumLock))
return false;
return true;
}
const char* getDisplayName() const
{
return m_displayName.c_str();
}
const char* getShortcut() const
{
return m_shortcut.c_str();
}
carb::input::KeyboardInput getKey() const
{
return m_key;
}
carb::input::KeyboardModifierFlags getModifiers() const
{
return m_mod;
}
private:
carb::input::KeyboardInput m_key = carb::input::KeyboardInput::eCount;
carb::input::KeyboardModifierFlags m_mod = 0;
std::string m_shortcut;
std::string m_displayName;
};
}
}
}
| 5,179 | C | 35.223776 | 121 | 0.644912 |
omniverse-code/kit/include/omni/kit/ui/PopupDialog.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/imgui/ImGui.h>
#include <string>
#include <utility>
#include <vector>
namespace carb
{
namespace imgui
{
struct ImGui;
}
}
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines an PopupDialog class that draws popup dialogbox.
*/
class PopupDialog
{
public:
/**
* Constructor.
*
* @param title Title of the popup dialog.
* @param message Message of the popup dialog.
* @modal True to create a modal popup.
*/
PopupDialog(const char* title, const char* message, bool modal) : m_title(title), m_message(message), m_modal(modal)
{
}
/**
* Adds option button to the dialog.
*
* @param name Name of the option button.
* @param tooltop Tooltip of the option button.
*/
void addOptionButton(const char* name, const char* tooltip)
{
m_options.emplace_back(name, tooltip);
}
/**
* Gets the selected option button index.
*
* @param index The selected index.
* @return True if the index is valid. False if none selected.
*/
bool getSelectedOption(size_t& index) const
{
if (m_selectedIndex != kInvalidSelection)
{
index = m_selectedIndex;
return true;
}
return false;
}
/**
* Draws the popup window.
*
* @param The imgui instance.
*/
void draw(carb::imgui::ImGui* imgui)
{
using namespace carb::imgui;
imgui->openPopup(m_title.c_str());
if (m_modal ? imgui->beginPopupModal(m_title.c_str(), nullptr, kWindowFlagAlwaysAutoResize) :
imgui->beginPopup(m_title.c_str(), kWindowFlagAlwaysAutoResize))
{
imgui->text(m_message.c_str());
m_selectedIndex = kInvalidSelection;
for (size_t i = 0; i < m_options.size(); i++)
{
if (imgui->button(m_options[i].first.c_str()))
{
m_selectedIndex = i;
}
if (imgui->isItemHovered(0) && m_options[i].second.length())
{
imgui->setTooltip(m_options[i].second.c_str());
}
imgui->sameLine();
}
imgui->endPopup();
}
}
private:
static const size_t kInvalidSelection = SIZE_MAX;
std::string m_title;
std::string m_message;
bool m_modal;
std::vector<std::pair<std::string, std::string>> m_options;
size_t m_selectedIndex = kInvalidSelection;
};
}
}
}
| 2,988 | C | 24.330508 | 120 | 0.592704 |
omniverse-code/kit/include/omni/kit/ui/Window.h | // 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
#include <carb/events/EventsUtils.h>
#include <omni/kit/ui/Common.h>
#include <omni/kit/ui/Menu.h>
#include <omni/ui/windowmanager/IWindowCallbackManager.h>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
namespace omni
{
namespace kit
{
namespace ui
{
class Container;
enum class WindowEventType : uint32_t
{
eVisibilityChange,
eUpdate
};
/**
* Defines a window.
*/
class OMNI_KIT_UI_CLASS_API Window
{
public:
typedef uint32_t Flags;
static constexpr Flags kWindowFlagNone = 0;
static constexpr Flags kWindowFlagNoTitleBar = (1 << 0);
static constexpr Flags kWindowFlagNoResize = (1 << 1);
static constexpr Flags kWindowFlagNoMove = (1 << 2);
static constexpr Flags kWindowFlagNoScrollbar = (1 << 3);
static constexpr Flags kWindowFlagNoCollapse = (1 << 4);
static constexpr Flags kWindowFlagNoSavedSettings = (1 << 5);
static constexpr Flags kWindowFlagShowHorizontalScrollbar = (1 << 7);
static constexpr Flags kWindowFlagForceVerticalScrollbar = (1 << 8);
static constexpr Flags kWindowFlagForceHorizontalScrollbar = (1 << 9);
static constexpr Flags kWindowFlagNoFocusOnAppearing = (1 << 10);
static constexpr Flags kWindowFlagNoClose = (1 << 11);
static constexpr Flags kWindowFlagModal = (1 << 12);
/**
* Constructor.
*
* @param title The window title.
* @param width The window default width.
* @param height The window default height.
*/
OMNI_KIT_UI_API explicit Window(
const char* title,
uint32_t width = 640,
uint32_t height = 480,
bool open = true,
bool addToMenu = true,
const std::string& menuPath = "",
bool isToggleMenu = true,
omni::ui::windowmanager::DockPreference dockPreference = omni::ui::windowmanager::DockPreference::eLeftBottom,
Flags flags = kWindowFlagNone);
/**
* Destructor.
*/
OMNI_KIT_UI_API ~Window();
/**
* Gets the title of the window.
*
* @return The title of the window.
*/
OMNI_KIT_UI_API const char* getTitle() const;
/**
* Sets the title for the window.
*
* @param title The title of the window.
*/
OMNI_KIT_UI_API void setTitle(const char* title);
/**
* Gets the width of the window.
*
* @return The width of the window.
*/
OMNI_KIT_UI_API uint32_t getWidth() const;
/**
* Sets the width of the window.
*
* @param width The width of the window.
*/
OMNI_KIT_UI_API void setWidth(uint32_t width);
/**
* Gets the height of the window.
*
* @return The height of the window.
*/
OMNI_KIT_UI_API uint32_t getHeight() const;
/**
* Sets the height of the window.
*
* @param height The height of the window.
*/
OMNI_KIT_UI_API void setHeight(uint32_t height);
/**
* Sets the size of the window.
*
* @param width The width of the window.
* @param height The height of the window.
*/
OMNI_KIT_UI_API void setSize(uint32_t width, uint32_t height);
/**
* Sets the flags for the window.
*
* @param fkags The flags for the window.
*/
void setFlags(Flags flags)
{
m_flags = flags;
}
/**
* Gets the flags for the window
*
* @param flags The flags for the window.
*/
Flags getFlags() const
{
return m_flags;
}
/**
* Sets the alpha value (transparency) of the window.
*
* @param alpha The alpha value of the window.
*/
OMNI_KIT_UI_API void setAlpha(float alpha);
/**
* Gets the layout for the window.
*
* @return The layout for the window.
*/
OMNI_KIT_UI_API std::shared_ptr<Container> getLayout() const;
/**
* Sets the layout for the window.
*
* @return The layout for the window.
*/
OMNI_KIT_UI_API void setLayout(std::shared_ptr<Container> layout);
/**
* Determines if the window is visible.
*
* @return true if the window is visible.
*/
OMNI_KIT_UI_API bool isVisible() const;
/**
* Determines if the window has modal popup.
*
* @return true if the window has modal popup.
*/
OMNI_KIT_UI_API bool isModal() const;
/**
* Shows a window and sets it to visible.
*/
OMNI_KIT_UI_API void show();
/**
* Hides a window and sets it to not visible.
*/
OMNI_KIT_UI_API void hide();
/**
*
*/
OMNI_KIT_UI_API void setUpdateFn(const std::function<void(float)>& fn);
OMNI_KIT_UI_API void setVisibilityChangedFn(const std::function<void(bool)>& fn);
OMNI_KIT_UI_API void setVisible(bool visible);
carb::events::IEventStream* getEventStream() const
{
return m_stream.get();
}
std::shared_ptr<Menu> menu;
carb::Float2 currentMousePos;
carb::Float2 windowPos;
bool windowPosValid = false;
private:
Window() = default;
void updateWindow(float elapsedTime);
carb::events::IEventStreamPtr m_stream;
omni::ui::windowmanager::IWindowCallbackPtr m_handle;
carb::events::ISubscriptionPtr m_updateSubId;
std::string m_title;
std::string m_menuPath;
uint32_t m_width = 0;
uint32_t m_height = 0;
float m_alpha = 1.0f;
bool m_visible = false;
std::shared_ptr<Container> m_layout = nullptr;
std::function<void(float)> m_updateFn;
std::function<void(bool)> m_visibilityChangedFn;
bool m_addToMenu;
bool m_menuTogglable;
bool m_autoResize = false;
omni::ui::windowmanager::DockPreference m_dock;
Flags m_flags;
};
}
}
}
| 6,128 | C | 24.326446 | 118 | 0.631527 |
omniverse-code/kit/include/omni/kit/ui/ValueWidget.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 "Button.h"
#include "ModelWidget.h"
namespace omni
{
namespace kit
{
namespace ui
{
template <class T>
class OMNI_KIT_UI_CLASS_API ValueWidget : public ModelWidget
{
public:
ValueWidget(T value) : ModelWidget(), m_value(value)
{
this->text = text;
auto model = createSimpleValueModel(Model::getNodeTypeForT<T>());
model->setValue(m_modelRoot.c_str(), "", value);
setModel(std::move(model), "");
}
void setValue(const T& v)
{
_setValue(v);
}
const T& getValue() const
{
return m_value;
}
bool isValueAmbiguous() const
{
return m_valueAmbiguous;
}
void setValueAmbiguous(bool state)
{
ModelChangeInfo info = { m_sender, false };
m_valueAmbiguous = state;
if (m_valueAmbiguous)
m_model->setType(m_modelRoot.c_str(), "", ModelNodeType::eUnknown, info);
}
bool leftHanded;
std::string text;
std::function<void(const T&)> onChangedFn;
std::function<void(const ValueWidget<T>*)> onRightClickFn;
std::shared_ptr<Widget> tooltip;
protected:
virtual void _onValueChange(){};
void rightClickHandler()
{
carb::imgui::ImGui* imgui = getImGui();
if (imgui->isItemHovered(0) && imgui->isMouseReleased(1))
{
if (onRightClickFn)
onRightClickFn(this);
}
}
void _setValue(const T& value, bool transient = false, bool force = false)
{
if (!almostEqual(value, m_value) || force || m_valueAmbiguous)
{
m_value = value;
m_valueAmbiguous = false;
this->_onValueChange();
ModelChangeInfo info = { m_sender, transient };
m_model->setValue(m_modelRoot.c_str(), "", m_value, 0, m_isTimeSampled, m_timeCode, info);
if (onChangedFn)
onChangedFn(m_value);
}
}
virtual void _onModelValueChange() override
{
ModelValue<T> newValue = m_model->getValue<T>(m_modelRoot.c_str(), "", 0, m_isTimeSampled, m_timeCode);
if (!almostEqual(newValue.value, m_value) || newValue.ambiguous != m_valueAmbiguous)
{
m_value = newValue.value;
m_valueAmbiguous = newValue.ambiguous;
this->_onValueChange();
if (onChangedFn)
onChangedFn(m_value);
}
}
T m_value;
bool m_valueAmbiguous;
};
template <class T>
class OMNI_KIT_UI_CLASS_API SimpleValueWidget : public ValueWidget<T>
{
public:
SimpleValueWidget(const std::string& text, T value) : ValueWidget<T>(value), leftHanded(false), m_wasActive(false)
{
this->text = text;
}
bool leftHanded;
std::string text;
std::shared_ptr<Widget> tooltip;
void draw(float dt) override
{
this->_processModelEvents();
if (!this->m_visible)
return;
carb::imgui::ImGui* imgui = getImGui();
carb::imgui::Font* font = this->m_font;
if (font)
imgui->pushFont(font);
imgui->pushItemFlag(carb::imgui::kItemFlagDisabled, !this->m_enabled);
imgui->pushStyleVarFloat(carb::imgui::StyleVar::eAlpha, this->m_enabled ? 1.0f : .6f);
if (this->leftHanded)
{
_drawWidget(imgui, dt);
_drawText(imgui);
}
else
{
_drawText(imgui);
_drawWidget(imgui, dt);
}
this->rightClickHandler();
imgui->popStyleVar();
imgui->popItemFlag();
if (font)
imgui->popFont();
}
protected:
virtual bool _drawImGuiWidget(carb::imgui::ImGui* imgui, T& value) = 0;
virtual bool _isTransientChangeSupported() const
{
return true;
}
private:
void _drawWidget(carb::imgui::ImGui* imgui, float dt)
{
if (this->m_label.empty())
{
this->m_label = "##hidelabel";
this->m_label += this->m_uniqueId;
}
if (m_wasActive)
{
processImguiInputEvents();
}
predictActiveProcessImguiInput(this->m_label.c_str());
float uiScale = imgui->getWindowDpiScale();
imgui->pushItemWidth(calculateWidth(this->width) * uiScale);
const bool isTransientChangeSupported = this->_isTransientChangeSupported();
T v = this->getValue();
if (this->_drawImGuiWidget(imgui, v))
{
this->_setValue(v, isTransientChangeSupported);
}
imgui->popItemWidth();
m_wasActive = imgui->isItemActive();
if (m_wasActive || this->m_isDragging)
this->m_isDragging = handleDragging(this->m_draggedFn, Widget::shared_from_this(), this->m_isDragging);
// Just finished editing -> force notify value with undo
if (imgui->isItemDeactivatedAfterEdit() && isTransientChangeSupported)
{
this->_setValue(v, false, true);
}
if (this->tooltip && imgui->isItemHovered(0))
{
imgui->beginTooltip();
this->tooltip->draw(dt);
imgui->endTooltip();
}
}
void _drawText(carb::imgui::ImGui* imgui)
{
if (this->text.size() > 0)
{
if (this->leftHanded)
imgui->sameLine();
imgui->text(this->text.c_str());
if (!this->leftHanded)
imgui->sameLine();
}
}
bool m_wasActive;
};
}
}
}
| 5,948 | C | 23.891213 | 118 | 0.575488 |
omniverse-code/kit/include/omni/kit/ui/Slider.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"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a slider.
*
* Usage:
* Slider<int>
* Slider<double>
*/
template <class T, class RangeT = double>
class OMNI_KIT_UI_CLASS_API Slider : public SimpleValueWidget<T>
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Slider<T>);
OMNI_KIT_UI_API explicit Slider(const char* text = "", T value = {}, RangeT min = {}, RangeT max = {});
OMNI_KIT_UI_API ~Slider();
RangeT min = {};
RangeT max = {};
float power = 1.0f;
std::string format;
WidgetType getType() override;
protected:
bool _drawImGuiWidget(carb::imgui::ImGui* imgui, T& value) override;
};
#if CARB_POSIX
extern template class OMNI_KIT_UI_API Slider<int, int>;
extern template class OMNI_KIT_UI_API Slider<uint32_t, uint32_t>;
extern template class OMNI_KIT_UI_API Slider<carb::Int2, int32_t>;
extern template class OMNI_KIT_UI_API Slider<double>;
extern template class OMNI_KIT_UI_API Slider<carb::Double2>;
extern template class OMNI_KIT_UI_API Slider<carb::Double3>;
extern template class OMNI_KIT_UI_API Slider<carb::Double4>;
#endif
}
}
}
| 1,611 | C | 25.426229 | 107 | 0.719429 |
omniverse-code/kit/include/omni/kit/ui/ModelWidget.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 "Container.h"
#include "Model.h"
namespace omni
{
namespace kit
{
namespace ui
{
/**
*
*/
class OMNI_KIT_UI_CLASS_API ModelWidget : public ContainerBase
{
public:
OMNI_KIT_UI_API ModelWidget();
OMNI_KIT_UI_API virtual ~ModelWidget();
OMNI_KIT_UI_API void setModel(const std::shared_ptr<Model>& model,
const std::string& root = "",
bool isTimeSampled = false,
double timeCode = -1.0);
std::shared_ptr<Model> getModel() const
{
return m_model;
}
const std::string& getModelRoot() const
{
return m_modelRoot;
}
const carb::events::IEventStream* getModelStream() const
{
return m_modelEvents.get();
}
void draw(float dt) override
{
this->_processModelEvents();
ContainerBase::draw(dt);
}
bool isTimeSampled() const
{
return m_isTimeSampled;
}
double getTimeCode() const
{
return m_timeCode;
}
void processModelEvents()
{
_processModelEvents();
}
protected:
bool _processModelEvents();
virtual void _onModelValueChange()
{
}
virtual void _onModelNodeChange()
{
}
carb::events::IEventStreamPtr m_modelEvents;
std::shared_ptr<Model> m_model;
std::string m_modelRoot;
bool m_isTimeSampled{ false };
double m_timeCode{ -1.0 };
carb::events::SenderId m_sender;
};
}
}
}
| 1,955 | C | 19.80851 | 77 | 0.621483 |
omniverse-code/kit/include/omni/kit/ui/Color.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"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a color edit.
*/
template <class T>
class OMNI_KIT_UI_CLASS_API Color : public SimpleValueWidget<T>
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Color<T>);
OMNI_KIT_UI_API explicit Color(const char* text = "", T value = {});
OMNI_KIT_UI_API ~Color();
OMNI_KIT_UI_API WidgetType getType() override;
protected:
bool _drawImGuiWidget(carb::imgui::ImGui* imgui, T& value) override;
};
#if CARB_POSIX
extern template class OMNI_KIT_UI_API Color<carb::ColorRgb>;
extern template class OMNI_KIT_UI_API Color<carb::ColorRgba>;
#endif
using ColorRgb = Color<carb::ColorRgb>;
using ColorRgba = Color<carb::ColorRgba>;
}
}
}
| 1,213 | C | 23.28 | 77 | 0.733718 |
omniverse-code/kit/include/omni/kit/ui/Button.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 "Label.h"
#include <functional>
#include <memory>
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a button.
*/
class OMNI_KIT_UI_CLASS_API Button : public Label
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Button);
/**
* Constructor.
*
* @param text The text for the button to use.
*/
OMNI_KIT_UI_API explicit Button(const char* text, bool isImage = false, uint32_t defaultColor = 0xffffffff);
/**
* Destructor.
*/
OMNI_KIT_UI_API ~Button() override;
/**
* Sets the callback function when the button is clicked.
*
* fn The callback function when the button 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;
/**
* Gets the url of the image.
*
* @return The url to be loaded.
*/
const char* getUrl() const
{
return m_image->getUrl();
}
/**
* Sets the alternative url of the image
*
* @param url The url to load.
*/
void setUrl(const char* url)
{
m_image->setUrl(url);
}
protected:
std::function<void(WidgetRef)> m_clickedFn;
std::shared_ptr<Image> m_image;
uint32_t m_defaultColor;
};
}
}
}
| 1,924 | C | 20.629213 | 112 | 0.637734 |
omniverse-code/kit/include/omni/kit/ui/WindowStandalone.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 <omni/kit/ui/ColumnLayout.h>
#include <omni/kit/ui/Common.h>
#include <omni/kit/ui/Container.h>
#include <omni/kit/ui/Menu.h>
#include <omni/kit/ui/Window.h>
#include <omni/ui/windowmanager/IWindowCallbackManager.h>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
namespace omni
{
namespace kit
{
namespace ui
{
class OMNI_KIT_UI_CLASS_API WindowMainStandalone : public Container
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::WindowMainStandalone);
WidgetType getType() override
{
return kType;
}
protected:
omni::ui::windowmanager::IWindowCallbackPtr m_uiWindow;
};
class OMNI_KIT_UI_CLASS_API WindowStandalone : public ContainerBase
{
public:
typedef uint32_t Flags;
static constexpr Flags kWindowFlagNone = 0;
static constexpr Flags kWindowFlagNoTitleBar = (1 << 0);
static constexpr Flags kWindowFlagNoResize = (1 << 1);
static constexpr Flags kWindowFlagNoMove = (1 << 2);
static constexpr Flags kWindowFlagNoScrollbar = (1 << 3);
static constexpr Flags kWindowFlagNoCollapse = (1 << 4);
static constexpr Flags kWindowFlagNoSavedSettings = (1 << 5);
static constexpr Flags kWindowFlagShowHorizontalScrollbar = (1 << 7);
static constexpr Flags kWindowFlagForceVerticalScrollbar = (1 << 8);
static constexpr Flags kWindowFlagForceHorizontalScrollbar = (1 << 9);
static constexpr Flags kWindowFlagNoClose = (1 << 10);
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::WindowStandalone);
WidgetType getType() override
{
return kType;
}
/**
* Constructor.
*
* @param title The window title.
* @param width The window default width.
* @param height The window default height.
*/
OMNI_KIT_UI_API explicit WindowStandalone(
const char* title,
uint32_t width = 640,
uint32_t height = 480,
bool open = true,
bool addToMenu = true,
const std::string& menuPath = "",
bool isToggleMenu = true,
omni::ui::windowmanager::DockPreference dockPreference = omni::ui::windowmanager::DockPreference::eLeftBottom,
Flags flags = kWindowFlagNone);
/**
* Destructor.
*/
OMNI_KIT_UI_API ~WindowStandalone();
/**
* Gets the title of the window.
*
* @return The title of the window.
*/
OMNI_KIT_UI_API const char* getTitle() const;
/**
* Sets the title for the window.
*
* @param title The title of the window.
*/
OMNI_KIT_UI_API void setTitle(const char* title);
/**
* Gets the width of the window.
*
* @return The width of the window.
*/
OMNI_KIT_UI_API uint32_t getWidth() const;
/**
* Sets the width of the window.
*
* @param width The width of the window.
*/
OMNI_KIT_UI_API void setWidth(uint32_t width);
/**
* Gets the height of the window.
*
* @return The height of the window.
*/
OMNI_KIT_UI_API uint32_t getHeight() const;
/**
* Sets the height of the window.
*
* @param height The height of the window.
*/
OMNI_KIT_UI_API void setHeight(uint32_t height);
/**
* Sets the size of the window.
*
* @param width The width of the window.
* @param height The height of the window.
*/
OMNI_KIT_UI_API void setSize(uint32_t width, uint32_t height);
/**
* Sets the flags for the window.
*
* @param fkags The flags for the window.
*/
OMNI_KIT_UI_API void setFlags(Flags flags)
{
m_flags = flags;
}
/**
* Gets the flags for the window
*
* @param flags The flags for the window.
*/
OMNI_KIT_UI_API Flags getFlags() const
{
return m_flags;
}
/**
* Sets the alpha value (transparency) of the window.
*
* @param alpha The alpha value of the window.
*/
OMNI_KIT_UI_API void setAlpha(float alpha);
/**
* Gets the layout for the window.
*
* @return The layout for the window.
*/
OMNI_KIT_UI_API std::shared_ptr<Container> getLayout() const;
/**
* Sets the layout for the window.
*
* @return The layout for the window.
*/
OMNI_KIT_UI_API void setLayout(std::shared_ptr<Container> layout);
/**
* Determines if the window is visible.
*
* @return true if the window is visible.
*/
OMNI_KIT_UI_API bool isVisible() const;
/**
* Shows a window and sets it to visible.
*/
OMNI_KIT_UI_API void show();
/**
* Hides a window and sets it to not visible.
*/
OMNI_KIT_UI_API void hide();
void draw(float elapsedTime) override;
/**
*
*/
OMNI_KIT_UI_API void setUpdateFn(const std::function<void(float)>& fn);
OMNI_KIT_UI_API void setVisibilityChangedFn(const std::function<void(bool)>& fn);
OMNI_KIT_UI_API void setVisible(bool visible);
carb::events::IEventStream* getEventStream() const
{
return m_stream.get();
}
std::shared_ptr<Menu> menu;
carb::Float2 currentMousePos;
carb::Float2 windowPos;
private:
WindowStandalone() = default;
carb::events::IEventStreamPtr m_stream;
omni::kit::Window* m_handle = nullptr;
omni::kit::SubscriptionId m_updateSubId;
std::string m_title;
std::string m_menuPath;
uint32_t m_width = 0;
uint32_t m_height = 0;
float m_alpha = 1.0f;
bool m_visible = false;
std::shared_ptr<Container> m_layout = nullptr;
std::function<void(float)> m_updateFn;
std::function<void(bool)> m_visibilityChangedFn;
omni::ui::windowmanager::IWindowCallbackPtr m_uiWindow;
bool m_addToMenu;
bool m_menuTogglable;
bool m_autoResize = false;
omni::ui::windowmanager::DockPreference m_dock;
Flags m_flags;
};
}
}
}
| 6,346 | C | 25.012295 | 118 | 0.63867 |
omniverse-code/kit/include/omni/kit/ui/AssetDragDropHandler.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.
//
#pragma once
#include <carb/datasource/DataSourceUtils.h>
#include <carb/extras/Path.h>
#include <carb/imgui/ImGui.h>
#include <carb/logging/Log.h>
#include <omniAudioSchema/sound.h>
#include <omni/kit/IViewport.h>
#include <omni/kit/PythonInterOpHelper.h>
#include <omni/timeline/ITimeline.h>
#include <omni/ui/Widget.h>
#include <omni/usd/AssetUtils.h>
#include <omni/usd/Selection.h>
#include <omni/usd/UsdContext.h>
#include <functional>
#include <regex>
namespace carb
{
namespace datasource
{
struct IDataSource;
struct Connection;
}
namespace imgui
{
struct ImGui;
}
}
namespace omni
{
namespace kit
{
namespace ui
{
static constexpr char kAssetDragDropPayloadId[] = "AssetDragDropPayloadId";
/**
* Defines a class to handle asset drag and drop action.
*/
class AssetDragDropHandler
{
public:
/**
* Defines the payload of a drag
*/
struct Payload
{
static constexpr size_t kStringBufferSize = 260;
char path[kStringBufferSize]; ///! Absolute path to the asset.
char dataSourcePath[kStringBufferSize]; ///! DataSource path to the asset.
carb::datasource::IDataSource* dataSource; ///! DataSource of the asset.
carb::datasource::Connection* connection; ///! Connection of the asset.
};
enum class AssetType
{
eUnknown,
eUsd,
eMdl,
eAudio,
ePrim,
};
using AssetDropHandlerFn = std::function<std::vector<PXR_NS::UsdPrim>(
AssetDragDropHandler*, carb::imgui::ImGui* imgui, const char* payloadId, const carb::imgui::Payload* payload, void* userData)>;
using AssetPeekHandlerFn = std::function<void(
AssetDragDropHandler*, carb::imgui::ImGui* imgui, const carb::imgui::Payload* payload, const carb::Float4& rect)>;
/**
* Constructor.
*
* @param canPeek If this AssetDragDropHandler support @ref peek operation.
* not be bound to any Prim.
*/
AssetDragDropHandler(bool canPeek) : kCanPeek(canPeek)
{
}
/**
* Handles asset drag option.
*
* @param imgui The imgui instance.
* @param payload The payload of the drag. Payload will be copied internally.
* @param tooltip Tool tip to show while dragging.
* @param flags DragDropFlags to control drag behaviors.
*/
void drag(carb::imgui::ImGui* imgui, const Payload& payload, const char* tooltip, carb::imgui::DragDropFlags flags = 0)
{
if (imgui->beginDragDropSource(flags))
{
imgui->setDragDropPayload(
kAssetDragDropPayloadId, &payload, sizeof(payload), carb::imgui::Condition::eAlways);
imgui->text(tooltip);
imgui->endDragDropSource();
}
}
/**
* Handles asset drop option.
*
* @param imgui The imgui instance.
*/
std::vector<PXR_NS::UsdPrim> drop(carb::imgui::ImGui* imgui,
const char* payloadId = kAssetDragDropPayloadId,
const AssetDropHandlerFn& dropHandler = nullptr,
void* userData = nullptr)
{
std::vector<PXR_NS::UsdPrim> prims;
if (imgui->beginDragDropTarget())
{
if (const carb::imgui::Payload* payload = imgui->acceptDragDropPayload(payloadId, 0))
{
if (dropHandler)
prims = dropHandler(this, imgui, payloadId, payload, userData);
else
prims = defaultDropHandler(this, imgui, payloadId, payload, userData);
}
imgui->endDragDropTarget();
}
return prims;
}
/**
* Peeks into current payload without releasing mouse button.
*
* @param imgui The imgui instance.
*/
void peek(carb::imgui::ImGui* imgui, const carb::Float4& rect, const AssetPeekHandlerFn& peekHandler)
{
const carb::imgui::Payload* payload = imgui->getDragDropPayload();
if (!payload)
{
stopPeek();
return;
}
if (!payload->isDataType(kAssetDragDropPayloadId) &&
!payload->isDataType(OMNIUI_NS::Widget::getDragDropPayloadId()))
{
return;
}
// Set mouse cursor shape to indicate drag
imgui->setMouseCursor(carb::imgui::MouseCursor::eHand);
if (!kCanPeek)
{
return;
}
peekHandler(this, imgui, payload, rect);
}
/**
* Checks if the payload wants to query Prim or position under mouse position.
*
* @param imgui The imgui instance.
* @param[out] addOutline Whether to add outline for queried Prim.
* @return true if payload wants to query Prim under mouse position.
*/
bool needsQuery(carb::imgui::ImGui* imgui, bool& addOutline) const
{
auto stage = omni::usd::UsdContext::getContext()->getStage();
if (!stage)
{
return false;
}
addOutline = false;
if (const carb::imgui::Payload* payload = imgui->getDragDropPayload())
{
if (strcmp(payload->dataType, kAssetDragDropPayloadId) != 0 &&
strcmp(payload->dataType, OMNIUI_NS::Widget::getDragDropPayloadId()) != 0)
{
return false;
}
const char* url = reinterpret_cast<const char*>(payload->data);
std::vector<std::string> assetUrls = splitMultiline(url);
for (const auto& assetUrl : assetUrls)
{
auto assetType = getAssetType(assetUrl);
if (assetType == AssetType::eMdl)
{
addOutline = true;
return true;
}
else if (assetType == AssetType::eUsd)
{
return true;
}
else if (assetType == AssetType::ePrim && PXR_NS::SdfPath::IsValidPathString(assetUrl))
{
// If it's a material, then highlight outline of the object under the mouse cursor.
auto prim = stage->GetPrimAtPath(PXR_NS::SdfPath{ assetUrl });
if (prim)
{
bool isMaterial = prim.IsA<PXR_NS::UsdShadeMaterial>();
addOutline = isMaterial;
return isMaterial;
}
}
}
}
return false;
}
/**
* Checks if peeking is in progress.
*/
bool isPeeking() const
{
return m_peeking;
}
/**
* @brief Checks if it's necessary to draw the full preview when peeking
*/
bool hasPreview() const
{
return m_preview;
}
/**
* Sets peeking state.
*
* @param peeking true to start peeking, false to stop peeking
* @param preview true if it's necessary to draw the full preview of the
* layer. false if it's necessary to draw the cross.
*/
void setPeeking(bool peeking, bool preview = false)
{
if (m_peeking == peeking)
{
return;
}
if (!peeking)
{
stopPeek();
}
else
{
PythonInterOpHelper::beginUndoGroup();
m_peeking = peeking;
m_preview = preview;
m_hasUndoGroup = true;
}
}
/**
* Sets the peeking prims.
*
* @param prims the peeking preview prims.
*/
void setPeekingPrims(const std::vector<PXR_NS::UsdPrim>& prims)
{
m_peekingPrims = prims;
}
/**
* Gets the peeking prims.
*/
std::vector<PXR_NS::UsdPrim> getPeekingPrims() const
{
return m_peekingPrims;
}
/**
* Gets asset type from url.
*
* @param url the url of the asset to be checked.
*/
static AssetType getAssetType(const std::string& url)
{
static const std::regex kMdlFile(
"^.*\\.mdl(\\?.*)?$", std::regex_constants::icase | std::regex_constants::optimize);
static const std::regex kAudioFile("^.*\\.(wav|wave|ogg|oga|flac|fla|mp3|m4a|spx|opus)(\\?.*)?$",
std::regex_constants::icase | std::regex_constants::optimize);
// Check for mdl first, because mdl may also be considered a readable
// SdfFileFormat - ie, UsdStage::IsSupportedFile might return true
if (std::regex_search(url, kMdlFile))
{
return AssetType::eMdl;
}
bool canBeOpened = PXR_NS::UsdStage::IsSupportedFile(url);
if (canBeOpened)
{
return AssetType::eUsd;
}
if (std::regex_search(url, kAudioFile))
{
return AssetType::eAudio;
}
if (PXR_NS::SdfPath::IsValidPathString(url))
{
return AssetType::ePrim;
}
return AssetType::eUnknown;
}
/**
* @brief Splits the given line to multilines.
*/
static std::vector<std::string> splitMultiline(const char* input)
{
std::vector<std::string> result;
const char* iterator = input;
while (iterator && *iterator != '\0')
{
const char* foundLineBreak = strchr(iterator, '\n');
if (foundLineBreak)
{
result.emplace_back(iterator, foundLineBreak - iterator);
}
else
{
result.emplace_back(iterator);
}
if (foundLineBreak)
{
iterator = foundLineBreak + 1;
}
else
{
iterator = nullptr;
}
}
return result;
}
static std::vector<std::string> filterAssetPaths(const std::vector<std::string>& assetPaths, AssetType type)
{
std::vector<std::string> filteredAssetPaths;
for (const std::string& assetPath : assetPaths)
{
if (getAssetType(assetPath) == type)
{
filteredAssetPaths.push_back(assetPath);
}
}
return filteredAssetPaths;
}
private:
void stopPeek()
{
if (m_peeking)
{
m_peeking = false;
for (auto& prim : m_peekingPrims)
{
if (prim.IsValid())
{
omni::usd::UsdUtils::removePrim(prim);
}
}
if (m_hasUndoGroup)
{
m_hasUndoGroup = false;
PythonInterOpHelper::endUndoGroup();
// Need to pop the previous undo group because peek is canceled and nothing done in between should be
// undoable.
PythonInterOpHelper::popLastUndoGroup();
}
}
}
static std::vector<PXR_NS::UsdPrim> defaultDropHandler(AssetDragDropHandler* handler,
carb::imgui::ImGui* imgui,
const char* payloadId,
const carb::imgui::Payload* payload,
void* userData)
{
std::vector<PXR_NS::UsdPrim> assetPrims;
const char* url = "";
const char* dataSourcePath = "";
carb::datasource::IDataSource* dataSource = nullptr;
carb::datasource::Connection* connection = nullptr;
// From old content window ? FIXME: Do we need old content window support?
// Old content window supports single drag and drop only.
bool oldContentWindow = strcmp(payloadId, kAssetDragDropPayloadId) == 0;
if (oldContentWindow)
{
const Payload* payloadData = reinterpret_cast<const Payload*>(payload->data);
url = payloadData->path;
dataSourcePath = payloadData->dataSourcePath;
dataSource = payloadData->dataSource;
connection = payloadData->connection;
}
else // From new content window
{
url = reinterpret_cast<const char*>(payload->data);
}
auto stage = omni::usd::UsdContext::getContext()->getStage();
std::vector<std::string> assets = stage && url ? splitMultiline(url) : std::vector<std::string>{};
auto usdAssets = filterAssetPaths(assets, AssetType::eUsd);
auto mdlAssets = filterAssetPaths(assets, AssetType::eMdl);
auto audioAssets = filterAssetPaths(assets, AssetType::eAudio);
auto unknownAssets = filterAssetPaths(assets, AssetType::eUnknown);
if (usdAssets.size() > 0 || mdlAssets.size() > 0 || audioAssets.size() > 0)
{
if (!handler->m_hasUndoGroup)
{
PythonInterOpHelper::beginUndoGroup();
handler->m_hasUndoGroup = true;
}
}
// If it can peek, we just directly use the existing peekingPrims.
if (handler->kCanPeek && handler->hasPreview())
{
if (handler->m_peeking)
{
handler->m_peeking = false;
PXR_NS::SdfPathVector selectedPrimPaths;
for (auto& assetPrim : handler->m_peekingPrims)
{
if (!assetPrim.IsValid())
{
continue;
}
PXR_NS::SdfPath path = assetPrim.GetPath();
selectedPrimPaths.push_back(path);
auto* isettings = carb::getCachedInterface<carb::settings::ISettings>();
// OM-38909: Since we're about to set the selection to this prim, make it un-pickable for snapping
constexpr char kSnapEnabledSetting[] = "/app/viewport/snapEnabled";
constexpr char kSnapToSurfaceSetting[] = PERSISTENT_SETTINGS_PREFIX "/app/viewport/snapToSurface";
const bool snapToSurface = isettings->getAsBool(kSnapEnabledSetting) && isettings->getAsBool(kSnapToSurfaceSetting);
omni::usd::UsdContext::getContext()->setPickable(path.GetText(), !snapToSurface);
if (assetPrim.IsA<PXR_NS::UsdGeomXform>())
{
assetPrim.SetInstanceable(isettings->getAsBool(PERSISTENT_SETTINGS_PREFIX "/app/stage/instanceableOnCreatingReference"));
}
assetPrims.push_back(assetPrim);
}
omni::usd::UsdContext::getContext()->getSelection()->setSelectedPrimPathsV2(selectedPrimPaths);
}
}
for (const auto& asset : usdAssets)
{
std::string relativeUrl = asset;
omni::usd::UsdUtils::makePathRelativeToLayer(stage->GetEditTarget().GetLayer(), relativeUrl);
// If it cannot peek, we'll create all prims.
if (!handler->kCanPeek || !handler->hasPreview())
{
carb::extras::Path urlPath(asset);
std::string warningMsg;
std::string newPrimPath = omni::usd::UsdUtils::findNextNoneExisitingNodePath(
stage, "/" + pxr::TfMakeValidIdentifier(urlPath.getStem().getString()), true);
PythonInterOpHelper::runCreateReferenceCommand(relativeUrl, newPrimPath, true);
auto assetPrim = stage->GetPrimAtPath(PXR_NS::SdfPath(newPrimPath));
if (assetPrim)
{
assetPrims.push_back(assetPrim);
}
}
}
const std::string targetPrim = (const char*)userData;
if (mdlAssets.size() > 1 && !targetPrim.empty())
{
PythonInterOpHelper::postNotification("Multiple materials assignment is not supported.", true, false);
CARB_LOG_WARN("Multiple materials assignment to prim %s is not supported.", targetPrim.c_str());
}
else
{
bool fallbackDataSource = false;
if (mdlAssets.size() > 0 && !dataSource)
{
dataSource = carb::getFramework()->acquireInterface<carb::datasource::IDataSource>(
"carb.datasource-omniclient.plugin");
connection = carb::datasource::connectAndWait({ "", nullptr, nullptr, false }, dataSource);
fallbackDataSource = true;
}
for (const auto& asset : mdlAssets)
{
std::string relativeUrl = asset;
omni::usd::UsdUtils::makePathRelativeToLayer(stage->GetEditTarget().GetLayer(), relativeUrl);
carb::extras::Path urlPath(asset);
if (!omni::usd::UsdUtils::hasPrimAtPath(stage, "/Looks"))
{
std::string looksPath = omni::usd::UsdUtils::findNextNoneExisitingNodePath(stage, "/Looks", true);
PythonInterOpHelper::runCreatePrimCommand(looksPath.c_str(), "Scope", false);
}
if (!oldContentWindow)
{
dataSourcePath = asset.c_str();
}
const std::string mtlName =
omni::usd::AssetUtils::findMaterialNameFromMdlContent(dataSource, connection, urlPath.getString().c_str(), dataSourcePath);
if (!mtlName.empty())
{
const std::string mtlPrimPath = omni::usd::UsdUtils::findNextNoneExisitingNodePath(
stage, "/Looks/" + PXR_NS::TfMakeValidIdentifier(mtlName), true);
PythonInterOpHelper::runCreateMdlMaterialPrimCommand(
url, mtlName, mtlPrimPath, targetPrim);
// when drag onto prim, material prim will not have been created yet so matrial assignment is done
// by runCreateMdlMaterialPrimCommand
auto assetPrim = stage->GetPrimAtPath(PXR_NS::SdfPath(mtlPrimPath));
if (assetPrim)
{
assetPrims.push_back(assetPrim);
}
}
}
if (fallbackDataSource)
{
dataSource->disconnect(connection);
}
}
for (const auto& asset : audioAssets)
{
std::string relativeUrl = asset;
omni::usd::UsdUtils::makePathRelativeToLayer(stage->GetEditTarget().GetLayer(), relativeUrl);
carb::extras::Path urlPath(asset);
std::string path = omni::usd::UsdUtils::findNextNoneExisitingNodePath(
stage, std::string("/") + PXR_NS::TfMakeValidIdentifier(std::string(urlPath.getStem())), true);
PythonInterOpHelper::runCreateAudioPrimFromAssetPathCommand(relativeUrl, path);
auto assetPrim = stage->GetPrimAtPath(PXR_NS::SdfPath(path));
if (assetPrim)
{
assetPrims.push_back(assetPrim);
}
}
for (const auto& asset : unknownAssets)
{
if (!payload->isDataType(OMNIUI_NS::Widget::getDragDropPayloadId()))
{
carb::getCachedInterface<omni::kit::IViewport>()->getViewportWindow(nullptr)->postToast("unsupported file format");
CARB_LOG_WARN("Unsupported file %s", asset.c_str());
break;
}
}
if (handler->m_hasUndoGroup)
{
handler->m_hasUndoGroup = false;
PythonInterOpHelper::endUndoGroup();
}
return assetPrims;
}
const bool kCanPeek;
bool m_peeking = false;
// true when it's necessary to draw the full preview when peeking
bool m_preview = false;
bool m_hasUndoGroup = false;
std::vector<PXR_NS::UsdPrim> m_peekingPrims;
};
}
}
}
| 20,144 | C | 32.687291 | 145 | 0.557834 |
omniverse-code/kit/include/omni/kit/ui/ViewCollapsing.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 "Container.h"
#include "Model.h"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Widget that spawns different widgets depending on the underlying model leaf node type.
*/
class OMNI_KIT_UI_CLASS_API ViewNode : public ModelWidget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ViewNode);
OMNI_KIT_UI_API ViewNode();
OMNI_KIT_UI_API ~ViewNode();
WidgetType getType() override
{
return kType;
}
OMNI_KIT_UI_API std::shared_ptr<Widget> getWidget() const;
private:
void _onModelNodeChange() override;
template <class T>
std::shared_ptr<Widget> _createWidget();
std::shared_ptr<Widget> _tryCreateWidgetFromMeta();
std::shared_ptr<Widget> _createWidgetFromValueType();
};
/**
* Widget to view Model Array nodes..
*/
class OMNI_KIT_UI_CLASS_API ViewArray : public ModelWidget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ViewArray);
OMNI_KIT_UI_API ViewArray();
OMNI_KIT_UI_API ~ViewArray();
WidgetType getType() override
{
return kType;
}
private:
void _onModelNodeChange() override;
void _createWidgetsFromArray();
};
/**
* Takes section of a model and represent it as a list of widgets.
* Supports filtering.
*/
class OMNI_KIT_UI_CLASS_API ViewFlat : public ModelWidget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ViewFlat);
OMNI_KIT_UI_API ViewFlat(bool sort);
OMNI_KIT_UI_API ~ViewFlat();
WidgetType getType() override
{
return kType;
}
OMNI_KIT_UI_API size_t setFilter(const char* filter);
protected:
bool m_sort;
private:
std::shared_ptr<Container> _createLayout();
void _createWidgetsFromModel();
void _createLeafWidgetPair(std::shared_ptr<Widget> labelWidget,
const std::string& modelRootPath,
std::shared_ptr<Container>& layout);
void _onModelNodeChange() override;
};
/**
* Takes topmost sections of a model and spawns CollapsingFrame+ViewFlat for each.
* Supports filtering.
*/
class OMNI_KIT_UI_CLASS_API ViewCollapsing : public ModelWidget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ViewCollapsing);
OMNI_KIT_UI_API ViewCollapsing(bool defaultOpen, bool sort);
OMNI_KIT_UI_API ~ViewCollapsing();
WidgetType getType() override
{
return kType;
}
OMNI_KIT_UI_API void setFilter(const char* filter);
void setUseFrameBackgroundColor(bool useFrameBackgroundColor)
{
m_useFrameBackgroundColor = useFrameBackgroundColor;
}
bool getUseFrameBackgroundColor() const
{
return m_useFrameBackgroundColor;
}
protected:
bool m_defaultOpen;
bool m_sort;
bool m_useFrameBackgroundColor;
private:
void _createWidgetsFromModel();
void _onModelNodeChange() override;
};
enum class DelegateAction
{
eCreateDefaultWidget = 0,
eSkipKey,
eUseCustomWidget
};
struct DelegateResult
{
DelegateAction action;
std::shared_ptr<Widget> customWidget;
};
class OMNI_KIT_UI_CLASS_API ViewTreeGrid : public ModelWidget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ViewTreeGrid);
OMNI_KIT_UI_API ViewTreeGrid(bool defaultOpen, bool sort, uint32_t columnCount);
OMNI_KIT_UI_API ~ViewTreeGrid();
WidgetType getType() override
{
return kType;
}
void draw(float elapsedTime) override;
OMNI_KIT_UI_API bool getDrawTableHeader() const;
OMNI_KIT_UI_API void setDrawTableHeader(bool drawTableHeader);
using OnBuildCellFn = DelegateResult (*)(std::shared_ptr<Model> model,
const char* modelPath,
uint32_t columnIdx,
uint32_t columnCount);
using OnBuildCellStdFn = std::function<std::remove_pointer_t<OnBuildCellFn>>;
OMNI_KIT_UI_API void setOnBuildCellFn(const OnBuildCellStdFn& onBuildCellStdFn);
OMNI_KIT_UI_API void setHeaderCellWidget(uint32_t columnIdx, std::shared_ptr<Widget> widget);
OMNI_KIT_UI_API std::shared_ptr<Widget> getHeaderCellWidget(uint32_t columnIdx);
OMNI_KIT_UI_API void setHeaderCellText(uint32_t columnIdx, const char* text);
OMNI_KIT_UI_API void setIsRoot(bool isRoot);
OMNI_KIT_UI_API bool getIsRoot() const;
OMNI_KIT_UI_API void setText(const char* text);
OMNI_KIT_UI_API const char* getText() const;
protected:
bool m_defaultOpen;
bool m_sort;
std::string m_text;
uint32_t m_columnCount;
bool m_isRoot = true;
bool m_drawTableHeader = false;
std::vector<std::shared_ptr<Widget>> m_headerWidgets;
std::vector<float> m_columnOffsets;
OnBuildCellStdFn m_onBuildCellStdFn;
bool m_widgetsValid = false;
bool m_isNodeOpen = false;
void setSibling(uint32_t columnIdx, std::shared_ptr<Widget> sibling);
std::shared_ptr<Widget> getSibling(uint32_t columnIdx);
std::vector<std::shared_ptr<Widget>> m_siblingCells;
std::shared_ptr<Widget> _buildDefaultLeafWidget(const char* sectionName, const char* sectionPath);
void _createWidgetsFromModel();
void _onModelNodeChange() override;
void _drawTableHeader(float elapsedTime);
const uint32_t kNoTreeNode = (uint32_t)-1;
uint32_t _findTreeNodeColumnIndexInRow(uint32_t rowIndex);
void _drawCommonChildrenTreeNodeRow(uint32_t rowIndex, uint32_t treeNodeColumnIndex, float elapsedTime);
void _drawCommonChildrenRegularRow(uint32_t rowIndex, float elapsedTime);
void _drawCommonChildrenGrid(float elapsedTime);
void _drawAsRoot(float elapsedTime);
void _drawAsChildHeader(float elapsedTime);
void _drawAsChildBody(float elapsedTime);
};
}
}
}
| 6,282 | C | 26.199134 | 108 | 0.692455 |
omniverse-code/kit/include/omni/kit/ui/ContentWindow.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>
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a ContentWindow.
*/
class OMNI_KIT_UI_CLASS_API ContentWindow : public Widget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ContentWindow);
/**
* Constructor.
*/
OMNI_KIT_UI_API ContentWindow();
OMNI_KIT_UI_API ContentWindow(uint32_t width, uint32_t height);
/**
* Destructor.
*/
OMNI_KIT_UI_API ~ContentWindow() override;
/**
* @see Widget::getType
*/
OMNI_KIT_UI_API WidgetType getType() override;
/**
* @see Widget::draw
*/
void draw(float elapsedTime) override;
OMNI_KIT_UI_API virtual void refresh();
OMNI_KIT_UI_API virtual void getSelectedTreeNodePaths(std::string* protocol,
std::string* realUrl,
std::string* contentUrl);
OMNI_KIT_UI_API virtual void getSelectedFileNodePaths(std::string* protocol,
std::string* realUrl,
std::string* contentUrl);
OMNI_KIT_UI_API virtual void setFilter(const std::string& regex);
OMNI_KIT_UI_API virtual void navigateTo(const std::string& path);
protected:
ContentWindowWidget* m_contentWindowWidget = nullptr;
};
}
}
}
| 1,906 | C | 25.859155 | 83 | 0.618573 |
omniverse-code/kit/include/omni/kit/ui/CollapsingFrame.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 "Container.h"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a expanding/collapsing frame layout.
*/
class OMNI_KIT_UI_CLASS_API CollapsingFrame : public Container
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::CollapsingFrame);
OMNI_KIT_UI_API CollapsingFrame(const char* title, bool defaultOpen);
OMNI_KIT_UI_API ~CollapsingFrame();
OMNI_KIT_UI_API WidgetType getType() override;
void draw(float elapsedTime) override;
void setTitle(const char* title)
{
m_title = title;
}
const char* getTitle() const
{
return m_title.c_str();
}
void setOpen(bool open)
{
m_open = open;
}
bool isOpen() const
{
return m_open;
}
void setUseFrameBackgroundColor(bool useFrameBackgroundColor)
{
m_useFrameBackgroundColor = useFrameBackgroundColor;
}
bool getUseFrameBackgroundColor() const
{
return m_useFrameBackgroundColor;
}
protected:
std::string m_title;
bool m_open;
float m_calculatedHeight;
bool m_useFrameBackgroundColor;
};
}
}
}
| 1,595 | C | 20.863013 | 83 | 0.692163 |
omniverse-code/kit/include/omni/kit/ui/RowColumnLayout.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 "Container.h"
#include <vector>
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a row/column (wrapping horizontal-style) layout.
*/
class OMNI_KIT_UI_CLASS_API RowColumnLayout : public Container
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::RowColumnLayout);
OMNI_KIT_UI_API RowColumnLayout(size_t columnCount, bool columnBorders);
OMNI_KIT_UI_API ~RowColumnLayout();
OMNI_KIT_UI_API const Length& getColumnWidth(size_t index) const;
OMNI_KIT_UI_API void setColumnWidth(size_t index, Length length, float min = 0.0f, float max = 0.0f);
void setColumnWidth(size_t index, float width, float min = 0.0f, float max = 0.0f)
{
setColumnWidth(index, Pixel(width), min, max);
}
OMNI_KIT_UI_API WidgetType getType() override;
void draw(float elapsedTime) override;
protected:
typedef struct
{
Length len;
float min;
float max;
} ColumnSize;
std::vector<ColumnSize> m_columnWidths;
bool m_columnBorders = false;
};
}
}
}
| 1,520 | C | 23.934426 | 105 | 0.711184 |
omniverse-code/kit/include/omni/kit/ui/Spacer.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"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a spacing element.
*/
class OMNI_KIT_UI_CLASS_API Spacer : public Widget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Spacer);
OMNI_KIT_UI_API explicit Spacer(Length width, Length height = Pixel(0));
OMNI_KIT_UI_API explicit Spacer(float width);
/**
* @see Widget::getType
*/
OMNI_KIT_UI_API WidgetType getType() override;
/**
* @see Widget::draw
*/
void draw(float elapsedTime) override;
};
}
}
}
| 1,018 | C | 21.152173 | 77 | 0.707269 |
omniverse-code/kit/include/omni/kit/ui/Library.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"
namespace omni
{
namespace kit
{
namespace ui
{
OMNI_KIT_UI_API void initializeKitUI();
OMNI_KIT_UI_API void terminateKitUI();
}
}
}
| 609 | C | 20.785714 | 77 | 0.768473 |
omniverse-code/kit/include/omni/kit/ui/CheckBox.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 "Button.h"
#include "ValueWidget.h"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a check box.
*/
class OMNI_KIT_UI_CLASS_API CheckBox : public SimpleValueWidget<bool>
{
public:
static const WidgetType kType = CARB_HASH_STRING("CheckBox");
OMNI_KIT_UI_API explicit CheckBox(const char* text = "",
bool value = false,
bool leftHanded = false,
bool styled = false);
OMNI_KIT_UI_API ~CheckBox() override;
OMNI_KIT_UI_API WidgetType getType() override;
bool styled;
protected:
bool _drawImGuiWidget(carb::imgui::ImGui* imgui, bool& value) override;
};
}
}
}
| 1,180 | C | 24.673913 | 77 | 0.664407 |
omniverse-code/kit/include/omni/kit/ui/Field.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"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a input field.
*
* Usage:
* Field<int>
* Field<double>
*/
template <class T>
class OMNI_KIT_UI_CLASS_API Field : public SimpleValueWidget<T>
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Field<T>);
OMNI_KIT_UI_API explicit Field(const char* text, T value = 0, T step = 1, T stepFast = 100);
OMNI_KIT_UI_API ~Field();
T step = 0;
T stepFast = 0;
std::string format;
OMNI_KIT_UI_API WidgetType getType() override;
protected:
bool _drawImGuiWidget(carb::imgui::ImGui* imgui, T& value) override;
};
}
}
}
| 1,114 | C | 21.3 | 96 | 0.709156 |
omniverse-code/kit/include/omni/kit/ui/ColumnLayout.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 "Container.h"
#include <carb/Types.h>
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a column(vertical-style) layout.
*/
class OMNI_KIT_UI_CLASS_API ColumnLayout : public Container
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ColumnLayout);
OMNI_KIT_UI_API explicit ColumnLayout(int itemSpacing = -1, int paddingX = -1, int paddingY = -1);
OMNI_KIT_UI_API ~ColumnLayout();
OMNI_KIT_UI_API WidgetType getType() override;
void draw(float elapsedTime) override;
protected:
carb::Int2 m_padding;
};
}
}
}
| 1,041 | C | 22.155555 | 102 | 0.735831 |
omniverse-code/kit/include/omni/kit/ui/Transform.h | // Copyright (c) 2018-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 "ScalarXYZ.h"
#include "ValueWidget.h"
namespace omni
{
namespace kit
{
namespace ui
{
inline Mat44 getIdentityMat44()
{
static Mat44 kIdentityMat44;
kIdentityMat44.rows[0] = { 1, 0, 0, 0 };
kIdentityMat44.rows[1] = { 0, 1, 0, 0 };
kIdentityMat44.rows[2] = { 0, 0, 1, 0 };
kIdentityMat44.rows[3] = { 0, 0, 0, 1 };
return kIdentityMat44;
}
/**
* Defines a transform widget.
*/
class OMNI_KIT_UI_CLASS_API Transform : public ValueWidget<Mat44>
{
public:
static const WidgetType kType = CARB_HASH_STRING("Transform");
OMNI_KIT_UI_API Transform(const char* posDisplayFormat = "%0.1f",
float posSpeed = 1.0f,
float posWrapValue = 0.0f,
float posMinValue = 0.0f,
float posMaxValue = 0.0f,
const char* rotDisplayFormat = "%0.1f",
float rotSpeed = 1.0f,
float rotWrapValue = 0.0f,
float rotMinValue = 0.0f,
float rotMaxValue = 0.0f,
Mat44 value = getIdentityMat44());
OMNI_KIT_UI_API ~Transform();
OMNI_KIT_UI_API WidgetType getType() override;
void draw(float elapsedTime) override;
private:
std::string m_labelRotation;
std::string m_labelScale;
enum class Types
{
ePosition,
eRotation,
eScale,
eCount
};
std::shared_ptr<ScalarXYZ> m_scalar[static_cast<size_t>(Types::eCount)];
};
}
}
}
| 2,056 | C | 26.797297 | 77 | 0.59144 |
omniverse-code/kit/include/omni/kit/ui/Container.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 <vector>
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines the base class for layouts.
*/
class OMNI_KIT_UI_CLASS_API ContainerBase : public Widget
{
public:
OMNI_KIT_UI_API ContainerBase();
OMNI_KIT_UI_API ~ContainerBase() override;
OMNI_KIT_UI_API void draw(float elapsedTime) override;
protected:
carb::Float2 m_childSpacing = { 8, 4 };
std::vector<std::shared_ptr<Widget>> m_children;
OMNI_KIT_UI_API virtual size_t _getChildCount() const;
OMNI_KIT_UI_API virtual std::shared_ptr<Widget> _getChildAt(size_t index) const;
OMNI_KIT_UI_API virtual std::shared_ptr<Widget> _addChild(std::shared_ptr<Widget> widget);
OMNI_KIT_UI_API virtual void _removeChild(std::shared_ptr<Widget> widget);
OMNI_KIT_UI_API virtual void _clear();
};
class OMNI_KIT_UI_CLASS_API Container : public ContainerBase
{
public:
OMNI_KIT_UI_API Container();
OMNI_KIT_UI_API ~Container() override;
OMNI_KIT_UI_API virtual carb::Float2 getChildSpacing() const;
OMNI_KIT_UI_API virtual void setChildSpacing(const carb::Float2& childSpacing);
OMNI_KIT_UI_API size_t getChildCount() const;
OMNI_KIT_UI_API std::shared_ptr<Widget> getChildAt(size_t index) const;
OMNI_KIT_UI_API std::shared_ptr<Widget> addChild(std::shared_ptr<Widget> widget);
template <class T, typename... Args>
std::shared_ptr<T> emplaceChild(Args&&... args);
OMNI_KIT_UI_API void removeChild(std::shared_ptr<Widget> widget);
OMNI_KIT_UI_API void clear();
protected:
carb::Float2 m_childSpacing = { 8, 4 };
};
}
}
}
| 2,065 | C | 24.506173 | 94 | 0.713317 |
omniverse-code/kit/include/omni/kit/ui/FilePicker.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 <omni/kit/IFileDialog.h>
#include <omni/kit/KitTypes.h>
#include <omni/ui/windowmanager/IWindowCallbackManager.h>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines an FilePicker class that handles file/folder selection.
*/
class OMNI_KIT_UI_CLASS_API FilePicker
{
public:
using OnFileSelected = std::function<void(const char* path)>;
using OnDialogCancelled = std::function<void()>;
enum class Mode
{
eOpen, ///! OpenFileDialog.
eSave, ///! SaveFileDialog.
};
enum class Type
{
eFile, ///! Select file.
eDirectory, ///! Select directory.
eAll ///! Select file or directory
};
enum class DataSource
{
eLocal, ///! Show local files only
eOmniverse, ///! Show omniverse files only
eAll ///! Show files form all data sources
};
/**
* Constructor.
*
* @param mode Open or Save dialog.
* @param type Choose File or Directory.
* @param title Title text.
* @param onFileSelctedFn Callback for path selection.
* @param onDialogCancelled Callback for dialog cancel.
* @param width Initial window width.
* @param height Initial window height.
* @param dataSource Data source that files come from.
*/
OMNI_KIT_UI_API FilePicker(const std::string& title,
Mode mode,
Type type,
OnFileSelected onFileSelctedFn,
OnDialogCancelled onDialogCancelled,
float width,
float height);
OMNI_KIT_UI_API ~FilePicker();
/**
* Shows the open file dialog.
*/
OMNI_KIT_UI_API void show(DataSource dataSource = DataSource::eAll);
OMNI_KIT_UI_API bool isVisible() const;
OMNI_KIT_UI_API const char* getTitle() const;
OMNI_KIT_UI_API void setTitle(const char* title);
OMNI_KIT_UI_API Type getSelectionType() const;
OMNI_KIT_UI_API void setSelectionType(Type type);
OMNI_KIT_UI_API void setFileSelectedFn(const OnFileSelected& fn);
OMNI_KIT_UI_API void setDialogCancelled(const OnDialogCancelled& fn);
/**
* Add file type filter.
*
* @param name Name of the file type.
* @param spec Specification of the file type.
*/
OMNI_KIT_UI_API void addFilter(const std::string& name, const std::string& spec);
/**
* Clear all filters.
*/
OMNI_KIT_UI_API void clearAllFilters();
/**
* Sets the directory where the dialog will open
*/
OMNI_KIT_UI_API void setCurrentDirectory(const char* dir);
/** sets the default name to use for the filename on save dialogs.
*
* @param[in] name the default filename to use for this dialog. This may be nullptr
* or an empty string to use the USD stage's default prim name. In
* this case, if the prim name cannot be retrieved, "Untitled" will
* be used instead. If a non-empty string is given here, this will
* always be used as the initial suggested filename.
* @returns no return value.
*
* @remarks This sets the default filename to be used when saving a file. This name will
* be ignored if the dialog is not in @ref FileDialogOpenMode::eSave mode. The
* given name will still be stored regardless. This default filename may omit
* the file extension to take the extension from the current filter. If an
* extension is explicitly given here, no extension will be appended regardless
* of the current filter.
*/
OMNI_KIT_UI_API void setDefaultSaveName(const char* name);
private:
void _draw(float dt);
FileDialog* m_fileDialog = nullptr;
omni::ui::windowmanager::IWindowCallbackPtr m_handle;
OnFileSelected m_fileSelectedFn;
OnDialogCancelled m_dialogCancelledFn;
};
}
}
}
| 4,587 | C | 30.210884 | 94 | 0.633312 |
omniverse-code/kit/include/omni/kit/ui/ColorScheme.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/Types.h>
#include <carb/logging/Log.h>
#include <unordered_map>
namespace omni
{
namespace kit
{
namespace ui
{
// Generic
const carb::Float4 kErrorMessageColor = { 1.f, 0.f, 0.f, 1.f };
// Asset Explorer
const carb::Float4 kAssetExplorerFilterIconEnabledColor = { 126.f / 255.f, 187.f / 255.f, 199.f / 255.f, 1.f };
const carb::Float4 kAssetExplorerClearFilterColor = { 15.f / 255.f, 110.f / 255.f, 131.f / 255.f, 1.f };
const carb::Float4 kAssetExplorerAssetIconSelectedBgColorDark = { 0.2f, 0.2f, 0.2f, 0.6f };
const carb::Float4 kAssetExplorerAssetIconSelectedBgColorLight = { 0.84f, 0.84f, 0.84f, 1.0f };
const carb::Float4 kAssetExplorerAssetIconHoveredBgColorDark = { 0.2f, 0.2f, 0.2f, 0.8f };
const carb::Float4 kAssetExplorerAssetIconHoveredBgColorLight = { 0.749f, 0.8f, 0.812f, 1.0f };
const carb::Float4 kAssetExplorerPopulatedFolderColor = { 119.f / 255.f, 134 / 255.f, 137 / 255.f, 1.0f };
const carb::Float4 kAssetExplorerUnpopulatedFolderColor = { 0.39f, 0.39f, 0.39f, 1.0f };
// ECS Debug View
const carb::Float4 kEcsDebugViewSelectedComponentColor = { 1.f, 1.f, 0.f, 1.f };
// IEditor Window
const carb::Float4 kEditorWindowConnectionStateDisconnectedColor = { 1.f, 0.f, 0.f, 1.f };
const carb::Float4 kEditorWindowConnectionStateConnectedNoLiveColor = { 0.796f, 0.416f, 0.416f, 1.f };
const carb::Float4 kEditorWindowConnectionStateConnectedLiveColor = { 0.46f, 0.72f, 0.f, 1.f };
// Scene Hierarchy
const carb::Float4 kSceneHierarchySearchMatchedColor = { 1.f, 1.f, 1.f, 1.f };
const carb::Float4 kSceneHierarchySearchUnmatchedColor = { 0.5f, 0.5f, 0.5f, 1.f };
// Status Bar
const carb::Float4 kStatusBarProgressColor = { 79.f / 255.f, 125.f / 255.f, 160.f / 255.f, 1.f };
// Simple Tree View
const carb::Float4 kTreeViewColor = { 0.3f, 0.3f, 0.3f, 1.0f };
// Viewport
const carb::Float4 kViewportChildWindowBgColor = { 0.f, 0.f, 0.f, 0.f };
// Layers Window
const carb::Float4 kLayerWarningColor = { 1.0f, 111.0f / 255.0f, 114.0f / 255.0f, 1.0f };
// Message
using ColorMap = std::unordered_map<int32_t, carb::Float4>;
const carb::Float4 kMessageTextColorLightDefault = { 0.30980f, 0.49020f, 0.62745f, 1.f };
const ColorMap kMessageTextColorLight = {
// Other levels use default color
{ carb::logging::kLevelVerbose, carb::Float4{ 0.49020f, 0.49020f, 0.49020f, 1.f } },
{ carb::logging::kLevelWarn, carb::Float4{ 0.89020f, 0.54118f, 0.14118f, 1.f } },
{ carb::logging::kLevelError, carb::Float4{ 0.57255f, 0.25882f, 0.22745f, 1.f } },
{ carb::logging::kLevelFatal, carb::Float4{ 0.57255f, 0.25882f, 0.22745f, 1.f } }
};
const carb::Float4 kMessageTextColorDarkDefault = { 0.47451f, 0.72941f, 0.92157f, 1.f };
const ColorMap kMessageTextColorDark = {
// Other levels use default color
{ carb::logging::kLevelVerbose, carb::Float4{ 0.72941f, 0.72941f, 0.72941f, 1.f } },
{ carb::logging::kLevelWarn, carb::Float4{ 0.87451f, 0.79608f, 0.29020f, 1.f } },
{ carb::logging::kLevelError, carb::Float4{ 0.96471f, 0.69412f, 0.66667f, 1.f } },
{ carb::logging::kLevelFatal, carb::Float4{ 0.96471f, 0.69412f, 0.66667f, 1.f } }
};
const carb::Float4 kMessageIconColorLightDefault = { 0.30980f, 0.49020f, 0.62745f, 1.f };
const ColorMap kMessageIconColorLight = {
// Other levels use default color
{ carb::logging::kLevelVerbose, carb::Float4{ 0.49020f, 0.49020f, 0.49020f, 1.f } },
{ carb::logging::kLevelWarn, carb::Float4{ 0.89020f, 0.54118f, 0.14118f, 1.f } },
{ carb::logging::kLevelError, carb::Float4{ 0.973f, 0.541f, 0.49f, 1.f } },
{ carb::logging::kLevelFatal, carb::Float4{ 0.973f, 0.541f, 0.49f, 1.f } }
};
const carb::Float4 kMessageIconColorDarkDefault = { 0.47451f, 0.72941f, 0.92157f, 1.f };
const ColorMap kMessageIconColorDark = {
// Other levels use default color
{ carb::logging::kLevelVerbose, carb::Float4{ 0.72941f, 0.72941f, 0.72941f, 1.f } },
{ carb::logging::kLevelWarn, carb::Float4{ 0.87451f, 0.79608f, 0.29020f, 1.f } },
{ carb::logging::kLevelError, carb::Float4{ 0.973f, 0.541f, 0.49f, 1.f } },
{ carb::logging::kLevelFatal, carb::Float4{ 0.973f, 0.541f, 0.49f, 1.f } }
};
inline carb::Float4 selectColor(bool darkUi,
int32_t level,
const ColorMap& darkMap,
const ColorMap& lightMap,
const carb::Float4& darkDefault,
const carb::Float4& lightDefault)
{
const ColorMap& colorMap = darkUi ? darkMap : lightMap;
carb::Float4 color = darkUi ? darkDefault : lightDefault;
auto colorEntry = colorMap.find(level);
if (colorEntry != colorMap.end())
{
color = colorEntry->second;
}
return color;
}
}
}
}
| 5,198 | C | 42.689075 | 111 | 0.674298 |
omniverse-code/kit/include/omni/kit/ui/Image.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 <carb/renderer/RendererTypes.h>
#include <atomic>
#include <mutex>
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a image.
*/
class OMNI_KIT_UI_CLASS_API Image : public Widget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Image);
/**
* Constructor.
* ALWAYS create Image with make_shared so enable_shared_from_this works correctly.
*
* @param text The text for the label to use.
*/
OMNI_KIT_UI_API Image(const char* url, uint32_t width, uint32_t height);
/**
* Destructor.
*/
OMNI_KIT_UI_API ~Image() override;
/**
* Gets the url of the image.
*
* @return The url to be loaded.
*/
OMNI_KIT_UI_API const char* getUrl() const;
/**
* Sets the url of the image
*
* @param url The url to load.
*/
OMNI_KIT_UI_API virtual void setUrl(const char* url);
/**
* @see Widget::getType
*/
OMNI_KIT_UI_API WidgetType getType() override;
/**
* @see Widget::draw
*/
void draw(float elapsedTime) override;
/**
* draw image
*
* @param imgui imgui ptr
* @param cursorPos position to draw image
* @param width width of image to draw
* @param height height of image to draw
* @param color color of image to draw
*/
OMNI_KIT_UI_API virtual void drawImage(carb::imgui::ImGui* imgui,
const carb::Float2& cursorPos,
float width,
float height,
uint32_t color = 0xffffffff,
uint32_t defaultColor = 0xffffffff,
bool hovered = false);
protected:
void loadUrl();
std::string m_url;
std::mutex m_textureMutex;
carb::renderer::Texture* m_texture = nullptr;
carb::renderer::TextureHandle m_textureGpuHandle = {};
bool m_hasSetUrl = false;
};
}
}
}
| 2,532 | C | 24.33 | 87 | 0.587678 |
omniverse-code/kit/include/omni/kit/ui/ProgressBar.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 "ColorScheme.h"
#include "Widget.h"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a progress bar.
*/
class OMNI_KIT_UI_CLASS_API ProgressBar : public Widget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ProgressBar);
OMNI_KIT_UI_API ProgressBar(Length width,
Length height = Pixel(0),
const carb::Float4& color = kStatusBarProgressColor);
OMNI_KIT_UI_API ProgressBar(float width, const carb::Float4& color = kStatusBarProgressColor);
/**
* Destructor.
*/
OMNI_KIT_UI_API virtual ~ProgressBar();
/**
* @see Widget::getType
*/
OMNI_KIT_UI_API virtual WidgetType getType();
/**
* @see Widget::draw
*/
OMNI_KIT_UI_API virtual void draw(float elapsedTime);
/**
* Set progress
*
* @param value The current value of progress bar (between 0-1).
* @param text The overlay text for the progress bar. If nullptr, the automatic percentage text is displayed.
*/
OMNI_KIT_UI_API void setProgress(float value, const char* text = nullptr);
/**
* Get current progress
*
* @return The current value of progress bar (between 0-1).
*/
OMNI_KIT_UI_API float getProgress() const;
/**
* Get current overlay
*
* @return The current overlay of progress bar.
*/
OMNI_KIT_UI_API const char* getOverlay() const;
/**
* Set color of bar
*
* @param color Value in carb::Float4.
*/
OMNI_KIT_UI_API void setColor(carb::Float4 color);
/**
* Get color of bar
*
* @return color Value in carb::Float4.
*/
OMNI_KIT_UI_API carb::Float4 getColor() const;
protected:
float m_value; ///< The progress bar value (between 0-1).
carb::Float4 m_color; // The color of progress bar.
};
}
}
}
| 2,350 | C | 24.554348 | 115 | 0.638298 |
omniverse-code/kit/include/omni/kit/ui/TextBox.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 text field.
*/
class OMNI_KIT_UI_CLASS_API TextBox : public ValueWidget<std::string>
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::TextBox);
static const size_t kMaxLength = 1024;
OMNI_KIT_UI_API explicit TextBox(const char* defaultText, bool changeValueOnEnter = false);
OMNI_KIT_UI_API TextBox(const char* defaultText, const char* hint, bool changeValueOnEnter = false);
OMNI_KIT_UI_API ~TextBox() override;
OMNI_KIT_UI_API void setValueChangedFn(const std::function<void(WidgetRef)>& fn);
OMNI_KIT_UI_API void setValueFinalizedFn(const std::function<void(WidgetRef)>& fn);
OMNI_KIT_UI_API void setListSuggestionsFn(const std::function<std::vector<std::string>(WidgetRef, const char*)>& fn);
OMNI_KIT_UI_API bool getReadOnly() const;
OMNI_KIT_UI_API void setReadOnly(bool readOnly);
OMNI_KIT_UI_API bool getShowBackground() const;
OMNI_KIT_UI_API void setShowBackground(bool showBackground);
OMNI_KIT_UI_API float getTextWidth();
/**
* Sets the color of the text.
*
* @param textColor
*/
OMNI_KIT_UI_API void setTextColor(const carb::ColorRgba& textColor);
/**
* Resets the color of the text.
*
* @param textColor
*/
OMNI_KIT_UI_API void resetTextColor();
/**
* @see Widget::getType
*/
OMNI_KIT_UI_API WidgetType getType() override;
/**
* @see Widget::draw
*/
OMNI_KIT_UI_API void draw(float elapsedTime) override;
OMNI_KIT_UI_API virtual std::vector<std::string> listSuggestions(const char* prefix);
/* NOTE: only eEllipsisLeft & eEllipsisRight are supported
when clipping is used, the TextBox will be readonly & disabled, but not greyed out
*/
ClippingType getClippingMode(ClippingType mode) const
{
return m_clippingMode;
}
void setClippingMode(ClippingType mode)
{
if (mode == ClippingType::eWrap)
{
CARB_LOG_ERROR("TextBox widget does not support ClippingType::eWrap");
return;
}
m_clippingMode = mode;
}
protected:
void _onValueChange() override;
private:
void setText(const char* text);
bool m_changeValueOnEnter;
bool m_isReadOnly = false;
bool m_wasActive = false;
bool m_showBackground = true;
char m_text[kMaxLength] = "";
char m_hint[kMaxLength] = "";
std::function<void(WidgetRef)> m_valueChangedFn;
std::function<void(WidgetRef)> m_valueFinalizedFn;
std::function<std::vector<std::string>(WidgetRef, const char*)> m_listSuggestionsFn;
SubscriptionId m_valueSubId;
float m_clippingWidth;
ClippingType m_clippingMode;
bool m_customColor = false;
carb::ColorRgba m_textColor;
};
}
}
}
| 3,354 | C | 25.626984 | 121 | 0.682171 |
omniverse-code/kit/include/omni/kit/ui/ScrollingFrame.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 "Container.h"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a FixedSizeFrame layout.
*/
class OMNI_KIT_UI_CLASS_API ScrollingFrame : public Container
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ScrollingFrame);
OMNI_KIT_UI_API ScrollingFrame(const char* title, float width, float height);
OMNI_KIT_UI_API ~ScrollingFrame();
OMNI_KIT_UI_API virtual void scrollTo(float scrollTo);
OMNI_KIT_UI_API WidgetType getType() override;
void draw(float elapsedTime) override;
protected:
float m_width;
float m_height;
bool m_needsScrolling = false;
float m_scrollTo;
std::string m_title;
bool m_defaultOpen;
};
}
}
}
| 1,171 | C | 22.918367 | 82 | 0.734415 |
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/ModelMeta.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 "Model.h"
namespace omni
{
namespace kit
{
namespace ui
{
constexpr const char* const kModelMetaWidgetType = "widgetType";
constexpr const char* const kModelMetaSerializedContents = "serializedContents";
}
}
}
| 678 | C | 23.249999 | 80 | 0.783186 |
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/Separator.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"
namespace omni
{
namespace kit
{
namespace ui
{
/**
* Defines a separator element.
*/
class OMNI_KIT_UI_CLASS_API Separator : public Widget
{
public:
static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Separator);
OMNI_KIT_UI_API Separator();
/**
* @see Widget::getType
*/
OMNI_KIT_UI_API WidgetType getType() override;
/**
* @see Widget::draw
*/
void draw(float elapsedTime) override;
};
}
}
}
| 931 | C | 20.181818 | 77 | 0.706767 |
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 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.