file_path
stringlengths
21
224
content
stringlengths
0
80.8M
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/gdtfFileFormat/gdtfFileFormat.cpp
// Copyright 2023 NVIDIA CORPORATION // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "gdtfFileFormat.h" #include <pxr/pxr.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/stringUtils.h> #include <pxr/base/tf/token.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usd/usdaFileFormat.h> #include <pxr/usd/usdGeom/mesh.h> #include <pxr/usd/usdGeom/scope.h> #include <pxr/usd/usdGeom/camera.h> #include <pxr/usd/usdGeom/cube.h> #include <pxr/usd/usdGeom/xformable.h> #include <pxr/usd/usdGeom/xform.h> #include <pxr/usd/usdLux/rectLight.h> #include <pxr/base/gf/matrix3f.h> #include <pxr/base/gf/vec3f.h> #include <pxr/base/gf/rotation.h> #include <pxr/usd/usd/payloads.h> #include "../mvrFileFormat/gdtfParser/GdtfParser.h" #include "gdtfUsdConverter.h" #include <fstream> #include <cmath> #include <iostream> #define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING #include <experimental/filesystem> PXR_NAMESPACE_OPEN_SCOPE GdtfFileFormat::GdtfFileFormat() : SdfFileFormat( GdtfFileFormatTokens->Id, GdtfFileFormatTokens->Version, GdtfFileFormatTokens->Target, GdtfFileFormatTokens->Extension) { } GdtfFileFormat::~GdtfFileFormat() { } bool GdtfFileFormat::CanRead(const std::string& filePath) const { return true; } static std::string CleanNameForUSD(const std::string& name) { std::string cleanedName = name; if(cleanedName.size() == 0) { return "Default"; } if(cleanedName.size() == 1 && !TfIsValidIdentifier(cleanedName)) { // If we have an index as a name, we only need to add _ beforehand. return CleanNameForUSD("_" + cleanedName); } return TfMakeValidIdentifier(cleanedName); } bool GdtfFileFormat::Read(SdfLayer* layer, const std::string& resolvedPath, bool metadataOnly) const { // Do parsing here... // TF_CODING_ERROR to throw errors // Create a new anonymous layer and wrap a stage around it. PXR_NAMESPACE_USING_DIRECTIVE if (!TF_VERIFY(layer)) { return false; } SdfLayerRefPtr newLayer = SdfLayer::CreateAnonymous(".usd"); UsdStageRefPtr stage = UsdStage::Open(newLayer); // Parse GDTF file auto parser = GDTF::GDTFParser(); GDTF::GDTFSpecification device = parser.ParseGDTFFile(resolvedPath); // Write to stage GDTF::ConvertToUsd(device, stage); // Copy contents into output layer. layer->TransferContent(newLayer); return true; } bool GdtfFileFormat::WriteToString(const SdfLayer& layer, std::string* str, const std::string& comment) const { // Implementation for two-way writting potentially return false; } bool GdtfFileFormat::WriteToStream(const SdfSpecHandle& spec, std::ostream& out, size_t indent) const { // this POC doesn't support writing return false; } bool GdtfFileFormat::_ShouldSkipAnonymousReload() const { return false; } bool GdtfFileFormat::_ShouldReadAnonymousLayers() const { return true; } void GdtfFileFormat::ComposeFieldsForFileFormatArguments(const std::string& assetPath, const PcpDynamicFileFormatContext& context, FileFormatArguments* args, VtValue* contextDependencyData) const { } bool GdtfFileFormat::CanFieldChangeAffectFileFormatArguments(const TfToken& field, const VtValue& oldValue, const VtValue& newValue, const VtValue& contextDependencyData) const { return true; } // these macros emit methods defined in the Pixar namespace // but not properly scoped, so we have to use the namespace // locally here TF_DEFINE_PUBLIC_TOKENS( GdtfFileFormatTokens, ((Id, "gdtfFileFormat")) ((Version, "1.0")) ((Target, "usd")) ((Extension, "gdtf")) ); TF_REGISTRY_FUNCTION(TfType) { SDF_DEFINE_FILE_FORMAT(GdtfFileFormat, SdfFileFormat); } PXR_NAMESPACE_CLOSE_SCOPE
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/gdtfFileFormat/tinyxml2.cpp
/* Original code by Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "tinyxml2.h" #include <new> // yes, this one new style header, is in the Android SDK. #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) # include <stddef.h> # include <stdarg.h> #else # include <cstddef> # include <cstdarg> #endif #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) // Microsoft Visual Studio, version 2005 and higher. Not WinCE. /*int _snprintf_s( char *buffer, size_t sizeOfBuffer, size_t count, const char *format [, argument] ... );*/ static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) { va_list va; va_start( va, format ); const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); va_end( va ); return result; } static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va ) { const int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); return result; } #define TIXML_VSCPRINTF _vscprintf #define TIXML_SSCANF sscanf_s #elif defined _MSC_VER // Microsoft Visual Studio 2003 and earlier or WinCE #define TIXML_SNPRINTF _snprintf #define TIXML_VSNPRINTF _vsnprintf #define TIXML_SSCANF sscanf #if (_MSC_VER < 1400 ) && (!defined WINCE) // Microsoft Visual Studio 2003 and not WinCE. #define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. #else // Microsoft Visual Studio 2003 and earlier or WinCE. static inline int TIXML_VSCPRINTF( const char* format, va_list va ) { int len = 512; for (;;) { len = len*2; char* str = new char[len](); const int required = _vsnprintf(str, len, format, va); delete[] str; if ( required != -1 ) { TIXMLASSERT( required >= 0 ); len = required; break; } } TIXMLASSERT( len >= 0 ); return len; } #endif #else // GCC version 3 and higher //#warning( "Using sn* functions." ) #define TIXML_SNPRINTF snprintf #define TIXML_VSNPRINTF vsnprintf static inline int TIXML_VSCPRINTF( const char* format, va_list va ) { int len = vsnprintf( 0, 0, format, va ); TIXMLASSERT( len >= 0 ); return len; } #define TIXML_SSCANF sscanf #endif #if defined(_WIN64) #define TIXML_FSEEK _fseeki64 #define TIXML_FTELL _ftelli64 #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || (__CYGWIN__) #define TIXML_FSEEK fseeko #define TIXML_FTELL ftello #elif defined(__ANDROID__) #if __ANDROID_API__ > 24 #define TIXML_FSEEK fseeko64 #define TIXML_FTELL ftello64 #else #define TIXML_FSEEK fseeko #define TIXML_FTELL ftello #endif #elif defined(__unix__) && defined(__x86_64__) #define TIXML_FSEEK fseeko64 #define TIXML_FTELL ftello64 #else #define TIXML_FSEEK fseek #define TIXML_FTELL ftell #endif static const char LINE_FEED = static_cast<char>(0x0a); // all line endings are normalized to LF static const char LF = LINE_FEED; static const char CARRIAGE_RETURN = static_cast<char>(0x0d); // CR gets filtered out static const char CR = CARRIAGE_RETURN; static const char SINGLE_QUOTE = '\''; static const char DOUBLE_QUOTE = '\"'; // Bunch of unicode info at: // http://www.unicode.org/faq/utf_bom.html // ef bb bf (Microsoft "lead bytes") - designates UTF-8 static const unsigned char TIXML_UTF_LEAD_0 = 0xefU; static const unsigned char TIXML_UTF_LEAD_1 = 0xbbU; static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; namespace tinyxml2 { struct Entity { const char* pattern; int length; char value; }; static const int NUM_ENTITIES = 5; static const Entity entities[NUM_ENTITIES] = { { "quot", 4, DOUBLE_QUOTE }, { "amp", 3, '&' }, { "apos", 4, SINGLE_QUOTE }, { "lt", 2, '<' }, { "gt", 2, '>' } }; StrPair::~StrPair() { Reset(); } void StrPair::TransferTo( StrPair* other ) { if ( this == other ) { return; } // This in effect implements the assignment operator by "moving" // ownership (as in auto_ptr). TIXMLASSERT( other != 0 ); TIXMLASSERT( other->_flags == 0 ); TIXMLASSERT( other->_start == 0 ); TIXMLASSERT( other->_end == 0 ); other->Reset(); other->_flags = _flags; other->_start = _start; other->_end = _end; _flags = 0; _start = 0; _end = 0; } void StrPair::Reset() { if ( _flags & NEEDS_DELETE ) { delete [] _start; } _flags = 0; _start = 0; _end = 0; } void StrPair::SetStr( const char* str, int flags ) { TIXMLASSERT( str ); Reset(); size_t len = strlen( str ); TIXMLASSERT( _start == 0 ); _start = new char[ len+1 ]; memcpy( _start, str, len+1 ); _end = _start + len; _flags = flags | NEEDS_DELETE; } char* StrPair::ParseText( char* p, const char* endTag, int strFlags, int* curLineNumPtr ) { TIXMLASSERT( p ); TIXMLASSERT( endTag && *endTag ); TIXMLASSERT(curLineNumPtr); char* start = p; const char endChar = *endTag; size_t length = strlen( endTag ); // Inner loop of text parsing. while ( *p ) { if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) { Set( start, p, strFlags ); return p + length; } else if (*p == '\n') { ++(*curLineNumPtr); } ++p; TIXMLASSERT( p ); } return 0; } char* StrPair::ParseName( char* p ) { if ( !p || !(*p) ) { return 0; } if ( !XMLUtil::IsNameStartChar( (unsigned char) *p ) ) { return 0; } char* const start = p; ++p; while ( *p && XMLUtil::IsNameChar( (unsigned char) *p ) ) { ++p; } Set( start, p, 0 ); return p; } void StrPair::CollapseWhitespace() { // Adjusting _start would cause undefined behavior on delete[] TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 ); // Trim leading space. _start = XMLUtil::SkipWhiteSpace( _start, 0 ); if ( *_start ) { const char* p = _start; // the read pointer char* q = _start; // the write pointer while( *p ) { if ( XMLUtil::IsWhiteSpace( *p )) { p = XMLUtil::SkipWhiteSpace( p, 0 ); if ( *p == 0 ) { break; // don't write to q; this trims the trailing space. } *q = ' '; ++q; } *q = *p; ++q; ++p; } *q = 0; } } const char* StrPair::GetStr() { TIXMLASSERT( _start ); TIXMLASSERT( _end ); if ( _flags & NEEDS_FLUSH ) { *_end = 0; _flags ^= NEEDS_FLUSH; if ( _flags ) { const char* p = _start; // the read pointer char* q = _start; // the write pointer while( p < _end ) { if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) { // CR-LF pair becomes LF // CR alone becomes LF // LF-CR becomes LF if ( *(p+1) == LF ) { p += 2; } else { ++p; } *q = LF; ++q; } else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) { if ( *(p+1) == CR ) { p += 2; } else { ++p; } *q = LF; ++q; } else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) { // Entities handled by tinyXML2: // - special entities in the entity table [in/out] // - numeric character reference [in] // &#20013; or &#x4e2d; if ( *(p+1) == '#' ) { const int buflen = 10; char buf[buflen] = { 0 }; int len = 0; const char* adjusted = const_cast<char*>( XMLUtil::GetCharacterRef( p, buf, &len ) ); if ( adjusted == 0 ) { *q = *p; ++p; ++q; } else { TIXMLASSERT( 0 <= len && len <= buflen ); TIXMLASSERT( q + len <= adjusted ); p = adjusted; memcpy( q, buf, len ); q += len; } } else { bool entityFound = false; for( int i = 0; i < NUM_ENTITIES; ++i ) { const Entity& entity = entities[i]; if ( strncmp( p + 1, entity.pattern, entity.length ) == 0 && *( p + entity.length + 1 ) == ';' ) { // Found an entity - convert. *q = entity.value; ++q; p += entity.length + 2; entityFound = true; break; } } if ( !entityFound ) { // fixme: treat as error? ++p; ++q; } } } else { *q = *p; ++p; ++q; } } *q = 0; } // The loop below has plenty going on, and this // is a less useful mode. Break it out. if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) { CollapseWhitespace(); } _flags = (_flags & NEEDS_DELETE); } TIXMLASSERT( _start ); return _start; } // --------- XMLUtil ----------- // const char* XMLUtil::writeBoolTrue = "true"; const char* XMLUtil::writeBoolFalse = "false"; void XMLUtil::SetBoolSerialization(const char* writeTrue, const char* writeFalse) { static const char* defTrue = "true"; static const char* defFalse = "false"; writeBoolTrue = (writeTrue) ? writeTrue : defTrue; writeBoolFalse = (writeFalse) ? writeFalse : defFalse; } const char* XMLUtil::ReadBOM( const char* p, bool* bom ) { TIXMLASSERT( p ); TIXMLASSERT( bom ); *bom = false; const unsigned char* pu = reinterpret_cast<const unsigned char*>(p); // Check for BOM: if ( *(pu+0) == TIXML_UTF_LEAD_0 && *(pu+1) == TIXML_UTF_LEAD_1 && *(pu+2) == TIXML_UTF_LEAD_2 ) { *bom = true; p += 3; } TIXMLASSERT( p ); return p; } void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) { const unsigned long BYTE_MASK = 0xBF; const unsigned long BYTE_MARK = 0x80; const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; if (input < 0x80) { *length = 1; } else if ( input < 0x800 ) { *length = 2; } else if ( input < 0x10000 ) { *length = 3; } else if ( input < 0x200000 ) { *length = 4; } else { *length = 0; // This code won't convert this correctly anyway. return; } output += *length; // Scary scary fall throughs are annotated with carefully designed comments // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc switch (*length) { case 4: --output; *output = static_cast<char>((input | BYTE_MARK) & BYTE_MASK); input >>= 6; //fall through case 3: --output; *output = static_cast<char>((input | BYTE_MARK) & BYTE_MASK); input >>= 6; //fall through case 2: --output; *output = static_cast<char>((input | BYTE_MARK) & BYTE_MASK); input >>= 6; //fall through case 1: --output; *output = static_cast<char>(input | FIRST_BYTE_MARK[*length]); break; default: TIXMLASSERT( false ); } } const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length ) { // Presume an entity, and pull it out. *length = 0; if ( *(p+1) == '#' && *(p+2) ) { unsigned long ucs = 0; TIXMLASSERT( sizeof( ucs ) >= 4 ); ptrdiff_t delta = 0; unsigned mult = 1; static const char SEMICOLON = ';'; if ( *(p+2) == 'x' ) { // Hexadecimal. const char* q = p+3; if ( !(*q) ) { return 0; } q = strchr( q, SEMICOLON ); if ( !q ) { return 0; } TIXMLASSERT( *q == SEMICOLON ); delta = q-p; --q; while ( *q != 'x' ) { unsigned int digit = 0; if ( *q >= '0' && *q <= '9' ) { digit = *q - '0'; } else if ( *q >= 'a' && *q <= 'f' ) { digit = *q - 'a' + 10; } else if ( *q >= 'A' && *q <= 'F' ) { digit = *q - 'A' + 10; } else { return 0; } TIXMLASSERT( digit < 16 ); TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); const unsigned int digitScaled = mult * digit; TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); ucs += digitScaled; TIXMLASSERT( mult <= UINT_MAX / 16 ); mult *= 16; --q; } } else { // Decimal. const char* q = p+2; if ( !(*q) ) { return 0; } q = strchr( q, SEMICOLON ); if ( !q ) { return 0; } TIXMLASSERT( *q == SEMICOLON ); delta = q-p; --q; while ( *q != '#' ) { if ( *q >= '0' && *q <= '9' ) { const unsigned int digit = *q - '0'; TIXMLASSERT( digit < 10 ); TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); const unsigned int digitScaled = mult * digit; TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); ucs += digitScaled; } else { return 0; } TIXMLASSERT( mult <= UINT_MAX / 10 ); mult *= 10; --q; } } // convert the UCS to UTF-8 ConvertUTF32ToUTF8( ucs, value, length ); return p + delta + 1; } return p+1; } void XMLUtil::ToStr( int v, char* buffer, int bufferSize ) { TIXML_SNPRINTF( buffer, bufferSize, "%d", v ); } void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize ) { TIXML_SNPRINTF( buffer, bufferSize, "%u", v ); } void XMLUtil::ToStr( bool v, char* buffer, int bufferSize ) { TIXML_SNPRINTF( buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse); } /* ToStr() of a number is a very tricky topic. https://github.com/leethomason/tinyxml2/issues/106 */ void XMLUtil::ToStr( float v, char* buffer, int bufferSize ) { TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v ); } void XMLUtil::ToStr( double v, char* buffer, int bufferSize ) { TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v ); } void XMLUtil::ToStr( int64_t v, char* buffer, int bufferSize ) { // horrible syntax trick to make the compiler happy about %lld TIXML_SNPRINTF(buffer, bufferSize, "%lld", static_cast<long long>(v)); } void XMLUtil::ToStr( uint64_t v, char* buffer, int bufferSize ) { // horrible syntax trick to make the compiler happy about %llu TIXML_SNPRINTF(buffer, bufferSize, "%llu", (long long)v); } bool XMLUtil::ToInt(const char* str, int* value) { if (IsPrefixHex(str)) { unsigned v; if (TIXML_SSCANF(str, "%x", &v) == 1) { *value = static_cast<int>(v); return true; } } else { if (TIXML_SSCANF(str, "%d", value) == 1) { return true; } } return false; } bool XMLUtil::ToUnsigned(const char* str, unsigned* value) { if (TIXML_SSCANF(str, IsPrefixHex(str) ? "%x" : "%u", value) == 1) { return true; } return false; } bool XMLUtil::ToBool( const char* str, bool* value ) { int ival = 0; if ( ToInt( str, &ival )) { *value = (ival==0) ? false : true; return true; } static const char* TRUE_VALS[] = { "true", "True", "TRUE", 0 }; static const char* FALSE_VALS[] = { "false", "False", "FALSE", 0 }; for (int i = 0; TRUE_VALS[i]; ++i) { if (StringEqual(str, TRUE_VALS[i])) { *value = true; return true; } } for (int i = 0; FALSE_VALS[i]; ++i) { if (StringEqual(str, FALSE_VALS[i])) { *value = false; return true; } } return false; } bool XMLUtil::ToFloat( const char* str, float* value ) { if ( TIXML_SSCANF( str, "%f", value ) == 1 ) { return true; } return false; } bool XMLUtil::ToDouble( const char* str, double* value ) { if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) { return true; } return false; } bool XMLUtil::ToInt64(const char* str, int64_t* value) { if (IsPrefixHex(str)) { unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llx if (TIXML_SSCANF(str, "%llx", &v) == 1) { *value = static_cast<int64_t>(v); return true; } } else { long long v = 0; // horrible syntax trick to make the compiler happy about %lld if (TIXML_SSCANF(str, "%lld", &v) == 1) { *value = static_cast<int64_t>(v); return true; } } return false; } bool XMLUtil::ToUnsigned64(const char* str, uint64_t* value) { unsigned long long v = 0; // horrible syntax trick to make the compiler happy about %llu if(TIXML_SSCANF(str, IsPrefixHex(str) ? "%llx" : "%llu", &v) == 1) { *value = (uint64_t)v; return true; } return false; } char* XMLDocument::Identify( char* p, XMLNode** node ) { TIXMLASSERT( node ); TIXMLASSERT( p ); char* const start = p; int const startLine = _parseCurLineNum; p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); if( !*p ) { *node = 0; TIXMLASSERT( p ); return p; } // These strings define the matching patterns: static const char* xmlHeader = { "<?" }; static const char* commentHeader = { "<!--" }; static const char* cdataHeader = { "<![CDATA[" }; static const char* dtdHeader = { "<!" }; static const char* elementHeader = { "<" }; // and a header for everything else; check last. static const int xmlHeaderLen = 2; static const int commentHeaderLen = 4; static const int cdataHeaderLen = 9; static const int dtdHeaderLen = 2; static const int elementHeaderLen = 1; TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLUnknown ) ); // use same memory pool TIXMLASSERT( sizeof( XMLComment ) == sizeof( XMLDeclaration ) ); // use same memory pool XMLNode* returnNode = 0; if ( XMLUtil::StringEqual( p, xmlHeader, xmlHeaderLen ) ) { returnNode = CreateUnlinkedNode<XMLDeclaration>( _commentPool ); returnNode->_parseLineNum = _parseCurLineNum; p += xmlHeaderLen; } else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) { returnNode = CreateUnlinkedNode<XMLComment>( _commentPool ); returnNode->_parseLineNum = _parseCurLineNum; p += commentHeaderLen; } else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) { XMLText* text = CreateUnlinkedNode<XMLText>( _textPool ); returnNode = text; returnNode->_parseLineNum = _parseCurLineNum; p += cdataHeaderLen; text->SetCData( true ); } else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) { returnNode = CreateUnlinkedNode<XMLUnknown>( _commentPool ); returnNode->_parseLineNum = _parseCurLineNum; p += dtdHeaderLen; } else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) { returnNode = CreateUnlinkedNode<XMLElement>( _elementPool ); returnNode->_parseLineNum = _parseCurLineNum; p += elementHeaderLen; } else { returnNode = CreateUnlinkedNode<XMLText>( _textPool ); returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character p = start; // Back it up, all the text counts. _parseCurLineNum = startLine; } TIXMLASSERT( returnNode ); TIXMLASSERT( p ); *node = returnNode; return p; } bool XMLDocument::Accept( XMLVisitor* visitor ) const { TIXMLASSERT( visitor ); if ( visitor->VisitEnter( *this ) ) { for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { if ( !node->Accept( visitor ) ) { break; } } } return visitor->VisitExit( *this ); } // --------- XMLNode ----------- // XMLNode::XMLNode( XMLDocument* doc ) : _document( doc ), _parent( 0 ), _value(), _parseLineNum( 0 ), _firstChild( 0 ), _lastChild( 0 ), _prev( 0 ), _next( 0 ), _userData( 0 ), _memPool( 0 ) { } XMLNode::~XMLNode() { DeleteChildren(); if ( _parent ) { _parent->Unlink( this ); } } const char* XMLNode::Value() const { // Edge case: XMLDocuments don't have a Value. Return null. if ( this->ToDocument() ) return 0; return _value.GetStr(); } void XMLNode::SetValue( const char* str, bool staticMem ) { if ( staticMem ) { _value.SetInternedStr( str ); } else { _value.SetStr( str ); } } XMLNode* XMLNode::DeepClone(XMLDocument* target) const { XMLNode* clone = this->ShallowClone(target); if (!clone) return 0; for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) { XMLNode* childClone = child->DeepClone(target); TIXMLASSERT(childClone); clone->InsertEndChild(childClone); } return clone; } void XMLNode::DeleteChildren() { while( _firstChild ) { TIXMLASSERT( _lastChild ); DeleteChild( _firstChild ); } _firstChild = _lastChild = 0; } void XMLNode::Unlink( XMLNode* child ) { TIXMLASSERT( child ); TIXMLASSERT( child->_document == _document ); TIXMLASSERT( child->_parent == this ); if ( child == _firstChild ) { _firstChild = _firstChild->_next; } if ( child == _lastChild ) { _lastChild = _lastChild->_prev; } if ( child->_prev ) { child->_prev->_next = child->_next; } if ( child->_next ) { child->_next->_prev = child->_prev; } child->_next = 0; child->_prev = 0; child->_parent = 0; } void XMLNode::DeleteChild( XMLNode* node ) { TIXMLASSERT( node ); TIXMLASSERT( node->_document == _document ); TIXMLASSERT( node->_parent == this ); Unlink( node ); TIXMLASSERT(node->_prev == 0); TIXMLASSERT(node->_next == 0); TIXMLASSERT(node->_parent == 0); DeleteNode( node ); } XMLNode* XMLNode::InsertEndChild( XMLNode* addThis ) { TIXMLASSERT( addThis ); if ( addThis->_document != _document ) { TIXMLASSERT( false ); return 0; } InsertChildPreamble( addThis ); if ( _lastChild ) { TIXMLASSERT( _firstChild ); TIXMLASSERT( _lastChild->_next == 0 ); _lastChild->_next = addThis; addThis->_prev = _lastChild; _lastChild = addThis; addThis->_next = 0; } else { TIXMLASSERT( _firstChild == 0 ); _firstChild = _lastChild = addThis; addThis->_prev = 0; addThis->_next = 0; } addThis->_parent = this; return addThis; } XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis ) { TIXMLASSERT( addThis ); if ( addThis->_document != _document ) { TIXMLASSERT( false ); return 0; } InsertChildPreamble( addThis ); if ( _firstChild ) { TIXMLASSERT( _lastChild ); TIXMLASSERT( _firstChild->_prev == 0 ); _firstChild->_prev = addThis; addThis->_next = _firstChild; _firstChild = addThis; addThis->_prev = 0; } else { TIXMLASSERT( _lastChild == 0 ); _firstChild = _lastChild = addThis; addThis->_prev = 0; addThis->_next = 0; } addThis->_parent = this; return addThis; } XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ) { TIXMLASSERT( addThis ); if ( addThis->_document != _document ) { TIXMLASSERT( false ); return 0; } TIXMLASSERT( afterThis ); if ( afterThis->_parent != this ) { TIXMLASSERT( false ); return 0; } if ( afterThis == addThis ) { // Current state: BeforeThis -> AddThis -> OneAfterAddThis // Now AddThis must disappear from it's location and then // reappear between BeforeThis and OneAfterAddThis. // So just leave it where it is. return addThis; } if ( afterThis->_next == 0 ) { // The last node or the only node. return InsertEndChild( addThis ); } InsertChildPreamble( addThis ); addThis->_prev = afterThis; addThis->_next = afterThis->_next; afterThis->_next->_prev = addThis; afterThis->_next = addThis; addThis->_parent = this; return addThis; } const XMLElement* XMLNode::FirstChildElement( const char* name ) const { for( const XMLNode* node = _firstChild; node; node = node->_next ) { const XMLElement* element = node->ToElementWithName( name ); if ( element ) { return element; } } return 0; } const XMLElement* XMLNode::LastChildElement( const char* name ) const { for( const XMLNode* node = _lastChild; node; node = node->_prev ) { const XMLElement* element = node->ToElementWithName( name ); if ( element ) { return element; } } return 0; } const XMLElement* XMLNode::NextSiblingElement( const char* name ) const { for( const XMLNode* node = _next; node; node = node->_next ) { const XMLElement* element = node->ToElementWithName( name ); if ( element ) { return element; } } return 0; } const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const { for( const XMLNode* node = _prev; node; node = node->_prev ) { const XMLElement* element = node->ToElementWithName( name ); if ( element ) { return element; } } return 0; } char* XMLNode::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) { // This is a recursive method, but thinking about it "at the current level" // it is a pretty simple flat list: // <foo/> // <!-- comment --> // // With a special case: // <foo> // </foo> // <!-- comment --> // // Where the closing element (/foo) *must* be the next thing after the opening // element, and the names must match. BUT the tricky bit is that the closing // element will be read by the child. // // 'endTag' is the end tag for this node, it is returned by a call to a child. // 'parentEnd' is the end tag for the parent, which is filled in and returned. XMLDocument::DepthTracker tracker(_document); if (_document->Error()) return 0; while( p && *p ) { XMLNode* node = 0; p = _document->Identify( p, &node ); TIXMLASSERT( p ); if ( node == 0 ) { break; } const int initialLineNum = node->_parseLineNum; StrPair endTag; p = node->ParseDeep( p, &endTag, curLineNumPtr ); if ( !p ) { _document->DeleteNode( node ); if ( !_document->Error() ) { _document->SetError( XML_ERROR_PARSING, initialLineNum, 0); } break; } const XMLDeclaration* const decl = node->ToDeclaration(); if ( decl ) { // Declarations are only allowed at document level // // Multiple declarations are allowed but all declarations // must occur before anything else. // // Optimized due to a security test case. If the first node is // a declaration, and the last node is a declaration, then only // declarations have so far been added. bool wellLocated = false; if (ToDocument()) { if (FirstChild()) { wellLocated = FirstChild() && FirstChild()->ToDeclaration() && LastChild() && LastChild()->ToDeclaration(); } else { wellLocated = true; } } if ( !wellLocated ) { _document->SetError( XML_ERROR_PARSING_DECLARATION, initialLineNum, "XMLDeclaration value=%s", decl->Value()); _document->DeleteNode( node ); break; } } XMLElement* ele = node->ToElement(); if ( ele ) { // We read the end tag. Return it to the parent. if ( ele->ClosingType() == XMLElement::CLOSING ) { if ( parentEndTag ) { ele->_value.TransferTo( parentEndTag ); } node->_memPool->SetTracked(); // created and then immediately deleted. DeleteNode( node ); return p; } // Handle an end tag returned to this level. // And handle a bunch of annoying errors. bool mismatch = false; if ( endTag.Empty() ) { if ( ele->ClosingType() == XMLElement::OPEN ) { mismatch = true; } } else { if ( ele->ClosingType() != XMLElement::OPEN ) { mismatch = true; } else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) { mismatch = true; } } if ( mismatch ) { _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, initialLineNum, "XMLElement name=%s", ele->Name()); _document->DeleteNode( node ); break; } } InsertEndChild( node ); } return 0; } /*static*/ void XMLNode::DeleteNode( XMLNode* node ) { if ( node == 0 ) { return; } TIXMLASSERT(node->_document); if (!node->ToDocument()) { node->_document->MarkInUse(node); } MemPool* pool = node->_memPool; node->~XMLNode(); pool->Free( node ); } void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const { TIXMLASSERT( insertThis ); TIXMLASSERT( insertThis->_document == _document ); if (insertThis->_parent) { insertThis->_parent->Unlink( insertThis ); } else { insertThis->_document->MarkInUse(insertThis); insertThis->_memPool->SetTracked(); } } const XMLElement* XMLNode::ToElementWithName( const char* name ) const { const XMLElement* element = this->ToElement(); if ( element == 0 ) { return 0; } if ( name == 0 ) { return element; } if ( XMLUtil::StringEqual( element->Name(), name ) ) { return element; } return 0; } // --------- XMLText ---------- // char* XMLText::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) { if ( this->CData() ) { p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); if ( !p ) { _document->SetError( XML_ERROR_PARSING_CDATA, _parseLineNum, 0 ); } return p; } else { int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) { flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; } p = _value.ParseText( p, "<", flags, curLineNumPtr ); if ( p && *p ) { return p-1; } if ( !p ) { _document->SetError( XML_ERROR_PARSING_TEXT, _parseLineNum, 0 ); } } return 0; } XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const { if ( !doc ) { doc = _document; } XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern? text->SetCData( this->CData() ); return text; } bool XMLText::ShallowEqual( const XMLNode* compare ) const { TIXMLASSERT( compare ); const XMLText* text = compare->ToText(); return ( text && XMLUtil::StringEqual( text->Value(), Value() ) ); } bool XMLText::Accept( XMLVisitor* visitor ) const { TIXMLASSERT( visitor ); return visitor->Visit( *this ); } // --------- XMLComment ---------- // XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc ) { } XMLComment::~XMLComment() { } char* XMLComment::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) { // Comment parses as text. p = _value.ParseText( p, "-->", StrPair::COMMENT, curLineNumPtr ); if ( p == 0 ) { _document->SetError( XML_ERROR_PARSING_COMMENT, _parseLineNum, 0 ); } return p; } XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const { if ( !doc ) { doc = _document; } XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern? return comment; } bool XMLComment::ShallowEqual( const XMLNode* compare ) const { TIXMLASSERT( compare ); const XMLComment* comment = compare->ToComment(); return ( comment && XMLUtil::StringEqual( comment->Value(), Value() )); } bool XMLComment::Accept( XMLVisitor* visitor ) const { TIXMLASSERT( visitor ); return visitor->Visit( *this ); } // --------- XMLDeclaration ---------- // XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc ) { } XMLDeclaration::~XMLDeclaration() { //printf( "~XMLDeclaration\n" ); } char* XMLDeclaration::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) { // Declaration parses as text. p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); if ( p == 0 ) { _document->SetError( XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0 ); } return p; } XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const { if ( !doc ) { doc = _document; } XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern? return dec; } bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const { TIXMLASSERT( compare ); const XMLDeclaration* declaration = compare->ToDeclaration(); return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() )); } bool XMLDeclaration::Accept( XMLVisitor* visitor ) const { TIXMLASSERT( visitor ); return visitor->Visit( *this ); } // --------- XMLUnknown ---------- // XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc ) { } XMLUnknown::~XMLUnknown() { } char* XMLUnknown::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) { // Unknown parses as text. p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); if ( !p ) { _document->SetError( XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0 ); } return p; } XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const { if ( !doc ) { doc = _document; } XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern? return text; } bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const { TIXMLASSERT( compare ); const XMLUnknown* unknown = compare->ToUnknown(); return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() )); } bool XMLUnknown::Accept( XMLVisitor* visitor ) const { TIXMLASSERT( visitor ); return visitor->Visit( *this ); } // --------- XMLAttribute ---------- // const char* XMLAttribute::Name() const { return _name.GetStr(); } const char* XMLAttribute::Value() const { return _value.GetStr(); } char* XMLAttribute::ParseDeep( char* p, bool processEntities, int* curLineNumPtr ) { // Parse using the name rules: bug fix, was using ParseText before p = _name.ParseName( p ); if ( !p || !*p ) { return 0; } // Skip white space before = p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); if ( *p != '=' ) { return 0; } ++p; // move up to opening quote p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); if ( *p != '\"' && *p != '\'' ) { return 0; } const char endTag[2] = { *p, 0 }; ++p; // move past opening quote p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, curLineNumPtr ); return p; } void XMLAttribute::SetName( const char* n ) { _name.SetStr( n ); } XMLError XMLAttribute::QueryIntValue( int* value ) const { if ( XMLUtil::ToInt( Value(), value )) { return XML_SUCCESS; } return XML_WRONG_ATTRIBUTE_TYPE; } XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const { if ( XMLUtil::ToUnsigned( Value(), value )) { return XML_SUCCESS; } return XML_WRONG_ATTRIBUTE_TYPE; } XMLError XMLAttribute::QueryInt64Value(int64_t* value) const { if (XMLUtil::ToInt64(Value(), value)) { return XML_SUCCESS; } return XML_WRONG_ATTRIBUTE_TYPE; } XMLError XMLAttribute::QueryUnsigned64Value(uint64_t* value) const { if(XMLUtil::ToUnsigned64(Value(), value)) { return XML_SUCCESS; } return XML_WRONG_ATTRIBUTE_TYPE; } XMLError XMLAttribute::QueryBoolValue( bool* value ) const { if ( XMLUtil::ToBool( Value(), value )) { return XML_SUCCESS; } return XML_WRONG_ATTRIBUTE_TYPE; } XMLError XMLAttribute::QueryFloatValue( float* value ) const { if ( XMLUtil::ToFloat( Value(), value )) { return XML_SUCCESS; } return XML_WRONG_ATTRIBUTE_TYPE; } XMLError XMLAttribute::QueryDoubleValue( double* value ) const { if ( XMLUtil::ToDouble( Value(), value )) { return XML_SUCCESS; } return XML_WRONG_ATTRIBUTE_TYPE; } void XMLAttribute::SetAttribute( const char* v ) { _value.SetStr( v ); } void XMLAttribute::SetAttribute( int v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); _value.SetStr( buf ); } void XMLAttribute::SetAttribute( unsigned v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); _value.SetStr( buf ); } void XMLAttribute::SetAttribute(int64_t v) { char buf[BUF_SIZE]; XMLUtil::ToStr(v, buf, BUF_SIZE); _value.SetStr(buf); } void XMLAttribute::SetAttribute(uint64_t v) { char buf[BUF_SIZE]; XMLUtil::ToStr(v, buf, BUF_SIZE); _value.SetStr(buf); } void XMLAttribute::SetAttribute( bool v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); _value.SetStr( buf ); } void XMLAttribute::SetAttribute( double v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); _value.SetStr( buf ); } void XMLAttribute::SetAttribute( float v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); _value.SetStr( buf ); } // --------- XMLElement ---------- // XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ), _closingType( OPEN ), _rootAttribute( 0 ) { } XMLElement::~XMLElement() { while( _rootAttribute ) { XMLAttribute* next = _rootAttribute->_next; DeleteAttribute( _rootAttribute ); _rootAttribute = next; } } const XMLAttribute* XMLElement::FindAttribute( const char* name ) const { for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) { if ( XMLUtil::StringEqual( a->Name(), name ) ) { return a; } } return 0; } const char* XMLElement::Attribute( const char* name, const char* value ) const { const XMLAttribute* a = FindAttribute( name ); if ( !a ) { return 0; } if ( !value || XMLUtil::StringEqual( a->Value(), value )) { return a->Value(); } return 0; } int XMLElement::IntAttribute(const char* name, int defaultValue) const { int i = defaultValue; QueryIntAttribute(name, &i); return i; } unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const { unsigned i = defaultValue; QueryUnsignedAttribute(name, &i); return i; } int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const { int64_t i = defaultValue; QueryInt64Attribute(name, &i); return i; } uint64_t XMLElement::Unsigned64Attribute(const char* name, uint64_t defaultValue) const { uint64_t i = defaultValue; QueryUnsigned64Attribute(name, &i); return i; } bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const { bool b = defaultValue; QueryBoolAttribute(name, &b); return b; } double XMLElement::DoubleAttribute(const char* name, double defaultValue) const { double d = defaultValue; QueryDoubleAttribute(name, &d); return d; } float XMLElement::FloatAttribute(const char* name, float defaultValue) const { float f = defaultValue; QueryFloatAttribute(name, &f); return f; } const char* XMLElement::GetText() const { /* skip comment node */ const XMLNode* node = FirstChild(); while (node) { if (node->ToComment()) { node = node->NextSibling(); continue; } break; } if ( node && node->ToText() ) { return node->Value(); } return 0; } void XMLElement::SetText( const char* inText ) { if ( FirstChild() && FirstChild()->ToText() ) FirstChild()->SetValue( inText ); else { XMLText* theText = GetDocument()->NewText( inText ); InsertFirstChild( theText ); } } void XMLElement::SetText( int v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); SetText( buf ); } void XMLElement::SetText( unsigned v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); SetText( buf ); } void XMLElement::SetText(int64_t v) { char buf[BUF_SIZE]; XMLUtil::ToStr(v, buf, BUF_SIZE); SetText(buf); } void XMLElement::SetText(uint64_t v) { char buf[BUF_SIZE]; XMLUtil::ToStr(v, buf, BUF_SIZE); SetText(buf); } void XMLElement::SetText( bool v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); SetText( buf ); } void XMLElement::SetText( float v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); SetText( buf ); } void XMLElement::SetText( double v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); SetText( buf ); } XMLError XMLElement::QueryIntText( int* ival ) const { if ( FirstChild() && FirstChild()->ToText() ) { const char* t = FirstChild()->Value(); if ( XMLUtil::ToInt( t, ival ) ) { return XML_SUCCESS; } return XML_CAN_NOT_CONVERT_TEXT; } return XML_NO_TEXT_NODE; } XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const { if ( FirstChild() && FirstChild()->ToText() ) { const char* t = FirstChild()->Value(); if ( XMLUtil::ToUnsigned( t, uval ) ) { return XML_SUCCESS; } return XML_CAN_NOT_CONVERT_TEXT; } return XML_NO_TEXT_NODE; } XMLError XMLElement::QueryInt64Text(int64_t* ival) const { if (FirstChild() && FirstChild()->ToText()) { const char* t = FirstChild()->Value(); if (XMLUtil::ToInt64(t, ival)) { return XML_SUCCESS; } return XML_CAN_NOT_CONVERT_TEXT; } return XML_NO_TEXT_NODE; } XMLError XMLElement::QueryUnsigned64Text(uint64_t* uval) const { if(FirstChild() && FirstChild()->ToText()) { const char* t = FirstChild()->Value(); if(XMLUtil::ToUnsigned64(t, uval)) { return XML_SUCCESS; } return XML_CAN_NOT_CONVERT_TEXT; } return XML_NO_TEXT_NODE; } XMLError XMLElement::QueryBoolText( bool* bval ) const { if ( FirstChild() && FirstChild()->ToText() ) { const char* t = FirstChild()->Value(); if ( XMLUtil::ToBool( t, bval ) ) { return XML_SUCCESS; } return XML_CAN_NOT_CONVERT_TEXT; } return XML_NO_TEXT_NODE; } XMLError XMLElement::QueryDoubleText( double* dval ) const { if ( FirstChild() && FirstChild()->ToText() ) { const char* t = FirstChild()->Value(); if ( XMLUtil::ToDouble( t, dval ) ) { return XML_SUCCESS; } return XML_CAN_NOT_CONVERT_TEXT; } return XML_NO_TEXT_NODE; } XMLError XMLElement::QueryFloatText( float* fval ) const { if ( FirstChild() && FirstChild()->ToText() ) { const char* t = FirstChild()->Value(); if ( XMLUtil::ToFloat( t, fval ) ) { return XML_SUCCESS; } return XML_CAN_NOT_CONVERT_TEXT; } return XML_NO_TEXT_NODE; } int XMLElement::IntText(int defaultValue) const { int i = defaultValue; QueryIntText(&i); return i; } unsigned XMLElement::UnsignedText(unsigned defaultValue) const { unsigned i = defaultValue; QueryUnsignedText(&i); return i; } int64_t XMLElement::Int64Text(int64_t defaultValue) const { int64_t i = defaultValue; QueryInt64Text(&i); return i; } uint64_t XMLElement::Unsigned64Text(uint64_t defaultValue) const { uint64_t i = defaultValue; QueryUnsigned64Text(&i); return i; } bool XMLElement::BoolText(bool defaultValue) const { bool b = defaultValue; QueryBoolText(&b); return b; } double XMLElement::DoubleText(double defaultValue) const { double d = defaultValue; QueryDoubleText(&d); return d; } float XMLElement::FloatText(float defaultValue) const { float f = defaultValue; QueryFloatText(&f); return f; } XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name ) { XMLAttribute* last = 0; XMLAttribute* attrib = 0; for( attrib = _rootAttribute; attrib; last = attrib, attrib = attrib->_next ) { if ( XMLUtil::StringEqual( attrib->Name(), name ) ) { break; } } if ( !attrib ) { attrib = CreateAttribute(); TIXMLASSERT( attrib ); if ( last ) { TIXMLASSERT( last->_next == 0 ); last->_next = attrib; } else { TIXMLASSERT( _rootAttribute == 0 ); _rootAttribute = attrib; } attrib->SetName( name ); } return attrib; } void XMLElement::DeleteAttribute( const char* name ) { XMLAttribute* prev = 0; for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) { if ( XMLUtil::StringEqual( name, a->Name() ) ) { if ( prev ) { prev->_next = a->_next; } else { _rootAttribute = a->_next; } DeleteAttribute( a ); break; } prev = a; } } char* XMLElement::ParseAttributes( char* p, int* curLineNumPtr ) { XMLAttribute* prevAttribute = 0; // Read the attributes. while( p ) { p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); if ( !(*p) ) { _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name() ); return 0; } // attribute. if (XMLUtil::IsNameStartChar( (unsigned char) *p ) ) { XMLAttribute* attrib = CreateAttribute(); TIXMLASSERT( attrib ); attrib->_parseLineNum = _document->_parseCurLineNum; const int attrLineNum = attrib->_parseLineNum; p = attrib->ParseDeep( p, _document->ProcessEntities(), curLineNumPtr ); if ( !p || Attribute( attrib->Name() ) ) { DeleteAttribute( attrib ); _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name() ); return 0; } // There is a minor bug here: if the attribute in the source xml // document is duplicated, it will not be detected and the // attribute will be doubly added. However, tracking the 'prevAttribute' // avoids re-scanning the attribute list. Preferring performance for // now, may reconsider in the future. if ( prevAttribute ) { TIXMLASSERT( prevAttribute->_next == 0 ); prevAttribute->_next = attrib; } else { TIXMLASSERT( _rootAttribute == 0 ); _rootAttribute = attrib; } prevAttribute = attrib; } // end of the tag else if ( *p == '>' ) { ++p; break; } // end of the tag else if ( *p == '/' && *(p+1) == '>' ) { _closingType = CLOSED; return p+2; // done; sealed element. } else { _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0 ); return 0; } } return p; } void XMLElement::DeleteAttribute( XMLAttribute* attribute ) { if ( attribute == 0 ) { return; } MemPool* pool = attribute->_memPool; attribute->~XMLAttribute(); pool->Free( attribute ); } XMLAttribute* XMLElement::CreateAttribute() { TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() ); XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); TIXMLASSERT( attrib ); attrib->_memPool = &_document->_attributePool; attrib->_memPool->SetTracked(); return attrib; } XMLElement* XMLElement::InsertNewChildElement(const char* name) { XMLElement* node = _document->NewElement(name); return InsertEndChild(node) ? node : 0; } XMLComment* XMLElement::InsertNewComment(const char* comment) { XMLComment* node = _document->NewComment(comment); return InsertEndChild(node) ? node : 0; } XMLText* XMLElement::InsertNewText(const char* text) { XMLText* node = _document->NewText(text); return InsertEndChild(node) ? node : 0; } XMLDeclaration* XMLElement::InsertNewDeclaration(const char* text) { XMLDeclaration* node = _document->NewDeclaration(text); return InsertEndChild(node) ? node : 0; } XMLUnknown* XMLElement::InsertNewUnknown(const char* text) { XMLUnknown* node = _document->NewUnknown(text); return InsertEndChild(node) ? node : 0; } // // <ele></ele> // <ele>foo<b>bar</b></ele> // char* XMLElement::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) { // Read the element name. p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); // The closing element is the </element> form. It is // parsed just like a regular element then deleted from // the DOM. if ( *p == '/' ) { _closingType = CLOSING; ++p; } p = _value.ParseName( p ); if ( _value.Empty() ) { return 0; } p = ParseAttributes( p, curLineNumPtr ); if ( !p || !*p || _closingType != OPEN ) { return p; } p = XMLNode::ParseDeep( p, parentEndTag, curLineNumPtr ); return p; } XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const { if ( !doc ) { doc = _document; } XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern? for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) { element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern? } return element; } bool XMLElement::ShallowEqual( const XMLNode* compare ) const { TIXMLASSERT( compare ); const XMLElement* other = compare->ToElement(); if ( other && XMLUtil::StringEqual( other->Name(), Name() )) { const XMLAttribute* a=FirstAttribute(); const XMLAttribute* b=other->FirstAttribute(); while ( a && b ) { if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) { return false; } a = a->Next(); b = b->Next(); } if ( a || b ) { // different count return false; } return true; } return false; } bool XMLElement::Accept( XMLVisitor* visitor ) const { TIXMLASSERT( visitor ); if ( visitor->VisitEnter( *this, _rootAttribute ) ) { for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { if ( !node->Accept( visitor ) ) { break; } } } return visitor->VisitExit( *this ); } // --------- XMLDocument ----------- // // Warning: List must match 'enum XMLError' const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = { "XML_SUCCESS", "XML_NO_ATTRIBUTE", "XML_WRONG_ATTRIBUTE_TYPE", "XML_ERROR_FILE_NOT_FOUND", "XML_ERROR_FILE_COULD_NOT_BE_OPENED", "XML_ERROR_FILE_READ_ERROR", "XML_ERROR_PARSING_ELEMENT", "XML_ERROR_PARSING_ATTRIBUTE", "XML_ERROR_PARSING_TEXT", "XML_ERROR_PARSING_CDATA", "XML_ERROR_PARSING_COMMENT", "XML_ERROR_PARSING_DECLARATION", "XML_ERROR_PARSING_UNKNOWN", "XML_ERROR_EMPTY_DOCUMENT", "XML_ERROR_MISMATCHED_ELEMENT", "XML_ERROR_PARSING", "XML_CAN_NOT_CONVERT_TEXT", "XML_NO_TEXT_NODE", "XML_ELEMENT_DEPTH_EXCEEDED" }; XMLDocument::XMLDocument( bool processEntities, Whitespace whitespaceMode ) : XMLNode( 0 ), _writeBOM( false ), _processEntities( processEntities ), _errorID(XML_SUCCESS), _whitespaceMode( whitespaceMode ), _errorStr(), _errorLineNum( 0 ), _charBuffer( 0 ), _parseCurLineNum( 0 ), _parsingDepth(0), _unlinked(), _elementPool(), _attributePool(), _textPool(), _commentPool() { // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) _document = this; } XMLDocument::~XMLDocument() { Clear(); } void XMLDocument::MarkInUse(const XMLNode* const node) { TIXMLASSERT(node); TIXMLASSERT(node->_parent == 0); for (int i = 0; i < _unlinked.Size(); ++i) { if (node == _unlinked[i]) { _unlinked.SwapRemove(i); break; } } } void XMLDocument::Clear() { DeleteChildren(); while( _unlinked.Size()) { DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete. } #ifdef TINYXML2_DEBUG const bool hadError = Error(); #endif ClearError(); delete [] _charBuffer; _charBuffer = 0; _parsingDepth = 0; #if 0 _textPool.Trace( "text" ); _elementPool.Trace( "element" ); _commentPool.Trace( "comment" ); _attributePool.Trace( "attribute" ); #endif #ifdef TINYXML2_DEBUG if ( !hadError ) { TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() ); TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() ); TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() ); TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() ); } #endif } void XMLDocument::DeepCopy(XMLDocument* target) const { TIXMLASSERT(target); if (target == this) { return; // technically success - a no-op. } target->Clear(); for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) { target->InsertEndChild(node->DeepClone(target)); } } XMLElement* XMLDocument::NewElement( const char* name ) { XMLElement* ele = CreateUnlinkedNode<XMLElement>( _elementPool ); ele->SetName( name ); return ele; } XMLComment* XMLDocument::NewComment( const char* str ) { XMLComment* comment = CreateUnlinkedNode<XMLComment>( _commentPool ); comment->SetValue( str ); return comment; } XMLText* XMLDocument::NewText( const char* str ) { XMLText* text = CreateUnlinkedNode<XMLText>( _textPool ); text->SetValue( str ); return text; } XMLDeclaration* XMLDocument::NewDeclaration( const char* str ) { XMLDeclaration* dec = CreateUnlinkedNode<XMLDeclaration>( _commentPool ); dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" ); return dec; } XMLUnknown* XMLDocument::NewUnknown( const char* str ) { XMLUnknown* unk = CreateUnlinkedNode<XMLUnknown>( _commentPool ); unk->SetValue( str ); return unk; } static FILE* callfopen( const char* filepath, const char* mode ) { TIXMLASSERT( filepath ); TIXMLASSERT( mode ); #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) FILE* fp = 0; const errno_t err = fopen_s( &fp, filepath, mode ); if ( err ) { return 0; } #else FILE* fp = fopen( filepath, mode ); #endif return fp; } void XMLDocument::DeleteNode( XMLNode* node ) { TIXMLASSERT( node ); TIXMLASSERT(node->_document == this ); if (node->_parent) { node->_parent->DeleteChild( node ); } else { // Isn't in the tree. // Use the parent delete. // Also, we need to mark it tracked: we 'know' // it was never used. node->_memPool->SetTracked(); // Call the static XMLNode version: XMLNode::DeleteNode(node); } } XMLError XMLDocument::LoadFile( const char* filename ) { if ( !filename ) { TIXMLASSERT( false ); SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=<null>" ); return _errorID; } Clear(); FILE* fp = callfopen( filename, "rb" ); if ( !fp ) { SetError( XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename ); return _errorID; } LoadFile( fp ); fclose( fp ); return _errorID; } XMLError XMLDocument::LoadFile( FILE* fp ) { Clear(); TIXML_FSEEK( fp, 0, SEEK_SET ); if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) { SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); return _errorID; } TIXML_FSEEK( fp, 0, SEEK_END ); unsigned long long filelength; { const long long fileLengthSigned = TIXML_FTELL( fp ); TIXML_FSEEK( fp, 0, SEEK_SET ); if ( fileLengthSigned == -1L ) { SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); return _errorID; } TIXMLASSERT( fileLengthSigned >= 0 ); filelength = static_cast<unsigned long long>(fileLengthSigned); } const size_t maxSizeT = static_cast<size_t>(-1); // We'll do the comparison as an unsigned long long, because that's guaranteed to be at // least 8 bytes, even on a 32-bit platform. if ( filelength >= static_cast<unsigned long long>(maxSizeT) ) { // Cannot handle files which won't fit in buffer together with null terminator SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); return _errorID; } if ( filelength == 0 ) { SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); return _errorID; } const size_t size = static_cast<size_t>(filelength); TIXMLASSERT( _charBuffer == 0 ); _charBuffer = new char[size+1]; const size_t read = fread( _charBuffer, 1, size, fp ); if ( read != size ) { SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); return _errorID; } _charBuffer[size] = 0; Parse(); return _errorID; } XMLError XMLDocument::SaveFile( const char* filename, bool compact ) { if ( !filename ) { TIXMLASSERT( false ); SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=<null>" ); return _errorID; } FILE* fp = callfopen( filename, "w" ); if ( !fp ) { SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename ); return _errorID; } SaveFile(fp, compact); fclose( fp ); return _errorID; } XMLError XMLDocument::SaveFile( FILE* fp, bool compact ) { // Clear any error from the last save, otherwise it will get reported // for *this* call. ClearError(); XMLPrinter stream( fp, compact ); Print( &stream ); return _errorID; } XMLError XMLDocument::Parse( const char* xml, size_t nBytes ) { Clear(); if ( nBytes == 0 || !xml || !*xml ) { SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); return _errorID; } if ( nBytes == static_cast<size_t>(-1) ) { nBytes = strlen( xml ); } TIXMLASSERT( _charBuffer == 0 ); _charBuffer = new char[ nBytes+1 ]; memcpy( _charBuffer, xml, nBytes ); _charBuffer[nBytes] = 0; Parse(); if ( Error() ) { // clean up now essentially dangling memory. // and the parse fail can put objects in the // pools that are dead and inaccessible. DeleteChildren(); _elementPool.Clear(); _attributePool.Clear(); _textPool.Clear(); _commentPool.Clear(); } return _errorID; } void XMLDocument::Print( XMLPrinter* streamer ) const { if ( streamer ) { Accept( streamer ); } else { XMLPrinter stdoutStreamer( stdout ); Accept( &stdoutStreamer ); } } void XMLDocument::ClearError() { _errorID = XML_SUCCESS; _errorLineNum = 0; _errorStr.Reset(); } void XMLDocument::SetError( XMLError error, int lineNum, const char* format, ... ) { TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT ); _errorID = error; _errorLineNum = lineNum; _errorStr.Reset(); const size_t BUFFER_SIZE = 1000; char* buffer = new char[BUFFER_SIZE]; TIXMLASSERT(sizeof(error) <= sizeof(int)); TIXML_SNPRINTF(buffer, BUFFER_SIZE, "Error=%s ErrorID=%d (0x%x) Line number=%d", ErrorIDToName(error), int(error), int(error), lineNum); if (format) { size_t len = strlen(buffer); TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": "); len = strlen(buffer); va_list va; va_start(va, format); TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va); va_end(va); } _errorStr.SetStr(buffer); delete[] buffer; } /*static*/ const char* XMLDocument::ErrorIDToName(XMLError errorID) { TIXMLASSERT( errorID >= 0 && errorID < XML_ERROR_COUNT ); const char* errorName = _errorNames[errorID]; TIXMLASSERT( errorName && errorName[0] ); return errorName; } const char* XMLDocument::ErrorStr() const { return _errorStr.Empty() ? "" : _errorStr.GetStr(); } void XMLDocument::PrintError() const { printf("%s\n", ErrorStr()); } const char* XMLDocument::ErrorName() const { return ErrorIDToName(_errorID); } void XMLDocument::Parse() { TIXMLASSERT( NoChildren() ); // Clear() must have been called previously TIXMLASSERT( _charBuffer ); _parseCurLineNum = 1; _parseLineNum = 1; char* p = _charBuffer; p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); p = const_cast<char*>( XMLUtil::ReadBOM( p, &_writeBOM ) ); if ( !*p ) { SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); return; } ParseDeep(p, 0, &_parseCurLineNum ); } void XMLDocument::PushDepth() { _parsingDepth++; if (_parsingDepth == TINYXML2_MAX_ELEMENT_DEPTH) { SetError(XML_ELEMENT_DEPTH_EXCEEDED, _parseCurLineNum, "Element nesting is too deep." ); } } void XMLDocument::PopDepth() { TIXMLASSERT(_parsingDepth > 0); --_parsingDepth; } XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) : _elementJustOpened( false ), _stack(), _firstElement( true ), _fp( file ), _depth( depth ), _textDepth( -1 ), _processEntities( true ), _compactMode( compact ), _buffer() { for( int i=0; i<ENTITY_RANGE; ++i ) { _entityFlag[i] = false; _restrictedEntityFlag[i] = false; } for( int i=0; i<NUM_ENTITIES; ++i ) { const char entityValue = entities[i].value; const unsigned char flagIndex = static_cast<unsigned char>(entityValue); TIXMLASSERT( flagIndex < ENTITY_RANGE ); _entityFlag[flagIndex] = true; } _restrictedEntityFlag[static_cast<unsigned char>('&')] = true; _restrictedEntityFlag[static_cast<unsigned char>('<')] = true; _restrictedEntityFlag[static_cast<unsigned char>('>')] = true; // not required, but consistency is nice _buffer.Push( 0 ); } void XMLPrinter::Print( const char* format, ... ) { va_list va; va_start( va, format ); if ( _fp ) { vfprintf( _fp, format, va ); } else { const int len = TIXML_VSCPRINTF( format, va ); // Close out and re-start the va-args va_end( va ); TIXMLASSERT( len >= 0 ); va_start( va, format ); TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 ); char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator. TIXML_VSNPRINTF( p, len+1, format, va ); } va_end( va ); } void XMLPrinter::Write( const char* data, size_t size ) { if ( _fp ) { fwrite ( data , sizeof(char), size, _fp); } else { char* p = _buffer.PushArr( static_cast<int>(size) ) - 1; // back up over the null terminator. memcpy( p, data, size ); p[size] = 0; } } void XMLPrinter::Putc( char ch ) { if ( _fp ) { fputc ( ch, _fp); } else { char* p = _buffer.PushArr( sizeof(char) ) - 1; // back up over the null terminator. p[0] = ch; p[1] = 0; } } void XMLPrinter::PrintSpace( int depth ) { for( int i=0; i<depth; ++i ) { Write( " " ); } } void XMLPrinter::PrintString( const char* p, bool restricted ) { // Look for runs of bytes between entities to print. const char* q = p; if ( _processEntities ) { const bool* flag = restricted ? _restrictedEntityFlag : _entityFlag; while ( *q ) { TIXMLASSERT( p <= q ); // Remember, char is sometimes signed. (How many times has that bitten me?) if ( *q > 0 && *q < ENTITY_RANGE ) { // Check for entities. If one is found, flush // the stream up until the entity, write the // entity, and keep looking. if ( flag[static_cast<unsigned char>(*q)] ) { while ( p < q ) { const size_t delta = q - p; const int toPrint = ( INT_MAX < delta ) ? INT_MAX : static_cast<int>(delta); Write( p, toPrint ); p += toPrint; } bool entityPatternPrinted = false; for( int i=0; i<NUM_ENTITIES; ++i ) { if ( entities[i].value == *q ) { Putc( '&' ); Write( entities[i].pattern, entities[i].length ); Putc( ';' ); entityPatternPrinted = true; break; } } if ( !entityPatternPrinted ) { // TIXMLASSERT( entityPatternPrinted ) causes gcc -Wunused-but-set-variable in release TIXMLASSERT( false ); } ++p; } } ++q; TIXMLASSERT( p <= q ); } // Flush the remaining string. This will be the entire // string if an entity wasn't found. if ( p < q ) { const size_t delta = q - p; const int toPrint = ( INT_MAX < delta ) ? INT_MAX : static_cast<int>(delta); Write( p, toPrint ); } } else { Write( p ); } } void XMLPrinter::PushHeader( bool writeBOM, bool writeDec ) { if ( writeBOM ) { static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 }; Write( reinterpret_cast< const char* >( bom ) ); } if ( writeDec ) { PushDeclaration( "xml version=\"1.0\"" ); } } void XMLPrinter::PrepareForNewNode( bool compactMode ) { SealElementIfJustOpened(); if ( compactMode ) { return; } if ( _firstElement ) { PrintSpace (_depth); } else if ( _textDepth < 0) { Putc( '\n' ); PrintSpace( _depth ); } _firstElement = false; } void XMLPrinter::OpenElement( const char* name, bool compactMode ) { PrepareForNewNode( compactMode ); _stack.Push( name ); Write ( "<" ); Write ( name ); _elementJustOpened = true; ++_depth; } void XMLPrinter::PushAttribute( const char* name, const char* value ) { TIXMLASSERT( _elementJustOpened ); Putc ( ' ' ); Write( name ); Write( "=\"" ); PrintString( value, false ); Putc ( '\"' ); } void XMLPrinter::PushAttribute( const char* name, int v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); PushAttribute( name, buf ); } void XMLPrinter::PushAttribute( const char* name, unsigned v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); PushAttribute( name, buf ); } void XMLPrinter::PushAttribute(const char* name, int64_t v) { char buf[BUF_SIZE]; XMLUtil::ToStr(v, buf, BUF_SIZE); PushAttribute(name, buf); } void XMLPrinter::PushAttribute(const char* name, uint64_t v) { char buf[BUF_SIZE]; XMLUtil::ToStr(v, buf, BUF_SIZE); PushAttribute(name, buf); } void XMLPrinter::PushAttribute( const char* name, bool v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); PushAttribute( name, buf ); } void XMLPrinter::PushAttribute( const char* name, double v ) { char buf[BUF_SIZE]; XMLUtil::ToStr( v, buf, BUF_SIZE ); PushAttribute( name, buf ); } void XMLPrinter::CloseElement( bool compactMode ) { --_depth; const char* name = _stack.Pop(); if ( _elementJustOpened ) { Write( "/>" ); } else { if ( _textDepth < 0 && !compactMode) { Putc( '\n' ); PrintSpace( _depth ); } Write ( "</" ); Write ( name ); Write ( ">" ); } if ( _textDepth == _depth ) { _textDepth = -1; } if ( _depth == 0 && !compactMode) { Putc( '\n' ); } _elementJustOpened = false; } void XMLPrinter::SealElementIfJustOpened() { if ( !_elementJustOpened ) { return; } _elementJustOpened = false; Putc( '>' ); } void XMLPrinter::PushText( const char* text, bool cdata ) { _textDepth = _depth-1; SealElementIfJustOpened(); if ( cdata ) { Write( "<![CDATA[" ); Write( text ); Write( "]]>" ); } else { PrintString( text, true ); } } void XMLPrinter::PushText( int64_t value ) { char buf[BUF_SIZE]; XMLUtil::ToStr( value, buf, BUF_SIZE ); PushText( buf, false ); } void XMLPrinter::PushText( uint64_t value ) { char buf[BUF_SIZE]; XMLUtil::ToStr(value, buf, BUF_SIZE); PushText(buf, false); } void XMLPrinter::PushText( int value ) { char buf[BUF_SIZE]; XMLUtil::ToStr( value, buf, BUF_SIZE ); PushText( buf, false ); } void XMLPrinter::PushText( unsigned value ) { char buf[BUF_SIZE]; XMLUtil::ToStr( value, buf, BUF_SIZE ); PushText( buf, false ); } void XMLPrinter::PushText( bool value ) { char buf[BUF_SIZE]; XMLUtil::ToStr( value, buf, BUF_SIZE ); PushText( buf, false ); } void XMLPrinter::PushText( float value ) { char buf[BUF_SIZE]; XMLUtil::ToStr( value, buf, BUF_SIZE ); PushText( buf, false ); } void XMLPrinter::PushText( double value ) { char buf[BUF_SIZE]; XMLUtil::ToStr( value, buf, BUF_SIZE ); PushText( buf, false ); } void XMLPrinter::PushComment( const char* comment ) { PrepareForNewNode( _compactMode ); Write( "<!--" ); Write( comment ); Write( "-->" ); } void XMLPrinter::PushDeclaration( const char* value ) { PrepareForNewNode( _compactMode ); Write( "<?" ); Write( value ); Write( "?>" ); } void XMLPrinter::PushUnknown( const char* value ) { PrepareForNewNode( _compactMode ); Write( "<!" ); Write( value ); Putc( '>' ); } bool XMLPrinter::VisitEnter( const XMLDocument& doc ) { _processEntities = doc.ProcessEntities(); if ( doc.HasBOM() ) { PushHeader( true, false ); } return true; } bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) { const XMLElement* parentElem = 0; if ( element.Parent() ) { parentElem = element.Parent()->ToElement(); } const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode; OpenElement( element.Name(), compactMode ); while ( attribute ) { PushAttribute( attribute->Name(), attribute->Value() ); attribute = attribute->Next(); } return true; } bool XMLPrinter::VisitExit( const XMLElement& element ) { CloseElement( CompactMode(element) ); return true; } bool XMLPrinter::Visit( const XMLText& text ) { PushText( text.Value(), text.CData() ); return true; } bool XMLPrinter::Visit( const XMLComment& comment ) { PushComment( comment.Value() ); return true; } bool XMLPrinter::Visit( const XMLDeclaration& declaration ) { PushDeclaration( declaration.Value() ); return true; } bool XMLPrinter::Visit( const XMLUnknown& unknown ) { PushUnknown( unknown.Value() ); return true; } } // namespace tinyxml2
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/gdtfFileFormat/plugInfo.json
{ "Plugins": [ { "Info": { "Types": { "GdtfFileFormat": { "bases": [ "SdfFileFormat" ], "displayName": "gdtf Dynamic File Format", "extensions": [ "gdtf" ], "formatId": "gdtfFileFormat", "primary": true, "target": "usd" } } }, "LibraryPath": "@PLUG_INFO_LIBRARY_PATH@", "Name": "gdtfFileFormat", "ResourcePath": "@PLUG_INFO_RESOURCE_PATH@", "Root": "@PLUG_INFO_ROOT@", "Type": "library" } ] }
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/gdtfFileFormat/gdtfUsdConverter.h
#pragma once #include "../mvrFileFormat/gdtfParser/ModelSpecification.h" #include <pxr/usd/usd/stage.h> namespace GDTF { void ConvertToUsd(const GDTFSpecification& spec, pxr::UsdStageRefPtr stage, const std::string& targetPrimPath = ""); }
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/gdtfFileFormat/gdtfFileFormat.h
// Copyright 2023 NVIDIA CORPORATION // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef OMNI_GDTF_GDTFFILEFORMAT_H_ #define OMNI_GDTF_GDTFFILEFORMAT_H_ #define NOMINMAX #include <pxr/base/tf/staticTokens.h> #include <pxr/pxr.h> #include <pxr/base/tf/token.h> #include <pxr/usd/sdf/fileFormat.h> #include <pxr/usd/sdf/layer.h> #include <pxr/usd/pcp/dynamicFileFormatInterface.h> #include <pxr/usd/pcp/dynamicFileFormatContext.h> #include "api.h" PXR_NAMESPACE_OPEN_SCOPE /// \class EdfFileFormat /// /// Represents a generic dynamic file format for external data. /// Actual acquisition of the external data is done via a set /// of plug-ins to various back-end external data systems. /// class GDTF_API GdtfFileFormat : public SdfFileFormat, public PcpDynamicFileFormatInterface { public: // SdfFileFormat overrides bool CanRead(const std::string& filePath) const override; bool Read(SdfLayer* layer, const std::string& resolvedPath, bool metadataOnly) const override; bool WriteToString(const SdfLayer& layer, std::string* str, const std::string& comment = std::string()) const override; bool WriteToStream(const SdfSpecHandle& spec, std::ostream& out, size_t indent) const override; // PcpDynamicFileFormatInterface overrides void ComposeFieldsForFileFormatArguments(const std::string& assetPath, const PcpDynamicFileFormatContext& context, FileFormatArguments* args, VtValue* contextDependencyData) const override; bool CanFieldChangeAffectFileFormatArguments(const TfToken& field, const VtValue& oldValue, const VtValue& newValue, const VtValue& contextDependencyData) const override; protected: SDF_FILE_FORMAT_FACTORY_ACCESS; bool _ShouldSkipAnonymousReload() const override; bool _ShouldReadAnonymousLayers() const override; virtual ~GdtfFileFormat(); GdtfFileFormat(); }; TF_DECLARE_PUBLIC_TOKENS( GdtfFileFormatTokens, ((Id, "gdtfFileFormat")) ((Version, "1.0")) ((Target, "usd")) ((Extension, "gdtf")) ); TF_DECLARE_WEAK_AND_REF_PTRS(GdtfFileFormat); PXR_NAMESPACE_CLOSE_SCOPE #endif
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/gdtfFileFormat/README.md
# usd-gdtf-plugin An OpenUSD plugin for the gdtf VESA standard # Requirements 1- An USD Installation 2- CMake # Build Instructions 1- cmake . -DPXR_PATH=PATH_TO_USD_INSTALL 2- Open generated .sln file and compile
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/gdtfFileFormat/gdtfUsdConverter.cpp
#include "gdtfUsdConverter.h" #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/stringUtils.h> #include <pxr/base/tf/token.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usd/usdaFileFormat.h> #include <pxr/usd/usdLux/diskLight.h> #include <pxr/usd/usdGeom/mesh.h> #include <pxr/usd/usdGeom/scope.h> #include <pxr/usd/usdGeom/camera.h> #include <pxr/usd/usdGeom/cube.h> #include <pxr/usd/usdGeom/xformable.h> #include <pxr/usd/usdGeom/xform.h> #include <pxr/usd/usdGeom/xformOp.h> #include <pxr/usd/usdLux/rectLight.h> #include <pxr/base/gf/matrix3f.h> #include <pxr/base/gf/rotation.h> #include <pxr/base/gf/vec3f.h> #include <pxr/usd/usd/payloads.h> #include <pxr/base/tf/stringUtils.h> #include <pxr/pxr.h> #include <pxr/base/tf/diagnostic.h> #include <pxr/base/tf/stringUtils.h> #include <pxr/base/tf/token.h> #include <iostream> #define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING #include <experimental/filesystem> namespace GDTF { std::string CleanNameForUSD(const std::string& name) { std::string cleanedName = name; if(cleanedName.size() == 0) { return "Default"; } if(cleanedName.size() == 1 && pxr::TfIsValidIdentifier(cleanedName)) { // If we have an index as a name, we only need to add _ beforehand. return CleanNameForUSD("_" + cleanedName); } return pxr::TfMakeValidIdentifier(cleanedName); } void ConvertToUsd(const GDTFSpecification& spec, pxr::UsdStageRefPtr stage, const std::string& targetPrimPath) { PXR_NAMESPACE_USING_DIRECTIVE SdfPath xformPath; const bool from3ds = spec.ConvertedFrom3ds; const bool isOnlyGDTF = targetPrimPath.empty(); if(isOnlyGDTF) { xformPath = SdfPath("/default_prim"); auto defaultPrim = UsdGeomXform::Define(stage, xformPath); stage->SetDefaultPrim(defaultPrim.GetPrim()); bool resetXform = false; defaultPrim.ClearXformOpOrder(); defaultPrim.AddTranslateOp(); defaultPrim.AddRotateYXZOp(UsdGeomXformOp::PrecisionDouble); defaultPrim.AddScaleOp().Set(GfVec3f(from3ds ? 1.0f : 100.0f)); } else { xformPath = SdfPath(targetPrimPath); } const GfMatrix3d rotateMinus90deg = GfMatrix3d(1, 0, 0, 0, 0, 1, 0, -1, 0); const std::string& parentPath = std::experimental::filesystem::temp_directory_path().string(); const auto& basePath = xformPath.AppendChild(TfToken("Base")); const auto& baseModelPath = basePath.AppendChild(TfToken("model")); const auto& baseXform = UsdGeomXform::Define(stage, basePath); const auto& baseModelXform = UsdGeomXform::Define(stage, baseModelPath); // Add GDTF custom properties to parent prim auto fixturePrim = stage->GetPrimAtPath(xformPath); fixturePrim.GetPrim().CreateAttribute(TfToken("mf:gdtf:LegHeight"), pxr::SdfValueTypeNames->Float).Set(spec.LegHeight); fixturePrim.GetPrim().CreateAttribute(TfToken("mf:gdtf:OperatingTemperature:High"), pxr::SdfValueTypeNames->Float).Set(spec.HighTemperature); fixturePrim.GetPrim().CreateAttribute(TfToken("mf:gdtf:OperatingTemperature:Low"), pxr::SdfValueTypeNames->Float).Set(spec.LowTemperature); fixturePrim.GetPrim().CreateAttribute(TfToken("mf:gdtf:Weight"), pxr::SdfValueTypeNames->Float).Set(spec.Weight); const float modelScaleFactor = spec.ConvertedFrom3ds ? 0.001f : 1.0f; const float modelBaseRotateAngle = from3ds ? -90.0f : 0.0f; if(spec.Name.empty()) { std::cout << "spec name is empty! " << std::endl; } SdfPath geoPath = xformPath; for(auto& geometry : spec.Geometries) { if(geometry.Name.empty()) { continue; } geoPath = geoPath.AppendChild(TfToken(CleanNameForUSD(geometry.Name))); if(!geometry.isBeam) { const auto& xform = UsdGeomXform::Define(stage, geoPath); GfMatrix4d transform = GfMatrix4d( geometry.Transform[0][0], geometry.Transform[1][0], geometry.Transform[2][0], 0, geometry.Transform[0][1], geometry.Transform[1][1], geometry.Transform[2][1], 0, geometry.Transform[0][2], geometry.Transform[1][2], geometry.Transform[2][2], 0, geometry.Transform[0][3], geometry.Transform[1][3], geometry.Transform[2][3], 1 ); GfVec3d translation = rotateMinus90deg * transform.ExtractTranslation(); GfRotation rotation = transform.GetTranspose().ExtractRotation(); GfVec3d euler = rotation.Decompose(GfVec3f::XAxis(), GfVec3f::YAxis(), GfVec3f::ZAxis()); GfVec3d rotate = rotateMinus90deg * euler; // Set transform xform.ClearXformOpOrder(); xform.AddTranslateOp().Set(translation); xform.AddRotateYZXOp(UsdGeomXformOp::PrecisionDouble).Set(rotate); xform.AddScaleOp().Set(GfVec3f(1.0)); const auto& modelPath = geoPath.AppendChild(TfToken("model")); const auto& modelXform = UsdGeomXform::Define(stage, modelPath); modelXform.AddTranslateOp().Set(GfVec3d(0)); modelXform.AddRotateYZXOp(UsdGeomXformOp::PrecisionDouble).Set(GfVec3d(modelBaseRotateAngle, 0, 0)); auto scaleOp = modelXform.AddScaleOp(); if(from3ds) { scaleOp.Set(GfVec3f(modelScaleFactor)); } std::string fileName = ""; for(auto m : spec.Models) { if(m.Name == geometry.Model) { fileName = m.File; } } std::string payloadPath = parentPath + "/" + spec.SpecName + "/" + fileName + ".gltf"; modelXform.GetPrim().GetPayloads().AddPayload(SdfPayload(payloadPath)); } else { SdfPath lightPath = geoPath.AppendChild(TfToken("Beam")); auto diskLight = UsdLuxDiskLight::Define(stage, lightPath); auto lightXform = UsdGeomXformable(diskLight); float heightOffset = 0.0f; // We need to find the parent of the beam, we use the depth to do this search // We fall back to the size of the beam if we cant find it. std::string parentModelName = geometry.Model; for(auto g : spec.Geometries) { if(g.Depth == geometry.Depth - 1) { parentModelName = g.Model; } } // Find the corresponding model of the parent const auto modelSpecIt = std::find_if(spec.Models.begin(), spec.Models.end(), [parentModelName](const ModelSpecification& model) { return model.Name == parentModelName; } ); // If we find it, we use the height as the offset if(modelSpecIt != spec.Models.end()) { const ModelSpecification& modelSpec = *modelSpecIt; heightOffset = modelSpec.Height * -0.5f; } GfMatrix4d transform = GfMatrix4d( geometry.Transform[0][0], geometry.Transform[1][0], geometry.Transform[2][0], 0, geometry.Transform[0][1], geometry.Transform[1][1], geometry.Transform[2][1], 0, geometry.Transform[0][2], geometry.Transform[1][2], geometry.Transform[2][2], 0, geometry.Transform[0][3], geometry.Transform[1][3], geometry.Transform[2][3], 1 ); GfRotation rotation = transform.GetTranspose().ExtractRotation(); GfVec3d euler = rotation.Decompose(GfVec3f::XAxis(), GfVec3f::YAxis(), GfVec3f::ZAxis()); GfVec3d rotate = (rotateMinus90deg * euler) + GfVec3d(-90, 0, 0); lightXform.ClearXformOpOrder(); lightXform.AddTranslateOp().Set(GfVec3d(0, heightOffset, 0)); lightXform.AddRotateYXZOp(UsdGeomXformOp::PrecisionDouble).Set(rotate); lightXform.AddScaleOp().Set(GfVec3f(spec.BeamRadius * 2.0, spec.BeamRadius * 2.0, 1)); diskLight.GetPrim().CreateAttribute( TfToken("intensity"), SdfValueTypeNames->Float ).Set(60000.0f); diskLight.GetPrim().CreateAttribute( TfToken("visibleInPrimaryRay"), SdfValueTypeNames->Bool ).Set(true); diskLight.GetPrim().CreateAttribute(TfToken("mf:gdtf:BeamAngle"), pxr::SdfValueTypeNames->Float).Set(spec.BeamAngle); diskLight.GetPrim().CreateAttribute(TfToken("mf:gdtf:BeamType"), pxr::SdfValueTypeNames->String).Set(spec.BeamType); diskLight.GetPrim().CreateAttribute(TfToken("mf:gdtf:ColorRenderingIndex"), pxr::SdfValueTypeNames->Int).Set(spec.ColorRenderingIndex); diskLight.GetPrim().CreateAttribute(TfToken("mf:gdtf:ColorTemperature"), pxr::SdfValueTypeNames->Float).Set(spec.ColorTemperature); diskLight.GetPrim().CreateAttribute(TfToken("mf:gdtf:FieldAngle"), pxr::SdfValueTypeNames->Float).Set(spec.FieldAngle); diskLight.GetPrim().CreateAttribute(TfToken("mf:gdtf:LampType"), pxr::SdfValueTypeNames->String).Set(spec.LampType); diskLight.GetPrim().CreateAttribute(TfToken("mf:gdtf:PowerConsumption"), pxr::SdfValueTypeNames->Float).Set(spec.PowerConsumption); diskLight.GetPrim().CreateAttribute(TfToken("mf:gdtf:LuminousFlux"), pxr::SdfValueTypeNames->Float).Set(spec.LuminousFlux); } } } }
MomentFactory/Omniverse-MVR-GDTF-converter/tools/packman/python.sh
#!/bin/bash # Copyright 2019-2020 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -e PACKMAN_CMD="$(dirname "${BASH_SOURCE}")/packman" if [ ! -f "$PACKMAN_CMD" ]; then PACKMAN_CMD="${PACKMAN_CMD}.sh" fi source "$PACKMAN_CMD" init export PYTHONPATH="${PM_MODULE_DIR}:${PYTHONPATH}" export PYTHONNOUSERSITE=1 # workaround for our python not shipping with certs if [[ -z ${SSL_CERT_DIR:-} ]]; then export SSL_CERT_DIR=/etc/ssl/certs/ fi "${PM_PYTHON}" -u "$@"
MomentFactory/Omniverse-MVR-GDTF-converter/tools/packman/python.bat
:: Copyright 2019-2020 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: http://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. @echo off setlocal call "%~dp0\packman" init set "PYTHONPATH=%PM_MODULE_DIR%;%PYTHONPATH%" set PYTHONNOUSERSITE=1 "%PM_PYTHON%" -u %*
MomentFactory/Omniverse-MVR-GDTF-converter/tools/packman/packmanconf.py
# Use this file to bootstrap packman into your Python environment (3.7.x). Simply # add the path by doing sys.insert to where packmanconf.py is located and then execute: # # >>> import packmanconf # >>> packmanconf.init() # # It will use the configured remote(s) and the version of packman in the same folder, # giving you full access to the packman API via the following module # # >> import packmanapi # >> dir(packmanapi) import os import platform import sys def init(): """Call this function to initialize the packman configuration. Calls to the packman API will work after successfully calling this function. Note: This function only needs to be called once during the execution of your program. Calling it repeatedly is harmless but wasteful. Compatibility with your Python interpreter is checked and upon failure the function will report what is required. Example: >>> import packmanconf >>> packmanconf.init() >>> import packmanapi >>> packmanapi.set_verbosity_level(packmanapi.VERBOSITY_HIGH) """ major = sys.version_info[0] minor = sys.version_info[1] if major != 3 or minor != 10: raise RuntimeError( f"This version of packman requires Python 3.10.x, but {major}.{minor} was provided" ) conf_dir = os.path.dirname(os.path.abspath(__file__)) os.environ["PM_INSTALL_PATH"] = conf_dir packages_root = get_packages_root(conf_dir) version = get_version(conf_dir) module_dir = get_module_dir(conf_dir, packages_root, version) sys.path.insert(1, module_dir) def get_packages_root(conf_dir: str) -> str: root = os.getenv("PM_PACKAGES_ROOT") if not root: platform_name = platform.system() if platform_name == "Windows": drive, _ = os.path.splitdrive(conf_dir) root = os.path.join(drive, "packman-repo") elif platform_name == "Darwin": # macOS root = os.path.join( os.path.expanduser("~"), "/Library/Application Support/packman-cache" ) elif platform_name == "Linux": try: cache_root = os.environ["XDG_HOME_CACHE"] except KeyError: cache_root = os.path.join(os.path.expanduser("~"), ".cache") return os.path.join(cache_root, "packman") else: raise RuntimeError(f"Unsupported platform '{platform_name}'") # make sure the path exists: os.makedirs(root, exist_ok=True) return root def get_module_dir(conf_dir, packages_root: str, version: str) -> str: module_dir = os.path.join(packages_root, "packman-common", version) if not os.path.exists(module_dir): import tempfile tf = tempfile.NamedTemporaryFile(delete=False) target_name = tf.name tf.close() url = f"http://bootstrap.packman.nvidia.com/packman-common@{version}.zip" print(f"Downloading '{url}' ...") import urllib.request urllib.request.urlretrieve(url, target_name) from importlib.machinery import SourceFileLoader # import module from path provided script_path = os.path.join(conf_dir, "bootstrap", "install_package.py") ip = SourceFileLoader("install_package", script_path).load_module() print("Unpacking ...") ip.install_package(target_name, module_dir) os.unlink(tf.name) return module_dir def get_version(conf_dir: str): path = os.path.join(conf_dir, "packman") if not os.path.exists(path): # in dev repo fallback path += ".sh" with open(path, "rt", encoding="utf8") as launch_file: for line in launch_file.readlines(): if line.startswith("PM_PACKMAN_VERSION"): _, value = line.split("=") return value.strip() raise RuntimeError(f"Unable to find 'PM_PACKMAN_VERSION' in '{path}'")
MomentFactory/Omniverse-MVR-GDTF-converter/tools/packman/packman.cmd
:: RUN_PM_MODULE must always be at the same spot for packman update to work (batch reloads file during update!) :: [xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx] :: Reset errorlevel status (don't inherit from caller) @call :ECHO_AND_RESET_ERROR :: You can remove this section if you do your own manual configuration of the dev machines call :CONFIGURE if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Everything below is mandatory if not defined PM_PYTHON goto :PYTHON_ENV_ERROR if not defined PM_MODULE goto :MODULE_ENV_ERROR set PM_VAR_PATH_ARG= if "%1"=="pull" goto :SET_VAR_PATH if "%1"=="install" goto :SET_VAR_PATH :RUN_PM_MODULE "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" %* %PM_VAR_PATH_ARG% if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Marshall environment variables into the current environment if they have been generated and remove temporary file if exist "%PM_VAR_PATH%" ( for /F "usebackq tokens=*" %%A in ("%PM_VAR_PATH%") do set "%%A" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) if exist "%PM_VAR_PATH%" ( del /F "%PM_VAR_PATH%" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) set PM_VAR_PATH= goto :eof :: Subroutines below :PYTHON_ENV_ERROR @echo User environment variable PM_PYTHON is not set! Please configure machine for packman or call configure.bat. exit /b 1 :MODULE_ENV_ERROR @echo User environment variable PM_MODULE is not set! Please configure machine for packman or call configure.bat. exit /b 1 :VAR_ERROR @echo Error while processing and setting environment variables! exit /b 1 :: pad [xxxx] :ECHO_AND_RESET_ERROR @echo off if /I "%PM_VERBOSITY%"=="debug" ( @echo on ) exit /b 0 :SET_VAR_PATH :: Generate temporary path for variable file for /f "delims=" %%a in ('%PM_PYTHON% -S -s -u -E -c "import tempfile;file = tempfile.NamedTemporaryFile(mode='w+t', delete=False);print(file.name)"') do (set PM_VAR_PATH=%%a) set PM_VAR_PATH_ARG=--var-path="%PM_VAR_PATH%" goto :RUN_PM_MODULE :CONFIGURE :: Must capture and set code page to work around issue #279, powershell invocation mutates console font :: This issue only happens in Windows CMD shell when using 65001 code page. Some Git Bash implementations :: don't support chcp so this workaround is a bit convoluted. :: Test for chcp: chcp > nul 2>&1 if %errorlevel% equ 0 ( for /f "tokens=2 delims=:" %%a in ('chcp') do (set PM_OLD_CODE_PAGE=%%a) ) else ( call :ECHO_AND_RESET_ERROR ) :: trim leading space (this is safe even when PM_OLD_CODE_PAGE has not been set) set PM_OLD_CODE_PAGE=%PM_OLD_CODE_PAGE:~1% if "%PM_OLD_CODE_PAGE%" equ "65001" ( chcp 437 > nul set PM_RESTORE_CODE_PAGE=1 ) call "%~dp0\bootstrap\configure.bat" set PM_CONFIG_ERRORLEVEL=%errorlevel% if defined PM_RESTORE_CODE_PAGE ( :: Restore code page chcp %PM_OLD_CODE_PAGE% > nul ) set PM_OLD_CODE_PAGE= set PM_RESTORE_CODE_PAGE= exit /b %PM_CONFIG_ERRORLEVEL%
MomentFactory/Omniverse-MVR-GDTF-converter/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
MomentFactory/Omniverse-MVR-GDTF-converter/tools/packman/bootstrap/generate_temp_file_name.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> $out = [System.IO.Path]::GetTempFileName() Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAK+Ewup1N0/mdf # 1l4R58rxyumHgZvTmEhrYTb2Zf0zd6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh # PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE # ChMUU3ltYW50ZWMg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yDw # HffXrwdqWy5/fgW3o3qJXqa5o7hLxYIoWSULOCpJRGdt+w7XKPAbZqHrN9elAhWJ # vpBTCEaj7dVxr1Ka4NsoPSYe0eidDBmmvGvp02J4Z1j8+ImQPKN6Hv/L8Ixaxe7V # mH4VtXIiBK8xXdi4wzO+A+qLtHEJXz3Gw8Bp3BNtlDGIUkIhVTM3Q1xcSEqhOLqo # PGdwCw9acxdXNWWPjOJkNH656Bvmkml+0p6MTGIeG4JCeRh1Wpqm1ZGSoEcXNaof # wOgj48YzI+dNqBD9i7RSWCqJr2ygYKRTxnuU # SIG # End signature block
MomentFactory/Omniverse-MVR-GDTF-converter/tools/packman/bootstrap/configure.bat
:: Copyright 2019-2023 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: http://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. set PM_PACKMAN_VERSION=7.3.2 :: Specify where packman command is rooted set PM_INSTALL_PATH=%~dp0.. :: The external root may already be configured and we should do minimal work in that case if defined PM_PACKAGES_ROOT goto ENSURE_DIR :: If the folder isn't set we assume that the best place for it is on the drive that we are currently :: running from set PM_DRIVE=%CD:~0,2% set PM_PACKAGES_ROOT=%PM_DRIVE%\packman-repo :: We use *setx* here so that the variable is persisted in the user environment echo Setting user environment variable PM_PACKAGES_ROOT to %PM_PACKAGES_ROOT% setx PM_PACKAGES_ROOT %PM_PACKAGES_ROOT% if %errorlevel% neq 0 ( goto ERROR ) :: The above doesn't work properly from a build step in VisualStudio because a separate process is :: spawned for it so it will be lost for subsequent compilation steps - VisualStudio must :: be launched from a new process. We catch this odd-ball case here: if defined PM_DISABLE_VS_WARNING goto ENSURE_DIR if not defined VSLANG goto ENSURE_DIR echo The above is a once-per-computer operation. Unfortunately VisualStudio cannot pick up environment change echo unless *VisualStudio is RELAUNCHED*. echo If you are launching VisualStudio from command line or command line utility make sure echo you have a fresh launch environment (relaunch the command line or utility). echo If you are using 'linkPath' and referring to packages via local folder links you can safely ignore this warning. echo You can disable this warning by setting the environment variable PM_DISABLE_VS_WARNING. echo. :: Check for the directory that we need. Note that mkdir will create any directories :: that may be needed in the path :ENSURE_DIR if not exist "%PM_PACKAGES_ROOT%" ( echo Creating packman packages cache at %PM_PACKAGES_ROOT% mkdir "%PM_PACKAGES_ROOT%" ) if %errorlevel% neq 0 ( goto ERROR_MKDIR_PACKAGES_ROOT ) :: The Python interpreter may already be externally configured if defined PM_PYTHON_EXT ( set PM_PYTHON=%PM_PYTHON_EXT% goto PACKMAN ) set PM_PYTHON_VERSION=3.10.5-1-windows-x86_64 set PM_PYTHON_BASE_DIR=%PM_PACKAGES_ROOT%\python set PM_PYTHON_DIR=%PM_PYTHON_BASE_DIR%\%PM_PYTHON_VERSION% set PM_PYTHON=%PM_PYTHON_DIR%\python.exe if exist "%PM_PYTHON%" goto PACKMAN if not exist "%PM_PYTHON_BASE_DIR%" call :CREATE_PYTHON_BASE_DIR set PM_PYTHON_PACKAGE=python@%PM_PYTHON_VERSION%.cab for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME%.zip call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_PYTHON_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching python from CDN !!! goto ERROR ) for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_folder.ps1" -parentPath "%PM_PYTHON_BASE_DIR%"') do set TEMP_FOLDER_NAME=%%a echo Unpacking Python interpreter ... "%SystemRoot%\system32\expand.exe" -F:* "%TARGET%" "%TEMP_FOLDER_NAME%" 1> nul del "%TARGET%" :: Failure during extraction to temp folder name, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error unpacking python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :: If python has now been installed by a concurrent process we need to clean up and then continue if exist "%PM_PYTHON%" ( call :CLEAN_UP_TEMP_FOLDER goto PACKMAN ) else ( if exist "%PM_PYTHON_DIR%" ( rd /s /q "%PM_PYTHON_DIR%" > nul ) ) :: Perform atomic move (allowing ovewrite, /y) move /y "%TEMP_FOLDER_NAME%" "%PM_PYTHON_DIR%" 1> nul :: Verify that python.exe is now where we expect if exist "%PM_PYTHON%" goto PACKMAN :: Wait a second and try again (can help with access denied weirdness) timeout /t 1 /nobreak 1> nul move /y "%TEMP_FOLDER_NAME%" "%PM_PYTHON_DIR%" 1> nul if %errorlevel% neq 0 ( echo !!! Error moving python %TEMP_FOLDER_NAME% -> %PM_PYTHON_DIR% !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :PACKMAN :: The packman module may already be externally configured if defined PM_MODULE_DIR_EXT ( set PM_MODULE_DIR=%PM_MODULE_DIR_EXT% ) else ( set PM_MODULE_DIR=%PM_PACKAGES_ROOT%\packman-common\%PM_PACKMAN_VERSION% ) set PM_MODULE=%PM_MODULE_DIR%\run.py if exist "%PM_MODULE%" goto END :: Clean out broken PM_MODULE_DIR if it exists if exist "%PM_MODULE_DIR%" ( rd /s /q "%PM_MODULE_DIR%" > nul ) set PM_MODULE_PACKAGE=packman-common@%PM_PACKMAN_VERSION%.zip for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME% call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_MODULE_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching packman from CDN !!! goto ERROR ) echo Unpacking ... "%PM_PYTHON%" -S -s -u -E "%~dp0\install_package.py" "%TARGET%" "%PM_MODULE_DIR%" if %errorlevel% neq 0 ( echo !!! Error unpacking packman !!! goto ERROR ) del "%TARGET%" goto END :ERROR_MKDIR_PACKAGES_ROOT echo Failed to automatically create packman packages repo at %PM_PACKAGES_ROOT%. echo Please set a location explicitly that packman has permission to write to, by issuing: echo. echo setx PM_PACKAGES_ROOT {path-you-choose-for-storing-packman-packages-locally} echo. echo Then launch a new command console for the changes to take effect and run packman command again. exit /B %errorlevel% :ERROR echo !!! Failure while configuring local machine :( !!! exit /B %errorlevel% :CLEAN_UP_TEMP_FOLDER rd /S /Q "%TEMP_FOLDER_NAME%" exit /B :CREATE_PYTHON_BASE_DIR :: We ignore errors and clean error state - if two processes create the directory one will fail which is fine md "%PM_PYTHON_BASE_DIR%" > nul 2>&1 exit /B 0 :END
MomentFactory/Omniverse-MVR-GDTF-converter/tools/packman/bootstrap/fetch_file_from_packman_bootstrap.cmd
:: Copyright 2019 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: http://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. :: You need to specify <package-name> <target-path> as input to this command @setlocal @set PACKAGE_NAME=%1 @set TARGET_PATH=%2 @echo Fetching %PACKAGE_NAME% ... @powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0download_file_from_url.ps1" ^ -source "http://bootstrap.packman.nvidia.com/%PACKAGE_NAME%" -output %TARGET_PATH% :: A bug in powershell prevents the errorlevel code from being set when using the -File execution option :: We must therefore do our own failure analysis, basically make sure the file exists: @if not exist %TARGET_PATH% goto ERROR_DOWNLOAD_FAILED @endlocal @exit /b 0 :ERROR_DOWNLOAD_FAILED @echo Failed to download file from S3 @echo Most likely because endpoint cannot be reached or file %PACKAGE_NAME% doesn't exist @endlocal @exit /b 1
MomentFactory/Omniverse-MVR-GDTF-converter/tools/packman/bootstrap/download_file_from_url.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> param( [Parameter(Mandatory=$true)][string]$source=$null, [string]$output="out.exe" ) $filename = $output $triesLeft = 4 $delay = 2 do { $triesLeft -= 1 try { Write-Host "Downloading from bootstrap.packman.nvidia.com ..." $wc = New-Object net.webclient $wc.Downloadfile($source, $fileName) exit 0 } catch { Write-Host "Error downloading $source!" Write-Host $_.Exception|format-list -force if ($triesLeft) { Write-Host "Retrying in $delay seconds ..." Start-Sleep -seconds $delay } $delay = $delay * $delay } } while ($triesLeft -gt 0) # We only get here if the retries have been exhausted, remove any left-overs: if (Test-Path $fileName) { Remove-Item $fileName } exit 1
MomentFactory/Omniverse-MVR-GDTF-converter/tools/packman/bootstrap/generate_temp_folder.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> param( [Parameter(Mandatory=$true)][string]$parentPath=$null ) [string] $name = [System.Guid]::NewGuid() $out = Join-Path $parentPath $name New-Item -ItemType Directory -Path ($out) | Out-Null Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgE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SIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG # SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3 # DQEJBDEiBCDvFxQ6lYLr8vB+9czUl19rjCw1pWhhUXw/SqOmvIa/VDANBgkqhkiG # 9w0BAQEFAASCAQB9ox2UrcUXQsBI4Uycnhl4AMpvhVXJME62tygFMppW1l7QftDy # LvfPKRYm2YUioak/APxAS6geRKpeMkLvXuQS/Jlv0kY3BjxkeG0eVjvyjF4SvXbZ # 3JCk9m7wLNE+xqOo0ICjYlIJJgRLudjWkC5Skpb1NpPS8DOaIYwRV+AWaSOUPd9P # O5yVcnbl7OpK3EAEtwDrybCVBMPn2MGhAXybIHnth3+MFp1b6Blhz3WlReQyarjq # 1f+zaFB79rg6JswXoOTJhwICBP3hO2Ua3dMAswbfl+QNXF+igKLJPYnaeSVhBbm6 # VCu2io27t4ixqvoD0RuPObNX/P3oVA38afiM # SIG # End signature block
MomentFactory/Omniverse-MVR-GDTF-converter/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import os import stat import time from typing import Any, Callable RENAME_RETRY_COUNT = 100 RENAME_RETRY_DELAY = 0.1 logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") def remove_directory_item(path): if os.path.islink(path) or os.path.isfile(path): try: os.remove(path) except PermissionError: # make sure we have access and try again: os.chmod(path, stat.S_IRWXU) os.remove(path) else: # try first to delete the dir because this will work for folder junctions, otherwise we would follow the junctions and cause destruction! clean_out_folder = False try: # make sure we have access preemptively - this is necessary because recursing into a directory without permissions # will only lead to heart ache os.chmod(path, stat.S_IRWXU) os.rmdir(path) except OSError: clean_out_folder = True if clean_out_folder: # we should make sure the directory is empty names = os.listdir(path) for name in names: fullname = os.path.join(path, name) remove_directory_item(fullname) # now try to again get rid of the folder - and not catch if it raises: os.rmdir(path) class StagingDirectory: def __init__(self, staging_path): self.staging_path = staging_path self.temp_folder_path = None os.makedirs(staging_path, exist_ok=True) def __enter__(self): self.temp_folder_path = tempfile.mkdtemp(prefix="ver-", dir=self.staging_path) return self def get_temp_folder_path(self): return self.temp_folder_path # this function renames the temp staging folder to folder_name, it is required that the parent path exists! def promote_and_rename(self, folder_name): abs_dst_folder_name = os.path.join(self.staging_path, folder_name) os.rename(self.temp_folder_path, abs_dst_folder_name) def __exit__(self, type, value, traceback): # Remove temp staging folder if it's still there (something went wrong): path = self.temp_folder_path if os.path.isdir(path): remove_directory_item(path) def rename_folder(staging_dir: StagingDirectory, folder_name: str): try: staging_dir.promote_and_rename(folder_name) except OSError as exc: # if we failed to rename because the folder now exists we can assume that another packman process # has managed to update the package before us - in all other cases we re-raise the exception abs_dst_folder_name = os.path.join(staging_dir.staging_path, folder_name) if os.path.exists(abs_dst_folder_name): logger.warning( f"Directory {abs_dst_folder_name} already present, package installation already completed" ) else: raise def call_with_retry( op_name: str, func: Callable, retry_count: int = 3, retry_delay: float = 20 ) -> Any: retries_left = retry_count while True: try: return func() except (OSError, IOError) as exc: logger.warning(f"Failure while executing {op_name} [{str(exc)}]") if retries_left: retry_str = "retry" if retries_left == 1 else "retries" logger.warning( f"Retrying after {retry_delay} seconds" f" ({retries_left} {retry_str} left) ..." ) time.sleep(retry_delay) else: logger.error("Maximum retries exceeded, giving up") raise retries_left -= 1 def rename_folder_with_retry(staging_dir: StagingDirectory, folder_name): dst_path = os.path.join(staging_dir.staging_path, folder_name) call_with_retry( f"rename {staging_dir.get_temp_folder_path()} -> {dst_path}", lambda: rename_folder(staging_dir, folder_name), RENAME_RETRY_COUNT, RENAME_RETRY_DELAY, ) def install_package(package_path, install_path): staging_path, version = os.path.split(install_path) with StagingDirectory(staging_path) as staging_dir: output_folder = staging_dir.get_temp_folder_path() with zipfile.ZipFile(package_path, allowZip64=True) as zip_file: zip_file.extractall(output_folder) # attempt the rename operation rename_folder_with_retry(staging_dir, version) print(f"Package successfully installed to {install_path}") if __name__ == "__main__": executable_paths = os.getenv("PATH") paths_list = executable_paths.split(os.path.pathsep) if executable_paths else [] target_path_np = os.path.normpath(sys.argv[2]) target_path_np_nc = os.path.normcase(target_path_np) for exec_path in paths_list: if os.path.normcase(os.path.normpath(exec_path)) == target_path_np_nc: raise RuntimeError(f"packman will not install to executable path '{exec_path}'") install_package(sys.argv[1], target_path_np)
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/gltfImporter.py
import logging import omni.client import os import subprocess import tempfile from typing import List import xml.etree.ElementTree as ET from zipfile import ZipFile from .filepathUtility import Filepath from .gdtfUtil import Model class GLTFImporter: TMP_ARCHIVE_EXTRACT_DIR = f"{tempfile.gettempdir()}/MF.OV.GDTF/" def convert(root: ET.Element, archive: ZipFile, output_dir: str) -> List[Model]: models: List[Model] = GLTFImporter._get_model_nodes(root) models_filtered: List[Model] = GLTFImporter._filter_models(models) GLTFImporter._extract_gltf_to_tmp(models_filtered, archive) GLTFImporter._convert_gltf(models_filtered, output_dir) return models def _get_model_nodes(root: ET.Element) -> List[Model]: node_fixture: ET.Element = root.find("FixtureType") node_models: ET.Element = node_fixture.find("Models") nodes_model = node_models.findall("Model") models: List[Model] = [] for node_model in nodes_model: models.append(Model(node_model)) return models def _filter_models(models: List[Model]) -> List[Model]: filters: List[str] = ['pigtail', 'beam'] filtered_models: List[Model] = [] for model in models: if model.has_file(): filtered_models.append(model) elif model.get_name().lower() not in filters: logger = logging.getLogger(__name__) logger.info(f"File attribute empty for model node {model.get_name()}, skipping.") return filtered_models def _extract_gltf_to_tmp(models: List[Model], gdtf_archive: ZipFile): namelist = gdtf_archive.namelist() to_remove: List[Model] = [] for model in models: filename = model.get_file() filepath_glb = f"models/gltf/{filename}.glb" filepath_gltf = f"models/gltf/{filename}.gltf" filepath_3ds = f"models/3ds/{filename}.3ds" if filepath_glb in namelist: tmp_export_path = gdtf_archive.extract(filepath_glb, GLTFImporter.TMP_ARCHIVE_EXTRACT_DIR) model.set_tmpdir_filepath(Filepath(tmp_export_path)) elif filepath_gltf in namelist: tmp_export_path = gdtf_archive.extract(filepath_gltf, GLTFImporter.TMP_ARCHIVE_EXTRACT_DIR) for filepath in namelist: # Also import .bin, textures, etc. if filepath.startswith(f"models/gltf/{filename}") and filepath != filepath_gltf: gdtf_archive.extract(filepath, GLTFImporter.TMP_ARCHIVE_EXTRACT_DIR) model.set_tmpdir_filepath(Filepath(tmp_export_path)) elif filepath_3ds in namelist: tmp_export_path = gdtf_archive.extract(filepath_3ds, GLTFImporter.TMP_ARCHIVE_EXTRACT_DIR) temp_export_path_gltf = tmp_export_path[:-4] + ".gltf" GLTFImporter._convert_3ds_to_gltf(tmp_export_path, temp_export_path_gltf) model.set_tmpdir_filepath(Filepath(temp_export_path_gltf)) model.set_converted_from_3ds() os.remove(tmp_export_path) else: logger = logging.getLogger(__name__) logger.warn(f"No file found for {filename}, skipping.") to_remove.append(model) for model in to_remove: models.remove(model) def _convert_3ds_to_gltf(input, output): path = __file__ my_env = os.environ.copy() my_env["PATH"] = path + '\\..\\' + os.pathsep + my_env['PATH'] scriptPath = path + "\\..\\3dsConverterScript.py" try: result = subprocess.run(["py", "-3.10", scriptPath, input, output], capture_output=True, env=my_env) if result.returncode != 0: logger = logging.getLogger(__name__) logger.error(f"Failed to convert 3ds file to gltf: {input}\nerror (Requires python 3.10): {result.stderr.decode('utf-8')}\nerror message: {result.stdout.decode('utf-8')}") except Exception as e: logger = logging.getLogger(__name__) logger.error(f"Failed to convert 3ds file to gltf: {input}\n{e}") def _convert_gltf(models: List[Model], gdtf_output_dir): output_dir = gdtf_output_dir + "gltf/" _, files_in_output_dir = omni.client.list(output_dir) # Ignoring omni.client.Result relative_paths_in_output_dir = [x.relative_path for x in files_in_output_dir] converted_models: List[Model] = [] for model in models: file: Filepath = model.get_tmpdir_filepath() if model.get_converted_from_3ds(): bin_file = file.basename[:-5] + ".bin" bin_path = output_dir + bin_file if bin_file not in relative_paths_in_output_dir: input_path = file.fullpath[:-5] + ".bin" result = result = omni.client.copy(input_path, bin_path, omni.client.CopyBehavior.OVERWRITE) output_file = file.basename output_path = output_dir + output_file if output_file not in relative_paths_in_output_dir: input_path = file.fullpath result = omni.client.copy(input_path, output_path, omni.client.CopyBehavior.OVERWRITE) if result == omni.client.Result.OK: model.set_converted_filepath(Filepath(output_path)) converted_models.append(model) else: logger = logging.getLogger(__name__) logger.error(f"Failure to convert file {input_path}: {result}") else: model.set_converted_filepath(Filepath(output_path)) converted_models.append(model) return converted_models
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/converterContext.py
class ConverterContext: usd_reference_path = ""
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/gdtfUtil.py
import math import xml.etree.ElementTree as ET from pxr import Usd, UsdGeom, UsdLux, Sdf from .filepathUtility import Filepath from .USDTools import USDTools def get_attrib_if_exists(node: ET.Element, attr: str): return node.attrib[attr] if attr in node.attrib else None def get_attrib_text_if_exists(node: ET.Element, attr: str): return get_attrib_if_exists(node, attr) def get_attrib_int_if_exists(node: ET.Element, attr: str): str_value = get_attrib_if_exists(node, attr) if str_value is not None: return int(str_value) return None def get_attrib_float_if_exists(node: ET.Element, attr: str): str_value = get_attrib_if_exists(node, attr) if str_value is not None: return float(str_value) return None def set_attribute_text_if_valid(prim: Usd.Prim, name: str, value: str): if value is not None: USDTools.set_prim_attribute(prim, name, Sdf.ValueTypeNames.String, value) def set_attribute_int_if_valid(prim: Usd.Prim, name: str, value: str): if value is not None: USDTools.set_prim_attribute(prim, name, Sdf.ValueTypeNames.Int, value) def set_attribute_float_if_valid(prim: Usd.Prim, name: str, value: str): if value is not None: USDTools.set_prim_attribute(prim, name, Sdf.ValueTypeNames.Float, value) class Model: def __init__(self, node: ET.Element): self._name = node.attrib["Name"] self._name_usd = USDTools.make_name_valid(self._name) self._file = get_attrib_if_exists(node, "File") self._primitive_type = node.attrib["PrimitiveType"] self._height = float(node.attrib["Height"]) self._length = float(node.attrib["Length"]) self._width = float(node.attrib["Width"]) self._converted_from_3ds = False def get_name(self) -> str: return self._name def get_name_usd(self) -> str: return self._name_usd def has_file(self) -> bool: return self._file is not None and self._file != "" def get_file(self) -> str: return self._file def set_tmpdir_filepath(self, path: Filepath): self._tmpdir_filepath = path def get_tmpdir_filepath(self) -> Filepath: return self._tmpdir_filepath def set_converted_from_3ds(self): self._converted_from_3ds = True def get_converted_from_3ds(self): return self._converted_from_3ds def set_converted_filepath(self, path: Filepath): self._converted_filepath = path def get_converted_filepath(self) -> Filepath: return self._converted_filepath def get_height(self) -> float: return self._height def get_width(self) -> float: return self._width class Geometry: def __init__(self, node: ET.Element): self._name: str = node.attrib["Name"] self._model_id: str = get_attrib_if_exists(node, "Model") self._position_matrix = node.attrib["Position"] self._tag = node.tag def get_tag(self) -> str: return self._tag def get_name(self) -> str: return self._name def get_model_id(self) -> str: if self._model_id is not None: return self._model_id return self._name def get_position_matrix(self) -> str: return self._position_matrix def set_model(self, model: Model): self._model = model def get_model(self) -> Model: return self._model def set_stage_path(self, path: str): self._stage_path = path def get_stage_path(self) -> str: return self._stage_path def set_depth(self, depth: int): self._depth = depth def get_depth(self) -> int: return self._depth def set_xform_model(self, xform: UsdGeom.Xform): self._xform_model = xform def get_xform_model(self) -> UsdGeom.Xform: return self._xform_model def set_xform_parent(self, xform: UsdGeom.Xform): self._xform_parent = xform def get_xform_parent(self) -> UsdGeom.Xform: return self._xform_parent class Beam: def __init__(self, geometry: Geometry, node: ET.Element): self._radius = float(node.attrib["BeamRadius"]) self._position_matrix = geometry.get_position_matrix() self._stage_path = geometry.get_stage_path() # The attributes should always exists as per standard definition self._beam_angle = get_attrib_float_if_exists(node, "BeamAngle") self._beam_type = get_attrib_text_if_exists(node, "BeamType") self._color_rendering_index = get_attrib_int_if_exists(node, "ColorRenderingIndex") self._color_temperature = get_attrib_float_if_exists(node, "ColorTemperature") self._field_angle = get_attrib_float_if_exists(node, "FieldAngle") self._lamp_type = get_attrib_text_if_exists(node, "LampType") self._luminous_flux = get_attrib_float_if_exists(node, "LuminousFlux") self._power_consumption = get_attrib_float_if_exists(node, "PowerConsumption") def get_radius(self) -> float: return self._radius def get_position_matrix(self) -> str: return self._position_matrix def get_stage_path(self) -> str: return self._stage_path def get_intensity(self) -> float: lumens = self._luminous_flux radius = self._radius if lumens is None: return None candela: float = lumens / 12.566 numerator = candela * 1000 denominator = 4 * math.pi * radius * radius result = numerator / denominator return result def apply_attributes_to_prim(self, light: UsdLux): prim: Usd.Prim = light.GetPrim() set_attribute_float_if_valid(prim, "BeamAngle", self._beam_angle) set_attribute_text_if_valid(prim, "BeamType", self._beam_type) set_attribute_int_if_valid(prim, "ColorRenderingIndex", self._color_rendering_index) set_attribute_float_if_valid(prim, "ColorTemperature", self._color_temperature) set_attribute_float_if_valid(prim, "FieldAngle", self._field_angle) set_attribute_text_if_valid(prim, "LampType", self._lamp_type) set_attribute_float_if_valid(prim, "LuminousFlux", self._luminous_flux) set_attribute_float_if_valid(prim, "PowerConsumption", self._power_consumption) USDTools.set_light_attributes(light, self._beam_angle, self.get_intensity(), self._color_temperature) class FixtureAttributes: def __init__(self, root: ET.Element): self._operating_temperature_high = None self._operating_temperature_low = None self._weight = None self._leg_height = None node_fixture: ET.Element = root.find("FixtureType") node_physdesc: ET.Element = node_fixture.find("PhysicalDescriptions") if node_physdesc is not None: node_properties: ET.Element = node_physdesc.find("Properties") if node_properties is not None: node_operatingtemp: ET.Element = node_properties.find("OperatingTemperature") if node_operatingtemp is not None: self._operating_temperature_high = get_attrib_float_if_exists(node_operatingtemp, "High") self._operating_temperature_low = get_attrib_float_if_exists(node_operatingtemp, "Low") node_weight: ET.Element = node_properties.find("Weight") if node_weight is not None: self._weight = get_attrib_float_if_exists(node_weight, "Value") node_legheight: ET.Element = node_properties.find("LegHeight") if node_legheight is not None: self._leg_height = get_attrib_float_if_exists(node_legheight, "Value") def apply_attributes_to_prim(self, prim: Usd.Prim): set_attribute_float_if_valid(prim, "OperatingTemperature:High", self._operating_temperature_high) set_attribute_float_if_valid(prim, "OperatingTemperature:Low", self._operating_temperature_low) set_attribute_float_if_valid(prim, "Weight", self._weight) set_attribute_float_if_valid(prim, "LegHeight", self._leg_height)
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/gdtfImporter.py
from io import BytesIO import logging from typing import List import xml.etree.ElementTree as ET from zipfile import ZipFile from pxr import Gf, Sdf, Usd, UsdGeom from .filepathUtility import Filepath from .gdtfUtil import Model, Geometry, Beam, FixtureAttributes from .gltfImporter import GLTFImporter from .USDTools import USDTools class GDTFImporter: def convert(file: Filepath, output_dir: str, output_ext: str = ".usd") -> str: try: with ZipFile(file.fullpath, 'r') as archive: gdtf_output_dir = output_dir + file.filename + "_gdtf/" url: str = GDTFImporter._convert(archive, gdtf_output_dir, file.filename, output_ext) return url except Exception as e: logger = logging.getLogger(__name__) logger.error(f"Failed to parse gdtf file at {file.fullpath}. Make sure it is not corrupt. {e}") return None def convert_from_mvr(spec_name: str, output_dir: str, mvr_archive: ZipFile, output_ext: str = ".usd") -> bool: spec_name_with_ext = spec_name + ".gdtf" if spec_name_with_ext in mvr_archive.namelist(): gdtf_data = BytesIO(mvr_archive.read(spec_name_with_ext)) gdtf_output_dir = output_dir + spec_name + "_gdtf/" with ZipFile(gdtf_data) as gdtf_archive: GDTFImporter._convert(gdtf_archive, gdtf_output_dir, spec_name, output_ext) return True else: return False def _convert(archive: ZipFile, output_dir: str, name: str, output_ext: str) -> str: data = archive.read("description.xml") root = ET.fromstring(data) converted_models: List[Model] = GLTFImporter.convert(root, archive, output_dir) url: str = GDTFImporter._convert_gdtf_usd(output_dir, name, output_ext, root, converted_models) return url def _convert_gdtf_usd(output_dir: str, filename: str, ext: str, root: ET.Element, models: List[Model]) -> str: url: str = output_dir + filename + ext stage: Usd.Stage = GDTFImporter._get_or_create_gdtf_usd(url) geometries, beams = GDTFImporter._get_stage_hierarchy(root, models, stage) GDTFImporter._add_gltf_reference(stage, geometries) GDTFImporter._apply_gdtf_matrix(stage, geometries) GDTFImporter._add_light_to_hierarchy(stage, beams, geometries) GDTFImporter._apply_gltf_scale(stage, geometries) GDTFImporter._set_general_attributes(stage, root) return url def _get_or_create_gdtf_usd(url: str) -> Usd.Stage: return USDTools.get_or_create_stage(url) def _get_stage_hierarchy(root: ET.Element, models: List[Model], stage: Usd.Stage) -> (List[Geometry], List[Beam]): node_fixture: ET.Element = root.find("FixtureType") node_geometries = node_fixture.find("Geometries") default_prim_path = stage.GetDefaultPrim().GetPath() geometries: List[Geometry] = [] beams: List[Beam] = [] GDTFImporter._get_stage_hierarchy_recursive(node_geometries, models, geometries, beams, default_prim_path, 0) return geometries, beams def _get_stage_hierarchy_recursive(parent_node: ET.Element, models: List[Model], geometries: List[Geometry], beams: List[Beam], path: str, depth: int): geometry_filter: List[str] = ['Geometry', 'Axis', 'Beam', 'Inventory'] for child_node in list(parent_node): if 'Model' in child_node.attrib: if child_node.tag not in geometry_filter: # Pass through (might want to add an xform) GDTFImporter._get_stage_hierarchy_recursive(child_node, models, geometries, beams, path, depth + 1) else: geometry: Geometry = Geometry(child_node) model_id: str = geometry.get_model_id() model: Model = next((model for model in models if model.get_name() == model_id), None) if model is not None and model.has_file(): geometry.set_model(model) stage_path = f"{path}/{model.get_name_usd()}" geometry.set_stage_path(stage_path) geometry.set_depth(depth) geometries.append(geometry) GDTFImporter._get_stage_hierarchy_recursive(child_node, models, geometries, beams, stage_path, depth + 1) else: if model_id.lower() == "pigtail": pass # Skip pigtail geometry elif model_id.lower() == "beam": stage_path = f"{path}/beam" geometry.set_stage_path(stage_path) beam: Beam = Beam(geometry, child_node) beams.append(beam) elif model is not None and not model.has_file(): logger = logging.getLogger(__name__) logger.warn(f"No file found for {model_id}, skipping.") else: # Probably could just be a transform pass else: # Probably could just be a transform pass def _add_gltf_reference(stage: Usd.Stage, geometries: List[Geometry]): stage_path = Filepath(USDTools.get_stage_directory(stage)) for geometry in geometries: model: Model = geometry.get_model() relative_path: str = stage_path.get_relative_from(model.get_converted_filepath()) xform_parent, xform_model = USDTools.add_reference(stage, relative_path, geometry.get_stage_path(), "/model") xform_model.GetPrim().CreateAttribute("mf:gdtf:converter_from_3ds", Sdf.ValueTypeNames.Bool).Set(model.get_converted_from_3ds()) geometry.set_xform_parent(xform_parent) geometry.set_xform_model(xform_model) stage.Save() def _apply_gltf_scale(stage: Usd.Stage, geometries: List[Geometry]): world_xform: UsdGeom.Xform = UsdGeom.Xform(stage.GetDefaultPrim()) stage_metersPerUnit = UsdGeom.GetStageMetersPerUnit(stage) scale = 1 / stage_metersPerUnit USDTools.apply_scale_xform_op(world_xform, scale) converted_3ds = False for geometry in geometries: model = geometry.get_model() if model.get_converted_from_3ds(): converted_3ds = True if converted_3ds: for geometry in geometries: if geometry.get_tag() != 'Beam': xform = geometry.get_xform_model() USDTools.apply_scale_xform_op(xform, UsdGeom.LinearUnits.millimeters) # force mm stage.Save() def _apply_gdtf_matrix(stage: Usd.Stage, geometries: List[Geometry]): applied_scale = USDTools.compute_applied_scale(stage) axis_matrix = USDTools.get_axis_rotation_matrix() for geometry in geometries: translation, rotation = USDTools.compute_xform_values(geometry.get_position_matrix(), applied_scale, axis_matrix) xform: UsdGeom.Xform = geometry.get_xform_parent() xform.ClearXformOpOrder() # Prevent error when overwritting xform.AddTranslateOp().Set(translation) xform.AddRotateZYXOp().Set(rotation) xform.AddScaleOp().Set(Gf.Vec3d(1, 1, 1)) stage.Save() def _add_light_to_hierarchy(stage: Usd.Stage, beams: List[Beam], geometries: List[Geometry]): if len(beams) > 0: GDTFImporter._add_beam_to_hierarchy(stage, beams) else: # Some gdtf files only represents brackets and such. They contain only "Inventory" geometry. # We don't want to add a light source to those. has_not_inventory_geometry = False for geometry in geometries: if geometry.get_tag() != 'Inventory': has_not_inventory_geometry = True if has_not_inventory_geometry: GDTFImporter._add_default_light_to_hierarchy(stage, geometries) def _add_beam_to_hierarchy(stage: Usd.Stage, beams: List[Beam]): for beam in beams: light = USDTools.add_beam(stage, beam.get_stage_path(), beam.get_position_matrix(), beam.get_radius()) beam.apply_attributes_to_prim(light) stage.Save() def _add_default_light_to_hierarchy(stage: Usd.Stage, geometries: List[Geometry]): deepest_geom = geometries[-1] max_depth = deepest_geom.get_depth() for geom in reversed(geometries): depth = geom.get_depth() if (depth > max_depth): deepest_geom = geom max_depth = depth light_stage_path = deepest_geom.get_stage_path() + "/Beam" model = deepest_geom.get_model() USDTools.add_light_default(stage, light_stage_path, model.get_height(), model.get_width()) stage.Save() def _set_general_attributes(stage: Usd.Stage, root: ET.Element): fixtureAttr = FixtureAttributes(root) prim: Usd.Prim = USDTools.get_default_prim(stage) fixtureAttr.apply_attributes_to_prim(prim) stage.Save()
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/3dsConverterScript.py
import sys import os def main(): os.environ["PATH"] = __file__ + os.pathsep + os.environ["PATH"] if len(sys.argv) <= 2: print("Need at least 2 arguments") exit(1) from pyassimp import load, export inputFile = sys.argv[1] outputFile = sys.argv[2] print("Input 3ds file:" + inputFile) print("output file: " + outputFile) with load(inputFile) as scene: export(scene, outputFile, "gltf2") if __name__ == "__main__": main()
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/extension.py
import omni.ext import omni.kit.tool.asset_importer as ai from .converterDelegate import ConverterDelegate class MfOvGdtfExtension(omni.ext.IExt): def on_startup(self, _): self._delegate_gdtf = ConverterDelegate( "GDTF Converter", ["(.*\\.gdtf$)"], ["GDTF Files (*.gdtf)"] ) ai.register_importer(self._delegate_gdtf) def on_shutdown(self): ai.remove_importer(self._delegate_gdtf) self._delegate_gdtf.destroy() self._delegate_gdtf = None
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/__init__.py
import os from pxr import Plug pluginsRoot = os.path.join(os.path.dirname(__file__), '../../../plugin/resources') Plug.Registry().RegisterPlugins(pluginsRoot) from .extension import *
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/converterDelegate.py
import os import omni.kit.tool.asset_importer as ai from .converterOptionsBuilder import ConverterOptionsBuilder from .converterHelper import ConverterHelper class ConverterDelegate(ai.AbstractImporterDelegate): def __init__(self, name, filters, descriptions): super().__init__() self._hoops_options_builder = ConverterOptionsBuilder() self._hoops_converter = ConverterHelper() self._name = name self._filters = filters self._descriptions = descriptions def destroy(self): if self._hoops_converter: # self._hoops_converter.destroy() self._hoops_converter = None if self._hoops_options_builder: self._hoops_options_builder.destroy() self._hoops_options_builder = None @property def name(self): return self._name @property def filter_regexes(self): return self._filters @property def filter_descriptions(self): return self._descriptions def build_options(self, paths): pass # TODO enable this after the filepicker bugfix: OM-47383 # self._hoops_options_builder.build_pane(paths) async def convert_assets(self, paths): context = self._hoops_options_builder.get_import_options() hoops_context = context.cad_converter_context absolute_paths = [] relative_paths = [] for file_path in paths: if self.is_supported_format(file_path): absolute_paths.append(file_path) filename = os.path.basename(file_path) relative_paths.append(filename) converted_assets = await self._hoops_converter.create_import_task( absolute_paths, context.export_folder, hoops_context ) return converted_assets
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/converterOptionsBuilder.py
from omni.kit.menu import utils from omni.kit.tool.asset_importer.file_picker import FilePicker from omni.kit.tool.asset_importer.filebrowser import FileBrowserMode, FileBrowserSelectionType import omni.kit.window.content_browser as content from .converterOptions import ConverterOptions class ConverterOptionsBuilder: def __init__(self): self._file_picker = None self._export_content = ConverterOptions() self._folder_button = None self._refresh_default_folder = False self._default_folder = None self._clear() def destroy(self): self._clear() if self._file_picker: self._file_picker.destroy() def _clear(self): self._built = False self._export_folder_field = None if self._folder_button: self._folder_button.set_clicked_fn(None) self._folder_button = None def set_default_target_folder(self, folder: str): self._default_folder = folder self._refresh_default_folder = True def _select_picked_folder_callback(self, paths): if paths: self._export_folder_field.model.set_value(paths[0]) def _cancel_picked_folder_callback(self): pass def _show_file_picker(self): if not self._file_picker: mode = FileBrowserMode.OPEN file_type = FileBrowserSelectionType.DIRECTORY_ONLY filters = [(".*", "All Files (*.*)")] self._file_picker = FilePicker("Select Folder", mode=mode, file_type=file_type, filter_options=filters) self._file_picker.set_file_selected_fn(self._select_picked_folder_callback) self._file_picker.set_cancel_fn(self._cancel_picked_folder_callback) folder = self._export_folder_field.model.get_value_as_string() if utils.is_folder(folder): self._file_picker.show(folder) else: self._file_picker.show(self._get_current_dir_in_content_window()) def _get_current_dir_in_content_window(self): content_window = content.get_content_window() return content_window.get_current_directory() def get_import_options(self): return ConverterOptions()
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/converterHelper.py
import logging import shutil from urllib.parse import unquote import omni.kit.window.content_browser from .filepathUtility import Filepath from .gdtfImporter import GDTFImporter from .gltfImporter import GLTFImporter class ConverterHelper: def _create_import_task(self, absolute_path, export_folder, _): absolute_path_unquoted = unquote(absolute_path) if absolute_path_unquoted.startswith("file:/"): path = absolute_path_unquoted[6:] else: path = absolute_path_unquoted current_nucleus_dir = omni.kit.window.content_browser.get_content_window().get_current_directory() file: Filepath = Filepath(path) output_dir = current_nucleus_dir if export_folder is None else export_folder if export_folder is not None and export_folder != "": output_dir = export_folder # Cannot Unzip directly from Nucleus, must download file beforehand if file.is_nucleus_path(): tmp_path = GLTFImporter.TMP_ARCHIVE_EXTRACT_DIR + file.basename result = omni.client.copy(file.fullpath, tmp_path, omni.client.CopyBehavior.OVERWRITE) if result == omni.client.Result.OK: file = Filepath(tmp_path) else: logger = logging.getLogger(__name__) logger.error(f"Could not import {file.fullpath} directly from Omniverse, try downloading the file instead") return url: str = GDTFImporter.convert(file, output_dir) return url async def create_import_task(self, absolute_paths, export_folder, hoops_context): converted_assets = {} for i in range(len(absolute_paths)): converted_assets[absolute_paths[i]] = self._create_import_task(absolute_paths[i], export_folder, hoops_context) shutil.rmtree(GLTFImporter.TMP_ARCHIVE_EXTRACT_DIR) return converted_assets
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/USDTools.py
import numpy as np from typing import List, Tuple from unidecode import unidecode from urllib.parse import unquote import omni.usd from pxr import Gf, Tf, Sdf, UsdLux, Usd, UsdGeom class USDTools: def make_name_valid(name: str) -> str: if name[:1].isdigit(): name = "_" + name return Tf.MakeValidIdentifier(unidecode(name)) def get_context(): return omni.usd.get_context() def get_stage() -> Usd.Stage: context = USDTools.get_context() return context.get_stage() def get_stage_directory(stage: Usd.Stage = None) -> str: if stage is None: stage = USDTools.get_stage() root_layer = stage.GetRootLayer() repository_path = root_layer.realPath repository_path_unquoted = unquote(repository_path) dir_index = repository_path_unquoted.rfind("/") return repository_path_unquoted[:dir_index + 1] def get_or_create_stage(url: str) -> Usd.Stage: try: # TODO: Better way to check if stage exists? return Usd.Stage.Open(url) except: stage = Usd.Stage.CreateNew(url) UsdGeom.SetStageMetersPerUnit(stage, UsdGeom.LinearUnits.centimeters) # TODO get user defaults UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y) # TODO get user defaults default_prim = stage.DefinePrim("/World", "Xform") stage.SetDefaultPrim(default_prim) stage.Save() return stage def get_default_prim(stage: Usd.Stage) -> Usd.Prim: return stage.GetDefaultPrim() def add_reference(stage: Usd.Stage, ref_path_relative: str, stage_path: str, stage_subpath: str) -> Tuple[ UsdGeom.Xform, UsdGeom.Xform]: xform_parent: UsdGeom.Xform = UsdGeom.Xform.Define(stage, stage_path) xform_ref: UsdGeom.Xform = UsdGeom.Xform.Define(stage, stage_path + stage_subpath) xform_ref_prim: Usd.Prim = xform_ref.GetPrim() path_unquoted = unquote(ref_path_relative) references: Usd.References = xform_ref_prim.GetReferences() references.AddReference(path_unquoted) return xform_parent, xform_ref def get_applied_scale(stage: Usd.Stage, scale_factor: float): stage_scale = UsdGeom.GetStageMetersPerUnit(stage) return scale_factor / stage_scale def apply_scale_xform_op(xform: UsdGeom.Xform, scale: float): scale_value = Gf.Vec3d(scale, scale, scale) xform_ordered_ops: List[UsdGeom.XformOp] = xform.GetOrderedXformOps() found_op = False for xform_op in xform_ordered_ops: if xform_op.GetOpType() == UsdGeom.XformOp.TypeScale: xform_op.Set(scale_value) found_op = True if not found_op: xform.AddScaleOp().Set(scale_value) def np_matrix_from_gdtf(value: str) -> np.matrix: # GDTF Matrix is: 4x4, row-major, Right-Handed, Z-up (Distance Unit not specified, but mm implied) # expect form like "{x,y,z,w}{x,y,z,w}{x,y,z,w}{x,y,z,w}" where "x","y","z", "w" is similar to 1.000000 # make source compatible with np.matrix constructor: "x y z; x y z; x y z; x y z" value_alt = value[1:] # Removes "{" prefix value_alt = value_alt[:-1] # Removes "}" suffix value_alt = value_alt.replace("}{", "; ") value_alt = value_alt.replace(",", " ") np_matrix: np.matrix = np.matrix(value_alt) return np_matrix def gf_matrix_from_gdtf(np_matrix: np.matrix, scale: float) -> Gf.Matrix4d: # Row major matrix gf_matrix = Gf.Matrix4d( np_matrix.item((0, 0)), np_matrix.item((1, 0)), np_matrix.item((2, 0)), np_matrix.item((3, 0)), np_matrix.item((0, 1)), np_matrix.item((1, 1)), np_matrix.item((2, 1)), np_matrix.item((3, 1)), np_matrix.item((0, 2)), np_matrix.item((1, 2)), np_matrix.item((2, 2)), np_matrix.item((3, 2)), np_matrix.item((0, 3)), np_matrix.item((1, 3)), np_matrix.item((2, 3)), np_matrix.item((3, 3)) ) return gf_matrix def add_beam(stage: Usd.Stage, path: str, position_matrix: str, radius: float) -> UsdLux: applied_scale = USDTools.compute_applied_scale(stage) axis_matrix = USDTools.get_axis_rotation_matrix() light: UsdLux.DiskLight = UsdLux.DiskLight.Define(stage, path) translation, rotation = USDTools.compute_xform_values(position_matrix, applied_scale, axis_matrix) rotation += Gf.Vec3d(-90, 0, 0) scale = Gf.Vec3d(radius * 2, radius * 2, 1) USDTools._set_light_xform(light, translation, rotation, scale) USDTools._additional_default_attributes(light) return light def add_light_default(stage: Usd.Stage, path: str, height: float, diameter: float): light: UsdLux.DiskLight = UsdLux.DiskLight.Define(stage, path) translation = Gf.Vec3d(0, -height * 0.5, 0) rotation = Gf.Vec3d(-90, 0, 0) scale = Gf.Vec3d(diameter, diameter, 1) USDTools._set_light_xform(light, translation, rotation, scale) USDTools._additional_default_attributes(light) def _additional_default_attributes(light: UsdLux): prim = light.GetPrim() prim.CreateAttribute("visibleInPrimaryRay", Sdf.ValueTypeNames.Bool).Set(True) light.CreateIntensityAttr().Set(60_000) # if UsdLux.ShapingAPI.CanApply(prim): UsdLux.ShapingAPI.Apply(prim) def _set_light_xform(light: UsdLux.DiskLight, translation: Gf.Vec3d, rotation: Gf.Vec3d, scale: Gf.Vec3d): light.ClearXformOpOrder() # Prevent error when overwritting light.AddTranslateOp().Set(translation) light.AddRotateZYXOp().Set(rotation) light.AddScaleOp().Set(scale) def set_light_attributes(light: UsdLux.DiskLight, beamAngle: float, intensity: float, colorTemp: float): if colorTemp is not None: light.GetEnableColorTemperatureAttr().Set(True) light.GetColorTemperatureAttr().Set(colorTemp) else: light.GetEnableColorTemperatureAttr().Set(False) light.GetColorTemperatureAttr().Set(6500) # default value if intensity is not None: light.GetIntensityAttr().Set(intensity) if beamAngle is not None: prim: Usd.Prim = light.GetPrim() shapingAPI = UsdLux.ShapingAPI(prim) shapingAPI.GetShapingConeAngleAttr().Set(beamAngle) def compute_applied_scale(stage: Usd.Stage) -> float: gdtf_scale = 1 # GDTF dimensions are in meters applied_scale = USDTools.get_applied_scale(stage, gdtf_scale) return applied_scale def get_axis_rotation_matrix() -> Gf.Matrix3d: rotate_minus90deg_xaxis = Gf.Matrix3d(1, 0, 0, 0, 0, 1, 0, -1, 0) return rotate_minus90deg_xaxis def compute_xform_values(position_matrix: str, scale: float, axis_matrix: Gf.Matrix3d) -> (Gf.Vec3d, Gf.Vec3d): np_matrix: np.matrix = USDTools.np_matrix_from_gdtf(position_matrix) gf_matrix: Gf.Matrix4d = USDTools.gf_matrix_from_gdtf(np_matrix, scale) rotation: Gf.Rotation = gf_matrix.GetTranspose().ExtractRotation() euler: Gf.Vec3d = rotation.Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) translation_value = axis_matrix * gf_matrix.ExtractTranslation() rotation_value = axis_matrix * euler return translation_value, rotation_value def set_prim_attribute(prim: Usd.Prim, attribute_name: str, attribute_type: Sdf.ValueTypeNames, attribute_value): prim.CreateAttribute(f"mf:gdtf:{attribute_name}", attribute_type).Set(attribute_value)
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/converterOptions.py
from .converterContext import ConverterContext class ConverterOptions: def __init__(self): self.cad_converter_context = ConverterContext() self.export_folder: str = None
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/filepathUtility.py
import os class Filepath: def __init__(self, filepath: str): self._is_none = filepath == "" self.fullpath = filepath self.directory = os.path.dirname(filepath) + "/" self.basename = os.path.basename(filepath) self.filename, self.ext = os.path.splitext(self.basename) def is_nucleus_path(self) -> bool: # TODO: Replace with omni utility method return self.directory[:12] == "omniverse://" def get_relative_from(self, other) -> str: if self._is_none: return other.fullpath else: return "./" + other.fullpath[len(self.directory):]
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/pyassimp/material.py
# Dummy value. # # No texture, but the value to be used as 'texture semantic' # (#aiMaterialProperty::mSemantic) for all material properties # # not* related to textures. # aiTextureType_NONE = 0x0 # The texture is combined with the result of the diffuse # lighting equation. # aiTextureType_DIFFUSE = 0x1 # The texture is combined with the result of the specular # lighting equation. # aiTextureType_SPECULAR = 0x2 # The texture is combined with the result of the ambient # lighting equation. # aiTextureType_AMBIENT = 0x3 # The texture is added to the result of the lighting # calculation. It isn't influenced by incoming light. # aiTextureType_EMISSIVE = 0x4 # The texture is a height map. # # By convention, higher gray-scale values stand for # higher elevations from the base height. # aiTextureType_HEIGHT = 0x5 # The texture is a (tangent space) normal-map. # # Again, there are several conventions for tangent-space # normal maps. Assimp does (intentionally) not # distinguish here. # aiTextureType_NORMALS = 0x6 # The texture defines the glossiness of the material. # # The glossiness is in fact the exponent of the specular # (phong) lighting equation. Usually there is a conversion # function defined to map the linear color values in the # texture to a suitable exponent. Have fun. # aiTextureType_SHININESS = 0x7 # The texture defines per-pixel opacity. # # Usually 'white' means opaque and 'black' means # 'transparency'. Or quite the opposite. Have fun. # aiTextureType_OPACITY = 0x8 # Displacement texture # # The exact purpose and format is application-dependent. # Higher color values stand for higher vertex displacements. # aiTextureType_DISPLACEMENT = 0x9 # Lightmap texture (aka Ambient Occlusion) # # Both 'Lightmaps' and dedicated 'ambient occlusion maps' are # covered by this material property. The texture contains a # scaling value for the final color value of a pixel. Its # intensity is not affected by incoming light. # aiTextureType_LIGHTMAP = 0xA # Reflection texture # # Contains the color of a perfect mirror reflection. # Rarely used, almost never for real-time applications. # aiTextureType_REFLECTION = 0xB # Unknown texture # # A texture reference that does not match any of the definitions # above is considered to be 'unknown'. It is still imported # but is excluded from any further postprocessing. # aiTextureType_UNKNOWN = 0xC
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/pyassimp/__init__.py
from .core import *
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/pyassimp/formats.py
FORMATS = ["CSM", "LWS", "B3D", "COB", "PLY", "IFC", "OFF", "SMD", "IRRMESH", "3D", "DAE", "MDL", "HMP", "TER", "WRL", "XML", "NFF", "AC", "OBJ", "3DS", "STL", "IRR", "Q3O", "Q3D", "MS3D", "Q3S", "ZGL", "MD2", "X", "BLEND", "XGL", "MD5MESH", "MAX", "LXO", "DXF", "BVH", "LWO", "NDO"] def available_formats(): return FORMATS
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/pyassimp/core.py
""" PyAssimp This is the main-module of PyAssimp. """ import sys if sys.version_info < (2,6): raise RuntimeError('pyassimp: need python 2.6 or newer') # xrange was renamed range in Python 3 and the original range from Python 2 was removed. # To keep compatibility with both Python 2 and 3, xrange is set to range for version 3.0 and up. if sys.version_info >= (3,0): xrange = range try: import numpy except ImportError: numpy = None import logging import ctypes from contextlib import contextmanager logger = logging.getLogger("pyassimp") # attach default null handler to logger so it doesn't complain # even if you don't attach another handler to logger logger.addHandler(logging.NullHandler()) from . import structs from . import helper from . import postprocess from .errors import AssimpError class AssimpLib(object): """ Assimp-Singleton """ load, load_mem, export, export_blob, release, dll = helper.search_library() _assimp_lib = AssimpLib() def make_tuple(ai_obj, type = None): res = None #notes: # ai_obj._fields_ = [ ("attr", c_type), ... ] # getattr(ai_obj, e[0]).__class__ == float if isinstance(ai_obj, structs.Matrix4x4): if numpy: res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_]).reshape((4,4)) #import pdb;pdb.set_trace() else: res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_] res = [res[i:i+4] for i in xrange(0,16,4)] elif isinstance(ai_obj, structs.Matrix3x3): if numpy: res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_]).reshape((3,3)) else: res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_] res = [res[i:i+3] for i in xrange(0,9,3)] else: if numpy: res = numpy.array([getattr(ai_obj, e[0]) for e in ai_obj._fields_]) else: res = [getattr(ai_obj, e[0]) for e in ai_obj._fields_] return res # Returns unicode object for Python 2, and str object for Python 3. def _convert_assimp_string(assimp_string): if sys.version_info >= (3, 0): return str(assimp_string.data, errors='ignore') else: return unicode(assimp_string.data, errors='ignore') # It is faster and more correct to have an init function for each assimp class def _init_face(aiFace): aiFace.indices = [aiFace.mIndices[i] for i in range(aiFace.mNumIndices)] assimp_struct_inits = { structs.Face : _init_face } def call_init(obj, caller = None): if helper.hasattr_silent(obj,'contents'): #pointer _init(obj.contents, obj, caller) else: _init(obj,parent=caller) def _is_init_type(obj): if obj and helper.hasattr_silent(obj,'contents'): #pointer return _is_init_type(obj[0]) # null-pointer case that arises when we reach a mesh attribute # like mBitangents which use mNumVertices rather than mNumBitangents # so it breaks the 'is iterable' check. # Basically: # FIXME! elif not bool(obj): return False tname = obj.__class__.__name__ return not (tname[:2] == 'c_' or tname == 'Structure' \ or tname == 'POINTER') and not isinstance(obj, (int, str, bytes)) def _init(self, target = None, parent = None): """ Custom initialize() for C structs, adds safely accessible member functionality. :param target: set the object which receive the added methods. Useful when manipulating pointers, to skip the intermediate 'contents' deferencing. """ if not target: target = self dirself = dir(self) for m in dirself: if m.startswith("_"): continue # We should not be accessing `mPrivate` according to structs.Scene. if m == 'mPrivate': continue if m.startswith('mNum'): if 'm' + m[4:] in dirself: continue # will be processed later on else: name = m[1:].lower() obj = getattr(self, m) setattr(target, name, obj) continue if m == 'mName': target.name = str(_convert_assimp_string(self.mName)) target.__class__.__repr__ = lambda x: str(x.__class__) + "(" + getattr(x, 'name','') + ")" target.__class__.__str__ = lambda x: getattr(x, 'name', '') continue name = m[1:].lower() obj = getattr(self, m) # Create tuples if isinstance(obj, structs.assimp_structs_as_tuple): setattr(target, name, make_tuple(obj)) logger.debug(str(self) + ": Added array " + str(getattr(target, name)) + " as self." + name.lower()) continue if m.startswith('m') and len(m) > 1 and m[1].upper() == m[1]: if name == "parent": setattr(target, name, parent) logger.debug("Added a parent as self." + name) continue if helper.hasattr_silent(self, 'mNum' + m[1:]): length = getattr(self, 'mNum' + m[1:]) # -> special case: properties are # stored as a dict. if m == 'mProperties': setattr(target, name, _get_properties(obj, length)) continue if not length: # empty! setattr(target, name, []) logger.debug(str(self) + ": " + name + " is an empty list.") continue try: if obj._type_ in structs.assimp_structs_as_tuple: if numpy: setattr(target, name, numpy.array([make_tuple(obj[i]) for i in range(length)], dtype=numpy.float32)) logger.debug(str(self) + ": Added an array of numpy arrays (type "+ str(type(obj)) + ") as self." + name) else: setattr(target, name, [make_tuple(obj[i]) for i in range(length)]) logger.debug(str(self) + ": Added a list of lists (type "+ str(type(obj)) + ") as self." + name) else: setattr(target, name, [obj[i] for i in range(length)]) #TODO: maybe not necessary to recreate an array? logger.debug(str(self) + ": Added list of " + str(obj) + " " + name + " as self." + name + " (type: " + str(type(obj)) + ")") # initialize array elements try: init = assimp_struct_inits[type(obj[0])] except KeyError: if _is_init_type(obj[0]): for e in getattr(target, name): call_init(e, target) else: for e in getattr(target, name): init(e) except IndexError: logger.error("in " + str(self) +" : mismatch between mNum" + name + " and the actual amount of data in m" + name + ". This may be due to version mismatch between libassimp and pyassimp. Quitting now.") sys.exit(1) except ValueError as e: logger.error("In " + str(self) + "->" + name + ": " + str(e) + ". Quitting now.") if "setting an array element with a sequence" in str(e): logger.error("Note that pyassimp does not currently " "support meshes with mixed triangles " "and quads. Try to load your mesh with" " a post-processing to triangulate your" " faces.") raise e else: # starts with 'm' but not iterable setattr(target, name, obj) logger.debug("Added " + name + " as self." + name + " (type: " + str(type(obj)) + ")") if _is_init_type(obj): call_init(obj, target) if isinstance(self, structs.Mesh): _finalize_mesh(self, target) if isinstance(self, structs.Texture): _finalize_texture(self, target) if isinstance(self, structs.Metadata): _finalize_metadata(self, target) return self def pythonize_assimp(type, obj, scene): """ This method modify the Assimp data structures to make them easier to work with in Python. Supported operations: - MESH: replace a list of mesh IDs by reference to these meshes - ADDTRANSFORMATION: add a reference to an object's transformation taken from their associated node. :param type: the type of modification to operate (cf above) :param obj: the input object to modify :param scene: a reference to the whole scene """ if type == "MESH": meshes = [] for i in obj: meshes.append(scene.meshes[i]) return meshes if type == "ADDTRANSFORMATION": def getnode(node, name): if node.name == name: return node for child in node.children: n = getnode(child, name) if n: return n node = getnode(scene.rootnode, obj.name) if not node: raise AssimpError("Object " + str(obj) + " has no associated node!") setattr(obj, "transformation", node.transformation) def recur_pythonize(node, scene): ''' Recursively call pythonize_assimp on nodes tree to apply several post-processing to pythonize the assimp datastructures. ''' node.meshes = pythonize_assimp("MESH", node.meshes, scene) for mesh in node.meshes: mesh.material = scene.materials[mesh.materialindex] for cam in scene.cameras: pythonize_assimp("ADDTRANSFORMATION", cam, scene) for c in node.children: recur_pythonize(c, scene) def release(scene): ''' Release resources of a loaded scene. ''' _assimp_lib.release(ctypes.pointer(scene)) @contextmanager def load(filename, file_type = None, processing = postprocess.aiProcess_Triangulate): ''' Load a model into a scene. On failure throws AssimpError. Arguments --------- filename: Either a filename or a file object to load model from. If a file object is passed, file_type MUST be specified Otherwise Assimp has no idea which importer to use. This is named 'filename' so as to not break legacy code. processing: assimp postprocessing parameters. Verbose keywords are imported from postprocessing, and the parameters can be combined bitwise to generate the final processing value. Note that the default value will triangulate quad faces. Example of generating other possible values: processing = (pyassimp.postprocess.aiProcess_Triangulate | pyassimp.postprocess.aiProcess_OptimizeMeshes) file_type: string of file extension, such as 'stl' Returns --------- Scene object with model data ''' if hasattr(filename, 'read'): # This is the case where a file object has been passed to load. # It is calling the following function: # const aiScene* aiImportFileFromMemory(const char* pBuffer, # unsigned int pLength, # unsigned int pFlags, # const char* pHint) if file_type is None: raise AssimpError('File type must be specified when passing file objects!') data = filename.read() model = _assimp_lib.load_mem(data, len(data), processing, file_type) else: # a filename string has been passed model = _assimp_lib.load(filename.encode(sys.getfilesystemencoding()), processing) if not model: raise AssimpError('Could not import file!') scene = _init(model.contents) recur_pythonize(scene.rootnode, scene) try: yield scene finally: release(scene) def export(scene, filename, file_type = None, processing = postprocess.aiProcess_Triangulate): ''' Export a scene. On failure throws AssimpError. Arguments --------- scene: scene to export. filename: Filename that the scene should be exported to. file_type: string of file exporter to use. For example "collada". processing: assimp postprocessing parameters. Verbose keywords are imported from postprocessing, and the parameters can be combined bitwise to generate the final processing value. Note that the default value will triangulate quad faces. Example of generating other possible values: processing = (pyassimp.postprocess.aiProcess_Triangulate | pyassimp.postprocess.aiProcess_OptimizeMeshes) ''' exportStatus = _assimp_lib.export(ctypes.pointer(scene), file_type.encode("ascii"), filename.encode(sys.getfilesystemencoding()), processing) if exportStatus != 0: raise AssimpError('Could not export scene!') def export_blob(scene, file_type = None, processing = postprocess.aiProcess_Triangulate): ''' Export a scene and return a blob in the correct format. On failure throws AssimpError. Arguments --------- scene: scene to export. file_type: string of file exporter to use. For example "collada". processing: assimp postprocessing parameters. Verbose keywords are imported from postprocessing, and the parameters can be combined bitwise to generate the final processing value. Note that the default value will triangulate quad faces. Example of generating other possible values: processing = (pyassimp.postprocess.aiProcess_Triangulate | pyassimp.postprocess.aiProcess_OptimizeMeshes) Returns --------- Pointer to structs.ExportDataBlob ''' exportBlobPtr = _assimp_lib.export_blob(ctypes.pointer(scene), file_type.encode("ascii"), processing) if exportBlobPtr == 0: raise AssimpError('Could not export scene to blob!') return exportBlobPtr def _finalize_texture(tex, target): setattr(target, "achformathint", tex.achFormatHint) if numpy: data = numpy.array([make_tuple(getattr(tex, "pcData")[i]) for i in range(tex.mWidth * tex.mHeight)]) else: data = [make_tuple(getattr(tex, "pcData")[i]) for i in range(tex.mWidth * tex.mHeight)] setattr(target, "data", data) def _finalize_mesh(mesh, target): """ Building of meshes is a bit specific. We override here the various datasets that can not be process as regular fields. For instance, the length of the normals array is mNumVertices (no mNumNormals is available) """ nb_vertices = getattr(mesh, "mNumVertices") def fill(name): mAttr = getattr(mesh, name) if numpy: if mAttr: data = numpy.array([make_tuple(getattr(mesh, name)[i]) for i in range(nb_vertices)], dtype=numpy.float32) setattr(target, name[1:].lower(), data) else: setattr(target, name[1:].lower(), numpy.array([], dtype="float32")) else: if mAttr: data = [make_tuple(getattr(mesh, name)[i]) for i in range(nb_vertices)] setattr(target, name[1:].lower(), data) else: setattr(target, name[1:].lower(), []) def fillarray(name): mAttr = getattr(mesh, name) data = [] for index, mSubAttr in enumerate(mAttr): if mSubAttr: data.append([make_tuple(getattr(mesh, name)[index][i]) for i in range(nb_vertices)]) if numpy: setattr(target, name[1:].lower(), numpy.array(data, dtype=numpy.float32)) else: setattr(target, name[1:].lower(), data) fill("mNormals") fill("mTangents") fill("mBitangents") fillarray("mColors") fillarray("mTextureCoords") # prepare faces if numpy: faces = numpy.array([f.indices for f in target.faces], dtype=numpy.int32) else: faces = [f.indices for f in target.faces] setattr(target, 'faces', faces) def _init_metadata_entry(entry): entry.type = entry.mType if entry.type == structs.MetadataEntry.AI_BOOL: entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_bool)).contents.value elif entry.type == structs.MetadataEntry.AI_INT32: entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_int32)).contents.value elif entry.type == structs.MetadataEntry.AI_UINT64: entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_uint64)).contents.value elif entry.type == structs.MetadataEntry.AI_FLOAT: entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_float)).contents.value elif entry.type == structs.MetadataEntry.AI_DOUBLE: entry.data = ctypes.cast(entry.mData, ctypes.POINTER(ctypes.c_double)).contents.value elif entry.type == structs.MetadataEntry.AI_AISTRING: assimp_string = ctypes.cast(entry.mData, ctypes.POINTER(structs.String)).contents entry.data = _convert_assimp_string(assimp_string) elif entry.type == structs.MetadataEntry.AI_AIVECTOR3D: assimp_vector = ctypes.cast(entry.mData, ctypes.POINTER(structs.Vector3D)).contents entry.data = make_tuple(assimp_vector) return entry def _finalize_metadata(metadata, target): """ Building the metadata object is a bit specific. Firstly, there are two separate arrays: one with metadata keys and one with metadata values, and there are no corresponding mNum* attributes, so the C arrays are not converted to Python arrays using the generic code in the _init function. Secondly, a metadata entry value has to be cast according to declared metadata entry type. """ length = metadata.mNumProperties setattr(target, 'keys', [str(_convert_assimp_string(metadata.mKeys[i])) for i in range(length)]) setattr(target, 'values', [_init_metadata_entry(metadata.mValues[i]) for i in range(length)]) class PropertyGetter(dict): def __getitem__(self, key): semantic = 0 if isinstance(key, tuple): key, semantic = key return dict.__getitem__(self, (key, semantic)) def keys(self): for k in dict.keys(self): yield k[0] def __iter__(self): return self.keys() def items(self): for k, v in dict.items(self): yield k[0], v def _get_properties(properties, length): """ Convenience Function to get the material properties as a dict and values in a python format. """ result = {} #read all properties for p in [properties[i] for i in range(length)]: #the name p = p.contents key = str(_convert_assimp_string(p.mKey)) key = (key.split('.')[1], p.mSemantic) #the data if p.mType == 1: arr = ctypes.cast(p.mData, ctypes.POINTER(ctypes.c_float * int(p.mDataLength/ctypes.sizeof(ctypes.c_float))) ).contents value = [x for x in arr] elif p.mType == 3: #string can't be an array value = _convert_assimp_string(ctypes.cast(p.mData, ctypes.POINTER(structs.MaterialPropertyString)).contents) elif p.mType == 4: arr = ctypes.cast(p.mData, ctypes.POINTER(ctypes.c_int * int(p.mDataLength/ctypes.sizeof(ctypes.c_int))) ).contents value = [x for x in arr] else: value = p.mData[:p.mDataLength] if len(value) == 1: [value] = value result[key] = value return PropertyGetter(result) def decompose_matrix(matrix): if not isinstance(matrix, structs.Matrix4x4): raise AssimpError("pyassimp.decompose_matrix failed: Not a Matrix4x4!") scaling = structs.Vector3D() rotation = structs.Quaternion() position = structs.Vector3D() _assimp_lib.dll.aiDecomposeMatrix(ctypes.pointer(matrix), ctypes.byref(scaling), ctypes.byref(rotation), ctypes.byref(position)) return scaling._init(), rotation._init(), position._init()
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/pyassimp/errors.py
#-*- coding: UTF-8 -*- """ All possible errors. """ class AssimpError(BaseException): """ If an internal error occurs. """ pass
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/pyassimp/structs.py
#-*- coding: utf-8 -*- from ctypes import POINTER, c_void_p, c_uint, c_char, c_float, Structure, c_double, c_ubyte, c_size_t, c_uint32 class Vector2D(Structure): """ See 'vector2.h' for details. """ _fields_ = [ ("x", c_float),("y", c_float), ] class Matrix3x3(Structure): """ See 'matrix3x3.h' for details. """ _fields_ = [ ("a1", c_float),("a2", c_float),("a3", c_float), ("b1", c_float),("b2", c_float),("b3", c_float), ("c1", c_float),("c2", c_float),("c3", c_float), ] class Texel(Structure): """ See 'texture.h' for details. """ _fields_ = [ ("b", c_ubyte),("g", c_ubyte),("r", c_ubyte),("a", c_ubyte), ] class Color4D(Structure): """ See 'color4.h' for details. """ _fields_ = [ # Red, green, blue and alpha color values ("r", c_float),("g", c_float),("b", c_float),("a", c_float), ] class Plane(Structure): """ See 'types.h' for details. """ _fields_ = [ # Plane equation ("a", c_float),("b", c_float),("c", c_float),("d", c_float), ] class Color3D(Structure): """ See 'types.h' for details. """ _fields_ = [ # Red, green and blue color values ("r", c_float),("g", c_float),("b", c_float), ] class String(Structure): """ See 'types.h' for details. """ MAXLEN = 1024 _fields_ = [ # Binary length of the string excluding the terminal 0. This is NOT the # logical length of strings containing UTF-8 multibyte sequences! It's # the number of bytes from the beginning of the string to its end. ("length", c_uint32), # String buffer. Size limit is MAXLEN ("data", c_char*MAXLEN), ] class MaterialPropertyString(Structure): """ See 'MaterialSystem.cpp' for details. The size of length is truncated to 4 bytes on 64-bit platforms when used as a material property (see MaterialSystem.cpp aiMaterial::AddProperty() for details). """ MAXLEN = 1024 _fields_ = [ # Binary length of the string excluding the terminal 0. This is NOT the # logical length of strings containing UTF-8 multibyte sequences! It's # the number of bytes from the beginning of the string to its end. ("length", c_uint32), # String buffer. Size limit is MAXLEN ("data", c_char*MAXLEN), ] class MemoryInfo(Structure): """ See 'types.h' for details. """ _fields_ = [ # Storage allocated for texture data ("textures", c_uint), # Storage allocated for material data ("materials", c_uint), # Storage allocated for mesh data ("meshes", c_uint), # Storage allocated for node data ("nodes", c_uint), # Storage allocated for animation data ("animations", c_uint), # Storage allocated for camera data ("cameras", c_uint), # Storage allocated for light data ("lights", c_uint), # Total storage allocated for the full import. ("total", c_uint), ] class Quaternion(Structure): """ See 'quaternion.h' for details. """ _fields_ = [ # w,x,y,z components of the quaternion ("w", c_float),("x", c_float),("y", c_float),("z", c_float), ] class Face(Structure): """ See 'mesh.h' for details. """ _fields_ = [ # Number of indices defining this face. # The maximum value for this member is #AI_MAX_FACE_INDICES. ("mNumIndices", c_uint), # Pointer to the indices array. Size of the array is given in numIndices. ("mIndices", POINTER(c_uint)), ] class VertexWeight(Structure): """ See 'mesh.h' for details. """ _fields_ = [ # Index of the vertex which is influenced by the bone. ("mVertexId", c_uint), # The strength of the influence in the range (0...1). # The influence from all bones at one vertex amounts to 1. ("mWeight", c_float), ] class Matrix4x4(Structure): """ See 'matrix4x4.h' for details. """ _fields_ = [ ("a1", c_float),("a2", c_float),("a3", c_float),("a4", c_float), ("b1", c_float),("b2", c_float),("b3", c_float),("b4", c_float), ("c1", c_float),("c2", c_float),("c3", c_float),("c4", c_float), ("d1", c_float),("d2", c_float),("d3", c_float),("d4", c_float), ] class Vector3D(Structure): """ See 'vector3.h' for details. """ _fields_ = [ ("x", c_float),("y", c_float),("z", c_float), ] class MeshKey(Structure): """ See 'anim.h' for details. """ _fields_ = [ # The time of this key ("mTime", c_double), # Index into the aiMesh::mAnimMeshes array of the # mesh corresponding to the #aiMeshAnim hosting this # key frame. The referenced anim mesh is evaluated # according to the rules defined in the docs for #aiAnimMesh. ("mValue", c_uint), ] class MetadataEntry(Structure): """ See 'metadata.h' for details """ AI_BOOL = 0 AI_INT32 = 1 AI_UINT64 = 2 AI_FLOAT = 3 AI_DOUBLE = 4 AI_AISTRING = 5 AI_AIVECTOR3D = 6 AI_META_MAX = 7 _fields_ = [ # The type field uniquely identifies the underlying type of the data field ("mType", c_uint), ("mData", c_void_p), ] class Metadata(Structure): """ See 'metadata.h' for details """ _fields_ = [ # Length of the mKeys and mValues arrays, respectively ("mNumProperties", c_uint), # Arrays of keys, may not be NULL. Entries in this array may not be NULL # as well. ("mKeys", POINTER(String)), # Arrays of values, may not be NULL. Entries in this array may be NULL # if the corresponding property key has no assigned value. ("mValues", POINTER(MetadataEntry)), ] class Node(Structure): """ See 'scene.h' for details. """ Node._fields_ = [ # The name of the node. # The name might be empty (length of zero) but all nodes which # need to be accessed afterwards by bones or anims are usually named. # Multiple nodes may have the same name, but nodes which are accessed # by bones (see #aiBone and #aiMesh::mBones) *must* be unique. # Cameras and lights are assigned to a specific node name - if there # are multiple nodes with this name, they're assigned to each of them. # <br> # There are no limitations regarding the characters contained in # this text. You should be able to handle stuff like whitespace, tabs, # linefeeds, quotation marks, ampersands, ... . ("mName", String), # The transformation relative to the node's parent. ("mTransformation", Matrix4x4), # Parent node. NULL if this node is the root node. ("mParent", POINTER(Node)), # The number of child nodes of this node. ("mNumChildren", c_uint), # The child nodes of this node. NULL if mNumChildren is 0. ("mChildren", POINTER(POINTER(Node))), # The number of meshes of this node. ("mNumMeshes", c_uint), # The meshes of this node. Each entry is an index into the mesh ("mMeshes", POINTER(c_uint)), # Metadata associated with this node or NULL if there is no metadata. # Whether any metadata is generated depends on the source file format. ("mMetadata", POINTER(Metadata)), ] class Light(Structure): """ See 'light.h' for details. """ _fields_ = [ # The name of the light source. # There must be a node in the scenegraph with the same name. # This node specifies the position of the light in the scene # hierarchy and can be animated. ("mName", String), # The type of the light source. # aiLightSource_UNDEFINED is not a valid value for this member. ("mType", c_uint), # Position of the light source in space. Relative to the # transformation of the node corresponding to the light. # The position is undefined for directional lights. ("mPosition", Vector3D), # Direction of the light source in space. Relative to the # transformation of the node corresponding to the light. # The direction is undefined for point lights. The vector # may be normalized, but it needn't. ("mDirection", Vector3D), # Up direction of the light source in space. Relative to the # transformation of the node corresponding to the light. # # The direction is undefined for point lights. The vector # may be normalized, but it needn't. ("mUp", Vector3D), # Constant light attenuation factor. # The intensity of the light source at a given distance 'd' from # the light's position is # @code # Atten = 1/( att0 + att1 # d + att2 # d*d) # @endcode # This member corresponds to the att0 variable in the equation. # Naturally undefined for directional lights. ("mAttenuationConstant", c_float), # Linear light attenuation factor. # The intensity of the light source at a given distance 'd' from # the light's position is # @code # Atten = 1/( att0 + att1 # d + att2 # d*d) # @endcode # This member corresponds to the att1 variable in the equation. # Naturally undefined for directional lights. ("mAttenuationLinear", c_float), # Quadratic light attenuation factor. # The intensity of the light source at a given distance 'd' from # the light's position is # @code # Atten = 1/( att0 + att1 # d + att2 # d*d) # @endcode # This member corresponds to the att2 variable in the equation. # Naturally undefined for directional lights. ("mAttenuationQuadratic", c_float), # Diffuse color of the light source # The diffuse light color is multiplied with the diffuse # material color to obtain the final color that contributes # to the diffuse shading term. ("mColorDiffuse", Color3D), # Specular color of the light source # The specular light color is multiplied with the specular # material color to obtain the final color that contributes # to the specular shading term. ("mColorSpecular", Color3D), # Ambient color of the light source # The ambient light color is multiplied with the ambient # material color to obtain the final color that contributes # to the ambient shading term. Most renderers will ignore # this value it, is just a remaining of the fixed-function pipeline # that is still supported by quite many file formats. ("mColorAmbient", Color3D), # Inner angle of a spot light's light cone. # The spot light has maximum influence on objects inside this # angle. The angle is given in radians. It is 2PI for point # lights and undefined for directional lights. ("mAngleInnerCone", c_float), # Outer angle of a spot light's light cone. # The spot light does not affect objects outside this angle. # The angle is given in radians. It is 2PI for point lights and # undefined for directional lights. The outer angle must be # greater than or equal to the inner angle. # It is assumed that the application uses a smooth # interpolation between the inner and the outer cone of the # spot light. ("mAngleOuterCone", c_float), # Size of area light source. ("mSize", Vector2D), ] class Texture(Structure): """ See 'texture.h' for details. """ _fields_ = [ # Width of the texture, in pixels # If mHeight is zero the texture is compressed in a format # like JPEG. In this case mWidth specifies the size of the # memory area pcData is pointing to, in bytes. ("mWidth", c_uint), # Height of the texture, in pixels # If this value is zero, pcData points to an compressed texture # in any format (e.g. JPEG). ("mHeight", c_uint), # A hint from the loader to make it easier for applications # to determine the type of embedded textures. # # If mHeight != 0 this member is show how data is packed. Hint will consist of # two parts: channel order and channel bitness (count of the bits for every # color channel). For simple parsing by the viewer it's better to not omit # absent color channel and just use 0 for bitness. For example: # 1. Image contain RGBA and 8 bit per channel, achFormatHint == "rgba8888"; # 2. Image contain ARGB and 8 bit per channel, achFormatHint == "argb8888"; # 3. Image contain RGB and 5 bit for R and B channels and 6 bit for G channel, # achFormatHint == "rgba5650"; # 4. One color image with B channel and 1 bit for it, achFormatHint == "rgba0010"; # If mHeight == 0 then achFormatHint is set set to '\\0\\0\\0\\0' if the loader has no additional # information about the texture file format used OR the # file extension of the format without a trailing dot. If there # are multiple file extensions for a format, the shortest # extension is chosen (JPEG maps to 'jpg', not to 'jpeg'). # E.g. 'dds\\0', 'pcx\\0', 'jpg\\0'. All characters are lower-case. # The fourth character will always be '\\0'. ("achFormatHint", c_char*9), # Data of the texture. # Points to an array of mWidth # mHeight aiTexel's. # The format of the texture data is always ARGB8888 to # make the implementation for user of the library as easy # as possible. If mHeight = 0 this is a pointer to a memory # buffer of size mWidth containing the compressed texture # data. Good luck, have fun! ("pcData", POINTER(Texel)), # Texture original filename # Used to get the texture reference ("mFilename", String), ] class Ray(Structure): """ See 'types.h' for details. """ _fields_ = [ # Position and direction of the ray ("pos", Vector3D),("dir", Vector3D), ] class UVTransform(Structure): """ See 'material.h' for details. """ _fields_ = [ # Translation on the u and v axes. # The default value is (0|0). ("mTranslation", Vector2D), # Scaling on the u and v axes. # The default value is (1|1). ("mScaling", Vector2D), # Rotation - in counter-clockwise direction. # The rotation angle is specified in radians. The # rotation center is 0.5f|0.5f. The default value # 0.f. ("mRotation", c_float), ] class MaterialProperty(Structure): """ See 'material.h' for details. """ _fields_ = [ # Specifies the name of the property (key) # Keys are generally case insensitive. ("mKey", String), # Textures: Specifies their exact usage semantic. # For non-texture properties, this member is always 0 # (or, better-said, #aiTextureType_NONE). ("mSemantic", c_uint), # Textures: Specifies the index of the texture. # For non-texture properties, this member is always 0. ("mIndex", c_uint), # Size of the buffer mData is pointing to, in bytes. # This value may not be 0. ("mDataLength", c_uint), # Type information for the property. # Defines the data layout inside the data buffer. This is used # by the library internally to perform debug checks and to # utilize proper type conversions. # (It's probably a hacky solution, but it works.) ("mType", c_uint), # Binary buffer to hold the property's value. # The size of the buffer is always mDataLength. ("mData", POINTER(c_char)), ] class Material(Structure): """ See 'material.h' for details. """ _fields_ = [ # List of all material properties loaded. ("mProperties", POINTER(POINTER(MaterialProperty))), # Number of properties in the data base ("mNumProperties", c_uint), # Storage allocated ("mNumAllocated", c_uint), ] class Bone(Structure): """ See 'mesh.h' for details. """ _fields_ = [ # The name of the bone. ("mName", String), # The number of vertices affected by this bone # The maximum value for this member is #AI_MAX_BONE_WEIGHTS. ("mNumWeights", c_uint), # The vertices affected by this bone ("mWeights", POINTER(VertexWeight)), # Matrix that transforms from mesh space to bone space in bind pose ("mOffsetMatrix", Matrix4x4), ] class AnimMesh(Structure): """ See 'mesh.h' for details. """ AI_MAX_NUMBER_OF_TEXTURECOORDS = 0x8 AI_MAX_NUMBER_OF_COLOR_SETS = 0x8 _fields_ = [ # Anim Mesh name ("mName", String), # Replacement for aiMesh::mVertices. If this array is non-NULL, # it *must* contain mNumVertices entries. The corresponding # array in the host mesh must be non-NULL as well - animation # meshes may neither add or nor remove vertex components (if # a replacement array is NULL and the corresponding source # array is not, the source data is taken instead) ("mVertices", POINTER(Vector3D)), # Replacement for aiMesh::mNormals. ("mNormals", POINTER(Vector3D)), # Replacement for aiMesh::mTangents. ("mTangents", POINTER(Vector3D)), # Replacement for aiMesh::mBitangents. ("mBitangents", POINTER(Vector3D)), # Replacement for aiMesh::mColors ("mColors", POINTER(Color4D) * AI_MAX_NUMBER_OF_COLOR_SETS), # Replacement for aiMesh::mTextureCoords ("mTextureCoords", POINTER(Vector3D) * AI_MAX_NUMBER_OF_TEXTURECOORDS), # The number of vertices in the aiAnimMesh, and thus the length of all # the member arrays. # # This has always the same value as the mNumVertices property in the # corresponding aiMesh. It is duplicated here merely to make the length # of the member arrays accessible even if the aiMesh is not known, e.g. # from language bindings. ("mNumVertices", c_uint), # Weight of the AnimMesh. ("mWeight", c_float), ] class Mesh(Structure): """ See 'mesh.h' for details. """ AI_MAX_FACE_INDICES = 0x7fff AI_MAX_BONE_WEIGHTS = 0x7fffffff AI_MAX_VERTICES = 0x7fffffff AI_MAX_FACES = 0x7fffffff AI_MAX_NUMBER_OF_COLOR_SETS = 0x8 AI_MAX_NUMBER_OF_TEXTURECOORDS = 0x8 _fields_ = [ # Bitwise combination of the members of the #aiPrimitiveType enum. # This specifies which types of primitives are present in the mesh. # The "SortByPrimitiveType"-Step can be used to make sure the # output meshes consist of one primitive type each. ("mPrimitiveTypes", c_uint), # The number of vertices in this mesh. # This is also the size of all of the per-vertex data arrays. # The maximum value for this member is #AI_MAX_VERTICES. ("mNumVertices", c_uint), # The number of primitives (triangles, polygons, lines) in this mesh. # This is also the size of the mFaces array. # The maximum value for this member is #AI_MAX_FACES. ("mNumFaces", c_uint), # Vertex positions. # This array is always present in a mesh. The array is # mNumVertices in size. ("mVertices", POINTER(Vector3D)), # Vertex normals. # The array contains normalized vectors, NULL if not present. # The array is mNumVertices in size. Normals are undefined for # point and line primitives. A mesh consisting of points and # lines only may not have normal vectors. Meshes with mixed # primitive types (i.e. lines and triangles) may have normals, # but the normals for vertices that are only referenced by # point or line primitives are undefined and set to QNaN (WARN: # qNaN compares to inequal to *everything*, even to qNaN itself. # Using code like this to check whether a field is qnan is: # @code #define IS_QNAN(f) (f != f) # @endcode # still dangerous because even 1.f == 1.f could evaluate to false! ( # remember the subtleties of IEEE754 artithmetics). Use stuff like # @c fpclassify instead. # @note Normal vectors computed by Assimp are always unit-length. # However, this needn't apply for normals that have been taken # directly from the model file. ("mNormals", POINTER(Vector3D)), # Vertex tangents. # The tangent of a vertex points in the direction of the positive # X texture axis. The array contains normalized vectors, NULL if # not present. The array is mNumVertices in size. A mesh consisting # of points and lines only may not have normal vectors. Meshes with # mixed primitive types (i.e. lines and triangles) may have # normals, but the normals for vertices that are only referenced by # point or line primitives are undefined and set to qNaN. See # the #mNormals member for a detailed discussion of qNaNs. # @note If the mesh contains tangents, it automatically also # contains bitangents (the bitangent is just the cross product of # tangent and normal vectors). ("mTangents", POINTER(Vector3D)), # Vertex bitangents. # The bitangent of a vertex points in the direction of the positive # Y texture axis. The array contains normalized vectors, NULL if not # present. The array is mNumVertices in size. # @note If the mesh contains tangents, it automatically also contains # bitangents. ("mBitangents", POINTER(Vector3D)), # Vertex color sets. # A mesh may contain 0 to #AI_MAX_NUMBER_OF_COLOR_SETS vertex # colors per vertex. NULL if not present. Each array is # mNumVertices in size if present. ("mColors", POINTER(Color4D)*AI_MAX_NUMBER_OF_COLOR_SETS), # Vertex texture coords, also known as UV channels. # A mesh may contain 0 to AI_MAX_NUMBER_OF_TEXTURECOORDS per # vertex. NULL if not present. The array is mNumVertices in size. ("mTextureCoords", POINTER(Vector3D)*AI_MAX_NUMBER_OF_TEXTURECOORDS), # Specifies the number of components for a given UV channel. # Up to three channels are supported (UVW, for accessing volume # or cube maps). If the value is 2 for a given channel n, the # component p.z of mTextureCoords[n][p] is set to 0.0f. # If the value is 1 for a given channel, p.y is set to 0.0f, too. # @note 4D coords are not supported ("mNumUVComponents", c_uint*AI_MAX_NUMBER_OF_TEXTURECOORDS), # The faces the mesh is constructed from. # Each face refers to a number of vertices by their indices. # This array is always present in a mesh, its size is given # in mNumFaces. If the #AI_SCENE_FLAGS_NON_VERBOSE_FORMAT # is NOT set each face references an unique set of vertices. ("mFaces", POINTER(Face)), # The number of bones this mesh contains. # Can be 0, in which case the mBones array is NULL. ("mNumBones", c_uint), # The bones of this mesh. # A bone consists of a name by which it can be found in the # frame hierarchy and a set of vertex weights. ("mBones", POINTER(POINTER(Bone))), # The material used by this mesh. # A mesh does use only a single material. If an imported model uses # multiple materials, the import splits up the mesh. Use this value # as index into the scene's material list. ("mMaterialIndex", c_uint), # Name of the mesh. Meshes can be named, but this is not a # requirement and leaving this field empty is totally fine. # There are mainly three uses for mesh names: # - some formats name nodes and meshes independently. # - importers tend to split meshes up to meet the # one-material-per-mesh requirement. Assigning # the same (dummy) name to each of the result meshes # aids the caller at recovering the original mesh # partitioning. # - Vertex animations refer to meshes by their names. ("mName", String), # The number of attachment meshes. # Currently known to work with loaders: # - Collada # - gltf ("mNumAnimMeshes", c_uint), # Attachment meshes for this mesh, for vertex-based animation. # Attachment meshes carry replacement data for some of the # mesh'es vertex components (usually positions, normals). # Currently known to work with loaders: # - Collada # - gltf ("mAnimMeshes", POINTER(POINTER(AnimMesh))), # Method of morphing when animeshes are specified. ("mMethod", c_uint), ] class Camera(Structure): """ See 'camera.h' for details. """ _fields_ = [ # The name of the camera. # There must be a node in the scenegraph with the same name. # This node specifies the position of the camera in the scene # hierarchy and can be animated. ("mName", String), # Position of the camera relative to the coordinate space # defined by the corresponding node. # The default value is 0|0|0. ("mPosition", Vector3D), # 'Up' - vector of the camera coordinate system relative to # the coordinate space defined by the corresponding node. # The 'right' vector of the camera coordinate system is # the cross product of the up and lookAt vectors. # The default value is 0|1|0. The vector # may be normalized, but it needn't. ("mUp", Vector3D), # 'LookAt' - vector of the camera coordinate system relative to # the coordinate space defined by the corresponding node. # This is the viewing direction of the user. # The default value is 0|0|1. The vector # may be normalized, but it needn't. ("mLookAt", Vector3D), # Half horizontal field of view angle, in radians. # The field of view angle is the angle between the center # line of the screen and the left or right border. # The default value is 1/4PI. ("mHorizontalFOV", c_float), # Distance of the near clipping plane from the camera. # The value may not be 0.f (for arithmetic reasons to prevent # a division through zero). The default value is 0.1f. ("mClipPlaneNear", c_float), # Distance of the far clipping plane from the camera. # The far clipping plane must, of course, be further away than the # near clipping plane. The default value is 1000.f. The ratio # between the near and the far plane should not be too # large (between 1000-10000 should be ok) to avoid floating-point # inaccuracies which could lead to z-fighting. ("mClipPlaneFar", c_float), # Screen aspect ratio. # This is the ration between the width and the height of the # screen. Typical values are 4/3, 1/2 or 1/1. This value is # 0 if the aspect ratio is not defined in the source file. # 0 is also the default value. ("mAspect", c_float), ] class VectorKey(Structure): """ See 'anim.h' for details. """ _fields_ = [ # The time of this key ("mTime", c_double), # The value of this key ("mValue", Vector3D), ] class QuatKey(Structure): """ See 'anim.h' for details. """ _fields_ = [ # The time of this key ("mTime", c_double), # The value of this key ("mValue", Quaternion), ] class MeshMorphKey(Structure): """ See 'anim.h' for details. """ _fields_ = [ # The time of this key ("mTime", c_double), # The values and weights at the time of this key ("mValues", POINTER(c_uint)), ("mWeights", POINTER(c_double)), # The number of values and weights ("mNumValuesAndWeights", c_uint), ] class NodeAnim(Structure): """ See 'anim.h' for details. """ _fields_ = [ # The name of the node affected by this animation. The node # must exist and it must be unique. ("mNodeName", String), # The number of position keys ("mNumPositionKeys", c_uint), # The position keys of this animation channel. Positions are # specified as 3D vector. The array is mNumPositionKeys in size. # If there are position keys, there will also be at least one # scaling and one rotation key. ("mPositionKeys", POINTER(VectorKey)), # The number of rotation keys ("mNumRotationKeys", c_uint), # The rotation keys of this animation channel. Rotations are # given as quaternions, which are 4D vectors. The array is # mNumRotationKeys in size. # If there are rotation keys, there will also be at least one # scaling and one position key. ("mRotationKeys", POINTER(QuatKey)), # The number of scaling keys ("mNumScalingKeys", c_uint), # The scaling keys of this animation channel. Scalings are # specified as 3D vector. The array is mNumScalingKeys in size. # If there are scaling keys, there will also be at least one # position and one rotation key. ("mScalingKeys", POINTER(VectorKey)), # Defines how the animation behaves before the first # key is encountered. # The default value is aiAnimBehaviour_DEFAULT (the original # transformation matrix of the affected node is used). ("mPreState", c_uint), # Defines how the animation behaves after the last # key was processed. # The default value is aiAnimBehaviour_DEFAULT (the original # transformation matrix of the affected node is taken). ("mPostState", c_uint), ] class MeshAnim(Structure): """ See 'anim.h' for details. """ _fields_ = [ # Name of the mesh to be animated. An empty string is not allowed, # animated meshes need to be named (not necessarily uniquely, # the name can basically serve as wild-card to select a group # of meshes with similar animation setup) ("mName", String), # Size of the #mKeys array. Must be 1, at least. ("mNumKeys", c_uint), # Key frames of the animation. May not be NULL. ("mKeys", POINTER(MeshKey)), ] class MeshMorphAnim(Structure): """ See 'anim.h' for details. """ _fields_ = [ # Name of the mesh to be animated. An empty string is not allowed, # animated meshes need to be named (not necessarily uniquely, # the name can basically serve as wildcard to select a group # of meshes with similar animation setup) ("mName", String), # Size of the #mKeys array. Must be 1, at least. ("mNumKeys", c_uint), # Key frames of the animation. May not be NULL. ("mKeys", POINTER(MeshMorphKey)), ] class Animation(Structure): """ See 'anim.h' for details. """ _fields_ = [ # The name of the animation. If the modeling package this data was # exported from does support only a single animation channel, this # name is usually empty (length is zero). ("mName", String), # Duration of the animation in ticks. ("mDuration", c_double), # Ticks per second. 0 if not specified in the imported file ("mTicksPerSecond", c_double), # The number of bone animation channels. Each channel affects # a single node. ("mNumChannels", c_uint), # The node animation channels. Each channel affects a single node. # The array is mNumChannels in size. ("mChannels", POINTER(POINTER(NodeAnim))), # The number of mesh animation channels. Each channel affects # a single mesh and defines vertex-based animation. ("mNumMeshChannels", c_uint), # The mesh animation channels. Each channel affects a single mesh. # The array is mNumMeshChannels in size. ("mMeshChannels", POINTER(POINTER(MeshAnim))), # The number of mesh animation channels. Each channel affects # a single mesh and defines morphing animation. ("mNumMorphMeshChannels", c_uint), # The morph mesh animation channels. Each channel affects a single mesh. # The array is mNumMorphMeshChannels in size. ("mMorphMeshChannels", POINTER(POINTER(MeshMorphAnim))), ] class ExportDataBlob(Structure): """ See 'cexport.h' for details. Note that the '_fields_' definition is outside the class to allow the 'next' field to be recursive """ pass ExportDataBlob._fields_ = [ # Size of the data in bytes ("size", c_size_t), # The data. ("data", c_void_p), # Name of the blob. An empty string always # indicates the first (and primary) blob, # which contains the actual file data. # Any other blobs are auxiliary files produced # by exporters (i.e. material files). Existence # of such files depends on the file format. Most # formats don't split assets across multiple files. # # If used, blob names usually contain the file # extension that should be used when writing # the data to disc. ("name", String), # Pointer to the next blob in the chain or NULL if there is none. ("next", POINTER(ExportDataBlob)), ] class Scene(Structure): """ See 'aiScene.h' for details. """ AI_SCENE_FLAGS_INCOMPLETE = 0x1 AI_SCENE_FLAGS_VALIDATED = 0x2 AI_SCENE_FLAGS_VALIDATION_WARNING = 0x4 AI_SCENE_FLAGS_NON_VERBOSE_FORMAT = 0x8 AI_SCENE_FLAGS_TERRAIN = 0x10 AI_SCENE_FLAGS_ALLOW_SHARED = 0x20 _fields_ = [ # Any combination of the AI_SCENE_FLAGS_XXX flags. By default # this value is 0, no flags are set. Most applications will # want to reject all scenes with the AI_SCENE_FLAGS_INCOMPLETE # bit set. ("mFlags", c_uint), # The root node of the hierarchy. # There will always be at least the root node if the import # was successful (and no special flags have been set). # Presence of further nodes depends on the format and content # of the imported file. ("mRootNode", POINTER(Node)), # The number of meshes in the scene. ("mNumMeshes", c_uint), # The array of meshes. # Use the indices given in the aiNode structure to access # this array. The array is mNumMeshes in size. If the # AI_SCENE_FLAGS_INCOMPLETE flag is not set there will always # be at least ONE material. ("mMeshes", POINTER(POINTER(Mesh))), # The number of materials in the scene. ("mNumMaterials", c_uint), # The array of materials. # Use the index given in each aiMesh structure to access this # array. The array is mNumMaterials in size. If the # AI_SCENE_FLAGS_INCOMPLETE flag is not set there will always # be at least ONE material. ("mMaterials", POINTER(POINTER(Material))), # The number of animations in the scene. ("mNumAnimations", c_uint), # The array of animations. # All animations imported from the given file are listed here. # The array is mNumAnimations in size. ("mAnimations", POINTER(POINTER(Animation))), # The number of textures embedded into the file ("mNumTextures", c_uint), # The array of embedded textures. # Not many file formats embed their textures into the file. # An example is Quake's MDL format (which is also used by # some GameStudio versions) ("mTextures", POINTER(POINTER(Texture))), # The number of light sources in the scene. Light sources # are fully optional, in most cases this attribute will be 0 ("mNumLights", c_uint), # The array of light sources. # All light sources imported from the given file are # listed here. The array is mNumLights in size. ("mLights", POINTER(POINTER(Light))), # The number of cameras in the scene. Cameras # are fully optional, in most cases this attribute will be 0 ("mNumCameras", c_uint), # The array of cameras. # All cameras imported from the given file are listed here. # The array is mNumCameras in size. The first camera in the # array (if existing) is the default camera view into # the scene. ("mCameras", POINTER(POINTER(Camera))), # This data contains global metadata which belongs to the scene like # unit-conversions, versions, vendors or other model-specific data. This # can be used to store format-specific metadata as well. ("mMetadata", POINTER(Metadata)), # Internal data, do not touch ("mPrivate", POINTER(c_char)), ] assimp_structs_as_tuple = (Matrix4x4, Matrix3x3, Vector2D, Vector3D, Color3D, Color4D, Quaternion, Plane, Texel)
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/pyassimp/postprocess.py
# <hr>Calculates the tangents and bitangents for the imported meshes. # # Does nothing if a mesh does not have normals. You might want this post # processing step to be executed if you plan to use tangent space calculations # such as normal mapping applied to the meshes. There's a config setting, # <tt>#AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE<tt>, which allows you to specify # a maximum smoothing angle for the algorithm. However, usually you'll # want to leave it at the default value. # aiProcess_CalcTangentSpace = 0x1 ## <hr>Identifies and joins identical vertex data sets within all # imported meshes. # # After this step is run, each mesh contains unique vertices, # so a vertex may be used by multiple faces. You usually want # to use this post processing step. If your application deals with # indexed geometry, this step is compulsory or you'll just waste rendering # time. <b>If this flag is not specified<b>, no vertices are referenced by # more than one face and <b>no index buffer is required<b> for rendering. # aiProcess_JoinIdenticalVertices = 0x2 ## <hr>Converts all the imported data to a left-handed coordinate space. # # By default the data is returned in a right-handed coordinate space (which # OpenGL prefers). In this space, +X points to the right, # +Z points towards the viewer, and +Y points upwards. In the DirectX # coordinate space +X points to the right, +Y points upwards, and +Z points # away from the viewer. # # You'll probably want to consider this flag if you use Direct3D for # rendering. The #aiProcess_ConvertToLeftHanded flag supersedes this # setting and bundles all conversions typically required for D3D-based # applications. # aiProcess_MakeLeftHanded = 0x4 ## <hr>Triangulates all faces of all meshes. # # By default the imported mesh data might contain faces with more than 3 # indices. For rendering you'll usually want all faces to be triangles. # This post processing step splits up faces with more than 3 indices into # triangles. Line and point primitives are #not# modified! If you want # 'triangles only' with no other kinds of primitives, try the following # solution: # <ul> # <li>Specify both #aiProcess_Triangulate and #aiProcess_SortByPType <li> # <li>Ignore all point and line meshes when you process assimp's output<li> # <ul> # aiProcess_Triangulate = 0x8 ## <hr>Removes some parts of the data structure (animations, materials, # light sources, cameras, textures, vertex components). # # The components to be removed are specified in a separate # configuration option, <tt>#AI_CONFIG_PP_RVC_FLAGS<tt>. This is quite useful # if you don't need all parts of the output structure. Vertex colors # are rarely used today for example... Calling this step to remove unneeded # data from the pipeline as early as possible results in increased # performance and a more optimized output data structure. # This step is also useful if you want to force Assimp to recompute # normals or tangents. The corresponding steps don't recompute them if # they're already there (loaded from the source asset). By using this # step you can make sure they are NOT there. # # This flag is a poor one, mainly because its purpose is usually # misunderstood. Consider the following case: a 3D model has been exported # from a CAD app, and it has per-face vertex colors. Vertex positions can't be # shared, thus the #aiProcess_JoinIdenticalVertices step fails to # optimize the data because of these nasty little vertex colors. # Most apps don't even process them, so it's all for nothing. By using # this step, unneeded components are excluded as early as possible # thus opening more room for internal optimizations. # aiProcess_RemoveComponent = 0x10 ## <hr>Generates normals for all faces of all meshes. # # This is ignored if normals are already there at the time this flag # is evaluated. Model importers try to load them from the source file, so # they're usually already there. Face normals are shared between all points # of a single face, so a single point can have multiple normals, which # forces the library to duplicate vertices in some cases. # #aiProcess_JoinIdenticalVertices is #senseless# then. # # This flag may not be specified together with #aiProcess_GenSmoothNormals. # aiProcess_GenNormals = 0x20 ## <hr>Generates smooth normals for all vertices in the mesh. # # This is ignored if normals are already there at the time this flag # is evaluated. Model importers try to load them from the source file, so # they're usually already there. # # This flag may not be specified together with # #aiProcess_GenNormals. There's a configuration option, # <tt>#AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE<tt> which allows you to specify # an angle maximum for the normal smoothing algorithm. Normals exceeding # this limit are not smoothed, resulting in a 'hard' seam between two faces. # Using a decent angle here (e.g. 80 degrees) results in very good visual # appearance. # aiProcess_GenSmoothNormals = 0x40 ## <hr>Splits large meshes into smaller sub-meshes. # # This is quite useful for real-time rendering, where the number of triangles # which can be maximally processed in a single draw-call is limited # by the video driverhardware. The maximum vertex buffer is usually limited # too. Both requirements can be met with this step: you may specify both a # triangle and vertex limit for a single mesh. # # The split limits can (and should!) be set through the # <tt>#AI_CONFIG_PP_SLM_VERTEX_LIMIT<tt> and <tt>#AI_CONFIG_PP_SLM_TRIANGLE_LIMIT<tt> # settings. The default values are <tt>#AI_SLM_DEFAULT_MAX_VERTICES<tt> and # <tt>#AI_SLM_DEFAULT_MAX_TRIANGLES<tt>. # # Note that splitting is generally a time-consuming task, but only if there's # something to split. The use of this step is recommended for most users. # aiProcess_SplitLargeMeshes = 0x80 ## <hr>Removes the node graph and pre-transforms all vertices with # the local transformation matrices of their nodes. # # The output scene still contains nodes, however there is only a # root node with children, each one referencing only one mesh, # and each mesh referencing one material. For rendering, you can # simply render all meshes in order - you don't need to pay # attention to local transformations and the node hierarchy. # Animations are removed during this step. # This step is intended for applications without a scenegraph. # The step CAN cause some problems: if e.g. a mesh of the asset # contains normals and another, using the same material index, does not, # they will be brought together, but the first meshes's part of # the normal list is zeroed. However, these artifacts are rare. # @note The <tt>#AI_CONFIG_PP_PTV_NORMALIZE<tt> configuration property # can be set to normalize the scene's spatial dimension to the -1...1 # range. # aiProcess_PreTransformVertices = 0x100 ## <hr>Limits the number of bones simultaneously affecting a single vertex # to a maximum value. # # If any vertex is affected by more than the maximum number of bones, the least # important vertex weights are removed and the remaining vertex weights are # renormalized so that the weights still sum up to 1. # The default bone weight limit is 4 (defined as <tt>#AI_LMW_MAX_WEIGHTS<tt> in # config.h), but you can use the <tt>#AI_CONFIG_PP_LBW_MAX_WEIGHTS<tt> setting to # supply your own limit to the post processing step. # # If you intend to perform the skinning in hardware, this post processing # step might be of interest to you. # aiProcess_LimitBoneWeights = 0x200 ## <hr>Validates the imported scene data structure. # This makes sure that all indices are valid, all animations and # bones are linked correctly, all material references are correct .. etc. # # It is recommended that you capture Assimp's log output if you use this flag, # so you can easily find out what's wrong if a file fails the # validation. The validator is quite strict and will find #all# # inconsistencies in the data structure... It is recommended that plugin # developers use it to debug their loaders. There are two types of # validation failures: # <ul> # <li>Error: There's something wrong with the imported data. Further # postprocessing is not possible and the data is not usable at all. # The import fails. #Importer::GetErrorString() or #aiGetErrorString() # carry the error message around.<li> # <li>Warning: There are some minor issues (e.g. 1000000 animation # keyframes with the same time), but further postprocessing and use # of the data structure is still safe. Warning details are written # to the log file, <tt>#AI_SCENE_FLAGS_VALIDATION_WARNING<tt> is set # in #aiScene::mFlags<li> # <ul> # # This post-processing step is not time-consuming. Its use is not # compulsory, but recommended. # aiProcess_ValidateDataStructure = 0x400 ## <hr>Reorders triangles for better vertex cache locality. # # The step tries to improve the ACMR (average post-transform vertex cache # miss ratio) for all meshes. The implementation runs in O(n) and is # roughly based on the 'tipsify' algorithm (see <a href=" # http:www.cs.princeton.edugfxpubsSander_2007_%3ETRtipsy.pdf">this # paper<a>). # # If you intend to render huge models in hardware, this step might # be of interest to you. The <tt>#AI_CONFIG_PP_ICL_PTCACHE_SIZE<tt>config # setting can be used to fine-tune the cache optimization. # aiProcess_ImproveCacheLocality = 0x800 ## <hr>Searches for redundantunreferenced materials and removes them. # # This is especially useful in combination with the # #aiProcess_PretransformVertices and #aiProcess_OptimizeMeshes flags. # Both join small meshes with equal characteristics, but they can't do # their work if two meshes have different materials. Because several # material settings are lost during Assimp's import filters, # (and because many exporters don't check for redundant materials), huge # models often have materials which are are defined several times with # exactly the same settings. # # Several material settings not contributing to the final appearance of # a surface are ignored in all comparisons (e.g. the material name). # So, if you're passing additional information through the # content pipeline (probably using #magic# material names), don't # specify this flag. Alternatively take a look at the # <tt>#AI_CONFIG_PP_RRM_EXCLUDE_LIST<tt> setting. # aiProcess_RemoveRedundantMaterials = 0x1000 ## <hr>This step tries to determine which meshes have normal vectors # that are facing inwards and inverts them. # # The algorithm is simple but effective: # the bounding box of all vertices + their normals is compared against # the volume of the bounding box of all vertices without their normals. # This works well for most objects, problems might occur with planar # surfaces. However, the step tries to filter such cases. # The step inverts all in-facing normals. Generally it is recommended # to enable this step, although the result is not always correct. # aiProcess_FixInfacingNormals = 0x2000 ## <hr>This step splits meshes with more than one primitive type in # homogeneous sub-meshes. # # The step is executed after the triangulation step. After the step # returns, just one bit is set in aiMesh::mPrimitiveTypes. This is # especially useful for real-time rendering where point and line # primitives are often ignored or rendered separately. # You can use the <tt>#AI_CONFIG_PP_SBP_REMOVE<tt> option to specify which # primitive types you need. This can be used to easily exclude # lines and points, which are rarely used, from the import. # aiProcess_SortByPType = 0x8000 ## <hr>This step searches all meshes for degenerate primitives and # converts them to proper lines or points. # # A face is 'degenerate' if one or more of its points are identical. # To have the degenerate stuff not only detected and collapsed but # removed, try one of the following procedures: # <br><b>1.<b> (if you support lines and points for rendering but don't # want the degenerates)<br> # <ul> # <li>Specify the #aiProcess_FindDegenerates flag. # <li> # <li>Set the <tt>AI_CONFIG_PP_FD_REMOVE<tt> option to 1. This will # cause the step to remove degenerate triangles from the import # as soon as they're detected. They won't pass any further # pipeline steps. # <li> # <ul> # <br><b>2.<b>(if you don't support lines and points at all)<br> # <ul> # <li>Specify the #aiProcess_FindDegenerates flag. # <li> # <li>Specify the #aiProcess_SortByPType flag. This moves line and # point primitives to separate meshes. # <li> # <li>Set the <tt>AI_CONFIG_PP_SBP_REMOVE<tt> option to # @code aiPrimitiveType_POINTS | aiPrimitiveType_LINES # @endcode to cause SortByPType to reject point # and line meshes from the scene. # <li> # <ul> # @note Degenerate polygons are not necessarily evil and that's why # they're not removed by default. There are several file formats which # don't support lines or points, and some exporters bypass the # format specification and write them as degenerate triangles instead. # aiProcess_FindDegenerates = 0x10000 ## <hr>This step searches all meshes for invalid data, such as zeroed # normal vectors or invalid UV coords and removesfixes them. This is # intended to get rid of some common exporter errors. # # This is especially useful for normals. If they are invalid, and # the step recognizes this, they will be removed and can later # be recomputed, i.e. by the #aiProcess_GenSmoothNormals flag.<br> # The step will also remove meshes that are infinitely small and reduce # animation tracks consisting of hundreds if redundant keys to a single # key. The <tt>AI_CONFIG_PP_FID_ANIM_ACCURACY<tt> config property decides # the accuracy of the check for duplicate animation tracks. # aiProcess_FindInvalidData = 0x20000 ## <hr>This step converts non-UV mappings (such as spherical or # cylindrical mapping) to proper texture coordinate channels. # # Most applications will support UV mapping only, so you will # probably want to specify this step in every case. Note that Assimp is not # always able to match the original mapping implementation of the # 3D app which produced a model perfectly. It's always better to let the # modelling app compute the UV channels - 3ds max, Maya, Blender, # LightWave, and Modo do this for example. # # @note If this step is not requested, you'll need to process the # <tt>#AI_MATKEY_MAPPING<tt> material property in order to display all assets # properly. # aiProcess_GenUVCoords = 0x40000 ## <hr>This step applies per-texture UV transformations and bakes # them into stand-alone vtexture coordinate channels. # # UV transformations are specified per-texture - see the # <tt>#AI_MATKEY_UVTRANSFORM<tt> material key for more information. # This step processes all textures with # transformed input UV coordinates and generates a new (pre-transformed) UV channel # which replaces the old channel. Most applications won't support UV # transformations, so you will probably want to specify this step. # # @note UV transformations are usually implemented in real-time apps by # transforming texture coordinates at vertex shader stage with a 3x3 # (homogenous) transformation matrix. # aiProcess_TransformUVCoords = 0x80000 ## <hr>This step searches for duplicate meshes and replaces them # with references to the first mesh. # # This step takes a while, so don't use it if speed is a concern. # Its main purpose is to workaround the fact that many export # file formats don't support instanced meshes, so exporters need to # duplicate meshes. This step removes the duplicates again. Please # note that Assimp does not currently support per-node material # assignment to meshes, which means that identical meshes with # different materials are currently #not# joined, although this is # planned for future versions. # aiProcess_FindInstances = 0x100000 ## <hr>A postprocessing step to reduce the number of meshes. # # This will, in fact, reduce the number of draw calls. # # This is a very effective optimization and is recommended to be used # together with #aiProcess_OptimizeGraph, if possible. The flag is fully # compatible with both #aiProcess_SplitLargeMeshes and #aiProcess_SortByPType. # aiProcess_OptimizeMeshes = 0x200000 ## <hr>A postprocessing step to optimize the scene hierarchy. # # Nodes without animations, bones, lights or cameras assigned are # collapsed and joined. # # Node names can be lost during this step. If you use special 'tag nodes' # to pass additional information through your content pipeline, use the # <tt>#AI_CONFIG_PP_OG_EXCLUDE_LIST<tt> setting to specify a list of node # names you want to be kept. Nodes matching one of the names in this list won't # be touched or modified. # # Use this flag with caution. Most simple files will be collapsed to a # single node, so complex hierarchies are usually completely lost. This is not # useful for editor environments, but probably a very effective # optimization if you just want to get the model data, convert it to your # own format, and render it as fast as possible. # # This flag is designed to be used with #aiProcess_OptimizeMeshes for best # results. # # @note 'Crappy' scenes with thousands of extremely small meshes packed # in deeply nested nodes exist for almost all file formats. # #aiProcess_OptimizeMeshes in combination with #aiProcess_OptimizeGraph # usually fixes them all and makes them renderable. # aiProcess_OptimizeGraph = 0x400000 ## <hr>This step flips all UV coordinates along the y-axis and adjusts # material settings and bitangents accordingly. # # <b>Output UV coordinate system:<b> # @code # 0y|0y ---------- 1x|0y # | | # | | # | | # 0x|1y ---------- 1x|1y # @endcode # # You'll probably want to consider this flag if you use Direct3D for # rendering. The #aiProcess_ConvertToLeftHanded flag supersedes this # setting and bundles all conversions typically required for D3D-based # applications. # aiProcess_FlipUVs = 0x800000 ## <hr>This step adjusts the output face winding order to be CW. # # The default face winding order is counter clockwise (CCW). # # <b>Output face order:<b> # @code # x2 # # x0 # x1 # @endcode # aiProcess_FlipWindingOrder = 0x1000000 ## <hr>This step splits meshes with many bones into sub-meshes so that each # su-bmesh has fewer or as many bones as a given limit. # aiProcess_SplitByBoneCount = 0x2000000 ## <hr>This step removes bones losslessly or according to some threshold. # # In some cases (i.e. formats that require it) exporters are forced to # assign dummy bone weights to otherwise static meshes assigned to # animated meshes. Full, weight-based skinning is expensive while # animating nodes is extremely cheap, so this step is offered to clean up # the data in that regard. # # Use <tt>#AI_CONFIG_PP_DB_THRESHOLD<tt> to control this. # Use <tt>#AI_CONFIG_PP_DB_ALL_OR_NONE<tt> if you want bones removed if and # only if all bones within the scene qualify for removal. # aiProcess_Debone = 0x4000000 aiProcess_GenEntityMeshes = 0x100000 aiProcess_OptimizeAnimations = 0x200000 aiProcess_FixTexturePaths = 0x200000 aiProcess_EmbedTextures = 0x10000000, ## @def aiProcess_ConvertToLeftHanded # @brief Shortcut flag for Direct3D-based applications. # # Supersedes the #aiProcess_MakeLeftHanded and #aiProcess_FlipUVs and # #aiProcess_FlipWindingOrder flags. # The output data matches Direct3D's conventions: left-handed geometry, upper-left # origin for UV coordinates and finally clockwise face order, suitable for CCW culling. # # @deprecated # aiProcess_ConvertToLeftHanded = ( \ aiProcess_MakeLeftHanded | \ aiProcess_FlipUVs | \ aiProcess_FlipWindingOrder | \ 0 ) ## @def aiProcessPreset_TargetRealtimeUse_Fast # @brief Default postprocess configuration optimizing the data for real-time rendering. # # Applications would want to use this preset to load models on end-user PCs, # maybe for direct use in game. # # If you're using DirectX, don't forget to combine this value with # the #aiProcess_ConvertToLeftHanded step. If you don't support UV transformations # in your application apply the #aiProcess_TransformUVCoords step, too. # @note Please take the time to read the docs for the steps enabled by this preset. # Some of them offer further configurable properties, while some of them might not be of # use for you so it might be better to not specify them. # aiProcessPreset_TargetRealtime_Fast = ( \ aiProcess_CalcTangentSpace | \ aiProcess_GenNormals | \ aiProcess_JoinIdenticalVertices | \ aiProcess_Triangulate | \ aiProcess_GenUVCoords | \ aiProcess_SortByPType | \ 0 ) ## @def aiProcessPreset_TargetRealtime_Quality # @brief Default postprocess configuration optimizing the data for real-time rendering. # # Unlike #aiProcessPreset_TargetRealtime_Fast, this configuration # performs some extra optimizations to improve rendering speed and # to minimize memory usage. It could be a good choice for a level editor # environment where import speed is not so important. # # If you're using DirectX, don't forget to combine this value with # the #aiProcess_ConvertToLeftHanded step. If you don't support UV transformations # in your application apply the #aiProcess_TransformUVCoords step, too. # @note Please take the time to read the docs for the steps enabled by this preset. # Some of them offer further configurable properties, while some of them might not be # of use for you so it might be better to not specify them. # aiProcessPreset_TargetRealtime_Quality = ( \ aiProcess_CalcTangentSpace | \ aiProcess_GenSmoothNormals | \ aiProcess_JoinIdenticalVertices | \ aiProcess_ImproveCacheLocality | \ aiProcess_LimitBoneWeights | \ aiProcess_RemoveRedundantMaterials | \ aiProcess_SplitLargeMeshes | \ aiProcess_Triangulate | \ aiProcess_GenUVCoords | \ aiProcess_SortByPType | \ aiProcess_FindDegenerates | \ aiProcess_FindInvalidData | \ 0 ) ## @def aiProcessPreset_TargetRealtime_MaxQuality # @brief Default postprocess configuration optimizing the data for real-time rendering. # # This preset enables almost every optimization step to achieve perfectly # optimized data. It's your choice for level editor environments where import speed # is not important. # # If you're using DirectX, don't forget to combine this value with # the #aiProcess_ConvertToLeftHanded step. If you don't support UV transformations # in your application, apply the #aiProcess_TransformUVCoords step, too. # @note Please take the time to read the docs for the steps enabled by this preset. # Some of them offer further configurable properties, while some of them might not be # of use for you so it might be better to not specify them. # aiProcessPreset_TargetRealtime_MaxQuality = ( \ aiProcessPreset_TargetRealtime_Quality | \ aiProcess_FindInstances | \ aiProcess_ValidateDataStructure | \ aiProcess_OptimizeMeshes | \ 0 )
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/mf/ov/gdtf/pyassimp/helper.py
#-*- coding: UTF-8 -*- """ Some fancy helper functions. """ import os import ctypes import operator from distutils.sysconfig import get_python_lib import re import sys try: import numpy except ImportError: numpy = None import logging;logger = logging.getLogger("pyassimp") from .errors import AssimpError additional_dirs, ext_whitelist = [],[] # populate search directories and lists of allowed file extensions # depending on the platform we're running on. if os.name=='posix': additional_dirs.append('./') additional_dirs.append('/usr/lib/') additional_dirs.append('/usr/lib/x86_64-linux-gnu/') additional_dirs.append('/usr/lib/aarch64-linux-gnu/') additional_dirs.append('/usr/local/lib/') if 'LD_LIBRARY_PATH' in os.environ: additional_dirs.extend([item for item in os.environ['LD_LIBRARY_PATH'].split(':') if item]) # check if running from anaconda. anaconda_keywords = ("conda", "continuum") if any(k in sys.version.lower() for k in anaconda_keywords): cur_path = get_python_lib() pattern = re.compile('.*\/lib\/') conda_lib = pattern.match(cur_path).group() logger.info("Adding Anaconda lib path:"+ conda_lib) additional_dirs.append(conda_lib) # note - this won't catch libassimp.so.N.n, but # currently there's always a symlink called # libassimp.so in /usr/local/lib. ext_whitelist.append('.so') # libassimp.dylib in /usr/local/lib ext_whitelist.append('.dylib') elif os.name=='nt': ext_whitelist.append('.dll') path_dirs = os.environ['PATH'].split(';') additional_dirs.extend(path_dirs) def vec2tuple(x): """ Converts a VECTOR3D to a Tuple """ return (x.x, x.y, x.z) def transform(vector3, matrix4x4): """ Apply a transformation matrix on a 3D vector. :param vector3: array with 3 elements :param matrix4x4: 4x4 matrix """ if numpy: return numpy.dot(matrix4x4, numpy.append(vector3, 1.)) else: m0,m1,m2,m3 = matrix4x4; x,y,z = vector3 return [ m0[0]*x + m0[1]*y + m0[2]*z + m0[3], m1[0]*x + m1[1]*y + m1[2]*z + m1[3], m2[0]*x + m2[1]*y + m2[2]*z + m2[3], m3[0]*x + m3[1]*y + m3[2]*z + m3[3] ] def _inv(matrix4x4): m0,m1,m2,m3 = matrix4x4 det = m0[3]*m1[2]*m2[1]*m3[0] - m0[2]*m1[3]*m2[1]*m3[0] - \ m0[3]*m1[1]*m2[2]*m3[0] + m0[1]*m1[3]*m2[2]*m3[0] + \ m0[2]*m1[1]*m2[3]*m3[0] - m0[1]*m1[2]*m2[3]*m3[0] - \ m0[3]*m1[2]*m2[0]*m3[1] + m0[2]*m1[3]*m2[0]*m3[1] + \ m0[3]*m1[0]*m2[2]*m3[1] - m0[0]*m1[3]*m2[2]*m3[1] - \ m0[2]*m1[0]*m2[3]*m3[1] + m0[0]*m1[2]*m2[3]*m3[1] + \ m0[3]*m1[1]*m2[0]*m3[2] - m0[1]*m1[3]*m2[0]*m3[2] - \ m0[3]*m1[0]*m2[1]*m3[2] + m0[0]*m1[3]*m2[1]*m3[2] + \ m0[1]*m1[0]*m2[3]*m3[2] - m0[0]*m1[1]*m2[3]*m3[2] - \ m0[2]*m1[1]*m2[0]*m3[3] + m0[1]*m1[2]*m2[0]*m3[3] + \ m0[2]*m1[0]*m2[1]*m3[3] - m0[0]*m1[2]*m2[1]*m3[3] - \ m0[1]*m1[0]*m2[2]*m3[3] + m0[0]*m1[1]*m2[2]*m3[3] return[[( m1[2]*m2[3]*m3[1] - m1[3]*m2[2]*m3[1] + m1[3]*m2[1]*m3[2] - m1[1]*m2[3]*m3[2] - m1[2]*m2[1]*m3[3] + m1[1]*m2[2]*m3[3]) /det, ( m0[3]*m2[2]*m3[1] - m0[2]*m2[3]*m3[1] - m0[3]*m2[1]*m3[2] + m0[1]*m2[3]*m3[2] + m0[2]*m2[1]*m3[3] - m0[1]*m2[2]*m3[3]) /det, ( m0[2]*m1[3]*m3[1] - m0[3]*m1[2]*m3[1] + m0[3]*m1[1]*m3[2] - m0[1]*m1[3]*m3[2] - m0[2]*m1[1]*m3[3] + m0[1]*m1[2]*m3[3]) /det, ( m0[3]*m1[2]*m2[1] - m0[2]*m1[3]*m2[1] - m0[3]*m1[1]*m2[2] + m0[1]*m1[3]*m2[2] + m0[2]*m1[1]*m2[3] - m0[1]*m1[2]*m2[3]) /det], [( m1[3]*m2[2]*m3[0] - m1[2]*m2[3]*m3[0] - m1[3]*m2[0]*m3[2] + m1[0]*m2[3]*m3[2] + m1[2]*m2[0]*m3[3] - m1[0]*m2[2]*m3[3]) /det, ( m0[2]*m2[3]*m3[0] - m0[3]*m2[2]*m3[0] + m0[3]*m2[0]*m3[2] - m0[0]*m2[3]*m3[2] - m0[2]*m2[0]*m3[3] + m0[0]*m2[2]*m3[3]) /det, ( m0[3]*m1[2]*m3[0] - m0[2]*m1[3]*m3[0] - m0[3]*m1[0]*m3[2] + m0[0]*m1[3]*m3[2] + m0[2]*m1[0]*m3[3] - m0[0]*m1[2]*m3[3]) /det, ( m0[2]*m1[3]*m2[0] - m0[3]*m1[2]*m2[0] + m0[3]*m1[0]*m2[2] - m0[0]*m1[3]*m2[2] - m0[2]*m1[0]*m2[3] + m0[0]*m1[2]*m2[3]) /det], [( m1[1]*m2[3]*m3[0] - m1[3]*m2[1]*m3[0] + m1[3]*m2[0]*m3[1] - m1[0]*m2[3]*m3[1] - m1[1]*m2[0]*m3[3] + m1[0]*m2[1]*m3[3]) /det, ( m0[3]*m2[1]*m3[0] - m0[1]*m2[3]*m3[0] - m0[3]*m2[0]*m3[1] + m0[0]*m2[3]*m3[1] + m0[1]*m2[0]*m3[3] - m0[0]*m2[1]*m3[3]) /det, ( m0[1]*m1[3]*m3[0] - m0[3]*m1[1]*m3[0] + m0[3]*m1[0]*m3[1] - m0[0]*m1[3]*m3[1] - m0[1]*m1[0]*m3[3] + m0[0]*m1[1]*m3[3]) /det, ( m0[3]*m1[1]*m2[0] - m0[1]*m1[3]*m2[0] - m0[3]*m1[0]*m2[1] + m0[0]*m1[3]*m2[1] + m0[1]*m1[0]*m2[3] - m0[0]*m1[1]*m2[3]) /det], [( m1[2]*m2[1]*m3[0] - m1[1]*m2[2]*m3[0] - m1[2]*m2[0]*m3[1] + m1[0]*m2[2]*m3[1] + m1[1]*m2[0]*m3[2] - m1[0]*m2[1]*m3[2]) /det, ( m0[1]*m2[2]*m3[0] - m0[2]*m2[1]*m3[0] + m0[2]*m2[0]*m3[1] - m0[0]*m2[2]*m3[1] - m0[1]*m2[0]*m3[2] + m0[0]*m2[1]*m3[2]) /det, ( m0[2]*m1[1]*m3[0] - m0[1]*m1[2]*m3[0] - m0[2]*m1[0]*m3[1] + m0[0]*m1[2]*m3[1] + m0[1]*m1[0]*m3[2] - m0[0]*m1[1]*m3[2]) /det, ( m0[1]*m1[2]*m2[0] - m0[2]*m1[1]*m2[0] + m0[2]*m1[0]*m2[1] - m0[0]*m1[2]*m2[1] - m0[1]*m1[0]*m2[2] + m0[0]*m1[1]*m2[2]) /det]] def get_bounding_box(scene): bb_min = [1e10, 1e10, 1e10] # x,y,z bb_max = [-1e10, -1e10, -1e10] # x,y,z inv = numpy.linalg.inv if numpy else _inv return get_bounding_box_for_node(scene.rootnode, bb_min, bb_max, inv(scene.rootnode.transformation)) def get_bounding_box_for_node(node, bb_min, bb_max, transformation): if numpy: transformation = numpy.dot(transformation, node.transformation) else: t0,t1,t2,t3 = transformation T0,T1,T2,T3 = node.transformation transformation = [ [ t0[0]*T0[0] + t0[1]*T1[0] + t0[2]*T2[0] + t0[3]*T3[0], t0[0]*T0[1] + t0[1]*T1[1] + t0[2]*T2[1] + t0[3]*T3[1], t0[0]*T0[2] + t0[1]*T1[2] + t0[2]*T2[2] + t0[3]*T3[2], t0[0]*T0[3] + t0[1]*T1[3] + t0[2]*T2[3] + t0[3]*T3[3] ],[ t1[0]*T0[0] + t1[1]*T1[0] + t1[2]*T2[0] + t1[3]*T3[0], t1[0]*T0[1] + t1[1]*T1[1] + t1[2]*T2[1] + t1[3]*T3[1], t1[0]*T0[2] + t1[1]*T1[2] + t1[2]*T2[2] + t1[3]*T3[2], t1[0]*T0[3] + t1[1]*T1[3] + t1[2]*T2[3] + t1[3]*T3[3] ],[ t2[0]*T0[0] + t2[1]*T1[0] + t2[2]*T2[0] + t2[3]*T3[0], t2[0]*T0[1] + t2[1]*T1[1] + t2[2]*T2[1] + t2[3]*T3[1], t2[0]*T0[2] + t2[1]*T1[2] + t2[2]*T2[2] + t2[3]*T3[2], t2[0]*T0[3] + t2[1]*T1[3] + t2[2]*T2[3] + t2[3]*T3[3] ],[ t3[0]*T0[0] + t3[1]*T1[0] + t3[2]*T2[0] + t3[3]*T3[0], t3[0]*T0[1] + t3[1]*T1[1] + t3[2]*T2[1] + t3[3]*T3[1], t3[0]*T0[2] + t3[1]*T1[2] + t3[2]*T2[2] + t3[3]*T3[2], t3[0]*T0[3] + t3[1]*T1[3] + t3[2]*T2[3] + t3[3]*T3[3] ] ] for mesh in node.meshes: for v in mesh.vertices: v = transform(v, transformation) bb_min[0] = min(bb_min[0], v[0]) bb_min[1] = min(bb_min[1], v[1]) bb_min[2] = min(bb_min[2], v[2]) bb_max[0] = max(bb_max[0], v[0]) bb_max[1] = max(bb_max[1], v[1]) bb_max[2] = max(bb_max[2], v[2]) for child in node.children: bb_min, bb_max = get_bounding_box_for_node(child, bb_min, bb_max, transformation) return bb_min, bb_max def try_load_functions(library_path, dll): ''' Try to bind to aiImportFile and aiReleaseImport Arguments --------- library_path: path to current lib dll: ctypes handle to library Returns --------- If unsuccessful: None If successful: Tuple containing (library_path, load from filename function, load from memory function, export to filename function, export to blob function, release function, ctypes handle to assimp library) ''' try: load = dll.aiImportFile release = dll.aiReleaseImport load_mem = dll.aiImportFileFromMemory export = dll.aiExportScene export2blob = dll.aiExportSceneToBlob except AttributeError: #OK, this is a library, but it doesn't have the functions we need return None # library found! from .structs import Scene, ExportDataBlob load.restype = ctypes.POINTER(Scene) load_mem.restype = ctypes.POINTER(Scene) export2blob.restype = ctypes.POINTER(ExportDataBlob) return (library_path, load, load_mem, export, export2blob, release, dll) def search_library(): ''' Loads the assimp library. Throws exception AssimpError if no library_path is found Returns: tuple, (load from filename function, load from memory function, export to filename function, export to blob function, release function, dll) ''' #this path folder = os.path.dirname(__file__) # silence 'DLL not found' message boxes on win try: ctypes.windll.kernel32.SetErrorMode(0x8007) except AttributeError: pass candidates = [] # test every file for curfolder in [folder]+additional_dirs: if os.path.isdir(curfolder): for filename in os.listdir(curfolder): # our minimum requirement for candidates is that # they should contain 'assimp' somewhere in # their name if filename.lower().find('assimp')==-1 : continue is_out=1 for et in ext_whitelist: if et in filename.lower(): is_out=0 break if is_out: continue library_path = os.path.join(curfolder, filename) logger.debug('Try ' + library_path) try: dll = ctypes.cdll.LoadLibrary(library_path) except Exception as e: logger.warning(str(e)) # OK, this except is evil. But different OSs will throw different # errors. So just ignore any errors. continue # see if the functions we need are in the dll loaded = try_load_functions(library_path, dll) if loaded: candidates.append(loaded) if not candidates: # no library found raise AssimpError("assimp library not found") else: # get the newest library_path candidates = map(lambda x: (os.lstat(x[0])[-2], x), candidates) res = max(candidates, key=operator.itemgetter(0))[1] logger.debug('Using assimp library located at ' + res[0]) # XXX: if there are 1000 dll/so files containing 'assimp' # in their name, do we have all of them in our address # space now until gc kicks in? # XXX: take version postfix of the .so on linux? return res[1:] def hasattr_silent(object, name): """ Calls hasttr() with the given parameters and preserves the legacy (pre-Python 3.2) functionality of silently catching exceptions. Returns the result of hasatter() or False if an exception was raised. """ try: if not object: return False return hasattr(object, name) except AttributeError: return False
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/config/extension.toml
[package] version = "1.0.0" title = "MF GDTF converter" description = "Support of GDTF (General Device Type Format) files in USD." authors = ["Moment Factory", "Frederic Lestage", "Antoine Pilote"] readme = "docs/README.md" changelog = "docs/CHANGELOG.md" repository = "https://github.com/MomentFactory/Omniverse-MVR-GDTF-converter" category = "Rendering" keywords = ["MVR", "GDTF","Audiovisual","Lighting","Fixture"] preview_image = "data/preview.png" icon = "data/icon.png" toggleable = false [core] reloadable = false # Load at the start, load all schemas with order -100 (with order -1000 the USD libs are loaded) order = -100 [dependencies] "omni.kit.uiapp" = {} "omni.kit.tool.asset_importer" = {} [[python.module]] name = "mf.ov.gdtf" [python.pipapi] requirements = [ "unidecode" ] use_online_index = true [package.target] kit = ["105.1"] [package.writeTarget] kit = true python = false
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/docs/CHANGELOG.md
# Changelog # [1.0.0] - 2024-01-24 - Added native OpenUSD file format plugin for payload support. - Fixed orientation and scale issues - Some light parameters are now applied to USD light (cone, color temp, intensity) - Deprecated kit 104 and 105.0 - Added Sample files for USDView # [0.4.0] - 2023-10-02 # Added - Sample file # Fixed - Enabled importing from Omniverse - Importing within the same repository as the source file fixed (for filesystem and Omniverse) # Changed - The name of the folder (the one created during importation that contains the files converted to usd) won't include the file extension ("myGDTFFile.gdtf/" will now be "myGDTFFile_gdtf/") - Properly remove the temporary directory created for archive extraction at the end of importation ## [0.3.0] - 2023-09-01 ## Added - Support for node type "Inventory" - Use "Beam" node when present for light xform ## Fixed - Global scale and rotation rework - Fix relative links issue with path and character escaping ## [0.2.0] - 2023-08-17 ### Fixed - Better support for 3ds files ### Changed - When making name valid for usd, add underscore if starts with number ## [0.1.0] - 2023-07-21 ### Added - Initial version of the extension - Support import of GDTF files
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.gdtf/docs/README.md
# GDTF extension for Omniverse [mf.ov.gdtf] Copyright 2023 Moment Factory Studios Inc. An Omniverse extension for [GDTF (General Device Type Format)](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md) files. Support GTDF to OpenUSD conversion as well as References to GDTF files through a native OpenUSD FileFormat Plugin.
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/mf/ov/mvr/converterContext.py
class ConverterContext: usd_reference_path = ""
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/mf/ov/mvr/mvrImporter.py
import logging import numpy as np from typing import List, Tuple import xml.etree.ElementTree as ET from zipfile import ZipFile from pxr import Gf, Usd, UsdGeom from mf.ov.gdtf import gdtfImporter as gdtf from .filepathUtility import Filepath from .mvrUtil import Layer, Fixture from .USDTools import USDTools class MVRImporter: def convert(file: Filepath, mvr_output_dir: str, output_ext: str = ".usd") -> str: # TODO: change output_ext to bool use_usda try: with ZipFile(file.fullpath, 'r') as archive: output_dir = mvr_output_dir + file.filename + "_mvr/" data = archive.read("GeneralSceneDescription.xml") root = ET.fromstring(data) MVRImporter._warn_for_version(root) url: str = MVRImporter.convert_mvr_usd(output_dir, file.filename, output_ext, root, archive) return url except Exception as e: logger = logging.getLogger(__name__) logger.error(f"Failed to parse mvr file at {file.fullpath}. Make sure it is not corrupt. {e}") return None def _warn_for_version(root): v_major = root.attrib["verMajor"] v_minor = root.attrib["verMinor"] if v_major != "1" or v_minor != "5": logger = logging.getLogger(__name__) logger.warn(f"This extension is tested with mvr v1.5, this file version is {v_major}.{v_minor}") def convert_mvr_usd(output_dir: str, filename: str, ext: str, root: ET.Element, archive: ZipFile) -> str: scene: ET.Element = root.find("Scene") layers: List[Layer] = MVRImporter._get_layers(scene) for layer in layers: layer.find_fixtures() stage, url = MVRImporter._make_mvr_stage(output_dir, filename, ext, layers) MVRImporter._convert_gdtf(stage, layers, output_dir, archive, ext) stage.Save() return url def _get_layers(scene: ET.Element) -> List[Layer]: layersNode: ET.Element = scene.find("Layers") layerNodes: ET.Element = layersNode.findall("Layer") layers: List[Layer] = [] for layerNode in layerNodes: layer: Layer = Layer(layerNode) layers.append(layer) return layers def _make_mvr_stage(output_dir: str, filename: str, ext: str, layers: List[Layer]) -> Tuple[Usd.Stage, str]: url: str = output_dir + filename + ext stage: Usd.Stage = USDTools.get_or_create_stage(url) MVRImporter._add_fixture_xform(stage, layers) return stage, url def _add_fixture_xform(stage: Usd.Stage, layers: List[Layer]): rotate_minus90deg_xaxis = Gf.Matrix3d(1, 0, 0, 0, 0, 1, 0, -1, 0) mvr_scale = UsdGeom.LinearUnits.millimeters # MVR dimensions are in millimeters applied_scale: float = USDTools.get_applied_scale(stage, mvr_scale) for layer in layers: if layer.fixtures_len() > 0: scope: UsdGeom.Scope = USDTools.add_scope(stage, layer.get_name_usd()) for fixture in layer.get_fixtures(): xform: UsdGeom.Xform = USDTools.add_fixture_xform(stage, scope, fixture.get_unique_name_usd()) fixture.set_stage_path(xform.GetPrim().GetPath()) np_matrix: np.matrix = USDTools.np_matrix_from_mvr(fixture.get_matrix()) gf_matrix: Gf.Matrix4d = USDTools.gf_matrix_from_mvr(np_matrix, applied_scale) rotation: Gf.Rotation = gf_matrix.ExtractRotation() euler: Gf.Vec3d = rotation.Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) # Z-up to Y-up # TODO: Validate with stage up axis translation = rotate_minus90deg_xaxis * gf_matrix.ExtractTranslation() rotate = rotate_minus90deg_xaxis * euler xform.ClearXformOpOrder() # Prevent error when overwritting xform.AddTranslateOp().Set(translation) xform.AddRotateZYXOp().Set(rotate) # Scale Op is added in _add_gdtf_reference fixture.apply_attributes_to_prim(xform.GetPrim()) stage.Save() def _convert_gdtf(stage: Usd.Stage, layers: List[Layer], mvr_output_dir: str, archive: ZipFile, ext: str): gdtf_spec_uniq: List[str] = MVRImporter._get_gdtf_to_import(layers) gdtf_output_dir = mvr_output_dir for gdtf_spec in gdtf_spec_uniq: gdtf.GDTFImporter.convert_from_mvr(gdtf_spec, gdtf_output_dir, archive) MVRImporter._add_gdtf_reference(layers, stage, ext) def _get_gdtf_to_import(layers: List[Layer]) -> List[str]: result: List[str] = [] for layer in layers: if layer.fixtures_len() > 0: current_fixture_names = [x.get_spec_name() for x in layer.get_fixtures()] current_fixture_names_set = set(current_fixture_names) current_fixture_names_uniq = list(current_fixture_names_set) for current_fixture_name_uniq in current_fixture_names_uniq: result.append(current_fixture_name_uniq) return result def _add_gdtf_reference(layers: List[Layer], stage: Usd.Stage, ext: str): for layer in layers: if layer.fixtures_len() > 0: for fixture in layer.get_fixtures(): spec = fixture.get_spec_name() relative_path = f"./{spec}_gdtf/{spec}{ext}" stage_path = fixture.get_stage_path() USDTools.add_reference(stage, relative_path, stage_path) USDTools.copy_gdtf_scale(stage, stage_path, relative_path)
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/mf/ov/mvr/extension.py
import omni.ext import omni.kit.tool.asset_importer as ai from .converterDelegate import ConverterDelegate class MfOvMvrExtension(omni.ext.IExt): def on_startup(self, _): self._delegate_mvr = ConverterDelegate( "MVR Converter", ["(.*\\.mvr$)"], ["MVR Files (*.mvr)"] ) ai.register_importer(self._delegate_mvr) def on_shutdown(self): ai.remove_importer(self._delegate_mvr) self._delegate_mvr.destroy() self._delegate_mvr = None
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/mf/ov/mvr/__init__.py
import os from pxr import Plug pluginsRoot = os.path.join(os.path.dirname(__file__), '../../../plugin/resources') Plug.Registry().RegisterPlugins(pluginsRoot) from .extension import *
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/mf/ov/mvr/converterDelegate.py
import os import omni.kit.tool.asset_importer as ai from .converterOptionsBuilder import ConverterOptionsBuilder from .converterHelper import ConverterHelper class ConverterDelegate(ai.AbstractImporterDelegate): def __init__(self, name, filters, descriptions): super().__init__() self._hoops_options_builder = ConverterOptionsBuilder() self._hoops_converter = ConverterHelper() self._name = name self._filters = filters self._descriptions = descriptions def destroy(self): if self._hoops_converter: # self._hoops_converter.destroy() self._hoops_converter = None if self._hoops_options_builder: self._hoops_options_builder.destroy() self._hoops_options_builder = None @property def name(self): return self._name @property def filter_regexes(self): return self._filters @property def filter_descriptions(self): return self._descriptions def build_options(self, paths): pass # TODO enable this after the filepicker bugfix: OM-47383 # self._hoops_options_builder.build_pane(paths) async def convert_assets(self, paths): context = self._hoops_options_builder.get_import_options() hoops_context = context.cad_converter_context absolute_paths = [] relative_paths = [] for file_path in paths: if self.is_supported_format(file_path): absolute_paths.append(file_path) filename = os.path.basename(file_path) relative_paths.append(filename) converted_assets = await self._hoops_converter.create_import_task( absolute_paths, context.export_folder, hoops_context ) return converted_assets
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/mf/ov/mvr/converterOptionsBuilder.py
from omni.kit.menu import utils from omni.kit.tool.asset_importer.file_picker import FilePicker from omni.kit.tool.asset_importer.filebrowser import FileBrowserMode, FileBrowserSelectionType import omni.kit.window.content_browser as content from .converterOptions import ConverterOptions class ConverterOptionsBuilder: def __init__(self): self._file_picker = None self._export_content = ConverterOptions() self._folder_button = None self._refresh_default_folder = False self._default_folder = None self._clear() def destroy(self): self._clear() if self._file_picker: self._file_picker.destroy() def _clear(self): self._built = False self._export_folder_field = None if self._folder_button: self._folder_button.set_clicked_fn(None) self._folder_button = None def set_default_target_folder(self, folder: str): self._default_folder = folder self._refresh_default_folder = True def _select_picked_folder_callback(self, paths): if paths: self._export_folder_field.model.set_value(paths[0]) def _cancel_picked_folder_callback(self): pass def _show_file_picker(self): if not self._file_picker: mode = FileBrowserMode.OPEN file_type = FileBrowserSelectionType.DIRECTORY_ONLY filters = [(".*", "All Files (*.*)")] self._file_picker = FilePicker("Select Folder", mode=mode, file_type=file_type, filter_options=filters) self._file_picker.set_file_selected_fn(self._select_picked_folder_callback) self._file_picker.set_cancel_fn(self._cancel_picked_folder_callback) folder = self._export_folder_field.model.get_value_as_string() if utils.is_folder(folder): self._file_picker.show(folder) else: self._file_picker.show(self._get_current_dir_in_content_window()) def _get_current_dir_in_content_window(self): content_window = content.get_content_window() return content_window.get_current_directory() def get_import_options(self): return ConverterOptions()
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/mf/ov/mvr/converterHelper.py
import logging import shutil import tempfile from urllib.parse import unquote import omni.kit.window.content_browser from .filepathUtility import Filepath from .mvrImporter import MVRImporter class ConverterHelper: TMP_ARCHIVE_EXTRACT_DIR = f"{tempfile.gettempdir()}/MF.OV.GDTF/" def _create_import_task(self, absolute_path, export_folder, _): absolute_path_unquoted = unquote(absolute_path) if absolute_path_unquoted.startswith("file:/"): path = absolute_path_unquoted[6:] else: path = absolute_path_unquoted current_nucleus_dir = omni.kit.window.content_browser.get_content_window().get_current_directory() file: Filepath = Filepath(path) output_dir = current_nucleus_dir if export_folder is None else export_folder if export_folder is not None and export_folder != "": output_dir = export_folder # Cannot Unzip directly from Nucleus, must download file beforehand if file.is_nucleus_path(): tmp_path = ConverterHelper.TMP_ARCHIVE_EXTRACT_DIR + file.basename result = omni.client.copy(file.fullpath, tmp_path, omni.client.CopyBehavior.OVERWRITE) if result == omni.client.Result.OK: file = Filepath(tmp_path) else: logger = logging.getLogger(__name__) logger.error(f"Could not import {file.fullpath} directly from Omniverse, try downloading the file instead") return url: str = MVRImporter.convert(file, output_dir) return url async def create_import_task(self, absolute_paths, export_folder, hoops_context): converted_assets = {} for i in range(len(absolute_paths)): converted_assets[absolute_paths[i]] = self._create_import_task(absolute_paths[i], export_folder, hoops_context) shutil.rmtree(ConverterHelper.TMP_ARCHIVE_EXTRACT_DIR) return converted_assets
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/mf/ov/mvr/USDTools.py
import numpy as np from typing import List from unidecode import unidecode from urllib.parse import unquote from pxr import Gf, Tf, Sdf, Usd, UsdGeom class USDTools: def make_name_valid(name: str) -> str: if name[:1].isdigit(): name = "_" + name return Tf.MakeValidIdentifier(unidecode(name)) def get_or_create_stage(url: str) -> Usd.Stage: try: # TODO: Better way to check if stage exists? return Usd.Stage.Open(url) except: stage = Usd.Stage.CreateNew(url) UsdGeom.SetStageMetersPerUnit(stage, UsdGeom.LinearUnits.centimeters) # TODO get user defaults UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y) # TODO get user defaults default_prim = stage.DefinePrim("/World", "Xform") stage.SetDefaultPrim(default_prim) stage.Save() return stage def add_scope(stage: Usd.Stage, name: str) -> UsdGeom.Scope: default_prim_path: Sdf.Path = stage.GetDefaultPrim().GetPrimPath() scope_path: Sdf.Path = default_prim_path.AppendPath(name) scope: UsdGeom.Scope = UsdGeom.Scope.Define(stage, scope_path) return scope def add_fixture_xform(stage: Usd.Stage, scope: UsdGeom.Scope, name: str) -> UsdGeom.Xform: path = scope.GetPath().AppendPath(name) xform: UsdGeom.Xform = UsdGeom.Xform.Define(stage, path) return xform def get_applied_scale(stage: Usd.Stage, scale_factor: float) -> float: stage_scale = UsdGeom.GetStageMetersPerUnit(stage) return scale_factor / stage_scale def np_matrix_from_mvr(value: str) -> np.matrix: # MVR Matrix is: 4x3, Right-handed, Z-up, 1 Distance Unit equals 1mm # expect form like "<Matrix>{x,y,z}{x,y,z}{x,y,z}{x,y,z}</Matrix>" where "x","y","z" is similar to 1.000000 # make source compatible with np.matrix constructor: "x y z; x y z; x y z; x y z" value_alt = value[1:] # Removes "{" prefix value_alt = value_alt[:-1] # Removes "}" suffix value_alt = value_alt.replace("}{", "; ") value_alt = value_alt.replace(",", " ") np_matrix: np.matrix = np.matrix(value_alt) return np_matrix def gf_matrix_from_mvr(np_matrix: np.matrix, scale: float) -> Gf.Matrix4d: # Column major matrix gf_matrix = Gf.Matrix4d( np_matrix.item((0, 0)), np_matrix.item((0, 1)), np_matrix.item((0, 2)), 0, np_matrix.item((1, 0)), np_matrix.item((1, 1)), np_matrix.item((1, 2)), 0, np_matrix.item((2, 0)), np_matrix.item((2, 1)), np_matrix.item((2, 2)), 0, np_matrix.item((3, 0)) * scale, np_matrix.item((3, 1)) * scale, np_matrix.item((3, 2)) * scale, 1 ) return gf_matrix def set_fixture_attribute(prim: Usd.Prim, attribute_name: str, attribute_type: Sdf.ValueTypeNames, attribute_value): prim.CreateAttribute(f"mf:mvr:{attribute_name}", attribute_type).Set(attribute_value) def add_reference(stage: Usd.Stage, ref_path_relative: str, stage_path: str): xform_ref: UsdGeom.Xform = stage.GetPrimAtPath(stage_path) path_unquoted = unquote(ref_path_relative) references: Usd.References = xform_ref.GetReferences() references.AddReference(path_unquoted) stage.Save() def copy_gdtf_scale(mvr_stage: Usd.Stage, stage_prim_path: str, relative_path: str): # Copy a reference default prim scale op value to a referencing xform in an other stage curr_root_layer = mvr_stage.GetRootLayer() curr_stage_url: str = curr_root_layer.realPath curr_stage_url_formatted: str = curr_stage_url.replace('\\', '/') curr_stage_dir_index: str = curr_stage_url_formatted.rindex("/") curr_stage_dir = curr_stage_url_formatted[:curr_stage_dir_index] mvr_xform_target = UsdGeom.Xform(mvr_stage.GetPrimAtPath(stage_prim_path)) gdtf_stage_filename: str = relative_path[1:] gdtf_stage_path: str = curr_stage_dir + gdtf_stage_filename gdtf_stage: Usd.Stage = Usd.Stage.Open(gdtf_stage_path) gdtf_default_prim = UsdGeom.Xform(gdtf_stage.GetDefaultPrim()) stage_scale = UsdGeom.GetStageMetersPerUnit(mvr_stage) scale_factor = 1 / stage_scale scale_value = Gf.Vec3d(scale_factor, scale_factor, scale_factor) xform_ordered_ops: List[UsdGeom.XformOp] = gdtf_default_prim.GetOrderedXformOps() for xform_op in xform_ordered_ops: if xform_op.GetOpType() == UsdGeom.XformOp.TypeScale: scale_value = xform_op.Get() mvr_xform_target.AddScaleOp().Set(scale_value) mvr_stage.Save()
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/mf/ov/mvr/converterOptions.py
from .converterContext import ConverterContext class ConverterOptions: def __init__(self): self.cad_converter_context = ConverterContext() self.export_folder: str = None
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/mf/ov/mvr/mvrUtil.py
from typing import List import xml.etree.ElementTree as ET from pxr import Usd, Sdf from .USDTools import USDTools class Fixture: def __init__(self, node: ET.Element): self._root = node self._name = node.attrib["name"] self._uuid = node.attrib["uuid"] self._matrix = self._get_value_text_if_exists("Matrix") self._gdtf_spec = self._get_value_text_if_exists("GDTFSpec") self._gdtf_mode = self._get_value_text_if_exists("GDTFMode") self._custom_commands = self._get_custom_commands_values() self._classing = self._get_value_text_if_exists("Classing") self._addresses = self._get_addresses_values() self._fixture_id = self._get_value_int_if_exists("fixtureID") self._unit_number = self._get_value_int_if_exists("UnitNumber") self._fixture_type_id = self._get_value_int_if_exists("FixtureTypeId") self._custom_id = self._get_value_int_if_exists("CustomId") self._cie_color = self._get_color_values() self._cast_shadow = self._get_value_bool_if_exists("CastShadow") def get_unique_name_usd(self) -> str: return USDTools.make_name_valid(self._name + "_" + self._uuid) def get_matrix(self) -> str: return self._matrix def set_stage_path(self, path: str): self._stage_path = path def get_stage_path(self) -> str: return self._stage_path def get_spec_name(self) -> str: spec_name = self._gdtf_spec if self._gdtf_spec[-5:] == ".gdtf": spec_name = self._gdtf_spec[:-5] return spec_name def _get_value_text_if_exists(self, name: str) -> str: node = self._get_child_node(name) if node is not None: text = node.text if text is not None: return node.text return None def _get_value_int_if_exists(self, name: str) -> int: txt = self._get_value_text_if_exists(name) if txt is None: return None return int(txt) def _get_value_bool_if_exists(self, name: str) -> bool: txt = self._get_value_text_if_exists(name) if txt is None: return None return bool(txt) def _get_child_node(self, node: str): return self._root.find(node) def _get_custom_commands_values(self) -> List[str]: values: List[str] = [] node = self._get_child_node("CustomCommands") if node is not None: subnodes = node.findall("CustomCommand") if subnodes is not None and len(subnodes) > 0: values = [x.text for x in subnodes] return values def _get_addresses_values(self) -> List[str]: values: List[str] = [] node = self._get_child_node("Addresses") if node is not None: subnodes = node.findall("Address") if subnodes is not None and len(subnodes): values = [int(x.text) for x in subnodes] return values def _get_color_values(self) -> List[float]: colors: List[float] = [] node = self._get_child_node("Color") if node is not None: colors = [float(x) for x in node.text.split(",")] return colors def apply_attributes_to_prim(self, prim: Usd.Prim): self._set_attribute_text_if_valid(prim, "name", self._name) self._set_attribute_text_if_valid(prim, "uuid", self._uuid) self._set_attribute_text_if_valid(prim, "GDTFSpec", self._gdtf_spec) self._set_attribute_text_if_valid(prim, "GDTFMode", self._gdtf_mode) self._set_attribute_textarray_if_valid(prim, "CustomCommands", self._custom_commands) self._set_attribute_text_if_valid(prim, "Classing", self._classing) self._set_attribute_intarray_if_valid(prim, "Addresses", self._addresses) self._set_attribute_int_if_valid(prim, "FixtureID", self._fixture_id) self._set_attribute_int_if_valid(prim, "UnitNumber", self._unit_number) self._set_attribute_int_if_valid(prim, "FixtureTypeId", self._fixture_type_id) self._set_attribute_int_if_valid(prim, "CustomId", self._custom_id) self._set_attribute_floatarray_if_valid(prim, "CIEColor", self._cie_color) self._set_attribute_bool_if_value(prim, "CastShadow", self._cast_shadow) def _set_attribute_text_if_valid(self, prim: Usd.Prim, name: str, value: str): if value is not None: USDTools.set_fixture_attribute(prim, name, Sdf.ValueTypeNames.String, value) def _set_attribute_int_if_valid(self, prim: Usd.Prim, name: str, value: int): if value is not None: USDTools.set_fixture_attribute(prim, name, Sdf.ValueTypeNames.Int, value) def _set_attribute_bool_if_value(self, prim: Usd.Prim, name: str, value: bool): if value is not None: USDTools.set_fixture_attribute(prim, name, Sdf.ValueTypeNames.Bool, value) def _set_attribute_textarray_if_valid(self, prim: Usd.Prim, name: str, value: List[str]): if value is not None and len(value) > 0: USDTools.set_fixture_attribute(prim, name, Sdf.ValueTypeNames.StringArray, value) def _set_attribute_intarray_if_valid(self, prim: Usd.Prim, name: str, value: List[int]): if value is not None and len(value) > 0: USDTools.set_fixture_attribute(prim, name, Sdf.ValueTypeNames.IntArray, value) def _set_attribute_floatarray_if_valid(self, prim: Usd.Prim, name: str, value: List[float]): if value is not None and len(value) > 0: USDTools.set_fixture_attribute(prim, name, Sdf.ValueTypeNames.FloatArray, value) class Layer: def __init__(self, node: ET.Element): self._name = node.attrib["name"] self._uuid = node.attrib["uuid"] self._node = node self._fixtures = [] def get_name_usd(self) -> str: return USDTools.make_name_valid(self._name) def find_fixtures(self): childlist = self._node.find("ChildList") fixtures = childlist.findall("Fixture") self._fixtures = [Fixture(x) for x in fixtures] def fixtures_len(self) -> int: return len(self._fixtures) def get_fixtures(self) -> List[Fixture]: return self._fixtures
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/mf/ov/mvr/filepathUtility.py
import os class Filepath: def __init__(self, filepath: str): self._is_none = filepath == "" self.fullpath = filepath self.directory = os.path.dirname(filepath) + "/" self.basename = os.path.basename(filepath) self.filename, self.ext = os.path.splitext(self.basename) def is_nucleus_path(self) -> bool: # TODO: Replace with omni utility method return self.directory[:12] == "omniverse://" def get_relative_from(self, other) -> str: if self._is_none: return other.fullpath else: return "./" + other.fullpath[len(self.directory):]
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/config/extension.toml
[package] version = "1.0.0" title = "MF MVR converter" description = "Support of MVR (My Virtual Rig) files in USD." authors = ["Moment Factory","Frederic Lestage", "Antoine Pilote"] readme = "docs/README.md" changelog = "docs/CHANGELOG.md" repository = "https://github.com/MomentFactory/Omniverse-MVR-GDTF-converter" category = "Rendering" keywords = ["MVR", "GDTF","Audiovisual","Lighting","Fixture"] preview_image = "data/preview.png" icon = "data/icon.png" toggleable = false [core] reloadable = false # Load at the start, load all schemas with order -100 (with order -1000 the USD libs are loaded) order = -100 [dependencies] "mf.ov.gdtf" = {} "omni.kit.uiapp" = {} "omni.kit.tool.asset_importer" = {} [[python.module]] name = "mf.ov.mvr" [python.pipapi] requirements = [ "unidecode" ] use_online_index = true [package.target] kit = ["105.1"] [package.writeTarget] kit = true python = false
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/docs/CHANGELOG.md
# Changelog # [1.0.0] - 2024-01-24 - Added native OpenUSD file format plugin for payload support. - Fixed orientation and scale issues - Some light parameters are now applied to USD light (cone, color temp, intensity) - Deprecated kit 104 and 105.0 - Added Sample files for USDView # [0.4.0] - 2023-10-02 # Added - Sample file # Fixed - Enabled importing from Omniverse - Importing within the same repository as the source file fixed (for filesystem and Omniverse) # Changed - The name of the folder (the one created during importation that contains the files converted to usd) won't include the file extension ("myMVRFile.mvr/" will now be "myMVRFile_mvr/") - GDTF attributes populated by MVR now better reflect naming convention of the specs ("fixture_id" becomes "FixtureID") - Properly remove the temporary directory created for archive extraction at the end of importation # [0.3.0] - 2023-09-01 ## Fixed - Global scale rework - Fix relative link issue with character escaping # [0.2.0] - 2023-08-17 ### Added - Support for multiple layers - Layers reflected as Scope in usd ### Changed - When making name valid for usd, add underscore if starts with number # [0.1.0] - 2023-07-21 ### Added - Initial version of the extension - Support import of MVR files
MomentFactory/Omniverse-MVR-GDTF-converter/exts/mf.ov.mvr/docs/README.md
# MVR extension for Omniverse [mf.ov.mvr] Copyright 2023 Moment Factory Studios Inc. An Omniverse extension for MVR [MVR (My Virtual Rig)](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md) files. Support MVR to OpenUSD conversion as well as References to MVR files through a native USD FileFormat Plugin. Requires the mf.ov.gdtf extension to fully work. MVR (My Virtual Rig) is a scene format that can describe an complete rig of lights, using GDTF assets at its core while adding capabilities to define groups, layers, DMX address and more to allow lighting designer to build virtual replicas of their lighting rigs and enforce a single file format from show design to previz to operation.
MomentFactory/Omniverse-MVR-GDTF-converter/resources/scene.usda
#usda 1.0 ( defaultPrim = "World" metersPerUnit = 0.01 upAxis = "Y" ) def Xform "World" { def "mvrPayload" ( payload = @./test.gdtf@ ) { } }
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/PACKAGE-INFO.yaml
Package : omniverse-lidar-live-synthetic-data License Type : Modified Apache 2.0
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/repo.bat
@echo off call "%~dp0tools\packman\python.bat" %~dp0tools\repoman\repoman.py %* if %errorlevel% neq 0 ( goto Error ) :Success exit /b 0 :Error exit /b %errorlevel%
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/build.bat
@echo off call "%~dp0repo" build %*
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/build.sh
#!/bin/bash set -e SCRIPT_DIR=$(dirname ${BASH_SOURCE}) source "$SCRIPT_DIR/repo.sh" build $@ || exit $?
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/VERSION.md
105.1
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/repo.sh
#!/bin/bash set -e SCRIPT_DIR=$(dirname ${BASH_SOURCE}) cd "$SCRIPT_DIR" exec "tools/packman/python.sh" tools/repoman/repoman.py $@
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/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"] # Repository Name name = "omniverse-lidar-live-synthetic-data" [repo_build] msbuild.vs_version = "vs2019" post_build.commands = [] [repo_docs] name = "MF Lidar live synthetic data" project = "omniverse-lidar-live-synthetic-data" api_output_directory = "api" use_fast_doxygen_conversion=false sphinx_version = "4.5.0.2-py3.10-${platform}" sphinx_exclude_patterns = [ "_build", "tools", "VERSION.md", "source/extensions/*/docs/Overview.md", "source/extensions/*/docs/CHANGELOG.md", ] [repo_docs.kit] extensions = [ "mf.ov.lidar_live_synth" ] [repo_package.packages."platform:windows-x86_64".docs] windows_max_path_length = 0
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/premake5.lua
-- Shared build scripts from repo_build package. repo_build = require("omni/repo/build") -- Repo root root = repo_build.get_abs_path(".") -- Set the desired MSVC, WINSDK, and MSBUILD versions before executing the kit template premake configuration. MSVC_VERSION = "14.27.29110" WINSDK_VERSION = "10.0.18362.0" MSBUILD_VERSION = "Current" -- Execute the kit template premake configuration, which creates the solution, finds extensions, etc. dofile("_repo/deps/repo_kit_tools/kit-template/premake5.lua")
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/README.md
# MF Lidar live synthetic data [mf.ov.lidar_live_synth] Adds an Action Graph Node ("Generic/Beam to Ouster UDP") to send Isaac beam data via the Ouster(tm) UDP procotol. This allows any third party software implementing Ouster(tm) lidars to be connected to simulated sensors instead of physical sensors. Developped for kit 105.1 and currently working only in Isaac Sim. This extensions provides pre-built binaries for Windows and Linux x86_64. You may want to compile from the [source code](https://github.com/MomentFactory/Omniverse-Lidar-Live-Synthetic-Data) ## Requirements - kit 105 based - Isaac Sim > 2023.1.0 - Linux or Windows platforms ### Supported Lidars Currently, only Ouster™ sensors are supported. The Lidar must have 16, 32, 64 or 128 rows to be supported by the procotol. Lidar FOVs and resolutions are not transmitted in the protocol and therefore should match those of an actual Ouster(tm) model (22.5, 45 or 90 degrees FOV) for an accurate reconstruction by the receiving software. JSON config files that describe the angles of the beams for an external application are included in the 'data' folder (example : [OusterJsonConfigOmniverse-OS0-16.json](source/extensions/mf.ov.lidar_live_synth/data/OusterJsonConfigOmniverse-OS0-16.json)). These files can be used in Cirrus as the Ouster(tm) Json Config file to properly recronstruct the data with the correct beam angles. OS0 are 90 degrees FOV, OS1 are 45 and OS2 are 22.5. ## Build ### Windows - Run `./build.bat` ### Linux - Install Docker - Run `./build.sh` ## Using the extension Requires Isaac Sim as well as a third party software that can receive and parse Ouster Lidar sensors frames. You can use the [isaac_lidar_sample_moving_cube.usd](source/extensions/mf.ov.lidar_live_synth/samples/isaac_lidar_sample_moving_cube.usd), or [isaac_lidar_ouster_sample.usd](source/extensions/mf.ov.lidar_live_synth/samples//isaac_lidar_ouster_sample.usd), or create your own following the instructions below. ### Enable the extension In Isaac Sim : - Windows > Extensions. - Switch to THIRD PARY tab. - Install and enable the extension. ### In Isaac Sim: 1. Open or create a scene - Meshes requires a Rigidbody to intercept Lidar raycast - Right-click a mesh, then select `Add / Physics / Rigid Body` 2. Add a Lidar to the scene if not present - `Create / Isaac / Sensors / Lidar / Generic` - Unfold Raw USD Properties - Check `drawPoints` and/or `drawLines` if you want to see the point cloud - Check the `enabled` property - Use `horizontalFov`, `horizontalResolution`. `maxRange`, `minRange`, `verticalFov`, and `verticalResolution` to define the Lidar raycast zone - set `rotationRate` to `0` if you want continuous raycast 3. Create an action graph - Right-click the Stage, then select `Create / Visual Scripting / Action Graph` - Right-click the Action Graph then select "Open Graph" - Add a `Event / On Playback Tick` node - Add a `Isaac Range Sensor / Isaac Read Lidar Beam Node` - Connect the "Tick" output to the "Exec In" input - Add a `Generic / Beam to Ouster UDP` node - Connect the "Exec Out" output to the "Exec In" input - Connect the outputs of `Isaac Read Lidar Beam Node` to the matching `Beam to Ouster UDP` inputs - `Azimuth Range` - `Horizontal Resolution` - `Linear Depth Data` - `Num Cols` - `Num Rows` 4. Press the play icon (SPACE) to begin the simulation #### Beam to Ouster UDP fields - `IP Address` (string): The IP address to send the data to. - `Port` (int): The port to send the data to. - `Broadcast` (bool): Check to indicate the IP Address is a broadcast address. ## Developer notes As the extension is written in C++ for performance reasons, developers need to build it before using it. Most of it works in the same way as the official [Omniverse C++ examples](https://github.com/NVIDIA-Omniverse/kit-extension-template-cpp). The first step is to run the `build.bat` file at the root of the repo. It will generate the actual extension files usable by Omniverse, as well as the Visual Studio files. It is recommended to work in Visual Studio (2019 and above) for C++, although VSCode should also work. The `build.bat` script generates the VS2019 `.sln` files in `_compiler\vs2019\kit-extension-template-cpp.sln` . It should work as-is. Do not upgrade the compiler and Windows SDK versions if asked to do so, and install the correct Windows SDK for the VS Installer if it is missing on your machine. Unlike the samples, we do not recommend running the project by launching it via Visual Studio, since the extension is made specifically for Isaac Sim, and Visual Studio doesnt launch it within an Isaac Sim environment. It is recommended to run Isaac and attach the VS debugger to it by going to Debug -> Attach to Process and selecting the kit.exe coresponding to Isaac. Make sure to attach to Native Code. If you have the "Python - Profiling" extension, it might want to try to attach to Python code instead. One thing to note is that the symbols for the extension will only be loaded IF the extension is enabled after attaching. If the extension is already enabled, disabling then enabling it will also work. Also, to update the extension in Isaac after doing some changes and building, it needs to be disabled and enabled again (The extension willl probably fail to build if it is in use as the dll cannot be overwritten anyways). To add the extension to Isaac, simply add the built plugin folder (`c:/git/omniverse/omniverse-lidar-synthetic-data/_build/windows-x86_64/release/exts` or `c:/git/omniverse/omniverse-lidar-synthetic-data/_build/windows-x86_64/debug/exts` for a debug build) to the extension manager paths. ## Resources - Inspired by : [NVIDIA's kit-extension-template-cpp](https://github.com/NVIDIA-Omniverse/kit-extension-template-cpp)
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/index.rst
MF Lidar live synthetic data ########################## .. mdinclude:: README.md Example Extensions ################## * `mf.ov.lidar_live_synth <../../mf.ov.lidar_live_synth/1.0.0/index.html>`_
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/deps/repo-deps.packman.xml
<project toolsVersion="5.0"> <dependency name="repo_build" linkPath="../_repo/deps/repo_build"> <package name="repo_build" version="0.44.6" checksum="11858f3d45b15d83f0279fa96e2813232bfd65755d0cf45861f5fdd28a5a39b6" /> </dependency> <dependency name="repo_changelog" linkPath="../_repo/deps/repo_changelog"> <package name="repo_changelog" version="0.3.2" checksum="fbe4bc4257d5aec1c964f2616257043095a9dfac8a10e027ac96aa89340f1423" /> </dependency> <dependency name="repo_docs" linkPath="../_repo/deps/repo_docs"> <package name="repo_docs" version="0.37.3" checksum="78bd6488c1cd7295ab6728d9cd0b79fac3684598bcaebefad710fc79e3a7b8ea" /> </dependency> <dependency name="repo_kit_tools" linkPath="../_repo/deps/repo_kit_tools"> <package name="repo_kit_tools" version="0.11.8" checksum="8d6e1ade8b75b40f880505ba62308958d87a88e52db6a3b932be3da387a8a571" /> </dependency> <dependency name="repo_licensing" linkPath="../_repo/deps/repo_licensing"> <package name="repo_licensing" version="1.12.0" checksum="2fa002302a776f1104896f39c8822a8c9516ef6c0ce251548b2b915979666b9d" /> </dependency> <dependency name="repo_man" linkPath="../_repo/deps/repo_man"> <package name="repo_man" version="1.36.1" checksum="aba22f72ec46b7d2761c5fe2eee397bcb6958dda9b4a8aaca947eb69b97f6089" /> </dependency> <dependency name="repo_package" linkPath="../_repo/deps/repo_package"> <package name="repo_package" version="5.8.8" checksum="b8279d841f7201b44d9b232b934960d9a302367be59ee64e976345854b741fec" /> </dependency> <dependency name="repo_format" linkPath="../_repo/deps/repo_format"> <package name="repo_format" version="2.7.0" checksum="8083eb423043de585dfdfd3cf7637d7e50ba2a297abb8bebcaef4307b80503bb" /> </dependency> <dependency name="repo_source" linkPath="../_repo/deps/repo_source"> <package name="repo_source" version="0.4.2" checksum="05776a984978d84611cb8becd5ed9c26137434e0abff6e3076f36ab354313423" /> </dependency> <dependency name="repo_test" linkPath="../_repo/deps/repo_test"> <package name="repo_test" version="2.9.3" checksum="1903a2a1c998ca4adc87bc20520e91a9af21bf18a6a48a8e05467fe29d674931" /> </dependency> </project>
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/deps/kit-sdk.packman.xml
<project toolsVersion="5.0"> <!-- We always depend on the release kit-sdk package, regardless of config --> <dependency name="kit_sdk_${config}" linkPath="../_build/${platform}/${config}/kit" tags="${config} non-redist"> <package name="kit-sdk" version="105.1+release.127680.dd92291b.tc.windows-x86_64.release" platforms="windows-x86_64" checksum="78b6054c730a44b97e6551eae9e17f45384621f244d4babde5264a1d6df3038f" /> <package name="kit-sdk" version="105.1+release.127680.dd92291b.tc.linux-x86_64.release" platforms="linux-x86_64" checksum="2f8357eda2de9232c0b4cb345eb6c4d3c3aa8c4c9685ed45d4bfe749af57b0b8" /> </dependency> </project>
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/deps/host-deps.packman.xml
<project toolsVersion="5.0"> <dependency name="premake" linkPath="../_build/host-deps/premake"> <package name="premake" version="5.0.0-alpha15.dev+pipeline3388156.1f299ea4-windows-x86_64" checksum="b1e5dcef9acf47b0c86a4630afa4fadc9485b878e25e4321ac5afbb826bbdf93" platforms="windows-x86_64" /> <package name="premake" version="5.0.0-alpha15.dev+pipeline3388156.1f299ea4-linux-x86_64" checksum="ae15e63cf6d53571fa3bdfa33ddcec8a3be90675cdd155590a26bcd75d04d73f" platforms="linux-x86_64" /> </dependency> <dependency name="msvc" linkPath="../_build/host-deps/msvc"> <package name="msvc" version="2019-16.7.6-license" platforms="windows-x86_64" checksum="0e37c0f29899fe10dcbef6756bcd69c2c4422a3ca1101206df272dc3d295b92d" /> </dependency> <dependency name="winsdk" linkPath="../_build/host-deps/winsdk"> <package name="winsdk" version="10.0.18362.0-license" platforms="windows-x86_64" checksum="2db7aeb2278b79c6c9fbca8f5d72b16090b3554f52b1f3e5f1c8739c5132a3d6" /> </dependency> </project>
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/deps/kit-sdk-deps.packman.xml
<project toolsVersion="5.0"> <!-- Import dependencies from Kit SDK to ensure we're using the same versions. --> <import path="../_build/${platform}/${config}/kit/dev/all-deps.packman.xml"> <filter include="carb_sdk_plugins"/> <filter include="cuda"/> <filter include="doctest"/> <filter include="pybind11"/> <filter include="python"/> </import> <!-- Override the link paths to point to the correct locations. --> <dependency name="carb_sdk_plugins" linkPath="../_build/target-deps/carb_sdk_plugins"/> <dependency name="cuda" linkPath="../_build/target-deps/cuda"/> <dependency name="doctest" linkPath="../_build/target-deps/doctest"/> <dependency name="pybind11" linkPath="../_build/target-deps/pybind11"/> <dependency name="python" linkPath="../_build/target-deps/python"/> </project>
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/deps/ext-deps.packman.xml
<project toolsVersion="5.0"> <!-- Import dependencies from Kit SDK to ensure we're using the same versions. --> <import path="../_build/${platform}/${config}/kit/dev/all-deps.packman.xml"> <filter include="boost_preprocessor"/> <filter include="imgui"/> <filter include="nv_usd_py310_release"/> </import> <!-- Override the link paths to point to the correct locations. --> <dependency name="boost_preprocessor" linkPath="../_build/target-deps/boost-preprocessor"/> <dependency name="imgui" linkPath="../_build/target-deps/imgui"/> <dependency name="nv_usd_py310_release" linkPath="../_build/target-deps/nv_usd/release"/> <!-- Because we always use the release kit-sdk we have to explicitly refer to the debug usd package. --> <dependency name="nv_usd_py310_debug" linkPath="../_build/target-deps/nv_usd/debug"> <package name="nv-usd" version="22.11.nv.0.2.1058.7d2f59ad-win64_py310_debug-dev_omniverse" platforms="windows-x86_64" checksum="02f7c3477830eb17699cc91774438edd8651f3ec0031582c67093ae3276f360b" /> <package name="nv-usd" version="22.11.nv.0.2.1058.7d2f59ad-linux64_py310-centos_debug-dev_omniverse" platforms="linux-x86_64" checksum="2ac18e0470d05b251a2f36691a1dc1b28da340da92b19175d890addb762adb0f"/> <package name="nv-usd" version="22.11.nv.0.2.1058.7d2f59ad-linux-aarch64_py310_debug-dev_omniverse" platforms="linux-aarch64" checksum="904ede636008fb011b5f3d66c1a7c2969dfba291dcf1a227fa7503a714f1f18d" /> </dependency> </project>
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/repoman/repoman.py
import os import sys import io import contextlib import packmanapi REPO_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..") REPO_DEPS_FILE = os.path.join(REPO_ROOT, "deps/repo-deps.packman.xml") def bootstrap(): """ Bootstrap all omni.repo modules. Pull with packman from repo.packman.xml and add them all to python sys.path to enable importing. """ #with contextlib.redirect_stdout(io.StringIO()): deps = packmanapi.pull(REPO_DEPS_FILE) for dep_path in deps.values(): if dep_path not in sys.path: sys.path.append(dep_path) if __name__ == "__main__": bootstrap() import omni.repo.man omni.repo.man.main(REPO_ROOT)
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/packman/python.sh
#!/bin/bash # Copyright 2019-2020 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -e PACKMAN_CMD="$(dirname "${BASH_SOURCE}")/packman" if [ ! -f "$PACKMAN_CMD" ]; then PACKMAN_CMD="${PACKMAN_CMD}.sh" fi source "$PACKMAN_CMD" init export PYTHONPATH="${PM_MODULE_DIR}:${PYTHONPATH}" if [ -z "${PYTHONNOUSERSITE:-}" ]; then export PYTHONNOUSERSITE=1 fi # For performance, default to unbuffered; however, allow overriding via # PYTHONUNBUFFERED=0 since PYTHONUNBUFFERED on windows can truncate output # when printing long strings if [ -z "${PYTHONUNBUFFERED:-}" ]; then export PYTHONUNBUFFERED=1 fi # workaround for our python not shipping with certs if [[ -z ${SSL_CERT_DIR:-} ]]; then export SSL_CERT_DIR=/etc/ssl/certs/ fi "${PM_PYTHON}" "$@"
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/packman/python.bat
:: Copyright 2019-2020 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: https://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. @echo off setlocal enableextensions call "%~dp0\packman" init set "PYTHONPATH=%PM_MODULE_DIR%;%PYTHONPATH%" if not defined PYTHONNOUSERSITE ( set PYTHONNOUSERSITE=1 ) REM For performance, default to unbuffered; however, allow overriding via REM PYTHONUNBUFFERED=0 since PYTHONUNBUFFERED on windows can truncate output REM when printing long strings if not defined PYTHONUNBUFFERED ( set PYTHONUNBUFFERED=1 ) "%PM_PYTHON%" %*
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/packman/packmanconf.py
# Use this file to bootstrap packman into your Python environment (3.7.x). Simply # add the path by doing sys.insert to where packmanconf.py is located and then execute: # # >>> import packmanconf # >>> packmanconf.init() # # It will use the configured remote(s) and the version of packman in the same folder, # giving you full access to the packman API via the following module # # >> import packmanapi # >> dir(packmanapi) import os import platform import sys def init(): """Call this function to initialize the packman configuration. Calls to the packman API will work after successfully calling this function. Note: This function only needs to be called once during the execution of your program. Calling it repeatedly is harmless but wasteful. Compatibility with your Python interpreter is checked and upon failure the function will report what is required. Example: >>> import packmanconf >>> packmanconf.init() >>> import packmanapi >>> packmanapi.set_verbosity_level(packmanapi.VERBOSITY_HIGH) """ major = sys.version_info[0] minor = sys.version_info[1] if major != 3 or minor != 10: raise RuntimeError( f"This version of packman requires Python 3.10.x, but {major}.{minor} was provided" ) conf_dir = os.path.dirname(os.path.abspath(__file__)) os.environ["PM_INSTALL_PATH"] = conf_dir packages_root = get_packages_root(conf_dir) version = get_version(conf_dir) module_dir = get_module_dir(conf_dir, packages_root, version) sys.path.insert(1, module_dir) def get_packages_root(conf_dir: str) -> str: root = os.getenv("PM_PACKAGES_ROOT") if not root: platform_name = platform.system() if platform_name == "Windows": drive, _ = os.path.splitdrive(conf_dir) root = os.path.join(drive, "packman-repo") elif platform_name == "Darwin": # macOS root = os.path.join( os.path.expanduser("~"), "/Library/Application Support/packman-cache" ) elif platform_name == "Linux": try: cache_root = os.environ["XDG_HOME_CACHE"] except KeyError: cache_root = os.path.join(os.path.expanduser("~"), ".cache") return os.path.join(cache_root, "packman") else: raise RuntimeError(f"Unsupported platform '{platform_name}'") # make sure the path exists: os.makedirs(root, exist_ok=True) return root def get_module_dir(conf_dir, packages_root: str, version: str) -> str: module_dir = os.path.join(packages_root, "packman-common", version) if not os.path.exists(module_dir): import tempfile tf = tempfile.NamedTemporaryFile(delete=False) target_name = tf.name tf.close() url = f"https://bootstrap.packman.nvidia.com/packman-common@{version}.zip" print(f"Downloading '{url}' ...") import urllib.request urllib.request.urlretrieve(url, target_name) from importlib.machinery import SourceFileLoader # import module from path provided script_path = os.path.join(conf_dir, "bootstrap", "install_package.py") ip = SourceFileLoader("install_package", script_path).load_module() print("Unpacking ...") ip.install_package(target_name, module_dir) os.unlink(tf.name) return module_dir def get_version(conf_dir: str): path = os.path.join(conf_dir, "packman") if not os.path.exists(path): # in dev repo fallback path += ".sh" with open(path, "rt", encoding="utf8") as launch_file: for line in launch_file.readlines(): if line.startswith("PM_PACKMAN_VERSION"): _, value = line.split("=") return value.strip() raise RuntimeError(f"Unable to find 'PM_PACKMAN_VERSION' in '{path}'")
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/packman/packman.cmd
:: RUN_PM_MODULE must always be at the same spot for packman update to work (batch reloads file during update!) :: [xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx] :: Reset errorlevel status (don't inherit from caller) @call :ECHO_AND_RESET_ERROR :: You can remove this section if you do your own manual configuration of the dev machines call :CONFIGURE if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Everything below is mandatory if not defined PM_PYTHON goto :PYTHON_ENV_ERROR if not defined PM_MODULE goto :MODULE_ENV_ERROR set PM_VAR_PATH_ARG= if "%1"=="pull" goto :SET_VAR_PATH if "%1"=="install" goto :SET_VAR_PATH :RUN_PM_MODULE "%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" %* %PM_VAR_PATH_ARG% if %errorlevel% neq 0 ( exit /b %errorlevel% ) :: Marshall environment variables into the current environment if they have been generated and remove temporary file if exist "%PM_VAR_PATH%" ( for /F "usebackq tokens=*" %%A in ("%PM_VAR_PATH%") do set "%%A" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) if exist "%PM_VAR_PATH%" ( del /F "%PM_VAR_PATH%" ) if %errorlevel% neq 0 ( goto :VAR_ERROR ) set PM_VAR_PATH= goto :eof :: Subroutines below :PYTHON_ENV_ERROR @echo User environment variable PM_PYTHON is not set! Please configure machine for packman or call configure.bat. exit /b 1 :MODULE_ENV_ERROR @echo User environment variable PM_MODULE is not set! Please configure machine for packman or call configure.bat. exit /b 1 :VAR_ERROR @echo Error while processing and setting environment variables! exit /b 1 :: pad [xxxx] :ECHO_AND_RESET_ERROR @echo off if /I "%PM_VERBOSITY%"=="debug" ( @echo on ) exit /b 0 :SET_VAR_PATH :: Generate temporary path for variable file for /f "delims=" %%a in ('%PM_PYTHON% -S -s -u -E -c "import tempfile;file = tempfile.NamedTemporaryFile(mode='w+t', delete=False);print(file.name)"') do (set PM_VAR_PATH=%%a) set PM_VAR_PATH_ARG=--var-path="%PM_VAR_PATH%" goto :RUN_PM_MODULE :CONFIGURE :: Must capture and set code page to work around issue #279, powershell invocation mutates console font :: This issue only happens in Windows CMD shell when using 65001 code page. Some Git Bash implementations :: don't support chcp so this workaround is a bit convoluted. :: Test for chcp: chcp > nul 2>&1 if %errorlevel% equ 0 ( for /f "tokens=2 delims=:" %%a in ('chcp') do (set PM_OLD_CODE_PAGE=%%a) ) else ( call :ECHO_AND_RESET_ERROR ) :: trim leading space (this is safe even when PM_OLD_CODE_PAGE has not been set) set PM_OLD_CODE_PAGE=%PM_OLD_CODE_PAGE:~1% if "%PM_OLD_CODE_PAGE%" equ "65001" ( chcp 437 > nul set PM_RESTORE_CODE_PAGE=1 ) call "%~dp0\bootstrap\configure.bat" set PM_CONFIG_ERRORLEVEL=%errorlevel% if defined PM_RESTORE_CODE_PAGE ( :: Restore code page chcp %PM_OLD_CODE_PAGE% > nul ) set PM_OLD_CODE_PAGE= set PM_RESTORE_CODE_PAGE= exit /b %PM_CONFIG_ERRORLEVEL%
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/packman/bootstrap/generate_temp_file_name.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> $out = [System.IO.Path]::GetTempFileName() Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAK+Ewup1N0/mdf # 1l4R58rxyumHgZvTmEhrYTb2Zf0zd6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh # PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE # ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0 # IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENsYXNzIDMgU0hBMjU2IENvZGUg # U2lnbmluZyBDQSAtIEcyMB4XDTE4MDcwOTAwMDAwMFoXDTIxMDcwOTIzNTk1OVow # gYMxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRQwEgYDVQQHDAtT # YW50YSBDbGFyYTEbMBkGA1UECgwSTlZJRElBIENvcnBvcmF0aW9uMQ8wDQYDVQQL # DAZJVC1NSVMxGzAZBgNVBAMMEk5WSURJQSBDb3Jwb3JhdGlvbjCCASIwDQYJKoZI # hvcNAQEBBQADggEPADCCAQoCggEBALEZN63dA47T4i90jZ84CJ/aWUwVtLff8AyP # YspFfIZGdZYiMgdb8A5tBh7653y0G/LZL6CVUkgejcpvBU/Dl/52a+gSWy2qJ2bH # jMFMKCyQDhdpCAKMOUKSC9rfzm4cFeA9ct91LQCAait4LhLlZt/HF7aG+r0FgCZa # HJjJvE7KNY9G4AZXxjSt8CXS8/8NQMANqjLX1r+F+Hl8PzQ1fVx0mMsbdtaIV4Pj # 5flAeTUnz6+dCTx3vTUo8MYtkS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NV # BAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBpbmcgQ0ECEA1C # SuC+Ooj/YEAhzhQA8N0wDQYJYIZIAWUDBAIBBQCggZgwGgYJKoZIhvcNAQkDMQ0G # CyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG # SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3 # DQEJBDEiBCCHEAmNNj2zWjWYRfEi4FgzZvrI16kv/U2b9b3oHw6UVDANBgkqhkiG # 9w0BAQEFAASCAQCdefEKh6Qmwx7xGCkrYi/A+/Cla6LdnYJp38eMs3fqTTvjhyDw # HffXrwdqWy5/fgW3o3qJXqa5o7hLxYIoWSULOCpJRGdt+w7XKPAbZqHrN9elAhWJ # vpBTCEaj7dVxr1Ka4NsoPSYe0eidDBmmvGvp02J4Z1j8+ImQPKN6Hv/L8Ixaxe7V # mH4VtXIiBK8xXdi4wzO+A+qLtHEJXz3Gw8Bp3BNtlDGIUkIhVTM3Q1xcSEqhOLqo # PGdwCw9acxdXNWWPjOJkNH656Bvmkml+0p6MTGIeG4JCeRh1Wpqm1ZGSoEcXNaof # wOgj48YzI+dNqBD9i7RSWCqJr2ygYKRTxnuU # SIG # End signature block
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/packman/bootstrap/configure.bat
:: Copyright 2019-2023 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: https://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. set PM_PACKMAN_VERSION=7.6 :: Specify where packman command is rooted set PM_INSTALL_PATH=%~dp0.. :: The external root may already be configured and we should do minimal work in that case if defined PM_PACKAGES_ROOT goto ENSURE_DIR :: If the folder isn't set we assume that the best place for it is on the drive that we are currently :: running from set PM_DRIVE=%CD:~0,2% set PM_PACKAGES_ROOT=%PM_DRIVE%\packman-repo :: We use *setx* here so that the variable is persisted in the user environment echo Setting user environment variable PM_PACKAGES_ROOT to %PM_PACKAGES_ROOT% setx PM_PACKAGES_ROOT %PM_PACKAGES_ROOT% if %errorlevel% neq 0 ( goto ERROR ) :: The above doesn't work properly from a build step in VisualStudio because a separate process is :: spawned for it so it will be lost for subsequent compilation steps - VisualStudio must :: be launched from a new process. We catch this odd-ball case here: if defined PM_DISABLE_VS_WARNING goto ENSURE_DIR if not defined VSLANG goto ENSURE_DIR echo The above is a once-per-computer operation. Unfortunately VisualStudio cannot pick up environment change echo unless *VisualStudio is RELAUNCHED*. echo If you are launching VisualStudio from command line or command line utility make sure echo you have a fresh launch environment (relaunch the command line or utility). echo If you are using 'linkPath' and referring to packages via local folder links you can safely ignore this warning. echo You can disable this warning by setting the environment variable PM_DISABLE_VS_WARNING. echo. :: Check for the directory that we need. Note that mkdir will create any directories :: that may be needed in the path :ENSURE_DIR if not exist "%PM_PACKAGES_ROOT%" ( echo Creating packman packages cache at %PM_PACKAGES_ROOT% mkdir "%PM_PACKAGES_ROOT%" ) if %errorlevel% neq 0 ( goto ERROR_MKDIR_PACKAGES_ROOT ) :: The Python interpreter may already be externally configured if defined PM_PYTHON_EXT ( set PM_PYTHON=%PM_PYTHON_EXT% goto PACKMAN ) set PM_PYTHON_VERSION=3.10.5-1-windows-x86_64 set PM_PYTHON_BASE_DIR=%PM_PACKAGES_ROOT%\python set PM_PYTHON_DIR=%PM_PYTHON_BASE_DIR%\%PM_PYTHON_VERSION% set PM_PYTHON=%PM_PYTHON_DIR%\python.exe if exist "%PM_PYTHON%" goto PACKMAN if not exist "%PM_PYTHON_BASE_DIR%" call :CREATE_PYTHON_BASE_DIR set PM_PYTHON_PACKAGE=python@%PM_PYTHON_VERSION%.cab for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME%.zip call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_PYTHON_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching python from CDN !!! goto ERROR ) for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_folder.ps1" -parentPath "%PM_PYTHON_BASE_DIR%"') do set TEMP_FOLDER_NAME=%%a echo Unpacking Python interpreter ... "%SystemRoot%\system32\expand.exe" -F:* "%TARGET%" "%TEMP_FOLDER_NAME%" 1> nul del "%TARGET%" :: Failure during extraction to temp folder name, need to clean up and abort if %errorlevel% neq 0 ( echo !!! Error unpacking python !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :: If python has now been installed by a concurrent process we need to clean up and then continue if exist "%PM_PYTHON%" ( call :CLEAN_UP_TEMP_FOLDER goto PACKMAN ) else ( if exist "%PM_PYTHON_DIR%" ( rd /s /q "%PM_PYTHON_DIR%" > nul ) ) :: Perform atomic move (allowing ovewrite, /y) move /y "%TEMP_FOLDER_NAME%" "%PM_PYTHON_DIR%" 1> nul :: Verify that python.exe is now where we expect if exist "%PM_PYTHON%" goto PACKMAN :: Wait a second and try again (can help with access denied weirdness) timeout /t 1 /nobreak 1> nul move /y "%TEMP_FOLDER_NAME%" "%PM_PYTHON_DIR%" 1> nul if %errorlevel% neq 0 ( echo !!! Error moving python %TEMP_FOLDER_NAME% -> %PM_PYTHON_DIR% !!! call :CLEAN_UP_TEMP_FOLDER goto ERROR ) :PACKMAN :: The packman module may already be externally configured if defined PM_MODULE_DIR_EXT ( set PM_MODULE_DIR=%PM_MODULE_DIR_EXT% ) else ( set PM_MODULE_DIR=%PM_PACKAGES_ROOT%\packman-common\%PM_PACKMAN_VERSION% ) set PM_MODULE=%PM_MODULE_DIR%\run.py if exist "%PM_MODULE%" goto END :: Clean out broken PM_MODULE_DIR if it exists if exist "%PM_MODULE_DIR%" ( rd /s /q "%PM_MODULE_DIR%" > nul ) set PM_MODULE_PACKAGE=packman-common@%PM_PACKMAN_VERSION%.zip for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a set TARGET=%TEMP_FILE_NAME% call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_MODULE_PACKAGE% "%TARGET%" if %errorlevel% neq 0 ( echo !!! Error fetching packman from CDN !!! goto ERROR ) echo Unpacking ... "%PM_PYTHON%" -S -s -u -E "%~dp0\install_package.py" "%TARGET%" "%PM_MODULE_DIR%" if %errorlevel% neq 0 ( echo !!! Error unpacking packman !!! goto ERROR ) del "%TARGET%" goto END :ERROR_MKDIR_PACKAGES_ROOT echo Failed to automatically create packman packages repo at %PM_PACKAGES_ROOT%. echo Please set a location explicitly that packman has permission to write to, by issuing: echo. echo setx PM_PACKAGES_ROOT {path-you-choose-for-storing-packman-packages-locally} echo. echo Then launch a new command console for the changes to take effect and run packman command again. exit /B %errorlevel% :ERROR echo !!! Failure while configuring local machine :( !!! exit /B %errorlevel% :CLEAN_UP_TEMP_FOLDER rd /S /Q "%TEMP_FOLDER_NAME%" exit /B :CREATE_PYTHON_BASE_DIR :: We ignore errors and clean error state - if two processes create the directory one will fail which is fine md "%PM_PYTHON_BASE_DIR%" > nul 2>&1 exit /B 0 :END
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/packman/bootstrap/fetch_file_from_packman_bootstrap.cmd
:: Copyright 2019 NVIDIA CORPORATION :: :: Licensed under the Apache License, Version 2.0 (the "License"); :: you may not use this file except in compliance with the License. :: You may obtain a copy of the License at :: :: https://www.apache.org/licenses/LICENSE-2.0 :: :: Unless required by applicable law or agreed to in writing, software :: distributed under the License is distributed on an "AS IS" BASIS, :: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. :: See the License for the specific language governing permissions and :: limitations under the License. :: You need to specify <package-name> <target-path> as input to this command @setlocal @set PACKAGE_NAME=%1 @set TARGET_PATH=%2 @echo Fetching %PACKAGE_NAME% ... @powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0download_file_from_url.ps1" ^ -source "https://bootstrap.packman.nvidia.com/%PACKAGE_NAME%" -output %TARGET_PATH% :: A bug in powershell prevents the errorlevel code from being set when using the -File execution option :: We must therefore do our own failure analysis, basically make sure the file exists: @if not exist %TARGET_PATH% goto ERROR_DOWNLOAD_FAILED @endlocal @exit /b 0 :ERROR_DOWNLOAD_FAILED @echo Failed to download file from S3 @echo Most likely because endpoint cannot be reached or file %PACKAGE_NAME% doesn't exist @endlocal @exit /b 1
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/packman/bootstrap/download_file_from_url.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> param( [Parameter(Mandatory=$true)][string]$source=$null, [string]$output="out.exe" ) $filename = $output $triesLeft = 4 $delay = 2 do { $triesLeft -= 1 try { Write-Host "Downloading from bootstrap.packman.nvidia.com ..." $wc = New-Object net.webclient $wc.Downloadfile($source, $fileName) exit 0 } catch { Write-Host "Error downloading $source!" Write-Host $_.Exception|format-list -force if ($triesLeft) { Write-Host "Retrying in $delay seconds ..." Start-Sleep -seconds $delay } $delay = $delay * $delay } } while ($triesLeft -gt 0) # We only get here if the retries have been exhausted, remove any left-overs: if (Test-Path $fileName) { Remove-Item $fileName } exit 1
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/packman/bootstrap/generate_temp_folder.ps1
<# Copyright 2019 NVIDIA CORPORATION Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #> param( [Parameter(Mandatory=$true)][string]$parentPath=$null ) [string] $name = [System.Guid]::NewGuid() $out = Join-Path $parentPath $name New-Item -ItemType Directory -Path ($out) | Out-Null Write-Host $out # SIG # Begin signature block # MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCB29nsqMEu+VmSF # 7ckeVTPrEZ6hsXjOgPFlJm9ilgHUB6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh # PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE # ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0 # IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENsYXNzIDMgU0hBMjU2IENvZGUg # U2lnbmluZyBDQSAtIEcyMB4XDTE4MDcwOTAwMDAwMFoXDTIxMDcwOTIzNTk1OVow # gYMxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRQwEgYDVQQHDAtT # YW50YSBDbGFyYTEbMBkGA1UECgwSTlZJRElBIENvcnBvcmF0aW9uMQ8wDQYDVQQL # DAZJVC1NSVMxGzAZBgNVBAMMEk5WSURJQSBDb3Jwb3JhdGlvbjCCASIwDQYJKoZI # hvcNAQEBBQADggEPADCCAQoC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o9WuWwPRYaQ18yAGxuSh1t5ljhSKMYcp5lH5Z/IwP42+1ASa2bKXuh1Eh # 5Fhgm7oMLSttosR+u8QlK0cCCHxJrhO24XxCQijGGFbPQTS2Zl22dHv1VjMiLyI2 # skuiSpXY9aaOUjGCAk0wggJJAgEBMIGGMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQK # EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNV # BAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBpbmcgQ0ECEA1C # SuC+Ooj/YEAhzhQA8N0wDQYJYIZIAWUDBAIBBQCggZgwGgYJKoZIhvcNAQkDMQ0G # CyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG # SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3 # DQEJBDEiBCDvFxQ6lYLr8vB+9czUl19rjCw1pWhhUXw/SqOmvIa/VDANBgkqhkiG # 9w0BAQEFAASCAQB9ox2UrcUXQsBI4Uycnhl4AMpvhVXJME62tygFMppW1l7QftDy # LvfPKRYm2YUioak/APxAS6geRKpeMkLvXuQS/Jlv0kY3BjxkeG0eVjvyjF4SvXbZ # 3JCk9m7wLNE+xqOo0ICjYlIJJgRLudjWkC5Skpb1NpPS8DOaIYwRV+AWaSOUPd9P # O5yVcnbl7OpK3EAEtwDrybCVBMPn2MGhAXybIHnth3+MFp1b6Blhz3WlReQyarjq # 1f+zaFB79rg6JswXoOTJhwICBP3hO2Ua3dMAswbfl+QNXF+igKLJPYnaeSVhBbm6 # VCu2io27t4ixqvoD0RuPObNX/P3oVA38afiM # SIG # End signature block
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import os import stat import time from typing import Any, Callable RENAME_RETRY_COUNT = 100 RENAME_RETRY_DELAY = 0.1 logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") def remove_directory_item(path): if os.path.islink(path) or os.path.isfile(path): try: os.remove(path) except PermissionError: # make sure we have access and try again: os.chmod(path, stat.S_IRWXU) os.remove(path) else: # try first to delete the dir because this will work for folder junctions, otherwise we would follow the junctions and cause destruction! clean_out_folder = False try: # make sure we have access preemptively - this is necessary because recursing into a directory without permissions # will only lead to heart ache os.chmod(path, stat.S_IRWXU) os.rmdir(path) except OSError: clean_out_folder = True if clean_out_folder: # we should make sure the directory is empty names = os.listdir(path) for name in names: fullname = os.path.join(path, name) remove_directory_item(fullname) # now try to again get rid of the folder - and not catch if it raises: os.rmdir(path) class StagingDirectory: def __init__(self, staging_path): self.staging_path = staging_path self.temp_folder_path = None os.makedirs(staging_path, exist_ok=True) def __enter__(self): self.temp_folder_path = tempfile.mkdtemp(prefix="ver-", dir=self.staging_path) return self def get_temp_folder_path(self): return self.temp_folder_path # this function renames the temp staging folder to folder_name, it is required that the parent path exists! def promote_and_rename(self, folder_name): abs_dst_folder_name = os.path.join(self.staging_path, folder_name) os.rename(self.temp_folder_path, abs_dst_folder_name) def __exit__(self, type, value, traceback): # Remove temp staging folder if it's still there (something went wrong): path = self.temp_folder_path if os.path.isdir(path): remove_directory_item(path) def rename_folder(staging_dir: StagingDirectory, folder_name: str): try: staging_dir.promote_and_rename(folder_name) except OSError as exc: # if we failed to rename because the folder now exists we can assume that another packman process # has managed to update the package before us - in all other cases we re-raise the exception abs_dst_folder_name = os.path.join(staging_dir.staging_path, folder_name) if os.path.exists(abs_dst_folder_name): logger.warning( f"Directory {abs_dst_folder_name} already present, package installation already completed" ) else: raise def call_with_retry( op_name: str, func: Callable, retry_count: int = 3, retry_delay: float = 20 ) -> Any: retries_left = retry_count while True: try: return func() except (OSError, IOError) as exc: logger.warning(f"Failure while executing {op_name} [{str(exc)}]") if retries_left: retry_str = "retry" if retries_left == 1 else "retries" logger.warning( f"Retrying after {retry_delay} seconds" f" ({retries_left} {retry_str} left) ..." ) time.sleep(retry_delay) else: logger.error("Maximum retries exceeded, giving up") raise retries_left -= 1 def rename_folder_with_retry(staging_dir: StagingDirectory, folder_name): dst_path = os.path.join(staging_dir.staging_path, folder_name) call_with_retry( f"rename {staging_dir.get_temp_folder_path()} -> {dst_path}", lambda: rename_folder(staging_dir, folder_name), RENAME_RETRY_COUNT, RENAME_RETRY_DELAY, ) def install_package(package_path, install_path): staging_path, version = os.path.split(install_path) with StagingDirectory(staging_path) as staging_dir: output_folder = staging_dir.get_temp_folder_path() with zipfile.ZipFile(package_path, allowZip64=True) as zip_file: zip_file.extractall(output_folder) # attempt the rename operation rename_folder_with_retry(staging_dir, version) print(f"Package successfully installed to {install_path}") if __name__ == "__main__": executable_paths = os.getenv("PATH") paths_list = executable_paths.split(os.path.pathsep) if executable_paths else [] target_path_np = os.path.normpath(sys.argv[2]) target_path_np_nc = os.path.normcase(target_path_np) for exec_path in paths_list: if os.path.normcase(os.path.normpath(exec_path)) == target_path_np_nc: raise RuntimeError(f"packman will not install to executable path '{exec_path}'") install_package(sys.argv[1], target_path_np)
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/premake5.lua
-- Setup the basic extension information. local ext = get_current_extension_info() project_ext(ext) -- -------------------------------------------------------------------------------------------------------------- -- Helper variable containing standard configuration information for projects containing OGN files. local ogn = get_ogn_project_information(ext, "mf/ov/lidar_live_synth") -- -------------------------------------------------------------------------------------------------------------- -- Link folders that should be packaged with the extension. repo_build.prebuild_link { { "data", ext.target_dir.."/data" }, { "docs", ext.target_dir.."/docs" }, } -- -------------------------------------------------------------------------------------------------------------- -- Copy the __init__.py to allow building of a non-linked ogn/ import directory. -- In a mixed extension this would be part of a separate Python-based project but since here it is just the one -- file it can be copied directly with no build dependencies. repo_build.prebuild_copy { { "mf/ov/lidar_live_synth/__init__.py", ogn.python_target_path } } -- -------------------------------------------------------------------------------------------------------------- -- Breaking this out as a separate project ensures the .ogn files are processed before their results are needed. project_ext_ogn( ext, ogn ) -- -------------------------------------------------------------------------------------------------------------- -- Build the C++ plugin that will be loaded by the extension. project_ext_plugin(ext, ogn.plugin_project) -- It is important that you add all subdirectories containing C++ code to this project add_files("source", "plugins/"..ogn.module) add_files("nodes", "plugins/nodes") -- Add the standard dependencies all OGN projects have; includes, libraries to link, and required compiler flags add_ogn_dependencies(ogn)
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/mf/ov/lidar_live_synth/__init__.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. ## # This file is needed so tests don't fail.
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/config/extension.toml
[package] version = "0.2.0" title = "MF Lidar live synthetic data" description = "Send real-time Lidar synthetic point cloud data from Omniverse to third party software." category = "Graph" keywords = ["lidar", "UDP", "omnigraph", "Graph", "Node", "OmniGraph", "synthetic", "realtime"] preview_image = "data/preview.png" icon = "data/icon.png" changelog = "docs/CHANGELOG.md" readme = "docs/README.md" authors = ["Moment Factory","Frederic Lestage","Steven Beliveau"] repository = "https://github.com/MomentFactory/Omniverse-Lidar-extension" [dependencies] "omni.graph" = {} [[python.module]] name = "mf.ov.lidar_live_synth" [[native.plugin]] path = "bin/*.plugin" [documentation] pages = [ "docs/README.md", "docs/CHANGELOG.md", ] [package.target] kit = ["105.1"] [package.writeTarget] kit = true python = false
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/plugins/mf.ov.lidar_live_synth/LidarLiveSyntheticDataExtension.cpp
#define CARB_EXPORTS #include <carb/PluginUtils.h> #include <omni/ext/IExt.h> #include <omni/graph/core/IGraphRegistry.h> #include <omni/graph/core/ogn/Database.h> #include <omni/graph/core/ogn/Registration.h> // Standard plugin definitions required by Carbonite. const struct carb::PluginImplDesc pluginImplDesc = { "mf.ov.lidar_live_synth.plugin", "MF Lidar live synthetic data.", "MF", carb::PluginHotReload::eEnabled, "dev" }; // These interface dependencies are required by all OmniGraph node types CARB_PLUGIN_IMPL_DEPS(omni::graph::core::IGraphRegistry, omni::fabric::IPath, omni::fabric::IToken) // This macro sets up the information required to register your node type definitions with OmniGraph DECLARE_OGN_NODES() namespace mf { namespace ov { namespace lidar_live_synth { class LidarLiveSyntheticDataExtension : public omni::ext::IExt { public: void onStartup(const char* extId) override { // This macro walks the list of pending node type definitions and registers them with OmniGraph INITIALIZE_OGN_NODES() } void onShutdown() override { // This macro walks the list of registered node type definitions and deregisters all of them. This is required // for hot reload to work. RELEASE_OGN_NODES() } private: }; } } } CARB_PLUGIN_IMPL(pluginImplDesc, mf::ov::lidar_live_synth::LidarLiveSyntheticDataExtension) void fillInterface(mf::ov::lidar_live_synth::LidarLiveSyntheticDataExtension& iface) { }
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/plugins/nodes/OgnBeamToOusterUDPNode.ogn
{ "BeamToOusterUDPNode": { "version": 1, "description": "Receives beam data from Isaac Lidar and send it via the Ouster UDP protocol", "metadata": { "uiName": "Beam to Ouster UDP" }, "inputs": { "execIn": { "type": "execution", "description": "Execution", "default": 0, "metadata": { "uiName": "Exec In" } }, "ip_address": { "type": "string", "description": "The message destination IP address", "metadata": { "uiName": "IP Address" }, "default": "127.0.0.1" }, "port": { "type": "int", "description": "The port to which to send the data to", "metadata": { "uiName": "Port" }, "default": 8037 }, "broadcast": { "type": "bool", "description": "Whether the IP address is a broadcast address or not", "metadata": { "uiName": "Broadcast" }, "default": false }, "linearDepthData": { "type": "float[]", "description": "Buffer array containing linear depth data", "metadata": { "uiName": "Linear Depth Data" }, "default": [] }, "azimuthRange": { "type": "float[2]", "description": "The azimuth range [min, max]", "metadata": { "uiName": "Azimuth Range" }, "default": [ -3.14159, 3.14159 ] }, "horizontalResolution": { "type": "float", "description": "Degrees in between rays for horizontal axis", "metadata": { "uiName": "Horizontal Resolution" }, "default": 2 }, "numCols": { "type": "int", "description": "Number of columns in buffers", "metadata": { "uiName": "Num Cols" }, "default": 1 }, "numRows": { "type": "int", "description": "Number of rows in buffers", "metadata": { "uiName": "Num Rows" }, "default": 1 } }, "outputs": { "execOut": { "type": "execution", "description": "Output execution triggers when the data has been sent", "metadata": { "uiName": "Exec Out" } } } } }
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/plugins/nodes/OgnBeamToOusterUDPNode.cpp
#include <OgnBeamToOusterUDPNodeDatabase.h> #include <chrono> #define WIN32_LEAN_AND_MEAN #define _WINSOCK_DEPRECATED_NO_WARNINGS #ifdef _WIN32 #include <Winsock2.h> #else #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/types.h> #define SOCKET int #define INVALID_SOCKET (SOCKET)(~0) #define SOCKET_ERROR (-1) #define closesocket close #define SOCKADDR sockaddr #endif namespace mf { namespace ov { namespace lidar_live_synth { static const int kColumnsPerPacket = 16; static const float kPi = 3.14159265359f; static const float kTwoPi = kPi * 2.0f; static const float kDegToRad = kTwoPi / 360.0f; static const int kOusterNumRotAngles = 90112; static const float kOusterNumRotAnglesOverTwoPi = kOusterNumRotAngles / kTwoPi; class OgnBeamToOusterUDPNode { int m_frameId{ 0 }; #pragma pack(push,4) // Force packing in 4-byte packs (Words) struct OusterChannelDataBlock { unsigned int rangemm; unsigned short reflectivity; unsigned short signal_photons; unsigned short noise_photons; unsigned short unused; OusterChannelDataBlock() : rangemm(0) , reflectivity(0) , signal_photons(0) , noise_photons(0) , unused(0) {} }; template <int NUMROWS> struct OusterAzimuthBlock { unsigned long long timeStamp; // Word 0,1 unsigned short measurementId; // Word 2[0:15] unsigned short frameId; // Word 2[16:31] unsigned int encoderCount; // Word 3 OusterChannelDataBlock channelDataBlock[NUMROWS]; // Word [4:195] in groups of 3 unsigned int azimuthDataBlockStatus; // word 196 OusterAzimuthBlock() : timeStamp(0) , measurementId(0) , frameId(0) , encoderCount(0) , channelDataBlock{} , azimuthDataBlockStatus(0) {} }; template <int NUMROWS> struct OusterDataPacket { OusterAzimuthBlock<NUMROWS> block[16]; // Each packet consists of 16 azimuth blocks OusterDataPacket() :block{} {} }; #pragma pack(pop) class OgnBeamToOusterUDPNodeSocket { public: OgnBeamToOusterUDPNodeSocket() : SendSocket(INVALID_SOCKET) , isBroadcastSocket(false) {} virtual ~OgnBeamToOusterUDPNodeSocket() { if (SendSocket != INVALID_SOCKET) { closesocket(SendSocket); } } bool prepare(OgnBeamToOusterUDPNodeDatabase& db) { if (isBroadcastSocket != db.inputs.broadcast()) { closesocket(SendSocket); SendSocket = INVALID_SOCKET; } if (SendSocket == INVALID_SOCKET) { SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (SendSocket == INVALID_SOCKET) { db.logError("Error in OgnBeamToOusterUDPNode opening socket : %d", SendSocket); return false; } if (db.inputs.broadcast()) { char broadcast = 1; int iResult = setsockopt(SendSocket, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)); if (!iResult) { closesocket(SendSocket); SendSocket = INVALID_SOCKET; db.logError("Error in OgnBeamToOusterUDPNode setting socket options : %d", iResult); return false; } } isBroadcastSocket = db.inputs.broadcast(); } RecvAddr.sin_family = AF_INET; RecvAddr.sin_port = htons(db.inputs.port()); std::string ipAddress = db.inputs.ip_address(); RecvAddr.sin_addr.s_addr = inet_addr(ipAddress.data()); return true; } template <int NUMROWS> bool send(const OusterDataPacket<NUMROWS>& packet, OgnBeamToOusterUDPNodeDatabase& db) { int iResult = sendto(SendSocket, reinterpret_cast<const char*>(&packet), sizeof(packet), 0, (SOCKADDR*)&RecvAddr, sizeof(RecvAddr)); if (iResult == SOCKET_ERROR) { db.logError("Error in OgnBeamToOusterUDPNode sending data on socket : %d", iResult); return false; } return true; } private: SOCKET SendSocket; sockaddr_in RecvAddr; bool isBroadcastSocket; }; OgnBeamToOusterUDPNodeSocket m_ognBeamToOusterUDPNodeSocket; template<int NUMROWS> static bool computeForSize(OgnBeamToOusterUDPNodeDatabase& db) { auto& state = db.internalState<OgnBeamToOusterUDPNode>(); const auto& linearDepthData = db.inputs.linearDepthData(); const int& numCols = db.inputs.numCols(); const float& azimuthStart = db.inputs.azimuthRange()[0] + kTwoPi + kTwoPi; const float& horizontalStepInRads = -1.0f * db.inputs.horizontalResolution() * kDegToRad; const int& frameId = state.m_frameId % 65536; try { if (!state.m_ognBeamToOusterUDPNodeSocket.prepare(db)) { return false; } int measurementId = 0; OusterDataPacket<NUMROWS> packet; int currentChunkColumn = 0; // We need to send data in ascending angle (encoder_count) order // Data is in right-to-left order, we need to iterate left-to-right // We also need to start at the middle (center) of the data which is encoderCount 0 int colEndIndex = (numCols - 1) / 2; int colStartIndex = colEndIndex + numCols; for (int tempColIndex = colStartIndex; tempColIndex > colEndIndex; tempColIndex--) { int colIndex = tempColIndex % numCols; // This assumes consistent input data across azimuthRange, horizontalResolution, numCols, numRows and linearDepthData size int currentEncoderCount = int((azimuthStart + horizontalStepInRads * tempColIndex) * kOusterNumRotAnglesOverTwoPi); if (currentEncoderCount < 0 || currentEncoderCount >= kOusterNumRotAngles) { db.logError("currentEncoderCount must be between 0 and %d, not %d", kOusterNumRotAngles, currentEncoderCount); return false; } // If previous chunk is complete, start new one if (currentChunkColumn == kColumnsPerPacket) { state.m_ognBeamToOusterUDPNodeSocket.send<NUMROWS>(packet, db); packet = OusterDataPacket<NUMROWS>(); currentChunkColumn = 0; } packet.block[currentChunkColumn].timeStamp = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); packet.block[currentChunkColumn].measurementId = measurementId; packet.block[currentChunkColumn].frameId = frameId; packet.block[currentChunkColumn].encoderCount = currentEncoderCount; measurementId = (measurementId + 1) % 65536; int colIndexStart = colIndex * NUMROWS; for (int rowIndex = 0; rowIndex < NUMROWS; rowIndex++) { packet.block[currentChunkColumn].channelDataBlock[rowIndex].rangemm = (int)(linearDepthData[colIndexStart + rowIndex] * 1000.0f); packet.block[currentChunkColumn].channelDataBlock[rowIndex].signal_photons = 0xFFFF; //0xFFFF means valid } packet.block[currentChunkColumn].azimuthDataBlockStatus = 0xFFFFFFFF; //0xFFFFFFFF means valid currentChunkColumn++; } if (currentChunkColumn != 0) { for (int extraColumnIndex = currentChunkColumn; extraColumnIndex < kColumnsPerPacket; extraColumnIndex++) { packet.block[extraColumnIndex].timeStamp = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); packet.block[extraColumnIndex].measurementId = measurementId; packet.block[extraColumnIndex].frameId = frameId; packet.block[extraColumnIndex].encoderCount = kOusterNumRotAngles; } state.m_ognBeamToOusterUDPNodeSocket.send<NUMROWS>(packet, db); } } catch (...) { db.logError("Error in OgnBeamToOusterUDPNode::compute"); return false; } state.m_frameId++; // Always enable the output execution db.outputs.execOut() = omni::graph::core::ExecutionAttributeState::kExecutionAttributeStateEnabled; // Even if inputs were edge cases like empty arrays, correct outputs mean success return true; } public: static bool compute(OgnBeamToOusterUDPNodeDatabase& db) { // TODO: why is state declared here // auto& state = db.internalState<OgnBeamToOusterUDPNode>(); const int& numRows = db.inputs.numRows(); switch (numRows) { case 16: return computeForSize<16>(db); break; case 32: return computeForSize<32>(db); break; case 64: return computeForSize<64>(db); break; case 128: return computeForSize<128>(db); break; } db.logError("Row count must be either 16, 32, 64 or 128, not %d", numRows); return false; } }; // This macro provides the information necessary to OmniGraph that lets it automatically register and deregister // your node type definition. REGISTER_OGN_NODE() } } }
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/docs/CHANGELOG.md
# Changelog ## [0.2.0] - 2023-12-20 ### Modified - Adapted for compatibility with kit 105 - Enhanced documentation ### Added - Linux support thanks to [@Samahu](https://github.com/Samahu)'s PR on Github ## [0.1.3] - 2023-08-30 ### Changed - Version bump for registry publishing ## [0.1.2] - 2023-08-30 ### Added - New example with more Lidars ### Modified - Now comes as C++ for maximum performance. ## [0.1.1] - 2023-05-09 ### Added - Documentation ### Modified - Name of the Node - Icon ## [0.1.0] - 2023-05-09 ### Added - Action Graph Node that sends Isaac Lidar Point Cloud data in UDP
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/docs/README.md
# MF Lidar live synthetic data [mf.ov.lidar_live_synth] Adds an Action Graph Node ("Generic/Beam to Ouster UDP") to send Isaac beam data via the Ouster(tm) UDP procotol. This allows any third party software implementing Ouster(tm) lidars to be connected to simulated sensors instead of physical sensors. Developped for kit 105.1 and currently working only in Isaac Sim. This extensions provides pre-built binaries for Windows and Linux x86_64. You may want to compile from the [source code](https://github.com/MomentFactory/Omniverse-Lidar-Live-Synthetic-Data)
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/data/OusterJsonConfigOmniverse-OS1-64.json
{ "base_pn" : "", "base_sn" : "", "beam_altitude_angles" : [ 22.5, 21.7857, 21.0714, 20.3571, 19.6429, 18.9286, 18.2143, 17.5, 16.7857, 16.0714, 15.3571, 14.6429, 13.9286, 13.2143, 12.5, 11.7857, 11.0714, 10.3571, 9.64286, 8.92857, 8.21428, 7.5, 6.78571, 6.07143, 5.35714, 4.64286, 3.92857, 3.21428, 2.5, 1.78571, 1.07143, 0.357141, -0.357143, -1.07143, -1.78572, -2.5, -3.21429, -3.92857, -4.64286, -5.35714, -6.07143, -6.78572, -7.5, -8.21429, -8.92857, -9.64286, -10.3571, -11.0714, -11.7857, -12.5, -13.2143, -13.9286, -14.6429, -15.3571, -16.0714, -16.7857, -17.5, -18.2143, -18.9286, -19.6429, -20.3571, -21.0714, -21.7857, -22.5 ], "beam_azimuth_angles" : [ 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "build_date" : "2022-02-15T19:39:39Z", "build_rev" : "v2.2.1", "data_format" : { "column_window" : [ 0, 1023 ], "columns_per_frame" : 1024, "columns_per_packet" : 16, "pixel_shift_by_row" : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "pixels_per_column" : 64, "udp_profile_imu" : "LEGACY", "udp_profile_lidar" : "LEGACY" }, "hostname" : "10.10.80.110", "image_rev" : "ousteros-image-prod-aries-v2.2.1+20220215193703.patch-v2.2.1", "imu_to_sensor_transform" : [ 1, 0, 0, 6.2530000000000001, 0, 1, 0, -11.775, 0, 0, 1, 7.6449999999999996, 0, 0, 0, 1 ], "initialization_id" : 8247301, "json_calibration_version" : 4, "lidar_mode" : "1024x10", "lidar_origin_to_beam_origin_mm" : 15.805999999999999, "lidar_to_sensor_transform" : [ -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 36.18, 0, 0, 0, 1 ], "prod_line" : "OS-1-64", "prod_pn" : "840-103575-06", "prod_sn" : "992216000244", "proto_rev" : "", "status" : "RUNNING" }
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/data/OusterJsonConfigOmniverse-OS2-64.json
{ "base_pn" : "", "base_sn" : "", "beam_altitude_angles" : [ 11.25, 10.8929, 10.5357, 10.1786, 9.82143, 9.46429, 9.10714, 8.75, 8.39286, 8.03571, 7.67857, 7.32143, 6.96429, 6.60714, 6.25, 5.89286, 5.53571, 5.17857, 4.82143, 4.46429, 4.10714, 3.75, 3.39286, 3.03571, 2.67857, 2.32143, 1.96429, 1.60714, 1.25, 0.892857, 0.535714, 0.178571, -0.178572, -0.535714, -0.892858, -1.25, -1.60714, -1.96429, -2.32143, -2.67857, -3.03572, -3.39286, -3.75, -4.10714, -4.46429, -4.82143, -5.17857, -5.53572, -5.89286, -6.25, -6.60714, -6.96429, -7.32143, -7.67857, -8.03572, -8.39286, -8.75, -9.10714, -9.46429, -9.82143, -10.1786, -10.5357, -10.8929, -11.25 ], "beam_azimuth_angles" : [ 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "build_date" : "2022-02-15T19:39:39Z", "build_rev" : "v2.2.1", "data_format" : { "column_window" : [ 0, 1023 ], "columns_per_frame" : 1024, "columns_per_packet" : 16, "pixel_shift_by_row" : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "pixels_per_column" : 64, "udp_profile_imu" : "LEGACY", "udp_profile_lidar" : "LEGACY" }, "hostname" : "10.10.80.110", "image_rev" : "ousteros-image-prod-aries-v2.2.1+20220215193703.patch-v2.2.1", "imu_to_sensor_transform" : [ 1, 0, 0, 6.2530000000000001, 0, 1, 0, -11.775, 0, 0, 1, 7.6449999999999996, 0, 0, 0, 1 ], "initialization_id" : 8247301, "json_calibration_version" : 4, "lidar_mode" : "1024x10", "lidar_origin_to_beam_origin_mm" : 15.805999999999999, "lidar_to_sensor_transform" : [ -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 36.18, 0, 0, 0, 1 ], "prod_line" : "OS-2-64", "prod_pn" : "840-103575-06", "prod_sn" : "992216000244", "proto_rev" : "", "status" : "RUNNING" }
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/data/OusterJsonConfigOmniverse-OS0-64.json
{ "base_pn" : "", "base_sn" : "", "beam_altitude_angles" : [ 45, 43.5714, 42.1429, 40.7143, 39.2857, 37.8571, 36.4286, 35, 33.5714, 32.1429, 30.7143, 29.2857, 27.8571, 26.4286, 25, 23.5714, 22.1429, 20.7143, 19.2857, 17.8571, 16.4286, 15, 13.5714, 12.1429, 10.7143, 9.28571, 7.85714, 6.42857, 5, 3.57143, 2.14286, 0.714283, -0.714287, -2.14286, -3.57143, -5, -6.42857, -7.85714, -9.28572, -10.7143, -12.1429, -13.5714, -15, -16.4286, -17.8571, -19.2857, -20.7143, -22.1429, -23.5714, -25, -26.4286, -27.8571, -29.2857, -30.7143, -32.1429, -33.5714, -35, -36.4286, -37.8571, -39.2857, -40.7143, -42.1429, -43.5714, -45 ], "beam_azimuth_angles" : [ 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "build_date" : "2022-02-15T19:39:39Z", "build_rev" : "v2.2.1", "data_format" : { "column_window" : [ 0, 1023 ], "columns_per_frame" : 1024, "columns_per_packet" : 16, "pixel_shift_by_row" : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "pixels_per_column" : 64, "udp_profile_imu" : "LEGACY", "udp_profile_lidar" : "LEGACY" }, "hostname" : "10.10.80.110", "image_rev" : "ousteros-image-prod-aries-v2.2.1+20220215193703.patch-v2.2.1", "imu_to_sensor_transform" : [ 1, 0, 0, 6.2530000000000001, 0, 1, 0, -11.775, 0, 0, 1, 7.6449999999999996, 0, 0, 0, 1 ], "initialization_id" : 8247301, "json_calibration_version" : 4, "lidar_mode" : "1024x10", "lidar_origin_to_beam_origin_mm" : 15.805999999999999, "lidar_to_sensor_transform" : [ -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 36.18, 0, 0, 0, 1 ], "prod_line" : "OS-0-64", "prod_pn" : "840-103575-06", "prod_sn" : "992216000244", "proto_rev" : "", "status" : "RUNNING" }
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/data/OusterJsonConfigOmniverse-OS1-128.json
{ "base_pn" : "", "base_sn" : "", "beam_altitude_angles" : [ 22.5, 22.1457, 21.7913, 21.437, 21.0827, 20.7283, 20.374, 20.0197, 19.6654, 19.311, 18.9567, 18.6024, 18.248, 17.8937, 17.5394, 17.185, 16.8307, 16.4764, 16.122, 15.7677, 15.4134, 15.0591, 14.7047, 14.3504, 13.9961, 13.6417, 13.2874, 12.9331, 12.5787, 12.2244, 11.8701, 11.5157, 11.1614, 10.8071, 10.4528, 10.0984, 9.74409, 9.38976, 9.03543, 8.6811, 8.32677, 7.97244, 7.61811, 7.26378, 6.90945, 6.55512, 6.20079, 5.84646, 5.49213, 5.13779, 4.78346, 4.42913, 4.0748, 3.72047, 3.36614, 3.01181, 2.65748, 2.30315, 1.94882, 1.59449, 1.24016, 0.885826, 0.531496, 0.177164, -0.177166, -0.531496, -0.885828, -1.24016, -1.59449, -1.94882, -2.30315, -2.65748, -3.01181, -3.36614, -3.72047, -4.0748, -4.42913, -4.78346, -5.1378, -5.49213, -5.84646, -6.20079, -6.55512, -6.90945, -7.26378, -7.61811, -7.97244, -8.32677, -8.6811, -9.03543, -9.38976, -9.74409, -10.0984, -10.4528, -10.8071, -11.1614, -11.5157, -11.8701, -12.2244, -12.5787, -12.9331, -13.2874, -13.6417, -13.9961, -14.3504, -14.7047, -15.0591, -15.4134, -15.7677, -16.122, -16.4764, -16.8307, -17.185, -17.5394, -17.8937, -18.248, -18.6024, -18.9567, -19.311, -19.6654, -20.0197, -20.374, -20.7283, -21.0827, -21.437, -21.7913, -22.1457, -22.5 ], "beam_azimuth_angles" : [ 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, 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, 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, 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, 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, 0, 0, 0 ], "build_date" : "2022-02-15T19:39:39Z", "build_rev" : "v2.2.1", "data_format" : { "column_window" : [ 0, 1023 ], "columns_per_frame" : 1024, "columns_per_packet" : 16, "pixel_shift_by_row" : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "pixels_per_column" : 128, "udp_profile_imu" : "LEGACY", "udp_profile_lidar" : "LEGACY" }, "hostname" : "10.10.80.110", "image_rev" : "ousteros-image-prod-aries-v2.2.1+20220215193703.patch-v2.2.1", "imu_to_sensor_transform" : [ 1, 0, 0, 6.2530000000000001, 0, 1, 0, -11.775, 0, 0, 1, 7.6449999999999996, 0, 0, 0, 1 ], "initialization_id" : 8247301, "json_calibration_version" : 4, "lidar_mode" : "1024x10", "lidar_origin_to_beam_origin_mm" : 15.805999999999999, "lidar_to_sensor_transform" : [ -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 36.18, 0, 0, 0, 1 ], "prod_line" : "OS-1-128", "prod_pn" : "840-103575-06", "prod_sn" : "992216000244", "proto_rev" : "", "status" : "RUNNING" }
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/data/OusterJsonConfigOmniverse-OS0-128.json
{ "base_pn" : "", "base_sn" : "", "beam_altitude_angles" : [ 45, 44.2913, 43.5827, 42.874, 42.1654, 41.4567, 40.748, 40.0394, 39.3307, 38.622, 37.9134, 37.2047, 36.4961, 35.7874, 35.0787, 34.3701, 33.6614, 32.9528, 32.2441, 31.5354, 30.8268, 30.1181, 29.4094, 28.7008, 27.9921, 27.2835, 26.5748, 25.8661, 25.1575, 24.4488, 23.7402, 23.0315, 22.3228, 21.6142, 20.9055, 20.1968, 19.4882, 18.7795, 18.0709, 17.3622, 16.6535, 15.9449, 15.2362, 14.5276, 13.8189, 13.1102, 12.4016, 11.6929, 10.9843, 10.2756, 9.56693, 8.85826, 8.1496, 7.44094, 6.73228, 6.02362, 5.31496, 4.6063, 3.89764, 3.18898, 2.48031, 1.77165, 1.06299, 0.354328, -0.354332, -1.06299, -1.77166, -2.48032, -3.18898, -3.89764, -4.6063, -5.31496, -6.02362, -6.73228, -7.44094, -8.14961, -8.85827, -9.56693, -10.2756, -10.9843, -11.6929, -12.4016, -13.1102, -13.8189, -14.5276, -15.2362, -15.9449, -16.6535, -17.3622, -18.0709, -18.7795, -19.4882, -20.1969, -20.9055, -21.6142, -22.3228, -23.0315, -23.7402, -24.4488, -25.1575, -25.8661, -26.5748, -27.2835, -27.9921, -28.7008, -29.4095, -30.1181, -30.8268, -31.5354, -32.2441, -32.9528, -33.6614, -34.3701, -35.0787, -35.7874, -36.4961, -37.2047, -37.9134, -38.622, -39.3307, -40.0394, -40.748, -41.4567, -42.1654, -42.874, -43.5827, -44.2913, -45 ], "beam_azimuth_angles" : [ 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, 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, 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, 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, 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, 0, 0, 0 ], "build_date" : "2022-02-15T19:39:39Z", "build_rev" : "v2.2.1", "data_format" : { "column_window" : [ 0, 1023 ], "columns_per_frame" : 1024, "columns_per_packet" : 16, "pixel_shift_by_row" : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "pixels_per_column" : 128, "udp_profile_imu" : "LEGACY", "udp_profile_lidar" : "LEGACY" }, "hostname" : "10.10.80.110", "image_rev" : "ousteros-image-prod-aries-v2.2.1+20220215193703.patch-v2.2.1", "imu_to_sensor_transform" : [ 1, 0, 0, 6.2530000000000001, 0, 1, 0, -11.775, 0, 0, 1, 7.6449999999999996, 0, 0, 0, 1 ], "initialization_id" : 8247301, "json_calibration_version" : 4, "lidar_mode" : "1024x10", "lidar_origin_to_beam_origin_mm" : 15.805999999999999, "lidar_to_sensor_transform" : [ -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 36.18, 0, 0, 0, 1 ], "prod_line" : "OS-0-128", "prod_pn" : "840-103575-06", "prod_sn" : "992216000244", "proto_rev" : "", "status" : "RUNNING" }
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/data/OusterJsonConfigOmniverse-OS2-128.json
{ "base_pn" : "", "base_sn" : "", "beam_altitude_angles" : [ 11.25, 11.0728, 10.8957, 10.7185, 10.5413, 10.3642, 10.187, 10.0098, 9.83268, 9.65551, 9.47835, 9.30118, 9.12402, 8.94685, 8.76968, 8.59252, 8.41535, 8.23819, 8.06102, 7.88386, 7.70669, 7.52953, 7.35236, 7.1752, 6.99803, 6.82087, 6.6437, 6.46654, 6.28937, 6.1122, 5.93504, 5.75787, 5.58071, 5.40354, 5.22638, 5.04921, 4.87205, 4.69488, 4.51772, 4.34055, 4.16339, 3.98622, 3.80905, 3.63189, 3.45472, 3.27756, 3.10039, 2.92323, 2.74606, 2.5689, 2.39173, 2.21457, 2.0374, 1.86024, 1.68307, 1.50591, 1.32874, 1.15157, 0.974409, 0.797244, 0.620078, 0.442913, 0.265748, 0.088582, -0.088583, -0.265748, -0.442914, -0.620079, -0.797244, -0.97441, -1.15158, -1.32874, -1.50591, -1.68307, -1.86024, -2.0374, -2.21457, -2.39173, -2.5689, -2.74606, -2.92323, -3.10039, -3.27756, -3.45473, -3.63189, -3.80906, -3.98622, -4.16339, -4.34055, -4.51772, -4.69488, -4.87205, -5.04921, -5.22638, -5.40354, -5.58071, -5.75787, -5.93504, -6.11221, -6.28937, -6.46654, -6.6437, -6.82087, -6.99803, -7.1752, -7.35236, -7.52953, -7.70669, -7.88386, -8.06102, -8.23819, -8.41536, -8.59252, -8.76969, -8.94685, -9.12402, -9.30118, -9.47835, -9.65551, -9.83268, -10.0098, -10.187, -10.3642, -10.5413, -10.7185, -10.8957, -11.0728, -11.25 ], "beam_azimuth_angles" : [ 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, 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, 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, 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, 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, 0, 0, 0 ], "build_date" : "2022-02-15T19:39:39Z", "build_rev" : "v2.2.1", "data_format" : { "column_window" : [ 0, 1023 ], "columns_per_frame" : 1024, "columns_per_packet" : 16, "pixel_shift_by_row" : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "pixels_per_column" : 128, "udp_profile_imu" : "LEGACY", "udp_profile_lidar" : "LEGACY" }, "hostname" : "10.10.80.110", "image_rev" : "ousteros-image-prod-aries-v2.2.1+20220215193703.patch-v2.2.1", "imu_to_sensor_transform" : [ 1, 0, 0, 6.2530000000000001, 0, 1, 0, -11.775, 0, 0, 1, 7.6449999999999996, 0, 0, 0, 1 ], "initialization_id" : 8247301, "json_calibration_version" : 4, "lidar_mode" : "1024x10", "lidar_origin_to_beam_origin_mm" : 15.805999999999999, "lidar_to_sensor_transform" : [ -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 36.18, 0, 0, 0, 1 ], "prod_line" : "OS-2-128", "prod_pn" : "840-103575-06", "prod_sn" : "992216000244", "proto_rev" : "", "status" : "RUNNING" }
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/data/OusterJsonConfigOmniverse-OS1-16.json
{ "base_pn" : "", "base_sn" : "", "beam_altitude_angles" : [ 22.5, 19.5, 16.5, 13.5, 10.5, 7.5, 4.5, 1.5, -1.5, -4.5, -7.5, -10.5, -13.5, -16.5, -19.5, -22.5 ], "beam_azimuth_angles" : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "build_date" : "2022-02-15T19:39:39Z", "build_rev" : "v2.2.1", "data_format" : { "column_window" : [ 0, 1023 ], "columns_per_frame" : 1024, "columns_per_packet" : 16, "pixel_shift_by_row" : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "pixels_per_column" : 16, "udp_profile_imu" : "LEGACY", "udp_profile_lidar" : "LEGACY" }, "hostname" : "10.10.80.110", "image_rev" : "ousteros-image-prod-aries-v2.2.1+20220215193703.patch-v2.2.1", "imu_to_sensor_transform" : [ 1, 0, 0, 6.2530000000000001, 0, 1, 0, -11.775, 0, 0, 1, 7.6449999999999996, 0, 0, 0, 1 ], "initialization_id" : 8247301, "json_calibration_version" : 4, "lidar_mode" : "1024x10", "lidar_origin_to_beam_origin_mm" : 15.805999999999999, "lidar_to_sensor_transform" : [ -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 36.18, 0, 0, 0, 1 ], "prod_line" : "OS-1-16", "prod_pn" : "840-103575-06", "prod_sn" : "992216000244", "proto_rev" : "", "status" : "RUNNING" }
MomentFactory/Omniverse-Lidar-Live-Synthetic-Data/source/extensions/mf.ov.lidar_live_synth/data/OusterJsonConfigOmniverse-OS1-32.json
{ "base_pn" : "", "base_sn" : "", "beam_altitude_angles" : [ 22.5, 21.0484, 19.5968, 18.1452, 16.6935, 15.2419, 13.7903, 12.3387, 10.8871, 9.43548, 7.98387, 6.53226, 5.08064, 3.62903, 2.17742, 0.725805, -0.725807, -2.17742, -3.62903, -5.08065, -6.53226, -7.98387, -9.43549, -10.8871, -12.3387, -13.7903, -15.2419, -16.6936, -18.1452, -19.5968, -21.0484, -22.5 ], "beam_azimuth_angles" : [ 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, 0, 0, 0, 0, 0, 0, 0 ], "build_date" : "2022-02-15T19:39:39Z", "build_rev" : "v2.2.1", "data_format" : { "column_window" : [ 0, 1023 ], "columns_per_frame" : 1024, "columns_per_packet" : 16, "pixel_shift_by_row" : [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], "pixels_per_column" : 32, "udp_profile_imu" : "LEGACY", "udp_profile_lidar" : "LEGACY" }, "hostname" : "10.10.80.110", "image_rev" : "ousteros-image-prod-aries-v2.2.1+20220215193703.patch-v2.2.1", "imu_to_sensor_transform" : [ 1, 0, 0, 6.2530000000000001, 0, 1, 0, -11.775, 0, 0, 1, 7.6449999999999996, 0, 0, 0, 1 ], "initialization_id" : 8247301, "json_calibration_version" : 4, "lidar_mode" : "1024x10", "lidar_origin_to_beam_origin_mm" : 15.805999999999999, "lidar_to_sensor_transform" : [ -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 36.18, 0, 0, 0, 1 ], "prod_line" : "OS-1-32", "prod_pn" : "840-103575-06", "prod_sn" : "992216000244", "proto_rev" : "", "status" : "RUNNING" }