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
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/core/PathUtils.cpp
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "PathUtils.h" #include <carb/logging/Log.h> #include <algorithm> #include <cctype> #include <cstring> #include <errno.h> #include <vector> #ifdef _WIN32 # include <direct.h> # include <windows.h> #else # include <sys/stat.h> # include <dirent.h> # include <unistd.h> #endif namespace omni { namespace importer { namespace urdf { PathType testPath(const char* path) { if (!path || !*path) { return PathType::eNone; } #ifdef _WIN32 DWORD attribs = GetFileAttributesA(path); if (attribs == INVALID_FILE_ATTRIBUTES) { return PathType::eNone; } else if (attribs & FILE_ATTRIBUTE_DIRECTORY) { return PathType::eDirectory; } else { // hmmm return PathType::eFile; } #else struct stat s; if (stat(path, &s) == -1) { return PathType::eNone; } else if (S_ISREG(s.st_mode)) { return PathType::eFile; } else if (S_ISDIR(s.st_mode)) { return PathType::eDirectory; } else { return PathType::eOther; } #endif } bool isAbsolutePath(const char* path) { if (!path || !*path) { return false; } #ifdef _WIN32 if (path[0] == '\\' || path[0] == '/') { return true; } else if (std::isalpha(path[0]) && path[1] == ':') { return true; } else { return false; } #else return path[0] == '/'; #endif } std::string pathJoin(const std::string& path1, const std::string& path2) { if (path1.empty()) { return path2; } else { auto last = path1.rbegin(); #ifdef _WIN32 if (*last != '/' && *last != '\\') #else if (*last != '/') #endif { return path1 + '/' + path2; } else { return path1 + path2; } } } std::string getCwd() { std::vector<char> buf(4096); #ifdef _WIN32 if (!_getcwd(buf.data(), int(buf.size()))) #else if (!getcwd(buf.data(), size_t(buf.size()))) #endif { return std::string(); } return std::string(buf.data()); } static int sysmkdir(const char* path) { #ifdef _WIN32 return _mkdir(path); #else return mkdir(path, 0755); #endif } static std::vector<std::string> tokenizePath(const char* path_) { std::vector<std::string> components; if (!path_ || !*path_) { return components; } std::string path(path_); size_t start = 0; bool done = false; while (!done) { #ifdef _WIN32 size_t end = path.find_first_of("/\\", start); #else size_t end = path.find_first_of('/', start); #endif if (end == std::string::npos) { end = path.length(); done = true; } if (end - start > 0) { components.push_back(path.substr(start, end - start)); } start = end + 1; } return components; } bool makeDirectory(const char* path) { std::vector<std::string> components = tokenizePath(path); if (components.empty()) { return false; } std::string pathSoFar; #ifndef _WIN32 // on Unixes, need to start with leading slash if absolute path if (isAbsolutePath(path)) { pathSoFar = "/"; } #endif for (unsigned i = 0; i < components.size(); i++) { if (i > 0) { pathSoFar += '/'; } pathSoFar += components[i]; if (sysmkdir(pathSoFar.c_str()) != 0 && errno != EEXIST) { fprintf(stderr, "*** Failed to create directory '%s'\n", pathSoFar.c_str()); return false; } // printf("Creating '%s'\n", pathSoFar.c_str()); } return true; } std::string getPathStem(const char* path) { if (!path || !*path) { return ""; } const char* p = strrchr(path, '/'); #ifdef _WIN32 const char* q = strrchr(path, '\\'); if (q > p) { p = q; } #endif const char* fnameStart = p ? p + 1 : path; const char* ext = strrchr(fnameStart, '.'); if (ext) { return std::string(fnameStart, ext); } else { return fnameStart; } } static void getFileListRecursiveRec(const std::string& dir, std::vector<std::string>& flist) { #if _WIN32 WIN32_FIND_DATAA fdata; memset(&fdata, 0, sizeof(fdata)); std::string pattern = dir + "\\*"; HANDLE handle = FindFirstFileA(pattern.c_str(), &fdata); while (handle != INVALID_HANDLE_VALUE) { if ((fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) { if (strcmp(fdata.cFileName, ".") != 0 && strcmp(fdata.cFileName, "..") != 0) { getFileListRecursiveRec(dir + '\\' + fdata.cFileName, flist); } } else { flist.push_back(dir + '\\' + fdata.cFileName); } if (FindNextFileA(handle, &fdata) == FALSE) { break; } } FindClose(handle); #else DIR* d = opendir(dir.c_str()); if (d) { struct dirent* dent; while ((dent = readdir(d)) != nullptr) { if (dent->d_type == DT_DIR) { if (strcmp(dent->d_name, ".") != 0 && strcmp(dent->d_name, "..") != 0) { getFileListRecursiveRec(dir + '/' + dent->d_name, flist); } } else if (dent->d_type == DT_REG) { flist.push_back(dir + '/' + dent->d_name); } } closedir(d); } #endif } std::vector<std::string> getFileListRecursive(const std::string& dir, bool sorted) { std::vector<std::string> flist; getFileListRecursiveRec(dir, flist); if (sorted) { std::sort(flist.begin(), flist.end()); } return flist; } std::string makeValidUSDIdentifier(const std::string& name) { auto validName = pxr::TfMakeValidIdentifier(name); if (validName[0] == '_') { validName = "a" + validName; } if (pxr::TfIsValidIdentifier(name) == false) { CARB_LOG_WARN("The path %s is not a valid usd path, modifying to %s", name.c_str(), validName.c_str()); } return validName; } } } }
7,015
C++
19.635294
111
0.535567
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/parse/UrdfParser.cpp
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "UrdfParser.h" #include "../core/PathUtils.h" #include <carb/logging/Log.h> namespace omni { namespace importer { namespace urdf { // Stream operators for nice printing std::ostream& operator<<(std::ostream& out, const Transform& origin) { out << "Origin: "; out << "px=" << origin.p.x << " py=" << origin.p.y << " pz=" << origin.p.z; out << " qx=" << origin.q.x << " qy=" << origin.q.y << " qz=" << origin.q.z << " qw=" << origin.q.w; return out; } std::ostream& operator<<(std::ostream& out, const UrdfInertia& inertia) { out << "Inertia: "; out << "ixx=" << inertia.ixx << " ixy=" << inertia.ixy << " ixz=" << inertia.ixz; out << " iyy=" << inertia.iyy << " iyz=" << inertia.iyz << " izz=" << inertia.izz; return out; } std::ostream& operator<<(std::ostream& out, const UrdfInertial& inertial) { out << "Inertial: " << std::endl; out << " \t \t" << inertial.origin << std::endl; if (inertial.hasMass) { out << " \t \tMass: " << inertial.mass << std::endl; } else { out << " \t \tMass: No mass was specified for the link" << std::endl; } if (inertial.hasInertia) { out << " \t \t" << inertial.inertia; } else { out << " \t \tInertia: No inertia was specified for the link" << std::endl; } return out; } std::ostream& operator<<(std::ostream& out, const UrdfAxis& axis) { out << "Axis: "; out << "x=" << axis.x << " y=" << axis.y << " z=" << axis.z; return out; } std::ostream& operator<<(std::ostream& out, const UrdfColor& color) { out << "Color: "; out << "r=" << color.r << " g=" << color.g << " b=" << color.b << " a=" << color.a; return out; } std::ostream& operator<<(std::ostream& out, const UrdfJointType& type) { out << "Type: "; std::string jointType = "unknown"; switch (type) { case UrdfJointType::REVOLUTE: jointType = "revolute"; break; case UrdfJointType::CONTINUOUS: jointType = "continuous"; break; case UrdfJointType::PRISMATIC: jointType = "prismatic"; break; case UrdfJointType::FIXED: jointType = "fixed"; break; case UrdfJointType::FLOATING: jointType = "floating"; break; case UrdfJointType::PLANAR: jointType = "planar"; break; } out << jointType; return out; } std::ostream& operator<<(std::ostream& out, const UrdfDynamics& dynamics) { out << "Dynamics: "; out << "damping=" << dynamics.damping << " friction=" << dynamics.friction; return out; } std::ostream& operator<<(std::ostream& out, const UrdfLimit& limit) { out << "Limit: "; out << "lower=" << limit.lower << " upper=" << limit.upper << " effort=" << limit.effort << " velocity=" << limit.velocity; out << std::endl; return out; } std::ostream& operator<<(std::ostream& out, const UrdfGeometry& geometry) { out << "Geometry: "; switch (geometry.type) { case UrdfGeometryType::BOX: out << "type=box size=" << geometry.size_x << " " << geometry.size_y << " " << geometry.size_z; break; case UrdfGeometryType::CYLINDER: out << "type=cylinder radius=" << geometry.radius << " length=" << geometry.length; break; case UrdfGeometryType::CAPSULE: out << "type=capsule radius=" << geometry.radius << " length=" << geometry.length; break; case UrdfGeometryType::SPHERE: out << "type=sphere, radius=" << geometry.radius; break; case UrdfGeometryType::MESH: out << "type=mesh filemame=" << geometry.meshFilePath; break; } return out; } std::ostream& operator<<(std::ostream& out, const UrdfMaterial& material) { out << "Material: "; out << " Name=" << material.name << " " << material.color; if (!material.textureFilePath.empty()) out << " textureFilePath=" << material.textureFilePath; return out; } std::ostream& operator<<(std::ostream& out, const UrdfVisual& visual) { out << "Visual:" << std::endl; if (!visual.name.empty()) out << " \t \tName=" << visual.name << std::endl; out << " \t \t" << visual.origin << std::endl; out << " \t \t" << visual.geometry << std::endl; out << " \t \t" << visual.material; return out; } std::ostream& operator<<(std::ostream& out, const UrdfCollision& collision) { out << "Collision:" << std::endl; if (!collision.name.empty()) out << " \t \tName=" << collision.name << std::endl; out << " \t \t" << collision.origin << std::endl; out << " \t \t" << collision.geometry; return out; } std::ostream& operator<<(std::ostream& out, const UrdfLink& link) { out << "Link: "; out << " \tName=" << link.name << std::endl; for (auto& visual : link.visuals) { out << " \t" << visual << std::endl; } for (auto& collision : link.collisions) { out << " \t" << collision << std::endl; } out << " \t" << link.inertial << std::endl; return out; } std::ostream& operator<<(std::ostream& out, const UrdfJoint& joint) { out << "Joint: "; out << " Name=" << joint.name << std::endl; out << " \t" << joint.type << std::endl; out << " \t" << joint.origin << std::endl; out << " \tParentLinkName=" << joint.parentLinkName << std::endl; out << " \tChildLinkName=" << joint.childLinkName << std::endl; out << " \t" << joint.axis << std::endl; out << " \t" << joint.dynamics << std::endl; out << " \t" << joint.limit << std::endl; out << " \t" << joint.dontCollapse << std::endl; return out; } std::ostream& operator<<(std::ostream& out, const UrdfRobot& robot) { out << "Robot: "; out << robot.name << std::endl; for (auto& link : robot.links) { out << link.second << std::endl; } for (auto& joint : robot.joints) { out << joint.second << std::endl; } for (auto& material : robot.materials) { out << material.second << std::endl; } return out; } using namespace tinyxml2; bool parseXyz(const char* str, float& x, float& y, float& z) { if (sscanf(str, "%f %f %f", &x, &y, &z) == 3) { return true; } else { printf("*** Could not parse xyz string '%s' \n", str); return false; } } bool parseColor(const char* str, float& r, float& g, float& b, float& a) { if (sscanf(str, "%f %f %f %f", &r, &g, &b, &a) == 4) { return true; } else { printf("*** Could not parse color string '%s' \n", str); return false; } } bool parseFloat(const char* str, float& value) { if (sscanf(str, "%f", &value) == 1) { return true; } else { printf("*** Could not parse float string '%s' \n", str); return false; } } bool parseInt(const char* str, int& value) { if (sscanf(str, "%d", &value) == 1) { return true; } else { printf("*** Could not parse int string '%s' \n", str); return false; } } bool parseJointType(const char* str, UrdfJointType& type) { if (strcmp(str, "revolute") == 0) { type = UrdfJointType::REVOLUTE; } else if (strcmp(str, "continuous") == 0) { type = UrdfJointType::CONTINUOUS; } else if (strcmp(str, "prismatic") == 0) { type = UrdfJointType::PRISMATIC; } else if (strcmp(str, "fixed") == 0) { type = UrdfJointType::FIXED; } else if (strcmp(str, "floating") == 0) { type = UrdfJointType::FLOATING; } else if (strcmp(str, "planar") == 0) { type = UrdfJointType::PLANAR; } else { printf("*** Unknown joint type '%s' \n", str); return false; } return true; } bool parseJointMimic(const XMLElement& element, UrdfJointMimic& mimic) { auto jointElement = element.Attribute("joint"); if (jointElement) { mimic.joint = std::string(jointElement); } auto multiplierElement = element.Attribute("multiplier"); if (!multiplierElement || !parseFloat(multiplierElement, mimic.multiplier)) { mimic.multiplier = 1.0f; } auto offsetElement = element.Attribute("offset"); if (!offsetElement ||!parseFloat(offsetElement, mimic.offset)) { mimic.offset = 0; } return true; } bool parseOrigin(const XMLElement& element, Transform& origin) { auto originElement = element.FirstChildElement("origin"); if (originElement) { auto attribute = originElement->Attribute("xyz"); if (attribute) { if (!parseXyz(attribute, origin.p.x, origin.p.y, origin.p.z)) { // optional, use zero vector origin.p = Vec3(0.0); } } attribute = originElement->Attribute("rpy"); if (attribute) { // parse roll pitch yaw float roll = 0.0f; float pitch = 0.0f; float yaw = 0.0f; if (!parseXyz(attribute, roll, pitch, yaw)) { roll = pitch = yaw = 0.0; } // convert to transform quaternion: origin.q = rpy2quat(roll, pitch, yaw); } return true; } return false; } bool parseAxis(const XMLElement& element, UrdfAxis& axis) { auto axisElement = element.FirstChildElement("axis"); if (axisElement) { auto attribute = axisElement->Attribute("xyz"); if (attribute) { if (!parseXyz(attribute, axis.x, axis.y, axis.z)) { printf("*** xyz not specified for axis\n"); return false; } } } return true; } bool parseLimit(const XMLElement& element, UrdfLimit& limit) { auto limitElement = element.FirstChildElement("limit"); if (limitElement) { auto attribute = limitElement->Attribute("lower"); if (attribute) { if (!parseFloat(attribute, limit.lower)) { // optional, use zero if not specified limit.lower = 0.0; } } attribute = limitElement->Attribute("upper"); if (attribute) { if (!parseFloat(attribute, limit.upper)) { // optional, use zero if not specified limit.upper = 0.0; } } attribute = limitElement->Attribute("effort"); if (attribute) { if (!parseFloat(attribute, limit.effort)) { printf("*** effort not specified for limit\n"); return false; } } attribute = limitElement->Attribute("velocity"); if (attribute) { if (!parseFloat(attribute, limit.velocity)) { printf("*** velocity not specified for limit\n"); return false; } } } return true; } bool parseDynamics(const XMLElement& element, UrdfDynamics& dynamics) { auto dynamicsElement = element.FirstChildElement("dynamics"); if (dynamicsElement) { auto attribute = dynamicsElement->Attribute("damping"); if (attribute) { if (!parseFloat(attribute, dynamics.damping)) { // optional dynamics.damping = 0; } } attribute = dynamicsElement->Attribute("friction"); if (attribute) { if (!parseFloat(attribute, dynamics.friction)) { // optional dynamics.friction = 0; } } } return true; } bool parseMass(const XMLElement& element, float& mass) { auto massElement = element.FirstChildElement("mass"); if (massElement) { auto attribute = massElement->Attribute("value"); if (attribute) { if (!parseFloat(attribute, mass)) { printf("*** couldn't parse mass \n"); return false; } return true; } else { printf("*** mass missing from inertia \n"); return false; } } return false; } bool parseInertia(const XMLElement& element, UrdfInertia& inertia) { auto inertiaElement = element.FirstChildElement("inertia"); if (inertiaElement) { auto attribute = inertiaElement->Attribute("ixx"); if (attribute) { if (!parseFloat(attribute, inertia.ixx)) { return false; } } else { printf("*** ixx missing from inertia \n"); return false; } attribute = inertiaElement->Attribute("ixz"); if (attribute) { if (!parseFloat(attribute, inertia.ixz)) { return false; } } else { printf("*** ixz missing from inertia \n"); return false; } attribute = inertiaElement->Attribute("ixy"); if (attribute) { if (!parseFloat(attribute, inertia.ixy)) { return false; } } else { printf("*** ixy missing from inertia \n"); return false; } attribute = inertiaElement->Attribute("iyy"); if (attribute) { if (!parseFloat(attribute, inertia.iyy)) { return false; } } else { printf("*** iyy missing from inertia \n"); return false; } attribute = inertiaElement->Attribute("iyz"); if (attribute) { if (!parseFloat(attribute, inertia.iyz)) { return false; } } else { printf("*** iyz missing from inertia \n"); return false; } attribute = inertiaElement->Attribute("izz"); if (attribute) { if (!parseFloat(attribute, inertia.izz)) { return false; } } else { printf("*** izz missing from inertia \n"); return false; } // if we made it here, all elements were parsed successfully return true; } return false; } bool parseInertial(const XMLElement& element, UrdfInertial& inertial) { auto inertialElement = element.FirstChildElement("inertial"); if (inertialElement) { inertial.hasOrigin = parseOrigin(*inertialElement, inertial.origin); inertial.hasMass = parseMass(*inertialElement, inertial.mass); inertial.hasInertia = parseInertia(*inertialElement, inertial.inertia); } return true; } bool parseGeometry(const XMLElement& element, UrdfGeometry& geometry) { auto geometryElement = element.FirstChildElement("geometry"); if (geometryElement) { auto geometryElementChild = geometryElement->FirstChildElement(); if (strcmp(geometryElementChild->Value(), "mesh") == 0) { geometry.type = UrdfGeometryType::MESH; auto filename = geometryElementChild->Attribute("filename"); if (filename) { geometry.meshFilePath = filename; } else { printf("*** mesh geometry requires a file path \n"); return false; } auto scale = geometryElementChild->Attribute("scale"); if (scale) { if (!parseXyz(scale, geometry.scale_x, geometry.scale_y, geometry.scale_z)) { printf("*** scale is missing xyz \n"); return false; } } } else if (strcmp(geometryElementChild->Value(), "box") == 0) { geometry.type = UrdfGeometryType::BOX; auto attribute = geometryElementChild->Attribute("size"); if (attribute) { if (!parseXyz(attribute, geometry.size_x, geometry.size_y, geometry.size_z)) { printf("*** couldn't parse xyz size \n"); return false; } } else { printf("*** box geometry requires a size \n"); return false; } } else if (strcmp(geometryElementChild->Value(), "cylinder") == 0) { geometry.type = UrdfGeometryType::CYLINDER; auto attribute = geometryElementChild->Attribute("radius"); if (attribute) { if (!parseFloat(attribute, geometry.radius)) { printf("*** couldn't parse radius \n"); return false; } } else { printf("*** cylinder geometry requires a radius \n"); return false; } attribute = geometryElementChild->Attribute("length"); if (attribute) { if (!parseFloat(attribute, geometry.length)) { printf("*** couldn't parse length \n"); return false; } } else { printf("*** cylinder geometry requires a length \n"); return false; } } else if (strcmp(geometryElementChild->Value(), "capsule") == 0) { geometry.type = UrdfGeometryType::CAPSULE; auto attribute = geometryElementChild->Attribute("radius"); if (attribute) { if (!parseFloat(attribute, geometry.radius)) { printf("*** couldn't parse radius \n"); return false; } } else { printf("*** capsule geometry requires a radius \n"); return false; } attribute = geometryElementChild->Attribute("length"); if (attribute) { if (!parseFloat(attribute, geometry.length)) { printf("*** couldn't parse length \n"); return false; } } else { printf("*** capsule geometry requires a length \n"); return false; } } else if (strcmp(geometryElementChild->Value(), "sphere") == 0) { geometry.type = UrdfGeometryType::SPHERE; auto attribute = geometryElementChild->Attribute("radius"); if (attribute) { if (!parseFloat(attribute, geometry.radius)) { printf("*** couldn't parse radius \n"); return false; } } else { printf("*** sphere geometry requires a radius \n"); return false; } } } return true; } bool parseChildAttributeFloat(const tinyxml2::XMLElement& element, const char* child, const char* attribute, float& output) { auto childElement = element.FirstChildElement(child); if (childElement) { const char* s = childElement->Attribute(attribute); if (s) { return parseFloat(s, output); } } return false; } bool parseChildAttributeString(const tinyxml2::XMLElement& element, const char* child, const char* attribute, std::string& output) { auto childElement = element.FirstChildElement(child); if (childElement) { const char* s = childElement->Attribute(attribute); if (s) { output = s; return true; } } return false; } // bool parseFem(const tinyxml2::XMLElement& element, UrdfFem& fem) // { // parseOrigin(element, fem.origin); // if (!parseChildAttributeFloat(element, "density", "value", fem.density)) // fem.density = 1000.0f; // if (!parseChildAttributeFloat(element, "youngs", "value", fem.youngs)) // fem.youngs = 1.e+4f; // if (!parseChildAttributeFloat(element, "poissons", "value", fem.poissons)) // fem.poissons = 0.3f; // if (!parseChildAttributeFloat(element, "damping", "value", fem.damping)) // fem.damping = 0.0f; // if (!parseChildAttributeFloat(element, "attachDistance", "value", fem.attachDistance)) // fem.attachDistance = 0.0f; // if (!parseChildAttributeString(element, "tetmesh", "filename", fem.meshFilePath)) // fem.meshFilePath = ""; // if (!parseChildAttributeFloat(element, "scale", "value", fem.scale)) // fem.scale = 1.0f; // return true; // } bool parseMaterial(const XMLElement& element, UrdfMaterial& material) { auto materialElement = element.FirstChildElement("material"); if (materialElement) { auto name = materialElement->Attribute("name"); if (name && strlen(name) > 0) { material.name = makeValidUSDIdentifier(name); } else { if (materialElement->FirstChildElement("color")) { if (!parseColor(materialElement->FirstChildElement("color")->Attribute("rgba"), material.color.r, material.color.g, material.color.b, material.color.a)) { // optional material.color = UrdfColor(); } } if (materialElement->FirstChildElement("texture")) { auto matString = materialElement->FirstChildElement("texture")->Attribute("filename"); if (matString == nullptr) { printf("*** filename required for material with texture \n"); return false; } material.textureFilePath = matString; } } } return true; } bool parseMaterials(const XMLElement& root, std::map<std::string, UrdfMaterial>& urdfMaterials) { auto materialElement = root.FirstChildElement("material"); if (materialElement) { do { UrdfMaterial material; auto name = materialElement->Attribute("name"); if (name) { material.name = makeValidUSDIdentifier(name); } else { printf("*** Found unnamed material \n"); return false; } auto elem = materialElement->FirstChildElement("color"); if (elem) { if (!parseColor(elem->Attribute("rgba"), material.color.r, material.color.g, material.color.b, material.color.a)) { return false; } } elem = materialElement->FirstChildElement("texture"); if (elem) { auto matString = elem->Attribute("filename"); if (matString == nullptr) { printf("*** filename required for material with texture \n"); return false; } } urdfMaterials.emplace(material.name, material); } while ((materialElement = materialElement->NextSiblingElement("material"))); } return true; } bool parseLinks(const XMLElement& root, std::map<std::string, UrdfLink>& urdfLinks) { auto linkElement = root.FirstChildElement("link"); if (linkElement) { do { UrdfLink link; // name auto name = linkElement->Attribute("name"); if (name) { link.name = makeValidUSDIdentifier(name); } else { printf("*** Found unnamed link \n"); return false; } // visuals auto visualElement = linkElement->FirstChildElement("visual"); if (visualElement) { do { UrdfVisual visual; auto name = visualElement->Attribute("name"); if (name) { visual.name = makeValidUSDIdentifier(name); } if (!parseOrigin(*visualElement, visual.origin)) { // optional default to identity transform visual.origin = Transform(); } if (!parseGeometry(*visualElement, visual.geometry)) { printf("*** Found visual without geometry \n"); return false; } if (!parseMaterial(*visualElement, visual.material)) { // optional, use default if not specified visual.material = UrdfMaterial(); } link.visuals.push_back(visual); } while ((visualElement = visualElement->NextSiblingElement("visual"))); } // collisions auto collisionElement = linkElement->FirstChildElement("collision"); if (collisionElement) { do { UrdfCollision collision; auto name = collisionElement->Attribute("name"); if (name) { collision.name = makeValidUSDIdentifier(name); } if (!parseOrigin(*collisionElement, collision.origin)) { // optional default to identity transform collision.origin = Transform(); } if (!parseGeometry(*collisionElement, collision.geometry)) { printf("*** Found collision without geometry \n"); return false; } link.collisions.push_back(collision); } while ((collisionElement = collisionElement->NextSiblingElement("collision"))); } // inertia if (!parseInertial(*linkElement, link.inertial)) { // optional, use default if not specified link.inertial = UrdfInertial(); } // auto femElement = linkElement->FirstChildElement("fem"); // if (femElement) // { // do // { // UrdfFem fem; // if (!parseFem(*femElement, fem)) // { // return false; // } // link.softs.push_back(fem); // } while ((femElement = femElement->NextSiblingElement("fem"))); // } urdfLinks.emplace(link.name, link); } while ((linkElement = linkElement->NextSiblingElement("link"))); } return true; } bool parseJoints(const XMLElement& root, std::map<std::string, UrdfJoint>& urdfJoints) { for(auto jointElement = root.FirstChildElement("joint"); jointElement; jointElement = jointElement->NextSiblingElement("joint")) { UrdfJoint joint; // name auto name = jointElement->Attribute("name"); if (name) { joint.name = makeValidUSDIdentifier(name); } else { printf("*** Found unnamed joint \n"); return false; } auto type = jointElement->Attribute("type"); if (type) { if (!parseJointType(type, joint.type)) { return false; } } else { printf("*** Found untyped joint \n"); return false; } auto dontCollapse = jointElement->Attribute("dont_collapse"); if (dontCollapse) { joint.dontCollapse = dontCollapse; } else { // default: if not specified, collapse the joint joint.dontCollapse = false; } auto parentElement = jointElement->FirstChildElement("parent"); if (parentElement) { joint.parentLinkName = makeValidUSDIdentifier(parentElement->Attribute("link")); } else { printf("*** Joint has no parent link \n"); return false; } auto childElement = jointElement->FirstChildElement("child"); if (childElement) { joint.childLinkName = makeValidUSDIdentifier(childElement->Attribute("link")); } else { printf("*** Joint has no child link \n"); return false; } if (!parseOrigin(*jointElement, joint.origin)) { // optional, default to identity joint.origin = Transform(); } if (!parseAxis(*jointElement, joint.axis)) { // optional, default to (1,0,0) joint.axis = UrdfAxis(); } if (!parseLimit(*jointElement, joint.limit)) { if (joint.type == UrdfJointType::REVOLUTE || joint.type == UrdfJointType::PRISMATIC) { printf("*** limit must be specified for revolute and prismatic \n"); return false; } joint.limit = UrdfLimit(); } if (!parseDynamics(*jointElement, joint.dynamics)) { // optional joint.dynamics = UrdfDynamics(); } urdfJoints.emplace(joint.name, joint); } // Add second pass to parse mimic information for(auto jointElement = root.FirstChildElement("joint"); jointElement; jointElement = jointElement->NextSiblingElement("joint")) { auto name = jointElement->Attribute("name"); if (name) { UrdfJoint& joint = urdfJoints[makeValidUSDIdentifier(name)]; auto mimicElement = jointElement->FirstChildElement("mimic"); if (mimicElement) { if(!parseJointMimic(*mimicElement, joint.mimic)) { joint.mimic.joint = ""; } else { auto& parentJoint = urdfJoints[joint.mimic.joint]; parentJoint.mimicChildren[joint.name] = joint.mimic.offset; } } } } return true; } // bool parseSpringGroup(const XMLElement& element, UrdfSpringGroup& springGroup) // { // auto start = element.Attribute("start"); // auto count = element.Attribute("size"); // auto scale = element.Attribute("scale"); // if (!start || !parseInt(start, springGroup.springStart)) // { // return false; // } // if (!count || !parseInt(count, springGroup.springCount)) // { // return false; // } // if (!scale || !parseFloat(scale, springGroup.scale)) // { // return false; // } // return true; // } // bool parseSoftActuators(const XMLElement& root, std::vector<UrdfSoft1DActuator>& urdfActs) // { // auto actuatorElement = root.FirstChildElement("actuator"); // while (actuatorElement) // { // auto name = actuatorElement->Attribute("name"); // auto type = actuatorElement->Attribute("type"); // if (type) // { // if (strcmp(type, "pneumatic1D") == 0) // { // UrdfSoft1DActuator act; // act.name = std::string(name); // act.link = std::string(actuatorElement->Attribute("link")); // auto gains = actuatorElement->FirstChildElement("gains"); // auto thresholds = actuatorElement->FirstChildElement("thresholds"); // auto springGroups = actuatorElement->FirstChildElement("springGroups"); // auto maxPressure = actuatorElement->Attribute("maxPressure"); // if (!maxPressure || !parseFloat(maxPressure, act.maxPressure)) // { // act.maxPressure = 0.0f; // } // if (gains) // { // auto inflate = gains->Attribute("inflate"); // auto deflate = gains->Attribute("deflate"); // if (!inflate || !parseFloat(inflate, act.inflateGain)) // { // act.inflateGain = 1.0f; // } // if (!deflate || !parseFloat(deflate, act.deflateGain)) // { // act.deflateGain = 1.0f; // } // } // if (thresholds) // { // auto deflate = thresholds->Attribute("deflate"); // auto deactivate = thresholds->Attribute("deactivate"); // if (!deflate || !parseFloat(deflate, act.deflateThreshold)) // { // act.deflateThreshold = 1.0f; // } // if (!deactivate || !parseFloat(deactivate, act.deactivateThreshold)) // { // act.deactivateThreshold = 1.0e-2f; // } // } // if (springGroups) // { // auto springGroup = springGroups->FirstChildElement("springGroup"); // while (springGroup) // { // UrdfSpringGroup sg; // if (parseSpringGroup(*springGroup, sg)) // { // act.springGroups.push_back(sg); // } // springGroup = springGroup->NextSiblingElement("springGroup"); // } // } // if (maxPressure && gains && thresholds && springGroups) // urdfActs.push_back(act); // else // { // printf("*** unable to parse soft actuator %s \n", act.name.c_str()); // return false; // } // } // } // actuatorElement = actuatorElement->NextSiblingElement("actuator"); // } // return true; // } bool parseRobot(const XMLElement& root, UrdfRobot& urdfRobot) { auto name = root.Attribute("name"); if (name) { urdfRobot.name = makeValidUSDIdentifier(name); } urdfRobot.links.clear(); urdfRobot.joints.clear(); urdfRobot.materials.clear(); if (!parseMaterials(root, urdfRobot.materials)) { return false; } if (!parseLinks(root, urdfRobot.links)) { return false; } if (!parseJoints(root, urdfRobot.joints)) { return false; } // if (!parseSoftActuators(root, urdfRobot.softActuators)) // { // return false; // } return true; } bool parseUrdf(const std::string& urdfPackagePath, const std::string& urdfFileRelativeToPackage, UrdfRobot& urdfRobot) { std::string path; // #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) // path = GetFilePathByPlatform((urdfPackagePath + "\\" + urdfFileRelativeToPackage).c_str()); //#else // path = GetFilePathByPlatform((urdfPackagePath + "/" + urdfFileRelativeToPackage).c_str()); //#endif path = urdfPackagePath + "/" + urdfFileRelativeToPackage; CARB_LOG_INFO("Loading URDF at '%s'", path.c_str()); // Weird stack smashing error with tinyxml2 when the descructor is called static tinyxml2::XMLDocument doc; if (doc.LoadFile(path.c_str()) != XML_SUCCESS) { printf("*** Failed to load '%s'", path.c_str()); return false; } XMLElement* root = doc.RootElement(); if (!root) { printf("*** Empty document '%s' \n", path.c_str()); return false; } if (!parseRobot(*root, urdfRobot)) { return false; } // std::cout << urdfRobot << std::endl; return true; } } // namespace urdf } }
37,675
C++
28.138438
135
0.503331
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/parse/UrdfParser.h
// SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "../UrdfTypes.h" #include <tinyxml2.h> namespace omni { namespace importer { namespace urdf { // Parsers bool parseJointType(const std::string& str, UrdfJointType& type); bool parseOrigin(const tinyxml2::XMLElement& element, Transform& origin); bool parseAxis(const tinyxml2::XMLElement& element, UrdfAxis& axis); bool parseLimit(const tinyxml2::XMLElement& element, UrdfLimit& limit); bool parseDynamics(const tinyxml2::XMLElement& element, UrdfDynamics& dynamics); bool parseMass(const tinyxml2::XMLElement& element, float& mass); bool parseInertia(const tinyxml2::XMLElement& element, UrdfInertia& inertia); bool parseInertial(const tinyxml2::XMLElement& element, UrdfInertial& inertial); bool parseGeometry(const tinyxml2::XMLElement& element, UrdfGeometry& geometry); bool parseMaterial(const tinyxml2::XMLElement& element, UrdfMaterial& material); bool parseMaterials(const tinyxml2::XMLElement& root, std::map<std::string, UrdfMaterial>& urdfMaterials); bool parseLinks(const tinyxml2::XMLElement& root, std::map<std::string, UrdfLink>& urdfLinks); bool parseJoints(const tinyxml2::XMLElement& root, std::map<std::string, UrdfJoint>& urdfJoints); bool parseUrdf(const std::string& urdfPackagePath, const std::string& urdfFileRelativeToPackage, UrdfRobot& urdfRobot); } // namespace urdf } }
2,032
C
32.327868
119
0.773622
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/docs/CHANGELOG.md
# Changelog ## [1.1.4] - 2023-10-18 ### Changed - Update code dependencies ## [1.1.3] - 2023-10-02 ### Changed - Mesh path parser now allows for prefixes other than "package://" ## [1.1.2] - 2023-08-21 ### Added - Added processing of capsule bodies to replace cylinders ### Fixed - Fixed computation of joint axis. Earlier arbitrary axis were not supported. - Fixed bug in merging joints when multiple levels of fixed joints exist. ## [1.1.1] - 2023-08-08 ### Added - Added support for the boolean attribute ``<joint dont_collapse>``: setting this parameter to true in the URDF joint tag prevents the child link from collapsing when the associated joint type is "fixed". ## [1.1.0] - 2023-08-04 ### Added - Suport for direct mimic joints - Maintain Merged Links as frames inside parent rigid body ### Fixed - Arbitrary joint axis were adding random 56.7 rotation degrees in the joint axis orientation ## [1.0.0] - 2023-07-03 ### Changed - Renamed the extension to omni.importer.urdf - Published the extension to the default registry ## [0.5.16] - 2023-06-27 ### Fixed - Support for arbitrary joint axis. ## [0.5.15] - 2023-06-26 ### Fixed - Support for non-diagonal inertia matrix - Support for convex decomposition mesh collision method ## [0.5.14] - 2023-06-13 ### Fixed - Kit 105.1 update - Accessing primvars is accessed through the PrimvarsAPI instead of usd convenience functions ## [0.5.13] - 2023-06-07 ### Fixed - Crash when name was not provided for a material, added check for null pointer and unit test ## [0.5.12] - 2023-05-16 ### Fixed - Removed duplicated code to copy collision geometry from the mesh visuals. ## [0.5.11] - 2023-05-06 ### Added - Collision geometry from visual meshes. ## [0.5.10] - 2023-05-04 ### Added - Code overview and limitations in README. ## [0.5.9] - 2023-02-28 ### Fixed - Appearance of carb warnings when setting the joint damping and stiffness to 0 for `NONE` drive type ## [0.5.8] - 2023-02-22 ### Fixed - removed max joint effort scaling by 60 during import - removed custom collision api when the shape is a cylinder ## [0.5.7] - 2023-02-17 ### Added - Unit test for joint limits. - URDF data file for joint limit unit test (test_limits.urdf) ## [0.5.6] - 2023-02-14 ### Fixed - Imported negative URDF effort and velocity joint constraints set the physics constraint value to infinity. ## [0.5.5] - 2023-01-06 ### Fixed - onclick_fn warning when creating UI ## [0.5.4] - 2022-10-13 ### Fixed - Fixes materials on instanceable imports ## [0.5.3] - 2022-10-13 ### Fixed - Added Test for import stl with custom material ## [0.5.2] - 2022-09-07 ### Fixed - Fixes for kit 103.5 ## [0.5.1] - 2022-01-02 ### Changed - Use omni.kit.viewport.utility when setting camera ## [0.5.0] - 2022-08-30 ### Changed - Remove direct legacy viewport calls ## [0.4.1] - 2022-08-30 ### Changed - Modified default gains in URDF -> USD converter to match gains for Franka and UR10 robots ## [0.4.0] - 2022-08-09 ### Added - Cobotta 900 urdf data files ## [0.3.1] - 2022-08-08 ### Fixed - Missing argument in example docstring ## [0.3.0] - 2022-07-09 ### Added - Add instanceable option to importer ## [0.2.2] - 2022-06-02 ### Changed - Fix title for file picker ## [0.2.1] - 2022-05-23 ### Changed - Fix units for samples ## [0.2.0] - 2022-05-17 ### Changed - Add joint values API ## [0.1.16] - 2022-04-19 ### Changed - Add Texture import compatibility for Windows. ## [0.1.16] - 2022-02-08 ### Changed - Revamped UI ## [0.1.15] - 2021-12-20 ### Changed - Fixed bug where missing mesh on part with urdf material assigned would crash on material binding in a non-existing prim. ## [0.1.14] - 2021-12-20 ### Changed - Fix bug where material was indexed by name and removing false duplicates. - Add Normal subdivision group import parameter. ## [0.1.13] - 2021-12-10 ### Changed - Texture support for OBJ and Collada assets. - Remove bug where an invalid link on a joint would stop importing the remainder of the urdf. raises an error message instead. ## [0.1.12] - 2021-12-03 ### Changed - Default to save Imported assets on a new USD and reference it on open stage. - Change base robot prim to also use orientOP instead of rotateOP - Change behavior where any stage event (e.g selection changed) was resetting some options on the UI ## [0.1.11] - 2021-11-29 ### Changed - Use double precision for xform ops to match isaac sim defaults ## [0.1.10] - 2021-11-04 ### Changed - create physics scene is false for import config - create physics scene will not create a scene if one exists - set default prim is false for import config ## [0.1.9] - 2021-10-25 ### Added - Support to specify usd paths for urdf meshes. ### Changed - distance_scale sets the stage to the same units for consistency - None drive mode still applies DriveAPI, but keeps the stiffness/damping at zero - rootJoint prim is renamed to root_joint for consistency with other joint names. ### Fixed - warnings when setting attributes as double when they should have been float ## [0.1.8] - 2021-10-18 ### Added - Floating joints are ignored but place any child links at the correct location. ### Fixed - Crash when urdf contained a floating joint ## [0.1.7] - 2021-09-23 ### Added - Default position drive damping to UI ### Fixed - Default config parameters are now respected ## [0.1.6] - 2021-08-31 ### Changed - Updated to New UI - Spheres and Cubes are treated as shapes - Cylinders are by default imported with custom geometry enabled - Joint drives are default force instead of acceleration ### Fixed - Meshes were not imported correctly, fixed subdivision scheme setting ### Removed - Parsing URDF is not a separate step with its own UI ## [0.1.5] - 2021-07-30 ### Fixed - Zero joint velocity issue - Artifact when dragging URDF file due to transform matrix ## [0.1.4] - 2021-06-09 ### Added - Fixed bugs with default density ## [0.1.3] - 2021-05-26 ### Added - Fixed bugs with import units - Streamlined UI and fixed missing elements - Fixed issues with creating new stage on import ## [0.1.2] - 2020-12-11 ### Added - Unit tests to extension - Add test urdf files - Fix unit issues with samples - Fix unit conversion issue with import ## [0.1.1] - 2020-12-03 ### Added - Sample URDF files for carter, franka ur10 and kaya ## [0.1.0] - 2020-12-03 ### Added - Initial version of URDF importer extension
6,385
Markdown
22.477941
205
0.701018
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/docs/index.rst
URDF Import Extension [omni.importer.urdf] ########################################## URDF Import Commands ==================== The following commands can be used to simplify the import process. Below is a sample demonstrating how to import the Carter URDF included with this extension .. code-block:: python :linenos: import omni.kit.commands from pxr import UsdLux, Sdf, Gf, UsdPhysics, PhysicsSchemaTools # setting up import configuration: status, import_config = omni.kit.commands.execute("URDFCreateImportConfig") import_config.merge_fixed_joints = False import_config.convex_decomp = False import_config.import_inertia_tensor = True import_config.fix_base = False import_config.collision_from_visuals = False # Get path to extension data: ext_manager = omni.kit.app.get_app().get_extension_manager() ext_id = ext_manager.get_enabled_extension_id("omni.importer.urdf") extension_path = ext_manager.get_extension_path(ext_id) # import URDF omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=extension_path + "/data/urdf/robots/carter/urdf/carter.urdf", import_config=import_config, ) # get stage handle stage = omni.usd.get_context().get_stage() # enable physics scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene")) # set gravity scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0)) scene.CreateGravityMagnitudeAttr().Set(9.81) # add ground plane PhysicsSchemaTools.addGroundPlane(stage, "/World/groundPlane", "Z", 1500, Gf.Vec3f(0, 0, -50), Gf.Vec3f(0.5)) # add lighting distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight")) distantLight.CreateIntensityAttr(500) .. automodule:: omni.importer.urdf.scripts.commands :members: :undoc-members: :exclude-members: do, undo .. automodule:: omni.importer.urdf._urdf .. autoclass:: omni.importer.urdf._urdf.Urdf :members: :undoc-members: :no-show-inheritance: .. autoclass:: omni.importer.urdf._urdf.ImportConfig :members: :undoc-members: :no-show-inheritance:
2,157
reStructuredText
31.208955
113
0.684747
NVIDIA-Omniverse/kit-extension-sample-defectsgen/README.md
# Defect Extension Sample ![Defect Preview](exts/omni.example.defects/data/preview.PNG) ### About This extension allows user's to generate a single defect on a target prim using images to project the defect onto the prim. Using Replicator's API the user can generate thousands of synthetic data to specify the dimensions, rotation, and position of the defect. ### Pre-req This extension has been tested to work with Omniverse Code 2022.3.3 or higher. ### [README](exts/omni.example.defects) See the [README for this extension](exts/omni.example.defects) to learn more about it including how to use it. ## Adding This Extension This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths. Link might look like this: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-defects?branch=main&dir=exts` Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual. To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path ## Linking with an Omniverse app If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included. Run: ``` > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ``` > link_app.bat --app create ``` You can also just pass a path to create link to: ``` > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
1,971
Markdown
34.214285
261
0.763064
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.1.1" # The title and description fields are primarily for displaying extension info in UI title = "Defects Generation Sample" description="Example of a replicator extension that creates material defects using a Decal Proxy Object" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Icon to show in the extension manager icon = "data/icon.png" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "omnigraph", "replicator", "defect", "material"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.ui" = {} "omni.replicator.core" = {} "omni.kit.window.file_importer" = {} "omni.kit.commands" = {} "omni.usd" = {} "omni.kit.notification_manager" = {} # Main python module this extension provides, it will be publicly available as "import omni.code.snippets". [[python.module]] name = "omni.example.defects"
1,068
TOML
25.724999
107
0.72191
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/rep_widgets.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui from .widgets import MinMaxWidget, CustomDirectory, PathWidget from .utils import * from pxr import Sdf from pathlib import Path import omni.kit.notification_manager as nm TEXTURE_DIR = Path(__file__).parent / "data" SCRATCHES_DIR = TEXTURE_DIR / "scratches" # Parameter Objects class DefectParameters: def __init__(self) -> None: self.semantic_label = ui.SimpleStringModel("defect") self.count = ui.SimpleIntModel(1) self._build_semantic_label() self.defect_text = CustomDirectory("Defect Texture Folder", default_dir=str(SCRATCHES_DIR.as_posix()), tooltip="A folder location containing a single or set of textures (.png)", file_types=[("*.png", "PNG"), ("*", "All Files")]) self.dim_w = MinMaxWidget("Defect Dimensions Width", min_value=0.1, tooltip="Defining the Minimum and Maximum Width of the Defect") self.dim_h = MinMaxWidget("Defect Dimensions Length", min_value=0.1, tooltip="Defining the Minimum and Maximum Length of the Defect") self.rot = MinMaxWidget("Defect Rotation", tooltip="Defining the Minimum and Maximum Rotation of the Defect") def _build_semantic_label(self): with ui.HStack(height=0, tooltip="The label that will be associated with the defect"): ui.Label("Defect Semantic") ui.StringField(model=self.semantic_label) def destroy(self): self.semantic_label = None self.defect_text.destroy() self.defect_text = None self.dim_w.destroy() self.dim_w = None self.dim_h.destroy() self.dim_h = None self.rot.destroy() self.rot = None class ObjectParameters(): def __init__(self) -> None: self.target_prim = PathWidget("Target Prim") def apply_primvars(prim): # Apply prim vars prim.CreateAttribute('primvars:d1_forward_vector', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0)) prim.CreateAttribute('primvars:d1_right_vector', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0)) prim.CreateAttribute('primvars:d1_up_vector', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0)) prim.CreateAttribute('primvars:d1_position', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0)) prim.CreateAttribute('primvars:v3_scale', Sdf.ValueTypeNames.Float3, custom=True).Set((0,0,0)) nm.post_notification(f"Applied Primvars to: {prim.GetPath()}", hide_after_timeout=True, duration=5, status=nm.NotificationStatus.INFO) def apply(): # Check Paths if not check_path(self.target_prim.path_value): return # Check if prim is valid prim = is_valid_prim(self.target_prim.path_value) if prim is None: return apply_primvars(prim) ui.Button("Apply", style={"padding": 5}, clicked_fn=lambda: apply(), tooltip="Apply Primvars and Material to selected Prim." ) def destroy(self): self.target_prim.destroy() self.target_prim = None class MaterialParameters(): def __init__(self) -> None: pass
4,224
Python
40.831683
146
0.608191
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/widgets.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui from omni.kit.window.file_importer import get_file_importer from typing import List import carb import omni.usd class CustomDirectory: def __init__(self, label: str, tooltip: str = "", default_dir: str = "", file_types: List[str] = None) -> None: self._label_text = label self._tooltip = tooltip self._file_types = file_types self._dir = ui.SimpleStringModel(default_dir) self._build_directory() @property def directory(self) -> str: """ Selected Directory name from file importer :type: str """ return self._dir.get_value_as_string() def _build_directory(self): with ui.HStack(height=0, tooltip=self._tooltip): ui.Label(self._label_text) ui.StringField(model=self._dir) ui.Button("Open", width=0, style={"padding": 5}, clicked_fn=self._pick_directory) def _pick_directory(self): file_importer = get_file_importer() if not file_importer: carb.log_warning("Unable to get file importer") file_importer.show_window(title="Select Folder", import_button_label="Import Directory", import_handler=self.import_handler, file_extension_types=self._file_types ) def import_handler(self, filename: str, dirname: str, selections: List[str] = []): self._dir.set_value(dirname) def destroy(self): self._dir = None class MinMaxWidget: def __init__(self, label: str, min_value: float = 0, max_value: float = 1, tooltip: str = "") -> None: self._min_model = ui.SimpleFloatModel(min_value) self._max_model = ui.SimpleFloatModel(max_value) self._label_text = label self._tooltip = tooltip self._build_min_max() @property def min_value(self) -> float: """ Min Value of the UI :type: int """ return self._min_model.get_value_as_float() @property def max_value(self) -> float: """ Max Value of the UI :type: int """ return self._max_model.get_value_as_float() def _build_min_max(self): with ui.HStack(height=0, tooltip=self._tooltip): ui.Label(self._label_text) with ui.HStack(): ui.Label("Min", width=0) ui.FloatDrag(model=self._min_model) ui.Label("Max", width=0) ui.FloatDrag(model=self._max_model) def destroy(self): self._max_model = None self._min_model = None class PathWidget: def __init__(self, label: str, button_label: str = "Copy", read_only: bool = False, tooltip: str = "") -> None: self._label_text = label self._tooltip = tooltip self._button_label = button_label self._read_only = read_only self._path_model = ui.SimpleStringModel() self._top_stack = ui.HStack(height=0, tooltip=self._tooltip) self._button = None self._build() @property def path_value(self) -> str: """ Path of the Prim in the scene :type: str """ return self._path_model.get_value_as_string() @path_value.setter def path_value(self, value) -> None: """ Sets the path value :type: str """ self._path_model.set_value(value) def _build(self): def copy(): ctx = omni.usd.get_context() selection = ctx.get_selection().get_selected_prim_paths() if len(selection) > 0: self._path_model.set_value(str(selection[0])) with self._top_stack: ui.Label(self._label_text) ui.StringField(model=self._path_model, read_only=self._read_only) self._button = ui.Button(self._button_label, width=0, style={"padding": 5}, clicked_fn=lambda: copy(), tooltip="Copies the Current Selected Path in the Stage") def destroy(self): self._path_model = None
4,815
Python
31.986301
171
0.58837
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/extension.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ext from .window import DefectsWindow class DefectsGenerator(omni.ext.IExt): WINDOW_NAME = "Defects Sample Extension" MENU_PATH = f"Window/{WINDOW_NAME}" def __init__(self) -> None: super().__init__() self._window = None def on_startup(self, ext_id): self._menu = omni.kit.ui.get_editor_menu().add_item( DefectsGenerator.MENU_PATH, self.show_window, toggle=True, value=True ) self.show_window(None, True) def on_shutdown(self): if self._menu: omni.kit.ui.get_editor_menu().remove_item(DefectsGenerator.MENU_PATH) self._menu if self._window: self._window.destroy() self._window = None def _set_menu(self, value): omni.kit.ui.get_editor_menu().set_value(DefectsGenerator.MENU_PATH, value) def _visibility_changed_fn(self, visible): self._set_menu(visible) if not visible: self._window = None def show_window(self, menu, value): self._set_menu(value) if value: self._set_menu(True) self._window = DefectsWindow(DefectsGenerator.WINDOW_NAME, width=450, height=700) self._window.set_visibility_changed_fn(self._visibility_changed_fn) elif self._window: self._window.visible = False
2,037
Python
34.13793
98
0.65783
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/utils.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.usd import carb import omni.kit.commands import os def get_current_stage(): context = omni.usd.get_context() stage = context.get_stage() return stage def check_path(path: str) -> bool: if not path: carb.log_error("No path was given") return False return True def is_valid_prim(path: str): prim = get_prim(path) if not prim.IsValid(): carb.log_warn(f"No valid prim at path given: {path}") return None return prim def delete_prim(path: str): omni.kit.commands.execute('DeletePrims', paths=[path], destructive=False) def get_prim_attr(prim_path: str, attr_name: str): prim = get_prim(prim_path) return prim.GetAttribute(attr_name).Get() def get_textures(dir_path, png_type=".png"): textures = [] dir_path += "/" for file in os.listdir(dir_path): if file.endswith(png_type): textures.append(dir_path + file) return textures def get_prim(prim_path: str): stage = get_current_stage() prim = stage.GetPrimAtPath(prim_path) return prim
1,768
Python
28
98
0.687783
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/window.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import carb import omni.ui as ui from omni.ui import DockPreference from .style import * from .widgets import CustomDirectory from .replicator_defect import create_defect_layer, rep_preview, does_defect_layer_exist, rep_run, get_defect_layer from .rep_widgets import DefectParameters, ObjectParameters from .utils import * from pathlib import Path class DefectsWindow(ui.Window): def __init__(self, title: str, dockPreference: DockPreference = DockPreference.DISABLED, **kwargs) -> None: super().__init__(title, dockPreference, **kwargs) # Models self.frames = ui.SimpleIntModel(1, min=1) self.rt_subframes = ui.SimpleIntModel(1, min=1) # Widgets self.defect_params = None self.object_params = None self.output_dir = None self.frame_change = None self.frame.set_build_fn(self._build_frame) def _build_collapse_base(self, label: str, collapsed: bool = False): v_stack = None with ui.CollapsableFrame(label, height=0, collapsed=collapsed): with ui.ZStack(): ui.Rectangle() v_stack = ui.VStack() return v_stack def _build_frame(self): with self.frame: with ui.ScrollingFrame(style=default_defect_main): with ui.VStack(style={"margin": 3}): self._build_object_param() self._build_defect_param() self._build_replicator_param() def _build_object_param(self): with self._build_collapse_base("Object Parameters"): self.object_params = ObjectParameters() def _build_defect_param(self): with self._build_collapse_base("Defect Parameters"): self.defect_params = DefectParameters() def _build_replicator_param(self): def preview_data(): if does_defect_layer_exist(): rep_preview() else: create_defect_layer(self.defect_params, self.object_params) self.rep_layer_button.text = "Recreate Replicator Graph" def remove_replicator_graph(): if get_defect_layer() is not None: layer, pos = get_defect_layer() omni.kit.commands.execute('RemoveSublayer', layer_identifier=layer.identifier, sublayer_position=pos) if is_valid_prim('/World/Looks/ProjectPBRMaterial'): delete_prim('/World/Looks/ProjectPBRMaterial') if is_valid_prim(self.object_params.target_prim.path_value + "/Projection"): delete_prim(self.object_params.target_prim.path_value + "/Projection") if is_valid_prim('/Replicator'): delete_prim('/Replicator') def run_replicator(): remove_replicator_graph() total_frames = self.frames.get_value_as_int() subframes = self.rt_subframes.get_value_as_int() if subframes <= 0: subframes = 0 if total_frames > 0: create_defect_layer(self.defect_params, self.object_params, total_frames, self.output_dir.directory, subframes, self._use_seg.as_bool, self._use_bb.as_bool) self.rep_layer_button.text = "Recreate Replicator Graph" rep_run() else: carb.log_error(f"Number of frames is {total_frames}. Input value needs to be greater than 0.") def create_replicator_graph(): remove_replicator_graph() create_defect_layer(self.defect_params, self.object_params) self.rep_layer_button.text = "Recreate Replicator Graph" def set_text(label, model): label.text = model.as_string with self._build_collapse_base("Replicator Parameters"): home_dir = Path.home() valid_out_dir = home_dir / "omni.replicator_out" self.output_dir = CustomDirectory("Output Directory", default_dir=str(valid_out_dir.as_posix()), tooltip="Directory to specify where the output files will be stored. Default is [DRIVE/Users/USER/omni.replicator_out]") with ui.HStack(height=0, tooltip="Check off which annotator you want to use; You can also use both"): ui.Label("Annotations: ", width=0) ui.Spacer() ui.Label("Segmentation", width=0) self._use_seg = ui.CheckBox().model ui.Label("Bounding Box", width=0) self._use_bb = ui.CheckBox().model ui.Spacer() with ui.HStack(height=0): ui.Label("Render Subframe Count: ", width=0, tooltip="Defines how many subframes of rendering occur before going to the next frame") ui.Spacer(width=ui.Fraction(0.25)) ui.IntField(model=self.rt_subframes) self.rep_layer_button = ui.Button("Create Replicator Layer", clicked_fn=lambda: create_replicator_graph(), tooltip="Creates/Recreates the Replicator Graph, based on the current Defect Parameters") with ui.HStack(height=0): ui.Button("Preview", width=0, clicked_fn=lambda: preview_data(), tooltip="Preview a Replicator Scene") ui.Label("or", width=0) ui.Button("Run for", width=0, clicked_fn=lambda: run_replicator(), tooltip="Run replicator for so many frames") with ui.ZStack(width=0): l = ui.Label("", style={"color": ui.color.transparent, "margin_width": 10}) self.frame_change = ui.StringField(model=self.frames) self.frame_change_cb = self.frame_change.model.add_value_changed_fn(lambda m, l=l: set_text(l, m)) ui.Label("frame(s)") def destroy(self) -> None: self.frames = None self.defect_semantic = None if self.frame_change is not None: self.frame_change.model.remove_value_changed_fn(self.frame_change_cb) if self.defect_params is not None: self.defect_params.destroy() self.defect_params = None if self.object_params is not None: self.object_params.destroy() self.object_params = None return super().destroy()
7,174
Python
46.833333
229
0.597017
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/omni/example/defects/replicator_defect.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.replicator.core as rep import carb from .rep_widgets import DefectParameters, ObjectParameters from .utils import * camera_path = "/World/Camera" def rep_preview(): rep.orchestrator.preview() def rep_run(): rep.orchestrator.run() def does_defect_layer_exist() -> bool: stage = get_current_stage() for layer in stage.GetLayerStack(): if layer.GetDisplayName() == "Defect": return True return False def get_defect_layer(): stage = get_current_stage() pos = 0 for layer in stage.GetLayerStack(): if layer.GetDisplayName() == "Defect": return layer, pos pos = pos + 1 return None def create_randomizers(defect_params: DefectParameters, object_params: ObjectParameters): diffuse_textures = get_textures(defect_params.defect_text.directory, "_D.png") normal_textures = get_textures(defect_params.defect_text.directory, "_N.png") roughness_textures = get_textures(defect_params.defect_text.directory, "_R.png") def move_defect(): defects = rep.get.prims(semantics=[('class', defect_params.semantic_label.as_string + '_mesh')]) plane = rep.get.prim_at_path(object_params.target_prim.path_value) with defects: rep.randomizer.scatter_2d(plane) rep.modify.pose( rotation=rep.distribution.uniform( (defect_params.rot.min_value, 0, 90), (defect_params.rot.max_value, 0, 90) ), scale=rep.distribution.uniform( (1, defect_params.dim_h.min_value,defect_params.dim_w.min_value), (1, defect_params.dim_h.max_value, defect_params.dim_w.max_value) ) ) return defects.node def change_defect_image(): projections = rep.get.prims(semantics=[('class', defect_params.semantic_label.as_string + '_projectmat')]) with projections: rep.modify.projection_material( diffuse=rep.distribution.sequence(diffuse_textures), normal=rep.distribution.sequence(normal_textures), roughness=rep.distribution.sequence(roughness_textures)) return projections.node rep.randomizer.register(move_defect) rep.randomizer.register(change_defect_image) def create_camera(target_path): if is_valid_prim(camera_path) is None: camera = rep.create.camera(position=1000, look_at=rep.get.prim_at_path(target_path)) carb.log_info(f"Creating Camera: {camera}") else: camera = rep.get.prim_at_path(camera_path) return camera def create_defects(defect_params: DefectParameters, object_params: ObjectParameters): target_prim = rep.get.prims(path_pattern=object_params.target_prim.path_value) count = 1 if defect_params.count.as_int > 1: count = defect_params.count.as_int for i in range(count): cube = rep.create.cube(visible=False, semantics=[('class', defect_params.semantic_label.as_string + '_mesh')], position=0, scale=1, rotation=(0, 0, 90)) with target_prim: rep.create.projection_material(cube, [('class', defect_params.semantic_label.as_string + '_projectmat')]) def create_defect_layer(defect_params: DefectParameters, object_params: ObjectParameters, frames: int = 1, output_dir: str = "_defects", rt_subframes: int = 0, use_seg: bool = False, use_bb: bool = True): if len(defect_params.defect_text.directory) <= 0: carb.log_error("No directory selected") return with rep.new_layer("Defect"): create_defects(defect_params, object_params) create_randomizers(defect_params=defect_params, object_params=object_params) # Create / Get camera camera = create_camera(object_params.target_prim.path_value) # Add Default Light distance_light = rep.create.light(rotation=(315,0,0), intensity=3000, light_type="distant") render_product = rep.create.render_product(camera, (1024, 1024)) # Initialize and attach writer writer = rep.WriterRegistry.get("BasicWriter") writer.initialize(output_dir=output_dir, rgb=True, semantic_segmentation=use_seg, bounding_box_2d_tight=use_bb) # Attach render_product to the writer writer.attach([render_product]) # Setup randomization with rep.trigger.on_frame(num_frames=frames, rt_subframes=rt_subframes): rep.randomizer.move_defect() rep.randomizer.change_defect_image()
5,247
Python
40.984
204
0.66438
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.1.1] - 2023-08-23 ### Changed - Changed annotations to use Tight Bounding Box instead of Loose - Updated ReadMe ## [1.1.0] - 2023-08-15 ### Removed - Ogn nodes, these nodes are now apart of the replicator pipeline - proxy.usd, Replicator has built in functionality in their nodes that creates the proxy - Functions in `utils.py` that are not longer being used - Region selection ### Added - Options to either use bounding boxes or segmentation - Functionality to remove new prims created by Replicator - Notificataion popup for when the prim vars are applied to the mesh ### Changed - Textures are now represented as a D, N, and R - D is Diffuse - N is Normal - R is Roughness - Default values for dimensions start at 0.1 - Output Directory UI defaults to replicator default output directory - Textures folder UI defaults to folder inside of extension with sample scratches - Updated README talking about the new images being used ## [1.0.1] - 2023-04-18 ### Changed - CustomDirectory now takes file_types if the user wants to specify the files they can filter by - Material that is applied to the prim ### Fixed - Nodes not connecting properly with Code 2022.3.3 - In utils.py if rotation is not found use (0,0,0) as default - lookat in utils.py could not subtract Vec3f by Vec3d
1,484
Markdown
28.117647
96
0.745957
NVIDIA-Omniverse/kit-extension-sample-defectsgen/exts/omni.example.defects/docs/README.md
# Defects Sample Extension (omni.sample.defects) ![Defects Preview](../data/preview.png) ## Overview The Defects Sample Extension allows users to choose a texture, that represents a defect, to apply to a [Prim](https://docs.omniverse.nvidia.com/prod_usd/prod_usd/quick-start/prims.html) and generate synthetic data of the position, rotation, and dimensions of that texture. This Sample Extension utilizes Omniverse's [Replicator](https://developer.nvidia.com/omniverse/replicator) functionality for randomizing and generating synthetic data. ## UI Overview ### Object Parameters ![Object Params](../data/objparam.png) 1. Target Prim - This defines what prim the material to apply to. To get the prim path, **select** a prim in the scene then hit the **Copy button** 2. Apply - Once you have a Target Prim selected and Copied it's path, hitting Apply will bring in the proxy, decal material and create the primvar's on the Target Prim. ### Defect Parameters ![Defect Params](../data/defectparam.png) Randomizations are based on Replicator's [Distributions](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator/distribution_examples.html) 1. Defect Semantic - The semantic label that will be used to represent the defect in the output file produced by Replicator. - Default Value: `defect` 2. Defect Texture Folder - A folder location that holds all the texture(s) to choose from. Textures should be in PNG format. - Default Value: data folder within the Defect Extension - Defect textures are composed of a Diffuse, Normal, and Roughness texture to represent the defect. Example shown below: Diffuse Texture | Normal Texture | Roughness Texture :-------------------------:|:-------------------------:|:-------------------------: ![](../omni/example/defects/data/scratches/scratch_0_D.png) | ![](../omni/example/defects/data/scratches/scratch_0_N.png) | ![](../omni/example/defects/data/scratches/scratch_0_R.png) 3. Defect Dimensions Width - Replicator will choose random values between the Min and Max defined (cms) - Default Value Min: `0.1` - Default Value Max: `1` 4. Defect Dimensions Length - Replicator will choose random values between the Min and Max defined (cms) - Default Value Min: `0.1` - Default Value Max: `1` 5. Defect Rotation - Replicator will choose random values between the Min and Max defined (cms) and will set that rotation. - Default Value Min: `0.1` - Default Value Max: `1` A recommended set of values using the CarDefectPanel scene is the following: - Defect Semantics: Scratch - Defect Texture: [Path to Scratchs located in Extension] - Defect Dimensions Width: Min 0.1 Max 0.2 - Defect Dimensions Length: Min 0.15 Max 0.2 - Defect Rotation: Min 0 Max 360 ### Replicator Parameters ![Rep Params](../data/repparam.png) 1. Output Directory - Defines the location in which Replicator will use to output data. By default it will be `DRIVE/Users/USER/omni.replicator_out` 2. Annotations - There are two types of annotations you can choose from: Segmentation and/or Bounding Box. You can select both of these. For other annotation options you will need to adjust the code inside the extension. 3. [Render Subframe](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator/subframes_examples.html) Count - If rendering in RTX Realtime mode, specifies the number of subframes to render in order to reduce artifacts caused by large changes in the scene. 4. Create Replicator Layer - Generates the [OmniGraph](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_omnigraph.html) or Omni.Replicator graph architecture, if changes are made the user can click this button to reflect changes. This does not run the actual execution or logic. 5. Preview - **Preview** performs a single iteration of randomizations and prevents data from being written to disk. 6. Run for X frames - **Run for** will run the generation for a specified amount of frames. Each frame will be one data file so 100 frames will produce 100 images/json/npy files. ![scratch](../data/scratch.gif)
4,187
Markdown
50.703703
276
0.736566
NVIDIA-Omniverse/kit-extension-sample-apiconnect/README.md
# API Connect Sample Omniverse Extension ![preview.png](/exts/omni.example.apiconnect/data/preview.png) ### About This Sample Omniverse Extension demonstrates how connect to an API. In this sample, we create a palette of colors using the [HueMint.com](https://huemint.com/). API. ### [README](exts/omni.example.apiconnect) See the [README for this extension](exts/omni.example.apiconnect) to learn more about it including how to use it. ## [Tutorial](exts/omni.example.apiconnect/docs/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.apiconnect/docs/tutorial.md) that walks you through how to build this extension using [asyncio](https://docs.python.org/3/library/asyncio.html) and [aiohttp](https://docs.aiohttp.org/en/stable/). ## Adding This Extension To add a this extension to your Omniverse app: 1. Go into: Extension Manager -> Hamburger Icon -> Settings -> Extension Search Path 2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-apiconnect.git?branch=main&dir=exts` Alternatively: 1. Download or Clone the extension, unzip the file if downloaded 2. Copy the `exts` folder path within the extension folder - i.e. home/.../kit-extension-sample-apiconnect/exts (Linux) or C:/.../kit-extension-sample-apiconnect/exts (Windows) 3. Go into: Extension Manager -> Hamburger Icon -> Settings -> Extension Search Path 4. Add the `exts` folder path as a search path ## Linking with an Omniverse app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash # Windows > link_app.bat ``` ```shell # Linux ~$ ./link_app.sh ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps are installed the script will select the recommended one. Or you can explicitly pass an app: ```bash # Windows > link_app.bat --app code ``` ```shell # Linux ~$ ./link_app.sh --app code ``` You can also pass a path that leads to the Omniverse package folder to create the link: ```bash # Windows > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3" ``` ```shell # Linux ~$ ./link_app.sh --path "home/bob/.local/share/ov/pkg/create-2022.1.3" ``` ## Attribution & Acknowledgements This extension uses the [Huemint.com API](https://huemint.com/about/). Huemint uses machine learning to create unique color schemes. Special thanks to Jack Qiao for allowing us to use the Huemint API for this demonstration. Check out [Huemint.com](https://huemint.com/) ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
2,739
Markdown
33.25
246
0.744797
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/extension.py
# SPDX-License-Identifier: Apache-2.0 import asyncio import aiohttp import carb import omni.ext import omni.ui as ui class APIWindowExample(ui.Window): def __init__(self, title: str, **kwargs) -> None: """ Initialize the widget. Args: title : Title of the widget. This is used to display the window title on the GUI. """ super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) # async function to get the color palette from huemint.com and print it async def get_colors_from_api(self, color_widgets): """ Get colors from HueMint API and store them in color_widgets. Args: color_widgets : List of widgets to """ # Create the task for progress indication and change button text self.button.text = "Loading" task = asyncio.create_task(self.run_forever()) # Create a aiohttp session to make the request, building the url and the data to send # By default it will timeout after 5 minutes. # See more here: https://docs.aiohttp.org/en/latest/client_quickstart.html async with aiohttp.ClientSession() as session: url = "https://api.huemint.com/color" data = { "mode": "transformer", # transformer, diffusion or random "num_colors": "5", # max 12, min 2 "temperature": "1.2", # max 2.4, min 0 "num_results": "1", # max 50 for transformer, 5 for diffusion "adjacency": ["0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0", ], # nxn adjacency matrix as a flat array of strings "palette": ["-", "-", "-", "-", "-"], # locked colors as hex codes, or '-' if blank } # make the request try: async with session.post(url, json=data) as resp: # get the response as json result = await resp.json(content_type=None) # get the palette from the json palette = result["results"][0]["palette"] # apply the colors to the color widgets await self.apply_colors(palette, color_widgets) # Cancel the progress indication and return the button to the original text task.cancel() self.button.text = "Refresh" except Exception as e: carb.log_info(f"Caught Exception {e}") # Cancel the progress indication and return the button to the original text task.cancel() self.button.text = "Connection Timed Out \nClick to Retry" # apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): """ Apply the colors to the ColorWidget. This is a helper method to allow us to get the color values from the API and set them in the color widgets Args: palette : The palette that we want to apply color_widgets : The list of color widgets """ colors = [palette[i] for i in range(5)] index = 0 # This will fetch the RGB colors from the color widgets and set them to the color of the color widget. for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() # we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) # we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 async def run_forever(self): """ Run the loop until we get a response from omni. """ count = 0 dot_count = 0 # Update the button text. while True: # Reset the button text to Loading if count % 10 == 0: # Reset the text for the button # Add a dot after Loading. if dot_count == 3: self.button.text = "Loading" dot_count = 0 # Add a dot after Loading else: self.button.text += "." dot_count += 1 count += 1 await omni.kit.app.get_app().next_update_async() # hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): """ Convert hex values to floating point numbers. This is useful for color conversion to a 3 or 5 digit hex value Args: h : RGB string in the format 0xRRGGBB Returns: float tuple of ( r g b ) where r g b are floats between 0 and 1 and b """ # Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i : i + 2], 16) / 255.0 for i in (1, 3, 5)) # skip '#' def _build_fn(self): """ Build the function to call the api when the app starts. """ with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): # Get the run loop run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette", height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1, 1, 1) for i in range(5)] def on_click(): """ Get colors from API and run task in run_loop. This is called when user clicks the button """ run_loop.create_task(self.get_colors_from_api(color_widgets)) # create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) # we execute the api call once on startup run_loop.create_task(self.get_colors_from_api(color_widgets)) # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): """ Called when the extension is started. Args: ext_id - id of the extension """ print("[omni.example.apiconnect] MyExtension startup") # create a new window self._window = APIWindowExample("API Connect Demo - HueMint", width=260, height=270) def on_shutdown(self): """ Called when the extension is shut down. Destroys the window if it exists and sets it to None """ print("[omni.example.apiconnect] MyExtension shutdown") # Destroys the window and releases the reference to the window. if self._window: self._window.destroy() self._window = None
7,649
Python
40.351351
130
0.569355
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/omni/example/apiconnect/__init__.py
# SPDX-License-Identifier: Apache-2.0 from .extension import *
64
Python
15.249996
37
0.75
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2022-10-07 ### Added - Initial version of extension ## [1.1.0] - 2023-10-17 ### Added - Step by Step tutorial - APIWindowExample class - Progress indicator when the API is being called - `next_update_async()` to prevent the App from hanging ### Changed - Updated README - Sizing of UI is dynamic rather than static - Using `create_task` rather than `ensure_future` - Moved Window functionality into it's own class - Moved outer functions to Window Class ### Removed - Unused imports
594
Markdown
23.791666
80
0.720539
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/docs/README.md
# API Connection (omni.example.apiconnect) ![](../data/preview.gif) ​ ## Overview This Extension makes a single API call and updates UI elements. It demonstrates how to make API calls without interfering with the main loop of Omniverse. See [Adding the Extension](../../../README.md#adding-this-extension) on how to add the extension to your project. ​ ## [Tutorial](tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. Learn how to create an Extension that calls an API and use that information to update components within Omniverse. ​[Get started with the tutorial here.](tutorial.md) ## Usage Once the extension is enabled in the *Extension Manager*, you should see a similar line inside the viewport like in the to the image before [Overview section](#overview). Clicking on the *Refresh* button will send a request to [HueMint.com](https://huemint.com/) API. HueMint then sends back a palette of colors which is used to update the 5 color widgets in the UI. Hovering over each color widget will display the values used to define the color. The color widgets can also be clicked on which opens a color picker UI.
1,230
Markdown
54.954543
349
0.772358
NVIDIA-Omniverse/kit-extension-sample-apiconnect/exts/omni.example.apiconnect/docs/tutorial.md
# Connecting API to Omniverse Extension The API Connection extension shows how to communicate with an API within Omniverse. This guide is great for extension builders who want to start using their own API tools or external API tools within Omniverse. > NOTE: Visual Studio Code is the preferred IDE, hence forth we will be referring to it throughout this guide. > NOTE: Omniverse Code is the preferred platform, hence forth we will be referring to it throughout this guide. # Learning Objectives In this tutorial you learn how to: - Use `asyncio` - Use `aiohttp` calls - Send an API Request - Use Results from API Request - Use async within Omniverse # Prerequisites We recommend that you complete these tutorials before moving forward: - [Extension Environment Tutorial](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial) - [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims) - [UI Window Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_window/tutorial/tutorial.md) # Step 1: Create an Extension > **Note:** This is a review, if you know how to create an extension, feel free to skip this step. For this guide, we will briefly go over how to create an extension. If you have not completed [How to make an extension by spawning prims](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims/blob/main/exts/omni.example.spawn_prims/tutorial/tutorial.md) we recommend you pause here and complete that before moving forward. ## Step 1.1: Create the extension template In Omniverse Code navigate to the `Extensions` tab and create a new extension by clicking the ➕ icon in the upper left corner and select `New Extension Template Project`. Name the project to `kit-ext-apiconnect` and the extension name to `my.api.connect`. ![](./images/ext_tab.png) > **Note:** If you don't see the *Extensions* Window, enable **Window > Extensions**: > > ![Show the Extensions panel](images/window_extensions.png) <icon> | <new template> :-------------------------:|:-------------------------: ![icon](./images/icon_create.png "Plus Icon") | ![new template](./images/new_template.png "New Extension Template") A new extension template window and Visual Studio Code will open after you have selected the folder location, folder name, and extension ID. ## Step 1.2: Naming your extension Before beginning to code, navigate into `VS Code` and change how the extension is viewed in the **Extension Manager**. It's important to give your extension a title and description for the end user to understand the extension's purpose. Inside of the `config` folder, locate the `extension.toml` file: > **Note:** `extension.toml` is located inside of the `exts` folder you created for your extension. ![](./images/fileStructTOML.PNG) Inside of this file, there is a title and description for how the extension will look in the **Extension Manager**. Change the title and description for the extension. ``` python title = "API Connection" description="Example on how to make an API response in Omniverse" ``` # Step 2: Set Up Window All coding will be contained within `extension.py`. Before setting up the API request, the first step is to get a window. The UI contained in the window will have a button to call the API and color widgets whose values will be updated based on the API's response. ## Step 2.1: Replace with Boilerplate Code With *VS Code* open, **go to** `extension.py` and replace all the code inside with the following: ```python import omni.ext import omni.ui as ui # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None ``` If you were to save `extension.py` it would throw an error since we have not defined `APIWindowExample`. This step is to setup a starting point for which our window can be created and destroyed when starting up or shutting down the extension. `APIWindowExample` will be the class we work on throughout the rest of the tutorial. ## Step 2.2: Create `APIWindowExample` class At the bottom of `extension.py`, **create** a new class called `APIWindowExample()` ```python class APIWindowExample(ui.Window): def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) ``` Save `extension.py` and go back to Omniverse. Right now, the Window should only have a label. ![](./images/step2-2.png) ## Step 2.3: Add Color Widgets Color Widgets are buttons that display a color and can open a picker window. In `extension.py`, **add** the following code block under `ui.Label()`: ```python with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] #create a button to trigger the api call self.button = ui.Button("Refresh") ``` Make sure `with ui.HStack()` is at the same indentation as `ui.Label()`. Here we create a Horizontal Stack that will contain 5 Color Widgets. Below that will be a button labeled Refresh. **Save** `extension.py` and go back to Omniverse. The Window will now have 5 white boxes. When hovered it will show the color values and when clicked on it will open a color picker window. ![](./images/step2-3.gif) After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] #create a button to trigger the api call self.button = ui.Button("Refresh") ``` # Step 3: Create API Request To make an API Request we use the `aiohttp` library. This comes packaged in the Python environment with Omniverse. We use the `asyncio` library as well to avoid the user interface freezing when there are very expensive Python operations. Async is a single threaded / single process design because it's using cooperative multitasking. ## Step 3.1: Create a Task 1. **Add** `import asyncio` at the top of `extension.py`. 2. In `APIWindowExample` class, **add** the following function: ```python #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): print("a") await asyncio.sleep(1) print("b") ``` This function contains the keyword `async` in front, meaning we cannot call it statically. To call this function we first need to grab the current event loop. 3. Before `ui.Label()` **add** the following line: - `run_loop = asyncio.get_event_loop()` Now we can use the event loop to create a task that runs concurrently. 4. Before `self.button`, **add** the following block of code: ```python def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) ``` `create_task` takes a coroutine, where coroutine is an object with the keyword async. 5. To connect it together **add** the following parameter in `self.button`: - `clicked_fn=on_click` After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): print("a") await asyncio.sleep(1) print("b") def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. Now when we click on the Refresh button, in the Console tab it will print 'a' and after one second it will print 'b'. ![](./images/step3-1.gif) ## Step 3.2: Make API Request To **create** the API Request, we first need to create an `aiohttp` session. 1. Add `import aiohttp` at the top of `extension.py`. 2. In `get_colors_from_api()` remove: ```python print("a") await asyncio.sleep(1) print("b") ``` and **add** the following: - `async with aiohttp.ClientSession() as session:` With the session created, we can build the URL and data to send to the API. For this example we are using the [HueMint.com](https://huemint.com/) API. 3. Under `aiohttp.ClientSession()`, **add** the following block of code: ```python url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } ``` > **Note:** If you are using a different URL make sure the data passed is correct. 4. Based on HueMint.com we will create a POST request. **Add** the following code block under `data`: ```python try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] print(palette) except Exception as e: import carb carb.log_info(f"Caught Exception {e}") ``` The `try / except` is used to catch when a Timeout occurs. To read more about Timeouts see [aiohttp Client Quick Start](https://docs.aiohttp.org/en/latest/client_quickstart.html). After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio import aiohttp # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): async with aiohttp.ClientSession() as session: url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] print(palette) except Exception as e: import carb carb.log_info(f"Caught Exception {e}") def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. When clicking on the Refresh button our Extension will now call the API, grab the JSON response, and store it in `palette`. We can see the value for `palette` in the Console Tab. ![](./images/step3-3.gif) # Step 4: Apply Results Now that the API call is returning a response, we can now take that response and apply it to our color widgets in the Window. ## Step 4.1: Setup `apply_colors()` To apply the colors received from the API, **create** the following two functions inside of `APIWindowExample`: ```python #apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): colors = [palette[i] for i in range(5)] index = 0 for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() #we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) #we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 #hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): #Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#' ``` In Kit there is a special awaitable: `await omni.kit.app.get_app().next_update_async()` - This waits for the next frame within Omniverse to run. It is used when you want to execute something with a one-frame delay. - Why do we need this? - Without this, running Python code that is expensive can cause the user interface to freeze ## Step 4.2: Link it together Inside `get_colors_from_api()` **replace** `print()` with the following line: - `await self.apply_colors(palette, color_widgets)` After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio import aiohttp # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): async with aiohttp.ClientSession() as session: url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] await self.apply_colors(palette, color_widgets) except Exception as e: import carb carb.log_info(f"Caught Exception {e}") #apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): colors = [palette[i] for i in range(5)] index = 0 for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() #we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) #we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 #hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): #Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#' def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. When clicking on the Refresh button our color widgets in the window will now update based on the results given by the API response. ![](./images/step4-2.gif) # Step 5: Visualize Progression Some API responses might not be as quick to return a result. Visual indicators can be added to indicate to the user that the extension is waiting for an API response. Examples can be loading bars, spinning circles, percent numbers, etc. For this example, we are going to change "Refresh" to "Loading" and as time goes on it will add up to three periods after Loading before resetting. How it looks when cycling: - Loading - Loading. - Loading.. - Loading... - Loading ## Step 5.1: Run Forever Task Using `async`, we can create as many tasks to run concurrently. One task so far is making a request to the API and our second task will be running the Loading visuals. **Add** the following code block in `APIWindowExample`: ```python async def run_forever(self): count = 0 dot_count = 0 while True: if count % 10 == 0: if dot_count == 3: self.button.text = "Loading" dot_count = 0 else: self.button.text += "." dot_count += 1 count += 1 await omni.kit.app.get_app().next_update_async() ``` > **Note:** This function will run forever. When creating coroutines make sure there is a way to end the process or cancel it to prevent it from running the entire time. Again we use `next_update_async()` to prevent the user interface from freezing. ## Step 5.2: Cancelling Tasks As noted before this coroutine runs forever so after we apply the colors we will cancel that task to stop it from running. 1. At the front of `get_colors_from_api()` **add** the following lines: ```python self.button.text = "Loading" task = asyncio.create_task(self.run_forever()) ``` To cancel a task we need a reference to the task that was created. 2. In `get_colors_from_api()` and after `await self.apply_colors()` **add** the following lines: ```python task.cancel() self.button.text = "Refresh" ``` 3. After `carb.log_info()`, **add** the following lines: ```python task.cancel() self.button.text = "Connection Timed Out \nClick to Retry" ``` After editing `extension.py` should look like the following: ```python import omni.ext import omni.ui as ui import asyncio import aiohttp # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.example.apiconnect] MyExtension startup") #create a new window self._window = APIWindowExample("API Connect Example", width=260, height=270) def on_shutdown(self): print("[omni.example.apiconnect] MyExtension shutdown") if self._window: self._window.destroy() self._window = None class APIWindowExample(ui.Window): #async function to get the color palette from huemint.com async def get_colors_from_api(self, color_widgets): self.button.text = "Loading" task = asyncio.create_task(self.run_forever()) async with aiohttp.ClientSession() as session: url = 'https://api.huemint.com/color' data = { "mode":"transformer", #transformer, diffusion or random "num_colors":"5", # max 12, min 2 "temperature":"1.2", #max 2.4, min 0 "num_results":"1", #max 50 for transformer, 5 for diffusion "adjacency":[ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], #nxn adjacency matrix as a flat array of strings "palette":["-", "-", "-", "-", "-"], #locked colors as hex codes, or '-' if blank } try: #make the request async with session.post(url, json=data) as resp: #get the response as json result = await resp.json(content_type=None) #get the palette from the json palette=result['results'][0]['palette'] await self.apply_colors(palette, color_widgets) task.cancel() self.button.text = "Refresh" except Exception as e: import carb carb.log_info(f"Caught Exception {e}") task.cancel() self.button.text = "Connection Timed Out \nClick to Retry" #apply the colors fetched from the api to the color widgets async def apply_colors(self, palette, color_widgets): colors = [palette[i] for i in range(5)] index = 0 for color_widget in color_widgets: await omni.kit.app.get_app().next_update_async() #we get the individual RGB colors from ColorWidget model color_model = color_widget.model children = color_model.get_item_children() hex_to_float = self.hextofloats(colors[index]) #we set the color of the color widget to the color fetched from the api color_model.get_item_value_model(children[0]).set_value(hex_to_float[0]) color_model.get_item_value_model(children[1]).set_value(hex_to_float[1]) color_model.get_item_value_model(children[2]).set_value(hex_to_float[2]) index = index + 1 async def run_forever(self): count = 0 dot_count = 0 while True: if count % 10 == 0: if dot_count == 3: self.button.text = "Loading" dot_count = 0 else: self.button.text += "." dot_count += 1 count += 1 await omni.kit.app.get_app().next_update_async() #hex to float conversion for transforming hex color codes to float values def hextofloats(self, h): #Convert hex rgb string in an RGB tuple (float, float, float) return tuple(int(h[i:i + 2], 16) / 255. for i in (1, 3, 5)) # skip '#' def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.VStack(alignment=ui.Alignment.CENTER): run_loop = asyncio.get_event_loop() ui.Label("Click the button to get a new color palette",height=30, alignment=ui.Alignment.CENTER) with ui.HStack(height=100): color_widgets = [ui.ColorWidget(1,1,1) for i in range(5)] def on_click(): run_loop.create_task(self.get_colors_from_api(color_widgets)) #create a button to trigger the api call self.button = ui.Button("Refresh", clicked_fn=on_click) ``` **Save** `extension.py` and go back to Omniverse. Clicking the Refresh Button now will display a visual progression to let the user know that the program is running. Once the program is done the button will revert back to displaying "Refresh" instead of "Loading". ![](./images/step5-2.gif)
30,812
Markdown
41.618257
338
0.642315
NVIDIA-Omniverse/kit-extension-sample-reticle/README.md
# Viewport Reticle Kit Extension Sample ## [Viewport Reticle (omni.example.reticle)](exts/omni.example.reticle) ![Camera Reticle Preview](exts/omni.example.reticle/data/preview.png) ### About This extension shows how to build a viewport reticle extension. The focus of this sample extension is to show how to use omni.ui.scene to draw additional graphical primitives on the viewport. ### [README](exts/omni.example.reticle) See the [README for this extension](exts/omni.example.reticle) to learn more about it including how to use it. ### [Tutorial](tutorial/tutorial.md) Follow a [step-by-step tutorial](tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension. ## Adding This Extension To add this extension to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-reticle?branch=main&dir=exts` ## Linking with an Omniverse app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` There is also an analogous `link_app.sh` for Linux. If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app code ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3" ``` ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
1,757
Markdown
36.404255
193
0.759818
NVIDIA-Omniverse/kit-extension-sample-reticle/tutorial/tutorial.md
![NVIDIA Omniverse Logo](images/logo.png) # Create a Reusable Reticle with Omniverse Kit Extensions Camera [reticles](https://en.wikipedia.org/wiki/Reticle) are patterns and lines you use to line up a camera to a scene. In this tutorial, you learn how to make a reticle extension. You'll test it in Omniverse Code, but it can be used in any Omniverse Application. ## Learning Objectives In this guide, you learn how to: * Create an Omniverse Extension * Include your Extension in Omniverse Code * Draw a line on top of the [viewport](https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_viewport.html) * Divide the viewport with multiple lines * Create a crosshair and letterboxes ## Prerequisites Before you begin, install [Omniverse Code](https://docs.omniverse.nvidia.com/app_code/app_code/overview.html) version 2022.1.2 or higher. We recommend that you understand the concepts in the following tutorial before proceeding: * [How to make an extension by spawning primitives](https://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims/blob/main/exts/omni.example.spawn_prims/tutorial/tutorial.md) ## Step 1: Familiarize Yourself with the Starter Project In this section, you download and familiarize yourself with the starter project you use throughout this tutorial. ### Step 1.1: Clone the Repository Clone the `tutorial-start` branch of the `kit-extension-sample-reticle` [github repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-reticle/tree/tutorial-start): ```shell git clone -b tutorial-start https://github.com/NVIDIA-Omniverse/kit-extension-sample-reticle.git ``` This repository contains the assets you use in this tutorial ### Step 1.2: Navigate to `views.py` From the root directory of the project, navigate to `exts/omni.example.reticle/omni/example/reticle/views.py`. ### Step 1.3: Familiarize Yourself with `build_viewport_overlay()` In `views.py`, navigate to `build_viewport_overlay()`: ```python def build_viewport_overlay(self, *args): """Build all viewport graphics and ReticleMenu button.""" if self.vp_win is not None: self.vp_win.frame.clear() with self.vp_win.frame: with ui.ZStack(): # Set the aspect ratio policy depending if the viewport is wider than it is taller or vice versa. if self.vp_win.width / self.vp_win.height > self.get_aspect_ratio_flip_threshold(): self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL) else: self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL) # Build all the scene view guidelines with self.scene_view.scene: if self.model.composition_mode.as_int == CompositionGuidelines.THIRDS: self._build_thirds() elif self.model.composition_mode.as_int == CompositionGuidelines.QUAD: self._build_quad() elif self.model.composition_mode.as_int == CompositionGuidelines.CROSSHAIR: self._build_crosshair() if self.model.action_safe_enabled.as_bool: self._build_safe_rect(self.model.action_safe_percentage.as_float / 100.0, color=cl.action_safe_default) if self.model.title_safe_enabled.as_bool: self._build_safe_rect(self.model.title_safe_percentage.as_float / 100.0, color=cl.title_safe_default) if self.model.custom_safe_enabled.as_bool: self._build_safe_rect(self.model.custom_safe_percentage.as_float / 100.0, color=cl.custom_safe_default) if self.model.letterbox_enabled.as_bool: self._build_letterbox() # Build ReticleMenu button with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() self.reticle_menu = ReticleMenu(self.model) ``` Here, `self.vp_win` is the [viewport](https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_viewport.html) on which you'll build your reticle overlay. If there is no viewport, there's nothing to build on, so execution stops here: ```python if self.vp_win is not None: ``` If there is a viewport, you create a clean slate by calling [`clear()`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Container.clear) on the [frame](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Frame): ```python self.vp_win.frame.clear() ``` Next, you create a [ZStack](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Stack): ```python with self.vp_win.frame: with ui.ZStack(): ``` ZStack is a type of [Stack](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.Stack) that orders elements along the Z axis (forward and backward from the camera, as opposed to up and down or left and right). After that, you create a [SceneView](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.SceneView), a widget that renders the [Scene](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Scene): ```python if self.vp_win.width / self.vp_win.height > self.get_aspect_ratio_flip_threshold(): self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL) else: self.scene_view = scene.SceneView(aspect_ratio_policy=scene.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL) ``` When doing this, you make a calculation to determine what the appropriate `aspect_ratio_policy`, which defines how to handle a [Camera](https://docs.omniverse.nvidia.com/app_create/prod_materials-and-rendering/cameras.html) with an aspect ratio different than the SceneView. The SceneView does not consider non-rendered areas such as [letterboxes](https://en.wikipedia.org/wiki/Letterboxing_(filming)), hence `get_aspect_ratio_flip_threshold()`. Further down in `build_viewport_overlay()`, there are a number of `if` statements: ```python with self.scene_view.scene: if self.model.composition_mode.as_int == CompositionGuidelines.THIRDS: self._build_thirds() elif self.model.composition_mode.as_int == CompositionGuidelines.QUAD: self._build_quad() elif self.model.composition_mode.as_int == CompositionGuidelines.CROSSHAIR: self._build_crosshair() if self.model.action_safe_enabled.as_bool: self._build_safe_rect(self.model.action_safe_percentage.as_float / 100.0, color=cl.action_safe_default) if self.model.title_safe_enabled.as_bool: self._build_safe_rect(self.model.title_safe_percentage.as_float / 100.0, color=cl.title_safe_default) if self.model.custom_safe_enabled.as_bool: self._build_safe_rect(self.model.custom_safe_percentage.as_float / 100.0, color=cl.custom_safe_default) if self.model.letterbox_enabled.as_bool: self._build_letterbox() # Build ReticleMenu button with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() self.reticle_menu = ReticleMenu(self.model) ``` These are the different modes and tools the user can select from the **ReticleMenu**. Throughout this tutorial, you write the logic for the following functions: - `self._build_quad()` - `self._build_thirds()` - `self._build_crosshair()` - `self._build_crosshair()` - `_build_safe_rect()` - `_build_letterbox()` Before you do that, you need to import your custom Extension into Omniverse Code. ## Step 2: Import your Extension into Omniverse Code In order to use and test your Extension, you need to add it to Omniverse Code. > **Important:** Make sure you're using Code version 2022.1.2 or higher. ### Step 2.1: Navigate to the Extensions List In Omniverse Code, navigate to the *Extensions* panel: ![Click the Extensions panel](images/extensions_panel.png) Here, you see a list of Omniverse Extensions that you can activate and use in Code. > **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**: > > ![Show the Extensions panel](images/window_extensions.png) ### Step 2.2: Import your Extension Click the **gear** icon to open *Extension Search Paths*: ![Click the gear icon](images/extension_search_paths.png) In this panel, you can add your custom Extension to the Extensions list. ### Step 2.3: Create a New Search Path Create a new search path to the `exts` directory of your Extension by clicking the green **plus** icon and double-clicking on the **path** field: ![New search path](images/new_search_path.png) When you submit your new search path, you should be able to find your extension in the *Extensions* list. Activate it: ![Reticle extensions list](images/reticle_extensions_list.png) Now that your Extension is imported and active, you can make changes to the code and see them in your Application. ## Step 3: Draw a Single Line The first step to building a camera reticle is drawing a line. Once you can do that, you can construct more complex shapes using the line as a foundation. For example, you can split the viewport into thirds or quads using multiple lines. ### Step 3.1: Familiarize Yourself with Some Useful Modules At the top of `views.py`, review the following imported modules: ```py from omni.ui import color as cl from omni.ui import scene ``` - `omni.ui.color` offers color functionality. - [`omni.ui.scene`](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html) offers a number of useful classes including [Line](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Line). ### Step 3.2: Draw a Line in `build_viewport_overlay()` In `build_viewport_overlay()`, create a line, providing a start, stop, and color: ```python with self.scene_view.scene: start_point = [0, -1, 0] # [x, y, z] end_point = [0, 1, 0] line_color = cl.white scene.Line(start_point, end_point, color=line_color) ``` In the Code viewport, you'll see the white line: ![Viewport line](images/white_line.png) > **Optional Challenge:** Change the `start_point`, `end_point`, and `line_color` values to see how it renders in Code. ### Step 3.3: Remove the Line Now that you've learned how to use `omni.ui.scene` to draw a line, remove it to prepare your viewport for more meaningful shapes. ## Step 4: Draw Quadrants Now that you know how to draw a line, implement `_build_quad()` to construct four quadrants. In other words, split the view into four zones: ![Break the Viewport into quadrants](images/quad.png) ### Step 4.1: Draw Two Dividers Draw your quadrant dividers in `_build_quad()`: ```python def _build_quad(self): """Build the scene ui graphics for the Quad composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([0, -1, 0], [0, 1, 0], color=line_color) scene.Line([-aspect_ratio, 0, 0], [aspect_ratio, 0, 0], color=line_color) else: scene.Line([0, -inverse_ratio, 0], [0, inverse_ratio, 0], color=line_color) scene.Line([-1, 0, 0], [1, 0, 0], color=line_color) ``` To divide the viewport into quadrants, you only need two lines, so why are there four lines in this code? Imagine the aspect ratio can grow and shrink in the horizontal direction, but the vertical height is static. That would preserve the vertical aspect ratio as with [scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL). In this case, a vertical position in the viewport is bound between -1 and 1, but the horizontal position bounds are determined by the aspect ratio. Conversely, if your horizontal width bounds are static and the vertical height bounds can change, you would need the inverse of the aspect ratio (`inverse_ratio`). ### Step 4.2: Review Your Change In Omniverse Code, select **Quad** from the **Reticle** menu: ![Select quad](images/select_quad.png) With this option selected, the viewport is divided into quadrants. ## Step 5: Draw Thirds The [Rule of Thirds](https://en.wikipedia.org/wiki/Rule_of_thirds) is a theory in photography that suggests the best way to align elements in an image is like this: ![Break the Viewport into nine zones](images/thirds.png) Like you did in the last section, here you draw a number of lines. This time, though, you use four lines to make nine zones in your viewport. But like before, these lines depend on the [Aspect Ratio Policy](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.AspectRatioPolicy). ### Step 5.1: Draw Four Dividers Draw your dividers in `_build_thirds()`: ```python def _build_thirds(self): """Build the scene ui graphics for the Thirds composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([-0.333 * aspect_ratio, -1, 0], [-0.333 * aspect_ratio, 1, 0], color=line_color) scene.Line([0.333 * aspect_ratio, -1, 0], [0.333 * aspect_ratio, 1, 0], color=line_color) scene.Line([-aspect_ratio, -0.333, 0], [aspect_ratio, -0.333, 0], color=line_color) scene.Line([-aspect_ratio, 0.333, 0], [aspect_ratio, 0.333, 0], color=line_color) else: scene.Line([-1, -0.333 * inverse_ratio, 0], [1, -0.333 * inverse_ratio, 0], color=line_color) scene.Line([-1, 0.333 * inverse_ratio, 0], [1, 0.333 * inverse_ratio, 0], color=line_color) scene.Line([-0.333, -inverse_ratio, 0], [-0.333, inverse_ratio, 0], color=line_color) scene.Line([0.333, -inverse_ratio, 0], [0.333, inverse_ratio, 0], color=line_color) ``` > **Optional Challenge:** Currently, you call `scene.Line` eight times to draw four lines based on two situations. Optimize this logic so you only call `scene.Line` four times to draw four lines, regardless of the aspect ratio. > > **Hint:** You may need to define new variables. > > <details> > <summary>One Possible Solution</summary> > > is_preserving_aspect_vertical = scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL > > x, y = aspect_ratio, 1 if is_preserving_aspect_vertical else 1, inverse_ratio > x1, x2, y1, y2 = .333 * x, 1 * x, 1 * y, .333 * y > > scene.Line([-x1, -y1, 0], [-x1, y1, 0], color=line_color) > scene.Line([x1, -y1, 0], [x1, y1, 0], color=line_color) > scene.Line([-x2, -y2, 0], [x2, -y2, 0], color=line_color) > scene.Line([-x2, y2, 0], [x2, y2, 0], color=line_color) > </details> ### Step 5.2: Review Your Change In Omniverse Code, select **Thirds** from the **Reticle** menu: ![Select thirds](images/select_thirds.png) With this option selected, the viewport is divided into nine zones. ## Step 6: Draw a Crosshair A crosshair is a type of reticle commonly used in [first-person shooter](https://en.wikipedia.org/wiki/First-person_shooter) games to designate a projectile's expected position. For the purposes of this tutorial, you draw a crosshair at the center of the screen. To do this, you draw four small lines about the center of the viewport, based on the Aspect Ratio Policy. ### Step 6.1: Draw Your Crosshair Draw your crosshair in `_build_crosshair()`: ```python def _build_crosshair(self): """Build the scene ui graphics for the Crosshair composition mode.""" aspect_ratio = self.get_aspect_ratio() line_color = cl.comp_lines_default if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Line([0, 0.05 * aspect_ratio, 0], [0, 0.1 * aspect_ratio, 0], color=line_color) scene.Line([0, -0.05 * aspect_ratio, 0], [0, -0.1 * aspect_ratio, 0], color=line_color) scene.Line([0.05 * aspect_ratio, 0, 0], [0.1 * aspect_ratio, 0, 0], color=line_color) scene.Line([-0.05 * aspect_ratio, 0, 0], [-0.1 * aspect_ratio, 0, 0], color=line_color) else: scene.Line([0, 0.05 * 1, 0], [0, 0.1 * 1, 0], color=line_color) scene.Line([0, -0.05 * 1, 0], [0, -0.1 * 1, 0], color=line_color) scene.Line([0.05 * 1, 0, 0], [0.1 * 1, 0, 0], color=line_color) scene.Line([-0.05 * 1, 0, 0], [-0.1 * 1, 0, 0], color=line_color) scene.Points([[0.00005, 0, 0]], sizes=[2], colors=[line_color]) ``` This implementation is similar to your previous reticles except for the addition of a [point](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Points) at the true center of the crosshair. > **Optional Challenge:** Express the crosshair length as a variable. ### Step 6.2: Review Your Change In Omniverse Code, select **Crosshair** from the **Reticle** menu: ![Select crosshair](images/select_crosshair.png) With this option selected, the viewport shows a centered crosshair. ## Step 7: Draw Safe Area Rectangles Different televisions or monitors may display video in different ways, cutting off the edges. To account for this, producers use [Safe Areas](https://en.wikipedia.org/wiki/Safe_area_(television)) to make sure text and graphics are rendered nicely regardless of the viewer's hardware. In this section, you implement three rectangles: - **Title Safe:** This helps align text so that it's not too close to the edge of the screen. - **Action Safe:** This helps align graphics such as news tickers and logos. - **Custom Safe:** This helps the user define their own alignment rectangle. ### Step 7.1: Draw Your Rectangle Draw your safe [rectangle](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Rectangle) in `_build_safe_rect()`: ```python def _build_safe_rect(self, percentage, color): """Build the scene ui graphics for the safe area rectangle Args: percentage (float): The 0-1 percentage the render target that the rectangle should fill. color: The color to draw the rectangle wireframe with. """ aspect_ratio = self.get_aspect_ratio() inverse_ratio = 1 / aspect_ratio if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: scene.Rectangle(aspect_ratio*2*percentage, 1*2*percentage, thickness=1, wireframe=True, color=color) else: scene.Rectangle(1*2*percentage, inverse_ratio*2*percentage, thickness=1, wireframe=True, color=color) ``` Like before, you draw two different rectangles based on how the aspect is preserved. You draw them from the center after defining the width and height. Since the center is at `[0, 0, 0]` and either the horizontal or vertical axis goes from -1 to 1 (as opposed to from 0 to 1), you multiply the width and height by two. ### Step 7.2: Review Your Change In Omniverse Code, select your **Safe Areas** from the **Reticle** menu: ![Select safe areas](images/select_safe_areas.png) With these option selected, the viewport shows your safe areas. ## Step 8: Draw Letterboxes [Letterboxes](https://en.wikipedia.org/wiki/Letterboxing_(filming)) are large rectangles (typically black), on the edges of a screen used to help fit an image or a movie constructed with one aspect ratio into another. It can also be used for dramatic effect to give something a more theatrical look. ### Step 8.1 Draw Your Letterbox Helper Write a function to draw and place a [rectangle](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Rectangle): ```python def _build_letterbox(self): def build_letterbox_helper(width, height, x_offset, y_offset): move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) ``` The [scene.Matrix44.get_translation_matrix](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui.scene/docs/index.html#omni.ui_scene.scene.Matrix44.get_translation_matrix) creates a 4x4 matrix that can be multiplied with a point to offset it by an x, y, or z amount. Since you don't need to move your rectangles toward or away from the camera, the z value is 0. > **Further Reading:** To learn more about the math behind this operation, please check out [this article](https://medium.com/swlh/understanding-3d-matrix-transforms-with-pixijs-c76da3f8bd8). `build_letterbox_helper()` first defines the coordinates of where you expect to rectangle to be placed with `move`. Then, it creates a rectangle with that [transform](https://medium.com/swlh/understanding-3d-matrix-transforms-with-pixijs-c76da3f8bd8). Finally, it repeats the same steps to place and create a rectangle in the opposite direction of the first. Now that you have your helper function, you it to construct your letterboxes. ### Step 8.2: Review Your Potential Aspect Ratios Consider the following situations: ![Letterbox ratio diagram](images/letterbox_ratio.png) In this case, the viewport height is static, but the horizontal width can change. Additionally, the letterbox ratio is larger than the aspect ratio, meaning the rendered area is just as wide as the viewport, but not as tall. Next, write your logic to handle this case. ### Step 8.3: Build Your First Letterbox Build your letterbox to handle the case you analyzed in the last step: ```python def _build_letterbox(self): """Build the scene ui graphics for the letterbox.""" aspect_ratio = self.get_aspect_ratio() letterbox_color = cl.letterbox_default letterbox_ratio = self.model.letterbox_ratio.as_float def build_letterbox_helper(width, height, x_offset, y_offset): move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: if letterbox_ratio >= aspect_ratio: height = 1 - aspect_ratio / letterbox_ratio rect_height = height / 2 rect_offset = 1 - rect_height build_letterbox_helper(aspect_ratio, rect_height, 0, rect_offset) ``` Here, you can think of the `height` calculated above as the percentage of the viewport height to be covered by the letterboxes. If the `aspect_ratio` is 2 to 1, but the `letterbox_ratio` is 4 to 1, then `aspect_ratio / letterbox_ratio` is .5, meaning the letterboxes will cover half of the height. However, this is split by both the top and bottom letterboxes, so you divide the `height` by 2 to get the rectangle height (`rect_height`), which, with our example above, is .25. Now that you know the height of the rectangle, you need to know where to place it. Thankfully, the vertical height is bound from -1 to 1, and since you're mirroring the letterboxes along both the top and bottom, so you can subtract `rect_height` from the maximum viewport height (1). ### Step 8.4: Build The Other Letterboxes Using math similar to that explained in the last step, write the `_build_letterbox()` logic for the other three cases: ```python def _build_letterbox(self): """Build the scene ui graphics for the letterbox.""" aspect_ratio = self.get_aspect_ratio() letterbox_color = cl.letterbox_default letterbox_ratio = self.model.letterbox_ratio.as_float def build_letterbox_helper(width, height, x_offset, y_offset): move = scene.Matrix44.get_translation_matrix(x_offset, y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) move = scene.Matrix44.get_translation_matrix(-x_offset, -y_offset, 0) with scene.Transform(transform=move): scene.Rectangle(width * 2, height * 2, thickness=0, wireframe=False, color=letterbox_color) if self.scene_view.aspect_ratio_policy == scene.AspectRatioPolicy.PRESERVE_ASPECT_VERTICAL: if letterbox_ratio >= aspect_ratio: height = 1 - aspect_ratio / letterbox_ratio rect_height = height / 2 rect_offset = 1 - rect_height build_letterbox_helper(aspect_ratio, rect_height, 0, rect_offset) else: width = aspect_ratio - letterbox_ratio rect_width = width / 2 rect_offset = aspect_ratio - rect_width build_letterbox_helper(rect_width, 1, rect_offset, 0) else: inverse_ratio = 1 / aspect_ratio if letterbox_ratio >= aspect_ratio: height = inverse_ratio - 1 / letterbox_ratio rect_height = height / 2 rect_offset = inverse_ratio - rect_height build_letterbox_helper(1, rect_height, 0, rect_offset) else: width = (aspect_ratio - letterbox_ratio) * inverse_ratio rect_width = width / 2 rect_offset = 1 - rect_width build_letterbox_helper(rect_width, inverse_ratio, rect_offset, 0) ``` ## 8. Congratulations! Great job completing this tutorial! Interested in improving your skills further? Check out the [Omni.ui.scene Example](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene). ![NVIDIA Omniverse Logo](images/logo.png)
26,738
Markdown
49.546314
621
0.69908
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/config/extension.toml
[package] version = "1.3.1" title = "Example Viewport Reticle" description="An example kit extension of a viewport reticle using omni.ui.scene." authors=["Matias Codesal <[email protected]>"] readme = "docs/README.md" changelog="docs/CHANGELOG.md" repository = "" category = "Rendering" keywords = ["camera", "reticle", "viewport"] preview_image = "data/preview.png" icon = "icons/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.viewport.utility" = {} "omni.ui.scene" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.example.reticle"
654
TOML
26.291666
105
0.724771
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/omni/example/reticle/__init__.py
from .extension import ExampleViewportReticleExtension
55
Python
26.999987
54
0.909091
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. ## [Unreleased] ## [1.3.1] - 2022-09-09 ### Changed - Fixed on_window_changed callback for VP2 ## [1.3.0] - 2022-09-09 ### Changed - Fixed bad use of viewport window frame for VP2 - Now using ViewportAPI.subscribe_to_view_change() to update reticle on resolution changes. ## [1.2.0] - 2022-06-24 ### Changed - Refactored to omni.example.reticle - Updated preview.png - Cleaned up READMEs ### Removed - menu.png ## [1.1.0] - 2022-06-22 ### Changed - Refactored reticle.py to views.py - Fixed bug where Viewport Docs was being treated as viewport. - Moved Reticle button to bottom right of viewport to not overlap axes decorator. ### Removed - All mutli-viewport logic. ## [1.0.0] - 2022-05-25 ### Added - Initial add of the Sample Viewport Reticle extension.
846
Markdown
23.199999
91
0.712766
NVIDIA-Omniverse/kit-extension-sample-reticle/exts/omni.example.reticle/docs/README.md
# Viewport Reticle (omni.example.reticle) ![Camera Reticle Preview](../data/preview.png) ## Overview The Viewport Reticle Sample extension adds a new menu button at the bottom, right of the viewport. From this menu, users can enable and configure: 1. Composition Guidelines 2. Safe Area Guidelines 3. Letterbox ## [Tutorial](../../../tutorial/tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. [Get started with the tutorial.](../../../tutorial/tutorial.md) ## Usage ### Composition Guidelines * Click on the **Thirds**, **Quad**, or **Crosshair** button to enable a different composition mode. * Use the guidelines to help frame your shots. Click on the **Off** button to disable the composition guidelines. ### Safe Area Guidelines * Click on the checkbox for the safe area that you are interested in to enable the safe area guidelines. * Use the slider to adjust the area percentage for the respective safe areas. * NOTE: The sliders are disabled if their respective checkbox is unchecked. ### Letterbox * Check on **Letterbox Ratio** to enable the letterbox. * Enter a value or drag on the **Letterbox Ratio** field to adjust the letterbox ratio.
1,263
Markdown
45.814813
146
0.756136
NVIDIA-Omniverse/kit-extension-sample-ui-window/README.md
# omni.ui Kit Extension Samples ## [Generic Window (omni.example.ui_window)](exts/omni.example.ui_window) ![Object Info](exts/omni.example.ui_window/data/preview.png) ### About This extension provides an end-to-end example and general recommendations on creating a simple window using `omni.ui`. It contains the best practices of building an extension, a menu item, a window itself, a custom widget, and a generic style. ### [README](exts/omni.example.ui_window) See the [README for this extension](exts/omni.example.ui_window) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_window/tutorial/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_window/tutorial/tutorial.md) that walks you through how to use omni.ui to build this extension. ## [Julia Modeler (omni.example.ui_julia_modeler)](exts/omni.example.ui_julia_modeler) ![Julia Modeler](exts/omni.example.ui_julia_modeler/data/preview.png) ### About This extension is an example of a more advanced window with custom styling and custom widgets. Study this example to learn more about applying styles to `omni.ui` widgets and building your own custom widgets. ### [README](exts/omni.example.ui_julia_modeler/) See the [README for this extension](exts/omni.example.ui_julia_modeler/) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_julia_modeler/tutorial/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_julia_modeler/tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension. ## [Gradient Window (omni.example.ui_gradient_window)](exts/omni.example.ui_gradient_window/) ![Gradient Window](exts/omni.example.ui_gradient_window/data/Preview.png) ### About This extension shows how to build a Window that applys gradient styles to widgets. The focus of this sample extension is to show how to use omni.ui to create gradients with `ImageWithProvider`. ### [README](exts/omni.example.ui_gradient_window/) See the [README for this extension](exts/omni.example.ui_gradient_window/) to learn more about it including how to use it. ### [Tutorial](exts/omni.example.ui_gradient_window/tutorial/tutorial.md) Follow a [step-by-step tutorial](exts/omni.example.ui_gradient_window/tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension. ## Adding These Extensions To add these extensions to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window?branch=main&dir=exts` ## Linking with an Omniverse app For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included. Run: ```bash > link_app.bat ``` There is also an analogous `link_app.sh` for Linux. If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ```bash > link_app.bat --app code ``` You can also just pass a path to create link to: ```bash > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3" ``` ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
3,432
Markdown
44.773333
208
0.766026
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/tutorial/tutorial.md
![](images/logo.png) # Gradient Style Window Tutorial In this tutorial we will cover how we can create a gradient style that will be used in various widgets. This tutorial will cover how to create a gradient image / style that can be applied to UI. ## Learning Objectives - How to use `ImageWithProvider` to create Image Widgets - Create functions to interpolate between colors - Apply custom styles to widgets ## Prerequisites - [UI Window Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/Tutorial/exts/omni.example.ui_window/tutorial/tutorial.md) - Omniverse Code version 2022.1.2 or higher ## Step 1: Add the Extension ### Step 1.1: Clone the repository Clone the `gradient-tutorial-start` branch of the `kit-extension-sample-ui-window` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/tree/gradient-tutorial-start): ```shell git clone -b gradient-tutorial-start https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window.git ``` This repository contains the assets you use in this tutorial. ### Step 1.2: Open Extension Search Paths Go to *Extension Manager -> Gear Icon -> Extension Search Path*: ![cog](images/extension_search_paths.png#center) ### Step 1.3: Add the Path Create a new search path to the exts directory of your Extension by clicking the green plus icon and double-clicking on the path field: ![search path](images/new_search_path.png#center) When you submit your new search path, you should be able to find your extension in the Extensions list. ### Step 1.4: Enable the Extension ![enable](images/enable%20extension.png#center) After Enabling the extension the following window will appear: <center> ![png1](images/tut-png1.PNG#center) </center> Unlike the main repo, this extension is missing quite a few things that we will need to add, mainly the gradient. Moving forward we will go into detail on how to create the gradient style and apply it to our UI Window. ## Step 2: Familiarize Yourself with Interpolation What is interpolation? [Interpolation](https://en.wikipedia.org/wiki/Interpolation) a way to find or estimate a point based on a range of discrete set of known data points. For our case we interpolate between colors to appropriately set the slider handle color. Let's say the start point is black and our end point is white. What is a color that is in between black and white? Gray is what most would say. Using interpolation we can get more than just gray. Here's a picture representation of what it looks like to interpolate between black and white: ![png2](images/tut-png2.PNG) We can also use blue instead of black. It would then look something like this: ![png3](images/tut-png3.PNG) Interpolation can also be used with a spectrum of colors: ![png4](images/tut-png4.PNG) ## Step 3: Set up the Gradients Hexadecimal (Hex) is a base 16 numbering system where `0-9` represents their base 10 counterparts and `A-F` represent the base 10 values `10-15`. A Hex color is written as `#RRGGBB` where `RR` is red, `GG` is green and `BB` is blue. The hex values have the range `00` - `ff` which is equivalent to `0` - `255` in base 10. So to write the hex value to a color for red it would be: `#ff0000`. This is equivalent to saying `R=255, G=0, B=0`. To flesh out the `hex_to_color` function we will use bit shift operations to convert the hex value to color. ### Step 3.1: Navigate to `style.py` Open the project in VS Code and open the `style.py` file inside of `omni.example.ui_gradient_window\omni\example\ui_gradient_window` > **Tip:** Remember to open up any extension in VS Code by browsing to that extension in the `Extension` tab, then select the extension and click on the VS Code logo. Locate the function `hex_to_color` towards the bottom of the file. There will be other functions that are not yet filled out: ``` python def hex_to_color(hex: int) -> tuple: # YOUR CODE HERE pass def generate_byte_data(colors): # YOUR CODE HERE pass def _interpolate_color(hex_min: int, hex_max: int, intep): # YOUR CODE HERE pass def get_gradient_color(value, max, colors): # YOUR CODE HERE pass def build_gradient_image(colors, height, style_name): # YOUR CODE HERE pass ``` Currently we have the `pass` statement in each of the functions because each function needs at least one statement to run. > **Warning:** Removing the pass in these functions without adding any code will break other features of this extension! ### Step 3.2: Add Red to `hex_to_color` Replace `pass` with `red = hex & 255`: ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 ``` > **Warning:** Don't save yet! We must return a tuple before our function will run. ### Step 3.3: Add Green to `hex_to_color` Underneath where we declared `red`, add the following line `green = (hex >> 8) & 255`: ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 ``` > **Note:** 255 in binary is 0b11111111 (8 set bits) ### Step 3.4: Add the remaining colors to `hex_to_color` Try to fill out the rest of the following code for `blue` and `alpha`: ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = # YOUR CODE alpha = # YOUR CODE rgba_values = [red, green, blue, alpha] return rgba_values ``` <details> <summary>Click for solution</summary> ``` python def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = (hex >> 16) & 255 alpha = (hex >> 24) & 255 rgba_values = [red, green, blue, alpha] return rgba_values ``` </details> ## Step 4: Create `generate_byte_data` We will now be filling out the function `generate_byte_data`. This function will take our colors and generate byte data that we can use to make an image using `ImageWithProvider`. Here is the function we will be editing: ``` python def generate_byte_data(colors): # YOUR CODE HERE pass ``` ### Step 4.1: Create an Array for Color Values Replace `pass` with `data = []`. This will contain the color values: ``` python def generate_byte_data(colors): data = [] ``` ### Step 4.2: Loop Through the Colors Next we will loop through all provided colors in hex form to color form and add it to `data`. This will use `hex_to_color` created previously: ``` python def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) ``` ### Step 4.3: Loop Through the Colors Use [ByteImageProvider](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html?highlight=byteimage#omni.ui.ByteImageProvider) to set the sequence as byte data that will be used later to generate the image: ``` python def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) _byte_provider = ui.ByteImageProvider() _byte_provider.set_bytes_data(data [len(colors), 1]) return _byte_provider ``` ## Step 5: Build the Image Now that we have our data we can use it to create our image. ### Step 5.1: Locate `build_gradient_image()` In `style.py`, navigate to `build_gradient_image()`: ``` python def build_gradient_image(colors, height, style_name): # YOUR CODE HERE pass ``` ### Step 5.2: Create Byte Sequence Replace `pass` with `byte_provider = generate_byte_data(colors)`: ``` python def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ``` ### Step 5.3: Transform Bytes into the Gradient Image Use [ImageWithProvider](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html?highlight=byteimage#omni.ui.ImageWithProvider) to transform our sequence of bytes to an image. ``` python def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ui.ImageWithProvider(byte_provider,fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, height=height, name=style_name) return byte_provider ``` Save `style.py` and take a look at our window. It should look like the following: <center> ![png5](images/tut-png5.PNG) </center> > **Note:** If the extension does not look like the following, close down Code and try to relaunch. ### Step 5.4: How are the Gradients Used? Head over to `color_widget.py`, then scroll to around line 90: ``` python self.color_button_gradient_R = build_gradient_image([cl_attribute_dark, cl_attribute_red], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_G = build_gradient_image([cl_attribute_dark, cl_attribute_green], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_B = build_gradient_image([cl_attribute_dark, cl_attribute_blue], 22, "button_background_gradient") ``` This corresponds to the widgets that look like this: <center> ![png6](images/tut-png6.PNG) </center> ### Step 5.5: Experiment - Change the red to pink Go to `style.py`, locate the pre-defined constants, change `cl_attribute_red`'s value to `cl("#fc03be")` ``` python # Pre-defined constants. It's possible to change them runtime. fl_attr_hspacing = 10 fl_attr_spacing = 1 fl_group_spacing = 5 cl_attribute_dark = cl("#202324") cl_attribute_red = cl("#fc03be") # previously was cl("#ac6060") cl_attribute_green = cl("#60ab7c") cl_attribute_blue = cl("#35889e") cl_line = cl("#404040") cl_text_blue = cl("#5eb3ff") cl_text_gray = cl("#707070") cl_text = cl("#a1a1a1") cl_text_hovered = cl("#ffffff") cl_field_text = cl("#5f5f5f") cl_widget_background = cl("#1f2123") cl_attribute_default = cl("#505050") cl_attribute_changed = cl("#55a5e2") cl_slider = cl("#383b3e") cl_combobox_background = cl("#252525") cl_main_background = cl("#2a2b2c") cls_temperature_gradient = [cl("#fe0a00"), cl("#f4f467"), cl("#a8b9ea"), cl("#2c4fac"), cl("#274483"), cl("#1f334e")] cls_color_gradient = [cl("#fa0405"), cl("#95668C"), cl("#4b53B4"), cl("#33C287"), cl("#9fE521"), cl("#ff0200")] cls_tint_gradient = [cl("#1D1D92"), cl("#7E7EC9"), cl("#FFFFFF")] cls_grey_gradient = [cl("#020202"), cl("#525252"), cl("#FFFFFF")] cls_button_gradient = [cl("#232323"), cl("#656565")] ``` > **Tip:** Storing colors inside of the style.py file will help with reusing those values for other widgets. The value only has to change in one location, inside of style.py, rather than everywhere that the hex value was hard coded. <center> ![png7](images/tut-png7.PNG) </center> The colors for the sliders can be changed the same way. ## Step 6: Get the Handle of the Slider to Show the Color as it's Moved Currently, the handle on the slider turns to black when interacting with it. <center> ![gif1](images/gif1.gif) </center> This is because we need to let it know what color we are on. This can be a bit tricky since the sliders are simple images. However, using interpolation we can approximate the color we are on. During this step we will be filling out `_interpolate_color` function inside of `style.py`. ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): pass ``` ### Step 6.1: Set the color range Define `max_color` and `min_color`. Then remove `pass`. ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) ``` ### Step 6.2: Calculate the color ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) color = [int((max - min) * intep) + min for max, min in zip(max_color, min_color)] ``` ### Step 6.3: Return the interpolated color ``` python def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) color = [int((max - min) * intep) + min for max, min in zip(max_color, min_color)] return (color[3] << 8 * 3) + (color[2] << 8 * 2) + (color[1] << 8 * 1) + color[0] ``` ## Step 7: Getting the Gradient Color Now that we can interpolate between two colors we can grab the color of the gradient in which the slider is on. To do this we will be using value which is the position of the slider along the gradient image, max being the maximum number the value can be, and a list of all the colors. After calculating the step size between the colors that made up the gradient image, we can then grab the index to point to the appropriate color in our list of colors that our slider is closest to. From that we can interpolate between the first color reference in the list and the next color in the list based on the index. ### Step 7.1: Locate `get_gradient_color` function ``` python def get_gradient_color(value, max, colors): pass ``` ### Step 7.2: Declare `step_size` and `step` ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) ``` ### Step 7.3: Declare `percentage` and `idx` ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) ``` ### Step 7.4: Check to see if our index is equal to our step size, to prevent an Index out of bounds exception ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) if idx == step_size: color = colors[-1] ``` ### Step 7.5: Else interpolate between the current index color and the next color in the list. Return the result afterwards. ``` python def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) if idx == step_size: color = colors[-1] else: color = _interpolate_color(colors[idx], colors[idx+1], percentage) return color ``` Save the file and head back into Omniverse to test out the slider. Now when moving the slider it will update to the closest color within the color list. <center> ![gif2](images/gif2.gif) </center> ## Conclusion This was a tutorial about how to create gradient styles in the Window. Check out the complete code in the main branch to see how other styles were created. To learn more about how to create custom widgets check out the [Julia Modeler](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/tree/main/exts/omni.example.ui_julia_modeler) example. As a challenge, try to use the color that gets set by the slider to update something in the scene.
15,265
Markdown
32.849224
356
0.693089
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/config/extension.toml
[package] title = "omni.ui Gradient Window Example" description = "The full end to end example of the window" version = "1.0.1" category = "Example" authors = ["Min Jiang"] repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-windows" keywords = ["example", "window", "ui"] changelog = "docs/CHANGELOG.md" icon = "data/icon.png" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.example.ui_gradient_window" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
710
TOML
22.699999
84
0.676056
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/style.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["main_window_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) # Pre-defined constants. It's possible to change them runtime. fl_attr_hspacing = 10 fl_attr_spacing = 1 fl_group_spacing = 5 cl_attribute_dark = cl("#202324") cl_attribute_red = cl("#ac6060") cl_attribute_green = cl("#60ab7c") cl_attribute_blue = cl("#35889e") cl_line = cl("#404040") cl_text_blue = cl("#5eb3ff") cl_text_gray = cl("#707070") cl_text = cl("#a1a1a1") cl_text_hovered = cl("#ffffff") cl_field_text = cl("#5f5f5f") cl_widget_background = cl("#1f2123") cl_attribute_default = cl("#505050") cl_attribute_changed = cl("#55a5e2") cl_slider = cl("#383b3e") cl_combobox_background = cl("#252525") cl_main_background = cl("#2a2b2c") cls_temperature_gradient = [cl("#fe0a00"), cl("#f4f467"), cl("#a8b9ea"), cl("#2c4fac"), cl("#274483"), cl("#1f334e")] cls_color_gradient = [cl("#fa0405"), cl("#95668C"), cl("#4b53B4"), cl("#33C287"), cl("#9fE521"), cl("#ff0200")] cls_tint_gradient = [cl("#1D1D92"), cl("#7E7EC9"), cl("#FFFFFF")] cls_grey_gradient = [cl("#020202"), cl("#525252"), cl("#FFFFFF")] cls_button_gradient = [cl("#232323"), cl("#656565")] # The main style dict main_window_style = { "Button::add": {"background_color": cl_widget_background}, "Field::add": { "font_size": 14, "color": cl_text}, "Field::search": { "font_size": 16, "color": cl_field_text}, "Field::path": { "font_size": 14, "color": cl_field_text}, "ScrollingFrame::main_frame": {"background_color": cl_main_background}, # for CollapsableFrame "CollapsableFrame::group": { "margin_height": fl_group_spacing, "background_color": 0x0, "secondary_color": 0x0, }, "CollapsableFrame::group:hovered": { "margin_height": fl_group_spacing, "background_color": 0x0, "secondary_color": 0x0, }, # for Secondary CollapsableFrame "Circle::group_circle": { "background_color": cl_line, }, "Line::group_line": {"color": cl_line}, # all the labels "Label::collapsable_name": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text }, "Label::attribute_bool": { "alignment": ui.Alignment.LEFT_BOTTOM, "margin_height": fl_attr_spacing, "margin_width": fl_attr_hspacing, "color": cl_text }, "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_CENTER, "margin_height": fl_attr_spacing, "margin_width": fl_attr_hspacing, "color": cl_text }, "Label::attribute_name:hovered": {"color": cl_text_hovered}, "Label::header_attribute_name": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text }, "Label::details": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text_blue, "font_size": 19, }, "Label::layers": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_text_gray, "font_size": 19, }, "Label::attribute_r": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_attribute_red }, "Label::attribute_g": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_attribute_green }, "Label::attribute_b": { "alignment": ui.Alignment.LEFT_CENTER, "color": cl_attribute_blue }, # for Gradient Float Slider "Slider::float_slider":{ "background_color": cl_widget_background, "secondary_color": cl_slider, "border_radius": 3, "corner_flag": ui.CornerFlag.ALL, "draw_mode": ui.SliderDrawMode.FILLED, }, # for color slider "Circle::slider_handle":{"background_color": 0x0, "border_width": 2, "border_color": cl_combobox_background}, # for Value Changed Widget "Rectangle::attribute_changed": {"background_color":cl_attribute_changed, "border_radius": 2}, "Rectangle::attribute_default": {"background_color":cl_attribute_default, "border_radius": 1}, # all the images "Image::pin": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/Pin.svg"}, "Image::expansion": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/Details_options.svg"}, "Image::transform": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/offset_dark.svg"}, "Image::link": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/link_active_dark.svg"}, "Image::on_off": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/on_off.svg"}, "Image::header_frame": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/head.png"}, "Image::checked": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/checked.svg"}, "Image::unchecked": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/unchecked.svg"}, "Image::separator":{"image_url": f"{EXTENSION_FOLDER_PATH}/icons/separator.svg"}, "Image::collapsable_opened": {"color": cl_text, "image_url": f"{EXTENSION_FOLDER_PATH}/icons/closed.svg"}, "Image::collapsable_closed": {"color": cl_text, "image_url": f"{EXTENSION_FOLDER_PATH}/icons/open.svg"}, "Image::combobox": {"image_url": f"{EXTENSION_FOLDER_PATH}/icons/combobox_bg.svg"}, # for Gradient Image "ImageWithProvider::gradient_slider":{"border_radius": 4, "corner_flag": ui.CornerFlag.ALL}, "ImageWithProvider::button_background_gradient": {"border_radius": 3, "corner_flag": ui.CornerFlag.ALL}, # for Customized ComboBox "ComboBox::dropdown_menu":{ "color": cl_text, # label color "background_color": cl_combobox_background, "secondary_color": 0x0, # button background color }, } def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = (hex >> 16) & 255 alpha = (hex >> 24) & 255 rgba_values = [red, green, blue, alpha] return rgba_values def _interpolate_color(hex_min: int, hex_max: int, intep): max_color = hex_to_color(hex_max) min_color = hex_to_color(hex_min) color = [int((max - min) * intep) + min for max, min in zip(max_color, min_color)] return (color[3] << 8 * 3) + (color[2] << 8 * 2) + (color[1] << 8 * 1) + color[0] def get_gradient_color(value, max, colors): step_size = len(colors) - 1 step = 1.0/float(step_size) percentage = value / float(max) idx = (int) (percentage / step) if idx == step_size: color = colors[-1] else: color = _interpolate_color(colors[idx], colors[idx+1], percentage) return color def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) _byte_provider = ui.ByteImageProvider() _byte_provider.set_bytes_data(data, [len(colors), 1]) return _byte_provider def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ui.ImageWithProvider(byte_provider,fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, height=height, name=style_name) return byte_provider
7,557
Python
34.819905
117
0.633849
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ExampleWindowExtension"] from .window import PropertyWindowExample from functools import partial import asyncio import omni.ext import omni.kit.ui import omni.ui as ui class ExampleWindowExtension(omni.ext.IExt): """The entry point for Gradient Style Window Example""" WINDOW_NAME = "Gradient Style Window Example" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Put the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(ExampleWindowExtension.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(ExampleWindowExtension.MENU_PATH, value) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): # Called when the user pressed "X" self._set_menu(visible) if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): if value: self._window = PropertyWindowExample(ExampleWindowExtension.WINDOW_NAME, width=450, height=900) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False
2,895
Python
36.610389
108
0.666321
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/collapsable_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomCollsableFrame"] import omni.ui as ui def build_collapsable_header(collapsed, title): """Build a custom title of CollapsableFrame""" with ui.HStack(): ui.Spacer(width=10) ui.Label(title, name="collapsable_name") if collapsed: image_name = "collapsable_opened" else: image_name = "collapsable_closed" ui.Image(name=image_name, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=16, height=16) class CustomCollsableFrame: """The compound widget for color input""" def __init__(self, frame_name, collapsed=False): with ui.ZStack(): self.collapsable_frame = ui.CollapsableFrame( frame_name, name="group", build_header_fn=build_collapsable_header, collapsed=collapsed) with ui.VStack(): ui.Spacer(height=29) with ui.HStack(): ui.Spacer(width=20) ui.Image(name="separator", fill_policy=ui.FillPolicy.STRETCH, height=15) ui.Spacer(width=20)
1,519
Python
35.190475
104
0.655036
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/color_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ColorWidget"] from ctypes import Union from typing import List, Optional import omni.ui as ui from .style import build_gradient_image, cl_attribute_red, cl_attribute_green, cl_attribute_blue, cl_attribute_dark SPACING = 16 class ColorWidget: """The compound widget for color input""" def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = args self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.__multifield: Optional[ui.MultiFloatDragField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__draw_colorpicker = kwargs.pop("draw_colorpicker", True) self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__model = None self.__multifield = None self.__colorpicker = None self.__frame = None def __getattr__(self, attr): """ Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__root_frame, attr) @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__multifield: return self.__multifield.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__multifield.model = value self.__colorpicker.model = value def _build_fn(self): def _on_value_changed(model, rect_changed, rect_default): if model.get_item_value_model().get_value_as_float() != 0: rect_changed.visible = False rect_default.visible = True else: rect_changed.visible = True rect_default.visible = False def _restore_default(model, rect_changed, rect_default): items = model.get_item_children() for id, item in enumerate(items): model.get_item_value_model(item).set_value(self.__defaults[id]) rect_changed.visible = False rect_default.visible = True with ui.HStack(spacing=SPACING): # The construction of multi field depends on what the user provided, # defaults or a model if self.__model: # the user provided a model self.__multifield = ui.MultiFloatDragField( min=0, max=1, model=self.__model, h_spacing=SPACING, name="attribute_color" ) model = self.__model else: # the user provided a list of default values with ui.ZStack(): with ui.HStack(): self.color_button_gradient_R = build_gradient_image([cl_attribute_dark, cl_attribute_red], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_G = build_gradient_image([cl_attribute_dark, cl_attribute_green], 22, "button_background_gradient") ui.Spacer(width=9) with ui.VStack(width=6): ui.Spacer(height=8) ui.Circle(name="group_circle", width=4, height=4) self.color_button_gradient_B = build_gradient_image([cl_attribute_dark, cl_attribute_blue], 22, "button_background_gradient") ui.Spacer(width=2) with ui.HStack(): with ui.VStack(): ui.Spacer(height=1) self.__multifield = ui.MultiFloatDragField( *self.__defaults, min=0, max=1, h_spacing=SPACING, name="attribute_color") ui.Spacer(width=3) with ui.HStack(spacing=22): labels = ["R", "G", "B"] if self.__draw_colorpicker else ["X", "Y", "Z"] ui.Label(labels[0], name="attribute_r") ui.Label(labels[1], name="attribute_g") ui.Label(labels[2], name="attribute_b") model = self.__multifield.model if self.__draw_colorpicker: self.__colorpicker = ui.ColorWidget(model, width=0) rect_changed, rect_default = self.__build_value_changed_widget() model.add_item_changed_fn(lambda model, i: _on_value_changed(model, rect_changed, rect_default)) rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(model, rect_changed, rect_default)) def __build_value_changed_widget(self): with ui.VStack(width=0): ui.Spacer(height=3) rect_changed = ui.Rectangle(name="attribute_changed", width=15, height=15, visible= False) ui.Spacer(height=4) with ui.HStack(): ui.Spacer(width=3) rect_default = ui.Rectangle(name="attribute_default", width=5, height=5, visible= True) return rect_changed, rect_default
5,735
Python
43.465116
150
0.565998
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/window.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved./icons/ # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["PropertyWindowExample"] from ast import With from ctypes import alignment import omni.kit import omni.ui as ui from .style import main_window_style, get_gradient_color, build_gradient_image from .style import cl_combobox_background, cls_temperature_gradient, cls_color_gradient, cls_tint_gradient, cls_grey_gradient, cls_button_gradient from .color_widget import ColorWidget from .collapsable_widget import CustomCollsableFrame, build_collapsable_header LABEL_WIDTH = 120 SPACING = 10 def _get_plus_glyph(): return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_context.svg") def _get_search_glyph(): return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_search.svg") class PropertyWindowExample(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = main_window_style # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def _build_transform(self): """Build the widgets of the "Calculations" group""" with ui.ZStack(): with ui.VStack(): ui.Spacer(height=5) with ui.HStack(): ui.Spacer() ui.Image(name="transform", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=24, height=24) ui.Spacer(width=30) ui.Spacer() with CustomCollsableFrame("TRANSFORMS").collapsable_frame: with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=2) self._build_vector_widget("Position", 70) self._build_vector_widget("Rotation", 70) with ui.ZStack(): self._build_vector_widget("Scale", 85) with ui.HStack(): ui.Spacer(width=42) ui.Image(name="link", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=20) def _build_path(self): CustomCollsableFrame("PATH", collapsed=True) def _build_light_properties(self): """Build the widgets of the "Parameters" group""" with CustomCollsableFrame("LIGHT PROPERTIES").collapsable_frame: with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=2) self._build_combobox("Type", ["Sphere Light", "Disk Light", "Rect Light"]) self.color_gradient_data, self.tint_gradient_data, self.grey_gradient_data = self._build_color_widget("Color") self._build_color_temperature() self.diffuse_button_data = self._build_gradient_float_slider("Diffuse Multiplier") self.exposture_button_data = self._build_gradient_float_slider("Exposture") self.intensity_button_data = self._build_gradient_float_slider("Intensity", default_value=3000, min=0, max=6000) self._build_checkbox("Normalize Power", False) self._build_combobox("Purpose", ["Default", "Customized"]) self.radius_button_data = self._build_gradient_float_slider("Radius") self._build_shaping() self.specular_button_data = self._build_gradient_float_slider("Specular Multiplier") self._build_checkbox("Treat As Point") def _build_line_dot(self, line_width, height): with ui.HStack(): ui.Spacer(width=10) with ui.VStack(width=line_width): ui.Spacer(height=height) ui.Line(name="group_line", alignment=ui.Alignment.TOP) with ui.VStack(width=6): ui.Spacer(height=height-2) ui.Circle(name="group_circle", width=6, height=6, alignment=ui.Alignment.BOTTOM) def _build_shaping(self): """Build the widgets of the "SHAPING" group""" with ui.ZStack(): with ui.HStack(): ui.Spacer(width=3) self._build_line_dot(10, 17) with ui.HStack(): ui.Spacer(width=13) with ui.VStack(): ui.Spacer(height=17) ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0) ui.Spacer(height=80) with ui.CollapsableFrame(" SHAPING", name="group", build_header_fn=build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): self.angle_button_data = self._build_gradient_float_slider("Cone Angle") self.softness_button_data = self._build_gradient_float_slider("Cone Softness") self.focus_button_data = self._build_gradient_float_slider("Focus") self.focus_color_data, self.focus_tint_data, self.focus_grey_data = self._build_color_widget("Focus Tint") def _build_vector_widget(self, widget_name, space): with ui.HStack(): ui.Label(widget_name, name="attribute_name", width=0) ui.Spacer(width=space) # The custom compound widget ColorWidget(1.0, 1.0, 1.0, draw_colorpicker=False) ui.Spacer(width=10) def _build_color_temperature(self): with ui.ZStack(): with ui.HStack(): ui.Spacer(width=10) with ui.VStack(): ui.Spacer(height=8) ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0) with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): self._build_line_dot(10, 8) ui.Label("Enable Color Temperature", name="attribute_name", width=0) ui.Spacer() ui.Image(name="on_off", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=20) rect_changed, rect_default = self.__build_value_changed_widget() self.temperature_button_data = self._build_gradient_float_slider(" Color Temperature", default_value=6500.0) self.temperature_slider_data = self._build_slider_handle(cls_temperature_gradient) with ui.HStack(): ui.Spacer(width=10) ui.Line(name="group_line", alignment=ui.Alignment.TOP) def _build_color_widget(self, widget_name): with ui.ZStack(): with ui.HStack(): ui.Spacer(width=10) with ui.VStack(): ui.Spacer(height=8) ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0) with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): self._build_line_dot(40, 9) ui.Label(widget_name, name="attribute_name", width=0) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) ui.Spacer(width=10) color_data = self._build_slider_handle(cls_color_gradient) tint_data = self._build_slider_handle(cls_tint_gradient) grey_data = self._build_slider_handle(cls_grey_gradient) with ui.HStack(): ui.Spacer(width=10) ui.Line(name="group_line", alignment=ui.Alignment.TOP) return color_data, tint_data, grey_data def _build_slider_handle(self, colors): handle_Style = {"background_color": colors[0], "border_width": 2, "border_color": cl_combobox_background} def set_color(placer, handle, offset): # first clamp the value max = placer.computed_width - handle.computed_width if offset < 0: placer.offset_x = 0 elif offset > max: placer.offset_x = max color = get_gradient_color(placer.offset_x.value, max, colors) handle_Style.update({"background_color": color}) handle.style = handle_Style with ui.HStack(): ui.Spacer(width=18) with ui.ZStack(): with ui.VStack(): ui.Spacer(height=3) byte_provider = build_gradient_image(colors, 8, "gradient_slider") with ui.HStack(): handle_placer = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=0) with handle_placer: handle = ui.Circle(width=15, height=15, style=handle_Style) handle_placer.set_offset_x_changed_fn(lambda offset: set_color(handle_placer, handle, offset.value)) ui.Spacer(width=22) return byte_provider def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(name="main_frame"): with ui.VStack(height=0, spacing=SPACING): self._build_head() self._build_transform() self._build_path() self._build_light_properties() ui.Spacer(height=30) def _build_head(self): with ui.ZStack(): ui.Image(name="header_frame", height=150, fill_policy=ui.FillPolicy.STRETCH) with ui.HStack(): ui.Spacer(width=12) with ui.VStack(spacing=8): self._build_tabs() ui.Spacer(height=1) self._build_selection_widget() self._build_stage_path_widget() self._build_search_field() ui.Spacer(width=12) def _build_tabs(self): with ui.HStack(height=35): ui.Label("DETAILS", width=ui.Percent(17), name="details") with ui.ZStack(): ui.Image(name="combobox", fill_policy=ui.FillPolicy.STRETCH, height=35) with ui.HStack(): ui.Spacer(width=15) ui.Label("LAYERS | ", name="layers", width=0) ui.Label(f"{_get_plus_glyph()}", width=0) ui.Spacer() ui.Image(name="pin", width=20) def _build_selection_widget(self): with ui.HStack(height=20): add_button = ui.Button(f"{_get_plus_glyph()} Add", width=60, name="add") ui.Spacer(width=14) ui.StringField(name="add").model.set_value("(2 models selected)") ui.Spacer(width=8) ui.Image(name="expansion", width=20) def _build_stage_path_widget(self): with ui.HStack(height=20): ui.Spacer(width=3) ui.Label("Stage Path", name="header_attribute_name", width=70) ui.StringField(name="path").model.set_value("/World/environment/tree") def _build_search_field(self): with ui.HStack(): ui.Spacer(width=2) # would add name="search" style, but there is a bug to use glyph together with style # make sure the test passes for now ui.StringField(height=23).model.set_value(f"{_get_search_glyph()} Search") def _build_checkbox(self, label_name, default_value=True): def _restore_default(rect_changed, rect_default): image.name = "checked" if default_value else "unchecked" rect_changed.visible = False rect_default.visible = True def _on_value_changed(image, rect_changed, rect_default): image.name = "unchecked" if image.name == "checked" else "checked" if (default_value and image.name == "unchecked") or (not default_value and image.name == "checked"): rect_changed.visible = True rect_default.visible = False else: rect_changed.visible = False rect_default.visible = True with ui.HStack(): ui.Label(label_name, name=f"attribute_bool", width=self.label_width, height=20) name = "checked" if default_value else "unchecked" image =ui.Image(name=name, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=18, width=18) ui.Spacer() rect_changed, rect_default = self.__build_value_changed_widget() image.set_mouse_pressed_fn(lambda x, y, b, m: _on_value_changed(image, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(rect_changed, rect_default)) def __build_value_changed_widget(self): with ui.VStack(width=20): ui.Spacer(height=3) rect_changed = ui.Rectangle(name="attribute_changed", width=15, height=15, visible= False) ui.Spacer(height=4) with ui.HStack(): ui.Spacer(width=3) rect_default = ui.Rectangle(name="attribute_default", width=5, height=5, visible= True) return rect_changed, rect_default def _build_gradient_float_slider(self, label_name, default_value=0, min=0, max=1): def _on_value_changed(model, rect_changed, rect_defaul): if model.as_float == default_value: rect_changed.visible = False rect_defaul.visible = True else: rect_changed.visible = True rect_defaul.visible = False def _restore_default(slider): slider.model.set_value(default_value) with ui.HStack(): ui.Label(label_name, name=f"attribute_name", width=self.label_width) with ui.ZStack(): button_background_gradient = build_gradient_image(cls_button_gradient, 22, "button_background_gradient") with ui.VStack(): ui.Spacer(height=1.5) with ui.HStack(): slider = ui.FloatSlider(name="float_slider", height=0, min=min, max=max) slider.model.set_value(default_value) ui.Spacer(width=1.5) ui.Spacer(width=4) rect_changed, rect_default = self.__build_value_changed_widget() # switch the visibility of the rect_changed and rect_default to indicate value changes slider.model.add_value_changed_fn(lambda model: _on_value_changed(model, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(slider)) return button_background_gradient def _build_combobox(self, label_name, options): def _on_value_changed(model, rect_changed, rect_defaul): index = model.get_item_value_model().get_value_as_int() if index == 0: rect_changed.visible = False rect_defaul.visible = True else: rect_changed.visible = True rect_defaul.visible = False def _restore_default(combo_box): combo_box.model.get_item_value_model().set_value(0) with ui.HStack(): ui.Label(label_name, name=f"attribute_name", width=self.label_width) with ui.ZStack(): ui.Image(name="combobox", fill_policy=ui.FillPolicy.STRETCH, height=35) with ui.HStack(): ui.Spacer(width=10) with ui.VStack(): ui.Spacer(height=10) option_list = list(options) combo_box = ui.ComboBox(0, *option_list, name="dropdown_menu") with ui.VStack(width=0): ui.Spacer(height=10) rect_changed, rect_default = self.__build_value_changed_widget() # switch the visibility of the rect_changed and rect_default to indicate value changes combo_box.model.add_item_changed_fn(lambda m, i: _on_value_changed(m, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(combo_box))
17,220
Python
45.923706
146
0.573403
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/tests/test_window.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["TestWindow"] from omni.example.ui_gradient_window import PropertyWindowExample from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import omni.kit.app import omni.kit.test EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests") class TestWindow(OmniUiTest): async def test_general(self): """Testing general look of section""" window = PropertyWindowExample("Test") await omni.kit.app.get_app().next_update_async() await self.docked_test_window( window=window, width=450, height=600, ) # Wait for images for _ in range(20): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="window.png")
1,363
Python
34.894736
115
0.710198
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/docs/CHANGELOG.md
# Changelog ## [1.0.1] - 2022-06-22 ### Changed - Added README.md - Clean up the style a bit and change some of the widgets function name ## [1.0.0] - 2022-06-09 ### Added - Initial window
191
Markdown
16.454544
71
0.65445
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/docs/README.md
# Gradient Window (omni.example.ui_gradient_window) ![](../data/preview.png) # Overview In this example, we create a window which heavily uses graident style in various widgets. The window is build using `omni.ui`. It contains the best practices of how to build customized widgets and leverage to reuse them without duplicating the code. ## [Tutorial](../tutorial/tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. [Get started with the tutorial.](../tutorial/tutorial.md) # Customized Widgets A customized widget can be a class or a function. It's not required to derive from anything. We build customized widget so that we can use them just like default `omni.ui` widgets which allows us to reuse the code and saves us from reinventing the wheel again and again. ## Gradient Image Gradient images are used a lot in this example. It is used in the customized slider and field background. Therefore, we encapsulate it into a function `build_gradient_image` which is a customized `ui.ImageWithProvider` under the hood. The `ImageWithProvider` has a source data which is generated by `ui.ByteImageProvider`. We define how to generate the byte data into a function called `generate_byte_data`. We use one pixel height data to generate the image data. For users' conveniences, we provide the function signature as an array of hex colors, so we provided a function to achieve `hex_to_color` conversion. ``` def hex_to_color(hex: int) -> tuple: # convert Value from int red = hex & 255 green = (hex >> 8) & 255 blue = (hex >> 16) & 255 alpha = (hex >> 24) & 255 rgba_values = [red, green, blue, alpha] return rgba_values def generate_byte_data(colors): data = [] for color in colors: data += hex_to_color(color) _byte_provider = ui.ByteImageProvider() _byte_provider.set_bytes_data(data, [len(colors), 1]) return _byte_provider def build_gradient_image(colors, height, style_name): byte_provider = generate_byte_data(colors) ui.ImageWithProvider(byte_provider,fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, height=height, name=style_name) return byte_provider ``` With this, the user will be able to generate gradient image easily which also allows flexibly set the height and style. Here are a couple of examples used in the example: ``` colors = cls_color_gradient = [cl("#fa0405"), cl("#95668C"), cl("#4b53B4"), cl("#33C287"), cl("#9fE521"), cl("#ff0200")] byte_provider = build_gradient_image(colors, 8, "gradient_slider") cls_button_gradient = [cl("#232323"), cl("#656565")] button_background_gradient = build_gradient_image(cls_button_gradient, 22, "button_background_gradient") ``` ![](../data/gradient_img.png) ## Value Changed Widget In this example, almost every attribute has got a widget which indicates whether the value has been changed or not. By default, the widget is a small gray rectangle, while the value has been changed it becomes a bigger blue rectangle. We wrapped this up into a function called `__build_value_changed_widget` and returns both rectangles so that the caller can switch the visiblity of them. It is not only an indicator of value change, it is also a button. While you click on it when the value has changed, it has the callback to restore the default value for the attribute. Since different attribute has different data model, the restore callbacks are added into different widgets instead of the value change widget itself. ## Gradient Float Slider Almost all the numeric attribute in this example is using gradient float slider which is defined by `_build_gradient_float_slider`. This customized float slider are consisted of three parts: the label, the float slider, and the value-changed-widget. The label is just a usual `ui.Label`. The slider is a normal `ui.FloatSlider` with a gradient image, composed by `ui.ZStack`. We also added the `add_value_changed_fn` callback for slider model change to trigger the value-changed-widget change visiblity and `rect_changed.set_mouse_pressed_fn` to add the callback to restore the default value of the silder. ``` rect_changed, rect_default = self.__build_value_changed_widget() # switch the visibility of the rect_changed and rect_default to indicate value changes slider.model.add_value_changed_fn(lambda model: _on_value_changed(model, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(slider)) ``` ![](../data/gradient_float_slider.png) ## Customized CheckBox The customized Checkbox is defined by `_build_checkbox`. It is also consisted of three parts: the label, the check box, and the value-changed-widget. The label is just a usual `ui.Label`. For the check box, since we have completely two different images for the checked and unchecked status. Therefore, we use `ui.Image` as the base for the customized CheckBox. The `name` of the image is used to switch between the corresponding styles which changes the `image_url` for the image. The callbacks of value-changed-widget are added similarly as gradient float slider. ![](../data/checked.png) ![](../data/unchecked.png) ## Customized ComboBox The customized ComboBox is defined by `_build_combobox`. It is also consisted of three parts: the label, the ComnoBox, and the value-changed-widget. The label is just a usual `ui.Label`. The ComboBox is a normal `ui.ComboBox` with a gradient image, composed by `ui.ZStack`. The callbacks of value-changed-widget are added similarly as gradient float slider. ![](../data/combobox.png) ![](../data/combobox2.png) ## Customized CollsableFrame The customized CollsableFrame is wrapped in `CustomCollsableFrame` class. It is a normal `ui.CollapsableFrame` with a customized header. It is the main widget groups other widgets as a collapsable frame. ![](../data/collapse_frame.png) ## Customized ColorWidget The customized ColorWidget is wrapped in `ColorWidget` class. ![](../data/color_widget.png) The RGB values `self.__multifield` is represented by a normal `ui.MultiFloatDragField`, composed with three gradient images of red, green and blue using `ui.ZStack`, as well as the lable and circle dots in between the three values. The colorpicker is just a normal `ui.ColorWidget`, which shares the same model of `self.__multifield`, so that these two widgets are connected. We also added the `add_item_changed_fn` callback for the shared model. When the model item changes, it will trigger the value-changed-widget to switch the visiblity and `rect_changed.set_mouse_pressed_fn` to add the callback to restore the default value for the shared model. # Style We kept all the styles of all the widgets in `style.py`. One advantage is that specific style or colors could be reused without duplication. The other advantage is that users don't need to go through the lengthy widgets code to change the styles. All the styles are recommended to be arranged and named in a self-explanatory way. # Window It's handy to derive a custom window from the class `ui.Window`. The UI can be defined right in __init__, so it's created immediately or it can be defined in a `set_build_fn` callback and it will be created when the window is visible. The later one is used in this example. ``` class PropertyWindowExample(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) ``` Inside the `self._build_fn`, we use the customized widgets to match the design layout for the window. # Extension When the extension starts up, we register a new menu item that controls the window and shows the window. A very important part is using `ui.Workspace.set_show_window_fn` to register the window in `omni.ui`. It will help to save and load the layout of Kit. ``` ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) ``` When the extension shuts down, we remove the menu item and deregister the window callback.
8,457
Markdown
52.194968
614
0.753104
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/tutorial/tutorial.md
# How to Understand and Navigate Omniverse Code from Other Developers This tutorial teaches how to access, navigate and understand source code from extensions written by other developers. This is done by opening an extension, navigating to its code and learning how its user interface is put together. It also teaches how custom widgets are organized. With this information developers can find user interface elements in other developers' extensions and re-use or extend them. The extension itself is a UI mockup for a [julia quaternion modeling tool](http://paulbourke.net/fractals/quatjulia/). ## Learning Objectives - Access Source of Omniverse Extensions - Understand UI Code Structure - Re-use Widget Code from Other Developers ## Prerequisites - [UI Window Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_window/tutorial/tutorial.md) - [UI Gradient Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_gradient_window/tutorial/tutorial.md) - Omniverse Code version 2022.1.1 or higher - Working understanding of GitHub - Visual Studio Code ## Step 1: Clone the Repository Clone the `main` branch of the `kit-extension-sample-ui-window` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window): ```shell git clone https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window.git ``` This repository contains the code you use in this tutorial. ## Step 2: Add the Extension to Omniverse Code In order to use and test your Extension, you need to add it to Omniverse Code. ### Step 2.1: Navigate to the Extensions List In Omniverse Code, navigate to the *Extensions* panel: ![Click the Extensions panel](Images/extensions_panel.png) Here, you see a list of Omniverse Extensions that you can activate and use in Code. > **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**: > > ![Show the Extensions panel](Images/window_extensions.png) ### Step 2.2: Navigate to the *Extension Search Paths* Click the **gear** icon to open *Extension Search Paths*: ![Click the gear icon](Images/extension_search_paths.png) In this panel, you can add your custom Extension to the Extensions list. ### Step 2.3: Create a New Search Path Create a new search path to the `exts` directory of your Extension by clicking the green **plus** icon and double-clicking on the **path** field: ![New search path](Images/new_search_path_ui-window.png) When you submit your new search path, you should be able to find your extension in the *Extensions* list. Search for "omni.example.ui_" to filter down the list. Activate the "OMNI.UI JULIA QUATERNION MO..." Extension: ![Reticle extensions list](Images/window_extensions_list_ui-julia.png) Now that your Extension is added and enabled, you can make changes to the code and see them in your Application. You will see the user interface pictured below: <p align="center"> <img src="Images/JuliaUI.png" width=25%> <p> ## Step 3: View the User Interface and Source Code ### Step 3.1: Review the User Interface Take a moment to think like a connoisseur of excellent user interface elements. What aspects of this user interface are worth collecting? Notice the styling on the collapsable frames, the backgrounds on the sliders. Edit some of the values and notice that the arrow on the right is now highlighted in blue. Click on that arrow and notice that the slider returns to a default value. Focus on the best aspects because you can collect those and leave the lesser features behind. ### Step 3.2: Access the Source Code Now, go back to the extensions window and navigate to the `Julia` extension. Along the top of its details window lies a row of icons as pictured below: <p align="center"> <img src="Images/VisualStudioIcon.png" width=75%> <p> Click on the Visual Studio icon to open the Extension's source in Visual Studio. This is a great way to access extension source code and learn how they were written. ## Step 4: Find `extension.py` This section explains how to start navigation of an extension's source code. ### Step 4.1: Access the Extension Source Code Open the Visual Studio window and expand the `exts` folder. The image below will now be visible: <p align="center"> <img src="Images/FolderStructure.png" width=35%> <p> Click on `omni\example\ui_julia_modeler` to expand it and see the files in that folder as shown below: <p align="center"> <img src="Images/DevFiles.png" width=35%> <p> ### Step 4.2: Open `extension.py` The file named `extension.py` is a great place to start. It contains a class that derives from `omni.ext.IExt`. ### Step 4.3: Find the `on_startup` Function Look for the `on_startup`. This function runs when the extension first starts and is where the UI should be built. It has been included below: ```Python def on_startup(self): # The ability to show the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, partial(self.show_window, None)) # Add the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( JuliaModelerExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(JuliaModelerExtension.WINDOW_NAME) ``` This function does a few steps that are common for a window-based extension. Not all extensions will be written in exactly this way, but these are best practices and are good things to look for. 1. It registers a `show` function with the application. 2. It adds the extension to the `Window` application menu. 3. It requests that the window be shown using the `show` function registered before. ### Step 4.4: Find the Function that Builds the Window What function has been registered to show the `Julia` extension window? It is `self.show_window()`. Scroll down until you find it in `extension.py`. It has been included below for convenience: ```Python def show_window(self, menu, value): if value: self._window = JuliaModelerWindow( JuliaModelerExtension.WINDOW_NAME, width=WIN_WIDTH, height=WIN_HEIGHT) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False ``` In this function `value` is a boolean that is `True` if the window should be shown and `False` if the window should be hidden. Take a look at the code block that will run if `value` is `True` and you will see that `self._window` is set equal to a class constructor. ### Step 4.5: Navigate to the Window Class To find out where this class originates, hold the `ctrl` button and click on `JuliaModelerWindow` in the third line of the function. This will navigate to that symbol's definition. In this case it opens the `window.py` file and takes the cursor to definition of the `JuliaModelerWindow` class. The next section explores this class and how the window is built. ## Step 5: Explore `JuliaModelerWindow` This sections explores the `JuliaModelerWindow` class, continuing the exploration of this extension, navigating the code that builds the UI from the top level towards specific elements. ### Step 5.1: Read `show_window()` The `show_window()` function in the previous section called the constructor from the `JuliaModelerWindow` class. The constructor in Python is the `__init__()` function and is copied below: ```Python def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = ATTR_LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = julia_modeler_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) ``` The first statement simply sets a label width. The next statement calls `super().__init__()`. This initializes all base classes of `JuliaModelerWindow`. This has to do with inheritance, a topic that will be briefly covered later in this tutorial. The third statement sets the window style, which is useful information, but is the topic of another tutorial. These styles are contained in `style.py` for the curious. Finally, the function registers the `self._build_fn` callback as the frame's build function. This is the function of interest. ### Step 5.2: Navigate to `_build_fn()` Hold ctrl and click on `self._build_fn` which has been reproduced below: ```Python def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(name="window_bg", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.VStack(height=0): self._build_title() self._build_calculations() self._build_parameters() self._build_light_1() self._build_scene() ``` This function builds an outer scrolling frame, a vertical stack, and then builds a few sections to add to that stack. Each of these methods has useful information worth taking a look at, but this tutorial will focus on `_build_parameters()`. ### Step 5.3: Navigate to `_build_parameters()` Navigate to `_build_parameters` using ctrl+click. As usual, it is duplicated below: ```Python def _build_parameters(self): """Build the widgets of the "Parameters" group""" with ui.CollapsableFrame("Parameters".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=-2, max=2, display_range=True, label="Iterations", default_val=0.75) CustomSliderWidget(min=0, max=2, display_range=True, label="i", default_val=0.65) CustomSliderWidget(min=0, max=2, display_range=True, label="j", default_val=0.25) CustomSliderWidget(min=0, max=2, display_range=True, label="k", default_val=0.55) CustomSliderWidget(min=0, max=3.14, display_range=True, label="Theta", default_val=1.25) ``` Here is a collapsable frame, a vertical stack, and then instead of the horizontal stacks with combinations of labels and controls seen in the `UI_Window` tutorial, there is a list of custom controls. In fact, scrolling up and down the class to look at the other build functions reveals quite a few custom controls. These custom controls are what gives the user interface a variety of controls, maintains a consistent look and feel, and gives them all the same functionality to restore a default value. Taking a closer at constructor for each `CustomSliderWidget` above reveals that each sets a default value for its respective widget. ### Step 5.4: Identify Custom Widgets In the folder structure are a few files that look like they contain custom widgets, namely: - `custom_base_widget.py` - `custom_bool_widget.py` - `custom_color_widget.py` - `custom_combobox_widget.py` - `custom_multifield_widget.py` - `custom_path_widget.py` - `custom_radio_widget.py` - `custom_slider_widget.py` ### Step 5.5: Recognize Hierarchical Class Structure `custom_base_widget.py` contains `CustomBaseWidget` which many of the other widgets `inherit` from. For example, open one of the widget modules such as `custom_slider_widget.py` and take a look at its class declaration: ```Python class CustomSliderWidget(CustomBaseWidget): ``` There, in parentheses is `CustomBaseWidget`, confirming that this is a hierarchical class structure with the specific widgets inheriting from `CustomBaseWidget`. For those unfamiliar with inheritance, a quick explanation in the next section is in order. ## Step 6: Inheritance In Python (and other programming languages) it is possible to group classes together if they have some things in common but are different in other ways and this is called inheritance. With inheritance, a base class is made containing everything in common, and sub-classes are made that contain the specific elements of each object. 2D Shapes are a classic example. <p align="center"> <img src="Images/Shape.svg" width=35%> <p> In this case all shapes have a background color, you can get their area, and you can get their perimeter. Circles, however have a radius where rectangles have a length and a width. When you use inheritance, the common code can be in a single location in the base class where the sub-classes contain the specific code. The next step is to look at `CustomBaseWidget` to see what all of the custom widgets have in common. Either navigate to `custom_base_widget.py` or ctrl+click on `CustomBaseWidget` in any of the sub-classes. Inheritance is one element of object-oriented programming (OOP). To learn more about OOP, check out [this video](https://www.youtube.com/watch?v=pTB0EiLXUC8). To learn more about inheritance syntax in Python, check out [this article](https://www.w3schools.com/Python/Python_inheritance.asp). ## Step 7: Explore `custom_base_widget.py` This section explores the code in `custom_base_widget.py` ### Step 7.1: Identify Code Patterns The developer who wrote this extension has a consistent style, so you should see a lot in common between this class and `JuliaModelerWindow` class. It starts with `__init__()` and `destroy()` functions and further down has a few `_build` functions: `_build_head()`, `_build_body()`, `_build_tail()`, and `_build_fn()`. The `_build_fn()` function is called from the constructor and in turn calls each of the other build functions. ### Step 7.2: Characterize Custom Widget Layout From this it can be determined that each of the custom widgets has a head, body and tail and if we look at the controls in the UI this makes sense as illustrated below: <p align="center"> <img src="Images/HeadBodyTail.png" width=35%> <p> This image shows a vertical stack containing 5 widgets. Each widget is a collection of smaller controls. The first highlighted column contains the head of each widget, the second contains their content and the third holds each tail. This tutorial will now look at how the head, content, and tail are created in turn. ### Step 7.3: Inspect `_build_head()` `_build_head()` is as follows: ```Python def _build_head(self): """Build the left-most piece of the widget line (label in this case)""" ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) ``` It has a single label that displays the text passed into the widget's constructor. This makes sense when looking at the UI, each control has a label and they are all aligned. ### Step 7.4: Inspect `_build_body()` `_build_body()` is as follows: ```Python def _build_body(self): """Build the custom part of the widget. Most custom widgets will override this method, as it is where the meat of the custom widget is. """ ui.Spacer() ``` In the comments it says that most widgets will override this method. This has to do with the inheritance mentioned before. Just like with `GetArea()` in the shape class, each shape has an area, but that area is calculated differently. In this situation, the function is placed in the base class but each sub-class implements that function in its own way. In this case `_build_body()` is essentially empty, and if you look at each custom widget sub-class, they each have their own `_build_body()` function that runs in place of the one in `CustomBaseWidget`. ### Step 7.5: Inspect `_build_tail()` Finally, the `_build_tail()` function contains the following code: ```Python def _build_tail(self): """Build the right-most piece of the widget line. In this case, we have a Revert Arrow button at the end of each widget line. """ with ui.HStack(width=0): ui.Spacer(width=5) with ui.VStack(height=0): ui.Spacer(height=3) self.revert_img = ui.Image( name="revert_arrow", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=13, enabled=False, ) ui.Spacer(width=5) # call back for revert_img click, to restore the default value self.revert_img.set_mouse_pressed_fn( lambda x, y, b, m: self._restore_default()) ``` This function draws the reverse arrow that lets a user revert a control to a default value and is the same for every custom control. In this way the author of this extension has ensured that all of the custom widgets are well aligned, have a consistent look and feel and don't have the same code repeated in each class. They each implemented their own body, but other than that are the same. The next section will show how the widget body is implmeneted in the `CustomSliderWidget` class. ## Step 8: Explore `custom_slider_widget.py` To view the `CustomSliderWidget` class open `custom_slider_widget.py` and take a look at the `build_body()` function which contains the following code: ```Python def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls( height=FIELD_HEIGHT, min=self.__min, max=self.__max, name="attr_slider" ) if self.__display_range: self._build_display_range() with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=2) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() ``` This function is significantly longer than others in this tutorial and could be overwhelming at first glance. This is the perfect situation to take advantage of code folding. If you hover over the blank column between the line numbers and the code window inside visual studio, downward carrats will appear next to code blocks. Click on the carrats next to the two vertical stacks to collapse those blocks of code and make the function easier to navigate. <p align="center"> <img src="Images/FoldedCode.png" width=75%> <p> Now it's clear that this function creates an outer horizontal stack which contains two vertical stacks. If you dig deeper you will find that the first vertical stack contains a float slider with an image background. In order to learn how to create an image background like this, check out the [UI Gradient Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_gradient_window/tutorial/tutorial.md). The second vertical stack contains a number field which displays the number set by the float slider. If you take a look at the other custom widgets, you will see that each of them has its own `_build_body` function. Exploring these is a great way to get ideas on how to create your own user interface. ## Step 9: Reusing UI code By exploring extensions in this manner, developers can get a head start creating their own user interfaces. This can range from copying and pasting controls from other extensions, to creating new sub-classes on top of existing base classes, to simply reading and understanding the code written by others to learn from it. Hopefully this tutorial has given you a few tips and tricks as you navigate code written by others. ## Conclusion This tutorial has explained how to navigate the file and logical structure of a typical Omniverse extension. In addition it has explained how custom widgets work, even when they are part of a hieararchical inheritance structure.
22,207
Markdown
50.7669
634
0.701806
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_radio_collection.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomRadioCollection"] from typing import List, Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH SPACING = 5 class CustomRadioCollection: """A custom collection of radio buttons. The group_name is on the first line, and each label and radio button are on subsequent lines. This one does not inherit from CustomBaseWidget because it doesn't have the same Head label, and doesn't have a Revert button at the end. """ def __init__(self, group_name: str, labels: List[str], model: ui.AbstractItemModel = None, default_value: bool = True, **kwargs): self.__group_name = group_name self.__labels = labels self.__default_val = default_value self.__images = [] self.__selection_model = ui.SimpleIntModel(default_value) self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__images = [] self.__selection_model = None self.__frame = None @property def model(self) -> Optional[ui.AbstractValueModel]: """The widget's model""" if self.__selection_model: return self.__selection_model @model.setter def model(self, value: int): """The widget's model""" self.__selection_model.set(value) def __getattr__(self, attr): """ Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__frame, attr) def _on_value_changed(self, index: int = 0): """Set states of all radio buttons so only one is On.""" self.__selection_model.set_value(index) for i, img in enumerate(self.__images): img.checked = i == index img.name = "radio_on" if img.checked else "radio_off" def _build_fn(self): """Main meat of the widget. Draw the group_name label, label and radio button for each row, and set up callbacks to keep them updated. """ with ui.VStack(spacing=SPACING): ui.Spacer(height=2) ui.Label(self.__group_name.upper(), name="radio_group_name", width=ATTR_LABEL_WIDTH) for i, label in enumerate(self.__labels): with ui.HStack(): ui.Label(label, name="attribute_name", width=ATTR_LABEL_WIDTH) with ui.HStack(): with ui.VStack(): ui.Spacer(height=2) self.__images.append( ui.Image( name=("radio_on" if self.__default_val == i else "radio_off"), fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) ) ui.Spacer() ui.Spacer(height=2) # Set up a mouse click callback for each radio button image for i in range(len(self.__labels)): self.__images[i].set_mouse_pressed_fn( lambda x, y, b, m, i=i: self._on_value_changed(i))
3,781
Python
35.718446
98
0.556467
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_bool_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomBoolWidget"] import omni.ui as ui from .custom_base_widget import CustomBaseWidget class CustomBoolWidget(CustomBaseWidget): """A custom checkbox or switch widget""" def __init__(self, model: ui.AbstractItemModel = None, default_value: bool = True, **kwargs): self.__default_val = default_value self.__bool_image = None # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__bool_image = None def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.__bool_image.checked = self.__default_val self.__bool_image.name = ( "checked" if self.__bool_image.checked else "unchecked" ) self.revert_img.enabled = False def _on_value_changed(self): """Swap checkbox images and set revert_img to correct state.""" self.__bool_image.checked = not self.__bool_image.checked self.__bool_image.name = ( "checked" if self.__bool_image.checked else "unchecked" ) self.revert_img.enabled = self.__default_val != self.__bool_image.checked def _build_body(self): """Main meat of the widget. Draw the appropriate checkbox image, and set up callback. """ with ui.HStack(): with ui.VStack(): # Just shift the image down slightly (2 px) so it's aligned the way # all the other rows are. ui.Spacer(height=2) self.__bool_image = ui.Image( name="checked" if self.__default_val else "unchecked", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) # Let this spacer take up the rest of the Body space. ui.Spacer() self.__bool_image.set_mouse_pressed_fn( lambda x, y, b, m: self._on_value_changed())
2,626
Python
37.072463
87
0.604722
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_multifield_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomMultifieldWidget"] from typing import List, Optional import omni.ui as ui from .custom_base_widget import CustomBaseWidget class CustomMultifieldWidget(CustomBaseWidget): """A custom multifield widget with a variable number of fields, and customizable sublabels. """ def __init__(self, model: ui.AbstractItemModel = None, sublabels: Optional[List[str]] = None, default_vals: Optional[List[float]] = None, **kwargs): self.__field_labels = sublabels or ["X", "Y", "Z"] self.__default_vals = default_vals or [0.0] * len(self.__field_labels) self.__multifields = [] # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__multifields = [] @property def model(self, index: int = 0) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__multifields: return self.__multifields[index].model @model.setter def model(self, value: ui.AbstractItemModel, index: int = 0): """The widget's model""" self.__multifields[index].model = value def _restore_default(self): """Restore the default values.""" if self.revert_img.enabled: for i in range(len(self.__multifields)): model = self.__multifields[i].model model.as_float = self.__default_vals[i] self.revert_img.enabled = False def _on_value_changed(self, val_model: ui.SimpleFloatModel, index: int): """Set revert_img to correct state.""" val = val_model.as_float self.revert_img.enabled = self.__default_vals[index] != val def _build_body(self): """Main meat of the widget. Draw the multiple Fields with their respective labels, and set up callbacks to keep them updated. """ with ui.HStack(): for i, (label, val) in enumerate(zip(self.__field_labels, self.__default_vals)): with ui.HStack(spacing=3): ui.Label(label, name="multi_attr_label", width=0) model = ui.SimpleFloatModel(val) # TODO: Hopefully fix height after Field padding bug is merged! self.__multifields.append( ui.FloatField(model=model, name="multi_attr_field")) if i < len(self.__default_vals) - 1: # Only put space between fields and not after the last one ui.Spacer(width=15) for i, f in enumerate(self.__multifields): f.model.add_value_changed_fn(lambda v: self._on_value_changed(v, i))
3,255
Python
39.19753
92
0.614132
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_color_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomColorWidget"] from ctypes import Union import re from typing import List, Optional import omni.ui as ui from .custom_base_widget import CustomBaseWidget from .style import BLOCK_HEIGHT COLOR_PICKER_WIDTH = ui.Percent(35) FIELD_WIDTH = ui.Percent(65) COLOR_WIDGET_NAME = "color_block" SPACING = 4 class CustomColorWidget(CustomBaseWidget): """The compound widget for color input. The color picker widget model converts its 3 RGB values into a comma-separated string, to display in the StringField. And vice-versa. """ def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = [a for a in args if a is not None] self.__strfield: Optional[ui.StringField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__color_sub = None self.__strfield_sub = None # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__strfield = None self.__colorpicker = None self.__color_sub = None self.__strfield_sub = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__colorpicker: return self.__colorpicker.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__colorpicker.model = value @staticmethod def simplify_str(val): s = str(round(val, 3)) s_clean = re.sub(r'0*$', '', s) # clean trailing 0's s_clean = re.sub(r'[.]$', '', s_clean) # clean trailing . s_clean = re.sub(r'^0', '', s_clean) # clean leading 0 return s_clean def set_color_stringfield(self, item_model: ui.AbstractItemModel, children: List[ui.AbstractItem]): """Take the colorpicker model that has 3 child RGB values, convert them to a comma-separated string, and set the StringField value to that string. Args: item_model: Colorpicker model children: child Items of the colorpicker """ field_str = ", ".join([self.simplify_str(item_model.get_item_value_model(c).as_float) for c in children]) self.__strfield.model.set_value(field_str) if self.revert_img: self._on_value_changed() def set_color_widget(self, str_model: ui.SimpleStringModel, children: List[ui.AbstractItem]): """Parse the new StringField value and set the ui.ColorWidget component items to the new values. Args: str_model: SimpleStringModel for the StringField children: Child Items of the ui.ColorWidget's model """ joined_str = str_model.get_value_as_string() for model, comp_str in zip(children, joined_str.split(",")): comp_str_clean = comp_str.strip() try: self.__colorpicker.model.get_item_value_model(model).as_float = float(comp_str_clean) except ValueError: # Usually happens in the middle of typing pass def _on_value_changed(self, *args): """Set revert_img to correct state.""" default_str = ", ".join([self.simplify_str(val) for val in self.__defaults]) cur_str = self.__strfield.model.as_string self.revert_img.enabled = default_str != cur_str def _restore_default(self): """Restore the default values.""" if self.revert_img.enabled: field_str = ", ".join([self.simplify_str(val) for val in self.__defaults]) self.__strfield.model.set_value(field_str) self.revert_img.enabled = False def _build_body(self): """Main meat of the widget. Draw the colorpicker, stringfield, and set up callbacks to keep them updated. """ with ui.HStack(spacing=SPACING): # The construction of the widget depends on what the user provided, # defaults or a model if self.existing_model: # the user provided a model self.__colorpicker = ui.ColorWidget( self.existing_model, width=COLOR_PICKER_WIDTH, height=BLOCK_HEIGHT, name=COLOR_WIDGET_NAME ) color_model = self.existing_model else: # the user provided a list of default values self.__colorpicker = ui.ColorWidget( *self.__defaults, width=COLOR_PICKER_WIDTH, height=BLOCK_HEIGHT, name=COLOR_WIDGET_NAME ) color_model = self.__colorpicker.model self.__strfield = ui.StringField(width=FIELD_WIDTH, name="attribute_color") self.__color_sub = self.__colorpicker.model.subscribe_item_changed_fn( lambda m, _, children=color_model.get_item_children(): self.set_color_stringfield(m, children)) self.__strfield_sub = self.__strfield.model.subscribe_value_changed_fn( lambda m, children=color_model.get_item_children(): self.set_color_widget(m, children)) # show data at the start self.set_color_stringfield(self.__colorpicker.model, children=color_model.get_item_children())
6,076
Python
39.245033
101
0.59842
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_path_button.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomPathButtonWidget"] from typing import Callable, Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH, BLOCK_HEIGHT class CustomPathButtonWidget: """A compound widget for holding a path in a StringField, and a button that can perform an action. TODO: Get text ellision working in the path field, to start with "..." """ def __init__(self, label: str, path: str, btn_label: str, btn_callback: Callable): self.__attr_label = label self.__pathfield: ui.StringField = None self.__path = path self.__btn_label = btn_label self.__btn = None self.__callback = btn_callback self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__pathfield = None self.__btn = None self.__callback = None self.__frame = None @property def model(self) -> Optional[ui.AbstractItem]: """The widget's model""" if self.__pathfield: return self.__pathfield.model @model.setter def model(self, value: ui.AbstractItem): """The widget's model""" self.__pathfield.model = value def get_path(self): return self.model.as_string def _build_fn(self): """Draw all of the widget parts and set up callbacks.""" with ui.HStack(): ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) self.__pathfield = ui.StringField( name="path_field", height=BLOCK_HEIGHT, width=ui.Fraction(2), ) # TODO: Add clippingType=ELLIPSIS_LEFT for long paths self.__pathfield.model.set_value(self.__path) self.__btn = ui.Button( self.__btn_label, name="tool_button", height=BLOCK_HEIGHT, width=ui.Fraction(1), clicked_fn=lambda path=self.get_path(): self.__callback(path), )
2,599
Python
30.707317
78
0.576376
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_slider_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomSliderWidget"] from typing import Optional import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl from .custom_base_widget import CustomBaseWidget NUM_FIELD_WIDTH = 50 SLIDER_WIDTH = ui.Percent(100) FIELD_HEIGHT = 22 # TODO: Once Field padding is fixed, this should be 18 SPACING = 4 TEXTURE_NAME = "slider_bg_texture" class CustomSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=1.0, default_val=0.0, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls( height=FIELD_HEIGHT, min=self.__min, max=self.__max, name="attr_slider" ) if self.__display_range: self._build_display_range() with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=2) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed)
6,797
Python
40.451219
105
0.529351
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/window.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["JuliaModelerWindow"] import omni.ui as ui from omni.kit.window.popup_dialog import MessageDialog from .custom_bool_widget import CustomBoolWidget from .custom_color_widget import CustomColorWidget from .custom_combobox_widget import CustomComboboxWidget from .custom_multifield_widget import CustomMultifieldWidget from .custom_path_button import CustomPathButtonWidget from .custom_radio_collection import CustomRadioCollection from .custom_slider_widget import CustomSliderWidget from .style import julia_modeler_style, ATTR_LABEL_WIDTH SPACING = 5 class JuliaModelerWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = ATTR_LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = julia_modeler_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) def destroy(self): # Destroys all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def on_export_btn_click(self, path): """Sample callback that is used when the Export button is pressed.""" dialog = MessageDialog( title="Button Pressed Dialog", message=f"Export Button was clicked with path inside: {path}", disable_cancel_button=True, ok_handler=lambda dialog: dialog.hide() ) dialog.show() def _build_title(self): with ui.VStack(): ui.Spacer(height=10) ui.Label("JULIA QUATERNION MODELER - 1.0", name="window_title") ui.Spacer(height=10) def _build_collapsable_header(self, collapsed, title): """Build a custom title of CollapsableFrame""" with ui.VStack(): ui.Spacer(height=8) with ui.HStack(): ui.Label(title, name="collapsable_name") if collapsed: image_name = "collapsable_opened" else: image_name = "collapsable_closed" ui.Image(name=image_name, width=10, height=10) ui.Spacer(height=8) ui.Line(style_type_name_override="HeaderLine") def _build_calculations(self): """Build the widgets of the "Calculations" group""" with ui.CollapsableFrame("Calculations".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=0, max=20, num_type="int", label="Precision", default_val=6) CustomSliderWidget(min=0, max=20, num_type="int", label="Iterations", default_val=10) def _build_parameters(self): """Build the widgets of the "Parameters" group""" with ui.CollapsableFrame("Parameters".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=-2, max=2, display_range=True, label="Iterations", default_val=0.75) CustomSliderWidget(min=0, max=2, display_range=True, label="i", default_val=0.65) CustomSliderWidget(min=0, max=2, display_range=True, label="j", default_val=0.25) CustomSliderWidget(min=0, max=2, display_range=True, label="k", default_val=0.55) CustomSliderWidget(min=0, max=3.14, display_range=True, label="Theta", default_val=1.25) def _build_light_1(self): """Build the widgets of the "Light 1" group""" with ui.CollapsableFrame("Light 1".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomMultifieldWidget( label="Orientation", default_vals=[0.0, 0.0, 0.0] ) CustomSliderWidget(min=0, max=1.75, label="Intensity", default_val=1.75) CustomColorWidget(1.0, 0.875, 0.5, label="Color") CustomBoolWidget(label="Shadow", default_value=True) CustomSliderWidget(min=0, max=2, label="Shadow Softness", default_val=.1) def _build_scene(self): """Build the widgets of the "Scene" group""" with ui.CollapsableFrame("Scene".upper(), name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): ui.Spacer(height=6) CustomSliderWidget(min=0, max=160, display_range=True, num_type="int", label="Field of View", default_val=60) CustomMultifieldWidget( label="Orientation", default_vals=[0.0, 0.0, 0.0] ) CustomSliderWidget(min=0, max=2, label="Camera Distance", default_val=.1) CustomBoolWidget(label="Antialias", default_value=False) CustomBoolWidget(label="Ambient Occlusion", default_value=True) CustomMultifieldWidget( label="Ambient Distance", sublabels=["Min", "Max"], default_vals=[0.0, 200.0] ) CustomComboboxWidget(label="Ambient Falloff", options=["Linear", "Quadratic", "Cubic"]) CustomColorWidget(.6, 0.62, 0.9, label="Background Color") CustomRadioCollection("Render Method", labels=["Path Traced", "Volumetric"], default_value=1) CustomPathButtonWidget( label="Export Path", path=".../export/mesh1.usd", btn_label="Export", btn_callback=self.on_export_btn_click, ) ui.Spacer(height=10) def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(name="window_bg", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.VStack(height=0): self._build_title() self._build_calculations() self._build_parameters() self._build_light_1() self._build_scene()
7,703
Python
37.909091
100
0.564975
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/docs/CHANGELOG.md
# Changelog ## [1.0.1] - 2022-06-23 ### Added - Readme ## [1.0.0] - 2022-06-22 ### Added - Initial window
108
Markdown
9.899999
23
0.555556
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/docs/README.md
# Julia Modeler (omni.example.ui_julia_modeler) ![](../data/preview.png) ## Overview In this example, we create a window which uses custom widgets that follow a similar pattern. The window is built using `omni.ui`. It contains the best practices of how to build customized widgets and reuse them without duplicating the code. The structure is very similar to that of `omni.example.ui_window`, so we won't duplicate all of that same documentation here. ## [Tutorial](../tutorial/tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. [Get started with the tutorial.](../tutorial/tutorial.md) ## Usage This is just a UI demo. You can interact with the various controls, but they have not additional effect in the Application. ## Explanations ### Custom Widgets Because this design had a pattern for most of its attribute rows, like: `<head><body><tail>` where "head" is always the same kind of attribute label, the "body" is the customized part of the widget, and then the "tail" is either a revert arrow button, or empty space, we decided it would be useful to make a base class for all of the similar custom widgets, to reduce code duplication, and to make sure that the 3 parts always line up in the UI. ![](../data/similar_widget_structure.png) By structuring the base class with 3 main methods for building the 3 sections, child classes can focus on just building the "body" section, by implementing `_build_body()`. These are the 3 main methods in the base class, and the `_build_fn()` method that puts them all together: ```python def _build_head(self): # The main attribute label ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) def _build_body(self): # Most custom widgets will override this method, # as it is where the meat of the custom widget is ui.Spacer() def _build_tail(self): # In this case, we have a Revert Arrow button # at the end of each widget line with ui.HStack(width=0): ui.Spacer(width=5) with ui.VStack(height=0): ui.Spacer(height=3) self.revert_img = ui.Image( name="revert_arrow", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=13, enabled=False, ) ui.Spacer(width=5) # add call back to revert_img click to restore the default value self.revert_img.set_mouse_pressed_fn( lambda x, y, b, m: self._restore_default()) def _build_fn(self): # Put all the parts together with ui.HStack(): self._build_head() self._build_body() self._build_tail() ``` and this is an example of implementing `_build_body()` in a child class: ```python def _build_body(self): with ui.HStack(): with ui.VStack(): ui.Spacer(height=2) self.__bool_image = ui.Image( name="checked" if self.__default_val else "unchecked", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=16, width=16, checked=self.__default_val ) ui.Spacer() self.__bool_image.set_mouse_pressed_fn( lambda x, y, b, m: self._on_value_changed()) ``` #### Value Changed "Revert" Widget In this example, almost every attribute row has a widget which indicates whether the value has been changed or not. By default, the revert arrow button is disabled and gray, and when the value has been changed it turns light blue and is enabled. Most of the functionality for this widget lives in the CustomBaseWidget class. The base class also calls a _restore_value method that needs to be implemented in the child class. Each child class can handle attribute values differently, so the logic of how to revert back needs to live at that level. The child class also takes care of enabling the revert button when the value has changed, turning it blue. ![](../data/revert_enabled.png) ![](../data/revert_disabled.png) #### Custom Int/Float Slider ![](../data/custom_float_slider.png) At a high level, this custom widget is just the combination of a `ui.FloatSlider` or `ui.IntSlider` and a `ui.FloatField` or `ui.IntField`. But there are a few more aspects that make this widget interesting: - The background of the slider has a diagonal lines texture. To accomplish that, a tiled image of that texture is placed behind the rest of the widget using a ZStack. A Slider is placed over top, almost completely transparent. The background color is transparent and the text is transparent. The foreground color, called the `secondary_color` is light gray with some transparency to let the texture show through. - Immediately below the slider is some optional tiny text that denotes the range of the slider. If both min and max are positive or both are negative, only the endpoints are shown. If the min is negative, and the max is positive, however, the 0 point is also added in between, based on where it would be. That tiny text is displayed by using `display_range=True` when creating a `CustomSliderWidget`. - There was a bug with sliders and fields around how the padding worked. It is fixed and will be available in the next version of Kit, but until then, there was a workaround to make things look right: a ui.Rectangle with the desired border is placed behind a ui.FloatField. The Field has a transparent background so all that shows up from it is the text. That way the Slider and Field can line up nicely and the text in the Field can be the same size as with other widgets in the UI. #### Customized ColorWidget The customized ColorWidget wraps a `ui.ColorWidget` widget and a `ui.StringField` widget in a child class of CustomBaseWidget. ![](../data/custom_color_widget.png) The colorpicker widget is a normal `ui.ColorWidget`, but the text part is really just a `ui.StringField` with comma-separated values, rather than a `ui.MultiFloatDragField` with separate R, G, and B values. So it wasn't as easy to just use the same model for both. Instead, to make them connect in both directions, we set up a callback for each widget, so that each would update the other one on any changes: ```python self.__color_sub = self.__colorpicker.model.subscribe_item_changed_fn( lambda m, _, children=color_model.get_item_children(): self.set_color_stringfield(m, children)) self.__strfield_sub = self.__strfield.model.subscribe_value_changed_fn( lambda m, children=color_model.get_item_children(): self.set_color_widget(m, children)) ``` #### Custom Path & Button Widget The Custom Path & Button widget doesn't follow quite the same pattern as most of the others, because it doesn't have a Revert button at the end, and the Field and Button take different proportions of the space. ![](../data/custom_path_button.png) In the widget's `_build_fn()` method, we draw the entire row all in one place. There's the typical label on the left, a StringField in the middle, and a Button at the end: ```python with ui.HStack(): ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) self.__pathfield = ui.StringField( name="path_field", height=BLOCK_HEIGHT, width=ui.Fraction(2), ) self.__pathfield.model.set_value(self.__path) self.__btn = ui.Button( self.__btn_label, name="tool_button", height=BLOCK_HEIGHT, width=ui.Fraction(1), clicked_fn=lambda path=self.get_path(): self.__callback(path), ) ``` All of those strings for labels and paths are customizable when creating the Widget. In window.py, this is how we instantiate the Export-style version: _(Note: In a real situation we would use the entire path, but we added the "..." ellipsis to show an ideal way to clip the text in the future.)_ ```python CustomPathButtonWidget( label="Export Path", path=".../export/mesh1.usd", btn_label="Export", btn_callback=self.on_export_btn_click, ) ``` And we show a sample callback hooked up to the button -- `self.on_export_btn_click`, which for this example, just pops up a MessageDialog telling the user what the path was that is in the Field: ```python def on_export_btn_click(self, path): """Sample callback that is used when the Export button is pressed.""" dialog = MessageDialog( title="Button Pressed Dialog", message=f"Export Button was clicked with path inside: {path}", disable_cancel_button=True, ok_handler=lambda dialog: dialog.hide() ) dialog.show() ``` ### Style Although the style can be applied to any widget, we recommend keeping the style dictionary in one location, such as `styles.py`. One comment on the organization of the styles. You may notice named constants that seem redundant, that could be consolidated, such as multiple font type sizes that are all `14`. ```python fl.window_title_font_size = 18 fl.field_text_font_size = 14 fl.main_label_font_size = 14 fl.multi_attr_label_font_size = 14 fl.radio_group_font_size = 14 fl.collapsable_header_font_size = 13 fl.range_text_size = 10 ``` While you definitely _could_ combine all of those into a single constant, it can be useful to break them out by type of label/text, so that if you later decide that you want just the Main Labels to be `15` instead of `14`, you can adjust just the one constant, without having to break out all of the other types of text that were using the same font size by coincidence. This same organization applies equally well to color assignments also. ### Window It's handy to derive a custom window from the class `ui.Window`. The UI can be defined right in `__init__`, so it's created immediately or it can be defined in a `set_build_fn` callback and it will be created when the window is visible. The later one is used in this example. ```python class PropertyWindowExample(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = julia_modeler_style # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) ``` Inside the `self._build_fn`, we use the customized widgets to match the design layout for the window. ### Extension When the extension starts up, we register a new menu item that controls the window and shows the window. A very important part is using `ui.Workspace.set_show_window_fn` to register the window in `omni.ui`. It will help to save and load the layout of Kit. ```python ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, partial(self.show_window, None)) ``` When the extension shuts down, we remove the menu item and deregister the window callback.
11,458
Markdown
49.480176
486
0.686245
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/tutorial/tutorial.md
# UI Window Tutorial In this tutorial, you learn how to create an Omniverse Extension that has a window and user interface (UI) elements inside that window. ## Learning Objectives * Create a window. * Add it to the **Window** menu. * Add various control widgets into different collapsable group with proper layout and alignment. ## Step 1: Clone the Repository Clone the `ui-window-tutorial-start` branch of the `kit-extension-sample-ui-window` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/tree/ui-window-tutorial-start): ```shell git clone -b ui-window-tutorial-start https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window.git ``` This repository contains the starting code you use in this tutorial. ## Step 2: Add the Extension to Omniverse Code In order to use and test your Extension, you need to add it to Omniverse Code. ### Step 2.1: Navigate to the Extensions List In Omniverse Code, navigate to the *Extensions* panel: ![Click the Extensions panel](Images/extensions_panel.png) Here, you see a list of Omniverse Extensions that you can activate and use in Code. > **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**: > > ![Show the Extensions panel](Images/window_extensions.png) ### Step 2.2: Navigate to the *Extension Search Paths* Click the **gear** icon to open *Extension Search Paths*: ![Click the gear icon](Images/extension_search_paths.png) In this panel, you can add your custom Extension to the Extensions list. ### Step 2.3: Create a New Search Path Create a new search path to the `exts` directory of your Extension by clicking the green **plus** icon and double-clicking on the **path** field: ![New search path](Images/new_search_path_ui-window.png) When you submit your new search path, you should be able to find your extension in the *Extensions* list. Search for "omni.example.ui_" to filter down the list. Activate the "OMNI.UI WINDOW EXAMPLE" Extension: ![Reticle extensions list](Images/window_extensions_list_ui-window.png) Now that your Extension is added and enabled, you can make changes to the code and see them in your Application. ## Step 3: Create A Window In this section, you create an empty window that you can hide and show and is integrated into the **Application** menu. This window incorporates a few best practices so that it's well-connected with Omniverse and feels like a natural part of the application it's being used from. You do all of this in the `extension.py` file. ### Step 3.1: Support Hide/Show Windows can be hidden and shown from outside the window code that you write. If you would like Omniverse to be able to show a window after it has been hidden, you must register a callback function to run when the window visibility changes. To do this, open the `extension.py` file, go to the `on_startup()` definition, and edit the function to match the following code: ```python def on_startup(self): # The ability to show the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Add a Menu Item for the window # Show the window through the 'set_show_window_fn' you wired up above # It will call `self.show_window` ``` The added line registers the `self.show_window` callback to be run whenever the visibility of your extension is changed. The `pass` line of code is deleted because it is no longer necessary. It was only included because all code had been removed from that function. ### Step 3.2: Add a Menu Item It is helpful to add extensions to the application menu so that if a user closes a window they can reopen it. This is done by adding the following code to `on_startup()`: ```python def on_startup(self): # The ability to show the window if the system requires it. # You use it in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Add a Menu Item for the window editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window through the 'set_show_window_fn' you wired up above # It will call `self.show_window` ``` The first added line grabs a reference to the application menu. The second new line adds a new menu item where `MENU_PATH` determines where the menu item will appear in the menu system, and `self.show_window` designates the function to run when the user toggles the window visibility by clicking on the menu item. ### Step 3.3: Show the Window To finish with `on_startup()`, add the following: ```python def on_startup(self): # The ability to show the window if the system requires it. # You use it in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Add a Menu Item for the window editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window through the 'set_show_window_fn' you wired up above # It will call `self.show_window` ui.Workspace.show_window(ExampleWindowExtension.WINDOW_NAME) ``` This calls `show_window()` through the registration you set up earlier. ### Step 3.4: Call the Window Constructor Finally, in the `extension.py` file, scroll down to the `show_window` method which is currently the code below: ```python def show_window(self, menu, value): #value is true if the window should be shown if value: #call our custom window constructor #Handles the change in visibility of the window gracefuly self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False ``` Add the following line to this function: ```python def show_window(self, menu, value): #value is true if the window should be shown if value: #call our custom window constructor self._window = ExampleWindow(ExampleWindowExtension.WINDOW_NAME, width=300, height=365) #Handles the change in visibility of the window gracefuly self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False ``` This calls the constructor of the custom window class in `window.py` and assigns it to the extension `self._window`. ## Step 4: Custom Window The custom window class can be found in `window.py`. It is possible to simply build all of your user interface in `extension.py`, but this is only a good practice for very simple extensions. More complex extensions should be broken into managable pieces. It is a good practice to put your user interface into its own file. Note that `window.py` contains a class that inherits from `ui.Window`. Change the `__init__()` function to include the line added below: ```python def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) ``` This line registers the `self._build_fn` callback to run when the window is visible, which is where you will build the user interface for this tutorial. ### Step 4.1: Create a Scrolling Frame Now scroll down to `_build_fn` at the bottom of `window.py` and edit it to match the following: ```python def _build_fn(self): # The method that is called to build all the UI once the window is visible. with ui.ScrollingFrame(): pass ``` The `with` statement begins a context block and you are creating a `ScrollingFrame`. What this means is that everything intended below the `with` will be a child of the `ScrollingFrame`. A [ScrollingFrame](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.ScrollingFrame) is an area within your user interface with a scroll bar. By creating one first, if the user makes the window small, a scrollbar will appear, allowing the user to still access all content in the user interface. ### Step 4.2: Create a Vertical Stack Next edit the `_build_fn()` definition by replacing the `pass` line with the following context block and put a `pass` keyword inside the new context block as shown below: ```python def _build_fn(self): # The method that is called to build all the UI once the window is visible. with ui.ScrollingFrame(): with ui.VStack(height=0): pass ``` Here you added a `VStack`, which stacks its children vertically. The first item is at the top and each subsequent item is placed below the previous item as demonstrated in the schematic below: <p align="center"> <img src="Images/VerticalStack.png" width=25%> <p> This will be used to organize the controls into rows. ### Step 4.3: Break the Construction into Chunks While it would be possible to create the entire user interface in this tutorial directly in `_build_fn()`, as a user interface gets large it can be unwieldly to have it entirely within one function. In order to demonstrate best practices, this tutorial builds each item in the vertical stack above in its own function. Go ahead and edit your code to match the block below: ```python def _build_fn(self): # The method that is called to build all the UI once the window is visible. with ui.ScrollingFrame(): with ui.VStack(height=0): self._build_calculations() self._build_parameters() self._build_light_1() ``` Each of these functions: `_build_calculations()`, `_build_parameters()`, and `_build_light_1()` builds an item in the vertical stack. Each of those items is a group of well-organized controls made with a consistent look and layout. If you save `window.py` it will `hot reload`, but will not look any different from before. That is because both `ScrollingFrame` and `VStack` are layout controls. This means that they are meant to organize content within them, not be displayed themselves. A `ScrollingFrame` can show a scroll bar, but only if it has content to be scrolled. ## Step 5: Build Calculations The first group you will create is the `Calculations group`. In this section `CollapsableFrame`, `HStack`, `Label`, and `IntSlider` will be introduced. Scroll up to the `_build_calculations` which looks like the following block of code: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group # A VStack is a vertical stack and aligns widgets vertically one after the other # An HStack is a horizontal stack and aligns widgets horizontally one after the other # A label displays text # An IntSlider lets a user choose an integer by sliding a bar back and forth # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider pass ``` In the remaining sub-sections you will fill this in and create your first group of controls. ### Step 5.1: Create a Collapsable Frame Edit `_build_calculations()` to match the following: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other # An HStack is a horizontal stack and aligns widgets horizontally one after the other # A label displays text # An IntSlider lets a user choose an integer by sliding a bar back and forth # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider pass ``` A `CollapsableFrame` is a control that you can expand and contract by clicking on its header, which will show or hide its content. The first argument passed into its constructor is the title string. The second argument is its name and the final argument is a reference to the function that builds its header. You can write this function to give the header whatever look you want. At this point if you save `window.py` and then test in Omniverse Code you will see a change in your extension's window. The `CollapsableFrame` will be visible and should look like this: <p align="center"> <img src="Images/CollapsableFrame.png" width=25%> <p> Next we will add content inside this `CollapsableFrame`. ### Step 5.2: Create a Horizontal Stack The next three steps demonstrate a very common user interface pattern, which is to have titled controls that are well aligned. A common mistake is to create a user interface that looks like this: <p align="center"> <img src="Images/BadUI.png" width=25%> <p> The controls have description labels, but they have inconsistent positions and alignments. The following is a better design: <p align="center"> <img src="Images/GoodUI.png" width=25%> <p> Notice that the description labels are all to the left of their respective controls, the labels are aligned, and the controls have a consistent width. This will be demonstrated twice within a `VStack` in this section. Add a `VStack` and then to create this common description-control layout, add an `HStack` to the user interface as demonstrated in the following code block: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text # An IntSlider allows a user choose an integer by sliding a bar back and forth pass # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider pass ``` An `HStack` is very similar to a `VStack` except that it stacks its content horizontally rather than vertically. Note that a `pass` you added to the `VStack` simply so that the code will run until you add more controls to this context. ### Step 5.3: Create a Label Next add a `Label` to the `HStack`: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text ui.Label("Precision", name="attribute_name", width=self.label_width) # An IntSlider allows a user choose an integer by sliding a bar back and forth # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider ``` If you save the file and go to `Code` you will see that the `Label` appears in the user interface. Take special note of the `width` attribute passed into the constructor. By making all of the labels the same width inside their respective `HStack` controls, the labels and the controls they describe will be aligned. Note also that all contexts now have code, so we have removed the `pass` statements. ### Step 5.4: Create an IntSlider Next add an `IntSlider` as shown below: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text ui.Label("Precision", name="attribute_name", width=self.label_width) # An IntSlider allows a user choose an integer by sliding a bar back and forth ui.IntSlider(name="attribute_int") # Pairing a label with a control is a common UI comb # The label makes the purpose of the control clear # You can set the min and max value on an IntSlider ``` An `IntSlider` is a slider bar that a user can click and drag to control an integer value. If you save your file and go to Omniverse Code, your user interface should now look like this: <p align="center"> <img src="Images/IntSlider.png" width=25%> <p> Go ahead and add a second label/control pair by adding the following code: ```python def _build_calculations(self): # Build the widgets of the "Calculations" group with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): # A VStack is a vertical stack and aligns widgets vertically one after the other with ui.VStack(height=0, spacing=SPACING): # An HStack is a horizontal stack and aligns widgets horizontally one after the other with ui.HStack(): # A label displays text ui.Label("Precision", name="attribute_name", width=self.label_width) # An IntSlider allows a user choose an integer by sliding a bar back and forth ui.IntSlider(name="attribute_int") # Pairing a label with a control is a common UI comb with ui.HStack(): # The label makes the purpose of the control clear ui.Label("Iterations", name="attribute_name", width=self.label_width) # You can set the min and max value on an IntSlider ui.IntSlider(name="attribute_int", min=0, max=5) ``` You have added another `HStack`. This one has a `Label` set to the same width as the first `Label`. This gives the group consistent alignment. `min` and `max` values have also been set on the second `IntSlider` as a demonstration. Save `window.py` and test the extension in Omniverse Code. Expand and collapse the `CollapsableFrame`, resize the window, and change the integer values. It is a good practice to move and resize your extension windows as you code to make sure that the layout looks good no matter how the user resizes it. ## Step 6: Build Parameters In this section you will introduce the `FloatSlider` and demonstrate how to keep the UI consistent across multiple groups. You will be working in the `_build_parameters()` definition which starts as shown below: ```python def _build_parameters(self): # Build the widgets of the "Parameters" group # A Float Slider is similar to an Int Slider # controls a 'float' which is a number with a decimal point (A Real number) # You can set the min and max of a float slider as well # Setting the labels all to the same width gives the UI a nice alignment # A few more examples of float sliders pass ``` Hopefullly this is starting to feel a bit more familiar. You have an empty function that has a `pass` command at the end as a placeholder until you add code to all of its contexts. ### Step 6.1: Create a FloatSlider A `FloatSlider` is very similar to an `IntSlider`. The difference is that it controls a `float` number rather than an `integer`. Match the code below to add one to your extension: ```python def _build_parameters(self): # Build the widgets of the "Parameters" group with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Value", name="attribute_name", width=self.label_width) # A Float Slider is similar to an Int Slider # controls a 'float' which is a number with a decimal point (A Real number) ui.FloatSlider(name="attribute_float") # You can set the min and max of a float slider as well # Setting the labels all to the same width gives the UI a nice alignment # A few more examples of float sliders ``` Here you added a second `CollapsableFrame` with a `VStack` inside of it. This will allow you to add as many label/control pairs as you want to this group. Note that the `Label` has the same width as the label above. Save `window.py` and you should see the following in Omniverse Code: <p align="center"> <img src="Images/SecondGroup.png" width=25%> <p> Note that the description labels and controls in the first and second group are aligned with each other. ### Step 6.2: Make a Consistent UI By using these description control pairs inside of collapsable groups, you can add many controls to a window while maintaining a clean, easy to navigate experience. The following code adds a few more `FloatSlider` controls to the user interface: ```python def _build_parameters(self): # Build the widgets of the "Parameters" group with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Value", name="attribute_name", width=self.label_width) # A Float Slider is similar to an Int Slider # controls a 'float' which is a number with a decimal point (A Real number) ui.FloatSlider(name="attribute_float") with ui.HStack(): ui.Label("i", name="attribute_name", width=self.label_width) # You can set the min and max of a float slider as well ui.FloatSlider(name="attribute_float", min=-1, max=1) # Setting the labels all to the same width gives the UI a nice alignment with ui.HStack(): ui.Label("j", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) # A few more examples of float sliders with ui.HStack(): ui.Label("k", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("Theta", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") ``` Save `window.py` and take a look in Omniverse Code. Your window should look like this: <p align="center"> <img src="Images/SecondGroupComplete.png" width=25%> <p> Note that a few of the sliders have `min` and `max` values and they they are all well-aligned. ## Step 7: Build Light In your final group you will add a few other control types to help give you a feel for what can be done in an extension UI. This will also be well-arranged, even though they are different control types to give the overall extension a consistent look and feel, even though it has a variety of control types. You will be working in `_build_light_1()`, which starts as shown below: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group # A multi float drag field lets you control a group of floats # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel #Feel free to copy this color widget and use it in your own UIs # The custom compound widget #An example of a checkbox pass ``` First you will add a `MultiFloatDragField` to it, then a custom color picker widget and finally a `Checkbox`. ### Step 7.1: Create a MultiFloatDragField Edit `_build_light_1` to match the following: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) # A multi float drag field allows you control a group of floats (Real numbers) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") #Feel free to copy this color widget and use it in your own UIs # The custom compound widget #An example of a checkbox ``` This adds a third `CollapsableFrame` with a `VStack` to hold its controls. Then it adds a label/control pair with a `MultiFloatDragField`. A `MultiFloatDragField` lets a user edit as many values as you put into its constructor, and is commonly used to edit 3-component vectors such as position and rotation. You also added a second label and control pair with a `FloatSlider` similar to the one you added in [section 5.1](#51-create-a-floatslider). ### Step 7.2: Add a Custom Widget Developers can create custom widgets and user interface elements. The color picker added in this section is just such an example. Add it to your extension with the following code: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) # A multi float drag field lets you control a group of floats (Real numbers) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") #Feel free to copy this color widget and use it in your own UIs with ui.HStack(): ui.Label("Color", name="attribute_name", width=self.label_width) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) #An example of a checkbox ``` This widget lets users click and then select a color. Feel free to use this widget in your own applications and feel free to write and share your own widgets. Over time you will have a wide variety of useful widgets and controls for everyone to use in their extensions. ### Step 7.3: Add a Checkbox Finally, edit `_build_light_1()` to match the following: ```python def _build_light_1(self): # Build the widgets of the "Light 1" group with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) # A multi float drag field lets you control a group of floats (Real numbers) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") # Notice what you use the same label width in all of the collapsable frames # This ensures that the entire UI has a consistent feel with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") #Feel free to copy this color widget and use it in your own UIs with ui.HStack(): ui.Label("Color", name="attribute_name", width=self.label_width) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) #An example of a checkbox with ui.HStack(): ui.Label("Shadow", name="attribute_name", width=self.label_width) ui.CheckBox(name="attribute_bool") ``` This adds a label/control pair with a `CheckBox`. A `CheckBox` control allows a user to set a boolean value. Save your `window.py` file and open Omniverse Code. Your user interface should look like this if you collapse the `Parameters` section: <p align="center"> <img src="Images/Complete.png" width=25%> <p> There are three collapsable groups, each with a variety of controls with a variety of settings and yet they are all well-aligned with a consistent look and feel. ## Conclusion In this tutorial you created an extension user interface using coding best practices to integrate it into an Omniverse application. It contains a variety of controls that edit integers, float, colors and more. These controls are well organized so that a user can easily find their way around the window. We look forward to seeing the excellent extensions you come up with and how you can help Omniverse users accomplish things that were hard or even impossible to do before you wrote an extension to help them.
30,589
Markdown
47.478605
565
0.696296
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/style.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["example_window_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) # Pre-defined constants. It's possible to change them runtime. cl.example_window_attribute_bg = cl("#1f2124") cl.example_window_attribute_fg = cl("#0f1115") cl.example_window_hovered = cl("#FFFFFF") cl.example_window_text = cl("#CCCCCC") fl.example_window_attr_hspacing = 10 fl.example_window_attr_spacing = 1 fl.example_window_group_spacing = 2 url.example_window_icon_closed = f"{EXTENSION_FOLDER_PATH}/data/closed.svg" url.example_window_icon_opened = f"{EXTENSION_FOLDER_PATH}/data/opened.svg" # The main style dict example_window_style = { "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_CENTER, "margin_height": fl.example_window_attr_spacing, "margin_width": fl.example_window_attr_hspacing, }, "Label::attribute_name:hovered": {"color": cl.example_window_hovered}, "Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER}, "Slider::attribute_int:hovered": {"color": cl.example_window_hovered}, "Slider": { "background_color": cl.example_window_attribute_bg, "draw_mode": ui.SliderDrawMode.HANDLE, }, "Slider::attribute_float": { "draw_mode": ui.SliderDrawMode.FILLED, "secondary_color": cl.example_window_attribute_fg, }, "Slider::attribute_float:hovered": {"color": cl.example_window_hovered}, "Slider::attribute_vector:hovered": {"color": cl.example_window_hovered}, "Slider::attribute_color:hovered": {"color": cl.example_window_hovered}, "CollapsableFrame::group": {"margin_height": fl.example_window_group_spacing}, "Image::collapsable_opened": {"color": cl.example_window_text, "image_url": url.example_window_icon_opened}, "Image::collapsable_closed": {"color": cl.example_window_text, "image_url": url.example_window_icon_closed}, }
2,530
Python
42.63793
112
0.717787
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/color_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ColorWidget"] from ctypes import Union from typing import List, Optional import omni.ui as ui COLOR_PICKER_WIDTH = 20 SPACING = 4 class ColorWidget: """The compound widget for color input""" def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = args self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.__multifield: Optional[ui.MultiFloatDragField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.__model = None self.__multifield = None self.__colorpicker = None self.__frame = None def __getattr__(self, attr): """ Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__root_frame, attr) @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__multifield: return self.__multifield.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__multifield.model = value self.__colorpicker.model = value def _build_fn(self): with ui.HStack(spacing=SPACING): # The construction of multi field depends on what the user provided, # defaults or a model if self.__model: # the user provided a model self.__multifield = ui.MultiFloatDragField( min=0, max=1, model=self.__model, h_spacing=SPACING, name="attribute_color" ) model = self.__model else: # the user provided a list of default values self.__multifield = ui.MultiFloatDragField( *self.__defaults, min=0, max=1, h_spacing=SPACING, name="attribute_color" ) model = self.__multifield.model self.__colorpicker = ui.ColorWidget(model, width=COLOR_PICKER_WIDTH)
2,600
Python
33.223684
95
0.611538
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/window.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ExampleWindow"] import omni.ui as ui from .style import example_window_style from .color_widget import ColorWidget LABEL_WIDTH = 120 SPACING = 4 class ExampleWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def _build_collapsable_header(self, collapsed, title): """Build a custom title of CollapsableFrame""" with ui.HStack(): ui.Label(title, name="collapsable_name") if collapsed: image_name = "collapsable_opened" else: image_name = "collapsable_closed" ui.Image(name=image_name, width=20, height=20) def _build_calculations(self): """Build the widgets of the "Calculations" group""" with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Precision", name="attribute_name", width=self.label_width) ui.IntSlider(name="attribute_int") with ui.HStack(): ui.Label("Iterations", name="attribute_name", width=self.label_width) ui.IntSlider(name="attribute_int", min=0, max=5) def _build_parameters(self): """Build the widgets of the "Parameters" group""" with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Value", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") with ui.HStack(): ui.Label("i", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("j", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("k", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float", min=-1, max=1) with ui.HStack(): ui.Label("Theta", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") def _build_light_1(self): """Build the widgets of the "Light 1" group""" with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Orientation", name="attribute_name", width=self.label_width) ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector") with ui.HStack(): ui.Label("Intensity", name="attribute_name", width=self.label_width) ui.FloatSlider(name="attribute_float") with ui.HStack(): ui.Label("Color", name="attribute_name", width=self.label_width) # The custom compound widget ColorWidget(0.25, 0.5, 0.75) with ui.HStack(): ui.Label("Shadow", name="attribute_name", width=self.label_width) ui.CheckBox(name="attribute_bool") def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ with ui.ScrollingFrame(): with ui.VStack(height=0): self._build_calculations() self._build_parameters() self._build_light_1()
5,056
Python
39.13492
111
0.584256
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/docs/README.md
# Generic Window (omni.example.ui_window) ![](../data/preview.png) ## Overview This extension provides an end-to-end example and general recommendations on creating a simple window using `omni.ui`. It contains the best practices of building an extension, a menu item, a window itself, a custom widget, and a generic style. ## [Tutorial](../tutorial/tutorial.md) This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. [Get started with the tutorial.](../tutorial/tutorial.md) ## Usage This is just a UI demo. You can interact with the various controls, but they have not additional effect in the Application. ## Explanations ### Extension When the extension starts up, we register a new menu item that controls the window and shows the window. A very important part is using `ui.Workspace.set_show_window_fn` to register the window in `omni.ui`. It will help to save and load the layout of Kit. ``` # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None)) ``` When the extension shuts down, we remove the menu item and deregister the window callback. ### Window It's handy to derive a custom window from the class `ui.Window`. The UI can be defined right in __init__, so it's created immediately. Or it can be defined in a callback and it will be created when the window is visible. ``` class ExampleWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) # Apply the style to all the widgets of this window self.frame.style = example_window_style # Set the function that is called to build widgets when the window is # visible self.frame.set_build_fn(self._build_fn) ``` ### Custom Widget A custom widget can be a class or a function. It's not required to derive anything. It's only necessary to create sub-widgets. ``` class ColorWidget: """The compound widget for color input""" def __init__(self, *args, model=None, **kwargs): self.__defaults: List[Union[float, int]] = args self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.__multifield: Optional[ui.MultiFloatDragField] = None self.__colorpicker: Optional[ui.ColorWidget] = None self.__frame = ui.Frame() with self.__frame: self._build_fn() ``` ### Style Although the style can be applied to any widget, we recommend keeping the style dictionary in one location. There is an exception to this recommendation. It's recommended to use styles directly on the widgets to hide a part of the widget. For example, it's OK to set {"color": cl.transparent} on a slider to hide the text. Or "background_color": cl.transparent to disable background on a field.
3,040
Markdown
35.202381
155
0.715789
NVIDIA-Omniverse/USD-Tutorials-And-Examples/README.md
# USD Tutorials and Examples ## About This project showcases educational material for [Pixar's Universal Scene Description](https://graphics.pixar.com/usd/docs/index.html) (USD). For convenience, the Jupyter notebook from the GTC session is available on Google Colaboratory, which offers an interactive environment from the comfort of your web browser. Colaboratory makes it possible to: * Try code snippets without building or installing USD on your machine * Run the samples on any device * Share code experiments with others Should you prefer to run the notebook on your local machine instead, simply download and execute it after [installing Jupyter](https://jupyter.org). ## Sample Notebook Follow along the tutorial using the sample notebook from the GTC session, or get acquainted with USD using other examples: |Notebook|Google Colab link| |--------|:----------------:| |Introduction to USD|[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/usd_introduction.ipynb)| |Opening USD Stages|[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/opening_stages.ipynb)| |Prims, Attributes and Metadata|[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/prims_attributes_and_metadata.ipynb)| |Hierarchy and Traversal|[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/hierarchy_and_traversal.ipynb)| ## Additional Resources * [Pixar's USD](https://graphics.pixar.com/usd) * [USD at NVIDIA](https://usd.nvidia.com) * [USD training content on _NVIDIA On-Demand_](https://www.nvidia.com/en-us/on-demand/playlist/playList-911c5614-4b7f-4668-b9eb-37f627ac8d17/)
2,140
Markdown
78.296293
263
0.784112
NVIDIA-Omniverse/kit-project-template/repo.toml
######################################################################################################################## # Repo tool base settings ######################################################################################################################## [repo] # Use the Kit Template repo configuration as a base. Only override things specific to the repo. import_configs = [ "${root}/_repo/deps/repo_kit_tools/kit-template/repo.toml", "${root}/_repo/deps/repo_kit_tools/kit-template/repo-external.toml", ] extra_tool_paths = [ "${root}/kit/dev", ] ######################################################################################################################## # Extensions precacher ######################################################################################################################## [repo_precache_exts] # Apps to run and precache apps = [ "${root}/source/apps/my_name.my_app.kit" ]
949
TOML
31.75862
120
0.33509
NVIDIA-Omniverse/kit-project-template/README.md
# *Omniverse Kit* Project Template This project is a template for developing apps and extensions for *Omniverse Kit*. # Important Links - [Omniverse Documentation Site](https://docs.omniverse.nvidia.com/kit/docs/kit-project-template) - [Github Repo for this Project Template](https://github.com/NVIDIA-Omniverse/kit-project-template) - [Extension System](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html) # Getting Started 1. Fork/Clone the Kit Project Template repo [link](https://github.com/NVIDIA-Omniverse/kit-project-template) to a local folder, for example in `C:\projects\kit-project-template` 2. (Optional) Open this cloned repo using Visual Studio Code: `code C:\projects\kit-project-template`. It will likely suggest installing a few extensions to improve python experience. None are required, but they may be helpful. 3. In a CLI terminal (if in VS Code, CTRL + \` or choose Terminal->New Terminal from the menu) run `pull_kit_kernel.bat` (windows) / `pull_kit_kernel.sh` (linux) to pull the *Omniverse Kit Kernel*. `kit` folder link will be created under the main folder in which your project is located. 4. Run the example app that includes example extensions: `source/apps/my_name.my_app.bat` (windows) / `./source/apps/my_name.my_app.sh` (linux) to ensure everything is working. The first start will take a while as it will pull all the extensions from the extension registry and build various caches. Subsequent starts will be much faster. Once finished, you should see a "Kit Base Editor" window and a welcome screen. Feel free to browse through the base application and exit when finished. You are now ready to begin development! ## An Omniverse App If you look inside a `source/apps/my_name.my_app.bat` or any other *Omniverse App*, they all run off of an SDK we call *Omniverse Kit* . The base application for *Omniverse Kit* (`kit.exe`) is the runtime that powers *Apps* build out of extensions. Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **All other functionality is provided by extensions.** To start an app we pass a `kit` file, which is a configuration file with a `kit` extension. It describes which extensions to pull and load, and which settings to apply. One kit file fully describes an app, but you may find value in having several for different methods to run and test your application. Notice that it includes `omni.hello.world` extension; that is an example extension found in this repo. All the other extensions are pulled from the `extension registry` on first startup. More info on building kit files: [doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/creating_kit_apps.html) ### Packaging an App Once you have developed, tested, and documented your app or extension, you will want to publish it. Before publishing the app, we must first assemble all its components into a single deliverable. This step is called "packaging". To package an app run `tools/package.bat` (or `repo package`). The package will be created in the `_build/packages` folder. To use the package, unzip the package that was created by the above step into its own separate folder. Then, run `pull_kit_kernel.bat` inside the new folder once before running the app. ### Version Lock An app `kit` file fully defines all the extensions, but their versions are not `locked`, which is to say that by default the latest versions of a given extension will be used. Also, many extensions have dependencies themselves which cause kit to download and enable other extensions. This said, for the final app it is important that it always gets the same extensions and the same versions on each run. This is meant to provide reliable and reproducible builds. This is called a *version lock* and we have a separate section at the end of `kit` file to lock versions of all extensions and all their dependencies. It is also important to update the version lock section when adding new extensions or updating existing ones. To update version lock the `precache_exts` tool is used. **To update version lock run:** `tools/update_version_lock.bat`. Once you've done this, use your source control methods to commit any changes to a kit file as part of the source necessary to reproduce the build. The packaging tool will verify that version locks exist and will fail if they do not. More info on dependency management: [doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/creating_kit_apps.html#application-dependencies-management) ## An Omniverse Extension This template includes one simple extension: `omni.hello.world`. It is loaded in the example app, but can also be loaded and tested in any other *Omniverse App*. You should feel free to copy or rename this extension to one that you wish to create. Please refer to Omniverse Documentation for more information on developing extensions. ### Using Omniverse Launcher 1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download) 2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*. ### Add a new extension to your *Omniverse App* If you want to add extensions from this repo to your other existing Omniverse App. 1. In the *Omniverse App* open extension manager: *Window* &rarr; *Extensions*. 2. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar. 3. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `source/extensions` subfolder there as another search path: `C:/projects/kit-project-template/source/extensions` ![Extension Manager Window](/images/add-ext-search-path.png) 4. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it. 5. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload. ### Adding a new extension * Now that `source/extensions` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*. * Look at the *Console* window for warnings and errors. It also has a small button to open current log file. * All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`. * Extension name is a folder name in `source/extensions`, in this example: `omni.hello.world`. This is most often the same name as the "Extension ID". * The most important thing that an extension has is its config file: `extension.toml`. You should familiarize yourself with its contents. * In the *Extensions* window, press *Burger* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be by displaying all its dependencies. * Extensions system documentation can be found [here](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html) ### Alternative way to add a new extension To get a better understanding of the extension topology, we recommend following: 1. Run bare `kit.exe` with `source/extensions` folder added as an extensions search path and new extension enabled: ```bash > kit\kit.exe --ext-folder source/extensions --enable omni.hello.world ``` - `--ext-folder [path]` - adds new folder to the search path - `--enable [extension]` - enables an extension on startup. Use `-h` for help: ```bash > kit\kit.exe -h ``` 2. After the *App* starts you should see: * new "My Window" window popup. * extension search paths in *Extensions* window as in the previous section. * extension enabled in the list of extensions. It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!): ```bash > kit\kit.exe --ext-folder source/extensions --enable omni.hello.world --enable omni.kit.window.extensions ``` You should see a menu in the top left. From this UI you can browse and enable more extensions. It is important to note that these enabled extensions are NOT added to your kit file, but instead live in a local "user" file as an addendum. If you want the extension to be a part of your app, you must add its name to the list of dependencies in the `[dependencies]` section. # A third way to add an extension Here is how to add an extension by copying the "hello world" extension as a template: 1. copy `source/extensions/omni.hello.world` to `source/extensions/[new extension id]` 2. rename python module (namespace) in `source/extensions/[new extension id]/omni/hello/world` to `source/extensions/[new extension id]/[new python module]` 3. update `source/extensions/[new extension name]/config/extension.toml`, most importantly specify new python module to load: 4. Optionally, add the `[extension id]` to the `[dependencies]` section of the app's kit file. [[python.module]] name = "[new python module]" # Running Tests To run tests we run a new configuration where only the tested extension (and its dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests: 1. Run: `tools\test_ext.bat omni.hello.world` That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code! 2. Alternatively, in *Extension Manager* (*Window &rarr; Extensions*) find your extension, click on *TESTS* tab, click *Run Test* For more information about testing refer to: [testing doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/testing_exts_python.html). No restart is needed, you should be able to find and enable `[new extension name]` in extension manager. # Sharing extensions To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository). 1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery. 2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes. # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions. # License By using any part of the files in the KIT-PROJECT-TEMPLATE repo you agree to the terms of the NVIDIA Omniverse License Agreement, the most recent version of which is available [here](https://docs.omniverse.nvidia.com/composer/latest/common/NVIDIA_Omniverse_License_Agreement.html).
11,077
Markdown
69.560509
533
0.769613
NVIDIA-Omniverse/kit-project-template/source/package/description.toml
# Description of the application for the Omniverse Launcher name = "My App" # displayed application name shortName = "My App" # displayed application name in smaller card and library view version = "${version}" # version must be semantic kind = "app" # enum of "app", "connector" and "experience" for now latest = true # boolean for if this version is the latest version slug = "my_app" # unique identifier for component, all lower case, persists between versions productArea = "My Company" # displayed before application name in launcher category = "Apps" # category of content channel = "release" # 3 filter types [ "alpha", "beta", "release "] enterpriseStatus = false # Set true if you want this package to show in enterprise launcher # values for filtering content tags = [ "Media & Entertainment", "Manufacturing", "Product Design", "Scene Composition", "Visualization", "Rendering" ] # string array, each line is a new line, keep lines under 256 char and keep lines under 4 description = [ "My App is an application to showcase how to build an Omniverse App. ", "FEATURES:", "- Small and simple.", "- Easy to change." ] # array of links for more info on product [[links]] title = "Release Notes" url = "https://google.com" [[links]] title = "Documentation" url = "https://google.com"
1,398
TOML
34.871794
104
0.67525
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/README.md
# AI Room Generator Extension Sample ![Extension Preview](exts/omni.example.airoomgenerator/data/preview.png) ### About This extension allows user's to generate 3D content using Generative AI, ChatGPT. Providing an area in the stage and a prompt the user can generate a room configuration designed by ChatGPT. This in turn can help end users automatically generate and place objects within their scene, saving hours of time that would typically be required to create a complex scene. ### [README](exts/omni.example.airoomgenerator) See the [README for this extension](exts/omni.example.airoomgenerator) to learn more about it including how to use it. > This sample is for educational purposes. For production please consider best security practices and scalability. ## Adding This Extension This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths. Link might look like this: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-airoomgenerator?branch=main&dir=exts` Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual. To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path ## Linking with an Omniverse app If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included. Run: ``` > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ``` > link_app.bat --app create ``` You can also just pass a path to create link to: ``` > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
2,140
Markdown
40.173076
363
0.775701
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/style.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui from pathlib import Path icons_path = Path(__file__).parent.parent.parent.parent / "icons" gen_ai_style = { "HStack": { "margin": 3 }, "Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976} }
946
Python
32.821427
98
0.726216
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/extension.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ext from .window import DeepSearchPickerWindow # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): self._window = DeepSearchPickerWindow("DeepSearch Swap", width=300, height=300) def on_shutdown(self): self._window.destroy() self._window = None
1,423
Python
44.935482
119
0.747013
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/deep_search.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from omni.kit.ngsearch.client import NGSearchClient import carb import asyncio class deep_search(): async def query_items(queries, url: str, paths): result = list(tuple()) for query in queries: query_result = await deep_search._query_first(query, url, paths) if query_result is not None: result.append(query_result) return result async def _query_first(query: str, url: str, paths): filtered_query = "ext:usd,usdz,usda path:" for path in paths: filtered_query = filtered_query + "\"" + str(path) + "\"," filtered_query = filtered_query[:-1] filtered_query = filtered_query + " " filtered_query = filtered_query + query SearchResult = await NGSearchClient.get_instance().find2( query=filtered_query, url=url) if len(SearchResult.paths) > 0: return (query, SearchResult.paths[0].uri) else: return None async def query_all(query: str, url: str, paths): filtered_query = "ext:usd,usdz,usda path:" for path in paths: filtered_query = filtered_query + "\"" + str(path) + "\"," filtered_query = filtered_query[:-1] filtered_query = filtered_query + " " filtered_query = filtered_query + query return await NGSearchClient.get_instance().find2(query=filtered_query, url=url)
2,185
Python
32.121212
98
0.632494
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/window.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui import omni.usd import carb from .style import gen_ai_style from .deep_search import deep_search import asyncio from pxr import UsdGeom, Usd, Sdf, Gf class DeepSearchPickerWindow(ui.Window): def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) # Models self.frame.set_build_fn(self._build_fn) self._index = 0 self._query_results = None self._selected_prim = None self._prim_path_model = ui.SimpleStringModel() def _build_fn(self): async def replace_prim(): self._index = 0 ctx = omni.usd.get_context() prim_paths = ctx.get_selection().get_selected_prim_paths() if len(prim_paths) != 1: carb.log_warn("You must select one and only one prim") return prim_path = prim_paths[0] stage = ctx.get_stage() self._selected_prim = stage.GetPrimAtPath(prim_path) query = self._selected_prim.GetAttribute("DeepSearch:Query").Get() prop_paths = ["/Projects/simready_content/common_assets/props/", "/NVIDIA/Assets/Isaac/2022.2.1/Isaac/Robots/", "/NVIDIA/Assets/Isaac/2022.1/NVIDIA/Assets/ArchVis/Residential/Furniture/"] self._query_results = await deep_search.query_all(query, "omniverse://ov-simready/", paths=prop_paths) self._prim_path_model.set_value(prim_path) def increment_prim_index(): if self._query_results is None: return self._index = self._index + 1 if self._index >= len(self._query_results.paths): self._index = 0 self.replace_reference() def decrement_prim_index(): if self._query_results is None: return self._index = self._index - 1 if self._index <= 0: self._index = len(self._query_results.paths) - 1 self.replace_reference() with self.frame: with ui.VStack(style=gen_ai_style): with ui.HStack(height=0): ui.Spacer() ui.StringField(model=self._prim_path_model, width=365, height=30) ui.Button(name="create", width=30, height=30, clicked_fn=lambda: asyncio.ensure_future(replace_prim())) ui.Spacer() with ui.HStack(height=0): ui.Spacer() ui.Button("<", width=200, clicked_fn=lambda: decrement_prim_index()) ui.Button(">", width=200, clicked_fn=lambda: increment_prim_index()) ui.Spacer() def replace_reference(self): references: Usd.references = self._selected_prim.GetReferences() references.ClearReferences() references.AddReference( assetPath="omniverse://ov-simready" + self._query_results.paths[self._index].uri) carb.log_info("Got it?") def destroy(self): super().destroy()
3,815
Python
36.048543
123
0.589253
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "AI Room Generator Sample" description="Generates Rooms using ChatGPT" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Icon to show in the extension manager icon = "data/preview_icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.kit.ngsearch" = {} "omni.kit.window.popup_dialog" = {} # Main python module this extension provides, it will be publicly available as "import company.hello.world". [[python.module]] name = "omni.example.airoomgenerator" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,091
TOML
24.999999
108
0.731439
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/priminfo.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pxr import Usd, Gf class PrimInfo: # Class that stores the prim info def __init__(self, prim: Usd.Prim, name: str = "") -> None: self.prim = prim self.child = prim.GetAllChildren()[0] self.length = self.GetLengthOfPrim() self.width = self.GetWidthOfPrim() self.origin = self.GetPrimOrigin() self.area_name = name def GetLengthOfPrim(self) -> str: # Returns the X value attr = self.child.GetAttribute('xformOp:scale') x_scale = attr.Get()[0] return str(x_scale) def GetWidthOfPrim(self) -> str: # Returns the Z value attr = self.child.GetAttribute('xformOp:scale') z_scale = attr.Get()[2] return str(z_scale) def GetPrimOrigin(self) -> str: attr = self.prim.GetAttribute('xformOp:translate') origin = Gf.Vec3d(0,0,0) if attr: origin = attr.Get() phrase = str(origin[0]) + ", " + str(origin[1]) + ", " + str(origin[2]) return phrase
1,706
Python
36.108695
98
0.651817
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/widgets.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui from omni.ui import color as cl import asyncio import omni import carb class ProgressBar: def __init__(self): self.progress_bar_window = None self.left = None self.right = None self._build_fn() async def play_anim_forever(self): fraction = 0.0 while True: fraction = (fraction + 0.01) % 1.0 self.left.width = ui.Fraction(fraction) self.right.width = ui.Fraction(1.0-fraction) await omni.kit.app.get_app().next_update_async() def _build_fn(self): with ui.VStack(): self.progress_bar_window = ui.HStack(height=0, visible=False) with self.progress_bar_window: ui.Label("Processing", width=0, style={"margin_width": 3}) self.left = ui.Spacer(width=ui.Fraction(0.0)) ui.Rectangle(width=50, style={"background_color": cl("#76b900")}) self.right = ui.Spacer(width=ui.Fraction(1.0)) def show_bar(self, to_show): self.progress_bar_window.visible = to_show
1,770
Python
34.419999
98
0.655367
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/chatgpt_apiconnect.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import carb import aiohttp import asyncio from .prompts import system_input, user_input, assistant_input from .deep_search import query_items from .item_generator import place_greyboxes, place_deepsearch_results async def chatGPT_call(prompt: str): # Load your API key from an environment variable or secret management service settings = carb.settings.get_settings() apikey = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey") my_prompt = prompt.replace("\n", " ") # Send a request API try: parameters = { "model": "gpt-3.5-turbo", "messages": [ {"role": "system", "content": system_input}, {"role": "user", "content": user_input}, {"role": "assistant", "content": assistant_input}, {"role": "user", "content": my_prompt} ] } chatgpt_url = "https://api.openai.com/v1/chat/completions" headers = {"Authorization": "Bearer %s" % apikey} # Create a completion using the chatGPT model async with aiohttp.ClientSession() as session: async with session.post(chatgpt_url, headers=headers, json=parameters) as r: response = await r.json() text = response["choices"][0]["message"]['content'] except Exception as e: carb.log_error("An error as occurred") return None, str(e) # Parse data that was given from API try: #convert string to object data = json.loads(text) except ValueError as e: carb.log_error(f"Exception occurred: {e}") return None, text else: # Get area_objects_list object_list = data['area_objects_list'] return object_list, text async def call_Generate(prim_info, prompt, use_chatgpt, use_deepsearch, response_label, progress_widget): run_loop = asyncio.get_event_loop() progress_widget.show_bar(True) task = run_loop.create_task(progress_widget.play_anim_forever()) response = "" #chain the prompt area_name = prim_info.area_name.split("/World/Layout/") concat_prompt = area_name[-1].replace("_", " ") + ", " + prim_info.length + "x" + prim_info.width + ", origin at (0.0, 0.0, 0.0), generate a list of appropriate items in the correct places. " + prompt root_prim_path = "/World/Layout/GPT/" if prim_info.area_name != "": root_prim_path= prim_info.area_name + "/items/" if use_chatgpt: #when calling the API objects, response = await chatGPT_call(concat_prompt) else: #when testing and you want to skip the API call data = json.loads(assistant_input) objects = data['area_objects_list'] if objects is None: response_label.text = response return if use_deepsearch: settings = carb.settings.get_settings() nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path") filter_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/filter_path") filter_paths = filter_path.split(',') queries = list() for item in objects: queries.append(item['object_name']) query_result = await query_items(queries=queries, url=nucleus_path, paths=filter_paths) if query_result is not None: place_deepsearch_results( gpt_results=objects, query_result=query_result, root_prim_path=root_prim_path) else: place_greyboxes( gpt_results=objects, root_prim_path=root_prim_path) else: place_greyboxes( gpt_results=objects, root_prim_path=root_prim_path) task.cancel() await asyncio.sleep(1) response_label.text = response progress_widget.show_bar(False)
4,729
Python
39.775862
204
0.623176
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/style.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui from pathlib import Path icons_path = Path(__file__).parent.parent.parent.parent / "icons" gen_ai_style = { "HStack": { "margin": 3 }, "Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976}, "Button.Image::properties": {"image_url": f"{icons_path}/cog.svg", "color": 0xFF989898}, "Line": { "margin": 3 }, "Label": { "margin_width": 5 } } guide = """ Step 1: Create a Floor - You can draw a floor outline using the pencil tool. Right click in the viewport then `Create>BasicCurves>From Pencil` - OR Create a prim and scale it to the size you want. i.e. Right click in the viewport then `Create>Mesh>Cube`. - Next, with the floor selected type in a name into "Area Name". Make sure the area name is relative to the room you want to generate. For example, if you inputted the name as "bedroom" ChatGPT will be prompted that the room is a bedroom. - Then click the '+' button. This will generate the floor and add the option to our combo box. Step 2: Prompt - Type in a prompt that you want to send along to ChatGPT. This can be information about what is inside of the room. For example, "generate a comfortable reception area that contains a front desk and an area for guest to sit down". Step 3: Generate - Select 'use ChatGPT' if you want to recieve a response from ChatGPT otherwise it will use a premade response. - Select 'use Deepsearch' if you want to use the deepsearch functionality. (ENTERPRISE USERS ONLY) When deepsearch is false it will spawn in cubes that greybox the scene. - Hit Generate, after hitting generate it will start making the appropriate calls. Loading bar will be shown as api-calls are being made. Step 4: More Rooms - To add another room you can repeat Steps 1-3. To regenerate a previous room just select it from the 'Current Room' in the dropdown menu. - The dropdown menu will remember the last prompt you used to generate the items. - If you do not like the items it generated, you can hit the generate button until you are satisfied with the items. """
2,792
Python
45.549999
138
0.731734
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/prompts.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. system_input='''You are an area generator expert. Given an area of a certain size, you can generate a list of items that are appropriate to that area, in the right place, and with a representative material. You operate in a 3D Space. You work in a X,Y,Z coordinate system. X denotes width, Y denotes height, Z denotes depth. 0.0,0.0,0.0 is the default space origin. You receive from the user the name of the area, the size of the area on X and Z axis in centimetres, the origin point of the area (which is at the center of the area). You answer by only generating JSON files that contain the following information: - area_name: name of the area - X: coordinate of the area on X axis - Y: coordinate of the area on Y axis - Z: coordinate of the area on Z axis - area_size_X: dimension in cm of the area on X axis - area_size_Z: dimension in cm of the area on Z axis - area_objects_list: list of all the objects in the area For each object you need to store: - object_name: name of the object - X: coordinate of the object on X axis - Y: coordinate of the object on Y axis - Z: coordinate of the object on Z axis - Length: dimension in cm of the object on X axis - Width: dimension in cm of the object on Y axis - Height: dimension in cm of the object on Z axis - Material: a reasonable material of the object using an exact name from the following list: Plywood, Leather_Brown, Leather_Pumpkin, Leather_Black, Aluminum_Cast, Birch, Beadboard, Cardboard, Cloth_Black, Cloth_Gray, Concrete_Polished, Glazed_Glass, CorrugatedMetal, Cork, Linen_Beige, Linen_Blue, Linen_White, Mahogany, MDF, Oak, Plastic_ABS, Steel_Carbon, Steel_Stainless, Veneer_OU_Walnut, Veneer_UX_Walnut_Cherry, Veneer_Z5_Maple. Each object name should include an appropriate adjective. Keep in mind, objects should be disposed in the area to create the most meaningful layout possible, and they shouldn't overlap. All objects must be within the bounds of the area size; Never place objects further than 1/2 the length or 1/2 the depth of the area from the origin. Also keep in mind that the objects should be disposed all over the area in respect to the origin point of the area, and you can use negative values as well to display items correctly, since origin of the area is always at the center of the area. Remember, you only generate JSON code, nothing else. It's very important. ''' user_input="Warehouse, 1000x1000, origin at (0.0,0.0,0.0), generate a list of appropriate items in the correct places. Generate warehouse objects" assistant_input='''{ "area_name": "Warehouse_Area", "X": 0.0, "Y": 0.0, "Z": 0.0, "area_size_X": 1000, "area_size_Z": 1000, "area_objects_list": [ { "object_name": "Parts_Pallet_1", "X": -150, "Y": 0.0, "Z": 250, "Length": 100, "Width": 100, "Height": 10, "Material": "Plywood" }, { "object_name": "Boxes_Pallet_2", "X": -150, "Y": 0.0, "Z": 150, "Length": 100, "Width": 100, "Height": 10, "Material": "Plywood" }, { "object_name": "Industrial_Storage_Rack_1", "X": -150, "Y": 0.0, "Z": 50, "Length": 200, "Width": 50, "Height": 300, "Material": "Steel_Carbon" }, { "object_name": "Empty_Pallet_3", "X": -150, "Y": 0.0, "Z": -50, "Length": 100, "Width": 100, "Height": 10, "Material": "Plywood" }, { "object_name": "Yellow_Forklift_1", "X": 50, "Y": 0.0, "Z": -50, "Length": 200, "Width": 100, "Height": 250, "Material": "Plastic_ABS" }, { "object_name": "Heavy_Duty_Forklift_2", "X": 150, "Y": 0.0, "Z": -50, "Length": 200, "Width": 100, "Height": 250, "Material": "Steel_Stainless" } ] }'''
4,898
Python
37.880952
435
0.612903
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/materials.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. MaterialPresets = { "Leather_Brown": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Brown.mdl', "Leather_Pumpkin_01": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Pumpkin.mdl', "Leather_Brown_02": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Brown.mdl', "Leather_Black_01": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Black.mdl', "Aluminum_cast": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Aluminum_Cast.mdl', "Birch": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Birch.mdl', "Beadboard": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Beadboard.mdl', "Cardboard": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/Cardboard.mdl', "Cloth_Black": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Cloth_Black.mdl', "Cloth_Gray": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Cloth_Gray.mdl', "Concrete_Polished": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Concrete_Polished.mdl', "Glazed_Glass": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Glass/Glazed_Glass.mdl', "CorrugatedMetal": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/CorrugatedMetal.mdl', "Cork": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Cork.mdl', "Linen_Beige": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_Beige.mdl', "Linen_Blue": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_Blue.mdl', "Linen_White": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_White.mdl', "Mahogany": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Mahogany.mdl', "MDF": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/MDF.mdl', "Oak": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Oak.mdl', "Plastic_ABS": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Plastic_ABS.mdl', "Steel_Carbon": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Steel_Carbon.mdl', "Steel_Stainless": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Steel_Stainless.mdl', "Veneer_OU_Walnut": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_OU_Walnut.mdl', "Veneer_UX_Walnut_Cherry": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_UX_Walnut_Cherry.mdl', "Veneer_Z5_Maple": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_Z5_Maple.mdl', "Plywood": 'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Plywood.mdl', "Concrete_Rough_Dirty": 'http://omniverse-content-production.s3.us-west-2.amazonaws.com/Materials/vMaterials_2/Concrete/Concrete_Rough.mdl' }
4,323
Python
58.232876
121
0.743234
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/utils.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.kit.commands from pxr import Gf, Sdf, UsdGeom from .materials import * import carb def CreateCubeFromCurve(curve_path: str, area_name: str = ""): ctx = omni.usd.get_context() stage = ctx.get_stage() min_coords, max_coords = get_coords_from_bbox(curve_path) x,y,z = get_bounding_box_dimensions(curve_path) xForm_scale = Gf.Vec3d(x, 1, z) cube_scale = Gf.Vec3d(0.01, 0.01, 0.01) prim = stage.GetPrimAtPath(curve_path) origin = prim.GetAttribute('xformOp:translate').Get() if prim.GetTypeName() == "BasisCurves": origin = Gf.Vec3d(min_coords[0]+x/2, 0, min_coords[2]+z/2) area_path = '/World/Layout/Area' if len(area_name) != 0: area_path = '/World/Layout/' + area_name.replace(" ", "_") new_area_path = omni.usd.get_stage_next_free_path(stage, area_path, False) new_cube_xForm_path = new_area_path + "/" + "Floor" new_cube_path = new_cube_xForm_path + "/" + "Cube" # Create xForm to hold all items item_container = create_prim(new_area_path) set_transformTRS_attrs(item_container, translate=origin) # Create Scale Xform for floor xform = create_prim(new_cube_xForm_path) set_transformTRS_attrs(xform, scale=xForm_scale) # Create Floor Cube omni.kit.commands.execute('CreateMeshPrimWithDefaultXform', prim_type='Cube', prim_path=new_cube_path, select_new_prim=True ) cube = stage.GetPrimAtPath(new_cube_path) set_transformTRS_attrs(cube, scale=cube_scale) cube.CreateAttribute("primvar:area_name", Sdf.ValueTypeNames.String, custom=True).Set(area_name) omni.kit.commands.execute('DeletePrims', paths=[curve_path], destructive=False) apply_material_to_prim('Concrete_Rough_Dirty', new_area_path) return new_area_path def apply_material_to_prim(material_name: str, prim_path: str): ctx = omni.usd.get_context() stage = ctx.get_stage() looks_path = '/World/Looks/' mat_path = looks_path + material_name mat_prim = stage.GetPrimAtPath(mat_path) if MaterialPresets.get(material_name, None) is not None: if not mat_prim.IsValid(): omni.kit.commands.execute('CreateMdlMaterialPrimCommand', mtl_url=MaterialPresets[material_name], mtl_name=material_name, mtl_path=mat_path) omni.kit.commands.execute('BindMaterialCommand', prim_path=prim_path, material_path=mat_path) def create_prim(prim_path, prim_type='Xform'): ctx = omni.usd.get_context() stage = ctx.get_stage() prim = stage.DefinePrim(prim_path) if prim_type == 'Xform': xform = UsdGeom.Xform.Define(stage, prim_path) else: xform = UsdGeom.Cube.Define(stage, prim_path) create_transformOps_for_xform(xform) return prim def create_transformOps_for_xform(xform): xform.AddTranslateOp() xform.AddRotateXYZOp() xform.AddScaleOp() def set_transformTRS_attrs(prim, translate: Gf.Vec3d = Gf.Vec3d(0,0,0), rotate: Gf.Vec3d=Gf.Vec3d(0,0,0), scale: Gf.Vec3d=Gf.Vec3d(1,1,1)): prim.GetAttribute('xformOp:translate').Set(translate) prim.GetAttribute('xformOp:rotateXYZ').Set(rotate) prim.GetAttribute('xformOp:scale').Set(scale) def get_bounding_box_dimensions(prim_path: str): min_coords, max_coords = get_coords_from_bbox(prim_path) length = max_coords[0] - min_coords[0] width = max_coords[1] - min_coords[1] height = max_coords[2] - min_coords[2] return length, width, height def get_coords_from_bbox(prim_path: str): ctx = omni.usd.get_context() bbox = ctx.compute_path_world_bounding_box(prim_path) min_coords, max_coords = bbox return min_coords, max_coords def scale_object_if_needed(prim_path): stage = omni.usd.get_context().get_stage() length, width, height = get_bounding_box_dimensions(prim_path) largest_dimension = max(length, width, height) if largest_dimension < 10: prim = stage.GetPrimAtPath(prim_path) # HACK: All Get Attribute Calls need to check if the attribute exists and add it if it doesn't if prim.IsValid(): scale_attr = prim.GetAttribute('xformOp:scale') if scale_attr.IsValid(): current_scale = scale_attr.Get() new_scale = (current_scale[0] * 100, current_scale[1] * 100, current_scale[2] * 100) scale_attr.Set(new_scale) carb.log_info(f"Scaled object by 100 times: {prim_path}") else: carb.log_info(f"Scale attribute not found for prim at path: {prim_path}") else: carb.log_info(f"Invalid prim at path: {prim_path}") else: carb.log_info(f"No scaling needed for object: {prim_path}")
5,463
Python
38.594203
139
0.663738
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/item_generator.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #hotkey # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pxr import Usd, Sdf, Gf from .utils import scale_object_if_needed, apply_material_to_prim, create_prim, set_transformTRS_attrs def place_deepsearch_results(gpt_results, query_result, root_prim_path): index = 0 for item in query_result: item_name = item[0] item_path = item[1] # Define Prim prim_parent_path = root_prim_path + item_name.replace(" ", "_") prim_path = prim_parent_path + "/" + item_name.replace(" ", "_") parent_prim = create_prim(prim_parent_path) next_prim = create_prim(prim_path) # Add reference to USD Asset references: Usd.references = next_prim.GetReferences() # TODO: The query results should returnt he full path of the prim references.AddReference( assetPath="omniverse://ov-simready" + item_path) # Add reference for future search refinement config = next_prim.CreateAttribute("DeepSearch:Query", Sdf.ValueTypeNames.String) config.Set(item_name) # HACK: All "GetAttribute" calls should need to check if the attribute exists # translate prim next_object = gpt_results[index] index = index + 1 x = next_object['X'] y = next_object['Y'] z = next_object['Z'] set_transformTRS_attrs(parent_prim, Gf.Vec3d(x,y,z), Gf.Vec3d(0,-90,-90), Gf.Vec3d(1.0,1.0,1.0)) scale_object_if_needed(prim_parent_path) def place_greyboxes(gpt_results, root_prim_path): index = 0 for item in gpt_results: # Define Prim prim_parent_path = root_prim_path + item['object_name'].replace(" ", "_") prim_path = prim_parent_path + "/" + item['object_name'].replace(" ", "_") # Define Dimensions and material length = item['Length']/100 width = item['Width']/100 height = item['Height']/100 x = item['X'] y = item['Y']+height*100*.5 #shift bottom of object to y=0 z = item['Z'] material = item['Material'] # Create Prim parent_prim = create_prim(prim_parent_path) set_transformTRS_attrs(parent_prim) prim = create_prim(prim_path, 'Cube') set_transformTRS_attrs(prim, translate=Gf.Vec3d(x,y,z), scale=Gf.Vec3d(length, height, width)) prim.GetAttribute('extent').Set([(-50.0, -50.0, -50.0), (50.0, 50.0, 50.0)]) prim.GetAttribute('size').Set(100) index = index + 1 # Add Attribute and Material attr = prim.CreateAttribute("object_name", Sdf.ValueTypeNames.String) attr.Set(item['object_name']) apply_material_to_prim(material, prim_path)
3,365
Python
38.139534
104
0.63477
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/window.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import omni.ui as ui import omni.usd import carb import asyncio import omni.kit.commands from omni.kit.window.popup_dialog.form_dialog import FormDialog from .utils import CreateCubeFromCurve from .style import gen_ai_style, guide from .chatgpt_apiconnect import call_Generate from .priminfo import PrimInfo from pxr import Sdf from .widgets import ProgressBar class GenAIWindow(ui.Window): def __init__(self, title: str, **kwargs) -> None: super().__init__(title, **kwargs) # Models self._path_model = ui.SimpleStringModel() self._prompt_model = ui.SimpleStringModel("generate warehouse objects") self._area_name_model = ui.SimpleStringModel() self._use_deepsearch = ui.SimpleBoolModel() self._use_chatgpt = ui.SimpleBoolModel() self._areas = [] self.response_log = None self.current_index = -1 self.current_area = None self._combo_changed_sub = None self.frame.set_build_fn(self._build_fn) def _build_fn(self): with self.frame: with ui.ScrollingFrame(): with ui.VStack(style=gen_ai_style): with ui.HStack(height=0): ui.Label("Content Generatation with ChatGPT", style={"font_size": 18}) ui.Button(name="properties", tooltip="Configure API Key and Nucleus Path", width=30, height=30, clicked_fn=lambda: self._open_settings()) with ui.CollapsableFrame("Getting Started Instructions", height=0, collapsed=True): ui.Label(guide, word_wrap=True) ui.Line() with ui.HStack(height=0): ui.Label("Area Name", width=ui.Percent(30)) ui.StringField(model=self._area_name_model) ui.Button(name="create", width=30, height=30, clicked_fn=lambda: self._create_new_area(self.get_area_name())) with ui.HStack(height=0): ui.Label("Current Room", width=ui.Percent(30)) self._build_combo_box() ui.Line() with ui.HStack(height=ui.Percent(50)): ui.Label("Prompt", width=0) ui.StringField(model=self._prompt_model, multiline=True) ui.Line() self._build_ai_section() def _save_settings(self, dialog): values = dialog.get_values() carb.log_info(values) settings = carb.settings.get_settings() settings.set_string("/persistent/exts/omni.example.airoomgenerator/APIKey", values["APIKey"]) settings.set_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path", values["deepsearch_nucleus_path"]) settings.set_string("/persistent/exts/omni.example.airoomgenerator/path_filter", values["path_filter"]) dialog.hide() def _open_settings(self): settings = carb.settings.get_settings() apikey_value = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey") nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path") path_filter = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/path_filter") if apikey_value == "": apikey_value = "Enter API Key Here" if nucleus_path == "": nucleus_path = "(ENTERPRISE ONLY) Enter Nucleus Path Here" if path_filter == "": path_filter = "" field_defs = [ FormDialog.FieldDef("APIKey", "API Key: ", ui.StringField, apikey_value), FormDialog.FieldDef("deepsearch_nucleus_path", "Nucleus Path: ", ui.StringField, nucleus_path), FormDialog.FieldDef("path_filter", "Path Filter: ", ui.StringField, path_filter) ] dialog = FormDialog( title="Settings", message="Your Settings: ", field_defs = field_defs, ok_handler=lambda dialog: self._save_settings(dialog)) dialog.show() def _build_ai_section(self): with ui.HStack(height=0): ui.Spacer() ui.Label("Use ChatGPT: ") ui.CheckBox(model=self._use_chatgpt) ui.Label("Use Deepsearch: ", tooltip="ENTERPRISE USERS ONLY") ui.CheckBox(model=self._use_deepsearch) ui.Spacer() with ui.HStack(height=0): ui.Spacer(width=ui.Percent(10)) ui.Button("Generate", height=40, clicked_fn=lambda: self._generate()) ui.Spacer(width=ui.Percent(10)) self.progress = ProgressBar() with ui.CollapsableFrame("ChatGPT Response / Log", height=0, collapsed=True): self.response_log = ui.Label("", word_wrap=True) def _build_combo_box(self): self.combo_model = ui.ComboBox(self.current_index, *[str(x) for x in self._areas] ).model def combo_changed(item_model, item): index_value_model = item_model.get_item_value_model(item) self.current_area = self._areas[index_value_model.as_int] self.current_index = index_value_model.as_int self.rebuild_frame() self._combo_changed_sub = self.combo_model.subscribe_item_changed_fn(combo_changed) def _create_new_area(self, area_name: str): if area_name == "": carb.log_warn("No area name provided") return new_area_name = CreateCubeFromCurve(self.get_prim_path(), area_name) self._areas.append(new_area_name) self.current_index = len(self._areas) - 1 index_value_model = self.combo_model.get_item_value_model() index_value_model.set_value(self.current_index) def rebuild_frame(self): # we do want to update the area name and possibly last prompt? area_name = self.current_area.split("/World/Layout/") self._area_name_model.set_value(area_name[-1].replace("_", " ")) attr_prompt = self.get_prim().GetAttribute('genai:prompt') if attr_prompt.IsValid(): self._prompt_model.set_value(attr_prompt.Get()) else: self._prompt_model.set_value("") self.frame.rebuild() def _generate(self): prim = self.get_prim() attr = prim.GetAttribute('genai:prompt') if not attr.IsValid(): attr = prim.CreateAttribute('genai:prompt', Sdf.ValueTypeNames.String) attr.Set(self.get_prompt()) items_path = self.current_area + "/items" ctx = omni.usd.get_context() stage = ctx.get_stage() if stage.GetPrimAtPath(items_path).IsValid(): omni.kit.commands.execute('DeletePrims', paths=[items_path], destructive=False) # asyncio.ensure_future(self.progress.fill_bar(0,100)) run_loop = asyncio.get_event_loop() run_loop.create_task(call_Generate(self.get_prim_info(), self.get_prompt(), self._use_chatgpt.as_bool, self._use_deepsearch.as_bool, self.response_log, self.progress )) # Returns a PrimInfo object containing the Length, Width, Origin and Area Name def get_prim_info(self) -> PrimInfo: prim = self.get_prim() prim_info = None if prim.IsValid(): prim_info = PrimInfo(prim, self.current_area) return prim_info # # Get the prim path specified def get_prim_path(self): ctx = omni.usd.get_context() selection = ctx.get_selection().get_selected_prim_paths() if len(selection) > 0: return str(selection[0]) carb.log_warn("No Prim Selected") return "" # Get the area name specified def get_area_name(self): if self._area_name_model == "": carb.log_warn("No Area Name Provided") return self._area_name_model.as_string # Get the prompt specified def get_prompt(self): if self._prompt_model == "": carb.log_warn("No Prompt Provided") return self._prompt_model.as_string # Get the prim based on the Prim Path def get_prim(self): ctx = omni.usd.get_context() stage = ctx.get_stage() prim = stage.GetPrimAtPath(self.current_area) if prim.IsValid() is None: carb.log_warn("No valid prim in the scene") return prim def destroy(self): super().destroy() self._combo_changed_sub = None self._path_model = None self._prompt_model = None self._area_name_model = None self._use_deepsearch = None self._use_chatgpt = None
9,607
Python
41.892857
161
0.595503
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/docs/README.md
# AI Room Generator Sample Extension (omni.sample.airoomgenerator) ![Preview](../data/preview.png) ## Overview The AI Room Generator Sample Extension allows users to generate 3D content to populate a room using Generative AI. The user will specify what area that defines the room and a prompt that will get passed to ChatGPT. > NOTE: To enable the extension you will need to have ngsearch module. By default it is already avaliable in Omniverse USD Composer. If using Omniverse Code follow these [instructions](https://docs.omniverse.nvidia.com/prod_nucleus/prod_services/services/deepsearch/client/using_deepsearch_ui.html#using-deepsearch-beta-in-usd-composer) to get ngsearch This Sample Extension utilizes Omniverse's [Deepsearch](https://docs.omniverse.nvidia.com/prod_nucleus/prod_services/services/deepsearch/overview.html) functionality to search for models within a nucleus server. (ENTERPRISE USERS ONLY) ## UI Overview ![UI Image](../data/ui.png) 1. Settings (Cog Button) - Where the user can input their API Key from [OpenAI](https://platform.openai.com/account/api-keys) - Enterprise users can input their Deepsearch Enabled Nucleus Path 2. Area Name - The name that will be applied to the Area once added. 3. Add Area (Plus Button) - With an area selected and an Area Name provided, it will remove the selected object and spawn in a cube resembling the dimensions of the selected area prim. 4. Current Room - By default this will be empty. As you add rooms this combo box will populate and allow you to switch between each generated room maintaining the prompt (if the room items have been generated). This allows users to adjust their prompt later for an already generated room. 5. Prompt - The prompt that will be sent to ChatGPT. - Here is an example prompt for a reception area: - "This is the room where we meet our customers. Make sure there is a set of comfortable armchairs, a sofa, and a coffee table" 6. Use ChatGPT - This enables the extension to call ChatGPT, otherwise it will use a default assistant prompt which will be the same every time. 7. Use Deepsearch (ENTERPRISE USERS ONLY) - This enables the extension to use Deepsearch 8. Generate - With a room selected and a prompt, this will send all the related information to ChatGPT. A progress bar will show up indicating if the response is still going. 9. ChatGPT Reponse / Log - Once you have hit *Generate* this collapsable frame will contain the output recieved from ChatGPT. Here you can view the JSON data or if any issues arise with ChatGPT. ## How it works ### Getting information about the 3D Scene Everything starts with the USD scene in Omniverse. Users can easily circle an area using the Pencil tool in Omniverse or create a cube and scale it in the scene, type in the kind of room/environment they want to generate - for example, a warehouse, or a reception room - and with one click that area is created. ![Pencil](../data/pencil.png) ### Creating the Prompt for ChatGPT The ChatGPT prompt is composed of four pieces; system input, user input example, assistant output example, and user prompt. Let’s start with the aspects of the prompt that tailor to the user’s scenario. This includes text that the user inputs plus data from the scene. For example, if the user wants to create a reception room, they specify something like “This is the room where we meet our customers. Make sure there is a set of comfortable armchairs, a sofa and a coffee table”. Or, if they want to add a certain number of items they could add “make sure to include a minimum of 10 items”. This text is combined with scene information like the size and name of the area where we will place items as the User Prompt. ### Passing the results from ChatGPT ![deepsearch](../data/deepsearch.png) The items from the ChatGPT JSON response are then parsed by the extension and passed to the Omnivere DeepSearch API. DeepSearch allows users to search 3D models stored within an Omniverse Nucleus server using natural language queries. This means that even if we don’t know the exact file name of a model of a sofa, for example, we can retrieve it just by searching for “Comfortable Sofa” which is exactly what we got from ChatGPT. DeepSearch understands natural language and by asking it for a “Comfortable Sofa” we get a list of items that our helpful AI librarian has decided are best suited from the selection of assets we have in our current asset library. It is surprisingly good at this and so we often can use the first item it returns, but of course we build in choice in case the user wants to select something from the list. ### When not using Deepsearch ![greyboxing](../data/greyboxing.png) For those who are not Enterprise users or users that want to use greyboxing, by default as long as `use Deepsearch` is turned off the extension will generate cube of various shapes and sizes to best suit the response from ChatGPT.
4,975
Markdown
73.268656
404
0.776482
NVIDIA-Omniverse/AnariUsdDevice/UsdParameterizedObject.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include <map> #include <string> #include <cstring> #include <cassert> #include <algorithm> #include <vector> #include "UsdAnari.h" #include "UsdSharedObjects.h" #include "UsdMultiTypeParameter.h" #include "helium/utility/IntrusivePtr.h" #include "anari/frontend/type_utility.h" class UsdDevice; class UsdBridge; // When deriving from UsdParameterizedObject<T>, define a a struct T::Data and // a static void T::registerParams() that registers any member of T::Data using REGISTER_PARAMETER_MACRO() template<typename T, typename D> class UsdParameterizedObject { public: struct UsdAnariDataTypeStore { ANARIDataType type0 = ANARI_UNKNOWN; ANARIDataType type1 = ANARI_UNKNOWN; ANARIDataType type2 = ANARI_UNKNOWN; ANARIDataType singleType() const { return type0; } bool isMultiType() const { return type1 != ANARI_UNKNOWN; } bool typeMatches(ANARIDataType inType) const { return inType == type0 || (isMultiType() && (inType == type1 || inType == type2)); } }; struct ParamTypeInfo { size_t dataOffset = 0; // offset of data, within paramDataSet D size_t typeOffset = 0; // offset of type, from data size_t size = 0; // Total size of data+type UsdAnariDataTypeStore types; }; using ParameterizedClassType = UsdParameterizedObject<T, D>; using ParamContainer = std::map<std::string, ParamTypeInfo>; void* getParam(const char* name, ANARIDataType& returnType) { // Check if name registered typename ParamContainer::iterator it = registeredParams->find(name); if (it != registeredParams->end()) { const ParamTypeInfo& typeInfo = it->second; void* destAddress = nullptr; getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo, returnType, destAddress); return destAddress; } return nullptr; } protected: helium::RefCounted** ptrToRefCountedPtr(void* address) { return reinterpret_cast<helium::RefCounted**>(address); } ANARIDataType* toAnariDataTypePtr(void* address) { return reinterpret_cast<ANARIDataType*>(address); } bool isRefCounted(ANARIDataType type) const { return anari::isObject(type) || type == ANARI_STRING; } void safeRefInc(void* paramPtr) // Pointer to the parameter address which holds a helium::RefCounted* { helium::RefCounted** refCountedPP = ptrToRefCountedPtr(paramPtr); if (*refCountedPP) (*refCountedPP)->refInc(helium::RefType::INTERNAL); } void safeRefDec(void* paramPtr, ANARIDataType paramType) // Pointer to the parameter address which holds a helium::RefCounted* { helium::RefCounted** refCountedPP = ptrToRefCountedPtr(paramPtr); if (*refCountedPP) { helium::RefCounted*& refCountedP = *refCountedPP; #ifdef CHECK_MEMLEAKS logDeallocationThroughDevice(allocDevice, refCountedP, paramType); #endif assert(refCountedP->useCount(helium::RefType::INTERNAL) > 0); refCountedP->refDec(helium::RefType::INTERNAL); refCountedP = nullptr; // Explicitly clear the pointer (see destructor) } } void* paramAddress(D& paramData, const ParamTypeInfo& typeInfo) { return reinterpret_cast<char*>(&paramData) + typeInfo.dataOffset; } ANARIDataType paramType(void* paramAddress, const ParamTypeInfo& typeInfo) { if(typeInfo.types.isMultiType()) return *toAnariDataTypePtr(static_cast<char*>(paramAddress) + typeInfo.typeOffset); else return typeInfo.types.singleType(); } void setMultiParamType(void* paramAddress, const ParamTypeInfo& typeInfo, ANARIDataType newType) { if(typeInfo.types.isMultiType()) *toAnariDataTypePtr(static_cast<char*>(paramAddress) + typeInfo.typeOffset) = newType; } void getParamTypeAndAddress(D& paramData, const ParamTypeInfo& typeInfo, ANARIDataType& returnType, void*& returnAddress) { returnAddress = paramAddress(paramData, typeInfo); returnType = paramType(returnAddress, typeInfo); } // Convenience function for usd-compatible parameters void formatUsdName(UsdSharedString* nameStr) { char* name = const_cast<char*>(UsdSharedString::c_str(nameStr)); assert(strlen(name) > 0); auto letter = [](unsigned c) { return ((c - 'A') < 26) || ((c - 'a') < 26); }; auto number = [](unsigned c) { return (c - '0') < 10; }; auto under = [](unsigned c) { return c == '_'; }; unsigned x = *name; if (!letter(x) && !under(x)) { *name = '_'; } x = *(++name); while (x != '\0') { if(!letter(x) && !number(x) && !under(x)) *name = '_'; x = *(++name); }; } public: UsdParameterizedObject() { static ParamContainer* reg = ParameterizedClassType::registerParams(); registeredParams = reg; } ~UsdParameterizedObject() { // Manually decrease the references on all objects in the read and writeparam datasets // (since the pointers are relinquished) auto it = registeredParams->begin(); while (it != registeredParams->end()) { const ParamTypeInfo& typeInfo = it->second; ANARIDataType readParamType, writeParamType; void* readParamAddress = nullptr; void* writeParamAddress = nullptr; getParamTypeAndAddress(paramDataSets[paramReadIdx], typeInfo, readParamType, readParamAddress); getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo, writeParamType, writeParamAddress); // Works even if two parameters point to the same object, as the object pointers are set to null if(isRefCounted(readParamType)) safeRefDec(readParamAddress, readParamType); if(isRefCounted(writeParamType)) safeRefDec(writeParamAddress, writeParamType); ++it; } } const D& getReadParams() const { return paramDataSets[paramReadIdx]; } D& getWriteParams() { return paramDataSets[paramWriteIdx]; } protected: void setParam(const char* name, ANARIDataType srcType, const void* rawSrc, UsdDevice* device) { #ifdef CHECK_MEMLEAKS allocDevice = device; #endif if(srcType == ANARI_UNKNOWN) { reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "Attempting to set param %s with type %s", name, AnariTypeToString(srcType)); return; } else if(anari::isArray(srcType)) { // Flatten the source type in case of array srcType = ANARI_ARRAY; } // Check if name registered typename ParamContainer::iterator it = registeredParams->find(name); if (it != registeredParams->end()) { const ParamTypeInfo& typeInfo = it->second; // Check if type matches if (typeInfo.types.typeMatches(srcType)) { ANARIDataType destType; void* destAddress = nullptr; getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo, destType, destAddress); const void* srcAddress = rawSrc; //temporary src size_t numBytes = anari::sizeOf(srcType); // Size is determined purely by source data bool contentUpdate = srcType != destType; // Always do a content update if types differ (in case of multitype params) // Update data for all the different types if (srcType == ANARI_BOOL) { bool* destBool_p = reinterpret_cast<bool*>(destAddress); bool srcBool = *(reinterpret_cast<const uint32_t*>(srcAddress)); contentUpdate = contentUpdate || (*destBool_p != srcBool); *destBool_p = srcBool; } else { UsdSharedString* sharedStr = nullptr; if (srcType == ANARI_STRING) { // Wrap strings to make them refcounted, // from that point they are considered normal RefCounteds. UsdSharedString* destStr = reinterpret_cast<UsdSharedString*>(*ptrToRefCountedPtr(destAddress)); const char* srcCstr = reinterpret_cast<const char*>(srcAddress); contentUpdate = contentUpdate || !destStr || !strEquals(destStr->c_str(), srcCstr); // Note that execution of strEquals => (srcType == destType) if(contentUpdate) { sharedStr = new UsdSharedString(srcCstr); // Remember to refdec numBytes = sizeof(void*); srcAddress = &sharedStr; #ifdef CHECK_MEMLEAKS logAllocationThroughDevice(allocDevice, sharedStr, ANARI_STRING); #endif } } else contentUpdate = contentUpdate || bool(std::memcmp(destAddress, srcAddress, numBytes)); if(contentUpdate) { if(isRefCounted(destType)) safeRefDec(destAddress, destType); std::memcpy(destAddress, srcAddress, numBytes); if(isRefCounted(srcType)) safeRefInc(destAddress); } // If a string object has been created, decrease its public refcount (1 at creation) if (sharedStr) { assert(sharedStr->useCount() == 2); // Single public and internal reference sharedStr->refDec(); } } // Update the type for multitype params (so far only data has been updated) if(contentUpdate) setMultiParamType(destAddress, typeInfo, srcType); if(!strEquals(name, "usd::time")) // Allow for re-use of object as reference at different timestep, without triggering a full re-commit of the referenced object { #ifdef TIME_BASED_CACHING paramChanged = true; //For time-varying parameters, comparisons between content of potentially different timesteps is meaningless #else paramChanged = paramChanged || contentUpdate; #endif } } else reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "Param %s is not of an accepted type. For example, use %s instead.", name, AnariTypeToString(typeInfo.types.type0)); } } void resetParam(const ParamTypeInfo& typeInfo) { size_t paramSize = typeInfo.size; // Copy to existing write param location ANARIDataType destType; void* destAddress = nullptr; getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo, destType, destAddress); // Create temporary default-constructed parameter set and find source param address ((multi-)type is of no concern) D defaultParamData; void* srcAddress = paramAddress(defaultParamData, typeInfo); // Make sure to dec existing ptr, as it will be relinquished if(isRefCounted(destType)) safeRefDec(destAddress, destType); // Just replace contents of the whole parameter structure, single or multiparam std::memcpy(destAddress, srcAddress, paramSize); } void resetParam(const char* name) { typename ParamContainer::iterator it = registeredParams->find(name); if (it != registeredParams->end()) { const ParamTypeInfo& typeInfo = it->second; resetParam(typeInfo); if(!strEquals(name, "usd::time")) { paramChanged = true; } } } void resetParams() { auto it = registeredParams->begin(); while (it != registeredParams->end()) { resetParam(it->second); ++it; } paramChanged = true; } void transferWriteToReadParams() { // Make sure object references are removed for // the overwritten readparams, and increased for the source writeparams auto it = registeredParams->begin(); while (it != registeredParams->end()) { const ParamTypeInfo& typeInfo = it->second; ANARIDataType srcType, destType; void* srcAddress = nullptr; void* destAddress = nullptr; getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo, srcType, srcAddress); getParamTypeAndAddress(paramDataSets[paramReadIdx], typeInfo, destType, destAddress); // SrcAddress and destAddress are not the same, but they may specifically contain the same object pointers. // Branch out on that situation (may also be disabled, which results in a superfluous inc/dec) if(std::memcmp(destAddress, srcAddress, typeInfo.size)) { // First inc, then dec (in case branch is taken out and the pointed to object is the same) if (isRefCounted(srcType)) safeRefInc(srcAddress); if (isRefCounted(destType)) safeRefDec(destAddress, destType); // Perform assignment immediately; there may be multiple parameters with the same object target, // which will be branched out at the compare the second time around std::memcpy(destAddress, srcAddress, typeInfo.size); } ++it; } } static ParamContainer* registerParams(); ParamContainer* registeredParams; typedef T DerivedClassType; typedef D DataType; D paramDataSets[2]; constexpr static unsigned int paramReadIdx = 0; constexpr static unsigned int paramWriteIdx = 1; bool paramChanged = false; #ifdef CHECK_MEMLEAKS UsdDevice* allocDevice = nullptr; #endif }; #define DEFINE_PARAMETER_MAP(DefClass, Params) template<> UsdParameterizedObject<DefClass,DefClass::DataType>::ParamContainer* UsdParameterizedObject<DefClass,DefClass::DataType>::registerParams() { static ParamContainer registeredParams; Params return &registeredParams; } #define REGISTER_PARAMETER_MACRO(ParamName, ParamType, ParamData) \ registeredParams.emplace( std::make_pair<std::string, ParamTypeInfo>( \ std::string(ParamName), \ {offsetof(DataType, ParamData), 0, sizeof(DataType::ParamData), {ParamType, ANARI_UNKNOWN, ANARI_UNKNOWN}} \ )); \ static_assert(ParamType == anari::ANARITypeFor<decltype(DataType::ParamData)>::value, "ANARI type " #ParamType " of member '" #ParamData "' does not correspond to member type"); #define REGISTER_PARAMETER_MULTITYPE_MACRO(ParamName, ParamType0, ParamType1, ParamType2, ParamData) \ { \ static_assert(ParamType0 == decltype(DataType::ParamData)::AnariType0, "MultiTypeParams registration: ParamType0 " #ParamType0 " of member '" #ParamData "' doesn't match AnariType0"); \ static_assert(ParamType1 == decltype(DataType::ParamData)::AnariType1, "MultiTypeParams registration: ParamType1 " #ParamType1 " of member '" #ParamData "' doesn't match AnariType1"); \ static_assert(ParamType2 == decltype(DataType::ParamData)::AnariType2, "MultiTypeParams registration: ParamType2 " #ParamType2 " of member '" #ParamData "' doesn't match AnariType2"); \ size_t dataOffset = offsetof(DataType, ParamData); \ size_t typeOffset = offsetof(DataType, ParamData.type); \ registeredParams.emplace( std::make_pair<std::string, ParamTypeInfo>( \ std::string(ParamName), \ {dataOffset, typeOffset - dataOffset, sizeof(DataType::ParamData), {ParamType0, ParamType1, ParamType2}} \ )); \ } // Static assert explainer: gets the element type of the array via the decltype of *std::begin(), which in turn accepts an array #define REGISTER_PARAMETER_ARRAY_MACRO(ParamName, ParamNameSuffix, ParamType, ParamData, NumEntries) \ { \ using element_type_t = std::remove_reference_t<decltype(*std::begin(std::declval<decltype(DataType::ParamData)&>()))>; \ static_assert(ParamType == anari::ANARITypeFor<element_type_t>::value, "ANARI type " #ParamType " of member '" #ParamData "' does not correspond to member type"); \ static_assert(sizeof(decltype(DataType::ParamData)) == sizeof(element_type_t)*NumEntries, "Number of elements of member '" #ParamData "' does not correspond with member declaration."); \ size_t offset0 = offsetof(DataType, ParamData[0]); \ size_t offset1 = offsetof(DataType, ParamData[1]); \ size_t paramSize = offset1-offset0; \ for(int i = 0; i < NumEntries; ++i) \ { \ registeredParams.emplace( std::make_pair<std::string, ParamTypeInfo>( \ ParamName + std::to_string(i) + ParamNameSuffix, \ {offset0+paramSize*i, 0, paramSize, {ParamType, ANARI_UNKNOWN, ANARI_UNKNOWN}} \ )); \ } \ }
16,145
C
35.947368
273
0.679282
NVIDIA-Omniverse/AnariUsdDevice/UsdRenderer.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBaseObject.h" #include "UsdParameterizedObject.h" struct UsdRendererData { }; class UsdRenderer : public UsdParameterizedBaseObject<UsdRenderer, UsdRendererData> { public: UsdRenderer(); ~UsdRenderer(); void remove(UsdDevice* device) override {} int getProperty(const char * name, ANARIDataType type, void * mem, uint64_t size, UsdDevice* device) override; protected: bool deferCommit(UsdDevice* device) override; bool doCommitData(UsdDevice* device) override; void doCommitRefs(UsdDevice* device) override {} UsdBridge* usdBridge; };
681
C
20.999999
114
0.737151
NVIDIA-Omniverse/AnariUsdDevice/UsdGeometry.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBridgedBaseObject.h" #include <memory> #include <limits> class UsdDataArray; struct UsdBridgeMeshData; static constexpr int MAX_ATTRIBS = 16; enum class UsdGeometryComponents { POSITION = 0, NORMAL, COLOR, INDEX, SCALE, ORIENTATION, ID, ATTRIBUTE0, ATTRIBUTE1, ATTRIBUTE2, ATTRIBUTE3 }; struct UsdGeometryData { UsdSharedString* name = nullptr; UsdSharedString* usdName = nullptr; double timeStep = 0.0; int timeVarying = 0xFFFFFFFF; // TimeVarying bits const UsdDataArray* vertexPositions = nullptr; const UsdDataArray* vertexNormals = nullptr; const UsdDataArray* vertexColors = nullptr; const UsdDataArray* vertexAttributes[MAX_ATTRIBS] = { nullptr }; const UsdDataArray* primitiveNormals = nullptr; const UsdDataArray* primitiveColors = nullptr; const UsdDataArray* primitiveAttributes[MAX_ATTRIBS] = { nullptr }; const UsdDataArray* primitiveIds = nullptr; const UsdSharedString* attributeNames[MAX_ATTRIBS] = { nullptr }; const UsdDataArray* indices = nullptr; // Spheres const UsdDataArray* vertexRadii = nullptr; float radiusConstant = 1.0f; bool UseUsdGeomPoints = #ifdef USE_USD_GEOM_POINTS true; #else false; #endif // Cylinders const UsdDataArray* primitiveRadii = nullptr; // Curves // Glyphs const UsdDataArray* vertexScales = nullptr; const UsdDataArray* primitiveScales = nullptr; const UsdDataArray* vertexOrientations = nullptr; const UsdDataArray* primitiveOrientations = nullptr; UsdFloat3 scaleConstant = {1.0f, 1.0f, 1.0f}; UsdQuaternion orientationConstant; UsdSharedString* shapeType = nullptr; UsdGeometry* shapeGeometry = nullptr; UsdFloatMat4 shapeTransform; double shapeGeometryRefTimeStep = std::numeric_limits<float>::quiet_NaN(); }; struct UsdGeometryTempArrays; class UsdGeometry : public UsdBridgedBaseObject<UsdGeometry, UsdGeometryData, UsdGeometryHandle, UsdGeometryComponents> { public: enum GeomType { GEOM_UNKNOWN = 0, GEOM_TRIANGLE, GEOM_QUAD, GEOM_SPHERE, GEOM_CYLINDER, GEOM_CONE, GEOM_CURVE, GEOM_GLYPH }; typedef std::vector<UsdBridgeAttribute> AttributeArray; typedef std::vector<std::vector<char>> AttributeDataArraysType; UsdGeometry(const char* name, const char* type, UsdDevice* device); ~UsdGeometry(); void remove(UsdDevice* device) override; void filterSetParam(const char *name, ANARIDataType type, const void *mem, UsdDevice* device) override; bool isInstanced() const { return geomType == GEOM_SPHERE || geomType == GEOM_CONE || geomType == GEOM_CYLINDER || geomType == GEOM_GLYPH; } static constexpr ComponentPair componentParamNames[] = { ComponentPair(UsdGeometryComponents::POSITION, "position"), ComponentPair(UsdGeometryComponents::NORMAL, "normal"), ComponentPair(UsdGeometryComponents::COLOR, "color"), ComponentPair(UsdGeometryComponents::INDEX, "index"), ComponentPair(UsdGeometryComponents::SCALE, "scale"), ComponentPair(UsdGeometryComponents::SCALE, "radius"), ComponentPair(UsdGeometryComponents::ORIENTATION, "orientation"), ComponentPair(UsdGeometryComponents::ID, "id"), ComponentPair(UsdGeometryComponents::ATTRIBUTE0, "attribute0"), ComponentPair(UsdGeometryComponents::ATTRIBUTE1, "attribute1"), ComponentPair(UsdGeometryComponents::ATTRIBUTE2, "attribute2"), ComponentPair(UsdGeometryComponents::ATTRIBUTE3, "attribute3")}; protected: bool deferCommit(UsdDevice* device) override; bool doCommitData(UsdDevice* device) override; void doCommitRefs(UsdDevice* device) override; void initializeGeomData(UsdBridgeMeshData& geomData); void initializeGeomData(UsdBridgeInstancerData& geomData); void initializeGeomData(UsdBridgeCurveData& geomData); void initializeGeomRefData(UsdBridgeInstancerRefData& geomRefData); bool checkArrayConstraints(const UsdDataArray* vertexArray, const UsdDataArray* primArray, const char* paramName, UsdDevice* device, const char* debugName, int attribIndex = -1); bool checkGeomParams(UsdDevice* device); void updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeMeshData& meshData, bool isNew); void updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeInstancerData& instancerData, bool isNew); void updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeCurveData& curveData, bool isNew); template<typename UsdGeomType> bool commitTemplate(UsdDevice* device); void commitPrototypes(UsdBridge* usdBridge); template<typename GeomDataType> void setAttributeTimeVarying(typename GeomDataType::DataMemberId& timeVarying); void syncAttributeArrays(); template<typename GeomDataType> void copyAttributeArraysToData(GeomDataType& geomData); void assignTempDataToAttributes(bool perPrimInterpolation); GeomType geomType = GEOM_UNKNOWN; bool protoShapeChanged = false; // Do not automatically commit shapes (the object may have been recreated onto an already existing USD prim) std::unique_ptr<UsdGeometryTempArrays> tempArrays; AttributeArray attributeArray; };
5,365
C
29.83908
144
0.741473
NVIDIA-Omniverse/AnariUsdDevice/UsdMaterial.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBridgedBaseObject.h" #include "UsdBridgeNumerics.h" #include "UsdDeviceUtils.h" #include <limits> class UsdSampler; template<typename ValueType> using UsdMaterialMultiTypeParameter = UsdMultiTypeParameter<ValueType, UsdSampler*, UsdSharedString*>; enum class UsdMaterialDataComponents { COLOR = 0, OPACITY, EMISSIVE, EMISSIVEFACTOR, ROUGHNESS, METALLIC, IOR }; struct UsdMaterialData { UsdSharedString* name = nullptr; UsdSharedString* usdName = nullptr; double timeStep = std::numeric_limits<float>::quiet_NaN(); int timeVarying = 0; // Bitmask indicating which attributes are time-varying. // Standard parameters UsdMaterialMultiTypeParameter<UsdFloat3> color = {{ 1.0f, 1.0f, 1.0f }, ANARI_FLOAT32_VEC3}; UsdMaterialMultiTypeParameter<float> opacity = {1.0f, ANARI_FLOAT32}; UsdSharedString* alphaMode = nullptr; // Timevarying state linked to opacity float alphaCutoff = 0.5f; // Timevarying state linked to opacity // Possible PBR parameters UsdMaterialMultiTypeParameter<UsdFloat3> emissiveColor = {{ 1.0f, 1.0f, 1.0f }, ANARI_FLOAT32_VEC3}; UsdMaterialMultiTypeParameter<float> emissiveIntensity = {0.0f, ANARI_FLOAT32}; UsdMaterialMultiTypeParameter<float> roughness = {0.5f, ANARI_FLOAT32}; UsdMaterialMultiTypeParameter<float> metallic = {0.0f, ANARI_FLOAT32}; UsdMaterialMultiTypeParameter<float> ior = {1.0f, ANARI_FLOAT32}; double colorSamplerTimeStep = std::numeric_limits<float>::quiet_NaN(); double opacitySamplerTimeStep = std::numeric_limits<float>::quiet_NaN(); double emissiveSamplerTimeStep = std::numeric_limits<float>::quiet_NaN(); double emissiveIntensitySamplerTimeStep = std::numeric_limits<float>::quiet_NaN(); double roughnessSamplerTimeStep = std::numeric_limits<float>::quiet_NaN(); double metallicSamplerTimeStep = std::numeric_limits<float>::quiet_NaN(); double iorSamplerTimeStep = std::numeric_limits<float>::quiet_NaN(); }; class UsdMaterial : public UsdBridgedBaseObject<UsdMaterial, UsdMaterialData, UsdMaterialHandle, UsdMaterialDataComponents> { public: using MaterialDMI = UsdBridgeMaterialData::DataMemberId; UsdMaterial(const char* name, const char* type, UsdDevice* device); ~UsdMaterial(); void remove(UsdDevice* device) override; bool isPerInstance() const { return perInstance; } void updateBoundParameters(bool boundToInstance, UsdDevice* device); static constexpr ComponentPair componentParamNames[] = { ComponentPair(UsdMaterialDataComponents::COLOR, "color"), ComponentPair(UsdMaterialDataComponents::COLOR, "baseColor"), ComponentPair(UsdMaterialDataComponents::OPACITY, "opacity"), ComponentPair(UsdMaterialDataComponents::EMISSIVE, "emissive"), ComponentPair(UsdMaterialDataComponents::EMISSIVEFACTOR, "emissiveIntensity"), ComponentPair(UsdMaterialDataComponents::ROUGHNESS, "roughness"), ComponentPair(UsdMaterialDataComponents::METALLIC, "metallic"), ComponentPair(UsdMaterialDataComponents::IOR, "ior")}; protected: using MaterialInputAttribNamePair = std::pair<MaterialDMI, const char*>; template<typename ValueType> bool getMaterialInputSourceName(const UsdMaterialMultiTypeParameter<ValueType>& param, MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo); template<typename ValueType> bool getSamplerRefData(const UsdMaterialMultiTypeParameter<ValueType>& param, double refTimeStep, MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo); template<typename ValueType> void assignParameterToMaterialInput( const UsdMaterialMultiTypeParameter<ValueType>& param, UsdBridgeMaterialData::MaterialInput<ValueType>& matInput, const UsdLogInfo& logInfo); bool deferCommit(UsdDevice* device) override; bool doCommitData(UsdDevice* device) override; void doCommitRefs(UsdDevice* device) override; void setMaterialTimeVarying(UsdBridgeMaterialData::DataMemberId& timeVarying); bool isPbr = false; bool perInstance = false; // Whether material is attached to a point instancer bool instanceAttributeAttached = false; // Whether a value to any parameter has been set which in USD is different between per-instance and regular geometries OptionalList<MaterialInputAttribNamePair> materialInputAttributes; OptionalList<UsdSamplerHandle> samplerHandles; OptionalList<UsdSamplerRefData> samplerRefDatas; };
4,548
C
39.981982
162
0.769789
NVIDIA-Omniverse/AnariUsdDevice/UsdMaterial.cpp
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #include "UsdMaterial.h" #include "UsdAnari.h" #include "UsdDevice.h" #include "UsdSampler.h" #include "UsdDataArray.h" #define SamplerType ANARI_SAMPLER using SamplerUsdType = AnariToUsdBridgedObject<SamplerType>::Type; #define REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO(ParamName, ParamType0, ParamData) \ REGISTER_PARAMETER_MULTITYPE_MACRO(ParamName, ParamType0, SamplerType, ANARI_STRING, ParamData) DEFINE_PARAMETER_MAP(UsdMaterial, REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name) REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName) REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep) REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying) REGISTER_PARAMETER_MACRO("usd::time.sampler.color", ANARI_FLOAT64, colorSamplerTimeStep) REGISTER_PARAMETER_MACRO("usd::time.sampler.baseColor", ANARI_FLOAT64, colorSamplerTimeStep) REGISTER_PARAMETER_MACRO("usd::time.sampler.opacity", ANARI_FLOAT64, opacitySamplerTimeStep) REGISTER_PARAMETER_MACRO("usd::time.sampler.emissive", ANARI_FLOAT64, emissiveSamplerTimeStep) REGISTER_PARAMETER_MACRO("usd::time.sampler.emissiveIntensity", ANARI_FLOAT64, emissiveIntensitySamplerTimeStep) REGISTER_PARAMETER_MACRO("usd::time.sampler.roughness", ANARI_FLOAT64, roughnessSamplerTimeStep) REGISTER_PARAMETER_MACRO("usd::time.sampler.metallic", ANARI_FLOAT64, metallicSamplerTimeStep) REGISTER_PARAMETER_MACRO("usd::time.sampler.ior", ANARI_FLOAT64, iorSamplerTimeStep) REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("color", ANARI_FLOAT32_VEC3, color) REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("baseColor", ANARI_FLOAT32_VEC3, color) REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("opacity", ANARI_FLOAT32, opacity) REGISTER_PARAMETER_MACRO("alphaMode", ANARI_STRING, alphaMode) REGISTER_PARAMETER_MACRO("alphaCutoff", ANARI_FLOAT32, alphaCutoff) REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("emissive", ANARI_FLOAT32_VEC3, emissiveColor) REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("emissiveIntensity", ANARI_FLOAT32, emissiveIntensity) REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("roughness", ANARI_FLOAT32, roughness) REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("metallic", ANARI_FLOAT32, metallic) REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("ior", ANARI_FLOAT32, ior) ) constexpr UsdMaterial::ComponentPair UsdMaterial::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays using DMI = UsdMaterial::MaterialDMI; UsdMaterial::UsdMaterial(const char* name, const char* type, UsdDevice* device) : BridgedBaseObjectType(ANARI_MATERIAL, name, device) { if (strEquals(type, "matte")) { isPbr = false; } else if (strEquals(type, "physicallyBased")) { isPbr = true; } else { device->reportStatus(this, ANARI_MATERIAL, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdMaterial '%s' intialization error: unknown material type", getName()); } } UsdMaterial::~UsdMaterial() { #ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME if(cachedBridge) cachedBridge->DeleteMaterial(usdHandle); #endif } void UsdMaterial::remove(UsdDevice* device) { applyRemoveFunc(device, &UsdBridge::DeleteMaterial); } template<typename ValueType> bool UsdMaterial::getMaterialInputSourceName(const UsdMaterialMultiTypeParameter<ValueType>& param, MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo) { bool hasPositionAttrib = false; UsdSharedString* anariAttribStr = nullptr; param.Get(anariAttribStr); const char* anariAttrib = UsdSharedString::c_str(anariAttribStr); if(anariAttrib) { hasPositionAttrib = strEquals(anariAttrib, "objectPosition"); if( hasPositionAttrib && instanceAttributeAttached) { // In case of a per-instance specific attribute name, there can be only one change of the attribute name. // Otherwise there is a risk of the material attribute being used for two differently named attributes. reportStatusThroughDevice(logInfo, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT, "UsdMaterial '%s' binds one of its parameters to %s, but is transitively bound to both an instanced geometry (cones, spheres, cylinders) and regular geometry. \ This is incompatible with USD, which demands a differently bound name for those categories. \ Please create two different samplers and bind each to only one of both categories of geometry. \ The parameter value will be updated, but may therefore invalidate previous bindings to the objectPosition attribute.", logInfo.sourceName, "'objectPosition'"); } const char* usdAttribName = AnariAttributeToUsdName(anariAttrib, perInstance, logInfo); materialInputAttributes.push_back(UsdBridge::MaterialInputAttribName(dataMemberId, usdAttribName)); } return hasPositionAttrib; } template<typename ValueType> bool UsdMaterial::getSamplerRefData(const UsdMaterialMultiTypeParameter<ValueType>& param, double refTimeStep, MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo) { UsdSampler* sampler = nullptr; param.Get(sampler); if(sampler) { const UsdSamplerData& samplerParamData = sampler->getReadParams(); double worldTimeStep = device->getReadParams().timeStep; double samplerObjTimeStep = samplerParamData.timeStep; double samplerRefTime = selectRefTime(refTimeStep, samplerObjTimeStep, worldTimeStep); // Reading child (sampler) data in the material has the consequence that the sampler's parameters as they were last committed are in effect "part of" the material parameter set, at this point of commit. // So in case a sampler at a particular timestep is referenced from a material at two different world timesteps // - ie. for this world timestep, a particular timestep of an image already committed and subsequently referenced at some other previous world timestep is reused - // the user needs to make sure that not only the timestep is set correctly on the sampler for the commit (which is by itself lightweight, as it does not trigger a full commit), // but also that the parameters read here have been re-set on the sampler to the values belonging to the referenced timestep, as if there is no USD representation of a sampler object. // Setting those parameters will in turn trigger a full commit of the sampler object, which is in theory inefficient. // However, in case of a sampler this is not a problem in practice; data transfer is only a concern when the filename is *not* set, at which point a relative file corresponding // to the sampler timestep will be automatically chosen and set for the material, without the sampler object requiring any updates. // In case a filename *is* set, only the filename is used and no data transfer/file io operations are performed. //const char* imageUrl = UsdSharedString::c_str(samplerParamData.imageUrl); // not required anymore since all materials are a graph int imageNumComponents = 4; if(samplerParamData.imageData) { imageNumComponents = static_cast<int>(anari::componentsOf(samplerParamData.imageData->getType())); } UsdSamplerRefData samplerRefData = {imageNumComponents, samplerRefTime, dataMemberId}; samplerHandles.push_back(sampler->getUsdHandle()); samplerRefDatas.push_back(samplerRefData); } return false; } template<typename ValueType> void UsdMaterial::assignParameterToMaterialInput(const UsdMaterialMultiTypeParameter<ValueType>& param, UsdBridgeMaterialData::MaterialInput<ValueType>& matInput, const UsdLogInfo& logInfo) { param.Get(matInput.Value); UsdSharedString* anariAttribStr = nullptr; matInput.SrcAttrib = param.Get(anariAttribStr) ? AnariAttributeToUsdName(anariAttribStr->c_str(), perInstance, logInfo) : nullptr; UsdSampler* sampler = nullptr; matInput.Sampler = param.Get(sampler); } void UsdMaterial::updateBoundParameters(bool boundToInstance, UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); const UsdMaterialData& paramData = getReadParams(); if(perInstance != boundToInstance) { UsdLogInfo logInfo = {device, this, ANARI_MATERIAL, getName()}; double worldTimeStep = device->getReadParams().timeStep; double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep); // Fix up any parameters that have a geometry-type-dependent name set as source attribute materialInputAttributes.clear(); bool hasPositionAttrib = getMaterialInputSourceName(paramData.color, DMI::DIFFUSE, device, logInfo) || getMaterialInputSourceName(paramData.opacity, DMI::OPACITY, device, logInfo) || getMaterialInputSourceName(paramData.emissiveColor, DMI::EMISSIVECOLOR, device, logInfo) || getMaterialInputSourceName(paramData.emissiveIntensity, DMI::EMISSIVEINTENSITY, device, logInfo) || getMaterialInputSourceName(paramData.roughness, DMI::ROUGHNESS, device, logInfo) || getMaterialInputSourceName(paramData.metallic, DMI::METALLIC, device, logInfo) || getMaterialInputSourceName(paramData.ior, DMI::IOR, device, logInfo); DMI timeVarying; setMaterialTimeVarying(timeVarying); // Fixup attribute name and type depending on the newly bound geometry if(materialInputAttributes.size()) usdBridge->ChangeMaterialInputAttributes(usdHandle, materialInputAttributes.data(), materialInputAttributes.size(), dataTimeStep, timeVarying); if(hasPositionAttrib) instanceAttributeAttached = true; // As soon as any parameter is set to a position attribute, the geometry type for this material is 'locked-in' perInstance = boundToInstance; } if(paramData.color.type == SamplerType) { UsdSampler* colorSampler = nullptr; if (paramData.color.Get(colorSampler)) { colorSampler->updateBoundParameters(boundToInstance, device); } } } bool UsdMaterial::deferCommit(UsdDevice* device) { //const UsdMaterialData& paramData = getReadParams(); //if(UsdObjectNotInitialized<SamplerUsdType>(paramData.color.type == SamplerType)) //{ // return true; //} return false; } bool UsdMaterial::doCommitData(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); if(!device->getReadParams().outputMaterial) return false; bool isNew = false; if (!usdHandle.value) isNew = usdBridge->CreateMaterial(getName(), usdHandle); if (paramChanged || isNew) { const UsdMaterialData& paramData = getReadParams(); double worldTimeStep = device->getReadParams().timeStep; double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep); UsdBridgeMaterialData matData; matData.IsPbr = isPbr; matData.AlphaMode = AnariToUsdAlphaMode(UsdSharedString::c_str(paramData.alphaMode)); matData.AlphaCutoff = paramData.alphaCutoff; UsdLogInfo logInfo = {device, this, ANARI_MATERIAL, getName()}; assignParameterToMaterialInput(paramData.color, matData.Diffuse, logInfo); assignParameterToMaterialInput(paramData.opacity, matData.Opacity, logInfo); assignParameterToMaterialInput(paramData.emissiveColor, matData.Emissive, logInfo); assignParameterToMaterialInput(paramData.emissiveIntensity, matData.EmissiveIntensity, logInfo); assignParameterToMaterialInput(paramData.roughness, matData.Roughness, logInfo); assignParameterToMaterialInput(paramData.metallic, matData.Metallic, logInfo); assignParameterToMaterialInput(paramData.ior, matData.Ior, logInfo); setMaterialTimeVarying(matData.TimeVarying); usdBridge->SetMaterialData(usdHandle, matData, dataTimeStep); paramChanged = false; return paramData.color.type == SamplerType; // Only commit refs when material actually contains a texture (filename param from diffusemap is required) } return false; } void UsdMaterial::doCommitRefs(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); const UsdMaterialData& paramData = getReadParams(); double worldTimeStep = device->getReadParams().timeStep; samplerHandles.clear(); samplerRefDatas.clear(); UsdLogInfo logInfo = {device, this, ANARI_MATERIAL, getName()}; getSamplerRefData(paramData.color, paramData.colorSamplerTimeStep, DMI::DIFFUSE, device, logInfo); getSamplerRefData(paramData.opacity, paramData.opacitySamplerTimeStep, DMI::OPACITY, device, logInfo); getSamplerRefData(paramData.emissiveColor, paramData.emissiveSamplerTimeStep, DMI::EMISSIVECOLOR, device, logInfo); getSamplerRefData(paramData.emissiveIntensity, paramData.emissiveIntensitySamplerTimeStep, DMI::EMISSIVEINTENSITY, device, logInfo); getSamplerRefData(paramData.roughness, paramData.roughnessSamplerTimeStep, DMI::ROUGHNESS, device, logInfo); getSamplerRefData(paramData.metallic, paramData.metallicSamplerTimeStep, DMI::METALLIC, device, logInfo); getSamplerRefData(paramData.ior, paramData.iorSamplerTimeStep, DMI::IOR, device, logInfo); if(samplerHandles.size()) usdBridge->SetSamplerRefs(usdHandle, samplerHandles.data(), samplerHandles.size(), worldTimeStep, samplerRefDatas.data()); else usdBridge->DeleteSamplerRefs(usdHandle, worldTimeStep); } void UsdMaterial::setMaterialTimeVarying(UsdBridgeMaterialData::DataMemberId& timeVarying) { timeVarying = DMI::ALL & (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::DIFFUSE) & (isTimeVarying(CType::OPACITY) ? DMI::ALL : ~DMI::OPACITY) & (isTimeVarying(CType::EMISSIVE) ? DMI::ALL : ~DMI::EMISSIVECOLOR) & (isTimeVarying(CType::EMISSIVEFACTOR) ? DMI::ALL : ~DMI::EMISSIVEINTENSITY) & (isTimeVarying(CType::ROUGHNESS) ? DMI::ALL : ~DMI::ROUGHNESS) & (isTimeVarying(CType::METALLIC) ? DMI::ALL : ~DMI::METALLIC) & (isTimeVarying(CType::IOR) ? DMI::ALL : ~DMI::IOR); }
13,810
C++
45.190635
207
0.767343
NVIDIA-Omniverse/AnariUsdDevice/UsdWorld.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBridgedBaseObject.h" class UsdDataArray; enum class UsdWorldComponents { INSTANCES = 0, SURFACES, VOLUMES }; struct UsdWorldData { UsdSharedString* name = nullptr; UsdSharedString* usdName = nullptr; int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying. UsdDataArray* instances = nullptr; UsdDataArray* surfaces = nullptr; UsdDataArray* volumes = nullptr; }; class UsdWorld : public UsdBridgedBaseObject<UsdWorld, UsdWorldData, UsdWorldHandle, UsdWorldComponents> { public: UsdWorld(const char* name, UsdDevice* device); ~UsdWorld(); void remove(UsdDevice* device) override; static constexpr ComponentPair componentParamNames[] = { ComponentPair(UsdWorldComponents::INSTANCES, "instance"), ComponentPair(UsdWorldComponents::SURFACES, "surface"), ComponentPair(UsdWorldComponents::VOLUMES, "volume")}; protected: bool deferCommit(UsdDevice* device) override; bool doCommitData(UsdDevice* device) override; void doCommitRefs(UsdDevice* device) override; std::vector<UsdInstanceHandle> instanceHandles; // for convenience std::vector<UsdSurfaceHandle> surfaceHandles; // for convenience std::vector<UsdVolumeHandle> volumeHandles; // for convenience };
1,375
C
26.519999
104
0.749818
NVIDIA-Omniverse/AnariUsdDevice/UsdLight.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBridgedBaseObject.h" struct UsdLightData { UsdSharedString* name = nullptr; UsdSharedString* usdName = nullptr; }; class UsdLight : public UsdBridgedBaseObject<UsdLight, UsdLightData, UsdLightHandle> { public: UsdLight(const char* name, UsdDevice* device); ~UsdLight(); void remove(UsdDevice* device) override; protected: bool deferCommit(UsdDevice* device) override; bool doCommitData(UsdDevice* device) override; void doCommitRefs(UsdDevice* device) override {} };
612
C
20.892856
84
0.73366
NVIDIA-Omniverse/AnariUsdDevice/UsdFrame.cpp
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #include "UsdFrame.h" #include "UsdBridge/UsdBridge.h" #include "UsdAnari.h" #include "UsdDevice.h" #include "anari/frontend/type_utility.h" DEFINE_PARAMETER_MAP(UsdFrame, REGISTER_PARAMETER_MACRO("world", ANARI_WORLD, world) REGISTER_PARAMETER_MACRO("renderer", ANARI_RENDERER, renderer) REGISTER_PARAMETER_MACRO("size", ANARI_UINT32_VEC2, size) REGISTER_PARAMETER_MACRO("channel.color", ANARI_DATA_TYPE, color) REGISTER_PARAMETER_MACRO("channel.depth", ANARI_DATA_TYPE, depth) ) UsdFrame::UsdFrame(UsdBridge* bridge) : UsdParameterizedBaseObject<UsdFrame, UsdFrameData>(ANARI_FRAME) { } UsdFrame::~UsdFrame() { delete[] mappedColorMem; delete[] mappedDepthMem; } bool UsdFrame::deferCommit(UsdDevice* device) { return false; } bool UsdFrame::doCommitData(UsdDevice* device) { return false; } const void* UsdFrame::mapBuffer(const char *channel, uint32_t *width, uint32_t *height, ANARIDataType *pixelType) { const UsdFrameData& paramData = getReadParams(); *width = paramData.size.Data[0]; *height = paramData.size.Data[1]; *pixelType = ANARI_UNKNOWN; if (strEquals(channel, "channel.color")) { mappedColorMem = ReserveBuffer(paramData.color); *pixelType = paramData.color; return mappedColorMem; } else if (strEquals(channel, "channel.depth")) { mappedDepthMem = ReserveBuffer(paramData.depth); *pixelType = paramData.depth; return mappedDepthMem; } *width = 0; *height = 0; return nullptr; } void UsdFrame::unmapBuffer(const char *channel) { if (strEquals(channel, "channel.color")) { delete[] mappedColorMem; mappedColorMem = nullptr; } else if (strEquals(channel, "channel.depth")) { delete[] mappedDepthMem; mappedDepthMem = nullptr; } } char* UsdFrame::ReserveBuffer(ANARIDataType format) { const UsdFrameData& paramData = getReadParams(); size_t formatSize = anari::sizeOf(format); size_t memSize = formatSize * paramData.size.Data[0] * paramData.size.Data[1]; return new char[memSize]; } void UsdFrame::saveUsd(UsdDevice* device) { device->getUsdBridge()->SaveScene(); }
2,184
C++
22
80
0.717491
NVIDIA-Omniverse/AnariUsdDevice/UsdSampler.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBridgedBaseObject.h" enum class UsdSamplerComponents { DATA = 0, WRAPS, WRAPT, WRAPR }; struct UsdSamplerData { UsdSharedString* name = nullptr; UsdSharedString* usdName = nullptr; double timeStep = 0.0; int timeVarying = 0; // Bitmask indicating which attributes are time-varying. const UsdDataArray* imageData = nullptr; UsdSharedString* inAttribute = nullptr; UsdSharedString* imageUrl = nullptr; UsdSharedString* wrapS = nullptr; UsdSharedString* wrapT = nullptr; UsdSharedString* wrapR = nullptr; }; class UsdSampler : public UsdBridgedBaseObject<UsdSampler, UsdSamplerData, UsdSamplerHandle, UsdSamplerComponents> { protected: enum SamplerType { SAMPLER_UNKNOWN = 0, SAMPLER_1D, SAMPLER_2D, SAMPLER_3D }; public: UsdSampler(const char* name, const char* type, UsdDevice* device); ~UsdSampler(); void remove(UsdDevice* device) override; bool isPerInstance() const { return perInstance; } void updateBoundParameters(bool boundToInstance, UsdDevice* device); static constexpr ComponentPair componentParamNames[] = { ComponentPair(CType::DATA, "image"), ComponentPair(CType::DATA, "imageUrl"), ComponentPair(CType::WRAPS, "wrapMode"), ComponentPair(CType::WRAPS, "wrapMode1"), ComponentPair(CType::WRAPT, "wrapMode2"), ComponentPair(CType::WRAPR, "wrapMode3")}; protected: bool deferCommit(UsdDevice* device) override; bool doCommitData(UsdDevice* device) override; void doCommitRefs(UsdDevice* device) override {} void setSamplerTimeVarying(UsdBridgeSamplerData::DataMemberId& timeVarying); SamplerType samplerType = SAMPLER_UNKNOWN; bool perInstance = false; // Whether sampler is attached to a point instancer bool instanceAttributeAttached = false; // Whether a value to inAttribute has been set which in USD is different between per-instance and regular geometries };
2,050
C
27.486111
160
0.725854
NVIDIA-Omniverse/AnariUsdDevice/UsdInstance.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBridgedBaseObject.h" class UsdGroup; enum class UsdInstanceComponents { GROUP = 0, TRANSFORM }; struct UsdInstanceData { UsdSharedString* name = nullptr; UsdSharedString* usdName = nullptr; int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying. UsdGroup* group = nullptr; UsdFloatMat4 transform; }; class UsdInstance : public UsdBridgedBaseObject<UsdInstance, UsdInstanceData, UsdInstanceHandle, UsdInstanceComponents> { public: UsdInstance(const char* name, UsdDevice* device); ~UsdInstance(); void remove(UsdDevice* device) override; static constexpr ComponentPair componentParamNames[] = { ComponentPair(UsdInstanceComponents::GROUP, "group"), ComponentPair(UsdInstanceComponents::TRANSFORM, "transform")}; protected: bool deferCommit(UsdDevice* device) override; bool doCommitData(UsdDevice* device) override; void doCommitRefs(UsdDevice* device) override; };
1,070
C
23.906976
119
0.750467
NVIDIA-Omniverse/AnariUsdDevice/UsdDataArray.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBaseObject.h" #include "UsdParameterizedObject.h" #include "anari/frontend/anari_enums.h" class UsdDevice; struct UsdDataLayout { bool isDense() const { return byteStride1 == typeSize && byteStride2 == numItems1*byteStride1 && byteStride3 == numItems2*byteStride2; } bool isOneDimensional() const { return numItems2 == 1 && numItems3 == 1; } void copyDims(uint64_t dims[3]) const { std::memcpy(dims, &numItems1, sizeof(uint64_t)*3); } void copyStride(int64_t stride[3]) const { std::memcpy(stride, &byteStride1, sizeof(int64_t)*3); } uint64_t typeSize = 0; uint64_t numItems1 = 0; uint64_t numItems2 = 0; uint64_t numItems3 = 0; int64_t byteStride1 = 0; int64_t byteStride2 = 0; int64_t byteStride3 = 0; }; struct UsdDataArrayParams { // Even though we are not dealing with a usd-backed object, the data array can still have an identifying name. // The pointer can then be used as id for resources (plus defining their filenames) such as textures, // so they can be shared and still removed during garbage collection (after an UsdAnari object has already been destroyed). // The persistence reason is why these strings have to be added to the string list of the device on construction. UsdSharedString* name = nullptr; UsdSharedString* usdName = nullptr; }; class UsdDataArray : public UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams> { public: UsdDataArray(const void *appMemory, ANARIMemoryDeleter deleter, const void *userData, ANARIDataType dataType, uint64_t numItems1, int64_t byteStride1, uint64_t numItems2, int64_t byteStride2, uint64_t numItems3, int64_t byteStride3, UsdDevice* device ); UsdDataArray(ANARIDataType dataType, uint64_t numItems1, uint64_t numItems2, uint64_t numItems3, UsdDevice* device ); ~UsdDataArray(); void filterSetParam(const char *name, ANARIDataType type, const void *mem, UsdDevice* device) override; int getProperty(const char *name, ANARIDataType type, void *mem, uint64_t size, UsdDevice* device) override; void commit(UsdDevice* device) override; void remove(UsdDevice* device) override {} void* map(UsdDevice* device); void unmap(UsdDevice* device); void privatize(); const char* getName() const override { return UsdSharedString::c_str(getReadParams().usdName); } const void* getData() const { return data; } ANARIDataType getType() const { return type; } const UsdDataLayout& getLayout() const { return layout; } size_t getDataSizeInBytes() const { return dataSizeInBytes; } protected: bool deferCommit(UsdDevice* device) override { return false; } bool doCommitData(UsdDevice* device) override { return false; } void doCommitRefs(UsdDevice* device) override {} void setLayoutAndSize(uint64_t numItems1, int64_t byteStride1, uint64_t numItems2, int64_t byteStride2, uint64_t numItems3, int64_t byteStride3); bool CheckFormatting(UsdDevice* device); // Ref manipulation on arrays of anariobjects void incRef(const ANARIObject* anariObjects, uint64_t numAnariObjects); void decRef(const ANARIObject* anariObjects, uint64_t numAnariObjects); // Private memory management void allocPrivateData(); void freePrivateData(bool mappedCopy = false); void freePublicData(const void* appMemory); void publicToPrivateData(); // Mapped memory management void CreateMappedObjectCopy(); void TransferAndRemoveMappedObjectCopy(); const void* data = nullptr; ANARIMemoryDeleter dataDeleter = nullptr; const void* deleterUserData = nullptr; ANARIDataType type; UsdDataLayout layout; size_t dataSizeInBytes; bool isPrivate; const void* mappedObjectCopy; #ifdef CHECK_MEMLEAKS UsdDevice* allocDevice; #endif };
4,032
C
30.263566
138
0.708829
NVIDIA-Omniverse/AnariUsdDevice/UsdDeviceQueries.h
// Copyright 2021 The Khronos Group // SPDX-License-Identifier: Apache-2.0 // This file was generated by generate_queries.py // Don't make changes to this directly #include <anari/anari.h> namespace anari { namespace usd { #define ANARI_INFO_required 0 #define ANARI_INFO_default 1 #define ANARI_INFO_minimum 2 #define ANARI_INFO_maximum 3 #define ANARI_INFO_description 4 #define ANARI_INFO_elementType 5 #define ANARI_INFO_value 6 #define ANARI_INFO_sourceExtension 7 #define ANARI_INFO_extension 8 #define ANARI_INFO_parameter 9 #define ANARI_INFO_channel 10 #define ANARI_INFO_use 11 const int extension_count = 17; const char ** query_extensions(); const char ** query_object_types(ANARIDataType type); const ANARIParameter * query_params(ANARIDataType type, const char *subtype); const void * query_param_info_enum(ANARIDataType type, const char *subtype, const char *paramName, ANARIDataType paramType, int infoName, ANARIDataType infoType); const void * query_param_info(ANARIDataType type, const char *subtype, const char *paramName, ANARIDataType paramType, const char *infoNameString, ANARIDataType infoType); const void * query_object_info_enum(ANARIDataType type, const char *subtype, int infoName, ANARIDataType infoType); const void * query_object_info(ANARIDataType type, const char *subtype, const char *infoNameString, ANARIDataType infoType); } }
1,368
C
41.781249
171
0.790205
NVIDIA-Omniverse/AnariUsdDevice/UsdDevice.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "anari/backend/DeviceImpl.h" #include "anari/backend/LibraryImpl.h" #include "UsdBaseObject.h" #include <vector> #include <memory> #ifdef _WIN32 #ifdef anari_library_usd_EXPORTS #define USDDevice_INTERFACE __declspec(dllexport) #else #define USDDevice_INTERFACE __declspec(dllimport) #endif #endif extern "C" { #ifdef WIN32 USDDevice_INTERFACE void __cdecl anari_library_usd_init(); #else void anari_library_usd_init(); #endif } class UsdDevice; class UsdDeviceInternals; class UsdBaseObject; class UsdVolume; struct UsdDeviceData { UsdSharedString* hostName = nullptr; UsdSharedString* outputPath = nullptr; bool createNewSession = true; bool outputBinary = false; bool writeAtCommit = false; double timeStep = 0.0; bool outputMaterial = true; bool outputPreviewSurfaceShader = true; bool outputMdlShader = true; }; class UsdDevice : public anari::DeviceImpl, public UsdParameterizedBaseObject<UsdDevice, UsdDeviceData> { public: UsdDevice(); UsdDevice(ANARILibrary library); ~UsdDevice(); /////////////////////////////////////////////////////////////////////////// // Main virtual interface to accepting API calls /////////////////////////////////////////////////////////////////////////// // Data Arrays //////////////////////////////////////////////////////////// ANARIArray1D newArray1D(const void *appMemory, ANARIMemoryDeleter deleter, const void *userdata, ANARIDataType, uint64_t numItems1) override; ANARIArray2D newArray2D(const void *appMemory, ANARIMemoryDeleter deleter, const void *userdata, ANARIDataType, uint64_t numItems1, uint64_t numItems2) override; ANARIArray3D newArray3D(const void *appMemory, ANARIMemoryDeleter deleter, const void *userdata, ANARIDataType, uint64_t numItems1, uint64_t numItems2, uint64_t numItems3) override; void* mapArray(ANARIArray) override; void unmapArray(ANARIArray) override; // Renderable Objects ///////////////////////////////////////////////////// ANARILight newLight(const char *type) override { return nullptr; } ANARICamera newCamera(const char *type) override; ANARIGeometry newGeometry(const char *type); ANARISpatialField newSpatialField(const char *type) override; ANARISurface newSurface() override; ANARIVolume newVolume(const char *type) override; // Model Meta-Data //////////////////////////////////////////////////////// ANARIMaterial newMaterial(const char *material_type) override; ANARISampler newSampler(const char *type) override; // Instancing ///////////////////////////////////////////////////////////// ANARIGroup newGroup() override; ANARIInstance newInstance(const char *type) override; // Top-level Worlds /////////////////////////////////////////////////////// ANARIWorld newWorld() override; // Query functions //////////////////////////////////////////////////////// const char ** getObjectSubtypes(ANARIDataType objectType) override; const void* getObjectInfo(ANARIDataType objectType, const char* objectSubtype, const char* infoName, ANARIDataType infoType) override; const void* getParameterInfo(ANARIDataType objectType, const char* objectSubtype, const char* parameterName, ANARIDataType parameterType, const char* infoName, ANARIDataType infoType) override; // Object + Parameter Lifetime Management ///////////////////////////////// void setParameter(ANARIObject object, const char *name, ANARIDataType type, const void *mem) override; void unsetParameter(ANARIObject object, const char *name) override; void unsetAllParameters(ANARIObject o) override; void* mapParameterArray1D(ANARIObject o, const char* name, ANARIDataType dataType, uint64_t numElements1, uint64_t *elementStride) override; void* mapParameterArray2D(ANARIObject o, const char* name, ANARIDataType dataType, uint64_t numElements1, uint64_t numElements2, uint64_t *elementStride) override; void* mapParameterArray3D(ANARIObject o, const char* name, ANARIDataType dataType, uint64_t numElements1, uint64_t numElements2, uint64_t numElements3, uint64_t *elementStride) override; void unmapParameterArray(ANARIObject o, const char* name) override; void commitParameters(ANARIObject object) override; void release(ANARIObject _obj) override; void retain(ANARIObject _obj) override; // Object Query Interface ///////////////////////////////////////////////// int getProperty(ANARIObject object, const char *name, ANARIDataType type, void *mem, uint64_t size, uint32_t mask) override; // FrameBuffer Manipulation /////////////////////////////////////////////// ANARIFrame newFrame() override; const void *frameBufferMap(ANARIFrame fb, const char *channel, uint32_t *width, uint32_t *height, ANARIDataType *pixelType) override; void frameBufferUnmap(ANARIFrame fb, const char *channel) override; // Frame Rendering //////////////////////////////////////////////////////// ANARIRenderer newRenderer(const char *type) override; void renderFrame(ANARIFrame frame) override; int frameReady(ANARIFrame, ANARIWaitMask) override { return 1; } void discardFrame(ANARIFrame) override {} // UsdParameterizedBaseObject interface /////////////////////////////////////////////////////////// void filterSetParam( const char *name, ANARIDataType type, const void *mem, UsdDevice* device) override; void filterResetParam( const char *name) override; void commit(UsdDevice* device) override; void remove(UsdDevice* device) override {} // USD Specific /////////////////////////////////////////////////////////// bool isInitialized() { return getUsdBridge() != nullptr; } UsdBridge* getUsdBridge(); bool nameExists(const char* name); void addToCommitList(UsdBaseObject* object, bool commitData); bool isFlushingCommitList() const { return lockCommitList; } void addToVolumeList(UsdVolume* volume); void removeFromVolumeList(UsdVolume* volume); // Allows for selected strings to persist, // so their pointers can be cached beyond their containing objects' lifetimes, // to be used for garbage collecting resource files. void addToResourceStringList(UsdSharedString* sharedString); #ifdef CHECK_MEMLEAKS // Memleak checking void LogObjAllocation(const UsdBaseObject* ptr); void LogObjDeallocation(const UsdBaseObject* ptr); std::vector<const UsdBaseObject*> allocatedObjects; void LogStrAllocation(const UsdSharedString* ptr); void LogStrDeallocation(const UsdSharedString* ptr); std::vector<const UsdSharedString*> allocatedStrings; void LogRawAllocation(const void* ptr); void LogRawDeallocation(const void* ptr); std::vector<const void*> allocatedRawMemory; #endif void reportStatus(void* source, ANARIDataType sourceType, ANARIStatusSeverity severity, ANARIStatusCode statusCode, const char *format, ...); void reportStatus(void* source, ANARIDataType sourceType, ANARIStatusSeverity severity, ANARIStatusCode statusCode, const char *format, va_list& arglist); protected: UsdBaseObject* getBaseObjectPtr(ANARIObject object); // UsdParameterizedBaseObject interface /////////////////////////////////////////////////////////// bool deferCommit(UsdDevice* device) { return false; }; bool doCommitData(UsdDevice* device) { return false; }; void doCommitRefs(UsdDevice* device) {}; // USD Specific Cleanup ///////////////////////////////////////////////////////////// void clearCommitList(); void flushCommitList(); void clearDeviceParameters(); void clearResourceStringList(); void initializeBridge(); const char* makeUniqueName(const char* name); ANARIArray CreateDataArray(const void *appMemory, ANARIMemoryDeleter deleter, const void *userData, ANARIDataType dataType, uint64_t numItems1, int64_t byteStride1, uint64_t numItems2, int64_t byteStride2, uint64_t numItems3, int64_t byteStride3); template<int typeInt> void writeTypeToUsd(); void removePrimsFromUsd(bool onlyRemoveHandles = false); std::unique_ptr<UsdDeviceInternals> internals; bool bridgeInitAttempt = false; // Using object pointers as basis for deferred commits; another option would be to traverse // the bridge's internal cache handles, but a handle may map to multiple objects (with the same name) // so that's not 1-1 with the effects of a non-deferred commit order. using CommitListType = std::pair<helium::IntrusivePtr<UsdBaseObject>, bool>; std::vector<CommitListType> commitList; std::vector<UsdBaseObject*> removeList; std::vector<UsdVolume*> volumeList; // Tracks all volumes to auto-commit when child fields have been committed bool lockCommitList = false; std::vector<helium::IntrusivePtr<UsdSharedString>> resourceStringList; ANARIStatusCallback statusFunc = nullptr; const void* statusUserData = nullptr; ANARIStatusCallback userSetStatusFunc = nullptr; const void* userSetStatusUserData = nullptr; std::vector<char> lastStatusMessage; };
9,712
C
30.031949
114
0.643637
NVIDIA-Omniverse/AnariUsdDevice/UsdCamera.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBaseObject.h" #include "UsdBridgedBaseObject.h" enum class UsdCameraComponents { VIEW = 0, PROJECTION }; struct UsdCameraData { UsdSharedString* name = nullptr; UsdSharedString* usdName = nullptr; int timeVarying = 0xFFFFFFFF; // TimeVarying bits UsdFloat3 position = {0.0f, 0.0f, 0.0f}; UsdFloat3 direction = {0.0f, 0.0f, -1.0f}; UsdFloat3 up = {0.0f, 1.0f, 0.0f}; UsdFloatBox2 imageRegion = {0.0f, 0.0f, 1.0f, 1.0f}; // perspective/orthographic float aspect = 1.0f; float near = 1.0f; float far = 10000; float fovy = M_PI/3.0f; float height = 1.0f; }; class UsdCamera : public UsdBridgedBaseObject<UsdCamera, UsdCameraData, UsdCameraHandle, UsdCameraComponents> { public: UsdCamera(const char* name, const char* type, UsdDevice* device); ~UsdCamera(); void remove(UsdDevice* device) override; enum CameraType { CAMERA_UNKNOWN = 0, CAMERA_PERSPECTIVE, CAMERA_ORTHOGRAPHIC }; static constexpr ComponentPair componentParamNames[] = { ComponentPair(UsdCameraComponents::VIEW, "view"), ComponentPair(UsdCameraComponents::PROJECTION, "projection")}; protected: bool deferCommit(UsdDevice* device) override; bool doCommitData(UsdDevice* device) override; void doCommitRefs(UsdDevice* device) override {} void copyParameters(UsdBridgeCameraData& camData); CameraType cameraType = CAMERA_UNKNOWN; };
1,521
C
23.548387
109
0.702827
NVIDIA-Omniverse/AnariUsdDevice/UsdDeviceUtils.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include <vector> #include <memory> template<typename ValueType, typename ContainerType = std::vector<ValueType>> struct OptionalList { void ensureList() { if(!list) list = std::make_unique<ContainerType>(); } void clear() { if(list) list->resize(0); } void push_back(const ValueType& value) { ensureList(); list->push_back(value); } void emplace_back(const ValueType& value) { ensureList(); list->emplace_back(value); } const ValueType* data() { if(list) return list->data(); return nullptr; } size_t size() { if(list) return list->size(); return 0; } std::unique_ptr<ContainerType> list; };
796
C
14.627451
77
0.614322
NVIDIA-Omniverse/AnariUsdDevice/UsdSurface.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBridgedBaseObject.h" #include <limits> class UsdGeometry; class UsdMaterial; struct UsdSurfaceData { UsdSharedString* name = nullptr; UsdSharedString* usdName = nullptr; // No timevarying data: geometry and material reference always set over all timesteps UsdGeometry* geometry = nullptr; UsdMaterial* material = nullptr; double geometryRefTimeStep = std::numeric_limits<float>::quiet_NaN(); double materialRefTimeStep = std::numeric_limits<float>::quiet_NaN(); }; class UsdSurface : public UsdBridgedBaseObject<UsdSurface, UsdSurfaceData, UsdSurfaceHandle> { public: UsdSurface(const char* name, UsdDevice* device); ~UsdSurface(); void remove(UsdDevice* device) override; protected: bool deferCommit(UsdDevice* device) override; bool doCommitData(UsdDevice* device) override; void doCommitRefs(UsdDevice* device) override; };
980
C
24.153846
92
0.753061
NVIDIA-Omniverse/AnariUsdDevice/UsdVolume.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBridgedBaseObject.h" #include <limits> class UsdSpatialField; class UsdDevice; class UsdDataArray; enum class UsdVolumeComponents { COLOR = 0, OPACITY, VALUERANGE }; struct UsdVolumeData { UsdSharedString* name = nullptr; UsdSharedString* usdName = nullptr; int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying. (field reference always set over all timesteps) UsdSpatialField* field = nullptr; double fieldRefTimeStep = std::numeric_limits<float>::quiet_NaN(); bool preClassified = false; //TF params const UsdDataArray* color = nullptr; const UsdDataArray* opacity = nullptr; UsdFloatBox1 valueRange = { 0.0f, 1.0f }; float unitDistance = 1.0f; }; class UsdVolume : public UsdBridgedBaseObject<UsdVolume, UsdVolumeData, UsdVolumeHandle, UsdVolumeComponents> { public: UsdVolume(const char* name, UsdDevice* device); ~UsdVolume(); void remove(UsdDevice* device) override; static constexpr ComponentPair componentParamNames[] = { ComponentPair(UsdVolumeComponents::COLOR, "color"), ComponentPair(UsdVolumeComponents::OPACITY, "opacity"), ComponentPair(UsdVolumeComponents::VALUERANGE, "valueRange")}; protected: bool deferCommit(UsdDevice* device) override; bool doCommitData(UsdDevice* device) override; void doCommitRefs(UsdDevice* device) override {} bool CheckTfParams(UsdDevice* device); bool UpdateVolume(UsdDevice* device, const char* debugName); UsdSpatialField* prevField = nullptr; UsdDevice* usdDevice = nullptr; };
1,669
C
25.507936
136
0.742361
NVIDIA-Omniverse/AnariUsdDevice/UsdDataArray.cpp
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #include "UsdDataArray.h" #include "UsdDevice.h" #include "UsdAnari.h" #include "anari/frontend/type_utility.h" DEFINE_PARAMETER_MAP(UsdDataArray, REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name) REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName) ) #define TO_OBJ_PTR reinterpret_cast<const ANARIObject*> UsdDataArray::UsdDataArray(const void *appMemory, ANARIMemoryDeleter deleter, const void *userData, ANARIDataType dataType, uint64_t numItems1, int64_t byteStride1, uint64_t numItems2, int64_t byteStride2, uint64_t numItems3, int64_t byteStride3, UsdDevice* device ) : UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams>(ANARI_ARRAY) , data(appMemory) , dataDeleter(deleter) , deleterUserData(userData) , type(dataType) , isPrivate(false) #ifdef CHECK_MEMLEAKS , allocDevice(device) #endif { setLayoutAndSize(numItems1, byteStride1, numItems2, byteStride2, numItems3, byteStride3); if (CheckFormatting(device)) { // Make sure to incref all anari objects in case of object array if (anari::isObject(type)) { incRef(TO_OBJ_PTR(data), layout.numItems1); } } } UsdDataArray::UsdDataArray(ANARIDataType dataType, uint64_t numItems1, uint64_t numItems2, uint64_t numItems3, UsdDevice* device) : UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams>(ANARI_ARRAY) , type(dataType) , isPrivate(true) #ifdef CHECK_MEMLEAKS , allocDevice(device) #endif { setLayoutAndSize(numItems1, 0, numItems2, 0, numItems3, 0); if (CheckFormatting(device)) { allocPrivateData(); } } UsdDataArray::~UsdDataArray() { // Decref anari objects in case of object array if (anari::isObject(type)) { decRef(TO_OBJ_PTR(data), layout.numItems1); } if (isPrivate) { freePrivateData(); } else { freePublicData(data); } } void UsdDataArray::filterSetParam(const char *name, ANARIDataType type, const void *mem, UsdDevice* device) { if(setNameParam(name, type, mem, device)) device->addToResourceStringList(getWriteParams().usdName); //Name is kept for the lifetime of the device (to allow using pointer for caching resource's names) } int UsdDataArray::getProperty(const char * name, ANARIDataType type, void * mem, uint64_t size, UsdDevice* device) { int nameResult = getNameProperty(name, type, mem, size, device); return nameResult; } void UsdDataArray::commit(UsdDevice* device) { if (anari::isObject(type) && (layout.numItems2 != 1 || layout.numItems3 != 1)) device->reportStatus(this, ANARI_ARRAY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdDataArray only supports one-dimensional ANARI_OBJECT arrays"); UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams>::commit(device); } void * UsdDataArray::map(UsdDevice * device) { if (anari::isObject(type)) { CreateMappedObjectCopy(); } return const_cast<void *>(data); } void UsdDataArray::unmap(UsdDevice * device) { if (anari::isObject(type)) { TransferAndRemoveMappedObjectCopy(); } } void UsdDataArray::privatize() { if(!isPrivate) { publicToPrivateData(); isPrivate = true; } } void UsdDataArray::setLayoutAndSize(uint64_t numItems1, int64_t byteStride1, uint64_t numItems2, int64_t byteStride2, uint64_t numItems3, int64_t byteStride3) { size_t typeSize = anari::sizeOf(type); if (byteStride1 == 0) byteStride1 = typeSize; if (byteStride2 == 0) byteStride2 = byteStride1 * numItems1; if (byteStride3 == 0) byteStride3 = byteStride2 * numItems2; dataSizeInBytes = byteStride3 * numItems3 - (byteStride1 - typeSize); layout = { typeSize, numItems1, numItems2, numItems3, byteStride1, byteStride2, byteStride3 }; } bool UsdDataArray::CheckFormatting(UsdDevice* device) { if (anari::isObject(type)) { if (!layout.isDense() || !layout.isOneDimensional()) { device->reportStatus(this, ANARI_ARRAY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdDataArray construction failed: arrays with object type have to be one dimensional and without stride."); layout.numItems1 = layout.numItems2 = layout.numItems3 = 0; data = nullptr; type = ANARI_UNKNOWN; return false; } } return true; } void UsdDataArray::incRef(const ANARIObject* anariObjects, uint64_t numAnariObjects) { for (int i = 0; i < numAnariObjects; ++i) { const UsdBaseObject* baseObj = (reinterpret_cast<const UsdBaseObject*>(anariObjects[i])); if (baseObj) baseObj->refInc(helium::RefType::INTERNAL); } } void UsdDataArray::decRef(const ANARIObject* anariObjects, uint64_t numAnariObjects) { for (int i = 0; i < numAnariObjects; ++i) { const UsdBaseObject* baseObj = (reinterpret_cast<const UsdBaseObject*>(anariObjects[i])); #ifdef CHECK_MEMLEAKS allocDevice->LogObjDeallocation(baseObj); #endif if (baseObj) { assert(baseObj->useCount(helium::RefType::INTERNAL) > 0); baseObj->refDec(helium::RefType::INTERNAL); } } } void UsdDataArray::allocPrivateData() { // Alloc the owned memory char* newData = new char[dataSizeInBytes]; memset(newData, 0, dataSizeInBytes); data = newData; #ifdef CHECK_MEMLEAKS allocDevice->LogRawAllocation(newData); #endif } void UsdDataArray::freePrivateData(bool mappedCopy) { const void*& memToFree = mappedCopy ? mappedObjectCopy : data; #ifdef CHECK_MEMLEAKS allocDevice->LogRawDeallocation(memToFree); #endif // Deallocate owned memory delete[](char*)memToFree; memToFree = nullptr; } void UsdDataArray::freePublicData(const void* appMemory) { if (dataDeleter) { dataDeleter(deleterUserData, appMemory); dataDeleter = nullptr; } } void UsdDataArray::publicToPrivateData() { // Alloc private dest, copy appMemory src to it const void* appMemory = data; allocPrivateData(); std::memcpy(const_cast<void *>(data), appMemory, dataSizeInBytes); // In case of object array, Refcount 'transfers' to the copy (splits off user-managed public refcount) // Delete appMemory if appropriate freePublicData(appMemory); // No refcount modification necessary, public refcount managed by user } void UsdDataArray::CreateMappedObjectCopy() { // Move the original array to a different spot and allocate new memory for the mapped object array. mappedObjectCopy = data; allocPrivateData(); // Transfer contents over to new memory, keep old one for managing references later on. std::memcpy(const_cast<void *>(data), mappedObjectCopy, dataSizeInBytes); } void UsdDataArray::TransferAndRemoveMappedObjectCopy() { const ANARIObject* newAnariObjects = TO_OBJ_PTR(data); const ANARIObject* oldAnariObjects = TO_OBJ_PTR(mappedObjectCopy); uint64_t numAnariObjects = layout.numItems1; // First, increase reference counts of all objects that different in the new object array for (int i = 0; i < numAnariObjects; ++i) { const UsdBaseObject* newObj = (reinterpret_cast<const UsdBaseObject*>(newAnariObjects[i])); const UsdBaseObject* oldObj = (reinterpret_cast<const UsdBaseObject*>(oldAnariObjects[i])); if (newObj != oldObj && newObj) newObj->refInc(helium::RefType::INTERNAL); } // Then, decrease reference counts of all objects that are different in the original array (which will delete those that not referenced anymore) for (int i = 0; i < numAnariObjects; ++i) { const UsdBaseObject* newObj = (reinterpret_cast<const UsdBaseObject*>(newAnariObjects[i])); const UsdBaseObject* oldObj = (reinterpret_cast<const UsdBaseObject*>(oldAnariObjects[i])); if (newObj != oldObj && oldObj) { #ifdef CHECK_MEMLEAKS allocDevice->LogObjDeallocation(oldObj); #endif oldObj->refDec(helium::RefType::INTERNAL); } } // Release the mapped object copy's allocated memory freePrivateData(true); }
7,904
C++
26.258621
207
0.721407
NVIDIA-Omniverse/AnariUsdDevice/UsdInstance.cpp
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #include "UsdInstance.h" #include "UsdAnari.h" #include "UsdDevice.h" #include "UsdGroup.h" #define GroupType ANARI_GROUP using GroupUsdType = AnariToUsdBridgedObject<GroupType>::Type; DEFINE_PARAMETER_MAP(UsdInstance, REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name) REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName) REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying) REGISTER_PARAMETER_MACRO("group", GroupType, group) REGISTER_PARAMETER_MACRO("transform", ANARI_FLOAT32_MAT4, transform) ) constexpr UsdInstance::ComponentPair UsdInstance::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays UsdInstance::UsdInstance(const char* name, UsdDevice* device) : BridgedBaseObjectType(ANARI_INSTANCE, name, device) { } UsdInstance::~UsdInstance() { #ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME if(cachedBridge) cachedBridge->DeleteInstance(usdHandle); #endif } void UsdInstance::remove(UsdDevice* device) { applyRemoveFunc(device, &UsdBridge::DeleteInstance); } bool UsdInstance::deferCommit(UsdDevice* device) { const UsdInstanceData& paramData = getReadParams(); if(UsdObjectNotInitialized<GroupUsdType>(paramData.group)) { return true; } return false; } bool UsdInstance::doCommitData(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); const char* instanceName = getName(); bool isNew = false; if (!usdHandle.value) isNew = usdBridge->CreateInstance(instanceName, usdHandle); if (paramChanged || isNew) { doCommitRefs(device); // Perform immediate commit of refs - no params from children required paramChanged = false; } return false; } void UsdInstance::doCommitRefs(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); const UsdInstanceData& paramData = getReadParams(); double timeStep = device->getReadParams().timeStep; bool groupTimeVarying = isTimeVarying(UsdInstanceComponents::GROUP); bool transformTimeVarying = isTimeVarying(UsdInstanceComponents::TRANSFORM); if (paramData.group) { usdBridge->SetGroupRef(usdHandle, paramData.group->getUsdHandle(), groupTimeVarying, timeStep); } else { usdBridge->DeleteGroupRef(usdHandle, groupTimeVarying, timeStep); } usdBridge->SetInstanceTransform(usdHandle, paramData.transform.Data, transformTimeVarying, timeStep); }
2,456
C++
25.706521
132
0.757329
NVIDIA-Omniverse/AnariUsdDevice/UsdGeometry.cpp
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #include "UsdGeometry.h" #include "UsdAnari.h" #include "UsdDataArray.h" #include "UsdDevice.h" #include "UsdBridgeUtils.h" #include "anari/frontend/type_utility.h" #include <cmath> DEFINE_PARAMETER_MAP(UsdGeometry, REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name) REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName) REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep) REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying) REGISTER_PARAMETER_MACRO("usd::time.shapeGeometry", ANARI_FLOAT64, shapeGeometryRefTimeStep) REGISTER_PARAMETER_MACRO("usd::useUsdGeomPoints", ANARI_BOOL, UseUsdGeomPoints) REGISTER_PARAMETER_MACRO("primitive.index", ANARI_ARRAY, indices) REGISTER_PARAMETER_MACRO("primitive.normal", ANARI_ARRAY, primitiveNormals) REGISTER_PARAMETER_MACRO("primitive.color", ANARI_ARRAY, primitiveColors) REGISTER_PARAMETER_MACRO("primitive.radius", ANARI_ARRAY, primitiveRadii) REGISTER_PARAMETER_MACRO("primitive.scale", ANARI_ARRAY, primitiveScales) REGISTER_PARAMETER_MACRO("primitive.orientation", ANARI_ARRAY, primitiveOrientations) REGISTER_PARAMETER_ARRAY_MACRO("primitive.attribute", "", ANARI_ARRAY, primitiveAttributes, MAX_ATTRIBS) REGISTER_PARAMETER_MACRO("primitive.id", ANARI_ARRAY, primitiveIds) REGISTER_PARAMETER_MACRO("vertex.position", ANARI_ARRAY, vertexPositions) REGISTER_PARAMETER_MACRO("vertex.normal", ANARI_ARRAY, vertexNormals) REGISTER_PARAMETER_MACRO("vertex.color", ANARI_ARRAY, vertexColors) REGISTER_PARAMETER_MACRO("vertex.radius", ANARI_ARRAY, vertexRadii) REGISTER_PARAMETER_MACRO("vertex.scale", ANARI_ARRAY, vertexScales) REGISTER_PARAMETER_MACRO("vertex.orientation", ANARI_ARRAY, vertexOrientations) REGISTER_PARAMETER_ARRAY_MACRO("vertex.attribute", "", ANARI_ARRAY, vertexAttributes, MAX_ATTRIBS) REGISTER_PARAMETER_ARRAY_MACRO("usd::attribute", ".name", ANARI_STRING, attributeNames, MAX_ATTRIBS) REGISTER_PARAMETER_MACRO("radius", ANARI_FLOAT32, radiusConstant) REGISTER_PARAMETER_MACRO("scale", ANARI_FLOAT32_VEC3, scaleConstant) REGISTER_PARAMETER_MACRO("orientation", ANARI_FLOAT32_QUAT_IJKW, orientationConstant) REGISTER_PARAMETER_MACRO("shapeType", ANARI_STRING, shapeType) REGISTER_PARAMETER_MACRO("shapeGeometry", ANARI_GEOMETRY, shapeGeometry) REGISTER_PARAMETER_MACRO("shapeTransform", ANARI_FLOAT32_MAT4, shapeTransform) ) // See .h for usage. constexpr UsdGeometry::ComponentPair UsdGeometry::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays struct UsdGeometryTempArrays { UsdGeometryTempArrays(const UsdGeometry::AttributeArray& attributes) : Attributes(attributes) {} std::vector<int> CurveLengths; std::vector<float> PointsArray; std::vector<float> NormalsArray; std::vector<float> RadiiArray; std::vector<float> ScalesArray; std::vector<float> OrientationsArray; std::vector<int64_t> IdsArray; std::vector<int64_t> InvisIdsArray; std::vector<char> ColorsArray; // generic byte array ANARIDataType ColorsArrayType; UsdGeometry::AttributeDataArraysType AttributeDataArrays; const UsdGeometry::AttributeArray& Attributes; void resetColorsArray(size_t numElements, ANARIDataType type) { ColorsArray.resize(numElements*anari::sizeOf(type)); ColorsArrayType = type; } void reserveColorsArray(size_t numElements) { ColorsArray.reserve(numElements*anari::sizeOf(ColorsArrayType)); } size_t expandColorsArray(size_t numElements) { size_t startByte = ColorsArray.size(); size_t typeSize = anari::sizeOf(ColorsArrayType); ColorsArray.resize(startByte+numElements*typeSize); return startByte/typeSize; } void copyToColorsArray(const void* source, size_t srcIdx, size_t destIdx, size_t numElements) { size_t typeSize = anari::sizeOf(ColorsArrayType); size_t srcStart = srcIdx*typeSize; size_t dstStart = destIdx*typeSize; size_t numBytes = numElements*typeSize; assert(dstStart+numBytes <= ColorsArray.size()); memcpy(ColorsArray.data()+dstStart, reinterpret_cast<const char*>(source)+srcStart, numBytes); } void resetAttributeDataArray(size_t attribIdx, size_t numElements) { if(Attributes[attribIdx].Data) { uint32_t eltSize = Attributes[attribIdx].EltSize; AttributeDataArrays[attribIdx].resize(numElements*eltSize); } else AttributeDataArrays[attribIdx].resize(0); } void reserveAttributeDataArray(size_t attribIdx, size_t numElements) { if(Attributes[attribIdx].Data) { uint32_t eltSize = Attributes[attribIdx].EltSize; AttributeDataArrays[attribIdx].reserve(numElements*eltSize); } } size_t expandAttributeDataArray(size_t attribIdx, size_t numElements) { if(Attributes[attribIdx].Data) { uint32_t eltSize = Attributes[attribIdx].EltSize; size_t startByte = AttributeDataArrays[attribIdx].size(); AttributeDataArrays[attribIdx].resize(startByte+numElements*eltSize); return startByte/eltSize; } return 0; } void copyToAttributeDataArray(size_t attribIdx, size_t srcIdx, size_t destIdx, size_t numElements) { if(Attributes[attribIdx].Data) { uint32_t eltSize = Attributes[attribIdx].EltSize; const void* attribSrc = reinterpret_cast<const char*>(Attributes[attribIdx].Data) + srcIdx*eltSize; size_t dstStart = destIdx*eltSize; size_t numBytes = numElements*eltSize; assert(dstStart+numBytes <= AttributeDataArrays[attribIdx].size()); void* attribDest = &AttributeDataArrays[attribIdx][dstStart]; memcpy(attribDest, attribSrc, numElements*eltSize); } } }; namespace { struct UsdGeometryDebugData { UsdDevice* device = nullptr; UsdGeometry* geometry = nullptr; const char* debugName = nullptr; }; UsdGeometry::GeomType GetGeomType(const char* type) { UsdGeometry::GeomType geomType; if (strEquals(type, "sphere")) geomType = UsdGeometry::GEOM_SPHERE; else if (strEquals(type, "cylinder")) geomType = UsdGeometry::GEOM_CYLINDER; else if (strEquals(type, "cone")) geomType = UsdGeometry::GEOM_CONE; else if (strEquals(type, "curve")) geomType = UsdGeometry::GEOM_CURVE; else if(strEquals(type, "triangle")) geomType = UsdGeometry::GEOM_TRIANGLE; else if (strEquals(type, "quad")) geomType = UsdGeometry::GEOM_QUAD; else if (strEquals(type, "glyph")) geomType = UsdGeometry::GEOM_GLYPH; else geomType = UsdGeometry::GEOM_UNKNOWN; return geomType; } uint64_t GetNumberOfPrims(bool hasIndices, const UsdDataLayout& indexLayout, UsdGeometry::GeomType geomType) { if(geomType == UsdGeometry::GEOM_CURVE) return indexLayout.numItems1 - 1; else if(hasIndices) return indexLayout.numItems1; int perPrimVertexCount = 1; switch(geomType) { case UsdGeometry::GEOM_CYLINDER: case UsdGeometry::GEOM_CONE: perPrimVertexCount = 2; break; case UsdGeometry::GEOM_TRIANGLE: perPrimVertexCount = 3; break; case UsdGeometry::GEOM_QUAD: perPrimVertexCount = 4; break; default: break; }; return indexLayout.numItems1 / perPrimVertexCount; } bool isBitSet(int value, int bit) { return (bool)(value & (1 << bit)); } size_t getIndex(const void* indices, ANARIDataType type, size_t elt) { size_t result; switch (type) { case ANARI_INT32: case ANARI_INT32_VEC2: result = (reinterpret_cast<const int*>(indices))[elt]; break; case ANARI_UINT32: case ANARI_UINT32_VEC2: result = (reinterpret_cast<const uint32_t*>(indices))[elt]; break; case ANARI_INT64: case ANARI_INT64_VEC2: result = (reinterpret_cast<const int64_t*>(indices))[elt]; break; case ANARI_UINT64: case ANARI_UINT64_VEC2: result = (reinterpret_cast<const uint64_t*>(indices))[elt]; break; default: result = 0; break; } return result; } void getValues1(const void* vertices, ANARIDataType type, size_t idx, float* result) { if (type == ANARI_FLOAT32) { const float* vertf = reinterpret_cast<const float*>(vertices); result[0] = vertf[idx]; } else if (type == ANARI_FLOAT64) { const double* vertd = reinterpret_cast<const double*>(vertices); result[0] = (float)vertd[idx]; } } void getValues2(const void* vertices, ANARIDataType type, size_t idx, float* result) { if (type == ANARI_FLOAT32_VEC2) { const float* vertf = reinterpret_cast<const float*>(vertices); result[0] = vertf[idx * 2]; result[1] = vertf[idx * 2 + 1]; } else if (type == ANARI_FLOAT64_VEC2) { const double* vertd = reinterpret_cast<const double*>(vertices); result[0] = (float)vertd[idx * 2]; result[1] = (float)vertd[idx * 2 + 1]; } } void getValues3(const void* vertices, ANARIDataType type, size_t idx, float* result) { if (type == ANARI_FLOAT32_VEC3) { const float* vertf = reinterpret_cast<const float*>(vertices); result[0] = vertf[idx * 3]; result[1] = vertf[idx * 3 + 1]; result[2] = vertf[idx * 3 + 2]; } else if (type == ANARI_FLOAT64_VEC3) { const double* vertd = reinterpret_cast<const double*>(vertices); result[0] = (float)vertd[idx * 3]; result[1] = (float)vertd[idx * 3 + 1]; result[2] = (float)vertd[idx * 3 + 2]; } } void getValues4(const void* vertices, ANARIDataType type, size_t idx, float* result) { if (type == ANARI_FLOAT32_VEC4) { const float* vertf = reinterpret_cast<const float*>(vertices); result[0] = vertf[idx * 4]; result[1] = vertf[idx * 4 + 1]; result[2] = vertf[idx * 4 + 2]; result[3] = vertf[idx * 4 + 3]; } else if (type == ANARI_FLOAT64_VEC4) { const double* vertd = reinterpret_cast<const double*>(vertices); result[0] = (float)vertd[idx * 4]; result[1] = (float)vertd[idx * 4 + 1]; result[2] = (float)vertd[idx * 4 + 2]; result[3] = (float)vertd[idx * 4 + 3]; } } void generateIndexedSphereData(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays) { if (paramData.indices) { auto& attribDataArrays = tempArrays->AttributeDataArrays; assert(attribDataArrays.size() == attributeArray.size()); uint64_t numVertices = paramData.vertexPositions->getLayout().numItems1; ANARIDataType scaleType = paramData.vertexScales ? paramData.vertexScales->getType() : (paramData.primitiveScales ? paramData.primitiveScales->getType() : ANARI_UNKNOWN); size_t scaleComps = anari::componentsOf(scaleType); bool perPrimNormals = !paramData.vertexNormals && paramData.primitiveNormals; bool perPrimRadii = !paramData.vertexRadii && paramData.primitiveRadii; bool perPrimScales = !paramData.vertexScales && paramData.primitiveScales; bool perPrimColors = !paramData.vertexColors && paramData.primitiveColors; bool perPrimOrientations = !paramData.vertexOrientations && paramData.primitiveOrientations; ANARIDataType colorType = perPrimColors ? paramData.primitiveColors->getType() : ANARI_UINT8; // Vertex colors aren't reordered // Effectively only has to reorder if the source array is perPrim, otherwise this function effectively falls through and the source array is assigned directly at parent scope. tempArrays->NormalsArray.resize(perPrimNormals ? numVertices*3 : 0); tempArrays->RadiiArray.resize(perPrimScales ? numVertices : 0); tempArrays->ScalesArray.resize(perPrimScales ? numVertices*scaleComps : 0); tempArrays->OrientationsArray.resize(perPrimOrientations ? numVertices*4 : 0); tempArrays->IdsArray.resize(numVertices, -1); // Always filled, since indices implies necessity for invisibleIds, and therefore also an Id array tempArrays->resetColorsArray(perPrimColors ? numVertices : 0, colorType); for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx) { tempArrays->resetAttributeDataArray(attribIdx, attributeArray[attribIdx].PerPrimData ? numVertices : 0); } const void* indices = paramData.indices->getData(); uint64_t numIndices = paramData.indices->getLayout().numItems1; ANARIDataType indexType = paramData.indices->getType(); int64_t maxId = -1; for (uint64_t primIdx = 0; primIdx < numIndices; ++primIdx) { size_t vertIdx = getIndex(indices, indexType, primIdx); // Normals if (perPrimNormals) { float* normalsDest = &tempArrays->NormalsArray[vertIdx * 3]; getValues3(paramData.primitiveNormals->getData(), paramData.primitiveNormals->getType(), primIdx, normalsDest); } // Orientations if (perPrimOrientations) { float* orientsDest = &tempArrays->OrientationsArray[vertIdx*4]; getValues4(paramData.primitiveOrientations->getData(), paramData.primitiveOrientations->getType(), primIdx, orientsDest); } // Radii if (perPrimRadii) { float* radiiDest = &tempArrays->RadiiArray[vertIdx]; getValues1(paramData.primitiveRadii->getData(), paramData.primitiveRadii->getType(), primIdx, radiiDest); } // Scales if (perPrimScales) { float* scalesDest = &tempArrays->ScalesArray[vertIdx*scaleComps]; if(scaleComps == 1) getValues1(paramData.primitiveScales->getData(), paramData.primitiveScales->getType(), primIdx, scalesDest); else if(scaleComps == 3) getValues3(paramData.primitiveScales->getData(), paramData.primitiveScales->getType(), primIdx, scalesDest); } // Colors if (perPrimColors) { assert(primIdx < paramData.primitiveColors->getLayout().numItems1); tempArrays->copyToColorsArray(paramData.primitiveColors->getData(), primIdx, vertIdx, 1); } // Attributes for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx) { if(attributeArray[attribIdx].PerPrimData) { tempArrays->copyToAttributeDataArray(attribIdx, primIdx, vertIdx, 1); } } // Ids if (paramData.primitiveIds) { int64_t id = static_cast<int64_t>(getIndex(paramData.primitiveIds->getData(), paramData.primitiveIds->getType(), primIdx)); tempArrays->IdsArray[vertIdx] = id; if (id > maxId) maxId = id; } else { int64_t id = static_cast<int64_t>(vertIdx); maxId = tempArrays->IdsArray[vertIdx] = id; } } // Assign unused ids to untouched vertices, then add those ids to invisible array tempArrays->InvisIdsArray.resize(0); tempArrays->InvisIdsArray.reserve(numVertices); for (uint64_t vertIdx = 0; vertIdx < numVertices; ++vertIdx) { if (tempArrays->IdsArray[vertIdx] == -1) { tempArrays->IdsArray[vertIdx] = ++maxId; tempArrays->InvisIdsArray.push_back(maxId); } } } } void convertLinesToSticks(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays) { // Converts arrays of vertex endpoint 2-tuples (optionally obtained via index 2-tuples) into center vertices with correct seglengths. auto& attribDataArrays = tempArrays->AttributeDataArrays; assert(attribDataArrays.size() == attributeArray.size()); const UsdDataArray* vertexArray = paramData.vertexPositions; uint64_t numVertices = vertexArray->getLayout().numItems1; const void* vertices = vertexArray->getData(); ANARIDataType vertexType = vertexArray->getType(); const UsdDataArray* indexArray = paramData.indices; uint64_t numSticks = indexArray ? indexArray->getLayout().numItems1 : numVertices/2; uint64_t numIndices = numSticks * 2; // Indices are 2-element vectors in ANARI const void* indices = indexArray ? indexArray->getData() : nullptr; ANARIDataType indexType = indexArray ? indexArray->getType() : ANARI_UINT32; tempArrays->PointsArray.resize(numSticks * 3); tempArrays->ScalesArray.resize(numSticks * 3); // Scales are always present tempArrays->OrientationsArray.resize(numSticks * 4); tempArrays->IdsArray.resize(paramData.primitiveIds ? numSticks : 0); // Only reorder per-vertex arrays, per-prim is already in order of the output stick center vertices ANARIDataType colorType = paramData.vertexColors ? paramData.vertexColors->getType() : ANARI_UINT8; tempArrays->resetColorsArray(paramData.vertexColors ? numSticks : 0, colorType); for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx) { tempArrays->resetAttributeDataArray(attribIdx, !attributeArray[attribIdx].PerPrimData ? numSticks : 0); } for (size_t i = 0; i < numIndices; i += 2) { size_t primIdx = i / 2; size_t vertIdx0 = indices ? getIndex(indices, indexType, i) : i; size_t vertIdx1 = indices ? getIndex(indices, indexType, i + 1) : i + 1; assert(vertIdx0 < numVertices); assert(vertIdx1 < numVertices); float point0[3], point1[3]; getValues3(vertices, vertexType, vertIdx0, point0); getValues3(vertices, vertexType, vertIdx1, point1); tempArrays->PointsArray[primIdx * 3] = (point0[0] + point1[0]) * 0.5f; tempArrays->PointsArray[primIdx * 3 + 1] = (point0[1] + point1[1]) * 0.5f; tempArrays->PointsArray[primIdx * 3 + 2] = (point0[2] + point1[2]) * 0.5f; float scaleVal = paramData.radiusConstant; if (paramData.vertexRadii) { getValues1(paramData.vertexRadii->getData(), paramData.vertexRadii->getType(), vertIdx0, &scaleVal); } else if (paramData.primitiveRadii) { getValues1(paramData.primitiveRadii->getData(), paramData.primitiveRadii->getType(), primIdx, &scaleVal); } float segDir[3] = { point1[0] - point0[0], point1[1] - point0[1], point1[2] - point0[2], }; float segLength = sqrtf(segDir[0] * segDir[0] + segDir[1] * segDir[1] + segDir[2] * segDir[2]); tempArrays->ScalesArray[primIdx * 3] = scaleVal; tempArrays->ScalesArray[primIdx * 3 + 1] = scaleVal; tempArrays->ScalesArray[primIdx * 3 + 2] = segLength * 0.5f; // Rotation // USD shapes are always lengthwise-oriented along the z axis usdbridgenumerics::DirectionToQuaternionZ(segDir, segLength, tempArrays->OrientationsArray.data() + primIdx*4); //Colors if (paramData.vertexColors) { assert(vertIdx0 < paramData.vertexColors->getLayout().numItems1); tempArrays->copyToColorsArray(paramData.vertexColors->getData(), vertIdx0, primIdx, 1); } // Attributes for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx) { if(!attributeArray[attribIdx].PerPrimData) { tempArrays->copyToAttributeDataArray(attribIdx, vertIdx0, primIdx, 1); } } // Ids if (paramData.primitiveIds) { tempArrays->IdsArray[primIdx] = (int64_t)getIndex(paramData.primitiveIds->getData(), paramData.primitiveIds->getType(), primIdx); } } } void pushVertex(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays, const void* vertices, ANARIDataType vertexType, bool hasNormals, bool hasColors, bool hasRadii, size_t segStart, size_t primIdx) { auto& attribDataArrays = tempArrays->AttributeDataArrays; float point[3]; getValues3(vertices, vertexType, segStart, point); tempArrays->PointsArray.push_back(point[0]); tempArrays->PointsArray.push_back(point[1]); tempArrays->PointsArray.push_back(point[2]); // Normals if (hasNormals) { float normals[3]; if (paramData.vertexNormals) { getValues3(paramData.vertexNormals->getData(), paramData.vertexNormals->getType(), segStart, normals); } else if (paramData.primitiveNormals) { getValues3(paramData.primitiveNormals->getData(), paramData.primitiveNormals->getType(), primIdx, normals); } tempArrays->NormalsArray.push_back(normals[0]); tempArrays->NormalsArray.push_back(normals[1]); tempArrays->NormalsArray.push_back(normals[2]); } // Radii if (hasRadii) { float radii; if (paramData.vertexRadii) { getValues1(paramData.vertexRadii->getData(), paramData.vertexRadii->getType(), segStart, &radii); } else if (paramData.primitiveRadii) { getValues1(paramData.primitiveRadii->getData(), paramData.primitiveRadii->getType(), primIdx, &radii); } tempArrays->ScalesArray.push_back(radii); } // Colors if (hasColors) { size_t destIdx = tempArrays->expandColorsArray(1); if (paramData.vertexColors) { tempArrays->copyToColorsArray(paramData.vertexColors->getData(), segStart, destIdx, 1); } else if (paramData.primitiveColors) { tempArrays->copyToColorsArray(paramData.primitiveColors->getData(), primIdx, destIdx, 1); } } // Attributes for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx) { size_t srcIdx = attributeArray[attribIdx].PerPrimData ? primIdx : segStart; size_t destIdx = tempArrays->expandAttributeDataArray(attribIdx, 1); tempArrays->copyToAttributeDataArray(attribIdx, srcIdx, destIdx, 1); } } #define PUSH_VERTEX(x, y) \ pushVertex(paramData, attributeArray, tempArrays, \ vertices, vertexType, \ hasNormals, hasColors, hasRadii, \ x, y) void reorderCurveGeometry(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays) { auto& attribDataArrays = tempArrays->AttributeDataArrays; assert(attribDataArrays.size() == attributeArray.size()); const UsdDataArray* vertexArray = paramData.vertexPositions; uint64_t numVertices = vertexArray->getLayout().numItems1; const void* vertices = vertexArray->getData(); ANARIDataType vertexType = vertexArray->getType(); const UsdDataArray* indexArray = paramData.indices; uint64_t numSegments = indexArray ? indexArray->getLayout().numItems1 : numVertices-1; const void* indices = indexArray ? indexArray->getData() : nullptr; ANARIDataType indexType = indexArray ? indexArray->getType() : ANARI_UINT32; uint64_t maxNumVerts = numSegments*2; tempArrays->CurveLengths.resize(0); tempArrays->PointsArray.resize(0); tempArrays->PointsArray.reserve(maxNumVerts * 3); // Conservative max number of points bool hasNormals = paramData.vertexNormals || paramData.primitiveNormals; if (hasNormals) { tempArrays->NormalsArray.resize(0); tempArrays->NormalsArray.reserve(maxNumVerts * 3); } bool hasColors = paramData.vertexColors || paramData.primitiveColors; if (hasColors) { tempArrays->resetColorsArray(0, paramData.vertexColors ? paramData.vertexColors->getType() : paramData.primitiveColors->getType()); tempArrays->reserveColorsArray(maxNumVerts); } bool hasRadii = paramData.vertexRadii || paramData.primitiveRadii; if (hasRadii) { tempArrays->ScalesArray.resize(0); tempArrays->ScalesArray.reserve(maxNumVerts); } for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx) { tempArrays->resetAttributeDataArray(attribIdx, 0); tempArrays->reserveAttributeDataArray(attribIdx, maxNumVerts); } size_t prevSegEnd = 0; int curveLength = 0; for (size_t primIdx = 0; primIdx < numSegments; ++primIdx) { size_t segStart = indices ? getIndex(indices, indexType, primIdx) : primIdx; if (primIdx != 0 && prevSegEnd != segStart) { PUSH_VERTEX(prevSegEnd, primIdx - 1); curveLength += 1; tempArrays->CurveLengths.push_back(curveLength); curveLength = 0; } assert(segStart+1 < numVertices); // begin and end vertex should be in range PUSH_VERTEX(segStart, primIdx); curveLength += 1; prevSegEnd = segStart + 1; } if (curveLength != 0) { PUSH_VERTEX(prevSegEnd, numSegments - 1); curveLength += 1; tempArrays->CurveLengths.push_back(curveLength); } } template<typename T> void setInstancerDataArray(const char* arrayName, const UsdDataArray* vertArray, const UsdDataArray* primArray, const std::vector<T>& tmpArray, UsdBridgeType tmpArrayType, void const*& instancerDataArray, UsdBridgeType& instancerDataArrayType, const UsdGeometryData& paramData, const UsdGeometryDebugData& dbgData) { // Normals if (paramData.indices && tmpArray.size()) { instancerDataArray = tmpArray.data(); instancerDataArrayType = tmpArrayType; } else { const UsdDataArray* normals = vertArray; if (normals) { instancerDataArray = normals->getData(); instancerDataArrayType = AnariToUsdBridgeType(normals->getType()); } else if(primArray) { dbgData.device->reportStatus(dbgData.geometry, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' primitive.%s not transferred: per-primitive arrays provided without setting primitive.index", dbgData.debugName, arrayName); } } } } UsdGeometry::UsdGeometry(const char* name, const char* type, UsdDevice* device) : BridgedBaseObjectType(ANARI_GEOMETRY, name, device) { bool createTempArrays = false; geomType = GetGeomType(type); if(isInstanced() || geomType == GEOM_CURVE) createTempArrays = true; if(geomType == GEOM_UNKNOWN) device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' construction failed: type %s not supported", getName(), type); if(createTempArrays) tempArrays = std::make_unique<UsdGeometryTempArrays>(attributeArray); } UsdGeometry::~UsdGeometry() { #ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME if(cachedBridge) cachedBridge->DeleteGeometry(usdHandle); #endif } void UsdGeometry::remove(UsdDevice* device) { applyRemoveFunc(device, &UsdBridge::DeleteGeometry); } void UsdGeometry::filterSetParam(const char *name, ANARIDataType type, const void *mem, UsdDevice* device) { if(geomType == GEOM_GLYPH && strEquals(name, "shapeType") || strEquals(name, "shapeGeometry") || strEquals(name, "shapeTransform")) protoShapeChanged = true; if(usdHandle.value && strEquals(name, "usd::useUsdGeomPoints")) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' filterSetParam failed: 'usd::useUsdGeomPoints' parameter cannot be changed after the first commit", getName()); return; } BridgedBaseObjectType::filterSetParam(name, type, mem, device); } template<typename GeomDataType> void UsdGeometry::setAttributeTimeVarying(typename GeomDataType::DataMemberId& timeVarying) { typedef typename GeomDataType::DataMemberId DMI; const UsdGeometryData& paramData = getReadParams(); static constexpr int attribStartBit = static_cast<int>(UsdGeometryComponents::ATTRIBUTE0); for(size_t attribIdx = 0; attribIdx < attributeArray.size(); ++attribIdx) { DMI attributeId = DMI::ATTRIBUTE0 + attribIdx; timeVarying = timeVarying & (isBitSet(paramData.timeVarying, attribStartBit+(int)attribIdx) ? DMI::ALL : ~attributeId); } } void UsdGeometry::syncAttributeArrays() { const UsdGeometryData& paramData = getReadParams(); // Find the max index of the last attribute that still contains an array int attribCount = 0; for(int i = 0; i < MAX_ATTRIBS; ++i) { if(paramData.primitiveAttributes[i] != nullptr || paramData.vertexAttributes[i] != nullptr) attribCount = i+1; } // Set the attribute arrays and related info, resize temporary attribute array data for reordering if(attribCount) { attributeArray.resize(attribCount); for(int i = 0; i < attribCount; ++i) { const UsdDataArray* attribArray = paramData.vertexAttributes[i] ? paramData.vertexAttributes[i] : paramData.primitiveAttributes[i]; if (attribArray) { attributeArray[i].Data = attribArray->getData(); attributeArray[i].DataType = AnariToUsdBridgeType(attribArray->getType()); attributeArray[i].PerPrimData = paramData.vertexAttributes[i] ? false : true; attributeArray[i].EltSize = static_cast<uint32_t>(anari::sizeOf(attribArray->getType())); attributeArray[i].Name = UsdSharedString::c_str(paramData.attributeNames[i]); } else { attributeArray[i].Data = nullptr; attributeArray[i].DataType = UsdBridgeType::UNDEFINED; } } if(tempArrays) tempArrays->AttributeDataArrays.resize(attribCount); } } template<typename GeomDataType> void UsdGeometry::copyAttributeArraysToData(GeomDataType& geomData) { geomData.Attributes = attributeArray.data(); geomData.NumAttributes = static_cast<uint32_t>(attributeArray.size()); } void UsdGeometry::assignTempDataToAttributes(bool perPrimInterpolation) { const AttributeDataArraysType& attribDataArrays = tempArrays->AttributeDataArrays; assert(attributeArray.size() == attribDataArrays.size()); for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx) { if(attribDataArrays[attribIdx].size()) // Always > 0 if attributeArray[attribIdx].Data is set attributeArray[attribIdx].Data = attribDataArrays[attribIdx].data(); attributeArray[attribIdx].PerPrimData = perPrimInterpolation; // Already converted to per-vertex (or per-prim) } } void UsdGeometry::initializeGeomData(UsdBridgeMeshData& geomData) { typedef UsdBridgeMeshData::DataMemberId DMI; const UsdGeometryData& paramData = getReadParams(); geomData.TimeVarying = DMI::ALL & (isTimeVarying(CType::POSITION) ? DMI::ALL : ~DMI::POINTS) & (isTimeVarying(CType::NORMAL) ? DMI::ALL : ~DMI::NORMALS) & (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::COLORS) & (isTimeVarying(CType::INDEX) ? DMI::ALL : ~DMI::INDICES); setAttributeTimeVarying<UsdBridgeMeshData>(geomData.TimeVarying); geomData.FaceVertexCount = geomType == GEOM_QUAD ? 4 : 3; } void UsdGeometry::initializeGeomData(UsdBridgeInstancerData& geomData) { typedef UsdBridgeInstancerData::DataMemberId DMI; const UsdGeometryData& paramData = getReadParams(); geomData.TimeVarying = DMI::ALL & (isTimeVarying(CType::POSITION) ? DMI::ALL : ~DMI::POINTS) & (( ((geomType == GEOM_CYLINDER || geomType == GEOM_CONE) && (isTimeVarying(CType::NORMAL) || isTimeVarying(CType::POSITION) || isTimeVarying(CType::INDEX))) || ((geomType == GEOM_GLYPH) && isTimeVarying(CType::ORIENTATION)) ) ? DMI::ALL : ~DMI::ORIENTATIONS) & (isTimeVarying(CType::SCALE) ? DMI::ALL : ~DMI::SCALES) & (isTimeVarying(CType::INDEX) ? DMI::ALL : ~DMI::INVISIBLEIDS) & (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::COLORS) & (isTimeVarying(CType::ID) ? DMI::ALL : ~DMI::INSTANCEIDS) & ~DMI::SHAPEINDICES; // Shapeindices are always the same, and USD clients typically do not support timevarying shapes setAttributeTimeVarying<UsdBridgeInstancerData>(geomData.TimeVarying); geomData.UseUsdGeomPoints = geomType == GEOM_SPHERE && paramData.UseUsdGeomPoints; } void UsdGeometry::initializeGeomData(UsdBridgeCurveData& geomData) { typedef UsdBridgeCurveData::DataMemberId DMI; const UsdGeometryData& paramData = getReadParams(); // Turn off what is not timeVarying geomData.TimeVarying = DMI::ALL & (isTimeVarying(CType::POSITION) ? DMI::ALL : ~DMI::POINTS) & (isTimeVarying(CType::NORMAL) ? DMI::ALL : ~DMI::NORMALS) & (isTimeVarying(CType::SCALE) ? DMI::ALL : ~DMI::SCALES) & (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::COLORS) & ((isTimeVarying(CType::POSITION) || isTimeVarying(CType::INDEX)) ? DMI::ALL : ~DMI::CURVELENGTHS); setAttributeTimeVarying<UsdBridgeCurveData>(geomData.TimeVarying); } void UsdGeometry::initializeGeomRefData(UsdBridgeInstancerRefData& geomRefData) { const UsdGeometryData& paramData = getReadParams(); // The anari side currently only supports only one shape, so just set DefaultShape bool isGlyph = geomType == GEOM_GLYPH; if(isGlyph && paramData.shapeGeometry) geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_MESH; else { UsdGeometry::GeomType defaultShape = (isGlyph && paramData.shapeType) ? GetGeomType(paramData.shapeType->c_str()) : geomType; switch (defaultShape) { case GEOM_CYLINDER: geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_CYLINDER; break; case GEOM_CONE: geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_CONE; break; default: geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_SPHERE; break; }; } geomRefData.ShapeTransform = paramData.shapeTransform; } bool UsdGeometry::checkArrayConstraints(const UsdDataArray* vertexArray, const UsdDataArray* primArray, const char* paramName, UsdDevice* device, const char* debugName, int attribIndex) { const UsdGeometryData& paramData = getReadParams(); UsdLogInfo logInfo(device, this, ANARI_GEOMETRY, debugName); const UsdDataArray* vertices = paramData.vertexPositions; const UsdDataLayout& vertLayout = vertices->getLayout(); const UsdDataArray* indices = paramData.indices; const UsdDataLayout& indexLayout = indices ? indices->getLayout() : vertLayout; const UsdDataLayout& perVertLayout = vertexArray ? vertexArray->getLayout() : vertLayout; const UsdDataLayout& perPrimLayout = primArray ? primArray->getLayout() : indexLayout; const UsdDataLayout& attrLayout = vertexArray ? perVertLayout : perPrimLayout; if (!AssertOneDimensional(attrLayout, logInfo, paramName) || !AssertNoStride(attrLayout, logInfo, paramName) ) { return false; } if (vertexArray && vertexArray->getLayout().numItems1 < vertLayout.numItems1) { if(attribIndex == -1) device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: all 'vertex.X' array elements should at least be the size of vertex.positions", debugName); else device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: all 'vertex.attribute%i' array elements should at least be the size of vertex.positions", debugName, attribIndex); return false; } uint64_t numPrims = GetNumberOfPrims(indices, indexLayout, geomType); if (primArray && primArray->getLayout().numItems1 < numPrims) { if(attribIndex == -1) device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: size of 'primitive.X' array too small", debugName); else device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: size of 'primitive.attribute%i' array too small", debugName, attribIndex); return false; } return true; } bool UsdGeometry::checkGeomParams(UsdDevice* device) { const UsdGeometryData& paramData = getReadParams(); const char* debugName = getName(); bool success = true; success = success && checkArrayConstraints(paramData.vertexPositions, nullptr, "vertex.position", device, debugName); success = success && checkArrayConstraints(nullptr, paramData.indices, "primitive.index", device, debugName); success = success && checkArrayConstraints(paramData.vertexNormals, paramData.primitiveNormals, "vertex/primitive.normal", device, debugName); for(int i = 0; i < MAX_ATTRIBS; ++i) success = success && checkArrayConstraints(paramData.vertexAttributes[i], paramData.primitiveAttributes[i], "vertex/primitive.attribute", device, debugName, i); success = success && checkArrayConstraints(paramData.vertexColors, paramData.primitiveColors, "vertex/primitive.color", device, debugName); success = success && checkArrayConstraints(paramData.vertexRadii, paramData.primitiveRadii, "vertex/primitive.radius", device, debugName); success = success && checkArrayConstraints(paramData.vertexScales, paramData.primitiveScales, "vertex/primitive.scale", device, debugName); success = success && checkArrayConstraints(paramData.vertexOrientations, paramData.primitiveOrientations, "vertex/primitive.orientation", device, debugName); success = success && checkArrayConstraints(nullptr, paramData.primitiveIds, "primitive.id", device, debugName); if (!success) return false; ANARIDataType vertType = paramData.vertexPositions->getType(); if (vertType != ANARI_FLOAT32_VEC3 && vertType != ANARI_FLOAT64_VEC3) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex.position' parameter should be of type ANARI_FLOAT32_VEC3 or ANARI_FLOAT64_VEC3.", debugName); return false; } if (paramData.indices) { ANARIDataType indexType = paramData.indices->getType(); UsdBridgeType flattenedType = AnariToUsdBridgeType_Flattened(indexType); if( (geomType == GEOM_TRIANGLE || geomType == GEOM_QUAD) && (flattenedType == UsdBridgeType::UINT || flattenedType == UsdBridgeType::ULONG || flattenedType == UsdBridgeType::LONG)) { static bool reported = false; // Hardcode this to show only once to make sure developers get to see it, without spamming the console. if(!reported) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' has 'primitive.index' of type other than ANARI_INT32, which may result in an overflow for FaceVertexIndicesAttr of UsdGeomMesh.", debugName); reported = true; } } if (geomType == GEOM_SPHERE || geomType == GEOM_CURVE || geomType == GEOM_GLYPH) { if(geomType == GEOM_SPHERE && paramData.UseUsdGeomPoints) device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' is a sphere geometry with indices, but the usd::useUsdGeomPoints parameter is not set, so all vertices will show as spheres.", debugName); if (indexType != ANARI_INT32 && indexType != ANARI_UINT32 && indexType != ANARI_INT64 && indexType != ANARI_UINT64) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT32/64.", debugName); return false; } } else if (geomType == GEOM_CYLINDER || geomType == GEOM_CONE) { if (indexType != ANARI_UINT32_VEC2 && indexType != ANARI_INT32_VEC2 && indexType != ANARI_UINT64_VEC2 && indexType != ANARI_INT64_VEC2) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT_VEC2.", debugName); return false; } } else if (geomType == GEOM_TRIANGLE) { if (indexType != ANARI_UINT32_VEC3 && indexType != ANARI_INT32_VEC3 && indexType != ANARI_UINT64_VEC3 && indexType != ANARI_INT64_VEC3) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT_VEC3.", debugName); return false; } } else if (geomType == GEOM_QUAD) { if (indexType != ANARI_UINT32_VEC4 && indexType != ANARI_INT32_VEC4 && indexType != ANARI_UINT64_VEC4 && indexType != ANARI_INT64_VEC4) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT_VEC4.", debugName); return false; } } } const UsdDataArray* normals = paramData.vertexNormals ? paramData.vertexNormals : paramData.primitiveNormals; if (normals) { ANARIDataType arrayType = normals->getType(); if (arrayType != ANARI_FLOAT32_VEC3 && arrayType != ANARI_FLOAT64_VEC3) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.normal' parameter should be of type ANARI_FLOAT32_VEC3 or ANARI_FLOAT64_VEC3.", debugName); return false; } } const UsdDataArray* colors = paramData.vertexColors ? paramData.vertexColors : paramData.primitiveColors; if (colors) { ANARIDataType arrayType = colors->getType(); if ((int)arrayType < (int)ANARI_INT8 || (int)arrayType > (int)ANARI_UFIXED8_R_SRGB) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.color' parameter should be of Color type (see ANARI standard)", debugName); return false; } } const UsdDataArray* radii = paramData.vertexRadii ? paramData.vertexRadii : paramData.primitiveRadii; if (radii) { ANARIDataType arrayType = radii->getType(); if (arrayType != ANARI_FLOAT32 && arrayType != ANARI_FLOAT64) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.radius' parameter should be of type ANARI_FLOAT32 or ANARI_FLOAT64.", debugName); return false; } } const UsdDataArray* scales = paramData.vertexScales ? paramData.vertexScales : paramData.primitiveScales; if (scales) { ANARIDataType arrayType = scales->getType(); if (arrayType != ANARI_FLOAT32 && arrayType != ANARI_FLOAT64 && arrayType != ANARI_FLOAT32_VEC3 && arrayType != ANARI_FLOAT64_VEC3) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.scale' parameter should be of type ANARI_FLOAT32(_VEC3) or ANARI_FLOAT64(_VEC3).", debugName); return false; } } const UsdDataArray* orientations = paramData.vertexOrientations ? paramData.vertexOrientations : paramData.primitiveOrientations; if (orientations) { ANARIDataType arrayType = orientations->getType(); if (arrayType != ANARI_FLOAT32_QUAT_IJKW) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.orientation' parameter should be of type ANARI_FLOAT32_QUAT_IJKW.", debugName); return false; } } if (paramData.primitiveIds) { ANARIDataType idType = paramData.primitiveIds->getType(); if (idType != ANARI_INT32 && idType != ANARI_UINT32 && idType != ANARI_INT64 && idType != ANARI_UINT64) { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.id' parameter should be of type ANARI_(U)INT or ANARI_(U)LONG.", debugName); return false; } } return true; } void UsdGeometry::updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeMeshData& meshData, bool isNew) { const UsdGeometryData& paramData = getReadParams(); const UsdDataArray* vertices = paramData.vertexPositions; meshData.NumPoints = vertices->getLayout().numItems1; meshData.Points = vertices->getData(); meshData.PointsType = AnariToUsdBridgeType(vertices->getType()); const UsdDataArray* normals = paramData.vertexNormals ? paramData.vertexNormals : paramData.primitiveNormals; if (normals) { meshData.Normals = normals->getData(); meshData.NormalsType = AnariToUsdBridgeType(normals->getType()); meshData.PerPrimNormals = paramData.vertexNormals ? false : true; } const UsdDataArray* colors = paramData.vertexColors ? paramData.vertexColors : paramData.primitiveColors; if (colors) { meshData.Colors = colors->getData(); meshData.ColorsType = AnariToUsdBridgeType(colors->getType()); meshData.PerPrimColors = paramData.vertexColors ? false : true; } const UsdDataArray* indices = paramData.indices; if (indices) { ANARIDataType indexType = indices->getType(); meshData.NumIndices = indices->getLayout().numItems1 * anari::componentsOf(indexType); meshData.Indices = indices->getData(); meshData.IndicesType = AnariToUsdBridgeType_Flattened(indexType); } else { meshData.NumIndices = meshData.NumPoints; // Vertices are implicitly indexed consecutively (FaceVertexCount determines how many prims) } //meshData.UpdatesToPerform = Still to be implemented double worldTimeStep = device->getReadParams().timeStep; double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep); usdBridge->SetGeometryData(usdHandle, meshData, dataTimeStep); } void UsdGeometry::updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeInstancerData& instancerData, bool isNew) { const UsdGeometryData& paramData = getReadParams(); const char* debugName = getName(); if (geomType == GEOM_SPHERE || geomType == GEOM_GLYPH) { // A paramData.indices (primitive-indexed spheres) array, is not supported in USD, also duplicate spheres make no sense. // Instead, Ids/InvisibleIds are assigned to emulate sparsely indexed spheres (sourced from paramData.primitiveIds if available), // with the per-vertex arrays remaining intact. Any per-prim arrays are explicitly converted to per-vertex via the tempArrays. generateIndexedSphereData(paramData, attributeArray, tempArrays.get()); const UsdDataArray* vertices = paramData.vertexPositions; instancerData.NumPoints = vertices->getLayout().numItems1; instancerData.Points = vertices->getData(); instancerData.PointsType = AnariToUsdBridgeType(vertices->getType()); UsdGeometryDebugData dbgData = { device, this, debugName }; // Orientations // are a bit extended beyond the spec: even spheres can set them, and the use of normals is also supported if(paramData.vertexOrientations || paramData.primitiveOrientations) { setInstancerDataArray("orientation", paramData.vertexOrientations, paramData.primitiveOrientations, tempArrays->OrientationsArray, UsdBridgeType::FLOAT4, instancerData.Orientations, instancerData.OrientationsType, paramData, dbgData); } else { setInstancerDataArray("normal", paramData.vertexNormals, paramData.primitiveNormals, tempArrays->NormalsArray, UsdBridgeType::FLOAT3, instancerData.Orientations, instancerData.OrientationsType, paramData, dbgData); } // Scales if(geomType == GEOM_SPHERE) { setInstancerDataArray("radius", paramData.vertexRadii, paramData.primitiveRadii, tempArrays->RadiiArray, UsdBridgeType::FLOAT, instancerData.Scales, instancerData.ScalesType, paramData, dbgData); } else { size_t numTmpScales = tempArrays->ScalesArray.size(); bool scalarScale = (numTmpScales == instancerData.NumPoints); assert(!numTmpScales || scalarScale || numTmpScales == instancerData.NumPoints*3); setInstancerDataArray("scale", paramData.vertexScales, paramData.primitiveScales, tempArrays->ScalesArray, scalarScale ? UsdBridgeType::FLOAT : UsdBridgeType::FLOAT3, instancerData.Scales, instancerData.ScalesType, paramData, dbgData); } // Colors setInstancerDataArray("color", paramData.vertexColors, paramData.primitiveColors, tempArrays->ColorsArray, AnariToUsdBridgeType(tempArrays->ColorsArrayType), instancerData.Colors, instancerData.ColorsType, paramData, dbgData); // Attributes // By default, syncAttributeArrays and initializeGeomData already set up instancerData.Attributes // Just set attributeArray's data to tempArrays where necessary if(paramData.indices) { // Type remains the same, everything per-vertex (as explained above) assignTempDataToAttributes(false); } else { // Check whether any perprim attributes exist for(size_t attribIdx = 0; attribIdx < attributeArray.size(); ++attribIdx) { if(attributeArray[attribIdx].Data && attributeArray[attribIdx].PerPrimData) { attributeArray[attribIdx].Data = nullptr; device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' primitive.attribute%i not transferred: per-primitive arrays provided without setting primitive.index", debugName, static_cast<int>(attribIdx)); } } } // Ids if (paramData.indices && tempArrays->IdsArray.size()) { instancerData.InstanceIds = tempArrays->IdsArray.data(); instancerData.InstanceIdsType = UsdBridgeType::LONG; } else { const UsdDataArray* ids = paramData.primitiveIds; if (ids) { instancerData.InstanceIds = ids->getData(); instancerData.InstanceIdsType = AnariToUsdBridgeType(ids->getType()); } } // Invisible Ids if (paramData.indices && tempArrays->InvisIdsArray.size()) { instancerData.InvisibleIds = tempArrays->InvisIdsArray.data(); instancerData.InvisibleIdsType = UsdBridgeType::LONG; instancerData.NumInvisibleIds = tempArrays->InvisIdsArray.size(); } for(int i = 0; i < 3; ++i) instancerData.Scale.Data[i] = (geomType == GEOM_SPHERE) ? paramData.radiusConstant : paramData.scaleConstant.Data[i]; instancerData.Orientation = paramData.orientationConstant; } else { convertLinesToSticks(paramData, attributeArray, tempArrays.get()); instancerData.NumPoints = tempArrays->PointsArray.size()/3; if (instancerData.NumPoints > 0) { instancerData.Points = tempArrays->PointsArray.data(); instancerData.PointsType = UsdBridgeType::FLOAT3; instancerData.Scales = tempArrays->ScalesArray.data(); instancerData.ScalesType = UsdBridgeType::FLOAT3; instancerData.Orientations = tempArrays->OrientationsArray.data(); instancerData.OrientationsType = UsdBridgeType::FLOAT4; // Colors if (tempArrays->ColorsArray.size()) { instancerData.Colors = tempArrays->ColorsArray.data(); instancerData.ColorsType = AnariToUsdBridgeType(tempArrays->ColorsArrayType); } else if(const UsdDataArray* colors = paramData.primitiveColors) { // Per-primitive color array corresponds to per-vertex stick output instancerData.Colors = colors->getData(); instancerData.ColorsType = AnariToUsdBridgeType(colors->getType()); } // Attributes assignTempDataToAttributes(false); // Ids if (tempArrays->IdsArray.size()) { instancerData.InstanceIds = tempArrays->IdsArray.data(); instancerData.InstanceIdsType = UsdBridgeType::LONG; } } } double worldTimeStep = device->getReadParams().timeStep; double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep); usdBridge->SetGeometryData(usdHandle, instancerData, dataTimeStep); if(isNew && geomType != GEOM_GLYPH && !instancerData.UseUsdGeomPoints) commitPrototypes(usdBridge); // Also initialize the prototype shape on the instancer geom } void UsdGeometry::updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeCurveData& curveData, bool isNew) { const UsdGeometryData& paramData = getReadParams(); reorderCurveGeometry(paramData, attributeArray, tempArrays.get()); curveData.NumPoints = tempArrays->PointsArray.size() / 3; if (curveData.NumPoints > 0) { curveData.Points = tempArrays->PointsArray.data(); curveData.PointsType = UsdBridgeType::FLOAT3; curveData.CurveLengths = tempArrays->CurveLengths.data(); curveData.NumCurveLengths = tempArrays->CurveLengths.size(); if (tempArrays->NormalsArray.size()) { curveData.Normals = tempArrays->NormalsArray.data(); curveData.NormalsType = UsdBridgeType::FLOAT3; } curveData.PerPrimNormals = false;// Always vertex colored as per reorderCurveGeometry. One entry per whole curve would be useless // Attributes assignTempDataToAttributes(false); // Copy colors if (tempArrays->ColorsArray.size()) { curveData.Colors = tempArrays->ColorsArray.data(); curveData.ColorsType = AnariToUsdBridgeType(tempArrays->ColorsArrayType); } curveData.PerPrimColors = false; // Always vertex colored as per reorderCurveGeometry. One entry per whole curve would be useless // Assign scales if (tempArrays->ScalesArray.size()) { curveData.Scales = tempArrays->ScalesArray.data(); curveData.ScalesType = UsdBridgeType::FLOAT; } curveData.UniformScale = paramData.radiusConstant; } double worldTimeStep = device->getReadParams().timeStep; double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep); usdBridge->SetGeometryData(usdHandle, curveData, dataTimeStep); } template<typename UsdGeomType> bool UsdGeometry::commitTemplate(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); const UsdGeometryData& paramData = getReadParams(); const char* debugName = getName(); UsdGeomType geomData; syncAttributeArrays(); initializeGeomData(geomData); copyAttributeArraysToData(geomData); bool isNew = false; if (!usdHandle.value) { isNew = usdBridge->CreateGeometry(debugName, usdHandle, geomData); } if (paramChanged || isNew) { if (paramData.vertexPositions) { if(checkGeomParams(device)) updateGeomData(device, usdBridge, geomData, isNew); } else { device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: missing 'vertex.position'.", debugName); } paramChanged = false; } return isNew; } void UsdGeometry::commitPrototypes(UsdBridge* usdBridge) { UsdBridgeInstancerRefData instancerRefData; initializeGeomRefData(instancerRefData); usdBridge->SetPrototypeData(usdHandle, instancerRefData); } bool UsdGeometry::deferCommit(UsdDevice* device) { return false; } bool UsdGeometry::doCommitData(UsdDevice* device) { if(geomType == GEOM_UNKNOWN) return false; bool isNew = false; switch (geomType) { case GEOM_TRIANGLE: isNew = commitTemplate<UsdBridgeMeshData>(device); break; case GEOM_QUAD: isNew = commitTemplate<UsdBridgeMeshData>(device); break; case GEOM_SPHERE: isNew = commitTemplate<UsdBridgeInstancerData>(device); break; case GEOM_CYLINDER: isNew = commitTemplate<UsdBridgeInstancerData>(device); break; case GEOM_CONE: isNew = commitTemplate<UsdBridgeInstancerData>(device); break; case GEOM_GLYPH: isNew = commitTemplate<UsdBridgeInstancerData>(device); break; case GEOM_CURVE: isNew = commitTemplate<UsdBridgeCurveData>(device); break; default: break; } return geomType == GEOM_GLYPH && (isNew || protoShapeChanged); // Defer commit of prototypes until the geometry refs are in place } void UsdGeometry::doCommitRefs(UsdDevice* device) { assert(geomType == GEOM_GLYPH && protoShapeChanged); UsdBridge* usdBridge = device->getUsdBridge(); const UsdGeometryData& paramData = getReadParams(); double worldTimeStep = device->getReadParams().timeStep; // Make sure the references are updated on the Bridge side. if (paramData.shapeGeometry) { double geomObjTimeStep = paramData.shapeGeometry->getReadParams().timeStep; UsdGeometryHandle protoGeomHandle = paramData.shapeGeometry->getUsdHandle(); size_t numHandles = 1; double protoTimestep = selectRefTime(paramData.shapeGeometryRefTimeStep, geomObjTimeStep, worldTimeStep); usdBridge->SetPrototypeRefs(usdHandle, &protoGeomHandle, numHandles, worldTimeStep, &protoTimestep ); } else { usdBridge->DeletePrototypeRefs(usdHandle, worldTimeStep); } // Now set the prototype relations to the reference paths (Bridge uses paths from SetPrototypeRefs) commitPrototypes(usdBridge); protoShapeChanged = false; }
56,898
C++
38.431046
265
0.704049
NVIDIA-Omniverse/AnariUsdDevice/UsdGroup.cpp
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #include "UsdGroup.h" #include "UsdAnari.h" #include "UsdDataArray.h" #include "UsdDevice.h" #include "UsdSurface.h" #include "UsdVolume.h" #define SurfaceType ANARI_SURFACE #define VolumeType ANARI_VOLUME using SurfaceUsdType = AnariToUsdBridgedObject<SurfaceType>::Type; using VolumeUsdType = AnariToUsdBridgedObject<VolumeType>::Type; DEFINE_PARAMETER_MAP(UsdGroup, REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name) REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName) REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying) REGISTER_PARAMETER_MACRO("surface", ANARI_ARRAY, surfaces) REGISTER_PARAMETER_MACRO("volume", ANARI_ARRAY, volumes) ) constexpr UsdGroup::ComponentPair UsdGroup::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays UsdGroup::UsdGroup(const char* name, UsdDevice* device) : BridgedBaseObjectType(ANARI_GROUP, name, device) { } UsdGroup::~UsdGroup() { #ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME if(cachedBridge) cachedBridge->DeleteGroup(usdHandle); #endif } void UsdGroup::remove(UsdDevice* device) { applyRemoveFunc(device, &UsdBridge::DeleteGroup); } bool UsdGroup::deferCommit(UsdDevice* device) { const UsdGroupData& paramData = getReadParams(); if(UsdObjectNotInitialized<SurfaceUsdType>(paramData.surfaces) || UsdObjectNotInitialized<VolumeUsdType>(paramData.volumes)) { return true; } return false; } bool UsdGroup::doCommitData(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); bool isNew = false; if (!usdHandle.value) isNew = usdBridge->CreateGroup(getName(), usdHandle); if (paramChanged || isNew) { doCommitRefs(device); // Perform immediate commit of refs - no params from children required paramChanged = false; } return false; } void UsdGroup::doCommitRefs(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); const UsdGroupData& paramData = getReadParams(); double timeStep = device->getReadParams().timeStep; UsdLogInfo logInfo(device, this, ANARI_GROUP, this->getName()); bool surfacesTimeVarying = isTimeVarying(UsdGroupComponents::SURFACES); bool volumesTimeVarying = isTimeVarying(UsdGroupComponents::VOLUMES); ManageRefArray<SurfaceType, ANARISurface, UsdSurface>(usdHandle, paramData.surfaces, surfacesTimeVarying, timeStep, surfaceHandles, &UsdBridge::SetSurfaceRefs, &UsdBridge::DeleteSurfaceRefs, usdBridge, logInfo, "UsdGroup commit failed: 'surface' array elements should be of type ANARI_SURFACE"); ManageRefArray<VolumeType, ANARIVolume, UsdVolume>(usdHandle, paramData.volumes, volumesTimeVarying, timeStep, volumeHandles, &UsdBridge::SetVolumeRefs, &UsdBridge::DeleteVolumeRefs, usdBridge, logInfo, "UsdGroup commit failed: 'volume' array elements should be of type ANARI_VOLUME"); }
2,925
C++
30.462365
126
0.764103
NVIDIA-Omniverse/AnariUsdDevice/UsdFrame.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBaseObject.h" #include "UsdParameterizedObject.h" class UsdRenderer; class UsdWorld; struct UsdFrameData { UsdWorld* world = nullptr; UsdRenderer* renderer = nullptr; UsdUint2 size = {0, 0}; ANARIDataType color = ANARI_UNKNOWN; ANARIDataType depth = ANARI_UNKNOWN; }; class UsdFrame : public UsdParameterizedBaseObject<UsdFrame, UsdFrameData> { public: UsdFrame(UsdBridge* bridge); ~UsdFrame(); void remove(UsdDevice* device) override {} const void* mapBuffer(const char* channel, uint32_t *width, uint32_t *height, ANARIDataType *pixelType); void unmapBuffer(const char* channel); void saveUsd(UsdDevice* device); protected: bool deferCommit(UsdDevice* device) override; bool doCommitData(UsdDevice* device) override; void doCommitRefs(UsdDevice* device) override {} char* ReserveBuffer(ANARIDataType format); char* mappedColorMem = nullptr; char* mappedDepthMem = nullptr; };
1,070
C
21.787234
74
0.718692
NVIDIA-Omniverse/AnariUsdDevice/UsdCamera.cpp
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #include "UsdCamera.h" #include "UsdAnari.h" #include "UsdDataArray.h" #include "UsdDevice.h" DEFINE_PARAMETER_MAP(UsdCamera, REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name) REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName) REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying) REGISTER_PARAMETER_MACRO("position", ANARI_FLOAT32_VEC3, position) REGISTER_PARAMETER_MACRO("direction", ANARI_FLOAT32_VEC3, direction) REGISTER_PARAMETER_MACRO("up", ANARI_FLOAT32_VEC3, up) REGISTER_PARAMETER_MACRO("imageRegion", ANARI_FLOAT32_BOX2, imageRegion) REGISTER_PARAMETER_MACRO("aspect", ANARI_FLOAT32, aspect) REGISTER_PARAMETER_MACRO("near", ANARI_FLOAT32, near) REGISTER_PARAMETER_MACRO("far", ANARI_FLOAT32, far) REGISTER_PARAMETER_MACRO("fovy", ANARI_FLOAT32, fovy) REGISTER_PARAMETER_MACRO("height", ANARI_FLOAT32, height) ) constexpr UsdCamera::ComponentPair UsdCamera::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays UsdCamera::UsdCamera(const char* name, const char* type, UsdDevice* device) : BridgedBaseObjectType(ANARI_CAMERA, name, device) { if(strEquals(type, "perspective")) cameraType = CAMERA_PERSPECTIVE; else if(strEquals(type, "orthographic")) cameraType = CAMERA_ORTHOGRAPHIC; } UsdCamera::~UsdCamera() { #ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME if(cachedBridge) cachedBridge->DeleteGroup(usdHandle); #endif } void UsdCamera::remove(UsdDevice* device) { applyRemoveFunc(device, &UsdBridge::DeleteCamera); } bool UsdCamera::deferCommit(UsdDevice* device) { return false; } void UsdCamera::copyParameters(UsdBridgeCameraData& camData) { typedef UsdBridgeCameraData::DataMemberId DMI; const UsdCameraData& paramData = getReadParams(); camData.Position = paramData.position; camData.Direction = paramData.direction; camData.Up = paramData.up; camData.ImageRegion = paramData.imageRegion; camData.Aspect = paramData.aspect; camData.Near = paramData.near; camData.Far = paramData.far; camData.Fovy = paramData.fovy; camData.Height = paramData.height; camData.TimeVarying = DMI::ALL & (isTimeVarying(CType::VIEW) ? DMI::ALL : ~DMI::VIEW) & (isTimeVarying(CType::PROJECTION) ? DMI::ALL : ~DMI::PROJECTION); } bool UsdCamera::doCommitData(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); const UsdCameraData& paramData = getReadParams(); double timeStep = device->getReadParams().timeStep; bool isNew = false; if (!usdHandle.value) isNew = usdBridge->CreateCamera(getName(), usdHandle); if (paramChanged || isNew) { UsdBridgeCameraData camData; copyParameters(camData); usdBridge->SetCameraData(usdHandle, camData, timeStep); paramChanged = false; } return false; }
2,864
C++
29.478723
128
0.745461
NVIDIA-Omniverse/AnariUsdDevice/UsdBaseObject.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "helium/utility/IntrusivePtr.h" #include "UsdCommonMacros.h" #include "UsdParameterizedObject.h" class UsdDevice; // Base parameterized class without being derived as such - nontemplated to allow for polymorphic use class UsdBaseObject : public helium::RefCounted { public: // If device != 0, the object is added to the commit list UsdBaseObject(ANARIDataType t, UsdDevice* device = nullptr); virtual void filterSetParam( const char *name, ANARIDataType type, const void *mem, UsdDevice* device) = 0; virtual void filterResetParam( const char *name) = 0; virtual void resetAllParams() = 0; virtual void* getParameter(const char* name, ANARIDataType& returnType) = 0; virtual int getProperty(const char *name, ANARIDataType type, void *mem, uint64_t size, UsdDevice* device) = 0; virtual void commit(UsdDevice* device) = 0; virtual void remove(UsdDevice* device) = 0; // Remove any committed data and refs ANARIDataType getType() const { return type; } protected: virtual bool deferCommit(UsdDevice* device) = 0; // Returns whether data commit has to be deferred virtual bool doCommitData(UsdDevice* device) = 0; // Data commit, execution can be immediate, returns whether doCommitRefs has to be performed virtual void doCommitRefs(UsdDevice* device) = 0; // For updates with dependencies on referenced object's data, is always executed deferred ANARIDataType type; friend class UsdDevice; }; // Templated base implementation of parameterized object template<typename T, typename D> class UsdParameterizedBaseObject : public UsdBaseObject, public UsdParameterizedObject<T, D> { public: typedef UsdParameterizedObject<T, D> ParamClass; UsdParameterizedBaseObject(ANARIDataType t, UsdDevice* device = nullptr) : UsdBaseObject(t, device) {} void filterSetParam( const char *name, ANARIDataType type, const void *mem, UsdDevice* device) override { ParamClass::setParam(name, type, mem, device); } void filterResetParam( const char *name) override { ParamClass::resetParam(name); } void resetAllParams() override { ParamClass::resetParams(); } void* getParameter(const char* name, ANARIDataType& returnType) override { return ParamClass::getParam(name, returnType); } int getProperty(const char *name, ANARIDataType type, void *mem, uint64_t size, UsdDevice* device) override { return 0; } void commit(UsdDevice* device) override { ParamClass::transferWriteToReadParams(); UsdBaseObject::commit(device); } // Convenience functions for commonly used name property virtual const char* getName() const { return ""; } protected: // Convenience functions for commonly used name property bool setNameParam(const char *name, ANARIDataType type, const void *mem, UsdDevice* device) { const char* objectName = static_cast<const char*>(mem); if (type == ANARI_STRING) { if (strEquals(name, "name")) { if (!objectName || strEquals(objectName, "")) { reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_WARNING, ANARI_STATUS_NO_ERROR, "%s: ANARI object %s cannot be an empty string, using auto-generated name instead.", getName(), "name"); } else { ParamClass::setParam(name, type, mem, device); ParamClass::setParam("usd::name", type, mem, device); this->formatUsdName(this->getWriteParams().usdName); } return true; } else if (strEquals(name, "usd::name")) { reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_WARNING, ANARI_STATUS_NO_ERROR, "%s parameter '%s' cannot be set, only read with getProperty().", getName(), "usd::name"); return true; } } return false; } int getNameProperty(const char *name, ANARIDataType type, void *mem, uint64_t size, UsdDevice* device) { if (type == ANARI_STRING && strEquals(name, "usd::name")) { snprintf((char*)mem, size, "%s", UsdSharedString::c_str(this->getReadParams().usdName)); return 1; } else if (type == ANARI_UINT64 && strEquals(name, "usd::name.size")) { if (Assert64bitStringLengthProperty(size, UsdLogInfo(device, this, ANARI_ARRAY, this->getName()), "usd::name.size")) { uint64_t nameLen = this->getReadParams().usdName ? strlen(this->getReadParams().usdName->c_str())+1 : 0; memcpy(mem, &nameLen, size); } return 1; } return 0; } };
5,007
C
29.168675
146
0.641901
NVIDIA-Omniverse/AnariUsdDevice/UsdAnari.h
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #pragma once #include "UsdBridgeData.h" #include "UsdCommonMacros.h" #include "anari/frontend/anari_enums.h" #include "anari/anari_cpp/Traits.h" #include <cstring> class UsdDevice; class UsdDataArray; class UsdFrame; class UsdGeometry; class UsdGroup; class UsdInstance; class UsdLight; class UsdMaterial; class UsdRenderer; class UsdSurface; class UsdSampler; class UsdSpatialField; class UsdVolume; class UsdWorld; class UsdCamera; class UsdSharedString; class UsdBaseObject; struct UsdDataLayout; namespace anari { ANARI_TYPEFOR_SPECIALIZATION(UsdUint2, ANARI_UINT32_VEC2); ANARI_TYPEFOR_SPECIALIZATION(UsdFloat2, ANARI_FLOAT32_VEC2); ANARI_TYPEFOR_SPECIALIZATION(UsdFloat3, ANARI_FLOAT32_VEC3); ANARI_TYPEFOR_SPECIALIZATION(UsdFloat4, ANARI_FLOAT32_VEC4); ANARI_TYPEFOR_SPECIALIZATION(UsdQuaternion, ANARI_FLOAT32_QUAT_IJKW); ANARI_TYPEFOR_SPECIALIZATION(UsdFloatMat4, ANARI_FLOAT32_MAT4); ANARI_TYPEFOR_SPECIALIZATION(UsdFloatBox1, ANARI_FLOAT32_BOX1); ANARI_TYPEFOR_SPECIALIZATION(UsdFloatBox2, ANARI_FLOAT32_BOX2); ANARI_TYPEFOR_SPECIALIZATION(UsdSharedString*, ANARI_STRING); ANARI_TYPEFOR_SPECIALIZATION(UsdDataArray*, ANARI_ARRAY); ANARI_TYPEFOR_SPECIALIZATION(UsdFrame*, ANARI_FRAME); ANARI_TYPEFOR_SPECIALIZATION(UsdGeometry*, ANARI_GEOMETRY); ANARI_TYPEFOR_SPECIALIZATION(UsdGroup*, ANARI_GROUP); ANARI_TYPEFOR_SPECIALIZATION(UsdInstance*, ANARI_INSTANCE); ANARI_TYPEFOR_SPECIALIZATION(UsdLight*, ANARI_LIGHT); ANARI_TYPEFOR_SPECIALIZATION(UsdMaterial*, ANARI_MATERIAL); ANARI_TYPEFOR_SPECIALIZATION(UsdRenderer*, ANARI_RENDERER); ANARI_TYPEFOR_SPECIALIZATION(UsdSampler*, ANARI_SAMPLER); ANARI_TYPEFOR_SPECIALIZATION(UsdSpatialField*, ANARI_SPATIAL_FIELD); ANARI_TYPEFOR_SPECIALIZATION(UsdSurface*, ANARI_SURFACE); ANARI_TYPEFOR_SPECIALIZATION(UsdVolume*, ANARI_VOLUME); ANARI_TYPEFOR_SPECIALIZATION(UsdWorld*, ANARI_WORLD); } // Shared convenience functions namespace { inline bool strEquals(const char* arg0, const char* arg1) { return strcmp(arg0, arg1) == 0; } template <typename T> inline void writeToVoidP(void *_p, T v) { T *p = (T *)_p; *p = v; } } // Standard log info struct UsdLogInfo { UsdLogInfo(UsdDevice* dev, void* src, ANARIDataType srcType, const char* srcName) : device(dev) , source(src) , sourceType(srcType) , sourceName(srcName) {} UsdDevice* device = nullptr; void* source = nullptr; ANARIDataType sourceType = ANARI_VOID_POINTER; const char* sourceName = nullptr; }; void reportStatusThroughDevice(const UsdLogInfo& logInfo, ANARIStatusSeverity severity, ANARIStatusCode statusCode, const char *format, const char* firstArg, const char* secondArg); // In case #include <UsdDevice.h> is undesired #ifdef CHECK_MEMLEAKS void logAllocationThroughDevice(UsdDevice* device, const void* ptr, ANARIDataType ptrType); void logDeallocationThroughDevice(UsdDevice* device, const void* ptr, ANARIDataType ptrType); #endif // Anari <=> USD conversions UsdBridgeType AnariToUsdBridgeType(ANARIDataType anariType); UsdBridgeType AnariToUsdBridgeType_Flattened(ANARIDataType anariType); const char* AnariTypeToString(ANARIDataType anariType); const char* AnariAttributeToUsdName(const char* param, bool perInstance, const UsdLogInfo& logInfo); UsdBridgeMaterialData::AlphaModes AnariToUsdAlphaMode(const char* alphaMode); ANARIStatusSeverity UsdBridgeLogLevelToAnariSeverity(UsdBridgeLogLevel level); bool Assert64bitStringLengthProperty(uint64_t size, const UsdLogInfo& logInfo, const char* propName); bool AssertOneDimensional(const UsdDataLayout& layout, const UsdLogInfo& logInfo, const char* arrayName); bool AssertNoStride(const UsdDataLayout& layout, const UsdLogInfo& logInfo, const char* arrayName); bool AssertArrayType(UsdDataArray* dataArray, ANARIDataType dataType, const UsdLogInfo& logInfo, const char* errorMessage); // Template definitions template<typename AnariType> class AnariToUsdObject {}; template<int AnariType> class AnariToUsdBridgedObject {}; template<int AnariType> class AnariToUsdBaseObject {}; #define USDBRIDGE_DEFINE_OBJECT_MAPPING(AnariType, UsdType) \ template<>\ class AnariToUsdObject<AnariType>\ {\ public:\ using Type = UsdType;\ }; #define USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(AnariType, UsdType) \ template<>\ class AnariToUsdBaseObject<(int)AnariType>\ {\ public:\ using Type = UsdType;\ }; #define USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(AnariType, UsdType)\ template<>\ class AnariToUsdBridgedObject<(int)AnariType>\ {\ public:\ using Type = UsdType;\ };\ template<>\ class AnariToUsdBaseObject<(int)AnariType>\ {\ public:\ using Type = UsdType;\ }; USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIObject, UsdBaseObject) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIDevice, UsdDevice) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray, UsdDataArray) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray1D, UsdDataArray) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray2D, UsdDataArray) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray3D, UsdDataArray) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIFrame, UsdFrame) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIGeometry, UsdGeometry) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIGroup, UsdGroup) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIInstance, UsdInstance) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARILight, UsdLight) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIMaterial, UsdMaterial) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARISampler, UsdSampler) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARISurface, UsdSurface) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIRenderer, UsdRenderer) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARISpatialField, UsdSpatialField) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIVolume, UsdVolume) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIWorld, UsdWorld) USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARICamera, UsdCamera) USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_DEVICE, UsdDevice) USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY, UsdDataArray) USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY1D, UsdDataArray) USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY2D, UsdDataArray) USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY3D, UsdDataArray) USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_FRAME, UsdFrame) USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_RENDERER, UsdRenderer) USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_GEOMETRY, UsdGeometry) USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_GROUP, UsdGroup) USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_INSTANCE, UsdInstance) USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_LIGHT, UsdLight) USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_MATERIAL, UsdMaterial) USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_SURFACE, UsdSurface) USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_SAMPLER, UsdSampler) USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_SPATIAL_FIELD, UsdSpatialField) USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_VOLUME, UsdVolume) USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_WORLD, UsdWorld) USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_CAMERA, UsdCamera) template<typename AnariType> typename AnariToUsdObject<AnariType>::Type* AnariToUsdObjectPtr(AnariType object) { return (typename AnariToUsdObject<AnariType>::Type*) object; }
7,214
C
36.38342
146
0.804963
NVIDIA-Omniverse/AnariUsdDevice/UsdWorld.cpp
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #include "UsdWorld.h" #include "UsdAnari.h" #include "UsdInstance.h" #include "UsdSurface.h" #include "UsdVolume.h" #include "UsdDevice.h" #include "UsdDataArray.h" #include "UsdGroup.h" #define InstanceType ANARI_INSTANCE #define SurfaceType ANARI_SURFACE #define VolumeType ANARI_VOLUME using InstanceUsdType = AnariToUsdBridgedObject<InstanceType>::Type; using SurfaceUsdType = AnariToUsdBridgedObject<SurfaceType>::Type; using VolumeUsdType = AnariToUsdBridgedObject<VolumeType>::Type; DEFINE_PARAMETER_MAP(UsdWorld, REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name) REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName) REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying) REGISTER_PARAMETER_MACRO("instance", ANARI_ARRAY, instances) REGISTER_PARAMETER_MACRO("surface", ANARI_ARRAY, surfaces) REGISTER_PARAMETER_MACRO("volume", ANARI_ARRAY, volumes) ) constexpr UsdWorld::ComponentPair UsdWorld::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays UsdWorld::UsdWorld(const char* name, UsdDevice* device) : BridgedBaseObjectType(ANARI_WORLD, name, device) { } UsdWorld::~UsdWorld() { #ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME if(cachedBridge) cachedBridge->DeleteWorld(usdHandle); #endif } void UsdWorld::remove(UsdDevice* device) { applyRemoveFunc(device, &UsdBridge::DeleteWorld); } bool UsdWorld::deferCommit(UsdDevice* device) { const UsdWorldData& paramData = getReadParams(); if(UsdObjectNotInitialized<InstanceUsdType>(paramData.instances) || UsdObjectNotInitialized<SurfaceUsdType>(paramData.surfaces) || UsdObjectNotInitialized<VolumeUsdType>(paramData.volumes)) { return true; } return false; } bool UsdWorld::doCommitData(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); const char* objName = getName(); bool isNew = false; if(!usdHandle.value) isNew = usdBridge->CreateWorld(objName, usdHandle); if (paramChanged || isNew) { doCommitRefs(device); // Perform immediate commit of refs - no params from children required paramChanged = false; } return false; } void UsdWorld::doCommitRefs(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); const UsdWorldData& paramData = getReadParams(); double timeStep = device->getReadParams().timeStep; const char* objName = getName(); bool instancesTimeVarying = isTimeVarying(UsdWorldComponents::INSTANCES); bool surfacesTimeVarying = isTimeVarying(UsdWorldComponents::SURFACES); bool volumesTimeVarying = isTimeVarying(UsdWorldComponents::VOLUMES); UsdLogInfo logInfo(device, this, ANARI_WORLD, this->getName()); ManageRefArray<InstanceType, ANARIInstance, UsdInstance>(usdHandle, paramData.instances, instancesTimeVarying, timeStep, instanceHandles, &UsdBridge::SetInstanceRefs, &UsdBridge::DeleteInstanceRefs, usdBridge, logInfo, "UsdWorld commit failed: 'instance' array elements should be of type ANARI_INSTANCE"); ManageRefArray<SurfaceType, ANARISurface, UsdSurface>(usdHandle, paramData.surfaces, surfacesTimeVarying, timeStep, surfaceHandles, &UsdBridge::SetSurfaceRefs, &UsdBridge::DeleteSurfaceRefs, usdBridge, logInfo, "UsdGroup commit failed: 'surface' array elements should be of type ANARI_SURFACE"); ManageRefArray<VolumeType, ANARIVolume, UsdVolume>(usdHandle, paramData.volumes, volumesTimeVarying, timeStep, volumeHandles, &UsdBridge::SetVolumeRefs, &UsdBridge::DeleteVolumeRefs, usdBridge, logInfo, "UsdGroup commit failed: 'volume' array elements should be of type ANARI_VOLUME"); }
3,668
C++
33.289719
126
0.771538
NVIDIA-Omniverse/AnariUsdDevice/UsdSurface.cpp
// Copyright 2020 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #include "UsdSurface.h" #include "UsdAnari.h" #include "UsdDevice.h" #include "UsdMaterial.h" #include "UsdGeometry.h" #define GeometryType ANARI_GEOMETRY #define MaterialType ANARI_MATERIAL using GeometryUsdType = AnariToUsdBridgedObject<GeometryType>::Type; using MaterialUsdType = AnariToUsdBridgedObject<MaterialType>::Type; DEFINE_PARAMETER_MAP(UsdSurface, REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name) REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName) REGISTER_PARAMETER_MACRO("usd::time.geometry", ANARI_FLOAT64, geometryRefTimeStep) REGISTER_PARAMETER_MACRO("usd::time.material", ANARI_FLOAT64, materialRefTimeStep) REGISTER_PARAMETER_MACRO("geometry", GeometryType, geometry) REGISTER_PARAMETER_MACRO("material", MaterialType, material) ) UsdSurface::UsdSurface(const char* name, UsdDevice* device) : BridgedBaseObjectType(ANARI_SURFACE, name, device) { } UsdSurface::~UsdSurface() { #ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME // Given that the object is destroyed, none of its references to other objects // has to be updated anymore. if(cachedBridge) cachedBridge->DeleteSurface(usdHandle); #endif } void UsdSurface::remove(UsdDevice* device) { applyRemoveFunc(device, &UsdBridge::DeleteSurface); } bool UsdSurface::deferCommit(UsdDevice* device) { // Given that all handles/data are used in doCommitRefs, which is always executed deferred, we don't need to check for initialization //const UsdSurfaceData& paramData = getReadParams(); //if(UsdObjectNotInitialized<GeometryUsdType>(paramData.geometry) || UsdObjectNotInitialized<MaterialUsdType>(paramData.material)) //{ // return true; //} return false; } bool UsdSurface::doCommitData(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); bool isNew = false; if (!usdHandle.value) isNew = usdBridge->CreateSurface(getName(), usdHandle); if (paramChanged || isNew) { paramChanged = false; return true; // In this case a doCommitRefs is required, with data (timesteps, handles) from children } return false; } void UsdSurface::doCommitRefs(UsdDevice* device) { UsdBridge* usdBridge = device->getUsdBridge(); const UsdSurfaceData& paramData = getReadParams(); double worldTimeStep = device->getReadParams().timeStep; // Make sure the references are updated on the Bridge side. if (paramData.geometry) { double geomObjTimeStep = paramData.geometry->getReadParams().timeStep; if(device->getReadParams().outputMaterial && paramData.material) { double matObjTimeStep = paramData.material->getReadParams().timeStep; // The geometry to which a material binds has an effect on attribute reader (geom primvar) names, and output types paramData.material->updateBoundParameters(paramData.geometry->isInstanced(), device); usdBridge->SetGeometryMaterialRef(usdHandle, paramData.geometry->getUsdHandle(), paramData.material->getUsdHandle(), worldTimeStep, selectRefTime(paramData.geometryRefTimeStep, geomObjTimeStep, worldTimeStep), selectRefTime(paramData.materialRefTimeStep, matObjTimeStep, worldTimeStep) ); } else { usdBridge->SetGeometryRef(usdHandle, paramData.geometry->getUsdHandle(), worldTimeStep, selectRefTime(paramData.geometryRefTimeStep, geomObjTimeStep, worldTimeStep) ); usdBridge->DeleteMaterialRef(usdHandle, worldTimeStep); } } else { usdBridge->DeleteGeometryRef(usdHandle, worldTimeStep); if (!paramData.material && device->getReadParams().outputMaterial) { usdBridge->DeleteMaterialRef(usdHandle, worldTimeStep); } } }
3,776
C++
30.475
135
0.739142