file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/include/omni/renderer/utils/AssetsManagement.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/assets/IAssets.h> #include <carb/datasource/DataSourceUtils.h> #include <carb/datasource/IDataSource.h> #include <carb/filesystem/IFileSystem.h> #include <carb/logging/Log.h> #include <omni/usd/PathUtils.h> #include <unordered_map> #include <vector> namespace omni { namespace renderer { namespace utils { inline carb::datasource::IDataSource* getDataSourceFile() { return carb::getFramework()->tryAcquireInterface<carb::datasource::IDataSource>("carb.datasource-file.plugin"); } static bool isPathPrefixed(const std::string& path, const char* prefix, size_t prefixLen) { return path.length() > prefixLen && strncasecmp(path.c_str(), prefix, prefixLen) == 0; } inline std::vector<std::tuple<char, carb::datasource::IDataSource*, carb::datasource::Connection*>> getFilesystemConnections() { carb::filesystem::IFileSystem* fs = carb::getFramework()->acquireInterface<carb::filesystem::IFileSystem>(); carb::datasource::IDataSource* dataSource = carb::getFramework()->tryAcquireInterface<carb::datasource::IDataSource>("carb.datasource-omniclient.plugin"); if (!dataSource) { dataSource = getDataSourceFile(); } std::vector<std::tuple<char, carb::datasource::IDataSource*, 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_tuple(drive, dataSource, 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_tuple('/', dataSource, connection)); #endif return vec; } class AssetsManager { public: struct DataSourceMapping { carb::datasource::IDataSource* dataSource; carb::datasource::Connection* connection; }; AssetsManager(); ~AssetsManager(); void notifyShutdown(); bool getAssetAndDataSource(const char* assetUri, std::string& assetStr, DataSourceMapping& mapping); bool addDataSource(carb::datasource::IDataSource* dataSource, carb::datasource::Connection* connection, const char* prefix); bool removeDataSource(const char* prefix); protected: DataSourceMapping m_omniDataSourceMapping = { nullptr, nullptr }; std::unordered_map<std::string /* prefix */, DataSourceMapping> m_mapDataSources; std::vector<std::pair<carb::datasource::IDataSource*, carb::datasource::Connection*>> m_connections; }; inline AssetsManager::AssetsManager() { auto localConnections = getFilesystemConnections(); for (auto& connection : localConnections) { addDataSource(std::get<1>(connection), std::get<2>(connection), std::string(1, std::get<0>(connection)).c_str()); #if CARB_PLATFORM_WINDOWS addDataSource(std::get<1>(connection), std::get<2>(connection), std::string(1, std::tolower(std::get<0>(connection))).c_str()); #endif m_connections.push_back(std::make_pair(std::get<1>(connection), std::get<2>(connection))); } } inline AssetsManager::~AssetsManager() { if (m_omniDataSourceMapping.dataSource && m_omniDataSourceMapping.connection) { m_omniDataSourceMapping.dataSource->disconnect(m_omniDataSourceMapping.connection); } for (auto& connection : m_connections) { connection.first->disconnect(connection.second); } m_connections.clear(); } inline void AssetsManager::notifyShutdown() { m_omniDataSourceMapping = {}; m_connections.clear(); m_mapDataSources.clear(); } inline bool AssetsManager::addDataSource(carb::datasource::IDataSource* dataSource, carb::datasource::Connection* connection, const char* prefix) { CARB_ASSERT(dataSource && connection); auto it = m_mapDataSources.find(prefix); if (it != m_mapDataSources.end()) { if ((it->second.dataSource != dataSource) || (it->second.connection != connection)) { CARB_LOG_ERROR("A different DataSource is already registered for prefix '%s'", prefix); return false; } return true; } DataSourceMapping& mapping = m_mapDataSources[prefix]; mapping.dataSource = dataSource; mapping.connection = connection; CARB_LOG_INFO("Added dataSource connection for prefix '%s'", prefix); return true; } inline bool AssetsManager::removeDataSource(const char* prefix) { return m_mapDataSources.erase(prefix) != 0; } inline bool AssetsManager::getAssetAndDataSource(const char* assetUri, std::string& assetStr, DataSourceMapping& mapping) { if (assetUri == nullptr) { CARB_LOG_ERROR("assetUri is null"); CARB_ASSERT(assetUri); return false; } // Extract prefix from string /* The URI should be parsed in the more accurate way according to the URI Generic Syntax. URI = scheme:[//authority]path[?query][#fragment] */ const char* colonPos = std::strchr(assetUri, ':'); std::string prefix; #if CARB_PLATFORM_WINDOWS if (colonPos == nullptr) { CARB_LOG_ERROR("assetUri not a valid Uri: '%s'", assetUri); CARB_ASSERT(false); return false; } // Sanity check to ensure Uri contains a valid path after prefix:// if (std::strlen(colonPos) <= 3) { CARB_LOG_ERROR("Invalid asset Uri: '%s'", assetUri); CARB_ASSERT(false); return false; } prefix = std::string(assetUri, colonPos); #else // ":" on Linux implies an omniverse connection // clang-format off /* This comment is not exactly correct, see e.g.: ls /sys/bus/usb/devices/ 1-0:1.0 1-13:1.0 1-5:1.0 1-5:1.2 1-6:1.0 1-6:1.2 1-8:1.0 2-6 3-0:1.0 5-0:1.0 7-0:1.0 usb1 usb3 usb5 usb7 1-13 1-5 1-5:1.1 1-6 1-6:1.1 1-8 2-0:1.0 2-6:1.0 4-0:1.0 6-0:1.0 8-0:1.0 usb2 usb4 usb6 usb8 */ // clang-format on if (colonPos) { prefix = std::string(assetUri, colonPos); } // on Linux the local filesystem will not contain ":" to extract a prefix from else { colonPos = std::strchr(assetUri, '/'); if (colonPos == nullptr) { CARB_LOG_ERROR("assetUri not a valid Uri: '%s'", assetUri); CARB_ASSERT(false); return false; } prefix = "/"; } #endif const std::string assetUriStr = assetUri; bool isClientLibPath = isPathPrefixed(assetUriStr, "omniverse:", 10) || isPathPrefixed(assetUriStr, "http:", 5) || isPathPrefixed(assetUriStr, "https:", 6) || isPathPrefixed(assetUriStr, "file:", 5); if (isClientLibPath) { if (!m_omniDataSourceMapping.dataSource) { using namespace carb::datasource; IDataSource* dataSource = carb::getFramework()->acquireInterface<IDataSource>("carb.datasource-omniclient.plugin"); Connection* connection = connectAndWait({ "" }, dataSource); if (connection) { m_omniDataSourceMapping.dataSource = dataSource; m_omniDataSourceMapping.connection = connection; } else { CARB_LOG_ERROR("Failed to establish omniverse connection!"); } } mapping.dataSource = m_omniDataSourceMapping.dataSource; mapping.connection = m_omniDataSourceMapping.connection; assetStr = assetUri; return (mapping.dataSource != nullptr); } // Look for the prefix in our dataSource mappings auto it = m_mapDataSources.find(prefix); if (it == m_mapDataSources.end()) { CARB_LOG_ERROR("assetUri '%s' contains unknown dataSource prefix '%s'", assetUri, prefix.c_str()); return false; } else { mapping = it->second; } // Return the extracted string and dataSource mapping // TODO1 - HACKHACK for GTC, this is more pathing fun to handle the various ways paths can get to this code if (colonPos[0] == '.' && (colonPos[1] == '/' || colonPos[1] == '\\')) { // We're going to try and use this as-is } else if (colonPos[0] == '/' || colonPos[0] == '\\') { // We're just going to try and see what happens here } else { while ((colonPos[0] == ':' || colonPos[1] == ':' || colonPos[1] == '/' || colonPos[0] == '\\') && colonPos[0] != '0') { colonPos++; } } assetStr = std::string(colonPos); // TODO??? return true; } using FileSystemConnectionPair = std::pair<char, carb::datasource::Connection*>; inline std::vector<FileSystemConnectionPair> getFileSystemConnections() { carb::filesystem::IFileSystem* fs = carb::getFramework()->acquireInterface<carb::filesystem::IFileSystem>(); carb::datasource::IDataSource* dataSourceFile = getDataSourceFile(); std::vector<FileSystemConnectionPair> vec; if (fs == nullptr || dataSourceFile == 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() }, dataSourceFile); 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{ "/" }, dataSourceFile); 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; } } } }
11,323
C
31.354286
203
0.624305
omniverse-code/kit/include/omni/timeline/ITimeline.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/InterfaceUtils.h> #include <carb/events/IEvents.h> namespace omni { namespace timeline { class Timeline; using TimelinePtr = std::shared_ptr<Timeline>; /** * Defines a timeline controller. */ class Timeline { public: /** * Plays animation with current timeCodePerSecond. if not set session start and end timecode, will play from global start time to end time in stage. * * @startTimeCode start timeCode of session play, won't change the global StartTime. * @endTimeCode start timeCode of session play, won't change the global EndTime. * @looping true to enable session play looping, false to disable, won't change the global Looping. */ virtual void play(double startTimeCode = 0, double endTimeCode = 0, bool looping = true) = 0; /** * Pauses animation. */ virtual void pause() = 0; /** * Stops animation. */ virtual void stop() = 0; /** * Rewinds the timeline by one frame. */ virtual void rewindOneFrame() = 0; /** * Forwards the timeline by one frame. */ virtual void forwardOneFrame() = 0; /** * Checks if animation is playing. * * @return true if animation is playing. */ virtual bool isPlaying() const = 0; /** * Checks if animation is stopped, as opposed to paused. * * @return true if animation is stopped. */ virtual bool isStopped() const = 0; /** * Turns on/off auto update * * @autoUpdate autoUpdate true to enable auto update, false to disable. */ virtual void setAutoUpdate(bool autoUpdate) = 0; /** * Checks if timeline auto updates the frame * * @return true if timeline is auto updating */ virtual bool isAutoUpdating() const = 0; /** * Turns on/off prerolling status * * @autoUpdate prerolling true to indicate timeline is in preroll state */ virtual void setPrerolling(bool autoUpdate) = 0; /** * Checks if timeline is in prerolling mode * * @return true if timeline is in preroll */ virtual bool isPrerolling() const = 0; /** * Sets animation looping mode. * * @looping looping true to enable looping, false to disable. */ virtual void setLooping(bool looping) = 0; /** * Checks if animation is looping. * * @return true if animation is looping. */ virtual bool isLooping() const = 0; /** * Sets current time of animation in seconds. * * @param timeInSeconds Current time of animation in seconds. */ virtual void setCurrentTime(double timeInSeconds) = 0; /** * Gets current time of animation in seconds. * * @return Current time of animation in seconds. */ virtual double getCurrentTime() const = 0; /** * Gets the start time of animation in seconds. * * @return Begin time of animation in seconds. */ virtual double getStartTime() const = 0; /** * Sets the start time of animation in seconds. This will write into current opened stage. * * @param startTime Begin time of animation in seconds. */ virtual void setStartTime(double startTime) = 0; /** * Gets the end time of animation in seconds. * * @return End time of animation in seconds. */ virtual double getEndTime() const = 0; /** * Sets the begin time of animation in seconds. This will write into current opened stage. * * @param beginTime Begin time of animation in seconds. */ virtual void setEndTime(double endTime) = 0; /** * Gets timeCodePerSecond metadata from currently opened stage. This is equivalent to calling GetTimeCodesPerSecond * on UsdStage. * * @return timeCodePerSecond for current UsdStage. */ virtual double getTimeCodesPerSecond() const = 0; /** * Sets timeCodePerSecond metadata to currently opened stage. This is equivalent to calling SetTimeCodesPerSecond on * UsdStage. * * @param timeCodesPerSecond TimeCodePerSecond to set into current stage. */ virtual void setTimeCodesPerSecond(double timeCodesPerSecond) = 0; /** * Gets TimelineEventStream, emitting TimelineEventType. * * @return IEventStream* of TimelineEventStream. */ virtual carb::events::IEventStream* getTimelineEventStream() = 0; /** * Sets a tentative time of animation in seconds. * * @param timeInSeconds A tentative current time of animation in seconds. */ virtual void setTentativeTime(double timeInSeconds) = 0; /** * Clear the tentative time of animation so it becomes invalid. * */ virtual void clearTentativeTime() = 0; /** * Gets the tentative time of animation in seconds. * * @return The tentative time if it is valid, current time if invalid. */ virtual double getTentativeTime() const = 0; /** * Sets the tick count per frame, i.e. how many times update event is ticked per frame. * * @param ticksPerFrame The tick per frame count. */ virtual void setTicksPerFrame(unsigned int ticksPerFrame) = 0; /** * Gets the tick count per frame, i.e. how many times update event is ticked per frame. * * @return The tick per frame count. */ virtual unsigned int getTicksPerFrame() const = 0; /** * Gets the tick count per seconds, i.e. how many times update event is ticked per second. * * @return The tick per second count. */ virtual double getTicksPerSecond() const = 0; /** * Gets the current tick index, starting from zero. Always returns zero when ticks per frame is one. * * @return The current tick index. */ virtual unsigned int getCurrentTick() const = 0; /** * Turns fast mode on or off. Deprecated, same as setPlayEveryFrame. * * @param fastMode true to turn on fast mode, false to turn it off. */ virtual void setFastMode(bool fastMode) = 0; /** * Checks if fast mode is on or off. Deprecated, same as getPlayEveryFrame. * * @return true is fast mode is on. */ virtual bool getFastMode() const = 0; /** * Sets the target frame rate, which affects the derived FPS of the runloop in play mode. * Exact runloop FPS is usually not the same as this value, as it is always a multiple of getTimeCodesPerSecond. * * @param targetFrameRate The target frame rate. */ virtual void setTargetFramerate(float targetFrameRate) = 0; /** * Gets the target frame rate, which affects the derived FPS of the runloop in play mode. * Exact runloop FPS is usually not the same as this value, as it is always a multiple of getTimeCodesPerSecond. * * @return The target frame rate. */ virtual float getTargetFramerate() const = 0; // These new methods have no equivalent in the deprecated interface to encourage the use of the new interface /** * Converts time in seconds to time codes, w.r.t. the current timeCodesPerSecond setting of the timeline. * * @return The converted time code. */ virtual double timeToTimeCode(double timeInSecs) const = 0; /** * Converts time codes to seconds, w.r.t. the current timeCodesPerSecond setting of the timeline. * * @return The converted time in seconds. */ virtual double timeCodeToTime(double timeCodes) const = 0; /** * Applies all pending state changes and invokes all callbacks. * * This method is not thread-safe, it should be called only from the main thread. * */ virtual void commit() = 0; /** * Applies all pending state changes but does not invoke any callbacks. * * This method is thread-safe. * */ virtual void commitSilently() = 0; /** * Turns frame skipping off (true) or on (false). Same as setFastMode. * * @param playEveryFrame true to turn frame skipping off. */ virtual void setPlayEveryFrame(bool playEveryFrame) = 0; /** * Checks if the timeline sends updates every frame. Same as getFastMode. * * @return true if the timeline does not skip frames. */ virtual bool getPlayEveryFrame() const = 0; /** * Sets a director Timeline. * * When a director is set, the timeline mimics its behavior and any * state changing call from all other sources are ignored. * @param timeline The timeline object to be set as the director. * Pass nullptr to clear the current director. */ virtual void setDirector(TimelinePtr timeline) = 0; /** * Returns the current director Timeline. * * @return The director timeline or nullptr if none is set. */ virtual TimelinePtr getDirector() const = 0; /** * Sets the zoom range, i.e. the playback interval. * * Values are truncated to the [getStartTime(), getEndTime()] interval, * which is also the default range. * A minimum of one frame long range is enforced. * * @startTime: start time of zoom in seconds. Must be less or equal than endTime. * @endTime: End time of zoom in seconds. Must be greater or equal than endTime. */ virtual void setZoomRange(double startTime, double endTime) = 0; /** * Clears the zoom state, i.e. sets the zoom range to [getStartTime(), getEndTime()]. */ virtual void clearZoom() = 0; /** * Returns whether a zoom is set, i.e. the zoom range is not the entire * [getStartTime(), getEndTime()] interval. * * @return true if getStartTime() < getZoomStartTime() or getZoomEndTime() < getEndTime() * (note that "<=" always holds). * false otherwise. */ virtual bool isZoomed() const = 0; /** * Gets the start time of zoomed animation in seconds. * * @return: The start time of zoomed animation in seconds. * When no zoom is set, this function returns getStartTime(). */ virtual double getZoomStartTime() const = 0; /** * Gets the end time of zoomed animation in seconds. * * @return: The end time of zoomed animation in seconds. * When no zoom is set, this function returns getEndTime(). */ virtual double getZoomEndTime() const = 0; }; /** * Defines a timeline controller factory. For compatibility reasons it also defines a timeline controller. */ class ITimeline { public: CARB_PLUGIN_INTERFACE("omni::timeline::ITimeline", 1, 0); //---------------------- // Deprecated interface //---------------------- /** * Deprecated Plays animation with current timeCodePerSecond. if not set session start and end timecode, will play from global start time to end time in stage. * * @startTimeCode start timeCode of session play, won't change the global StartTime. * @endTimeCode start timeCode of session play, won't change the global EndTime. * @looping true to enable session play looping, false to disable, won't change the global Looping. */ virtual void play(double startTimeCode = 0, double endTimeCode = 0, bool looping = true) = 0; /** * Deprecated. Pauses animation. */ virtual void pause() = 0; /** * Deprecated. Stops animation. */ virtual void stop() = 0; /** * Deprecated. Rewinds the timeline by one frame. */ virtual void rewindOneFrame() = 0; /** * Deprecated. Forwards the timeline by one frame. */ virtual void forwardOneFrame() = 0; /** * Deprecated. Checks if animation is playing. * * @return true if animation is playing. */ virtual bool isPlaying() const = 0; /** * Deprecated. Checks if animation is stopped, as opposed to paused. * * @return true if animation is stopped. */ virtual bool isStopped() const = 0; /** * Deprecated. Turns on/off auto update * * @autoUpdate autoUpdate true to enable auto update, false to disable. */ virtual void setAutoUpdate(bool autoUpdate) = 0; /** * Deprecated. Checks if timeline auto updates the frame * * @return true if timeline is auto updating */ virtual bool isAutoUpdating() const = 0; /** * Deprecated. Turns on/off prerolling status * * @autoUpdate prerolling true to indicate timeline is in preroll state */ virtual void setPrerolling(bool autoUpdate) = 0; /** * Deprecated. Checks if timeline is in prerolling mode * * @return true if timeline is in preroll */ virtual bool isPrerolling() const = 0; /** * Deprecated. Sets animation looping mode. * * @looping looping true to enable looping, false to disable. */ virtual void setLooping(bool looping) = 0; /** * Deprecated. Checks if animation is looping. * * @return true if animation is looping. */ virtual bool isLooping() const = 0; /** * Deprecated. Sets current time of animation in seconds. * * @param timeInSeconds Current time of animation in seconds. */ virtual void setCurrentTime(double timeInSeconds) = 0; /** * Deprecated. Gets current time of animation in seconds. * * @return Current time of animation in seconds. */ virtual double getCurrentTime() const = 0; /** * Deprecated. Gets the start time of animation in seconds. * * @return Begin time of animation in seconds. */ virtual double getStartTime() const = 0; /** * Deprecated. Sets the start time of animation in seconds. This will write into current opened stage. * * @param startTime Begin time of animation in seconds. */ virtual void setStartTime(double startTime) = 0; /** * Deprecated. Gets the end time of animation in seconds. * * @return End time of animation in seconds. */ virtual double getEndTime() const = 0; /** * Deprecated. Sets the begin time of animation in seconds. This will write into current opened stage. * * @param beginTime Begin time of animation in seconds. */ virtual void setEndTime(double endTime) = 0; /** * Deprecated. Gets timeCodePerSecond metadata from currently opened stage. This is equivalent to calling GetTimeCodesPerSecond * on UsdStage. * * @return timeCodePerSecond for current UsdStage. */ virtual double getTimeCodesPerSecond() const = 0; /** * Deprecated. Sets timeCodePerSecond metadata to currently opened stage. This is equivalent to calling SetTimeCodesPerSecond on * UsdStage. * * @param timeCodesPerSecond TimeCodePerSecond to set into current stage. */ virtual void setTimeCodesPerSecond(double timeCodesPerSecond) = 0; /** * Deprecated. Gets TimelineEventStream, emitting TimelineEventType. * * @return IEventStream* of TimelineEventStream. */ virtual carb::events::IEventStream* getTimelineEventStream() = 0; /** * Deprecated. Sets a tentative time of animation in seconds. * * @param timeInSeconds A tentative current time of animation in seconds. */ virtual void setTentativeTime(double timeInSeconds) = 0; /** * Deprecated. Clear the tentative time of animation so it becomes invalid. * */ virtual void clearTentativeTime() = 0; /** * Deprecated. Gets the tentative time of animation in seconds. * * @return The tentative time if it is valid, current time if invalid. */ virtual double getTentativeTime() const = 0; /** * Deprecated. Sets the tick count per frame, i.e. how many times update event is ticked per frame. * * @param ticksPerFrame The tick per frame count. */ virtual void setTicksPerFrame(unsigned int ticksPerFrame) = 0; /** * Deprecated. Gets the tick count per frame, i.e. how many times update event is ticked per frame. * * @return The tick per frame count. */ virtual unsigned int getTicksPerFrame() const = 0; /** * Deprecated. Gets the tick count per seconds, i.e. how many times update event is ticked per second. * * @return The tick per second count. */ virtual double getTicksPerSecond() const = 0; /** * Deprecated. Gets the current tick index, starting from zero. Always returns zero when ticks per frame is one. * * @return The current tick index. */ virtual unsigned int getCurrentTick() const = 0; /** * Deprecated. Turns fast mode on or off. * * @param fastMode true to turn on fast mode, false to turn it off. */ virtual void setFastMode(bool fastMode) = 0; /** * Deprecated. Checks if fast mode is on or off. * * @return true is fast mode is on. */ virtual bool getFastMode() const = 0; /** * Deprecated. Sets the target frame rate, which affects the derived FPS of the runloop in play mode. * Exact runloop FPS is usually not the same as this value, as it is always a multiple of getTimeCodesPerSecond. * * @param targetFrameRate The target frame rate. */ virtual void setTargetFramerate(float targetFrameRate) = 0; /** * Deprecated. Gets the target frame rate, which affects the derived FPS of the runloop in play mode. * Exact runloop FPS is usually not the same as this value, as it is always a multiple of getTimeCodesPerSecond. * * @return The target frame rate. */ virtual float getTargetFramerate() const = 0; //--------------- // New interface //--------------- /** * Gets timeline with the given name. Creates a new one if it is not exist. * * @param name Name of the timeline. * * @return The timeline */ virtual TimelinePtr getTimeline(const char* name = nullptr) = 0; /** * Destroys the timeline with the given name if nothing references it. Does not release the default timeline. * * @param name Name of the timeline. * * @return True if a timeline was deleted, false otherwise. The latter happens when the timeline does not exist, it is in use, or it is the default timeline. */ virtual bool destroyTimeline(const char* name) = 0; }; /** * Gets cached ITimeline interface. * * @return Cached ITimeline interface. */ inline TimelinePtr getTimeline(const char* name = nullptr) { auto manager = carb::getCachedInterface<omni::timeline::ITimeline>(); return manager == nullptr ? nullptr : manager->getTimeline(name); } } }
19,310
C
29.032659
161
0.641792
omniverse-code/kit/include/omni/timeline/TimelineTypes.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/InterfaceUtils.h> namespace omni { namespace timeline { /** * Defines timeline event types to be used by TimelineEventStream. */ enum class TimelineEventType { ePlay, ///! Timeline started to play. ePause, ///! Timeline paused eStop, ///! Timeline stopped eCurrentTimeChanged, ///! Current time is changed by user (isn't called when timeline ticked). eCurrentTimeTickedPermanent, ///! Current time is ticked by update function (called per subframe=tick even if not playing). eCurrentTimeTicked, ///! Current time is ticked by update function (called per subframe=tick when playing). eLoopModeChanged, ///! Looping mode changed. eStartTimeChanged, ///! Start time changed. eEndTimeChanged, ///! End time changed. eTimeCodesPerSecondChanged, ///! Timecode per second (animation framerate) changed. eAutoUpdateChanged, ///! Auto update changed ePrerollingChanged, ///! Prerolling changed eTentativeTimeChanged, ///! Tentative current time is changed by user (isn't called when timeline ticked). eTicksPerFrameChanged, ///! Ticks per frame count changed eFastModeChanged, ///! Fast mode changed. Same as eFastModeChanged, kept for backward compatibility. ePlayEveryFrameChanged = eFastModeChanged, ///! Play every frame (no frame skipping) changed eTargetFramerateChanged, ///! Target runloop frame rate changed eDirectorChanged, ///! Timeline is driven by a new director timeline eZoomChanged ///! Zoom range changed }; } }
1,994
C
41.446808
127
0.74674
omniverse-code/kit/include/omni/structuredlog/BinarySerializer.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 Module for serializing data into the structured logging queue. */ #pragma once #include "../structuredlog/StringView.h" #include "../../carb/extras/StringSafe.h" #include "../../carb/Defines.h" #include <stdint.h> namespace omni { namespace structuredlog { /** A helper class to calculate the required size of a binary blob. * To use this, just track all of the data that you want to insert into your * binary blob. */ class BinaryBlobSizeCalculator { public: /** The version of binary blob ABI * Headers that use these binary blobs should static assert on its version. * Do not modify the layout of the binary blob without incrementing this. */ static constexpr uint32_t kVersion = 0; /** Retrieve the tracked blob size. * @returns The memory size that is needed to store this blob. */ size_t getSize() { return m_counter; } /** Track a primitive type. * @param[in] v The value to track. * The actual value doesn't matter; only the type matters. */ template <typename T> void track(T v) { CARB_UNUSED(v); static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); m_counter = alignOffset<T>(m_counter); m_counter += sizeof(T); } /** Track an array type. * @param[in] v The array of values to track. * This may also be a string. * @param[in] len The number of elements in array @p v. * If this is a string, this length *includes* the null terminator. */ template <typename T> void track(T* v, uint16_t len) { CARB_UNUSED(v); static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); if (len > 0) { m_counter = alignOffset<T>(m_counter); m_counter += sizeof(T) * len; } } /** Track a @ref StringView. * @param[in] v The string view to track. */ void track(const StringView& v) { m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); m_counter += v.length() + 1; } /** Track a @ref StringView. * @param[in] v The string view to track. */ void track(StringView& v) { track(static_cast<const StringView&>(v)); } /** Track an array of strings into the buffer with pre-calculated lengths * @param[in] v The array of strings to track. * This may not be nullptr. * The elements of this array may be nullptr; each element * of this must be a null terminated string otherwise. * @param[in] stringLengths The length of each string in @p v. * These length must include the null terminator of the string. * This may not be nullptr. * @param[in] len The number of elements in array @p v and array @p stringLengths. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. * * @note This overload exists to avoid having to perform a strlen() on each * string in the array twice (once when calculating the buffer size * and once when writing the buffer). */ void track(const char* const* v, const uint16_t* stringLengths, uint16_t len) { CARB_UNUSED(v); m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); for (uint16_t i = 0; i < len; i++) { m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); m_counter += stringLengths[i]; } } /** Track an array of strings type. * @param[in] v The array of strings to track. * This may not be nullptr. * The elements of this array may be nullptr; each element * of this must be a null terminated string otherwise. * @param[in] len The number of elements in array @p v. */ void track(const char* const* v, uint16_t len) { m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); for (uint16_t i = 0; i < len; i++) { m_counter = alignOffset<uint16_t>(m_counter); m_counter += sizeof(uint16_t); if (v[i] != nullptr) { size_t size = strlen(v[i]) + 1; m_counter += CARB_MIN(size_t(UINT16_MAX), size); } } } /** Track an array of fixed size. * @param[in] v The array of values to track. * This may also be a string. * @param[in] len The fixed length of this data array as specified by * the data schema. This can be larger than @p v. */ template <typename T> void trackFixed(T* v, uint16_t len) { CARB_UNUSED(v); static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); m_counter = alignOffset<T>(m_counter); m_counter += sizeof(T) * len; } /** Round an offset up to be aligned for a given type. * @param[in] offset The offset to align. * @returns @p offset rounded up to be aligned for the specified type. */ template <typename T> static size_t alignOffset(size_t offset) { size_t misalign = offset & (sizeof(T) - 1); if (misalign != 0) offset += sizeof(T) - misalign; return offset; } private: /** The length of the blob that's been tracked so far. */ size_t m_counter = 0; }; /** @{ * Constants to make the template specialization more readable. */ static constexpr bool kBlobWriterValidate = true; static constexpr bool kBlobWriterNoValidate = false; /** @} */ /** Anonymous namespace for a helper function */ namespace { void ignoreBlobWriterValidationError(const char* s) noexcept { CARB_UNUSED(s); } } // namespace /** The prototype of the function to call when a validation error occurs. * @param[in] message The error message explaining what went wrong. */ using OnBlobWriterValidationErrorFunc = void (*)(const char* message); /** A class to build a binary blob. * The binary blob only has internal markers for variable length fields; to * decode the binary blob, you will need some sort of external schema or fixed * layout to decode the binary blob. * * @param validate If this parameter is true, then the length of the blob will * be tracked while writing the blob and attempting to write * past the end of the buffer will cause methods to fail. * This is needed for the tests. * * @param onValidationError This is a callback that gets executed when a validation * error is triggered, so logging can be called. * Logging cannot be called directly from this class * because it is used inside the logging system. */ template <bool validate = false, OnBlobWriterValidationErrorFunc onValidationError = ignoreBlobWriterValidationError> class BlobWriter { public: /** The version of binary blob ABI * Headers that use these binary blobs should static assert on its version. * Do not modify the layout of the binary blob without incrementing this. */ static constexpr uint32_t kVersion = 0; /** Constructor. * @param[in] buffer The buffer to write into. * This buffer must be aligned to sizeof(void*). * @param[in] bytes The length of @p buffer. */ BlobWriter(void* buffer, size_t bytes) { CARB_ASSERT(buffer != nullptr); CARB_ASSERT((uintptr_t(buffer) & (sizeof(void*) - 1)) == 0); m_buffer = static_cast<uint8_t*>(buffer); m_bufferLen = bytes; } /** Copy a primitive type element into the buffer. * @param[in] v The value to copy into the buffer. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. */ template <typename T> bool copy(T v) { static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); alignBuffer<T>(); if (validate && m_bufferLen < m_written + sizeof(v)) { outOfMemoryErrorMessage(sizeof(v)); return false; } reinterpret_cast<T*>(m_buffer + m_written)[0] = v; m_written += sizeof(v); return true; } /** Copy an array of strings into the buffer with pre-calculated lengths * @param[in] v The array of strings to write into the buffer. * This may be nullptr if @p len is 0. * The elements of this array may be nullptr; each element * of this must be a null terminated string otherwise. * @param[in] stringLengths The length of each string in @p v. * These length must include the null terminator of the string. * This may be nullptr if @p len is 0. * @param[in] len The number of elements in array @p v and array @p stringLengths. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. * * @note This overload exists to avoid having to perform a strlen() on each * string in the array twice (once when calculating the buffer size * and once when writing the buffer). */ bool copy(const char* const* v, const uint16_t* stringLengths, uint16_t len) { CARB_ASSERT(v != nullptr || len == 0); CARB_ASSERT(stringLengths != nullptr || len == 0); alignBuffer<decltype(len)>(); if (validate && m_bufferLen < m_written + sizeof(len)) { outOfMemoryErrorMessage(sizeof(len)); return false; } reinterpret_cast<decltype(len)*>(m_buffer + m_written)[0] = len; m_written += sizeof(len); for (uint16_t i = 0; i < len; i++) { alignBuffer<decltype(stringLengths[i])>(); if (validate && m_bufferLen < m_written + sizeof(stringLengths[i]) + stringLengths[i]) { outOfMemoryErrorMessage(sizeof(stringLengths[i]) + stringLengths[i]); return false; } reinterpret_cast<uint16_t*>(m_buffer + m_written)[0] = stringLengths[i]; m_written += sizeof(stringLengths[i]); memcpy(m_buffer + m_written, v[i], stringLengths[i]); m_written += stringLengths[i]; } return true; } /** Copy an array of strings into the buffer. * @param[in] v The array of strings to write into the buffer. * This may be nullptr if @p len is 0. * The elements of this array may be nullptr; each element * of this must be a null terminated string otherwise. * @param[in] len The number of elements in array @p v. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. */ bool copy(const char* const* v, uint16_t len) { CARB_ASSERT(v != nullptr || len == 0); alignBuffer<decltype(len)>(); if (validate && m_bufferLen < m_written + sizeof(len)) { outOfMemoryErrorMessage(sizeof(len)); return false; } reinterpret_cast<decltype(len)*>(m_buffer + m_written)[0] = len; m_written += sizeof(len); for (uint16_t i = 0; i < len; i++) { size_t size; uint16_t s = 0; if (v[i] == nullptr) { alignBuffer<uint16_t>(); if (validate && m_bufferLen < m_written + sizeof(uint16_t)) { outOfMemoryErrorMessage(sizeof(uint16_t)); return false; } reinterpret_cast<uint16_t*>(m_buffer + m_written)[0] = 0; m_written += sizeof(uint16_t); continue; } // this might silently truncate if a really long string is passed size = strlen(v[i]) + 1; s = uint16_t(CARB_MIN(size_t(UINT16_MAX), size)); alignBuffer<decltype(s)>(); if (validate && m_bufferLen < m_written + sizeof(s) + s) { outOfMemoryErrorMessage(sizeof(s) + s); return false; } reinterpret_cast<decltype(s)*>(m_buffer + m_written)[0] = s; m_written += sizeof(s); memcpy(m_buffer + m_written, v[i], s); m_written += s; } return true; } /** Copy an array of data into the buffer. * @param[in] v The array of values to copy. * This may also be a string. * This may be nullptr if @p len is 0. * @param[in] len The number of elements in array @p v. * If this is a string, this length *includes* the null terminator. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. */ template <typename T> bool copy(T* v, uint16_t len) { static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); CARB_ASSERT(v != nullptr || len == 0); alignBuffer<decltype(len)>(); if (validate && m_bufferLen < m_written + sizeof(len)) { outOfMemoryErrorMessage(sizeof(len)); return false; } reinterpret_cast<decltype(len)*>(m_buffer + m_written)[0] = len; m_written += sizeof(len); if (len == 0) return true; alignBuffer<T>(); if (validate && m_bufferLen < m_written + sizeof(T) * len) { outOfMemoryErrorMessage(sizeof(T) * len); return false; } memcpy(m_buffer + m_written, v, sizeof(T) * len); m_written += sizeof(T) * len; return true; } /** Copy a @ref StringView into the blob. * @param[in] v The @ref StringView to copy in. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. */ bool copy(const StringView& v) { uint16_t len = uint16_t(CARB_MIN(size_t(UINT16_MAX), v.length() + 1)); alignBuffer<decltype(len)>(); if (validate && m_bufferLen < m_written + sizeof(len)) { outOfMemoryErrorMessage(sizeof(len)); return false; } reinterpret_cast<decltype(len)*>(m_buffer + m_written)[0] = len; m_written += sizeof(len); if (len == 0) return true; if (validate && m_bufferLen < m_written + len) { outOfMemoryErrorMessage(len); return false; } // the string view may not be null terminated, so we need to write the // terminator separately if (len > 1) { memcpy(m_buffer + m_written, v.data(), len - 1); m_written += len - 1; } m_buffer[m_written++] = '\0'; return true; } /** Copy a @ref StringView into the buffer. * @param[in] v The string view to copy. */ bool copy(StringView& v) { return copy(static_cast<const StringView&>(v)); } /** Copy an array of data into the buffer. * @param[in] v The array of values to copy. * This may also be a string. * This may not be nullptr because that would imply * @p fixedLen is 0, which is not a valid use case. * @param[in] actualLen The length of array @p v. * This must be less than or equal to @p fixedLen. * @param[in] fixedLen The fixed length as specified by your data schema. * If this is greater than @p actualLen, then the * excess size at the end of the array will be zeroed. * @returns `true` if the value was successfully written. * @returns `false` if the blob ran out of buffer space. */ template <typename T> bool copy(T* v, uint16_t actualLen, uint16_t fixedLen) { const size_t total = sizeof(T) * fixedLen; const size_t written = sizeof(T) * actualLen; static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); CARB_ASSERT(v != nullptr); CARB_ASSERT(fixedLen >= actualLen); alignBuffer<T>(); if (validate && m_bufferLen < m_written + total) { outOfMemoryErrorMessage(total); return false; } // write out the actual values memcpy(m_buffer + m_written, v, written); // zero the padding at the end memset(m_buffer + m_written + written, 0, total - written); m_written += total; return true; } /** Align the buffer for a given type. * @remarks This will advance the buffer so that the next write is aligned * for the specified type. */ template <typename T> void alignBuffer() { size_t next = BinaryBlobSizeCalculator::alignOffset<T>(m_written); // there's no strict requirement for the padding to be 0 if (validate) memset(m_buffer + m_written, 0, next - m_written); m_written = next; } private: void outOfMemoryErrorMessage(size_t size) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "hit end of buffer while writing" " (tried to write %zu bytes, with %zd available)", size, m_bufferLen - m_written); onValidationError(tmp); } /** The buffer being written. */ uint8_t* m_buffer = nullptr; /** The length of @p m_buffer. */ size_t m_bufferLen = 0; /** The amount that has been written to @p m_buffer. */ size_t m_written = 0; }; /** @{ * Constants to make the template specialization more readable. */ static constexpr bool kBlobReaderValidate = true; static constexpr bool kBlobReaderNoValidate = false; /** @} */ /** A class to read binary blobs produced by the @ref BlobWriter. * You'll need some sort of external schema or fixed layout to be able to read * the blob. * * @param validate If this parameter is true, then the read position will * be tracked while reading the blob and attempting to read * past the end of the buffer will cause methods to fail. * Note that a message will not be logged because this class * is used in the log system. * This is needed for the tests. */ template <bool validate = false, OnBlobWriterValidationErrorFunc onValidationError = ignoreBlobWriterValidationError> class BlobReader { public: /** The version of binary blob ABI that this reader was built to read. */ static constexpr uint32_t kVersion = 0; /** Constructor. * @param[in] blob The buffer to read from. * @param[in] blobSize The length of @p buffer. */ BlobReader(const void* blob, size_t blobSize) { CARB_ASSERT(blob != nullptr || blobSize == 0); m_buffer = static_cast<const uint8_t*>(blob); m_bufferLen = blobSize; } /** read a primitive type element out of the buffer. * @param[out] out The value will be written to this. * This may not be nullptr. * @returns `true` if the value was successfully read. * @returns `false` if the end of the buffer was reached. */ template <typename T> bool read(T* out) { static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); CARB_ASSERT(out != nullptr); alignBuffer<T>(); if (validate && m_bufferLen < m_read + sizeof(T)) { outOfMemoryErrorMessage(sizeof(T)); return false; } *out = reinterpret_cast<const T*>(m_buffer + m_read)[0]; m_read += sizeof(T); return true; } /** Read an array of strings out of the buffer. * @param[out] out Receives the array of strings from the blob if @p maxLen is not 0. * This may be nullptr if @p maxLen is 0. * Note that the strings pointed to will point into the * data blob that's being read from. * @param[out] outLen Receives the length of the output array. * This may not be nullptr. * @param[in] maxLen The maximum length that can be read into @p out in this call. * If this is set to 0, then the array length with be * read into @p outLen and the buffer pointer will not * increment to point at the next member, so that an * array can be allocated and read in the next call to * this function. * An exception to this is the case where @p outLen * is set to 0; the buffer pointer will be incremented * to point at the next member in this case. * * @returns `true` if the value was successfully read. * @returns `false` if the end of the buffer was reached. */ bool read(const char** out, uint16_t* outLen, uint16_t maxLen) { uint16_t len = 0; alignBuffer<decltype(len)>(); if (validate && m_bufferLen < m_read + sizeof(uint16_t)) { outOfMemoryErrorMessage(sizeof(uint16_t)); return false; } len = reinterpret_cast<const decltype(len)*>(m_buffer + m_read)[0]; *outLen = len; if (maxLen == 0 && len != 0) return true; m_read += sizeof(len); if (validate && len > maxLen) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "buffer is too small to read the data" " (length = %" PRIu16 ", needed = %" PRIu16 ")", maxLen, len); onValidationError(tmp); } for (uint16_t i = 0; i < len; i++) { uint16_t s = 0; alignBuffer<decltype(s)>(); if (validate && m_bufferLen < m_read + sizeof(uint16_t)) { outOfMemoryErrorMessage(sizeof(uint16_t)); return false; } s = reinterpret_cast<const decltype(s)*>(m_buffer + m_read)[0]; m_read += sizeof(len); if (validate && m_bufferLen < m_read + s) { outOfMemoryErrorMessage(s); return false; } if (s == 0) { out[i] = nullptr; continue; } out[i] = reinterpret_cast<const char*>(m_buffer + m_read); m_read += s; } return true; } /** Read a string out of the buffer. * @param[out] out Receives the array from the binary blob. * This will be pointing to data from within the blob. * This may not be nullptr. * @param[out] outLen Receives the length of the array that was read. * This includes the null terminator if this was as string. * This may not be nullptr. * * @returns `true` if the value was successfully read. * @returns `false` if the end of the buffer was reached. */ template <typename T> bool read(const T** out, uint16_t* outLen) { CARB_ASSERT(out != nullptr); CARB_ASSERT(outLen != nullptr); alignBuffer<uint16_t>(); if (validate && m_bufferLen < m_read + sizeof(uint16_t)) { outOfMemoryErrorMessage(sizeof(uint16_t)); return false; } *outLen = reinterpret_cast<const uint16_t*>(m_buffer + m_read)[0]; m_read += sizeof(*outLen); if (*outLen == 0) { *out = nullptr; return true; } alignBuffer<T>(); if (validate && m_bufferLen < m_read + *outLen) { outOfMemoryErrorMessage(*outLen); return false; } *out = reinterpret_cast<const T*>(m_buffer + m_read); m_read += *outLen * sizeof(T); return true; } /** Read a fixed length array out of the buffer. * @param[out] out Receives the array from the binary blob. * This will be pointing to data from within the blob. * This may not be nullptr. * @param[out] fixedLen The fixed length of the array/string. * This should not be 0. * * @returns `true` if the value was successfully read. * @returns `false` if the end of the buffer was reached. */ template <typename T> bool read(const T** out, uint16_t fixedLen) { CARB_ASSERT(out != nullptr); alignBuffer<T>(); if (validate && m_bufferLen < m_read + fixedLen) { outOfMemoryErrorMessage(fixedLen); return false; } *out = reinterpret_cast<const T*>(m_buffer + m_read); m_read += fixedLen * sizeof(T); return true; } /** Align the buffer for a given type. * @remarks This will advance the buffer so that the next write is aligned * for the specified type. */ template <typename T> void alignBuffer() { m_read = BinaryBlobSizeCalculator::alignOffset<T>(m_read); } protected: /** Send an error message to the onValidationError callback when the end of the buffer has been reached. * @param[in] size The size that was requested that would have extended past the end of the buffer. */ void outOfMemoryErrorMessage(size_t size) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "hit end of buffer while reading" " (tried to read %zu bytes, with %zd available)", size, m_bufferLen - m_read); onValidationError(tmp); } /** The buffer being written. */ const uint8_t* m_buffer = nullptr; /** The length of @p m_buffer. */ size_t m_bufferLen = 0; /** The amount that has been read from @p m_buffer. */ size_t m_read = 0; }; } // namespace structuredlog } // namespace omni
27,854
C
34.393901
117
0.555827
omniverse-code/kit/include/omni/structuredlog/Telemetry.h
// Copyright (c) 2021-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 uploading telemetry events. */ #pragma once #include "IStructuredLogSettings.h" #include "../extras/UniqueApp.h" #include "../../carb/launcher/ILauncher.h" #include "../../carb/launcher/LauncherUtils.h" #include "../../carb/settings/ISettings.h" namespace omni { namespace telemetry { /** Telemetry transmitter app settings. These control the behavior of the transmitter * app. They can be specified either on the command line (prefixed by '--'), or in * the transmitter app's config file (`omni.telemetry.transmitter.toml`). * @{ */ /** This setting will cause the transmitter to stay alive until it is manually killed. * This setting is mostly meant for developer use, but could also be used in server * or farm environments where Omniverse apps are frequently run and exited. This will * bypass the normal exit condition check of testing whether all apps that tried to * launch the transmitter have exited on their own. When this option is disabled, * once all apps have exited, the transmitter will exit on its own. When this option * is enabled, this exit condition will simply be ignored. This defaults to `false`. * * Note that if no schemas are available for the transmitter to process, this option * is ignored. In that case, the transmitter will simply exit immediately after * trying to download the schemas package. */ constexpr const char* const kStayAliveSetting = "/telemetry/stayAlive"; /** The time, in seconds, that the transmitter will wait between polling the log files. * This determines how reactive the transmitter will be to checking for new messages and * how much work it potentially does in the background. This defaults to 60 seconds. */ constexpr const char* const kPollTimeSetting = "/telemetry/pollTime"; /** The mode to run the transmitter in. The value of this setting can be either "dev" or "test". * By default, the transmitter will run in "production" mode. In "dev" mode, the transmitter * will use the default development schemas URL. In "test" mode, the default staging endpoint * URL will be used. The "test" mode is only supported in debug builds. If "test" is used * in a release build, it will be ignored and the production endpoint will be used instead. * * Note that if the schemas package for the requested mode is empty, the transmitter will * just immediately exit since there is nothing for it to process. */ constexpr const char* const kTelemetryModeSetting = "/telemetry/mode"; /** Sets the run environment that determines which flavor of Kit is currently being run. * This should be either `Individual` (for OVI), `Cloud` (for OVC), or `Enterprise` (for * OVE). This helps to choose the appropriate schema ID when automatically adding the * `schemaid` field to messages being sent to an open endpoint. */ constexpr const char* const kTelemetryRunEnvironmentSetting = "/telemetry/runEnvironment"; /** This allows the transmitter to run as the root user on Linux. * The root user is disabled by default because it could make some of the transmitter's * files non-writable by regular users. By default, if the transmitter is launched as * the root user or with `sudo`, it will report an error and exit immediately. If it is * intended to launch as the root or super user, this option must be explicitly specified * so that there is a clear intention from the user. The default value is `false`. This * setting is ignored on Windows. */ constexpr const char* const kAllowRootSetting = "/telemetry/allowRoot"; /** The list of restricted regions for the transmitter. If the transmitter is launched * in one of these regions, it will exit immediately on startup. The entries in this * list are either the country names or the two-letter ISO 3166-1 alpha-2 country code. * Entries in the list are separated by commas (','), bars ('|'), slash ('/'), or whitespace. * Whitespace should not be used when specifying the option on the command line. It is * typically best to use the two-letter country codes in the list since they are standardized. * This defaults to an empty list. */ constexpr const char* const kRestrictedRegionsSetting = "/telemetry/restrictedRegions"; /** The assumption of success or failure that should be assumed if the country name and code * could not be retrieved. Set this to `true` if the transmitter should be allowed to run * if the country code or name could not be retrieved. Set this to `false` if the transmitter * should not be allowed to run in that error case. This defaults to `true`. */ constexpr const char* const kRestrictedRegionAssumptionSetting = "/telemetry/restrictedRegionAssumption"; /** The log file path that will be used for any transmitter processes launched. * If it is not specified, the log path from @ref IStructuredLogSettings::getLogOutputPath() * will be used; If @ref IStructuredLogSettings could not be acquired for some reason, * the CWD will be used. */ constexpr const char* const kLogFileSetting = "/telemetry/log/file"; /** The log level that will be used for any transmitter process launched. * If this is not specified, the parent process's log level will be used. */ constexpr const char* const kLogLevelSetting = "/telemetry/log/level"; /** This allows the telemetry transmitter to be launched in an 'open endpoint' mode. This will * point it to one of the Kratos open endpoint URLs, disable authentication, and set the event * processing protocol to @ref omni::telemetry::EndpointProtocol::eDefaultWithList. This mode * may only be used when the `/telemetry/extraFields/schemaid` value is also properly setup * and the rest of the app has been properly configured for use with an open endpoint. Without * a proper configuration, all events will be rejected from the open endpoint. */ constexpr const char* const kUseOpenEndpointSetting = "/telemetry/useOpenEndpoint"; /** This allows only a subset of the extra fields specified under `/structuredLog/extraFields/` * to be passed on to the transmitter when it is launched. By default all extra fields specified * under `/structuredLog/extraFields/` will be passed on to the transmitter to use, but will be * ignored by the transmitter. If a subset of those extra fields should be automatically added * to each message by the transmitter, they can be added to this setting's value in a single * comma separated list in a string. Any whitespace in the string will be ignored. If this * setting is undefined or contains an empty string, no extra fields will be automatically added * to each message. */ constexpr const char* const kExtraFieldsToAddSetting = "/telemetry/extraFieldsToAdd"; /** This controls whether the extra fields specified in @ref kExtraFieldsToAddSetting will be * replaced in each message if one or more of them already exists or if any fields that already * exist in the event will just be ignored. When set to `true`, the listed extra fields with * their given values will always overwrite any existing fields with the same name. When set * to `false`, if a field with the same name as one of the extra fields already exists in a * given event message, it will not be replaced. The default behavior is to never overwrite * existing fields (ie: set to `false`). */ constexpr const char* const kReplaceExtraFieldsSetting = "/telemetry/replaceExtraFields"; /** This settings key holds an object or an array of objects. * Each object is one transmitter instance. * In the settings JSON, this would look something like: * @code{JSON} * { * "telemetry": { * "transmitter": [ * { * "endpoint": "https://telemetry.not-a-real-url.nvidia.com", * }, * { * "endpoint": "https://metrics.also-not-a-real-url.nvidia.com" * } * ] * } * } * @endcode * You can also specify this on command line like this. * You must ensure that all entries under `/telemetry/transmitter` are contiguous numeric indices * otherwise `/telemetry/transmitter` will be interpreted as a single object. * @code{bash} * "--/telemetry/transmitter/0/endpoint=https://omniverse.kratos-telemetry.nvidia.com" \ * "--/telemetry/transmitter/1/endpoint=https://gpuwa.nvidia.com/dataflow/sandbox-jfeather-omniverse/posting" * @endcode * A transmitter instance sends data to a telemetry endpoint with a specific * configuration. * Each instance can be configured to use a different protocol and a different * set of schema URLs, so data sent to each endpoint can be substantially different. * To send data to multiple endpoints, you set up an array of objects under * this settings key. * Note that */ constexpr const char* const kTransmitterSetting = "/telemetry/transmitter"; /** This setting is an optional member of the @ref kTransmitterSetting object. * If this is set to `true`, the transmitter will ignore the `seek` field in the header * and start parsing from the start of each log again. This is only intended to be used * for testing purposes. This defaults to `false`. */ constexpr const char* const kResendEventsSettingLeaf = "resendEvents"; /** This setting is an optional member of the @ref kTransmitterSetting object. * The maximum number of bytes to send in one transmission to the server. Event messages * will be sent in batches as large as possible up to this size. If more message data is * available than this limit, it will be broken up into multiple transmission units. This * must be less than or equal to the transmission limit of the endpoint the messages are * being sent to. If this is larger than the server's limit, large message buffers will * simply be rejected and dropped. This defaults to 10MiB. */ constexpr const char* const kTransmissionLimitSettingLeaf = "transmissionLimit"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This sets the maximum number of messages to process in a single pass on this transmitter. * The transmitter will stop processing log messages and start to upload messages when it * has found, validated, processed, and queued at most this number of messages on any given * transmitter object. Only validated and queued messages will count toward this limit. * This limit paired with @ref kTransmissionLimitSettingLeaf helps to limit how much of any * log file is processed and transmitted at any given point. This defaults to 10000 messages. */ constexpr const char* const kQueueLimitSettingLeaf = "queueLimit"; /** This setting is an optional member of the @ref kTransmitterSetting object. * Sets the URL to send the telemetry events to. This can be used to send the events to a * custom endpoint. This will override the default URL inferred by @ref kTelemetryModeSetting. * By default, the @ref kTelemetryModeSetting setting will determine the endpoint URL to use. * You can set this as an array if you want to specify multiple fallback endpoints * to use if the retry limit is exhausted; each endpoint will be tried in order * and will be abandoned if connectivity fails after the retry limit. * * This may also be a file URI if the output is to be written to a local log file. In this case, * this must be a "file:///" style URI since only local files are supported (ie: no server or * host name component). This file URI may also point to the special paths `/dev/stdout` or * `/dev/stderr` (ie: as "file:///dev/stdout") to output to stdout or stderr respectively * (supported on all platforms). When a local file or stdout/stderr is used as the destination * endpoint, all newly processed events will simply be appended to the end of the log file. * Exclusive write access to the local log file is expected while the transmitter is running. * The transmitter will lock the file (except stdout and stderr) while writing to it, but will * close the log after each write. If another process needs to read from it, advisory locking * should be used to guarantee the contents are not in a partial state. On Windows, this locking * should be done using one of the `LockFile*()` functions. On Posix platforms that support file * locking, this should be done using either `fcntl(f, F_SETLKW, ...)` for a blocking lock or * `fcntl(f, F_SETLK, ...)` for a non-blocking lock. Each line in the log file will represent * a single output event. * * @note Writing the transmitter output to a log file is only supported with the 'default' * and `defaultWithStringify` output protocols @ref kEventProtocolLeaf. If another * event protocol is used, it will be reverted to `default` instead. A warning message * will be output in this case. * * @note When outputting data to a file instead of a server URL, authentication will be * implicitly disabled since it is not needed. If the file URI should ever fail and * be removed from the transmitter (unlikely except in situations where for example the * device is full), the original specified state of the authentication flag will be * restored. In almost all situations, there is no need to authenticate with anything * when writing a local file. Leaving authentication enabled (the default behavior) would * just lead to that transmitter object simply sitting idle if the authentication * information could not be downloaded. The authentication can be disabled using the * @ref kTelemetryAuthenticateSettingLeaf setting. */ constexpr const char* const kTelemetryEndpointSettingLeaf = "endpoint"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies the URL or URLs to download approved schemas from. This may be used to * override the default URL and the one specified by @ref kTelemetryModeSetting. This may * be treated either as a single URL string value or as an array of URL strings. The usage * depends on how the setting is specified by the user or config. If an array of URLs is * given, they are assumed to be in priority order starting with the first as the highest * priority URL. The first one that successfully downloads will be used as the schema * package. The others are considered to be backup URLs. This will be overridden by both * @ref kTelemetrySchemaFileSetting and @ref kTelemetrySchemasDirectorySetting. This * defaults to the Omniverse production schemas URL. * * @note In debug builds, this schemas package URL may also point to a local file. This * may be specified in both the single string and array forms of this setting. The * local file URI may be in the `file://` scheme form or as just a local (absolute) * or relative) filename. */ constexpr const char* const kTelemetrySchemasUrlSettingLeaf = "schemasUrl"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies that authentication should be enabled when sending event messages to the * telemetry endpoint. When disabled, this will prevent the auth token from being retrieved * from the Omniverse Launcher app. This should be used in situations where the Omniverse * Launcher app is not running or an endpoint that does not need or expect authorization is * used. If this is not used and the auth token cannot be retrieved from the Launcher app, the * transmitter will go into an idle mode where nothing is processed or sent. This mode is * expecting the Launcher app to become available at some future point. Setting this option * to `false` will disable the authentication checks and just attempt to push the events to * the specified telemetry endpoint URL. Note that the default endpoint URL will not work * if this option is used since it expected authentication. The default value is `true`. */ constexpr const char* const kTelemetryAuthenticateSettingLeaf = "authenticate"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies the URL to download the authentication token from. This option will be * ignored if @ref kTelemetryAuthenticateSetting is `false`. A file will be expected to * be downloaded from this URL. The downloaded file is expected to be JSON formatted and * is expected to contain the authentication token in the format that the authentication * server expects. The name of the data property in the file that contains the actual * token to be sent with each message is specified in @ref kTelemetryAuthTokenKeyNameSetting. * The data property in the file that contains the token's expiry date is specified in * @ref kTelemetryAuthTokenExpiryNameSetting. Alternatively, this setting may also point * to a file on disk (either with the 'file://' protocol or by naming the file directly). * If a file on disk is named, it is assumed to either be JSON formatted and also contain * the token data and expiry under the same key names as given with * @ref kTelemetryAuthTokenKeyNameSetting and @ref kTelemetryAuthTokenExpiryNameSetting, * or it will be a file whose entire contents will be the token itself. The latter mode * is only used when the @ref kTelemetryAuthTokenKeyNameSetting setting is an empty string. * By default, the URL for the Omniverse Launcher's authentication web API will be used. */ constexpr const char* const kTelemetryAuthTokenUrlSettingLeaf = "authTokenUrl"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies the name of the key in the downloaded authentication token's JSON data * that contains the actual token data to be sent with each set of uploaded messages. * This option will be ignored if @ref kTelemetryAuthenticateSetting is `false`. * This must be in the format that the authentication server expects. The token data * itself can be any length, but is expected to be string data in the JSON file. The * key is looked up in a case sensitive manner. This defaults to "idToken". */ constexpr const char* const kTelemetryAuthTokenKeyNameSettingLeaf = "authTokenKeyName"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies the name of the key in the downloaded authentication token's JSON data * that contains the optional expiry date for the token. This option will be ignored if * @ref kTelemetryAuthenticateSetting is `false`.If this property exists, it will be used * to predict when the token should be retrieved again. If this property does not exist, * the token will only be retrieved again if sending a message results in a failure due * to a permission error. This property is expected to be string data in the JSON * file. Its contents must be formatted as an RFC3339 date/time string. This defaults to * "expires". */ constexpr const char* const kTelemetryAuthTokenExpiryNameSettingLeaf = "authTokenExpiryName"; /** This setting is an optional member of the @ref kTransmitterSetting object. * What serialization protocol is being used by the transmitter. * This can be set to one of three possible (case-insensitive) values: * - "default": This is the default protocol. The event will not be modified from its * original generated format and content. This includes leaving the `data` * field as a nested JSON object. This will send events in batches (as many * as are available at the time) to the server with each JSON event separated * by a newline (aka JSON lines format). * - "defaultWithStringify": This sends batches of events at a time to the server with each * JSON event separated by a newline (aka JSON lines format). Structuredlog * event format is largely left as-is; the only change is that the `data` * field's object is stringified. This is the only difference between this * protocol and the @ref `default` protocol above. * - "NVDF": This is also a batch serialization protocol, except that the event property * names are modified to follow the expectations of the server. * This flattens each event's `data` payload into the event base. * The `time` field is renamed to `ts_created` and its format * is changed to a *nix epoch time in milliseconds. * The `id` field is renamed to `_id`. * All data fields are also prefixed in a Hungarian-notation * style system. */ constexpr const char* const kEventProtocolLeaf = "eventProtocol"; /** This setting is an optional member of the @ref kTransmitterSetting object. * The tag name that will be used to record how much of the file was processed. * Unless `kResendEventsSetting` is set to `true`, the seek tags are used to * tell the transmitter how much of the log has been processed so far so that * it won't try to send old events again. * The default value of this is "seek". * You may want to change the seek tag name if you need to send data to multiple * telemetry endpoints with separate transmitter processes. * * @note The telemetry log files have a 256 byte header. * Each seek tag will add 13 bytes to the header + the length of the tag * name. * When the log header space is exhausted, the header will not be updated, * which is equivalent to having `kResendEventsSetting` is set to `true`. * Please avoid long tag names to avoid this risk. */ constexpr const char* const kSeekTagNameLeaf = "seekTagName"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This specifies the expected type of the authentication token. This can be any of * "auto", "jwt", or "api-key". By default this is set to "auto" and will attempt to * detect the type of authentication token based on where the @ref kTelemetryAuthTokenUrlSetting * setting points. If the value points to a URL, a JWT will be assumed. If the value points * to a file on disk or directly contains the token itself, a long-lived API key will be assumed. * If an alternate storage method is needed but the assumed type doesn't match the actual * token type, this setting can be used to override the auto detection. The default value is * "auto". This setting will be ignored if @ref kTelemetryAuthenticateSetting is set to false. */ constexpr const char* const kTelemetryAuthTokenTypeLeaf = "authTokenType"; /** This setting is an optional member of the @ref kTransmitterSetting object. * The number of days before the current time where events in a log start to be considered old. * When set to 0 (and this setting isn't overridden on a per-schema or per-event level), all * events are processed as normal and no events are considered old. When set to a non-zero * value, any events that are found to be older than this number of days will be processed * differently depending on the flags specified globally (@ref kIgnoreOldEventsSetting and * @ref kPseudonymizeOldEventsSetting), at the schema level (``fSchemaFlagIgnoreOldEvents`` * and ``fSchemaFlagPseudonymizeOldEvents``), and at the event level (``fEventFlagIgnoreOldEvents`` * and ``fEventFlagPseudonymizeOldEvents``). If no special flags are given, the default * behavior is to anonymize old events before transmitting them. This will only override the * old events threshold given at the schema (``#/oldEventsThreshold``) or event * (``#/events/<eventName>/oldEventsThreshold``) if it is a smaller non-zero value than the * values given at the lower levels. This defaults to 0 days (ie: disables checking for 'old' * events). */ constexpr const char* const kOldEventThresholdSettingLeaf = "oldEventThreshold"; /** This setting is an optional member of the @ref kTransmitterSetting object. * Flag to indicate that when an old event is detected, it should simply be discarded instead * of being anonymized or pseudonymized before transmission. This is useful if processing * old events is not interesting for analysis or if transmitting an old event will violate a * data retention policy. An event is considered old if it is beyond the 'old events threshold' * (see @ref kOldEventThresholdSetting). By default, old events will be anonymized before being * transmitted. If this flag is set here at the global level, it will override any old event * settings from the schema and event levels. */ constexpr const char* const kIgnoreOldEventsSettingLeaf = "ignoreOldEvents"; /** This setting is an optional member of the @ref kTransmitterSetting object. * Flag to indicate that when an old event is detected, it should be pseudonymized instead of * anonymized before transmission. This setting is ignored for any given event if the * @ref kIgnoreOldEventsSetting setting, ``fSchemaFlagIgnoreOldEvents`` flag, or * ``fEventFlagIgnoreOldEvents`` flag is used for that event. When not specified, the default * behavior is to anonymize old events before transmission. */ constexpr const char* const kPseudonymizeOldEventsSettingLeaf = "pseudonymizeOldEvents"; /** This setting is an optional member of the @ref kTransmitterSetting object. * The number of attempts to transmit data that will be made before giving up. * This can be set to -1 to retry forever. * This setting is only important in a multi-endpoint context; if one endpoint * goes offline, a retry limit will allow the transmitter to give up and start * sending data to other endpoints. * There is an exponential backoff after every retry, so the first retry will * occur after 1 second, then 2 second, then 4 seconds, etc. * The backoff takes the transmission time into account, so the 4 second backoff * would only wait 1 second if the failed transmission took 3 seconds. * A setting of 5 will roughly wait for 1 minute in total. * A setting of 11 will roughly wait for 1 hour in total. * After the 12th wait, wait time will no longer increase, so each subsequent * wait will only last 4096 seconds. */ constexpr const char* const kRetryLimitSettingLeaf = "retryLimit"; /** This setting is an optional member of the @ref kTransmitterSetting object. * This controls which messages will be considered by the transmitter and * which will be filtered out before validating against a schema. This is * intended to match each message's transmission mode against the mode that * the transmitter is currently running in. This value can be one of the * following: * * "all": allow all messages to be validated against schemas. * * "matching": allow messages whose source mode matches the transmitter's * current run mode. * * "matching+": allow messages whose source mode matches the transmitter's * current run mode or higher. * * "test": only consider messages from the 'test' source mode. * * "dev": only consider messages from the 'dev' source mode. * * "prod": only consider messages from the 'prod' source mode. * * "dev,prod" (or other combinations): only consider messages from the listed * source modes. * * This defaults to "all". This setting value may be used either on a * per-transmitter basis when using multiple transmitters, or it may be used in * the legacy setting `/telemetry/messageMatchMode`. If both the legacy and the * per-transmitter setting are present, the per-transmitter ones will always * override the legacy setting. * * @note Setting this to a value other than "all" would result in certain messages * not being transmitted because they were rejected during a previous run and * were skipped over in the log. It is intended that if this setting is used * for a given transmitter, it is likely to be used with that same matching * mode most often on any given machine. Note that multiple transmitters with * different matching modes can also be used. */ constexpr const char* const kMessageMatchingModeLeaf = "messageMatchMode"; /** @} */ /** Create a guard with the standard name and path for the transmitter. * @returns A UniqueApp guard that is used to let the transmitter know when * it should exit on its own. Telemetry clients should use this to * 'connect' to the transmitter (note that this does not require the * transmitter to be running yet). See launchTransmitter() for an * example usage. * @remarks This guard is needed by all telemetry clients to let the transmitter * know when all clients have shut down so it can exit as well. */ inline extras::UniqueApp createGuard() { constexpr const char* kLaunchGuardNameSetting = "/telemetry/launchGuardName"; carb::settings::ISettings* settings; const char* guardName = "omni.telemetry.transmitter"; auto getGuardPath = []() -> std::string { #if OMNI_PLATFORM_LINUX // XDG_RUNTIME_DIR is the standard place for putting runtime IPC objects on Linux const char* runDir = getenv("XDG_RUNTIME_DIR"); if (runDir != nullptr) { return runDir; } #endif core::ObjectPtr<omni::structuredlog::IStructuredLog> strucLog; core::ObjectPtr<omni::structuredlog::IStructuredLogSettings> settings; strucLog = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); if (strucLog.get() == nullptr) { OMNI_LOG_ERROR("failed to get IStructuredLog"); return ""; } settings = strucLog.as<structuredlog::IStructuredLogSettings>(); if (settings.get() == nullptr) { OMNI_LOG_ERROR("failed to get IStructuredLogSettings"); return ""; } return settings->getLogOutputPath(); }; settings = carb::getCachedInterface<carb::settings::ISettings>(); if (settings != nullptr && settings->isAccessibleAs(carb::dictionary::ItemType::eString, kLaunchGuardNameSetting)) guardName = settings->getStringBuffer(kLaunchGuardNameSetting); return extras::UniqueApp(getGuardPath().c_str(), guardName); } /** Determine the directory where the logs of a launched transmitter process should go. * @returns The log output directory. */ inline std::string getTransmitterLogPath() { constexpr const char* kLogFileFallback = "./omni.telemetry.transmitter.log"; const char* logFile = nullptr; carb::settings::ISettings* settings = carb::getFramework()->tryAcquireInterface<carb::settings::ISettings>(); core::ObjectPtr<omni::structuredlog::IStructuredLog> strucLog = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); core::ObjectPtr<omni::structuredlog::IStructuredLogSettings> strucLogSettings; if (settings != nullptr) { settings->setDefaultString(kLogFileSetting, ""); logFile = settings->getStringBuffer(kLogFileSetting); if (logFile != nullptr && logFile[0] != '\0') return logFile; } else { CARB_LOG_ERROR("failed to acquire ISettings"); } if (strucLog.get() == nullptr) { OMNI_LOG_ERROR("failed to get IStructuredLog - using CWD"); return kLogFileFallback; } strucLogSettings = strucLog.as<structuredlog::IStructuredLogSettings>(); if (strucLogSettings.get() == nullptr) { OMNI_LOG_ERROR("failed to get IStructuredLogSettings - using CWD for the log file"); return kLogFileFallback; } return std::string(strucLogSettings->getLogOutputPath()) + "/omni.telemetry.transmitter.log"; } /** Launch the telemetry transmitter process. * @param[in] transmitterPath The path to the transmitter binary and .py file. * @param[in] pythonHome The path to your python install directory. * @param[in] pythonPath The path to the Carbonite python bindings. * @param[in] extraArgs Extra arguments to pass to the transmitter process. * @returns `true` if the transmitter child process is successfully launched. * Returns `false` otherwise. * * @remarks This function will launch an instance of the telemetry transmitter. * Any app using telemetry should launch the transmitter. * The transmitter process will upload telemetry events from the logs * to the Kratos endpoint. * The transmitter is currently dependent on the Omniverse Launcher to * obtain an authentication token to send telemetry. * Only one transmitter process will exist on a system at a time; if * one is launched while another exists, the new instance will exit. * The transmitter process will run until all telemetry client * processes have exited. * * @note The `/telemetry/log` tree of settings exists to specify log options for * the transmitter without affecting the parent process. * - `/telemetry/log/file` is passed to the transmitter as `/log/file'. * - `/telemetry/log/level` is passed to the transmitter as `/log/level'. * * @note This transmitter process won't log to the standard streams by default. * Logs will go to a standard log file path instead, but `--/log/file` can * be used to override this. * The transmitter process will exit after the host app, so logging to * the standard streams will result in messages being written into terminal * over the user's prompt. */ inline bool launchTransmitter(const char* transmitterPath, const std::vector<std::string> extraArgs = {}) { #if OMNI_PLATFORM_WINDOWS const char* ext = ".exe"; #else const char* ext = ""; #endif carb::launcher::ILauncher* launcher = carb::getFramework()->tryAcquireInterface<carb::launcher::ILauncher>(); carb::settings::ISettings* settings = carb::getFramework()->tryAcquireInterface<carb::settings::ISettings>(); extras::UniqueApp guard = createGuard(); carb::launcher::ArgCollector args; carb::launcher::EnvCollector env; carb::launcher::LaunchDesc desc = {}; size_t envCount; const char* logLevel = nullptr; if (launcher == nullptr) { OMNI_LOG_ERROR("failed to acquire ILauncher"); return false; } guard.connectClientProcess(); args.format("%s/omni.telemetry.transmitter%s", transmitterPath, ext); args.add("/telemetry", "--/", carb::launcher::fSettingsEnumFlagRecursive); args.add("/structuredLog/extraFields", "--/", 0); args.add("/log", "--/", carb::launcher::fSettingsEnumFlagRecursive, [](const char* path, void* ctx) { CARB_UNUSED(ctx); return strcmp(path, "/log/enableStandardStreamOutput") != 0 && strcmp(path, "/log/file") != 0 && strcmp(path, "/log/level") != 0; }); // output will not go to the standard streams because it's annoying if // output goes to your terminal after your process finishes and there is no // way to ensure the transmitter shuts down before your process args.add("--/log/enableStandardStreamOutput=false"); args.format("--/log/file=%s", getTransmitterLogPath().c_str()); if (settings == nullptr) { OMNI_LOG_ERROR("failed to acquire ISettings"); } else { settings->setDefaultString(kLogLevelSetting, ""); logLevel = settings->getStringBuffer(kLogLevelSetting); if (logLevel != nullptr && logLevel[0] != '\0') { args.format("--/log/level=%s", logLevel); } else { logLevel = settings->getStringBuffer("/log/level"); if (logLevel != nullptr && logLevel[0] != '\0') { args.format("--/log/level=%s", logLevel); } } } for (const std::string& arg : extraArgs) { args.add(arg); } // add the parent environment but remove the `CARB_APP_PATH` and `CARB_APP_NAME` variables // since they will negatively affect the behaviour of the transmitter. Note that since // we're explicitly adding the full parent environment here and just subtracting some // variables, we need to also use the `fLaunchFlagNoInheritEnv` flag when launching the // child process so that ILauncher doesn't implicitly add them back. env.add(); envCount = env.getCount(); env.remove("CARB_APP_PATH"); env.remove("CARB_APP_NAME"); if (env.getCount() != envCount) { desc.flags |= carb::launcher::fLaunchFlagAllowBadEnv | carb::launcher::fLaunchFlagNoInheritEnv; desc.env = env.getEnv(); desc.envCount = env.getCount(); } desc.argv = args.getArgs(&desc.argc); desc.flags |= carb::launcher::fLaunchFlagNoStdStreams; return launcher->launchProcessDetached(desc) != carb::launcher::kBadId; } } // namespace telemetry } // namespace omni
37,487
C
54.785714
118
0.722277
omniverse-code/kit/include/omni/structuredlog/StringView.h
// Copyright (c) 2021-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 A string_view wrapper to make telemetry calls easier. */ #pragma once #include "../../carb/cpp/StringView.h" #include <string> namespace omni { namespace structuredlog { /** An extension of carb::cpp::basic_string_view that can handle nullptr and * `std::basic_string` as inputs * * @tparam CharT The char type pointed to by the view. * @tparam Traits The type traits for @p CharT. */ template <class CharT, class Traits = std::char_traits<CharT>> class BasicStringView : public carb::cpp::basic_string_view<CharT, Traits> { public: constexpr BasicStringView() : base() { } /** Create a string view from a C string. * @param[in] s The C string to create a view into. * This original pointer continues to be used and nothing is copied. */ constexpr BasicStringView(const CharT* s) : base(s, s == nullptr ? 0 : Traits::length(s)) { } /** Create a string view from a char buffer * @param[in] s The char buffer to create a view into. * This does not need to be null terminated. * This original pointer continues to be used and nothing is copied. * @param[in] len The length of the view into @p s, in characters. */ constexpr BasicStringView(const CharT* s, size_t len) : base(s, len) { } /** Create a string view from a std::basic_string. * @param[in] s The string to create this string view for. */ constexpr BasicStringView(const std::basic_string<CharT>& s) : base(s.c_str(), s.size()) { } private: using base = carb::cpp::basic_string_view<CharT, Traits>; }; /** String view for `char` strings. */ using StringView = BasicStringView<char>; } // namespace structuredlog } // namespace omni
2,226
C
31.275362
93
0.672507
omniverse-code/kit/include/omni/structuredlog/StructuredLog.ProcessLifetime.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. // // DO NOT MODIFY THIS FILE. This is a generated file. // This file was generated from: StructuredLog.ProcessLifetime.json // #pragma once #include <omni/log/ILog.h> #include <omni/structuredlog/IStructuredLog.h> #include <omni/structuredlog/JsonTree.h> #include <omni/structuredlog/BinarySerializer.h> #include <omni/structuredlog/StringView.h> #include <memory> namespace omni { namespace structuredlog { /** helper macro to send the 'event' event. * * @param[in] eventFlags_ The flags to pass directly to the event handling * function. This may be any of the AllocFlags flags that can * be passed to @ref omni::structuredlog::IStructuredLog::allocEvent(). * @param[in] event_ Parameter from schema at path '/event'. * the name of the process lifetime event that occurred. This may be * any string to identify the event. This event may be used by the * host app as well to measure its own startup times. * @param[in] context_ Parameter from schema at path '/context'. * extra information about the event that occurred. This may be * nullptr or an empty string if not needed for a particular event. * @returns no return value. * * @remarks Event to send when the app starts, exits, crashes, etc. This * event can also be used to measure other host app events by simply * sending different 'event' and 'context' strings. The main purpose * of this is to track session time and the relative frequency of * crashes. * * @sa @ref Schema_omni_processlifetime_1_1::event_sendEvent(). * @sa @ref Schema_omni_processlifetime_1_1::event_isEnabled(). */ #define OMNI_OMNI_PROCESSLIFETIME_1_1_EVENT(eventFlags_, event_, context_) \ OMNI_STRUCTURED_LOG(omni::structuredlog::Schema_omni_processlifetime_1_1::event, eventFlags_, event_, context_) /** helper macro to send the 'heartbeat' event. * * @returns no return value. * * @remarks Event to send periodically to give an indication that the process * is still alive and the session is still valid. This can also be * used to measure session lengths in the case where no 'exit' or * 'crash' event can be found (ie: power loss, user kill, BSOD/kernel * panic, etc). * * @sa @ref Schema_omni_processlifetime_1_1::heartbeat_sendEvent(). * @sa @ref Schema_omni_processlifetime_1_1::heartbeat_isEnabled(). */ #define OMNI_OMNI_PROCESSLIFETIME_1_1_HEARTBEAT() \ OMNI_STRUCTURED_LOG(omni::structuredlog::Schema_omni_processlifetime_1_1::heartbeat) class Schema_omni_processlifetime_1_1 { public: /** the event ID names used to send the events in this schema. These IDs * are used when the schema is first registered, and are passed to the * allocEvent() function when sending the event. */ enum : uint64_t { kEventEventId = OMNI_STRUCTURED_LOG_EVENT_ID( "omni.processlifetime", "com.nvidia.carbonite.processlifetime.event", "1.1", "0"), kHeartbeatEventId = OMNI_STRUCTURED_LOG_EVENT_ID( "omni.processlifetime", "com.nvidia.carbonite.processlifetime.heartbeat", "1.1", "0"), }; Schema_omni_processlifetime_1_1() = default; /** Register this class with the @ref omni::structuredlog::IStructuredLog interface. * @param[in] flags The flags to pass into @ref omni::structuredlog::IStructuredLog::allocSchema() * This may be zero or more of the @ref omni::structuredlog::SchemaFlags flags. * @returns `true` if the operation succeeded. * @returns `false` if @ref omni::structuredlog::IStructuredLog couldn't be loaded. * @returns `false` if a memory allocation failed. */ static bool registerSchema(omni::structuredlog::IStructuredLog* strucLog) noexcept { return _registerSchema(strucLog); } /** Check whether this structured log schema is enabled. * @param[in] eventId the ID of the event to check the enable state for. * This must be one of the @a k*EventId symbols * defined above. * @returns Whether this client is enabled. */ static bool isEnabled(omni::structuredlog::EventId eventId) noexcept { return _isEnabled(eventId); } /** Enable/disable an event in this schema. * @param[in] eventId the ID of the event to enable or disable. * This must be one of the @a k*EventId symbols * defined above. * @param[in] enabled Whether is enabled or disabled. */ static void setEnabled(omni::structuredlog::EventId eventId, bool enabled) noexcept { _setEnabled(eventId, enabled); } /** Enable/disable this schema. * @param[in] enabled Whether is enabled or disabled. */ static void setEnabled(bool enabled) noexcept { _setEnabled(enabled); } /** event enable check helper functions. * * @param[in] strucLog The structured log object to use to send this event. This * must not be nullptr. It is the caller's responsibility * to ensure that a valid object is passed in. * @returns `true` if the specific event and this schema are both enabled. * @returns `false` if either the specific event or this schema is disabled. * * @remarks These check if an event corresponding to the function name is currently * enabled. These are useful to avoid parameter evaluation before calling * into one of the event emitter functions. These will be called from the * OMNI_STRUCTURED_LOG() macro. These may also be called directly if an event * needs to be emitted manually, but the only effect would be the potential * to avoid parameter evaluation in the *_sendEvent() function. Each * *_sendEvent() function itself will also internally check if the event * is enabled before sending it. * @{ */ static bool event_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kEventEventId); } static bool heartbeat_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kHeartbeatEventId); } /** @} */ /** Send the event 'com.nvidia.carbonite.processlifetime.event' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @param[in] eventFlags The flags to pass directly to the event handling * function. This may be any of the AllocFlags flags that can * be passed to @ref omni::structuredlog::IStructuredLog::allocEvent(). * @param[in] event Parameter from schema at path '/event'. * the name of the process lifetime event that occurred. This may be * any string to identify the event. This event may be used by the * host app as well to measure its own startup times. * @param[in] context Parameter from schema at path '/context'. * extra information about the event that occurred. This may be * nullptr or an empty string if not needed for a particular event. * @returns no return value. * * @remarks Event to send when the app starts, exits, crashes, etc. This * event can also be used to measure other host app events by simply * sending different 'event' and 'context' strings. The main purpose * of this is to track session time and the relative frequency of * crashes. */ static void event_sendEvent(omni::structuredlog::IStructuredLog* strucLog, AllocFlags eventFlags, const omni::structuredlog::StringView& event, const omni::structuredlog::StringView& context) noexcept { _event_sendEvent(strucLog, eventFlags, event, context); } /** Send the event 'com.nvidia.carbonite.processlifetime.heartbeat' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @returns no return value. * * @remarks Event to send periodically to give an indication that the process * is still alive and the session is still valid. This can also be * used to measure session lengths in the case where no 'exit' or * 'crash' event can be found (ie: power loss, user kill, BSOD/kernel * panic, etc). */ static void heartbeat_sendEvent(omni::structuredlog::IStructuredLog* strucLog) noexcept { _heartbeat_sendEvent(strucLog); } private: /** This will allow us to disable array length checks in release builds, * since they would have a negative performance impact and only be hit * in unusual circumstances. */ static constexpr bool kValidateLength = CARB_DEBUG; /** body for the registerSchema() public function. */ static bool _registerSchema(omni::structuredlog::IStructuredLog* strucLog) { omni::structuredlog::AllocHandle handle = {}; omni::structuredlog::SchemaResult result; uint8_t* buffer; omni::structuredlog::EventInfo events[2] = {}; size_t bufferSize = 0; size_t total = 0; omni::structuredlog::SchemaFlags flags = 0; if (strucLog == nullptr) { OMNI_LOG_WARN( "no structured log object! The schema " "'Schema_omni_processlifetime_1_1' " "will be disabled."); return false; } // calculate the tree sizes size_t event_size = _event_calculateTreeSize(); size_t heartbeat_size = _heartbeat_calculateTreeSize(); // calculate the event buffer size bufferSize += event_size; bufferSize += heartbeat_size; // begin schema creation buffer = strucLog->allocSchema("omni.processlifetime", "1.1", flags, bufferSize, &handle); if (buffer == nullptr) { OMNI_LOG_ERROR("allocSchema failed (size = %zu bytes)", bufferSize); return false; } // register all the events events[0].schema = _event_buildJsonTree(event_size, buffer + total); events[0].eventName = "com.nvidia.carbonite.processlifetime.event"; events[0].parserVersion = 0; events[0].eventId = kEventEventId; events[0].flags = omni::structuredlog::fEventFlagCriticalEvent | omni::structuredlog::fEventFlagUseLocalLog; total += event_size; events[1].schema = _heartbeat_buildJsonTree(heartbeat_size, buffer + total); events[1].eventName = "com.nvidia.carbonite.processlifetime.heartbeat"; events[1].parserVersion = 0; events[1].eventId = kHeartbeatEventId; events[1].flags = omni::structuredlog::fEventFlagCriticalEvent | omni::structuredlog::fEventFlagUseLocalLog; total += heartbeat_size; result = strucLog->commitSchema(handle, events, CARB_COUNTOF(events)); if (result != omni::structuredlog::SchemaResult::eSuccess && result != omni::structuredlog::SchemaResult::eAlreadyExists) { OMNI_LOG_ERROR( "failed to register structured log events " "{result = %s (%zu)}", getSchemaResultName(result), size_t(result)); return false; } return true; } /** body for the isEnabled() public function. */ static bool _isEnabled(omni::structuredlog::EventId eventId) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); return strucLog != nullptr && strucLog->isEnabled(eventId); } /** body for the setEnabled() public function. */ static void _setEnabled(omni::structuredlog::EventId eventId, bool enabled) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; strucLog->setEnabled(eventId, 0, enabled); } /** body for the setEnabled() public function. */ static void _setEnabled(bool enabled) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; strucLog->setEnabled(kEventEventId, omni::structuredlog::fEnableFlagWholeSchema, enabled); } #if OMNI_PLATFORM_WINDOWS # pragma warning(push) # pragma warning(disable : 4127) // warning C4127: conditional expression is constant. #endif /** body for the event_sendEvent() function. */ static void _event_sendEvent(omni::structuredlog::IStructuredLog* strucLog, AllocFlags eventFlags, const omni::structuredlog::StringView& event, const omni::structuredlog::StringView& context) noexcept { omni::structuredlog::AllocHandle handle = {}; // calculate the required buffer size for the event omni::structuredlog::BinaryBlobSizeCalculator calc; { if (kValidateLength && event.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'event' exceeds max value 65535 - " "it will be truncated (size was %zu)", event.length() + 1); } // property event calc.track(event); if (kValidateLength && context.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'context' exceeds max value 65535 - " "it will be truncated (size was %zu)", context.length() + 1); } // property context calc.track(context); } // write out the event into the buffer void* buffer = strucLog->allocEvent(0, kEventEventId, eventFlags, calc.getSize(), &handle); if (buffer == nullptr) { OMNI_LOG_ERROR( "failed to allocate a %zu byte buffer for structured log event " "'com.nvidia.carbonite.processlifetime.event'", calc.getSize()); return; } omni::structuredlog::BlobWriter<CARB_DEBUG, _onStructuredLogValidationError> writer(buffer, calc.getSize()); { // property event writer.copy(event); // property context writer.copy(context); } strucLog->commitEvent(handle); } /** body for the heartbeat_sendEvent() function. */ static void _heartbeat_sendEvent(omni::structuredlog::IStructuredLog* strucLog) noexcept { omni::structuredlog::AllocHandle handle = {}; // write out the event into the buffer if (strucLog->allocEvent(0, kHeartbeatEventId, 0, 0, &handle) == nullptr) { OMNI_LOG_ERROR( "failed to allocate a buffer for structured log event com.nvidia.carbonite.processlifetime.heartbeat"); return; } strucLog->commitEvent(handle); } #if OMNI_PLATFORM_WINDOWS # pragma warning(pop) #endif /** Calculate JSON tree size for structured log event: com.nvidia.carbonite.processlifetime.event. * @returns The JSON tree size in bytes for this event. */ static size_t _event_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(2); // object has 2 properties { // property event calc.trackName("event"); calc.track(static_cast<const char*>(nullptr)); // property context calc.trackName("context"); calc.track(static_cast<const char*>(nullptr)); } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.carbonite.processlifetime.event. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _event_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.carbonite.processlifetime.event' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { // property event result = builder.setName(&base->data.objVal[0], "event"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property context result = builder.setName(&base->data.objVal[1], "context"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } } return base; } /** Calculate JSON tree size for structured log event: com.nvidia.carbonite.processlifetime.heartbeat. * @returns The JSON tree size in bytes for this event. */ static size_t _heartbeat_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(0); // object has 0 properties { } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.carbonite.processlifetime.heartbeat. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _heartbeat_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.carbonite.processlifetime.heartbeat' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 0); // object has 0 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { } return base; } /** The callback that is used to report validation errors. * @param[in] s The validation error message. */ static void _onStructuredLogValidationError(const char* s) { OMNI_LOG_ERROR("error sending a structured log event: %s", s); } }; // asserts to ensure that no one's modified our dependencies static_assert(omni::structuredlog::BlobWriter<>::kVersion == 0, "BlobWriter version changed"); static_assert(omni::structuredlog::JsonNode::kVersion == 0, "JsonNode version changed"); static_assert(sizeof(omni::structuredlog::JsonNode) == 24, "unexpected size"); static_assert(std::is_standard_layout<omni::structuredlog::JsonNode>::value, "this type needs to be ABI safe"); static_assert(offsetof(omni::structuredlog::JsonNode, type) == 0, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, flags) == 1, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, len) == 2, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, nameLen) == 4, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, name) == 8, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, data) == 16, "struct layout changed"); } // namespace structuredlog } // namespace omni OMNI_STRUCTURED_LOG_ADD_SCHEMA(omni::structuredlog::Schema_omni_processlifetime_1_1, omni_processlifetime, 1_1, 0);
22,993
C
41.346225
120
0.616753
omniverse-code/kit/include/omni/structuredlog/IStructuredLog.gen.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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Main structured log interface. This should be treated internally as a global singleton. Any * attempt to create or acquire this interface will return the same object just with a new * reference taken on it. * * There are three main steps to using this interface: * * Set up the interface. For most app's usage, all of the default settings will suffice. * The default log path will point to the Omniverse logs folder and the default user ID * will be the one read from the current user's privacy settings file (if it exists). If * the default values for these is not sufficient, a new user ID should be set with * @ref omni::structuredlog::IStructuredLogSettings::setUserId() and a log output path should be set with * @ref omni::structuredlog::IStructuredLogSettings::setLogOutputPath(). * If the privacy settings file is not present, * the user name will default to a random number. The other defaults should be sufficient * for most apps. This setup only needs to be performed once by the host app if at all. * The @ref omni::structuredlog::IStructuredLogSettings interface can be acquired either * by casting an @ref omni::structuredlog::IStructuredLog * object to that type or by directly creating the @ref omni::structuredlog::IStructuredLogSettings * object using omni::core::ITypeFactory_abi::createType(). * * Register one or more event schemas. * This is done with @ref omni::structuredlog::IStructuredLog::allocSchema() and * @ref omni::structuredlog::IStructuredLog::commitSchema(). * At least one event must be registered for any events to * be processed. Once a schema has been registered, it will remain valid until the * structured log module is unloaded from the process. There is no way to forcibly * unregister a set of events once registered. * * Send zero or more events. This is done with the @ref omni::structuredlog::IStructuredLog::allocEvent() and * @ref omni::structuredlog::IStructuredLog::commitEvent() functions. * * For the most part, the use of this interface will be dealt with in generated code. This * generated code will come from the 'omni.structuredlog' tool in the form of an inlined header * file. It is the host app's responsibility to call the header's schema registration helper * function at some point on startup before any event helper functions are called. * * All messages generated by this structured log system will be CloudEvents v1.0 compliant. * These should be parsable by any tool that is capable of understanding CloudEvents. * * Before an event can be sent, at least one schema describing at least one event must be * registered. This is done with the @ref omni::structuredlog::IStructuredLog::allocSchema() and * @ref omni::structuredlog::IStructuredLog::commitSchema() functions. * The @ref omni::structuredlog::IStructuredLog::allocSchema() function returns * a handle to a block of memory owned by the structured log system and a pointer to that block's * data. The caller is responsible for both calculating the required size of the buffer before * allocating, and filling it in with the schema data trees for each event that can be sent as * part of that schema. The helper functions in @ref omni::structuredlog::JsonTreeSizeCalculator and * @ref omni::structuredlog::JsonBuilder can be used to build these trees. Once these trees are built, they are * stored in a number of entries in an array of @ref omni::structuredlog::EventInfo objects. This array of event * info objects is then passed to @ref omni::structuredlog::IStructuredLog::commitSchema() to complete the schema * registration process. * * Sending of a message is split into two parts for efficiency. The general idea is that the * caller will allocate a block of memory in the event queue's buffer and write its data directly * there. * The allocation occurs with the @ref omni::structuredlog::IStructuredLog::allocEvent() call. * This will return a * handle to the allocated block and a pointer to the first byte to start writing the payload * data to. The buffer's header will already have been filled in upon return from * @ref omni::structuredlog::IStructuredLog::allocEvent(). * Once the caller has written its event payload information to * the buffer, it will call @ref omni::structuredlog::IStructuredLog::commitEvent() * to commit the message to the queue. At * this point, the message can be consumed by the event processing thread. * * Multiple events may be safely allocated from and written to the queue's buffer simultaneously. * There is no required order that the messages be committed in however. If a buffer is * allocated after one that has not been committed yet, and that newer event is committed first, * the only side effect will be that the event processing thread will be stalled in processing * new events until the first message is also committed. This is important since the events * would still need to be committed to the log in the correct order. * * All events that are processed through this interface will be written to a local log file. The * log file will be periodically consumed by an external process (the Omniverse Transmitter app) * that will send all the approved events to the telemetry servers. Only events that have been * approved by legal will be sent. All other messages will be rejected and only remain in the * log files on the local machine. */ template <> class omni::core::Generated<omni::structuredlog::IStructuredLog_abi> : public omni::structuredlog::IStructuredLog_abi { public: OMNI_PLUGIN_INTERFACE("omni::structuredlog::IStructuredLog") /** Checks whether a specific event or schema is enabled. * * @param[in] eventId The unique ID of the event to check the enable state of. This * is the ID that was originally used to register the event. * @returns `true` if both the requested event and its schema is enabled. * @returns `false` if either the requested event or its schema is disabled. * * @remarks This checks if a named event or its schema is currently enabled in the structured * log system. Individual events or entire schemas may be disabled at any given * time. Both the schema and each event has its own enable state. A schema can be * disabled while still leaving its events' previous enable/disable states * unmodified. When the schema is enabled again, its events will still retain their * previous enable states. Set @ref omni::structuredlog::IStructuredLog::setEnabled() * for more information on how to enable and disable events and schemas. */ bool isEnabled(omni::structuredlog::EventId eventId) noexcept; /** Sets the enable state for a structured log event or schema, or the system globally. * * @param[in] eventId The ID of the event to change the enable state of. This is the ID * that was originally used to register the event. If the * @ref omni::structuredlog::fEnableFlagAll flag is used, this must be * set to @ref omni::structuredlog::kBadEventId. * @param[in] flags Flags to control the behavior of this function. This may be zero or * more of the @ref omni::structuredlog::EnableFlags flags. * If this includes the @ref omni::structuredlog::fEnableFlagAll * flag, @p eventId must be set to @ref omni::structuredlog::kBadEventId. * @param[in] enabled Set to true to enable the named event or schema. Set to false to * disable the named event or schema. If the * @ref omni::structuredlog::fEnableFlagAll flag is used, this sets the * new enable/disable state for the structured log system as a whole. * @returns No return value. * * @remarks This changes the current enable state for an event or schema. The scope of the * enable change depends on the flags that are passed in. When an event is * disabled (directly or from its schema or the structured log system being * disabled), it will also prevent it from being generated manually. In this case, * any attempt to call @ref omni::structuredlog::IStructuredLog::allocEvent() for * that disabled event or schema will simply fail immediately. * * @remarks When a schema is disabled, it effectively disables all of its events. Depending * on the flag usage however (ie: @ref omni::structuredlog::fEnableFlagOverrideEnableState), * disabling the schema may or may not change the enable states of each of its * individual events as well (see @ref omni::structuredlog::fEnableFlagOverrideEnableState * for more information). * * @note The @ref omni::structuredlog::fEnableFlagAll flag should only ever by used by the * main host app since this will affect the behavior of all modules' events regardless * of their own internal state. Disabling the entire system should also only ever be * used sparingly in cases where it is strictly necessary (ie: compliance with local * privacy laws). */ void setEnabled(omni::structuredlog::EventId eventId, omni::structuredlog::EnableFlags flags, bool enabled) noexcept; /** Allocates a block of memory for an event schema. * * @param[in] schemaName The name of the schema being registered. This may not be * nullptr or an empty string. There is no set format for this * schema name, but it should at least convey some information * about the app's name and current release version. This name * will be used to construct the log file name for the schema. * @param[in] schemaVersion The version number for the schema itself. This may not be * nullptr or an empty string. This should be the version number * of the schema itself, not of the app or component. This will * be used to construct the 'dataschema' name that gets passed * along with each CloudEvents message header. * @param[in] flags Flags to control the behavior of the schema. This may be * zero or more of the @ref omni::structuredlog::SchemaFlags flags. * @param[in] size The size of the block to allocate in bytes. If this is 0, a * block will still be allocated, but its actual size cannot be * guaranteed. The @ref omni::structuredlog::JsonTreeSizeCalculator * helper class can be used to calculate the size needs for the new schema. * @param[out] outHandle Receives the handle to the allocated memory block on success. * On failure, this receives nullptr. Each successful call * must pass this handle to @ref omni::structuredlog::IStructuredLog::commitSchema() * even if an intermediate failure occurs. In the case of a schema * tree creation failure, nullptr should be passed for @a events * in the corresponding @ref omni::structuredlog::IStructuredLog::commitSchema() call. * This will allow the allocated block to be cleaned up. * @returns A pointer to the allocated block on success. This block does not need to be * explicitly freed - it will be managed internally. This pointer will point to * the first byte that can be written to by the caller and will be at least @p size * bytes in length. This pointer will always be aligned to the size of a pointer. * @returns `nullptr` if no more memory is available. * @returns `nullptr` if an invalid parameter is passed in. * * @remarks This allocates a block of memory that the schema tree(s) for the event(s) in a * schema can be created and stored in. Pointers to the start of each event schema * within this block are expected to be stored in one of the @ref omni::structuredlog::EventInfo objects * that will later be passed to @ref omni::structuredlog::IStructuredLog::commitSchema(). The caller is * responsible for creating and filling in returned block and the array of * @ref omni::structuredlog::EventInfo objects. * The @ref omni::structuredlog::BlockAllocator helper class may be used to * allocate smaller chunks of memory from the returned block. * * @note This should only be used in generated structured log source code. This should not * be directly except when absolutely necessary. This should also not be used as a * generic allocator. Failure to use this properly will result in memory being * leaked. * * @thread_safety This call is thread safe. */ uint8_t* allocSchema(const char* schemaName, const char* schemaVersion, omni::structuredlog::SchemaFlags flags, size_t size, omni::structuredlog::AllocHandle* outHandle) noexcept; /** Commits an allocated block and registers events for a single schema. * * @param[in] schemaBlock The block previously returned from * @ref omni::structuredlog::IStructuredLog::allocSchema() * that contains the built event trees for the schema to register. * These trees must be pointed to by the @ref omni::structuredlog::EventInfo::schema * members of the @p events array. * @param[in] events The table of events that belong to this schema. This provides * information about each event such as its name, control flags, * event identifier, and a schema describing how to interpret its * binary blob on the consumer side. This may not be nullptr. Each * of the trees pointed to by @ref omni::structuredlog::EventInfo::schema in this table * must either be set to nullptr or point to an address inside the * allocated schema block @p schemaBlock that was returned from the * corresponding call to @ref omni::structuredlog::IStructuredLog::allocSchema(). * If any of the schema trees point to an address outside of the schema block, * this call will fail. * @param[in] eventCount The total number of events in the @p events table. At least one * event must be registered. This may not be 0. * @retval omni::structuredlog::SchemaResult::eSuccess if the new schema * is successfully registered as a set of unique events. * @retval omni::structuredlog::SchemaResult::eAlreadyExists if the new * schema exactly matches one that has already been successfully registered. * This can be considered a successful result. * In this case, the schema block will be destroyed before return. * @retval omni::structuredlog::SchemaResult::eEventIdCollision if the new schema contains an event whose * identifier matches that of an event that has already been registered with another * schema. This indicates that the name of the event that was used to generate the * identifier was likely not unique enough, or that two different versions of the * same schema are trying to be registered without changing the schema's version * number first. No new events will be registered in this case and the schema * block will be destroyed before return. * @retval omni::structuredlog::SchemaResult::eFlagsDiffer if the new schema exactly matches another schema * that has already been registered except for the schema flags that were used * in the new one. This is not allowed without a version change in the new schema. * No new events will be registered in this case and the schema block will be * destroyed before return. * @returns Another @ref omni::structuredlog::SchemaResult error code for other types of failures. No new events * will be registered in this case and the schema block will be destroyed before * return. * * @remarks This registers a new schema and its events with the structured log system. This * will create a new set of events in the structured log system. These events * cannot be unregistered except by unloading the entire structured log system * altogether. Upon successful registration, the events in the schema can be * emitted using the event identifiers they were registered with. * * @remarks If the new schema matches one that has already been registered, The operation * will succeed with the result @ref omni::structuredlog::SchemaResult::eAlreadyExists. * The existing * schema's name, version, flags, and event table (including order of events) must * match the new one exactly in order to be considered a match. If anything differs * (even the flags for a single event or events out of order but otherwise the same * content), the call will fail. If the schema with the differing flags or event * order is to be used, its version or name must be changed to avoid conflict with * the existing schema. * * @remarks When generating the event identifiers for @ref omni::structuredlog::EventInfo::eventId it is * recommended that a string uniquely identifying the event be created then hashed * using an algorithm such as FNV1. The string should contain the schema's client * name, the event's name, the schema's version, and any other values that may * help to uniquely identify the event. Once hashed, it is very unlikely that * the event identifier will collide with any others. This is the method that the * code generator tool uses to create the unique event identifiers. * * @remarks Up to 65536 (ie: 16-bit index values) events may be registered with the * structured log system. The performance of managing a list of events this large * is unknown and not suggested however. Each module, app, or component should only * register its schema(s) once on startup. This can be a relatively expensive * operation if done frequently and unnecessarily. * * @thread_safety This call is thread safe. */ omni::structuredlog::SchemaResult commitSchema(omni::structuredlog::AllocHandle schemaBlock, const omni::structuredlog::EventInfo* events, size_t eventCount) noexcept; /** Allocates a block of memory to store an event's payload data in. * * @param[in] version The version of the parser that should be used to read this * event's payload data. This should be @ref omni::structuredlog::kParserVersion. * If the structured log system that receives this message does not * support this particular version (ie: a newer module is run * on an old structured log system), the event message will simply * be dropped. * @param[in] eventId the unique ID of the event that is being generated. This ID must * exactly match the event ID that was provided in the * @ref omni::structuredlog::EventInfo::eventId value when the event * was registered. * @param[in] flags Flags to control how the event's block is allocated. This may * be a combination of zero or more of the @ref omni::structuredlog::AllocFlags * flags. * @param[in] payloadSize The total number of bytes needed to store the event's payload * data. The caller is responsible for calculating this ahead * of time. If the event does not have a payload, this should be * 0. The number of bytes should be calculated according to how * the requested event's schema (ie: @ref omni::structuredlog::EventInfo::schema) lays * it out in memory. * @param[out] outHandle Receives the handle to the allocated block of memory. This * must be passed to IStructuredLog::commitEvent() once the caller * has finished writing all of the payload data to the returned * buffer. The IStructuredLog::commitEvent() call acts as the * cleanup function for this handle. * @returns A pointer to the buffer to use for the event's payload data if successfully * allocated. The caller should start writing its payload data at this address * according to the formatting information in the requested event's schema. This * returned pointer will always be aligned to the size of a pointer. * @returns `nullptr` if the requested event, its schema, or the entire system is currently * disabled. * @returns `nullptr` if the event queue's buffer is full and a buffer of the requested * size could not be allocated. In this case, a invalid handle will be returned * in @p outHandle. The IStructuredLog::commitEvent() function does not need to be * called in this case. * @returns `nullptr` if the event queue failed to be created or its processing thread failed * start up. * @returns `nullptr` if the given event ID is not valid. * * @remarks This is the main entry point for creating an event message. This allocates * a block of memory that the caller can fill in with its event payload data. * The caller is expected to fill in this buffer as quickly as possible. Once * the buffer has been filled, its handle must be passed to the * @ref omni::structuredlog::IStructuredLog::commitEvent() function to finalize and send. * Failing to pass a * valid handle to @ref omni::structuredlog::IStructuredLog::commitEvent() will stall the event queue * indefinitely. * * @remarks If the requested event has been marked as 'critical' by using the event flag * @ref omni::structuredlog::fEventFlagCriticalEvent, a blocking allocation will be used here instead. * In this case, this will not fail due to the event queue being out of space. * * @note This call will fail immediately if either the requested event, its schema, or * the entire system has been explicitly disabled. It is the caller's responsibility * to both check the enable state of the event before attempting to send it (ie: to * avoid doing unnecessary work), and to gracefully handle the potential of this * call failing. * * @note It is the caller's responsibility to ensure that no events are generated during * C++ static destruction time for the process during shutdown. Especially on * Windows, doing so could result in an event being allocated but not committed * thereby stalling the event queue. This could lead to a hang on shutdown. * * @thread_safety This call is thread safe. */ uint8_t* allocEvent(omni::structuredlog::ParserVersion version, omni::structuredlog::EventId eventId, omni::structuredlog::AllocFlags flags, size_t payloadSize, omni::structuredlog::AllocHandle* outHandle) noexcept; /** finishes writing a message's payload and queues it for processing. * * @param[in] handle The handle to the queue buffer block to be committed. This must not * be nullptr. This must be the same handle that was returned through * @a outHandle on a recent call to @ref omni::structuredlog::IStructuredLog::allocEvent() * on this same thread. Upon return, this handle will be invalid and should be * discarded by the caller. * @returns No return value. * * @remarks This commits a block that was previously allocated on this thread with * @ref omni::structuredlog::IStructuredLog::allocEvent(). * It is required that the commit call occur on the * same thread that the matching @ref omni::structuredlog::IStructuredLog::allocEvent() * call was made on. * Each successful @ref omni::structuredlog::IStructuredLog::allocEvent() call must * be paired with exactly one * @ref omni::structuredlog::IStructuredLog::commitEvent() call on the same thread. * Failing to do so would result in the event queue thread stalling. * * @thread_safety This call is thread safe. */ void commitEvent(omni::structuredlog::AllocHandle handle) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::isEnabled( omni::structuredlog::EventId eventId) noexcept { return isEnabled_abi(eventId); } inline void omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::setEnabled( omni::structuredlog::EventId eventId, omni::structuredlog::EnableFlags flags, bool enabled) noexcept { setEnabled_abi(eventId, flags, enabled); } inline uint8_t* omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::allocSchema( const char* schemaName, const char* schemaVersion, omni::structuredlog::SchemaFlags flags, size_t size, omni::structuredlog::AllocHandle* outHandle) noexcept { return allocSchema_abi(schemaName, schemaVersion, flags, size, outHandle); } inline omni::structuredlog::SchemaResult omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::commitSchema( omni::structuredlog::AllocHandle schemaBlock, const omni::structuredlog::EventInfo* events, size_t eventCount) noexcept { return commitSchema_abi(schemaBlock, events, eventCount); } inline uint8_t* omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::allocEvent( omni::structuredlog::ParserVersion version, omni::structuredlog::EventId eventId, omni::structuredlog::AllocFlags flags, size_t payloadSize, omni::structuredlog::AllocHandle* outHandle) noexcept { return allocEvent_abi(version, eventId, flags, payloadSize, outHandle); } inline void omni::core::Generated<omni::structuredlog::IStructuredLog_abi>::commitEvent( omni::structuredlog::AllocHandle handle) noexcept { commitEvent_abi(handle); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL static_assert(std::is_standard_layout<omni::structuredlog::EventInfo>::value, "omni::structuredlog::EventInfo must be standard layout to be used in ONI ABI");
29,545
C
65.695259
123
0.652192
omniverse-code/kit/include/omni/structuredlog/IStructuredLogControl.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Structured log state control interface. This allows for some control over the processing of * events and log files for the structured log system. The structured log system's event queue * can be temporarily stopped if needed or the output log for a schema may be closed. Each of * these operations is only temporary as the event queue will be restarted and the log file * opened when the next event is queued with @ref omni::structuredlog::IStructuredLog::allocEvent(). * * This interface object can be acquired either by requesting it from the type factory or * by casting an @ref omni::structuredlog::IStructuredLog object to this type. */ template <> class omni::core::Generated<omni::structuredlog::IStructuredLogControl_abi> : public omni::structuredlog::IStructuredLogControl_abi { public: OMNI_PLUGIN_INTERFACE("omni::structuredlog::IStructuredLogControl") /** Closes one or more schema's persistently open log file(s). * * @param[in] event The ID of the event to close the log for. This may also be * @ref omni::structuredlog::kAllSchemas to close all log file for * the process. The log file for the schema that the given event * belongs to will be closed. * @returns No return value. * * @remarks This closes the persistently open log file(s) for one or more schemas. This * operation will effectively be ignored for schemas that were not registered * using the @ref omni::structuredlog::fSchemaFlagKeepLogOpen schema flag since those schemas will * not leave their logs open. The named log files will only remain closed until * the next attempt to write an event message to it. It is the responsibility * of the host app to ensure no events are written to the effected log file(s) * for the duration that the log needs to remain closed. * * @note This call itself is thread safe. However the log file may be reopened if a * pending event is processed in the event queue or a new event is sent while * the calling thread expects the log to remain closed. It is the caller's * responsibility to either stop the event queue, disable structured logging, or * prevent other events from being sent while the log(s) need to remain closed. */ void closeLog(omni::structuredlog::EventId event) noexcept; /** Stop the structured log event consumer thread. * * @returns No return value. * * @remarks This stops the structured log event processing system. This will stop the * processing thread and flush all pending event messages to the log. The * processing system will be restarted when the next * @ref omni::structuredlog::IStructuredLog::allocEvent() * call is made to attempt to send a new message. This call is useful if the * structured log plugin needs to be unloaded. If the processing thread is left * running, it will prevent the plugin from being unloaded (or even being attempted * to be unloaded). This can also be used to temporarily disable the structured * log system if its not needed or wanted. If the structured log system needs to * be disabled completely, a call to @ref omni::structuredlog::IStructuredLog::setEnabled() * using the @ref omni::structuredlog::fEnableFlagAll flag should be made before stopping * the event queue. * * @thread_safety This call is thread safe. */ void stop() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::structuredlog::IStructuredLogControl_abi>::closeLog( omni::structuredlog::EventId event) noexcept { closeLog_abi(event); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogControl_abi>::stop() noexcept { stop_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
4,973
C
45.055555
112
0.687915
omniverse-code/kit/include/omni/structuredlog/IStructuredLogSettings2.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/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Interface for the second version of the IStructuredLogSettings interface. This interface * exposes more settings to control the behaviour of the structured logging system. This * object can be retrieved directly or by casting the main IStructuredLog interface to this * type using `omni::core::ObjectPtr::as<>()`. */ template <> class omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi> : public omni::structuredlog::IStructuredLogSettings2_abi { public: OMNI_PLUGIN_INTERFACE("omni::structuredlog::IStructuredLogSettings2") /** Retrieves the current heartbeat message period in seconds. * * @returns The minimum time in seconds between heartbeat events. This will be * @ref omni::structuredlog::kHeartbeatDisabled if the heartbeat events are * disabled. When enabled, the heartbeat events will be generated within * ~100ms of this scheduled time. In general, it is expected that the heartbeat * period be on the scale of one minute or more to reduce the overall amount of * event traffic. */ uint64_t getHeartbeatPeriod() noexcept; /** Sets the new heartbeat event period in seconds. * * @param[in] period The minimum time in seconds between generated heartbeat events. * This may be @ref omni::structuredlog::kHeartbeatDisabled to disable * the heartbeat events. * @returns No return value. * * @remarks The heartbeat events can be used to get an estimate of a session's length even if * the 'exit' or 'crash' process lifetime events are missing (ie: power loss, user * kills the process, blue screen of death or kernel panic, etc). The session can * neither be assumed to have exited normally nor crashed with only these heartbeat * events present however. */ void setHeartbeatPeriod(uint64_t period) noexcept; /** Retrieves whether header objects will be added to each newly written log file. * * @returns `true` if headers will be written to each new log file. Returns `false` if * header objects will be omitted from new log files. */ bool getNeedLogHeaders() noexcept; /** Sets whether headers will be added to each newly written log file. * * @param[in] needHeaders Set to `true` to indicate that headers should be added to each * newly written log file. Set to `false` to indicate that the * header should be omitted. * @returns No return value. * * @remarks This sets whether log headers will be written out to each new log file. The * header is consumed and modified by the telemetry transmitter app to allow it * to store its progress in processing each log file. If the header is missing, * the transmitter app will simply ignore the log file. Omitting the headers * in log files allows the log output to purely just be the structured log event * messages so they can be more easily consumed wholesale by external apps. * * @note Changing this setting will only take effect the next time a new log file is written * out to disk. Disabling this will not remove the header object from an existing log * file. */ void setNeedLogHeaders(bool needHeaders) noexcept; /** Retrieves the current set of output flags for structured logging. * * @returns The current output flags for the structured logging system. These indicate how * various aspects of the logging system will function. Note that some flags may * affect whether the produced messages are compatible with the remainder of the * telemetry toolchain in Omniverse apps. By default, all output flags are off. */ omni::structuredlog::OutputFlags getOutputFlags() noexcept; /** Sets or clears one or more output flags for structured logging. * * @param[in] flagsToAdd A set of zero or more flag bits to set. These must be either * @ref omni::structuredlog::fOutputFlagNone or one or more of * the @ref omni::structuredlog::OutputFlags flags. * @param[in] flagsToRemove A set of zero or more flag bits to cleared. These must be * either @ref omni::structuredlog::fOutputFlagNone or one or * more of the @ref omni::structuredlog::OutputFlags flags. * @returns No return value. * * @remarks This sets or clears flags that affect the output from the structured logging * system. These flags are all disabled by default. These flags will take effect * the next time a message is emitted. */ void setOutputFlags(omni::structuredlog::OutputFlags flagsToAdd, omni::structuredlog::OutputFlags flagsToRemove) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline uint64_t omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi>::getHeartbeatPeriod() noexcept { return getHeartbeatPeriod_abi(); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi>::setHeartbeatPeriod(uint64_t period) noexcept { setHeartbeatPeriod_abi(period); } inline bool omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi>::getNeedLogHeaders() noexcept { return getNeedLogHeaders_abi(); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi>::setNeedLogHeaders(bool needHeaders) noexcept { setNeedLogHeaders_abi(needHeaders); } inline omni::structuredlog::OutputFlags omni::core::Generated< omni::structuredlog::IStructuredLogSettings2_abi>::getOutputFlags() noexcept { return getOutputFlags_abi(); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi>::setOutputFlags( omni::structuredlog::OutputFlags flagsToAdd, omni::structuredlog::OutputFlags flagsToRemove) noexcept { setOutputFlags_abi(flagsToAdd, flagsToRemove); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
7,196
C
44.264151
129
0.68274
omniverse-code/kit/include/omni/structuredlog/JsonTree.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 ABI safe structure for specifying structured log schemas. */ #pragma once #include "../../carb/logging/Log.h" #include "../extras/ScratchBuffer.h" #include <cstdint> #include <cstddef> namespace omni { namespace structuredlog { /** The data type contained within a JsonNode. * @note For future maintainability, do not use `default` when switching on * this enum; we'll be able to catch all the places where the new type * needs to be handled in that case. */ enum class NodeType : uint8_t { eNull, /**< No type has been set. */ eBool, /**< bool type. */ eBoolArray, /**< bool array type. */ eInt32, /**< int32_t type. This corresponds to the JSON integer type. */ eInt32Array, /**< int32_t array type. This corresponds to the JSON integer type. */ eUint32, /**< uint32_t type. This corresponds to the JSON integer type. */ eUint32Array, /**< uint32_t array type. This corresponds to the JSON integer type. */ /** int64_t type. For interoperability, we cannot store a 64 bit int directly * in JSON, so the high and low 32 bits get stores in an array [high, low]. */ eInt64, /** int64_t array type. For interoperability, we cannot store a 64 bit int * directly in JSON, so each element of this array is itself an array * [high, low], where high is the top 32 bits and low is the bottom 32 bits. */ eInt64Array, eUint64, /**< uint64_t type. stored identically to @ref NodeType::eInt64. */ eUint64Array, /**< uint64_t array type. stored identically to @ref NodeType::eInt64Array. */ eFloat64, /**< double type. This corresponds to the JSON number type. */ eFloat64Array, /**< double array type. This corresponds to the JSON number type. */ eFloat32, /**< float type. This corresponds to the JSON number type. */ eFloat32Array, /**< float array type. This corresponds to the JSON number type. */ eBinary, /**< array of bytes that will be base64 encoded into JSON. */ eString, /**< char* type. */ eStringArray, /**< char ** type. */ eObject, /**< object type. */ eObjectArray, /**< array of objects type. */ }; /** A node in a JSON structure. * This is a standard layout type for @rstref{ABI safety <abi-compatibility>}. * Do not directly write this struct; use @ref JsonBuilder to set the members * to ensure the layout is as-expected by the consumers of this struct. */ struct JsonNode { /** The version of the structure. * Headers that use this struct should static assert on its version. * Do not modify the layout of this struct without incrementing this. */ static constexpr uint32_t kVersion = 0; /** The base type to be used for enums. */ using EnumBase = uint16_t; /** The type of the @ref flags member. */ using Flag = uint8_t; /** This specifies that the value is constant. * This is used for schemas to specify whether a property is constant. * This flag has no meaning when @p type is @ref NodeType::eObject or * @ref NodeType::eObjectArray; for an object to be constant, each * property of that object must be constant. */ static constexpr Flag fFlagConst = 0x01; /** This specifies that an array has a fixed length. * This is used for a schema node in a tree to specify that an array in * the tree has a fixed length (that length is specified by @p len). * This is only valid for array types and string. * This is ignored if combined with @ref fFlagConst. */ static constexpr Flag fFlagFixedLength = 0x02; /** This specifies that the parameter is an enum type. * An enum type is stored in the data blob as an @ref EnumBase. * The @ref EnumBase is used as an index into the array of values stored * in this node. * This flag is only valid for a @ref NodeType that is an array type other * than @ref NodeType::eObjectArray. */ static constexpr Flag fFlagEnum = 0x04; /** The type of this node. * This and @ref len decide which member of @ref data is in use. */ NodeType type = NodeType::eNull; /** Behavioral flags for this node. */ Flag flags = 0; /** The length of the data array. * This is ignored for non-array and non-object types. * For @ref NodeType::eString, this is the length of the stored string (as * an optimization). * For other values of @ref type, this is the length of the array stored * in @ref data. */ uint16_t len = 0; /** The length of @ref name in bytes. */ uint16_t nameLen = 0; /* 2 bytes of padding exists here (on x86_64 at least), which may be used * for something in the future without breaking the ABI. */ /** The JSON node name. * This will be nullptr when @ref type is @ref NodeType::eObjectArray. */ char* name = nullptr; /** The union of possible values that can be used. * This may not be accessed if @ref type is @ref NodeType::eNull. */ union { /** This is in use when @ref type is @ref NodeType::eBool. */ bool boolVal; /** This is in use when @ref type is @ref NodeType::eInt32 or @ref NodeType::eInt64. */ int64_t intVal; /** This is in use when @ref type is @ref NodeType::eUint32 or @ref NodeType::eUint64. */ uint64_t uintVal; /** This is in use when @ref type is @ref NodeType::eFloat32 or @ref NodeType::eFloat64. */ double floatVal; /** This is used when @ref type is @ref NodeType::eBinary. */ uint8_t* binaryVal; /** This is in use when @ref type is @ref NodeType::eString. */ char* strVal; /** This is in use when @ref type is @ref NodeType::eBoolArray. */ bool* boolArrayVal; /** This is in use when @ref type is @ref NodeType::eInt32Array. */ int32_t* int32ArrayVal; /** This is in use when @ref type is @ref NodeType::eInt64Array. */ int64_t* int64ArrayVal; /** This is in use when @ref type is @ref NodeType::eUint32Array */ uint32_t* uint32ArrayVal; /** This is in use when @ref type is @ref NodeType::eUint64Array */ uint64_t* uint64ArrayVal; /** This is in use when @ref type is @ref NodeType::eFloat32Array. */ float* float32ArrayVal; /** This is in use when @ref type is @ref NodeType::eFloat64Array. */ double* float64ArrayVal; /** This is in use when @ref type is @ref NodeType::eStringArray. */ char** strArrayVal; /** This is in use when @ref type is @ref NodeType::eObject or * @ref NodeType::eObjectArray. * In the case where @ref type is @ref NodeType::eObject, this node * is an object and each element in @ref objVal is a property of that * object. * In the case where @ref type is @ref NodeType::eObjectArray, this * node is an object array and each element is an entry in the object * array (each entry should have type @ref NodeType::eObject). */ JsonNode* objVal; } data; }; CARB_ASSERT_INTEROP_SAFE(JsonNode); static_assert(sizeof(JsonNode) == 24, "unexpected size"); static_assert(offsetof(JsonNode, type) == 0, "struct layout changed"); static_assert(offsetof(JsonNode, flags) == 1, "struct layout changed"); static_assert(offsetof(JsonNode, len) == 2, "struct layout changed"); static_assert(offsetof(JsonNode, nameLen) == 4, "struct layout changed"); static_assert(offsetof(JsonNode, name) == 8, "struct layout changed"); static_assert(offsetof(JsonNode, data) == 16, "struct layout changed"); /** Options to do a less of a strict comparison when comparing trees. */ enum class JsonTreeCompareFuzz { /** Strict comparison: trees must be identical. * Ordering of all elements in the tree must be identical. */ eStrict, /** Ignore the ordering of constant elements. */ eNoConstOrder, /** Ignore ordering of all elements. */ eNoOrder, }; /** Perform a deep comparison of two nodes. * @param[in] a The first node to compare. * @param[in] b The second node to compare. * @param[in] fuzz How strict this comparison will be. * @returns `true` of the objects are equal. * @returns `false` if the objects differ in any ways. * * @note This assumes a properly formed @ref JsonNode. An incorrectly set len * member will likely result in a crash. */ inline bool compareJsonTrees(const JsonNode* a, const JsonNode* b, JsonTreeCompareFuzz fuzz = JsonTreeCompareFuzz::eStrict) { if (a->flags != b->flags || a->type != b->type || a->len != b->len) return false; if ((a->name == nullptr && b->name != nullptr) || (a->name != nullptr && b->name == nullptr)) return false; if (a->name != nullptr && strcmp(a->name, b->name) != 0) return false; switch (a->type) { case NodeType::eNull: return true; case NodeType::eBool: return a->data.boolVal == b->data.boolVal; case NodeType::eInt32: case NodeType::eInt64: return a->data.intVal == b->data.intVal; case NodeType::eUint32: case NodeType::eUint64: return a->data.uintVal == b->data.uintVal; case NodeType::eFloat32: case NodeType::eFloat64: return a->data.floatVal == b->data.floatVal; case NodeType::eBoolArray: return a->len == 0 || memcmp(b->data.int32ArrayVal, a->data.int32ArrayVal, a->len * sizeof(bool)) == 0; case NodeType::eUint32Array: return a->len == 0 || memcmp(b->data.uint32ArrayVal, a->data.uint32ArrayVal, a->len * sizeof(uint32_t)) == 0; case NodeType::eInt32Array: return a->len == 0 || memcmp(b->data.int32ArrayVal, a->data.int32ArrayVal, a->len * sizeof(int32_t)) == 0; case NodeType::eFloat32Array: return a->len == 0 || memcmp(b->data.float32ArrayVal, a->data.float32ArrayVal, a->len * sizeof(float)) == 0; case NodeType::eInt64Array: return a->len == 0 || memcmp(b->data.int64ArrayVal, a->data.int64ArrayVal, a->len * sizeof(int64_t)) == 0; case NodeType::eUint64Array: return a->len == 0 || memcmp(b->data.uint64ArrayVal, a->data.uint64ArrayVal, a->len * sizeof(uint64_t)) == 0; case NodeType::eFloat64Array: return a->len == 0 || memcmp(b->data.float64ArrayVal, a->data.float64ArrayVal, a->len * sizeof(double)) == 0; case NodeType::eBinary: case NodeType::eString: return a->len == 0 || memcmp(b->data.binaryVal, a->data.binaryVal, a->len) == 0; case NodeType::eStringArray: for (uint16_t i = 0; i < a->len; i++) { if ((a->data.strArrayVal[i] == nullptr && b->data.strArrayVal[i] != nullptr) || (a->data.strArrayVal[i] != nullptr && b->data.strArrayVal[i] == nullptr)) return false; if (a->data.strArrayVal[i] != nullptr && strcmp(a->data.strArrayVal[i], b->data.strArrayVal[i]) != 0) return false; } return true; case NodeType::eObject: case NodeType::eObjectArray: switch (fuzz) { case JsonTreeCompareFuzz::eStrict: for (uint16_t i = 0; i < a->len; i++) { if (!compareJsonTrees(&a->data.objVal[i], &b->data.objVal[i])) return false; } break; case JsonTreeCompareFuzz::eNoConstOrder: { extras::ScratchBuffer<bool, 256> hits; if (!hits.resize(a->len)) { // shouldn't ever happen fprintf(stderr, "failed to allocate %u bytes\n", a->len); return false; } for (size_t i = 0; i < a->len; i++) { hits[i] = false; } // first compare the variable fields in order for (uint16_t i = 0, j = 0; i < a->len; i++, j++) { // skip to the next non-constant member while ((a->data.objVal[i].flags & JsonNode::fFlagConst) != 0) { i++; } if (i >= a->len) break; // skip to the next non-constant member while ((b->data.objVal[j].flags & JsonNode::fFlagConst) != 0) { j++; } if (j >= b->len) return false; if (!compareJsonTrees(&a->data.objVal[i], &b->data.objVal[j])) return false; } // compare the constants for (uint16_t i = 0; i < a->len; i++) { if ((a->data.objVal[i].flags & JsonNode::fFlagConst) == 0) continue; for (uint16_t j = 0; j < a->len; j++) { if (!hits[j] && (b->data.objVal[j].flags & JsonNode::fFlagConst) != 0 && compareJsonTrees(&a->data.objVal[i], &b->data.objVal[j])) { hits[j] = true; break; } } } for (uint16_t i = 0; i < a->len; i++) { if ((b->data.objVal[i].flags & JsonNode::fFlagConst) != 0 && !hits[i]) return false; } } break; case JsonTreeCompareFuzz::eNoOrder: { extras::ScratchBuffer<bool, 256> hits; if (!hits.resize(a->len)) { // shouldn't ever happen fprintf(stderr, "failed to allocate %u bytes\n", a->len); return false; } for (size_t i = 0; i < a->len; i++) { hits[i] = false; } for (uint16_t i = 0; i < a->len; i++) { for (uint16_t j = 0; j < a->len; j++) { if (!hits[j] && compareJsonTrees(&a->data.objVal[i], &b->data.objVal[j])) { hits[j] = true; break; } } } for (uint16_t i = 0; i < a->len; i++) { if (!hits[i]) return false; } } break; } return true; } return false; } /** A memory allocator interface, which can be overwritten with your custom allocator */ class Allocator { public: /** The alignment that each allocation must be */ static constexpr size_t kAlignment = alignof(void*); virtual ~Allocator() { } /** Allocated memory. * @param[in] size The number of bytes to allocate. * @returns The allocated memory. * @returns nullptr if memory was not available. * @remarks This should be overwritten by custom memory allocators to use * another allocation mechanism. */ virtual void* alloc(size_t size) { return malloc(size); } /** Deallocate a previously allocated block. * @param[in] mem A block previously allocated by alloc(). */ virtual void dealloc(void* mem) { free(mem); } /** Round a size up to be aligned to @ref kAlignment. * @param[in] size The size to align. * @returns @p size rounded up to the next multiple of @ref kAlignment. */ static size_t fixupAlignment(size_t size) { if (size % Allocator::kAlignment != 0) return size + (kAlignment - (size % Allocator::kAlignment)); else return size; } }; /** An implementation of @ref Allocator which will just allocate from a * preallocated block of memory and never deallocate memory until the full * preallocated block is freed. * This is useful for something like a structured log event, where the required * size of the tree can be preallocated. */ class BlockAllocator : public Allocator { public: /** Create the allocator from a preallocated block. * @param[in] block The block of memory to allocate from. * @param[in] len The length of @p block in bytes. */ BlockAllocator(void* block, size_t len) { m_block = static_cast<uint8_t*>(block); m_left = len; } void* alloc(size_t size) override { void* m = m_block; size = fixupAlignment(size); if (size > m_left) return nullptr; m_block += size; m_left -= size; return m; } void dealloc(void* mem) override { CARB_UNUSED(mem); // leak it - m_block will be freed when we're done with this allocator } private: /** The block being allocated from. * This has m_left bytes available. */ uint8_t* m_block = nullptr; /** The number of bytes available in m_left. */ size_t m_left = 0; }; /** Free any memory allocated to a @ref JsonNode and clear it out to an empty node. * @param[inout] node The node to clear out. * This node must be {} or have had its contents set by * createObject(), createObjectArray() or setNode(). * @param[in] alloc The allocator used to allocate @p node. */ static inline void clearJsonTree(JsonNode* node, Allocator* alloc) { switch (node->type) { case NodeType::eNull: case NodeType::eBool: case NodeType::eInt32: case NodeType::eUint32: case NodeType::eInt64: case NodeType::eUint64: case NodeType::eFloat32: case NodeType::eFloat64: break; case NodeType::eString: case NodeType::eBinary: case NodeType::eBoolArray: case NodeType::eInt32Array: case NodeType::eUint32Array: case NodeType::eInt64Array: case NodeType::eUint64Array: case NodeType::eFloat32Array: case NodeType::eFloat64Array: alloc->dealloc(node->data.strVal); node->data.strVal = nullptr; break; case NodeType::eStringArray: for (uint16_t i = 0; i < node->len; i++) { alloc->dealloc(node->data.strArrayVal[i]); } alloc->dealloc(node->data.strArrayVal); node->data.strArrayVal = nullptr; break; case NodeType::eObjectArray: // object arrays allocate their elements and their elements' // properties in the same allocation for (uint16_t i = 0; i < node->len; i++) { for (uint16_t j = 0; j < node->data.objVal[i].len; j++) clearJsonTree(&node->data.objVal[i].data.objVal[j], alloc); } alloc->dealloc(node->data.objVal); node->data.objVal = nullptr; break; case NodeType::eObject: for (uint16_t i = 0; i < node->len; i++) clearJsonTree(&node->data.objVal[i], alloc); alloc->dealloc(node->data.objVal); node->data.objVal = nullptr; break; } alloc->dealloc(node->name); node = {}; } /** A temporary JsonNode object that will be cleaned up at the end of a scope. */ class TempJsonNode : public JsonNode { public: /** Create a temporary @ref JsonNode. * @param[in] alloc The allocator used to allocate this tree. */ TempJsonNode(Allocator* alloc) { m_alloc = alloc; } ~TempJsonNode() { clearJsonTree(this, m_alloc); } private: Allocator* m_alloc; }; /** Class for determining the allocation size required to build a JSON tree in a * single block of memory. * To use this, you simply track all of the items that you will store in your * tree, then you can retrieve the size that is required to store this tree. * This final size can be used to allocate a block for a @ref BlockAllocator * to allocate a tree of the exact correct size. * * @note This size calculator rounds up all sizes to the nearest alignment so * that allocator can always return properly aligned allocations. * Because of this, ordering of the track calls does not have to exactly * match the ordering of the setNode() calls. */ class JsonTreeSizeCalculator { public: /** Get the size required for the tree. * @returns The size in bytes. */ size_t getSize() { return m_count; } /** Track the root node in the tree. * @remarks Call this if you're planning on allocating the root node of the * tree, rather than keeping it as a local variable or something * like that. */ void trackRoot() { m_count += sizeof(JsonNode); } /** Track the size of a JSON object node. * @param[in] propertyCount The number of properties that JSON node has. * For example `{"a": 0, "b": 2}` is an object * with 2 properties. */ void trackObject(size_t propertyCount) { m_count += Allocator::fixupAlignment(sizeof(JsonNode) * propertyCount); } /** Track the size for a JSON array of objects * @param[in] propertyCount The number of properties that each object * element has. This implies that each element * will be an object with the same layout. * For an array of objects with varying layouts, * trackObject() would need to be called for each * element. * @param[in] len The length of the object array. * (e.g. [{}, {}] is length 2). */ void trackObjectArray(size_t propertyCount, size_t len) { m_count += Allocator::fixupAlignment(sizeof(JsonNode) * (propertyCount + 1) * len); } /** Track the size occupied by the node name. * @param[in] name The node name. * @param[in] nameLen The length of @p name including the null terminator. */ void trackName(const char* name, uint16_t nameLen) { track(name, nameLen); } /** Track the size occupied by the node name. * @param[in] name The node name. * @returns The number of bytes required to encode @p name. */ void trackName(const char* name) { track(name); } /** Track the size of a node without any associated data. * @remarks This is useful when using the @ref JsonNode structure for * defining a schema, so each node may not store a value, just * type information and a name. */ void track() { } /** Track the size of an arithmetic type node. * @param[in] value The value that will be encoded in the future. */ template <typename T> void track(T value) { CARB_UNUSED(value); static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); } /** track the size of a string array node. * @param[in] str The array of strings that will be encoded. * @param[in] len The length of array @p b. */ void track(const char* const* str, uint16_t len) { size_t size = 0; if (len == 0) return; for (uint16_t i = 0; i < len; i++) { if (str[i] != nullptr) size += Allocator::fixupAlignment(strlen(str[i]) + 1); } m_count += size + Allocator::fixupAlignment(sizeof(const char*) * len); } /** Track the size of an array node with the string length pre-calculated. * @param[in] value The array that will be used for the node. * @param[in] len The length of @p value. * If @p value is a string, this includes the null terminator. */ template <typename T> void track(const T* value, uint16_t len) { CARB_UNUSED(value); static_assert(std::is_arithmetic<T>::value, "this is only valid for primitive types"); m_count += Allocator::fixupAlignment(len * sizeof(T)); } /** Track the size of a binary blob node. * @param[in] value The array of binary data that will be used for the node. * @param[in] len The length of @p value. */ void track(const void* value, uint16_t len) { track(static_cast<const uint8_t*>(value), len); } /** Track the size of a binary blob node. * @param[in] value The array of binary data that will be used for the node. * @param[in] len The length of @p value. */ void track(void* value, uint16_t len) { track(static_cast<const uint8_t*>(value), len); } /** track the size of a string node. * @param[in] str The string to be encoded. * This string must be less than 64KiB. */ void track(const char* str) { if (str != nullptr) track(str, uint16_t(strlen(str)) + 1); } /** track the size of a string node. * @param[in] str The string to be encoded. */ void track(char* str) { track(static_cast<const char*>(str)); } /** Track the size required for a deep copy of a node. * @param[in] node The node to calculate the size for. * @note This includes the size required for the root node. */ void track(const JsonNode* node) { trackName(node->name); switch (node->type) { case NodeType::eNull: track(); break; case NodeType::eBool: track(node->data.boolVal); break; case NodeType::eInt32: case NodeType::eInt64: track(node->data.intVal); break; case NodeType::eUint32: case NodeType::eUint64: track(node->data.uintVal); break; case NodeType::eFloat32: case NodeType::eFloat64: track(node->data.floatVal); break; case NodeType::eBinary: track(node->data.binaryVal, node->len); break; case NodeType::eBoolArray: track(node->data.boolArrayVal, node->len); break; case NodeType::eInt32Array: track(node->data.uint32ArrayVal, node->len); break; case NodeType::eUint32Array: track(node->data.int32ArrayVal, node->len); break; case NodeType::eInt64Array: track(node->data.uint64ArrayVal, node->len); break; case NodeType::eUint64Array: track(node->data.int64ArrayVal, node->len); break; case NodeType::eFloat32Array: track(node->data.float32ArrayVal, node->len); break; case NodeType::eFloat64Array: track(node->data.float64ArrayVal, node->len); break; case NodeType::eString: track(node->data.strVal, node->len); break; case NodeType::eStringArray: // if you don't cast this, it doesn't infer the template correctly track(static_cast<const char* const*>(node->data.strArrayVal), node->len); break; case NodeType::eObjectArray: if (node->len > 0) trackObjectArray(node->data.objVal[0].len, node->len); for (size_t i = 0; i < node->len; i++) { for (size_t j = 0; j < node->data.objVal[i].len; j++) // if you don't cast this, it doesn't infer the template correctly track(static_cast<const JsonNode*>(&node->data.objVal[i].data.objVal[j])); } break; case NodeType::eObject: trackObject(node->len); for (size_t i = 0; i < node->len; i++) // if you don't cast this, it doesn't infer the template correctly track(static_cast<const JsonNode*>(&node->data.objVal[i])); break; } } /** Track the size required for a deep copy of a node. * @param[in] node The node to calculate the size for. * @note This includes the size required for the root node. */ void track(JsonNode* node) { return track(static_cast<const JsonNode*>(node)); } private: size_t m_count = 0; }; /** A class to build JSON trees using @ref JsonNode structs. * These functions all expect an empty node to have been passed in, which * speeds up tree creation by avoiding unnecessary clearNode() calls. * * @note These functions do expect that memory allocation may fail. * This is used in the unit tests to verify that the node size * calculator is correct. */ class JsonBuilder { public: /** Constructor. * @param[in] alloc The allocator that will be used to create new @ref JsonNode objects. */ JsonBuilder(Allocator* alloc) { m_alloc = alloc; } /** Create a JSON object node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] propertyCount The number of properties that JSON node has. * For example `{"a": 0, "b": 2}` is an object * with 2 properties. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool createObject(JsonNode* node, uint16_t propertyCount) { void* b; CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); b = m_alloc->alloc(propertyCount * sizeof(*node->data.objVal)); if (b == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (node = '%s', requested %zu bytes)", node->name, propertyCount * sizeof(*node->data.objVal)); return false; } node->data.objVal = new (b) JsonNode[propertyCount]; node->len = propertyCount; node->type = NodeType::eObject; CARB_ASSERT((uintptr_t(node->data.objVal) & (alignof(JsonNode) - 1)) == 0); return true; } /** Create a JSON node that is an array of objects. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] propertyCount The number of properties that each object * element has. This implies that each element * will be an object with the same layout. * For an array of objects with varying layouts, * calcJsonObjectSize() would need to be called * for each element. * @param[in] len The length of the object array. * When defining an object array in a schema, * you should set this length to 1, then * specify the object layout in that element. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool createObjectArray(JsonNode* node, uint16_t propertyCount, uint16_t len) { void* b; CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); // allocate it all as one array b = m_alloc->alloc((len * (1 + propertyCount)) * sizeof(*node->data.objVal)); if (b == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (node = '%s', requested %zu bytes)", node->name, (len * (1 + propertyCount)) * sizeof(*node->data.objVal)); return false; } node->data.objVal = new (b) JsonNode[len]; CARB_ASSERT((uintptr_t(node->data.objVal) & (alignof(JsonNode) - 1)) == 0); b = static_cast<uint8_t*>(b) + sizeof(JsonNode) * len; for (size_t i = 0; i < len; i++) { node->data.objVal[i].data.objVal = new (b) JsonNode[propertyCount]; CARB_ASSERT((uintptr_t(node->data.objVal[i].data.objVal) & (alignof(JsonNode) - 1)) == 0); b = static_cast<uint8_t*>(b) + sizeof(JsonNode) * propertyCount; node->data.objVal[i].len = propertyCount; node->data.objVal[i].type = NodeType::eObject; } node->len = len; node->type = NodeType::eObjectArray; return true; } /** Set a bool node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] b The boolean value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, bool b) { return setNode(node, b, &node->data.boolVal, NodeType::eBool); } /** Set a bool array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The boolean array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const bool* data, uint16_t len) { return setNode(node, data, len, &node->data.boolArrayVal, NodeType::eBoolArray); } /** Set a 32 bit integer node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] i The integer value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, int32_t i) { return setNode(node, i, &node->data.intVal, NodeType::eInt32); } /** Set a 32 bit integer array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The integer array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const int32_t* data, uint16_t len) { return setNode(node, data, len, &node->data.int32ArrayVal, NodeType::eInt32Array); } /** Set an unsigned 32 bit integer node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] u The integer value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, uint32_t u) { return setNode(node, u, &node->data.uintVal, NodeType::eUint32); } /** Set an unsigned 32 bit integer array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The integer array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const uint32_t* data, uint16_t len) { return setNode(node, data, len, &node->data.uint32ArrayVal, NodeType::eUint32Array); } /** Set a 64 bit integer node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] i The integer value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, int64_t i) { return setNode(node, i, &node->data.intVal, NodeType::eInt64); } /** Set a 64 bit integer array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The integer array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const int64_t* data, uint16_t len) { return setNode(node, data, len, &node->data.int64ArrayVal, NodeType::eInt64Array); } /** Set an unsigned 64 bit integer node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] u The integer value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, uint64_t u) { return setNode(node, u, &node->data.uintVal, NodeType::eUint64); } /** Set an unsigned 64 bit integer array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The integer array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const uint64_t* data, uint16_t len) { return setNode(node, data, len, &node->data.uint64ArrayVal, NodeType::eUint64Array); } /** Set a float node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] f The float value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, float f) { return setNode(node, f, &node->data.floatVal, NodeType::eFloat32); } /** Set a float array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The double array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const float* data, uint16_t len) { return setNode(node, data, len, &node->data.float32ArrayVal, NodeType::eFloat32Array); } /** Set a double node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] f The double value to set on this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, double f) { return setNode(node, f, &node->data.floatVal, NodeType::eFloat64); } /** Set a double array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The double array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const double* data, uint16_t len) { return setNode(node, data, len, &node->data.float64ArrayVal, NodeType::eFloat64Array); } /** Set a string array node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] data The string array to set on this node. * This is copied into the node. * @param[in] len The length of the array @p data. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const char* const* data, uint16_t len) { CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); if (len == 0) { node->data.strArrayVal = nullptr; node->type = NodeType::eStringArray; node->len = len; return true; } // allocate each of the strings individually to avoid having to create // a temporary buffer of string lengths or call strlen() multiple times // on each string node->data.strArrayVal = static_cast<char**>(m_alloc->alloc(len * sizeof(*node->data.strArrayVal))); CARB_ASSERT((uintptr_t(node->data.strArrayVal) & (alignof(char*) - 1)) == 0); if (node->data.strArrayVal == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (node = '%s', requested %zu bytes)", node->name, len * sizeof(*node->data.strArrayVal)); return false; } for (uint16_t i = 0; i < len; i++) { if (data[i] == nullptr) { node->data.strArrayVal[i] = nullptr; } else { size_t s = strlen(data[i]) + 1; node->data.strArrayVal[i] = static_cast<char*>(m_alloc->alloc(s)); if (node->data.strArrayVal[i] == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (requested %zu bytes)", s); for (uint16_t j = 0; j < i; j++) m_alloc->dealloc(node->data.strArrayVal[j]); m_alloc->dealloc(node->data.strArrayVal); node->data.strArrayVal = nullptr; return false; } memcpy(node->data.strArrayVal[i], data[i], s); } } node->type = NodeType::eStringArray; node->len = len; return true; } /** Set a string node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] str The string to copy into this node. * @param[in] len The length of @p str including the null terminator. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const char* str, uint16_t len) { return setNode(node, str, len, &node->data.strVal, NodeType::eString); } /** Set a string node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] str The string to copy into this node. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. * @returns `false` if @p str was longer than 64KiB. */ bool setNode(JsonNode* node, const char* str) { size_t len; CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); if (str == nullptr) return setNode(node, str, 0); len = strlen(str) + 1; if (len > UINT16_MAX) { CARB_LOG_ERROR("string length exceeds 64KiB maximum (node = '%s', %zu characters, str = '%64s...')", node->name, len, str); return false; } return setNode(node, str, uint16_t(len)); } /** Set a binary blob node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] blob The data to copy into this node. * @param[in] len The number of bytes of data in @p blob. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const void* blob, uint16_t len) { return setNode<uint8_t>(node, static_cast<const uint8_t*>(blob), len, &node->data.binaryVal, NodeType::eBinary); } /** Set a binary blob node. * @param[inout] node The node to create. * This node must be equal to {} when passed in. * @param[in] blob The data to copy into this node. * @param[in] len The number of bytes of data in @p blob. * * @returns `true` if the node was successfully created. * @returns `false` if a memory allocation failed. */ bool setNode(JsonNode* node, const uint8_t* blob, uint16_t len) { return setNode<uint8_t>(node, blob, len, &node->data.binaryVal, NodeType::eBinary); } /** Set the name of a JSON node. * @param[inout] node The node to modify. * The previous name will be cleared out, if any. * @param[in] name The name to copy into the node. * This may be nullptr to just free the previous name. * @param[in] nameLen The length of @p name, including the null terminator. * This must be 0 if @p name is nullptr. * * @returns `true` if the node's name was successfully copied. * @returns `false` if a memory allocation failed. */ bool setName(JsonNode* node, const char* name, uint16_t nameLen) { m_alloc->dealloc(node->name); node->name = nullptr; if (nameLen == 0) return true; node->name = static_cast<char*>(m_alloc->alloc(nameLen)); if (node->name == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (name = '%s', requested %" PRIu16 " bytes)", name, nameLen); return false; } node->nameLen = nameLen; memcpy(node->name, name, nameLen); return true; } /** Set the name of a JSON node. * @param[inout] node The node to modify. * The previous name will be cleared out, if any. * @param[in] name The name to copy into the node. * This may be nullptr to just free the previous name. * * @returns `true` if the node's name was successfully copied. * @returns `false` if a memory allocation failed. */ bool setName(JsonNode* node, const char* name) { if (name == nullptr) return setName(node, nullptr, 0); return setName(node, name, uint16_t(strlen(name) + 1)); } /** Perform a deep copy of a node. * @param[in] node The node to deep copy. * This node must be equal to {} when passed in. * @param[inout] out The new node that was created. * @returns The deep copied node. */ bool deepCopy(const JsonNode* node, JsonNode* out) { bool result = true; CARB_ASSERT(out->type == NodeType::eNull); CARB_ASSERT(out->len == 0); if (!setName(out, node->name)) return false; out->flags = node->flags; switch (node->type) { case NodeType::eNull: break; case NodeType::eBool: result = setNode(out, node->data.boolVal); break; case NodeType::eBoolArray: result = setNode(out, node->data.boolArrayVal, node->len); break; case NodeType::eInt32: result = setNode(out, int32_t(node->data.intVal)); break; case NodeType::eInt64: result = setNode(out, node->data.intVal); break; case NodeType::eInt32Array: result = setNode(out, node->data.int32ArrayVal, node->len); break; case NodeType::eUint32: result = setNode(out, uint32_t(node->data.uintVal)); break; case NodeType::eUint64: result = setNode(out, node->data.uintVal); break; case NodeType::eUint32Array: result = setNode(out, node->data.uint32ArrayVal, node->len); break; case NodeType::eInt64Array: result = setNode(out, node->data.int64ArrayVal, node->len); break; case NodeType::eUint64Array: result = setNode(out, node->data.uint64ArrayVal, node->len); break; case NodeType::eFloat32: result = setNode(out, float(node->data.floatVal)); break; case NodeType::eFloat64: result = setNode(out, node->data.floatVal); break; case NodeType::eFloat32Array: result = setNode(out, node->data.float32ArrayVal, node->len); break; case NodeType::eFloat64Array: result = setNode(out, node->data.float64ArrayVal, node->len); break; case NodeType::eString: result = setNode(out, node->data.strVal, node->len); break; case NodeType::eStringArray: result = setNode(out, node->data.strArrayVal, node->len); break; case NodeType::eBinary: result = setNode(out, node->data.binaryVal, node->len); break; case NodeType::eObjectArray: if (node->len == 0) break; result = createObjectArray(out, node->data.objVal[0].len, node->len); if (!result) break; for (uint16_t i = 0; i < node->len; i++) { out->data.objVal[i].flags = node->data.objVal[i].flags; for (uint16_t j = 0; result && j < node->data.objVal[i].len; j++) { result = deepCopy(&node->data.objVal[i].data.objVal[j], &out->data.objVal[i].data.objVal[j]); } } break; case NodeType::eObject: result = createObject(out, node->len); if (!result) break; for (size_t i = 0; i < node->len; i++) { deepCopy(&node->data.objVal[i], &out->data.objVal[i]); } break; } if (!result) clearJsonTree(out, m_alloc); return result; } /** Set the flags on a @ref JsonNode. * @param[in] node The node to update the flags on. * This node must have already had its value and length set. * This may not be nullptr. * @param[in] flags The flags to set on @p node. * * @tparam failOnNonFatal If this is set to true, the function will return * false when a non-fatal flag error occurred. * This is intended for testing. * The behavior is not changed otherwise by this flag. * The only fatal cases are: passing in unknown * flags, setting an enum flag on an incorrect type * and setting an enum flag on an empty array. * * @returns `true` if the flags set were valid. * @returns `false` if the flags set were invalid for the given node. */ template <bool failOnNonFatal = false> static bool setFlags(JsonNode* node, JsonNode::Flag flags) { constexpr JsonNode::Flag fixedLengthConst = JsonNode::fFlagConst | JsonNode::fFlagFixedLength; constexpr JsonNode::Flag constEnum = JsonNode::fFlagEnum | JsonNode::fFlagConst; constexpr JsonNode::Flag validFlags = JsonNode::fFlagConst | JsonNode::fFlagFixedLength | JsonNode::fFlagEnum; bool result = true; CARB_ASSERT(node != nullptr); // filter out unknown flags because they pose an ABI risk if ((flags & ~validFlags) != 0) { CARB_LOG_ERROR("unknown flags were used %02x (node = '%s')", flags & ~validFlags, node->name); return false; } // a node cannot be fixed length and constant if ((flags & ~fixedLengthConst) == fixedLengthConst) { CARB_LOG_ERROR("attempted to set node to be both const and fixed length (node = '%s')", node->name); result = !failOnNonFatal; } if ((flags & constEnum) == constEnum) { CARB_LOG_ERROR("a node cannot be both constant and an enum (node = '%s')", node->name); flags &= ~JsonNode::fFlagConst; result = !failOnNonFatal; } if ((flags & JsonNode::fFlagEnum) != 0 && node->len == 0) { CARB_LOG_ERROR("an empty array can not be made into an enum (node = '%s')", node->name); return false; } // check for invalid enum type usage switch (node->type) { case NodeType::eNull: case NodeType::eBool: case NodeType::eInt32: case NodeType::eUint32: case NodeType::eInt64: case NodeType::eUint64: case NodeType::eFloat64: case NodeType::eFloat32: case NodeType::eObject: case NodeType::eObjectArray: case NodeType::eBinary: case NodeType::eString: if ((flags & JsonNode::fFlagEnum) != 0) { CARB_LOG_ERROR("an enum type must be on a non-object array type (node = '%s')", node->name); return false; } break; case NodeType::eBoolArray: case NodeType::eInt32Array: case NodeType::eUint32Array: case NodeType::eInt64Array: case NodeType::eUint64Array: case NodeType::eFloat64Array: case NodeType::eFloat32Array: case NodeType::eStringArray: // arrays can be const or fixed length break; } // check for invalid const or fixed length usage switch (node->type) { case NodeType::eNull: case NodeType::eBool: case NodeType::eInt32: case NodeType::eUint32: case NodeType::eInt64: case NodeType::eUint64: case NodeType::eFloat64: case NodeType::eFloat32: // fixed length is only valid on arrays if ((flags & JsonNode::fFlagFixedLength) != 0) { CARB_LOG_ERROR("fixed length cannot be set on a scalar node (node = '%s')", node->name); result = !failOnNonFatal; } break; case NodeType::eObject: if ((flags & JsonNode::fFlagConst) != 0) { CARB_LOG_ERROR("const is meaningless on an object node (node = '%s')", node->name); result = !failOnNonFatal; } if ((flags & JsonNode::fFlagFixedLength) != 0) { CARB_LOG_ERROR("const is meaningless on an object node (node = '%s')", node->name); result = !failOnNonFatal; } break; case NodeType::eObjectArray: if ((flags & JsonNode::fFlagConst) != 0) { CARB_LOG_ERROR("const is meaningless on an object array (node = '%s')", node->name); result = !failOnNonFatal; } break; case NodeType::eBinary: case NodeType::eString: case NodeType::eBoolArray: case NodeType::eInt32Array: case NodeType::eUint32Array: case NodeType::eInt64Array: case NodeType::eUint64Array: case NodeType::eFloat64Array: case NodeType::eFloat32Array: case NodeType::eStringArray: // arrays can be const or fixed length break; } node->flags = flags; return result; } private: template <typename T0, typename T1> bool setNode(JsonNode* node, T0 value, T1* dest, NodeType type) { CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); node->len = 1; node->type = type; *dest = value; return true; } template <typename T> bool setNode(JsonNode* node, const T* data, uint16_t len, T** dest, NodeType type) { CARB_ASSERT(node->type == NodeType::eNull); CARB_ASSERT(node->len == 0); if (len == 0) { *dest = nullptr; node->type = type; node->len = len; return true; } *dest = static_cast<T*>(m_alloc->alloc(len * sizeof(**dest))); if (*dest == nullptr) { CARB_LOG_ERROR("allocator ran out of memory (requested %zu bytes)", len * sizeof(**dest)); return false; } CARB_ASSERT((uintptr_t(*dest) & (alignof(bool) - 1)) == 0); node->type = type; node->len = len; memcpy(*dest, data, len * sizeof(*data)); return true; } Allocator* m_alloc; }; } // namespace structuredlog } // namespace omni
60,463
C
34.990476
123
0.540827
omniverse-code/kit/include/omni/structuredlog/IStructuredLogSettings.gen.h
// Copyright (c) 2021-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/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Structured log settings interface. This allows a host app to modify some behavior of the * structured log system for the process or to retrieve information about the current settings. * These settings control features such as the event queue size, log rotation, event ID * generation, the output log path, and the user ID. Most of the default settings should be * sufficient for most apps with the exception of the user ID. For host apps that use at * least one non-anonymized schema the only settings that must be set is the user ID. * * This interface object can be acquired either by requesting it from the type factory or * by casting an IStructuredLog object to this type. */ template <> class omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi> : public omni::structuredlog::IStructuredLogSettings_abi { public: OMNI_PLUGIN_INTERFACE("omni::structuredlog::IStructuredLogSettings") /** Retrieves the current event queue size. * * @returns The current size of the event queue buffer in bytes. Note that once the first * event message is sent, the event queue will be running and this will continue * to return the 'active' size of the event queue regardless of any new size that * is passed to @ref omni::structuredlog::IStructuredLogSettings::setEventQueueSize(). * Any new size will only be made active once the event queue is stopped with * @ref omni::structuredlog::IStructuredLogControl::stop(). The default size is 2MiB. * * @thread_safety This call is thread safe. */ size_t getEventQueueSize() noexcept; /** Retrieves the current maximum log file size. * * @returns The current maximum log file size in bytes. This helps to control when log files * get rotated out and started anew for the process. The number of old logs that * are kept is controlled by the log retention count. The default size is 50MB. * * @thread_safety This call is thread safe. */ int64_t getLogSizeLimit() noexcept; /** Retrieves the current log retention count. * * @returns The maximum number of log files to retain when rotating log files. When a new * log is rotated out, the oldest one that is beyond this count will be deleted. * The default is 3. * * @thread_safety This call is thread safe. */ size_t getLogRetentionCount() noexcept; /** Retrieves the current event identifier mode. * * @returns The current event identifier mode. The default is @ref omni::structuredlog::IdMode::eFastSequential. * * @thread_safety This call is thread safe. */ omni::structuredlog::IdMode getEventIdMode() noexcept; /** Retrieves the current event identifier type. * * @returns The current event identifier type. The default is @ref omni::structuredlog::IdType::eUuid. * * @thread_safety This call is thread safe. */ omni::structuredlog::IdType getEventIdType() noexcept; /** Retrieves the current log output path. * * @returns The path that log files will be written to. This defaults to the launcher app's * default log directory. The host app should override that if that location is * not suitable. * * @thread_safety This call is thread safe to retrieve the path string. However, the string * itself may become invalidated after return if the log output path is * changed with a call to @ref omni::structuredlog::IStructuredLogSettings::setLogOutputPath(). * It is * the host app's responsibility to ensure the log output path is not being * changed while this string is being used. The returned string generally * should not be cached anywhere. It should be retrieved from here any time * it is needed. */ const char* getLogOutputPath() noexcept; /** Retrieves the default log name if any has been set. * * @returns The default log file name that will be used to output all events that are not * explicitly marked with the @ref omni::structuredlog::fEventFlagUseLocalLog flag. * This name will include the log output path as set by * @ref omni::structuredlog::IStructuredLogSettings::getLogOutputPath(). * @returns `nullptr` if no default log name has been set with * @ref omni::structuredlog::IStructuredLogSettings::setLogDefaultName() * or the default log name has been cleared. * * @thread_safety This call itself is thread safe. However, the returned string is only * valid until either the log path or the default log name changes. It is * the caller's responsibility to ensure the returned string is used safely. */ const char* getLogDefaultName() noexcept; /** Retrieves the log path that a given event will be written to. * * @param[in] eventId The ID of the event to retrieve the log path for. This must be the * same ID used when the event was registered. This may also be * @ref omni::structuredlog::kDefaultLogPathEvent to retrieve the * path for the default log. * @returns The name and path of the log file that the requested event would go to if it * were emitted with current settings. * @returns the name and path of the default log file if kDefaultLogPathEvent is used for * for the event ID. * @returns `nullptr` if the given event ID is unknown or kDefaultLogPathEvent was used * and no default log name has been set. * * @thread_safety This call itself is thread safe. However, the returned string is only * valid until either the log path or the default log name changes. It is * the caller's responsibility to ensure the returned string is used safely. */ const char* getLogPathForEvent(omni::structuredlog::EventId eventId) noexcept; /** Retrieves the current user ID. * * @returns The current user ID. This may be a user name or user identification number. * The specific format and content is left entirely up to the host app itself. * By default, the user ID will either be the user ID listed in the privacy * settings file if present, or a random number if the user ID setting is not * present. When a random number is used for the user ID, it is useful for * anonymizing user event messages. * * @thread_safety This call is thread safe to retrieve the user ID. However, the string * itself may become invalidated after return if the user ID is changed with * a call to to @ref omni::structuredlog::IStructuredLogSettings::setUserId(). * It is the host app's responsibility to ensure the user ID is not being changed while this * string is being used. The returned string generally should not be cached * anywhere. It should be retrieved from here any time it is needed. */ const char* getUserId() noexcept; /** Retrieves the current session ID. * * @returns The identifier for the current session if the current privacy settings allow it. * * @remarks This retrieves the session ID for the current structured log session. This ID is * chosen when the structured log session starts and remains constant for its * lifetime. */ omni::structuredlog::SessionId getSessionId() noexcept; /** Sets the new event queue buffer size. * * @param[in] sizeInBytes the new event queue buffer size in bytes to use. This will be * silently clamped to an acceptable minimum size. The default is * 2MiB. * @returns No return value. * * @remarks This sets the new event queue buffer size. A larger buffer allows more events * to be sent and processed simultaneously in an app. If the buffer ever fills * up, events may be dropped if they cannot be processed fast enough. For host apps * that infrequently send small events, some memory can be saved by reducing this * buffer size. However, host apps that need to be able to send messages frequently, * especially simultaneously from multiple threads, should use a larger buffer size * to allow the event queue to keep up with the incoming event demand. * * @remarks Once the event queue is running (ie: the first message has been sent), changing * its size will cause a second queue to be created at the new size. The old queue * will be flushed and the new queue will be made active. There will be a short * period where two queues will be running simultaneously. Any new events that * are queued during this period will be added to the new queue. There is no need * to stop the old queue before changing the size, this will be handled * automatically. Note that during one of these queue transitions there may be * a short period where omni::structuredlog::getEventQueueSize() may return the * new queue's size even if the old queue is still active. * * @note Changing the queue size frequently will lead to stalls in the processing pipeline. * Generally the queue size should be set once on startup of an app and left at that * configured size for the process' lifetime. * * @thread_safety This call is thread safe. */ void setEventQueueSize(size_t sizeInBytes) noexcept; /** Sets the log size limit. * * @param[in] limitInBytes The new log size limit in bytes. This controls the maximum * size a log file can get up to before it is rotated out and * a new log is started. This will be silently clamped to an * acceptable minimum size. The default is 50MiB. * The minimum size limit is 256KiB. * @returns No return value. * * @remarks This sets the log size limit. When a log reaches (approximately) this size, * it will be rotated out and a new log file started. The number of old log files * that are kept is controlled by the log retention count. * * @thread_safety This call is thread safe. */ void setLogSizeLimit(int64_t limitInBytes) noexcept; /** Sets the log retention count. * * @param[in] count The maximum number of old log files to maintain. When a log file * grows beyond the current size limit, it will be renamed and a new * log opened with the original name. The oldest log file may be * deleted if there are more logs than this count. The default is 3. * @returns No return value. * * @thread_safety This call is thread safe. */ void setLogRetentionCount(size_t count) noexcept; /** Sets the current event identifier mode and type. * * @param[in] mode The new identifier mode to use. This will take effect on the next * event that is sent. The default is IdMode::eFastSequential. * @param[in] type The new identifier type to use. This will take effect on the next * event that is sent. The default is IdType::eUuid. * @returns No return value. * * @thread_safety This call is thread safe. */ void setEventIdMode(omni::structuredlog::IdMode mode, omni::structuredlog::IdType type) noexcept; /** Sets the new log output path. * * @param[in] path The new log file path to use. This may not be an empty string. The * default is the Launcher app's expected log file path. This may be * either a relative or absolute path. However, note that if this is * relative, the location of the log files may change if the process's * current working directory ever changes. It is highly suggested that * only absolute paths be used. This may also be * @ref omni::structuredlog::kDefaultLogPathName or nullptr to set the * log output path back to its default location. * @returns No return value. * * @remarks This changes the log file location for the calling process. The log file * locations for all registered schemas will be updated as well. If a schema has * been set to keep its log file open, it will be closed at this point (if already * open). The next event that is written to the log file will open a new log at * the new location. The old log file (if any) will not be moved from the previous * location. * * @note There is still a possible race condition with changing the log directory if events * are pending for processing. If the log file had been opened to write out a message * at the same time this is changing the log path, the change in log path will not take * effect until the next event message is being processed. * * @thread_safety This call is thread safe. However, it is the caller's responsibility to * ensure that no other host thread is simultaneously operating on the log * output path string returned from * @ref omni::structuredlog::IStructuredLogSettings::getLogOutputPath() * and that nothing else has cached that returned string since it could become * invalidated here. */ void setLogOutputPath(const char* path) noexcept; /** Sets the new default log name to use for message output. * * @param[in] name The new default name to set for the message log file. This may be * an empty string or nullptr to restore the default behavior of writing * each new message to its own schema's log file. This should just be * the name of the file and not include any path components. This may * also be one of the special values `/dev/stdout` or `/dev/stderr` to * send the output to only the stdout or stderr streams. In this case, * all events are output to these streams even if a given schema uses * the `fSchemaFlagUseLocalLog` or event uses the `fEventFlagUseLocalLog` * flag. Otherwise, if a filename is given and this name contains any * path components (ie: a '/'), setting the default log name will fail. * The log output path should be set using * @ref omni::structuredlog::IStructuredLogSettings::setLogOutputPath() instead. * If this name does not have a file * extension, a ".log" extension will be added. If the ".log" extension * is not desired, this may be suppressed by ending the name in ".". In * this case, the final trailing "." will be removed from the name. This * name may also contain the token '${pid}' that will be replaced by the * current process ID. * @returns No return value. * * @remarks This sets the new default log file name. When set to a valid file name, all * messages coming from events that do not use the @ref omni::structuredlog::fEventFlagUseLocalLog flag * will be written to the log file using this name in the current log output * directory. When either this name or the log output directory changes, any * open log files will be closed and reopened under the new name and path when * the next event is written. * * @note When log rotation occurs, the rotation number is inserted before the file extension * (e.g. `filename.ext` is rotated to `filename.1.ext`). * If no extension is detected, the number is just appended to the file name. * A file extension is detected with the following regex: `\..{0,4}$`. */ void setLogDefaultName(const char* name) noexcept; /** Sets the user ID to use in messages. * * @param[in] userId The user ID to use with all event messages going forward. This may * not be nullptr or an empty string. The default is a random number. * @returns No return value. * * @remarks This sets the user ID to be used in the 'source' property of all event messages * going forward. This will not affect the user ID of any messages that are * currently being processed at the time of this call. This will affect all pending * messages that are not being immediately processed however. Only the host app * should set this user ID. External plugins and extensions should never change the * user ID. * * @thread_safety This call is thread safe. However, it is the caller's responsibility to * ensure that no other host thread is simultaneously operating on the user * ID string returned from @ref omni::structuredlog::IStructuredLogSettings::getUserId() and that * nothing else has cached that returned string since it could become * invalidated here. */ void setUserId(const char* userId) noexcept; /** Attempts to load the privacy settings file. * * @returns `true` if the privacy settings file was successfully loaded. * @returns `false` if the privacy settings file could not be loaded. This failure may be * caused by the file being missing, failing to open the file due to permissions, * failing to allocate memory to read in the file, the file not being formatted * correctly as a TOML file, or failing to merge the new values into the settings * registry. * * @remarks This will attempt to load the privacy settings file for the current user. Regardless * of whether the file is successfully loaded, appropriate defaults will always be set * for each of the expected privacy settings (as long as the ISettings interface is * available). * * @note This expects that some other system has already found and attempted to load the * plugin that implements the ISettings interface. */ bool loadPrivacySettings() noexcept; /** Checks app settings to see if any schemas or events should be disabled or enabled. * * @returns `true` if the settings registry was successfully checked for enable or disable * states. Returns `false` if the \ref carb::settings::ISettings or \ref carb::dictionary::IDictionary * plugins have not been loaded yet. * * @remarks This checks the settings registry to determine if any schemas or events should * be disabled initially. The keys in the settings registry that will be looked * at are under @ref omni::structuredlog::kSchemasStateListSetting, * @ref omni::structuredlog::kEventsStateListSetting, * @ref omni::structuredlog::kEventsStateArraySetting, * and @ref omni::structuredlog::kSchemasStateArraySetting. Each of these parts * of the settings registry expects the schema or event name to be specified in * a different way. Once the settings have been loaded, they are cached internally * and will be used as the initial state of any newly registered schemas or events. * Any state changes to events or schemas after these settings are cached can still * be done programmatically with @ref omni::structuredlog::IStructuredLog::setEnabled(). */ bool enableSchemasFromSettings() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline size_t omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getEventQueueSize() noexcept { return getEventQueueSize_abi(); } inline int64_t omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getLogSizeLimit() noexcept { return getLogSizeLimit_abi(); } inline size_t omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getLogRetentionCount() noexcept { return getLogRetentionCount_abi(); } inline omni::structuredlog::IdMode omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getEventIdMode() noexcept { return getEventIdMode_abi(); } inline omni::structuredlog::IdType omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getEventIdType() noexcept { return getEventIdType_abi(); } inline const char* omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getLogOutputPath() noexcept { return getLogOutputPath_abi(); } inline const char* omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getLogDefaultName() noexcept { return getLogDefaultName_abi(); } inline const char* omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getLogPathForEvent( omni::structuredlog::EventId eventId) noexcept { return getLogPathForEvent_abi(eventId); } inline const char* omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getUserId() noexcept { return getUserId_abi(); } inline omni::structuredlog::SessionId omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::getSessionId() noexcept { return getSessionId_abi(); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setEventQueueSize(size_t sizeInBytes) noexcept { setEventQueueSize_abi(sizeInBytes); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setLogSizeLimit(int64_t limitInBytes) noexcept { setLogSizeLimit_abi(limitInBytes); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setLogRetentionCount(size_t count) noexcept { setLogRetentionCount_abi(count); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setEventIdMode( omni::structuredlog::IdMode mode, omni::structuredlog::IdType type) noexcept { setEventIdMode_abi(mode, type); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setLogOutputPath(const char* path) noexcept { setLogOutputPath_abi(path); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setLogDefaultName(const char* name) noexcept { setLogDefaultName_abi(name); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::setUserId(const char* userId) noexcept { setUserId_abi(userId); } inline bool omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::loadPrivacySettings() noexcept { return loadPrivacySettings_abi(); } inline bool omni::core::Generated<omni::structuredlog::IStructuredLogSettings_abi>::enableSchemasFromSettings() noexcept { return enableSchemasFromSettings_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
25,166
C
51.213693
133
0.652468
omniverse-code/kit/include/omni/structuredlog/IStructuredLogExtraFields.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. // /** @file * @brief Interface to manage extra CloudEvent fields in all structured log messages. */ #pragma once #include "StructuredLogCommon.h" #include "../core/IObject.h" #include <omni/String.h> namespace omni { namespace structuredlog { class IStructuredLogExtraFields; /** Base type for flags that control how extra field flags are specified or retrieved in * omni::structuredlog::IStructuredLogExtraFields::getExtraCloudEventField() and * omni::structuredlog::IStructuredLogExtraFields::setExtraCloudEventField(). */ using ExtraFieldFlags = uint32_t; /** Value to indicate that no special flags are being specified. */ constexpr ExtraFieldFlags fExtraFieldFlagNone = 0; // ***************************** IStructuredLogExtraFields interface ****************************** /** Interface to manage extra CloudEvent fields to be included in each emitted message. This * allows for fields to be added and removed as needed. It also allows existing registered * fields to be enumerated at any given time. An extra field is a key/value pair that is * included at the top level of the JSON object for each message that follows. Only string * values are allowed for each key. */ class IStructuredLogExtraFields_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.structuredlog.IStructuredLogExtraFields")> { protected: /** Adds, modifies, or removes an extra field key/value pair. * * @param[in] fieldName The name of the field to add, modify or remove. This may not be * `nullptr` or and empty string. The field name must only contain * alphabetic, numeric, or underscore ASCII characters. Any * characters outside these will cause the field to not be updated. * Further, this may not be one of the reserved CloudEvent field * names such as "specversion", "data", "time", "source", "session", * "dataschema", "type", or "subject". * @param[in] value The new value to set for the requested extra field. This may be * `nullptr` to indicate that the named field should be removed. * The value string may include any characters, but should be limited * to a small number of characters (ideally less than 64 characters). * @param[in] flags Flags to control how the new value is added, modified, or removed. * Currently no flags are defined. This must be set to * @ref omni::structuredlog::fExtraFieldFlagNone. * @returns `true` if the requested extra field is successfully added, modified, or removed. * Returns `false` if an invalid field name is given, or the operation could not * be completed for any reason. * * @remarks This adds, modifies, or removes a registered extra field and value. Any extra * fields that are registered at the time a message is emitted will be added to the * message on output. At least for the first version of this interface it is * expected that extra fields be largely static. * * @thread_safety This call is thread safe. */ virtual bool setValue_abi(OMNI_ATTR("c_str, in, not_null") const char* fieldName, OMNI_ATTR("c_str, in, not_null") const char* value, ExtraFieldFlags flags) noexcept = 0; }; } // namespace structuredlog } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IStructuredLogExtraFields.gen.h" // insert custom API functions here. /** @copydoc omni::structuredlog::IStructuredLogExtraFields_abi */ class omni::structuredlog::IStructuredLogExtraFields : public omni::core::Generated<omni::structuredlog::IStructuredLogExtraFields_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IStructuredLogExtraFields.gen.h"
4,539
C
46.291666
116
0.662701
omniverse-code/kit/include/omni/structuredlog/StructuredLogStandalone.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. // /** @file * @brief Helper header to be able to use the `omni.structuredlog.plugin` plugin in a standalone * mode. When using this mode, the rest of the Carbonite framework is not necessary. * Only the single module `omni.structuredlog.plugin` library will be needed. The main * feature of this header is the `omni::structuredlog::StructuredLogStandalone` helper * class. This manages loading the structured log library, registers all schemas for * the calling module, and allows access to the supported structured log interfaces. * * @note In order to use the structured logging system in standalone mode, this header must * be included instead of any other structured log headers. This header will pull in * all other structured log interface headers that are supported in standalone mode. * Other structured log headers are neither guaranteed to compile nor function as * expected in a non-Carbonite app. * * @note It is left up to the host app to handle launching the telemetry transmitter app * if that is needed. When used in standalone mode in a non-Carbonite app, this header * is only intended to provide the functionality for emitting log messages. The host * app can either rely on another external Omniverse app to launch the transmitter for * it, or launch it manually if needed. */ #pragma once #define STRUCTUREDLOG_STANDALONE_MODE 1 #include "../../carb/Defines.h" #include "IStructuredLog.h" #include "IStructuredLogSettings.h" #include "IStructuredLogControl.h" namespace omni { namespace structuredlog { /** Helper class to provide structured log functionality in non-Carbonite based apps. This * provides loading and shutdown functionality for the library and also allows for some * common setup in one easy call. This class is intended to be able to gracefully fail * if the structured log plugin isn't available or couldn't be loaded for any reason. * As long as the init() method returns `true`, it can be assumed that all functionality * and features are present and available. * * Once initialized, this object doesn't necessarily need to be interacted with directly * any further. As long as the object exists, the structured log functionality is available. * Once this object is destroyed however, the structured log functionality cannot be * guaranteed to be available any more. It is intended for this object to be instantiated * and initialized in main() or at the global scope in the process' main module. It can * also be used from other libraries if they want to integrate structured logging as well. * Only a single instance of this object should be necessary. * * Before any structured logging features can be used, the object must be initialized * with init(). This allows the log path and the default log filename to be specified * and will also load the library and register all the schemas for the calling module. * Note that if no schemas are registered, no log messages will be emitted, the calls * will just be silently ignored. If modules other than the process' main module also * have schemas to be registered, they can either call registerSchemas() from this * class (from the process's single instantiation) or they can make a call into * `omni::structuredlog::addModulesSchemas()` from within the other modules. It is * safe to call those functions even if no schemas are used in a module or if the * structured log system has not been initialized yet. If either are called before * the structured log system has been initialized, an attempt will be made to load * the library first. * * @note On Windows it is expected that this object be instantiated in the process' * main module. If it is instantiated from a DLL it will not be guaranteed * that all pending log messages will be flushed to disk before the process * exits. If instantiating this from a DLL is unavoidable, it is the app's * responsibility to call flush() before shutdown to ensure all messages have * been flushed to disk. * * This requirement is caused by the way that Windows processes shutdown and * is unfortunately not possible to work around. When exiting the process * by returning from main(), the CRT is shutdown completely before any DLLs * get a chance to do any kind of cleanup task, and ntdll will kill all threads * except the exiting one. This means that there is a possibility that attempting * to flush the queue could result in a deadlock. Further, if any cleanup code * tries to use a win32 locking primitive (ie: SRW lock, critical section, etc) * the process may just be terminated immediately even in the middle of cleanup. */ class StructuredLogStandalone { public: StructuredLogStandalone() = default; /** Destructor: flushes the logging queue to disk and cleans up. * * @remarks This ensures that all log messages have been flushed to disk and puts the * structured logging system in a state where it can safely be cleaned up * without issue. */ ~StructuredLogStandalone() { // stop the log queue to guarantee that all messages have been flushed to disk. flush(); // release the objects explicitly to make debugging any release issues easier. Note that // this isn't strictly necessary since they will be released anyway when cleaning up this // object. log.release(); settings.release(); control.release(); } bool init(const char* logPath = nullptr, const char* defaultLogName = nullptr) { // When in standalone mode, the structured log plugin is set to load itself when the // omniGetStructuredLogWithoutAcquire() function is called by anything. This is the main // entry point to grab its instance in standalone mode. It is called by (among other things) // `omni::structuredlog::addModuleSchemas()`. This function needs to be called regardless // in standalone mode in order to register the schemas that have been included in the // calling module. It must be called once by each module that wants to use structured // logging in standalone mode. In non-standalone mode (ie: with carb), this step is done // automatically on module load. registerSchemas(); // grab the structured log object so we can grab the settings interface from it and setup // the configuration that's needed here. There isn't strictly anything that we must do here, // but in our case we want to change the log directory and default log name. We can also do // things like change the user ID, the queue size, some of the message formatting, etc. All // of these additional tasks are done through the `omni::structuredlog::IStructuredLogSettings` // interface. This can be acquired with `strucLog.as<omni::structuredlog::IStructuredLogSettings>()`. log = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); if (log == nullptr) return false; settings = log.as<omni::structuredlog::IStructuredLogSettings>(); control = log.as<omni::structuredlog::IStructuredLogControl>(); if (settings != nullptr) { if (logPath != nullptr) settings->setLogOutputPath(logPath); if (defaultLogName != nullptr) settings->setLogDefaultName(defaultLogName); } return log != nullptr && settings != nullptr && control != nullptr; } /** Registers all schemas used by the calling module. * * @returns No return value. * * @remarks This registers all schemas that have been included in the calling module. When * any source file in any module includes a schema header, an entry for it is * automatically added to a list local to the module. When this is called from * within the context of that module, all schemas for that module will be registered * and become available for use. * * @remarks This must be called from each module that includes a schema header. If it is * not, emitting a log message for an unregistered schema will be silently ignored. * It is possible however that the same schema could be used in multiple modules. * If that is the case, it only needs to be registered once, then all modules in * the process may use it. It is safe to register any given schema multiple times. * After it is registered once, later attempts to re-register it will just succeed * immediately. * * @note This is called from init() as well. Any module that calls init() does not also have * to explicitly call this. */ void registerSchemas() { addModulesSchemas(); } /** Flushes all pending log messages to disk. * * @returns No return value. * * @remarks This flushes all pending log messages to disk. Upon return, any messages that * has been issued before the call will have made it to disk. If there is another * thread emitting a message during this call, it is undefined whether it will * be fully flushed to disk. This should be called in situations where the caller * can guarantee that no messages are in the process of being emitted. * * @note This should be called at points where messages must be guaranteed to be present on * disk. This includes process exit time. This will be called implicitly when this * object is destroyed, but if an exit path is taken that will not guarantee this * object is destroyed (ie: calling `_exit()`, `TerminateProcess()`, etc), this * can be called explicitly to accomplish the same result. */ void flush() { if (control != nullptr) control->stop(); } /** Various structured log objects. These are publicly accessible so that callers can use * them directly to get direct access to the structured log features that may be needed. * As long as init() succeeds, these objects will be valid. * @{ */ /** Main IStructuredLog instance object. This is a global singleton that provides direct * access to the functionality for registering new schemas (manually), enabling and disabling * events or schemas, and emitting messages. */ omni::core::ObjectPtr<omni::structuredlog::IStructuredLog> log; /** Structured log settings interface. This is used to make changes to the various settings * for the structured logging system and to retrieve information about its current settings. * The most common uses of this are to change the log directory or name (though that is * already done more easily through init()). */ omni::core::ObjectPtr<omni::structuredlog::IStructuredLogSettings> settings; /** Structured log control interface. This is used to stop and flush the message queue and * to ensure any open log files are closed. Closing a log file is only necessary for example * to ensure a log file would not prevent a directory from being deleted on Windows. */ omni::core::ObjectPtr<omni::structuredlog::IStructuredLogControl> control; /** @} */ }; } // namespace structuredlog } // namespace omni
12,134
C
52.69469
110
0.694412
omniverse-code/kit/include/omni/structuredlog/StructuredLogUtils.h
// Copyright (c) 2021-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 structured log functionality. */ #pragma once #include "../extras/UniqueApp.h" #include "IStructuredLogSettings.h" #include "../../carb/extras/StringSafe.h" #if CARB_PLATFORM_WINDOWS # include "../../carb/CarbWindows.h" #elif CARB_POSIX # include <time.h> #else CARB_UNSUPPORTED_PLATFORM(); #endif namespace omni { namespace structuredlog { /** Base type for a CloudEvents timestamp. This will always be a value in nanoseconds. */ using TimestampNs = uint64_t; /** Generate the 'dataschema' field for events of a schema. * @param[in] clientName The client name specified in the schema's metadata. * @param[in] schemaVersion The version specified in the schema's metadata. * @returns The 'dataschema' field that will be emitted with the event. */ inline std::string generateDataSchema(const char* clientName, const char* schemaVersion) { return std::string(clientName) + '-' + schemaVersion; } /** retrieves a UTC timestamp relative to the system epoch in nanoseconds. * * @returns the number of system specific ticks that have elapsed since the system epoch. * The specifc epoch depends on the platform. On Windows, this is midnight Jan * 1, 1601. On Linux, this is midnight Jan 1, 1970. * * @thread_safety This is thread safe and only operates on local values. */ inline TimestampNs getUtcTimestamp() { #if CARB_PLATFORM_WINDOWS CARBWIN_FILETIME ft; // use GetSystemTimeAsFileTime() since that gives higher than millisecond resolution // (number of 100 nanosecond ticks since January 1, 1601). Other time functions // either do not have a reliable granularity, unknown epoch, or have a resolution // lower than milliseconds. This value has ~29247 years of space on it so overflow // should not be a concern. This then needs to be converted to nanoseconds for // return. GetSystemTimeAsFileTime(reinterpret_cast<FILETIME*>(&ft)); return ((((uint64_t)ft.dwHighDateTime) << 32) | ft.dwLowDateTime) * 100; #elif CARB_POSIX struct timespec ts; // use clock_gettime() since that gives higher than millisecond resolution (number // of nanoseconds since January 1, 1970). Other time functions either have an // unknown epoch, have a resolution lower than milliseconds, or are just built on // top of this function (ie: gettimeofday()). Storing this as a 64-bit integer // should give approximately 292 years worth of space. That is significantly more // than the 136 years of space that clock_gettime() gives in the first place. // Overflow of the value should not be an concern. clock_gettime(CLOCK_REALTIME, &ts); return (ts.tv_sec * 1'000'000'000ull) + ts.tv_nsec; #else CARB_UNSUPPORTED_PLATFORM(); #endif } /** Prints a UTC timestamp as an RfC3339 formatted string. * * @param[in] time The UTC timestamp to print. This should have been retrieved from a * previous call to getUtcTimestamp(). * @param[out] buffer Receives the printed timestamp string. This buffer must be large * enough to hold at least @p len characters. This buffer will always * be null terminated. This may not be nullptr. * @param[in] len The maximum number of characters that will fit in @p buffer including * the null terminator. * @returns The number of characters written to the output buffer. * This will truncate the timestamp if there was not enough buffer space. * * @thread_safety This is thread safe and only operates on local buffers. */ inline size_t printUtcTimestamp(TimestampNs time, char* buffer, size_t len) { size_t count; int32_t year; int32_t month; int32_t day; int32_t hour; int32_t minute; int32_t second; int32_t microseconds; #if CARB_PLATFORM_WINDOWS CARBWIN_FILETIME ft; CARBWIN_SYSTEMTIME st; TimestampNs t; // convert the given time index from nanoseconds back to NT ticks (100ns units). t = time / 100; // convert this back to a FILETIME object (a split 64-bit value representing the number // of 100 nanosecond ticks since January 1, 1601) so we can convert it to an adjusted // date/time stamp. The native call already provides milliseconds so we don't need to // calculate that separately. ft.dwLowDateTime = t & 0xffffffffull; ft.dwHighDateTime = t >> 32; FileTimeToSystemTime(reinterpret_cast<FILETIME*>(&ft), reinterpret_cast<SYSTEMTIME*>(&st)); year = st.wYear; month = st.wMonth; day = st.wDay; hour = st.wHour; minute = st.wMinute; second = st.wSecond; #elif CARB_POSIX struct tm tm; time_t t; // convert this back to a time_t and a count of remaining milliseconds. The input time // value will be the number of nanoseconds since January 1, 1970. This will convert it // to an adjusted date/time stamp. Since time_t values only hold times in seconds and // gmtime*() are the only functions that provide an adjusted date/time stamp, we'll // extract the microseconds count from the original value manually. Microseconds are // not affected by leaps (days or seconds), so they can be safely extracted from the // original time without having to adjust the date/time further. t = time / 1'000'000'000ull; gmtime_r(&t, &tm); year = tm.tm_year + 1900; month = tm.tm_mon + 1; day = tm.tm_mday; hour = tm.tm_hour; minute = tm.tm_min; second = tm.tm_sec; #else CARB_UNSUPPORTED_PLATFORM(); #endif microseconds = static_cast<int32_t>((time / 1'000ull) % 1'000'000ull); count = carb::extras::formatString( buffer, len, "%04d-%02d-%02dT%02d:%02d:%02d.%06dZ", year, month, day, hour, minute, second, microseconds); return count; } } // namespace structuredlog } // namespace omni
6,336
C
37.640244
114
0.696496
omniverse-code/kit/include/omni/structuredlog/IStructuredLogFromILog.gen.h
// Copyright (c) 2021-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/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** This interface controls the ability to send Carbonite and Omniverse logging through the * structured log system. The output is equivalent to the standard logging output, except that it * is in JSON, so it will be easier for programs to consume. * * The default state of structured log logging is off, but it can be enabled by calling * @ref omni::structuredlog::IStructuredLogFromILog::enableLogging() or setting `/structuredLog/enableLogConsumer` * to true with ISettings. */ template <> class omni::core::Generated<omni::structuredlog::IStructuredLogFromILog_abi> : public omni::structuredlog::IStructuredLogFromILog_abi { public: OMNI_PLUGIN_INTERFACE("omni::structuredlog::IStructuredLogFromILog") /** Enable the structured log logger. * @remarks Enabling this will result in all Carbonite logging (e.g. CARB_LOG_*) and all * Omniverse logging (e.g. OMNI_LOG_*) going to the structured log log file. * This may be useful if you want the logs to be consumed by some sort of log reader * program. * These log events will be sent to the default structured log system's log file if * there is one; they will otherwise go to a log file named * "omni.structuredlog.logging-{version}". * These log events will not be sent to the collection servers. */ void enableLogging() noexcept; /** Disables the structured log logger. * @remarks After this is called, log messages will no longer be sent as structured log * events to the structured log system's log file. */ void disableLogging() noexcept; /** Get the @ref omni::structuredlog::EventId of the logging schema. * @retval omni::structuredlog::EventId of the logging schema. * * @remarks This is only needed if you need to query properties of the logging schema, * such as the log file name. * * @note The logging schema will still be valid when logging is disabled. */ omni::structuredlog::EventId getLoggingEventId() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::structuredlog::IStructuredLogFromILog_abi>::enableLogging() noexcept { enableLogging_abi(); } inline void omni::core::Generated<omni::structuredlog::IStructuredLogFromILog_abi>::disableLogging() noexcept { disableLogging_abi(); } inline omni::structuredlog::EventId omni::core::Generated<omni::structuredlog::IStructuredLogFromILog_abi>::getLoggingEventId() noexcept { return getLoggingEventId_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
3,513
C
36.382978
136
0.711642
omniverse-code/kit/include/omni/structuredlog/IStructuredLogFromILog.h
// Copyright (c) 2021-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 An interface for redirecting @ref omni::log::ILog messages to structured logging. */ #pragma once #include "StructuredLogCommon.h" #include "../core/IObject.h" namespace omni { namespace structuredlog { class IStructuredLogFromILog; // ****************************** IStructuredLogFromILog interface ******************************** /** This interface controls the ability to send Carbonite and Omniverse logging through the * structured log system. The output is equivalent to the standard logging output, except that it * is in JSON, so it will be easier for programs to consume. * * The default state of structured log logging is off, but it can be enabled by calling * @ref omni::structuredlog::IStructuredLogFromILog::enableLogging() or setting `/structuredLog/enableLogConsumer` * to true with ISettings. */ class IStructuredLogFromILog_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.structuredlog.IStructuredLogFromILog")> { protected: // ****** structured logging functions ****** /** Enable the structured log logger. * @remarks Enabling this will result in all Carbonite logging (e.g. CARB_LOG_*) and all * Omniverse logging (e.g. OMNI_LOG_*) going to the structured log log file. * This may be useful if you want the logs to be consumed by some sort of log reader * program. * These log events will be sent to the default structured log system's log file if * there is one; they will otherwise go to a log file named * "omni.structuredlog.logging-{version}". * These log events will not be sent to the collection servers. */ virtual void enableLogging_abi() noexcept = 0; /** Disables the structured log logger. * @remarks After this is called, log messages will no longer be sent as structured log * events to the structured log system's log file. */ virtual void disableLogging_abi() noexcept = 0; /** Get the @ref omni::structuredlog::EventId of the logging schema. * @retval omni::structuredlog::EventId of the logging schema. * * @remarks This is only needed if you need to query properties of the logging schema, * such as the log file name. * * @note The logging schema will still be valid when logging is disabled. */ virtual EventId getLoggingEventId_abi() noexcept = 0; }; } // namespace structuredlog } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IStructuredLogFromILog.gen.h" /** @copydoc omni::structuredlog::IStructuredLogFromILog_abi */ class omni::structuredlog::IStructuredLogFromILog : public omni::core::Generated<omni::structuredlog::IStructuredLogFromILog_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IStructuredLogFromILog.gen.h"
3,343
C
38.809523
115
0.697876
omniverse-code/kit/include/omni/structuredlog/IStructuredLogSettings2.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. // /** @file * @brief Interface to querying and adjusting structured logging settings. */ #pragma once #include "StructuredLogCommon.h" #include "IStructuredLogSettings.h" #include "../core/IObject.h" namespace omni { namespace structuredlog { class IStructuredLogSettings2; /** Base type for the ouptut flags for the structured logging system. These flags are used * in the omni::structuredlog::IStructuredLogSettings2::getOutputFlags() and * omni::structuredlog::IStructuredLogSEttings2::setOutputFlags() functions. */ using OutputFlags = uint32_t; /** Special flag value to indicate that no output flags are being specified. */ constexpr OutputFlags fOutputFlagNone = 0; /** Flag to indicate that only emit the payload portion of each message as the full output instead * of including the CloudEvents wrapper as well. In this case, it is expected to be the host * app's responsibility to ensure all the useful or required information is included in the * payload itself (ie: timestamps, user information, etc). Also, when this flag is used, log * files created containing these messages cannot be consumed by the telemetry transmitter. * This flag should only be used when the host app wants to use structured logging messages * but does not want to use them as part of the telemetry toolchain. This flag is off by * default. Adding this flag will take effect the next time a message is emitted. */ constexpr OutputFlags fOutputFlagPayloadOnly = 0x00000001; /** Flag to indicate that no header should be written out to log files created by the structured * logging system. The header is consumed and modified by the telemetry transmitter app to allow * it to store its progress in processing each log file. If the header is missing, the * transmitter app will simply ignore the log file. Omitting the headers in log files allows the * log output to purely just be the structured log event messages so they can be more easily * consumed wholesale by external apps. Note that when this flag is used, the structured log * files created by the host app will be incompatible with the rest of the telemetry toolchain * in Omniverse. This flag is off by default. Adding this flag will take effect the next time * a new log file is created. */ constexpr OutputFlags fOutputFlagSkipLogHeaders = 0x00000002; /** Flag to indicate that the cloud heartbeat events should be emitted as well as the normal * heartbeat events. This cloud heartbeat event is effectively duplciate data and will only * be emitted when this flag is used and the normal heartbeat events are also enabled. This * defaults to off. */ constexpr OutputFlags fOutputFlagEmitCloudHeartbeat = 0x00000004; // ****************************** IStructuredLogSettings2 interface ******************************* /** Interface for the second version of the IStructuredLogSettings interface. This interface * exposes more settings to control the behaviour of the structured logging system. This * object can be retrieved directly or by casting the main IStructuredLog interface to this * type using `omni::core::ObjectPtr::as<>()`. */ class IStructuredLogSettings2_abi : public omni::core::Inherits<omni::structuredlog::IStructuredLogSettings_abi, OMNI_TYPE_ID("omni.structuredlog.IStructuredLogSettings2")> { protected: /** Retrieves the current heartbeat message period in seconds. * * @returns The minimum time in seconds between heartbeat events. This will be * @ref omni::structuredlog::kHeartbeatDisabled if the heartbeat events are * disabled. When enabled, the heartbeat events will be generated within * ~100ms of this scheduled time. In general, it is expected that the heartbeat * period be on the scale of one minute or more to reduce the overall amount of * event traffic. */ virtual uint64_t getHeartbeatPeriod_abi() noexcept = 0; /** Sets the new heartbeat event period in seconds. * * @param[in] period The minimum time in seconds between generated heartbeat events. * This may be @ref omni::structuredlog::kHeartbeatDisabled to disable * the heartbeat events. * @returns No return value. * * @remarks The heartbeat events can be used to get an estimate of a session's length even if * the 'exit' or 'crash' process lifetime events are missing (ie: power loss, user * kills the process, blue screen of death or kernel panic, etc). The session can * neither be assumed to have exited normally nor crashed with only these heartbeat * events present however. */ virtual void setHeartbeatPeriod_abi(uint64_t period) noexcept = 0; /** Retrieves whether header objects will be added to each newly written log file. * * @returns `true` if headers will be written to each new log file. Returns `false` if * header objects will be omitted from new log files. */ virtual bool getNeedLogHeaders_abi() noexcept = 0; /** Sets whether headers will be added to each newly written log file. * * @param[in] needHeaders Set to `true` to indicate that headers should be added to each * newly written log file. Set to `false` to indicate that the * header should be omitted. * @returns No return value. * * @remarks This sets whether log headers will be written out to each new log file. The * header is consumed and modified by the telemetry transmitter app to allow it * to store its progress in processing each log file. If the header is missing, * the transmitter app will simply ignore the log file. Omitting the headers * in log files allows the log output to purely just be the structured log event * messages so they can be more easily consumed wholesale by external apps. * * @note Changing this setting will only take effect the next time a new log file is written * out to disk. Disabling this will not remove the header object from an existing log * file. */ virtual void setNeedLogHeaders_abi(bool needHeaders) noexcept = 0; /** Retrieves the current set of output flags for structured logging. * * @returns The current output flags for the structured logging system. These indicate how * various aspects of the logging system will function. Note that some flags may * affect whether the produced messages are compatible with the remainder of the * telemetry toolchain in Omniverse apps. By default, all output flags are off. */ virtual OutputFlags getOutputFlags_abi() noexcept = 0; /** Sets or clears one or more output flags for structured logging. * * @param[in] flagsToAdd A set of zero or more flag bits to set. These must be either * @ref omni::structuredlog::fOutputFlagNone or one or more of * the @ref omni::structuredlog::OutputFlags flags. * @param[in] flagsToRemove A set of zero or more flag bits to cleared. These must be * either @ref omni::structuredlog::fOutputFlagNone or one or * more of the @ref omni::structuredlog::OutputFlags flags. * @returns No return value. * * @remarks This sets or clears flags that affect the output from the structured logging * system. These flags are all disabled by default. These flags will take effect * the next time a message is emitted. */ virtual void setOutputFlags_abi(OutputFlags flagsToAdd, OutputFlags flagsToRemove) noexcept = 0; }; } // namespace structuredlog } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IStructuredLogSettings2.gen.h" // insert custom API functions here. /** @copydoc omni::structuredlog::IStructuredLogSettings2_abi */ class omni::structuredlog::IStructuredLogSettings2 : public omni::core::Generated<omni::structuredlog::IStructuredLogSettings2_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IStructuredLogSettings2.gen.h"
8,883
C
50.651162
100
0.695148
omniverse-code/kit/include/omni/structuredlog/StructuredLogCommon.h
// Copyright (c) 2021-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 Common types/macros/functions for structured logging. */ #pragma once #include "../core/IObject.h" #include "../extras/ForceLink.h" namespace omni { namespace structuredlog { /** Helper macro to piece together a unique event name to generate an ID from. * * @param schemaName The name of the schema that the event belongs to. This should be * the name from the schema's "#/schemaMeta/clientName" property. * This value must be a string literal. * @param eventName The full name of the event that the ID is being generated for. * This should be the name of one of the objects in the * "#/definitions/events/" listing. This value must be a string * literal. * @param schemaVersion The version of the schema the event belongs to. This should be * the value from the schema's "#/schemaMeta/schemaVersion" property. * This value must be a string literal. * @param parserVersion The version of the object parser that this event ID is being built * for. This should be the value of kParserVersion expressed as * a string. This value must be a string literal. * @returns A string representing the full name of an event. This string is suitable for passing * to OMNI_STRUCTURED_LOG_EVENT_ID() to generate a unique event ID from. */ #define OMNI_STRUCTURED_LOG_EVENT_ID(schemaName, eventName, schemaVersion, parserVersion) \ CARB_HASH_STRING(schemaName "-" eventName "-" schemaVersion "." parserVersion) #ifndef DOXYGEN_SHOULD_SKIP_THIS // used internally in OMNI_STRUCTURED_LOG_ADD_SCHEMA(). Do not call directly. # define OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME(name_, version_, parser_, line_) \ OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME_INNER(name_, version_, parser_, line_) // used internally in OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME(). Do not call directly. # define OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME_INNER(name_, version_, parser_, line_) \ sSchema_##name_##_##version_##_##parser_##_##line_ #endif /** Sets that a schema should be registered on module load. * * @param schemaType_ The name and fully qualified namespace of the generated schema class * to be registered. This will be added to a list of schemas to be * registered when the module is initialized. * @param schemaName_ The name of the schema to be registered. This may be any valid C++ * token string, but should reflect the schema's name. This is used * to make the initialization symbol more unique to the generated schema * class. * @param version_ The schema's version expressed as a C++ token. This should replace * any dots ("."), dashes ("-"), colons (":"), whitespace (" "), or * commas (",") with an underscore ("_"). This is used to make the * initialization symbol more unique to the generated schema class. * @param parser_ The parser version being used for the generated schema expressed as * a C++ token. This should replace any dots ("."), dashes ("-"), colons * (":"), whitespace (" "), or commas (",") with an underscore ("_"). * This is used to make the initialization symbol more unique to the * generated schema class. * @returns No return value. * * @remarks This creates and registers a helper function that will call into a generated * schema's registerSchema() function during omni core or framework initialization. * The symbol used to force the registration at C++ initialization time is named * based on the schema's name, schema's version, parser version, and the line number * in the header file that this call appears on. All of these values are used to * differentiate this schema's registration from that of all others, even for * different versions of the same generated schema. */ #define OMNI_STRUCTURED_LOG_ADD_SCHEMA(schemaType_, schemaName_, version_, parser_) \ CARB_ATTRIBUTE(weak) \ CARB_DECLSPEC(selectany) \ bool OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME(schemaName_, version_, parser_, __LINE__) = []() { \ omni::structuredlog::getModuleSchemas().push_back(&schemaType_::registerSchema); \ return true; \ }(); \ OMNI_FORCE_SYMBOL_LINK( \ OMNI_STRUCTURED_LOG_SCHEMA_ADDED_NAME(schemaName_, version_, parser_, __LINE__), schemaRegistration) /** Possible results from registering a new schema. These indicate whether the schema was * successfully registered or why it may have failed. Each result code can be considered a * failure unless otherwise noted. In all failure cases, the schema's allocated data block * will be destroyed before returning and no new events will be registered. */ enum class SchemaResult { /** The new schema was successfully registered with a unique set of event identifiers. */ eSuccess, /** The new schema exactly matches one that has already been successfully registered. The * events in the new schema are still valid and can be used, however no new action was * taken to register the schema again. This condition can always be considered successful. */ eAlreadyExists, /** The new schema contains an event identifier that collides with an event in another schema. * The schema that the existing event belongs to does not match this new one. This often * indicates that either the name of an event in the schema is not unique enough or that * another version of the schema had already been registered. This is often remedied by * bumping the version number of the schema so that its event identifiers no longer matches * the previous schema's event(s). */ eEventIdCollision, /** The same schema was registered multiple times, but with different schema flags. This is * not allowed and will fail the new schema's registration. This can be fixed by bumping * the version of the new schema. */ eFlagsDiffer, /** Too many events have been registered. There is an internal limit of unique events that * can be registered in any one process. Failed schemas or schemas that exactly match an * existing schema do not contribute their event count to this limit. When this is * returned, none of the new schema's events will be registered. There is no recovering * from this failure code. This is often an indication that the process's events should be * reorganized to not have so many. The internal limit will be at least 65536 events. */ eOutOfEvents, /** An invalid parameter was passed into IStructuredLog::commitSchema(). This includes a * nullptr @a schemaBlock parameter, a nullptr event table, or a zero event count. It is the * caller's responsibility to ensure valid parameters are passed in. */ eInvalidParameter, /** An event's schema payload information was not contained within the block of memory that * was returned from IStructuredLog::allocSchema(). This is a requirement to ensure all the * event's information memory is owned by the structured log core. */ eEventNotInBlock, /** Memory could not be allocated for the new schema information object. This can usually * be considered fatal. */ eOutOfMemory, }; /** Base type for a unique ID of a registered event. Each registered event is identified by an * integer value that is derived from its name, schema, and version number. */ using EventId = uint64_t; /** A special value to indicate a bad event identifier. This is used as a failure code * in some of the IStructuredLog accessor functions. */ constexpr EventId kBadEventId = ~1ull; /** Retrieves a string containing the name of a SchemaResult value. * * @param[in] result The result code to convert to a string. * @returns The result code's name as a string if a valid code is passed in. * @returns "<unknown_result>" if an invalid or unknown result code is passed in. */ constexpr const char* getSchemaResultName(SchemaResult result) { #ifndef DOXYGEN_SHOULD_SKIP_THIS # define OMNI_STRUCTUREDLOG_GETNAME(r, prefix) \ case r: \ return &(#r)[sizeof(#prefix) - 1] switch (result) { OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eSuccess, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eAlreadyExists, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eEventIdCollision, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eFlagsDiffer, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eOutOfEvents, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eInvalidParameter, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eEventNotInBlock, SchemaResult::e); OMNI_STRUCTUREDLOG_GETNAME(SchemaResult::eOutOfMemory, SchemaResult::e); default: return "<unknown_result>"; } # undef OMNI_STRUCTUREDLOG_GETNAME #endif } } // namespace structuredlog } // namespace omni
10,770
C
53.954081
120
0.626277
omniverse-code/kit/include/omni/structuredlog/StructuredLog.Cloud.python.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. // // DO NOT MODIFY THIS FILE. This is a generated file. // This file was generated from: StructuredLog.Cloud.schema #pragma once #include <carb/BindingsPythonUtils.h> #include "StructuredLog.Cloud.gen.h" namespace omni { namespace telemetry { struct Struct_Wrap_startup_ident { /** The identifier of the cluster this pod is running on. */ std::string cluster; /** The identifier of the node this pod is running on. This will be * either a hostname or the IPv4/IPv6 address of the node. */ std::string node; }; struct Struct_Wrap_startup_application { /** The name of the app that is starting up. */ std::string name; /** The version of the app that is starting up. */ std::string version; }; struct Struct_Wrap_exit_application { /** The name of the app that is starting up. */ std::string name; /** The version of the app that is starting up. */ std::string version; }; class Wrap_omni_carb_cloud { public: Wrap_omni_carb_cloud() = default; ~Wrap_omni_carb_cloud() = default; void startup_sendEvent(std::string cloud_link_id, const Struct_Wrap_startup_ident& ident, const Struct_Wrap_startup_application& application) { Schema_omni_carb_cloud_1_0::Struct_startup_ident ident_ = {}; ident_.cluster = ident.cluster; ident_.node = ident.node; Schema_omni_carb_cloud_1_0::Struct_startup_application application_ = {}; application_.name = application.name; application_.version = application.version; OMNI_STRUCTURED_LOG(Schema_omni_carb_cloud_1_0::startup, cloud_link_id, ident_, application_); } void heartbeat_sendEvent(std::string cloud_link_id) { OMNI_STRUCTURED_LOG(Schema_omni_carb_cloud_1_0::heartbeat, cloud_link_id); } void exit_sendEvent(std::string cloud_link_id, const Struct_Wrap_exit_application& application, bool exit_abnormally) { Schema_omni_carb_cloud_1_0::Struct_exit_application application_ = {}; application_.name = application.name; application_.version = application.version; OMNI_STRUCTURED_LOG(Schema_omni_carb_cloud_1_0::exit, cloud_link_id, application_, exit_abnormally); } }; inline void definePythonModule_omni_carb_cloud(py::module& m) { using namespace omni::structuredlog; m.doc() = "bindings for structured log schema omni.carb.cloud"; { py::class_<Struct_Wrap_startup_ident> bind_ident(m, "Struct_startup_ident"); bind_ident.def(py::init<>()); bind_ident.def_readwrite("cluster", &Struct_Wrap_startup_ident::cluster); bind_ident.def_readwrite("node", &Struct_Wrap_startup_ident::node); } { py::class_<Struct_Wrap_startup_application> bind_application(m, "Struct_startup_application"); bind_application.def(py::init<>()); bind_application.def_readwrite("name", &Struct_Wrap_startup_application::name); bind_application.def_readwrite("version", &Struct_Wrap_startup_application::version); } { py::class_<Struct_Wrap_exit_application> bind_application(m, "Struct_exit_application"); bind_application.def(py::init<>()); bind_application.def_readwrite("name", &Struct_Wrap_exit_application::name); bind_application.def_readwrite("version", &Struct_Wrap_exit_application::version); } // the main structured log class py::class_<Wrap_omni_carb_cloud>(m, "Schema_omni_carb_cloud_1_0") .def(py::init<>()) .def("startup_sendEvent", &Wrap_omni_carb_cloud::startup_sendEvent, py::arg("cloud_link_id"), py::arg("ident"), py::arg("application")) .def("heartbeat_sendEvent", &Wrap_omni_carb_cloud::heartbeat_sendEvent, py::arg("cloud_link_id")) .def("exit_sendEvent", &Wrap_omni_carb_cloud::exit_sendEvent, py::arg("cloud_link_id"), py::arg("application"), py::arg("exit_abnormally")); } } // namespace telemetry } // namespace omni
4,450
C
35.785124
121
0.669888
omniverse-code/kit/include/omni/structuredlog/JsonTreeSerializer.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 Module for Serializing the @ref omni::structuredlog::JsonNode tree structures. */ #pragma once #include "JsonSerializer.h" #include "BinarySerializer.h" #include "JsonTree.h" namespace omni { namespace structuredlog { /** Default value for the onValidationError template parameter. * @param[in] s The validation error message. This is ignored. */ static inline void ignoreJsonTreeSerializerValidationError(const char* s) { CARB_UNUSED(s); } /** Serialize a scalar type from a JSON tree. * @param[inout] serial The JSON serializer to serialize the data into. * @param[in] root The node in the schema that represents this scalar value. * @param[in] constVal The constant value from the data union of @p root. * This is only read if root is marked as constant. * @param[inout] reader The blob reader, which will be read if @p root is not * marked as constant. * * @returns `true` if no validation error occurred. * @returns `false` if any form of validation error occurred. */ template <bool validate = false, typename T, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeScalar(JsonSerializerType* serial, const JsonNodeType* root, T constVal, BlobReaderType* reader) { if ((root->flags & JsonNode::fFlagConst) != 0) { return serial->writeValue(constVal); } else { T b = {}; bool result = reader->read(&b); if (validate && !result) return false; return serial->writeValue(b); } } /** Serialize an array type from a JSON tree. * @param[inout] serial The JSON serializer to serialize the data into. * @param[in] root The node in the schema that represents this scalar value. * @param[in] constVal The constant array value from the data union of @p root. * This is only read if root is marked as constant; * in that case, this is of length @p root->len. * @param[inout] reader The blob reader, which will be read if @p root is not * marked as constant. * * @returns `true` if no validation error occurred. * @returns `false` if any form of validation error occurred. */ template <bool validate = false, typename T, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeArray(JsonSerializerType* serial, const JsonNodeType* root, const T* constVal, BlobReaderType* reader) { bool result = true; result = serial->openArray(); if (validate && !result) return false; if ((root->flags & JsonNode::fFlagConst) != 0) { for (uint16_t i = 0; i < root->len; i++) { result = serial->writeValue(constVal[i]); if (validate && !result) return false; } } else { const T* b = nullptr; uint16_t len = 0; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { len = root->len; result = reader->read(&b, len); if (validate && !result) return false; } else { result = reader->read(&b, &len); if (validate && !result) return false; } for (uint16_t i = 0; i < len; i++) { result = serial->writeValue(b[i]); if (validate && !result) return false; } } return serial->closeArray(); } template <bool validate = false, typename T, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeEnum(JsonSerializerType* serial, const JsonNodeType* root, T* enumChoices, BlobReaderType* reader) { JsonNode::EnumBase b = {}; bool result = reader->read(&b); if (validate && !result) return false; if (b > root->len) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "enum value is out of range" " {value = %" PRIu16 ", max = %" PRIu16 "}", b, root->len); serial->m_onValidationError(tmp); return false; } return serial->writeValue(enumChoices[b]); } /** Serialize JSON using a @ref JsonNode as the schema and a binary blob to read data. * * @remarks This overload uses a @ref BlobReader instead of the binary blob * directly, so that the read position from within the blob can be * tracked across recursive calls. * External code should use the other overload. * * @note If you use this overload, you must call @p serial->finish(), since this * is the recursive overload so there's no obvious point to finish at. */ template <bool validate = false, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeJsonTree(JsonSerializerType* serial, const JsonNodeType* root, BlobReaderType* reader) { bool result = true; if (root->name != nullptr) { result = serial->writeKey(root->name, root->nameLen - 1); if (validate && !result) return false; } switch (root->type) { case NodeType::eNull: return serial->writeValue(); case NodeType::eBool: return serializeScalar<validate>(serial, root, root->data.boolVal, reader); case NodeType::eInt32: return serializeScalar<validate>(serial, root, int32_t(root->data.intVal), reader); case NodeType::eUint32: return serializeScalar<validate>(serial, root, uint32_t(root->data.uintVal), reader); case NodeType::eInt64: return serializeScalar<validate>(serial, root, root->data.intVal, reader); case NodeType::eUint64: return serializeScalar<validate>(serial, root, root->data.uintVal, reader); case NodeType::eFloat32: return serializeScalar<validate>(serial, root, float(root->data.floatVal), reader); case NodeType::eFloat64: return serializeScalar<validate>(serial, root, root->data.floatVal, reader); case NodeType::eBinary: if ((root->flags & JsonNode::fFlagConst) != 0) { return serial->writeValueWithBase64Encoding(root->data.binaryVal, root->len); } else { const uint8_t* b = nullptr; uint16_t len = 0; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { len = root->len; result = reader->read(&b, len); } else { result = reader->read(&b, &len); } if (validate && !result) return false; // null terminator is included in the length return serial->writeValueWithBase64Encoding(b, len); } case NodeType::eBoolArray: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.boolArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.boolArrayVal, reader); case NodeType::eInt32Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.int32ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.int32ArrayVal, reader); case NodeType::eUint32Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.uint32ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.uint32ArrayVal, reader); case NodeType::eInt64Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.int64ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.int64ArrayVal, reader); case NodeType::eUint64Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.uint64ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.uint64ArrayVal, reader); case NodeType::eFloat32Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.float32ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.float32ArrayVal, reader); case NodeType::eFloat64Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum(serial, root, root->data.float64ArrayVal, reader); else return serializeArray(serial, root, root->data.float64ArrayVal, reader); case NodeType::eString: if ((root->flags & JsonNode::fFlagConst) != 0) { return serial->writeValue(root->data.strVal, (root->len == 0) ? 0 : root->len - 1); } else { const char* b = nullptr; uint16_t len = 0; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { len = root->len; result = reader->read(&b, len); } else { result = reader->read(&b, &len); } if (validate && !result) return false; // null terminator is included in the length return serial->writeValue(b, (len == 0) ? 0 : len - 1); } case NodeType::eStringArray: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.strArrayVal, reader); result = serial->openArray(); if (validate && !result) return false; if ((root->flags & JsonNode::fFlagConst) != 0) { for (uint16_t i = 0; i < root->len; i++) { result = serial->writeValue(root->data.strArrayVal[i]); if (validate && !result) return false; } } else { const char** b = nullptr; uint16_t len = 0; // fixed length isn't supported here result = reader->read(b, &len, 0); if (validate && !result) return false; // FIXME: dangerous b = static_cast<const char**>(alloca(len * sizeof(*b))); result = reader->read(b, &len, len); if (validate && !result) return false; for (uint16_t i = 0; i < len; i++) { result = serial->writeValue(b[i]); if (validate && !result) return false; } } return serial->closeArray(); case NodeType::eObject: result = serial->openObject(); if (validate && !result) return false; for (uint16_t i = 0; i < root->len; i++) { result = serializeJsonTree<validate>(serial, &root->data.objVal[i], reader); if (validate && !result) return false; } return serial->closeObject(); case NodeType::eObjectArray: result = serial->openArray(); if (validate && !result) return false; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { for (uint16_t i = 0; i < root->len; i++) { result = serializeJsonTree<validate>(serial, &root->data.objVal[i], reader); if (validate && !result) return false; } } else { uint16_t len = 0; // read the array length result = reader->read(&len); if (validate && !result) return false; // a variable length object array uses the same object schema for // each object in the array, so we just pass the 0th element here for (uint16_t i = 0; i < len; i++) { result = serializeJsonTree<validate>(serial, &root->data.objVal[0], reader); if (validate && !result) return false; } } return serial->closeArray(); } return false; } /** Serialize JSON using a @ref JsonNode as the schema and a binary blob to read data. * @param[inout] serial The JSON serializer to serialize the data into. * @param[in] root The JSON tree to use for the data schema. * @param[in] blob The binary blob to read data directly from. * @param[in] blobSize The length of @p blob in bytes. * * @tparam validate If this is true, validation will be performed. * This ensures the output JSON will be valid. * This also will add bounds checking onto @p blob. * If this is false, out of bounds reading is possible * when the blob was generated incorrectly. * @tparam prettyPrint If this is set to false, the output will be printed * with minimal spacing. * Human-readable spacing will be used otherwise. * @tparam onValidationError This callback will be used when a validation error * occurs, so that logging can be performed. * * @returns `true` if no validation error occurred. * @returns `false` if any form of validation error occurred. */ template <bool validate = false, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeJsonTree(JsonSerializerType* serial, const JsonNodeType* root, const void* blob, size_t blobSize) { BlobReaderType reader(blob, blobSize); return serializeJsonTree<validate>(serial, root, &reader) && serial->finish(); } /* we don't extract static symbols so this breaks exhale somehow */ #ifndef DOXYGEN_SHOULD_SKIP_THIS /** @copydoc serializeJsonSchema */ template <typename JsonSerializerType = JsonSerializer<true, true>, typename JsonNodeType = JsonNode> static inline void serializeJsonSchema_(JsonSerializerType* serial, const JsonNodeType* root) { auto nodeTypeString = [](NodeType n) -> const char* { switch (n) { case NodeType::eNull: return "null"; case NodeType::eBool: return "boolean"; case NodeType::eInt32: return "integer"; case NodeType::eUint32: return "uint32"; case NodeType::eInt64: return "int64"; case NodeType::eUint64: return "uint64"; case NodeType::eFloat32: return "float"; case NodeType::eFloat64: return "double"; case NodeType::eBinary: return "binary"; case NodeType::eBoolArray: return "bool[]"; case NodeType::eInt32Array: return "integer[]"; case NodeType::eUint32Array: return "uint32[]"; case NodeType::eInt64Array: return "int64[]"; case NodeType::eUint64Array: return "uint64[]"; case NodeType::eFloat32Array: return "float[]"; case NodeType::eFloat64Array: return "double[]"; case NodeType::eString: return "string"; case NodeType::eStringArray: return "string[]"; case NodeType::eObject: return "object"; case NodeType::eObjectArray: return "object[]"; } return "unknown"; }; if (root->name != nullptr) { serial->writeKey(root->name, root->nameLen - 1); } serial->openObject(); serial->writeKey("type"); serial->writeValue(nodeTypeString(root->type)); serial->writeKey("flags"); serial->writeValue(root->flags); if ((root->flags & JsonNode::fFlagConst) != 0) { serial->writeKey("const"); switch (root->type) { case NodeType::eNull: serial->writeValue(); break; case NodeType::eBool: serial->writeValue(root->data.boolVal); break; case NodeType::eInt32: serial->writeValue(root->data.intVal); break; case NodeType::eUint32: serial->writeValue(root->data.uintVal); break; case NodeType::eInt64: serial->writeValue(root->data.intVal); break; case NodeType::eUint64: serial->writeValue(root->data.uintVal); break; case NodeType::eFloat32: serial->writeValue(root->data.floatVal); break; case NodeType::eFloat64: serial->writeValue(root->data.floatVal); break; case NodeType::eBinary: serial->writeValueWithBase64Encoding(root->data.binaryVal, root->len); break; case NodeType::eBoolArray: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.boolArrayVal[i]); } serial->closeArray(); break; case NodeType::eInt32Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.int32ArrayVal[i]); } serial->closeArray(); break; case NodeType::eUint32Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.uint32ArrayVal[i]); } serial->closeArray(); break; case NodeType::eInt64Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.int64ArrayVal[i]); } serial->closeArray(); break; case NodeType::eUint64Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.uint64ArrayVal[i]); } serial->closeArray(); break; case NodeType::eFloat32Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.float32ArrayVal[i]); } serial->closeArray(); break; case NodeType::eFloat64Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.float64ArrayVal[i]); } serial->closeArray(); break; case NodeType::eString: serial->writeValue(root->data.strVal, (root->len == 0) ? 0 : root->len - 1); break; case NodeType::eStringArray: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.strArrayVal[i]); } serial->closeArray(); break; case NodeType::eObject: serial->writeValue(); break; case NodeType::eObjectArray: serial->openArray(); serial->closeArray(); break; } } if ((root->flags & JsonNode::fFlagEnum) != 0) { serial->writeKey("enum"); serial->writeValue(true); } if (root->type == NodeType::eObject || root->type == NodeType::eObjectArray) { serial->writeKey("properties"); serial->openObject(); for (size_t i = 0; i < root->len; i++) { serializeJsonSchema_(serial, &root->data.objVal[i]); } serial->closeObject(); } serial->closeObject(); } /** Serialize a JSON schema to JSON. * @param[in] serial The serializer object to use. * @param[in] root The schema being serialized. * @remarks This function will serialize a JSON schema to JSON. * This is mainly intended to be used for debugging. * serializeJsonTree() can't be used for serializing the schema because * a binary blob is needed for the variable values in the schema. */ template <typename JsonSerializerType = JsonSerializer<true, true>, typename JsonNodeType = JsonNode> static inline void serializeJsonSchema(JsonSerializerType* serial, const JsonNodeType* root) { serializeJsonSchema_(serial, root); serial->finish(); } #endif } // namespace structuredlog } // namespace omni
23,705
C
35.867807
126
0.538789
omniverse-code/kit/include/omni/structuredlog/StructuredLog.Cloud.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. // // DO NOT MODIFY THIS FILE. This is a generated file. // This file was generated from: StructuredLog.Cloud.schema // #pragma once #include <omni/log/ILog.h> #include <omni/structuredlog/IStructuredLog.h> #include <omni/structuredlog/JsonTree.h> #include <omni/structuredlog/BinarySerializer.h> #include <omni/structuredlog/StringView.h> #include <memory> namespace omni { namespace telemetry { /** helper macro to send the 'startup' event. * * @param[in] cloud_link_id_ Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] ident_ Parameter from schema at path '/ident'. * The information of where this pod is running. * @param[in] application_ Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was launched, * its version, the user, node, and cluster information, and the * cloud session ID that needs to be linked to this telemetry session * ID. * * @sa @ref Schema_omni_carb_cloud_1_0::startup_sendEvent(). * @sa @ref Schema_omni_carb_cloud_1_0::startup_isEnabled(). */ #define OMNI_OMNI_CARB_CLOUD_1_0_STARTUP(cloud_link_id_, ident_, application_) \ OMNI_STRUCTURED_LOG(omni::telemetry::Schema_omni_carb_cloud_1_0::startup, cloud_link_id_, ident_, application_) /** helper macro to send the 'heartbeat' event. * * @param[in] cloud_link_id_ Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @returns no return value. * * @remarks This event notes that the app is still running. The intention is * that this event should be emitted periodically to provide a way to * estimate session lengths even in cases where the exit event is not * present (ie: unexpected exit, power loss, process killed by the * user, etc). * * @sa @ref Schema_omni_carb_cloud_1_0::heartbeat_sendEvent(). * @sa @ref Schema_omni_carb_cloud_1_0::heartbeat_isEnabled(). */ #define OMNI_OMNI_CARB_CLOUD_1_0_HEARTBEAT(cloud_link_id_) \ OMNI_STRUCTURED_LOG(omni::telemetry::Schema_omni_carb_cloud_1_0::heartbeat, cloud_link_id_) /** helper macro to send the 'exit' event. * * @param[in] cloud_link_id_ Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] application_ Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @param[in] exit_abnormally_ Parameter from schema at path '/exit_abnormally'. * A flag indicating whether a crash occurred (true) or if a normal * exit was used (false). * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was exited, its * version, whether the exit was clean or not, and the cloud session * ID that needs to be linked to this telemetry session ID. * * @sa @ref Schema_omni_carb_cloud_1_0::exit_sendEvent(). * @sa @ref Schema_omni_carb_cloud_1_0::exit_isEnabled(). */ #define OMNI_OMNI_CARB_CLOUD_1_0_EXIT(cloud_link_id_, application_, exit_abnormally_) \ OMNI_STRUCTURED_LOG( \ omni::telemetry::Schema_omni_carb_cloud_1_0::exit, cloud_link_id_, application_, exit_abnormally_) class Schema_omni_carb_cloud_1_0 { public: /** struct definition for parameter ident of event com.nvidia.omni.carb.cloud.startup. */ struct Struct_startup_ident { /** The identifier of the cluster this pod is running on. */ omni::structuredlog::StringView cluster; /** The identifier of the node this pod is running on. This will be * either a hostname or the IPv4/IPv6 address of the node. */ omni::structuredlog::StringView node; /** Default constructor for @ref Struct_startup_ident. */ Struct_startup_ident() = default; /** Basic constructor for @ref Struct_startup_ident. */ Struct_startup_ident(omni::structuredlog::StringView cluster_, omni::structuredlog::StringView node_) { cluster = cluster_; node = node_; } /** Basic assignment operator for @ref Struct_startup_ident. */ Struct_startup_ident& operator=(const Struct_startup_ident& other) { cluster = other.cluster; node = other.node; return *this; } /** Basic copy constructor for @ref Struct_startup_ident. */ Struct_startup_ident(const Struct_startup_ident& other) { *this = other; } }; /** struct definition for parameter application of event com.nvidia.omni.carb.cloud.startup. */ struct Struct_startup_application { /** The name of the app that is starting up. */ omni::structuredlog::StringView name; /** The version of the app that is starting up. */ omni::structuredlog::StringView version; /** Default constructor for @ref Struct_startup_application. */ Struct_startup_application() = default; /** Basic constructor for @ref Struct_startup_application. */ Struct_startup_application(omni::structuredlog::StringView name_, omni::structuredlog::StringView version_) { name = name_; version = version_; } /** Basic assignment operator for @ref Struct_startup_application. */ Struct_startup_application& operator=(const Struct_startup_application& other) { name = other.name; version = other.version; return *this; } /** Basic copy constructor for @ref Struct_startup_application. */ Struct_startup_application(const Struct_startup_application& other) { *this = other; } }; /** struct definition for parameter application of event com.nvidia.omni.carb.cloud.exit. */ struct Struct_exit_application { /** The name of the app that is starting up. */ omni::structuredlog::StringView name; /** The version of the app that is starting up. */ omni::structuredlog::StringView version; /** Default constructor for @ref Struct_exit_application. */ Struct_exit_application() = default; /** Basic constructor for @ref Struct_exit_application. */ Struct_exit_application(omni::structuredlog::StringView name_, omni::structuredlog::StringView version_) { name = name_; version = version_; } /** Basic assignment operator for @ref Struct_exit_application. */ Struct_exit_application& operator=(const Struct_exit_application& other) { name = other.name; version = other.version; return *this; } /** Basic copy constructor for @ref Struct_exit_application. */ Struct_exit_application(const Struct_exit_application& other) { *this = other; } }; /** the event ID names used to send the events in this schema. These IDs * are used when the schema is first registered, and are passed to the * allocEvent() function when sending the event. */ enum : uint64_t { kStartupEventId = OMNI_STRUCTURED_LOG_EVENT_ID("omni.carb.cloud", "com.nvidia.omni.carb.cloud.startup", "1.0", "0"), kHeartbeatEventId = OMNI_STRUCTURED_LOG_EVENT_ID("omni.carb.cloud", "com.nvidia.omni.carb.cloud.heartbeat", "1.0", "0"), kExitEventId = OMNI_STRUCTURED_LOG_EVENT_ID("omni.carb.cloud", "com.nvidia.omni.carb.cloud.exit", "1.0", "0"), }; Schema_omni_carb_cloud_1_0() = default; /** Register this class with the @ref omni::structuredlog::IStructuredLog interface. * @param[in] flags The flags to pass into @ref omni::structuredlog::IStructuredLog::allocSchema() * This may be zero or more of the @ref omni::structuredlog::SchemaFlags flags. * @returns `true` if the operation succeeded. * @returns `false` if @ref omni::structuredlog::IStructuredLog couldn't be loaded. * @returns `false` if a memory allocation failed. */ static bool registerSchema(omni::structuredlog::IStructuredLog* strucLog) noexcept { return _registerSchema(strucLog); } /** Check whether this structured log schema is enabled. * @param[in] eventId the ID of the event to check the enable state for. * This must be one of the @a k*EventId symbols * defined above. * @returns Whether this client is enabled. */ static bool isEnabled(omni::structuredlog::EventId eventId) noexcept { return _isEnabled(eventId); } /** Enable/disable an event in this schema. * @param[in] eventId the ID of the event to enable or disable. * This must be one of the @a k*EventId symbols * defined above. * @param[in] enabled Whether is enabled or disabled. */ static void setEnabled(omni::structuredlog::EventId eventId, bool enabled) noexcept { _setEnabled(eventId, enabled); } /** Enable/disable this schema. * @param[in] enabled Whether is enabled or disabled. */ static void setEnabled(bool enabled) noexcept { _setEnabled(enabled); } /** event enable check helper functions. * * @param[in] strucLog The structured log object to use to send this event. This * must not be nullptr. It is the caller's responsibility * to ensure that a valid object is passed in. * @returns `true` if the specific event and this schema are both enabled. * @returns `false` if either the specific event or this schema is disabled. * * @remarks These check if an event corresponding to the function name is currently * enabled. These are useful to avoid parameter evaluation before calling * into one of the event emitter functions. These will be called from the * OMNI_STRUCTURED_LOG() macro. These may also be called directly if an event * needs to be emitted manually, but the only effect would be the potential * to avoid parameter evaluation in the *_sendEvent() function. Each * *_sendEvent() function itself will also internally check if the event * is enabled before sending it. * @{ */ static bool startup_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kStartupEventId); } static bool heartbeat_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kHeartbeatEventId); } static bool exit_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kExitEventId); } /** @} */ /** Send the event 'com.nvidia.omni.carb.cloud.startup' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @param[in] cloud_link_id Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] ident Parameter from schema at path '/ident'. * The information of where this pod is running. * @param[in] application Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was launched, * its version, the user, node, and cluster information, and the * cloud session ID that needs to be linked to this telemetry session * ID. */ static void startup_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_startup_ident& ident, const Struct_startup_application& application) noexcept { _startup_sendEvent(strucLog, cloud_link_id, ident, application); } /** Send the event 'com.nvidia.omni.carb.cloud.heartbeat' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @param[in] cloud_link_id Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @returns no return value. * * @remarks This event notes that the app is still running. The intention is * that this event should be emitted periodically to provide a way to * estimate session lengths even in cases where the exit event is not * present (ie: unexpected exit, power loss, process killed by the * user, etc). */ static void heartbeat_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id) noexcept { _heartbeat_sendEvent(strucLog, cloud_link_id); } /** Send the event 'com.nvidia.omni.carb.cloud.exit' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @param[in] cloud_link_id Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] application Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @param[in] exit_abnormally Parameter from schema at path '/exit_abnormally'. * A flag indicating whether a crash occurred (true) or if a normal * exit was used (false). * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was exited, its * version, whether the exit was clean or not, and the cloud session * ID that needs to be linked to this telemetry session ID. */ static void exit_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_exit_application& application, bool exit_abnormally) noexcept { _exit_sendEvent(strucLog, cloud_link_id, application, exit_abnormally); } private: /** This will allow us to disable array length checks in release builds, * since they would have a negative performance impact and only be hit * in unusual circumstances. */ static constexpr bool kValidateLength = CARB_DEBUG; /** body for the registerSchema() public function. */ static bool _registerSchema(omni::structuredlog::IStructuredLog* strucLog) { omni::structuredlog::AllocHandle handle = {}; omni::structuredlog::SchemaResult result; uint8_t* buffer; omni::structuredlog::EventInfo events[3] = {}; size_t bufferSize = 0; size_t total = 0; omni::structuredlog::SchemaFlags flags = 0; if (strucLog == nullptr) { OMNI_LOG_WARN( "no structured log object! The schema " "'Schema_omni_carb_cloud_1_0' " "will be disabled."); return false; } // calculate the tree sizes size_t startup_size = _startup_calculateTreeSize(); size_t heartbeat_size = _heartbeat_calculateTreeSize(); size_t exit_size = _exit_calculateTreeSize(); // calculate the event buffer size bufferSize += startup_size; bufferSize += heartbeat_size; bufferSize += exit_size; // begin schema creation buffer = strucLog->allocSchema("omni.carb.cloud", "1.0", flags, bufferSize, &handle); if (buffer == nullptr) { OMNI_LOG_ERROR("allocSchema failed (size = %zu bytes)", bufferSize); return false; } // register all the events events[0].schema = _startup_buildJsonTree(startup_size, buffer + total); events[0].eventName = "com.nvidia.omni.carb.cloud.startup"; events[0].parserVersion = 0; events[0].eventId = kStartupEventId; total += startup_size; events[1].schema = _heartbeat_buildJsonTree(heartbeat_size, buffer + total); events[1].eventName = "com.nvidia.omni.carb.cloud.heartbeat"; events[1].parserVersion = 0; events[1].eventId = kHeartbeatEventId; total += heartbeat_size; events[2].schema = _exit_buildJsonTree(exit_size, buffer + total); events[2].eventName = "com.nvidia.omni.carb.cloud.exit"; events[2].parserVersion = 0; events[2].eventId = kExitEventId; total += exit_size; result = strucLog->commitSchema(handle, events, CARB_COUNTOF(events)); if (result != omni::structuredlog::SchemaResult::eSuccess && result != omni::structuredlog::SchemaResult::eAlreadyExists) { OMNI_LOG_ERROR( "failed to register structured log events " "{result = %s (%zu)}", getSchemaResultName(result), size_t(result)); return false; } return true; } /** body for the isEnabled() public function. */ static bool _isEnabled(omni::structuredlog::EventId eventId) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); return strucLog != nullptr && strucLog->isEnabled(eventId); } /** body for the setEnabled() public function. */ static void _setEnabled(omni::structuredlog::EventId eventId, bool enabled) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; strucLog->setEnabled(eventId, 0, enabled); } /** body for the setEnabled() public function. */ static void _setEnabled(bool enabled) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; strucLog->setEnabled(kStartupEventId, omni::structuredlog::fEnableFlagWholeSchema, enabled); } #if OMNI_PLATFORM_WINDOWS # pragma warning(push) # pragma warning(disable : 4127) // warning C4127: conditional expression is constant. #endif /** body for the startup_sendEvent() function. */ static void _startup_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_startup_ident& ident, const Struct_startup_application& application) noexcept { omni::structuredlog::AllocHandle handle = {}; // calculate the required buffer size for the event omni::structuredlog::BinaryBlobSizeCalculator calc; { if (kValidateLength && cloud_link_id.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'cloud_link_id' exceeds max value 65535 - " "it will be truncated (size was %zu)", cloud_link_id.length() + 1); } // property cloud_link_id calc.track(cloud_link_id); // property ident { if (kValidateLength && ident.cluster.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'ident.cluster' exceeds max value 65535 - " "it will be truncated (size was %zu)", ident.cluster.length() + 1); } // property ident.cluster calc.track(ident.cluster); if (kValidateLength && ident.node.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'ident.node' exceeds max value 65535 - " "it will be truncated (size was %zu)", ident.node.length() + 1); } // property ident.node calc.track(ident.node); } // property application { if (kValidateLength && application.name.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.name' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.name.length() + 1); } // property application.name calc.track(application.name); if (kValidateLength && application.version.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.version' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.version.length() + 1); } // property application.version calc.track(application.version); } } // write out the event into the buffer void* buffer = strucLog->allocEvent(0, kStartupEventId, 0, calc.getSize(), &handle); if (buffer == nullptr) { OMNI_LOG_ERROR( "failed to allocate a %zu byte buffer for structured log event " "'com.nvidia.omni.carb.cloud.startup'", calc.getSize()); return; } omni::structuredlog::BlobWriter<CARB_DEBUG, _onStructuredLogValidationError> writer(buffer, calc.getSize()); { // property cloud_link_id writer.copy(cloud_link_id); // property ident { // property ident.cluster writer.copy(ident.cluster); // property ident.node writer.copy(ident.node); } // property application { // property application.name writer.copy(application.name); // property application.version writer.copy(application.version); } } strucLog->commitEvent(handle); } /** body for the heartbeat_sendEvent() function. */ static void _heartbeat_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id) noexcept { omni::structuredlog::AllocHandle handle = {}; // calculate the required buffer size for the event omni::structuredlog::BinaryBlobSizeCalculator calc; { if (kValidateLength && cloud_link_id.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'cloud_link_id' exceeds max value 65535 - " "it will be truncated (size was %zu)", cloud_link_id.length() + 1); } // property cloud_link_id calc.track(cloud_link_id); } // write out the event into the buffer void* buffer = strucLog->allocEvent(0, kHeartbeatEventId, 0, calc.getSize(), &handle); if (buffer == nullptr) { OMNI_LOG_ERROR( "failed to allocate a %zu byte buffer for structured log event " "'com.nvidia.omni.carb.cloud.heartbeat'", calc.getSize()); return; } omni::structuredlog::BlobWriter<CARB_DEBUG, _onStructuredLogValidationError> writer(buffer, calc.getSize()); { // property cloud_link_id writer.copy(cloud_link_id); } strucLog->commitEvent(handle); } /** body for the exit_sendEvent() function. */ static void _exit_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_exit_application& application, bool exit_abnormally) noexcept { omni::structuredlog::AllocHandle handle = {}; // calculate the required buffer size for the event omni::structuredlog::BinaryBlobSizeCalculator calc; { if (kValidateLength && cloud_link_id.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'cloud_link_id' exceeds max value 65535 - " "it will be truncated (size was %zu)", cloud_link_id.length() + 1); } // property cloud_link_id calc.track(cloud_link_id); // property application { if (kValidateLength && application.name.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.name' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.name.length() + 1); } // property application.name calc.track(application.name); if (kValidateLength && application.version.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.version' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.version.length() + 1); } // property application.version calc.track(application.version); } // property exit_abnormally calc.track(exit_abnormally); } // write out the event into the buffer void* buffer = strucLog->allocEvent(0, kExitEventId, 0, calc.getSize(), &handle); if (buffer == nullptr) { OMNI_LOG_ERROR( "failed to allocate a %zu byte buffer for structured log event " "'com.nvidia.omni.carb.cloud.exit'", calc.getSize()); return; } omni::structuredlog::BlobWriter<CARB_DEBUG, _onStructuredLogValidationError> writer(buffer, calc.getSize()); { // property cloud_link_id writer.copy(cloud_link_id); // property application { // property application.name writer.copy(application.name); // property application.version writer.copy(application.version); } // property exit_abnormally writer.copy(exit_abnormally); } strucLog->commitEvent(handle); } #if OMNI_PLATFORM_WINDOWS # pragma warning(pop) #endif /** Calculate JSON tree size for structured log event: com.nvidia.omni.carb.cloud.startup. * @returns The JSON tree size in bytes for this event. */ static size_t _startup_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(5); // object has 5 properties { // property cloud_link_id calc.trackName("cloud_link_id"); calc.track(static_cast<const char*>(nullptr)); // property ident calc.trackName("ident"); calc.trackObject(2); // object has 2 properties { // property cluster calc.trackName("cluster"); calc.track(static_cast<const char*>(nullptr)); // property node calc.trackName("node"); calc.track(static_cast<const char*>(nullptr)); } // property application calc.trackName("application"); calc.trackObject(2); // object has 2 properties { // property name calc.trackName("name"); calc.track(static_cast<const char*>(nullptr)); // property version calc.trackName("version"); calc.track(static_cast<const char*>(nullptr)); } // property version calc.trackName("version"); calc.track("1", sizeof("1")); // property event calc.trackName("event"); calc.track("cloud-startup", sizeof("cloud-startup")); } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.omni.carb.cloud.startup. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _startup_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.omni.carb.cloud.startup' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 5); // object has 5 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { // property cloud_link_id result = builder.setName(&base->data.objVal[0], "cloud_link_id"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property ident result = builder.setName(&base->data.objVal[1], "ident"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.createObject(&base->data.objVal[1], 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create a new object node (bad size calculation?)"); return nullptr; } { // property cluster result = builder.setName(&base->data.objVal[1].data.objVal[0], "cluster"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property node result = builder.setName(&base->data.objVal[1].data.objVal[1], "node"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[1], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } } // property application result = builder.setName(&base->data.objVal[2], "application"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.createObject(&base->data.objVal[2], 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create a new object node (bad size calculation?)"); return nullptr; } { // property name result = builder.setName(&base->data.objVal[2].data.objVal[0], "name"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[2].data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property version result = builder.setName(&base->data.objVal[2].data.objVal[1], "version"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[2].data.objVal[1], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } } // property version result = builder.setName(&base->data.objVal[3], "version"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[3], "1", sizeof("1")); if (!result) { OMNI_LOG_ERROR("failed to copy string '1' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[3], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } // property event result = builder.setName(&base->data.objVal[4], "event"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[4], "cloud-startup", sizeof("cloud-startup")); if (!result) { OMNI_LOG_ERROR("failed to copy string 'cloud-startup' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[4], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } } return base; } /** Calculate JSON tree size for structured log event: com.nvidia.omni.carb.cloud.heartbeat. * @returns The JSON tree size in bytes for this event. */ static size_t _heartbeat_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(2); // object has 2 properties { // property cloud_link_id calc.trackName("cloud_link_id"); calc.track(static_cast<const char*>(nullptr)); // property event calc.trackName("event"); calc.track("cloud-heartbeat", sizeof("cloud-heartbeat")); } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.omni.carb.cloud.heartbeat. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _heartbeat_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.omni.carb.cloud.heartbeat' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { // property cloud_link_id result = builder.setName(&base->data.objVal[0], "cloud_link_id"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property event result = builder.setName(&base->data.objVal[1], "event"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1], "cloud-heartbeat", sizeof("cloud-heartbeat")); if (!result) { OMNI_LOG_ERROR("failed to copy string 'cloud-heartbeat' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[1], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } } return base; } /** Calculate JSON tree size for structured log event: com.nvidia.omni.carb.cloud.exit. * @returns The JSON tree size in bytes for this event. */ static size_t _exit_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(4); // object has 4 properties { // property cloud_link_id calc.trackName("cloud_link_id"); calc.track(static_cast<const char*>(nullptr)); // property application calc.trackName("application"); calc.trackObject(2); // object has 2 properties { // property name calc.trackName("name"); calc.track(static_cast<const char*>(nullptr)); // property version calc.trackName("version"); calc.track(static_cast<const char*>(nullptr)); } // property exit_abnormally calc.trackName("exit_abnormally"); calc.track(bool(false)); // property event calc.trackName("event"); calc.track("cloud-exit", sizeof("cloud-exit")); } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.omni.carb.cloud.exit. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _exit_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.omni.carb.cloud.exit' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 4); // object has 4 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { // property cloud_link_id result = builder.setName(&base->data.objVal[0], "cloud_link_id"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property application result = builder.setName(&base->data.objVal[1], "application"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.createObject(&base->data.objVal[1], 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create a new object node (bad size calculation?)"); return nullptr; } { // property name result = builder.setName(&base->data.objVal[1].data.objVal[0], "name"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property version result = builder.setName(&base->data.objVal[1].data.objVal[1], "version"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[1], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } } // property exit_abnormally result = builder.setName(&base->data.objVal[2], "exit_abnormally"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[2], bool(false)); if (!result) { OMNI_LOG_ERROR("failed to set type 'bool' (shouldn't be possible)"); return nullptr; } // property event result = builder.setName(&base->data.objVal[3], "event"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[3], "cloud-exit", sizeof("cloud-exit")); if (!result) { OMNI_LOG_ERROR("failed to copy string 'cloud-exit' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[3], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } } return base; } /** The callback that is used to report validation errors. * @param[in] s The validation error message. */ static void _onStructuredLogValidationError(const char* s) { OMNI_LOG_ERROR("error sending a structured log event: %s", s); } }; // asserts to ensure that no one's modified our dependencies static_assert(omni::structuredlog::BlobWriter<>::kVersion == 0, "BlobWriter version changed"); static_assert(omni::structuredlog::JsonNode::kVersion == 0, "JsonNode version changed"); static_assert(sizeof(omni::structuredlog::JsonNode) == 24, "unexpected size"); static_assert(std::is_standard_layout<omni::structuredlog::JsonNode>::value, "this type needs to be ABI safe"); static_assert(offsetof(omni::structuredlog::JsonNode, type) == 0, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, flags) == 1, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, len) == 2, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, nameLen) == 4, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, name) == 8, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, data) == 16, "struct layout changed"); } // namespace telemetry } // namespace omni OMNI_STRUCTURED_LOG_ADD_SCHEMA(omni::telemetry::Schema_omni_carb_cloud_1_0, omni_carb_cloud, 1_0, 0);
50,954
C
40.225728
120
0.56237
omniverse-code/kit/include/omni/structuredlog/JsonSerializer.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 Module for manually serializing JSON data with low performance overhead. */ #pragma once #include "../../carb/extras/StringSafe.h" #include "../../carb/extras/Utf8Parser.h" #include "../../carb/extras/Base64.h" #include <stdint.h> #include <float.h> namespace omni { namespace structuredlog { /** An interface for consuming the output JSON from the @ref JsonSerializer. */ class JsonConsumer { public: virtual ~JsonConsumer() { } /** The function that will consume strings of JSON. * @param[in] json The string of JSON. * This string's lifetime ends after the return from this call. * @param[in] jsonLen The length of @p json, excluding the null terminator. * The null terminator will be included in the length * when the final call to this writes out a null terminator. * It is possible this may be 0 in some edge cases. * It's possible that @p jsonLen may be used to refer to * a substring of @p json. * @remarks This will be called when the @ref JsonSerializer wants to write * something to the output. * The @ref JsonSerializer will write very small units of text to * this function, so the implementation should plan accordingly. */ virtual void consume(const char* json, size_t jsonLen) noexcept = 0; /** Terminate the output, if needed. * @remarks This will be called to ensure the output is null terminated. */ virtual void terminate() noexcept = 0; }; /** An implementation of @ref JsonConsumer that just counts the length of the * output string. * You may serialize some JSON through this to find the required buffer length, * then allocate the buffer and serialize the JSON again with @ref JsonPrinter * using that allocated buffer. */ class JsonLengthCounter : public JsonConsumer { public: void consume(const char* json, size_t jsonLen) noexcept override { CARB_UNUSED(json); m_count += jsonLen; } void terminate() noexcept override { m_count++; } /** Get the number of bytes that have been consumed so far. * @returns the number of bytes that have been consumed so far. */ size_t getcount() noexcept { return m_count; } private: size_t m_count = 0; }; /** An implementation of @ref JsonConsumer that just prints to a fixed string. */ class JsonPrinter : public JsonConsumer { public: JsonPrinter() { reset(nullptr, 0); } /** Create a printer from a fixed string buffer. * @param[out] output The instance will write to this buffer. * @param[in] outputLen The number of bytes that can be written to @p output. */ JsonPrinter(char* output, size_t outputLen) noexcept { reset(output, outputLen); } /** Reinitialize the printer with a new buffer. * @param[out] output The instance will write to this buffer. * @param[in] outputLen The number of bytes that can be written to @p output. */ void reset(char* output, size_t outputLen) noexcept { m_output = (outputLen == 0) ? nullptr : output; m_left = outputLen; m_overflowed = false; } /** Write a string into the buffer. * @param[in] json The data to write into the buffer. * @param[in] jsonLen The length of @p json, excluding any null terminator. */ void consume(const char* json, size_t jsonLen) noexcept override { size_t w = CARB_MIN(m_left, jsonLen); memcpy(m_output, json, w); m_left -= w; m_output += w; m_overflowed = m_overflowed || w < jsonLen; } void terminate() noexcept override { if (m_output != nullptr) { if (m_left == 0) { m_output[-1] = '\0'; } else { m_output[0] = '\0'; m_output++; m_left--; } } } /** Check whether more data was printed than would fit in the printer's buffer. * @returns `true` if the buffer was too small to fit all the consumed data. * @returns `false` if the buffer was able to fit all the consumed data. */ bool hasOverflowed() noexcept { return m_overflowed; } /** Get the pointer to the next char to be written in the buffer. * @returns The pointer to the next character to be written. * If the buffer has overflowed, this will point past the end of * the buffer. */ char* getNextChar() const noexcept { return m_output; } private: char* m_output; size_t m_left; bool m_overflowed = false; }; /** Anonymous namespace for a helper function */ namespace { void ignoreJsonSerializerValidationError(const char* s) noexcept { CARB_UNUSED(s); } } // namespace /** The prototype of the function to call when a validation error occurs. */ using OnValidationErrorFunc = void (*)(const char*); /** A utility that allows you to easily encode JSON data. * This class won't allocate any memory unless you use an excessive number of scopes. * * @param validate If this is set to true, methods will return false when an * invalid operation is performed. * onValidationError is used for logging because this struct * is used in the logging system, so OMNI_LOG_* cannot be * directly called from within this class. * If this is set to false, methods will assume that all calls * will produce valid JSON data. Invalid calls will write out * invalid JSON data. Methods will only return false if an * unavoidable check failed. * * @tparam prettyPrint If this is set to true, the output will be pretty-printed. * If this is set to false, the output will have no added white space. * * @tparam onValidationError This is a callback that gets executed when a validation * error is triggered, so logging can be called. */ template <bool validate = false, bool prettyPrint = false, OnValidationErrorFunc onValidationError = ignoreJsonSerializerValidationError> class JsonSerializer { public: /** The function that will be called when a validation error occurs. */ OnValidationErrorFunc m_onValidationError = onValidationError; /** Constructor. * @param[in] consumer The object that will consume the output JSON data. * This may not be nullptr. * @param[in] indentLen The number of spaces to indent by when pretty printing is enabled. */ JsonSerializer(JsonConsumer* consumer, size_t indentLen = 4) noexcept { CARB_ASSERT(consumer != nullptr); m_consumer = consumer; m_indentLen = indentLen; } ~JsonSerializer() { // it starts to use heap memory at this point if (m_scopes != m_scopesBuffer) free(m_scopes); } /** Reset the internal state back to where it was after construction. */ void reset() { m_scopesTop = 0; m_firstInScope = true; m_hasKey = false; m_firstPrint = true; m_indentTotal = 0; } /** Write out a JSON key for an object property. * @param[in] key The string value for the key. * This can be nullptr. * @param[in] keyLen The length of @p key, excluding the null terminator. * @returns whether or not validation succeeded. */ bool writeKey(const char* key, size_t keyLen) noexcept { if (validate) { if (CARB_UNLIKELY(getCurrentScope() != ScopeType::eObject)) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "attempted to write a key outside an object" " {key name = '%s', len = %zu}", key, keyLen); onValidationError(tmp); return false; } if (CARB_UNLIKELY(m_hasKey)) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "attempted to write out two key names in a row" " {key name = '%s', len = %zu}", key, keyLen); onValidationError(tmp); return false; } } if (!m_firstInScope) m_consumer->consume(",", 1); prettyPrintHook(); m_consumer->consume("\"", 1); if (key != nullptr) m_consumer->consume(key, keyLen); m_consumer->consume("\":", 2); m_firstInScope = false; if (validate) m_hasKey = true; return true; } /** Write out a JSON key for an object property. * @param[in] key The key name for this property. * This may be nullptr. * @returns whether or not validation succeeded. */ bool writeKey(const char* key) noexcept { return writeKey(key, key == nullptr ? 0 : strlen(key)); } /** Write out a JSON null value. * @returns whether or not validation succeeded. */ bool writeValue() noexcept { if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("null", sizeof("null") - 1); if (validate) m_hasKey = false; return true; } /** Write out a JSON boolean value. * @param[in] value The boolean value. * @returns whether or not validation succeeded. */ bool writeValue(bool value) noexcept { const char* val = value ? "true" : "false"; size_t len = (value ? sizeof("true") : sizeof("false")) - 1; if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume(val, len); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. */ bool writeValue(int32_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRId32, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. */ bool writeValue(uint32_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRIu32, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. * @note 64 bit integers are stored as double precision floats in JavaScript's * JSON library, so a JSON library with BigInt support should be * used instead when reading 64 bit numbers. */ bool writeValue(int64_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRId64, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. * @note 64 bit integers are stored as double precision floats in JavaScript's * JSON library, so a JSON library with BigInt support should be * used instead when reading 64 bit numbers. */ bool writeValue(uint64_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRIu64, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON double (aka number) value. * @param[in] value The double value. * @returns whether or not validation succeeded. */ bool writeValue(double value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString( buffer, CARB_COUNTOF(buffer), "%.*g", std::numeric_limits<double>::max_digits10, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON float (aka number) value. * @param[in] value The double value. * @returns whether or not validation succeeded. */ bool writeValue(float value) noexcept { return writeValue(double(value)); } /** Write out a JSON string value. * @param[in] value The string value. * This can be nullptr if @p len is 0. * @param[in] len The length of @p value, excluding the null terminator. * @returns whether or not validation succeeded. */ bool writeValue(const char* value, size_t len) noexcept { size_t last = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("\"", 1); for (size_t i = 0; i < len;) { const carb::extras::Utf8Parser::CodeByte* next = carb::extras::Utf8Parser::nextCodePoint(value + i, len - i); if (next == nullptr) { m_consumer->consume(value + last, i - last); m_consumer->consume("\\u0000", 6); i++; last = i; continue; } // early out for non-escape characters // multi-byte characters never need to be escaped if (size_t(next - value) > i + 1 || (value[i] > 0x1F && value[i] != '"' && value[i] != '\\')) { i = next - value; continue; } m_consumer->consume(value + last, i - last); switch (value[i]) { case '"': m_consumer->consume("\\\"", 2); break; case '\\': m_consumer->consume("\\\\", 2); break; case '\b': m_consumer->consume("\\b", 2); break; case '\f': m_consumer->consume("\\f", 2); break; case '\n': m_consumer->consume("\\n", 2); break; case '\r': m_consumer->consume("\\r", 2); break; case '\t': m_consumer->consume("\\t", 2); break; default: { char tmp[] = "\\u0000"; tmp[4] = getHexChar(uint8_t(value[i]) >> 4); tmp[5] = getHexChar(value[i] & 0x0F); m_consumer->consume(tmp, CARB_COUNTOF(tmp) - 1); } break; } i++; last = i; } if (len > last) m_consumer->consume(value + last, len - last); m_consumer->consume("\"", 1); if (validate) m_hasKey = false; return true; } /** Write out a JSON string value. * @param[in] value The string value. * This can be nullptr. * @returns whether or not validation succeeded. */ bool writeValue(const char* value) noexcept { return writeValue(value, value == nullptr ? 0 : strlen(value)); } /** Write a binary blob into the output JSON as a base64 encoded string. * @param[in] value_ The binary blob to write in. * @param[in] size The number of bytes of data in @p value_. * @returns whether or not validation succeeded. * @remarks This will take the input string and encode it in base64, then * store that as base64 data in a string. */ bool writeValueWithBase64Encoding(const void* value_, size_t size) { char buffer[4096]; const size_t readSize = carb::extras::Base64::getEncodeInputSize(sizeof(buffer)); const uint8_t* value = static_cast<const uint8_t*>(value_); if (CARB_UNLIKELY(!writeValuePrologue())) return false; m_consumer->consume("\"", 1); for (size_t i = 0; i < size; i += readSize) { size_t written = m_base64Encoder.encode(value + i, CARB_MIN(readSize, size - i), buffer, sizeof(buffer)); m_consumer->consume(buffer, written); } m_consumer->consume("\"", 1); if (validate) m_hasKey = false; return true; } /** Begin a JSON array. * @returns whether or not validation succeeded. * @returns false if a memory allocation failed. */ bool openArray() noexcept { if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("[", 1); m_firstInScope = true; if (!pushScope(ScopeType::eArray)) return false; prettyPrintOpenScope(); if (validate) m_hasKey = false; return true; } /** Finish writing a JSON array. * @returns whether or not validation succeeded. */ bool closeArray() noexcept { if (validate && CARB_UNLIKELY(getCurrentScope() != ScopeType::eArray)) { onValidationError("attempted to close an array that was never opened"); return false; } popScope(); prettyPrintCloseScope(); prettyPrintHook(); m_consumer->consume("]", 1); m_firstInScope = false; if (validate) m_hasKey = false; return true; } /** Begin a JSON object. * @returns whether or not validation succeeded. * @returns false if a memory allocation failed. */ bool openObject() noexcept { if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("{", 1); m_firstInScope = true; pushScope(ScopeType::eObject); prettyPrintOpenScope(); if (validate) m_hasKey = false; return true; } /** Finish writing a JSON object. * @returns whether or not validation succeeded. */ bool closeObject() noexcept { if (validate && CARB_UNLIKELY(getCurrentScope() != ScopeType::eObject)) { onValidationError("attempted to close an object that was never opened"); return false; } popScope(); prettyPrintCloseScope(); prettyPrintHook(); m_consumer->consume("}", 1); m_firstInScope = false; if (validate) m_hasKey = false; return true; } /** Finish writing your JSON. * @returns whether or not validation succeeded. */ bool finish() noexcept { bool result = true; // check whether we are ending in the middle of an object/array if (validate && getCurrentScope() != ScopeType::eGlobal) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "finished writing in the middle of an %s", getCurrentScope() == ScopeType::eArray ? "array" : "object"); onValidationError(tmp); result = false; } if (prettyPrint) m_consumer->consume("\n", 1); m_consumer->terminate(); return result; } private: /** The type of a scope in the scope stack. */ enum class ScopeType : uint8_t { eGlobal, /**< global scope (not in anything). */ eArray, /**< JSON array type. (e.g. []) */ eObject, /**< JSON object type. (e.g. {}) */ }; /** A hook used before JSON elements to perform pretty print formatting. */ void prettyPrintHook() noexcept { if (prettyPrint) { const size_t s = CARB_COUNTOF(m_indent) - 1; if (!m_firstPrint) m_consumer->consume("\n", 1); m_firstPrint = false; for (size_t i = s; i <= m_indentTotal; i += s) m_consumer->consume(m_indent, s); m_consumer->consume(m_indent, m_indentTotal % s); } } /** A hook used before printing a value element to perform pretty print formatting. */ void prettyPrintValueHook() noexcept { if (prettyPrint) { if (getCurrentScope() != ScopeType::eObject) return prettyPrintHook(); else /* if it's in an object, a key preceded this so this should be on the same line */ m_consumer->consume(" ", 1); } } /** Track when a scope was opened for pretty print indenting. */ void prettyPrintOpenScope() noexcept { if (prettyPrint) m_indentTotal += m_indentLen; } /** Track when a scope was closed for pretty print indenting. */ void prettyPrintCloseScope() noexcept { if (prettyPrint) m_indentTotal -= m_indentLen; } /** A common prologue to writeValue() functions. * @returns Whether validation succeeded. */ inline bool writeValuePrologue() noexcept { if (validate) { // the global scope is only allowed to have one item in it if (CARB_UNLIKELY(getCurrentScope() == ScopeType::eGlobal && !m_firstInScope)) { onValidationError("attempted to put multiple values into the global scope"); return false; } // if we're in an object, a key needs to have been written before each value if (CARB_UNLIKELY(getCurrentScope() == ScopeType::eObject && !m_hasKey)) { onValidationError("attempted to write a value without a key inside an object"); return false; } } if (getCurrentScope() == ScopeType::eArray && !m_firstInScope) m_consumer->consume(",", 1); m_firstInScope = false; return true; } bool pushScope(ScopeType s) noexcept { if (m_scopesTop == m_scopesLen) { size_t newLen = m_scopesTop + 64; size_t size = sizeof(*m_scopes) * newLen; void* tmp; if (m_scopes == m_scopesBuffer) tmp = malloc(size); else tmp = realloc(m_scopes, size); if (tmp == nullptr) { char log[256]; carb::extras::formatString(log, sizeof(log), "failed to allocate %zu bytes", size); onValidationError(log); return false; } if (m_scopes == m_scopesBuffer) memcpy(tmp, m_scopes, sizeof(*m_scopes) * m_scopesLen); m_scopes = static_cast<ScopeType*>(tmp); m_scopesLen = newLen; } m_scopes[m_scopesTop++] = s; return true; } void popScope() noexcept { m_scopesTop--; } ScopeType getCurrentScope() noexcept { if (m_scopesTop == 0) return ScopeType::eGlobal; return m_scopes[m_scopesTop - 1]; } char getHexChar(uint8_t c) noexcept { char lookup[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; CARB_ASSERT(c < CARB_COUNTOF(lookup)); return lookup[c]; } ScopeType m_scopesBuffer[8]; ScopeType* m_scopes = m_scopesBuffer; size_t m_scopesLen = CARB_COUNTOF(m_scopesBuffer); size_t m_scopesTop = 0; /** The consumer of the output JSON data. */ JsonConsumer* m_consumer; /** This flag is the current key/value being written is the first one inside * the current scope (this decides comma placement). */ bool m_firstInScope = true; /** This is set when a key has been specified. * This is done for validation. */ bool m_hasKey = false; /** This is true when the first character has not been printed yet. * This is used for pretty printing. */ bool m_firstPrint = true; /** The indent buffer used for pretty printing. */ char m_indent[33] = " "; /** The length into m_indent to print for the pretty-printing indent. */ size_t m_indentTotal = 0; /** The length of an individual indent when pretty-printing. */ size_t m_indentLen = 4; /** The base64 encoder. This is just cached here to improve performance. */ carb::extras::Base64 m_base64Encoder; }; } // namespace structuredlog } // namespace omni
26,725
C
29.474344
137
0.551356
omniverse-code/kit/include/omni/structuredlog/StructuredLogSettingsUtils.h
// Copyright (c) 2021-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 the carb::settings::ISettings settings for structured logging. */ #pragma once #include "IStructuredLog.h" #include "IStructuredLogExtraFields.h" #include "IStructuredLogSettings.h" #include "IStructuredLogSettings2.h" #include "IStructuredLogFromILog.h" #include "../../carb/extras/StringSafe.h" #include "../../carb/settings/ISettings.h" #include "../extras/PrivacySettings.h" #include "../extras/OmniConfig.h" #include "../log/ILog.h" namespace omni { namespace structuredlog { /** Constants for default and minimum values for various settings. * @{ */ /** The default value for the log size limit in bytes. * See IStructuredLogSettings::setLogSizeLimit() for details. */ constexpr int64_t kDefaultLogSizeLimit = 50ll * 1024ll * 1024ll; /** The minimum value that can be set for the log size limit in bytes. * See IStructuredLogSettings::setLogSizeLimit() for details. */ constexpr int64_t kMinLogSizeLimit = 256ll * 1024ll; /** The default log retention setting. * See IStructuredLogSettings::setLogRetentionCount() for details. */ constexpr size_t kDefaultLogRetentionCount = 3; /** The minimum allowed log retention setting. * See IStructuredLogSettings::setLogRetentionCount() for details. */ constexpr size_t kMinLogRetentionCount = 1; /** The default value for the event queue size in bytes. * See IStructuredLogSettings::setEventQueueSize() for details. */ constexpr size_t kDefaultEventQueueSize = 2 * 1024 * 1024; /** The minimum allowed event queue size in bytes. * See IStructuredLogSettings::setEventQueueSize() for details. */ constexpr size_t kMinEventQueueSize = 512 * 1024; /** The maximum allowed event queue size in bytes. * See IStructuredLogSettings::setEventQueueSize() for details. */ constexpr size_t kMaxEventQueueSize = 1024 * 1024 * 1024; /** The default mode for generating event IDs. * See IStructuredLogSettings::setEventIdMode() for details. */ constexpr IdMode kDefaultIdMode = IdMode::eFastSequential; /** The default type of event ID to generate. * See IStructuredLogSettings::setEventIdMode() for details. */ constexpr IdType kDefaultIdType = IdType::eUuid; /** Special value to indicate that the heartbeat event should be disabled. Any other value * will indicate that the heartbeat events will be generated. */ constexpr uint64_t kHeartbeatDisabled = 0; /** The default minimum time between heartbeat events in seconds. This can be * @ref kHeartbeatDisabled to indicate that the heartbeat events are disabled. For more * details, please see IStructuredLogSettings2::setHeartbeatPeriod(). */ constexpr uint64_t kDefaultHeartbeatPeriod = kHeartbeatDisabled; /** The default state for whether headers will be added to each written log file. For * more details, please see IStructuredLogSettings2::setNeedsLogHeaders(). */ constexpr bool kDefaultNeedLogHeaders = true; /** The default state for whether the CloudEvents wrapper will be output with each message. * By default, all messages will be emitted as CloudEvents 1.0 compliant messages. The * omni::structuredlog::IStructuredLogSettings2::setOutputFlags() function or the * @ref kEmitPayloadOnlySettings setting can be used to change this setting. */ constexpr bool kDefaultEmitPayloadOnlySettings = false; /** The default state for whether the cloud heartbeat events will be emitted. For these * events to be emitted, the normal heartbeat event must also be enabled with * @ref kHeartbeatPeriodSetting. These cloud heartbeat events are effectively duplicate * data and are not strictly necessary. */ constexpr bool kDefaultEmitCloudHeartbeat = false; /** @} */ /** Names for various settings that can be used to override some of the default settings. Note * that these will not override any values that are explicitly set by the host app itself. * @{ */ /** Global enable/disable for structured logging. When set to `false`, the structured log system * will be disabled. This will prevent any event messages from being written out unless the * host app explicitly wants them to. When set to `true`, the structured log system will be * enabled and event messages will be emitted normally. This defaults to `false`. */ constexpr const char* kGlobalEnableSetting = "/structuredLog/enable"; /** Specifies the directory that log files should be written to. This is also the directory that * the telemetry transmitter app will check for when enumerating and consuming logs. This must * always be a local path and may be either absolute or relative. The default location is * `$HOME/.nvidia-omniverse/logs/` (where ``$HOME`` is ``%USERPROFILE%`` on Windows and the usual * meaning on POSIX platforms). This setting is mainly intended for testing and the default * directory should be used whenever possible. If this setting is used in a Kit launch (either * on command line or in a config file), it will be passed on to the telemetry transmitter app * when it gets launched. */ constexpr const char* kLogDirectory = "/structuredLog/logDirectory"; /** The default log name to use. If a default log name is set, all events that do not use the * @ref fEventFlagUseLocalLog flag will write their messages to this log file. Events that * do use the @ref fEventFlagUseLocalLog flag will write only to their schema's log file. This * value must be only the log file's name, not including its path. The logs will always be * created in the structured logging system's current log output path. As a special case, this * may also be set to either "/dev/stdout" or "/dev/stderr" (on all platforms) to output all * events directly to stdout or stderr respectively. When one of these log names are used, all * events will be unconditionally written to stdout/stderr regardless of their event or schema * flags. There will also be no log header written out when events are being sent to stdout or * stderr. This defaults to an empty string. */ constexpr const char* kDefaultLogNameSetting = "/structuredLog/defaultLogName"; /** The setting path for the privacy settings file to load. This allows the default location of * the privacy settings file to be overridden. The default location for the privacy settings * file is `$HOME/.nvidia-omniverse/config/privacy.toml` on all platforms, where `$HOME` on * Windows is `%USERPROFILE%). Note that even if this setting is used and it points to a valid * file, the settings from the default `privacy.toml` file will still be loaded first if it * is present. The settings in the file specified here will simply override any settings given * in the default file. This allows any missing settings in the new file to still be provided * by what was present in the default file's location. */ constexpr const char* kPrivacyFileSetting = "/structuredLog/privacySettingsFile"; /** The setting path for the log retention count. This controls how many log files will be * left in the log directory when a log rotation occurs. When a log file reaches its size * limit, it is renamed and a new empty log with the original name is created. A rolling * history of the few most recent logs is maintained after a rotation. This setting controls * exactly how many of each log will be retained after a rotation. This defaults to 3. */ constexpr const char* kLogRetentionCountSetting = "/structuredLog/logRetentionCount"; /** The setting path for the log size limit in megabytes. When a log file reaches this size, * it is rotated out by renaming it and creating a new log file with the original name. If * too many logs exist after this rotation, the oldest one is deleted. This defaults to 50MB. */ constexpr const char* kLogSizeLimitSetting = "/structuredLog/logSizeLimit"; /** The setting path for the size of the event queue buffer in kilobytes. The size of the * event queue controls how many messages can be queued in the message processing queue before * events start to get dropped (or a stall potentially occurs). The event queue can fill up * if the app is emitting messages from multiple threads at a rate that is higher than they * can be processed or written to disk. In general, there should not be a situation where * the app is emitting messages at a rate that causes the queue to fill up. However, this * may be beyond the app's control if (for example) the drive the log is being written to * is particularly slow or extremely busy. This defaults to 2048KB. */ constexpr const char* kEventQueueSizeSetting = "/structuredLog/eventQueueSize"; /** The setting path for the event identifier mode. This controls how event identifiers are * generated. Valid values are 'fast-sequential', `sequential`, and `random`. Each has its * own benefits and drawbacks: * * `sequential` ensures that all generated event IDs are in sequential order. When the * event ID type is set to `UUID`, this will ensure that each generated event ID can be * easily sorted after the previous one. With a UUID type ID, this mode can be expensive * to generate. With a `uint64` ID, this is the most performant to generate. * * `fast-sequential` is only effective when the event ID type is set to 'UUID'. In this * mode, the UUIDs that are generated are sequential, but in memory order, not lexicographical * order. It takes some extra effort to sort these events on the data analysis side, but * they are generated very quickly. When the event ID type is not 'UUID', this mode behaves * in the same way as `sequential`. * * `random` generates a random event ID for each new event. This does not preserve any * kind of order of events. If the app does not require sequential events, this can be * more performant to generate especially for UUIDs. * * This defaults to 'fast-sequential. This setting is not case sensitive. */ constexpr const char* kEventIdModeSetting = "/structuredLog/eventIdMode"; /** The setting path for the event identifier data type. This determines what kind of event * ID will be generated for each new event and how it will be printed out with each message. * The following types are supported: * * `UUID` generates a 128 bit universally unique identifier. The event ID mode determines * how one event ID will be related to the next. This is printed into each event message * in the standard UUID format ("00000000-0000-0000-0000-000000000000"). This type provides * the most uniqueness and room for scaling in large data sets. * * `uint64` generates a 64 bit integer identifier. The event ID mode determines how one * event ID will be related to the next. This is printed into each event message as a * simple decimal integer value. * * This defaults to 'UUID'. This setting is not case sensitive. */ constexpr const char* kEventIdTypeSetting = "/structuredLog/eventIdType"; /** The setting path for the log consumer toggle. This enables or disables the redirection * of normal Carbonite (ie: `CARB_LOG_*()`) and Omni (ie: `OMNI_LOG_*()`) messages as structured * log events as well. The log messages will still go to their original destination (stdout, * stderr, log file, MSVC output window, etc) as well. This defaults to `false`. */ constexpr const char* kEnableLogConsumerSetting = "/structuredLog/enableLogConsumer"; /** The setting path that will contain zero or more keys that will be used to disable schemas * when they are first registered. Each key under this setting will have a name that matches * zero or schema names. From a .schema file, this would match the "name" property. From a * JSON schema file, this would match the @a `#/schemaMeta/clientName` property. The key's * value is expected to be a boolean that indicates whether it is enabled upon registration. * * The names of the keys under this path may either be a schema's full name or a wildcard * string that matches to zero or more schema names. In either version, the case of the * non-wildcard portions of the key name is important. The wildcard characters '*' (match * to zero or more characters) and '?' (match to exactly one character) may be used. This * is only meant to be a simple wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * schemas: * @rst .. code-block:: toml [structuredLog.state.schemas] "omni.test_schema" = false # disable 'omni.test_schema' on registration. "omni.other_schema" = true # enable 'omni.other_schema' on registration. "carb.*" = false # disable all schemas starting with 'carb.'. @endrst * * @note The keys in this setting path are inherently unordered. If a set of dependent * enable/disable settings is needed, the @ref kSchemasStateArraySetting setting path * should be used instead. This other setting allows an array to be specified that * preserves the order of keys. This is useful for doing things like disabling all * schemas then only enabling a select few. */ constexpr const char* kSchemasStateListSetting = "/structuredLog/state/schemas"; /** The setting path that will contain zero or more keys that will be used to disable events * when they are first registered. Each key under this setting will have a name that matches * zero or event names. From a .schema file, this would match the "namespace" property plus * one of the properties under @a `#/events/`. From a JSON schema file, this would match one * of the event properties under @a `#/definitions/events/`. The key's value is expected to * be a boolean that indicates whether it is enabled upon registration. * * The names of the keys under this path may either be an event's full name or a wildcard * string that matches to zero or more event names. In either version, the case of the * non-wildcard portions of the key name is important. The wildcard characters '*' (match * to zero or more characters) and '?' (match to exactly one character) may be used. This * is only meant to be a simple wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * events: * @rst .. code-block:: toml [structuredLog.state.events] "com.nvidia.omniverse.fancy_event" = false "com.nvidia.carbonite.*" = false # disable all 'com.nvidia.carbonite' events. @endrst * * @note The keys in this setting path are inherently unordered. If a set of dependent * enable/disable settings is needed, the @ref kEventsStateArraySetting setting path * should be used instead. This other setting allows an array to be specified that * preserves the order of keys. This is useful for doing things like disabling all * events then only enabling a select few. */ constexpr const char* kEventsStateListSetting = "/structuredLog/state/events"; /** The setting path to an array that will contain zero or more values that will be used to * disable or enable schemas when they are first registered. Each value in this array will * have a name that matches zero or more schema names. From a .schema file, this would match the * "name" property. From a JSON schema file, this would match the @a `#/schemaMeta/clientName` * property. The schema name may be optionally prefixed by either '+' or '-' to enable or * disable (respectively) matching schemas. Alternatively, the schema's name may be assigned * a boolean value to indicate whether it is enabled or not. If neither a '+'/'-' prefix nor * a boolean assignment suffix is specified, 'enabled' is assumed. * * The names in this array either be a schema's full name or a wildcard string that matches * to zero or more schema names. In either version, the case of the non-wildcard portions * of the key name is important. The wildcard characters '*' (match to zero or more characters) * and '?' (match to exactly one character) may be used. This is only meant to be a simple * wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * schemas: * @rst .. code-block:: toml structuredLog.schemaStates = [ "-omni.test_schema", # disable 'omni.test_schema' on registration. "omni.other_schema = true", # enable 'omni.other_schema' on registration. "-carb.*" # disable all schemas starting with 'carb.'. ] @endrst * * @note TOML does not allow static arrays such as above to be appended to with later lines. * Attempting to do so will result in a parsing error. */ constexpr const char* kSchemasStateArraySetting = "/structuredLog/schemaStates"; /** The setting path to an array that will contain zero or more values that will be used to * disable or enable events when they are first registered. Each value in this array will * have a name that matches zero or more event names. From a .schema file, this would match one * of the property names under `#/events/`. From a JSON schema file, this would match one * of the event object names in @a `#/definitions/events/`. The event name may be optionally * prefixed by either '+' or '-' to enable or disable (respectively) matching event(s). * Alternatively, the event's name may be assigned a boolean value to indicate whether it is * enabled or not. If neither a '+'/'-' prefix nor a boolean assignment suffix is specified, * 'enabled' is assumed. * * The names in this array either be an event's full name or a wildcard string that matches * to zero or more event names. In either version, the case of the non-wildcard portions * of the array entry name is important. The wildcard characters '*' (match to zero or more characters) * and '?' (match to exactly one character) may be used. This is only meant to be a simple * wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * schemas: * @rst .. code-block:: toml structuredLog.schemaStates = [ "-com.nvidia.omniverse.fancy_event", "com.nvidia.carbonite.* = false" # disable all 'com.nvidia.carbonite' events. ] @endrst * * @note that TOML does not allow static arrays such as above to be appended to with later lines. * Attempting to do so will result in a parsing error. */ constexpr const char* kEventsStateArraySetting = "/structuredLog/eventStates"; /** The setting path that will contain the minimum number of seconds between heartbeat events * A heartbeat event is one that is sent periodically to help calculate session lengths even * if the expected 'exit' or 'crash' process lifetime events are missing. These events can * be missing in such unavoidable cases as a power loss, the user killing the process, a blue * screen of death or kernel panic, etc. These situations cannot be assumed as either crashes * or normal exits, but at least these events can help indicate how long the actual session was. * This can be set to 0 to disable the heartbeat messages. By default the heartbeat events are * disabled (ie: set to @ref kHeartbeatDisabled). */ constexpr const char* kHeartbeatPeriodSetting = "/structuredLog/heartbeatPeriod"; /** The setting path that will indicate whether headers will be added to each log file that is * written to disk. Each log file will have one header on the first line that is a JSON object * that indicates the origin of the log and the version of the `omni.structuredlog.plugin` * plugin that created it. This header object is followed by whitespace to allow it to be * modified later as needed without having to rewrite the entire file. The telemetry transmitter * consumes this header object and modifies it to indicate its processing progress. Without * this header, the telemetry transmitter will ignore the log file. This setting defaults to * `true`. */ constexpr const char* kNeedLogHeadersSetting = "/structuredLog/needLogHeaders"; /** The setting path that will indicate whether the CloudEvents wrapper should be added to the * payload of each emitted event. By default, each event will be emitted as a CloudEvent * compliant JSON object. If this setting is enabled, the CloudEvent wrapper will be skipped * and only the schema's defined payload for the event will be emitted. The main payload will * be emitted as the top level object in the JSON output when this setting is enabled. * * Note that when this setting is used, the output will be incompatible with the telemetry * transmitter and the rest of the Omniverse telemetry toolchain. If a host app decides to * use this feature, they will be responsible for including all the relevant information that * would normally be part of the CloudEvents header. This includes fields such as the user * ID, event type, event schema, event ID, etc. This setting defaults to `false`. */ constexpr const char* kEmitPayloadOnlySettings = "/structuredLog/emitPayloadOnly"; /** The setting path that will indicate whether the cloud heartbeat events will be enabled. * These will only be emitted if the normal heartbeat events are also enabled * (with @ref kHeartbeatPeriodSetting). These events are effectively duplicate data and * are not strictly necessary. This defaults to `false`. */ constexpr const char* kEmitCloudHeartbeatSetting = "/structuredLog/emitCloudHeartbeat"; /** The settings branch that will be expected to contain zero or more key/value pairs for extra * fields to be added to each output message. This branch will only be parsed once on startup. * Any extra dynamic fields that need to be added at runtime need to be added or removed * programmatically using the `omni::structuredlog::IStructuredLogExtraFields` interface. * Only string values will be accepted under this branch. By default this settings branch * is expected to be empty and no extra fields will be added. * * Note that the number of extra fields added should be kept to a minimum required count and * size since they can affect both output and transmission performance. */ constexpr const char* kExtraFieldsSettingBranch = "/structuredLog/extraFields"; /** @} */ /** Enables or disables the structured logging log message redirection. * * @param[in] enabled Set to ``true`` to enable structured logging log message redirection. * Set to ``false`` to disable structured logging log message redirection. * @returns ``true`` if logging redirection was successfully enabled. Returns ``false`` * otherwise * * This enables or disables structured logging log message redirection. This system * will monitor log messages and emit them as structured log messages. */ inline bool setStructuredLogLoggingEnabled(bool enabled = true) { omni::core::ObjectPtr<IStructuredLog> strucLog; omni::core::ObjectPtr<IStructuredLogFromILog> log; strucLog = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); if (strucLog.get() == nullptr) return false; log = strucLog.as<IStructuredLogFromILog>(); if (log.get() == nullptr) return false; if (enabled) log->enableLogging(); else log->disableLogging(); return true; } /** Checks the settings registry for structured log settings and makes them active. * * @param[in] settings The settings interface to use to retrieve configuration values. * This may not be `nullptr`. * @returns No return value. * * @remarks This sets appropriate default values for all the structured log related settings then * attempts to retrieve their current values and set them as active. This assumes * that the settings hive has already been loaded from disk and made active in the * main settings registry. * * @thread_safety This call is thread safe. */ inline void configureStructuredLogging(carb::settings::ISettings* settings) { omni::core::ObjectPtr<IStructuredLog> strucLog; omni::core::ObjectPtr<IStructuredLogSettings> ts; omni::core::ObjectPtr<IStructuredLogSettings2> ts2; omni::core::ObjectPtr<IStructuredLogFromILog> log; omni::core::ObjectPtr<IStructuredLogExtraFields> extraFields; const char* value; int64_t count; IdMode idMode = kDefaultIdMode; IdType idType = kDefaultIdType; if (settings == nullptr) return; // ****** set appropriate defaults for each setting ****** settings->setDefaultBool(kGlobalEnableSetting, false); settings->setDefaultString(kLogDirectory, ""); settings->setDefaultString(kDefaultLogNameSetting, ""); settings->setDefaultInt64(kLogRetentionCountSetting, kDefaultLogRetentionCount); settings->setDefaultInt64(kLogSizeLimitSetting, kDefaultLogSizeLimit / 1048576); settings->setDefaultInt64(kEventQueueSizeSetting, kDefaultEventQueueSize / 1024); settings->setDefaultString(kEventIdModeSetting, "fast-sequential"); settings->setDefaultString(kEventIdTypeSetting, "UUID"); settings->setDefaultBool(kEnableLogConsumerSetting, false); settings->setDefaultInt64(kHeartbeatPeriodSetting, kDefaultHeartbeatPeriod); settings->setDefaultBool(kNeedLogHeadersSetting, kDefaultNeedLogHeaders); settings->setDefaultBool(kEmitPayloadOnlySettings, kDefaultEmitPayloadOnlySettings); settings->setDefaultBool(kEmitCloudHeartbeatSetting, kDefaultEmitCloudHeartbeat); // ****** grab the structured log settings object so the config can be set ****** strucLog = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); if (strucLog.get() == nullptr) return; ts = strucLog.as<IStructuredLogSettings>(); if (ts.get() == nullptr) return; // ****** retrieve the settings and make them active ****** strucLog->setEnabled(omni::structuredlog::kBadEventId, omni::structuredlog::fEnableFlagAll, settings->getAsBool(kGlobalEnableSetting)); // set the default log name. value = settings->getStringBuffer(kDefaultLogNameSetting); if (value != nullptr && value[0] != 0) ts->setLogDefaultName(value); value = settings->getStringBuffer(kLogDirectory); if (value != nullptr && value[0] != 0) { ts->setLogOutputPath(value); } else { // This setting needs to be reloaded after ISerializer has been loaded, since it can read // omniverse.toml now in case there are overrides there. extras::OmniConfig config; ts->setLogOutputPath(config.getBaseLogsPath().c_str()); } // set the log retention count. count = settings->getAsInt64(kLogRetentionCountSetting); ts->setLogRetentionCount(count); // set the log size limit. count = settings->getAsInt64(kLogSizeLimitSetting); ts->setLogSizeLimit(count * 1048576); // set the event queue size. count = settings->getAsInt64(kEventQueueSizeSetting); ts->setEventQueueSize(count * 1024); // set the event ID mode. value = settings->getStringBuffer(kEventIdModeSetting); if (carb::extras::compareStringsNoCase(value, "fast-sequential") == 0) idMode = IdMode::eFastSequential; else if (carb::extras::compareStringsNoCase(value, "sequential") == 0) idMode = IdMode::eSequential; else if (carb::extras::compareStringsNoCase(value, "random") == 0) idMode = IdMode::eRandom; else OMNI_LOG_WARN("unknown event ID mode '%s'. Assuming 'fast-sequential'.", value); // set the event ID type. value = settings->getStringBuffer(kEventIdTypeSetting); if (carb::extras::compareStringsNoCase(value, "UUID") == 0) idType = IdType::eUuid; else if (carb::extras::compareStringsNoCase(value, "uint64") == 0) idType = IdType::eUint64; else OMNI_LOG_WARN("unknown event ID type '%s'. Assuming 'UUID'.", value); ts->setEventIdMode(idMode, idType); // load the privacy settings and set the user ID from it. ts->loadPrivacySettings(); // load the enable states for each schema and event. ts->enableSchemasFromSettings(); value = omni::extras::PrivacySettings::getUserId(); if (value != nullptr && value[0] != 0) ts->setUserId(value); // setup the structured log logger. log = strucLog.as<IStructuredLogFromILog>(); if (log.get() == nullptr) return; if (settings->getAsBool(kEnableLogConsumerSetting)) log->enableLogging(); // setup the default heartbeat event period. ts2 = strucLog.as<IStructuredLogSettings2>(); if (ts2 != nullptr) { OutputFlags flags = fOutputFlagNone; count = settings->getAsInt64(kHeartbeatPeriodSetting); ts2->setHeartbeatPeriod(count); if (!settings->getAsBool(kNeedLogHeadersSetting)) flags |= fOutputFlagSkipLogHeaders; if (settings->getAsBool(kEmitPayloadOnlySettings)) flags |= fOutputFlagPayloadOnly; if (settings->getAsBool(kEmitCloudHeartbeatSetting)) flags |= fOutputFlagEmitCloudHeartbeat; ts2->setOutputFlags(flags, 0); } extraFields = strucLog.as<IStructuredLogExtraFields>(); if (extraFields != nullptr) { // walk through the extra fields branch of the settings registry and add an extra field // for each key/value pair in there. In general we don't expect there to be more than // a couple extra fields present. if (settings->isAccessibleAs(carb::dictionary::ItemType::eDictionary, kExtraFieldsSettingBranch)) { carb::dictionary::IDictionary* dictionary = carb::getCachedInterface<carb::dictionary::IDictionary>(); const carb::dictionary::Item* branch = settings->getSettingsDictionary(kExtraFieldsSettingBranch); size_t childCount = dictionary->getItemChildCount(branch); for (size_t i = 0; i < childCount; i++) { const carb::dictionary::Item* item = dictionary->getItemChildByIndex(branch, i); if (item == nullptr) continue; const char* key = dictionary->getItemName(item); value = dictionary->getStringBuffer(item); if (key != nullptr && value != nullptr) { extraFields->setValue(key, value, omni::structuredlog::fExtraFieldFlagNone); } } } } strucLog.release(); } } // namespace structuredlog } // namespace omni
31,314
C
47.400309
114
0.722648
omniverse-code/kit/include/omni/structuredlog/IStructuredLog.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 The core structured logging interface. */ #pragma once #include "StructuredLogCommon.h" #include "../core/BuiltIn.h" #include "../core/IObject.h" #include "../core/Api.h" #ifdef STRUCTUREDLOG_STANDALONE_MODE # include "../../carb/extras/Library.h" #endif #include <vector> namespace omni { /** Structured logging and Telemetry. */ namespace structuredlog { class IStructuredLog; // ******************************* enums, types, and constants ************************************ /** The expected base name for the structured log plugin. This isn't strictly necessary unless * the plugin needs to be explicitly loaded in standalone mode in an special manner. By default * the plugin is expected to be present in the same directory as the main executable. If it is * not in that location, it is the host app's responsibility to load the plugin dynamically * before attempting to call any structured log functions (even `addModuleSchemas()`). If the * module is not loaded before making any calls, all calls will just silently fail and the * structured log functionality will be in a disabled state. * * The structured log plugin can be loading using carb::extras::loadLibrary(). Using the * @ref carb::extras::fLibFlagMakeFullLibName flag will be useful unless the name is being * constructed manually using carb::extras::createLibraryNameForModule(). */ constexpr const char* OMNI_ATTR("no_py") kStructuredLogPluginName = "omni.structuredlog.plugin"; /** Base type for the version of the event payload parser to use. This is used as part of a * versioning scheme for the payload reader and event schema walker. */ using ParserVersion = uint16_t; /** Base type for the handle to an allocated block of memory returned from either the * @ref IStructuredLog::allocSchema() or @ref IStructuredLog::allocEvent() functions. * These handles uniquely identify the allocated block but should be treated as opaque handles. */ using AllocHandle = void*; /** A special string length value to indicate that a string parameter to a generated event * sending function is null terminated and should have its length calculated instead of * passing in an explicit length. */ constexpr size_t kNullTerminatedString = SIZE_MAX; /** The current event payload parser version that will be used in the IStructuredLog interface. * This symbol can be used by the generated code to set versioning information in each * event payload. This may be incremented in the future. */ constexpr ParserVersion kParserVersion = 0; /** Approximate size of the maximum data payload in bytes that a message can contain that can be * transmitted in a single message. This is a matter of the typical size of message that * can be sent to some data servers minus the average additional space needed for the message * body and other identifying information. Note that this is only an approximate guideline * and should not be taken as an exact limit. Also note that this does not account for the * change in size related to data encoding methods such as Base64. If a Base64 encoding is * to be used for the data payload, the @ref kMaxMessageLengthBase64 limit should be used * instead. */ constexpr size_t kMaxMessageLength = (10000000 - 256); /** Approximate size of the maximum data payload in bytes that a message can contain that can be * transmitted in a single message when the payload is encoded in Base64. This is a matter of * the typical message transmission limit for some data servers minus the average additional * space needed for the message body and other identifying information, then converted to * Base64's 6-to-8 bit encoding ratio (ie: every 6 bits of input data converts to 8 bits of * encoded data). Note that this is only an approximate guideline and should not be taken * as an exact limit. */ constexpr size_t kMaxMessageLengthBase64 = (kMaxMessageLength * 6) / 8; /** Base type for flags to control the behavior of the handling of a schema as a whole. A schema * encompasses the settings for a group of events that are all registered in a single call pair * to @ref IStructuredLog::allocSchema() and @ref IStructuredLog::commitSchema(). */ using SchemaFlags OMNI_ATTR("flag, prefix=fSchemaFlag") = uint32_t; /** Flag to indicate that the log file should remain open between messages. By default, each * event message will cause the log file to be opened, the message written, then the log file * closed. This flag can make writing a large number of frequent event messages more efficient * by avoiding the expense of opening and closing the log file repeatedly. However, using this * may also prevent the log file from being moved or deleted while an app is still running. To * work around that, all persistently open log files can be temporarily forced closed using * @ref IStructuredLogControl::closeLog(). */ constexpr SchemaFlags fSchemaFlagKeepLogOpen = 0x00000001; /** Flag to indicate that the log file for this schema should include the process ID in the * filename. Note that using this flag will likely lead to a lot of log files being generated * for an app since each session will create a [somewhat] unique file. This will however * reduce the possibility of potential performance issues related to many processes trying * to lock and access the same file(s) simultaneously. By default, the process ID is not * included in a schema's log filename. */ constexpr SchemaFlags fSchemaFlagLogWithProcessId = 0x00000002; /** Base type for flags to control the behavior of processing a single event. These flags * affect how events are processed and how they affect their log. */ using EventFlags OMNI_ATTR("flag, prefix=fEventFlag") = uint32_t; /** Use the log file specified by the owning event's schema instead of the default log for the * process. This can be controlled at the per-event level and would be specified by either * manually changing the flags in the generated event table or by passing a specific command * line option to the code generator tool that would set this flag on all of the schema's * events in the generated code. This can be useful if an external plugin would like to * have its events go to its own log file instead of the process's default log file. */ constexpr EventFlags fEventFlagUseLocalLog = 0x00000001; /** Flag to indicate that this event is critical to succeed and should potentially block the * calling thread on IStructuredLog::allocEvent() calls if the event queue is full. The call * will block until a buffer of the requested size can be successfully allocated instead of * failing immediately. This flag should be used sparingly since it could result in blocking * the calling thread. */ constexpr EventFlags fEventFlagCriticalEvent = 0x00000002; /** Flag to indicate that this event should be output to the stderr file. If the * @ref fEventFlagSkipLog flag is not also used, this output will be in addition to the * normal output to the schema's log file. If the @ref fEventFlagSkipLog flag is used, * the normal log file will not be written to. The default behavior is to only write the * event to the schema's log file. This can be combined with the @c fSchemaFlagOutputToStderr * and @c fSchemaFlagSkipLog flags. */ constexpr EventFlags fEventFlagOutputToStderr = 0x00000010; /** Flag to indicate that this event should be output to the stdout file. If the * @ref fEventFlagSkipLog flag is not also used, this output will be in addition to the * normal output to the schema's log file. If the @ref fEventFlagSkipLog flag is used, * the normal log file will not be written to. The default behavior is to only write the * event to the schema's log file. This can be combined with the @c fSchemaFlagOutputToStdout * and @c fSchemaFlagSkipLog flags. */ constexpr EventFlags fEventFlagOutputToStdout = 0x00000020; /** Flag to indicate that this event should not be output to the schema's specified log file. * This flag is intended to be used in combination with the @ref fEventFlagOutputToStdout * and @ref fEventFlagOutputToStderr flags to control which destination(s) each event log * message would be written to. The default behavior is to write each event message to * the schema's specified log file. Note that if this flag is used and neither the * @ref fEventFlagOutputToStderr nor @ref fEventFlagOutputToStdout flags are used, it is * effectively the same as disabling the event since there is no set destination for the * message. */ constexpr EventFlags fEventFlagSkipLog = 0x00000040; /** Base type for flags to control how events and schemas are enabled or disabled. These flags * can be passed to the @ref omni::structuredlog::IStructuredLog::setEnabled() function. */ using EnableFlags OMNI_ATTR("flag, prefix=fEnableFlag") = uint32_t; /** Flag to indicate that a call to @ref IStructuredLog::setEnabled() should * affect the entire schema that the named event ID belongs to instead of just the event. When * this flag is used, each of the schema's events will behave as though they are disabled. * However, each event's individual enable state will not be modified. When the schema is * enabled again, the individual events will retain their previous enable states. */ constexpr EnableFlags fEnableFlagWholeSchema = 0x00000002; /** Flag to indicate that the enable state of each event in a schema should be overridden when * the @ref fEnableFlagWholeSchema flag is also used. When this flag is used, the enable state * of each event in the schema will be modified instead of just the enable state of the schema * itself. When this flag is not used, the default behavior is to change the enable state * of just the schema but leave the enable states for its individual events unmodified. */ constexpr EnableFlags fEnableFlagOverrideEnableState = 0x00000004; /** Flag to indicate that an enable state change should affect the entire system, not just * one schema or event. When this flag is used in @ref IStructuredLog::setEnabled(), the @a eventId * parameter must be set to @ref kBadEventId. */ constexpr EnableFlags fEnableFlagAll = 0x00000008; /** Base type for flags to control how new events are allocated. These flags can be passed * to the @ref IStructuredLog::allocEvent() function. */ using AllocFlags OMNI_ATTR("flag, prefix=fAllocFlag") = uint32_t; /** Flag to indicate that the event should only be added to the queue on commit but that the * consumer thread should not be started yet if it is not already running. */ constexpr AllocFlags fAllocFlagOnlyQueue = 0x00000010; /** A descriptor for a single structured log event. This struct should not need to be used * externally but will be used by the generated code in the schema event registration helper * function. A schema consists of a set of one or more of these structs plus some additional * name and version information. The schema metadata is passed to @ref IStructuredLog::allocSchema(). * The array of these event info objects is passed to @ref IStructuredLog::commitSchema(). */ struct EventInfo { /** The fully qualified name of this event. While there is no strict formatting requirement * for this name, this should be an RDNS style name that specifies the full ownership chain * of the event. This should be similar to the following format: * "com.nvidia.omniverse.<appName>.<eventName>" */ const char* eventName; /** Flags controlling the behavior of this event when being generated or processed. Once * registered, these flags may not change. This may be zero or more of the @ref EventFlags * flags. */ EventFlags flags; /** Version of the schema tree building object that is passed in through @ref schema. This * is used to indicate which version of the event payload block helper classes will be used * to create and read the blocks. In general this should be @ref kParserVersion. */ ParserVersion parserVersion; /** The event ID that will be used to identify this event from external callers. This should * be a value that uniquely identifies the event's name, schema's version, and the JSON * parser version (ie: @ref parserVersion above) that will be used. Ideally this should be * a hash of a string containing all of the above information. It is the caller's * responsibility to ensure the event ID is globally unique enough for any given app's usage. */ uint64_t eventId; /** Schema tree object for this event. This tree object is expected to be built in the * block of memory that is returned from @ref IStructuredLog::allocSchema(). Optionally, this may * be nullptr to indicate that the event's payload is intended to be empty (ie: the event * is just intended to be an "I was here" event). */ const void* schema; }; // ********************************* IStructuredLog interface ************************************* /** Main structured log interface. This should be treated internally as a global singleton. Any * attempt to create or acquire this interface will return the same object just with a new * reference taken on it. * * There are three main steps to using this interface: * * Set up the interface. For most app's usage, all of the default settings will suffice. * The default log path will point to the Omniverse logs folder and the default user ID * will be the one read from the current user's privacy settings file (if it exists). If * the default values for these is not sufficient, a new user ID should be set with * @ref omni::structuredlog::IStructuredLogSettings::setUserId() and a log output path should be set with * @ref omni::structuredlog::IStructuredLogSettings::setLogOutputPath(). * If the privacy settings file is not present, * the user name will default to a random number. The other defaults should be sufficient * for most apps. This setup only needs to be performed once by the host app if at all. * The @ref omni::structuredlog::IStructuredLogSettings interface can be acquired either * by casting an @ref omni::structuredlog::IStructuredLog * object to that type or by directly creating the @ref omni::structuredlog::IStructuredLogSettings * object using omni::core::ITypeFactory_abi::createType(). * * Register one or more event schemas. * This is done with @ref omni::structuredlog::IStructuredLog::allocSchema() and * @ref omni::structuredlog::IStructuredLog::commitSchema(). * At least one event must be registered for any events to * be processed. Once a schema has been registered, it will remain valid until the * structured log module is unloaded from the process. There is no way to forcibly * unregister a set of events once registered. * * Send zero or more events. This is done with the @ref omni::structuredlog::IStructuredLog::allocEvent() and * @ref omni::structuredlog::IStructuredLog::commitEvent() functions. * * For the most part, the use of this interface will be dealt with in generated code. This * generated code will come from the 'omni.structuredlog' tool in the form of an inlined header * file. It is the host app's responsibility to call the header's schema registration helper * function at some point on startup before any event helper functions are called. * * All messages generated by this structured log system will be CloudEvents v1.0 compliant. * These should be parsable by any tool that is capable of understanding CloudEvents. * * Before an event can be sent, at least one schema describing at least one event must be * registered. This is done with the @ref omni::structuredlog::IStructuredLog::allocSchema() and * @ref omni::structuredlog::IStructuredLog::commitSchema() functions. * The @ref omni::structuredlog::IStructuredLog::allocSchema() function returns * a handle to a block of memory owned by the structured log system and a pointer to that block's * data. The caller is responsible for both calculating the required size of the buffer before * allocating, and filling it in with the schema data trees for each event that can be sent as * part of that schema. The helper functions in @ref omni::structuredlog::JsonTreeSizeCalculator and * @ref omni::structuredlog::JsonBuilder can be used to build these trees. Once these trees are built, they are * stored in a number of entries in an array of @ref omni::structuredlog::EventInfo objects. This array of event * info objects is then passed to @ref omni::structuredlog::IStructuredLog::commitSchema() to complete the schema * registration process. * * Sending of a message is split into two parts for efficiency. The general idea is that the * caller will allocate a block of memory in the event queue's buffer and write its data directly * there. * The allocation occurs with the @ref omni::structuredlog::IStructuredLog::allocEvent() call. * This will return a * handle to the allocated block and a pointer to the first byte to start writing the payload * data to. The buffer's header will already have been filled in upon return from * @ref omni::structuredlog::IStructuredLog::allocEvent(). * Once the caller has written its event payload information to * the buffer, it will call @ref omni::structuredlog::IStructuredLog::commitEvent() * to commit the message to the queue. At * this point, the message can be consumed by the event processing thread. * * Multiple events may be safely allocated from and written to the queue's buffer simultaneously. * There is no required order that the messages be committed in however. If a buffer is * allocated after one that has not been committed yet, and that newer event is committed first, * the only side effect will be that the event processing thread will be stalled in processing * new events until the first message is also committed. This is important since the events * would still need to be committed to the log in the correct order. * * All events that are processed through this interface will be written to a local log file. The * log file will be periodically consumed by an external process (the Omniverse Transmitter app) * that will send all the approved events to the telemetry servers. Only events that have been * approved by legal will be sent. All other messages will be rejected and only remain in the * log files on the local machine. */ class IStructuredLog_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.structuredlog.IStructuredLog")> { protected: /** Checks whether a specific event or schema is enabled. * * @param[in] eventId The unique ID of the event to check the enable state of. This * is the ID that was originally used to register the event. * @returns `true` if both the requested event and its schema is enabled. * @returns `false` if either the requested event or its schema is disabled. * * @remarks This checks if a named event or its schema is currently enabled in the structured * log system. Individual events or entire schemas may be disabled at any given * time. Both the schema and each event has its own enable state. A schema can be * disabled while still leaving its events' previous enable/disable states * unmodified. When the schema is enabled again, its events will still retain their * previous enable states. Set @ref omni::structuredlog::IStructuredLog::setEnabled() * for more information on how to enable and disable events and schemas. */ virtual bool isEnabled_abi(EventId eventId) noexcept = 0; /** Sets the enable state for a structured log event or schema, or the system globally. * * @param[in] eventId The ID of the event to change the enable state of. This is the ID * that was originally used to register the event. If the * @ref omni::structuredlog::fEnableFlagAll flag is used, this must be * set to @ref omni::structuredlog::kBadEventId. * @param[in] flags Flags to control the behavior of this function. This may be zero or * more of the @ref omni::structuredlog::EnableFlags flags. * If this includes the @ref omni::structuredlog::fEnableFlagAll * flag, @p eventId must be set to @ref omni::structuredlog::kBadEventId. * @param[in] enabled Set to true to enable the named event or schema. Set to false to * disable the named event or schema. If the * @ref omni::structuredlog::fEnableFlagAll flag is used, this sets the * new enable/disable state for the structured log system as a whole. * @returns No return value. * * @remarks This changes the current enable state for an event or schema. The scope of the * enable change depends on the flags that are passed in. When an event is * disabled (directly or from its schema or the structured log system being * disabled), it will also prevent it from being generated manually. In this case, * any attempt to call @ref omni::structuredlog::IStructuredLog::allocEvent() for * that disabled event or schema will simply fail immediately. * * @remarks When a schema is disabled, it effectively disables all of its events. Depending * on the flag usage however (ie: @ref omni::structuredlog::fEnableFlagOverrideEnableState), * disabling the schema may or may not change the enable states of each of its * individual events as well (see @ref omni::structuredlog::fEnableFlagOverrideEnableState * for more information). * * @note The @ref omni::structuredlog::fEnableFlagAll flag should only ever by used by the * main host app since this will affect the behavior of all modules' events regardless * of their own internal state. Disabling the entire system should also only ever be * used sparingly in cases where it is strictly necessary (ie: compliance with local * privacy laws). */ virtual void setEnabled_abi(EventId eventId, EnableFlags flags, bool enabled) noexcept = 0; // ****** schema registration function ****** /** Allocates a block of memory for an event schema. * * @param[in] schemaName The name of the schema being registered. This may not be * nullptr or an empty string. There is no set format for this * schema name, but it should at least convey some information * about the app's name and current release version. This name * will be used to construct the log file name for the schema. * @param[in] schemaVersion The version number for the schema itself. This may not be * nullptr or an empty string. This should be the version number * of the schema itself, not of the app or component. This will * be used to construct the 'dataschema' name that gets passed * along with each CloudEvents message header. * @param[in] flags Flags to control the behavior of the schema. This may be * zero or more of the @ref omni::structuredlog::SchemaFlags flags. * @param[in] size The size of the block to allocate in bytes. If this is 0, a * block will still be allocated, but its actual size cannot be * guaranteed. The @ref omni::structuredlog::JsonTreeSizeCalculator * helper class can be used to calculate the size needs for the new schema. * @param[out] outHandle Receives the handle to the allocated memory block on success. * On failure, this receives nullptr. Each successful call * must pass this handle to @ref omni::structuredlog::IStructuredLog::commitSchema() * even if an intermediate failure occurs. In the case of a schema * tree creation failure, nullptr should be passed for @a events * in the corresponding @ref omni::structuredlog::IStructuredLog::commitSchema() call. * This will allow the allocated block to be cleaned up. * @returns A pointer to the allocated block on success. This block does not need to be * explicitly freed - it will be managed internally. This pointer will point to * the first byte that can be written to by the caller and will be at least @p size * bytes in length. This pointer will always be aligned to the size of a pointer. * @returns `nullptr` if no more memory is available. * @returns `nullptr` if an invalid parameter is passed in. * * @remarks This allocates a block of memory that the schema tree(s) for the event(s) in a * schema can be created and stored in. Pointers to the start of each event schema * within this block are expected to be stored in one of the @ref omni::structuredlog::EventInfo objects * that will later be passed to @ref omni::structuredlog::IStructuredLog::commitSchema(). The caller is * responsible for creating and filling in returned block and the array of * @ref omni::structuredlog::EventInfo objects. * The @ref omni::structuredlog::BlockAllocator helper class may be used to * allocate smaller chunks of memory from the returned block. * * @note This should only be used in generated structured log source code. This should not * be directly except when absolutely necessary. This should also not be used as a * generic allocator. Failure to use this properly will result in memory being * leaked. * * @thread_safety This call is thread safe. */ virtual uint8_t* allocSchema_abi(OMNI_ATTR("c_str, in, not_null") const char* schemaName, OMNI_ATTR("c_str, in, not_null") const char* schemaVersion, SchemaFlags flags, size_t size, OMNI_ATTR("out") AllocHandle* outHandle) noexcept = 0; /** Commits an allocated block and registers events for a single schema. * * @param[in] schemaBlock The block previously returned from * @ref omni::structuredlog::IStructuredLog::allocSchema() * that contains the built event trees for the schema to register. * These trees must be pointed to by the @ref omni::structuredlog::EventInfo::schema * members of the @p events array. * @param[in] events The table of events that belong to this schema. This provides * information about each event such as its name, control flags, * event identifier, and a schema describing how to interpret its * binary blob on the consumer side. This may not be nullptr. Each * of the trees pointed to by @ref omni::structuredlog::EventInfo::schema in this table * must either be set to nullptr or point to an address inside the * allocated schema block @p schemaBlock that was returned from the * corresponding call to @ref omni::structuredlog::IStructuredLog::allocSchema(). * If any of the schema trees point to an address outside of the schema block, * this call will fail. * @param[in] eventCount The total number of events in the @p events table. At least one * event must be registered. This may not be 0. * @retval omni::structuredlog::SchemaResult::eSuccess if the new schema * is successfully registered as a set of unique events. * @retval omni::structuredlog::SchemaResult::eAlreadyExists if the new * schema exactly matches one that has already been successfully registered. * This can be considered a successful result. * In this case, the schema block will be destroyed before return. * @retval omni::structuredlog::SchemaResult::eEventIdCollision if the new schema contains an event whose * identifier matches that of an event that has already been registered with another * schema. This indicates that the name of the event that was used to generate the * identifier was likely not unique enough, or that two different versions of the * same schema are trying to be registered without changing the schema's version * number first. No new events will be registered in this case and the schema * block will be destroyed before return. * @retval omni::structuredlog::SchemaResult::eFlagsDiffer if the new schema exactly matches another schema * that has already been registered except for the schema flags that were used * in the new one. This is not allowed without a version change in the new schema. * No new events will be registered in this case and the schema block will be * destroyed before return. * @returns Another @ref omni::structuredlog::SchemaResult error code for other types of failures. No new events * will be registered in this case and the schema block will be destroyed before * return. * * @remarks This registers a new schema and its events with the structured log system. This * will create a new set of events in the structured log system. These events * cannot be unregistered except by unloading the entire structured log system * altogether. Upon successful registration, the events in the schema can be * emitted using the event identifiers they were registered with. * * @remarks If the new schema matches one that has already been registered, The operation * will succeed with the result @ref omni::structuredlog::SchemaResult::eAlreadyExists. * The existing * schema's name, version, flags, and event table (including order of events) must * match the new one exactly in order to be considered a match. If anything differs * (even the flags for a single event or events out of order but otherwise the same * content), the call will fail. If the schema with the differing flags or event * order is to be used, its version or name must be changed to avoid conflict with * the existing schema. * * @remarks When generating the event identifiers for @ref omni::structuredlog::EventInfo::eventId it is * recommended that a string uniquely identifying the event be created then hashed * using an algorithm such as FNV1. The string should contain the schema's client * name, the event's name, the schema's version, and any other values that may * help to uniquely identify the event. Once hashed, it is very unlikely that * the event identifier will collide with any others. This is the method that the * code generator tool uses to create the unique event identifiers. * * @remarks Up to 65536 (ie: 16-bit index values) events may be registered with the * structured log system. The performance of managing a list of events this large * is unknown and not suggested however. Each module, app, or component should only * register its schema(s) once on startup. This can be a relatively expensive * operation if done frequently and unnecessarily. * * @thread_safety This call is thread safe. */ virtual SchemaResult commitSchema_abi(OMNI_ATTR("in, out, not_null") AllocHandle schemaBlock, OMNI_ATTR("in, *in, count=eventCount, not_null") const EventInfo* events, size_t eventCount) noexcept = 0; // ****** event message generation functions ****** /** Allocates a block of memory to store an event's payload data in. * * @param[in] version The version of the parser that should be used to read this * event's payload data. This should be @ref omni::structuredlog::kParserVersion. * If the structured log system that receives this message does not * support this particular version (ie: a newer module is run * on an old structured log system), the event message will simply * be dropped. * @param[in] eventId the unique ID of the event that is being generated. This ID must * exactly match the event ID that was provided in the * @ref omni::structuredlog::EventInfo::eventId value when the event * was registered. * @param[in] flags Flags to control how the event's block is allocated. This may * be a combination of zero or more of the @ref omni::structuredlog::AllocFlags * flags. * @param[in] payloadSize The total number of bytes needed to store the event's payload * data. The caller is responsible for calculating this ahead * of time. If the event does not have a payload, this should be * 0. The number of bytes should be calculated according to how * the requested event's schema (ie: @ref omni::structuredlog::EventInfo::schema) lays * it out in memory. * @param[out] outHandle Receives the handle to the allocated block of memory. This * must be passed to IStructuredLog::commitEvent() once the caller * has finished writing all of the payload data to the returned * buffer. The IStructuredLog::commitEvent() call acts as the * cleanup function for this handle. * @returns A pointer to the buffer to use for the event's payload data if successfully * allocated. The caller should start writing its payload data at this address * according to the formatting information in the requested event's schema. This * returned pointer will always be aligned to the size of a pointer. * @returns `nullptr` if the requested event, its schema, or the entire system is currently * disabled. * @returns `nullptr` if the event queue's buffer is full and a buffer of the requested * size could not be allocated. In this case, a invalid handle will be returned * in @p outHandle. The IStructuredLog::commitEvent() function does not need to be * called in this case. * @returns `nullptr` if the event queue failed to be created or its processing thread failed * start up. * @returns `nullptr` if the given event ID is not valid. * * @remarks This is the main entry point for creating an event message. This allocates * a block of memory that the caller can fill in with its event payload data. * The caller is expected to fill in this buffer as quickly as possible. Once * the buffer has been filled, its handle must be passed to the * @ref omni::structuredlog::IStructuredLog::commitEvent() function to finalize and send. * Failing to pass a * valid handle to @ref omni::structuredlog::IStructuredLog::commitEvent() will stall the event queue * indefinitely. * * @remarks If the requested event has been marked as 'critical' by using the event flag * @ref omni::structuredlog::fEventFlagCriticalEvent, a blocking allocation will be used here instead. * In this case, this will not fail due to the event queue being out of space. * * @note This call will fail immediately if either the requested event, its schema, or * the entire system has been explicitly disabled. It is the caller's responsibility * to both check the enable state of the event before attempting to send it (ie: to * avoid doing unnecessary work), and to gracefully handle the potential of this * call failing. * * @note It is the caller's responsibility to ensure that no events are generated during * C++ static destruction time for the process during shutdown. Especially on * Windows, doing so could result in an event being allocated but not committed * thereby stalling the event queue. This could lead to a hang on shutdown. * * @thread_safety This call is thread safe. */ virtual uint8_t* allocEvent_abi(ParserVersion version, EventId eventId, AllocFlags flags, size_t payloadSize, OMNI_ATTR("out") AllocHandle* outHandle) noexcept = 0; /** finishes writing a message's payload and queues it for processing. * * @param[in] handle The handle to the queue buffer block to be committed. This must not * be nullptr. This must be the same handle that was returned through * @a outHandle on a recent call to @ref omni::structuredlog::IStructuredLog::allocEvent() * on this same thread. Upon return, this handle will be invalid and should be * discarded by the caller. * @returns No return value. * * @remarks This commits a block that was previously allocated on this thread with * @ref omni::structuredlog::IStructuredLog::allocEvent(). * It is required that the commit call occur on the * same thread that the matching @ref omni::structuredlog::IStructuredLog::allocEvent() * call was made on. * Each successful @ref omni::structuredlog::IStructuredLog::allocEvent() call must * be paired with exactly one * @ref omni::structuredlog::IStructuredLog::commitEvent() call on the same thread. * Failing to do so would result in the event queue thread stalling. * * @thread_safety This call is thread safe. */ virtual void commitEvent_abi(OMNI_ATTR("in, not_null") const AllocHandle handle) noexcept = 0; }; // skipping this because exhale can't handle the function pointer type #ifndef DOXYGEN_SHOULD_SKIP_THIS /** Registration function to install a schema with the structured logging system. * * @param[in] log A pointer to the global singleton structured logging system to install * the schema in. * @returns `true` if the schema is successfully installed or was already installed. * @returns `false` if the schema could not be installed. This may be caused by a lack of * available memory, or too many events have been registered in the system. */ using SchemaAddFn = bool (*)(IStructuredLog*); /** Retrieves the local schema registration list for this module. * * @returns The static list of schemas to register for this module. This is intended to be * a static list that can be built up at compile time to collect schemas to * register. Each module will have its own copy of this list. */ inline std::vector<SchemaAddFn>& getModuleSchemas() { static std::vector<SchemaAddFn> sSchemas; return sSchemas; } #endif } // namespace structuredlog } // namespace omni #ifdef OMNI_COMPILE_AS_DYNAMIC_LIBRARY OMNI_API omni::structuredlog::IStructuredLog* omniGetStructuredLogWithoutAcquire(); #else /** * Retrieves the module's structured log object. omni::core::IObject::acquire() is **not** called on the returned * pointer. * * The global omni::structuredlog::IStructuredLog instance can be configured by passing an * @ref omni::structuredlog::IStructuredLog to omniCoreStart(). * If an instance is not provided, omniCoreStart() attempts to create one. * * @returns the calling module's structured log object. The caller will not own a reference to * the object. If the caller intends to store the object for an extended period, it * must take a reference to it using either a call to acquire() or by borrowing it into * an ObjectPtr<> object. This object must not be released by the caller unless a * reference to it is explicitly taken. */ # ifndef STRUCTUREDLOG_STANDALONE_MODE inline omni::structuredlog::IStructuredLog* omniGetStructuredLogWithoutAcquire() { return static_cast<omni::structuredlog::IStructuredLog*>(omniGetBuiltInWithoutAcquire(OmniBuiltIn::eIStructuredLog)); } # else inline omni::structuredlog::IStructuredLog* omniGetStructuredLogWithoutAcquire() { using GetFunc = omni::structuredlog::IStructuredLog* (*)(); static GetFunc s_get = nullptr; if (s_get == nullptr) { carb::extras::LibraryHandle module = carb::extras::loadLibrary( omni::structuredlog::kStructuredLogPluginName, carb::extras::fLibFlagMakeFullLibName); s_get = carb::extras::getLibrarySymbol<GetFunc>(module, "omniGetStructuredLogWithoutAcquire_"); if (s_get == nullptr) return nullptr; } return s_get(); } # endif #endif #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IStructuredLog.gen.h" /** Common entry point for sending an event. * * @param event_ The name of the event to send. This is expected to be the 'short' * name for the event as named in its schema's *_sendEvent() function. * This short name will be the portion of the function name before the * '_sendEvent' portion of the name. * @param ... The set of parameters specific to the event to be sent. These are * potentially different for each event. Callers should refer to the * original schema to determine the actual set of parameters to send. * @returns No return value. * * @remarks This is intended to be used to send all structured log events instead of calling the * generated schema class's functions directly. This provides a consistent entry * point into sending event messages and allows parameter evaluation to be delayed * if either the event or schema is disabled. */ #define OMNI_STRUCTURED_LOG(event_, ...) \ do \ { \ auto strucLog__ = omniGetStructuredLogWithoutAcquire(); \ if (strucLog__) \ { \ if (event_##_isEnabled(strucLog__)) \ { \ event_##_sendEvent(strucLog__, ##__VA_ARGS__); \ } \ } \ } while (0) namespace omni { namespace structuredlog { //! A function that registers all schemas within a module. //! //! \note It is not necessary to call this function; it is automatically called by \ref carbOnPluginPreStartup inline void addModulesSchemas() noexcept { auto strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; for (auto& schemaAddFn : getModuleSchemas()) { schemaAddFn(strucLog); } } } // namespace structuredlog } // namespace omni /** @copydoc omni::structuredlog::IStructuredLog_abi */ class omni::structuredlog::IStructuredLog : public omni::core::Generated<omni::structuredlog::IStructuredLog_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IStructuredLog.gen.h"
46,650
C
60.463768
121
0.660815
omniverse-code/kit/include/omni/audio/IAudioPlayer.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. // //! @file //! @brief Defines an interface to provide a simple audio player interface. #pragma once #include <carb/Interface.h> #include <carb/audio/IAudioData.h> namespace omni { namespace audio { /** Handle for a created audio player object. This will be `nullptr` to indicate an invalid * audio player object. */ struct AudioPlayer; /** Prototype of a callback function to signal that a sound data log operation completed. * * @param[in] success Set to `true` if the load operation was successful. Set to `false` * otherwise. * @param[in] context The original caller specified context value that was provided when * this callback was registered in either IAudioPlayer::playSound() or * IAudioPlayer::loadSound() families of functions. * @returns No return value. */ using OnLoadedCallback = void (*)(bool success, void* context); /** Prototype of a callback function to signal that a sound completed its playback. * * @param[in] context The original caller specified context value that was provided when * this callback was registered in either IAudioPlayer::playSound() * family of functions. * @returns No return value. */ using OnEndedCallback = void (*)(void* context); /** Base type for flags that can be provided to IAudioPlayer::loadSoundInMemory() or * IAudioPlayer::playSoundInMemory(). * @{ */ using AudioPlayerFlags = uint32_t; /** Flag to indicate that the data blob being passed in only contains the raw PCM data and * no header or format information. When this flag is used, the frame rate, channel count, * and sample data format must also be specified when passing the blob to either * IAudioPlayer::loadSoundInMemory() or IAudioPlayer::playSoundInMemory(). */ constexpr AudioPlayerFlags fPlayerFlagRawData = 0x01; /** Flag to indicate that the data blob should be reloaded even if it is already cached in * the audio player object. */ constexpr AudioPlayerFlags fPlayerFlagForceReload = 0x02; /** @} */ /** The supported PCM formats for loading or playing raw PCM data through the * IAudioPlayer::loadSoundInMemory() or IAudioPlayer::playSoundInMemory() functions. */ enum class RawPcmFormat { ePcm8, ///< unsigned 8-bits per sample integer PCM data. ePcm16, ///< signed 16-bits per sample integer PCM data. ePcm32, ///< signed 32-bits per sample integer PCM data. ePcmFloat, ///< 32-bits per sample floating point PCM data. }; /** The descriptor for IAudioPlayer::drawWaveform(). */ struct DrawWaveformDesc { /** The name for the output image file. * This path supports the standard path aliases (e.g. "${resources}") * The path must point to an existing directory on disk. * This must be nullptr to store the image in @p outputBuffer. */ const char* filename; /** The buffer to store the raw RGBA8888 in. * @p filename must be nullptr for this to be used. * This needs to be at least @p width * @p height * 4 bytes long. */ uint8_t* outputBuffer; /** The width of the output image, in pixels. */ size_t width; /** The height of the output image, in pixels. */ size_t height; /** The foreground color in normalized RGBA color. */ carb::Float4 fgColor; /** The background color in normalized RGBA color. */ carb::Float4 bgColor; }; /** Descriptor of a blob of audio data in memory. This data can either be a full supported sound * file in memory, or just simple raw PCM data. If raw PCM data is provided, the information * about the data format must also be provided. */ struct AudioDataInMemory { /** The name to be used to cache the file data in the audio player. This may be `nullptr` or * an empty string to indicate that it shouldn't be cached. If it is not cached, the sound * is only expected to be played once. If it is played again, it will be reloaded instead of * pulling a cached version that was previously loaded or played. */ const char* name = nullptr; /** The buffer of sound data to be loaded. This is interpreted according to the flags passed * to either IAudioPlayer::loadSoundInMemory() or IAudioPlayer::playSoundInMemory(). If the * flags indicate that raw data is passed in, the frame rate, channel count, and data format * values will also be required. This may not be `nullptr`. */ const void* buffer; /** The size of @ref buffer in bytes. This may not be 0. */ size_t byteCount; /** The frame rate to play the audio data back at. This must be a non-zero value if raw PCM * data is being provided. This is measured in Hertz. Typical values for this are 44100Hz, * or 48000Hz. Any value in the range from 1000Hz to 200000Hz is generally accepted. Though * note that if this value is not correct for the given sound data, it may play back either * to quickly or too slowly. The pitch of the sound will also be affected accordingly. This * value will be ignored if the blob in @ref buffer already contains format information. */ size_t frameRate = 0; /** The number of channels in each frame of data in the sound. This must be a non-zero value * if raw PCM data is being provided. If this is incorrect for the given data, the sound will * play incorrectly. This value will be ignored if the blob in @ref buffer already contains * format information. */ size_t channels = 0; /** The format of the PCM data. This must be a valid value if raw PCM data is being provided. * This must be well known by the caller otherwise the audio data will load incorrectly and * undefined output would be likely to result (it won't be generally problematic except to * the ears of listeners). This value will be ignored if the bob in @ref buffer already * contains format information. */ RawPcmFormat format = RawPcmFormat::ePcm16; }; /** Simple interface to be able to play audio assets. * All of the calls to this interface are internally serialized by a mutex. * This provides an interface for an audio player that has one voice and * allows individual assets to be played. * Multiple audio players can be opened per-process but they all share the same * IAudioPlayer backend which limits the number of simultaneously playing audio * players to 4. */ struct IAudioPlayer { CARB_PLUGIN_INTERFACE("omni::audio::IAudioPlayer", 0, 3); /** Create an audio player instance. * @returns A new audio player if creation succeeded. * @returns nullptr if creation failed. * * @remarks This creates an audio system with 1 voice that can play sound assets. */ AudioPlayer*(CARB_ABI* createAudioPlayer)(); /** Destroy an audio player instance. * @param[in] player The player to destroy. * * @remarks This will stop any audio playing, release all assets and free * the memory of @p player. */ void(CARB_ABI* destroyAudioPlayer)(AudioPlayer* player); /** Play a sound asset. * @param[in] player The player to play this sound on. * @param[in] path The path to the sound asset to play. * This must be an absolute file path to a sound asset. * @param[in] onLoaded A callback to execute once the asset has * loaded and is about to play. * This may be used for something like turning * off a spinner icon to indicate that the * asset has loaded. * The first parameter of this callback indicates * whether the load request succeeded. * The second parameter is @p context. * This may be nullptr if the callback is not needed. * @param[in] onEnded A callback to execute once the asset has finished * playing or has been stopped. * The parameter passed is @p context. * This may be nullptr if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] startTime The time offset into the sound to start playing it * at. This is measured in seconds. * * @remarks This will spawn a task to play this sound asset once it has loaded. * This is intended to be used for auditioning sounds to a user * from something like the content window, to allow them to hear * a sound before they use it in their scene. * * @note If another sound is currently playing, it will be stopped before * playing this sound. * * @note The callbacks are called within an internal static recursive * mutex, so the callbacks must be careful to avoid deadlock if they * need to acquire another lock, such as the python GIL. * * @note Playing the sound will fail if too many other audio players are * playing simultaneously. */ void(CARB_ABI* playSound)(AudioPlayer* player, const char* path, OnLoadedCallback onLoaded, OnEndedCallback onEnded, void* context, double startTime); /** Load a sound asset for future playback * @param[in] player The player to play this sound on. * @param[in] path The path to the sound asset to play. * This must be an absolute file path to a sound asset. * @param[in] onLoaded A callback to execute once the asset has * loaded and is about to play. * This may be used for something like turning * off a spinner icon to indicate that the * asset has loaded. * The first parameter of this callback indicates * whether the load request succeeded. * The second parameter is @p context. * This may be nullptr if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * * @remarks This will fetch an asset so that the next call to playSound() * can begin playing the sound immediately. * This will also stop the currently playing sound, if any. * This function will also cause getSoundLength() to begin * returning the length of this sound. */ void(CARB_ABI* loadSound)(AudioPlayer* player, const char* path, OnLoadedCallback onLoaded, void* context); /** Stop playing the current sound, if any. * @param[in] player The player to play this sound on. */ void(CARB_ABI* stopSound)(AudioPlayer* player); /** Pause playback of the current sound, if any. * @param[in] player The player to play this sound on. */ void(CARB_ABI* pauseSound)(AudioPlayer* player); /** Unpause playback of the current sound, if any. * @param[in] player The player to play this sound on. */ void(CARB_ABI* unpauseSound)(AudioPlayer* player); /** Get the length of the currently playing sound. * @param[in] player The player to play this sound on. * @returns The length of the currently playing sound in seconds. * @returns 0.0 if there is no playing sound. */ double(CARB_ABI* getSoundLength)(AudioPlayer* player); /** Get the play cursor position in the currently playing sound. * @param[in] player The player to play this sound on. * @returns The play cursor position in the currently playing sound in seconds. * @returns 0.0 if there is no playing sound. */ double(CARB_ABI* getPlayCursor)(AudioPlayer* player); /** Set the cursor in the sound. * @param[in] player The player to use to set the cursor in the sound. * @param[in] onLoaded A callback to execute once the asset has * loaded and is about to play. * This may be used for something like turning * off a spinner icon to indicate that the * asset has loaded. * The first parameter of this callback indicates * whether the load request succeeded. * The second parameter is @p context. * This may be nullptr if the callback is not needed. * @param[in] onEnded A callback to execute once the asset has finished * playing or has been stopped. * The parameter passed is @p context. * This may be nullptr if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] startTime The time offset to set the cursor to. This is measured in seconds. * * @note The previous onEnded() callback that was passed to playSound() will * be called after @p onLoaded() is called. */ void(CARB_ABI* setPlayCursor)(AudioPlayer* player, OnLoadedCallback onLoaded, OnEndedCallback onEnded, void* context, double startTime); /** Render the waveform to an image to a file. * @param[in] player The player whose waveform image will be rendered. * @param[in] desc The descriptor for the waveform to draw. * @return true if the operation was successful. * @returns false if the file could not be generated. * * @note The functionality of writing to a file is a temporary workaround. * This will eventually be changed to output a memory buffer. */ bool(CARB_ABI* drawWaveform)(AudioPlayer* player, const DrawWaveformDesc* desc); /** Play a sound asset from data in memory. * * @param[in] player The player to play this sound on. * @param[in] data The descriptor of the data blob and its required format * information. This must include the format information for the * sound if the @ref fPlayerFlagRawData flag is given in @p flags. * This may not be `nullptr`. * @param[in] onLoaded A callback to execute once the asset has loaded and is about to * play. This may be used for something like turning off a spinner * icon to indicate that the asset has loaded. The first parameter * of this callback indicates whether the load request succeeded. * The second parameter is @p context. This may be `nullptr` if the * callback is not needed. * @param[in] onEnded A callback to execute once the asset has finished playing or has * been stopped. The parameter passed is @p context. This may be * `nullptr` if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] startTime The time offset into the sound to start playing it at. This is * measured in seconds. * @param[in] flags Flags to control how the sound data is loaded and cached. If the * data blob does not contain format information and is just raw PCM * sample data, the @ref fPlayerFlagRawData flag must be specified * and the @a frameRate, @a channels, and @a format values in @p data * must also be given. Without these, the sound data cannot be * properly loaded. * @returns No return value. * * @remarks The sound asset will start playing asynchronously when the asset has loaded. * The asset is given as a data blob in memory. The data may either be a full * file loaded into memory or just raw PCM data. If raw PCM data is given, * additional parameters must be used to specify the sample type, channel count, * and frame rate so that the data can be successfully decoded. * * @note If another sound is currently playing, it will be stopped before * playing this sound. * * @note The callbacks are called within an internal static recursive * mutex, so the callbacks must be careful to avoid deadlock if they * need to acquire another lock, such as the python GIL. * * @note Playing the sound will fail if too many other audio players are * playing simultaneously. */ void(CARB_ABI* playSoundInMemory)(AudioPlayer* player, const AudioDataInMemory* data, OnLoadedCallback onLoaded, OnEndedCallback onEnded, void* context, double startTime, AudioPlayerFlags flags); /** Play a sound asset from data in memory. * * @param[in] player The player to play this sound on. * @param[in] data The descriptor of the data blob and its required format * information. This must include the format information for the * sound if the @ref fPlayerFlagRawData flag is given in @p flags. * This may not be `nullptr`. * @param[in] onLoaded A callback to execute once the asset has loaded and is about to * play. This may be used for something like turning off a spinner * icon to indicate that the asset has loaded. The first parameter * of this callback indicates whether the load request succeeded. * The second parameter is @p context. This may be `nullptr` if the * callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] flags Flags to control how the sound data is loaded and cached. If the * data blob does not contain format information and is just raw PCM * sample data, the @ref fPlayerFlagRawData flag must be specified * and the @a frameRate, @a channels, and @a format values in @p data * must also be given. Without these, the sound data cannot be * properly loaded. * @returns No return value. * * @remarks This will fetch an asset in memory so that the next call to playSound() can begin * playing the sound immediately. In order for this to be useful, the @a name value * in @p data must be a non-empty string so that the loaded sound is cached. If no * name is given, the operation will just fail immediately. This will also stop the * currently playing sound, if any. This function will also cause getSoundLength() * to begin returning the length of this sound. */ void(CARB_ABI* loadSoundInMemory)(AudioPlayer* player, const AudioDataInMemory* data, OnLoadedCallback onLoaded, void* context, AudioPlayerFlags flags); }; } }
20,840
C
50.080882
111
0.606958
omniverse-code/kit/include/omni/audio/IAudioDeviceEnum.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. // //! @file //! @brief Provides an interface that allows the connected audio devices to be enumerated. #pragma once #include <carb/Interface.h> #include <carb/extras/Guid.h> namespace omni { namespace audio { /** The direction to collect device information for. This is passed to most functions in the * IAudioDeviceEnum interface to specify which types of devices are currently interesting. */ enum class Direction { ePlayback, ///< Enumerate audio playback devices only. eCapture, ///< Enumerate audio capture devices only. }; /** Names for the type of sample that an audio device can use. */ enum class SampleType { eUnknown, ///< Could not determine the sample type or an invalid device index was given. ePcmSignedInteger, ///< Signed integer PCM samples. This is usually used for 16-bit an up. ePcmUnsignedInteger, ///< Unsigned integer PCM samples. This is often used for 8-bit samples. ePcmFloat, ///< Single precision floating point PCM samples. eCompressed, ///< A compressed sample format such as ADPCM, MP3, Vorbis, etc. }; /** An interface to provide simple audio device enumeration functionality. This is able to * enumerate all audio devices attached to the system at any given point and collect the * information for each device. This is only intended to collect the device information * needed to display to the user for device selection purposes. If a device is to be * chosen based on certain needs (ie: channel count, frame rate, etc), it should be done * directly through the audio playback or capture context during creation. This is able * to collect information for both playback and capture devices. * * Note that audio devices in the system are generally volatile - they can be added or * removed at any time with no control from this interface. Because of this, it is * highly suggested that device information not be cached, but instead queried each time * it needs to be refreshed. * * Currently this interface does not expose a device change notifier. This is only * available from the `carb::audio::IAudioDevice` interface for the moment. A future * version of this interface may expose an event stream for device change notifications. * The caller may then use those notifications to decide when to refresh the cached * device information in the UI for example. */ struct IAudioDeviceEnum { CARB_PLUGIN_INTERFACE("omni::audio::IAudioDeviceEnum", 0, 1); /** Retrieves the total number of devices attached to the system of a requested type. * * @param[in] dir The audio direction to get the device count for. * @returns The total number of connected audio devices of the requested type. * @returns 0 if no audio devices are connected to the system. */ size_t(CARB_ABI* getDeviceCount)(Direction dir); /** Retrieves a descriptive string for a requested audio device. * * @param[in] dir The audio direction to get the description string for. * @param[in] index The index of the device to retrieve the description for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] desc Receives the description string for the requested device if * it is still present in the system and its information can be * retrieved. This may not be nullptr. * @param[in] maxLength The maximum number of characters including the null terminator * that can be stored in the output buffer. * @returns `true` if the device description was successfully created. * @returns `false` if the device index was out of range. * * @remarks This retrieves a descriptive string for the requested device. This string is * suitable for display to a user in a menu or selection list. */ bool(CARB_ABI* getDeviceDescription)(Direction dir, size_t index, char* desc, size_t maxLength); /** Retrieves the friendly name of a requested device. * * @param[in] dir The audio direction to get the device name for. * @param[in] index The index of the device to retrieve the name for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] name Receives the name of the requested device if it could be * retrieved. This may not be nullptr. * @param[in] maxLength The maximum number of characters including the null terminator * that can be stored in the output buffer. * @returns `true` if the device name was successfully retrieved. * @returns `false` if the device index was out of range. */ bool(CARB_ABI* getDeviceName)(Direction dir, size_t index, char* name, size_t maxLength); /** Retrieves the GUID of a requested device. * * @param[in] dir The audio direction to get the device GUID for. * @param[in] index The index of the device to retrieve the GUID for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] guid Receives the GUID of the requested device if it could be * retrieved. This may not be nullptr. * @returns `true` if the device GUID was successfully retrieved. * @returns `false` if the device index was out of range. */ bool(CARB_ABI* getDeviceGuid)(Direction dir, size_t index, carb::extras::Guid* guid); /** Retrieves the unique identifier for the requested device. * * @param[in] dir The audio direction to get the device name for. * @param[in] index The index of the device to retrieve the identifier for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] id Receives the identifier of the requested device if it could be * retrieved. This may not be nullptr. * @param[in] maxLength The maximum number of characters including the null terminator * that can be stored in the output buffer. * @returns `true` if the device identifier was successfully retrieved. * @returns `false` if the device index was out of range. */ bool(CARB_ABI* getDeviceId)(Direction dir, size_t index, char* id, size_t maxLength); /** Retrieves the closest matching device index from an identifier. * * @param[in] dir The audio direction to get the device index for. * @param[in] id The identifier of the device to match to the current device list. * @returns The index of the device that matches the given identifier if an exact match * was found. Note that the match may have been made either by the device's * friendly name or by its unique identifier. This should be an identifier * returned from a previous call to getDeviceId() or getDeviceName(). Note * that this identifier may be stored persistently to attempt access to the * same device in a future launch. * @returns 0 if no matching device was found and the system's default device was * chosen instead. * * @remarks This checks the current system device list to find a device that matches * the given identifier. The device identifiers returned from getDeviceId() * contain both the device's friendly name and its unique identifier code. * Matches will first check the unique identifier. If no match is found, * it will compare against the friendly name. If the unique identifier portion * is not present, a match by the friendly name will be attempted instead. Note * that the device's friendly name may not necessarily be unique, even among * different removeable devices. For example, multiple USB headsets may have * their output sides appear to the system as just simply "Speakers". If a * persistent storage of the device identifier is needed, the name returned * from getDeviceId() should be preferred over that of getDeviceName(). */ size_t(CARB_ABI* getDeviceIndexFromId)(Direction dir, const char* id); /** Retrieves the preferred frame rate of a requested device. * * @param[in] dir The audio direction to get the preferred frame rate for. * @param[in] index The index of the device to retrieve the frame rate for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @returns The preferred frame rate of the requested device if it could be retrieved. * @returns 0 if the device index was out of range. * * @remarks This retrieves the preferred frame rate of a requested device. The preferred * frame rate is the rate at which the device natively wants to process audio data. * Using the device at other frame rates may be possible but would require extra * processing time. Using a device at a different frame rate than its preferred * one may also result in degraded quality depending on what the processing versus * preferred frame rate is. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ size_t(CARB_ABI* getDeviceFrameRate)(Direction dir, size_t index); /** Retrieves the maximum channel count for a requested device. * * @param[in] dir The audio direction to get the maximum channel count for. * @param[in] index The index of the device to retrieve the channel count for. * This should be between 0 and one less than the most recent * return value of getDeviceCount(). * @returns The maximum channel count of the requested device if it could be retrieved. * @returns 0 if the device index was out of range. * * @remarks This retrieves the maximum channel count for a requested device. This count * is the maximum number of channels that the device can natively handle without * having to trim or reprocess the data. Using a device with a different channel * count than its maximum is allowed but will result in extra processing time to * upmix or downmix channels in the stream. Note that downmixing channel counts * (ie: 7.1 to stereo) will often result in multiple channels being blended * together and can result in an unexpected final signal in certain cases. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ size_t(CARB_ABI* getDeviceChannelCount)(Direction dir, size_t index); /** Retrieves the native sample size for a requested device. * * @param[in] dir The audio direction to get the native sample size for. * @param[in] index The index of the device to retrieve the sample size for. * This should be between 0 and one less than the most recent * return value of getDeviceCount(). * @returns The native sample size in bits per sample of the requested device if it * could be retrieved. * @returns 0 if the device index was out of range. * * @remarks This retrieves the bits per sample that a requested device prefers to process * its data at. It may be possible to use the device at a different sample size, * but that would likely result in extra processing time. Using a device at a * different sample rate than its native could degrade the quality of the final * signal. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ size_t(CARB_ABI* getDeviceSampleSize)(Direction dir, size_t index); /** Retrieves the native sample data type for a requested device. * * @param[in] dir The audio direction to get the native sample data type for. * @param[in] index The index of the device to retrieve the sample data type for. * This should be between 0 and one less than the most recent * return value of getDeviceCount(). * @returns The native sample data type of the requested device if it could be retrieved. * @returns @ref SampleType::eUnknown if the device index was out of range. * * @remarks This retrieves the sample data type that a requested device prefers to process * its data in. It may be possible to use the device with a different data type, * but that would likely result in extra processing time. Using a device with a * different sample data type than its native could degrade the quality of the * final signal. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ SampleType(CARB_ABI* getDeviceSampleType)(Direction dir, size_t index); /** Check if the audio device backend uses direct hardware access. * @returns `true` if this backend has direct hardware access. * This will be returned when ALSA is in use. * @returns `false` if the backend is an audio mixing server. * This will be returned when Pulse Audio or Window Audio Services * are in use. * * @remarks A direct hardware audio backend is capable of exclusively locking * audio devices, so devices are not guaranteed to open successfully * and opening devices to test their format may be disruptive to the system. * * @remarks ALSA is the only 'direct hardware' backend that's currently supported. * Some devices under ALSA will exclusively lock the audio device; * these may fail to open because they're busy. * Additionally, some devices under ALSA can fail to open because * they're misconfigured (Ubuntu's default ALSA configuration can * contain misconfigured devices). * In addition to this, opening some devices under ALSA can take * a substantial amount of time (over 100ms). * For these reasons, it is important to verify that you are not * using a 'direct hardware' backend if you are going to call certain * functions in this interface. */ bool(CARB_ABI* isDirectHardwareBackend)(); }; } }
16,850
C
58.126316
100
0.651751
omniverse-code/kit/include/omni/audio/AudioSettings.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 <omni/kit/SettingsUtils.h> /** audio setting group names. These provide the starting path to all of the common * audio settings. * @{ */ /** the group name for all playback audio settings in Kit. */ #define AUDIO_SETTING_GROUP_CONTEXT "/audio/context" /** @} */ /** setting leaf names. These must be prefixed by @ref AUDIO_SETTING_GROUP_CONTEXT * to be valid for a settings lookup. * @{ */ #define AUDIO_SETTING_NAME_MAXBUSES "maxBuses" #define AUDIO_SETTING_NAME_SPEAKERMODE "speakerMode" #define AUDIO_SETTING_NAME_STREAMERFILE "streamerFile" #define AUDIO_SETTING_NAME_ENABLESTREAMER "enableStreamer" #define AUDIO_SETTING_NAME_DEVICENAME "deviceName" #define AUDIO_SETTING_NAME_CAPTUREDEVICENAME "captureDeviceName" #define AUDIO_SETTING_NAME_AUTOSTREAM "autoStreamThreshold" #define AUDIO_SETTING_NAME_AUDIO_PLAYER_AUTOSTREAM "audioPlayerAutoStreamThreshold" #define AUDIO_SETTING_NAME_CLOSEONSOUNDSTOP "closeAudioPlayerOnStop" #define AUDIO_SETTING_NAME_MASTERVOLUME "masterVolume" #define AUDIO_SETTING_NAME_USDVOLUME "usdVolume" #define AUDIO_SETTING_NAME_SPATIALVOLUME "spatialVolume" #define AUDIO_SETTING_NAME_NONSPATIALVOLUME "nonSpatialVolume" #define AUDIO_SETTING_NAME_UIVOLUME "uiVolume" /** @} */ /********************************** Audio Settings Paths *****************************************/ namespace omni { namespace audio { /** full path suffixes for the Kit audio settings. For the app preferences settings values * that should persist between launches of Kit, these names should each be prefixed with * @ref PERSISTENT_SETTINGS_PREFIX. If a value should not persist but instead be reset * between launches, it should not have a prefix. * * Each of these settings paths should be created by concatenating an optional persistence * prefix, one AUDIO_SETTING_GROUP_* name, a group separator (ie: @ref SETTING_SEP), and one * AUDIO_SETTING_NAME_* value name. * * @{ */ /** the number of buses to create the main audio playback context with. This will control * the maximum number of simultaneous voices that can be heard during playback. Any playing * voices beyond this count will be 'virtual' and will only be heard when another voice * releases its bus. This defaults to 0 which lets the context decide on creation. */ constexpr const char* const kSettingMaxBuses = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_MAXBUSES; /** the standard speaker layout to use for playback. This defaults to the speaker mode that * most closely corresponds to the device's preferred channel count. */ constexpr const char* const kSettingSpeakerMode = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_SPEAKERMODE; /** the name of the file to stream output to. This will be written as a RIFF wave file in * the same data format that the playback context chooses. The file will not be created * unless audio (even silent audio) is written to it. The file will also only be created * if the @ref AUDIO_SETTING_NAME_ENABLESTREAMER setting is also enabled. This defaults * to an empty string. */ constexpr const char* const kSettingStreamerFile = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_STREAMERFILE; /** boolean option to control whether the streamer is used or not for the current session. * Note that this setting is intentionally not persistent. This should always be disabled * on launch. If it were persistent, it would lead to all audio being recorded even when * not intended, and potentially filling up the local drive. */ constexpr const char* const kSettingEnableStreamer = AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_ENABLESTREAMER; /** the identifier of the device that should be used for audio playback. This name can be * retrieved from the omni::audio::IAudioDeviceEnum interface using the getDeviceId() * function. This name may consist of a device GUID, a friendly device name, or a * combination of both. If a GUID is provided, a connected device using that name will * be chosen if found. If a GUID is not provided or no connected device matches the * given GUID, the device will attempt to match by its friendly name. Note that this * friendly name is not necessarily unique in the system and the wrong device may end * up being selected in this case (if multiple devices with the same friendly name * are connected). This defaults to an empty string indicating that the system's default * device should always be used. */ constexpr const char* const kSettingDeviceName = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_DEVICENAME; /** The identifier of the device that should be used for audio capture. * This functions identically to @ref kSettingDeviceName, except that it's used * to specify the capture device instead of the playback device. */ constexpr const char* const kSettingCaptureDeviceName = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_CAPTUREDEVICENAME; /** the current auto-stream threshold setting in kilobytes. This controls when the audio * data system decides to stream an encoded sound versus decode it fully on load. This * threshold represents the decoded size of a sound above which it will be streamed instead * of decoded. If the decoded size of the sound is less than this threshold, it will be * decoded on load instead. */ constexpr const char* const kSettingAutoStream = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_AUTOSTREAM; /** the current auto-stream threshold setting in kilobytes specifically for the audio player. * This controls when the audio data system decides to stream an encoded sound versus decode it fully on load. * This threshold represents the decoded size of a sound above which it will be streamed instead * of decoded. If the decoded size of the sound is less than this threshold, it will be * decoded on load instead. Note that this setting is only for the audio player. Use @ref kSettingAutoStream * for the Audio Manager's auto stream threshold. */ constexpr const char* const kSettingAudioPlayerAutoStream = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_AUDIO_PLAYER_AUTOSTREAM; /** The option to close the audio player window when the sound is stopped. * If this is enabled, then the audio player will be automatically closed when the user clicks * the stop button or when the sound reaches its natural end. */ constexpr const char* const kSettingCloseOnSoundStop = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_CLOSEONSOUNDSTOP; /** the master volume level setting to use. This master volume affects all audio output * from the USD stage audio manager, UI audio manager, and the audio player interfaces. * This level should be set to 1.0 for full volume and 0.0 for silence. The volume scale * is approximately linear. This defaults to 1.0. */ constexpr const char* const kSettingMasterVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_MASTERVOLUME; /** the master volume for the USD stage audio manager to use. This does not affect the * UI audio manager or the audio player interfaces. This level should be set to 1.0 for * full volume and 0.0 for silence. The volume scale is approximately linear. This * defaults to 1.0. */ constexpr const char* const kSettingUsdVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_USDVOLUME; /** the relative volume level for spatial audio sounds in the USD stage audio manager. This * volume level will effectively be multiplied by the master volume and USD volume levels * above to get the final effective volume level for spatial sounds. This level should be * set to 1.0 for full volume and 0.0 for silence. The volume scale is approximately linear. * This defaults to 1.0. */ constexpr const char* const kSettingSpatialVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_SPATIALVOLUME; /** the relative volume level for non-spatial audio sounds in the USD stage audio manager. This * volume level will effectively be multiplied by the master volume and USD volume levels above * to get the final effective volume level for non-spatial sounds. This level should be set to * 1.0 for full volume and 0.0 for silence. The volume scale is approximately linear. This * defaults to 1.0. */ constexpr const char* const kSettingNonSpatialVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_NONSPATIALVOLUME; /** the master volume level for the UI audio manager. This level should be set to 1.0 for full * volume, and 0.0 for silence. The volume scale is approximately linear. This defaults to * 1.0. */ constexpr const char* const kSettingUiVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_UIVOLUME; /** @} */ } }
9,705
C
52.32967
114
0.766306
omniverse-code/kit/include/omni/audio/IUiAudio.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/Interface.h> namespace omni { namespace audio { /** public container for a loaded editor UI sound. These objects are returned from * @ref IUiAudio::createSound(). These objects can be copied as needed. Once destroyed, * the sound itself will only be destroyed if the no other objects refer to it as well. */ class UiSound { public: UiSound() = default; UiSound(const UiSound&) = default; virtual ~UiSound() = default; virtual UiSound& operator=(const UiSound&) = 0; }; /** simple interface to manage editor UI sound objects. This allows new sound objects to be * created (and loaded) from local disk, sounds to be played, stopped, and queried. */ struct IUiAudio { CARB_PLUGIN_INTERFACE("omni::audio::IUiAudio", 0, 1); /** Loads an editor UI sound from local disk. * * @param[in] filename the path to the sound file to load. This should be an absolute * path, but can be a relative path that will be resolved using the * current working directory for the process. This may not be * nullptr. Parts of this path may include some special path * specifiers that will be resolved when trying to open the file. * See the remarks section below for more info. This may not be * nullptr or an empty string. * @return the sound object representing the new loaded sound. This sound can be passed to * playSound() later. Each sound object returned here must be destroyed by * deleting it when it is no longer needed. Note that destroying the sound object * will stop all playing instances of it. However, if more than one reference to * the same sound object still exists, deleting one of the sound objects will not * stop any of the instances from playing. It is best practice to always explicitly * stop a sound before destroying it. * @return nullptr if the file could not be loaded could not be loaded. * * @remarks This loads a sound that can be played with playSound() at a later time. This * sound only needs to be loaded once but can be played as many times as needed. * When no longer needed, the sound should be destroyed by deleting it. * * @remarks File names passed in here may contain special path markers. * * @note This operation is always thread safe. */ UiSound*(CARB_ABI* createSound)(const char* filename); /** Immediately plays the requested UI sound if it is loaded. * * @param[in] sound the name of the UI sound to be played. This may not be nullptr. * @return no return value. * * @remarks This plays a single non-looping instance of a UI sound immediately. The UI sound * must have already been loaded. If the sound resource was missing or couldn't be * loaded, this call will simply be ignored. This will return immediately after * scheduling the sound to play. It will never block for the duration of the sound's * playback. This sound may be prematurely stopped with stopSound(). * * @note This operation is always thread safe. */ void(CARB_ABI* playSound)(UiSound* soundToPlay); /** Queries whether a sound object is currently playing. * * @param[in] sound the sound object to query the playing state for. This may not be * nullptr. * @return true if the sound object is currently playing. * @return false if the sound has either finished playing or has not been played yet. * * @remarks This queries whether a sound is currently playing. If this fails, that may mean * that the sound ended naturally on its own or it was explicitly stopped. Note * that this may continue to return true for a short period after a sound has been * stopped with stopSound() or stopAllSounds(). This period may be up to 10 * milliseconds. */ bool(CARB_ABI* isSoundPlaying)(const UiSound* sound); /** Immediately stops the playback of a sound. * * @param[in] sound the sound object to stop playback for. This may not be nullptr. * @return no return value. * * @remarks This stops the playback of an active sound. If the sound was not playing or had * already naturally stopped on its own, this call is ignored. */ void(CARB_ABI* stopSound)(UiSound* sound); /** Retrieves length of a sound in seconds (if known). * * @param[in] sound the sound to retrieve the length for. This may not be nullptr. * @return the play length of the sound in seconds if the asset is loaded and the length * can be calculated. * @return 0.0 if the sound asset is not available yet or the length could not be properly * calculated. * * @remarks This calculates the length of a UI sound in seconds. This is just the length * of the sound asset in seconds. */ double(CARB_ABI* getSoundLength)(UiSound* sound); }; } }
5,794
C
46.113821
99
0.648602
omniverse-code/kit/include/omni/audio/IAudioRecorder.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/audio/IAudioCapture.h> namespace omni { namespace audio { /** The audio recorder instance. * This is created to reserve a device that can record audio. */ struct AudioRecorder; /** A callback to read data from the audio device. * @param[in] data The audio data that was recorded. * @param[in] frames The number of frames of audio that are available in @p data. * @param[inout] context A user-defined context that gets passed through to the callback. */ using ReadCallback = void (*)(const void* data, size_t frames, void* context); /** The descriptor used to create a recording session. */ struct AudioRecordDesc { /** Flags for future expansion. * This must be set to 0. */ uint32_t flags = 0; /** The filename to write the output audio to. * This can be nullptr to use @p callback to receive audio instead. */ const char* filename = nullptr; /** The read callback to receive data with. * This will be called periodically when data is available. * This can be nullptr if @ref filename is non-null. * If this is set to non-null and @ref filename is non-null, this callback * will be called after the data has been written to the file (the data may * not have been flushed at this point though). * Note that if this callback takes too long, it can cause a recording overrun. * This callback occurs asynchronously under the recursive mutex of the * @ref AudioRecorder; if a lock is acquired in @ref callback, it is * important to ensure this does not result in the two locks being * acquired in different orders, which could potentially cause deadlock. */ ReadCallback callback = nullptr; /** A parameter that gets passed into the callback. * This is ignored if @ref callback is nullptr. */ void* callbackContext = nullptr; /** The frame rate to capture audio at. * This may be set to 0 to use the default rate for the device. * You can query the device's rate with IAudioRecorder::getDeviceCaps(). * If this is not a frame rate supported by the device, a resampler will be * introduced, which adds a small performance cost. */ size_t frameRate = 0; /** The number of channels that the audio is being captured at. * This may be set to 0 to use the default channel count for the device. * You can query the device's channel count with IAudioRecorder::getDeviceCaps(). * If this is different than the device's channel count an up/downmixing * operation may have to be introduced, which add a small performance cost. * The channel mixing matrices chosen are chosen based on the set of * default speaker modes used by carb.audio for a given channel count; * see carb::audio::getSpeakerModeForCount() for this list of defaults. */ size_t channels = 0; /** The format that data will be produced by the capture device. * This may be @ref carb::audio::SampleFormat::eDefault to use the device's * preferred format. * You can query the device's rate with IAudioRecorder::getDeviceCaps(). * This must be set to a PCM format if @ref callback is non-null. * If this is not a format supported by the device, a format conversion * will be introduced which adds a very small performance cost. */ carb::audio::SampleFormat sampleFormat = carb::audio::SampleFormat::eDefault; /** The format that gets written to the file. * This is only used if @ref filename is non-null. * This can be any valid sample format. * If this is set to @ref carb::audio::SampleFormat::eDefault, @ref sampleFormat * is used. */ carb::audio::SampleFormat outputFormat = carb::audio::SampleFormat::eDefault; /** The length of the recording buffer. * This setting, combined with @ref period will allow you to choose the * recording latency, as well as the tolerance for variance in recording * latency. * It is important to set this to a large enough value that fluctuation * in system timing can be handled without the audio buffer filling up. * The length can be set to 0 to use the device's default buffer length. */ size_t bufferLength = 0; /** The time between read callbacks. * This value can be used to reduce latency without reducing the ability to * handle fluctuations in timing; for example, setting @ref bufferLength to * 64ms and setting @ref period to 8ms will result in roughly 8ms latency * but the ability to tolerate up to 56ms of lag. * The default value is @ref bufferLength / 2. * This will be clamped to the default period if it exceeds the default period. * Two callbacks may be sent for a given period to handle the end of the * ring buffer. * This may send more data than expected for a given period if the system's * timing fluctuates. */ size_t period = 0; /** Describes how @ref bufferLength and @ref period should be interpreted. * This value is ignored if @ref bufferLength and @ref period are 0. Note * that the buffer size will always be rounded up to the next frame * boundary even if the size is specified in bytes. */ carb::audio::UnitType lengthType = carb::audio::UnitType::eFrames; }; /** Simple interface to be able to record audio. */ struct IAudioRecorder { CARB_PLUGIN_INTERFACE("omni::audio::IAudioRecorder", 0, 1); /** Create an audio recorder instance. * @returns A new audio recorder if creation succeeded. * This must be passed to destroyAudioRecorder() when you are * finished with the instance. * @returns nullptr if creation failed. * * @remarks This creates an audio system that can record audio to a file or to a callback. * * @note Each call to createAudioRecorder() opens a connection to the audio * recording device set in the preferences (@ref kSettingCaptureDeviceName). * It is not recommended to open a large number of these connections. */ AudioRecorder*(CARB_ABI* createAudioRecorder)(); /** Destroy an audio recorder instance. * @param[inout] recorder The recorder to destroy. * * @remarks This function frees the memory allocated to the @ref AudioRecorder. * This will stop the recorder if it was recoding audio when this is called. */ void(CARB_ABI* destroyAudioRecorder)(AudioRecorder* recorder); /** Being recording audio. * @param[inout] recorder The audio recorder to begin recording with. * This should not be nullptr. * @param[in] desc The descriptor for how audio should be recorded. * This should not be nullptr. * * @returns true If recording has started. * @returns false if @p recorder or @p desc are nullptr. * @returns false if another error occurred. */ bool(CARB_ABI* beginRecording)(AudioRecorder* recorder, const AudioRecordDesc* desc); /** Stop recording audio. * @param[inout] recorder The audio recorder to stop recording on. * This should not be nullptr. * @param[in] flush Set this to true to flush the rest of the data * that is currently in the capture device's buffer. * Set this to false to discard any remaining queued * data. * * @remarks This should be called when beginRecording() has been previously * called and you want to stop recording. */ void(CARB_ABI* stopRecording)(AudioRecorder* recorder, bool flush); /** Retrieves the sound format for the recorder. * @param[in] recorder The recorder to retrieve the device information for. * This should not be nullptr. * @param[out] format Receives the format. * This should not be nullptr. * If beginRecording() was called, this will return * the current format that is being used for recording. * If beginRecording() has not been called yet, this * will return the default format specified by the device. * @returns true if the device info was successfully retrieved. * @returns false if either parameter was nullptr. * @returns false if the call fails for any other reason. */ bool(CARB_ABI* getFormat)(AudioRecorder* recorder, carb::audio::SoundFormat* format); }; } }
9,209
C
44.594059
95
0.664676
omniverse-code/kit/include/omni/audio/experimental/IAudioCapture.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/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** An individual audio capture stream. */ template <> class omni::core::Generated<omni::audio::experimental::ICaptureStream_abi> : public omni::audio::experimental::ICaptureStream_abi { public: OMNI_PLUGIN_INTERFACE("omni::audio::experimental::ICaptureStream") /** Starts capturing audio data from the stream. * * @param[in] flags Flags to alter the recording behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture is successfully started. * @returns An @ref AudioResult error code if the stream could not be started. * * @remarks Audio streams are in a stopped state when they're created. * You must call start() to start recording audio. * * @remarks Without @ref fCaptureStreamStartFlagOneShot, the stream will * perform looping capture. This means that once the ring buffer * has been filled, audio will start being recorded from the start * of the buffer again. * * @remarks Looping audio will not overwrite unread parts of the ring buffer. * Only parts of the buffer that have been unlocked can be overwritten * by the audio system. * Data written into the ring buffer must be unlocked periodically * when using looping capture or the ring buffer will fill up and * the device will overrun. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ omni::audio::experimental::AudioResult start(omni::audio::experimental::CaptureStreamStartFlags flags) noexcept; /** Stop capturing audio data from the stream. * * @param[in] flags Flags to alter the stopping behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture was successfully stopped. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream was already stopped. * @returns An @ref AudioResult error code if something else went wrong. * The stream is likely broken in this case. * * @remarks This will stop capturing audio. Any audio data that would have * been captured between this point and the next call to @ref ICaptureStream_abi::start_abi() * will be lost. * * @remarks If there is unread data in the buffer, that data can still be * read with lock() after the stream is stopped. * * @note If fCaptureStreamStopFlagSync was not specified, the stop call will not sync with the * device so you could still receive callbacks after. * * @note CC-1180: You cannot use fCaptureStreamStopFlagSync from a callback. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ omni::audio::experimental::AudioResult stop(omni::audio::experimental::CaptureStreamStopFlags flags) noexcept; /** Check if the stream is still capturing data. * @returns `true` if the stream is still capturing. * @returns `false` if the stream is stopped. * Callbacks will no longer be sent if `false` was returned unless the strema was * stoped with @ref ICaptureStream_abi::stop_abi() was called without fCaptureStreamStopFlagSync. */ bool isCapturing() noexcept; /** Get the available number of frames to be read. * * @param[out] available The number of frames that can be read from the buffer. * * @returns @ref carb::audio::AudioResult::eOk if the frame count was retrieved successfully. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast enough and * the buffer filled up. * @returns @ref carb::audio::AudioResult::eNotAllowed if callback recording is being used. * @returns An @ref AudioResult error code if the operation fails for any other reason. * * @remarks This will check how much data is available to be read from the buffer. * This call is only valid when polling style recording is in use. */ omni::audio::experimental::AudioResult getAvailableFrames(size_t* available) noexcept; /** Lock the next chunk of the buffer to be read. * * @param[in] request The length of the buffer to lock, in frames. * This may be 0 to lock as much data as possible. * This does not need to be a multiple of the fragment * length. * If you need to convert bytes to frames, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes() (note that this is * slow due to requiring a division). * @param[out] region Receives the audio data. * This can be `nullptr` to query the available data * in the buffer, rather than locking it. * This buffer can be held until unlock() is called; * after unlock is called, the stream can start writing * into this buffer. * @param[out] received The length of data available in @p buffer, in frames. * This will not exceed @p request. * Due to the fact that a ring buffer is used, you may * have more data in the buffer than is returned in one * call; a second call would be needed to read the full * buffer. * If you need to convert this to bytes, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes(). * * @returns @ref carb::audio::AudioResult::eOk if the requested region is successfully locked. * @returns @ref carb::audio::AudioResult::eOutOfMemory if there is no audio data available * in the buffer yet. * @returns @ref carb::audio::AudioResult::eNotAllowed if a region is already locked * and needs to be unlocked. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream is using callback * style recording. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast * enough and the underlying device has overrun. * This will happen on some audio systems (e.g. ALSA) if the * capture buffer fills up. * This can also happen on some audio systems sporadically if the * device's timing characteristics are too aggressive. * @returns an carb::audio::AudioResult::e* error code if the region could not be locked. * * @remarks This is used to get data from the capture stream when polling * style recording is being used (ie: there is no data callback). * When using this style of recording, portions of the buffer must * be periodically locked and unlocked. * * @remarks This retrieves the next portion of the buffer. * This portion of the buffer is considered to be locked until * @ref ICaptureStream_abi::unlock_abi() is called. * Only one region of the buffer can be locked at a time. * When using a looping capture, the caller should ensure that data * is unlocked before the buffer fills up or overruns may occur. */ omni::audio::experimental::AudioResult lock(size_t request, const void** region, size_t* received) noexcept; /** Unlocks a previously locked region of the buffer. * * @param[in] consumed The number of frames in the previous buffer that were consumed. * Any frames that were not consumed will be returned in future * @ref ICaptureStream_abi::lock_abi() calls. * 0 is valid here if you want to have the same locked region * returned on the next lock() call. * * @returns @ref carb::audio::AudioResult::eOk if the region is successfully unlocked. * @returns @ref carb::audio::AudioResult::eOutOfRange if @p consumed was larger than * the locked region. * @returns @ref carb::audio::AudioResult::eNotAllowed if no region is currently locked. * @returns an carb::audio::AudioResult::e* error code if the region could not be unlocked. * * @remarks This unlocks a region of the buffer that was locked with a * previous call to ICaptureStream_abi::lock_abi(). * Now that this region is unlocked, the device can start writing to it, * so the caller should no longer access that region. * Once the buffer is unlocked, a new region may be locked with ICaptureStream_abi::lock_abi(). * * @note If the locked region is not fully unlocked, the part of the region that * was not unlocked will be returned on the next call to ICaptureStream_abi::lock_abi(). * A second call to unlock cannot be made in this situation, it will fail. */ omni::audio::experimental::AudioResult unlock(size_t consumed) noexcept; /** Retrieve the size of the capture buffer. * * @returns The size of the capture buffer, in frames. * You can use @ref ICaptureStream_abi::getSoundFormat_abi() and @ref carb::audio::convertUnits() * to convert to bytes or other units. * * @remarks If your code is dependent on the buffer's actual size, it is * better to retrieve it with this function since the buffer size * used with device creation can be adjusted. */ size_t getBufferSize() noexcept; /** Retrieve the number of fragments used in this stream. * * @returns The number of buffer fragments. * This is the number of regions the recording buffer is divided * into. */ size_t getFragmentCount() noexcept; /** Retrieve the format of the audio being captured. * * @param[out] format The format of the audio being captured. * This may not be `nullptr`. */ void getSoundFormat(omni::audio::experimental::SoundFormat* format) noexcept; /** Clear any data that is currently in the recording buffer. * * @returns @ref carb::audio::AudioResult::eOk if the buffer was successfully cleared. * @returns an carb::audio::AudioResult::e* error code if the buffer could not be cleared. * * @remarks This is a quick way to get rid of any data that is left in the * buffer. * This will also reset the write position on the buffer back to * 0, so the next lock call will return the start of the buffer * (this can be useful if you want to do a one shot capture of the * entire buffer). * * @note If this is called while the capture stream is recording, the stream * will be paused before it is reset. */ omni::audio::experimental::AudioResult reset() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::start( omni::audio::experimental::CaptureStreamStartFlags flags) noexcept { return start_abi(flags); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::stop( omni::audio::experimental::CaptureStreamStopFlags flags) noexcept { return stop_abi(flags); } inline bool omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::isCapturing() noexcept { return isCapturing_abi(); } inline omni::audio::experimental::AudioResult omni::core::Generated< omni::audio::experimental::ICaptureStream_abi>::getAvailableFrames(size_t* available) noexcept { return getAvailableFrames_abi(available); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::lock( size_t request, const void** region, size_t* received) noexcept { return lock_abi(request, region, received); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::unlock( size_t consumed) noexcept { return unlock_abi(consumed); } inline size_t omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::getBufferSize() noexcept { return getBufferSize_abi(); } inline size_t omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::getFragmentCount() noexcept { return getFragmentCount_abi(); } inline void omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::getSoundFormat( omni::audio::experimental::SoundFormat* format) noexcept { getSoundFormat_abi(format); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::reset() noexcept { return reset_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL static_assert(std::is_standard_layout<omni::audio::experimental::Format>::value, "omni::audio::experimental::Format must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::audio::experimental::CaptureDeviceDesc>::value, "omni::audio::experimental::CaptureDeviceDesc must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::audio::experimental::CaptureInfoData>::value, "omni::audio::experimental::CaptureInfoData must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::audio::experimental::CaptureStreamDesc>::value, "omni::audio::experimental::CaptureStreamDesc must be standard layout to be used in ONI ABI");
15,201
C
48.197411
132
0.649299
omniverse-code/kit/include/omni/audio/experimental/IAudioCapture.h
// Copyright (c) 2021-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 An updated audio capture interface. */ #pragma once #include <omni/core/BuiltIn.h> #include <omni/core/IObject.h> #include <omni/core/Api.h> #include <omni/log/ILog.h> #include <carb/audio/AudioTypes.h> namespace omni { /** Omniverse audio project. */ namespace audio { /** The omni::audio namespace is part of an audio refresh that is still in the experimental stages. * This currently only contains the IAudioCapture interface, which was created to address a number * of defects in carb::audio::IAudioCapture. * IAudioCapture is currently in beta stage; the interface is complete and unlikely to change * substantially but it has not been tested heavily in a real-world use case yet. * The ABI of IAudioCapture and ICaptureStream are stable and will not be broken without a * deprecation warning given in advance. */ namespace experimental { /******************************** renamed carb::audio types **************************************/ /** @copydoc carb::audio::AudioResult */ using AudioResult = carb::audio::AudioResult; /** @copydoc carb::audio::SpeakerMode */ using SpeakerMode = carb::audio::SpeakerMode; /** @copydoc carb::audio::SampleFormat */ using SampleFormat = carb::audio::SampleFormat; /** @copydoc carb::audio::SoundFormat */ using SoundFormat = carb::audio::SoundFormat; /******************************** typedefs, enums, & macros **************************************/ /** The minimal format needed to interpret an PCM audio stream. * Non-PCM (compressed) audio streams may need different format information or * no format information to interpret. */ struct Format { /** The rate at which this audio stream is intended to be played (number of * audio frames per second). * A frame is a group of @ref channels audio samples taken at a given time point; * this is often referred to as the 'sample rate'. */ size_t frameRate = 0; /** The number of channels in the audio stream. */ size_t channels = 0; /** This specifies the intended usage of each channel in the audio stream. * This will be a combination of one or more of the @ref carb::audio::Speaker names or * a @ref carb::audio::SpeakerMode name. */ SpeakerMode channelMask = carb::audio::kSpeakerModeDefault; /** The data type of each audio sample in this audio stream. */ SampleFormat format = SampleFormat::eDefault; }; /** Flags to indicate some additional behaviour of the device. * No flags are currently defined. */ using CaptureDeviceFlags = uint32_t; /** The parameters to use when opening a capture device. */ struct CaptureDeviceDesc { /** Flags to indicate some additional behaviour of the device. * No flags are currently defined. This should be set to 0. */ CaptureDeviceFlags flags = 0; /** The index of the device to be opened. * Index 0 will always be the system's default capture device. * These indices are the same as the ones used in @ref carb::audio::IAudioDevice, * so that interface should be used to enumerate the system's audio devices. * * This must be less than the return value of the most recent call to @ref * carb::audio::IAudioDevice::getDeviceCount() for capture devices. * Note that since the capture device list can change at any time * asynchronously due to external user action, setting any particular * value here is never guaranteed to be valid. * There is always the possibility the user could remove the device after * its information is collected but before it is opened. * * Additionally, there is always a possibility that a device will fail to * open or the system has no audio capture devices, so code must be able to * handle that possibility. * In particular, it is common to run into misconfigured devices under ALSA; * some distributions automatically configure devices that will not open. */ size_t index = 0; /** The format to use for the capture stream. * Leaving this struct at its default values will cause the audio device's * default format to be used * (This can be queried later with @ref ICaptureStream_abi::getSoundFormat_abi()). * The audio stream will accept any valid PCM format, even if the underlying * device does not support that format. */ Format format = {}; /** The length of the ring buffer to capture data into, in frames. * The buffer length in combination with @ref bufferFragments determines * the minimum possible latency of the audio stream, which the time to * record one fragment of audio. * The buffer length will be automatically adjusted to ensure that its size * is divisible by the fragment count. * * This will not determine the buffer size of the underlying audio device, * but if it is possible, the underlying audio device will be adjusted to * best match this buffer length and fragment combination. * * Setting this to 0 will choose the underlying device's buffer length or * a default value if the underlying device has no buffer. */ size_t bufferLength = 0; /** The number of fragments that the recording buffer is divided into. * When using callback based recording, one fragment of audio will be sent * to each callback. * When using polling based recording, data will become available in one * fragment increments. * One fragment of audio becomes the minimum latency for the audio stream. * Setting an excessive number of fragments will reduce the efficiency of * the audio stream. * * Setting this to 0 will choose the underlying device's fragment count or * a default value if the underlying device doesn't use a ring buffer system. */ size_t bufferFragments = 0; }; class ICaptureStream; /** A callback that's used to receive audio data from an audio capture stream. * @param[inout] stream The stream that this callback was fired from. * @param[in] buffer The audio data that's been captured. * The data in the buffer will be in the format specified * by ICaptureStream::getSoundFormat(). * If the stream was created with @ref fCaptureStreamFlagLowLatency, * this buffer will not be valid once the callback returns; * otherwise, the buffer will be invalidated once ICaptureStream::unlock() * is called for this portion of the buffer. * See the note on unlocking the buffer for more detail on this. * @param[in] frames The length of audio in @p buffer, in frames. * If the stream was created with @ref fCaptureStreamFlagLowLatency, * the frame count passed to each callback may differ; * otherwise, the frame count will be exactly one fragment long. * If you need to convert to bytes, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes(). * @param[inout] context The user-specified callback data. * * @note If the stream was not created with @ref fCaptureStreamFlagLowLatency, * data returned from this function is considered *locked*. * For data to become unlocked, the caller needs to call * ICaptureStream::unlock() with the number of frames that have been * locked by this call. * If the data is not unlocked, that portion of the buffer cannot be overwritten. * It is not required to release the buffer before the callback ends, but * the data needs to be unlocked eventually otherwise you will stop receiving * data and an overrun may occur. * * @note This callback executes from its own thread, so thread safety will need * to be considered. * This is called on the same thread as CaptureInfoCallback, so these * two calls can access the same data without concurrency issues. * * @note This callback must return as fast as possible, since this is called * directly from the audio capture thread (e.g. under 1ms). * A callback that takes too long could cause capture overruns. * Doing anything that could involve substantial waits (e.g. calling into python) * should be avoided; in those cases you should copy the buffer somewhere else * or use a omni::extras::DataStreamer for a series of asynchronous * data packets. * * @note It is safe to call any @ref ICaptureStream function from within this * callback, but it is not safe to destroy the @ref ICaptureStream object * from within it. */ using CaptureDataCallback = void (*)(ICaptureStream* stream, const void* buffer, size_t frames, void* context); /** The reason that a CaptureInfoCallback was called. */ enum class CaptureInfoType { /** An overrun has occurred. * Overruns occur when data is not captured fast enough from the audio * device, the device's buffer fills up and data is lost. * An overrun can occur because a callback took too long, data was not * unlocked fast enough or the underlying audio device encountered an * overrun for other reasons (e.g. system latency). */ eOverrun, /** The audio device has encountered an unrecoverable issue, such as the * device being unplugged, so capture has stopped. */ eDeviceLost, }; /** Extra data for @ref CaptureInfoCallback. * The union member used is based off of the `type` parameter. */ union CaptureInfoData { /** Data for @ref CaptureInfoType::eOverrun. * Overruns have no additional data. */ struct { } overrun; /** Data for @ref CaptureInfoType::eDeviceLost. * Device lost events have no additional data. */ struct { } deviceLost; /** Size reservation to avoid ABI breaks. */ struct { OMNI_ATTR("no_py") uint8_t x[256]; } reserved; }; /** A callback that's used to signal capture stream events. * @param[inout] stream The stream that this callback was fired from. * @param[in] type What type of event occurred. * @param[in] data Data related to this error. * @param[inout] context The user-specified callback data. * * @remarks This callback is used to signal various events that a capture stream * can encounter. * Overrun events indicate that data from the capture stream has been lost. * The callee should do whatever is appropriate to handle this situation * (e.g. toggle a warning indicator on the UI). * Device lost events indicate that an unrecoverable issue has occurred * with the audio device (such as it being unplugged) and capture cannot * continue. * * @note This callback executes from its own thread, so thread safety will need * to be considered. * This is called on the same thread as @ref CaptureDataCallback, so these * two calls can access the same data without concurrency issues. * * @note Similarly to @ref CaptureDataCallback, this callback should return as * quickly as possible to avoid causing overruns. * After an overrun has occurred, the device will be restarted immediately, * so this callback taking too long could result in another overrun callback * happening immediately after your callback returns. */ using CaptureInfoCallback = void (*)(ICaptureStream* stream, CaptureInfoType type, const CaptureInfoData* data, void* context); /** Flags to indicate some additional behaviour of the stream. */ using CaptureStreamFlags = uint32_t; /** Bypass the stream's capture buffer entirely to minimize audio capture * latency as much as possible. * When this flag is set, audio buffers received from the underlying device * will be passed directly to the capture callback. * * @note In this mode, you are at the mercy of the underlying audio system. * The buffers sent to the callback may vary in size and timing. * The bufferLength and bufferFragments parameters passed to the device * are ignored when using this flag. * Since the buffer size may vary, your callbacks must complete as fast * as possible in case the device sends you very small buffers. * * @note The audio buffer *must* be discarded before the callback returns. * This will also cause @ref ICaptureStream_abi::unlock_abi() to be a noop. * * @note If a format conversion is required, the data will be written to an * intermediate buffer that will be sent to your callback. */ constexpr CaptureStreamFlags fCaptureStreamFlagLowLatency = 0x1; /** The descriptor used to create a new @ref ICaptureStream. */ struct CaptureStreamDesc { /** Flags to indicate some additional behaviour of the stream. */ CaptureStreamFlags flags = 0; /** A callback that can be used to receive captured data. * This can be nullptr if a polling style of capture is desired. * This may not be nullptr if @ref fCaptureStreamFlagLowLatency is specified * in @ref flags. */ CaptureDataCallback dataCallback = nullptr; /** A callback that can be used to receive notifications of when an overrun occurs. * This call be nullptr if these notifications are not needed. * This callback can be used when either polling or callback style recording * are being used. */ CaptureInfoCallback errorCallback = nullptr; /** An opaque context value to be passed to the callback whenever it is performed. * This is passed to @ref dataCallback and @ref errorCallback. */ void* callbackContext = nullptr; /** A descriptor of the capture device to use for this stream. */ CaptureDeviceDesc device; }; /** Flags that alter the behavior of @ref ICaptureStream_abi::start_abi(). */ using CaptureStreamStartFlags = uint32_t; /** This will cause recording to be stopped once the full buffer has been recorded. * This may be useful if you want to capture a fixed length of data without having * to time stopping the device. * After capture has stopped, you can use @ref ICaptureStream_abi::lock_abi() to grab * the whole buffer and just use it directly. */ constexpr CaptureStreamStartFlags fCaptureStreamStartFlagOneShot = 0x1; /** Flags that alter the behavior of @ref ICaptureStream_abi::stop_abi(). */ using CaptureStreamStopFlags = uint32_t; /** If this flag is passed, the call to @ref ICaptureStream_abi::stop_abi() will block * until the capture thread has stopped. * This guarantees that no more data will be captured and no more capture * callbacks will be sent. */ constexpr CaptureStreamStopFlags fCaptureStreamStopFlagSync = 0x1; /********************************** IAudioCapture Interface **************************************/ /** An individual audio capture stream. */ class ICaptureStream_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.audio.ICaptureStream")> { protected: /** Starts capturing audio data from the stream. * * @param[in] flags Flags to alter the recording behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture is successfully started. * @returns An @ref AudioResult error code if the stream could not be started. * * @remarks Audio streams are in a stopped state when they're created. * You must call start() to start recording audio. * * @remarks Without @ref fCaptureStreamStartFlagOneShot, the stream will * perform looping capture. This means that once the ring buffer * has been filled, audio will start being recorded from the start * of the buffer again. * * @remarks Looping audio will not overwrite unread parts of the ring buffer. * Only parts of the buffer that have been unlocked can be overwritten * by the audio system. * Data written into the ring buffer must be unlocked periodically * when using looping capture or the ring buffer will fill up and * the device will overrun. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ virtual AudioResult start_abi(CaptureStreamStartFlags flags) noexcept = 0; /** Stop capturing audio data from the stream. * * @param[in] flags Flags to alter the stopping behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture was successfully stopped. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream was already stopped. * @returns An @ref AudioResult error code if something else went wrong. * The stream is likely broken in this case. * * @remarks This will stop capturing audio. Any audio data that would have * been captured between this point and the next call to @ref ICaptureStream_abi::start_abi() * will be lost. * * @remarks If there is unread data in the buffer, that data can still be * read with lock() after the stream is stopped. * * @note If fCaptureStreamStopFlagSync was not specified, the stop call will not sync with the * device so you could still receive callbacks after. * * @note CC-1180: You cannot use fCaptureStreamStopFlagSync from a callback. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ virtual AudioResult stop_abi(CaptureStreamStopFlags flags) noexcept = 0; /** Check if the stream is still capturing data. * @returns `true` if the stream is still capturing. * @returns `false` if the stream is stopped. * Callbacks will no longer be sent if `false` was returned unless the strema was * stoped with @ref ICaptureStream_abi::stop_abi() was called without fCaptureStreamStopFlagSync. */ virtual bool isCapturing_abi() noexcept = 0; /** Get the available number of frames to be read. * * @param[out] available The number of frames that can be read from the buffer. * * @returns @ref carb::audio::AudioResult::eOk if the frame count was retrieved successfully. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast enough and * the buffer filled up. * @returns @ref carb::audio::AudioResult::eNotAllowed if callback recording is being used. * @returns An @ref AudioResult error code if the operation fails for any other reason. * * @remarks This will check how much data is available to be read from the buffer. * This call is only valid when polling style recording is in use. */ virtual AudioResult getAvailableFrames_abi(OMNI_ATTR("out") size_t* available) noexcept = 0; /** Lock the next chunk of the buffer to be read. * * @param[in] request The length of the buffer to lock, in frames. * This may be 0 to lock as much data as possible. * This does not need to be a multiple of the fragment * length. * If you need to convert bytes to frames, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes() (note that this is * slow due to requiring a division). * @param[out] region Receives the audio data. * This can be `nullptr` to query the available data * in the buffer, rather than locking it. * This buffer can be held until unlock() is called; * after unlock is called, the stream can start writing * into this buffer. * @param[out] received The length of data available in @p buffer, in frames. * This will not exceed @p request. * Due to the fact that a ring buffer is used, you may * have more data in the buffer than is returned in one * call; a second call would be needed to read the full * buffer. * If you need to convert this to bytes, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes(). * * @returns @ref carb::audio::AudioResult::eOk if the requested region is successfully locked. * @returns @ref carb::audio::AudioResult::eOutOfMemory if there is no audio data available * in the buffer yet. * @returns @ref carb::audio::AudioResult::eNotAllowed if a region is already locked * and needs to be unlocked. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream is using callback * style recording. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast * enough and the underlying device has overrun. * This will happen on some audio systems (e.g. ALSA) if the * capture buffer fills up. * This can also happen on some audio systems sporadically if the * device's timing characteristics are too aggressive. * @returns an carb::audio::AudioResult::e* error code if the region could not be locked. * * @remarks This is used to get data from the capture stream when polling * style recording is being used (ie: there is no data callback). * When using this style of recording, portions of the buffer must * be periodically locked and unlocked. * * @remarks This retrieves the next portion of the buffer. * This portion of the buffer is considered to be locked until * @ref ICaptureStream_abi::unlock_abi() is called. * Only one region of the buffer can be locked at a time. * When using a looping capture, the caller should ensure that data * is unlocked before the buffer fills up or overruns may occur. */ virtual AudioResult lock_abi(size_t request, OMNI_ATTR("*in, out") const void** region, OMNI_ATTR("out") size_t* received) noexcept = 0; /** Unlocks a previously locked region of the buffer. * * @param[in] consumed The number of frames in the previous buffer that were consumed. * Any frames that were not consumed will be returned in future * @ref ICaptureStream_abi::lock_abi() calls. * 0 is valid here if you want to have the same locked region * returned on the next lock() call. * * @returns @ref carb::audio::AudioResult::eOk if the region is successfully unlocked. * @returns @ref carb::audio::AudioResult::eOutOfRange if @p consumed was larger than * the locked region. * @returns @ref carb::audio::AudioResult::eNotAllowed if no region is currently locked. * @returns an carb::audio::AudioResult::e* error code if the region could not be unlocked. * * @remarks This unlocks a region of the buffer that was locked with a * previous call to ICaptureStream_abi::lock_abi(). * Now that this region is unlocked, the device can start writing to it, * so the caller should no longer access that region. * Once the buffer is unlocked, a new region may be locked with ICaptureStream_abi::lock_abi(). * * @note If the locked region is not fully unlocked, the part of the region that * was not unlocked will be returned on the next call to ICaptureStream_abi::lock_abi(). * A second call to unlock cannot be made in this situation, it will fail. */ virtual AudioResult unlock_abi(size_t consumed) noexcept = 0; /** Retrieve the size of the capture buffer. * * @returns The size of the capture buffer, in frames. * You can use @ref ICaptureStream_abi::getSoundFormat_abi() and @ref carb::audio::convertUnits() * to convert to bytes or other units. * * @remarks If your code is dependent on the buffer's actual size, it is * better to retrieve it with this function since the buffer size * used with device creation can be adjusted. */ virtual size_t getBufferSize_abi() noexcept = 0; /** Retrieve the number of fragments used in this stream. * * @returns The number of buffer fragments. * This is the number of regions the recording buffer is divided * into. */ virtual size_t getFragmentCount_abi() noexcept = 0; /** Retrieve the format of the audio being captured. * * @param[out] format The format of the audio being captured. * This may not be `nullptr`. */ virtual void getSoundFormat_abi(OMNI_ATTR("out") SoundFormat* format) noexcept = 0; /** Clear any data that is currently in the recording buffer. * * @returns @ref carb::audio::AudioResult::eOk if the buffer was successfully cleared. * @returns an carb::audio::AudioResult::e* error code if the buffer could not be cleared. * * @remarks This is a quick way to get rid of any data that is left in the * buffer. * This will also reset the write position on the buffer back to * 0, so the next lock call will return the start of the buffer * (this can be useful if you want to do a one shot capture of the * entire buffer). * * @note If this is called while the capture stream is recording, the stream * will be paused before it is reset. */ virtual AudioResult reset_abi() noexcept = 0; }; /** Low-Level Audio Capture Plugin Interface. * * See these pages for more detail: * @rst * :ref:`carbonite-audio-label` * :ref:`carbonite-audio-capture-label` @endrst */ class IAudioCapture { public: CARB_PLUGIN_INTERFACE("omni::audio::IAudioCapture", 0, 0) /** ABI version of createStream() * * @param[in] desc A descriptor of the settings for the stream. * @param[out] stream The raw stream object. * * @returns @ref carb::audio::AudioResult::eOk on success. @see createStream() for failure codes. */ AudioResult (*internalCreateStream)(const CaptureStreamDesc* desc, ICaptureStream** stream); /** Creates a new audio capture stream. * * @param[in] desc A descriptor of the settings for the stream. * This may be nullptr to create a context that uses the * default capture device in its preferred format. * The device's format information may later be retrieved * with getSoundFormat(). * @param[out] stream The capture stream that is being created. * * @returns @ref carb::audio::AudioResult::eOk if the stream was successfully created. * @returns @ref carb::audio::AudioResult::eInvalidParameter if @p desc is `nullptr`. * @returns @ref carb::audio::AudioResult::eOutOfMemory if the stream's allocation failed. * @returns @ref carb::audio::AudioResult::eOutOfRange if the device's index does not * correspond to a device that exists. * @returns @ref carb::audio::AudioResult::eDeviceLost if the audio device selected fails * to open. */ inline AudioResult createStream(const CaptureStreamDesc* desc, omni::core::ObjectPtr<ICaptureStream>* stream) { if (stream == nullptr) { OMNI_LOG_ERROR("stream was null"); return carb::audio::AudioResult::eInvalidParameter; } ICaptureStream* raw = nullptr; AudioResult res = internalCreateStream(desc, &raw); *stream = omni::core::steal(raw); return res; } }; } // namespace experimental } // namespace audio } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IAudioCapture.gen.h" /** @copydoc omni::audio::experimental::ICaptureStream_abi */ class omni::audio::experimental::ICaptureStream : public omni::core::Generated<omni::audio::experimental::ICaptureStream_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IAudioCapture.gen.h"
29,753
C
46.079114
118
0.651161
omniverse-code/kit/include/omni/inspect/IInspector.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 <omni/core/Omni.h> #include <omni/core/IObject.h> namespace omni { using namespace omni::core; } namespace omni { namespace inspect { OMNI_DECLARE_INTERFACE(IInspector); //! Base class for object inspection requests. class IInspector_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.inspect.IInspector")> { protected: /** Set the help information for the current invocation of the inspector. For when behavior == eHelp * @param[in] helpString The help information, describing the configuration of the inspector */ virtual void setHelp_abi(OMNI_ATTR("c_str, not_null")const char* helpString) noexcept = 0; /** Returns the help information currently available on the inspector. Note that this could change * from one invocation to the next so it's important to read it immediately after requesting it. * @returns String containing the help information describing the current configuration of the inspector */ virtual OMNI_ATTR("c_str")const char* helpInformation_abi() noexcept = 0; /** Returns the common flag used to tell the inspection process to put the help information into the * inspector using the setHelp_abi function. Using this approach avoids having every inspector/object * combination add an extra ABI function just for retrieving the help information, as well as providing a * consistent method for requesting it. * @returns String containing the name of the common flag used for help information */ virtual OMNI_ATTR("c_str, not_null")const char* helpFlag_abi() noexcept = 0; /** Enable or disable an inspection flag. It's up to the individual inspection operations or the derived * inspector interfaces to interpret the flag. * @param[in] flagName Name of the flag to set * @param[in] flagState New state for the flag */ virtual void setFlag_abi(OMNI_ATTR("c_str, not_null")const char* flagName, bool flagState) noexcept = 0; /** Checks whether a particular flag is currently set or not. * @param[in] flagName Name of the flag to check * @returns True if the named flag is set, false if not */ virtual bool isFlagSet_abi(OMNI_ATTR("c_str, not_null")const char* flagName) noexcept = 0; }; } // namespace inspect } // namespace omni #include "IInspector.gen.h"
2,794
C
44.819671
109
0.734431
omniverse-code/kit/include/omni/inspect/IInspector.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/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 //! Base class for object inspection requests. template <> class omni::core::Generated<omni::inspect::IInspector_abi> : public omni::inspect::IInspector_abi { public: OMNI_PLUGIN_INTERFACE("omni::inspect::IInspector") /** Set the help information for the current invocation of the inspector. For when behavior == eHelp * @param[in] helpString The help information, describing the configuration of the inspector */ void setHelp(const char* helpString) noexcept; /** Returns the help information currently available on the inspector. Note that this could change * from one invocation to the next so it's important to read it immediately after requesting it. * @returns String containing the help information describing the current configuration of the inspector */ const char* helpInformation() noexcept; /** Returns the common flag used to tell the inspection process to put the help information into the * inspector using the setHelp_abi function. Using this approach avoids having every inspector/object * combination add an extra ABI function just for retrieving the help information, as well as providing a * consistent method for requesting it. * @returns String containing the name of the common flag used for help information */ const char* helpFlag() noexcept; /** Enable or disable an inspection flag. It's up to the individual inspection operations or the derived * inspector interfaces to interpret the flag. * @param[in] flagName Name of the flag to set * @param[in] flagState New state for the flag */ void setFlag(const char* flagName, bool flagState) noexcept; /** Checks whether a particular flag is currently set or not. * @param[in] flagName Name of the flag to check * @returns True if the named flag is set, false if not */ bool isFlagSet(const char* flagName) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::inspect::IInspector_abi>::setHelp(const char* helpString) noexcept { setHelp_abi(helpString); } inline const char* omni::core::Generated<omni::inspect::IInspector_abi>::helpInformation() noexcept { return helpInformation_abi(); } inline const char* omni::core::Generated<omni::inspect::IInspector_abi>::helpFlag() noexcept { return helpFlag_abi(); } inline void omni::core::Generated<omni::inspect::IInspector_abi>::setFlag(const char* flagName, bool flagState) noexcept { setFlag_abi(flagName, flagState); } inline bool omni::core::Generated<omni::inspect::IInspector_abi>::isFlagSet(const char* flagName) noexcept { return isFlagSet_abi(flagName); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
3,578
C
34.79
120
0.734768
omniverse-code/kit/include/omni/inspect/PyIInspector.gen.h
// Copyright (c) 2021-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. ---------- // #pragma once #include <omni/core/ITypeFactory.h> #include <omni/python/PyBind.h> #include <omni/python/PyString.h> #include <omni/python/PyVec.h> #include <sstream> auto bindIInspector(py::module& m) { // hack around pybind11 issues with C++17 // - https://github.com/pybind/pybind11/issues/2234 // - https://github.com/pybind/pybind11/issues/2666 // - https://github.com/pybind/pybind11/issues/2856 py::class_<omni::core::Generated<omni::inspect::IInspector_abi>, omni::python::detail::PyObjectPtr<omni::core::Generated<omni::inspect::IInspector_abi>>, omni::core::IObject> clsParent(m, "_IInspector"); py::class_<omni::inspect::IInspector, omni::core::Generated<omni::inspect::IInspector_abi>, omni::python::detail::PyObjectPtr<omni::inspect::IInspector>, omni::core::IObject> cls(m, "IInspector", R"OMNI_BIND_RAW_(Base class for object inspection requests.)OMNI_BIND_RAW_"); cls.def(py::init( [](const omni::core::ObjectPtr<omni::core::IObject>& obj) { auto tmp = omni::core::cast<omni::inspect::IInspector>(obj.get()); if (!tmp) { throw std::runtime_error("invalid type conversion"); } return tmp; })); cls.def(py::init( []() { auto tmp = omni::core::createType<omni::inspect::IInspector>(); if (!tmp) { throw std::runtime_error("unable to create omni::inspect::IInspector instantiation"); } return tmp; })); cls.def_property( "help", nullptr, [](omni::inspect::IInspector* self, const char* helpString) { self->setHelp(helpString); }); cls.def("help_information", &omni::inspect::IInspector::helpInformation, R"OMNI_BIND_RAW_(Returns the help information currently available on the inspector. Note that this could change from one invocation to the next so it's important to read it immediately after requesting it. @returns String containing the help information describing the current configuration of the inspector)OMNI_BIND_RAW_"); cls.def("help_flag", &omni::inspect::IInspector::helpFlag, R"OMNI_BIND_RAW_(Returns the common flag used to tell the inspection process to put the help information into the inspector using the setHelp_abi function. Using this approach avoids having every inspector/object combination add an extra ABI function just for retrieving the help information, as well as providing a consistent method for requesting it. @returns String containing the name of the common flag used for help information)OMNI_BIND_RAW_"); cls.def("set_flag", [](omni::inspect::IInspector* self, const char* flagName, bool flagState) { self->setFlag(flagName, flagState); }, R"OMNI_BIND_RAW_(Enable or disable an inspection flag. It's up to the individual inspection operations or the derived inspector interfaces to interpret the flag. @param[in] flagName Name of the flag to set @param[in] flagState New state for the flag)OMNI_BIND_RAW_", py::arg("flag_name"), py::arg("flag_state")); cls.def("is_flag_set", [](omni::inspect::IInspector* self, const char* flagName) { auto return_value = self->isFlagSet(flagName); return return_value; }, R"OMNI_BIND_RAW_(Checks whether a particular flag is currently set or not. @param[in] flagName Name of the flag to check @returns True if the named flag is set, false if not)OMNI_BIND_RAW_", py::arg("flag_name")); return omni::python::PyBind<omni::inspect::IInspector>::bind(cls); }
4,234
C
48.823529
129
0.664147
omniverse-code/kit/include/omni/inspect/IInspectMemoryUse.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 <omni/core/Omni.h> #include "IInspector.h" namespace omni { using namespace omni::core; } namespace omni { namespace inspect { OMNI_DECLARE_INTERFACE(IInspectMemoryUse); //! Base class for object inspection requests. class IInspectMemoryUse_abi : public omni::Inherits<omni::inspect::IInspector, OMNI_TYPE_ID("omni.inspect.IInspectMemoryUse")> { protected: /** Add a block of used memory * Returns false if the memory was not recorded (e.g. because it was already recorded) * * @param[in] ptr Pointer to the memory location being logged as in-use * @param[in] bytesUsed Number of bytes in use at that location */ virtual bool useMemory_abi(OMNI_ATTR("in, not_null") const void* ptr, size_t bytesUsed) noexcept = 0; /** Reset the memory usage data to a zero state */ virtual void reset_abi() noexcept = 0; /** @returns the total number of bytes of memory used since creation or the last call to reset(). */ virtual size_t totalUsed_abi() noexcept = 0; }; } // namespace inspect } // namespace oni #include "IInspectMemoryUse.gen.h"
1,558
C
33.644444
105
0.725931
omniverse-code/kit/include/omni/inspect/IInspectSerializer.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 <omni/core/Omni.h> #include "IInspector.h" namespace omni { using namespace omni::core; } namespace omni { namespace inspect { OMNI_DECLARE_INTERFACE(IInspectSerializer); //! Base class for object serialization requests. class IInspectSerializer_abi : public omni::Inherits<omni::inspect::IInspector, OMNI_TYPE_ID("omni.inspect.IInspectSerializer")> { protected: /** Write a fixed string to the serializer output location * * @param[in] toWrite String to be written to the serializer */ virtual void writeString_abi(OMNI_ATTR("c_str, not_null") const char* toWrite) noexcept = 0; /** Write a printf-style formatted string to the serializer output location * * @param[in] fmt Formatting string in the printf() style * @param[in] args Variable list of arguments to the formatting string */ virtual OMNI_ATTR("no_py") void write_abi(OMNI_ATTR("c_str, not_null") const char* fmt, va_list args) noexcept = 0; /** Set the output location of the serializer data to be a specified file path. * Doesn't actually do anything with it until data is being written though. * Recognizes the special file paths "cout", "stdout", "cerr", and "stderr" as the standard output streams. * * @param[in] filePath New location of the output file */ virtual void setOutputToFilePath_abi(OMNI_ATTR("c_str, not_null") const char* filePath) noexcept = 0; /** Set the output location of the serializer data to be a local string. * No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. */ virtual void setOutputToString_abi() noexcept = 0; /** Get the current location of the output data. * * @returns Current file path where the output is going. nullptr means the output is going to a string. */ virtual const char* getOutputLocation_abi() noexcept = 0; /** Get the current output as a string. * * @returns The output that has been sent to the serializer. If the output is being sent to a file path then read * the file at that path and return the contents of the file. If the output is being sent to stdout or stderr * then nothing is returned as that output is unavailable after flushing. */ virtual const char* asString_abi() noexcept = 0; /** Clear the contents of the serializer output, either emptying the file or clearing the string, depending on * where the current output is directed. */ virtual void clear_abi() noexcept = 0; }; } // namespace inspect } // namespace omni #include "IInspectSerializer.gen.h"
3,087
C
40.729729
119
0.712666
omniverse-code/kit/include/omni/inspect/IInspectJsonSerializer.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 <omni/core/Omni.h> #include "IInspector.h" namespace omni { using namespace omni::core; } namespace omni { namespace inspect { OMNI_DECLARE_INTERFACE(IInspectJsonSerializer); //! Base class for object inspection requests. class IInspectJsonSerializer_abi : public omni::Inherits<omni::inspect::IInspector, OMNI_TYPE_ID("omni.inspect.IInspectJsonSerializer")> { protected: /** Set the output location of the serializer data to be a specified file path. * Doesn't actually do anything with it until data is being written though. * * @param[in] filePath Absolute location of the file to be written. */ virtual void setOutputToFilePath_abi(OMNI_ATTR("c_str, not_null") const char* filePath) noexcept = 0; /** Set the output location of the serializer data to be a local string. * No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. */ virtual void setOutputToString_abi() noexcept = 0; /** Get the current location of the output data. * * @returns Path to the output file, or nullptr if output is going to a string */ virtual const char* getOutputLocation_abi() noexcept = 0; /** Get the current output as a string. If the output is being sent to a file path then read the file at that path * and return the contents of the file (with the usual caveats about file size). * * @returns String representation of the output so far */ virtual const char* asString_abi() noexcept = 0; /** Clear the contents of the serializer output, either emptying the file or clearing the string, depending on * where the current output is directed. */ virtual void clear_abi() noexcept = 0; /** Write out a JSON key for an object property. * * @param[in] key The string value for the key. This can be nullptr. * @param[in] keyLen The length of @ref key, excluding the null terminator. * @returns whether or not validation succeeded. */ virtual bool writeKeyWithLength_abi(OMNI_ATTR("c_str")const char* key, size_t keyLen) noexcept = 0; /** Write out a JSON key for an object property. * * @param[in] key The key name for this property. This may be nullptr. * @returns whether or not validation succeeded. */ virtual bool writeKey_abi(OMNI_ATTR("c_str")const char* key) noexcept = 0; /** Write out a JSON null value. * * @returns whether or not validation succeeded. */ virtual bool writeNull_abi() noexcept = 0; /** Write out a JSON boolean value. * * @param[in] value The boolean value. * @returns whether or not validation succeeded. */ virtual bool writeBool_abi(bool value) noexcept = 0; /** Write out a JSON integer value. * * @param[in] value The integer value. * @returns whether or not validation succeeded. */ virtual bool writeInt_abi(int32_t value) noexcept = 0; /** Write out a JSON unsigned integer value. * * @param[in] value The unsigned integer value. * @returns whether or not validation succeeded. */ virtual bool writeUInt_abi(uint32_t value) noexcept = 0; /** Write out a JSON 64-bit integer value. * * @param[in] value The 64-bit integer value. * @returns whether or not validation succeeded. * @note 64 bit integers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ virtual bool writeInt64_abi(int64_t value) noexcept = 0; /** Write out a JSON 64-bit unsigned integer value. * * @param[in] value The 64-bit unsigned integer value. * @returns whether or not validation succeeded. * @note 64 bit integers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ virtual bool writeUInt64_abi(uint64_t value) noexcept = 0; /** Write out a JSON pointer value as an unsigned int 64. * Not available through the Python bindings as Python has no concept of pointers. Use either writeUInt64() * or writeBase64Encoded() to write out binary data. * * @param[in] value The pointer value. * @returns whether or not validation succeeded. * @note Pointers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ virtual OMNI_ATTR("no_py") bool writePointer_abi(OMNI_ATTR("in")const void* value) noexcept = 0; /** Write out a JSON double (aka number) value. * * @param[in] value The double value. * @returns whether or not validation succeeded. */ virtual bool writeDouble_abi(double value) noexcept = 0; /** Write out a JSON float (aka number) value. * * @param[in] value The double value. * @returns whether or not validation succeeded. */ virtual bool writeFloat_abi(float value) noexcept = 0; /** Write out a JSON string value. * * @param[in] value The string value. This can be nullptr if @p len is 0. * @param[in] len The length of @p value, excluding the null terminator. * @returns whether or not validation succeeded. */ virtual bool writeStringWithLength_abi(OMNI_ATTR("c_str")const char* value, size_t len) noexcept = 0; /** Write out a JSON string value. * * @param[in] value The string value. This can be nullptr. * @returns whether or not validation succeeded. */ virtual bool writeString_abi(OMNI_ATTR("c_str")const char* value) noexcept = 0; /** Write a binary blob into the output JSON as a base64 encoded string. * * @param[in] value The binary blob to write in. * @param[in] size The number of bytes of data in @p value. * @returns whether or not validation succeeded. * @remarks This will take the input bytes and encode it in base64, then store that as base64 data in a string. */ virtual OMNI_ATTR("no_py") bool writeBase64Encoded_abi(OMNI_ATTR("in")const void* value, size_t size) noexcept = 0; /** Begin a JSON array. * * @returns whether or not validation succeeded. * @note This may throw a std::bad_alloc or a std::length_error if the stack of scopes gets too large */ virtual bool openArray_abi() noexcept = 0; /** Finish writing a JSON array. * * @returns whether or not validation succeeded. */ virtual bool closeArray_abi() noexcept = 0; /** Begin a JSON object. * * @returns whether or not validation succeeded. */ virtual bool openObject_abi() noexcept = 0; /** Finish writing a JSON object. * * @returns whether or not validation succeeded. */ virtual bool closeObject_abi() noexcept = 0; /** Finishes writing the entire JSON dictionary. * * @returns whether or not validation succeeded. */ virtual bool finish_abi() noexcept = 0; }; } // namespace inspect } // namespace omni #include "IInspectJsonSerializer.gen.h"
7,696
C
37.10396
119
0.674636
omniverse-code/kit/include/omni/inspect/IInspectJsonSerializer.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/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 //! Base class for object inspection requests. template <> class omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi> : public omni::inspect::IInspectJsonSerializer_abi { public: OMNI_PLUGIN_INTERFACE("omni::inspect::IInspectJsonSerializer") /** Set the output location of the serializer data to be a specified file path. * Doesn't actually do anything with it until data is being written though. * * @param[in] filePath Absolute location of the file to be written. */ void setOutputToFilePath(const char* filePath) noexcept; /** Set the output location of the serializer data to be a local string. * No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. */ void setOutputToString() noexcept; /** Get the current location of the output data. * * @returns Path to the output file, or nullptr if output is going to a string */ const char* getOutputLocation() noexcept; /** Get the current output as a string. If the output is being sent to a file path then read the file at that path * and return the contents of the file (with the usual caveats about file size). * * @returns String representation of the output so far */ const char* asString() noexcept; /** Clear the contents of the serializer output, either emptying the file or clearing the string, depending on * where the current output is directed. */ void clear() noexcept; /** Write out a JSON key for an object property. * * @param[in] key The string value for the key. This can be nullptr. * @param[in] keyLen The length of @ref key, excluding the null terminator. * @returns whether or not validation succeeded. */ bool writeKeyWithLength(const char* key, size_t keyLen) noexcept; /** Write out a JSON key for an object property. * * @param[in] key The key name for this property. This may be nullptr. * @returns whether or not validation succeeded. */ bool writeKey(const char* key) noexcept; /** Write out a JSON null value. * * @returns whether or not validation succeeded. */ bool writeNull() noexcept; /** Write out a JSON boolean value. * * @param[in] value The boolean value. * @returns whether or not validation succeeded. */ bool writeBool(bool value) noexcept; /** Write out a JSON integer value. * * @param[in] value The integer value. * @returns whether or not validation succeeded. */ bool writeInt(int32_t value) noexcept; /** Write out a JSON unsigned integer value. * * @param[in] value The unsigned integer value. * @returns whether or not validation succeeded. */ bool writeUInt(uint32_t value) noexcept; /** Write out a JSON 64-bit integer value. * * @param[in] value The 64-bit integer value. * @returns whether or not validation succeeded. * @note 64 bit integers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ bool writeInt64(int64_t value) noexcept; /** Write out a JSON 64-bit unsigned integer value. * * @param[in] value The 64-bit unsigned integer value. * @returns whether or not validation succeeded. * @note 64 bit integers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ bool writeUInt64(uint64_t value) noexcept; /** Write out a JSON pointer value as an unsigned int 64. * Not available through the Python bindings as Python has no concept of pointers. Use either writeUInt64() * or writeBase64Encoded() to write out binary data. * * @param[in] value The pointer value. * @returns whether or not validation succeeded. * @note Pointers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ bool writePointer(const void* value) noexcept; /** Write out a JSON double (aka number) value. * * @param[in] value The double value. * @returns whether or not validation succeeded. */ bool writeDouble(double value) noexcept; /** Write out a JSON float (aka number) value. * * @param[in] value The double value. * @returns whether or not validation succeeded. */ bool writeFloat(float value) noexcept; /** Write out a JSON string value. * * @param[in] value The string value. This can be nullptr if @p len is 0. * @param[in] len The length of @p value, excluding the null terminator. * @returns whether or not validation succeeded. */ bool writeStringWithLength(const char* value, size_t len) noexcept; /** Write out a JSON string value. * * @param[in] value The string value. This can be nullptr. * @returns whether or not validation succeeded. */ bool writeString(const char* value) noexcept; /** Write a binary blob into the output JSON as a base64 encoded string. * * @param[in] value The binary blob to write in. * @param[in] size The number of bytes of data in @p value. * @returns whether or not validation succeeded. * @remarks This will take the input bytes and encode it in base64, then store that as base64 data in a string. */ bool writeBase64Encoded(const void* value, size_t size) noexcept; /** Begin a JSON array. * * @returns whether or not validation succeeded. * @note This may throw a std::bad_alloc or a std::length_error if the stack of scopes gets too large */ bool openArray() noexcept; /** Finish writing a JSON array. * * @returns whether or not validation succeeded. */ bool closeArray() noexcept; /** Begin a JSON object. * * @returns whether or not validation succeeded. */ bool openObject() noexcept; /** Finish writing a JSON object. * * @returns whether or not validation succeeded. */ bool closeObject() noexcept; /** Finishes writing the entire JSON dictionary. * * @returns whether or not validation succeeded. */ bool finish() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::setOutputToFilePath(const char* filePath) noexcept { setOutputToFilePath_abi(filePath); } inline void omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::setOutputToString() noexcept { setOutputToString_abi(); } inline const char* omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::getOutputLocation() noexcept { return getOutputLocation_abi(); } inline const char* omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::asString() noexcept { return asString_abi(); } inline void omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::clear() noexcept { clear_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeKeyWithLength(const char* key, size_t keyLen) noexcept { return writeKeyWithLength_abi(key, keyLen); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeKey(const char* key) noexcept { return writeKey_abi(key); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeNull() noexcept { return writeNull_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeBool(bool value) noexcept { return writeBool_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeInt(int32_t value) noexcept { return writeInt_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeUInt(uint32_t value) noexcept { return writeUInt_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeInt64(int64_t value) noexcept { return writeInt64_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeUInt64(uint64_t value) noexcept { return writeUInt64_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writePointer(const void* value) noexcept { return writePointer_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeDouble(double value) noexcept { return writeDouble_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeFloat(float value) noexcept { return writeFloat_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeStringWithLength(const char* value, size_t len) noexcept { return writeStringWithLength_abi(value, len); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeString(const char* value) noexcept { return writeString_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeBase64Encoded(const void* value, size_t size) noexcept { return writeBase64Encoded_abi(value, size); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::openArray() noexcept { return openArray_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::closeArray() noexcept { return closeArray_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::openObject() noexcept { return openObject_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::closeObject() noexcept { return closeObject_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::finish() noexcept { return finish_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
11,325
C
32.410029
128
0.683974
omniverse-code/kit/include/omni/inspect/MemorySizes.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 // Collection of helpers to get memory size information #include <array> #include <iostream> #include <map> #include <set> #include <string> #include <unordered_map> #include <unordered_set> #include <type_traits> namespace omni { namespace inspect { // Uncomment this to enable debug output in this file // #define MEMORY_DEBUG constexpr bool memoryDebug{ #ifdef MEMORY_DEBUG true #else false #endif }; template <typename> struct sfinae_true : std::true_type {}; template <typename> struct sfinae_false : std::false_type {}; using SizeFunction = std::add_pointer<size_t()>::type; // // This detail implementation will allow switching on map types so that their size can be recursively calculated // namespace detail { // Until C++17... template <typename... Ts> using void_t = void; // Check for map-like objects template<typename Object, typename U = void> struct isMappishImpl : std::false_type {}; template<typename Object> struct isMappishImpl<Object, void_t<typename Object::key_type, typename Object::mapped_type, decltype(std::declval<Object&>()[std::declval<const typename Object::key_type&>()])>> : std::true_type {}; // Check for array types, whose size is entirely described by the object size template<typename Contained> struct isArrayImpl : std::false_type {}; template<typename Contained, size_t Size> struct isArrayImpl<std::array<Contained, Size>> : std::true_type {}; // Check for other iterable types template<typename Contained> struct isIterableImpl : std::false_type {}; template<typename Contained, typename Allocator> struct isIterableImpl<std::vector<Contained, Allocator>> : std::true_type {}; template<typename Contained, typename Allocator> struct isIterableImpl<std::set<Contained, Allocator>> : std::true_type {}; template<typename Contained, typename Allocator> struct isIterableImpl<std::unordered_set<Contained, Allocator>> : std::true_type {}; template <typename Object, typename Enable = void> struct hasCalculateMemorySizeFunctionImpl : std::false_type {}; template <typename Object> struct hasCalculateMemorySizeFunctionImpl<Object, void_t<decltype(std::declval<const Object&>().calculateMemorySize())>> : std::true_type {}; } template <typename Object> struct isMappish : detail::isMappishImpl<Object>::type {}; template <typename Object> struct isArray : detail::isArrayImpl<Object>::type {}; template <typename Object> struct isIterable : detail::isIterableImpl<Object>::type {}; template <typename Object> struct hasCalculateMemorySizeFunction : detail::hasCalculateMemorySizeFunctionImpl<Object>::type {}; // // Fallback to sizeof() template <typename Object, std::enable_if_t<! hasCalculateMemorySizeFunction<Object>{} && ! isMappish<Object>{} && ! isIterable<Object>{} && ! isArray<Object>{}, bool> = 0> size_t calculateMemorySize(const Object& object) { memoryDebug && (std::cout << "POD " << typeid(object).name() << " = " << sizeof(Object) << std::endl); return sizeof(Object); } // If the object has a calculateMemorySize() function use it // template <typename Object, typename std::enable_if_t<hasCalculateMemorySizeFunction<Object>{}, bool> = 0> size_t calculateMemorySize(const Object& object) { memoryDebug && (std::cout << "Has Method " << typeid(object).name() << " = " << object.calculateMemorySize() << std::endl); return object.calculateMemorySize(); } // // Third check, has to be at the end so that recursive calls work, handle map-like objects (map, unordered_map) template <typename Object, std::enable_if_t<isMappish<Object>{}, bool> = 0> size_t calculateMemorySize(const Object& object) { size_t size = sizeof(Object); for(auto it = object.begin(); it != object.end(); ++it) { size += calculateMemorySize(it->first); size += calculateMemorySize(it->second); } memoryDebug && (std::cout << "Mappish " << typeid(object).name() << " = " << size << std::endl); return size; } // // Fourth check, handle the array type, which doesn't have a separately allocated set of members template <typename Object, std::enable_if_t<isArray<Object>{}, bool> = 0> size_t calculateMemorySize(const Object& object) { memoryDebug && (std::cout << "Array " << typeid(object).name() << " = " << sizeof(Object) << std::endl); return sizeof(Object); } // // Fifth check, has to be at the end so that recursive calls work, handle the rest of the single object container-like objects // (set, unordered_set, vector) template <typename Object, std::enable_if_t<isIterable<Object>{} && ! isArray<Object>{}, bool> = 0> size_t calculateMemorySize(const Object& object) { size_t size = sizeof(Object); for(const auto& member : object) { size += calculateMemorySize(member); } memoryDebug && (std::cout << "Iterable " << typeid(object).name() << " = " << size << std::endl); return size; } // Helper macro to make it easy to add the memory used by class members to the IInspector #define INSPECT_MEMORY_CLASS_MEMBER(INSPECTOR, OBJECT, MEMBER_NAME) \ INSPECTOR.useMemory(&(OBJECT.MEMBER_NAME), omni::inspect::calculateMemorySize(OBJECT.MEMBER_NAME)); } // namespace inspect } // namespace omni
5,763
C
39.879432
172
0.699809
omniverse-code/kit/include/omni/inspect/PyIInspectMemoryUse.gen.h
// Copyright (c) 2021-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. ---------- // #pragma once #include <omni/core/ITypeFactory.h> #include <omni/python/PyBind.h> #include <omni/python/PyString.h> #include <omni/python/PyVec.h> #include <sstream> auto bindIInspectMemoryUse(py::module& m) { // hack around pybind11 issues with C++17 // - https://github.com/pybind/pybind11/issues/2234 // - https://github.com/pybind/pybind11/issues/2666 // - https://github.com/pybind/pybind11/issues/2856 py::class_<omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>, omni::python::detail::PyObjectPtr<omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>>, omni::core::Api<omni::inspect::IInspector_abi>> clsParent(m, "_IInspectMemoryUse"); py::class_<omni::inspect::IInspectMemoryUse, omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>, omni::python::detail::PyObjectPtr<omni::inspect::IInspectMemoryUse>, omni::core::Api<omni::inspect::IInspector_abi>> cls(m, "IInspectMemoryUse", R"OMNI_BIND_RAW_(Base class for object inspection requests.)OMNI_BIND_RAW_"); cls.def(py::init( [](const omni::core::ObjectPtr<omni::core::IObject>& obj) { auto tmp = omni::core::cast<omni::inspect::IInspectMemoryUse>(obj.get()); if (!tmp) { throw std::runtime_error("invalid type conversion"); } return tmp; })); cls.def(py::init( []() { auto tmp = omni::core::createType<omni::inspect::IInspectMemoryUse>(); if (!tmp) { throw std::runtime_error("unable to create omni::inspect::IInspectMemoryUse instantiation"); } return tmp; })); cls.def("use_memory", [](omni::inspect::IInspectMemoryUse* self, const void* ptr, size_t bytesUsed) { auto return_value = self->useMemory(ptr, bytesUsed); return return_value; }, R"OMNI_BIND_RAW_(Add a block of used memory Returns false if the memory was not recorded (e.g. because it was already recorded) @param[in] ptr Pointer to the memory location being logged as in-use @param[in] bytesUsed Number of bytes in use at that location)OMNI_BIND_RAW_", py::arg("ptr"), py::arg("bytes_used")); cls.def("reset", &omni::inspect::IInspectMemoryUse::reset, R"OMNI_BIND_RAW_(Reset the memory usage data to a zero state)OMNI_BIND_RAW_"); cls.def( "total_used", &omni::inspect::IInspectMemoryUse::totalUsed, R"OMNI_BIND_RAW_(@returns the total number of bytes of memory used since creation or the last call to reset().)OMNI_BIND_RAW_"); return omni::python::PyBind<omni::inspect::IInspectMemoryUse>::bind(cls); }
3,319
C
43.864864
136
0.639349
omniverse-code/kit/include/omni/inspect/IInspectMemoryUse.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/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 //! Base class for object inspection requests. template <> class omni::core::Generated<omni::inspect::IInspectMemoryUse_abi> : public omni::inspect::IInspectMemoryUse_abi { public: OMNI_PLUGIN_INTERFACE("omni::inspect::IInspectMemoryUse") /** Add a block of used memory * Returns false if the memory was not recorded (e.g. because it was already recorded) * * @param[in] ptr Pointer to the memory location being logged as in-use * @param[in] bytesUsed Number of bytes in use at that location */ bool useMemory(const void* ptr, size_t bytesUsed) noexcept; /** Reset the memory usage data to a zero state */ void reset() noexcept; /** @returns the total number of bytes of memory used since creation or the last call to reset(). */ size_t totalUsed() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>::useMemory(const void* ptr, size_t bytesUsed) noexcept { return useMemory_abi(ptr, bytesUsed); } inline void omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>::reset() noexcept { reset_abi(); } inline size_t omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>::totalUsed() noexcept { return totalUsed_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
2,260
C
29.146666
111
0.695133
omniverse-code/kit/include/omni/inspect/PyIInspectJsonSerializer.gen.h
// Copyright (c) 2021-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. ---------- // #pragma once #include <omni/core/ITypeFactory.h> #include <omni/python/PyBind.h> #include <omni/python/PyString.h> #include <omni/python/PyVec.h> #include <sstream> auto bindIInspectJsonSerializer(py::module& m) { // hack around pybind11 issues with C++17 // - https://github.com/pybind/pybind11/issues/2234 // - https://github.com/pybind/pybind11/issues/2666 // - https://github.com/pybind/pybind11/issues/2856 py::class_<omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>, omni::python::detail::PyObjectPtr<omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>>, omni::core::Api<omni::inspect::IInspector_abi>> clsParent(m, "_IInspectJsonSerializer"); py::class_<omni::inspect::IInspectJsonSerializer, omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>, omni::python::detail::PyObjectPtr<omni::inspect::IInspectJsonSerializer>, omni::core::Api<omni::inspect::IInspector_abi>> cls(m, "IInspectJsonSerializer", R"OMNI_BIND_RAW_(Base class for object inspection requests.)OMNI_BIND_RAW_"); cls.def(py::init( [](const omni::core::ObjectPtr<omni::core::IObject>& obj) { auto tmp = omni::core::cast<omni::inspect::IInspectJsonSerializer>(obj.get()); if (!tmp) { throw std::runtime_error("invalid type conversion"); } return tmp; })); cls.def(py::init( []() { auto tmp = omni::core::createType<omni::inspect::IInspectJsonSerializer>(); if (!tmp) { throw std::runtime_error("unable to create omni::inspect::IInspectJsonSerializer instantiation"); } return tmp; })); cls.def_property("output_to_file_path", nullptr, [](omni::inspect::IInspectJsonSerializer* self, const char* filePath) { self->setOutputToFilePath(filePath); }); cls.def_property_readonly("output_location", &omni::inspect::IInspectJsonSerializer::getOutputLocation); cls.def("set_output_to_string", &omni::inspect::IInspectJsonSerializer::setOutputToString, R"OMNI_BIND_RAW_(Set the output location of the serializer data to be a local string. No check is made to ensure that the string size doesn't get too large so when in doubt use a file path.)OMNI_BIND_RAW_"); cls.def("as_string", &omni::inspect::IInspectJsonSerializer::asString, R"OMNI_BIND_RAW_(Get the current output as a string. If the output is being sent to a file path then read the file at that path and return the contents of the file (with the usual caveats about file size). @returns String representation of the output so far)OMNI_BIND_RAW_"); cls.def("clear", &omni::inspect::IInspectJsonSerializer::clear, R"OMNI_BIND_RAW_(Clear the contents of the serializer output, either emptying the file or clearing the string, depending on where the current output is directed.)OMNI_BIND_RAW_"); cls.def("write_key_with_length", [](omni::inspect::IInspectJsonSerializer* self, const char* key, size_t keyLen) { auto return_value = self->writeKeyWithLength(key, keyLen); return return_value; }, R"OMNI_BIND_RAW_(Write out a JSON key for an object property. @param[in] key The string value for the key. This can be nullptr. @param[in] keyLen The length of @ref key, excluding the null terminator. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("key"), py::arg("key_len")); cls.def("write_key", [](omni::inspect::IInspectJsonSerializer* self, const char* key) { auto return_value = self->writeKey(key); return return_value; }, R"OMNI_BIND_RAW_(Write out a JSON key for an object property. @param[in] key The key name for this property. This may be nullptr. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("key")); cls.def("write_null", &omni::inspect::IInspectJsonSerializer::writeNull, R"OMNI_BIND_RAW_(Write out a JSON null value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_"); cls.def("write_bool", &omni::inspect::IInspectJsonSerializer::writeBool, R"OMNI_BIND_RAW_(Write out a JSON boolean value. @param[in] value The boolean value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_int", &omni::inspect::IInspectJsonSerializer::writeInt, R"OMNI_BIND_RAW_(Write out a JSON integer value. @param[in] value The integer value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_u_int", &omni::inspect::IInspectJsonSerializer::writeUInt, R"OMNI_BIND_RAW_(Write out a JSON unsigned integer value. @param[in] value The unsigned integer value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_int64", &omni::inspect::IInspectJsonSerializer::writeInt64, R"OMNI_BIND_RAW_(Write out a JSON 64-bit integer value. @param[in] value The 64-bit integer value. @returns whether or not validation succeeded. @note 64 bit integers will be written as a string of they are too long to be stored as a number that's interoperable with javascript's double precision floating point format.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_u_int64", &omni::inspect::IInspectJsonSerializer::writeUInt64, R"OMNI_BIND_RAW_(Write out a JSON 64-bit unsigned integer value. @param[in] value The 64-bit unsigned integer value. @returns whether or not validation succeeded. @note 64 bit integers will be written as a string of they are too long to be stored as a number that's interoperable with javascript's double precision floating point format.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_double", &omni::inspect::IInspectJsonSerializer::writeDouble, R"OMNI_BIND_RAW_(Write out a JSON double (aka number) value. @param[in] value The double value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_float", &omni::inspect::IInspectJsonSerializer::writeFloat, R"OMNI_BIND_RAW_(Write out a JSON float (aka number) value. @param[in] value The double value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_string_with_length", [](omni::inspect::IInspectJsonSerializer* self, const char* value, size_t len) { auto return_value = self->writeStringWithLength(value, len); return return_value; }, R"OMNI_BIND_RAW_(Write out a JSON string value. @param[in] value The string value. This can be nullptr if @p len is 0. @param[in] len The length of @p value, excluding the null terminator. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value"), py::arg("len")); cls.def("write_string", [](omni::inspect::IInspectJsonSerializer* self, const char* value) { auto return_value = self->writeString(value); return return_value; }, R"OMNI_BIND_RAW_(Write out a JSON string value. @param[in] value The string value. This can be nullptr. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("open_array", &omni::inspect::IInspectJsonSerializer::openArray, R"OMNI_BIND_RAW_(Begin a JSON array. @returns whether or not validation succeeded. @note This may throw a std::bad_alloc or a std::length_error if the stack of scopes gets too large)OMNI_BIND_RAW_"); cls.def("close_array", &omni::inspect::IInspectJsonSerializer::closeArray, R"OMNI_BIND_RAW_(Finish writing a JSON array. @returns whether or not validation succeeded.)OMNI_BIND_RAW_"); cls.def("open_object", &omni::inspect::IInspectJsonSerializer::openObject, R"OMNI_BIND_RAW_(Begin a JSON object. @returns whether or not validation succeeded.)OMNI_BIND_RAW_"); cls.def("close_object", &omni::inspect::IInspectJsonSerializer::closeObject, R"OMNI_BIND_RAW_(Finish writing a JSON object. @returns whether or not validation succeeded.)OMNI_BIND_RAW_"); cls.def("finish", &omni::inspect::IInspectJsonSerializer::finish, R"OMNI_BIND_RAW_(Finishes writing the entire JSON dictionary. @returns whether or not validation succeeded.)OMNI_BIND_RAW_"); return omni::python::PyBind<omni::inspect::IInspectJsonSerializer>::bind(cls); }
9,338
C
48.412698
139
0.669629
omniverse-code/kit/include/omni/inspect/IInspectSerializer.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/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 //! Base class for object serialization requests. template <> class omni::core::Generated<omni::inspect::IInspectSerializer_abi> : public omni::inspect::IInspectSerializer_abi { public: OMNI_PLUGIN_INTERFACE("omni::inspect::IInspectSerializer") /** Write a fixed string to the serializer output location * * @param[in] toWrite String to be written to the serializer */ void writeString(const char* toWrite) noexcept; /** Write a printf-style formatted string to the serializer output location * * @param[in] fmt Formatting string in the printf() style * @param[in] args Variable list of arguments to the formatting string */ void write(const char* fmt, ...) noexcept; /** Set the output location of the serializer data to be a specified file path. * Doesn't actually do anything with it until data is being written though. * Recognizes the special file paths "cout", "stdout", "cerr", and "stderr" as the standard output streams. * * @param[in] filePath New location of the output file */ void setOutputToFilePath(const char* filePath) noexcept; /** Set the output location of the serializer data to be a local string. * No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. */ void setOutputToString() noexcept; /** Get the current location of the output data. * * @returns Current file path where the output is going. nullptr means the output is going to a string. */ const char* getOutputLocation() noexcept; /** Get the current output as a string. * * @returns The output that has been sent to the serializer. If the output is being sent to a file path then read * the file at that path and return the contents of the file. If the output is being sent to stdout or stderr * then nothing is returned as that output is unavailable after flushing. */ const char* asString() noexcept; /** Clear the contents of the serializer output, either emptying the file or clearing the string, depending on * where the current output is directed. */ void clear() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::inspect::IInspectSerializer_abi>::writeString(const char* toWrite) noexcept { writeString_abi(toWrite); } inline void omni::core::Generated<omni::inspect::IInspectSerializer_abi>::write(const char* fmt, ...) noexcept { va_list arg_list_; va_start(arg_list_, fmt); write_abi(fmt, arg_list_); va_end(arg_list_); } inline void omni::core::Generated<omni::inspect::IInspectSerializer_abi>::setOutputToFilePath(const char* filePath) noexcept { setOutputToFilePath_abi(filePath); } inline void omni::core::Generated<omni::inspect::IInspectSerializer_abi>::setOutputToString() noexcept { setOutputToString_abi(); } inline const char* omni::core::Generated<omni::inspect::IInspectSerializer_abi>::getOutputLocation() noexcept { return getOutputLocation_abi(); } inline const char* omni::core::Generated<omni::inspect::IInspectSerializer_abi>::asString() noexcept { return asString_abi(); } inline void omni::core::Generated<omni::inspect::IInspectSerializer_abi>::clear() noexcept { clear_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
4,213
C
32.444444
124
0.715879
omniverse-code/kit/include/omni/inspect/PyIInspectSerializer.gen.h
// Copyright (c) 2021-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. ---------- // #pragma once #include <omni/core/ITypeFactory.h> #include <omni/python/PyBind.h> #include <omni/python/PyString.h> #include <omni/python/PyVec.h> #include <sstream> auto bindIInspectSerializer(py::module& m) { // hack around pybind11 issues with C++17 // - https://github.com/pybind/pybind11/issues/2234 // - https://github.com/pybind/pybind11/issues/2666 // - https://github.com/pybind/pybind11/issues/2856 py::class_<omni::core::Generated<omni::inspect::IInspectSerializer_abi>, omni::python::detail::PyObjectPtr<omni::core::Generated<omni::inspect::IInspectSerializer_abi>>, omni::core::Api<omni::inspect::IInspector_abi>> clsParent(m, "_IInspectSerializer"); py::class_<omni::inspect::IInspectSerializer, omni::core::Generated<omni::inspect::IInspectSerializer_abi>, omni::python::detail::PyObjectPtr<omni::inspect::IInspectSerializer>, omni::core::Api<omni::inspect::IInspector_abi>> cls(m, "IInspectSerializer", R"OMNI_BIND_RAW_(Base class for object serialization requests.)OMNI_BIND_RAW_"); cls.def(py::init( [](const omni::core::ObjectPtr<omni::core::IObject>& obj) { auto tmp = omni::core::cast<omni::inspect::IInspectSerializer>(obj.get()); if (!tmp) { throw std::runtime_error("invalid type conversion"); } return tmp; })); cls.def(py::init( []() { auto tmp = omni::core::createType<omni::inspect::IInspectSerializer>(); if (!tmp) { throw std::runtime_error("unable to create omni::inspect::IInspectSerializer instantiation"); } return tmp; })); cls.def_property("output_to_file_path", nullptr, [](omni::inspect::IInspectSerializer* self, const char* filePath) { self->setOutputToFilePath(filePath); }); cls.def_property_readonly("output_location", &omni::inspect::IInspectSerializer::getOutputLocation); cls.def("write_string", [](omni::inspect::IInspectSerializer* self, const char* toWrite) { self->writeString(toWrite); }, R"OMNI_BIND_RAW_(Write a fixed string to the serializer output location @param[in] toWrite String to be written to the serializer)OMNI_BIND_RAW_", py::arg("to_write")); cls.def("set_output_to_string", &omni::inspect::IInspectSerializer::setOutputToString, R"OMNI_BIND_RAW_(Set the output location of the serializer data to be a local string. No check is made to ensure that the string size doesn't get too large so when in doubt use a file path.)OMNI_BIND_RAW_"); cls.def("as_string", &omni::inspect::IInspectSerializer::asString, R"OMNI_BIND_RAW_(Get the current output as a string. @returns The output that has been sent to the serializer. If the output is being sent to a file path then read the file at that path and return the contents of the file. If the output is being sent to stdout or stderr then nothing is returned as that output is unavailable after flushing.)OMNI_BIND_RAW_"); cls.def("clear", &omni::inspect::IInspectSerializer::clear, R"OMNI_BIND_RAW_(Clear the contents of the serializer output, either emptying the file or clearing the string, depending on where the current output is directed.)OMNI_BIND_RAW_"); return omni::python::PyBind<omni::inspect::IInspectSerializer>::bind(cls); }
4,010
C
51.090908
135
0.669327
omniverse-code/kit/include/omni/ext/IExt.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 omni.ext interface definition file #pragma once #include "../../carb/Interface.h" namespace omni { //! Namespace for Omniverse Extension system namespace ext { /** * Extension plugin interface. * * Interface for writing simple C++ plugins used by extension system. * When extension loads a plugin with this interface it gets automatically acquired and \ref IExt::onStartup() is * called. \ref IExt::onShutdown() is called when extension gets shutdown. * * @see ExtensionManager */ class IExt { public: CARB_PLUGIN_INTERFACE("omni::ext::IExt", 0, 1); /** * Called by the Extension Manager when the extension is being started. * * @param extId Unique extension id is passed in. It can be used to query more extension info from extension * manager. */ virtual void onStartup(const char* extId) = 0; /** * Called by the Extension Manager when the extension is shutdown. */ virtual void onShutdown() = 0; }; } // namespace ext } // namespace omni
1,473
C
26.81132
113
0.716225
omniverse-code/kit/include/omni/ext/IExtensionHooks.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. // #pragma once #include <omni/core/IObject.h> #include <omni/ext/IExtensionData.h> namespace omni { namespace ext { //! Declaration of IExtensionHooks OMNI_DECLARE_INTERFACE(IExtensionHooks); //! Hooks that can be defined by plugins to better understand how the plugin is being used by the extension system. class IExtensionHooks_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.ext.IExtensionHooks")> { protected: //! Called when an extension loads the plugin. //! //! If multiple extensions load the plugin, this method will be called multiple times. //! @param ext The \ref IExtensionData_abi of the starting extension virtual void onStartup_abi(OMNI_ATTR("not_null") IExtensionData* ext) noexcept = 0; //! Called when an extension that uses this plugin is unloaded. //! //! If multiple extension load the plugin, this method will be called multiple times. //! @param ext The \ref IExtensionData_abi of the extension that is shutting down virtual void onShutdown_abi(IExtensionData* ext) noexcept = 0; }; } // namespace ext } // namespace omni #include "IExtensionHooks.gen.h"
1,589
C
35.976743
118
0.750157
omniverse-code/kit/include/omni/ext/ExtensionsUtils.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 omni.ext #pragma once #include "IExtensions.h" #include "../../carb/ObjectUtils.h" #include "../../carb/dictionary/DictionaryUtils.h" #include "../../carb/settings/ISettings.h" #include "../../carb/settings/SettingsUtils.h" #include <functional> #include <string> #include <utility> #include <vector> namespace omni { namespace ext { /** * Helper function to look up the path from an extension dictionary. * @warning Undefined behavior results if `extId` is not a valid Extension ID. Check for the existence of the extension * before calling this function. * @param manager A pointer to the \ref ExtensionManager * @param extId The Extension ID as required by \ref ExtensionManager::getExtensionDict() * @returns a `std::string` representing the `path` member of the extension info dictionary * @see ExtensionManager, ExtensionManager::getExtensionDict() */ inline std::string getExtensionPath(ExtensionManager* manager, const char* extId) { auto dict = carb::dictionary::getCachedDictionaryInterface(); carb::dictionary::Item* infoDict = manager->getExtensionDict(extId); return infoDict ? dict->get<const char*>(infoDict, "path") : ""; } /** * Helper function to find the Extension ID of a given Extension. * @param manager A pointer to the \ref ExtensionManager * @param extFullName The full extension name as required by \ref ExtensionManager::fetchExtensionVersions() * @returns The Extension ID of the enabled extension, or "" if the extension was not found or not enabled */ inline const char* getEnabledExtensionId(ExtensionManager* manager, const char* extFullName) { size_t count; ExtensionInfo* extensions; manager->fetchExtensionVersions(extFullName, &extensions, &count); for (size_t i = 0; i < count; i++) { if (extensions[i].enabled) return extensions[i].id; } return nullptr; } /** * Helper function to check if an extension is enabled by name. * @param manager A pointer to the \ref ExtensionManager * @param extFullName The full extension name as required by \ref ExtensionManager::fetchExtensionVersions() * @returns `true` if the extension is enabled (that is if \ref getEnabledExtensionId() would return a non-`nullptr` * value); `false` if the extension is not found or not enabled */ inline bool isExtensionEnabled(ExtensionManager* manager, const char* extFullName) { return getEnabledExtensionId(manager, extFullName) != nullptr; } /** * Helper function to fetch all extension packages and load them into the memory. * * @warning This function is extemely slow, can take seconds, depending on the size of registry. * * After calling this function extension manager will have all registry extensions loaded into memory. Functions like * \ref ExtensionManager::getRegistryExtensions() will be returning a full list of all extensions after. * * @param manager A pointer to the \ref ExtensionManager * @returns A vector of of \ref ExtensionInfo objects */ inline std::vector<ExtensionInfo> fetchAllExtensionPackages(ExtensionManager* manager) { std::vector<ExtensionInfo> packages; ExtensionSummary* summaries; size_t summaryCount; manager->fetchExtensionSummaries(&summaries, &summaryCount); for (size_t i = 0; i < summaryCount; i++) { const ExtensionSummary& summary = summaries[i]; ExtensionInfo* extensions; size_t extensionCount; manager->fetchExtensionPackages(summary.fullname, &extensions, &extensionCount); packages.insert(packages.end(), extensions, extensions + extensionCount); } return packages; } /** * A wrapper object to allow passing an invocable type (i.e. lambda) as an extension hook. */ class ExtensionStateChangeHookLambda : public IExtensionStateChangeHook { public: /** * Constructor. * @note Typically this is not constructed directly. Instead use \ref createExtensionStateChangeHook(). * @param fn a `std::function` that will be called on extension state change. May be empty. */ ExtensionStateChangeHookLambda(const std::function<void(const char*, ExtensionStateChangeType)>& fn) : m_fn(fn) { } /** * State change handler function. * @note Typically this is not called directly; it is called by \ref ExtensionManager. * @param extId The Extension ID that is changing * @param type The \ref ExtensionStateChangeType describing the state change */ void onStateChange(const char* extId, ExtensionStateChangeType type) override { if (m_fn) m_fn(extId, type); } private: std::function<void(const char*, ExtensionStateChangeType)> m_fn; CARB_IOBJECT_IMPL }; /** * Wrapper to pass an invocable object to Extension Manager Hooks. * @param hooks The \ref IExtensionManagerHooks instance * @param onStateChange The `std::function` that captures the invocable type (may be empty) * @param type The type to monitor for (see \ref IExtensionManagerHooks::createExtensionStateChangeHook()) * @param extFullName See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @param extDictPath See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @param order See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @param hookName See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @returns see \ref IExtensionManagerHooks::createExtensionStateChangeHook() */ inline IHookHolderPtr createExtensionStateChangeHook( IExtensionManagerHooks* hooks, const std::function<void(const char* extId, ExtensionStateChangeType type)>& onStateChange, ExtensionStateChangeType type, const char* extFullName = "", const char* extDictPath = "", Order order = kDefaultOrder, const char* hookName = nullptr) { return hooks->createExtensionStateChangeHook( carb::stealObject(new ExtensionStateChangeHookLambda(onStateChange)).get(), type, extFullName, extDictPath, order, hookName); } /** * A wrapper function to subscribe to extension enable (and optionally disable) events. * @param manager The \ref ExtensionManager instance * @param onEnable The `std::function` that captures the invocable to call on enable (may be empty). If the extension is * already enabled, this is invoked immediately * @param onDisable The `std::function` that captures the invocable to call on disable (may be empty) * @param extFullName See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @param hookName See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @returns a `std::pair` of \ref IHookHolderPtr objects (`first` represents the enable holder and `second` represents * the disable holder) */ inline std::pair<IHookHolderPtr, IHookHolderPtr> subscribeToExtensionEnable( ExtensionManager* manager, const std::function<void(const char* extId)>& onEnable, const std::function<void(const char* extId)>& onDisable = nullptr, const char* extFullName = "", const char* hookName = nullptr) { // Already enabled? if (extFullName && extFullName[0] != '\0') { const char* enabledExtId = getEnabledExtensionId(manager, extFullName); if (enabledExtId) onEnable(enabledExtId); } // Subscribe for enabling: IHookHolderPtr holder0 = createExtensionStateChangeHook( manager->getHooks(), [onEnable = onEnable](const char* extId, ExtensionStateChangeType) { onEnable(extId); }, ExtensionStateChangeType::eAfterExtensionEnable, extFullName, "", kDefaultOrder, hookName); // Optionally subscribe for disabling IHookHolderPtr holder1; if (onDisable) holder1 = createExtensionStateChangeHook( manager->getHooks(), [onDisable = onDisable](const char* extId, ExtensionStateChangeType) { onDisable(extId); }, ExtensionStateChangeType::eBeforeExtensionShutdown, extFullName, "", kDefaultOrder, hookName); return std::make_pair(holder0, holder1); } //! The result of parsing an extension URL. //! //! Given "omniverse://path/to/object", `scheme` would contain "omniverse" and `path` would contain "path/to/object" struct ExtPathUrl { std::string scheme; //!< The extension URL scheme std::string path; //!< The extension URL path }; /** * Simple helper function to parse a given URL into a scheme and a path. * @note If a path is given such as "f:/path/to/ext", this will return as \ref ExtPathUrl::scheme empty and everything * in \ref ExtPathUrl::path. * @param url The extension URL to parse * @returns a \ref ExtPathUrl containing the separate parts */ inline ExtPathUrl parseExtUrl(const std::string& url) { const std::string kSchemeDelimiter = ":"; auto pos = url.find(kSchemeDelimiter); if (pos == std::string::npos || pos == 1) return { "", url }; ExtPathUrl res = {}; res.scheme = url.substr(0, pos); res.path = url.substr(pos + kSchemeDelimiter.size() + 1); res.path = res.path.erase(0, res.path.find_first_not_of("/")); return res; } } // namespace ext } // namespace omni
9,585
C
38.941667
120
0.726552
omniverse-code/kit/include/omni/ext/IExtensions.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.ext Extension System interfaces #pragma once #include "../../carb/Framework.h" #include "../../carb/IObject.h" #include "../../carb/Interface.h" #include "../../carb/events/IEvents.h" namespace omni { namespace ext { /** * Extension version struct * * Follows Semantic Versioning 2.0. https://semver.org/ */ struct Version { int32_t major; //!< The major version (i.e. the 'x' in x.y.z), incremented for incompatible changes int32_t minor; //!< The minor version (i.e. the 'y' in x.y.z), for backwards compatible functionality int32_t patch; //!< The patch version (i.e. the 'z' in x.y.z), for backwards compatible bug fixes const char* prerelease; //!< The pre-release string const char* build; //!< The build string }; //! A struct describing Extension information struct ExtensionInfo { const char* id; //!< Unique Identifier used for python module name const char* name; //!< Extension name const char* packageId; //!< A package identifier Version version; //!< The version descriptor bool enabled; //!< Indicates whether this extension is enabled const char* title; //!< An optional descriptive title const char* path; //!< Extension path }; //! An enum describing Extensions Path type enum class ExtensionPathType { eCollection, //!< Folder with extensions eDirectPath, //!< Direct path to extension (as single file or a folder) eExt1Folder, //!< Deprecated Ext 1.0 Folder eCollectionUser, //!< Folder with extensions, read and stored in persistent settings eCollectionCache, //!< Folder with extensions, used for caching extensions downloaded from the registry eCount //!< Count of items in this enumeration }; //! A struct for describing Extension Folder information struct ExtensionFolderInfo { const char* path; //!< Extension path ExtensionPathType type; //!< Type of information in `path` member. }; //! A struct for describing Registry Provider information struct RegistryProviderInfo { const char* name; //!< The name of the Registry Provider }; //! A bit type for Extension Summary //! @see ExtensionSummary using ExtensionSummaryFlag = uint32_t; //! Empty flag constexpr ExtensionSummaryFlag kExtensionSummaryFlagNone = 0; //! Extension Summary flag meaning that extensions are enabled constexpr ExtensionSummaryFlag kExtensionSummaryFlagAnyEnabled = (1 << 1); //! Extension Summary flag meaning that an extension is built-in constexpr ExtensionSummaryFlag kExtensionSummaryFlagBuiltin = (1 << 2); //! Extension Summary flag meaning that an extension is installed constexpr ExtensionSummaryFlag kExtensionSummaryFlagInstalled = (1 << 3); //! A struct describing an Extension Summary //! @see ExtensionManager::fetchExtensionSummaries() struct ExtensionSummary { const char* fullname; //!< The full extension name, typically "ext_name-ext_tag" ExtensionSummaryFlag flags; //!< Summary flags about this extension //! Information about the enabled version, if any. If not present, \ref ExtensionInfo::id will be an empty string. ExtensionInfo enabledVersion; //! Information about the latest version. ExtensionInfo latestVersion; }; /** * Extension manager change event stream events */ //! An event type denoting a changed script. //! @see carb::events::IEvents const carb::events::EventType kEventScriptChanged = CARB_EVENTS_TYPE_FROM_STR("SCRIPT_CHANGED"); //! An event type denoting a changed folder. //! @see carb::events::IEvents const carb::events::EventType kEventFolderChanged = CARB_EVENTS_TYPE_FROM_STR("FOLDER_CHANGED"); /** * Extra events sent to IApp::getMessageBusEventStream() by extension manager */ //! An event type denoting the beginning of registry refresh. //! @see carb::events::IEvents const carb::events::EventType kEventRegistryRefreshBegin = CARB_EVENTS_TYPE_FROM_STR("omni.ext.REGISTRY_REFRESH_BEGIN"); //! An event type denoting the successful end of registry refresh. //! @see carb::events::IEvents const carb::events::EventType kEventRegistryRefreshEndSuccess = CARB_EVENTS_TYPE_FROM_STR("omni.ext.REGISTRY_REFRESH_END_SUCCESS"); //! An event type denoting end of registry refresh with failure. //! @see carb::events::IEvents const carb::events::EventType kEventRegistryRefreshEndFailure = CARB_EVENTS_TYPE_FROM_STR("omni.ext.REGISTRY_REFRESH_END_FAILURE"); //! An event type denoting the beginning of pulling an extension. //! @see carb::events::IEvents const carb::events::EventType kEventExtensionPullBegin = CARB_EVENTS_TYPE_FROM_STR("omni.ext.EXTENSION_PULL_BEGIN"); //! An event type denoting the successful end of pulling an extension. //! @see carb::events::IEvents const carb::events::EventType kEventExtensionPullEndSuccess = CARB_EVENTS_TYPE_FROM_STR("omni.ext.EXTENSION_PULL_END_SUCCESS"); //! An event type denoting the end of pulling an extension with failure. //! @see carb::events::IEvents const carb::events::EventType kEventExtensionPullEndFailure = CARB_EVENTS_TYPE_FROM_STR("omni.ext.EXTENSION_PULL_END_FAILURE"); /** * Version lock generation parameters * @see ExtensionManager::generateVersionLock() */ struct VersionLockDesc { bool separateFile; //!< Separate file bool skipCoreExts; //!< Skip core extensions bool overwrite; //!< Overwrite }; /** * The download state communicated by registry provider to extension manager * * Generally for index refresh or extension pull operations */ enum class DownloadState { eDownloading, //!< Currently downloading eDownloadSuccess, //!< Downloading finished successfully eDownloadFailure //!< Download failed }; /** * Input to running custom extension solver. * @see ExtensionManager::solveExtensions() */ struct SolverInput { //! List of extension names to enable (and therefore solve) //! //! Names may include full or partial versions, such as "omni.foo-1.2.3", or "omni.foo-1" //! The count of names is specified in `extensionNameCount`. const char** extensionNames; //! The number of names provided in the `extensionNames` array size_t extensionNameCount; //! Automatically add already enabled extension to the input (to take into account) bool addEnabled; //! If `true`, exclude extensions that are currently already enabled from the result. bool returnOnlyDisabled; }; /** * Interface to be implemented by registry providers. * * Extension manager will use it to pull (when resolving dependencies) and publish extensions. * * This is a sub-interface, with version controlled by \ref IExtensions. * * @see ExtensionManager, ExtensionManager::addRegistryProvider(), IExtensions */ class IRegistryProvider : public carb::IObject { public: /** * Called by ExtensionManager to begin an asynchronous index refresh or check status on an asynchronous refresh * * This function will be called many times and should return immediately. The returned state should be one of * \ref DownloadState. The first call to this function should begin a background index refresh and return * \ref DownloadState::eDownloading. Further calls to this function may return the same result while the refresh is * in process. When the refresh is finished, the next call should return \ref DownloadState::eDownloadSuccess, at * which point the \ref ExtensionManager will call \ref syncIndex(). * * @see ExtensionManager * @returns the \ref DownloadState */ virtual DownloadState refreshIndex() = 0; /** * Called by ExtensionManager to get the index * * Extension manager will call that function from time to time to get remote index. The structure of this dictionary * is a map from extension ids to extension configuration (mostly extension.toml files). * * @see ExtensionManager, carb::dictionary::IDictionary * @returns A \ref carb::dictionary::Item tree representing the remote index. */ virtual carb::dictionary::Item* syncIndex() = 0; /** * Called by ExtensionManager to trigger extension publishing * * @see ExtensionManager, unpublishExtension(), carb::dictionary::IDictionary * @param extPath The path to the extension to publish * @param extDict A \ref carb::dictionary::Item containing data about this extension * @returns `true` if publishing was successful; `false` if an error occurs */ virtual bool publishExtension(const char* extPath, carb::dictionary::Item* extDict) = 0; /** * Called by ExtensionManager to remove an extension * * @see ExtensionManager, publishExtension() * @param extId the extension ID of the extension to remove * @returns `true` if removal was successful; `false` if an error occurs */ virtual bool unpublishExtension(const char* extId) = 0; /** * Called by ExtensionManager to pull an extension, from a remote location to local cache * * @see ExtensionManager * @param extId The extension ID of the extension to pull * @param extFolder The folder to store the extension files in * @returns `true` if pulling was successful; `false` if an error occurs */ virtual bool pullExtension(const char* extId, const char* extFolder) = 0; /** * Called by ExtensionManager to asynchronously pull an extension, from a remote location to local cache * * This function will be called several times. The first time it is called for a given @p extId and @p extFolder, it * should start a background download process and return \ref DownloadState::eDownloading. It will be called * periodically to check the download state. Once the extension has been downloaded, this function should return * @ref DownloadState::eDownloadSuccess, or @ref DownloadState::eDownloadFailure if an error occurs. * @see ExtensionManager, DownloadState * @param extId The extension ID of the extension to pull * @param extFolder The folder to store the extension files in * @returns the current \ref DownloadState of the given \p extId */ virtual DownloadState pullExtensionAsync(const char* extId, const char* extFolder) = 0; /** * Called by ExtensionManager to set the maximum level of index stripping * * @rst .. deprecated:: This method is deprecated and no longer called. @endrst */ CARB_DEPRECATED("Not called. Index stripping was deprecated.") virtual bool setMaxStrippingLevel(int32_t level) = 0; }; //! Pointer type using IRegistryProviderPtr = carb::ObjectPtr<IRegistryProvider>; /** * Interface to be implemented to add new extension path protocols. */ class IPathProtocolProvider : public carb::IObject { public: /** * Called by ExtensionManager to register a protocol * * It must return local file system path for the provided url to be registered instead of url. It is a job of * protocol provider to update and maintain that local path. Extension manager will treat that path the same as * regular local extension search paths. * @param url The protocol to register * @returns A local filesystem path */ virtual const char* addPath(const char* url) = 0; /** * Called by ExtensionManager to unregister a protocol * @param url The protocol previously passed to \ref addPath(). */ virtual void removePath(const char* url) = 0; }; //! Pointer type using IPathProtocolProviderPtr = carb::ObjectPtr<IPathProtocolProvider>; class IExtensionManagerHooks; /** * The manager class that is responsible for all Extensions. * @see IExtensions::createExtensionManager */ class ExtensionManager : public carb::IObject { public: /** * Process all outstanding extension changes since the previous call to this function. * * If an extension was changed it will be reloaded. If it was added or removed (including adding new folders) * changes will also be applied. Events (@ref kEventScriptChanged, @ref kEventFolderChanged) are also dispatched. */ virtual void processAndApplyAllChanges() = 0; /** * Returns the number of registered local extensions. * @returns the number of registered local extensions */ virtual size_t getExtensionCount() const = 0; /** * Fills an array with information about registered local extensions. * * @param extensions The array of \ref ExtensionInfo structs to be filled. It must be large enough to hold * @ref getExtensionCount() entries. */ virtual void getExtensions(ExtensionInfo* extensions) const = 0; /** * Get an extension info dictionary for a single extension. * @see carb::dictionary::IDictionary * @param extId The extension ID to retrieve info for * @returns A \ref carb::dictionary::Item pointer containing the information; `nullptr` if the extension was not * found. */ virtual carb::dictionary::Item* getExtensionDict(const char* extId) const = 0; /** * Helper function to enable or disable a single extension. * @note The operation is deferred until \ref processAndApplyAllChanges() is called. Use * \ref setExtensionEnabledImmediate() to perform the action immediately. * @see setExtensionEnabledBatch * @param extensionId The extension ID to enable or disable * @param enabled `true` to enable the extension; `false` to disable the extension */ void setExtensionEnabled(const char* extensionId, bool enabled) { setExtensionEnabledBatch(&extensionId, 1, enabled); } /** * Enables or disables several extensions. * @note The operation is deferred until \ref processAndApplyAllChanges() is called. Use * \ref setExtensionEnabledBatchImmediate() to perform the action immediately. * @param extensionIds An array of extension IDs that should be enabled or disabled * @param extensionIdCount The number of items in \p extensionIds * @param enabled `true` to enable the extensions; `false` to disable the extensions */ virtual void setExtensionEnabledBatch(const char** extensionIds, size_t extensionIdCount, bool enabled) = 0; /** * Helper function to enable or disable a single extension, immediately. * @see setExtensionEnabledBatchImmediate * @param extensionId The extension ID to enable or disable * @param enabled `true` to enable the extension; `false` to disable the extension * @returns `true` if the operation could be completed; `false` otherwise */ bool setExtensionEnabledImmediate(const char* extensionId, bool enabled) { return setExtensionEnabledBatchImmediate(&extensionId, 1, enabled); } /** * Enables or disables several extensions immediately. * @param extensionIds An array of extension IDs that should be enabled or disabled * @param extensionIdCount The number of items in \p extensionIds * @param enabled `true` to enable the extensions; `false` to disable the extensions * @returns `true` if the operation could be completed; `false` otherwise */ virtual bool setExtensionEnabledBatchImmediate(const char** extensionIds, size_t extensionIdCount, bool enabled) = 0; /** * Set extensions to exclude on following solver/startup routines. * * @note The extensions set persist until next call to this function. * @param extensionIds An array of extension IDs that should be excluded * @param extensionIdCount The number of items in \p extensionIds */ virtual void setExtensionsExcluded(const char** extensionIds, size_t extensionIdCount) = 0; /** * Gets number of monitored extension folders. * * @return Extension folder count. */ virtual size_t getFolderCount() const = 0; /** * Gets monitored extension folders. * @param extensionFolderInfos The extension folder info array to be filled. It must be large enough to hold * @ref getFolderCount() entries. */ virtual void getFolders(ExtensionFolderInfo* extensionFolderInfos) const = 0; /** * Add extension path. * @see removePath() * @param path The path to add (folder or direct path) * @param type An \ref ExtensionPathType describing how \p path should be treated */ virtual void addPath(const char* path, ExtensionPathType type = ExtensionPathType::eCollection) = 0; /** * Remove extension path. * @see addPath() * @param path The path previously given to \ref addPath() */ virtual void removePath(const char* path) = 0; /** * Accesses the IEventStream that is used for change events. * * @see carb::events::IEventStream * @returns The \ref carb::events::IEventStream used for change events */ virtual carb::events::IEventStream* getChangeEventStream() const = 0; /** * Interface to install hooks to "extend" extension manager. * @returns an \ref IExtensionManagerHooks instance to allow hooking the Extension Manager */ virtual IExtensionManagerHooks* getHooks() const = 0; /** * Adds a new registry provider. * @see IRegistryProvider, removeRegistryProvider() * @param providerName unique name for the registry provider * @param provider a \ref IRegistryProvider instance that will be retained by `*this` * @returns `true` if registration was successful; `false` otherwise (i.e. the provided name was not unique) */ virtual bool addRegistryProvider(const char* providerName, IRegistryProvider* provider) = 0; /** * Removes a registry provider. * @see IRegistryProvider, addRegistryProvider() * @param providerName the unique name previously passed to \ref addRegistryProvider() */ virtual void removeRegistryProvider(const char* providerName) = 0; /** * Gets the number of current registry providers. * @returns the number of registry providers */ virtual size_t getRegistryProviderCount() const = 0; /** * Fills an array with info about current registry providers. * @param infos an array of \ref RegistryProviderInfo objects to be filled. It must be large enough to hold * @ref getRegistryProviderCount() entries. */ virtual void getRegistryProviders(RegistryProviderInfo* infos) = 0; /** * Non blocking call to initiate registry refresh. */ virtual void refreshRegistry() = 0; /** * Blocking call to synchronize with remote registry. * @returns `true` if the synchronization was successful; `false` if an error occurred. */ virtual bool syncRegistry() = 0; /** * Gets the number of extensions in the registry. */ virtual size_t getRegistryExtensionCount() const = 0; /** * Fills an array with compatible extensions in the registry. * * @param extensions an array of \ref ExtensionInfo objects to be filled. It must be large enough to hold * @ref getRegistryExtensionCount() entries. */ virtual void getRegistryExtensions(ExtensionInfo* extensions) const = 0; /** * Gets the number of extension packages in the registry. */ virtual size_t getRegistryExtensionPackageCount() const = 0; /** * Fills the array with all extension packages in the registry. * * @note this function will return all extensions in the registry, including packages for other platforms, * incompatible with current runtime. * * @param extensions an array of \ref ExtensionInfo objects to be filled. It must be large enough to hold * @ref getRegistryExtensionPackageCount() entries. */ virtual void getRegistryExtensionPackages(ExtensionInfo* extensions) const = 0; /** * Get an extension info dictionary for a single extension from the registry. * @see carb::dictionary::IDictionary * @param extId The extension ID to retrieve information for * @returns A \ref carb::dictionary::Item containing information about the given extension; `nullptr` if the * extension ID was not found. */ virtual carb::dictionary::Item* getRegistryExtensionDict(const char* extId) = 0; /** * Package and upload extension to the registry. * * @note If \p providerName is empty and there are multiple providers, the provider specified in the setting key * `/app/extensions/registryPublishDefault` is used. * @see unpublishExtension() * @param extId The extension ID to publish * @param providerName The provider name to use for publish. If an empty string is provided and multiple providers * are registered, the provider specified in the setting key `/app/extensions/registryPublishDefault` is used. * @param allowOverwrite If `true`, the extension already specified in the registry maybe overwritten */ virtual bool publishExtension(const char* extId, const char* providerName = "", bool allowOverwrite = false) = 0; /** * Removes an extension from the registry. * * @note If \p providerName is empty and there are multiple providers, the provider specified in the setting key * `/app/extensions/registryPublishDefault` is used. * @see publishExtension() * @param extId The extension ID to unpublish * @param providerName The provider name to use. If an empty string is provided and multiple providers * are registered, the provider specified in the setting key `/app/extensions/registryPublishDefault` is used. */ virtual bool unpublishExtension(const char* extId, const char* providerName = "") = 0; /** * Downloads the specified extension from the registry. * @note This is a blocking call. Use @ref pullExtensionAsync() if asynchronous behavior is desired. * @see pullExtensionAsync() * @param extId The extension ID to download * @returns `true` if the extension was downloaded successfully; `false` otherwise. */ virtual bool pullExtension(const char* extId) = 0; /** * Starts an asynchronous extension download from the registry. * @note this function returns immediately * @see pullExtension() * @param extId The extension ID to download */ virtual void pullExtensionAsync(const char* extId) = 0; /** * Fetches extension summaries for all extensions. * * Summary are extensions grouped by version. One summary per fullname(name+tag). * @note The array that is received is valid until the next call to this function. * @param[out] summaries Receives an array of \ref ExtensionSummary instances * @param[out] summaryCount Receives the size of the array passed to \p summaries. */ virtual void fetchExtensionSummaries(ExtensionSummary** summaries, size_t* summaryCount) = 0; /** * Fetch all matching compatible extensions. * * A partial version can also be passed. So `omni.foo`, `omni.foo-2`, `omni.foo-1.2.3` all valid values for * @p nameAndVersion. * * @note The returned array is valid until next call of this function. * @param nameAndVersion The name (and optional partial or full version) to search * @param[out] extensions Receives an array of \ref ExtensionInfo instances * @param[out] extensionCount Receives the size of the array passed to \p extensions */ virtual void fetchExtensionVersions(const char* nameAndVersion, ExtensionInfo** extensions, size_t* extensionCount) = 0; /** * Fetch all matching extension packages. * * A partial version can also be passed. So `omni.foo`, `omni.foo-2`, `omni.foo-1.2.3` all valid values for * @p nameAndVersion. * * This function will return all extensions in the registry, including packages for other platforms, incompatible * with current runtime. * * @note The returned array is valid until next call of this function. * @param nameAndVersion The name (and optional partial or full version) to search * @param[out] extensions Receives an array of \ref ExtensionInfo instances * @param[out] extensionCount Receives the size of the array passed to \p extensions */ virtual void fetchExtensionPackages(const char* nameAndVersion, ExtensionInfo** extensions, size_t* extensionCount) = 0; /** * Disables all enabled extensions. * * @note this is called automatically upon destruction. */ virtual void disableAllExtensions() = 0; /** * Adds user paths from persistent settings. * * All of the extension search path from persistent settings are added as \ref ExtensionPathType::eCollectionUser. */ virtual void addUserPaths() = 0; /** * Add cache paths from settings. * * All of the cache paths from settings are added as \ref ExtensionPathType::eCollectionCache. * This is necessary for registry usage. */ virtual void addCachePath() = 0; /** * Generate settings that contains versions of started dependencies to lock them (experimental). * @param extId The extension ID * @param desc A \ref VersionLockDesc descriptor * @returns `true` if generation succeeded; `false` otherwise */ virtual bool generateVersionLock(const char* extId, const VersionLockDesc& desc) = 0; /** * Adds a new path protocol provider. * @see removePathProtocolProvider() * @param scheme A unique name for this provider * @param provider A \ref IPathProtocolProvider instance that will be retained by the Extension Manager * @returns `true` if the provider was registered; `false` otherwise (i.e. if \p scheme is not unique) */ virtual bool addPathProtocolProvider(const char* scheme, IPathProtocolProvider* provider) = 0; /** * Removes a path protocol provider. * @see addPathProtocolProvider() * @param scheme The unique name previously passed to \ref addPathProtocolProvider() */ virtual void removePathProtocolProvider(const char* scheme) = 0; /** * Runs the extension dependencies solver on the input. * * Input is a list of extension, they can be names, full id, partial versions like `ommi.foo-2`. * * If solver succeeds it returns a list of extensions that satisfy the input and `true`, otherwise `errorMessage` * contains explanation of what failed. * * @note The returned array and error message is valid until next call of this function. * @param input The \ref SolverInput containing a list of extensions * @param[out] extensions If `true` returned, receives an array of \ref ExtensionInfo instances that satisfy * \p input, otherwise undefined * @param[out] extensionCount If `true` returned, receives the count of items passed to \p extensions, otherwise * undefined * @param[out] errorMessage If `false` returned, receives an error message, otherwise undefined * @returns `true` if the solver succeeds and \p extensions and \p extensionCount contain the array of extensions * that satisfy \p input; `false` otherwise, \p errorMessage contains a description of the error, but * \p extensions and \p extensionCount are undefined and should not be accessed. */ virtual bool solveExtensions(const SolverInput& input, ExtensionInfo** extensions, size_t* extensionCount, const char** errorMessage) = 0; /** * Gets number of local extension packages. * @returns the number of local extension packages */ virtual size_t getExtensionPackageCount() const = 0; /** * Fills an array with local extension packages. * * @note This function will return all local extensions, including packages for other platforms, incompatible * with current targets. * @param extensions An array of \ref ExtensionInfo instances to be filled. It must be large enough to hold * @ref getExtensionPackageCount() entries. */ virtual void getExtensionPackages(ExtensionInfo* extensions) const = 0; /** * Removes a downloaded extension. * @param extId The extension ID to remove * @returns `true` if the extension was removed; `false` otherwise */ virtual bool uninstallExtension(const char* extId) = 0; }; /** * omni.ext plugin interface * * This interface is used to access the \ref ExtensionManager */ struct IExtensions { CARB_PLUGIN_INTERFACE("omni::ext::IExtensions", 1, 1) /** * Creates a new extension manager. * @warning This function should not be used; instead call \ref createExtensionManager() to return a RAII pointer. * @param changeEventStream The \ref carb::events::IEventStream to push change events. The stream will not be * pumped by the manager. Optional (may be `nullptr`) * @returns A pointer to an \ref ExtensionManager */ ExtensionManager*(CARB_ABI* createExtensionManagerPtr)(carb::events::IEventStream* changeEventStream); /** * Creates a new extension manager. * @param changeEventStream The \ref carb::events::IEventStream to push change events. The stream will not be * pumped by the manager. Optional (may be `nullptr`) * @returns An RAII pointer to an \ref ExtensionManager */ carb::ObjectPtr<ExtensionManager> createExtensionManager(carb::events::IEventStream* changeEventStream = nullptr); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Extension Manager Hooks // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Different moments in extension state lifetime. * * Used with \ref IExtensionStateChangeHook::onStateChange() to receive notifications at different points of an * extension state change. */ enum class ExtensionStateChangeType { eBeforeExtensionEnable, //!< Sent right before extension is enabled. eAfterExtensionEnable, //!< Sent right after extension is enabled. eBeforeExtensionShutdown, //!< Sent right before extension is disabled. eAfterExtensionShutdown, //!< Sent right after extension is disabled. eCount, //!< Count of extension state change entries. }; /** * An interface that can be implemented to receive extension state changes. */ class IExtensionStateChangeHook : public carb::IObject { public: /** * Called by the ExtensionManager upon extension state changes. * @see ExtensionManager * @param extId The extension ID that is experiencing a state change * @param type The \ref ExtensionStateChangeType that describes the type of state change */ virtual void onStateChange(const char* extId, ExtensionStateChangeType type) = 0; }; //! RAII pointer type using IExtensionStateChangeHookPtr = carb::ObjectPtr<IExtensionStateChangeHook>; /** * Hook call order. * * Lower hook values are called first. Negative values are acceptable. * @see kDefaultOrder */ using Order = int32_t; /** * Default order. */ static constexpr Order kDefaultOrder = 0; /** * Hook holder. Hook is valid while the holder is alive. */ class IHookHolder : public carb::IObject { }; //! RAII pointer type for \ref IHookHolder. using IHookHolderPtr = carb::ObjectPtr<IHookHolder>; /** * Extension manager subclass with all the hooks that can be installed into it. * @see ExtensionManager::getHooks() */ class IExtensionManagerHooks { public: /** * Installs a hook for extension state change. * * The hook will be called for the states specified by \ref ExtensionStateChangeType. * * You can filter for extensions with specific config/dict to only be called for those. That allows to implement * new configuration parameters handled by your hook. * * @param hook The instance that will be called. The \ref ExtensionManager will retain this object until the * returned \ref IHookHolderPtr expires * @param type Extension state change moment to hook into (see \ref ExtensionStateChangeType) * @param extFullName Extension name to look for. Hook is only called for extensions with matching name. Can be * empty. * @param extDictPath Extension dictionary path to look for. Hook is only called if it is present. * @param order Hook call order (if there are multiple). * @param hookName Hook name for debugging and logging. Optional (may be `nullptr`) * @returns a \ref IHookHolder object. When it expires \p hook will be released and no longer active. */ IHookHolderPtr createExtensionStateChangeHook(IExtensionStateChangeHook* hook, ExtensionStateChangeType type, const char* extFullName = "", const char* extDictPath = "", Order order = kDefaultOrder, const char* hookName = nullptr); //! @copydoc createExtensionStateChangeHook() virtual IHookHolder* createExtensionStateChangeHookPtr(IExtensionStateChangeHook* hook, ExtensionStateChangeType type, const char* extFullName = "", const char* extDictPath = "", Order order = kDefaultOrder, const char* hookName = nullptr) = 0; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Inline Functions // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////// ExtensionManagerHooks ////////////// inline IHookHolderPtr IExtensionManagerHooks::createExtensionStateChangeHook(IExtensionStateChangeHook* hook, ExtensionStateChangeType type, const char* extFullName, const char* extDictPath, Order order, const char* hookName) { return carb::stealObject( this->createExtensionStateChangeHookPtr(hook, type, extFullName, extDictPath, order, hookName)); } ////////////// IExtensions ////////////// inline carb::ObjectPtr<ExtensionManager> IExtensions::createExtensionManager(carb::events::IEventStream* changeEventStream) { return carb::stealObject(this->createExtensionManagerPtr(changeEventStream)); } } // namespace ext } // namespace omni
35,819
C
40.362587
124
0.676987
omniverse-code/kit/include/omni/ext/IExtensionHooks.gen.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. // // --------- 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 //! Hooks that can be defined by plugins to better understand how the plugin is being used by the extension system. template <> class omni::core::Generated<omni::ext::IExtensionHooks_abi> : public omni::ext::IExtensionHooks_abi { public: OMNI_PLUGIN_INTERFACE("omni::ext::IExtensionHooks") //! Called when an extension loads the plugin. //! //! If multiple extensions load the plugin, this method will be called multiple times. void onStartup(omni::core::ObjectParam<omni::ext::IExtensionData> ext) noexcept; //! Called when an extension that uses this plugin is unloaded. //! //! If multiple extension load the plugin, this method will be called multiple times. void onShutdown(omni::core::ObjectParam<omni::ext::IExtensionData> ext) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::ext::IExtensionHooks_abi>::onStartup( omni::core::ObjectParam<omni::ext::IExtensionData> ext) noexcept { onStartup_abi(ext.get()); } inline void omni::core::Generated<omni::ext::IExtensionHooks_abi>::onShutdown( omni::core::ObjectParam<omni::ext::IExtensionData> ext) noexcept { onShutdown_abi(ext.get()); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
2,086
C
31.107692
115
0.733941
omniverse-code/kit/include/omni/ext/IExtensionData.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. // #pragma once #include <omni/core/IObject.h> namespace omni { namespace ext { //! Declaration of IExtensionData. OMNI_DECLARE_INTERFACE(IExtensionData); //! Information about an extension. class IExtensionData_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.ext.IExtensionData")> { protected: //! Access the extension id. For example: "omni.example.greet". //! //! @returns The Extension ID. The memory returned is valid for the lifetime of `*this`. virtual OMNI_ATTR("c_str, not_null") const char* getId_abi() noexcept = 0; //! Access the directory which contains the extension. For example: //! c:/users/ncournia/dev/kit/kit/_build/windows-x86_64/debug/exts/omni.example.greet. //! //! @returns The Extension Directory. The memory returned is valid for the lifetime of `*this`. virtual OMNI_ATTR("c_str, not_null") const char* getDirectory_abi() noexcept = 0; }; } // namespace ext } // namespace omni #include "IExtensionData.gen.h"
1,445
C
34.268292
116
0.731488
omniverse-code/kit/include/omni/ext/IExtensionData.gen.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. // // --------- 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 //! Information about an extension. template <> class omni::core::Generated<omni::ext::IExtensionData_abi> : public omni::ext::IExtensionData_abi { public: OMNI_PLUGIN_INTERFACE("omni::ext::IExtensionData") //! The extension id. For example: omni.example.greet. //! //! The memory returned is valid for the lifetime of this object. const char* getId() noexcept; //! The directory which contains the extension. For example: //! c:/users/ncournia/dev/kit/kit/_build/windows-x86_64/debug/exts/omni.example.greet. //! //! The memory returned is valid for the lifetime of this object. const char* getDirectory() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline const char* omni::core::Generated<omni::ext::IExtensionData_abi>::getId() noexcept { return getId_abi(); } inline const char* omni::core::Generated<omni::ext::IExtensionData_abi>::getDirectory() noexcept { return getDirectory_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
1,850
C
27.921875
97
0.722703
omniverse-code/kit/include/omni/python/PyString.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. // #pragma once #include "PyBind.h" #include "../String.h" namespace pybind11 { namespace detail { //! This converts between @c omni::string and native Python @c str types. template <> struct type_caster<omni::string> { // NOTE: The _ is needed to convert the character literal into a `pybind::descr` or functions using this type will // fail to initialize inside of `def`. PYBIND11_TYPE_CASTER(omni::string, _("omni::string")); //! Convert @a src Python string into @c omni::string instance. bool load(handle src, bool) { PyObject* source = src.ptr(); if (PyObject* source_bytes_raw = PyUnicode_AsEncodedString(source, "UTF-8", "strict")) { auto source_bytes = reinterpret_steal<bytes>(handle{ source_bytes_raw }); char* str; Py_ssize_t str_len; int rc = PyBytes_AsStringAndSize(source_bytes.ptr(), &str, &str_len); // Getting the string should always work here -- we've already ensured it encoded to UTF-8 bytes if (rc == -1) { return false; } this->value.assign(str, omni::string::size_type(str_len)); return true; } else { return false; } } //! Convert @a src string into a Python Unicode string. //! //! @note //! The return value policy and parent object arguments are ignored. The return policy is irrelevant, as the source //! string is always copied into the native form. The parent object is not supported by the Python string type. static handle cast(const omni::string& src, return_value_policy, handle) noexcept { PyObject* native = PyUnicode_FromStringAndSize(src.data(), Py_ssize_t(src.size())); return handle{ native }; } }; } // namespace detail } // namespace pybind11
2,310
C
34.015151
119
0.647619
omniverse-code/kit/include/omni/python/PyVec.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. // #pragma once #include "PyBind.h" #include <cstring> namespace omni { namespace python { namespace detail { template <typename VT, typename T, size_t S> T getVectorValue(const VT& vector, size_t i) { if (i >= S) { throw py::index_error(); } const T* components = reinterpret_cast<const T*>(&vector); return components[i]; } template <typename VT, typename T, size_t S> void setVectorValue(VT& vector, size_t i, T value) { if (i >= S) { throw py::index_error(); } T* components = reinterpret_cast<T*>(&vector); components[i] = value; } template <typename VT, typename T, size_t S> py::list getVectorSlice(const VT& s, const py::slice& slice) { size_t start, stop, step, slicelength; if (!slice.compute(S, &start, &stop, &step, &slicelength)) throw py::error_already_set(); py::list returnList; for (size_t i = 0; i < slicelength; ++i) { returnList.append(getVectorValue<VT, T, S>(s, start)); start += step; } return returnList; } template <typename VT, typename T, size_t S> void setVectorSlice(VT& s, const py::slice& slice, const py::sequence& value) { size_t start, stop, step, slicelength; if (!slice.compute(S, &start, &stop, &step, &slicelength)) throw py::error_already_set(); if (slicelength != value.size()) throw std::runtime_error("Left and right hand size of slice assignment have different sizes!"); for (size_t i = 0; i < slicelength; ++i) { setVectorValue<VT, T, S>(s, start, value[i].cast<T>()); start += step; } } template <typename TupleT, class T, size_t S> py::class_<TupleT> bindVec(py::module& m, const char* name, const char* docstring = nullptr) { py::class_<TupleT> c(m, name, docstring); c.def(py::init<>()); // Python special methods for iterators, [], len(): c.def("__len__", [](const TupleT&) { return S; }); c.def("__getitem__", [](const TupleT& t, size_t i) { return getVectorValue<TupleT, T, S>(t, i); }); c.def("__setitem__", [](TupleT& t, size_t i, T v) { setVectorValue<TupleT, T, S>(t, i, v); }); c.def("__getitem__", [](const TupleT& t, py::slice slice) -> py::list { return getVectorSlice<TupleT, T, S>(t, slice); }); c.def("__setitem__", [](TupleT& t, py::slice slice, const py::sequence& value) { setVectorSlice<TupleT, T, S>(t, slice, value); }); c.def("__eq__", [](TupleT& self, TupleT& other) { return 0 == std::memcmp(&self, &other, sizeof(TupleT)); }); // That allows passing python sequence into C++ function which accepts concrete TupleT: py::implicitly_convertible<py::sequence, TupleT>(); return c; } } // namespace detail } // namespace python } // namespace omni
3,196
C
30.97
120
0.63423
omniverse-code/kit/include/omni/python/PyBind.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 Python binding helpers. #pragma once #include "../core/IObject.h" #include "../log/ILog.h" #include "../../carb/IObject.h" #include "../../carb/BindingsPythonUtils.h" #include <pybind11/pybind11.h> #include <pybind11/functional.h> #include <sstream> #include <vector> namespace py = pybind11; namespace omni { //! Python related functionality. namespace python { //! Private implementation details for Python. namespace detail { //! pybind11 "holder" for objects inherited from @ref omni::core::ObjectPtr. //! //! By default, @ref omni::core::ObjectPtr does not have a constructor that //! accepts a lone pointer. This is because it is ambiguous if @c //! addReference() should be called on the pointer. Unfortunately, pybind11 //! expects such a constructor to exists. The purpose of this class is provide //! the constructor pybind11 expects. //! //! Note that we're careful to never generate bindings that call the ambiguous //! constructor. To protect against future breakage, @ref OMNI_FATAL_UNLESS is //! used to flag bad code is being generated. Unfortunately, this check must be //! performed at runtime. //! //! An future alternative to this approach is to patch pybind11 //! //! OM-18948: Update PyBind to not require a raw pointer to "holder" //! constructor. template <typename T> class PyObjectPtr : public core::ObjectPtr<T> { public: //! Allow implicit conversion from `nullptr` to an @ref omni::core::ObjectPtr. constexpr PyObjectPtr(std::nullptr_t = nullptr) noexcept { } //! Never call this method as it will terminate the application. See class //! description for rationale. explicit PyObjectPtr(T*) { // if this assertion hits, something is amiss in our bindings (or PyBind was updated) OMNI_FATAL_UNLESS(false, "pybind11 created an ambiguous omni::core::ObjectPtr"); } //! Copy constructor. PyObjectPtr(const core::ObjectPtr<T>& other) noexcept : core::ObjectPtr<T>(other) { } //! Copy constructor. template <typename U> PyObjectPtr(const core::ObjectPtr<U>& other) noexcept : core::ObjectPtr<T>(other) { } //! Move constructor. template <typename U> PyObjectPtr(core::ObjectPtr<U>&& other) noexcept : core::ObjectPtr<T>(std::move(other)) { } }; } // namespace detail } // namespace python } // namespace omni #ifndef DOXYGEN_BUILD // tell pybind the smart pointer it should use to manage or interfaces PYBIND11_DECLARE_HOLDER_TYPE(T, omni::python::detail::PyObjectPtr<T>, true); PYBIND11_DECLARE_HOLDER_TYPE(T, omni::core::ObjectPtr<T>, true); // See comment block for DISABLE_PYBIND11_DYNAMIC_CAST for an explanation. namespace pybind11 { template <typename itype> struct polymorphic_type_hook<itype, detail::enable_if_t<std::is_base_of<omni::core::IObject, itype>::value>> { static const void* get(const itype* src, const std::type_info*&) { return src; } }; } // namespace pybind11 namespace omni { namespace python { //! Specialize this class to define hand-written bindings for T. template <typename T> struct PyBind { template <typename S> static S& bind(S& s) { return s; } }; //! Given a pointer, pokes around in pybind's internals to see if there's already a PyObject managing the pointer. This //! can be used to avoid data copies. inline bool hasPyObject(const void* p) { auto& instances = py::detail::get_internals().registered_instances; return (instances.end() != instances.find(p)); } //! Converts a C value to Python. Makes a copy if needed. //! //! The default template (this template) handles: //! - pointer to primitive type (int, float, etc.) //! - pointer to interface //! - primitive value (int, float, etc.) template <typename T, bool isInterface = std::is_base_of<omni::core::IObject, typename std::remove_pointer<T>::type>::value, bool isStruct = std::is_class<typename std::remove_pointer<T>::type>::value> class ValueToPython { public: explicit ValueToPython(T orig) : m_orig{ orig } { } T get() { return m_orig; } private: T m_orig; }; //! Specialization of ValueToPython //! //! This specialization handles: //! //! - pointer to struct template <typename T> class ValueToPython<T, /*interface*/ false, /*struct*/ true> { public: using Type = typename std::remove_pointer<T>::type; explicit ValueToPython(Type* orig) { m_orig = orig; if (!hasPyObject(orig)) { m_copy.reset(new Type{ *orig }); } } Type* getData() { if (m_copy) { return m_copy.get(); } else { return m_orig; } } private: Type* m_orig; std::unique_ptr<Type> m_copy; }; template <typename T, bool isPointer = std::is_pointer<T>::value, bool isInterface = std::is_base_of<omni::core::IObject, typename std::remove_pointer<T>::type>::value, bool isStruct = std::is_class<typename std::remove_pointer<T>::type>::value> struct PyCopy { // code generator shouldn't get here }; // primitive value template <typename T> struct PyCopy<T, false, false, false> { static py::object toPython(T cObj) { return py::cast(cObj); } static T fromPython(py::object pyObj) { return pyObj.cast<T>(); } }; // pointer to struct or primitive template <typename T, bool isStruct> struct PyCopy<T, /*isPointer=*/true, false, isStruct> { /* static py::object toPython(T cObj) { return py::cast(cObj); } */ static void fromPython(T out, py::object pyObj) { *out = *(pyObj.cast<T>()); } }; // struct template <typename T> struct PyCopy<T, false, false, true> { static py::object toPython(const T& cObj) { return py::cast(cObj); } static const T& fromPython(py::object pyObj) { return *pyObj.cast<T*>(); } }; template <typename T, bool elementIsPointer = std::is_pointer<typename std::remove_pointer<T>::type>::value, bool elementIsInterfacePointer = std::is_base_of<omni::core::IObject, typename std::remove_pointer<typename std::remove_pointer<T>::type>::type>::value, bool elementIsStruct = std::is_class<typename std::remove_pointer<T>::type>::value> struct PyArrayCopy { using ItemType = typename std::remove_const<typename std::remove_pointer<T>::type>::type; static py::object toPython(T in, uint32_t count) { py::tuple out(count); for (uint32_t i = 0; i < count; ++i) { out[i] = PyCopy<ItemType>::toPython(in[i]); } return out; } static void fromPython(T out, uint32_t count, py::sequence in) { if (count != uint32_t(in.size())) { std::ostringstream msg; msg << "expected " << count << " elements in the sequence, python returned " << int32_t(in.size()); throw std::runtime_error(msg.str()); } T dst = out; for (const auto& elem : in) { PyCopy<T>::fromPython(dst, elem); ++dst; } } }; template <typename T, bool elementIsInterfacePointer, bool elementIsStruct> struct PyArrayCopy<T, /*elementIsPointer=*/true, elementIsInterfacePointer, elementIsStruct> { // TODO: handle array of pointers }; template <> struct PyArrayCopy<const char* const*, /*elementIsPointer=*/true, /*elementIsInterfacePointer=*/false, /*elementIsStruct=*/false> { static py::object toPython(const char* const* in, uint32_t count) { py::tuple out(count); for (uint32_t i = 0; i < count; ++i) { out[i] = py::str(in[i]); } return out; } }; template <typename T> class ArrayToPython { public: using ItemType = typename std::remove_const<typename std::remove_pointer<T>::type>::type; ArrayToPython(T src, uint32_t sz) : m_tuple{ PyArrayCopy<T>::toPython(src, sz) } { } py::tuple& getPyObject() { return m_tuple; } private: py::tuple m_tuple; }; template <typename T> class ArrayFromPython { public: using ItemType = typename std::remove_const<typename std::remove_pointer<T>::type>::type; ArrayFromPython(py::sequence seq) { m_data.reserve(seq.size()); for (auto pyObj : seq) { m_data.emplace_back(PyCopy<ItemType>::fromPython(pyObj)); } } T getData() { return m_data.data(); } uint32_t getCount() const { return uint32_t(m_data.size()); } py::tuple createPyObject() { py::tuple out{ m_data.size() }; for (size_t i = 0; i < m_data.size(); ++i) { out[i] = PyCopy<ItemType>::toPython(m_data[i]); } return out; } private: std::vector<ItemType> m_data; }; template <typename T, bool isInterface = std::is_base_of<omni::core::IObject, typename std::remove_pointer<T>::type>::value, bool isStruct = std::is_class<typename std::remove_pointer<T>::type>::value> class PointerFromPython { // code generator should never instantiate this version }; // inout pointer to struct template <typename T> class PointerFromPython<T, /*interface=*/false, /*struct=*/true> { public: using Type = typename std::remove_const<typename std::remove_pointer<T>::type>::type; PointerFromPython() : m_copy{ new Type } { } explicit PointerFromPython(T orig) : m_copy{ new Type{ *orig } } { } T getData() { return m_copy.get(); } py::object createPyObject() { return py::cast(std::move(m_copy.release()), py::return_value_policy::take_ownership); } private: std::unique_ptr<Type> m_copy; }; // inout pointer to primitive type template <typename T> class PointerFromPython<T, /*interface=*/false, /*struct=*/false> { public: using Type = typename std::remove_const<typename std::remove_pointer<T>::type>::type; PointerFromPython() = default; explicit PointerFromPython(T orig) : m_copy{ *orig } { } T getData() { return &m_copy; } py::object createPyObject() { return py::cast(m_copy); } private: Type m_copy; }; inline void throwIfNone(const py::object& pyObj) { if (pyObj.is_none()) { throw std::runtime_error("python object must not be None"); } } } // namespace python } // namespace omni #endif // DOXYGEN_BUILD //! Declare a compilation unit as script language bindings. //! //! This macro should be called from each Python module to correctly initialize //! bindings. //! //! @param name_ The name of the module (e.g. "omni.core-pyd"). This is passed //! to @ref CARB_GLOBALS_EX which will be used as `g_carbClientName` for the //! module. This will also be the name of the module's default logging channel. //! //! @param desc_ The description passed to @ref OMNI_GLOBALS_ADD_DEFAULT_CHANNEL //! to describe the Python module's default logging channel. #define OMNI_PYTHON_GLOBALS(name_, desc_) CARB_BINDINGS_EX(name_, desc_)
11,636
C
24.24295
133
0.636215
omniverse-code/kit/include/omni/platforminfo/IOsInfo.h
// Copyright (c) 2021-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 Helper interface to retrieve operating system info. */ #pragma once #include "../core/IObject.h" namespace omni { /** Platform and operating system info namespace. */ namespace platforminfo { /** Forward declaration of the IOSInfo API object. */ class IOsInfo; /** Names for the supported operating systems. */ enum class OMNI_ATTR("prefix=e") Os { eUnknown, ///< The OS is unknown or could not be determined. eWindows, ///< Microsoft Windows. eLinux, ///< Any flavor of Linux. eMacOs, ///< Mac OS. }; /** Names for the processor architecture for the system. */ enum class OMNI_ATTR("prefix=e") Architecture { eUnknown, ///< The architecture is unknown or could not be determined. eX86_64, ///< Intel X86 64 bit. eAarch64, ///< ARM 64-bit. }; /** A three-part operating system version number. This includes the major, minor, and * build number. This is often expressed as "<major>.<minor>.<buildNumber>" when printed. */ struct OsVersion { uint32_t major; ///< Major version. uint32_t minor; ///< Minor version. uint32_t buildNumber; ///< OS specific build number. }; /** Information about the active compositor on the system. */ struct CompositorInfo { const char* name; ///< The name of the active compositor. This must not be modified. const char* vendor; ///< The vendor of the active compositor. This must not be modified. int32_t releaseVersion; ///< The release version number of the active compositor. }; /** Interface to collect and retrieve information about the operating system. */ class IOsInfo_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.platforminfo.IOsInfo")> { protected: /** Retrieves the processor architecture for this platform. * * @returns An architecture name. This will never be * @ref omni::platforminfo::Architecture::eUnknown. * * @thread_safety This call is thread safe. */ virtual Architecture getArchitecture_abi() noexcept = 0; /** Retrieves an identifier for the current platform. * * @returns An operating system name. This will never be * @ref omni::platforminfo::Os::eUnknown. * * @thread_safety This call is thread safe. */ virtual Os getOs_abi() noexcept = 0; /** Retrieves the OS version information. * * @returns The operating system version numbers. These will be retrieved from the system * as directly as possible. If possible, these will not be parsed from a string * version of the operating system's name. * * @thread_safety This call is thread safe. */ virtual OsVersion getOsVersion_abi() noexcept = 0; /** Retrieves the name and version information for the system compositor. * * @returns An object describing the active compositor. * * @thread_safety This call is thread safe. */ virtual CompositorInfo getCompositorInfo_abi() noexcept = 0; /** Retrieves the friendly printable name of the operating system. * * @returns A string describing the operating system. This is retrieved from the system and * does not necessarily follow any specific formatting. This may or may not contain * specific version information. This string is intended for display to users. * * @thread_safety This call is thread safe. */ virtual const char* getPrettyName_abi() noexcept = 0; /** Retrieves the name of the operating system. * * @returns A string describing the operating system. This is retrieved from the system if * possible and does not necessarily follow any specific formatting. This may * include different information than the 'pretty' name (though still identifying * the same operating system version). This string is more intended for logging * or parsing purposes than display to the user. * * @thread_safety This call is thread safe. */ virtual const char* getName_abi() noexcept = 0; /** Retrieves the operating system distribution name. * * @returns The operating system distribution name. For Windows 10 and up, this often * contains the build's version name (ie: v1909). For Linux, this contains the * distro name (ie: "Ubuntu", "Gentoo", etc). * * @thread_safety This call is thread safe. */ virtual const char* getDistroName_abi() noexcept = 0; /** Retrieves the operating system's build code name. * * @returns The code name of the operating system's current version. For Windows 10 and up, * this is the Microsoft internal code name for each release (ie: "RedStone 5", * "21H2", etc). If possible it will be retrieved from the system. If not * available, a best guess will be made based on the build version number. For * Linux, this will be the build name of the current installed version (ie: * "Bionic", "Xenial", etc). * * @thread_safety This call is thread safe. */ virtual const char* getCodeName_abi() noexcept = 0; /** Retrieves the operating system's kernel version as a string. * * @returns A string containing the OS's kernel version information. There is no standard * layout for a kernel version across platforms so this isn't split up into a * struct of numeric values. For example, Linux kernel versions often contain * major-minor-hotfix-build_number-string components whereas Mac OS is typically * just major-minor-hotfix. Windows kernel versions are also often four values. * This is strictly for informational purposes. Splitting this up into numerical * components is left as an exercise for the caller if needed. */ virtual const char* getKernelVersion_abi() noexcept = 0; }; } // namespace platforminfo } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IOsInfo.gen.h" /** @copydoc omni::platforminfo::IOsInfo_abi */ class omni::platforminfo::IOsInfo : public omni::core::Generated<omni::platforminfo::IOsInfo_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IOsInfo.gen.h"
6,825
C
38.686046
111
0.669744
omniverse-code/kit/include/omni/platforminfo/IDisplayInfo.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Interface to collect and retrieve information about displays attached to the system. Each * display is a viewport onto the desktop's virtual screen space and has an origin and size. * Most displays are capable of switching between several modes. A mode is a combination of * a viewport resolution (width, height, and color depth), and refresh rate. Display info * may be collected using this interface, but it does not handle making changes to the current * mode for any given display. */ template <> class omni::core::Generated<omni::platforminfo::IDisplayInfo_abi> : public omni::platforminfo::IDisplayInfo_abi { public: OMNI_PLUGIN_INTERFACE("omni::platforminfo::IDisplayInfo") /** Retrieves the total number of displays connected to the system. * * @returns The total number of displays connected to the system. This typically includes * displays that are currently turned off. Note that the return value here is * volatile and may change at any point due to user action (either in the OS or * by unplugging or connecting a display). This value should not be cached for * extended periods of time. * * @thread_safety This call is thread safe. */ size_t getDisplayCount() noexcept; /** Retrieves information about a single connected display. * * @param[in] displayIndex The zero based index of the display to retrieve the information * for. This call will fail if the index is out of the range of * the number of connected displays, thus it is not necessary to * IDisplayInfo::getDisplayCount() to enumerate display information * in a counted loop. * @param[out] infoOut Receives the information for the requested display. This may * not be `nullptr`. This returned information may change at any * time due to user action and should therefore not be cached. * @returns `true` if the information for the requested display is successfully retrieved. * Returns `false` if the @p displayIndex index was out of the range of connected * display devices or the information could not be retrieved for any reason. * * @thread_safety This call is thread safe. */ bool getDisplayInfo(size_t displayIndex, omni::platforminfo::DisplayInfo* infoOut) noexcept; /** Retrieves the total number of display modes for a given display. * * @param[in] display The display to retrieve the mode count for. This may not be * `nullptr`. This must have been retrieved from a recent call to * IDisplayInfo::getDisplayInfo(). * @returns The total number of display modes supported by the requested display. Returns * 0 if the mode count information could not be retrieved. A connected valid * display will always support at least one mode. * * @thread_safety This call is thread safe. */ size_t getModeCount(const omni::platforminfo::DisplayInfo* display) noexcept; /** Retrieves the information for a single display mode for a given display. * * @param[in] display The display to retrieve the mode count for. This may not be * `nullptr`. This must have been retrieved from a recent call to * IDisplayInfo::getDisplayInfo(). * @param[in] modeIndex The zero based index of the mode to retrieve for the given * display. This make also be @ref kModeIndexCurrent to retrieve the * information for the given display's current mode. This call will * simply fail if this index is out of range of the number of modes * supported by the given display, thus it is not necessary to call * IDisplayInfo::getModeCount() to use in a counted loop. * @param[out] infoOut Receives the information for the requested mode of the given * display. This may not be `nullptr`. * @returns `true` if the information for the requested mode is successfully retrieved. * Returns `false` if the given index was out of range of the number of modes * supported by the given display or the mode's information could not be retrieved * for any reason. * * @thread_safety This call is thread safe. */ bool getModeInfo(const omni::platforminfo::DisplayInfo* display, omni::platforminfo::ModeIndex modeIndex, omni::platforminfo::ModeInfo* infoOut) noexcept; /** Retrieves the total virtual screen size that all connected displays cover. * * @param[out] origin Receives the coordinates of the origin of the rectangle that the * virtual screen covers. This may be `nullptr` if the origin point * is not needed. * @param[out] size Receives the width and height of the rectangle that the virtual * screen covers. This may be `nullptr` if the size is not needed. * @returns `true` if either the origin, size, or both origin and size of the virtual * screen are retrieved successfully. Returns `false` if the size of the virtual * screen could not be retrieved or both @p origin and @p size are `nullptr`. * * @remarks This retrieves the total virtual screen size for the system. This is the * union of the rectangles that all connected displays cover. Note that this * will also include any empty space between or around displays that is not * covered by another display. * * @thread_safety This call is thread safe. */ bool getTotalDisplaySize(carb::Int2* origin, carb::Int2* size) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline size_t omni::core::Generated<omni::platforminfo::IDisplayInfo_abi>::getDisplayCount() noexcept { return getDisplayCount_abi(); } inline bool omni::core::Generated<omni::platforminfo::IDisplayInfo_abi>::getDisplayInfo( size_t displayIndex, omni::platforminfo::DisplayInfo* infoOut) noexcept { return getDisplayInfo_abi(displayIndex, infoOut); } inline size_t omni::core::Generated<omni::platforminfo::IDisplayInfo_abi>::getModeCount( const omni::platforminfo::DisplayInfo* display) noexcept { return getModeCount_abi(display); } inline bool omni::core::Generated<omni::platforminfo::IDisplayInfo_abi>::getModeInfo( const omni::platforminfo::DisplayInfo* display, omni::platforminfo::ModeIndex modeIndex, omni::platforminfo::ModeInfo* infoOut) noexcept { return getModeInfo_abi(display, modeIndex, infoOut); } inline bool omni::core::Generated<omni::platforminfo::IDisplayInfo_abi>::getTotalDisplaySize(carb::Int2* origin, carb::Int2* size) noexcept { return getTotalDisplaySize_abi(origin, size); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL static_assert(std::is_standard_layout<omni::platforminfo::ModeInfo>::value, "omni::platforminfo::ModeInfo must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::platforminfo::DisplayInfo>::value, "omni::platforminfo::DisplayInfo must be standard layout to be used in ONI ABI");
8,583
C
49.19883
119
0.655831
omniverse-code/kit/include/omni/platforminfo/IOsInfo2.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. // /** @file * @brief Helper interface to retrieve operating system info. */ #pragma once #include "IOsInfo.h" namespace omni { /** Platform and operating system info namespace. */ namespace platforminfo { /** Forward declaration of the IOSInfo2 API object. */ class IOsInfo2; /** Extended interface to collect and retrieve more information about the operating system. * This inherits from omni::platforminfo::IOsInfo and also provides all of its functionality. */ class IOsInfo2_abi : public omni::core::Inherits<omni::platforminfo::IOsInfo, OMNI_TYPE_ID("omni.platforminfo.IOsInfo2")> { protected: /** [Windows] Tests whether this process is running under compatibility mode. * * @returns `true` if this process is running in compatibility mode for an older version * of Windows. Returns `false` otherwise. Returns `false` on all non-Windows * platforms. * * @remarks Windows 10 and up allow a way for apps to run in 'compatibility mode'. This * causes many of the OS version functions to return values that represent an * older version of windows (ie: Win8.1 and earlier) instead of the actual version * information. This can allow some apps that don't fully support Win10 and up to * start properly. */ virtual bool isCompatibilityModeEnabled_abi() noexcept = 0; }; } // namespace platforminfo } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IOsInfo2.gen.h" /** @copydoc omni::platforminfo::IOsInfo2_abi */ class omni::platforminfo::IOsInfo2 : public omni::core::Generated<omni::platforminfo::IOsInfo2_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IOsInfo2.gen.h"
2,182
C
34.786885
121
0.718607
omniverse-code/kit/include/omni/platforminfo/IOsInfo.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Interface to collect and retrieve information about the operating system. */ template <> class omni::core::Generated<omni::platforminfo::IOsInfo_abi> : public omni::platforminfo::IOsInfo_abi { public: OMNI_PLUGIN_INTERFACE("omni::platforminfo::IOsInfo") /** Retrieves the processor architecture for this platform. * * @returns An architecture name. This will never be * @ref omni::platforminfo::Architecture::eUnknown. * * @thread_safety This call is thread safe. */ omni::platforminfo::Architecture getArchitecture() noexcept; /** Retrieves an identifier for the current platform. * * @returns An operating system name. This will never be * @ref omni::platforminfo::Os::eUnknown. * * @thread_safety This call is thread safe. */ omni::platforminfo::Os getOs() noexcept; /** Retrieves the OS version information. * * @returns The operating system version numbers. These will be retrieved from the system * as directly as possible. If possible, these will not be parsed from a string * version of the operating system's name. * * @thread_safety This call is thread safe. */ omni::platforminfo::OsVersion getOsVersion() noexcept; /** Retrieves the name and version information for the system compositor. * * @returns An object describing the active compositor. * * @thread_safety This call is thread safe. */ omni::platforminfo::CompositorInfo getCompositorInfo() noexcept; /** Retrieves the friendly printable name of the operating system. * * @returns A string describing the operating system. This is retrieved from the system and * does not necessarily follow any specific formatting. This may or may not contain * specific version information. This string is intended for display to users. * * @thread_safety This call is thread safe. */ const char* getPrettyName() noexcept; /** Retrieves the name of the operating system. * * @returns A string describing the operating system. This is retrieved from the system if * possible and does not necessarily follow any specific formatting. This may * include different information than the 'pretty' name (though still identifying * the same operating system version). This string is more intended for logging * or parsing purposes than display to the user. * * @thread_safety This call is thread safe. */ const char* getName() noexcept; /** Retrieves the operating system distribution name. * * @returns The operating system distribution name. For Windows 10 and up, this often * contains the build's version name (ie: v1909). For Linux, this contains the * distro name (ie: "Ubuntu", "Gentoo", etc). * * @thread_safety This call is thread safe. */ const char* getDistroName() noexcept; /** Retrieves the operating system's build code name. * * @returns The code name of the operating system's current version. For Windows 10 and up, * this is the Microsoft internal code name for each release (ie: "RedStone 5", * "21H2", etc). If possible it will be retrieved from the system. If not * available, a best guess will be made based on the build version number. For * Linux, this will be the build name of the current installed version (ie: * "Bionic", "Xenial", etc). * * @thread_safety This call is thread safe. */ const char* getCodeName() noexcept; /** Retrieves the operating system's kernel version as a string. * * @returns A string containing the OS's kernel version information. There is no standard * layout for a kernel version across platforms so this isn't split up into a * struct of numeric values. For example, Linux kernel versions often contain * major-minor-hotfix-build_number-string components whereas Mac OS is typically * just major-minor-hotfix. Windows kernel versions are also often four values. * This is strictly for informational purposes. Splitting this up into numerical * components is left as an exercise for the caller if needed. */ const char* getKernelVersion() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline omni::platforminfo::Architecture omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getArchitecture() noexcept { return getArchitecture_abi(); } inline omni::platforminfo::Os omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getOs() noexcept { return getOs_abi(); } inline omni::platforminfo::OsVersion omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getOsVersion() noexcept { return getOsVersion_abi(); } inline omni::platforminfo::CompositorInfo omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getCompositorInfo() noexcept { return getCompositorInfo_abi(); } inline const char* omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getPrettyName() noexcept { return getPrettyName_abi(); } inline const char* omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getName() noexcept { return getName_abi(); } inline const char* omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getDistroName() noexcept { return getDistroName_abi(); } inline const char* omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getCodeName() noexcept { return getCodeName_abi(); } inline const char* omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getKernelVersion() noexcept { return getKernelVersion_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL static_assert(std::is_standard_layout<omni::platforminfo::OsVersion>::value, "omni::platforminfo::OsVersion must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::platforminfo::CompositorInfo>::value, "omni::platforminfo::CompositorInfo must be standard layout to be used in ONI ABI");
7,117
C
37.475675
126
0.682872
omniverse-code/kit/include/omni/platforminfo/IMemoryInfo.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Interface to collect and retrieve information about memory installed in the system. */ template <> class omni::core::Generated<omni::platforminfo::IMemoryInfo_abi> : public omni::platforminfo::IMemoryInfo_abi { public: OMNI_PLUGIN_INTERFACE("omni::platforminfo::IMemoryInfo") /** Retrieves the total installed physical RAM in the system. * * @returns The number of bytes of physical RAM installed in the system. This value will * not change during the lifetime of the calling process. * * @thread_safety This call is thread safe. */ size_t getTotalPhysicalMemory() noexcept; /** Retrieves the available physical memory in the system. * * @returns The number of bytes of physical RAM that is currently available for use by the * operating system. Note that this is not a measure of how much memory is * available to the calling process, but rather for the entire system. * * @thread_safety This call is thread safe. However, two consecutive or concurrent calls * are unlikely to return the same value. */ size_t getAvailablePhysicalMemory() noexcept; /** Retrieves the total page file space in the system. * * @returns The number of bytes of page file space in the system. The value will not * change during the lifetime of the calling process. * * @thread_safety This call is thread safe. */ size_t getTotalPageFileMemory() noexcept; /** Retrieves the available page file space in the system. * * @returns The number of bytes of page file space that is currently available for use * by the operating system. * * @thread_safety This call is thread safe. However, two consecutive or concurrent calls * are unlikely to return the same value. */ size_t getAvailablePageFileMemory() noexcept; /** Retrieves the total memory usage for the calling process. * * @returns The number of bytes of memory used by the calling process. This will not * necessarily be the amount of the process's virtual memory space that is * currently in use, but rather the amount of memory that the OS currently * has wired for this process (ie: the process's working set memory). It is * possible that the process could have a lot more memory allocated, just * inactive as far as the OS is concerned. * * @thread_safety This call is thread safe. However, two consecutive calls are unlikely * to return the same value. */ size_t getProcessMemoryUsage() noexcept; /** Retrieves the peak memory usage of the calling process. * * @returns The maximum number of bytes of memory used by the calling process. This will * not necessarily be the maximum amount of the process's virtual memory space that * was ever allocated, but rather the maximum amount of memory that the OS ever had * wired for the process (ie: the process's working set memory). It is possible * that the process could have had a lot more memory allocated, just inactive as * far as the OS is concerned. */ size_t getProcessPeakMemoryUsage() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getTotalPhysicalMemory() noexcept { return getTotalPhysicalMemory_abi(); } inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getAvailablePhysicalMemory() noexcept { return getAvailablePhysicalMemory_abi(); } inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getTotalPageFileMemory() noexcept { return getTotalPageFileMemory_abi(); } inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getAvailablePageFileMemory() noexcept { return getAvailablePageFileMemory_abi(); } inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getProcessMemoryUsage() noexcept { return getProcessMemoryUsage_abi(); } inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getProcessPeakMemoryUsage() noexcept { return getProcessPeakMemoryUsage_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
5,280
C
37.547445
111
0.693182
omniverse-code/kit/include/omni/platforminfo/ICpuInfo.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Interface to collect information about the CPUs installed in the calling system. This * can provide some basic information about the CPU(s) and get access to features that are * supported by them. */ template <> class omni::core::Generated<omni::platforminfo::ICpuInfo_abi> : public omni::platforminfo::ICpuInfo_abi { public: OMNI_PLUGIN_INTERFACE("omni::platforminfo::ICpuInfo") /** Retrieves the total number of CPU packages installed on the system. * * @returns The total number of CPU packages installed in the system. A CPU package * is a single physical CPU chip that is connected to a physical socket on * the motherboard. * * @remarks A system may have multiple CPUs installed if the motherboard supports it. * At least in the Intel (and compatible) case, there are some restrictions * to doing this - all CPUs must be in the same family, share the same core * count, feature set, and bus speed. Outside of that, the CPUs do not need * to be identical. * * @thread_safety This call is thread safe. */ size_t getCpuPackageCount() noexcept; /** Retrieves the total number of physical cores across all CPUs in the system. * * @returns The total number of physical cores across all CPUs in the system. This includes * the sum of all physical cores on all CPU packages. This will not be zero. * * @thread_safety This call is thread safe. */ size_t getTotalPhysicalCoreCount() noexcept; /** Retrieves the total number of logical cores across all CPUs in the system. * * @returns The total number of logical cores across all CPUs in the system. This includes * the sum of all logical cores on all CPU packages. * * @thread_safety This call is thread safe. */ size_t getTotalLogicalCoreCount() noexcept; /** Retrieves the number of physical cores per CPU package in the system. * * @returns The total number of physical cores per CPU package. Since all CPU packages * must have the same core counts, this is a common value to all packages. * * @thread_safety This call is thread safe. */ size_t getPhysicalCoresPerPackage() noexcept; /** Retrieves the number of logical cores per CPU package in the system. * * @returns The total number of logical cores per CPU package. Since all CPU packages * must have the same core counts, this is a common value to all packages. * * @thread_safety This call is thread safe. */ size_t getLogicalCoresPerPackage() noexcept; /** Checks if a requested feature is supported by the CPU(s) in the system. * * @returns `true` if the requested feature is supported. Returns `false` otherwise. * * @remarks See @ref omni::platforminfo::CpuFeature for more information on the features * that can be queried. * * @thread_safety This call is thread safe. */ bool isFeatureSupported(omni::platforminfo::CpuFeature feature) noexcept; /** Retrieves the friendly name of a CPU in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the name * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The friendly name of the requested CPU package. This string should be suitable * for display to the user. This will contain a rough outline of the processor * model and architecture. It may or may not contain the clock speed. * * @thread_safety This call is thread safe. */ const char* getPrettyName(size_t cpuIndex) noexcept; /** Retrieves the identifier of a CPU in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the identifier * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The identifier string of the requested CPU package. This string should be * suitable for display to the user. This will contain information about the * processor family, vendor, and architecture. * * @thread_safety This call is thread safe. */ const char* getIdentifier(size_t cpuIndex) noexcept; /** Retrieves the vendor string for a CPU package in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the vendor * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The name of the vendor as reported by the CPU itself. This may be something * along the lines of "GenuineIntel" or "AuthenticAMD" for x86_64 architectures, * or the name of the CPU implementer for ARM architectures. * * @thread_safety This call is thread safe. */ const char* getVendor(size_t cpuIndex) noexcept; /** Note: the mask may be 0 if out of range of 64 bits. */ /** Retrieves a bit mask for the processor cores in a CPU package in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the identifier * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns A mask identifying which CPU cores the given CPU covers. A set bit indicates * a core that belongs to the given CPU. A 0 bit indicates either a core from * another package or a non-existent core. This may also be 0 if more than 64 * cores are present in the system or they are out of range of a single 64-bit * value. * * @thread_safety This call is thread safe. */ uint64_t getProcessorMask(size_t cpuIndex) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline size_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getCpuPackageCount() noexcept { return getCpuPackageCount_abi(); } inline size_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getTotalPhysicalCoreCount() noexcept { return getTotalPhysicalCoreCount_abi(); } inline size_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getTotalLogicalCoreCount() noexcept { return getTotalLogicalCoreCount_abi(); } inline size_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getPhysicalCoresPerPackage() noexcept { return getPhysicalCoresPerPackage_abi(); } inline size_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getLogicalCoresPerPackage() noexcept { return getLogicalCoresPerPackage_abi(); } inline bool omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::isFeatureSupported( omni::platforminfo::CpuFeature feature) noexcept { return isFeatureSupported_abi(feature); } inline const char* omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getPrettyName(size_t cpuIndex) noexcept { return getPrettyName_abi(cpuIndex); } inline const char* omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getIdentifier(size_t cpuIndex) noexcept { return getIdentifier_abi(cpuIndex); } inline const char* omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getVendor(size_t cpuIndex) noexcept { return getVendor_abi(cpuIndex); } inline uint64_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getProcessorMask(size_t cpuIndex) noexcept { return getProcessorMask_abi(cpuIndex); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
8,724
C
39.581395
115
0.672054
omniverse-code/kit/include/omni/platforminfo/ICpuInfo.h
// Copyright (c) 2021-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 Helper interface to retrieve CPU info. */ #pragma once #include "../core/IObject.h" namespace omni { /** Platform and operating system info namespace. */ namespace platforminfo { /** Forward declaration of the API layer. */ class ICpuInfo; /** CPU feature names. Each feature name is used with ICpuInfo::isFeatureSupported() to * determine if the requested CPU running on the calling system supports the feature. * These feature flags mostly focus on the availability of specific instructions sets * on the host CPU. */ enum class OMNI_ATTR("prefix=e") CpuFeature { /** Intel specific features. These names are largely labeled to match the mnemonics * used in the Intel Instruction Set Programming Reference document from Intel. For * the most part, only the casing differs and '-' has been converted to an underscore. * * @note Many of these features originated with Intel hardware and therefore have * 'X86' in their name. However, many of these features are or can also be * supported on AMD CPUs. If an AMD CPU is detected, these feature names could * still be valid and the related instructions usable. * * @{ */ eX86Sse, ///< Intel SSE instructions are supported. eX86Sse2, ///< Intel SSE2 instructions are supported. eX86Sse3, ///< Intel SSE3 instructions are supported. eX86Ssse3, ///< Intel supplementary SSE3 instructions are supported. eX86Fma, ///< Fused multiply-add SIMD operations are supported. eX86Sse41, ///< Intel SSE4.1 instructions are supported. eX86Sse42, ///< Intel SSE4.2 instructions are supported. eX86Avx, ///< Intel AVX instructions are supported. eX86F16c, ///< 16-bit floating point conversion instructions are supported. eX86Popcnt, ///< Instruction for counting set bits are supported. eX86Tsc, ///< The `RDTSC` instruction is supported. eX86Mmx, ///< Intel MMX instructions are supported. eX86Avx2, ///< Intel AVX2 instructions are supported. eX86Avx512F, ///< The AVX-512 foundation instructions are supported. eX86Avx512Dq, ///< The AVX-512 double and quad word instructions are supported. eX86Avx512Ifma, ///< The AVX-512 integer fused multiply-add instructions are supported. eX86Avx512Pf, ///< The AVX-512 prefetch instructions are supported. eX86Avx512Er, ///< The AVX-512 exponential and reciprocal instructions are supported. eX86Avx512Cd, ///< The AVX-512 conflict detection instructions are supported. eX86Avx512Bw, ///< The AVX-512 byte and word instructions are supported. eX86Avx512Vl, ///< The AVX-512 vector length extensions instructions are supported. eX86Avx512_Vbmi, ///< The AVX-512 vector byte manipulation instructions are supported. eX86Avx512_Vbmi2, ///< The AVX-512 vector byte manipulation 2 instructions are supported. eX86Avx512_Vnni, ///< The AVX-512 vector neural network instructions are supported. eX86Avx512_Bitalg, ///< The AVX-512 bit algorithms instructions are supported. eX86Avx512_Vpopcntdq, ///< The AVX-512 vector population count instructions are supported. eX86Avx512_4Vnniw, ///< The AVX-512 word vector neural network instructions are supported. eX86Avx512_4fmaps, ///< The AVX-512 packed single fused multiply-add instructions are supported. eX86Avx512_Vp2intersect, ///< The AVX-512 vector pair intersection instructions are supported. eX86AvxVnni, ///< The AVX VEX-encoded versions of the neural network instructions are supported. eX86Avx512_Bf16, ///< The AVX-512 16-bit floating point vector NN instructions are supported. /** @} */ /** AMD specific features. * @{ */ eAmd3DNow, ///< The AMD 3DNow! instruction set is supported. eAmd3DNowExt, ///< The AMD 3DNow! extensions instruction set is supported. eAmdMmxExt, ///< The AMD MMX extensions instruction set is supported. /** @} */ /** ARM specific features: * @{ */ eArmAsimd, ///< The advanced SIMD instructions are supported. eArmNeon, ///< The ARM Neon instruction set is supported. eArmAtomics, ///< The ARMv8 atomic instructions are supported. eArmSha, ///< The SHA1 and SHA2 instruction sets are supported. eArmCrypto, ///< The ARM AES instructions are supported. eArmCrc32, ///< The ARM CRC32 instructions are supported. /** @} */ eFeatureCount, /// Total number of features. Not a valid feature name. }; /** Interface to collect information about the CPUs installed in the calling system. This * can provide some basic information about the CPU(s) and get access to features that are * supported by them. */ class ICpuInfo_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.platforminfo.ICpuInfo")> { protected: /** Retrieves the total number of CPU packages installed on the system. * * @returns The total number of CPU packages installed in the system. A CPU package * is a single physical CPU chip that is connected to a physical socket on * the motherboard. * * @remarks A system may have multiple CPUs installed if the motherboard supports it. * At least in the Intel (and compatible) case, there are some restrictions * to doing this - all CPUs must be in the same family, share the same core * count, feature set, and bus speed. Outside of that, the CPUs do not need * to be identical. * * @thread_safety This call is thread safe. */ virtual size_t getCpuPackageCount_abi() noexcept = 0; /** Retrieves the total number of physical cores across all CPUs in the system. * * @returns The total number of physical cores across all CPUs in the system. This includes * the sum of all physical cores on all CPU packages. This will not be zero. * * @thread_safety This call is thread safe. */ virtual size_t getTotalPhysicalCoreCount_abi() noexcept = 0; /** Retrieves the total number of logical cores across all CPUs in the system. * * @returns The total number of logical cores across all CPUs in the system. This includes * the sum of all logical cores on all CPU packages. * * @thread_safety This call is thread safe. */ virtual size_t getTotalLogicalCoreCount_abi() noexcept = 0; /** Retrieves the number of physical cores per CPU package in the system. * * @returns The total number of physical cores per CPU package. Since all CPU packages * must have the same core counts, this is a common value to all packages. * * @thread_safety This call is thread safe. */ virtual size_t getPhysicalCoresPerPackage_abi() noexcept = 0; /** Retrieves the number of logical cores per CPU package in the system. * * @returns The total number of logical cores per CPU package. Since all CPU packages * must have the same core counts, this is a common value to all packages. * * @thread_safety This call is thread safe. */ virtual size_t getLogicalCoresPerPackage_abi() noexcept = 0; /** Checks if a requested feature is supported by the CPU(s) in the system. * * @returns `true` if the requested feature is supported. Returns `false` otherwise. * * @remarks See @ref omni::platforminfo::CpuFeature for more information on the features * that can be queried. * * @thread_safety This call is thread safe. */ virtual bool isFeatureSupported_abi(CpuFeature feature) noexcept = 0; /** Retrieves the friendly name of a CPU in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the name * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The friendly name of the requested CPU package. This string should be suitable * for display to the user. This will contain a rough outline of the processor * model and architecture. It may or may not contain the clock speed. * * @thread_safety This call is thread safe. */ virtual const char* getPrettyName_abi(size_t cpuIndex) noexcept = 0; /** Retrieves the identifier of a CPU in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the identifier * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The identifier string of the requested CPU package. This string should be * suitable for display to the user. This will contain information about the * processor family, vendor, and architecture. * * @thread_safety This call is thread safe. */ virtual const char* getIdentifier_abi(size_t cpuIndex) noexcept = 0; /** Retrieves the vendor string for a CPU package in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the vendor * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The name of the vendor as reported by the CPU itself. This may be something * along the lines of "GenuineIntel" or "AuthenticAMD" for x86_64 architectures, * or the name of the CPU implementer for ARM architectures. * * @thread_safety This call is thread safe. */ virtual const char* getVendor_abi(size_t cpuIndex) noexcept = 0; /** Note: the mask may be 0 if out of range of 64 bits. */ /** Retrieves a bit mask for the processor cores in a CPU package in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the identifier * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns A mask identifying which CPU cores the given CPU covers. A set bit indicates * a core that belongs to the given CPU. A 0 bit indicates either a core from * another package or a non-existent core. This may also be 0 if more than 64 * cores are present in the system or they are out of range of a single 64-bit * value. * * @thread_safety This call is thread safe. */ virtual uint64_t getProcessorMask_abi(size_t cpuIndex) noexcept = 0; }; } // namespace platforminfo } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "ICpuInfo.gen.h" /** @copydoc omni::platforminfo::ICpuInfo_abi */ class omni::platforminfo::ICpuInfo : public omni::core::Generated<omni::platforminfo::ICpuInfo_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "ICpuInfo.gen.h"
11,529
C
47.445378
113
0.673432
omniverse-code/kit/include/omni/platforminfo/IMemoryInfo.h
// Copyright (c) 2021-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 Helper interface to retrieve memory info. */ #pragma once #include "../core/IObject.h" namespace omni { /** Platform and operating system info namespace. */ namespace platforminfo { /** Forward declaration of the IMemoryInfo API object. */ class IMemoryInfo; /** Interface to collect and retrieve information about memory installed in the system. */ class IMemoryInfo_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.platforminfo.IMemoryInfo")> { protected: /** Retrieves the total installed physical RAM in the system. * * @returns The number of bytes of physical RAM installed in the system. This value will * not change during the lifetime of the calling process. * * @thread_safety This call is thread safe. */ virtual size_t getTotalPhysicalMemory_abi() noexcept = 0; /** Retrieves the available physical memory in the system. * * @returns The number of bytes of physical RAM that is currently available for use by the * operating system. Note that this is not a measure of how much memory is * available to the calling process, but rather for the entire system. * * @thread_safety This call is thread safe. However, two consecutive or concurrent calls * are unlikely to return the same value. */ virtual size_t getAvailablePhysicalMemory_abi() noexcept = 0; /** Retrieves the total page file space in the system. * * @returns The number of bytes of page file space in the system. The value will not * change during the lifetime of the calling process. * * @thread_safety This call is thread safe. */ virtual size_t getTotalPageFileMemory_abi() noexcept = 0; /** Retrieves the available page file space in the system. * * @returns The number of bytes of page file space that is currently available for use * by the operating system. * * @thread_safety This call is thread safe. However, two consecutive or concurrent calls * are unlikely to return the same value. */ virtual size_t getAvailablePageFileMemory_abi() noexcept = 0; /** Retrieves the total memory usage for the calling process. * * @returns The number of bytes of memory used by the calling process. This will not * necessarily be the amount of the process's virtual memory space that is * currently in use, but rather the amount of memory that the OS currently * has wired for this process (ie: the process's working set memory). It is * possible that the process could have a lot more memory allocated, just * inactive as far as the OS is concerned. * * @thread_safety This call is thread safe. However, two consecutive calls are unlikely * to return the same value. */ virtual size_t getProcessMemoryUsage_abi() noexcept = 0; /** Retrieves the peak memory usage of the calling process. * * @returns The maximum number of bytes of memory used by the calling process. This will * not necessarily be the maximum amount of the process's virtual memory space that * was ever allocated, but rather the maximum amount of memory that the OS ever had * wired for the process (ie: the process's working set memory). It is possible * that the process could have had a lot more memory allocated, just inactive as * far as the OS is concerned. */ virtual size_t getProcessPeakMemoryUsage_abi() noexcept = 0; }; } // namespace platforminfo } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IMemoryInfo.gen.h" /** @copydoc omni::platforminfo::IMemoryInfo_abi */ class omni::platforminfo::IMemoryInfo : public omni::core::Generated<omni::platforminfo::IMemoryInfo_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IMemoryInfo.gen.h"
4,517
C
40.833333
119
0.680097
omniverse-code/kit/include/omni/platforminfo/IOsInfo2.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/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Extended interface to collect and retrieve more information about the operating system. * This inherits from omni::platforminfo::IOsInfo and also provides all of its functionality. */ template <> class omni::core::Generated<omni::platforminfo::IOsInfo2_abi> : public omni::platforminfo::IOsInfo2_abi { public: OMNI_PLUGIN_INTERFACE("omni::platforminfo::IOsInfo2") /** [Windows] Tests whether this process is running under compatibility mode. * * @returns `true` if this process is running in compatibility mode for an older version * of Windows. Returns `false` otherwise. Returns `false` on all non-Windows * platforms. * * @remarks Windows 10 and up allow a way for apps to run in 'compatibility mode'. This * causes many of the OS version functions to return values that represent an * older version of windows (ie: Win8.1 and earlier) instead of the actual version * information. This can allow some apps that don't fully support Win10 and up to * start properly. */ bool isCompatibilityModeEnabled() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<omni::platforminfo::IOsInfo2_abi>::isCompatibilityModeEnabled() noexcept { return isCompatibilityModeEnabled_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
2,245
C
34.093749
106
0.714922
omniverse-code/kit/include/omni/platforminfo/IDisplayInfo.h
// Copyright (c) 2021-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 Helper interface to retrieve display info. */ #pragma once #include "../../carb/Types.h" #include "../core/IObject.h" namespace omni { /** Platform and operating system info namespace. */ namespace platforminfo { /** Forward declaration of the IDisplayInfo API object. */ class IDisplayInfo; /** Base type for the display information flags. These flags all start with @a fDisplayFlag*. */ using DisplayFlags OMNI_ATTR("flag, prefix=fDisplayFlag") = uint32_t; /** Flag that indicates that the display is the primary one in the system. * * This often means that new windows will open on this display by default or that the main * system menu (ie: Windows' task bar, Linux's or Mac OS's menu bar, etc) will appear on. */ constexpr DisplayFlags fDisplayFlagPrimary = 0x01; /** Base type for the display mode information flags. These flags all start with @a fModeFlag*. */ using ModeFlags OMNI_ATTR("flag, prefix=fModeFlag") = uint32_t; /** Flag to indicate that the screen mode is interlaced. * * An interlaced display will render every other line of the image alternating between even * and odd scanlines each frame. This can result in less flicker at the same refresh rate * as a non-interlaced display, or less data transmission required per frame at a lower * refresh rate. */ constexpr ModeFlags fModeFlagInterlaced = 0x01; /** Flag to indicate that this mode will be stretched. * * When this flag is present, it indicates that the given display mode will be stretched to * to fill the display if it is not natively supported by the hardware. This may result in * scaling artifacts depending on the amount of stretching that is done. */ constexpr ModeFlags fModeFlagStretched = 0x02; /** Flag to indicate that this mode will be centered on the display. * * When this flag is present, it indicates that the given display mode will be centered * on the display if it is not natively supported by the hardware. This will result in * blank bars being used around the edges of the display to fill in unused space. */ constexpr ModeFlags fModeFlagCentered = 0x04; /** Base type for a display mode index. */ using ModeIndex OMNI_ATTR("constant, prefix=kModeIndex") = size_t; /** Special mode index value to get the information for a display's current mode. * * This is accepted by IDisplayInfo::getModeInfo() in the @a modeIndex parameter. */ constexpr ModeIndex kModeIndexCurrent = (ModeIndex)~0ull; /** Possible display orientation names. * * These indicate how the screen is rotated from its native default orientation. The rotation * angle is considered in a clockwise direction. */ enum class OMNI_ATTR("prefix=e") Orientation { eDefault, ///< The natural display orientation for the display. e90, ///< The image is rotated 90 degrees clockwise. e180, ///< The image is rotated 180 degrees clockwise. e270, ///< The image is rotated 270 degrees clockwise. }; /** Contains information about a single display mode. This includes the mode's size in pixels, * bit depth, refresh rate, and orientation. */ struct ModeInfo { carb::Int2 size = {}; ///< Horizontal (x) and vertical (y) size of the screen in pixels. uint32_t bitsPerPixel = 0; ///< Pixel bit depth. Many modern systems will only report 32 bits. uint32_t refreshRate = 0; ///< The refresh rate of the display in Hertz or zero if not applicable. ModeFlags flags = 0; ///< Flags describing the state of the mode. Orientation orientation = Orientation::eDefault; ///< The orientation of the mode. }; /** Contains information about a single display device. This includes the name of the display, * the adapter it is connected to, the virtual coordinates on the desktop where the display's * image maps to, and the current display mode information. */ struct DisplayInfo { /** The name of the display device. This typically maps to a monitor, laptop screen, or other * pixel display device. This name should be suitable for display to a user. */ char OMNI_ATTR("c_str") displayName[128] = {}; /** The system specific identifier of the display device. This is suitable for using with * other platform specific APIs that accept a display device name. */ char OMNI_ATTR("c_str") displayId[128] = {}; /** The name of the graphics adapter the display is connected to. Typically this is the * name of the GPU or other graphics device that the display is connected to. This name * should be suitable for display to a user. */ char OMNI_ATTR("c_str") adapterName[128] = {}; /** The system specific identifier of the graphics adapter device. This is suitable for using * with other platform specific APIs that accept a graphics adapter name. */ char OMNI_ATTR("c_str") adapterId[128] = {}; /** The coordinates of the origin of this display device on the desktop's virtual screen. * In situations where there is only a single display, this will always be (0, 0). It will * be in non-mirrored multi-display setups that this can be used to determine how each * display's viewport is positioned relative to each other. */ carb::Int2 origin = {}; /** The current display mode in use on the display. */ ModeInfo current = {}; /** Flags to indicate additional information about this display. */ DisplayFlags flags = 0; }; /** Interface to collect and retrieve information about displays attached to the system. Each * display is a viewport onto the desktop's virtual screen space and has an origin and size. * Most displays are capable of switching between several modes. A mode is a combination of * a viewport resolution (width, height, and color depth), and refresh rate. Display info * may be collected using this interface, but it does not handle making changes to the current * mode for any given display. */ class IDisplayInfo_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.platforminfo.IDisplayInfo")> { protected: /** Retrieves the total number of displays connected to the system. * * @returns The total number of displays connected to the system. This typically includes * displays that are currently turned off. Note that the return value here is * volatile and may change at any point due to user action (either in the OS or * by unplugging or connecting a display). This value should not be cached for * extended periods of time. * * @thread_safety This call is thread safe. */ virtual size_t getDisplayCount_abi() noexcept = 0; /** Retrieves information about a single connected display. * * @param[in] displayIndex The zero based index of the display to retrieve the information * for. This call will fail if the index is out of the range of * the number of connected displays, thus it is not necessary to * IDisplayInfo::getDisplayCount() to enumerate display information * in a counted loop. * @param[out] infoOut Receives the information for the requested display. This may * not be `nullptr`. This returned information may change at any * time due to user action and should therefore not be cached. * @returns `true` if the information for the requested display is successfully retrieved. * Returns `false` if the @p displayIndex index was out of the range of connected * display devices or the information could not be retrieved for any reason. * * @thread_safety This call is thread safe. */ virtual bool getDisplayInfo_abi(size_t displayIndex, OMNI_ATTR("out, not_null") DisplayInfo* infoOut) noexcept = 0; /** Retrieves the total number of display modes for a given display. * * @param[in] display The display to retrieve the mode count for. This may not be * `nullptr`. This must have been retrieved from a recent call to * IDisplayInfo::getDisplayInfo(). * @returns The total number of display modes supported by the requested display. Returns * 0 if the mode count information could not be retrieved. A connected valid * display will always support at least one mode. * * @thread_safety This call is thread safe. */ virtual size_t getModeCount_abi(OMNI_ATTR("in, not_null") const DisplayInfo* display) noexcept = 0; /** Retrieves the information for a single display mode for a given display. * * @param[in] display The display to retrieve the mode count for. This may not be * `nullptr`. This must have been retrieved from a recent call to * IDisplayInfo::getDisplayInfo(). * @param[in] modeIndex The zero based index of the mode to retrieve for the given * display. This make also be @ref kModeIndexCurrent to retrieve the * information for the given display's current mode. This call will * simply fail if this index is out of range of the number of modes * supported by the given display, thus it is not necessary to call * IDisplayInfo::getModeCount() to use in a counted loop. * @param[out] infoOut Receives the information for the requested mode of the given * display. This may not be `nullptr`. * @returns `true` if the information for the requested mode is successfully retrieved. * Returns `false` if the given index was out of range of the number of modes * supported by the given display or the mode's information could not be retrieved * for any reason. * * @thread_safety This call is thread safe. */ virtual bool getModeInfo_abi(OMNI_ATTR("in, not_null") const DisplayInfo* display, ModeIndex modeIndex, OMNI_ATTR("out, not_null") ModeInfo* infoOut) noexcept = 0; /** Retrieves the total virtual screen size that all connected displays cover. * * @param[out] origin Receives the coordinates of the origin of the rectangle that the * virtual screen covers. This may be `nullptr` if the origin point * is not needed. * @param[out] size Receives the width and height of the rectangle that the virtual * screen covers. This may be `nullptr` if the size is not needed. * @returns `true` if either the origin, size, or both origin and size of the virtual * screen are retrieved successfully. Returns `false` if the size of the virtual * screen could not be retrieved or both @p origin and @p size are `nullptr`. * * @remarks This retrieves the total virtual screen size for the system. This is the * union of the rectangles that all connected displays cover. Note that this * will also include any empty space between or around displays that is not * covered by another display. * * @thread_safety This call is thread safe. */ virtual bool getTotalDisplaySize_abi(OMNI_ATTR("out") carb::Int2* origin, OMNI_ATTR("out") carb::Int2* size) noexcept = 0; }; } // namespace platforminfo } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IDisplayInfo.gen.h" /** @copydoc omni::platforminfo::IDisplayInfo_abi */ class omni::platforminfo::IDisplayInfo : public omni::core::Generated<omni::platforminfo::IDisplayInfo_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IDisplayInfo.gen.h"
12,519
C
48.098039
121
0.672817
omniverse-code/kit/include/omni/resourcemonitor/ResourceMonitorSettings.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 <omni/kit/SettingsUtils.h> #define RESOURCE_MONITOR_SETTING_GROUP_CONTEXT "resourcemonitor" #define RESOURCE_MONITOR_SETTING_TIME_BETWEEN_QUERIES "timeBetweenQueries" #define RESOURCE_MONITOR_SETTING_SEND_DEVICE_MEMORY_WARNING "sendDeviceMemoryWarning" #define RESOURCE_MONITOR_SETTING_DEVICE_MEMORY_WARN_MB "deviceMemoryWarnMB" #define RESOURCE_MONITOR_SETTING_DEVICE_MEMORY_WARN_FRACTION "deviceMemoryWarnFraction" #define RESOURCE_MONITOR_SETTING_SEND_HOST_MEMORY_WARNING "sendHostMemoryWarning" #define RESOURCE_MONITOR_SETTING_HOST_MEMORY_WARN_MB "hostMemoryWarnMB" #define RESOURCE_MONITOR_SETTING_HOST_MEMORY_WARN_FRACTION "hostMemoryWarnFraction" namespace omni { namespace resourcemonitor { constexpr const char* const kSettingTimeBetweenQueries = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_TIME_BETWEEN_QUERIES; constexpr const char* const kSettingSendDeviceMemoryWarning = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_SEND_DEVICE_MEMORY_WARNING; constexpr const char* const kSettingDeviceMemoryWarnMB = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_DEVICE_MEMORY_WARN_MB; constexpr const char* const kSettingDeviceMemoryWarnFraction = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_DEVICE_MEMORY_WARN_FRACTION; constexpr const char* const kSettingSendHostMemoryWarning = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_SEND_HOST_MEMORY_WARNING; constexpr const char* const kSettingHostMemoryWarnMB = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_HOST_MEMORY_WARN_MB; constexpr const char* const kSettingHostMemoryWarnFraction = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_HOST_MEMORY_WARN_FRACTION; } }
2,639
C
44.517241
95
0.817355
omniverse-code/kit/include/omni/resourcemonitor/ResourceMonitorTypes.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 namespace omni { namespace resourcemonitor { enum class ResourceMonitorEventType { eUpdateDeviceMemory, ///! ResourceMonitor has updated information about device memory eUpdateHostMemory, ///! ResourceMonitor has updated information about host memory eLowDeviceMemory, ///! A device's memory has fallen below a specified threshold eLowHostMemory, ///! Host's memory has fallen below a specified threshold }; } }
890
C
31.999999
89
0.77191
omniverse-code/kit/include/omni/resourcemonitor/IResourceMonitor.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/Defines.h> #include <carb/events/IEvents.h> #include <carb/Types.h> namespace omni { namespace resourcemonitor { /** * This interface wraps the wraps the memory queries of the graphics and * GpuFoundation APIs. Clients can subscribe to the resource monitor's * event stream to be notified when memory resources fall below user-specified * thresholds. */ struct IResourceMonitor { CARB_PLUGIN_INTERFACE("omni::resourcemonitor::IResourceMonitor", 1, 0) /** * Call into GpuFoundation's SystemInfo interface and returns available main memory * * @return available main memory (in bytes) */ uint64_t(CARB_ABI* getAvailableHostMemory)(); /** * Call into GpuFoundation's SystemInfo interface and returns total main memory * * @return total main memory (in bytes) */ uint64_t(CARB_ABI* getTotalHostMemory)(); /** * Call into the Graphics API and returns available GPU memory for the * specified device. * * @param deviceIndex Index of the device to query. * * @return available GPU memory for the specified device (in bytes) */ uint64_t(CARB_ABI* getAvailableDeviceMemory)(uint32_t deviceIndex); /** * Call into the Graphics API and returns total GPU memory for the * specified device. * * @param deviceIndex Index of the device to query. * * @return total GPU memory for the specified device (in bytes) */ uint64_t(CARB_ABI* getTotalDeviceMemory)(uint32_t deviceIndex); /** * Get the resource monitor's event stream in order to subscribe to * updates and warnings. * * @return Pointer to resource monitor's event stream */ carb::events::IEventStream*(CARB_ABI* getEventStream)(); }; } // namespace resourcemonitor } // namespace omni
2,283
C
29.453333
87
0.701708
omniverse-code/kit/include/omni/ui/IntField.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 "AbstractField.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The IntField widget is a one-line text editor with a string model. */ class OMNIUI_CLASS_API IntField : public AbstractField { OMNIUI_OBJECT(IntField) protected: /** * @brief Construct IntField */ OMNIUI_API IntField(const std::shared_ptr<AbstractValueModel>& model = {}); private: /** * @brief It's necessary to implement it to convert model to string buffer that is displayed by the field. It's * possible to use it for setting the string format. */ std::string _generateTextForField() override; /** * @brief Set/get the field data and the state on a very low level of the underlying system. */ void _updateSystemText(void*) override; /** * @brief Determines the flags that are used in the underlying system widget. */ int32_t _getSystemFlags() const override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,410
C
28.395833
115
0.714894
omniverse-code/kit/include/omni/ui/TreeView.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 "ItemModelHelper.h" #include <memory> OMNIUI_NAMESPACE_OPEN_SCOPE class AbstractItemModel; class AbstractItemDelegate; /** * @brief TreeView is a widget that presents a hierarchical view of information. Each item can have a number of subitems. * An indentation often visualizes this in a list. An item can be expanded to reveal subitems, if any exist, and * collapsed to hide subitems. * * TreeView can be used in file manager applications, where it allows the user to navigate the file system directories. * They are also used to present hierarchical data, such as the scene object hierarchy. * * TreeView uses a model/view pattern to manage the relationship between data and the way it is presented. The * separation of functionality gives developers greater flexibility to customize the presentation of items and provides * a standard interface to allow a wide range of data sources to be used with other widgets. * * TreeView is responsible for the presentation of model data to the user and processing user input. To allow some * flexibility in the way the data is presented, the creation of the sub-widgets is performed by the delegate. It * provides the ability to customize any sub-item of TreeView. */ class OMNIUI_CLASS_API TreeView : public Widget, public ItemModelHelper { OMNIUI_OBJECT(TreeView) public: OMNIUI_API ~TreeView() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented the method from ItemModelHelper that is called when the model is changed. * * @param item The item in the model that is changed. If it's NULL, the root is chaged. */ OMNIUI_API void onModelUpdated(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item) override; /** * @brief Deselects all selected items. */ OMNIUI_API void clearSelection(); /** * @brief Set current selection. */ OMNIUI_API void setSelection(std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>> items); /** * @brief Switches the selection state of the given item. */ OMNIUI_API void toggleSelection(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Extends the current selection selecting all the items between currently selected nodes and the given item. * It's when user does shift+click. */ OMNIUI_API void extendSelection(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Return the list of selected items. */ OMNIUI_API const std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>>& getSelection(); /** * @brief Set the callback that is called when the selection is changed. */ OMNIUI_CALLBACK(SelectionChanged, void, std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>>); /** * @brief Sets the function that will be called when the user use mouse enter/leave on the item. * function specification is the same as in setItemHovedFn. * void onItemHovered(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item, bool hovered) */ OMNIUI_CALLBACK(HoverChanged, void, std::shared_ptr<const AbstractItemModel::AbstractItem>, bool); /** * @brief Returns true if the given item is expanded. */ OMNIUI_API bool isExpanded(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Sets the given item expanded or collapsed. * * @param item The item to expand or collapse. * @param expanded True if it's necessary to expand, false to collapse. * @param recursive True if it's necessary to expand children. */ OMNIUI_API void setExpanded(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item, bool expanded, bool recursive); /** * @brief When called, it will make the delegate to regenerate all visible widgets the next frame. */ OMNIUI_API void dirtyWidgets(); /** * @brief The Item delegate that generates a widget per item. */ OMNIUI_PROPERTY(std::shared_ptr<AbstractItemDelegate>, delegate, WRITE, setDelegate, PROTECTED, READ, getDelegate, NOTIFY, setDelegateChangedFn); /** * @brief Widths of the columns. If not set, the width is Fraction(1). */ OMNIUI_PROPERTY(std::vector<Length>, columnWidths, READ, getColumnWidths, WRITE, setColumnWidths); /** * @brief When true, the columns can be resized with the mouse. */ OMNIUI_PROPERTY(bool, columnsResizable, DEFAULT, false, READ, isColumnsResizable, WRITE, setColumnsResizable); /** * @brief This property holds if the header is shown or not. */ OMNIUI_PROPERTY(bool, headerVisible, DEFAULT, false, READ, isHeaderVisible, WRITE, setHeaderVisible); /** * @brief This property holds if the root is shown. It can be used to make a single level tree appear like a simple * list. */ OMNIUI_PROPERTY( bool, rootVisible, DEFAULT, true, READ, isRootVisible, WRITE, setRootVisible, NOTIFY, setRootVisibleChangedFn); /** * @brief This flag allows to prevent expanding when the user clicks the plus icon. It's used in the case the user * wants to control how the items expanded or collapsed. */ OMNIUI_PROPERTY(bool, expandOnBranchClick, DEFAULT, true, READ, isExpandOnBranchClick, WRITE, setExpandOnBranchClick); /** * @brief When true, the tree nodes are never destroyed even if they are disappeared from the model. It's useul for * the temporary filtering if it's necessary to display thousands of nodes. */ OMNIUI_PROPERTY(bool, keepAlive, DEFAULT, false, READ, isKeepAlive, WRITE, setKeepAlive); /** * @brief Expand all the nodes and keep them expanded regardless their state. */ OMNIUI_PROPERTY( bool, keepExpanded, DEFAULT, false, READ, isKeepExpanded, WRITE, setKeepExpanded, NOTIFY, setKeepExpandedChangedFn); /** * @brief When true, the tree nodes can be dropped between items. */ OMNIUI_PROPERTY(bool, dropBetweenItems, DEFAULT, false, READ, isDropBetweenItems, WRITE, setDropBetweenItems); /** * @brief The expanded state of the root item. Changing this flag doesn't make the children repopulated. */ OMNIUI_PROPERTY(bool, rootExpanded, DEFAULT, true, READ, isRootExpanded, WRITE, setRootExpanded, PROTECTED, NOTIFY, _setRootExpandedChangedFn); /** * @brief Minimum widths of the columns. If not set, the minimum width is Pixel(0). */ OMNIUI_PROPERTY(std::vector<Length>, minColumnWidths, READ, getMinColumnWidths, WRITE, setMinColumnWidths); protected: /** * @brief Create TreeView with the given model. * * @param model The given model. */ OMNIUI_API TreeView(const std::shared_ptr<AbstractItemModel>& model = {}); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: friend class Inspector; /** * @brief The location of Drag and Drop. * * Specifies where exactly the user droped the item. */ enum class DropLocation : uint8_t { eOver = 0, eAbove, eBelow, eUndefined, }; struct Node { // Child nodes std::vector<std::unique_ptr<Node>> children; // Root level widget per column std::vector<std::shared_ptr<Widget>> widgets; // Branch + widget the user created in the delegate for the inspector std::vector<std::pair<std::shared_ptr<Widget>, std::shared_ptr<Widget>>> widgetsForInspector; // The state of the node. If it's false, then it's necessary to skip all the children. bool expanded = false; // True if it already has correct children. bool childrenPopulated = false; // True if it already has correct widgets. Not populated means it will be reconstructed the next frame. bool widgetsPopulated = false; // Dirty means it it will be reconstructed only if it's visible. bool widgetsDirty = false; // The corresponding item in the model. std::shared_ptr<const AbstractItemModel::AbstractItem> item = nullptr; // The indentation level uint32_t level = 0; // Selection state bool selected = false; // Flag if the widget size was already comuted and it doesn't require to be computed more. We need it to be able // to compute the size only of visible widgets. // This is the flag for _setNodeComputedWidth/_setNodeComputedHeight bool widthComputed = false; bool heightComputed = false; // Cached size of widgets float nodeHeight = 0.0f; // Cached position of widgets float positionOffset = 0.0f; // Indicates that the user drags this node bool dragInProgress = false; // True when the mouse already entered the drag and drop zone of this node and dropAccepted has the valid value. DropLocation dragEntered = DropLocation::eUndefined; // True if the current drag and drop can be accepted by the current model. bool dropAccepted = false; // When keepAlive is true, the nodes are never removed. Instead or removing, TreeView makes active = false and // such nodes are not drawing. bool active = true; // True if mouse hover on this node bool hovered = false; }; /** * @brief Populate the children of the given node. Usually, it's called when the user presses the expand button the * first time. */ void _populateNodeChildren(TreeView::Node* node); /** * @brief Calls _populateNodeChildren in every expanded node. Usually, _populateNodeChildren is called in a draw * cycle. But sometimes it's necessary to call it immediately for example when the model is changed and draw cycle * didn't happen yet. */ void _populateNodeChildrenRecursive(TreeView::Node* node); /** * @brief Populate the widgets of the given node. It's called when the user presses the expand button the first time * and when the node is expanded or collapsed. */ void _populateNodeWidget(TreeView::Node* node); /** * @brief It's only used in Inspector to make sure all the widgets prepopulated */ void _populateNodeWidgetsRecursive(TreeView::Node* node); /** * @brief Populate the widgets of the header. */ void _populateHeader(); /** * @brief Compute width of the header widgets. */ void _setHeaderComputedWidth(); /** * @brief Compute height of the header widgets. */ void _setHeaderComputedHeight(); /** * @brief Recursively draw the widgets of the given node. */ float _drawNodeInTable(const std::unique_ptr<Node>& node, const std::unique_ptr<Node>& parent, uint32_t hoveringColor, uint32_t hoveringBorderColor, uint32_t backgroundColor, uint32_t dropIndicatorColor, uint32_t dropIndicatorBorderColor, float dropIndicatorThickness, float cursorAtBeginTableX, float cursorAtBeginTableY, float currentOffset, bool blockMouse, float elapsedTime); /** * @brief Set computed width of the node and its children. */ void _setNodeComputedWidth(const std::unique_ptr<Node>& node); /** * @brief Set computed height of the node and its children. */ bool _setNodeComputedHeight(const std::unique_ptr<Node>& node, float& offset); /** * @brief Fills m_columnComputedSizes with absolute widths using property columnWidths. */ float _computeColumnWidths(float width); /** * @brief Return the node that corresponds to the given model item. * * This is the internal function that shouldn't be called from outside because it's not guaranteed that the returned * object is valid for the next draw call. */ Node* _getNode(const std::unique_ptr<TreeView::Node>& node, const std::shared_ptr<const AbstractItemModel::AbstractItem>& item) const; /** * @brief Return the node that corresponds to the given model item. * * This is the internal function that shouldn't be called from outside because it's not guaranteed that the returned * object is valid for the next draw call. */ Node* _getNode(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item) const; /** * @brief Fills gived list with the flat list of the nodes. Only expanded nodes are considered. * * @param root The node to start the flat list from. * @param list The list where the noreds are written. */ void _createFlatNodeList(std::unique_ptr<TreeView::Node>& root, std::vector<std::unique_ptr<Node>*>& list) const; /** * @brief Deselects the given node and the children. */ static void _clearNodeSelection(std::unique_ptr<TreeView::Node>& node); /** * @brief Called by TreeView when the selection is changed. It calls callbacks if they exist. */ void _onSelectionChanged(); /** * @brief It is called every frame to check if it's necessary to draw Drag And Drop highlight. Returns true if the * node needs highlight. */ bool _hasAcceptedDrop(const std::unique_ptr<TreeView::Node>& node, const std::unique_ptr<TreeView::Node>& parent, DropLocation dropLocation) const; /** * @brief This function converts the flat drop location (above-below-over) on the table to the tree's location. * * When the user drops an item, he drops it between rows. And we need to know the child index that corresponds to * the parent into which the new rows are inserted. * * @param node The node the user droped something. * @param parent The parent of the node the user droped it. * @param dropLocation Above-below-over position in the table. * @param dropNode Output. The parent node into which the new item should be inserted. * @param dropId Output. The index of child the new item should be inserted. If -1, the new item should be inseted * to the end. */ static void _getDropNode(const TreeView::Node* node, const TreeView::Node* parent, DropLocation dropLocation, TreeView::Node const** dropNode, int32_t& dropId); /** * @brief Sets the given node expanded or collapsed. It immidiatley populates children which is very useful when * doing search in the tree. * * @see TreeView::setExpanded */ void _setExpanded(TreeView::Node* node, bool expanded, bool recursive, bool pouplateChildren = true); /** * @brief Checks both the state of the node and the `keepExpanded` property. */ bool _isExpanded(TreeView::Node* node) const; /** * @brief Makes the widget and his children dirty. Dirty means that whe widget will be regenerated only if the node * is visible. */ void _setWidgetsDirty(TreeView::Node* node, bool dirty, bool recursive) const; /** * @brief Called when the user started dragging the node. It generates drag and drop buffers. */ void _beginDrag(TreeView::Node* node); /** * @brief Called when the user is dragging the node. It draws the widgets the user drags. */ void _drawDrag(float elapsedTime, uint32_t backgroundColor) const; /** * @brief Called when the user droped the node. It cleans up the drag and drop caches. It doesn't send anything to * the model because it's closing _beginDrag. And it will be called even if the user drops it somwhere else. The * code that sends the drop notification is in TreeView::_drawNodeInTable because it should accept drag and drop * from other widgets. */ void _endDrag() const; /** * @brief Calls drop with the model on the given node. * * @param node The node that accepted drop. */ void _dragDropTarget(TreeView::Node* node, TreeView::Node* parent) const; /** * @brief Called by Inspector to inspect all the children. */ std::vector<std::shared_ptr<Widget>> _getChildren(); std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>> _payloadToItems(const void* payload) const; // The main cache of this widget. It has everything that this widget draws including the hirarchy of the nodes and // the widgets they have. std::unique_ptr<Node> m_root; // Cache to quick query item node. std::unordered_map<const AbstractItemModel::AbstractItem*, Node*> m_itemNodeCache; // The cached number of columns. size_t m_columnsCount = 0; // Absolute widths of each column. std::vector<float> m_columnComputedSizes; // Absolute minimum widths of each column. std::vector<float> m_minColumnComputedSizes; // The list of the selected items. Vector because the selection order is important. std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>> m_selection; // Callback when the selection is changed std::function<void(std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>>)> m_selectionChangedFn; // Callback when item hover status is changed std::function<void(std::shared_ptr<const AbstractItemModel::AbstractItem>, bool)> m_hoverChangedFn; // Header widgets std::vector<std::shared_ptr<Frame>> m_headerWidgets; bool m_headerPopulated = false; // When the node is just selected, it used to scroll the tree view to the node. Node* m_scrollHere = nullptr; // Drag and drop caches. mutable std::unique_ptr<char[]> m_dragAndDropPayloadBuffer; mutable size_t m_dragAndDropPayloadBufferSize; mutable std::vector<const Node*> m_dragAndDropNodes; // False when internal Node structures are not synchronized with the model. Nodes are synchronized during the draw // loop. bool m_modelSynchronized = false; // Indicates that at least one node has heightComputed false bool m_contentHeightDirty = true; // Sum of all columns float m_contentWidth = 0.0f; // Height of internal content float m_contentHeight = 0.f; // Relative Y position of visible area float m_relativeRectMin = 0.f; float m_relativeRectMax = 0.f; // The variables to find the average of all the widgets created. We need it to assume the total length of the // TreeView without creating the widgets. float m_sumHeights = 0.f; uint64_t m_numHeights = 0; // If the column is resizing at this moment, it is the id of the right column. When 0, no resize happens. uint32_t m_resizeColumn = 0; // We need it for autoscrolling when drag and drop. Since ImGui rounds pixel, we can only scroll with int values, // and when FPS is very high, it doesn't scroll at all. We accumulate the small scrolling to this variable. float m_accumulatedAutoScroll = 0.0f; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
20,845
C
37.603704
124
0.661166
omniverse-code/kit/include/omni/ui/IntSlider.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 "AbstractSlider.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along * a horizontal groove and translates the handle's position into an integer value within the legal range. */ template <typename T> class OMNIUI_CLASS_API CommonIntSlider : public AbstractSlider { public: /** * @brief Reimplemented the method from ValueModelHelper that is called when the model is changed. */ OMNIUI_API void onModelUpdated() override; /** * @brief This property holds the slider's minimum value. */ OMNIUI_PROPERTY(T, min, DEFAULT, 0, READ, getMin, WRITE, setMin); /** * @brief This property holds the slider's maximum value. */ OMNIUI_PROPERTY(T, max, DEFAULT, 100, READ, getMax, WRITE, setMax); protected: OMNIUI_API CommonIntSlider(const std::shared_ptr<AbstractValueModel>& model = {}); /** * @brief the ration calculation is requiere to draw the Widget as Gauge, it is calculated with Min/Max & Value */ virtual float _getValueRatio() override; private: /** * @brief Reimplemented. _drawContent sets everything up including styles and fonts and calls this method. */ void _drawUnderlyingItem() override; /** * @brief It has to run a very low level function to call the widget. */ virtual bool _drawUnderlyingItem(T* value, T min, T max) = 0; // The cached state of the slider. T m_valueCache; }; /** * @brief The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along * a horizontal groove and translates the handle's position into an integer value within the legal range. */ class OMNIUI_CLASS_API IntSlider : public CommonIntSlider<int64_t> { OMNIUI_OBJECT(IntSlider) protected: /** * @brief Constructs IntSlider * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API IntSlider(const std::shared_ptr<AbstractValueModel>& model = {}) : CommonIntSlider<int64_t>{ model } { } private: /** * @brief Runs a very low level function to call the widget. */ OMNIUI_API virtual bool _drawUnderlyingItem(int64_t* value, int64_t min, int64_t max) override; }; /** * @brief The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along * a horizontal groove and translates the handle's position into an integer value within the legal range. * * The difference with IntSlider is that UIntSlider has unsigned min/max. */ class OMNIUI_CLASS_API UIntSlider : public CommonIntSlider<uint64_t> { OMNIUI_OBJECT(UIntSlider) protected: /** * @brief Constructs UIntSlider * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API UIntSlider(const std::shared_ptr<AbstractValueModel>& model = {}) : CommonIntSlider<uint64_t>{ model } { } private: /** * @brief Runs a very low level function to call the widget. */ OMNIUI_API virtual bool _drawUnderlyingItem(uint64_t* value, uint64_t min, uint64_t max) override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
3,771
C
30.433333
119
0.700875
omniverse-code/kit/include/omni/ui/Workspace.h
// Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // //! @file //! //! @brief omni::ui Workspace #pragma once #include "Api.h" #include "WindowHandle.h" #include <functional> #include <memory> #include <stack> #include <vector> namespace omni { namespace kit { class IAppWindow; } } OMNIUI_NAMESPACE_OPEN_SCOPE namespace windowmanager { class IWindowCallback; } class WindowHandle; class Window; class ToolBar; /** * @brief Workspace object provides access to the windows in Kit. * * TODO: It's more like a namespace because all the methods are static. But the idea is to have it as a singleton, and * it will allow using it as the abstract factory for many systems (Kit full and Kit mini for example). */ class Workspace { public: class AppWindowGuard; /** * @brief Singleton that tracks the current application window. */ class AppWindow { public: OMNIUI_API static AppWindow& instance(); omni::kit::IAppWindow* getCurrent(); private: friend class AppWindowGuard; AppWindow() = default; ~AppWindow() = default; AppWindow(const AppWindow&) = delete; AppWindow& operator=(const AppWindow&) = delete; void push(omni::kit::IAppWindow* window); void pop(); std::stack<omni::kit::IAppWindow*> m_stack; }; /** * @brief Guard that pushes the current application window to class AppWindow when created and pops when destroyed. */ class AppWindowGuard { public: AppWindowGuard(omni::kit::IAppWindow* window); ~AppWindowGuard(); }; Workspace() = delete; /** * @brief Returns current DPI Scale. */ OMNIUI_API static float getDpiScale(); /** * @brief Returns the list of windows ordered from back to front. * * If the window is a Omni::UI window, it can be upcasted. */ OMNIUI_API static std::vector<std::shared_ptr<WindowHandle>> getWindows(); /** * @brief Find Window by name. */ OMNIUI_API static std::shared_ptr<WindowHandle> getWindow(const std::string& title); /** * @brief Find Window by window callback. */ OMNIUI_API static std::shared_ptr<WindowHandle> getWindowFromCallback(const windowmanager::IWindowCallback* callback); /** * @brief Get all the windows that docked with the given widow. */ OMNIUI_API static std::vector<std::shared_ptr<WindowHandle>> getDockedNeighbours(const std::shared_ptr<WindowHandle>& member); /** * @brief Get currently selected window inedx from the given dock id. */ OMNIUI_API static uint32_t getSelectedWindowIndex(uint32_t dockId); /** * @brief Undock all. */ OMNIUI_API static void clear(); /** * @brief Get the width in points of the current main window. */ OMNIUI_API static float getMainWindowWidth(); /** * @brief Get the height in points of the current main window. */ OMNIUI_API static float getMainWindowHeight(); /** * @brief Get all the windows of the given dock ID */ OMNIUI_API static std::vector<std::shared_ptr<WindowHandle>> getDockedWindows(uint32_t dockId); /** * @brief Return the parent Dock Node ID * * @param dockId the child Dock Node ID to get parent */ OMNIUI_API static uint32_t getParentDockId(uint32_t dockId); /** * @brief Get two dock children of the given dock ID. * * @return true if the given dock ID has children * @param dockId the given dock ID * @param first output. the first child dock ID * @param second output. the second child dock ID */ OMNIUI_API static bool getDockNodeChildrenId(uint32_t dockId, uint32_t& first, uint32_t& second); /** * @brief Returns the position of the given dock ID. Left/Right/Top/Bottom */ OMNIUI_API static WindowHandle::DockPosition getDockPosition(uint32_t dockId); /** * @brief Returns the width of the docking node. * * @param dockId the given dock ID */ OMNIUI_API static float getDockIdWidth(uint32_t dockId); /** * @brief Returns the height of the docking node. * * It's different from the window height because it considers dock tab bar. * * @param dockId the given dock ID */ OMNIUI_API static float getDockIdHeight(uint32_t dockId); /** * @brief Set the width of the dock node. * * It also sets the width of parent nodes if necessary and modifies the * width of siblings. * * @param dockId the given dock ID * @param width the given width */ OMNIUI_API static void setDockIdWidth(uint32_t dockId, float width); /** * @brief Set the height of the dock node. * * It also sets the height of parent nodes if necessary and modifies the * height of siblings. * * @param dockId the given dock ID * @param height the given height */ OMNIUI_API static void setDockIdHeight(uint32_t dockId, float height); /** * @brief Makes the window visible or create the window with the callback provided with set_show_window_fn. * * @return true if the window is already created, otherwise it's necessary to wait one frame * @param title the given window title * @param show true to show, false to hide */ OMNIUI_API static bool showWindow(const std::string& title, bool show = true); /** * @brief Addd the callback that is triggered when a new window is created */ OMNIUI_API static void setWindowCreatedCallback( std::function<void(const std::shared_ptr<WindowHandle>& window)> windowCreatedCallbackFn); /** * @brief Add the callback to create a window with the given title. When the callback's argument is true, it's * necessary to create the window. Otherwise remove. */ OMNIUI_API static void setShowWindowFn(const std::string& title, std::function<void(bool)> showWindowFn); /** * @brief Add the callback that is triggered when a window's visibility changed */ OMNIUI_API static uint32_t setWindowVisibilityChangedCallback(std::function<void(const std::string& title, bool visible)> windowVisibilityChangedCallbackFn); /** * @brief Remove the callback that is triggered when a window's visibility changed */ OMNIUI_API static void removeWindowVisibilityChangedCallback(uint32_t id); /** * @brief Call it from inside each windows' setVisibilityChangedFn to triggered VisibilityChangedCallback. */ OMNIUI_API static void onWindowVisibilityChanged(const std::string& title, bool visible); private: friend class Window; friend class ToolBar; /** * @brief Register Window, so it's possible to return it in getWindows. It's called by Window creator. */ OMNIUI_API static void RegisterWindow(const std::shared_ptr<Window>& window); /** * @brief Deregister window. It's called by Window destructor. */ OMNIUI_API static void OmitWindow(const Window* window); /** * @brief * */ static std::vector<std::shared_ptr<WindowHandle>> _getWindows(const void* windowsStorage, bool considerRegistered = false); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
7,842
C
26.616197
150
0.655573
omniverse-code/kit/include/omni/ui/FloatDrag.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 "FloatSlider.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The drag widget that looks like a field but it's possible to change the value with dragging. */ class OMNIUI_CLASS_API FloatDrag : public FloatSlider { OMNIUI_OBJECT(FloatDrag) protected: /** * @brief Construct FloatDrag */ OMNIUI_API FloatDrag(const std::shared_ptr<AbstractValueModel>& model = {}); private: /** * @brief Reimplemented. It has to run a very low level function to call the widget. */ virtual bool _drawUnderlyingItem(double* value, double min, double max) override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,085
C
28.351351
102
0.737327
omniverse-code/kit/include/omni/ui/Label.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 "Alignment.h" #include "FontHelper.h" #include "Widget.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The Label widget provides a text to display. * * Label is used for displaying text. No additional to Widget user interaction functionality is provided. */ class OMNIUI_CLASS_API Label : public Widget, public FontHelper { OMNIUI_OBJECT(Label) public: OMNIUI_API ~Label() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the text. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the text. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented. Something happened with the style or with the parent style. We need to update the saved * font. */ OMNIUI_API void onStyleUpdated() override; /** * @brief Return the exact width of the content of this label. Computed content width is a size hint and may be * bigger than the text in the label */ OMNIUI_API float exactContentWidth(); /** * @brief Return the exact height of the content of this label. Computed content height is a size hint and may be * bigger than the text in the label */ OMNIUI_API float exactContentHeight(); /** * @brief This property holds the label's text. */ OMNIUI_PROPERTY(std::string, text, READ, getText, WRITE, setText, NOTIFY, setTextChangedFn); /** * @brief This property holds the label's word-wrapping policy * If this property is true then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped * at all. * By default, word wrap is disabled. */ OMNIUI_PROPERTY(bool, wordWrap, DEFAULT, false, READ, isWordWrap, WRITE, setWordWrap); /** * @brief When the text of a big length has to be displayed in a small area, it can be useful to give the user a * visual hint that not all text is visible. Label can elide text that doesn't fit in the area. When this property * is true, Label elides the middle of the last visible line and replaces it with "...". */ OMNIUI_PROPERTY(bool, elidedText, DEFAULT, false, READ, isElidedText, WRITE, setElidedText); /** * @brief Customized elidedText string when elidedText is True, default is "...". */ OMNIUI_PROPERTY(std::string, elidedTextStr, DEFAULT, "...", READ, getElidedTextStr, WRITE, setElidedTextStr); /** * @brief This property holds the alignment of the label's contents * By default, the contents of the label are left-aligned and vertically-centered. */ OMNIUI_PROPERTY(Alignment, alignment, DEFAULT, Alignment::eLeftCenter, READ, getAlignment, WRITE, setAlignment); /** * @brief Hide anything after a '##' string or not */ OMNIUI_PROPERTY(bool, hideTextAfterHash, DEFAULT, true, READ, isHideTextAfterHash, WRITE, setHideTextAfterHash); protected: /** * @brief Create a label with the given text. * * @param text The text for the label. */ OMNIUI_API Label(const std::string& text); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: /** * @brief Compute the size of the text and save result to the private members. * * @param width Is used for wrapping. If wrapping enabled, it has the maximum allowed text width. If there is no * wrapping, it's ignored. */ void _computeTextSize(float width); // Flag that the text size is computed. We need it because we don't want to compute the size each call of draw(). bool m_textMinimalSizeComputed = false; float m_textMinimalWidth; float m_textMinimalHeight; // We need it for multiline eliding. float m_lastAvailableHeight = 0.0f; // The pointer to the font that is used by this label. void* m_font = nullptr; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
4,913
C
33.125
118
0.688988
omniverse-code/kit/include/omni/ui/Rectangle.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 "Shape.h" OMNIUI_NAMESPACE_OPEN_SCOPE struct RectangleStyleSnapshot; /** * @brief The Rectangle widget provides a colored rectangle to display. */ class OMNIUI_CLASS_API Rectangle : public Shape { OMNIUI_OBJECT(Rectangle) public: OMNIUI_API ~Rectangle() override; protected: /** * @brief Constructs Rectangle */ OMNIUI_API Rectangle(); /** * @brief Reimplemented the rendering code of the widget. */ OMNIUI_API void _drawShape(float elapsedTime, float x, float y, float width, float height) override; /** * @brief Reimplemented the draw shadow of the shape. */ OMNIUI_API void _drawShadow( float elapsedTime, float x, float y, float width, float height, uint32_t shadowColor, float dpiScale, ImVec2 shadowOffset, float shadowThickness, uint32_t shadowFlag) override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,429
C
23.237288
93
0.686494
omniverse-code/kit/include/omni/ui/RadioButton.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 "Button.h" #include <functional> OMNIUI_NAMESPACE_OPEN_SCOPE class RadioCollection; /** * @brief RadioButton is the widget that allows the user to choose only one of a predefined set of mutually exclusive * options. * * RadioButtons are arranged in collections of two or more with the class RadioCollection, which is the central * component of the system and controls the behavior of all the RadioButtons in the collection. * * @see RadioCollection */ class OMNIUI_CLASS_API RadioButton : public Button { OMNIUI_OBJECT(RadioButton) public: OMNIUI_API ~RadioButton() override; /** * @brief This property holds the button's text. */ OMNIUI_PROPERTY(std::shared_ptr<RadioCollection>, radioCollection, READ, getRadioCollection, WRITE, setRadioCollection, NOTIFY, onRadioCollectionChangedFn); protected: /** * @brief Constructs RadioButton */ OMNIUI_API RadioButton(); private: /** * @brief Reimplemented from InvisibleButton. Called then the user clicks this button. We don't use `m_clickedFn` * because the user can set it. If we are using it in our internal code and the user overrides it, the behavior of * the button will be changed. */ OMNIUI_API void _clicked() override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,909
C
27.939394
118
0.682556
omniverse-code/kit/include/omni/ui/AbstractItemModel.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 "Api.h" #include <functional> #include <memory> #include <string> #include <unordered_set> #include <vector> OMNIUI_NAMESPACE_OPEN_SCOPE class AbstractValueModel; class ItemModelHelper; /** * @brief The central component of the item widget. It is the application's dynamic data structure, independent of the * user interface, and it directly manages the nested data. It follows closely model-view pattern. It's abstract, and it * defines the standard interface to be able to interoperate with the components of the model-view architecture. It is * not supposed to be instantiated directly. Instead, the user should subclass it to create a new model. * * The overall architecture is described in the following drawing: * * \internal * * # Data is inside the model (cache) * # Data is outside the model (mirror) * |----------------------------| * |-------------------| * | AbstractItemModel | * | AbstractItemModel | * | |------- Data -------|| * | | |----- Data -----| * | | |- Item1 || <-- AbstractItem * | | -- AbstractItem -->| |- Item1 | * | | | |- SubItem1 || <-- AbstractItem * | | -- AbstractItem -->| | |- Sub1 | * | | | | |- SubSubItem1|| <-- AbstractItem * | | -- AbstractItem -->| | | |- SubSub1| * | | | | |- SubSubItem2|| <-- AbstractItem * | | -- AbstractItem -->| | | |- SubSub2| * | | | |- SubItem2 || <-- AbstractItem * | | -- AbstractItem -->| | |- Sub2 | * | | |- Item2 || <-- AbstractItem * | | -- AbstractItem -->| |- Item2 | * | | |- SubItem3 || <-- AbstractItem * | | -- AbstractItem -->| |- Sub3 | * | | |- SubItem4 || <-- AbstractItem * | | -- AbstractItem -->| |- Sub4 | * | |--------------------|| * | | |----------------| * |----------------------------| * |-------------------| * | * | * | * | * |----------------------------| * |----------------------------| * | ItemModelHelper | * | ItemModelHelper | * ||--------------------------|| * ||--------------------------|| * || Root || * || Root || * || |- World || * || |- World || * || | |- Charater || * || | |- Charater || * || | | |- Head || * || | | |- Head || * || | | |- Body || * || | | |- Body || * || | |- Sphere || * || | |- Sphere || * || |- Materials || * || |- Materials || * || |- GGX || * || |- GGX || * || |- GTR || * || |- GTR || * ||--------------------------|| * ||--------------------------|| * |----------------------------| * |----------------------------| * * \endinternal * * The item model doesn't return the data itself. Instead, it returns the value model that can contain any data type and * supports callbacks. Thus the client of the model can track the changes in both the item model and any value it holds. * * From any item, the item model can get both the value model and the nested items. Therefore, the model is flexible to * represent anything from color to complicated tree-table construction. * * TODO: We can see there is a lot of methods that are similar to the AbstractValueModel. We need to template them. */ class OMNIUI_CLASS_API AbstractItemModel { public: /** * @brief The object that is associated with the data entity of the AbstractItemModel. * * The item should be created and stored by the model implementation. And can contain any data in it. Another option * would be to use it as a raw pointer to the data. In any case it's the choice of the model how to manage this * class. */ class AbstractItem { public: virtual ~AbstractItem() = default; }; OMNIUI_API virtual ~AbstractItemModel(); // We assume that all the operations with the model should be performed with smart pointers because it will register // subscription. If the object is copied or moved, it will break the subscription. // No copy AbstractItemModel(const AbstractItemModel&) = delete; // No copy-assignment AbstractItemModel& operator=(const AbstractItemModel&) = delete; // No move constructor and no move-assignments are allowed because of 12.8 [class.copy]/9 and 12.8 [class.copy]/20 // of the C++ standard /** * @brief Returns the vector of items that are nested to the given parent item. * * @param id The item to request children from. If it's null, the children of root will be returned. */ OMNIUI_API virtual std::vector<std::shared_ptr<const AbstractItem>> getItemChildren( const std::shared_ptr<const AbstractItem>& parentItem = nullptr) = 0; /** * @brief Returns true if the item can have children. In this way the delegate usually draws +/- icon. * * @param id The item to request children from. If it's null, the children of root will be returned. */ OMNIUI_API virtual bool canItemHaveChildren(const std::shared_ptr<const AbstractItem>& parentItem = nullptr); /** * @brief Creates a new item from the value model and appends it to the list of the children of the given item. */ OMNIUI_API virtual std::shared_ptr<const AbstractItem> appendChildItem(const std::shared_ptr<const AbstractItem>& parentItem, std::shared_ptr<AbstractValueModel> model); /** * @brief Removes the item from the model. * * There is no parent here because we assume that the reimplemented model deals with its data and can figure out how * to remove this item. */ OMNIUI_API virtual void removeItem(const std::shared_ptr<const AbstractItem>& item); /** * @brief Returns the number of columns this model item contains. */ OMNIUI_API virtual size_t getItemValueModelCount(const std::shared_ptr<const AbstractItem>& item = nullptr) = 0; /** * @brief Get the value model associated with this item. * * @param item The item to request the value model from. If it's null, the root value model will be returned. * @param index The column number to get the value model. */ OMNIUI_API virtual std::shared_ptr<AbstractValueModel> getItemValueModel(const std::shared_ptr<const AbstractItem>& item = nullptr, size_t index = 0) = 0; /** * @brief Called when the user starts the editing. If it's a field, this method is called when the user activates * the field and places the cursor inside. */ OMNIUI_API virtual void beginEdit(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Called when the user finishes the editing. If it's a field, this method is called when the user presses * Enter or selects another field for editing. It's useful for undo/redo. */ OMNIUI_API virtual void endEdit(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Called to determine if the model can perform drag and drop to the given item. If this method returns * false, the widget shouldn't highlight the visual element that represents this item. */ OMNIUI_API virtual bool dropAccepted(const std::shared_ptr<const AbstractItem>& itemTarget, const std::shared_ptr<const AbstractItem>& itemSource, int32_t dropLocation = -1); /** * @brief Called to determine if the model can perform drag and drop of the given string to the given item. If this * method returns false, the widget shouldn't highlight the visual element that represents this item. */ OMNIUI_API virtual bool dropAccepted(const std::shared_ptr<const AbstractItem>& itemTarget, const char* source, int32_t dropLocation = -1); /** * @brief Called when the user droped one item to another. * * @note Small explanation why the same default value is declared in multiple places. We use the default value to be * compatible with the previous API and especially with Stage 2.0. Thr signature in the old Python API is: `def * drop(self, target_item, source)`. So when the user drops something over the item, we call 2-args `drop(self, * target_item, source)`, see `PyAbstractItemModel::drop`, and to call 2-args drop PyBind11 needs default value in * both here and Python implementation of `AbstractItemModel.drop`. W also set the default value in * `pybind11::class_<AbstractItemModel>.def("drop")` and PyBind11 uses it when the user calls the C++ binding of * AbstractItemModel from the python code. * * @see PyAbstractItemModel::drop */ OMNIUI_API virtual void drop(const std::shared_ptr<const AbstractItem>& itemTarget, const std::shared_ptr<const AbstractItem>& itemSource, int32_t dropLocation = -1); /** * @brief Called when the user droped a string to the item. */ OMNIUI_API virtual void drop(const std::shared_ptr<const AbstractItem>& itemTarget, const char* source, int32_t dropLocation = -1); /** * @brief Returns Multipurpose Internet Mail Extensions (MIME) for drag and drop. */ OMNIUI_API virtual std::string getDragMimeData(const std::shared_ptr<const AbstractItem>& item); /** * @brief Subscribe the ItemModelHelper widget to the changes of the model. * * We need to use regular pointers because we subscribe in the constructor of the widget and unsubscribe in the * destructor. In constructor smart pointers are not available. We also don't allow copy and move of the widget. * * TODO: It's similar to AbstractValueModel::subscribe, we can template it. */ OMNIUI_API void subscribe(ItemModelHelper* widget); /** * @brief Unsubscribe the ItemModelHelper widget from the changes of the model. * * TODO: It's similar to AbstractValueModel::unsubscribe, we can template it. */ OMNIUI_API void unsubscribe(ItemModelHelper* widget); /** * @brief Adds the function that will be called every time the value changes. * * @return The id of the callback that is used to remove the callback. * * TODO: It's similar to AbstractValueModel::addItemChangedFn, we can template it. */ OMNIUI_API uint32_t addItemChangedFn(std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)> fn); /** * @brief Remove the callback by its id. * * @param id The id that addValueChangedFn returns. * * TODO: It's similar to AbstractValueModel::removeItemChangedFn, we can template it. */ OMNIUI_API void removeItemChangedFn(uint32_t id); /** * @brief Adds the function that will be called every time the user starts the editing. * * @return The id of the callback that is used to remove the callback. */ OMNIUI_API uint32_t addBeginEditFn(std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)> fn); /** * @brief Remove the callback by its id. * * @param id The id that addBeginEditFn returns. */ OMNIUI_API void removeBeginEditFn(uint32_t id); /** * @brief Adds the function that will be called every time the user finishes the editing. * * @return The id of the callback that is used to remove the callback. */ OMNIUI_API uint32_t addEndEditFn(std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)> fn); /** * @brief Remove the callback by its id. * * @param id The id that addEndEditFn returns. */ OMNIUI_API void removeEndEditFn(uint32_t id); /** * @brief Called by the widget when the user starts editing. It calls beginEdit and the callbacks. */ OMNIUI_API void processBeginEditCallbacks(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Called by the widget when the user finishes editing. It calls endEdit and the callbacks. */ OMNIUI_API void processEndEditCallbacks(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); protected: /** * @brief Constructs AbstractItemModel */ OMNIUI_API AbstractItemModel(); /** * @brief Called when any data of the model is changed. It will notify the subscribed widgets. * * @param item The item in the model that is changed. If it's NULL, the root is chaged. */ OMNIUI_API void _itemChanged(const std::shared_ptr<const AbstractItem>& item); // All the widgets who use this model. See description of subscribe for the information why it's regular pointers. // TODO: we can use m_callbacks for subscribe-unsubscribe. But in this way it's nesessary to keep widget-id map. // When the _valueChanged code will be more complicated, we need to do it. Now it's simple enought and m_widgets // stays here. std::unordered_set<ItemModelHelper*> m_widgets; // All the callbacks. std::vector<std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)>> m_itemChangedCallbacks; // Callbacks that called when the user starts the editing. std::vector<std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)>> m_beginEditCallbacks; // Callbacks that called when the user finishes the editing. std::vector<std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)>> m_endEditCallbacks; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
15,271
C
45.419453
126
0.589549
omniverse-code/kit/include/omni/ui/RasterHelper.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 "Api.h" #include "Callback.h" #include "Property.h" #include "RasterPolicy.h" OMNIUI_NAMESPACE_OPEN_SCOPE class Widget; struct RasterHelperPrivate; /** * @brief The "RasterHelper" class is used to manage the draw lists or raster * images. This class is responsible for rasterizing (or baking) the UI, which * involves adding information about widgets to the cache. Once the UI has been * baked, the draw list cache can be used to quickly re-render the UI without * having to iterate over the widgets again. This is useful because it allows * the UI to be rendered more efficiently, especially in cases where the widgets * have not changed since the last time the UI was rendered. The "RasterHelper" * class provides methods for modifying the cache and rendering the UI from the * cached information. */ class OMNIUI_CLASS_API RasterHelper : private CallbackHelper<RasterHelper> { public: OMNIUI_API virtual ~RasterHelper(); /** * @brief Determine how the content of the frame should be rasterized. */ OMNIUI_PROPERTY(RasterPolicy, rasterPolicy, DEFAULT, RasterPolicy::eNever, READ, getRasterPolicy, WRITE, setRasterPolicy, PROTECTED, NOTIFY, _setRasterPolicyChangedFn); /** * @brief This method regenerates the raster image of the widget, even if * the widget's content has not changed. This can be used with both the * eOnDemand and eAuto raster policies, and is used to update the content * displayed in the widget. Note that this operation may be * resource-intensive, and should be used sparingly. */ OMNIUI_API void invalidateRaster(); protected: friend class MenuDelegate; /** * @brief Constructor */ OMNIUI_API RasterHelper(); /** * @brief Should be called by the widget in init time. */ void _rasterHelperInit(Widget& widget); /** * @brief Should be called by the widget in destroy time. */ void _rasterHelperDestroy(); OMNIUI_API bool _rasterHelperBegin(float posX, float posY, float width, float height); OMNIUI_API void _rasterHelperEnd(); OMNIUI_API void _rasterHelperSetDirtyDrawList(); OMNIUI_API void _rasterHelperSetDirtyLod(); OMNIUI_API void _rasterHelperSuspendRasterization(bool stopRasterization); OMNIUI_API bool _isInRasterWindow() const; private: void _captureRaster(float originX, float originY); void _drawRaster(float originX, float originY) const; bool _isDirtyDrawList() const; std::unique_ptr<RasterHelperPrivate> m_prv; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
3,270
C
28.205357
80
0.680734
omniverse-code/kit/include/omni/ui/Api.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 #ifdef _WIN32 # define OMNIUI_EXPORT __declspec(dllexport) # define OMNIUI_IMPORT __declspec(dllimport) # define OMNIUI_CLASS_EXPORT #else # define OMNIUI_EXPORT __attribute__((visibility("default"))) # define OMNIUI_IMPORT # define OMNIUI_CLASS_EXPORT __attribute__((visibility("default"))) #endif #if defined(OMNIUI_STATIC) # define OMNIUI_API # define OMNIUI_CLASS_API #else # if defined(OMNIUI_EXPORTS) # define OMNIUI_API OMNIUI_EXPORT # define OMNIUI_CLASS_API OMNIUI_CLASS_EXPORT # else # define OMNIUI_API OMNIUI_IMPORT # define OMNIUI_CLASS_API # endif #endif #define OMNIUI_NS omni::ui #define OMNIUI_NAMESPACE_USING_DIRECTIVE using namespace OMNIUI_NS; #define OMNIUI_NAMESPACE_OPEN_SCOPE \ namespace omni \ { \ namespace ui \ { #define OMNIUI_NAMESPACE_CLOSE_SCOPE \ } \ }
1,918
C
42.613635
120
0.49635
omniverse-code/kit/include/omni/ui/Font.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 "Api.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief List of all font sizes */ enum class FontStyle { eNone, /** * @brief 14 */ eNormal, /** * @brief 16 */ eLarge, /** * @brief 12 */ eSmall, /** * @brief 18 */ eExtraLarge, /** * @brief 20 */ eXXL, /** * @brief 22 */ eXXXL, /** * @brief 10 */ eExtraSmall, /** * @brief 8 */ eXXS, /** * @brief 6 */ eXXXS, /** * @brief 66 */ eUltra, eCount }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,083
C
13.263158
77
0.558633
omniverse-code/kit/include/omni/ui/Frame.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 "Container.h" #include "RasterHelper.h" OMNIUI_NAMESPACE_OPEN_SCOPE struct FramePrivate; /** * @brief The Frame is a widget that can hold one child widget. * * Frame is used to crop the contents of a child widget or to draw small widget in a big view. The child widget must be * specified with addChild(). */ class OMNIUI_CLASS_API Frame : public Container, public RasterHelper { OMNIUI_OBJECT(Frame) public: using CallbackHelperBase = Widget; OMNIUI_API ~Frame() override; OMNIUI_API void destroy() override; /** * @brief Reimplemented adding a widget to this Frame. The Frame class can not contain multiple widgets. The widget * overrides * * @see Container::addChild */ OMNIUI_API void addChild(std::shared_ptr<Widget> widget) override; /** * @brief Reimplemented removing all the child widgets from this Stack. * * @see Container::clear */ OMNIUI_API void clear() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widgets. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widgets. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief It's called when the style is changed. It should be propagated to children to make the style cached and * available to children. */ OMNIUI_API void cascadeStyle() override; /** * @brief Next frame the content will be forced to re-bake. */ OMNIUI_API void forceRasterDirty(BakeDirtyReason reason) override; /** * @brief Set the callback that will be called once the frame is visible and the content of the callback will * override the frame child. It's useful for lazy load. */ OMNIUI_CALLBACK(Build, void); /** * @brief After this method is called, the next drawing cycle build_fn will be called again to rebuild everything. */ OMNIUI_API virtual void rebuild(); /** * @brief Change dirty bits when the visibility is changed. */ OMNIUI_API void setVisiblePreviousFrame(bool wasVisible, bool dirtySize = true) override; /** * @brief When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is * on. It only works for horizontal direction. */ OMNIUI_PROPERTY(bool, horizontalClipping, DEFAULT, false, READ, isHorizontalClipping, WRITE, setHorizontalClipping); /** * @brief When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is * on. It only works for vertial direction. */ OMNIUI_PROPERTY(bool, verticalClipping, DEFAULT, false, READ, isVerticalClipping, WRITE, setVerticalClipping); /** * @brief A special mode where the child is placed to the transparent borderless window. We need it to be able to * place the UI to the exact stacking order between other windows. */ OMNIUI_PROPERTY(bool, separateWindow, DEFAULT, false, READ, isSeparateWindow, WRITE, setSeparateWindow); OMNIUI_PROPERTY(bool, frozen, DEFAULT, false, READ, isFrozen, WRITE, setFrozen, PROTECTED, NOTIFY, _setFrozenChangedFn); protected: /** * @brief Constructs Frame */ OMNIUI_API Frame(); /** * @brief Reimplemented the rendering code of the widget. * * Draw the content. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; /** * @brief Return the list of children for the Container. */ OMNIUI_API const std::vector<std::shared_ptr<Widget>> _getChildren() const override; /** * @brief This method fills an unordered set with the visible minimum and * maximum values of the Widget and children. */ OMNIUI_API void _fillVisibleThreshold(void* thresholds) const override; // Disables padding. We need it mostly for CollapsableFrame because it creates multiple nested frames and we need to // have only one padding applied. bool m_needPadding = true; private: friend class Placer; friend class Inspector; static float _evaluateLayout(const Length& canvasLength, float availableLength, float dpiScale); /** * @brief Replaces m_canvas with m_canvasPending is possible. */ void _processPendingWidget(); /** * @brief Used in Inspector. Calls build_fn if necessary. */ void _populate(); // The only child of this frame std::shared_ptr<Widget> m_canvas; // The widget that will be the current at the next draw std::shared_ptr<Widget> m_canvasPending; // Lazy load callback. It's destroyed right after it's called. std::function<void()> m_buildFn; // Flag to rebuild the children with m_buildFn. bool m_needRebuildWithCallback = false; std::unique_ptr<FramePrivate> m_prv; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
5,869
C
30.55914
124
0.689385
omniverse-code/kit/include/omni/ui/AbstractSlider.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 "FontHelper.h" #include "ValueModelHelper.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The abstract widget that is base for drags and sliders. */ class OMNIUI_CLASS_API AbstractSlider : public Widget, public ValueModelHelper, public FontHelper { public: // TODO: this need to be moved to be a Header like Alignment enum class DrawMode : uint8_t { // filled mode will render the left portion of the slider with filled solid color from styling eFilled = 0, // handle mode draw a knobs at the slider position eHandle, // The Slider doesn't display either Handle or Filled Rect eDrag }; OMNIUI_API ~AbstractSlider() override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented. Something happened with the style or with the parent style. We need to gerenerate the * cache. */ OMNIUI_API void onStyleUpdated() override; protected: OMNIUI_API AbstractSlider(const std::shared_ptr<AbstractValueModel>& model); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; /** * @brief Should be called before editing the model to make sure model::beginEdit called properly. */ OMNIUI_API virtual void _beginModelChange(); /** * @brief Should be called after editing the model to make sure model::endEdit called properly. */ OMNIUI_API virtual void _endModelChange(); /** * @brief the ration calculation is requiere to draw the Widget as Gauge, it is calculated with Min/Max & Value */ virtual float _getValueRatio() = 0; // True if the mouse is down bool m_editActive = false; private: /** * @brief _drawContent sets everything up including styles and fonts and calls this method. */ virtual void _drawUnderlyingItem() = 0; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
2,676
C
28.417582
116
0.690583
omniverse-code/kit/include/omni/ui/VGrid.h
// Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Grid.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Shortcut for Grid{eTopToBottom}. The grid grows from top to bottom with the widgets placed. * * @see Grid */ class OMNIUI_CLASS_API VGrid : public Grid { OMNIUI_OBJECT(VGrid) public: OMNIUI_API ~VGrid() override; protected: /** * @brief Construct a grid that grows from top to bottom with the widgets placed. */ OMNIUI_API VGrid(); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
936
C
23.657894
101
0.729701
omniverse-code/kit/include/omni/ui/RasterPolicy.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 "Api.h" #include <cstdint> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Used to set the rasterization behaviour. */ enum class RasterPolicy : uint8_t { // Do not rasterize the widget at any time. eNever = 0, // Rasterize the widget as soon as possible and always use the // rasterized version. This means that the widget will only be updated // when the user called invalidateRaster. eOnDemand, // Automatically determine whether to rasterize the widget based on // performance considerations. If necessary, the widget will be // rasterized and updated when its content changes. eAuto }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,121
C
31.057142
77
0.748439
omniverse-code/kit/include/omni/ui/IntDrag.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 "IntSlider.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The drag widget that looks like a field but it's possible to change the value with dragging. */ class OMNIUI_CLASS_API IntDrag : public IntSlider { OMNIUI_OBJECT(IntDrag) public: /** * @brief This property controls the steping speed on the drag, its float to enable slower speed, * but of course the value on the Control are still integer */ OMNIUI_PROPERTY(float, step, DEFAULT, 0.1f, READ, getStep, WRITE, setStep); protected: /** * @brief Constructs IntDrag * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API IntDrag(const std::shared_ptr<AbstractValueModel>& model = {}); private: /** * @brief Reimplemented. It has to run a very low level function to call the widget. */ virtual bool _drawUnderlyingItem(int64_t* value, int64_t min, int64_t max) override; }; class OMNIUI_CLASS_API UIntDrag : public UIntSlider { OMNIUI_OBJECT(UIntDrag) public: /** * @brief This property controls the steping speed on the drag, its float to enable slower speed, * but of course the value on the Control are still integer */ OMNIUI_PROPERTY(float, step, DEFAULT, 0.1f, READ, getStep, WRITE, setStep); protected: /** * @brief Constructs UIntDrag * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API UIntDrag(const std::shared_ptr<AbstractValueModel>& model = {}); private: /** * @brief Reimplemented. It has to run a very low level function to call the widget. */ virtual bool _drawUnderlyingItem(uint64_t* value, uint64_t min, uint64_t max) override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
2,272
C
30.136986
102
0.701144
omniverse-code/kit/include/omni/ui/Placer.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 "Axis.h" #include "Container.h" #include "RasterHelper.h" #include <vector> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The Placer class place a single widget to a particular position based on the offet */ class OMNIUI_CLASS_API Placer : public Container, public RasterHelper { OMNIUI_OBJECT(Placer) public: using CallbackHelperBase = Widget; OMNIUI_API ~Placer() override; OMNIUI_API void destroy() override; /** * @brief Reimplemented adding a widget to this Placer. The Placer class can not contain multiple widgets. * * @see Container::addChild */ OMNIUI_API void addChild(std::shared_ptr<Widget> widget) override; /** * @brief Reimplemented to simply set the single child to null * * @see Container::clear */ OMNIUI_API void clear() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widget. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widget. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief It's called when the style is changed. It should be propagated to children to make the style cached and * available to children. */ OMNIUI_API void cascadeStyle() override; /** * @brief Next frame the content will be forced to re-bake. */ OMNIUI_API void forceRasterDirty(BakeDirtyReason reason) override; /** * @brief offsetX defines the offset placement for the child widget relative to the Placer * * TODO: We will need percents to be able to keep the relative position when scaling. * Example: In Blender sequencer when resizing the window the relative position of tracks is not changing. */ OMNIUI_PROPERTY(Length, offsetX, DEFAULT, Pixel(0.0f), READ, getOffsetX, WRITE, setOffsetX, NOTIFY, setOffsetXChangedFn); /** * @brief offsetY defines the offset placement for the child widget relative to the Placer * */ OMNIUI_PROPERTY(Length, offsetY, DEFAULT, Pixel(0.0f), READ, getOffsetY, WRITE, setOffsetY, NOTIFY, setOffsetYChangedFn); /** * @brief Provides a convenient way to make an item draggable. * * TODO: * dragMaximumX * dragMaximumY * dragMinimumX * dragMinimumY * dragThreshold */ OMNIUI_PROPERTY(bool, draggable, DEFAULT, false, READ, isDraggable, WRITE, setDraggable); /** * @brief Sets if dragging can be horizontally or vertically. */ OMNIUI_PROPERTY(Axis, dragAxis, DEFAULT, Axis::eXY, READ, getDragAxis, WRITE, setDragAxis); /** * @brief The placer size depends on the position of the child when false. */ OMNIUI_PROPERTY(bool, stableSize, DEFAULT, false, READ, isStableSize, WRITE, setStableSize); /** * @brief Set number of frames to start dragging if drag is not detected the first frame. */ OMNIUI_PROPERTY(uint32_t, framesToStartDrag, DEFAULT, 0, READ, getFramesToStartDrag, WRITE, setFramesToStartDrag); protected: /** * @brief Construct Placer */ OMNIUI_API Placer(); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; /** * @brief Return the list of children for the Container. */ OMNIUI_API const std::vector<std::shared_ptr<Widget>> _getChildren() const override; /** * @brief This method fills an unordered set with the visible minimum and * maximum values of the Widget and children. */ OMNIUI_API void _fillVisibleThreshold(void* thresholds) const override; private: std::shared_ptr<Widget> m_childWidget; // True when the user drags the child. We need it to know if the user was dragging the child on the previous frame. bool m_dragActive = false; // Count duration when the mouse button is pressed. We need it to detect the second frame from mouse click. uint32_t m_pressedFrames = 0; float m_offsetXCached; float m_offsetYCached; float m_widthCached; float m_heightCached; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
5,119
C
29.658682
125
0.686853
omniverse-code/kit/include/omni/ui/Inspector.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 "Widget.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Inspector is the helper to check the internal state of the widget. * It's not recommended to use it for the routine UI. */ class OMNIUI_CLASS_API Inspector { public: /** * @brief Get the children of the given Widget. */ OMNIUI_API static std::vector<std::shared_ptr<Widget>> getChildren(const std::shared_ptr<Widget>& widget); /** * @brief Get the resolved style of the given Widget. */ OMNIUI_API static const std::shared_ptr<StyleContainer>& getResolvedStyle(const std::shared_ptr<Widget>& widget); /** * @brief Start counting how many times Widget::setComputedWidth is called */ OMNIUI_API static void beginComputedWidthMetric(); /** * @brief Increases the number Widget::setComputedWidth is called */ OMNIUI_API static void bumpComputedWidthMetric(); /** * @brief Start counting how many times Widget::setComputedWidth is called * and return the number */ OMNIUI_API static size_t endComputedWidthMetric(); /** * @brief Start counting how many times Widget::setComputedHeight is called */ OMNIUI_API static void beginComputedHeightMetric(); /** * @brief Increases the number Widget::setComputedHeight is called */ OMNIUI_API static void bumpComputedHeightMetric(); /** * @brief Start counting how many times Widget::setComputedHeight is called * and return the number */ OMNIUI_API static size_t endComputedHeightMetric(); /** * @brief Provides the information about font atlases */ OMNIUI_API static std::vector<std::pair<std::string, uint32_t>> getStoredFontAtlases(); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
2,243
C
27.05
106
0.693268
omniverse-code/kit/include/omni/ui/Window.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 "Api.h" #include "Callback.h" #include "Property.h" #include "RasterPolicy.h" #include "WindowHandle.h" #include "Workspace.h" #include "windowmanager/WindowManagerUtils.h" #include <carb/IObject.h> #include <carb/input/InputTypes.h> // KeyPressed #include <float.h> #include <memory> #include <string> namespace omni { namespace ui { namespace windowmanager { class IWindowCallback; } } } OMNIUI_NAMESPACE_OPEN_SCOPE class Frame; class MenuBar; /** * @brief The Window class represents a window in the underlying windowing system. * * This window is a child window of main Kit window. And it can be docked. * * Rasterization * * omni.ui generates vertices every frame to render UI elements. One of the * features of the framework is the ability to bake a DrawList per window and * reuse it if the content has not changed, which can significantly improve * performance. However, in some cases, such as the Viewport window and Console * window, it may not be possible to detect whether the window content has * changed, leading to a frozen window. To address this problem, you can control * the rasterization behavior by adjusting RasterPolicy. The RasterPolicy is an * enumeration class that defines the rasterization behavior of a window. It has * three possible values: * * NEVER: Do not rasterize the widget at any time. * ON_DEMAND: Rasterize the widget as soon as possible and always use the * rasterized version. The widget will only be updated when the user calls * invalidateRaster. * AUTO: Automatically determine whether to rasterize the widget based on * performance considerations. If necessary, the widget will be rasterized and * updated when its content changes. * * To resolve the frozen window issue, you can manually set the RasterPolicy of * the problematic window to Never. This will force the window to rasterize its * content and use the rasterized version until the user explicitly calls * invalidateRaster to request an update. * * window = ui.Window("Test window", raster_policy=ui.RasterPolicy.NEVER) */ class OMNIUI_CLASS_API Window : public std::enable_shared_from_this<Window>, public WindowHandle, protected CallbackHelper<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 kWindowFlagNoScrollWithMouse = (1 << 4); static constexpr Flags kWindowFlagNoCollapse = (1 << 5); static constexpr Flags kWindowFlagNoBackground = 1 << 7; static constexpr Flags kWindowFlagNoSavedSettings = (1 << 8); static constexpr Flags kWindowFlagNoMouseInputs = 1 << 9; static constexpr Flags kWindowFlagMenuBar = 1 << 10; static constexpr Flags kWindowFlagShowHorizontalScrollbar = (1 << 11); static constexpr Flags kWindowFlagNoFocusOnAppearing = (1 << 12); static constexpr Flags kWindowFlagForceVerticalScrollbar = (1 << 14); static constexpr Flags kWindowFlagForceHorizontalScrollbar = (1 << 15); static constexpr Flags kWindowFlagNoDocking = (1 << 21); static constexpr Flags kWindowFlagPopup = (1 << 26); static constexpr Flags kWindowFlagModal = (1 << 27); static constexpr Flags kWindowFlagNoClose = (1 << 31); static constexpr float kWindowFloatInvalid = FLT_MAX; // this will need to be reviewed, it is not clear in the future we can really have known position for docking enum class DockPreference : uint8_t { eDisabled, eMain, eRight, eLeft, eRightTop, eRightBottom, eLeftBottom }; enum class DockPolicy : uint8_t { eDoNothing, eCurrentWindowIsActive, eTargetWindowIsActive }; enum class FocusPolicy : uint8_t { eFocusOnLeftMouseDown, // Focus Window on left mouse down and right-click-up. eFocusOnAnyMouseDown, // Focus Window on any mouse down. eFocusOnHover, // Focus Window when mouse hovered over it. // Default to existing behavior: eFocusOnLeftMouseDown eDefault = eFocusOnLeftMouseDown, }; virtual ~Window(); /** * @brief Removes all the callbacks and circular references. */ OMNIUI_API virtual void destroy(); // We need it to make sure it's created as a shared pointer. template <typename... Args> static std::shared_ptr<Window> create(Args&&... args) { /* make_shared doesn't work because the constructor is protected: */ /* auto ptr = std::make_shared<This>(std::forward<Args>(args)...); */ /* TODO: Find the way to use make_shared */ auto window = std::shared_ptr<Window>{ new Window{ std::forward<Args>(args)... } }; Workspace::RegisterWindow(window); return window; } /** * @brief Notifies the window that window set has changed. * * \internal * TODO: We probably don't need it. * \endinternal */ OMNIUI_API void notifyAppWindowChange(omni::kit::IAppWindow* newAppWindow) override; /** * @brief Returns window set draw callback pointer for the given UI window. * * \internal * TODO: We probably don't need it. * \endinternal */ OMNIUI_API windowmanager::IWindowCallback* getWindowCallback() const; /** * @brief Moves the window to the specific OS window. */ OMNIUI_API void moveToAppWindow(omni::kit::IAppWindow* newAppWindow); /** * @brief Current IAppWindow */ OMNIUI_API omni::kit::IAppWindow * getAppWindow() const; /** * @brief Brings this window to the top level of modal windows. */ OMNIUI_API void setTopModal() const; /** * @brief Get DPI scale currently associated to the current window's viewport. It's static since currently we can * only have one window. * * \internal * TODO: class MainWindow * \endinternal */ OMNIUI_API static float getDpiScale(); /** * @brief Get the width in points of the current main window. * * \internal * TODO: class MainWindow * \endinternal */ OMNIUI_API static float getMainWindowWidth(); /** * @brief Get the height in points of the current main window. * * \internal * TODO: class MainWindow * \endinternal */ OMNIUI_API static float getMainWindowHeight(); /** * @brief Deferred docking. We need it when we want to dock windows before they were actually created. It's helpful * when extension initialization, before any window is created. * * @param[in] targetWindowTitle Dock to window with this title when it appears. * @param[in] activeWindow Make target or this window active when docked. */ OMNIUI_API virtual void deferredDockIn(const std::string& targetWindowTitle, DockPolicy activeWindow = DockPolicy::eDoNothing); /** * @brief Indicates if the window was already destroyed. */ OMNIUI_API bool isValid() const; /** * @brief Determine how the content of the window should be rastered. */ OMNIUI_API RasterPolicy getRasterPolicy() const; /** * @brief Determine how the content of the window should be rastered. */ OMNIUI_API void setRasterPolicy(RasterPolicy policy); /** * @brief Sets the function that will be called when the user presses the keyboard key on the focused window. */ OMNIUI_CALLBACK(KeyPressed, void, int32_t, carb::input::KeyboardModifierFlags, bool); /** * @brief This property holds the window's title. */ OMNIUI_PROPERTY(std::string, title, READ_VALUE, getTitle, WRITE, setTitle); /** * @brief This property holds whether the window is visible. */ OMNIUI_PROPERTY(bool, visible, DEFAULT, true, READ_VALUE, isVisible, WRITE, setVisible, NOTIFY, setVisibilityChangedFn); /** * @brief The main layout of this window. */ OMNIUI_PROPERTY(std::shared_ptr<Frame>, frame, READ, getFrame, PROTECTED, WRITE, setFrame); /** * @brief The MenuBar for this Window, it is always present but hidden when the MENUBAR Flag is missing * you need to use kWindowFlagMenuBar to show it */ OMNIUI_PROPERTY(std::shared_ptr<MenuBar>, menuBar, READ, getMenuBar, PROTECTED, WRITE, setMenuBar); /** * @brief This property holds the window Width */ OMNIUI_PROPERTY(float, width, DEFAULT, 400, READ_VALUE, getWidth, WRITE, setWidth, NOTIFY, setWidthChangedFn); /** * @brief This property holds the window Height */ OMNIUI_PROPERTY(float, heigh, DEFAULT, 600, READ_VALUE, getHeight, WRITE, setHeight, NOTIFY, setHeightChangedFn); /** * @brief This property set the padding to the frame on the X axis */ OMNIUI_PROPERTY(float, paddingX, DEFAULT, 4.f, READ, getPaddingX, WRITE, setPaddingX); /** * @brief This property set the padding to the frame on the Y axis */ OMNIUI_PROPERTY(float, paddingY, DEFAULT, 4.f, READ, getPaddingY, WRITE, setPaddingY); /** * @brief Read only property that is true when the window is focused. */ OMNIUI_PROPERTY( bool, focused, DEFAULT, false, READ, getFocused, NOTIFY, setFocusedChangedFn, PROTECTED, WRITE, _setFocused); /** * @brief This property set/get the position of the window in the X Axis. * The default is kWindowFloatInvalid because we send the window position to the underlying system only if the * position is explicitly set by the user. Otherwise the underlying system decides the position. */ OMNIUI_PROPERTY(float, positionX, DEFAULT, kWindowFloatInvalid, READ_VALUE, getPositionX, WRITE, setPositionX, NOTIFY, setPositionXChangedFn); /** * @brief This property set/get the position of the window in the Y Axis. * The default is kWindowFloatInvalid because we send the window position to the underlying system only if the * position is explicitly set by the user. Otherwise the underlying system decides the position. */ OMNIUI_PROPERTY(float, positionY, DEFAULT, kWindowFloatInvalid, READ_VALUE, getPositionY, WRITE, setPositionY, NOTIFY, setPositionYChangedFn); /** * @brief This property set/get the position of the window in both axis calling the property */ OMNIUI_API void setPosition(float x, float y); /** * @brief This property set the Flags for the Window */ OMNIUI_PROPERTY(Flags, flags, DEFAULT, kWindowFlagNone, READ, getFlags, WRITE, setFlags, NOTIFY, setFlagsChangedFn); /** * @brief setup the visibility of the TabBar Handle, this is the small triangle at the corner of the view * If it is not shown then it is not possible to undock that window and it need to be closed/moved programatically * */ OMNIUI_PROPERTY(bool, noTabBar, DEFAULT, false, READ, getNoTabBar, WRITE, setNoTabBar); /** * @brief setup the window to resize automatically based on its content * */ OMNIUI_PROPERTY(bool, autoResize, DEFAULT, false, READ, getAutoResize, WRITE, setAutoResize); /** * @brief Has true if this window is docked. False otherwise. It's a read-only property. */ OMNIUI_PROPERTY( bool, docked, DEFAULT, false, READ_VALUE, isDocked, NOTIFY, setDockedChangedFn, PROTECTED, WRITE, setDocked); /** * @brief Has true if this window is currently selected in the dock. False otherwise. It's a read-only property. */ OMNIUI_PROPERTY(bool, selectedInDock, DEFAULT, false, READ_VALUE, isSelectedInDock, NOTIFY, setSelectedInDockChangedFn, PROTECTED, WRITE, setSelectedInDock); /** * @brief place the window in a specific docking position based on a target window name. * We will find the target window dock node and insert this window in it, either by spliting on ratio or on top * if the window is not found false is return, otherwise true * */ OMNIUI_API bool dockInWindow(const std::string& windowName, const Window::DockPosition& dockPosition, const float& ratio = 0.5); /** * @brief place a named window in a specific docking position based on a target window name. * We will find the target window dock node and insert this named window in it, either by spliting on ratio or on * top if the windows is not found false is return, otherwise true * */ OMNIUI_API static bool dockWindowInWindow(const std::string& windowName, const std::string& targetWindowName, const Window::DockPosition& dockPosition, const float& ratio = 0.5); /** * @brief Move the Window Callback to a new OS Window */ OMNIUI_API void moveToNewOSWindow(); /** * @brief Bring back the Window callback to the Main Window and destroy the Current OS Window */ OMNIUI_API void moveToMainOSWindow(); /** * @brief When true, only the current window will receive keyboard events when it's focused. It's useful to override * the global key bindings. */ OMNIUI_PROPERTY(bool, exclusiveKeyboard, DEFAULT, false, READ_VALUE, isExclusiveKeyboard, WRITE, setExclusiveKeyboard); /** * @brief If the window is able to be separated from the main application window. */ OMNIUI_PROPERTY(bool, detachable, DEFAULT, true, READ_VALUE, isDetachable, WRITE, setDetachable); /** * @brief Vitrual window is the window that is rendered to internal buffer. */ OMNIUI_PROPERTY(bool, virtual, DEFAULT, false, READ_VALUE, isVirtual, PROTECTED, WRITE, _setVirtual); /** * @brief How the Window gains focus. */ OMNIUI_PROPERTY(FocusPolicy, focusPolicy, DEFAULT, FocusPolicy::eDefault, READ_VALUE, getFocusPolicy, WRITE, setFocusPolicy); protected: /** * @brief Construct the window, add it to the underlying windowing system, and makes it appear. * * TODO: By default, the window should not be visible, and the user must call setVisible(true), or show() or similar * to make it visible because right now it's impossible to create invisible window. * * @param title The window title. It's also used as an internal window ID. * @param dockPrefence In the old Kit determines where the window should be docked. In Kit Next it's unused. */ OMNIUI_API Window(const std::string& title, Window::DockPreference dockPrefence = DockPreference::eDisabled); /** * @brief Execute the rendering code of the widget. * * It's in protected section because it can be executed only by this object itself. */ virtual void _draw(const char* windowName, float elapsedTime); /** * @brief Execute the update code for the window, this is to be called inside some ImGui::Begin* code * it is used by modal popup and the main begin window code * * It's in protected section so object overiding behavior can re-use this logic */ void _updateWindow(const char* windowName, float elapsedTime, bool cachePosition); /** * @brief this will push the window style, this need to be called within the _draw function to enable styling */ void _pushWindowStyle(); /** * @brief if you have pushed Window StyleContainer you need to pop it before the end of the _draw method */ void _popWindowStyle(); private: /** * @brief Used as a callback of the underlying windowing system. Calls draw(). */ static void _drawWindow(const char* windowName, float elapsedTime, void* window); /** * @brief Used as a callback when the user call setPosition(X!Y) */ void _positionExplicitlyChanged(); /** * @brief Used as a callback when the user call setPosition(X!Y) */ void _sizeExplicitlyChanged(); /** * @brief Internal function that adds the window to the top level of the stack of modal windows. */ void _addToModalStack() const; /** * @brief Internal function that removes the window from the stack of modal windows. */ void _removeFromModalStack() const; /** * @brief Internal function that returns true if it's on the top of the stack of modal windows. */ bool _isTopModal() const; /** * @brief Force propagate the window state to the backend. */ void _forceWindowState(); /** * @brief Update the Window's focused state, retuns whether it has changed. */ bool _updateFocusState(); // we only support this when in the new kit stack, we might also want to make it a setting bool m_multiOSWindowSupport = false; bool m_enableWindowDetach = false; // we have some marker to tack os window move and timing bool m_osWindowMoving = false; bool m_mouseWasDragging = false; carb::Float2 m_mouseDragPoint = {}; carb::Float2 m_mouseDeltaOffset = {}; Window::DockPreference m_dockingPreference; bool m_positionExplicitlyChanged = false; bool m_sizeExplicitlyChanged = false; float m_prevContentRegionWidth = 0.0f; float m_prevContentRegionHeight = 0.0f; omni::kit::IAppWindow* m_appWindow = nullptr; omni::ui::windowmanager::IWindowCallbackPtr m_uiWindow; uint32_t m_pushedColorCount = { 0 }; uint32_t m_pushedFloatCount = { 0 }; // We need it for multi-modal windows because when the modal window is just created, ImGui puts it to (60, 60) and // the second frame the position is correct. We need to know when it's the first frame of the modal window. bool m_wasModalPreviousFrame = false; bool m_wasVisiblePreviousFrame = false; bool m_firstAppearance = true; // The name of the window we need to dock when it will appear. std::string m_deferredDocking; DockPolicy m_deferredDockingMakeTargetActive = DockPolicy::eDoNothing; class DeferredWindowRelease; std::unique_ptr<DeferredWindowRelease> m_deferedWindowRelease; std::function<void(int32_t, carb::input::KeyboardModifierFlags, bool)> m_keyPressedFn; // True if the title bar context menu is open. bool m_titleMenuOpened = false; bool m_destroyed = false; // True if the previous frame is visible bool m_wasPreviousShowItems = false; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
19,654
C
34.161002
124
0.662918
omniverse-code/kit/include/omni/ui/Ellipse.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 "Alignment.h" #include "Shape.h" OMNIUI_NAMESPACE_OPEN_SCOPE struct EllipseStyleSnapshot; /** * @brief The Ellipse widget provides a colored ellipse to display. */ class OMNIUI_CLASS_API Ellipse : public Shape { OMNIUI_OBJECT(Ellipse) public: OMNIUI_API ~Ellipse() override; protected: /** * @brief Constructs Ellipse */ OMNIUI_API Ellipse(); /** * @brief Reimplemented the rendering code of the shape. * * @see Widget::_drawContent */ OMNIUI_API void _drawShape(float elapsedTime, float x, float y, float width, float height) override; /** * @brief Reimplemented the draw shadow of the shape. */ OMNIUI_API void _drawShadow( float elapsedTime, float x, float y, float width, float height, uint32_t shadowColor, float dpiScale, ImVec2 shadowOffset, float shadowThickness, uint32_t shadowFlag) override; private: // this need to become a property, stylable ? int32_t m_numSegments = 40; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,567
C
22.757575
93
0.67709
omniverse-code/kit/include/omni/ui/StringField.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 "AbstractField.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The StringField widget is a one-line text editor with a string model. */ class OMNIUI_CLASS_API StringField : public AbstractField { OMNIUI_OBJECT(StringField) public: /** * @brief This property holds the password mode. If the field is in the password mode when the entered text is obscured. */ OMNIUI_PROPERTY(bool, passwordMode, DEFAULT, false, READ, isPasswordMode, WRITE, setPasswordMode); /** * @brief This property holds if the field is read-only. */ OMNIUI_PROPERTY(bool, readOnly, DEFAULT, false, READ, isReadOnly, WRITE, setReadOnly); /** * @brief Multiline allows to press enter and create a new line. */ OMNIUI_PROPERTY(bool, multiline, DEFAULT, false, READ, isMultiline, WRITE, setMultiline); /** * @brief This property holds if the field allows Tab input. */ OMNIUI_PROPERTY(bool, allowTabInput, DEFAULT, false, READ, isTabInputAllowed, WRITE, setTabInputAllowed); protected: /** * @brief Constructs StringField * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API StringField(const std::shared_ptr<AbstractValueModel>& model = {}); private: /** * @brief It's necessary to implement it to convert model to string buffer that is displayed by the field. It's * possible to use it for setting the string format. */ std::string _generateTextForField() override; /** * @brief Set/get the field data and the state on a very low level of the underlying system. */ void _updateSystemText(void*) override; /** * @brief Determines the flags that are used in the underlying system widget. */ int32_t _getSystemFlags() const override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
2,327
C
31.788732
124
0.70434
omniverse-code/kit/include/omni/ui/CanvasFrame.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 <imgui/imgui.h> #include "Frame.h" #include "ScrollBarPolicy.h" OMNIUI_NAMESPACE_OPEN_SCOPE struct CanvasFramePrivate; /** * @brief CanvasFrame is a widget that allows the user to pan and zoom its children with a mouse. It has a layout * that can be infinitely moved in any direction. */ class OMNIUI_CLASS_API CanvasFrame : public Frame { OMNIUI_OBJECT(CanvasFrame) public: OMNIUI_API ~CanvasFrame() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Transforms screen-space X to canvas-space X */ OMNIUI_API float screenToCanvasX(float x) const; /** * @brief Transforms screen-space Y to canvas-space Y */ OMNIUI_API float screenToCanvasY(float y) const; /** * @brief Specify the mouse button and key to pan the canvas. */ OMNIUI_API void setPanKeyShortcut(uint32_t mouseButton, carb::input::KeyboardModifierFlags keyFlag); /** * @brief Specify the mouse button and key to zoom the canvas. */ OMNIUI_API void setZoomKeyShortcut(uint32_t mouseButton, carb::input::KeyboardModifierFlags keyFlag); /** * @brief The horizontal offset of the child item. */ OMNIUI_PROPERTY(float, panX, DEFAULT, 0.0f, READ, getPanX, WRITE, setPanX, NOTIFY, setPanXChangedFn); /** * @brief The vertical offset of the child item. */ OMNIUI_PROPERTY(float, panY, DEFAULT, 0.0f, READ, getPanY, WRITE, setPanY, NOTIFY, setPanYChangedFn); /** * @brief The zoom level of the child item. */ OMNIUI_PROPERTY(float, zoom, DEFAULT, 1.0f, READ, getZoom, WRITE, setZoom, NOTIFY, setZoomChangedFn); /** * @brief The zoom minimum of the child item. */ OMNIUI_PROPERTY(float, zoomMin, DEFAULT, 0.0f, READ, getZoomMin, WRITE, setZoomMin, NOTIFY, setZoomMinChangedFn); /** * @brief The zoom maximum of the child item. */ OMNIUI_PROPERTY(float, zoomMax, DEFAULT, std::numeric_limits<float>::max(), READ, getZoomMax, WRITE, setZoomMax, NOTIFY, setZoomMaxChangedFn); /** * @brief When true, zoom is smooth like in Bifrost even if the user is using mouse wheel that doesn't provide * smooth scrolling. */ OMNIUI_PROPERTY(bool, smoothZoom, DEFAULT, false, READ, isSmoothZoom, WRITE, setSmoothZoom); /** * @brief Provides a convenient way to make the content draggable and zoomable. */ OMNIUI_PROPERTY(bool, draggable, DEFAULT, true, READ, isDraggable, WRITE, setDraggable); /** * @brief This boolean property controls the behavior of CanvasFrame. When * set to true, the widget will function in the old way. When set to false, * the widget will use a newer and faster implementation. This variable is * included as a transition period to ensure that the update does not break * any existing functionality. Please be aware that the old behavior may be * deprecated in the future, so it is recommended to set this variable to * false once you have thoroughly tested the new implementation. */ OMNIUI_PROPERTY(bool, compatibility, DEFAULT, true, READ, isCompatibility, WRITE, setCompatibility, PROTECTED, NOTIFY, _setCompatibilityChangedFn); protected: /** * @brief Constructs CanvasFrame */ OMNIUI_API CanvasFrame(); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; /** * @brief Returns true to let the children widgets know they are in scalable * environment. * * @return bool - true */ OMNIUI_API bool _isParentCanvasFrame() const override; private: /** * @brief This function contains the drawing code for the old behavior of * the widget. It's only called when the 'compatibility' variable is set to * true. This function is included as a transition period to ensure that the * update does not break any existing functionality. Please be aware that * the old behavior may be deprecated in the future. */ void _drawContentCompatibility(float elapsedTime); // True when the user pans the child. We need it to know if the user did it on the previous frame to be able to // continue panning outside of the widget. bool m_panActive = false; // That's how the pan is initiated uint32_t m_panMouseButton; carb::input::KeyboardModifierFlags m_panKeyFlag; // That's how the zoom is initiated uint32_t m_zoomMouseButton; carb::input::KeyboardModifierFlags m_zoomKeyFlag; // focus position for mouse move scrolling zoom ImVec2 m_focusPosition; // flag to show whether the mouse moving zoom is active bool m_zoomMoveActive = false; // The real zoom, we need it to make the zoom smooth when scrolling with mouse. float m_zoomSmooth; // Return the zoom with limits cap float _getZoom(float zoom); std::unique_ptr<CanvasFramePrivate> m_prv; // only mouse click inside the CanvasFrame considers the signal of checking the pan and zoom bool m_panStarted = false; bool m_zoomStarted = false; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
6,340
C
31.352041
146
0.672713
omniverse-code/kit/include/omni/ui/MenuBar.h
// Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Menu.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The MenuBar class provides a MenuBar at the top of the Window, could also be the MainMenuBar of the MainWindow * * it can only contain Menu, at the moment there is no way to remove item appart from clearing it all together */ class OMNIUI_CLASS_API MenuBar : public Menu { OMNIUI_OBJECT(MenuBar) public: OMNIUI_API ~MenuBar() override; protected: /** * @brief Construct MenuBar */ OMNIUI_API MenuBar(bool mainMenuBar = false); /** * @brief Reimplemented the rendering code of the widget. * * Draw the content. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: void _drawContentCompatibility(float elapsedTime); bool m_mainMenuBar = { false }; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,333
C
24.653846
120
0.714179
omniverse-code/kit/include/omni/ui/ContainerScope.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 "Api.h" #include <memory> #include <stack> // Creates the scope with the given stack widget. So all the items in the scope will be automatically placed to the // given stack. // TODO: Probably it's not the best name. #define OMNIKIT_WITH_CONTAINER(A) \ for (omni::ui::ContainerScope<> __parent{ A }; __parent.isValid(); __parent.invalidate()) OMNIUI_NAMESPACE_OPEN_SCOPE class Container; class Widget; /** * @brief Singleton object that holds the stack of containers. We use it to automatically add widgets to the top * container when the widgets are created. */ class OMNIUI_CLASS_API ContainerStack { public: // Singleton pattern. ContainerStack(const ContainerStack&) = delete; ContainerStack& operator=(const ContainerStack&) = delete; // No move constructor and no move-assignments are allowed because of 12.8 [class.copy]/9 and 12.8 [class.copy]/20 // of the C++ standard /** * @brief The only instance of the singleton. */ OMNIUI_API static ContainerStack& instance(); /** * @brief Push the container to the top of the stack. All the newly created widgets will be added to this container. */ OMNIUI_API void push(std::shared_ptr<Container> current); /** * @brief Removes the container from the stack. The previous one will be active. */ OMNIUI_API void pop(); /** * @brief Add the given widget to the top container. */ OMNIUI_API bool addChildToTop(std::shared_ptr<Widget> child); private: // Disallow instantiation outside of the class. ContainerStack() = default; std::stack<std::shared_ptr<Container>> m_stack; }; /** * @brief Puts the given container to the top of the stack when this object is constructed. And removes this container * when it's destructed. */ class OMNIUI_CLASS_API ContainerScopeBase { public: OMNIUI_API ContainerScopeBase(const std::shared_ptr<Container> current); OMNIUI_API virtual ~ContainerScopeBase(); /** * @brief Returns the container it was created with. */ const std::shared_ptr<Container>& get() const { return m_current; } /** * @brief Checks if this object is valid. It's always valid untill it's invalidated. Once it's invalidated, there is * no way to make it valid again. */ bool isValid() const { return m_isValid; } /** * @brief Makes this object invalid. */ void invalidate() { m_isValid = false; } private: std::shared_ptr<Container> m_current; bool m_isValid; }; /** * @brief The templated class ContainerScope creates a new container and puts it to the top of the stack. */ template <class T = void> class ContainerScope : public ContainerScopeBase { public: template <typename... Args> ContainerScope(Args&&... args) : ContainerScopeBase{ T::create(std::forward<Args>(args)...) } { } }; /** * @brief Specialization. It takes existing container and puts it to the top of the stack. */ template <> class ContainerScope<void> : public ContainerScopeBase { public: template <typename... Args> ContainerScope(const std::shared_ptr<Container> current) : ContainerScopeBase{ std::move(current) } { } }; OMNIUI_NAMESPACE_CLOSE_SCOPE
3,845
C
26.084507
120
0.66762
omniverse-code/kit/include/omni/ui/Button.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 "Alignment.h" #include "InvisibleButton.h" #include "Stack.h" OMNIUI_NAMESPACE_OPEN_SCOPE class Label; class Rectangle; class Image; /** * @brief The Button widget provides a command button. * * The command button, is perhaps the most commonly used widget in any graphical user interface. Click a button to * execute a command. It is rectangular and typically displays a text label describing its action. */ class OMNIUI_CLASS_API Button : public InvisibleButton { OMNIUI_OBJECT(Button) public: OMNIUI_API ~Button() override; OMNIUI_API void destroy() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the text. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the text. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented. Something happened with the style or with the parent style. We need to gerenerate the * cache. */ OMNIUI_API void onStyleUpdated() override; /** * @brief Reimplemented. It's called when the style is changed. It should be propagated to children to make the * style cached and available to children. */ OMNIUI_API void cascadeStyle() override; /** * @brief This property holds the button's text. */ OMNIUI_PROPERTY(std::string, text, READ, getText, WRITE, setText, NOTIFY, setTextChangedFn); /** * @brief This property holds the button's optional image URL. */ OMNIUI_PROPERTY(std::string, imageUrl, READ, getImageUrl, WRITE, setImageUrl, NOTIFY, setImageUrlChangedFn); /** * @brief This property holds the width of the image widget. Do not use this function to find the width of the * image. */ OMNIUI_PROPERTY(Length, imageWidth, DEFAULT, Fraction{ 1.0f }, READ, getImageWidth, WRITE, setImageWidth, NOTIFY, setImageWidthChangedFn); /** * @brief This property holds the height of the image widget. Do not use this function to find the height of the * image. */ OMNIUI_PROPERTY(Length, imageHeight, DEFAULT, Fraction{ 1.0f }, READ, getImageHeight, WRITE, setImageHeight, NOTIFY, setImageHeightChangedFn); /** * @brief Sets a non-stretchable space in points between image and text. */ OMNIUI_PROPERTY(float, spacing, DEFAULT, 0.0f, READ, getSpacing, WRITE, setSpacing, NOTIFY, setSpacingChangedFn); protected: /** * @brief Construct a button with a text on it. * * @param text The text for the button to use. */ OMNIUI_API Button(const std::string& text = {}); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: /** * @brief Compute the size of the button and save result to the private members. */ void _computeButtonSize(); /** * @brief Return the name of the child widget. Basically it creates a string like this: "Button.{childType}". */ std::string _childTypeName(const std::string& childType) const; // Flag that the content size is computed. We need it because we don't want to recompute the size each call of // draw(). bool m_minimalContentSizeComputed = false; float m_minimalContentWidth; float m_minimalContentHeight; // Flag when the image visibility can potentially be changed bool m_imageVisibilityUpdated = false; // The background rectangle of the button for fast access. std::shared_ptr<Rectangle> m_rectangleWidget; // The main layout. All the sub-widgets (Label and Rectangle) are children of the main layout. std::shared_ptr<Stack> m_labelImageLayout; // The text of the button for fast access. std::shared_ptr<Label> m_labelWidget; std::shared_ptr<Image> m_imageWidget; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
5,159
C
30.851852
117
0.648769
omniverse-code/kit/include/omni/ui/SimpleStringModel.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 "AbstractValueModel.h" #include <memory> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief A very simple value model that holds a single string. */ class OMNIUI_CLASS_API SimpleStringModel : public AbstractValueModel { public: using Base = SimpleStringModel; using CarriedType = std::string; template <typename... Args> static std::shared_ptr<SimpleStringModel> create(Args&&... args) { /* make_shared doesn't work because the constructor is protected: */ /* auto ptr = std::make_shared<This>(std::forward<Args>(args)...); */ /* TODO: Find the way to use make_shared */ return std::shared_ptr<SimpleStringModel>{ new SimpleStringModel{ std::forward<Args>(args)... } }; } /** * @brief Get the value. */ OMNIUI_API bool getValueAsBool() const override; OMNIUI_API double getValueAsFloat() const override; OMNIUI_API int64_t getValueAsInt() const override; OMNIUI_API std::string getValueAsString() const override; /** * @brief Set the value. */ OMNIUI_API void setValue(bool value) override; OMNIUI_API void setValue(double value) override; OMNIUI_API void setValue(int64_t value) override; OMNIUI_API void setValue(std::string value) override; protected: OMNIUI_API SimpleStringModel(const std::string& defaultValue = {}); private: std::string m_value; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,908
C
27.073529
106
0.694444
omniverse-code/kit/include/omni/ui/ScrollBarPolicy.h
// Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include <cstdint> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Describes when the scroll bar should appear. */ enum class ScrollBarPolicy : uint8_t { /** * @brief Show a scroll bar when the content is too big to fit to the provided area. */ eScrollBarAsNeeded = 0, /** * @brief Never show a scroll bar. */ eScrollBarAlwaysOff, /** * @brief Always show a scroll bar. */ eScrollBarAlwaysOn }; OMNIUI_NAMESPACE_CLOSE_SCOPE
949
C
23.358974
88
0.710221
omniverse-code/kit/include/omni/ui/Spacer.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 "Widget.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The Spacer class provides blank space. * * Normally, it's used to place other widgets correctly in a layout. * * TODO: Do we need to handle mouse events in this class? */ class OMNIUI_CLASS_API Spacer : public Widget { OMNIUI_OBJECT(Spacer) public: OMNIUI_API ~Spacer() override; protected: /** * @brief Construct Spacer */ OMNIUI_API Spacer(); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,121
C
22.87234
77
0.709188
omniverse-code/kit/include/omni/ui/MenuItemCollection.h
// Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Menu.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The MenuItemCollection is the menu that unchecks children when one of * them is checked */ class OMNIUI_CLASS_API MenuItemCollection : public Menu { OMNIUI_OBJECT(MenuItemCollection) public: OMNIUI_API ~MenuItemCollection() override; /** * @brief Adds the menu. We subscribe to the `checked` changes and uncheck * others. */ void addChild(std::shared_ptr<Widget> widget) override; protected: /** * @brief Construct MenuItemCollection */ OMNIUI_API MenuItemCollection(const std::string& text = ""); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,108
C
25.404761
79
0.729242
omniverse-code/kit/include/omni/ui/StyleStore.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 "Api.h" #include <algorithm> #include <cctype> #include <string> #include <vector> OMNIUI_NAMESPACE_OPEN_SCOPE inline std::string __toLower(std::string name) { std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) { return std::tolower(c); }); return name; } /** * @brief A common template for indexing the style properties of the specific * types. */ template <typename T> class StyleStore { public: OMNIUI_API virtual ~StyleStore() = default; /** * @brief Save the color by name */ OMNIUI_API virtual void store(const std::string& name, T color, bool readOnly = false) { size_t found = this->find(name); if (found == SIZE_MAX) { m_store.emplace_back(__toLower(name), color, readOnly); } else if (!m_store[found].readOnly) { m_store[found].value = color; m_store[found].readOnly = readOnly; } } /** * @brief Return the color by index. */ OMNIUI_API T get(size_t id) const { if (id == SIZE_MAX) { return static_cast<T>(NULL); } return m_store[id].value; } /** * @brief Return the index of the color with specific name. */ OMNIUI_API size_t find(const std::string& name) const { std::string lowerName = __toLower(name); auto found = std::find_if(m_store.begin(), m_store.end(), [&lowerName](const auto& it) { return it.name == lowerName; }); if (found != m_store.end()) { return std::distance(m_store.begin(), found); } return SIZE_MAX; } protected: StyleStore() { } struct Entry { Entry(std::string entryName, T entryValue, bool entryReadOnly = false) : name{ std::move(entryName) }, value{ entryValue }, readOnly{ entryReadOnly } { } std::string name; T value; bool readOnly; }; std::vector<Entry> m_store; }; /** * @brief A singleton that stores all the UI Style color properties of omni.ui. */ class OMNIUI_CLASS_API ColorStore : public StyleStore<uint32_t> { public: /** * @brief Get the instance of this singleton object. */ OMNIUI_API static ColorStore& getInstance(); // A singleton pattern ColorStore(ColorStore const&) = delete; void operator=(ColorStore const&) = delete; private: ColorStore(); }; /** * @brief A singleton that stores all the UI Style float properties of omni.ui. */ class OMNIUI_CLASS_API FloatStore : public StyleStore<float> { public: /** * @brief Get the instance of this singleton object. */ OMNIUI_API static FloatStore& getInstance(); // A singleton pattern FloatStore(FloatStore const&) = delete; void operator=(FloatStore const&) = delete; private: FloatStore(); }; /** * @brief A singleton that stores all the UI Style string properties of omni.ui. */ class OMNIUI_CLASS_API StringStore : public StyleStore<const char*> { public: OMNIUI_API ~StringStore() override; /** * @brief Get the instance of this singleton object. */ OMNIUI_API static StringStore& getInstance(); // A singleton pattern StringStore(StringStore const&) = delete; void operator=(StringStore const&) = delete; OMNIUI_API void store(const std::string& name, const char* string_value, bool readOnly = false) override; private: StringStore(); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
4,024
C
22.265896
120
0.622763
omniverse-code/kit/include/omni/ui/Alignment.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // //! @file //! //! @brief omni::ui Alignment types. #pragma once #include "Api.h" #include <cstdint> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Used when it's necessary to align the content to the wigget. */ enum Alignment : uint8_t { eUndefined = 0, eLeft = 1 << 1, eRight = 1 << 2, eHCenter = 1 << 3, eTop = 1 << 4, eBottom = 1 << 5, eVCenter = 1 << 6, eLeftTop = eLeft | eTop, eLeftCenter = eLeft | eVCenter, eLeftBottom = eLeft | eBottom, eCenterTop = eHCenter | eTop, eCenter = eHCenter | eVCenter, eCenterBottom = eHCenter | eBottom, eRightTop = eRight | eTop, eRightCenter = eRight | eVCenter, eRightBottom = eRight | eBottom, }; OMNIUI_NAMESPACE_CLOSE_SCOPE
1,179
C
22.6
77
0.681086