file_path
stringlengths 21
224
| content
stringlengths 0
80.8M
|
---|---|
MomentFactory/Omniverse-NDI-extension/tools/packman/bootstrap/configure.bat | :: 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.
set PM_PACKMAN_VERSION=6.33.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 directory %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.7.9-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 rename
rename "%TEMP_FOLDER_NAME%" "%PM_PYTHON_VERSION%" 1> nul
:: Failure during move, need to clean up and abort
if %errorlevel% neq 0 (
echo !!! Error renaming python !!!
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%\packman.py
if exist "%PM_MODULE%" goto ENSURE_7ZA
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%"
:ENSURE_7ZA
set PM_7Za_VERSION=16.02.4
set PM_7Za_PATH=%PM_PACKAGES_ROOT%\7za\%PM_7ZA_VERSION%
if exist "%PM_7Za_PATH%" goto END
set PM_7Za_PATH=%PM_PACKAGES_ROOT%\chk\7za\%PM_7ZA_VERSION%
if exist "%PM_7Za_PATH%" goto END
"%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" pull "%PM_MODULE_DIR%\deps.packman.xml"
if %errorlevel% neq 0 (
echo !!! Error fetching packman dependencies !!!
goto ERROR
)
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-NDI-extension/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 and is larger than 0 bytes:
@if not exist %TARGET_PATH% goto ERROR_DOWNLOAD_FAILED
@if %~z2==0 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-NDI-extension/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 = 3
do
{
$triesLeft -= 1
try
{
Write-Host "Downloading from bootstrap.packman.nvidia.com ..."
$wc = New-Object net.webclient
$wc.Downloadfile($source, $fileName)
$triesLeft = 0
}
catch
{
Write-Host "Error downloading $source!"
Write-Host $_.Exception|format-list -force
}
} while ($triesLeft -gt 0)
|
MomentFactory/Omniverse-NDI-extension/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
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCB29nsqMEu+VmSF
# 7ckeVTPrEZ6hsXjOgPFlJm9ilgHUB6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh
# PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE
# ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0
# IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENsYXNzIDMgU0hBMjU2IENvZGUg
# U2lnbmluZyBDQSAtIEcyMB4XDTE4MDcwOTAwMDAwMFoXDTIxMDcwOTIzNTk1OVow
# gYMxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRQwEgYDVQQHDAtT
# YW50YSBDbGFyYTEbMBkGA1UECgwSTlZJRElBIENvcnBvcmF0aW9uMQ8wDQYDVQQL
# DAZJVC1NSVMxGzAZBgNVBAMMEk5WSURJQSBDb3Jwb3JhdGlvbjCCASIwDQYJKoZI
# hvcNAQEBBQADggEPADCCAQoCggEBALEZN63dA47T4i90jZ84CJ/aWUwVtLff8AyP
# YspFfIZGdZYiMgdb8A5tBh7653y0G/LZL6CVUkgejcpvBU/Dl/52a+gSWy2qJ2bH
# jMFMKCyQDhdpCAKMOUKSC9rfzm4cFeA9ct91LQCAait4LhLlZt/HF7aG+r0FgCZa
# HJjJvE7KNY9G4AZXxjSt8CXS8/8NQMANqjLX1r+F+Hl8PzQ1fVx0mMsbdtaIV4Pj
# 5flAeTUnz6+dCTx3vTUo8MYtkS2UBaQv7t7H2B7iwJDakEQKk1XHswJdeqG0osDU
# z6+NVks7uWE1N8UIhvzbw0FEX/U2kpfyWaB/J3gMl8rVR8idPj8CAwEAAaOCAT4w
# ggE6MAkGA1UdEwQCMAAwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUF
# BwMDMGEGA1UdIARaMFgwVgYGZ4EMAQQBMEwwIwYIKwYBBQUHAgEWF2h0dHBzOi8v
# ZC5zeW1jYi5jb20vY3BzMCUGCCsGAQUFBwICMBkMF2h0dHBzOi8vZC5zeW1jYi5j
# b20vcnBhMB8GA1UdIwQYMBaAFNTABiJJ6zlL3ZPiXKG4R3YJcgNYMCsGA1UdHwQk
# MCIwIKAeoByGGmh0dHA6Ly9yYi5zeW1jYi5jb20vcmIuY3JsMFcGCCsGAQUFBwEB
# BEswSTAfBggrBgEFBQcwAYYTaHR0cDovL3JiLnN5bWNkLmNvbTAmBggrBgEFBQcw
# AoYaaHR0cDovL3JiLnN5bWNiLmNvbS9yYi5jcnQwDQYJKoZIhvcNAQELBQADggEB
# AIJKh5vKJdhHJtMzATmc1BmXIQ3RaJONOZ5jMHn7HOkYU1JP0OIzb4pXXkH8Xwfr
# K6bnd72IhcteyksvKsGpSvK0PBBwzodERTAu1Os2N+EaakxQwV/xtqDm1E3IhjHk
# fRshyKKzmFk2Ci323J4lHtpWUj5Hz61b8gd72jH7xnihGi+LORJ2uRNZ3YuqMNC3
# SBC8tAyoJqEoTJirULUCXW6wX4XUm5P2sx+htPw7szGblVKbQ+PFinNGnsSEZeKz
# D8jUb++1cvgTKH59Y6lm43nsJjkZU77tNqyq4ABwgQRk6lt8cS2PPwjZvTmvdnla
# ZhR0K4of+pQaUQHXVIBdji8wggVHMIIEL6ADAgECAhB8GzU1SufbdOdBXxFpymuo
# MA0GCSqGSIb3DQEBCwUAMIG9MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNp
# Z24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNV
# BAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
# IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmlj
# YXRpb24gQXV0aG9yaXR5MB4XDTE0MDcyMjAwMDAwMFoXDTI0MDcyMTIzNTk1OVow
# gYQxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEf
# MB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazE1MDMGA1UEAxMsU3ltYW50
# ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBIC0gRzIwggEiMA0GCSqG
# SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXlUPU3N9nrjn7UqS2JjEEcOm3jlsqujdp
# NZWPu8Aw54bYc7vf69F2P4pWjustS/BXGE6xjaUz0wt1I9VqeSfdo9P3Dodltd6t
# HPH1NbQiUa8iocFdS5B/wFlOq515qQLXHkmxO02H/sJ4q7/vUq6crwjZOeWaUT5p
# XzAQTnFjbFjh8CAzGw90vlvLEuHbjMSAlHK79kWansElC/ujHJ7YpglwcezAR0yP
# fcPeGc4+7gRyjhfT//CyBTIZTNOwHJ/+pXggQnBBsCaMbwDIOgARQXpBsKeKkQSg
# mXj0d7TzYCrmbFAEtxRg/w1R9KiLhP4h2lxeffUpeU+wRHRvbXL/AgMBAAGjggF4
# MIIBdDAuBggrBgEFBQcBAQQiMCAwHgYIKwYBBQUHMAGGEmh0dHA6Ly9zLnN5bWNk
# LmNvbTASBgNVHRMBAf8ECDAGAQH/AgEAMGYGA1UdIARfMF0wWwYLYIZIAYb4RQEH
# FwMwTDAjBggrBgEFBQcCARYXaHR0cHM6Ly9kLnN5bWNiLmNvbS9jcHMwJQYIKwYB
# BQUHAgIwGRoXaHR0cHM6Ly9kLnN5bWNiLmNvbS9ycGEwNgYDVR0fBC8wLTAroCmg
# J4YlaHR0cDovL3Muc3ltY2IuY29tL3VuaXZlcnNhbC1yb290LmNybDATBgNVHSUE
# DDAKBggrBgEFBQcDAzAOBgNVHQ8BAf8EBAMCAQYwKQYDVR0RBCIwIKQeMBwxGjAY
# BgNVBAMTEVN5bWFudGVjUEtJLTEtNzI0MB0GA1UdDgQWBBTUwAYiSes5S92T4lyh
# uEd2CXIDWDAfBgNVHSMEGDAWgBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG
# 9w0BAQsFAAOCAQEAf+vKp+qLdkLrPo4gVDDjt7nc+kg+FscPRZUQzSeGo2bzAu1x
# +KrCVZeRcIP5Un5SaTzJ8eCURoAYu6HUpFam8x0AkdWG80iH4MvENGggXrTL+QXt
# nK9wUye56D5+UaBpcYvcUe2AOiUyn0SvbkMo0yF1u5fYi4uM/qkERgSF9xWcSxGN
# xCwX/tVuf5riVpLxlrOtLfn039qJmc6yOETA90d7yiW5+ipoM5tQct6on9TNLAs0
# vYsweEDgjY4nG5BvGr4IFYFd6y/iUedRHsl4KeceZb847wFKAQkkDhbEFHnBQTc0
# 0D2RUpSd4WjvCPDiaZxnbpALGpNx1CYCw8BaIzGCD4swgg+HAgEBMIGZMIGEMQsw
# CQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNV
# BAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENs
# YXNzIDMgU0hBMjU2IENvZGUgU2lnbmluZyBDQSAtIEcyAhBi50XpIWUhPJcfXEkK
# 6hKlMA0GCWCGSAFlAwQCAQUAoHwwEAYKKwYBBAGCNwIBDDECMAAwGQYJKoZIhvcN
# AQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUw
# LwYJKoZIhvcNAQkEMSIEIG5YDmcpqLxn4SB0H6OnuVkZRPh6OJ77eGW/6Su/uuJg
# MA0GCSqGSIb3DQEBAQUABIIBAA3N2vqfA6WDgqz/7EoAKVIE5Hn7xpYDGhPvFAMV
# BslVpeqE3apTcYFCEcwLtzIEc/zmpULxsX8B0SUT2VXbJN3zzQ80b+gbgpq62Zk+
# dQLOtLSiPhGW7MXLahgES6Oc2dUFaQ+wDfcelkrQaOVZkM4wwAzSapxuf/13oSIk
# ZX2ewQEwTZrVYXELO02KQIKUR30s/oslGVg77ALnfK9qSS96Iwjd4MyT7PzCkHUi
# ilwyGJi5a4ofiULiPSwUQNynSBqxa+JQALkHP682b5xhjoDfyG8laR234FTPtYgs
# P/FaeviwENU5Pl+812NbbtRD+gKlWBZz+7FKykOT/CG8sZahgg1EMIINQAYKKwYB
# BAGCNwMDATGCDTAwgg0sBgkqhkiG9w0BBwKggg0dMIINGQIBAzEPMA0GCWCGSAFl
# AwQCAQUAMHcGCyqGSIb3DQEJEAEEoGgEZjBkAgEBBglghkgBhv1sBwEwMTANBglg
# hkgBZQMEAgEFAAQgJhABfkDIPbI+nWYnA30FLTyaPK+W3QieT21B/vK+CMICEDF0
# worcGsdd7OxpXLP60xgYDzIwMjEwNDA4MDkxMTA5WqCCCjcwggT+MIID5qADAgEC
# AhANQkrgvjqI/2BAIc4UAPDdMA0GCSqGSIb3DQEBCwUAMHIxCzAJBgNVBAYTAlVT
# MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
# b20xMTAvBgNVBAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBp
# bmcgQ0EwHhcNMjEwMTAxMDAwMDAwWhcNMzEwMTA2MDAwMDAwWjBIMQswCQYDVQQG
# EwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xIDAeBgNVBAMTF0RpZ2lDZXJ0
# IFRpbWVzdGFtcCAyMDIxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
# wuZhhGfFivUNCKRFymNrUdc6EUK9CnV1TZS0DFC1JhD+HchvkWsMlucaXEjvROW/
# m2HNFZFiWrj/ZwucY/02aoH6KfjdK3CF3gIY83htvH35x20JPb5qdofpir34hF0e
# dsnkxnZ2OlPR0dNaNo/Go+EvGzq3YdZz7E5tM4p8XUUtS7FQ5kE6N1aG3JMjjfdQ
# Jehk5t3Tjy9XtYcg6w6OLNUj2vRNeEbjA4MxKUpcDDGKSoyIxfcwWvkUrxVfbENJ
# Cf0mI1P2jWPoGqtbsR0wwptpgrTb/FZUvB+hh6u+elsKIC9LCcmVp42y+tZji06l
# chzun3oBc/gZ1v4NSYS9AQIDAQABo4IBuDCCAbQwDgYDVR0PAQH/BAQDAgeAMAwG
# A1UdEwEB/wQCMAAwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwgwQQYDVR0gBDowODA2
# BglghkgBhv1sBwEwKTAnBggrBgEFBQcCARYbaHR0cDovL3d3dy5kaWdpY2VydC5j
# b20vQ1BTMB8GA1UdIwQYMBaAFPS24SAd/imu0uRhpbKiJbLIFzVuMB0GA1UdDgQW
# BBQ2RIaOpLqwZr68KC0dRDbd42p6vDBxBgNVHR8EajBoMDKgMKAuhixodHRwOi8v
# Y3JsMy5kaWdpY2VydC5jb20vc2hhMi1hc3N1cmVkLXRzLmNybDAyoDCgLoYsaHR0
# cDovL2NybDQuZGlnaWNlcnQuY29tL3NoYTItYXNzdXJlZC10cy5jcmwwgYUGCCsG
# AQUFBwEBBHkwdzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29t
# ME8GCCsGAQUFBzAChkNodHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNl
# cnRTSEEyQXNzdXJlZElEVGltZXN0YW1waW5nQ0EuY3J0MA0GCSqGSIb3DQEBCwUA
# A4IBAQBIHNy16ZojvOca5yAOjmdG/UJyUXQKI0ejq5LSJcRwWb4UoOUngaVNFBUZ
# B3nw0QTDhtk7vf5EAmZN7WmkD/a4cM9i6PVRSnh5Nnont/PnUp+Tp+1DnnvntN1B
# Ion7h6JGA0789P63ZHdjXyNSaYOC+hpT7ZDMjaEXcw3082U5cEvznNZ6e9oMvD0y
# 0BvL9WH8dQgAdryBDvjA4VzPxBFy5xtkSdgimnUVQvUtMjiB2vRgorq0Uvtc4GEk
# JU+y38kpqHNDUdq9Y9YfW5v3LhtPEx33Sg1xfpe39D+E68Hjo0mh+s6nv1bPull2
# YYlffqe0jmd4+TaY4cso2luHpoovMIIFMTCCBBmgAwIBAgIQCqEl1tYyG35B5AXa
# NpfCFTANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln
# aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtE
# aWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMTYwMTA3MTIwMDAwWhcNMzEw
# MTA3MTIwMDAwWjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5j
# MRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBT
# SEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBMIIBIjANBgkqhkiG9w0BAQEF
# AAOCAQ8AMIIBCgKCAQEAvdAy7kvNj3/dqbqCmcU5VChXtiNKxA4HRTNREH3Q+X1N
# aH7ntqD0jbOI5Je/YyGQmL8TvFfTw+F+CNZqFAA49y4eO+7MpvYyWf5fZT/gm+vj
# RkcGGlV+Cyd+wKL1oODeIj8O/36V+/OjuiI+GKwR5PCZA207hXwJ0+5dyJoLVOOo
# CXFr4M8iEA91z3FyTgqt30A6XLdR4aF5FMZNJCMwXbzsPGBqrC8HzP3w6kfZiFBe
# /WZuVmEnKYmEUeaC50ZQ/ZQqLKfkdT66mA+Ef58xFNat1fJky3seBdCEGXIX8RcG
# 7z3N1k3vBkL9olMqT4UdxB08r8/arBD13ays6Vb/kwIDAQABo4IBzjCCAcowHQYD
# VR0OBBYEFPS24SAd/imu0uRhpbKiJbLIFzVuMB8GA1UdIwQYMBaAFEXroq/0ksuC
# MS1Ri6enIZ3zbcgPMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGG
# MBMGA1UdJQQMMAoGCCsGAQUFBwMIMHkGCCsGAQUFBwEBBG0wazAkBggrBgEFBQcw
# AYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEMGCCsGAQUFBzAChjdodHRwOi8v
# Y2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3J0
# MIGBBgNVHR8EejB4MDqgOKA2hjRodHRwOi8vY3JsNC5kaWdpY2VydC5jb20vRGln
# aUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMDqgOKA2hjRodHRwOi8vY3JsMy5kaWdp
# Y2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMFAGA1UdIARJMEcw
# OAYKYIZIAYb9bAACBDAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2Vy
# dC5jb20vQ1BTMAsGCWCGSAGG/WwHATANBgkqhkiG9w0BAQsFAAOCAQEAcZUS6VGH
# VmnN793afKpjerN4zwY3QITvS4S/ys8DAv3Fp8MOIEIsr3fzKx8MIVoqtwU0HWqu
# mfgnoma/Capg33akOpMP+LLR2HwZYuhegiUexLoceywh4tZbLBQ1QwRostt1AuBy
# x5jWPGTlH0gQGF+JOGFNYkYkh2OMkVIsrymJ5Xgf1gsUpYDXEkdws3XVk4WTfraS
# Z/tTYYmo9WuWwPRYaQ18yAGxuSh1t5ljhSKMYcp5lH5Z/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-NDI-extension/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 shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/NDItools.py | from .eventsystem import EventSystem
import carb.profiler
import logging
from .deps import NDIlib as ndi
import numpy as np
import omni.ui
import threading
import time
from typing import List
import warp as wp
class NDItools():
def __init__(self):
self._ndi_ok = False
self._ndi_find = None
self._ndi_init()
self._ndi_find_init()
self._finder = None
self._create_finder()
self._streams = []
stream = omni.kit.app.get_app().get_update_event_stream()
self._sub = stream.create_subscription_to_pop(self._on_update, name="update")
def destroy(self):
self._sub.unsubscribe()
self._sub = None
self._finder.destroy()
for stream in self._streams:
stream.destroy()
self._streams.clear()
if self._ndi_ok:
if self._ndi_find is not None:
ndi.find_destroy(self._ndi_find)
ndi.destroy()
self._ndi_ok = False
def is_ndi_ok(self) -> bool:
return self._ndi_ok
def _on_update(self, e):
to_remove = []
for stream in self._streams:
if not stream.is_running():
to_remove.append(stream)
for stream in to_remove:
self._streams.remove(stream)
EventSystem.send_event(EventSystem.STREAM_STOP_TIMEOUT_EVENT, payload={"dynamic_id": stream.get_id()})
stream.destroy()
def _ndi_init(self):
if not ndi.initialize():
logger = logging.getLogger(__name__)
logger.error("Could not initialize NDI®")
return
self._ndi_ok = True
def _ndi_find_init(self):
self._ndi_find = ndi.find_create_v2()
if self._ndi_find is None:
logger = logging.getLogger(__name__)
logger.error("Could not initialize NDI® find")
return
def _create_finder(self):
if self._ndi_find:
self._finder = NDIfinder(self)
def get_ndi_find(self):
return self._ndi_find
def get_stream(self, dynamic_id):
return next((x for x in self._streams if x.get_id() == dynamic_id), None)
def try_add_stream(self, dynamic_id: str, ndi_source: str, lowbandwidth: bool,
update_fps_fn, update_dimensions_fn) -> bool:
stream: NDIVideoStream = NDIVideoStream(dynamic_id, ndi_source, lowbandwidth, self,
update_fps_fn, update_dimensions_fn)
if not stream.is_ok:
logger = logging.getLogger(__name__)
logger.error(f"Error opening stream: {ndi_source}")
return False
self._streams.append(stream)
return True
def try_add_stream_proxy(self, dynamic_id: str, ndi_source: str, fps: float,
lowbandwidth: bool) -> bool:
stream: NDIVideoStreamProxy = NDIVideoStreamProxy(dynamic_id, ndi_source, fps, lowbandwidth)
if not stream.is_ok:
logger = logging.getLogger(__name__)
logger.error(f"Error opening stream: {ndi_source}")
return False
self._streams.append(stream)
return True
def stop_stream(self, dynamic_id: str):
stream = self.get_stream(dynamic_id)
if stream is not None:
self._streams.remove(stream)
stream.destroy()
def stop_all_streams(self):
for stream in self._streams:
stream.destroy()
self._streams.clear()
class NDIfinder():
SLEEP_INTERVAL: float = 2 # seconds
def __init__(self, tools: NDItools):
self._tools = tools
self._previous_sources: List[str] = []
self._is_running = True
self._thread = threading.Thread(target=self._search)
self._thread.start()
def destroy(self):
self._is_running = False
self._thread.join()
self._thread = None
def _search(self):
find = self._tools.get_ndi_find()
if find:
while self._is_running:
sources = ndi.find_get_current_sources(find)
result = [s.ndi_name for s in sources]
delta = set(result) ^ set(self._previous_sources)
if len(delta) > 0:
self._previous_sources = result
EventSystem.send_event(EventSystem.NDIFINDER_NEW_SOURCES, payload={"sources": result})
time.sleep(NDIfinder.SLEEP_INTERVAL)
self._is_running = False
class NDIVideoStream():
NO_FRAME_TIMEOUT = 5 # seconds
def __init__(self, dynamic_id: str, ndi_source: str, lowbandwidth: bool, tools: NDItools,
update_fps_fn, update_dimensions_fn):
wp.init()
self._dynamic_id = dynamic_id
self._ndi_source = ndi_source
self._lowbandwidth = lowbandwidth
self._thread: threading.Thread = None
self._ndi_recv = None
self._update_fps_fn = update_fps_fn
self._fps_current = 0.0
self._fps_avg_total = 0.0
self._fps_avg_count = 0
self._fps_expected = 0.0
self._update_dimensions_fn = update_dimensions_fn
self.is_ok = False
if not tools.is_ndi_ok():
return
ndi_find = tools.get_ndi_find()
source = None
sources = ndi.find_get_current_sources(ndi_find)
source_candidates = [s for s in sources if s.ndi_name == self._ndi_source]
if len(source_candidates) != 0:
source = source_candidates[0]
if source is None:
logger = logging.getLogger(__name__)
logger.error(f"TIMEOUT: Could not find source at \"{self._ndi_source}\".")
return
if lowbandwidth:
recv_create_desc = self.get_recv_low_bandwidth()
else:
recv_create_desc = self.get_recv_high_bandwidth()
self._ndi_recv = ndi.recv_create_v3(recv_create_desc)
if self._ndi_recv is None:
logger = logging.getLogger(__name__)
logger.error("Could not create NDI® receiver")
return
ndi.recv_connect(self._ndi_recv, source)
self._is_running = True
self._thread = threading.Thread(target=self._update_texture, args=(self._dynamic_id, ))
self._thread.start()
self.is_ok = True
def _update_fps(self):
self._update_fps_fn(self._fps_current, self._fps_avg_total / self._fps_avg_count if self._fps_avg_count != 0 else 0, self._fps_expected)
def destroy(self):
self._update_fps()
self._is_running = False
self._thread.join()
self._thread = None
ndi.recv_destroy(self._ndi_recv)
def get_id(self) -> str:
return self._dynamic_id
def is_running(self) -> bool:
return self._is_running
def get_recv_high_bandwidth(self):
recv_create_desc = ndi.RecvCreateV3()
recv_create_desc.color_format = ndi.RECV_COLOR_FORMAT_RGBX_RGBA
recv_create_desc.bandwidth = ndi.RECV_BANDWIDTH_HIGHEST
return recv_create_desc
def get_recv_low_bandwidth(self):
recv_create_desc = ndi.RecvCreateV3()
recv_create_desc.color_format = ndi.RECV_COLOR_FORMAT_RGBX_RGBA
recv_create_desc.bandwidth = ndi.RECV_BANDWIDTH_LOWEST
return recv_create_desc
@carb.profiler.profile
def _update_texture(self, dynamic_id: str):
carb.profiler.begin(0, 'Omniverse NDI®::Init')
dynamic_texture = omni.ui.DynamicTextureProvider(dynamic_id)
last_read = time.time() - 1 # Make sure we run on the first frame
fps = 120.0
no_frame_chances = NDIVideoStream.NO_FRAME_TIMEOUT * fps
index = 0
self._fps_avg_total = 0.0
self._fps_avg_count = 0
carb.profiler.end(0)
while self._is_running:
carb.profiler.begin(1, 'Omniverse NDI®::loop outer')
now = time.time()
time_delta = now - last_read
if (time_delta < 1.0 / fps):
carb.profiler.end(1)
continue
carb.profiler.begin(2, 'Omniverse NDI®::loop inner')
self._fps_current = 1.0 / time_delta
last_read = now
carb.profiler.begin(3, 'Omniverse NDI®::receive frame')
t, v, _, _ = ndi.recv_capture_v2(self._ndi_recv, 0)
carb.profiler.end(3)
if t == ndi.FRAME_TYPE_VIDEO:
carb.profiler.begin(3, 'Omniverse NDI®::prepare frame')
fps = v.frame_rate_N / v.frame_rate_D
self._fps_expected = fps
if (index == 0):
self._fps_current = fps
color_format = v.FourCC
frame = v.data
height, width, channels = frame.shape
isGPU = height == width
carb.profiler.end(3)
if isGPU:
carb.profiler.begin(3, 'Omniverse NDI®::begin gpu')
with wp.ScopedDevice("cuda"):
# CUDA doesnt handle non square texture well, so we need to resize if the te
# We are keeping this code in case we find a workaround
#
# carb.profiler.begin(4, 'Omniverse NDI®::begin cpu resize')
# frame = np.resize(frame, (width, width, channels))
# carb.profiler.end(4)
# 38 ms
carb.profiler.begin(4, 'Omniverse NDI®::gpu uploading')
pixels_data = wp.from_numpy(frame, dtype=wp.uint8, device="cuda")
carb.profiler.end(4)
# 1 ms
carb.profiler.begin(4, 'Omniverse NDI®::create gpu texture')
self._update_dimensions_fn(width, height, str(color_format))
dynamic_texture.set_bytes_data_from_gpu(pixels_data.ptr, [width, width])
carb.profiler.end(4)
carb.profiler.end(3)
else:
carb.profiler.begin(3, 'Omniverse NDI®::begin cpu')
self._update_dimensions_fn(width, height, str(color_format))
dynamic_texture.set_data_array(frame, [width, height, channels])
carb.profiler.end(3)
ndi.recv_free_video_v2(self._ndi_recv, v)
carb.profiler.end(3)
self._fps_avg_total += self._fps_current
self._fps_avg_count += 1
self._update_fps()
index += 1
if t == ndi.FRAME_TYPE_NONE:
no_frame_chances -= 1
if (no_frame_chances <= 0):
self._is_running = False
else:
no_frame_chances = NDIVideoStream.NO_FRAME_TIMEOUT * fps
carb.profiler.end(2)
carb.profiler.end(1)
class NDIVideoStreamProxy():
def __init__(self, dynamic_id: str, ndi_source: str, fps: float, lowbandwidth: bool):
self._dynamic_id = dynamic_id
self._ndi_source = ndi_source
self._fps = fps
self._lowbandwidth = lowbandwidth
self._thread: threading.Thread = None
self.is_ok = False
denominator = 1
if lowbandwidth:
denominator = 3
w = int(1920 / denominator) # TODO: dimensions from name like for fps
h = int(1080 / denominator)
self._is_running = True
self._thread = threading.Thread(target=self._update_texture, args=(self._dynamic_id, self._fps, w, h, ))
self._thread.start()
self.is_ok = True
def destroy(self):
self._is_running = False
self._thread.join()
self._thread = None
def get_id(self) -> str:
return self._dynamic_id
def is_running(self) -> bool:
return self._is_running
@carb.profiler.profile
def _update_texture(self, dynamic_id: str, fps: float, width: float, height: float):
carb.profiler.begin(0, 'Omniverse NDI®::Init')
color = np.array([255, 0, 0, 255], np.uint8)
channels = len(color)
dynamic_texture = omni.ui.DynamicTextureProvider(dynamic_id)
frame = np.full((height, width, channels), color, dtype=np.uint8)
last_read = time.time() - 1
carb.profiler.end(0)
while self._is_running:
carb.profiler.begin(1, 'Omniverse NDI®::Proxy loop outer')
now = time.time()
time_delta = now - last_read
if (time_delta < 1.0 / fps):
carb.profiler.end(1)
continue
carb.profiler.begin(2, 'Omniverse NDI®::Proxy loop inner')
last_read = now
carb.profiler.begin(3, 'Omniverse NDI®::set_data')
dynamic_texture.set_data_array(frame, [width, height, channels])
carb.profiler.end(3)
carb.profiler.end(2)
carb.profiler.end(1)
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/extension.py | from .window import Window
import asyncio
import omni.ext
import omni.kit.app
import omni.kit.ui
class MFOVNdiExtension(omni.ext.IExt):
MENU_PATH = f"Window/{Window.WINDOW_NAME}"
def on_startup(self, _):
self._menu = None
self._window: Window = None
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(
MFOVNdiExtension.MENU_PATH, self._show_window, toggle=True, value=True
)
self._show_window(None, True)
def on_shutdown(self):
if self._menu:
self._menu = None
if self._window:
self._destroy_window()
def _destroy_window(self):
self._window.destroy()
self._window = None
def _set_menu(self, visible):
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(MFOVNdiExtension.MENU_PATH, visible)
async def _destroy_window_async(self):
await omni.kit.app.get_app().next_update_async()
if self._window:
self._destroy_window()
def _visibility_changed_fn(self, visible):
self._set_menu(visible)
if not visible:
asyncio.ensure_future(self._destroy_window_async())
def _show_window(self, _, value):
if value:
self._window = Window(width=800, height=275)
self._window.set_visibility_changed_fn(self._visibility_changed_fn)
elif self._window:
self._destroy_window()
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/__init__.py | from .extension import *
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/model.py | from .bindings import Binding, BindingsModel
from .comboboxModel import ComboboxModel
from .NDItools import NDItools
from .USDtools import DynamicPrim, USDtools
import logging
import re
from typing import List
class Model():
def __init__(self):
self._bindings_model: BindingsModel = BindingsModel()
self._ndi: NDItools = NDItools()
def destroy(self):
self._ndi.destroy()
self._bindings_model.destroy()
# region bindings
def get_bindings_count(self) -> int:
return self._bindings_model.count()
def get_binding_data_from_index(self, index: int):
return self._bindings_model.get(index)
def get_ndi_source_list(self) -> List[str]:
return self._bindings_model.get_source_list()
def apply_new_binding_source(self, dynamic_id: str, new_source: str):
self._bindings_model.bind(dynamic_id, new_source)
def apply_lowbandwidth_value(self, dynamic_id: str, value: bool):
self._bindings_model.set_low_bandwidth(dynamic_id, value)
# endregion
# region dynamic
def create_dynamic_material(self, name: str):
safename = USDtools.make_name_valid(name)
if name != safename:
logger = logging.getLogger(__name__)
logger.warn(f"Name \"{name}\" was not a valid USD identifier, changed it to \"{safename}\"")
final_name = safename
index = 1
while (self._bindings_model.find_binding_from_id(final_name) is not None):
suffix = str(index) if index >= 10 else "0" + str(index) # name, name_01, name_02, ..., name_99, name_100
final_name = safename + "_" + suffix
index += 1
USDtools.create_dynamic_material(final_name)
self.search_for_dynamic_material()
def search_for_dynamic_material(self):
result: List[DynamicPrim] = USDtools.find_all_dynamic_sources()
self._bindings_model.update_dynamic_prims(result)
def _get_prims_with_id(self, dynamic_id: str) -> List[DynamicPrim]:
prims: List[DynamicPrim] = self._bindings_model.get_prim_list()
return [x for x in prims if x.dynamic_id == dynamic_id]
def set_ndi_source_prim_attr(self, dynamic_id: str, source: str):
for prim in self._get_prims_with_id(dynamic_id):
USDtools.set_prim_ndi_attribute(prim.path, source)
def set_lowbandwidth_prim_attr(self, dynamic_id: str, value: bool):
for prim in self._get_prims_with_id(dynamic_id):
USDtools.set_prim_lowbandwidth_attribute(prim.path, value)
# endregion
# region stream
def try_add_stream(self, binding: Binding, lowbandwidth: bool, update_fps_fn, update_dimensions_fn) -> bool:
if self._ndi.get_stream(binding.dynamic_id) is not None:
logger = logging.getLogger(__name__)
logger.warning(f"There's already a stream running for {binding.dynamic_id}")
return False
if binding.ndi_source == ComboboxModel.NONE_VALUE:
logger = logging.getLogger(__name__)
logger.warning("Won't create stream without NDI® source")
return False
if binding.ndi_source == ComboboxModel.PROXY_VALUE:
fps = float(re.search("\((.*)\)", binding.ndi_source).group(1).split("p")[1])
success: bool = self._ndi.try_add_stream_proxy(binding.dynamic_id, binding.ndi_source, fps, lowbandwidth)
return success
else:
success: bool = self._ndi.try_add_stream(binding.dynamic_id, binding.ndi_source, lowbandwidth,
update_fps_fn, update_dimensions_fn)
return success
def stop_stream(self, binding: Binding):
self._ndi.stop_stream(binding.dynamic_id)
def stop_all_streams(self):
self._ndi.stop_all_streams()
# endregion
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/eventsystem.py | import carb.events
import omni.kit.app
class EventSystem():
BINDINGS_CHANGED_EVENT = carb.events.type_from_string("mf.ov.ndi.BINDINGS_CHANGED_EVENT")
COMBOBOX_CHANGED_EVENT = carb.events.type_from_string("mf.ov.ndi.COMBOBOX_CHANGED_EVENT")
NDIFINDER_NEW_SOURCES = carb.events.type_from_string("mf.ov.ndi.NDIFINDER_NEW_SOURCES")
COMBOBOX_SOURCE_CHANGE_EVENT = carb.events.type_from_string("mf.ov.ndi.COMBOBOX_SOURCE_CHANGE_EVENT")
NDI_STATUS_CHANGE_EVENT = carb.events.type_from_string("mf.ov.ndi.NDI_STATUS_CHANGE_EVENT")
STREAM_STOP_TIMEOUT_EVENT = carb.events.type_from_string("mf.ov.ndi.STREAM_STOP_TIMEOUT_EVENT")
def subscribe(event: int, cb: callable) -> carb.events.ISubscription:
bus = omni.kit.app.get_app().get_message_bus_event_stream()
return bus.create_subscription_to_push_by_type(event, cb)
def send_event(event: int, payload: dict = {}):
bus = omni.kit.app.get_app().get_message_bus_event_stream()
bus.push(event, payload=payload)
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/USDtools.py | from .bindings import DynamicPrim
import logging
import numpy as np
import omni.ext
from pxr import Usd, UsdGeom, UsdShade, Sdf, UsdLux, Tf
from typing import List
from unidecode import unidecode
class USDtools():
ATTR_NDI_NAME = 'ndi:source'
ATTR_BANDWIDTH_NAME = "ndi:lowbandwidth"
PREFIX = "dynamic://"
SCOPE_NAME = "NDI_Looks"
def get_stage() -> Usd.Stage:
usd_context = omni.usd.get_context()
return usd_context.get_stage()
def make_name_valid(name: str) -> str:
return Tf.MakeValidIdentifier(unidecode(name))
def create_dynamic_material(safename: str):
stage = USDtools.get_stage()
if not stage:
logger = logging.getLogger(__name__)
logger.error("Could not get stage")
return
scope_path: str = f"{stage.GetDefaultPrim().GetPath()}/{USDtools.SCOPE_NAME}"
UsdGeom.Scope.Define(stage, scope_path)
USDtools._create_material_and_shader(stage, scope_path, safename)
USDtools._fill_dynamic_with_magenta(safename)
def _create_material_and_shader(stage: Usd.Stage, scope_path: str, safename: str):
material_path = f"{scope_path}/{safename}"
material: UsdShade.Material = UsdShade.Material.Define(stage, material_path)
shader: UsdShade.Shader = UsdShade.Shader.Define(stage, f"{material_path}/Shader")
shader.SetSourceAsset("OmniPBR.mdl", "mdl")
shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl")
shader.CreateIdAttr("OmniPBR")
shader.CreateInput("diffuse_texture", Sdf.ValueTypeNames.Asset).Set(f"{USDtools.PREFIX}{safename}")
material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface")
def _fill_dynamic_with_magenta(safename: str):
magenta = np.array([255, 0, 255, 255], np.uint8)
frame = np.full((1, 1, 4), magenta, dtype=np.uint8)
height, width, channels = frame.shape
dynamic_texture = omni.ui.DynamicTextureProvider(safename)
dynamic_texture.set_data_array(frame, [width, height, channels])
def find_all_dynamic_sources() -> List[DynamicPrim]:
stage = USDtools.get_stage()
if not stage:
logger = logging.getLogger(__name__)
logger.warning("Could not get stage")
return []
dynamic_sources: List[str] = []
dynamic_shaders, dynamic_sources = USDtools._find_all_dynamic_shaders(stage, dynamic_sources)
dynamic_lights, _ = USDtools._find_all_dynamic_lights(stage, dynamic_sources)
return dynamic_shaders + dynamic_lights
def _find_all_dynamic_shaders(stage: Usd.Stage, sources: List[str]):
shaders: List[UsdShade.Shader] = [UsdShade.Shader(x) for x in stage.Traverse() if x.IsA(UsdShade.Shader)]
result: List[DynamicPrim] = []
prefix_length: int = len(USDtools.PREFIX)
for shader in shaders:
albedo = shader.GetInput("diffuse_texture").Get()
# roughness = shader.GetInput("reflectionroughness_texture").Get()
# metallic = shader.GetInput("metallic_texture").Get()
# orm = shader.GetInput("ORM_texture").Get()
# ambient_occlusion = shader.GetInput("ao_texture").Get()
emissive = shader.GetInput("emissive_color_texture").Get()
# emissive_mask = shader.GetInput("emissive_mask_texture").Get()
# opacity = shader.GetInput("opacity_texture").Get()
# normal = shader.GetInput("normalmap_texture").Get()
# normal_detail = shader.GetInput("detail_normalmap_texture").Get()
values_set = set([albedo, emissive])
values_unique = list(values_set)
for texture_value in values_unique:
if texture_value:
path: str = texture_value.path
if len(path) > prefix_length:
candidate = path[:prefix_length]
if candidate == USDtools.PREFIX:
name = path[prefix_length:]
if name not in sources:
sources.append(name)
attr_ndi = shader.GetPrim().GetAttribute(USDtools.ATTR_NDI_NAME)
attr_ndi = attr_ndi.Get() if attr_ndi.IsValid() else None
attr_low = shader.GetPrim().GetAttribute(USDtools.ATTR_BANDWIDTH_NAME)
attr_low = attr_low.Get() if attr_low.IsValid() else False
p = DynamicPrim(shader.GetPath().pathString, name, attr_ndi, attr_low)
result.append(p)
return result, sources
def _find_all_dynamic_lights(stage: Usd.Stage, sources: List[str]):
rect_lights: List[UsdLux.Rectlight] = [UsdLux.RectLight(x) for x in stage.Traverse() if x.IsA(UsdLux.RectLight)]
result: List[DynamicPrim] = []
prefix_length: int = len(USDtools.PREFIX)
for rect_light in rect_lights:
# TODO: Filter those that have "isProjector" (the attribute doesn't exist)
attribute = rect_light.GetPrim().GetAttribute("texture:file").Get()
if attribute:
path: str = attribute.path
if len(path) > prefix_length:
candidate = path[:prefix_length]
if candidate == USDtools.PREFIX:
name = path[prefix_length:]
if name not in sources:
attr_ndi = rect_light.GetPrim().GetAttribute(USDtools.ATTR_NDI_NAME)
attr_ndi = attr_ndi.Get() if attr_ndi.IsValid() else None
attr_low = rect_light.GetPrim().GetAttribute(USDtools.ATTR_BANDWIDTH_NAME)
attr_low = attr_low.Get() if attr_low.IsValid() else False
p = DynamicPrim(rect_light.GetPath().pathString, name, attr_ndi, attr_low)
result.append(p)
return result, sources
def set_prim_ndi_attribute(path: str, value: str):
stage = USDtools.get_stage()
if not stage:
logger = logging.getLogger(__name__)
logger.error("Could not get stage")
return
prim: Usd.Prim = stage.GetPrimAtPath(path)
if not prim.IsValid():
logger = logging.getLogger(__name__)
logger.error(f"Could not set the ndi attribute of prim at {path}")
return
prim.CreateAttribute(USDtools.ATTR_NDI_NAME, Sdf.ValueTypeNames.String).Set(value)
def set_prim_lowbandwidth_attribute(path: str, value: bool):
stage = USDtools.get_stage()
if not stage:
logger = logging.getLogger(__name__)
logger.error("Could not get stage")
return
prim: Usd.Prim = stage.GetPrimAtPath(path)
if not prim.IsValid():
logger = logging.getLogger(__name__)
logger.error(f"Could not set the bandwidth attribute of prim at {path}")
prim.CreateAttribute(USDtools.ATTR_BANDWIDTH_NAME, Sdf.ValueTypeNames.Bool).Set(value)
# region stage events
def subscribe_to_stage_events(callback):
return (
omni.usd.get_context()
.get_stage_event_stream()
.create_subscription_to_pop(callback, name="mf.ov.ndi.STAGE_EVENT")
)
def is_StageEventType_OPENED(type) -> bool:
return type == int(omni.usd.StageEventType.OPENED)
def is_StageEventType_CLOSE(type) -> bool:
return type == int(omni.usd.StageEventType.CLOSING) or type == int(omni.usd.StageEventType.CLOSED)
# endregion
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/comboboxModel.py | from .eventsystem import EventSystem
import omni.ui as ui
from typing import List
class ComboboxItem(ui.AbstractItem):
def __init__(self, value: str):
super().__init__()
self.model = ui.SimpleStringModel(value)
def value(self):
return self.model.get_value_as_string()
class ComboboxModel(ui.AbstractItemModel):
NONE_VALUE = "NONE"
PROXY_VALUE = "PROXY (1080p30) - RED"
def __init__(self, items: List[str], selected: str, name: str, index: int):
super().__init__()
self._name = name
self._index = index
# minimal model implementation
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(lambda a: self._current_index_changed_fn())
self.set_items_and_current(items, selected)
def _current_index_changed_fn(self):
self._item_changed(None)
EventSystem.send_event(EventSystem.COMBOBOX_CHANGED_EVENT,
payload={"id": self._name, "index": self._index, "value": self._current_value()})
def set_items_and_current(self, items: List[str], current: str):
self._items = [ComboboxItem(text) for text in items]
self._set_current_from_value(current)
def _set_current_from_value(self, current: str):
index = next((i for i, item in enumerate(self._items) if item.value() == current), 0)
self._current_index.set_value(index)
self._item_changed(None)
def _current_value(self) -> str:
current_item = self._items[self._current_index.get_value_as_int()]
return current_item.value()
# minimal model implementation
def get_item_children(self, item):
return self._items
# minimal model implementation
def get_item_value_model(self, item, _):
if item is None:
return self._current_index
return item.model
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/window.py | from .bindings import Binding
from .comboboxModel import ComboboxModel
from .eventsystem import EventSystem
from .model import Model
from .USDtools import USDtools
import asyncio
import carb.events
import omni.ui as ui
import omni.kit.app
import pyperclip
from typing import List
class Window(ui.Window):
WINDOW_NAME = "NDI®"
DEFAULT_TEXTURE_NAME = "myDynamicMaterial"
NEW_TEXTURE_BTN_TXT = "Create Dynamic Texture"
DISCOVER_TEX_BTN_TXT = "Discover Dynamic Textures"
STOP_STREAMS_BTN_TXT = "Stop all streams"
EMPTY_TEXTURE_LIST_TXT = "No dynamic texture found"
def __init__(self, delegate=None, **kwargs):
self._model: Model = Model()
self._bindingPanels: List[BindingPanel] = []
self._last_material_name = Window.DEFAULT_TEXTURE_NAME
super().__init__(Window.WINDOW_NAME, **kwargs)
self.frame.set_build_fn(self._build_fn)
self._subscribe()
self._model.search_for_dynamic_material()
def destroy(self):
for panel in self._bindingPanels:
panel.destroy()
self._model.destroy()
self._unsubscribe()
super().destroy()
def _subscribe(self):
self._sub: List[carb.events.ISubscription] = []
self._sub.append(EventSystem.subscribe(EventSystem.BINDINGS_CHANGED_EVENT, self._bindings_updated_evt_callback))
self._sub.append(EventSystem.subscribe(EventSystem.COMBOBOX_CHANGED_EVENT, self._combobox_changed_evt_callback))
self._sub.append(EventSystem.subscribe(EventSystem.COMBOBOX_SOURCE_CHANGE_EVENT,
self._ndi_sources_changed_evt_callback))
self._sub.append(EventSystem.subscribe(EventSystem.NDI_STATUS_CHANGE_EVENT,
self._ndi_status_change_evt_callback))
self._sub.append(EventSystem.subscribe(EventSystem.STREAM_STOP_TIMEOUT_EVENT,
self._stream_stop_timeout_evt_callback))
self._sub.append(USDtools.subscribe_to_stage_events(self._stage_event_evt_callback))
def _unsubscribe(self):
for sub in self._sub:
sub.unsubscribe()
sub = None
self._sub.clear()
def _build_fn(self):
with ui.VStack(style={"margin": 3}):
self._ui_section_header()
self._ui_section_bindings()
# region events callback
def _bindings_updated_evt_callback(self, e: carb.events.IEvent):
self.frame.rebuild()
def _combobox_changed_evt_callback(self, e: carb.events.IEvent):
value: str = e.payload["value"]
dynamic_id = e.payload["id"]
panel_index = e.payload["index"]
self._model.apply_new_binding_source(dynamic_id, value)
self._model.set_ndi_source_prim_attr(dynamic_id, value)
if (len(self._bindingPanels) > panel_index):
self._bindingPanels[panel_index].combobox_item_changed()
def _ndi_sources_changed_evt_callback(self, e: carb.events.IEvent):
for panel in self._bindingPanels:
panel.combobox_items_changed(e.payload["sources"])
def _ndi_status_change_evt_callback(self, e: carb.events.IEvent):
for panel in self._bindingPanels:
panel.check_for_ndi_status()
def _stream_stop_timeout_evt_callback(self, e: carb.events.IEvent):
panel: BindingPanel = next(x for x in self._bindingPanels if x.get_dynamic_id() == e.payload["dynamic_id"])
panel.on_stop_stream()
def _stage_event_evt_callback(self, e: carb.events.IEvent):
if USDtools.is_StageEventType_OPENED(e.type):
self._model.search_for_dynamic_material()
self._model.stop_all_streams()
if USDtools.is_StageEventType_CLOSE(e.type):
self._model.stop_all_streams()
# endregion
# region UI
def _ui_section_header(self):
button_style = {"Button": {"stack_direction": ui.Direction.LEFT_TO_RIGHT}}
with ui.HStack(height=0):
self._dynamic_name = ui.StringField()
self._dynamic_name.model.set_value(self._last_material_name)
ui.Button(Window.NEW_TEXTURE_BTN_TXT, image_url="resources/glyphs/menu_plus.svg", image_width=24,
style=button_style, clicked_fn=self._on_click_create_dynamic_material)
with ui.HStack(height=0):
ui.Button(Window.DISCOVER_TEX_BTN_TXT, image_url="resources/glyphs/menu_refresh.svg", image_width=24,
style=button_style, clicked_fn=self._on_click_refresh_materials)
ui.Button(Window.STOP_STREAMS_BTN_TXT, clicked_fn=self._on_click_stop_all_streams)
def _ui_section_bindings(self):
self._bindingPanels = []
with ui.ScrollingFrame():
with ui.VStack():
count: int = self._model.get_bindings_count()
if count == 0:
ui.Label(Window.EMPTY_TEXTURE_LIST_TXT)
else:
for i in range(count):
self._bindingPanels.append(BindingPanel(i, self, height=0))
# endregion
# region controls
def _on_click_create_dynamic_material(self):
self._stop_all_streams()
name: str = self._dynamic_name.model.get_value_as_string()
self._last_material_name = name
self._model.create_dynamic_material(name)
def _on_click_refresh_materials(self):
self._stop_all_streams()
self._model.search_for_dynamic_material()
def _on_click_stop_all_streams(self):
self._stop_all_streams()
def _stop_all_streams(self):
self._model.stop_all_streams()
for panel in self._bindingPanels:
panel.on_stop_stream()
# endregion
# region BindingPanel Callable
def get_binding_data_from_index(self, index: int):
return self._model.get_binding_data_from_index(index)
def get_choices_for_combobox(self) -> List[str]:
return self._model.get_ndi_source_list()
def apply_lowbandwidth_value(self, dynamic_id: str, value: bool):
self._model.apply_lowbandwidth_value(dynamic_id, value)
self._model.set_lowbandwidth_prim_attr(dynamic_id, value)
def try_add_stream(self, binding: Binding, lowbandwidth: bool, update_fps_fn, update_dimensions_fn) -> bool:
return self._model.try_add_stream(binding, lowbandwidth, update_fps_fn, update_dimensions_fn)
def stop_stream(self, binding: Binding):
return self._model.stop_stream(binding)
# endregion
class BindingPanel(ui.CollapsableFrame):
NDI_COLOR_STOPPED = "#E6E7E8"
NDI_COLOR_PLAYING = "#78B159"
NDI_COLOR_WARNING = "#F4900C"
NDI_COLOR_INACTIVE = "#DD2E45"
NDI_STATUS = "resources/glyphs/circle.svg"
PLAY_ICON = "resources/glyphs/timeline_play.svg"
PAUSE_ICON = "resources/glyphs/toolbar_pause.svg"
COPY_ICON = "resources/glyphs/copy.svg"
LOW_BANDWIDTH_ICON = "resources/glyphs/AOV_dark.svg"
PLAYPAUSE_BTN_NAME = "play_pause_btn"
BANDWIDTH_BTN_NAME = "low_bandwidth_btn"
COPYPATH_BTN_NAME = "copy_path_btn"
RUNNING_LABEL_SUFFIX = " - running"
def __init__(self, index: int, window: Window, **kwargs):
self._index = index
self._window = window
binding, _, ndi = self._get_data()
choices = self._get_choices()
self._dynamic_id = binding.dynamic_id
self._lowbandwidth_value = binding.lowbandwidth
self._is_playing = False
super().__init__(binding.dynamic_id, **kwargs)
self._info_window = None
with self:
with ui.HStack():
self._status_icon = ui.Image(BindingPanel.NDI_STATUS, width=20,
mouse_released_fn=self._show_info_window)
self._set_ndi_status_icon(ndi.active)
self._combobox_alt = ui.Label("")
self._set_combobox_alt_text(binding.ndi_source)
self._combobox_alt.visible = False
self._combobox = ComboboxModel(choices, binding.ndi_source, binding.dynamic_id, self._index)
self._combobox_ui = ui.ComboBox(self._combobox)
self.play_pause_toolbutton = ui.Button(text="", image_url=BindingPanel.PLAY_ICON, height=30,
width=30, clicked_fn=self._on_click_play_pause_ndi,
name=BindingPanel.PLAYPAUSE_BTN_NAME)
self._lowbandwidth_toolbutton = ui.ToolButton(image_url=BindingPanel.LOW_BANDWIDTH_ICON, width=30,
height=30, tooltip="Low bandwidth mode",
clicked_fn=self._set_low_bandwidth_value,
name=BindingPanel.BANDWIDTH_BTN_NAME)
self._lowbandwidth_toolbutton.model.set_value(self._lowbandwidth_value)
ui.Button("", image_url=BindingPanel.COPY_ICON, width=30, height=30, clicked_fn=self._on_click_copy,
tooltip="Copy dynamic texture path(dynamic://*)", name=BindingPanel.COPYPATH_BTN_NAME)
def destroy(self):
self._info_window_destroy()
# region Info Window
def _show_info_window(self, _x, _y, button, _modifier):
if (button == 0): # left click
binding, _, _ = self._get_data()
if not self._info_window:
self._info_window = StreamInfoWindow(f"{self._dynamic_id} info", binding.ndi_source,
width=280, height=200)
self._info_window.set_visibility_changed_fn(self._info_window_visibility_changed)
elif self._info_window:
self._info_window_destroy()
def _info_window_visibility_changed(self, visible):
if not visible:
asyncio.ensure_future(self._info_window_destroy_async())
def _info_window_destroy(self):
if self._info_window:
self._info_window.destroy()
self._info_window = None
async def _info_window_destroy_async(self):
await omni.kit.app.get_app().next_update_async()
if self._info_window:
self._info_window_destroy()
def update_fps(self, fps_current: float, fps_average: float, fps_expected: float):
if self._info_window:
self._info_window.set_fps_values(fps_current, fps_average, fps_expected)
def update_details(self, width: int, height: int, color_format: str):
if self._info_window:
self._info_window.set_stream_details(width, height, color_format)
# endregion
def combobox_items_changed(self, items: List[str]):
binding, _, _ = self._get_data()
self._combobox.set_items_and_current(items, binding.ndi_source)
def check_for_ndi_status(self):
_, _, ndi = self._get_data()
self._set_ndi_status_icon(ndi.active)
def combobox_item_changed(self):
binding, _, ndi = self._get_data()
self._set_combobox_alt_text(binding.ndi_source)
self._set_ndi_status_icon(ndi.active)
if self._info_window:
self._info_window.set_stream_name(binding.ndi_source)
def get_dynamic_id(self) -> str:
return self._dynamic_id
def _get_data(self):
return self._window.get_binding_data_from_index(self._index)
def _get_choices(self):
return self._window.get_choices_for_combobox()
def _on_click_copy(self):
pyperclip.copy(f"{USDtools.PREFIX}{self._dynamic_id}")
def _set_low_bandwidth_value(self):
self._lowbandwidth_value = not self._lowbandwidth_value
self._window.apply_lowbandwidth_value(self._dynamic_id, self._lowbandwidth_value)
def _on_play_stream(self):
self._is_playing = True
self.play_pause_toolbutton.image_url = BindingPanel.PAUSE_ICON
self._lowbandwidth_toolbutton.enabled = False
self._combobox_ui.visible = False
self._combobox_alt.visible = True
self.check_for_ndi_status()
def on_stop_stream(self):
self._is_playing = False
self.play_pause_toolbutton.image_url = BindingPanel.PLAY_ICON
self._lowbandwidth_toolbutton.enabled = True
self._combobox_ui.visible = True
self._combobox_alt.visible = False
self.check_for_ndi_status()
def _on_click_play_pause_ndi(self):
binding, _, _ = self._get_data()
if self._is_playing:
self._window.stop_stream(binding)
self.on_stop_stream()
else:
if self._window.try_add_stream(binding, self._lowbandwidth_value, self.update_fps, self.update_details):
self._on_play_stream()
def _set_combobox_alt_text(self, text: str):
self._combobox_alt.text = f"{text}{BindingPanel.RUNNING_LABEL_SUFFIX}"
def _set_ndi_status_icon(self, active: bool):
if active and self._is_playing:
self._status_icon.style = {"color": ui.color(BindingPanel.NDI_COLOR_PLAYING)}
elif active and not self._is_playing:
self._status_icon.style = {"color": ui.color(BindingPanel.NDI_COLOR_STOPPED)}
elif not active and self._is_playing:
self._status_icon.style = {"color": ui.color(BindingPanel.NDI_COLOR_WARNING)}
else: # not active and not self._is_playing
self._status_icon.style = {"color": ui.color(BindingPanel.NDI_COLOR_INACTIVE)}
class StreamInfoWindow(ui.Window):
def __init__(self, dynamic_id: str, ndi_id: str, delegate=None, **kwargs):
super().__init__(dynamic_id, **kwargs)
self.frame.set_build_fn(self._build_fn)
self._stream_name = ndi_id
def destroy(self):
super().destroy()
def _build_fn(self):
with ui.VStack(height=0):
with ui.HStack():
ui.Label("Stream name:")
self._stream_name_model = ui.StringField(enabled=False).model
self._stream_name_model.set_value(self._stream_name)
with ui.HStack():
ui.Label("Current fps:")
self._fps_current_model = ui.FloatField(enabled=False).model
self._fps_current_model.set_value(0.0)
with ui.HStack():
ui.Label("Average fps:")
self._fps_average_model = ui.FloatField(enabled=False).model
self._fps_average_model.set_value(0.0)
with ui.HStack():
ui.Label("Expected fps:")
self._fps_expected_model = ui.FloatField(enabled=False).model
self._fps_expected_model.set_value(0.0)
with ui.HStack():
ui.Label("Width:")
self._dimensions_width_model = ui.IntField(enabled=False).model
self._dimensions_width_model.set_value(0)
with ui.HStack():
ui.Label("Height:")
self._dimensions_height_model = ui.IntField(enabled=False).model
self._dimensions_height_model.set_value(0)
with ui.HStack():
ui.Label("Color format:")
self._color_format_model = ui.StringField(enabled=False).model
self._color_format_model.set_value("")
def set_fps_values(self, fps_current: float, fps_average: float, fps_expected: float):
# If this property exists, all the other do as well since its the last one to be initialized
if hasattr(self, "_fps_expected_model"):
self._fps_current_model.set_value(fps_current)
self._fps_average_model.set_value(fps_average)
self._fps_expected_model.set_value(fps_expected)
def set_stream_name(self, name: str):
# No need to check if attribute exists because no possibility of concurrency between build fn and caller
self._stream_name_model.set_value(name)
# Reset other values
self._fps_current_model.set_value(0.0)
self._fps_average_model.set_value(0.0)
self._fps_expected_model.set_value(0.0)
self._dimensions_width_model.set_value(0)
self._dimensions_height_model.set_value(0)
self._color_format_model.set_value("")
def set_stream_details(self, width: int, height: int, color_format: str):
if hasattr(self, "_color_format_model"):
self._dimensions_width_model.set_value(width)
self._dimensions_height_model.set_value(height)
# Original format is similar to FourCCVideoType.FOURCC_VIDEO_TYPE_RGBA, we want to display only "RGBA"
color_format_simple = color_format.split("_")[-1]
self._color_format_model.set_value(color_format_simple)
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/bindings.py | from .comboboxModel import ComboboxModel
from .eventsystem import EventSystem
import carb.events
from dataclasses import dataclass
from typing import List
@dataclass
class DynamicPrim:
path: str
dynamic_id: str
ndi_source_attr: str
lowbandwidth_attr: bool
@dataclass
class Binding():
dynamic_id: str
ndi_source: str
lowbandwidth: bool
@dataclass
class NDIData():
source: str
active: bool
class BindingsModel():
NONE_DATA = NDIData(ComboboxModel.NONE_VALUE, False)
def __init__(self):
self._bindings: List[Binding] = []
self._dynamic_prims: List[DynamicPrim] = []
self._ndi_sources: List[NDIData] = []
self._ndi_sources.append(BindingsModel.NONE_DATA)
self._sub = EventSystem.subscribe(EventSystem.NDIFINDER_NEW_SOURCES, self._ndi_sources_change_evt_callback)
def destroy(self):
self._sub.unsubscribe()
self._sub = None
self._dynamic_prims = []
self._bindings = []
self._ndi_sources = []
def count(self):
return len(self._bindings)
def get(self, index: int) -> Binding:
binding: Binding = self._bindings[index]
prim: DynamicPrim = self.find_binding_from_id(binding.dynamic_id)
ndi: NDIData = self._find_ndi_from_source(binding.ndi_source)
return binding, prim, ndi
def get_source_list(self) -> List[str]:
return [x.source for x in self._ndi_sources]
def _get_non_static_source_list(self) -> List[NDIData]:
return self._ndi_sources[1:] # Excludes NONE_DATA
def get_prim_list(self) -> List[str]:
return [x for x in self._dynamic_prims]
def bind(self, dynamic_id, new_source):
binding: Binding = self.find_binding_from_id(dynamic_id)
binding.ndi_source = new_source
def set_low_bandwidth(self, dynamic_id: str, value: bool):
binding: Binding = self.find_binding_from_id(dynamic_id)
binding.lowbandwidth = value
def find_binding_from_id(self, dynamic_id: str) -> Binding:
return next((x for x in self._bindings if x.dynamic_id == dynamic_id), None)
def _find_binding_from_ndi(self, ndi_source: str) -> Binding:
return next((x for x in self._bindings if x.source == ndi_source), None)
def _find_ndi_from_source(self, ndi_source: str) -> NDIData:
if ndi_source is None:
return self._ndi_sources[0]
return next((x for x in self._ndi_sources if x.source == ndi_source), None)
def update_dynamic_prims(self, prims: List[DynamicPrim]):
self._dynamic_prims = prims
self._update_ndi_from_prims()
self._update_bindings_from_prims()
EventSystem.send_event(EventSystem.BINDINGS_CHANGED_EVENT)
def _update_ndi_from_prims(self):
for dynamic_prim in self._dynamic_prims:
ndi: NDIData = self._find_ndi_from_source(dynamic_prim.ndi_source_attr)
if ndi is None:
self._ndi_sources.append(NDIData(dynamic_prim.ndi_source_attr, False))
def _update_bindings_from_prims(self):
self._bindings.clear()
for dynamic_prim in self._dynamic_prims:
source_attr = dynamic_prim.ndi_source_attr
source: str = source_attr if source_attr is not None else BindingsModel.NONE_DATA.source
self._bindings.append(Binding(dynamic_prim.dynamic_id, source, dynamic_prim.lowbandwidth_attr))
def _ndi_sources_change_evt_callback(self, e: carb.events.IEvent):
sources = e.payload["sources"]
self._update_ndi_new_and_active_sources(sources)
self._update_ndi_inactive_sources(sources)
EventSystem.send_event(EventSystem.COMBOBOX_SOURCE_CHANGE_EVENT,
payload={"sources": [x.source for x in self._ndi_sources]})
EventSystem.send_event(EventSystem.NDI_STATUS_CHANGE_EVENT)
def _update_ndi_new_and_active_sources(self, sources: List[str]):
for source in sources:
data: NDIData = self._find_ndi_from_source(source)
if data is None:
data = NDIData(source, True)
self._ndi_sources.append(data)
else:
data.active = True
def _update_ndi_inactive_sources(self, sources: List[str]):
for ndi in self._get_non_static_source_list():
is_active = next((x for x in sources if x == ndi.source), None)
if is_active is None:
ndi.active = False
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/deps/NDIlib/__init__.py | import os
import sys
if os.name == 'nt' and sys.version_info.major >= 3 and sys.version_info.minor >= 8:
os.add_dll_directory(os.path.dirname(__file__))
from .NDIlib import *
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/deps/NDIlib/Processing.NDI.Lib.Licenses.txt | ********************************************************************************
NewTek NDI
Copyright (C) 2014-2023, NewTek, inc.
********************************************************************************
The NDI SDK license available at:
http://new.tk/ndisdk_license/
The NDI Embedded SDK license is available at
http://new.tk/ndisdk_embedded_license/
For more information about NDI please visit:
http://ndi.tv/
This file should be included with all distribution of the binary files included with the NDI SDK.
We are truly thankful for the NDI community and the amazing support that it has shown us over the years.
********************************************************************************
NDI gratefully uses the following third party libraries.
********************************************************************************
RapidJSON (https://rapidjson.org)
Tencent is pleased to support the open source community by making RapidJSON available.
Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
http://opensource.org/licenses/MIT
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.
****************************************************
SpeexDSP (https://www.speex.org), resampling code only.
© 2002-2003, Jean-Marc Valin/Xiph.Org Foundation
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************
RapidXML (http://rapidxml.sourceforge.net)
Copyright (c) 2006, 2007 Marcin Kalicinski
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
********************************************************************************
CxxUrl (https://github.com/chmike/CxxUrl)
The MIT License (MIT)
Copyright (c) 2015 Christophe Meessen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
********************************************************************************
ASIO (https://think-async.com)
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
Copyright (c) Microsoft Corporation.
********************************************************************************
MsQuic (https://github.com/microsoft/msquic)
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
********************************************************************************
Opus Interactive Audio Codec (https://opus-codec.org)
Copyright 2001-2011 Xiph.Org, Skype Limited, Octasic,
Jean-Marc Valin, Timothy B. Terriberry,
CSIRO, Gregory Maxwell, Mark Borgerding,
Erik de Castro Lopo
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Internet Society, IETF or IETF Trust, nor the
names of specific contributors, may be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Opus is subject to the royalty-free patent licenses which are
specified at:
Xiph.Org Foundation:
https://datatracker.ietf.org/ipr/1524/
Microsoft Corporation:
https://datatracker.ietf.org/ipr/1914/
Broadcom Corporation:
https://datatracker.ietf.org/ipr/1526/
********************************************************************************
Updated to C++, zedwood.com 2012
Based on Olivier Gay's version
See Modified BSD License below:
FIPS 180-2 SHA-224/256/384/512 implementation
Issue date: 04/30/2005
http://www.ouah.org/ogay/sha2/
Copyright (C) 2005, 2007 Olivier Gay <[email protected]>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/tests/__init__.py | from .test_USDtools import *
from .test_ui import *
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/tests/test_ui.py | import omni.kit.test
from ..window import Window, BindingPanel
from ..comboboxModel import ComboboxModel
from .test_utils import (make_stage, close_stage, get_window, DYNAMIC_ID1, DYNAMIC_ID2, create_dynamic_material,
create_dynamic_rectlight, refresh_dynamic_list, get_dynamic_material_prim, add_proxy_source)
class UITestsHeader(omni.kit.test.AsyncTestCase):
def setUp(self):
self._stage = make_stage()
self._window = get_window()
def tearDown(self):
close_stage()
async def test_create_material_button(self):
field = self._window.find("**/StringField[*]")
field.widget.model.set_value(DYNAMIC_ID1)
self.assertEqual(field.widget.model.get_value_as_string(), DYNAMIC_ID1)
button = self._window.find(f"**/Button[*].text=='{Window.NEW_TEXTURE_BTN_TXT}'")
await button.click()
prim = get_dynamic_material_prim(DYNAMIC_ID1)
self.assertTrue(prim.IsValid)
async def test_texture_discovery(self):
create_dynamic_material()
create_dynamic_rectlight()
await refresh_dynamic_list(self._window)
panels = self._window.find_all("**/BindingPanel[*]")
self.assertEqual(len(panels), 2)
panel1_found = False
panel2_found = False
for panel in panels:
labels = panel.find_all("**/Label[*]")
for label in labels:
if label.widget.text == DYNAMIC_ID1:
panel1_found = True
elif label.widget.text == DYNAMIC_ID2:
panel2_found = True
self.assertTrue(panel1_found)
self.assertTrue(panel2_found)
class UITestsPanel(omni.kit.test.AsyncTestCase):
def setUp(self):
self._stage = make_stage()
self._window = get_window()
def tearDown(self):
close_stage()
async def test_no_panel_on_start(self):
await refresh_dynamic_list(self._window)
panel = self._window.find("**/BindingPanel[*]")
self.assertIsNone(panel)
label = self._window.find("**/Label[*]")
self.assertEqual(label.widget.text, Window.EMPTY_TEXTURE_LIST_TXT)
async def test_combobox_defaults(self):
await refresh_dynamic_list(self._window)
add_proxy_source(self._window.widget)
button = self._window.find(f"**/Button[*].text=='{Window.NEW_TEXTURE_BTN_TXT}'")
await button.click()
combobox = self._window.find("**/ComboBox[*]")
model = combobox.widget.model
self.assertEqual(model._current_value(), ComboboxModel.NONE_VALUE)
model._current_index.set_value(1)
self.assertNotEquals(model._current_value(), ComboboxModel.NONE_VALUE)
model._current_index.set_value(0)
self.assertEqual(model._current_value(), ComboboxModel.NONE_VALUE)
async def test_low_bandwidth_btn(self):
await refresh_dynamic_list(self._window)
button = self._window.find(f"**/Button[*].text=='{Window.NEW_TEXTURE_BTN_TXT}'")
await button.click()
panel = self._window.find("**/BindingPanel[*]")
binding, _, _ = panel.widget._get_data()
self.assertFalse(binding.lowbandwidth)
button = panel.find(f"**/ToolButton[*].name=='{BindingPanel.BANDWIDTH_BTN_NAME}'")
await button.click()
binding, _, _ = panel.widget._get_data()
self.assertTrue(binding.lowbandwidth)
await button.click()
binding, _, _ = panel.widget._get_data()
self.assertFalse(binding.lowbandwidth)
async def test_low_bandwidth_stream(self):
await refresh_dynamic_list(self._window)
add_proxy_source(self._window.widget)
button = self._window.find(f"**/Button[*].text=='{Window.NEW_TEXTURE_BTN_TXT}'")
await button.click()
combobox = self._window.find("**/ComboBox[*]")
combobox.widget.model._set_current_from_value(ComboboxModel.PROXY_VALUE)
panel = self._window.find("**/BindingPanel[*]")
button_bandwidth = panel.find(f"**/ToolButton[*].name=='{BindingPanel.BANDWIDTH_BTN_NAME}'")
button_playpause = button = panel.find(f"**/Button[*].name=='{BindingPanel.PLAYPAUSE_BTN_NAME}'")
self.assertTrue(panel.widget._lowbandwidth_toolbutton.enabled)
await button_playpause.click()
self.assertFalse(self._window.widget._model._ndi._streams[0]._lowbandwidth)
self.assertFalse(panel.widget._lowbandwidth_toolbutton.enabled)
await button_playpause.click()
self.assertTrue(panel.widget._lowbandwidth_toolbutton.enabled)
await button_bandwidth.click()
await button_playpause.click()
self.assertTrue(self._window.widget._model._ndi._streams[0]._lowbandwidth)
await button_playpause.click()
async def test_proxy_play_pause(self):
await refresh_dynamic_list(self._window)
add_proxy_source(self._window.widget)
button_create = self._window.find(f"**/Button[*].text=='{Window.NEW_TEXTURE_BTN_TXT}'")
await button_create.click()
combobox = self._window.find("**/ComboBox[*]")
combobox.widget.model._set_current_from_value(ComboboxModel.PROXY_VALUE)
panel = self._window.find("**/BindingPanel[*]")
button_playpause = panel.find(f"**/Button[*].name=='{BindingPanel.PLAYPAUSE_BTN_NAME}'")
self.assertTrue(panel.widget._combobox_ui.visible)
self.assertFalse(panel.widget._combobox_alt.visible)
await button_playpause.click()
self.assertGreater(len(self._window.widget._model._ndi._streams), 0)
self.assertFalse(panel.widget._combobox_ui.visible)
self.assertTrue(panel.widget._combobox_alt.visible)
await button_playpause.click()
self.assertEquals(len(self._window.widget._model._ndi._streams), 0)
async def test_proxy_multiple(self):
await refresh_dynamic_list(self._window)
field = self._window.find("**/StringField[*]")
button_create = self._window.find(f"**/Button[*].text=='{Window.NEW_TEXTURE_BTN_TXT}'")
field.widget.model.set_value(DYNAMIC_ID1)
await button_create.click()
field.widget.model.set_value(DYNAMIC_ID2)
await button_create.click()
comboboxes = self._window.find_all("**/ComboBox[*]")
for combobox in comboboxes:
combobox.widget.model._set_current_from_value(ComboboxModel.PROXY_VALUE)
buttons_playpause = self._window.find_all(f"**/Button[*].name=='{BindingPanel.PLAYPAUSE_BTN_NAME}'")
for button_playpause in buttons_playpause:
await button_playpause.click()
self.assertEquals(len(self._window.widget._model._ndi._streams), 2)
button_stopall = self._window.find(f"**/Button[*].text=='{Window.STOP_STREAMS_BTN_TXT}'")
await button_stopall.click()
self.assertEquals(len(self._window.widget._model._ndi._streams), 0)
panels = self._window.find_all("**/BindingPanel[*]")
for panel in panels:
self.assertTrue(panel.widget._combobox_ui.visible)
self.assertFalse(panel.widget._combobox_alt.visible)
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/tests/test_utils.py | import omni
import omni.kit.ui_test as ui_test
from pxr import Usd, UsdLux, UsdShade
from ..USDtools import USDtools
from ..window import Window
from ..eventsystem import EventSystem
from ..comboboxModel import ComboboxModel
SOURCE1 = "MY-PC (Test Pattern)"
SOURCE2 = "MY-PC (Test Pattern 2)"
DYNAMIC_ID1 = "myDynamicMaterial1"
DYNAMIC_ID2 = "myDynamicMaterial2"
DUMMY_PATH = "/path/to/dummy"
RECTLIGHT_NAME = "MyRectLight"
DEFAULT_PRIM_NAME = "World"
def make_stage() -> Usd.Stage:
usd_context = omni.usd.get_context()
usd_context.new_stage()
# self._stage = Usd.Stage.CreateInMemory()
stage = usd_context.get_stage()
prim = stage.DefinePrim(f"/{DEFAULT_PRIM_NAME}")
stage.SetDefaultPrim(prim)
return stage
def get_stage() -> Usd.Stage:
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
return stage
def close_stage():
usd_context = omni.usd.get_context()
assert usd_context.can_close_stage()
usd_context.close_stage()
def get_window():
return ui_test.find(Window.WINDOW_NAME)
def create_dynamic_material() -> UsdShade.Material:
USDtools.create_dynamic_material(DYNAMIC_ID1)
return get_dynamic_material_prim(DYNAMIC_ID1)
def create_dynamic_rectlight():
stage = get_stage()
path: str = f"{stage.GetDefaultPrim().GetPath()}/{RECTLIGHT_NAME}"
light = UsdLux.RectLight.Define(stage, path)
light.GetPrim().GetAttribute("texture:file").Set(f"{USDtools.PREFIX}{DYNAMIC_ID2}")
def get_dynamic_material_prim(name: str):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
return stage.GetPrimAtPath(f"{stage.GetDefaultPrim().GetPath()}/{USDtools.SCOPE_NAME}/{name}")
async def refresh_dynamic_list(window):
button = window.find(f"**/Button[*].text=='{Window.DISCOVER_TEX_BTN_TXT}'")
await button.click()
def add_proxy_source(window):
EventSystem.send_event(EventSystem.NDIFINDER_NEW_SOURCES, payload={"sources": [ComboboxModel.PROXY_VALUE]})
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/mf/ov/ndi/tests/test_USDtools.py | from ..USDtools import USDtools
from .test_utils import make_stage, close_stage, create_dynamic_material, create_dynamic_rectlight, SOURCE1
import omni.kit.test
class USDValidNameUnitTest(omni.kit.test.AsyncTestCase):
async def test_name_valid(self):
self.check_name_valid("myDynamicMaterial", "myDynamicMaterial")
self.check_name_valid("789testing123numbers456", "_89testing123numbers456")
self.check_name_valid("", "_")
self.check_name_valid("àâáäãåÀÂÁÃÅÄ", "aaaaaaAAAAAA")
self.check_name_valid("èêéëÈÊÉË", "eeeeEEEE")
self.check_name_valid("ìîíïÌÎÍÏ", "iiiiIIII")
self.check_name_valid("òôóöõøÒÔÓÕÖØ", "ooooooOOOOOO")
self.check_name_valid("ùûúüÙÛÚÜ", "uuuuUUUU")
self.check_name_valid("æœÆŒçǰðÐñÑýÝþÞÿß", "aeoeAEOEcCdegdDnNyYthThyss")
self.check_name_valid("!¡¿@#$%?&*()-_=+/`^~.,'\\<>`;:¤{}[]|\"¦¨«»¬¯±´·¸÷",
"___________________________________________________")
self.check_name_valid("¢£¥§©ªº®¹²³µ¶¼½¾×", "C_PSY_SS_c_ao_r_123uP_1_4_1_2_3_4x")
def check_name_valid(self, source, expected):
v: str = USDtools.make_name_valid(source)
self.assertEqual(v, expected, f"Expected \"{v}\", derived from \"{source}\", to equals \"{expected}\"")
class USDToolsUnitTest(omni.kit.test.AsyncTestCase):
def setUp(self):
self._stage = make_stage()
def tearDown(self):
close_stage()
async def test_create_dynamic_material(self):
material = create_dynamic_material()
prim = self._stage.GetPrimAtPath(material.GetPath())
self.assertIsNotNone(prim)
async def test_find_dynamic_sources(self):
create_dynamic_material()
create_dynamic_rectlight()
sources = USDtools.find_all_dynamic_sources()
self.assertEqual(len(sources), 2)
async def test_set_property_ndi(self):
material = create_dynamic_material()
path = material.GetPath()
USDtools.set_prim_ndi_attribute(path, SOURCE1)
attr = material.GetPrim().GetAttribute(USDtools.ATTR_NDI_NAME)
self.assertEqual(attr.Get(), SOURCE1)
async def test_set_property_bandwidth(self):
material = create_dynamic_material()
path = material.GetPath()
USDtools.set_prim_lowbandwidth_attribute(path, True)
attr = material.GetPrim().GetAttribute(USDtools.ATTR_BANDWIDTH_NAME)
self.assertTrue(attr.Get())
USDtools.set_prim_lowbandwidth_attribute(path, False)
self.assertFalse(attr.Get())
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/config/extension.toml | [package]
version = "1.0.1"
title = "MF NDI® extension"
description = "An extension to enable NDI® live video input in Omniverse."
authors = ["Moment Factory","Frederic Lestage"]
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
repository = "https://github.com/MomentFactory/Omniverse-NDI-extension"
category = "Services"
keywords = ["NDI®", "texture", "live-feed", "video", "broadcast", "audiovisual", "realtime","streaming","voip"]
preview_image = "data/preview.png"
icon = "data/mf-ov-extensions-icons.png"
[dependencies]
"omni.kit.uiapp" = {}
"omni.warp" = {}
[[python.module]]
name = "mf.ov.ndi"
[python.pipapi]
requirements = [
"unidecode"
]
use_online_index = true
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false"
]
dependencies = [
"omni.kit.ui_test",
"omni.usd"
]
timeout = 60
[package.target]
kit = ["105.1"]
[package.writeTarget]
kit = true
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/docs/CHANGELOG.md | # Changelog
## [1.0.1] - 2023-12-21
### Fixed
- Stream properly shut down when closing, opening, or reopening stage
## [1.0.0] - 2023-07-18
### Added
- Compatibility with USD Composer 2023.1.1
### Changed
- Creating a texture with the same name doesn't block (will follow pattern: "name", "name_01", "name_02", ...)
- Bundle pip dependency `ndi-python` with the extension
- Search now look for dynamic texture in the emissive texture field
## [0.12.0] - 2023-05-18
### Added
- Display stream statistics when running (fps, dimensions, color format)
- Opens as a new window when left-clicking on the status dot of a particular stream
### Changed
- Improved performances when using GPU for texture copy when stream source is square
### Fixed
- Streams stop when refreshing or adding a new dynamic texture to prevent ghost streams
- Removed the possibility of overwriting a stream when creating a new one with the same name
- Removed the double color conversion by requesting RGBA color profile from NDI®
## Removed
- Proxy stream no longer available in the list of streams
## [0.11.0] - 2023-04-20
### Changed
- NDI® status now displayed as a dot with colors
- red: NDI® source offline
- white: NDI® source online
- green: Stream playing
- orange: NDI® drops
- Code refactor
## [0.10.0] - 2023-04-12
### Added
- Unit and UI tests
## [0.9.0] - 2023-04-04
### Changed
- UI rework: less text, more icons
- Documentation and icons Overhaul
- Material are now created in a scope under the default prim instead of an Xform
- Updated example.usd to reflect this change
- Material identifier now keep the letter if there's an accent (i.e. é becomes e)
## [0.8.1] - 2023-03-29
### Changed
- Dedicated NDI® threads no longer daemonic
### Fixed
- Stream UI did not go back to its non running state when using the button "kill all streams"
- Order of calls on application shutdown that could cause a crash on hot reload (affected developers)
- Status of NDI® source not properly reflected in the icons
## [0.8.0] - 2023-03-27
### Added
- Profiling in NDI® stream functions
### Changed
- When a stream is running, it is no longer possible to change its source, display a running status instead
### Fixed
- Selected NDI® source in combobox doesn't change when wources are updated
- Make name USD safe when creating new material instead of throwing error
- NDI® status icon goes back to valid if a NDI® source is started after being closed
- Won't attempt to start a stream if it isn't valid (i.e. can't find the source)
## [0.7.0] - 2023-03-21
### Fixed
- Removed the parts of the extension that caused the app to freeze. Might still encounter low fps during the following:
- Starting a stream
- Closing a NDI® source while the stream is still running in the extension
- Using Remote Connection 1 or proxy as a stream source
## [0.6.0] - 2023-03-16
### Changed
- Stream Optimization (no need to flatten the NDI® frame)
- Individual streams now run in different thread
- Removed refresh NDI® feed button in favor of a watcher that runs on a second thread
- If a NDI® source closes while the stream is still running in the extension, it will automatically stop after a few seconds (5)
### Fixed
- Extension is now know as mf.ov.ndi
- Omniverse app won't crash when the NDI® source is closed and a stream is still running
- The app will still freeze for a few seconds
## [0.5.0] - 2023-03-07
### Added
- Support for receiving the low bandwidth version of a NDI® stream (this is a feature of NDI® that we now support)
## [0.4.0] - 2023-03-03
### Added
- Support for dynamic rect light (works when `IsProjector` is enabled to simulate a projector)
### Changed
- Now uses the [recommended logging](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/logging.html) system
### Removed
- Obsolete pip dependency to open-cv
## [0.3.1] - 2023-03-02
### Fixed
- Crash when searching for dynamic textures and finding those that aren't dynamic
## [0.3.0] - 2023-03-01
### Added
- Can use a proxy feed which simulates a solid red color 1920x1080 at 30fps
## Fixed
- Filling dynamic texture with a default magenta color
- Fixes frame drop when assigning a dynamic texture without pushing data to it first
- Fixes for developpers to the window management targeting hot reload
### Changed
- Menu element is now at "Window > NDI® Dynamic Texture" instead of "Window > NDI® > NDI® Dynamic Texture"
## [0.2.0] - 2023-02-28
### Added
- Support for managing multiple NDI® feeds
## [0.1.0] - 2023-02-22
### Added
- Initial version of extension
- Supports one NDI® feed
|
MomentFactory/Omniverse-NDI-extension/exts/mf.ov.ndi/docs/README.md | # NDI® extension for Omniverse [mf.ov.ndi]
Copyright 2023 Moment Factory Studios Inc.
An extension to enable NDI® live video input in Omniverse.
- Requires Omniverse Kit >= 105
- Requires USD Composer > 2023.1.0
- Requires [NDI® 5.5.3 runtime for Windows](https://go.ndi.tv/tools-for-windows)
|
MomentFactory/Omniverse-NDI-extension/PACKAGE-LICENSES/NDI-LICENSE.md | NewTek’s NDI® Software Development Kit (SDK) License Agreement
Please read this document carefully before proceeding. You (the undersigned Licensee) hereby agree to the terms of this
NDI® Software Development Kit (SDK) License Agreement (the "License") in order to use the SDK. NewTek, Inc.
(“NewTek”) agrees to license you certain rights as set forth herein under these terms.
1. Definitions
a. "SDK" means the entire NewTek NDI® Software Development Kit, including those portions pertaining to the
Specific SDK, provided to you pursuant to this License, including any source code, compiled executables or
libraries, and all documentation provided to you to assist you in building tools that use the NDI® Software for data
transfer over a local network.
b. "Products" means your software product(s) and/or service(s) that you develop or that are developed on your behalf
through the use of the SDK and that are designed to be, and/or are, used, sold and/or distributed to work closely
with other NewTek Products or Third Party Video Products.
c. “NewTek Products refers to NewTek’s video line of products distributed by NewTek and any upgrades.
d. “SDK Documentation” refers to the documentation included with the Software Development Kit including that
portion pertaining to the Specific SDK.
e. “Specific SDK” refers to the specific SDK for which you intend to use the NewTek SDK and this license (for example:
NDI® Send, NDI® Receive, NDI® Find, or other SDK’s that are available from time to time. These are examples
only and NewTek may add or subtract to this list at its discretion, and you agree to use them only in accordance
with this Agreement), and includes the documentation relating to it.
f. “Third Party Video Products” refers to products of third parties developed by or for them also using the NewTek
NDI® Software Development Kit in any way.
2. License
a. Pursuant to the terms, conditions and requirements of this License and the SDK Documentation, you are hereby
granted a nonexclusive royalty-free license to use the sample code, object code and documentation included in
the SDK for the sole purpose of developing Products using the Specific SDK, and to distribute, only in accordance
with the SDK Documentation requirements, object code included in the SDK solely as used by such Products (your
Product and compiled sample code referred to as the “Bundled Product”).
b. If you are making a product release you must use a version of the SDK that is less than thirty (30) days old if there
is one.
c. This is a License only, and no employment, joint venture, partnership, or other business venture is created by this
License.
d. Unless otherwise stated in the SDK, no files within the SDK and the Specific SDK may be distributed. Certain files
within the SDK or the Specific SDK may be distributed, said files and their respective distribution license are
individually identified within the SDK documentation. This is not a license to create revisions or other derivative
works of any NewTek software or technology.
e. You agree to comply with the steps outlined in the SDK Documentation, including the SDK manual for the Specific
SDK. Different obligations and restrictions may be imposed by NewTek with respect to different Specific SDK’s.
NewTek will not agree to sponsor your Product or show affiliation; however NewTek shall have the right to test the
Product, and if it does not work or operate to NewTek’s satisfaction, NewTek may terminate this license pursuant to
Section 10. Notwithstanding that NewTek may test the Product, it does not warrant the test; it is for NewTek’s
benefit, and you agree not to promote in your Product marketing or elsewhere any results or that NewTek has
tested the Product.
f. You acknowledge that information provided to NewTek to induce NewTek to enter into this license with you about
your experience in the industry, sales, distribution, SDK experience or otherwise, whether such information is
provided to NewTek verbally or in writing, is true.
g. NewTek makes the SDK available for developers for developing Products only, under these specific conditions
herein, and if any, or all, of the terms of this license are not enforceable within your legal jurisdiction in any way, or
if any clause is voided or modified in any way, then you may not enter into this agreement, any license and
permission granted herein is revoked and withdrawn as of the date you first downloaded and/or used the SDK, and
you are then unauthorized to copy, create derivative works, or otherwise use the SDK in any way.
3. Restrictions and Confidentiality.
a. “Confidential Information” includes the SDK and all specifications, source code, example code, tools and
documentation provided within the SDK, and any support thereof, and any other proprietary information provided
by NewTek and identified as Confidential in the course of assisting You with your NDI® implementation.
Confidential Information does not include information that: 1) is or becomes generally available to the public other
than as a result of a disclosure by You, or 2) becomes available to You on a non-confidential basis from a source
that was not prohibited from disclosing such information. Except as authorized herein, or in the SDK
Documentation, or as otherwise approved in writing by NewTek: 1) The disclosure to you of the SDK and all other
Confidential Information shall not be disclosed to any third party 2)You agree not to commercialize the
Confidential Information for yours or others benefit in any way; 3) You will not make or distribute copies of the
SDK, or other Confidential Information or electronically transfer the SDK to any individual within your business or
company who does not need to know or view the SDK, and under no circumstances shall you disclose it, or any
part of it, to any company, or any other individual not employed directly by the business or company you
represent, without express written permission of NewTek.
b. You will not modify, sell, rent, transfer, resell for profit, distribute, or create derivative works based upon the SDK or
any part thereof other than as set forth herein, and you will not allow independent contractors to create derivative
works; however, you may use the SDK to create your own program for the primary purpose of making it or your
Product compatible with the NDI® network APIs, a NewTek Product, or for other purposes expressly set forth by
you in advance in writing and agreed to in writing by NewTek. In the case of your derivative works based upon the
SDK, you may create and revise your Product using the SDK, and sell, rent, transfer, resell for profit and distribute,
so long as it is for the Principal objective for which you were provided the SDK and it otherwise complies with this
agreement, including the requirement that your Product or any other Third Party Product using any portion of the
SDK continues to use the current SDK as required herein and functions properly using the SDK. NewTek reserves
the right to determine at any time the compliance of your Product or any Third Party Product as properly using the
SDK including maintaining current and complete NDI® compatability. Notwithstanding anything to the contrary
herein, no intellectual property claim, whether in patent, trademark, copyright, or otherwise, is made by NewTek in
or to your Product (except as to the SDK including software code and/or Libraries, and copyright rights therein,
and any Confidential Information used in or with the Product).
c. You will comply with applicable export control and trade sanctions laws, rules, regulations and licenses and will not
export or re-export, directly or indirectly, the SDK into any country, to any organization or individual prohibited by
the United States Export Administration Act and the regulations thereunder.
d. Any direct or indirect distribution of your Product or any Bundled Products by you that include your Product, shall
be under the terms of a license agreement containing terms that: (i) prohibit any modifications to the SDK or any
part thereof, (ii) prohibit any reverse engineering, disassembly or recompilation of the the SDK or any part thereof,
or any protocols used in the SDK, and further prohibit any attempt to do so; (iii) disclaim any and all warranties on
behalf of NewTek and each of its licensors, (iv) disclaim, to the extent permitted by applicable law, liability of
NewTek and/or its licensors for any damages, whether direct, indirect, incidental or consequential, arising from the
use of the Product or Bundled Products, (v) comply fully with all relevant export laws and regulations of the United
States to assure that the Bundled Products or any part thereof is not exported, directly or indirectly, in violation of
United States law; (vi) include the appropriate copyright notice showing NewTek, Inc. as copyright owner; (vii)
require all third party developers using your Product to develop Third Party Products to comply with the terms of
the NewTek SDK license, including that such Third Party Products have current and complete NDI® compatability,
and further require such third party developers to include in their End User License Agreement the terms of this
paragraph 3d.
e. You agree not to use the SDK for any unlawful propose or in any way to cause injury, harm or damage to NewTek,
Inc., or its Products, trademarks, reputation and/or goodwill, or use information provided pursuant to the SDK, to
interfere with NewTek in the commercialization of NewTek Products.
f. You agree to use NewTek trademarks (NewTek trademarks include, but are not limited to NDI®, NDI|HX™,
NewTek™, TriCaster®, and LightWave 3D®), only in accordance with applicable policies of NewTek for such
trademark usage by software developers in effect from time to time, which policy may be amended at any time
with or without notice. NewTek’s trademarks shall not be utilized within the Product itself, or on the Product
packaging or promotion, or on websites, except to identify that the Product is compatible with NewTek’s pertinent Video Product, and in all cases where NewTek trademarks are utilized, special and clear notations shall be provided
that the marks are NewTek trademarks. Your Product is not a product of NewTek and no promotion, packaging, or
use of NewTek trademarks shall suggest sponsorship by NewTek of your Products, except where specifically
authorized by NewTek in writing. Any distribution of your Product in a fraudulent manner, or in any other manner
or method that violates any civil or criminal laws shall constitute a default under this agreement and result in
immediate revocation of any right to utilize NewTek’s marks.
g. NewTek owns or has licensed copyright rights to the SDK. To the extent any of the SDK is incorporated into your
Product, you agree to include all applicable copyright notices, along with yours, indicating NewTek’s copyright
rights as applicable and as requested by NewTek.
h. You agree that by using the SDK, or any portion or part of the NDI® Software, in your Products, that you shall not
at any time during the term create, use or distribute Products utilizing the NDI® SDK that are not interoperable
with, or have significantly degraded performance of functionality when working with, NewTek Products or Third
Party Video Products that are created with or utilize in whole or in part the SDK. Your Products and Third Party
Products must maintain current and complete NDI® compatability at all times.
i. You agree to not to reverse engineer, disassemble or recompile the SDK or any part thereof, or any protocols used
in the SDK, or attempt to do so.
j. You agree not to use the SDK, or cause the SDK to be used, for any purpose that it was not designed for, and in
particular, you agree not to use the SDK for any purpose but for the precise purposes as expressly identified to
NewTek in writing that is the basis of the SDK and this license, and you agree you will not attempt to violate any of
the foregoing, or encourage third parties to do so.
4. Software Defect Reporting
If you find software defects in the SDK, you agree to make reasonable effort to report them to NewTek in accordance
with the SDK documentation or in such other manner as NewTek directs in writing. NewTek will evaluate and, at its sole
discretion, may address them in a future revision of the SDK. NewTek does not warrant the SDK to be free of defects.
5. Updates
You understand and agree that NewTek may amend, modify, change, and/or cease distribution or production of the SDK
at any time. You understand that you are not entitled to receive any upgrades, updates, or future versions of the SDK
under this License. NewTek does not warrant or represent that its future updates and revisions will be compatible with
your Product, and NewTek does not warrant that its updates and/or revisions will allow your Product to be compatible
with or without modifications to your Product.
6. Ownership
Nothing herein is intended to convey to you any patent, trademark, copyright, trade secret or other Intellectual Property
owned by NewTek or its Licensors in the SDK or in any NewTek software, hardware, products, trade names, or
trademarks. NewTek and its suppliers or licensors shall retain all right, title, and interest to the foregoing Intellectual
Property and to the SDK. All rights not expressly granted herein are reserved by NewTek.
7. Indemnity and Limitations
You agree to indemnify and hold NewTek harmless from any third party claim, loss, or damage (including attorney's fees)
related to your use, sale or distribution of the SDK. THE SDK IS PROVIDED TO YOU FREE OF CHARGE, AND ON AN "AS
IS" BASIS AND "WITH ALL FAULTS", WITHOUT ANY TECHNICAL SUPPORT OR WARRANTY OF ANY KIND FROM
NEWTEK. YOU ASSUME ALL RISKS THAT THE SDK IS SUITABLE OR ACCURATE FOR YOUR NEEDS AND YOUR USE OF
THE SDK IS AT YOUR OWN DISCRETION AND RISK. NEWTEK AND ITS LICENSORS DISCLAIM ALL EXPRESS AND IMPLIED
WARRANTIES FOR THE SDK INCLUDING, WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR FITNESS
FOR A PARTICULAR PURPOSE. ALSO, THERE IS NO WARRANTY OF NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT.
SOME STATES DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSION MAY NOT
APPLY TO YOU. YOU MAY ALSO HAVE OTHER LEGAL RIGHTS THAT VARY FROM STATE TO STATE.
8. Limitation of Damages
NEITHER NEWTEK NOR ITS SUPPLIERS OR LICENSORS SHALL BE LIABLE FOR ANY INDIRECT, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES OR LOSS (INCLUDING DAMAGES FOR LOSS OF BUSINESS, LOSS OF PROFITS, OR THE
LIKE), ARISING OUT OF THIS LICENSE WHETHER BASED ON BREACH OF CONTRACT, TORT (INCLUDING NEGLIGENCE),STRICT LIABILITY, PRODUCT LIABILITY OR OTHERWISE, EVEN IF NEWTEK OR ITS REPRESENTATIVES HAVE BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE LIMITATION OR EXCLUSION OF
LIABILITY FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS LIMITATION OR EXCLUSION MAY NOT APPLY TO
YOU. The limited warranty, exclusive remedies and limited liability set forth above are fundamental elements of the basis
of the bargain between NewTek and you. You agree that NewTek would not be able to provide the Software on an
economic basis without such limitations. IN NO EVENT WILL NEWTEK BE LIABLE FOR ANY AMOUNT GREATER THAN
WHAT YOU ACTUALLY PAID FOR THE SDK.
9. US Government - Restricted Rights
The SDK and accompanying materials are provided with Restricted Rights. Use, duplication, or disclosure by the U.S.
Government is subject to restrictions as set forth in this License and as provided in Federal Regulations, as applicable.
(Manufacturer: NewTek, Inc., 5131 Beckwith Blvd., San Antonio, TX 78249).
10. Termination
Either party may terminate this License upon thirty (30) days written notice. Either party may also terminate if the other
party materially defaults in the performance of any provision of this License, the non-defaulting party gives written notice
to the other party of such default, and the defaulting party fails to cure such default within ten (10) days after receipt of
such notice. Upon the termination of this License, the rights and licenses granted to you by NewTek pursuant to this
License will automatically cease. Nothing herein shall prevent either party from pursuing any injunctive relief at any time
if necessary, or seeking any other remedies available in equity. Each party reserves the right to pursue all legal and
equitable remedies available. Upon termination, all SDK materials shall be promptly returned to NewTek, and any and all
copies stored in electronic or other format shall be deleted and destroyed, and any rights to use NewTek’s trademarks
are revoked. If this License is terminated for any reason, the provisions of Sections 1, 3, 6, 7, 8, 9, 10, and 11 shall survive
such termination.
11. General
Notices given hereunder may be sent to either party at the address below by either overnight mail or by email and are
deemed effective when sent. This License shall be governed by the laws of the State of Texas, without regard to its choice
of law rules and you agree to exclusive jurisdiction therein. This License contains the complete agreement between you
and NewTek with respect to the subject matter (SDK) of this License, and supersedes all prior or contemporaneous
agreements or understandings, whether oral or written. It does not replace any licenses accompanying NewTek
Products. You may not assign this SDK License. |
MomentFactory/Omniverse-NDI-extension/PACKAGE-LICENSES/USD-LICENSE.md | Universal Scene Description (USD) components are licensed under the following terms:
Modified Apache 2.0 License
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor
and its affiliates, except as required to comply with Section 4(c) of
the License and to reproduce the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
============================================================
RapidJSON
============================================================
Tencent is pleased to support the open source community by making RapidJSON available.
Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License.
If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON. To avoid the problematic JSON license in your own projects, it's sufficient to exclude the bin/jsonchecker/ directory, as it's the only code under the JSON license.
A copy of the MIT License is included in this file.
Other dependencies and licenses:
Open Source Software Licensed Under the BSD License:
--------------------------------------------------------------------
The msinttypes r29
Copyright (c) 2006-2013 Alexander Chemeris
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Open Source Software Licensed Under the JSON License:
--------------------------------------------------------------------
json.org
Copyright (c) 2002 JSON.org
All Rights Reserved.
JSON_checker
Copyright (c) 2002 JSON.org
All Rights Reserved.
Terms of the JSON License:
---------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Terms of the MIT License:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
============================================================
pygilstate_check
============================================================
The MIT License (MIT)
Copyright (c) 2014, Pankaj Pandey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================
double-conversion
============================================================
Copyright 2006-2011, the V8 project authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
============================================================
OpenEXR/IlmBase/Half
============================================================
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
============================================================
Apple Technical Q&A QA1361 - Detecting the Debugger
https://developer.apple.com/library/content/qa/qa1361/_index.html
============================================================
Sample code project: Detecting the Debugger
Version: 1.0
Abstract: Shows how to determine if code is being run under the debugger.
IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
============================================================
LZ4
============================================================
LZ4 - Fast LZ compression algorithm
Copyright (C) 2011-2017, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 homepage : http://www.lz4.org
- LZ4 source repository : https://github.com/lz4/lz4
============================================================
stb
============================================================
stb_image - v2.19 - public domain image loader - http://nothings.org/stb
no warranty implied; use at your own risk
stb_image_resize - v0.95 - public domain image resizing
by Jorge L Rodriguez (@VinoBS) - 2014
http://github.com/nothings/stb
stb_image_write - v1.09 - public domain - http://nothings.org/stb/stb_image_write.h
writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015
no warranty implied; use at your own risk
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
MomentFactory/Omniverse-MPCDI-converter/build.bat | :: 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.
@echo off
setlocal enabledelayedexpansion
pushd %~dp0
REM options defining what the script runs
set GENERATE=false
set BUILD=false
set CLEAN=false
set CONFIGURE=false
set STAGE=false
set HELP=false
set CONFIG=release
set HELP_EXIT_CODE=0
set DIRECTORIES_TO_CLEAN=_install _build _repo src\usd-plugins\schema\omniExampleSchema\generated src\usd-plugins\schema\omniExampleCodelessSchema\generated src\usd-plugins\schema\omniMetSchema\generated
REM default arguments for script - note this script does not actually perform
REM any build step so that you can integrate the generated code into your build
REM system - an option can be added here to run your build step (e.g. cmake)
REM on the generated files
:parseargs
if not "%1"=="" (
if "%1" == "--clean" (
set CLEAN=true
)
if "%1" == "--generate" (
set GENERATE=true
)
if "%1" == "--build" (
set BUILD=true
)
if "%1" == "--prep-ov-install" (
set STAGE=true
)
if "%1" == "--configure" (
set CONFIGURE=true
)
if "%1" == "--debug" (
set CONFIG=debug
)
if "%1" == "--help" (
set HELP=true
)
shift
goto :parseargs
)
if not "%CLEAN%" == "true" (
if not "%GENERATE%" == "true" (
if not "%BUILD%" == "true" (
if not "%STAGE%" == "true" (
if not "%CONFIGURE%" == "true" (
if not "%HELP%" == "true" (
REM default action when no arguments are passed is to do everything
set GENERATE=true
set BUILD=true
set STAGE=true
set CONFIGURE=true
)
)
)
)
)
)
REM requesting how to run the script
if "%HELP%" == "true" (
echo build.bat [--clean] [--generate] [--build] [--stage] [--configure] [--debug] [--help]
echo --clean: Removes the following directories ^(customize as needed^):
for %%a in (%DIRECTORIES_TO_CLEAN%) DO (
echo %%a
)
echo --generate: Perform code generation of schema libraries
echo --build: Perform compilation and installation of USD schema libraries
echo --prep-ov-install: Preps the kit-extension by copying it to the _install directory and stages the
echo built USD schema libraries in the appropriate sub-structure
echo --configure: Performs a configuration step after you have built and
echo staged the schema libraries to ensure the plugInfo.json has the right information
echo --debug: Performs the steps with a debug configuration instead of release
echo ^(default = release^)
echo --help: Display this help message
exit %HELP_EXIT_CODE%
)
REM should we clean the target directory?
if "%CLEAN%" == "true" (
for %%a in (%DIRECTORIES_TO_CLEAN%) DO (
if exist "%~dp0%%a/" (
rmdir /s /q "%~dp0%%a"
)
)
if !errorlevel! neq 0 (goto Error)
goto Success
)
REM should we generate the schema code?
if "%GENERATE%" == "true" (
REM pull down NVIDIA USD libraries
REM NOTE: If you have your own local build, you can comment out this step
call "%~dp0tools\packman\packman.cmd" pull deps/usd-deps.packman.xml -p windows-x86_64 -t config=%CONFIG%
if !errorlevel! neq 0 ( goto Error )
REM generate the schema code and plug-in information
REM NOTE: this will pull the NVIDIA repo_usd package to do this work
call "%~dp0tools\packman\python.bat" bootstrap.py usd --configuration %CONFIG%
if !errorlevel! neq 0 ( goto Error )
)
REM should we build the USD schema?
REM NOTE: Modify this build step if using a build system other than cmake (ie, premake)
if "%BUILD%" == "true" (
REM pull down target-deps to build dynamic payload which relies on CURL
call "%~dp0tools\packman\packman.cmd" pull deps/target-deps.packman.xml -p windows-x86_64 -t config=%CONFIG%
REM Below is an example of using CMake to build the generated files
REM You may also want to explicitly specify the toolset depending on which
REM version of Visual Studio you are using (e.g. -T v141)
REM NVIDIA USD 22.11 was built with the v142 toolset, so we set that here
REM Note that NVIDIA USD 20.08 was build with the v141 toolset
cmake -B ./_build/cmake -T v142
cmake --build ./_build/cmake --config=%CONFIG% --target install
)
REM is this a configure only? This will configure the plugInfo.json files
if "%CONFIGURE%" == "true" (
call "%~dp0tools\packman\python.bat" bootstrap.py usd --configure-pluginfo --configuration %CONFIG%
if !errorlevel! neq 0 (goto Error)
)
REM do we need to stage?
if "%STAGE%" == "true" (
REM Copy the kit-extension into the _install directory
REM we can do this directly because it's a python extension, so there's nothing to compile
REM but we want to combine it together with the output of the USD schema extension
REM Why not build the USD schema extension to the exact structure we are creating here?
REM Because we are illustrating that you can build the C++ schemas and distribute them
REM independent of anything kit related. All the copy is doing is putting everything in
REM one structure that can be referenced as a complete kit extension
REM this seems to be an example of how we can bring back all the python and other files from the ext folder to the _install folder.
REM commented but left here for reference
REM echo D | xcopy "%~dp0src\kit-extension\exts\omni.example.schema" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema" /s /Y
REM if not exist "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema" mkdir "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema"
REM echo F | xcopy "%~dp0_install\windows-x86_64\%CONFIG%\omniExampleSchema\OmniExampleSchema\*.*" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema" /Y
REM echo D | xcopy "%~dp0_install\windows-x86_64\%CONFIG%\omniExampleSchema\include" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema\include" /s /Y
REM echo D | xcopy "%~dp0_install\windows-x86_64\%CONFIG%\omniExampleSchema\lib" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema\lib" /s /Y
REM echo D | xcopy "%~dp0_install\windows-x86_64\%CONFIG%\omniExampleSchema\resources" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema\resources" /s /Y
REM if not exist "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleCodelessSchema" mkdir "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleCodelessSchema"
REM echo D | xcopy "%~dp0_install\windows-x86_64\%CONFIG%\omniExampleCodelessSchema\resources" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleCodelessSchema\resources" /s /Y
copy the files we need for a clean prepackaged extension ready for publishing
xcopy "%~dp0exts\mf.ov.mpcdi_converter\*" "%~dp0_install\windows-x86_64\%CONFIG%\mf.ov.mpcdi_converter" /E /I /H /Y
ren "%~dp0_install\windows-x86_64\%CONFIG%\mpcdiFileFormat" "plugin"
move "%~dp0_install\windows-x86_64\%CONFIG%\plugin" "%~dp0_install\windows-x86_64\%CONFIG%\mf.ov.mpcdi_converter"
xcopy "%~dp0LICENSE" "%~dp0_install\windows-x86_64\%CONFIG%\mf.ov.mpcdi_converter\" /Y
if !errorlevel! neq 0 ( goto Error )
)
:Success
exit /b 0
:Error
exit /b !errorlevel! |
MomentFactory/Omniverse-MPCDI-converter/bootstrap.py | # 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.
import contextlib
import io
import packmanapi
import os
import sys
REPO_ROOT = os.path.dirname(os.path.realpath(__file__))
REPO_DEPS_FILE = os.path.join(REPO_ROOT, "deps", "repo-deps.packman.xml")
if __name__ == "__main__":
# pull all repo dependencies first
# and add them to the python path
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)
sys.path.append(REPO_ROOT)
import omni.repo.usd
omni.repo.usd.bootstrap(REPO_ROOT) |
MomentFactory/Omniverse-MPCDI-converter/link_app.sh | #!/bin/bash
set -e
SCRIPT_DIR=$(dirname ${BASH_SOURCE})
cd "$SCRIPT_DIR"
exec "tools/packman/python.sh" tools/scripts/link_app.py $@
|
MomentFactory/Omniverse-MPCDI-converter/CMakeLists.txt | # 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.
# 3.20 is required to access target_link_directories and cmake_path
cmake_minimum_required(VERSION 3.20)
project(usd-plugins)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_LIST_DIR}/_repo/repo_usd/templates/cmake)
include(PxrPlugin)
add_subdirectory(src/usd-plugins/fileFormat/mpcdiFileFormat)
|
MomentFactory/Omniverse-MPCDI-converter/build.sh | # 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.
set -e
CWD="$( cd "$( dirname "$0" )" && pwd )"
# default config is release
CLEAN=false
BUILD=false
GENERATE=false
STAGE=false
CONFIGURE=false
HELP=false
CONFIG=release
HELP_EXIT_CODE=0
DIRECTORIES_TO_CLEAN=(
_install
_build
_repo
src/usd-plugins/schema/omniExampleCodelessSchema/generated
src/usd-plugins/schema/omniExampleSchema/generated
src/usd-plugins/schema/omniMetSchema/generated
)
while [ $# -gt 0 ]
do
if [[ "$1" == "--clean" ]]
then
CLEAN=true
fi
if [[ "$1" == "--generate" ]]
then
GENERATE=true
fi
if [[ "$1" == "--build" ]]
then
BUILD=true
fi
if [[ "$1" == "--prep-ov-install" ]]
then
STAGE=true
fi
if [[ "$1" == "--configure" ]]
then
CONFIGURE=true
fi
if [[ "$1" == "--debug" ]]
then
CONFIG=debug
fi
if [[ "$1" == "--help" ]]
then
HELP=true
fi
shift
done
if [[
"$CLEAN" != "true"
&& "$GENERATE" != "true"
&& "$BUILD" != "true"
&& "$STAGE" != "true"
&& "$CONFIGURE" != "true"
&& "$HELP" != "true"
]]
then
# default action when no arguments are passed is to do everything
GENERATE=true
BUILD=true
STAGE=true
CONFIGURE=true
fi
# requesting how to run the script
if [[ "$HELP" == "true" ]]
then
echo "build.sh [--clean] [--generate] [--build] [--stage] [--configure] [--debug] [--help]"
echo "--clean: Removes the following directories (customize as needed):"
for dir_to_clean in "${DIRECTORIES_TO_CLEAN[@]}" ; do
echo " $dir_to_clean"
done
echo "--generate: Perform code generation of schema libraries"
echo "--build: Perform compilation and installation of USD schema libraries"
echo "--prep-ov-install: Preps the kit-extension by copying it to the _install directory and stages the"
echo " built USD schema libraries in the appropriate sub-structure"
echo "--configure: Performs a configuration step after you have built and"
echo " staged the schema libraries to ensure the plugInfo.json has the right information"
echo "--debug: Performs the steps with a debug configuration instead of release"
echo " (default = release)"
echo "--help: Display this help message"
exit $HELP_EXIT_CODE
fi
# do we need to clean?
if [[ "$CLEAN" == "true" ]]
then
for dir_to_clean in "${DIRECTORIES_TO_CLEAN[@]}" ; do
rm -rf "$CWD/$dir_to_clean"
done
fi
# do we need to generate?
if [[ "$GENERATE" == "true" ]]
then
# pull down NVIDIA USD libraries
# NOTE: If you have your own local build, you can comment out this step
$CWD/tools/packman/packman pull deps/usd-deps.packman.xml -p linux-$(arch) -t config=$CONFIG
# generate the schema code and plug-in information
# NOTE: this will pull the NVIDIA repo_usd package to do this work
export CONFIG=$CONFIG
$CWD/tools/packman/python.sh bootstrap.py usd --configuration $CONFIG
fi
# do we need to build?
# NOTE: Modify this build step if using a build system other than cmake (ie, premake)
if [[ "$BUILD" == "true" ]]
then
# pull down target-deps to build dynamic payload which relies on CURL
$CWD/tools/packman/packman pull deps/target-deps.packman.xml -p linux-$(arch) -t config=$CONFIG
# Below is an example of using CMake to build the generated files
cmake -B ./_build/cmake -DCMAKE_BUILD_TYPE=$CONFIG
cmake --build ./_build/cmake --config $CONFIG --target install
fi
# do we need to configure? This will configure the plugInfo.json files
if [[ "$CONFIGURE" == "true" ]]
then
$CWD/tools/packman/python.sh bootstrap.py usd --configure-pluginfo --configuration $CONFIG
fi
# do we need to stage?
if [[ "$STAGE" == "true" ]]
then
mkdir -p $CWD/_install/linux-$(arch)/$CONFIG
cp -rf $CWD/src/kit-extension/exts/omni.example.schema $CWD/_install/linux-$(arch)/$CONFIG/
mkdir -p $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleSchema
mkdir -p $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleCodelessSchema
cp -rf $CWD/_install/linux-$(arch)/$CONFIG/omniExampleSchema/OmniExampleSchema/*.* $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleSchema/
cp -rf $CWD/_install/linux-$(arch)/$CONFIG/omniExampleSchema/include $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleSchema/
cp -rf $CWD/_install/linux-$(arch)/$CONFIG/omniExampleSchema/lib $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleSchema/
cp -rf $CWD/_install/linux-$(arch)/$CONFIG/omniExampleSchema/resources $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleSchema/
cp -rf $CWD/_install/linux-$(arch)/$CONFIG/omniExampleCodelessSchema/* $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleCodelessSchema/
fi |
MomentFactory/Omniverse-MPCDI-converter/link_app.bat | @echo off
call "%~dp0tools\packman\python.bat" %~dp0tools\scripts\link_app.py %*
if %errorlevel% neq 0 ( goto Error )
:Success
exit /b 0
:Error
exit /b %errorlevel%
|
MomentFactory/Omniverse-MPCDI-converter/repo.toml | # common settings for repo_usd for all USD plug-ins
[repo_usd]
usd_root = "${root}/_build/usd-deps/nv-usd/%{config}"
# usd_root = "${root}/../../USD_INSTALLATIONS/USD_22-11"
usd_python_root = "${root}/_build/usd-deps/python"
generate_plugin_buildfiles = true
plugin_buildfile_format = "cmake"
generate_root_buildfile = true
[repo_usd.plugin.mpcdiFileFormat]
plugin_dir = "${root}/src/usd-plugins/fileFormat/mpcdiFileFormat"
install_root = "${root}/_install/%{platform}/%{config}/mpcdiFileFormat"
include_dir = "include/mpcdiFileFormat"
additional_include_dirs = [
"../../../../_build/usd-deps/nv_usd/%{config}/include/tbb"
]
public_headers = [
"api.h",
"iMpcdiDataProvider.h",
"mpcdiDataProviderFactory.h"
]
private_headers = [
"mpcdiData.cpp",
"mpcdiPluginManager.h",
"mpcdiFileFormat.h",
"tinyxml2.h"
]
cpp_files = [
"mpcdiData.cpp",
"mpcdiDataProviderFactory.cpp",
"iMpcdiDataProvider.cpp",
"mpcdiPluginManager.cpp",
"mpcdiFileFormat.cpp",
"tinyxml2.cpp"
]
resource_files = [
"plugInfo.json"
]
usd_lib_dependencies = [
"arch",
"tf",
"plug",
"vt",
"gf",
"sdf",
"js",
"pcp",
"usdGeom",
"usd",
"usdLux"
]
|
MomentFactory/Omniverse-MPCDI-converter/README.md | # mf.ov.mpcdi_converter
An Omniverse extension for MPDCI files.
Support MPCDI* to OpenUSD conversion as well as References to MPDCI files through a native USD FileFormat plugin.
MPCDI* is a VESA interchange format for videoprojectors technical data.
*Multiple Projection Common Data Interchange
MPCDIv2 is under Copyright © 2013 – 2015 Video Electronics Standards Association. All rights reserved.
## Requirements
- Requires Omniverse Kit >= 105.1
- Tested in USD Composer 2023.2.2 and 2023.2.0
## Build
The extension comes pre-built for Omniverse users but here are the steps if you want to build it by yourself.
### Build DLL for Omniverse
Just run `build.bat`.
### Test in Omniverse
1. `Window` > `Extensions`
2. ☰ > Settings
3. ✚ Add `_install\windows-x86_64\release` folder to the Extension Search Paths
4. The user extension should appear on the left
5. `Autoload` needs to be checked for the FileFormat plugin to be correctly loaded at USD Runtime.
### Build DLL for USDview
The dependency configuration is contained in the [usd-deps.packman.xml](deps/usd-deps.packman.xml) file
To switch to the correct OpenUSD version for USDview compilation, it is required to edit the packman configuration file to:
```
<project toolsVersion="5.6">
<dependency name="nv-usd" linkPath="../_build/usd-deps/nv-usd/${config}">
<package name="usd.py310.${platform}.usdview.${config}" version="0.23.05-tc.47+v23.05.b53573ea" />
</dependency>
<dependency name="python" linkPath="../_build/usd-deps/python">
<package name="python" version="3.10.13+nv1-${platform}" />
</dependency>
</project>
```
Then build as usual with `./build.bat`
To run USDview :
- `source setenvwindows`
- `usdview resource/scene.usda`
### Other OpenUSD compatible platforms
Waiting for an improved build process, we documented how you can build for other platforms (Unreal, Blender) in [this repo](https://github.com/MomentFactory/Omniverse-MVR-GDTF-converter).
## Using the extension
Enable the Extension ( `Window` > `Extensions` from USD Composer ).
[A sample MPCDI file](./exts/mf.ov.mpcdi_converter/mf/ov/mpcdi_converter/sample/Cube-mapping.mpcdi.xml) is provided.
### Reference an MPCDI file
To reference an MPCDI file, just drag and drop the file on your viewport or your Stage Window.
### Convert an MPCDI file
Three ways to convert from USD Composer :
1. `File` > `Import`.
Or from the Content window :
2. `+Import` button.
3. Right click > `Convert to USD` on an `.mpcdi.xml` file.
## Implementation note
- Since they are no projectors in Omniverse, a projector will be represented as:
- A camera with the frustum of the projector
- A child `RectLight` with the correct frustum that represents the light emitted
- A simple mesh to represent the physical projector box
- Each buffer is represented as a scope in the scene tree with each projector as a child.
- MPCDI \<Extensions\> are currently ignored
- The frustum of each projector is currently calculated with a focus distance of 2 unit and a focal length of 10.
## Resources
- Inspired by : [NVIDIA' usd-plugin-sample](https://github.com/NVIDIA-Omniverse/usd-plugin-samples)
- [MPCDI Christie Digital Github](https://github.com/ChristieDigital/mpcdi/blob/master/MPCDI_explained.md)
- MPCDIv2 standard can be downloaded from [the VESA website](https://vesa.org/vesa-standards/)
- MPCDIv2 is under Copyright © 2013 – 2015 Video Electronics Standards Association. All rights reserved.
## Known issues
- While USD Cameras support Lens shift through the `offset`, the `RectLight` used to simulate the projector light does not offer such feature yet.
- Does not support yet the full MPCDI zip archive, only `.mpcdi.xml`
- XML extension usage : Fileformat plugin doesn't support having multiple extenions such as .mpcdi.xml (while Omniverse allows it). Currently this extension uses the .xml extension, which is not very convenient. |
MomentFactory/Omniverse-MPCDI-converter/setenvwindows.bat | :: Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
::
:: NVIDIA CORPORATION and its licensors retain all intellectual property
:: and proprietary rights in and to this software, related documentation
:: and any modifications thereto. Any use, reproduction, disclosure or
:: distribution of this software and related documentation without an express
:: license agreement from NVIDIA CORPORATION is strictly prohibited.
@echo off
set CONFIG=release
:parseargs
if not "%1" == "" (
if "%1" == "debug" (
set CONFIG=debug
)
shift
goto parseargs
)
echo Setting environment for %CONFIG% configuration...
if not exist %~dp0_venv (
%~dp0_build\usd-deps\python\python.exe -m venv %~dp0_venv
call "%~dp0_venv\Scripts\activate.bat"
pip install PySide2
pip install PyOpenGL
pip install warp-lang
) else (
call "%~dp0_venv\Scripts\activate.bat"
)
set PYTHONPATH=%~dp0_build\usd-deps\nv-usd\%CONFIG%\lib\python;%~dp0_build\target-deps\omni-geospatial;%~dp0_install\windows-x86_64\%CONFIG%\omniWarpSceneIndex
set PATH=%PATH%;%~dp0_build\usd-deps\python;%~dp0_build\usd-deps\nv-usd\%CONFIG%\bin;%~dp0_build\usd-deps\nv-usd\%CONFIG%\lib;%~dp0_build\target-deps\zlib\lib\rt_dynamic\release;%~dp0_install\windows-x86_64\%CONFIG%\edfFileFormat\lib;%~dp0_install\windows-x86_64\%CONFIG%\omniMetProvider\lib;%~dp0_build\target-deps\omni-geospatial\bin;$~dp0_install\windows-x86_64\$CONFIG\omniWarpSceneIndex\lib
set PXR_PLUGINPATH_NAME=%~dp0_install\windows-x86_64\%CONFIG%\omniMetSchema\resources;%~dp0_install\windows-x86_64\%CONFIG%\edfFileFormat\resources;%~dp0_install\windows-x86_64\%CONFIG%\omniMetProvider\resources;%~dp0_build\target-deps\omni-geospatial\plugins\OmniGeospatial\resources;%~dp0_install\windows-x86_64\%CONFIG%\omniGeoSceneIndex\resources;%~dp0_install\windows-x86_64\%CONFIG%\omniMetricsAssembler\resources;%~dp0_install\windows-x86_64\%CONFIG%\omniWarpSceneIndex\resources
set USDIMAGINGGL_ENGINE_ENABLE_SCENE_INDEX=true |
MomentFactory/Omniverse-MPCDI-converter/deps/target-deps.packman.xml | <project toolsVersion="5.6">
<dependency name="libcurl" linkPath="../_build/target-deps/libcurl">
<package name="libcurl" version="8.1.2-3-${platform}-static-release"/>
</dependency>
<dependency name="zlib" linkPath="../_build/target-deps/zlib">
<package name="zlib" version="1.2.13+nv1-${platform}" />
</dependency>
<dependency name="openssl" linkPath="../_build/target-deps/openssl">
<package name="openssl" version="3.0.10-3-${platform}-static-release" />
</dependency>
<dependency name="omni-geospatial" linkPath="../_build/target-deps/omni-geospatial">
<package name="omni-geospatial" version="2.0.3-pxr_23_05+mr17.384.337fb43b.tc.${platform}.${config}" />
</dependency>
</project> |
MomentFactory/Omniverse-MPCDI-converter/deps/repo-deps.packman.xml | <project toolsVersion="5.6">
<dependency name="repo_usd" linkPath="../_repo/repo_usd">
<package name="repo_usd" version="4.0.1" />
</dependency>
</project> |
MomentFactory/Omniverse-MPCDI-converter/deps/usd-deps.packman.xml | <project toolsVersion="5.6">
<dependency name="nv-usd" linkPath="../_build/usd-deps/nv-usd/${config}">
<package name="nv-usd" version="22.11.nv.0.2.1071.7d2f59ad-win64_py310_${config}-dev_omniverse" platforms="windows-x86_64" />
<package name="nv-usd" version="22.11.nv.0.2.1071.7d2f59ad-linux64_py310-centos_${config}-dev_omniverse" platforms="linux-x86_64" />
<package name="nv-usd" version="22.11.nv.0.2.1071.7d2f59ad-linux-aarch64_py310_${config}-dev_omniverse" platforms="linux-aarch64" />
</dependency>
<dependency name="python" linkPath="../_build/usd-deps/python">
<package name="python" version="3.10.13+nv1-${platform}" />
</dependency>
</project>
|
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/api.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_MPCDI_API_H_
#define OMNI_MPCDI_API_H_
#include "pxr/base/arch/export.h"
#if defined(PXR_STATIC)
# define MPCDI_API
# define MPCDI_API_TEMPLATE_CLASS(...)
# define MPCDI_API_TEMPLATE_STRUCT(...)
# define MPCDI_LOCAL
#else
# if defined(MPCDIFILEFORMAT_EXPORTS)
# define MPCDI_API ARCH_EXPORT
# define MPCDI_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__)
# define MPCDI_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__)
# else
# define MPCDI_API ARCH_IMPORT
# define MPCDI_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__)
# define MPCDI_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__)
# endif
# define MPCDI_LOCAL ARCH_HIDDEN
#endif
#endif |
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/iMpcdiDataProvider.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_MPCDI_IMPCDIDATAPROVIDER_H_
#define OMNI_MPCDI_IMPCDIDATAPROVIDER_H_
#include <unordered_map>
#include <functional>
#include <memory>
#include <pxr/pxr.h>
#include <pxr/base/tf/token.h>
#include <pxr/base/vt/value.h>
#include <pxr/usd/sdf/fileFormat.h>
#include <pxr/usd/sdf/specType.h>
#include <pxr/usd/sdf/primSpec.h>
#include "api.h"
PXR_NAMESPACE_OPEN_SCOPE
///
/// \struct EdfDataParameters
///
/// Represents a class used to hold the specific metadata
/// parameter values used to construct the dynamic layer.
///
struct EdfDataParameters
{
public:
std::string dataProviderId;
std::unordered_map<std::string, std::string> providerArgs;
// conversion functions to and from USD structures
static EdfDataParameters FromFileFormatArgs(const SdfFileFormat::FileFormatArguments& args);
};
///
/// \class IEdfSourceData
///
/// Interface for data providers to create prim / attribute information
/// and to read back attribute values as needed.
///
class IEdfSourceData
{
public:
MPCDI_API virtual ~IEdfSourceData();
/// Creates a new prim from data read from a back-end data source.
/// \param parentPath The prim path that will be the parent of the newly created prim.
/// \param name The name of the new prim. This must be a valid USD identifier.
/// \param specifier The spec type of the new prim (e.g., def, over, etc.).
/// \param typeName The name of the type of the prim.
///
MPCDI_API virtual void CreatePrim(const SdfPath& parentPath, const std::string& name, const SdfSpecifier& specifier,
const TfToken& typeName) = 0;
/// Creates a new attribute on the specified prim.
/// \param parentPrimPath The prim path of the prim that will contain the attribute.
/// \param name The name of the attribute.
/// \param typeName The name of the type of the attribute.
/// \param variability The variability of the attribute (e.g., uniformm, varying, etc.).
/// \param value The default value of the new attribute.
///
MPCDI_API virtual void CreateAttribute(const SdfPath& parentPrimPath, const std::string& name, const SdfValueTypeName& typeName,
const SdfVariability& variability, const VtValue& value) = 0;
/// Sets the value of a field on a prim at the given path.
/// If the value exists, the current value will be overwritten.
/// \param primPath The full path of the prim to set the field value for.
/// \param fieldName The name of the field to set.
/// \param value The value to set.
///
MPCDI_API virtual void SetField(const SdfPath& primPath, const TfToken& fieldName, const VtValue& value) = 0;
/// Determines if the field fieldName exists on the given prim path.
/// If the field exists, the current value will be returned in value if value is valid.
/// \param primPath The full path of the prim to look for the field.
/// \param fieldName The name of the field to look for on the prim.
/// \param value A pointer to a VtValue object that will be filled with the value of
/// the field if it exists.
///
MPCDI_API virtual bool HasField(const SdfPath& primPath, const TfToken& fieldName, VtValue* value) = 0;
/// Determines if the attribute at the given path exists and if so, returns the default value.
/// \param attributePath The full path of the attribute (i.e., primPath + "." + attributeName).
/// \param defaultValue A pointer to a VtValue object that will be filled with the default value
/// of the attribute if it exists.
///
MPCDI_API virtual bool HasAttribute(const SdfPath& attributePath, VtValue* defaultValue) = 0;
};
///
/// \class IEdfDataProvider
///
/// Interface for acquring data from an external data system based on a set of
/// metadata parameters fed to a dynamic payload. This object is responsible for
/// acquiring the data from the external system and turning it into USD representations
/// that can be added to a layer.
///
class IEdfDataProvider
{
public:
MPCDI_API virtual ~IEdfDataProvider();
// disallow copies
IEdfDataProvider(const IEdfDataProvider&) = delete;
IEdfDataProvider& operator=(const IEdfDataProvider&) = delete;
/// Asks the data provider to read whatever information they would like to read
/// from the back-end system when a payload layer is first opened.
///
/// \param sourceData The source data interface which the data provider
/// can use to create prims / attributes as needed when
/// they read data from their back-end.
///
MPCDI_API virtual bool Read(std::shared_ptr<IEdfSourceData> sourceData) = 0;
/// Asks the data provider to read whatever would be considered the
/// children of the provided prim path. This gives the opportunity
/// for the data provider to defer reading hierarhical children
/// from their back-end store all at once when the data is large.
///
/// \param primPath The path of the prim to create children for.
/// This value is either "/Data", indicating the root
/// of the hierarchy, or the full path to a prim
/// that was created by the data provider previously
/// on a Read / ReadChildren call.
///
/// \param sourceData The source data interface which the data provider
/// can use to create prims / attributes as needed when
/// they read data from their back-end.
///
MPCDI_API virtual bool ReadChildren(const std::string& primPath, std::shared_ptr<IEdfSourceData> sourceData) = 0;
/// Asks the data provider whether all of its data was read on the initial
/// Read call (i.e. the data has been cached in the source) or not.
///
/// \returns True if all data was read on initial Read, false otherwise.
MPCDI_API virtual bool IsDataCached() const = 0;
protected:
MPCDI_API IEdfDataProvider(const EdfDataParameters& parameters);
MPCDI_API const EdfDataParameters& GetParameters() const;
private:
EdfDataParameters _parameters;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif |
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/tinyxml2.h | /*
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.
*/
#ifndef TINYXML2_INCLUDED
#define TINYXML2_INCLUDED
#if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__)
# include <ctype.h>
# include <limits.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# if defined(__PS3__)
# include <stddef.h>
# endif
#else
# include <cctype>
# include <climits>
# include <cstdio>
# include <cstdlib>
# include <cstring>
#endif
#include <stdint.h>
/*
TODO: intern strings instead of allocation.
*/
/*
gcc:
g++ -Wall -DTINYXML2_DEBUG tinyxml2.cpp xmltest.cpp -o gccxmltest.exe
Formatting, Artistic Style:
AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h
*/
#if defined( _DEBUG ) || defined (__DEBUG__)
# ifndef TINYXML2_DEBUG
# define TINYXML2_DEBUG
# endif
#endif
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4251)
#endif
#ifdef _WIN32
# ifdef TINYXML2_EXPORT
# define TINYXML2_LIB __declspec(dllexport)
# elif defined(TINYXML2_IMPORT)
# define TINYXML2_LIB __declspec(dllimport)
# else
# define TINYXML2_LIB
# endif
#elif __GNUC__ >= 4
# define TINYXML2_LIB __attribute__((visibility("default")))
#else
# define TINYXML2_LIB
#endif
#if !defined(TIXMLASSERT)
#if defined(TINYXML2_DEBUG)
# if defined(_MSC_VER)
# // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like
# define TIXMLASSERT( x ) do { if ( !((void)0,(x))) { __debugbreak(); } } while(false)
# elif defined (ANDROID_NDK)
# include <android/log.h>
# define TIXMLASSERT( x ) do { if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } } while(false)
# else
# include <assert.h>
# define TIXMLASSERT assert
# endif
#else
# define TIXMLASSERT( x ) do {} while(false)
#endif
#endif
/* Versioning, past 1.0.14:
http://semver.org/
*/
static const int TIXML2_MAJOR_VERSION = 9;
static const int TIXML2_MINOR_VERSION = 0;
static const int TIXML2_PATCH_VERSION = 0;
#define TINYXML2_MAJOR_VERSION 9
#define TINYXML2_MINOR_VERSION 0
#define TINYXML2_PATCH_VERSION 0
// A fixed element depth limit is problematic. There needs to be a
// limit to avoid a stack overflow. However, that limit varies per
// system, and the capacity of the stack. On the other hand, it's a trivial
// attack that can result from ill, malicious, or even correctly formed XML,
// so there needs to be a limit in place.
static const int TINYXML2_MAX_ELEMENT_DEPTH = 500;
namespace tinyxml2
{
class XMLDocument;
class XMLElement;
class XMLAttribute;
class XMLComment;
class XMLText;
class XMLDeclaration;
class XMLUnknown;
class XMLPrinter;
/*
A class that wraps strings. Normally stores the start and end
pointers into the XML file itself, and will apply normalization
and entity translation if actually read. Can also store (and memory
manage) a traditional char[]
Isn't clear why TINYXML2_LIB is needed; but seems to fix #719
*/
class TINYXML2_LIB StrPair
{
public:
enum Mode {
NEEDS_ENTITY_PROCESSING = 0x01,
NEEDS_NEWLINE_NORMALIZATION = 0x02,
NEEDS_WHITESPACE_COLLAPSING = 0x04,
TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION,
ATTRIBUTE_NAME = 0,
ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION,
ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION,
COMMENT = NEEDS_NEWLINE_NORMALIZATION
};
StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {}
~StrPair();
void Set( char* start, char* end, int flags ) {
TIXMLASSERT( start );
TIXMLASSERT( end );
Reset();
_start = start;
_end = end;
_flags = flags | NEEDS_FLUSH;
}
const char* GetStr();
bool Empty() const {
return _start == _end;
}
void SetInternedStr( const char* str ) {
Reset();
_start = const_cast<char*>(str);
}
void SetStr( const char* str, int flags=0 );
char* ParseText( char* in, const char* endTag, int strFlags, int* curLineNumPtr );
char* ParseName( char* in );
void TransferTo( StrPair* other );
void Reset();
private:
void CollapseWhitespace();
enum {
NEEDS_FLUSH = 0x100,
NEEDS_DELETE = 0x200
};
int _flags;
char* _start;
char* _end;
StrPair( const StrPair& other ); // not supported
void operator=( const StrPair& other ); // not supported, use TransferTo()
};
/*
A dynamic array of Plain Old Data. Doesn't support constructors, etc.
Has a small initial memory pool, so that low or no usage will not
cause a call to new/delete
*/
template <class T, int INITIAL_SIZE>
class DynArray
{
public:
DynArray() :
_mem( _pool ),
_allocated( INITIAL_SIZE ),
_size( 0 )
{
}
~DynArray() {
if ( _mem != _pool ) {
delete [] _mem;
}
}
void Clear() {
_size = 0;
}
void Push( T t ) {
TIXMLASSERT( _size < INT_MAX );
EnsureCapacity( _size+1 );
_mem[_size] = t;
++_size;
}
T* PushArr( int count ) {
TIXMLASSERT( count >= 0 );
TIXMLASSERT( _size <= INT_MAX - count );
EnsureCapacity( _size+count );
T* ret = &_mem[_size];
_size += count;
return ret;
}
T Pop() {
TIXMLASSERT( _size > 0 );
--_size;
return _mem[_size];
}
void PopArr( int count ) {
TIXMLASSERT( _size >= count );
_size -= count;
}
bool Empty() const {
return _size == 0;
}
T& operator[](int i) {
TIXMLASSERT( i>= 0 && i < _size );
return _mem[i];
}
const T& operator[](int i) const {
TIXMLASSERT( i>= 0 && i < _size );
return _mem[i];
}
const T& PeekTop() const {
TIXMLASSERT( _size > 0 );
return _mem[ _size - 1];
}
int Size() const {
TIXMLASSERT( _size >= 0 );
return _size;
}
int Capacity() const {
TIXMLASSERT( _allocated >= INITIAL_SIZE );
return _allocated;
}
void SwapRemove(int i) {
TIXMLASSERT(i >= 0 && i < _size);
TIXMLASSERT(_size > 0);
_mem[i] = _mem[_size - 1];
--_size;
}
const T* Mem() const {
TIXMLASSERT( _mem );
return _mem;
}
T* Mem() {
TIXMLASSERT( _mem );
return _mem;
}
private:
DynArray( const DynArray& ); // not supported
void operator=( const DynArray& ); // not supported
void EnsureCapacity( int cap ) {
TIXMLASSERT( cap > 0 );
if ( cap > _allocated ) {
TIXMLASSERT( cap <= INT_MAX / 2 );
const int newAllocated = cap * 2;
T* newMem = new T[newAllocated];
TIXMLASSERT( newAllocated >= _size );
memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs
if ( _mem != _pool ) {
delete [] _mem;
}
_mem = newMem;
_allocated = newAllocated;
}
}
T* _mem;
T _pool[INITIAL_SIZE];
int _allocated; // objects allocated
int _size; // number objects in use
};
/*
Parent virtual class of a pool for fast allocation
and deallocation of objects.
*/
class MemPool
{
public:
MemPool() {}
virtual ~MemPool() {}
virtual int ItemSize() const = 0;
virtual void* Alloc() = 0;
virtual void Free( void* ) = 0;
virtual void SetTracked() = 0;
};
/*
Template child class to create pools of the correct type.
*/
template< int ITEM_SIZE >
class MemPoolT : public MemPool
{
public:
MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {}
~MemPoolT() {
MemPoolT< ITEM_SIZE >::Clear();
}
void Clear() {
// Delete the blocks.
while( !_blockPtrs.Empty()) {
Block* lastBlock = _blockPtrs.Pop();
delete lastBlock;
}
_root = 0;
_currentAllocs = 0;
_nAllocs = 0;
_maxAllocs = 0;
_nUntracked = 0;
}
virtual int ItemSize() const {
return ITEM_SIZE;
}
int CurrentAllocs() const {
return _currentAllocs;
}
virtual void* Alloc() {
if ( !_root ) {
// Need a new block.
Block* block = new Block;
_blockPtrs.Push( block );
Item* blockItems = block->items;
for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) {
blockItems[i].next = &(blockItems[i + 1]);
}
blockItems[ITEMS_PER_BLOCK - 1].next = 0;
_root = blockItems;
}
Item* const result = _root;
TIXMLASSERT( result != 0 );
_root = _root->next;
++_currentAllocs;
if ( _currentAllocs > _maxAllocs ) {
_maxAllocs = _currentAllocs;
}
++_nAllocs;
++_nUntracked;
return result;
}
virtual void Free( void* mem ) {
if ( !mem ) {
return;
}
--_currentAllocs;
Item* item = static_cast<Item*>( mem );
#ifdef TINYXML2_DEBUG
memset( item, 0xfe, sizeof( *item ) );
#endif
item->next = _root;
_root = item;
}
void Trace( const char* name ) {
printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n",
name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs,
ITEM_SIZE, _nAllocs, _blockPtrs.Size() );
}
void SetTracked() {
--_nUntracked;
}
int Untracked() const {
return _nUntracked;
}
// This number is perf sensitive. 4k seems like a good tradeoff on my machine.
// The test file is large, 170k.
// Release: VS2010 gcc(no opt)
// 1k: 4000
// 2k: 4000
// 4k: 3900 21000
// 16k: 5200
// 32k: 4300
// 64k: 4000 21000
// Declared public because some compilers do not accept to use ITEMS_PER_BLOCK
// in private part if ITEMS_PER_BLOCK is private
enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE };
private:
MemPoolT( const MemPoolT& ); // not supported
void operator=( const MemPoolT& ); // not supported
union Item {
Item* next;
char itemData[ITEM_SIZE];
};
struct Block {
Item items[ITEMS_PER_BLOCK];
};
DynArray< Block*, 10 > _blockPtrs;
Item* _root;
int _currentAllocs;
int _nAllocs;
int _maxAllocs;
int _nUntracked;
};
/**
Implements the interface to the "Visitor pattern" (see the Accept() method.)
If you call the Accept() method, it requires being passed a XMLVisitor
class to handle callbacks. For nodes that contain other nodes (Document, Element)
you will get called with a VisitEnter/VisitExit pair. Nodes that are always leafs
are simply called with Visit().
If you return 'true' from a Visit method, recursive parsing will continue. If you return
false, <b>no children of this node or its siblings</b> will be visited.
All flavors of Visit methods have a default implementation that returns 'true' (continue
visiting). You need to only override methods that are interesting to you.
Generally Accept() is called on the XMLDocument, although all nodes support visiting.
You should never change the document from a callback.
@sa XMLNode::Accept()
*/
class TINYXML2_LIB XMLVisitor
{
public:
virtual ~XMLVisitor() {}
/// Visit a document.
virtual bool VisitEnter( const XMLDocument& /*doc*/ ) {
return true;
}
/// Visit a document.
virtual bool VisitExit( const XMLDocument& /*doc*/ ) {
return true;
}
/// Visit an element.
virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) {
return true;
}
/// Visit an element.
virtual bool VisitExit( const XMLElement& /*element*/ ) {
return true;
}
/// Visit a declaration.
virtual bool Visit( const XMLDeclaration& /*declaration*/ ) {
return true;
}
/// Visit a text node.
virtual bool Visit( const XMLText& /*text*/ ) {
return true;
}
/// Visit a comment node.
virtual bool Visit( const XMLComment& /*comment*/ ) {
return true;
}
/// Visit an unknown node.
virtual bool Visit( const XMLUnknown& /*unknown*/ ) {
return true;
}
};
// WARNING: must match XMLDocument::_errorNames[]
enum XMLError {
XML_SUCCESS = 0,
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,
XML_ERROR_COUNT
};
/*
Utility functionality.
*/
class TINYXML2_LIB XMLUtil
{
public:
static const char* SkipWhiteSpace( const char* p, int* curLineNumPtr ) {
TIXMLASSERT( p );
while( IsWhiteSpace(*p) ) {
if (curLineNumPtr && *p == '\n') {
++(*curLineNumPtr);
}
++p;
}
TIXMLASSERT( p );
return p;
}
static char* SkipWhiteSpace( char* const p, int* curLineNumPtr ) {
return const_cast<char*>( SkipWhiteSpace( const_cast<const char*>(p), curLineNumPtr ) );
}
// Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't
// correct, but simple, and usually works.
static bool IsWhiteSpace( char p ) {
return !IsUTF8Continuation(p) && isspace( static_cast<unsigned char>(p) );
}
inline static bool IsNameStartChar( unsigned char ch ) {
if ( ch >= 128 ) {
// This is a heuristic guess in attempt to not implement Unicode-aware isalpha()
return true;
}
if ( isalpha( ch ) ) {
return true;
}
return ch == ':' || ch == '_';
}
inline static bool IsNameChar( unsigned char ch ) {
return IsNameStartChar( ch )
|| isdigit( ch )
|| ch == '.'
|| ch == '-';
}
inline static bool IsPrefixHex( const char* p) {
p = SkipWhiteSpace(p, 0);
return p && *p == '0' && ( *(p + 1) == 'x' || *(p + 1) == 'X');
}
inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) {
if ( p == q ) {
return true;
}
TIXMLASSERT( p );
TIXMLASSERT( q );
TIXMLASSERT( nChar >= 0 );
return strncmp( p, q, nChar ) == 0;
}
inline static bool IsUTF8Continuation( const char p ) {
return ( p & 0x80 ) != 0;
}
static const char* ReadBOM( const char* p, bool* hasBOM );
// p is the starting location,
// the UTF-8 value of the entity will be placed in value, and length filled in.
static const char* GetCharacterRef( const char* p, char* value, int* length );
static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length );
// converts primitive types to strings
static void ToStr( int v, char* buffer, int bufferSize );
static void ToStr( unsigned v, char* buffer, int bufferSize );
static void ToStr( bool v, char* buffer, int bufferSize );
static void ToStr( float v, char* buffer, int bufferSize );
static void ToStr( double v, char* buffer, int bufferSize );
static void ToStr(int64_t v, char* buffer, int bufferSize);
static void ToStr(uint64_t v, char* buffer, int bufferSize);
// converts strings to primitive types
static bool ToInt( const char* str, int* value );
static bool ToUnsigned( const char* str, unsigned* value );
static bool ToBool( const char* str, bool* value );
static bool ToFloat( const char* str, float* value );
static bool ToDouble( const char* str, double* value );
static bool ToInt64(const char* str, int64_t* value);
static bool ToUnsigned64(const char* str, uint64_t* value);
// Changes what is serialized for a boolean value.
// Default to "true" and "false". Shouldn't be changed
// unless you have a special testing or compatibility need.
// Be careful: static, global, & not thread safe.
// Be sure to set static const memory as parameters.
static void SetBoolSerialization(const char* writeTrue, const char* writeFalse);
private:
static const char* writeBoolTrue;
static const char* writeBoolFalse;
};
/** XMLNode is a base class for every object that is in the
XML Document Object Model (DOM), except XMLAttributes.
Nodes have siblings, a parent, and children which can
be navigated. A node is always in a XMLDocument.
The type of a XMLNode can be queried, and it can
be cast to its more defined type.
A XMLDocument allocates memory for all its Nodes.
When the XMLDocument gets deleted, all its Nodes
will also be deleted.
@verbatim
A Document can contain: Element (container or leaf)
Comment (leaf)
Unknown (leaf)
Declaration( leaf )
An Element can contain: Element (container or leaf)
Text (leaf)
Attributes (not on tree)
Comment (leaf)
Unknown (leaf)
@endverbatim
*/
class TINYXML2_LIB XMLNode
{
friend class XMLDocument;
friend class XMLElement;
public:
/// Get the XMLDocument that owns this XMLNode.
const XMLDocument* GetDocument() const {
TIXMLASSERT( _document );
return _document;
}
/// Get the XMLDocument that owns this XMLNode.
XMLDocument* GetDocument() {
TIXMLASSERT( _document );
return _document;
}
/// Safely cast to an Element, or null.
virtual XMLElement* ToElement() {
return 0;
}
/// Safely cast to Text, or null.
virtual XMLText* ToText() {
return 0;
}
/// Safely cast to a Comment, or null.
virtual XMLComment* ToComment() {
return 0;
}
/// Safely cast to a Document, or null.
virtual XMLDocument* ToDocument() {
return 0;
}
/// Safely cast to a Declaration, or null.
virtual XMLDeclaration* ToDeclaration() {
return 0;
}
/// Safely cast to an Unknown, or null.
virtual XMLUnknown* ToUnknown() {
return 0;
}
virtual const XMLElement* ToElement() const {
return 0;
}
virtual const XMLText* ToText() const {
return 0;
}
virtual const XMLComment* ToComment() const {
return 0;
}
virtual const XMLDocument* ToDocument() const {
return 0;
}
virtual const XMLDeclaration* ToDeclaration() const {
return 0;
}
virtual const XMLUnknown* ToUnknown() const {
return 0;
}
/** The meaning of 'value' changes for the specific type.
@verbatim
Document: empty (NULL is returned, not an empty string)
Element: name of the element
Comment: the comment text
Unknown: the tag contents
Text: the text string
@endverbatim
*/
const char* Value() const;
/** Set the Value of an XML node.
@sa Value()
*/
void SetValue( const char* val, bool staticMem=false );
/// Gets the line number the node is in, if the document was parsed from a file.
int GetLineNum() const { return _parseLineNum; }
/// Get the parent of this node on the DOM.
const XMLNode* Parent() const {
return _parent;
}
XMLNode* Parent() {
return _parent;
}
/// Returns true if this node has no children.
bool NoChildren() const {
return !_firstChild;
}
/// Get the first child node, or null if none exists.
const XMLNode* FirstChild() const {
return _firstChild;
}
XMLNode* FirstChild() {
return _firstChild;
}
/** Get the first child element, or optionally the first child
element with the specified name.
*/
const XMLElement* FirstChildElement( const char* name = 0 ) const;
XMLElement* FirstChildElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->FirstChildElement( name ));
}
/// Get the last child node, or null if none exists.
const XMLNode* LastChild() const {
return _lastChild;
}
XMLNode* LastChild() {
return _lastChild;
}
/** Get the last child element or optionally the last child
element with the specified name.
*/
const XMLElement* LastChildElement( const char* name = 0 ) const;
XMLElement* LastChildElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->LastChildElement(name) );
}
/// Get the previous (left) sibling node of this node.
const XMLNode* PreviousSibling() const {
return _prev;
}
XMLNode* PreviousSibling() {
return _prev;
}
/// Get the previous (left) sibling element of this node, with an optionally supplied name.
const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ;
XMLElement* PreviousSiblingElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->PreviousSiblingElement( name ) );
}
/// Get the next (right) sibling node of this node.
const XMLNode* NextSibling() const {
return _next;
}
XMLNode* NextSibling() {
return _next;
}
/// Get the next (right) sibling element of this node, with an optionally supplied name.
const XMLElement* NextSiblingElement( const char* name = 0 ) const;
XMLElement* NextSiblingElement( const char* name = 0 ) {
return const_cast<XMLElement*>(const_cast<const XMLNode*>(this)->NextSiblingElement( name ) );
}
/**
Add a child node as the last (right) child.
If the child node is already part of the document,
it is moved from its old location to the new location.
Returns the addThis argument or 0 if the node does not
belong to the same document.
*/
XMLNode* InsertEndChild( XMLNode* addThis );
XMLNode* LinkEndChild( XMLNode* addThis ) {
return InsertEndChild( addThis );
}
/**
Add a child node as the first (left) child.
If the child node is already part of the document,
it is moved from its old location to the new location.
Returns the addThis argument or 0 if the node does not
belong to the same document.
*/
XMLNode* InsertFirstChild( XMLNode* addThis );
/**
Add a node after the specified child node.
If the child node is already part of the document,
it is moved from its old location to the new location.
Returns the addThis argument or 0 if the afterThis node
is not a child of this node, or if the node does not
belong to the same document.
*/
XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis );
/**
Delete all the children of this node.
*/
void DeleteChildren();
/**
Delete a child of this node.
*/
void DeleteChild( XMLNode* node );
/**
Make a copy of this node, but not its children.
You may pass in a Document pointer that will be
the owner of the new Node. If the 'document' is
null, then the node returned will be allocated
from the current Document. (this->GetDocument())
Note: if called on a XMLDocument, this will return null.
*/
virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0;
/**
Make a copy of this node and all its children.
If the 'target' is null, then the nodes will
be allocated in the current document. If 'target'
is specified, the memory will be allocated is the
specified XMLDocument.
NOTE: This is probably not the correct tool to
copy a document, since XMLDocuments can have multiple
top level XMLNodes. You probably want to use
XMLDocument::DeepCopy()
*/
XMLNode* DeepClone( XMLDocument* target ) const;
/**
Test if 2 nodes are the same, but don't test children.
The 2 nodes do not need to be in the same Document.
Note: if called on a XMLDocument, this will return false.
*/
virtual bool ShallowEqual( const XMLNode* compare ) const = 0;
/** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the
XML tree will be conditionally visited and the host will be called back
via the XMLVisitor interface.
This is essentially a SAX interface for TinyXML-2. (Note however it doesn't re-parse
the XML for the callbacks, so the performance of TinyXML-2 is unchanged by using this
interface versus any other.)
The interface has been based on ideas from:
- http://www.saxproject.org/
- http://c2.com/cgi/wiki?HierarchicalVisitorPattern
Which are both good references for "visiting".
An example of using Accept():
@verbatim
XMLPrinter printer;
tinyxmlDoc.Accept( &printer );
const char* xmlcstr = printer.CStr();
@endverbatim
*/
virtual bool Accept( XMLVisitor* visitor ) const = 0;
/**
Set user data into the XMLNode. TinyXML-2 in
no way processes or interprets user data.
It is initially 0.
*/
void SetUserData(void* userData) { _userData = userData; }
/**
Get user data set into the XMLNode. TinyXML-2 in
no way processes or interprets user data.
It is initially 0.
*/
void* GetUserData() const { return _userData; }
protected:
explicit XMLNode( XMLDocument* );
virtual ~XMLNode();
virtual char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr);
XMLDocument* _document;
XMLNode* _parent;
mutable StrPair _value;
int _parseLineNum;
XMLNode* _firstChild;
XMLNode* _lastChild;
XMLNode* _prev;
XMLNode* _next;
void* _userData;
private:
MemPool* _memPool;
void Unlink( XMLNode* child );
static void DeleteNode( XMLNode* node );
void InsertChildPreamble( XMLNode* insertThis ) const;
const XMLElement* ToElementWithName( const char* name ) const;
XMLNode( const XMLNode& ); // not supported
XMLNode& operator=( const XMLNode& ); // not supported
};
/** XML text.
Note that a text node can have child element nodes, for example:
@verbatim
<root>This is <b>bold</b></root>
@endverbatim
A text node can have 2 ways to output the next. "normal" output
and CDATA. It will default to the mode it was parsed from the XML file and
you generally want to leave it alone, but you can change the output mode with
SetCData() and query it with CData().
*/
class TINYXML2_LIB XMLText : public XMLNode
{
friend class XMLDocument;
public:
virtual bool Accept( XMLVisitor* visitor ) const;
virtual XMLText* ToText() {
return this;
}
virtual const XMLText* ToText() const {
return this;
}
/// Declare whether this should be CDATA or standard text.
void SetCData( bool isCData ) {
_isCData = isCData;
}
/// Returns true if this is a CDATA text element.
bool CData() const {
return _isCData;
}
virtual XMLNode* ShallowClone( XMLDocument* document ) const;
virtual bool ShallowEqual( const XMLNode* compare ) const;
protected:
explicit XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {}
virtual ~XMLText() {}
char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr );
private:
bool _isCData;
XMLText( const XMLText& ); // not supported
XMLText& operator=( const XMLText& ); // not supported
};
/** An XML Comment. */
class TINYXML2_LIB XMLComment : public XMLNode
{
friend class XMLDocument;
public:
virtual XMLComment* ToComment() {
return this;
}
virtual const XMLComment* ToComment() const {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const;
virtual XMLNode* ShallowClone( XMLDocument* document ) const;
virtual bool ShallowEqual( const XMLNode* compare ) const;
protected:
explicit XMLComment( XMLDocument* doc );
virtual ~XMLComment();
char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr);
private:
XMLComment( const XMLComment& ); // not supported
XMLComment& operator=( const XMLComment& ); // not supported
};
/** In correct XML the declaration is the first entry in the file.
@verbatim
<?xml version="1.0" standalone="yes"?>
@endverbatim
TinyXML-2 will happily read or write files without a declaration,
however.
The text of the declaration isn't interpreted. It is parsed
and written as a string.
*/
class TINYXML2_LIB XMLDeclaration : public XMLNode
{
friend class XMLDocument;
public:
virtual XMLDeclaration* ToDeclaration() {
return this;
}
virtual const XMLDeclaration* ToDeclaration() const {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const;
virtual XMLNode* ShallowClone( XMLDocument* document ) const;
virtual bool ShallowEqual( const XMLNode* compare ) const;
protected:
explicit XMLDeclaration( XMLDocument* doc );
virtual ~XMLDeclaration();
char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr );
private:
XMLDeclaration( const XMLDeclaration& ); // not supported
XMLDeclaration& operator=( const XMLDeclaration& ); // not supported
};
/** Any tag that TinyXML-2 doesn't recognize is saved as an
unknown. It is a tag of text, but should not be modified.
It will be written back to the XML, unchanged, when the file
is saved.
DTD tags get thrown into XMLUnknowns.
*/
class TINYXML2_LIB XMLUnknown : public XMLNode
{
friend class XMLDocument;
public:
virtual XMLUnknown* ToUnknown() {
return this;
}
virtual const XMLUnknown* ToUnknown() const {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const;
virtual XMLNode* ShallowClone( XMLDocument* document ) const;
virtual bool ShallowEqual( const XMLNode* compare ) const;
protected:
explicit XMLUnknown( XMLDocument* doc );
virtual ~XMLUnknown();
char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr );
private:
XMLUnknown( const XMLUnknown& ); // not supported
XMLUnknown& operator=( const XMLUnknown& ); // not supported
};
/** An attribute is a name-value pair. Elements have an arbitrary
number of attributes, each with a unique name.
@note The attributes are not XMLNodes. You may only query the
Next() attribute in a list.
*/
class TINYXML2_LIB XMLAttribute
{
friend class XMLElement;
public:
/// The name of the attribute.
const char* Name() const;
/// The value of the attribute.
const char* Value() const;
/// Gets the line number the attribute is in, if the document was parsed from a file.
int GetLineNum() const { return _parseLineNum; }
/// The next attribute in the list.
const XMLAttribute* Next() const {
return _next;
}
/** IntValue interprets the attribute as an integer, and returns the value.
If the value isn't an integer, 0 will be returned. There is no error checking;
use QueryIntValue() if you need error checking.
*/
int IntValue() const {
int i = 0;
QueryIntValue(&i);
return i;
}
int64_t Int64Value() const {
int64_t i = 0;
QueryInt64Value(&i);
return i;
}
uint64_t Unsigned64Value() const {
uint64_t i = 0;
QueryUnsigned64Value(&i);
return i;
}
/// Query as an unsigned integer. See IntValue()
unsigned UnsignedValue() const {
unsigned i=0;
QueryUnsignedValue( &i );
return i;
}
/// Query as a boolean. See IntValue()
bool BoolValue() const {
bool b=false;
QueryBoolValue( &b );
return b;
}
/// Query as a double. See IntValue()
double DoubleValue() const {
double d=0;
QueryDoubleValue( &d );
return d;
}
/// Query as a float. See IntValue()
float FloatValue() const {
float f=0;
QueryFloatValue( &f );
return f;
}
/** QueryIntValue interprets the attribute as an integer, and returns the value
in the provided parameter. The function will return XML_SUCCESS on success,
and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful.
*/
XMLError QueryIntValue( int* value ) const;
/// See QueryIntValue
XMLError QueryUnsignedValue( unsigned int* value ) const;
/// See QueryIntValue
XMLError QueryInt64Value(int64_t* value) const;
/// See QueryIntValue
XMLError QueryUnsigned64Value(uint64_t* value) const;
/// See QueryIntValue
XMLError QueryBoolValue( bool* value ) const;
/// See QueryIntValue
XMLError QueryDoubleValue( double* value ) const;
/// See QueryIntValue
XMLError QueryFloatValue( float* value ) const;
/// Set the attribute to a string value.
void SetAttribute( const char* value );
/// Set the attribute to value.
void SetAttribute( int value );
/// Set the attribute to value.
void SetAttribute( unsigned value );
/// Set the attribute to value.
void SetAttribute(int64_t value);
/// Set the attribute to value.
void SetAttribute(uint64_t value);
/// Set the attribute to value.
void SetAttribute( bool value );
/// Set the attribute to value.
void SetAttribute( double value );
/// Set the attribute to value.
void SetAttribute( float value );
private:
enum { BUF_SIZE = 200 };
XMLAttribute() : _name(), _value(),_parseLineNum( 0 ), _next( 0 ), _memPool( 0 ) {}
virtual ~XMLAttribute() {}
XMLAttribute( const XMLAttribute& ); // not supported
void operator=( const XMLAttribute& ); // not supported
void SetName( const char* name );
char* ParseDeep( char* p, bool processEntities, int* curLineNumPtr );
mutable StrPair _name;
mutable StrPair _value;
int _parseLineNum;
XMLAttribute* _next;
MemPool* _memPool;
};
/** The element is a container class. It has a value, the element name,
and can contain other elements, text, comments, and unknowns.
Elements also contain an arbitrary number of attributes.
*/
class TINYXML2_LIB XMLElement : public XMLNode
{
friend class XMLDocument;
public:
/// Get the name of an element (which is the Value() of the node.)
const char* Name() const {
return Value();
}
/// Set the name of the element.
void SetName( const char* str, bool staticMem=false ) {
SetValue( str, staticMem );
}
virtual XMLElement* ToElement() {
return this;
}
virtual const XMLElement* ToElement() const {
return this;
}
virtual bool Accept( XMLVisitor* visitor ) const;
/** Given an attribute name, Attribute() returns the value
for the attribute of that name, or null if none
exists. For example:
@verbatim
const char* value = ele->Attribute( "foo" );
@endverbatim
The 'value' parameter is normally null. However, if specified,
the attribute will only be returned if the 'name' and 'value'
match. This allow you to write code:
@verbatim
if ( ele->Attribute( "foo", "bar" ) ) callFooIsBar();
@endverbatim
rather than:
@verbatim
if ( ele->Attribute( "foo" ) ) {
if ( strcmp( ele->Attribute( "foo" ), "bar" ) == 0 ) callFooIsBar();
}
@endverbatim
*/
const char* Attribute( const char* name, const char* value=0 ) const;
/** Given an attribute name, IntAttribute() returns the value
of the attribute interpreted as an integer. The default
value will be returned if the attribute isn't present,
or if there is an error. (For a method with error
checking, see QueryIntAttribute()).
*/
int IntAttribute(const char* name, int defaultValue = 0) const;
/// See IntAttribute()
unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const;
/// See IntAttribute()
int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const;
/// See IntAttribute()
uint64_t Unsigned64Attribute(const char* name, uint64_t defaultValue = 0) const;
/// See IntAttribute()
bool BoolAttribute(const char* name, bool defaultValue = false) const;
/// See IntAttribute()
double DoubleAttribute(const char* name, double defaultValue = 0) const;
/// See IntAttribute()
float FloatAttribute(const char* name, float defaultValue = 0) const;
/** Given an attribute name, QueryIntAttribute() returns
XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion
can't be performed, or XML_NO_ATTRIBUTE if the attribute
doesn't exist. If successful, the result of the conversion
will be written to 'value'. If not successful, nothing will
be written to 'value'. This allows you to provide default
value:
@verbatim
int value = 10;
QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10
@endverbatim
*/
XMLError QueryIntAttribute( const char* name, int* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryIntValue( value );
}
/// See QueryIntAttribute()
XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryUnsignedValue( value );
}
/// See QueryIntAttribute()
XMLError QueryInt64Attribute(const char* name, int64_t* value) const {
const XMLAttribute* a = FindAttribute(name);
if (!a) {
return XML_NO_ATTRIBUTE;
}
return a->QueryInt64Value(value);
}
/// See QueryIntAttribute()
XMLError QueryUnsigned64Attribute(const char* name, uint64_t* value) const {
const XMLAttribute* a = FindAttribute(name);
if(!a) {
return XML_NO_ATTRIBUTE;
}
return a->QueryUnsigned64Value(value);
}
/// See QueryIntAttribute()
XMLError QueryBoolAttribute( const char* name, bool* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryBoolValue( value );
}
/// See QueryIntAttribute()
XMLError QueryDoubleAttribute( const char* name, double* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryDoubleValue( value );
}
/// See QueryIntAttribute()
XMLError QueryFloatAttribute( const char* name, float* value ) const {
const XMLAttribute* a = FindAttribute( name );
if ( !a ) {
return XML_NO_ATTRIBUTE;
}
return a->QueryFloatValue( value );
}
/// See QueryIntAttribute()
XMLError QueryStringAttribute(const char* name, const char** value) const {
const XMLAttribute* a = FindAttribute(name);
if (!a) {
return XML_NO_ATTRIBUTE;
}
*value = a->Value();
return XML_SUCCESS;
}
/** Given an attribute name, QueryAttribute() returns
XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion
can't be performed, or XML_NO_ATTRIBUTE if the attribute
doesn't exist. It is overloaded for the primitive types,
and is a generally more convenient replacement of
QueryIntAttribute() and related functions.
If successful, the result of the conversion
will be written to 'value'. If not successful, nothing will
be written to 'value'. This allows you to provide default
value:
@verbatim
int value = 10;
QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10
@endverbatim
*/
XMLError QueryAttribute( const char* name, int* value ) const {
return QueryIntAttribute( name, value );
}
XMLError QueryAttribute( const char* name, unsigned int* value ) const {
return QueryUnsignedAttribute( name, value );
}
XMLError QueryAttribute(const char* name, int64_t* value) const {
return QueryInt64Attribute(name, value);
}
XMLError QueryAttribute(const char* name, uint64_t* value) const {
return QueryUnsigned64Attribute(name, value);
}
XMLError QueryAttribute( const char* name, bool* value ) const {
return QueryBoolAttribute( name, value );
}
XMLError QueryAttribute( const char* name, double* value ) const {
return QueryDoubleAttribute( name, value );
}
XMLError QueryAttribute( const char* name, float* value ) const {
return QueryFloatAttribute( name, value );
}
XMLError QueryAttribute(const char* name, const char** value) const {
return QueryStringAttribute(name, value);
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, const char* value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, int value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, unsigned value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute(const char* name, int64_t value) {
XMLAttribute* a = FindOrCreateAttribute(name);
a->SetAttribute(value);
}
/// Sets the named attribute to value.
void SetAttribute(const char* name, uint64_t value) {
XMLAttribute* a = FindOrCreateAttribute(name);
a->SetAttribute(value);
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, bool value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, double value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/// Sets the named attribute to value.
void SetAttribute( const char* name, float value ) {
XMLAttribute* a = FindOrCreateAttribute( name );
a->SetAttribute( value );
}
/**
Delete an attribute.
*/
void DeleteAttribute( const char* name );
/// Return the first attribute in the list.
const XMLAttribute* FirstAttribute() const {
return _rootAttribute;
}
/// Query a specific attribute in the list.
const XMLAttribute* FindAttribute( const char* name ) const;
/** Convenience function for easy access to the text inside an element. Although easy
and concise, GetText() is limited compared to getting the XMLText child
and accessing it directly.
If the first child of 'this' is a XMLText, the GetText()
returns the character string of the Text node, else null is returned.
This is a convenient method for getting the text of simple contained text:
@verbatim
<foo>This is text</foo>
const char* str = fooElement->GetText();
@endverbatim
'str' will be a pointer to "This is text".
Note that this function can be misleading. If the element foo was created from
this XML:
@verbatim
<foo><b>This is text</b></foo>
@endverbatim
then the value of str would be null. The first child node isn't a text node, it is
another element. From this XML:
@verbatim
<foo>This is <b>text</b></foo>
@endverbatim
GetText() will return "This is ".
*/
const char* GetText() const;
/** Convenience function for easy access to the text inside an element. Although easy
and concise, SetText() is limited compared to creating an XMLText child
and mutating it directly.
If the first child of 'this' is a XMLText, SetText() sets its value to
the given string, otherwise it will create a first child that is an XMLText.
This is a convenient method for setting the text of simple contained text:
@verbatim
<foo>This is text</foo>
fooElement->SetText( "Hullaballoo!" );
<foo>Hullaballoo!</foo>
@endverbatim
Note that this function can be misleading. If the element foo was created from
this XML:
@verbatim
<foo><b>This is text</b></foo>
@endverbatim
then it will not change "This is text", but rather prefix it with a text element:
@verbatim
<foo>Hullaballoo!<b>This is text</b></foo>
@endverbatim
For this XML:
@verbatim
<foo />
@endverbatim
SetText() will generate
@verbatim
<foo>Hullaballoo!</foo>
@endverbatim
*/
void SetText( const char* inText );
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( int value );
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( unsigned value );
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText(int64_t value);
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText(uint64_t value);
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( bool value );
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( double value );
/// Convenience method for setting text inside an element. See SetText() for important limitations.
void SetText( float value );
/**
Convenience method to query the value of a child text node. This is probably best
shown by example. Given you have a document is this form:
@verbatim
<point>
<x>1</x>
<y>1.4</y>
</point>
@endverbatim
The QueryIntText() and similar functions provide a safe and easier way to get to the
"value" of x and y.
@verbatim
int x = 0;
float y = 0; // types of x and y are contrived for example
const XMLElement* xElement = pointElement->FirstChildElement( "x" );
const XMLElement* yElement = pointElement->FirstChildElement( "y" );
xElement->QueryIntText( &x );
yElement->QueryFloatText( &y );
@endverbatim
@returns XML_SUCCESS (0) on success, XML_CAN_NOT_CONVERT_TEXT if the text cannot be converted
to the requested type, and XML_NO_TEXT_NODE if there is no child text to query.
*/
XMLError QueryIntText( int* ival ) const;
/// See QueryIntText()
XMLError QueryUnsignedText( unsigned* uval ) const;
/// See QueryIntText()
XMLError QueryInt64Text(int64_t* uval) const;
/// See QueryIntText()
XMLError QueryUnsigned64Text(uint64_t* uval) const;
/// See QueryIntText()
XMLError QueryBoolText( bool* bval ) const;
/// See QueryIntText()
XMLError QueryDoubleText( double* dval ) const;
/// See QueryIntText()
XMLError QueryFloatText( float* fval ) const;
int IntText(int defaultValue = 0) const;
/// See QueryIntText()
unsigned UnsignedText(unsigned defaultValue = 0) const;
/// See QueryIntText()
int64_t Int64Text(int64_t defaultValue = 0) const;
/// See QueryIntText()
uint64_t Unsigned64Text(uint64_t defaultValue = 0) const;
/// See QueryIntText()
bool BoolText(bool defaultValue = false) const;
/// See QueryIntText()
double DoubleText(double defaultValue = 0) const;
/// See QueryIntText()
float FloatText(float defaultValue = 0) const;
/**
Convenience method to create a new XMLElement and add it as last (right)
child of this node. Returns the created and inserted element.
*/
XMLElement* InsertNewChildElement(const char* name);
/// See InsertNewChildElement()
XMLComment* InsertNewComment(const char* comment);
/// See InsertNewChildElement()
XMLText* InsertNewText(const char* text);
/// See InsertNewChildElement()
XMLDeclaration* InsertNewDeclaration(const char* text);
/// See InsertNewChildElement()
XMLUnknown* InsertNewUnknown(const char* text);
// internal:
enum ElementClosingType {
OPEN, // <foo>
CLOSED, // <foo/>
CLOSING // </foo>
};
ElementClosingType ClosingType() const {
return _closingType;
}
virtual XMLNode* ShallowClone( XMLDocument* document ) const;
virtual bool ShallowEqual( const XMLNode* compare ) const;
protected:
char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr );
private:
XMLElement( XMLDocument* doc );
virtual ~XMLElement();
XMLElement( const XMLElement& ); // not supported
void operator=( const XMLElement& ); // not supported
XMLAttribute* FindOrCreateAttribute( const char* name );
char* ParseAttributes( char* p, int* curLineNumPtr );
static void DeleteAttribute( XMLAttribute* attribute );
XMLAttribute* CreateAttribute();
enum { BUF_SIZE = 200 };
ElementClosingType _closingType;
// The attribute list is ordered; there is no 'lastAttribute'
// because the list needs to be scanned for dupes before adding
// a new attribute.
XMLAttribute* _rootAttribute;
};
enum Whitespace {
PRESERVE_WHITESPACE,
COLLAPSE_WHITESPACE
};
/** A Document binds together all the functionality.
It can be saved, loaded, and printed to the screen.
All Nodes are connected and allocated to a Document.
If the Document is deleted, all its Nodes are also deleted.
*/
class TINYXML2_LIB XMLDocument : public XMLNode
{
friend class XMLElement;
// Gives access to SetError and Push/PopDepth, but over-access for everything else.
// Wishing C++ had "internal" scope.
friend class XMLNode;
friend class XMLText;
friend class XMLComment;
friend class XMLDeclaration;
friend class XMLUnknown;
public:
/// constructor
XMLDocument( bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE );
~XMLDocument();
virtual XMLDocument* ToDocument() {
TIXMLASSERT( this == _document );
return this;
}
virtual const XMLDocument* ToDocument() const {
TIXMLASSERT( this == _document );
return this;
}
/**
Parse an XML file from a character string.
Returns XML_SUCCESS (0) on success, or
an errorID.
You may optionally pass in the 'nBytes', which is
the number of bytes which will be parsed. If not
specified, TinyXML-2 will assume 'xml' points to a
null terminated string.
*/
XMLError Parse( const char* xml, size_t nBytes=static_cast<size_t>(-1) );
/**
Load an XML file from disk.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError LoadFile( const char* filename );
/**
Load an XML file from disk. You are responsible
for providing and closing the FILE*.
NOTE: The file should be opened as binary ("rb")
not text in order for TinyXML-2 to correctly
do newline normalization.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError LoadFile( FILE* );
/**
Save the XML file to disk.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError SaveFile( const char* filename, bool compact = false );
/**
Save the XML file to disk. You are responsible
for providing and closing the FILE*.
Returns XML_SUCCESS (0) on success, or
an errorID.
*/
XMLError SaveFile( FILE* fp, bool compact = false );
bool ProcessEntities() const {
return _processEntities;
}
Whitespace WhitespaceMode() const {
return _whitespaceMode;
}
/**
Returns true if this document has a leading Byte Order Mark of UTF8.
*/
bool HasBOM() const {
return _writeBOM;
}
/** Sets whether to write the BOM when writing the file.
*/
void SetBOM( bool useBOM ) {
_writeBOM = useBOM;
}
/** Return the root element of DOM. Equivalent to FirstChildElement().
To get the first node, use FirstChild().
*/
XMLElement* RootElement() {
return FirstChildElement();
}
const XMLElement* RootElement() const {
return FirstChildElement();
}
/** Print the Document. If the Printer is not provided, it will
print to stdout. If you provide Printer, this can print to a file:
@verbatim
XMLPrinter printer( fp );
doc.Print( &printer );
@endverbatim
Or you can use a printer to print to memory:
@verbatim
XMLPrinter printer;
doc.Print( &printer );
// printer.CStr() has a const char* to the XML
@endverbatim
*/
void Print( XMLPrinter* streamer=0 ) const;
virtual bool Accept( XMLVisitor* visitor ) const;
/**
Create a new Element associated with
this Document. The memory for the Element
is managed by the Document.
*/
XMLElement* NewElement( const char* name );
/**
Create a new Comment associated with
this Document. The memory for the Comment
is managed by the Document.
*/
XMLComment* NewComment( const char* comment );
/**
Create a new Text associated with
this Document. The memory for the Text
is managed by the Document.
*/
XMLText* NewText( const char* text );
/**
Create a new Declaration associated with
this Document. The memory for the object
is managed by the Document.
If the 'text' param is null, the standard
declaration is used.:
@verbatim
<?xml version="1.0" encoding="UTF-8"?>
@endverbatim
*/
XMLDeclaration* NewDeclaration( const char* text=0 );
/**
Create a new Unknown associated with
this Document. The memory for the object
is managed by the Document.
*/
XMLUnknown* NewUnknown( const char* text );
/**
Delete a node associated with this document.
It will be unlinked from the DOM.
*/
void DeleteNode( XMLNode* node );
/// Clears the error flags.
void ClearError();
/// Return true if there was an error parsing the document.
bool Error() const {
return _errorID != XML_SUCCESS;
}
/// Return the errorID.
XMLError ErrorID() const {
return _errorID;
}
const char* ErrorName() const;
static const char* ErrorIDToName(XMLError errorID);
/** Returns a "long form" error description. A hopefully helpful
diagnostic with location, line number, and/or additional info.
*/
const char* ErrorStr() const;
/// A (trivial) utility function that prints the ErrorStr() to stdout.
void PrintError() const;
/// Return the line where the error occurred, or zero if unknown.
int ErrorLineNum() const
{
return _errorLineNum;
}
/// Clear the document, resetting it to the initial state.
void Clear();
/**
Copies this document to a target document.
The target will be completely cleared before the copy.
If you want to copy a sub-tree, see XMLNode::DeepClone().
NOTE: that the 'target' must be non-null.
*/
void DeepCopy(XMLDocument* target) const;
// internal
char* Identify( char* p, XMLNode** node );
// internal
void MarkInUse(const XMLNode* const);
virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const {
return 0;
}
virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const {
return false;
}
private:
XMLDocument( const XMLDocument& ); // not supported
void operator=( const XMLDocument& ); // not supported
bool _writeBOM;
bool _processEntities;
XMLError _errorID;
Whitespace _whitespaceMode;
mutable StrPair _errorStr;
int _errorLineNum;
char* _charBuffer;
int _parseCurLineNum;
int _parsingDepth;
// Memory tracking does add some overhead.
// However, the code assumes that you don't
// have a bunch of unlinked nodes around.
// Therefore it takes less memory to track
// in the document vs. a linked list in the XMLNode,
// and the performance is the same.
DynArray<XMLNode*, 10> _unlinked;
MemPoolT< sizeof(XMLElement) > _elementPool;
MemPoolT< sizeof(XMLAttribute) > _attributePool;
MemPoolT< sizeof(XMLText) > _textPool;
MemPoolT< sizeof(XMLComment) > _commentPool;
static const char* _errorNames[XML_ERROR_COUNT];
void Parse();
void SetError( XMLError error, int lineNum, const char* format, ... );
// Something of an obvious security hole, once it was discovered.
// Either an ill-formed XML or an excessively deep one can overflow
// the stack. Track stack depth, and error out if needed.
class DepthTracker {
public:
explicit DepthTracker(XMLDocument * document) {
this->_document = document;
document->PushDepth();
}
~DepthTracker() {
_document->PopDepth();
}
private:
XMLDocument * _document;
};
void PushDepth();
void PopDepth();
template<class NodeType, int PoolElementSize>
NodeType* CreateUnlinkedNode( MemPoolT<PoolElementSize>& pool );
};
template<class NodeType, int PoolElementSize>
inline NodeType* XMLDocument::CreateUnlinkedNode( MemPoolT<PoolElementSize>& pool )
{
TIXMLASSERT( sizeof( NodeType ) == PoolElementSize );
TIXMLASSERT( sizeof( NodeType ) == pool.ItemSize() );
NodeType* returnNode = new (pool.Alloc()) NodeType( this );
TIXMLASSERT( returnNode );
returnNode->_memPool = &pool;
_unlinked.Push(returnNode);
return returnNode;
}
/**
A XMLHandle is a class that wraps a node pointer with null checks; this is
an incredibly useful thing. Note that XMLHandle is not part of the TinyXML-2
DOM structure. It is a separate utility class.
Take an example:
@verbatim
<Document>
<Element attributeA = "valueA">
<Child attributeB = "value1" />
<Child attributeB = "value2" />
</Element>
</Document>
@endverbatim
Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very
easy to write a *lot* of code that looks like:
@verbatim
XMLElement* root = document.FirstChildElement( "Document" );
if ( root )
{
XMLElement* element = root->FirstChildElement( "Element" );
if ( element )
{
XMLElement* child = element->FirstChildElement( "Child" );
if ( child )
{
XMLElement* child2 = child->NextSiblingElement( "Child" );
if ( child2 )
{
// Finally do something useful.
@endverbatim
And that doesn't even cover "else" cases. XMLHandle addresses the verbosity
of such code. A XMLHandle checks for null pointers so it is perfectly safe
and correct to use:
@verbatim
XMLHandle docHandle( &document );
XMLElement* child2 = docHandle.FirstChildElement( "Document" ).FirstChildElement( "Element" ).FirstChildElement().NextSiblingElement();
if ( child2 )
{
// do something useful
@endverbatim
Which is MUCH more concise and useful.
It is also safe to copy handles - internally they are nothing more than node pointers.
@verbatim
XMLHandle handleCopy = handle;
@endverbatim
See also XMLConstHandle, which is the same as XMLHandle, but operates on const objects.
*/
class TINYXML2_LIB XMLHandle
{
public:
/// Create a handle from any node (at any depth of the tree.) This can be a null pointer.
explicit XMLHandle( XMLNode* node ) : _node( node ) {
}
/// Create a handle from a node.
explicit XMLHandle( XMLNode& node ) : _node( &node ) {
}
/// Copy constructor
XMLHandle( const XMLHandle& ref ) : _node( ref._node ) {
}
/// Assignment
XMLHandle& operator=( const XMLHandle& ref ) {
_node = ref._node;
return *this;
}
/// Get the first child of this handle.
XMLHandle FirstChild() {
return XMLHandle( _node ? _node->FirstChild() : 0 );
}
/// Get the first child element of this handle.
XMLHandle FirstChildElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 );
}
/// Get the last child of this handle.
XMLHandle LastChild() {
return XMLHandle( _node ? _node->LastChild() : 0 );
}
/// Get the last child element of this handle.
XMLHandle LastChildElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->LastChildElement( name ) : 0 );
}
/// Get the previous sibling of this handle.
XMLHandle PreviousSibling() {
return XMLHandle( _node ? _node->PreviousSibling() : 0 );
}
/// Get the previous sibling element of this handle.
XMLHandle PreviousSiblingElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 );
}
/// Get the next sibling of this handle.
XMLHandle NextSibling() {
return XMLHandle( _node ? _node->NextSibling() : 0 );
}
/// Get the next sibling element of this handle.
XMLHandle NextSiblingElement( const char* name = 0 ) {
return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 );
}
/// Safe cast to XMLNode. This can return null.
XMLNode* ToNode() {
return _node;
}
/// Safe cast to XMLElement. This can return null.
XMLElement* ToElement() {
return ( _node ? _node->ToElement() : 0 );
}
/// Safe cast to XMLText. This can return null.
XMLText* ToText() {
return ( _node ? _node->ToText() : 0 );
}
/// Safe cast to XMLUnknown. This can return null.
XMLUnknown* ToUnknown() {
return ( _node ? _node->ToUnknown() : 0 );
}
/// Safe cast to XMLDeclaration. This can return null.
XMLDeclaration* ToDeclaration() {
return ( _node ? _node->ToDeclaration() : 0 );
}
private:
XMLNode* _node;
};
/**
A variant of the XMLHandle class for working with const XMLNodes and Documents. It is the
same in all regards, except for the 'const' qualifiers. See XMLHandle for API.
*/
class TINYXML2_LIB XMLConstHandle
{
public:
explicit XMLConstHandle( const XMLNode* node ) : _node( node ) {
}
explicit XMLConstHandle( const XMLNode& node ) : _node( &node ) {
}
XMLConstHandle( const XMLConstHandle& ref ) : _node( ref._node ) {
}
XMLConstHandle& operator=( const XMLConstHandle& ref ) {
_node = ref._node;
return *this;
}
const XMLConstHandle FirstChild() const {
return XMLConstHandle( _node ? _node->FirstChild() : 0 );
}
const XMLConstHandle FirstChildElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 );
}
const XMLConstHandle LastChild() const {
return XMLConstHandle( _node ? _node->LastChild() : 0 );
}
const XMLConstHandle LastChildElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 );
}
const XMLConstHandle PreviousSibling() const {
return XMLConstHandle( _node ? _node->PreviousSibling() : 0 );
}
const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 );
}
const XMLConstHandle NextSibling() const {
return XMLConstHandle( _node ? _node->NextSibling() : 0 );
}
const XMLConstHandle NextSiblingElement( const char* name = 0 ) const {
return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 );
}
const XMLNode* ToNode() const {
return _node;
}
const XMLElement* ToElement() const {
return ( _node ? _node->ToElement() : 0 );
}
const XMLText* ToText() const {
return ( _node ? _node->ToText() : 0 );
}
const XMLUnknown* ToUnknown() const {
return ( _node ? _node->ToUnknown() : 0 );
}
const XMLDeclaration* ToDeclaration() const {
return ( _node ? _node->ToDeclaration() : 0 );
}
private:
const XMLNode* _node;
};
/**
Printing functionality. The XMLPrinter gives you more
options than the XMLDocument::Print() method.
It can:
-# Print to memory.
-# Print to a file you provide.
-# Print XML without a XMLDocument.
Print to Memory
@verbatim
XMLPrinter printer;
doc.Print( &printer );
SomeFunction( printer.CStr() );
@endverbatim
Print to a File
You provide the file pointer.
@verbatim
XMLPrinter printer( fp );
doc.Print( &printer );
@endverbatim
Print without a XMLDocument
When loading, an XML parser is very useful. However, sometimes
when saving, it just gets in the way. The code is often set up
for streaming, and constructing the DOM is just overhead.
The Printer supports the streaming case. The following code
prints out a trivially simple XML file without ever creating
an XML document.
@verbatim
XMLPrinter printer( fp );
printer.OpenElement( "foo" );
printer.PushAttribute( "foo", "bar" );
printer.CloseElement();
@endverbatim
*/
class TINYXML2_LIB XMLPrinter : public XMLVisitor
{
public:
/** Construct the printer. If the FILE* is specified,
this will print to the FILE. Else it will print
to memory, and the result is available in CStr().
If 'compact' is set to true, then output is created
with only required whitespace and newlines.
*/
XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 );
virtual ~XMLPrinter() {}
/** If streaming, write the BOM and declaration. */
void PushHeader( bool writeBOM, bool writeDeclaration );
/** If streaming, start writing an element.
The element must be closed with CloseElement()
*/
void OpenElement( const char* name, bool compactMode=false );
/// If streaming, add an attribute to an open element.
void PushAttribute( const char* name, const char* value );
void PushAttribute( const char* name, int value );
void PushAttribute( const char* name, unsigned value );
void PushAttribute( const char* name, int64_t value );
void PushAttribute( const char* name, uint64_t value );
void PushAttribute( const char* name, bool value );
void PushAttribute( const char* name, double value );
/// If streaming, close the Element.
virtual void CloseElement( bool compactMode=false );
/// Add a text node.
void PushText( const char* text, bool cdata=false );
/// Add a text node from an integer.
void PushText( int value );
/// Add a text node from an unsigned.
void PushText( unsigned value );
/// Add a text node from a signed 64bit integer.
void PushText( int64_t value );
/// Add a text node from an unsigned 64bit integer.
void PushText( uint64_t value );
/// Add a text node from a bool.
void PushText( bool value );
/// Add a text node from a float.
void PushText( float value );
/// Add a text node from a double.
void PushText( double value );
/// Add a comment
void PushComment( const char* comment );
void PushDeclaration( const char* value );
void PushUnknown( const char* value );
virtual bool VisitEnter( const XMLDocument& /*doc*/ );
virtual bool VisitExit( const XMLDocument& /*doc*/ ) {
return true;
}
virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute );
virtual bool VisitExit( const XMLElement& element );
virtual bool Visit( const XMLText& text );
virtual bool Visit( const XMLComment& comment );
virtual bool Visit( const XMLDeclaration& declaration );
virtual bool Visit( const XMLUnknown& unknown );
/**
If in print to memory mode, return a pointer to
the XML file in memory.
*/
const char* CStr() const {
return _buffer.Mem();
}
/**
If in print to memory mode, return the size
of the XML file in memory. (Note the size returned
includes the terminating null.)
*/
int CStrSize() const {
return _buffer.Size();
}
/**
If in print to memory mode, reset the buffer to the
beginning.
*/
void ClearBuffer( bool resetToFirstElement = true ) {
_buffer.Clear();
_buffer.Push(0);
_firstElement = resetToFirstElement;
}
protected:
virtual bool CompactMode( const XMLElement& ) { return _compactMode; }
/** Prints out the space before an element. You may override to change
the space and tabs used. A PrintSpace() override should call Print().
*/
virtual void PrintSpace( int depth );
virtual void Print( const char* format, ... );
virtual void Write( const char* data, size_t size );
virtual void Putc( char ch );
inline void Write(const char* data) { Write(data, strlen(data)); }
void SealElementIfJustOpened();
bool _elementJustOpened;
DynArray< const char*, 10 > _stack;
private:
/**
Prepares to write a new node. This includes sealing an element that was
just opened, and writing any whitespace necessary if not in compact mode.
*/
void PrepareForNewNode( bool compactMode );
void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities.
bool _firstElement;
FILE* _fp;
int _depth;
int _textDepth;
bool _processEntities;
bool _compactMode;
enum {
ENTITY_RANGE = 64,
BUF_SIZE = 200
};
bool _entityFlag[ENTITY_RANGE];
bool _restrictedEntityFlag[ENTITY_RANGE];
DynArray< char, 20 > _buffer;
// Prohibit cloning, intentionally not implemented
XMLPrinter( const XMLPrinter& );
XMLPrinter& operator=( const XMLPrinter& );
};
} // tinyxml2
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // TINYXML2_INCLUDED |
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/iMpcdiDataProvider.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 <pxr/pxr.h>
#include <pxr/base/tf/token.h>
#include <pxr/base/tf/type.h>
#include "iMpcdiDataProvider.h"
PXR_NAMESPACE_OPEN_SCOPE
IEdfDataProvider::IEdfDataProvider(const EdfDataParameters& parameters) : _parameters(parameters)
{
}
IEdfDataProvider::~IEdfDataProvider() = default;
IEdfSourceData::~IEdfSourceData() = default;
const EdfDataParameters& IEdfDataProvider::GetParameters() const
{
return this->_parameters;
}
TF_REGISTRY_FUNCTION(TfType)
{
TfType::Define<IEdfDataProvider>();
}
PXR_NAMESPACE_CLOSE_SCOPE |
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/mpcdiDataProviderFactory.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_EDF_EDFDATAPROVIDERFACTORY_H_
#define OMNI_EDF_EDFDATAPROVIDERFACTORY_H_
#include <pxr/pxr.h>
#include <pxr/base/tf/registryManager.h>
#include <pxr/base/tf/type.h>
#include "api.h"
#include "iMpcdiDataProvider.h"
PXR_NAMESPACE_OPEN_SCOPE
#ifdef doxygen
#define EDF_DEFINE_DATAPROVIDER(ProviderClass, BaseClass1, ...)
#else
#define EDF_DEFINE_DATAPROVIDER(...) \
TF_REGISTRY_FUNCTION(TfType) { \
EdfDefineDataProvider<__VA_ARGS__>(); \
}
#endif
class EdfDataProviderFactoryBase : public TfType::FactoryBase
{
public:
MPCDI_API virtual ~EdfDataProviderFactoryBase();
MPCDI_API virtual IEdfDataProvider* New(const EdfDataParameters& parameters) const = 0;
};
template <class T>
class EdfDataProviderFactory : public EdfDataProviderFactoryBase
{
public:
virtual IEdfDataProvider* New(const EdfDataParameters& parameters) const override
{
return new T(parameters);
}
};
template <class DataProvider, class ...Bases>
void EdfDefineDataProvider()
{
TfType::Define<DataProvider, TfType::Bases<Bases...>>().template SetFactory<EdfDataProviderFactory<DataProvider> >();
}
PXR_NAMESPACE_CLOSE_SCOPE
#endif |
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/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]
// 中 or 中
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-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/mpcdiData.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 <pxr/base/plug/plugin.h>
#include <pxr/base/plug/registry.h>
#include <pxr/base/tf/token.h>
#include <pxr/usd/sdf/schema.h>
#include "mpcdiData.h"
#include "mpcdiDataProviderFactory.h"
#include "mpcdiPluginManager.h"
#include <iostream>
PXR_NAMESPACE_OPEN_SCOPE
static const SdfPath ROOT_PATH("/");
static const SdfPath DATA_ROOT_PATH("/Data");
TF_DEFINE_PUBLIC_TOKENS(
EdfDataParametersTokens,
// plugin metadata to specify an id for a specific data provider
(dataProviderId)
// plugin metadata describing the arguments for the provider to use
// to load the layer
(providerArgs)
);
EdfDataParameters EdfDataParameters::FromFileFormatArgs(const SdfFileFormat::FileFormatArguments& args)
{
EdfDataParameters parameters;
parameters.dataProviderId = *(TfMapLookupPtr(args, EdfDataParametersTokens->dataProviderId));
// unpack the file format argument representation of the provider arguments
std::string prefix = EdfDataParametersTokens->providerArgs.GetString() + ":";
size_t prefixLength = prefix.length();
for (SdfFileFormat::FileFormatArguments::const_iterator it = args.begin(); it != args.end(); it++)
{
size_t index = it->first.find(prefix);
if (index == 0)
{
// this is an unpacked prefixed provider argument
parameters.providerArgs[it->first.substr(prefixLength)] = it->second;
}
}
return parameters;
}
EdfSourceData::EdfSourceData(EdfData* data)
{
this->_data = data;
}
EdfSourceData::~EdfSourceData()
{
this->_data = nullptr;
}
void EdfSourceData::CreatePrim(const SdfPath& parentPath, const std::string& name, const SdfSpecifier& specifier,
const TfToken& typeName)
{
if (this->_data != nullptr)
{
this->_data->_CreatePrim(parentPath, name, specifier, typeName);
}
}
void EdfSourceData::CreateAttribute(const SdfPath& parentPrimPath, const std::string& name, const SdfValueTypeName& typeName,
const SdfVariability& variability, const VtValue& value)
{
if (this->_data != nullptr)
{
this->_data->_CreateAttribute(parentPrimPath, name, typeName, variability, value);
}
}
void EdfSourceData::SetField(const SdfPath& primPath, const TfToken& fieldName, const VtValue& value)
{
if (this->_data != nullptr)
{
this->_data->_SetFieldValue(primPath, fieldName, value);
}
}
bool EdfSourceData::HasField(const SdfPath& primPath, const TfToken& fieldName, VtValue* value)
{
if (this ->_data != nullptr)
{
return this->_data->Has(primPath, fieldName, value);
}
return false;
}
bool EdfSourceData::HasAttribute(const SdfPath& attributePath, VtValue* defaultValue)
{
if (this->_data != nullptr)
{
return this->_data->Has(attributePath, SdfFieldKeys->Default, defaultValue);
}
return false;
}
EdfData::EdfData(std::unique_ptr<IEdfDataProvider> dataProvider)
{
this->_dataProvider = std::move(dataProvider);
this->_sourceData = std::make_shared<EdfSourceData>(this);
}
EdfDataRefPtr EdfData::CreateFromParameters(const EdfDataParameters& parameters)
{
std::unique_ptr<IEdfDataProvider> dataProvider = MPCDIPluginManager::GetInstance().CreateDataProvider(parameters.dataProviderId, parameters);
if (dataProvider == nullptr)
{
// there was no provider responsible for this data or it didn't load properly,
// so the best we can do is provide an empty EdfData object with no backing provider
// this will load nothing except an empty default Root prim
return TfCreateRefPtr(new EdfData(nullptr));
}
return TfCreateRefPtr(new EdfData(std::move(dataProvider)));
}
void EdfData::CreateSpec(const SdfPath& path, SdfSpecType specType)
{
// not supported in this PoC
// the data provider can create new prim / property specs
// via the callbacks, but the external public API cannot
// but if it were, here's how it would be
// done concurrently
/*
this->_CreateSpec(path, specType);
*/
}
void EdfData::Erase(const SdfPath& path, const TfToken& fieldName)
{
// not supported in this PoC
// but if it were, here's how it would be
// done concurrently
/*
SpecData::accessor accessor;
if (_specData.find(accessor, path))
{
_SpecData& spec = accessor->second;
size_t fieldSize = spec.fields.size();
for (size_t i = 0; i < fieldSize; i++)
{
if (spec.fields[i].first == fieldName)
{
spec.fields.erase(spec.fields.begin() + i);
accessor.release();
return;
}
}
}
accessor.release();
*/
}
void EdfData::EraseSpec(const SdfPath& path)
{
// not supported in this PoC
// but it it were, here's how we'd do it
// with the concurrent hash
/*
SpecData::const_accessor accessor;
if (_specData.find(accessor, path))
{
_specData.erase(accessor);
}
accessor.release();
*/
}
VtValue EdfData::Get(const SdfPath& path, const TfToken& fieldName) const
{
VtValue val;
this->Has(path, fieldName, &val);
return val;
}
SdfSpecType EdfData::GetSpecType(const SdfPath& path) const
{
// in all cases we either have the spec data available
// because we created e.g. the root on Read
// or because the data provider created
// prims / properties when it performed its Read
// or we don't know
SpecData::const_accessor accessor;
if (_specData.find(accessor, path))
{
return accessor->second.specType;
}
accessor.release();
return SdfSpecType::SdfSpecTypeUnknown;
}
bool EdfData::Has(const SdfPath& path, const TfToken& fieldName, SdfAbstractDataValue* value) const
{
if (value != nullptr)
{
VtValue val;
if (this->Has(path, fieldName, &val))
{
return value->StoreValue(val);
}
}
else
{
VtValue val;
return this->Has(path, fieldName, &val);
}
return false;
}
bool EdfData::Has(const SdfPath& path, const TfToken& fieldName, VtValue* value) const
{
// in general, we can just get the value for whatever is being asked for
// from the hash (and know whether it was there or not)
// children are a special case, because those we want to ask the back-end
// provider to load - one tricky bit is understanding when we want the data provider
// to load and when we want to use the cached value
// as a general rule, if SdfChildrenKeys isn't present in the list of fields
// for the prim, but we have the prim, we need to ask the data provider to load
// for simplicity sake, this is a one-time load -> the data provider will use
// the callbacks to insert the children prims / attributes
// if we asked the data provider to load the children, and after that the field
// still isn't present, then we insert the field with an empty list since
// the provider never created any children (maybe the back-end query returned nothing)
std::cout << path.GetAsString() << " " << fieldName.GetString() << std::endl;
bool hasValue = this->_GetFieldValue(path, fieldName, value);
if (!hasValue && fieldName == SdfChildrenKeys->PrimChildren &&
this->_dataProvider != nullptr)
{
// give the data provider an opportunity to load their children
this->_dataProvider->ReadChildren(path.GetAsString(), this->_sourceData);
// after the read call, we check again to see if it's present
hasValue = this->_GetFieldValue(path, fieldName, value);
if (!hasValue)
{
// if it still doesn't exist, we assume that there were no children
// and we cache that fact now
TfTokenVector primChildren;
VtValue primChildrenValue(primChildren);
this->_SetFieldValue(path, SdfChildrenKeys->PrimChildren, primChildrenValue);
if(value != nullptr)
{
*value = primChildrenValue;
}
hasValue = true;
}
}
return hasValue;
}
bool EdfData::HasSpec(const SdfPath& path) const
{
return this->GetSpecType(path) != SdfSpecType::SdfSpecTypeUnknown;
}
bool EdfData::IsEmpty() const
{
return false;
}
std::vector<TfToken> EdfData::List(const SdfPath& path) const
{
TfTokenVector names;
SpecData::const_accessor accessor;
if (_specData.find(accessor, path))
{
size_t numFields = accessor->second.fields.size();
names.resize(numFields);
for (size_t i = 0; i < numFields; i++)
{
names[i] = accessor->second.fields[i].first;
}
}
accessor.release();
return names;
}
void EdfData::MoveSpec(const SdfPath& oldPath, const SdfPath& newPath)
{
// not supported in this PoC
// but it it were, here's how we'd do it
// with the concurrent hash
/*
SpecData::accessor accessor;
if (_specData.find(accessor, path))
{
SpecData::accessor writeAccessor;
_specData.insert(writeAccessor, newPath);
writeAccessor->second = accessor->second;
writeAccessor.release();
_specData.erase(accessor);
}
accessor.release();
*/
}
void EdfData::Set(const SdfPath& path, const TfToken& fieldName, const VtValue& value)
{
// not supported in this PoC
// but it it were, here's how we'd do it
// with the concurrent hash
/*
this->_SetFieldValue(path, fieldName, value);
*/
}
void EdfData::Set(const SdfPath& path, const TfToken& fieldName, const SdfAbstractDataConstValue& value)
{
// not supported in this PoC
// but it it were, here's how we'd do it
// with the concurrent hash
/*
VtValue wrappedValue;
value.GetValue(&wrappedValue);
this->_SetFieldValue(path, fieldName, wrappedValue);
*/
}
bool EdfData::StreamsData() const
{
// by default, we assume the backing provider will stream data
// but it will tell us whether it has cached that data or not later
return true;
}
bool EdfData::IsDetached() const
{
if (this->_dataProvider != nullptr)
{
return this->_dataProvider->IsDataCached();
}
else
{
return SdfAbstractData::IsDetached();
}
}
std::set<double> EdfData::ListAllTimeSamples() const
{
// not supported in this POC
return std::set<double>();
}
std::set<double> EdfData::ListTimeSamplesForPath(const SdfPath& path) const
{
// not supported in this POC
return std::set<double>();
}
bool EdfData::GetBracketingTimeSamples(double time, double* tLower, double* tUpper) const
{
// not supported in this POC
return false;
}
size_t EdfData::GetNumTimeSamplesForPath(const SdfPath& path) const
{
// not supported in this POC
return 0;
}
bool EdfData::GetBracketingTimeSamplesForPath(const SdfPath& path, double time, double* tLower, double* tUpper) const
{
// not supported in this POC
return false;
}
bool EdfData::QueryTimeSample(const SdfPath& path, double time, VtValue* optionalValue) const
{
// not supported in this POC
return false;
}
bool EdfData::QueryTimeSample(const SdfPath& path, double time, SdfAbstractDataValue* optionalValue) const
{
// not supported in this POC
return false;
}
void EdfData::SetTimeSample(const SdfPath& path, double time, const VtValue& value)
{
// not supported in this POC
}
void EdfData::EraseTimeSample(const SdfPath& path, double time)
{
// not supported in this POC
}
void EdfData::_VisitSpecs(SdfAbstractDataSpecVisitor* visitor) const
{
// not supported in this POC
}
bool EdfData::Read()
{
// on first read, create the specs for the absolute root path and
// for the /Data path where the provider will root their data
SpecData::accessor accessor;
_specData.insert(accessor, SdfPath::AbsoluteRootPath());
accessor->second.specType = SdfSpecType::SdfSpecTypePseudoRoot;
accessor.release();
// insert known field names for the root path
// this includes at minimum:
// SdfFieldKeys->DefaultPrim
// SdfChildrenKeys->PrimChildren
TfTokenVector rootChildren({DATA_ROOT_PATH.GetNameToken()});
VtValue primChildrenValue(rootChildren);
VtValue defaultPrimValue(DATA_ROOT_PATH.GetNameToken());
this->_SetFieldValue(ROOT_PATH, SdfChildrenKeys->PrimChildren, primChildrenValue);
this->_SetFieldValue(ROOT_PATH, SdfFieldKeys->DefaultPrim, defaultPrimValue);
// insert the data root path
_specData.insert(accessor, DATA_ROOT_PATH);
accessor->second.specType = SdfSpecType::SdfSpecTypePrim;
accessor.release();
// insert known field names for the data root path
// this includes at minimum:
// SdfFieldKeys->Specifier
// SdfFieldKeys->TypeName
// SdfFieldKeys->PrimChildren
// SdfFieldKeys->PropertyChildren
// prim children is loaded on demand during both deferred
// and non-deferred reads, so we don't set it here
TfTokenVector dataRootPropertyChildren;
VtValue specifierValue(SdfSpecifier::SdfSpecifierDef);
VtValue typeNameValue;
VtValue dataRootPropertyChildrenValue(dataRootPropertyChildren);
this->_SetFieldValue(DATA_ROOT_PATH, SdfFieldKeys->Specifier, specifierValue);
this->_SetFieldValue(DATA_ROOT_PATH, SdfFieldKeys->TypeName, typeNameValue);
this->_SetFieldValue(DATA_ROOT_PATH, SdfChildrenKeys->PropertyChildren, dataRootPropertyChildrenValue);
// if we have a valid provider, ask it to read it's data based on what parameters
// it was initialized with, otherwise just return true because we only have an empty
// root in the default implementation
bool readResult = true;
if (this->_dataProvider != nullptr)
{
readResult = this->_dataProvider->Read(this->_sourceData);
}
return readResult;
}
void EdfData::_CreatePrim(const SdfPath& parentPath, const std::string& name,
const SdfSpecifier& specifier, const TfToken& typeName)
{
SdfPath primPath = SdfPath(parentPath.GetAsString() + "/" + name);
this->_CreateSpec(primPath, SdfSpecType::SdfSpecTypePrim);
this->_SetFieldValue(primPath, SdfFieldKeys->TypeName, VtValue(typeName));
this->_SetFieldValue(primPath, SdfFieldKeys->Specifier, VtValue(specifier));
// add this prim to the PrimChildren property of parentPath
VtValue existingPrimChildrenValue;
if (this->_GetFieldValue(parentPath, SdfChildrenKeys->PrimChildren, &existingPrimChildrenValue))
{
// there are already children present, so append to the list
TfTokenVector existingChildren = existingPrimChildrenValue.UncheckedGet<TfTokenVector>();
existingChildren.push_back(TfToken(name));
// set the value back
this->_SetFieldValue(parentPath, SdfChildrenKeys->PrimChildren, VtValue(existingChildren));
}
else
{
// no children present yet
TfTokenVector children;
children.push_back(TfToken(name));
this->_SetFieldValue(parentPath, SdfChildrenKeys->PrimChildren, VtValue(children));
}
}
void EdfData::_CreateAttribute(const SdfPath& primPath, const std::string& name,
const SdfValueTypeName& typeName, const SdfVariability& variability, const VtValue& value)
{
// creating an attribute means setting the attribute path
// which is a combination of the prim path and the attribute name
// the type name field key of the attribute
// the variability field key of the attribute
// and a default field key holding its value
SdfPath attributePath = SdfPath(primPath.GetAsString() + "." + name);
this->_CreateSpec(attributePath, SdfSpecType::SdfSpecTypeAttribute);
this->_SetFieldValue(attributePath, SdfFieldKeys->TypeName, VtValue(typeName));
this->_SetFieldValue(attributePath, SdfFieldKeys->Variability, VtValue(variability));
this->_SetFieldValue(attributePath, SdfFieldKeys->Default, value);
// add this attribute to PropertyChildren of primPath
VtValue existingPropertyChildrenValue;
if (this->_GetFieldValue(primPath, SdfChildrenKeys->PropertyChildren, &existingPropertyChildrenValue))
{
// there are already children present, so append to the list
TfTokenVector existingChildren = existingPropertyChildrenValue.UncheckedGet<TfTokenVector>();
existingChildren.push_back(TfToken(name));
// set the value back
this->_SetFieldValue(primPath, SdfChildrenKeys->PropertyChildren, VtValue(existingChildren));
}
else
{
// no children present yet
TfTokenVector children;
children.push_back(TfToken(name));
this->_SetFieldValue(primPath, SdfChildrenKeys->PropertyChildren, VtValue(children));
}
}
void EdfData::_CreateSpec(const SdfPath& path, const SdfSpecType& specType)
{
SpecData::accessor accessor;
if (_specData.find(accessor, path))
{
accessor->second.specType = specType;
}
else
{
_specData.insert(accessor, path);
accessor->second.specType = specType;
}
accessor.release();
}
bool EdfData::_GetSpecTypeAndFieldValue(const SdfPath& path,
const TfToken& fieldName, SdfSpecType* specType, VtValue* value) const
{
// specType and value can be nullptrs here - this just means
// we want to know if we have the field at all for a possible
// subsequent call in the future
if (specType != nullptr)
{
*specType = SdfSpecTypeUnknown;
}
SpecData::const_accessor accessor;
if (_specData.find(accessor, path))
{
const _SpecData &spec = accessor->second;
if (specType != nullptr)
{
*specType = spec.specType;
}
for (auto const& f: spec.fields)
{
if (f.first == fieldName)
{
// copy so that we don't give
// back a direct pointer to a released
// accessor
if (value != nullptr)
{
*value = value;
}
accessor.release();
return true;
}
}
}
accessor.release();
return false;
}
bool EdfData::_GetFieldValue(const SdfPath& path,
const TfToken& fieldName, VtValue* value) const
{
// value can be a nullptr here - this just means
// we want to know if we have the field at all for a
// possible subsequent call in the future
SpecData::const_accessor accessor;
if (_specData.find(accessor, path))
{
const _SpecData &spec = accessor->second;
for (auto const& f: spec.fields)
{
if (f.first == fieldName)
{
// copy so that we don't give
// back a direct pointer to a released
// accessor
if (value != nullptr)
{
*value = f.second;
}
accessor.release();
return true;
}
}
}
accessor.release();
return false;
}
void EdfData::_SetFieldValue(const SdfPath& path, const TfToken& fieldName, const VtValue& value)
{
// NOTE: if we ever wanted to add support for querying whether
// the backend data provider could support writes, we should
// query that here and ask them to write to their backing data store
SpecData::accessor accessor;
if (_specData.find(accessor, path))
{
_SpecData& spec = accessor->second;
for (auto &f: spec.fields)
{
if (f.first == fieldName)
{
f.second = value;
accessor.release();
return;
}
}
// if we get here, we didn't have the field yet so create it
spec.fields.emplace_back(std::piecewise_construct,
std::forward_as_tuple(fieldName),
std::forward_as_tuple());
spec.fields.back().second = value;
accessor.release();
return;
}
accessor.release();
}
void EdfData::_SetFieldValue(const SdfPath& path, const TfToken& fieldName, const VtValue& value) const
{
// NOTE: if we ever wanted to add support for querying whether
// the backend data provider could support writes, we should
// query that here and ask them to write to their backing data store
SpecData::accessor accessor;
if (_specData.find(accessor, path))
{
_SpecData& spec = accessor->second;
for (auto& f : spec.fields)
{
if (f.first == fieldName)
{
f.second = value;
accessor.release();
return;
}
}
// if we get here, we didn't have the field yet so create it
spec.fields.emplace_back(std::piecewise_construct,
std::forward_as_tuple(fieldName),
std::forward_as_tuple());
spec.fields.back().second = value;
accessor.release();
return;
}
accessor.release();
}
PXR_NAMESPACE_CLOSE_SCOPE
|
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/mpcdiFileFormat.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 "mpcdiFileFormat.h"
#include "tinyxml2.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 <fstream>
#include <cmath>
PXR_NAMESPACE_OPEN_SCOPE
MpcdiFileFormat::MpcdiFileFormat() : SdfFileFormat(
MpcdiFileFormatTokens->Id,
MpcdiFileFormatTokens->Version,
MpcdiFileFormatTokens->Target,
MpcdiFileFormatTokens->Extension)
{
}
MpcdiFileFormat::~MpcdiFileFormat()
{
}
static const double defaultSideLengthValue = 1.0;
static double _ExtractSideLengthFromContext(const PcpDynamicFileFormatContext& context)
{
// Default sideLength.
double sideLength = defaultSideLengthValue;
VtValue value;
if (!context.ComposeValue(MpcdiFileFormatTokens->SideLength,
&value) ||
value.IsEmpty()) {
return sideLength;
}
if (!value.IsHolding<double>()) {
return sideLength;
}
return value.UncheckedGet<double>();
}
static double
_ExtractSideLengthFromArgs(const SdfFileFormat::FileFormatArguments& args)
{
// Default sideLength.
double sideLength = defaultSideLengthValue;
// Find "sideLength" file format argument.
auto it = args.find(MpcdiFileFormatTokens->SideLength);
if (it == args.end()) {
return sideLength;
}
// Try to convert the string value to the actual output value type.
double extractVal;
bool success = true;
extractVal = TfUnstringify<double>(it->second, &success);
if (!success) {
return sideLength;
}
sideLength = extractVal;
return sideLength;
}
bool MpcdiFileFormat::CanRead(const std::string& filePath) const
{
return true;
}
static float GetXMLFloat(tinyxml2::XMLElement* node, const std::string key)
{
return std::stof(node->FirstChildElement(key.c_str())->GetText());
}
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 MpcdiFileFormat::Read(SdfLayer* layer, const std::string& resolvedPath, bool metadataOnly) const
{
// these macros emit methods defined in the Pixar namespace
// but not properly scoped, so we have to use the namespace
// locally here - note this isn't strictly true since we had to open
// the namespace scope anyway because the macros won't allow non-Pixar namespaces
// to be used because of some auto-generated content
// Read file, file exists?
const std::ifstream filePath(resolvedPath);
if(!filePath.good())
{
TF_CODING_ERROR("File doesn't exist with resolved path: " + resolvedPath);
return false;
}
// Read XML file
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError xmlReadSuccess = doc.LoadFile(resolvedPath.c_str());
if(xmlReadSuccess != 0)
{
TF_CODING_ERROR("Failed to load xml file: " + resolvedPath);
return false;
}
// Parsing of MPCDI data
tinyxml2::XMLElement* rootNode = doc.RootElement();
if(rootNode == nullptr)
{
TF_CODING_ERROR("XML Root node is null: " + resolvedPath);
return false;
}
// Create a new anonymous layer and wrap a stage around it.
SdfLayerRefPtr newLayer = SdfLayer::CreateAnonymous(".usd");
UsdStageRefPtr stage = UsdStage::Open(newLayer);
const auto& xformPath = SdfPath("/mpcdi_payload");
auto mpdiScope = UsdGeomXform::Define(stage, xformPath);
stage->SetDefaultPrim(mpdiScope.GetPrim());
auto displayNode = rootNode->FirstChildElement("display");
for(auto* buffer = displayNode->FirstChildElement("buffer"); buffer != nullptr; buffer = buffer->NextSiblingElement("buffer"))
{
const std::string bufferId = std::string(buffer->Attribute("id"));
std::string bufferIdentifier = CleanNameForUSD(bufferId);
SdfPath bufferPath = xformPath.AppendChild(TfToken(bufferIdentifier));
auto bufferScope = UsdGeomScope::Define(stage, bufferPath);
// Get region
for(auto* regionNode = buffer->FirstChildElement("region"); regionNode != nullptr; regionNode = regionNode->NextSiblingElement("region"))
{
const std::string regionId = std::string(regionNode->Attribute("id"));
const std::string cleanedRegionId = CleanNameForUSD(regionId);
SdfPath regionPath = bufferPath.AppendChild(TfToken(cleanedRegionId));
// Get Frustum
auto frustumNode = regionNode->FirstChildElement("frustum");
const auto frustumYaw = GetXMLFloat(frustumNode, "yaw") * -1.0f;
const auto frustumPitch = GetXMLFloat(frustumNode, "pitch");
const auto frustumRoll = GetXMLFloat(frustumNode, "roll");
const auto frustumRightAngle = GetXMLFloat(frustumNode, "rightAngle");
const auto frustumLeftAngle = GetXMLFloat(frustumNode, "leftAngle");
const auto frustumUpAngle = GetXMLFloat(frustumNode, "upAngle");
const auto frustumDownAngle = GetXMLFloat(frustumNode, "downAngle");
constexpr const float toRad = 3.14159265358979323846 / 180.0;
constexpr const float focalLength = 10.0f;
constexpr const float focusDistance = 2000.0f;
const float tanRight = std::tan(frustumRightAngle * toRad);
const float tanLeft = std::tan(frustumLeftAngle * toRad);
const float tanUp = std::tan(frustumUpAngle * toRad);
const float tanDown = std::tan(frustumDownAngle * toRad);
const float apertureH = (std::abs(tanRight) + std::abs(tanLeft)) * focalLength;
const float apertureV = (std::abs(tanUp) + std::abs(tanDown)) * focalLength;
const float lightWidth = std::abs(tanRight) + std::abs(tanLeft);
const float lightHeight = std::abs(tanUp) + std::abs(tanDown);
const float lensShiftH = (tanLeft + tanRight) / (tanLeft - tanRight);
const float lensShiftV = (tanUp + tanDown) / (tanUp - tanDown);
const float apertureOffsetH = lensShiftH * apertureH / 2.0;
const float apertureOffsetV = lensShiftV * apertureV / 2.0;
// Coordinate frame
const float posScaling = 10.0f;
auto coordFrameNode = regionNode->FirstChildElement("coordinateFrame");
const auto posX = GetXMLFloat(coordFrameNode, "posx") * posScaling;
const auto posY = GetXMLFloat(coordFrameNode, "posy") * posScaling;
const auto posZ = GetXMLFloat(coordFrameNode, "posz") * posScaling;
const auto yawX = GetXMLFloat(coordFrameNode, "yawx");
const auto yawY = GetXMLFloat(coordFrameNode, "yawy");
const auto yawZ = GetXMLFloat(coordFrameNode, "yawz");
const auto pitchX = GetXMLFloat(coordFrameNode, "pitchx");
const auto pitchY = GetXMLFloat(coordFrameNode, "pitchy");
const auto pitchZ = GetXMLFloat(coordFrameNode, "pitchz");
const auto rollX = GetXMLFloat(coordFrameNode, "rollx");
const auto rollY = GetXMLFloat(coordFrameNode, "rolly");
const auto rollZ = GetXMLFloat(coordFrameNode, "rollz");
GfMatrix3f sourceToStandard = GfMatrix3f(pitchX, pitchY, pitchZ, yawX, yawY, yawZ, rollX, rollY, rollZ);
auto newPosition = sourceToStandard * GfVec3f(posX, posY, posZ);
newPosition[1] = -newPosition[1];
newPosition[2] = -newPosition[2];
// Camera
UsdGeomCamera camera = UsdGeomCamera::Define(stage, regionPath);
// Camera transform
auto cameraXform = UsdGeomXformable(camera);
auto translateOperation = cameraXform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat);
translateOperation.Set<GfVec3f>(newPosition * 10.0);
cameraXform.AddRotateYOp().Set(frustumYaw);
cameraXform.AddRotateXOp().Set(frustumPitch);
cameraXform.AddRotateZOp().Set(frustumRoll);
// Set camera attributes
camera.GetFocalLengthAttr().Set(focalLength);
camera.GetFocusDistanceAttr().Set(focusDistance);
camera.GetHorizontalApertureAttr().Set(apertureH);
camera.GetHorizontalApertureOffsetAttr().Set(apertureOffsetH);
camera.GetVerticalApertureAttr().Set(apertureV);
camera.GetVerticalApertureOffsetAttr().Set(apertureOffsetV);
// Light
SdfPath lightPath = regionPath.AppendChild(TfToken("RectLight"));
auto rectLight = UsdLuxRectLight::Define(stage, lightPath);
auto lightXform = UsdGeomXformable(rectLight);
auto lightTranslateOperation = lightXform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat);
rectLight.GetPrim().CreateAttribute(
TfToken("isProjector"),
SdfValueTypeNames->Bool
).Set(true);
rectLight.GetPrim().CreateAttribute(
TfToken("exposure"),
SdfValueTypeNames->Float
).Set(5.0f);
rectLight.GetPrim().CreateAttribute(
TfToken("intensity"),
SdfValueTypeNames->Float
).Set(15000.0f);
rectLight.GetWidthAttr().Set(lightWidth);
rectLight.GetHeightAttr().Set(lightHeight);
// Projector box
SdfPath cubePath = regionPath.AppendChild(TfToken("ProjectorBox"));
UsdGeomCube projectorBoxMesh = UsdGeomCube::Define(stage, cubePath);
const auto projectorBoxSize = GfVec3f(50, 15, 40);
const auto projectorBoxOffset = GfVec3f(0, 0, 42);
auto projectorBoxXform = UsdGeomXformable(projectorBoxMesh);
projectorBoxXform.AddTranslateOp(UsdGeomXformOp::PrecisionFloat).Set<GfVec3f>(projectorBoxOffset);
projectorBoxXform.AddScaleOp(UsdGeomXformOp::PrecisionFloat).Set<GfVec3f>(projectorBoxSize);
}
}
// Copy contents into output layer.
layer->TransferContent(newLayer);
return true;
}
bool MpcdiFileFormat::WriteToString(const SdfLayer& layer, std::string* str, const std::string& comment) const
{
// this POC doesn't support writing
return false;
}
bool MpcdiFileFormat::WriteToStream(const SdfSpecHandle& spec, std::ostream& out, size_t indent) const
{
// this POC doesn't support writing
return false;
}
/*
void MpcdiFileFormat::ComposeFieldsForFileFormatArguments(const std::string& assetPath, const PcpDynamicFileFormatContext& context, FileFormatArguments* args, VtValue* contextDependencyData) const
{
// Default sideLength.
double sideLength = 1.0;
VtValue value;
if (!context.ComposeValue(MpcdiFileFormatTokens->SideLength,
&value) ||
value.IsEmpty()) {
}
if (!value.IsHolding<double>()) {
// error;
}
double length;
(*args)[MpcdiFileFormatTokens->SideLength] = TfStringify(sideLength);
}
bool MpcdiFileFormat::CanFieldChangeAffectFileFormatArguments(const TfToken& field, const VtValue& oldValue, const VtValue& newValue, const VtValue& contextDependencyData) const
{
// Check if the "sideLength" argument changed.
double oldLength = oldValue.IsHolding<double>()
? oldValue.UncheckedGet<double>()
: 1.0;
double newLength = newValue.IsHolding<double>()
? newValue.UncheckedGet<double>()
: 1.0;
return oldLength != newLength;
}
*/
// 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(
MpcdiFileFormatTokens,
((Id, "mpcdiFileFormat"))
((Version, "1.0"))
((Target, "usd"))
((Extension, "xml"))
((SideLength, "Usd_Triangle_SideLength"))
);
TF_REGISTRY_FUNCTION(TfType)
{
SDF_DEFINE_FILE_FORMAT(MpcdiFileFormat, SdfFileFormat);
}
PXR_NAMESPACE_CLOSE_SCOPE |
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/plugInfo.json | {
"Plugins": [
{
"Info": {
"Types": {
"MpcdiFileFormat": {
"bases": [
"SdfFileFormat"
],
"displayName": "MPCDI Dynamic File Format",
"extensions": [
"xml"
],
"formatId": "mpcdiFileFormat",
"primary": true,
"target": "usd"
}
}
},
"LibraryPath": "@PLUG_INFO_LIBRARY_PATH@",
"Name": "mpcdiFileFormat",
"ResourcePath": "@PLUG_INFO_RESOURCE_PATH@",
"Root": "@PLUG_INFO_ROOT@",
"Type": "library"
}
]
} |
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/mpcdiFileFormat.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_MPCDI_MPCDIFILEFORMAT_H_
#define OMNI_MPCDI_MPCDIFILEFORMAT_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 MPCDI_API MpcdiFileFormat : public SdfFileFormat
{
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;
virtual ~MpcdiFileFormat();
MpcdiFileFormat();
};
TF_DECLARE_PUBLIC_TOKENS(
MpcdiFileFormatTokens,
((Id, "mpcdiFileFormat"))
((Version, "1.0"))
((Target, "usd"))
((Extension, "xml"))
((SideLength, "Usd_Triangle_SideLength"))
);
TF_DECLARE_WEAK_AND_REF_PTRS(MpcdiFileFormat);
PXR_NAMESPACE_CLOSE_SCOPE
#endif |
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/mpcdiPluginManager.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_MPCDI_MPCDIPLUGINMANAGER_H_
#define OMNI_MPCDI_MPCDIPLUGINMANAGER_H_
#include <string>
#include <unordered_map>
#include <pxr/pxr.h>
#include <pxr/base/tf/singleton.h>
#include <pxr/base/tf/type.h>
#include <pxr/base/plug/plugin.h>
#include "iMpcdiDataProvider.h"
PXR_NAMESPACE_OPEN_SCOPE
struct _DataProviderInfo
{
public:
PlugPluginPtr plugin;
TfType dataProviderType;
};
/// \class EdfPluginmanager
///
/// Singleton object responsible for managing the different data provider
/// plugins registered for use by the EDF file format provider.
///
class MPCDIPluginManager
{
public:
static MPCDIPluginManager& GetInstance()
{
return TfSingleton<MPCDIPluginManager>::GetInstance();
}
// prevent copying and assignment
MPCDIPluginManager(const MPCDIPluginManager&) = delete;
MPCDIPluginManager& operator=(const MPCDIPluginManager&) = delete;
std::unique_ptr<IEdfDataProvider> CreateDataProvider(const std::string& dataProviderId, const EdfDataParameters& parameters);
private:
MPCDIPluginManager();
~MPCDIPluginManager();
void _GetDataProviders();
friend class TfSingleton<MPCDIPluginManager>;
private:
bool _pluginsLoaded;
std::unordered_map<std::string, _DataProviderInfo> _dataProviderPlugins;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif |
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/mpcdiPluginManager.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 <pxr/base/tf/instantiateSingleton.h>
#include <pxr/base/plug/registry.h>
#include <pxr/base/js/value.h>
#include <pxr/base/js/utils.h>
#include "mpcdiPluginManager.h"
#include "mpcdiDataProviderFactory.h"
PXR_NAMESPACE_OPEN_SCOPE
TF_INSTANTIATE_SINGLETON(MPCDIPluginManager);
TF_DEFINE_PRIVATE_TOKENS(
MPCDIDataProviderPlugInTokens,
// metadata describing a unique id for the data provider plugin
(dataProviderId)
);
MPCDIPluginManager::MPCDIPluginManager()
{
this->_pluginsLoaded = false;
}
MPCDIPluginManager::~MPCDIPluginManager()
{
}
std::unique_ptr<IEdfDataProvider> MPCDIPluginManager::CreateDataProvider(const std::string& dataProviderId, const EdfDataParameters& parameters)
{
// load the plugins if not already loaded
this->_GetDataProviders();
// attempt to find the plugin responsible for the data provider id
const std::unordered_map<std::string, _DataProviderInfo>::iterator it = this->_dataProviderPlugins.find(dataProviderId);
if (it == this->_dataProviderPlugins.end())
{
TF_CODING_ERROR("Failed to find plugin for %s", dataProviderId.c_str());
return nullptr;
}
// load the corresponding plugin if not already loaded
if (!it->second.plugin->Load())
{
TF_CODING_ERROR("Failed to load plugin %s for %s", it->second.plugin->GetName().c_str(), it->second.dataProviderType.GetTypeName().c_str());
return nullptr;
}
std::unique_ptr<IEdfDataProvider> dataProvider;
EdfDataProviderFactoryBase* factory = it->second.dataProviderType.GetFactory<EdfDataProviderFactoryBase>();
if (factory != nullptr)
{
dataProvider.reset(factory->New(parameters));
}
if (dataProvider == nullptr)
{
TF_CODING_ERROR("Failed to create data provider %s from plugin %s", it->second.dataProviderType.GetTypeName().c_str(), it->second.plugin->GetName().c_str());
}
return dataProvider;
}
void MPCDIPluginManager::_GetDataProviders()
{
// this uses the standard Pixar plug-in mechansim to load and discover
// plug-ins of a certain type
if (!this->_pluginsLoaded)
{
std::set<TfType> dataProviderTypes;
PlugRegistry::GetAllDerivedTypes(TfType::Find<IEdfDataProvider>(), &dataProviderTypes);
for (const TfType dataProviderType : dataProviderTypes)
{
// get the plugin for the specified type from the plugin registry
const PlugPluginPtr plugin = PlugRegistry::GetInstance().GetPluginForType(dataProviderType);
if (plugin == nullptr)
{
TF_CODING_ERROR("Failed to find plugin for %s", dataProviderType.GetTypeName().c_str());
continue;
}
std::string dataProviderId;
const JsOptionalValue dataProviderIdVal = JsFindValue(plugin->GetMetadataForType(dataProviderType), MPCDIDataProviderPlugInTokens->dataProviderId.GetString());
if (!dataProviderIdVal.has_value() || !dataProviderIdVal->Is<std::string>())
{
TF_CODING_ERROR("'%s' metadata for '%s' must be specified!", MPCDIDataProviderPlugInTokens->dataProviderId.GetText(), dataProviderType.GetTypeName().c_str());
continue;
}
dataProviderId = dataProviderIdVal->GetString();
// store the map between the data provider id and the plugin
_DataProviderInfo providerInfo;
providerInfo.plugin = plugin;
providerInfo.dataProviderType = dataProviderType;
this->_dataProviderPlugins[dataProviderId] = providerInfo;
}
this->_pluginsLoaded = true;
}
}
PXR_NAMESPACE_CLOSE_SCOPE |
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/mpcdiData.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_EDF_EDFDATA_H_
#define OMNI_EDF_EDFDATA_H_
#include <string>
#include <set>
#include <pxr/pxr.h>
#include <pxr/base/tf/declarePtrs.h>
#include <pxr/usd/sdf/abstractData.h>
#include <pxr/usd/sdf/fileFormat.h>
#include <tbb/concurrent_hash_map.h>
#include "iMpcdiDataProvider.h"
PXR_NAMESPACE_OPEN_SCOPE
TF_DECLARE_PUBLIC_TOKENS(
EdfDataParametersTokens,
(dataProviderId)
(providerArgs)
);
TF_DECLARE_WEAK_AND_REF_PTRS(EdfData);
/// \class EdfSourceData
///
/// Serves as a wrapper around EdfData for data providers to populate
/// information into.
///
class EdfSourceData : public IEdfSourceData
{
public:
EdfSourceData(EdfData* data);
virtual ~EdfSourceData();
virtual void CreatePrim(const SdfPath& parentPath, const std::string& name, const SdfSpecifier& specifier,
const TfToken& typeName) override;
virtual void CreateAttribute(const SdfPath& parentPrimPath, const std::string& name, const SdfValueTypeName& typeName,
const SdfVariability& variability, const VtValue& value) override;
virtual void SetField(const SdfPath& primPath, const TfToken& fieldName, const VtValue& value) override;
virtual bool HasField(const SdfPath& primPath, const TfToken& fieldName, VtValue* value) override;
virtual bool HasAttribute(const SdfPath& attributePath, VtValue* defaultValue) override;
private:
EdfData* _data;
};
/// \class EdfData
///
/// This class is used to hold the data required to open
/// a layer from files of "edf" format. This data is initialized
/// by metadata unique to the prim the payload is attached to
/// and turned into file format args to create the appropriate
/// layer identifier for USD.
///
class EdfData : public SdfAbstractData
{
public:
static EdfDataRefPtr CreateFromParameters(const EdfDataParameters& parameters);
// SdfAbstractData overrides
void CreateSpec(const SdfPath& path, SdfSpecType specType) override;
void Erase(const SdfPath& path, const TfToken& fieldName) override;
void EraseSpec(const SdfPath& path) override;
VtValue Get(const SdfPath& path, const TfToken& fieldName) const override;
SdfSpecType GetSpecType(const SdfPath& path) const override;
bool Has(const SdfPath& path, const TfToken& fieldName, SdfAbstractDataValue* value) const override;
bool Has(const SdfPath& path, const TfToken& fieldName, VtValue* value = nullptr) const override;
bool HasSpec(const SdfPath& path) const override;
bool IsEmpty() const override;
std::vector<TfToken> List(const SdfPath& path) const override;
void MoveSpec(const SdfPath& oldPath, const SdfPath& newPath) override;
void Set(const SdfPath& path, const TfToken& fieldName, const VtValue& value) override;
void Set(const SdfPath& path, const TfToken& fieldName, const SdfAbstractDataConstValue& value) override;
bool StreamsData() const override;
bool IsDetached() const override;
std::set<double> ListAllTimeSamples() const override;
std::set<double> ListTimeSamplesForPath(const SdfPath& path) const override;
bool GetBracketingTimeSamples(double time, double* tLower, double* tUpper) const override;
size_t GetNumTimeSamplesForPath(const SdfPath& path) const override;
bool GetBracketingTimeSamplesForPath(const SdfPath& path, double time, double* tLower, double* tUpper) const override;
bool QueryTimeSample(const SdfPath& path, double time, VtValue* optionalValue = nullptr) const override;
bool QueryTimeSample(const SdfPath& path, double time, SdfAbstractDataValue* optionalValue) const override;
void SetTimeSample(const SdfPath& path, double time, const VtValue& value) override;
void EraseTimeSample(const SdfPath& path, double time) override;
virtual bool Read();
protected:
// SdfAbstractDataOverrides
void _VisitSpecs(SdfAbstractDataSpecVisitor* visitor) const override;
private:
friend class EdfSourceData;
// can only be constructed via CreateFromParameters
EdfData(std::unique_ptr<IEdfDataProvider> dataProvider);
// helper methods for retrieving spec properties
// modeled after SdfData
bool _GetSpecTypeAndFieldValue(const SdfPath& path,
const TfToken& fieldName, SdfSpecType* specType, VtValue* value) const;
bool _GetFieldValue(const SdfPath& path,
const TfToken& fieldName, VtValue* value) const;
// helper methods for setting properties for the root
// we don't have functionality for the public Set API
// but we need to do it internally - if we ever added
// support for the set API (i.e. the backend provider
// supported writes), we could call this internally
void _SetFieldValue(const SdfPath& path, const TfToken& fieldName, const VtValue& value);
void _SetFieldValue(const SdfPath& path, const TfToken& fieldName, const VtValue& value) const;
void _CreateSpec(const SdfPath& path, const SdfSpecType& specType);
// instance methods for callbacks on context
void _CreatePrim(const SdfPath& parentPath, const std::string& name,
const SdfSpecifier& specifier, const TfToken& typeName);
void _CreateAttribute(const SdfPath& primPath, const std::string& name,
const SdfValueTypeName& typeName, const SdfVariability& variability, const VtValue& value);
private:
// holds a pointer to the specific data provider to use
// to query back-end data
std::unique_ptr<IEdfDataProvider> _dataProvider;
// holds a shared pointer to the source data object
// used to callback on to create prims / attributes
std::shared_ptr<IEdfSourceData> _sourceData;
// mimic the storage structure of SdfData, just put it
// in a concurrent_hash_map rather than a TfHashMap
// the downside here is if we lock one field value for a write
// the whole prim gets locked, but for our purposes
// here that should be ok - the advantage we get is
// that on deferred reads we should be able to multithread
// the back-end object acquisition during prim indexing
typedef std::pair<TfToken, VtValue> _FieldValuePair;
struct _SpecData {
_SpecData() : specType(SdfSpecTypeUnknown) {}
SdfSpecType specType;
std::vector<_FieldValuePair> fields;
};
// Hash structure consistent with what TBB expects
// but forwarded to what's already in USD
struct SdfPathHash {
static size_t hash(const SdfPath& path)
{
return path.GetHash();
}
static bool equal(const SdfPath& path1, const SdfPath& path2)
{
return path1 == path2;
}
};
typedef tbb::concurrent_hash_map<SdfPath, _SpecData, SdfPathHash> SpecData;
mutable SpecData _specData;
};
PXR_NAMESPACE_CLOSE_SCOPE
#endif |
MomentFactory/Omniverse-MPCDI-converter/src/usd-plugins/fileFormat/mpcdiFileFormat/mpcdiDataProviderFactory.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 <pxr/pxr.h>
#include "mpcdiDataProviderFactory.h"
PXR_NAMESPACE_OPEN_SCOPE
EdfDataProviderFactoryBase::~EdfDataProviderFactoryBase() = default;
PXR_NAMESPACE_CLOSE_SCOPE |
MomentFactory/Omniverse-MPCDI-converter/tools/scripts/link_app.py | import argparse
import json
import os
import sys
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
|
MomentFactory/Omniverse-MPCDI-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-MPCDI-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-MPCDI-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-MPCDI-converter/tools/packman/packman.cmd | :: Reset errorlevel status (don't inherit from caller) [xxxxxxxxxxx]
@call :ECHO_AND_RESET_ERROR
:: You can remove the call below if you do your own manual configuration of the dev machines
call "%~dp0\bootstrap\configure.bat"
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
:: Generate temporary path for variable file
for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile ^
-File "%~dp0bootstrap\generate_temp_file_name.ps1"') do set PM_VAR_PATH=%%a
if %1.==. (
set PM_VAR_PATH_ARG=
) else (
set PM_VAR_PATH_ARG=--var-path="%PM_VAR_PATH%"
)
"%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
:ECHO_AND_RESET_ERROR
@echo off
if /I "%PM_VERBOSITY%"=="debug" (
@echo on
)
exit /b 0
|
MomentFactory/Omniverse-MPCDI-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-MPCDI-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
# ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0
# IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENsYXNzIDMgU0hBMjU2IENvZGUg
# U2lnbmluZyBDQSAtIEcyMB4XDTE4MDcwOTAwMDAwMFoXDTIxMDcwOTIzNTk1OVow
# gYMxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRQwEgYDVQQHDAtT
# YW50YSBDbGFyYTEbMBkGA1UECgwSTlZJRElBIENvcnBvcmF0aW9uMQ8wDQYDVQQL
# DAZJVC1NSVMxGzAZBgNVBAMMEk5WSURJQSBDb3Jwb3JhdGlvbjCCASIwDQYJKoZI
# hvcNAQEBBQADggEPADCCAQoCggEBALEZN63dA47T4i90jZ84CJ/aWUwVtLff8AyP
# YspFfIZGdZYiMgdb8A5tBh7653y0G/LZL6CVUkgejcpvBU/Dl/52a+gSWy2qJ2bH
# jMFMKCyQDhdpCAKMOUKSC9rfzm4cFeA9ct91LQCAait4LhLlZt/HF7aG+r0FgCZa
# HJjJvE7KNY9G4AZXxjSt8CXS8/8NQMANqjLX1r+F+Hl8PzQ1fVx0mMsbdtaIV4Pj
# 5flAeTUnz6+dCTx3vTUo8MYtkS2UBaQv7t7H2B7iwJDakEQKk1XHswJdeqG0osDU
# z6+NVks7uWE1N8UIhvzbw0FEX/U2kpfyWaB/J3gMl8rVR8idPj8CAwEAAaOCAT4w
# ggE6MAkGA1UdEwQCMAAwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUF
# BwMDMGEGA1UdIARaMFgwVgYGZ4EMAQQBMEwwIwYIKwYBBQUHAgEWF2h0dHBzOi8v
# ZC5zeW1jYi5jb20vY3BzMCUGCCsGAQUFBwICMBkMF2h0dHBzOi8vZC5zeW1jYi5j
# b20vcnBhMB8GA1UdIwQYMBaAFNTABiJJ6zlL3ZPiXKG4R3YJcgNYMCsGA1UdHwQk
# MCIwIKAeoByGGmh0dHA6Ly9yYi5zeW1jYi5jb20vcmIuY3JsMFcGCCsGAQUFBwEB
# BEswSTAfBggrBgEFBQcwAYYTaHR0cDovL3JiLnN5bWNkLmNvbTAmBggrBgEFBQcw
# AoYaaHR0cDovL3JiLnN5bWNiLmNvbS9yYi5jcnQwDQYJKoZIhvcNAQELBQADggEB
# AIJKh5vKJdhHJtMzATmc1BmXIQ3RaJONOZ5jMHn7HOkYU1JP0OIzb4pXXkH8Xwfr
# K6bnd72IhcteyksvKsGpSvK0PBBwzodERTAu1Os2N+EaakxQwV/xtqDm1E3IhjHk
# fRshyKKzmFk2Ci323J4lHtpWUj5Hz61b8gd72jH7xnihGi+LORJ2uRNZ3YuqMNC3
# SBC8tAyoJqEoTJirULUCXW6wX4XUm5P2sx+htPw7szGblVKbQ+PFinNGnsSEZeKz
# D8jUb++1cvgTKH59Y6lm43nsJjkZU77tNqyq4ABwgQRk6lt8cS2PPwjZvTmvdnla
# ZhR0K4of+pQaUQHXVIBdji8wggVHMIIEL6ADAgECAhB8GzU1SufbdOdBXxFpymuo
# MA0GCSqGSIb3DQEBCwUAMIG9MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNp
# Z24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNV
# BAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
# IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmlj
# YXRpb24gQXV0aG9yaXR5MB4XDTE0MDcyMjAwMDAwMFoXDTI0MDcyMTIzNTk1OVow
# gYQxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEf
# MB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazE1MDMGA1UEAxMsU3ltYW50
# ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBIC0gRzIwggEiMA0GCSqG
# SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXlUPU3N9nrjn7UqS2JjEEcOm3jlsqujdp
# NZWPu8Aw54bYc7vf69F2P4pWjustS/BXGE6xjaUz0wt1I9VqeSfdo9P3Dodltd6t
# HPH1NbQiUa8iocFdS5B/wFlOq515qQLXHkmxO02H/sJ4q7/vUq6crwjZOeWaUT5p
# XzAQTnFjbFjh8CAzGw90vlvLEuHbjMSAlHK79kWansElC/ujHJ7YpglwcezAR0yP
# fcPeGc4+7gRyjhfT//CyBTIZTNOwHJ/+pXggQnBBsCaMbwDIOgARQXpBsKeKkQSg
# mXj0d7TzYCrmbFAEtxRg/w1R9KiLhP4h2lxeffUpeU+wRHRvbXL/AgMBAAGjggF4
# MIIBdDAuBggrBgEFBQcBAQQiMCAwHgYIKwYBBQUHMAGGEmh0dHA6Ly9zLnN5bWNk
# LmNvbTASBgNVHRMBAf8ECDAGAQH/AgEAMGYGA1UdIARfMF0wWwYLYIZIAYb4RQEH
# FwMwTDAjBggrBgEFBQcCARYXaHR0cHM6Ly9kLnN5bWNiLmNvbS9jcHMwJQYIKwYB
# BQUHAgIwGRoXaHR0cHM6Ly9kLnN5bWNiLmNvbS9ycGEwNgYDVR0fBC8wLTAroCmg
# J4YlaHR0cDovL3Muc3ltY2IuY29tL3VuaXZlcnNhbC1yb290LmNybDATBgNVHSUE
# DDAKBggrBgEFBQcDAzAOBgNVHQ8BAf8EBAMCAQYwKQYDVR0RBCIwIKQeMBwxGjAY
# BgNVBAMTEVN5bWFudGVjUEtJLTEtNzI0MB0GA1UdDgQWBBTUwAYiSes5S92T4lyh
# uEd2CXIDWDAfBgNVHSMEGDAWgBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG
# 9w0BAQsFAAOCAQEAf+vKp+qLdkLrPo4gVDDjt7nc+kg+FscPRZUQzSeGo2bzAu1x
# +KrCVZeRcIP5Un5SaTzJ8eCURoAYu6HUpFam8x0AkdWG80iH4MvENGggXrTL+QXt
# nK9wUye56D5+UaBpcYvcUe2AOiUyn0SvbkMo0yF1u5fYi4uM/qkERgSF9xWcSxGN
# xCwX/tVuf5riVpLxlrOtLfn039qJmc6yOETA90d7yiW5+ipoM5tQct6on9TNLAs0
# vYsweEDgjY4nG5BvGr4IFYFd6y/iUedRHsl4KeceZb847wFKAQkkDhbEFHnBQTc0
# 0D2RUpSd4WjvCPDiaZxnbpALGpNx1CYCw8BaIzGCD4swgg+HAgEBMIGZMIGEMQsw
# CQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNV
# BAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENs
# YXNzIDMgU0hBMjU2IENvZGUgU2lnbmluZyBDQSAtIEcyAhBi50XpIWUhPJcfXEkK
# 6hKlMA0GCWCGSAFlAwQCAQUAoHwwEAYKKwYBBAGCNwIBDDECMAAwGQYJKoZIhvcN
# AQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUw
# LwYJKoZIhvcNAQkEMSIEIPW+EpFrZSdzrjFFo0UT+PzFeYn/GcWNyWFaU/JMrMfR
# MA0GCSqGSIb3DQEBAQUABIIBAA8fmU/RJcF9t60DZZAjf8FB3EZddOaHgI9z40nV
# CnfTGi0OEYU48Pe9jkQQV2fABpACfW74xmNv3QNgP2qP++mkpKBVv28EIAuINsFt
# YAITEljLN/VOVul8lvjxar5GSFFgpE5F6j4xcvI69LuCWbN8cteTVsBGg+eGmjfx
# QZxP252z3FqPN+mihtFegF2wx6Mg6/8jZjkO0xjBOwSdpTL4uyQfHvaPBKXuWxRx
# ioXw4ezGAwkuBoxWK8UG7Qu+7CSfQ3wMOjvyH2+qn30lWEsvRMdbGAp7kvfr3EGZ
# a3WN7zXZ+6KyZeLeEH7yCDzukAjptaY/+iLVjJsuzC6tCSqhgg1EMIINQAYKKwYB
# BAGCNwMDATGCDTAwgg0sBgkqhkiG9w0BBwKggg0dMIINGQIBAzEPMA0GCWCGSAFl
# AwQCAQUAMHcGCyqGSIb3DQEJEAEEoGgEZjBkAgEBBglghkgBhv1sBwEwMTANBglg
# hkgBZQMEAgEFAAQg14BnPazQkW9whhZu1d0bC3lqqScvxb3SSb1QT8e3Xg0CEFhw
# aMBZ2hExXhr79A9+bXEYDzIwMjEwNDA4MDkxMTA5WqCCCjcwggT+MIID5qADAgEC
# AhANQkrgvjqI/2BAIc4UAPDdMA0GCSqGSIb3DQEBCwUAMHIxCzAJBgNVBAYTAlVT
# MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
# b20xMTAvBgNVBAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBp
# bmcgQ0EwHhcNMjEwMTAxMDAwMDAwWhcNMzEwMTA2MDAwMDAwWjBIMQswCQYDVQQG
# EwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xIDAeBgNVBAMTF0RpZ2lDZXJ0
# IFRpbWVzdGFtcCAyMDIxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
# wuZhhGfFivUNCKRFymNrUdc6EUK9CnV1TZS0DFC1JhD+HchvkWsMlucaXEjvROW/
# m2HNFZFiWrj/ZwucY/02aoH6KfjdK3CF3gIY83htvH35x20JPb5qdofpir34hF0e
# dsnkxnZ2OlPR0dNaNo/Go+EvGzq3YdZz7E5tM4p8XUUtS7FQ5kE6N1aG3JMjjfdQ
# Jehk5t3Tjy9XtYcg6w6OLNUj2vRNeEbjA4MxKUpcDDGKSoyIxfcwWvkUrxVfbENJ
# Cf0mI1P2jWPoGqtbsR0wwptpgrTb/FZUvB+hh6u+elsKIC9LCcmVp42y+tZji06l
# chzun3oBc/gZ1v4NSYS9AQIDAQABo4IBuDCCAbQwDgYDVR0PAQH/BAQDAgeAMAwG
# A1UdEwEB/wQCMAAwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwgwQQYDVR0gBDowODA2
# BglghkgBhv1sBwEwKTAnBggrBgEFBQcCARYbaHR0cDovL3d3dy5kaWdpY2VydC5j
# b20vQ1BTMB8GA1UdIwQYMBaAFPS24SAd/imu0uRhpbKiJbLIFzVuMB0GA1UdDgQW
# BBQ2RIaOpLqwZr68KC0dRDbd42p6vDBxBgNVHR8EajBoMDKgMKAuhixodHRwOi8v
# Y3JsMy5kaWdpY2VydC5jb20vc2hhMi1hc3N1cmVkLXRzLmNybDAyoDCgLoYsaHR0
# cDovL2NybDQuZGlnaWNlcnQuY29tL3NoYTItYXNzdXJlZC10cy5jcmwwgYUGCCsG
# AQUFBwEBBHkwdzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29t
# ME8GCCsGAQUFBzAChkNodHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNl
# cnRTSEEyQXNzdXJlZElEVGltZXN0YW1waW5nQ0EuY3J0MA0GCSqGSIb3DQEBCwUA
# A4IBAQBIHNy16ZojvOca5yAOjmdG/UJyUXQKI0ejq5LSJcRwWb4UoOUngaVNFBUZ
# B3nw0QTDhtk7vf5EAmZN7WmkD/a4cM9i6PVRSnh5Nnont/PnUp+Tp+1DnnvntN1B
# Ion7h6JGA0789P63ZHdjXyNSaYOC+hpT7ZDMjaEXcw3082U5cEvznNZ6e9oMvD0y
# 0BvL9WH8dQgAdryBDvjA4VzPxBFy5xtkSdgimnUVQvUtMjiB2vRgorq0Uvtc4GEk
# JU+y38kpqHNDUdq9Y9YfW5v3LhtPEx33Sg1xfpe39D+E68Hjo0mh+s6nv1bPull2
# YYlffqe0jmd4+TaY4cso2luHpoovMIIFMTCCBBmgAwIBAgIQCqEl1tYyG35B5AXa
# NpfCFTANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln
# aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtE
# aWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMTYwMTA3MTIwMDAwWhcNMzEw
# MTA3MTIwMDAwWjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5j
# MRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBT
# SEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBMIIBIjANBgkqhkiG9w0BAQEF
# AAOCAQ8AMIIBCgKCAQEAvdAy7kvNj3/dqbqCmcU5VChXtiNKxA4HRTNREH3Q+X1N
# aH7ntqD0jbOI5Je/YyGQmL8TvFfTw+F+CNZqFAA49y4eO+7MpvYyWf5fZT/gm+vj
# RkcGGlV+Cyd+wKL1oODeIj8O/36V+/OjuiI+GKwR5PCZA207hXwJ0+5dyJoLVOOo
# CXFr4M8iEA91z3FyTgqt30A6XLdR4aF5FMZNJCMwXbzsPGBqrC8HzP3w6kfZiFBe
# /WZuVmEnKYmEUeaC50ZQ/ZQqLKfkdT66mA+Ef58xFNat1fJky3seBdCEGXIX8RcG
# 7z3N1k3vBkL9olMqT4UdxB08r8/arBD13ays6Vb/kwIDAQABo4IBzjCCAcowHQYD
# VR0OBBYEFPS24SAd/imu0uRhpbKiJbLIFzVuMB8GA1UdIwQYMBaAFEXroq/0ksuC
# MS1Ri6enIZ3zbcgPMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGG
# MBMGA1UdJQQMMAoGCCsGAQUFBwMIMHkGCCsGAQUFBwEBBG0wazAkBggrBgEFBQcw
# AYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEMGCCsGAQUFBzAChjdodHRwOi8v
# Y2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3J0
# MIGBBgNVHR8EejB4MDqgOKA2hjRodHRwOi8vY3JsNC5kaWdpY2VydC5jb20vRGln
# aUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMDqgOKA2hjRodHRwOi8vY3JsMy5kaWdp
# Y2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMFAGA1UdIARJMEcw
# OAYKYIZIAYb9bAACBDAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2Vy
# dC5jb20vQ1BTMAsGCWCGSAGG/WwHATANBgkqhkiG9w0BAQsFAAOCAQEAcZUS6VGH
# VmnN793afKpjerN4zwY3QITvS4S/ys8DAv3Fp8MOIEIsr3fzKx8MIVoqtwU0HWqu
# mfgnoma/Capg33akOpMP+LLR2HwZYuhegiUexLoceywh4tZbLBQ1QwRostt1AuBy
# x5jWPGTlH0gQGF+JOGFNYkYkh2OMkVIsrymJ5Xgf1gsUpYDXEkdws3XVk4WTfraS
# Z/tTYYmo9WuWwPRYaQ18yAGxuSh1t5ljhSKMYcp5lH5Z/IwP42+1ASa2bKXuh1Eh
# 5Fhgm7oMLSttosR+u8QlK0cCCHxJrhO24XxCQijGGFbPQTS2Zl22dHv1VjMiLyI2
# skuiSpXY9aaOUjGCAk0wggJJAgEBMIGGMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQK
# EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNV
# 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-MPCDI-converter/tools/packman/bootstrap/configure.bat | :: 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.
set PM_PACKMAN_VERSION=6.33.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 directory %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.7.9-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 rename
rename "%TEMP_FOLDER_NAME%" "%PM_PYTHON_VERSION%" 1> nul
:: Failure during move, need to clean up and abort
if %errorlevel% neq 0 (
echo !!! Error renaming python !!!
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%\packman.py
if exist "%PM_MODULE%" goto ENSURE_7ZA
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%"
:ENSURE_7ZA
set PM_7Za_VERSION=16.02.4
set PM_7Za_PATH=%PM_PACKAGES_ROOT%\7za\%PM_7ZA_VERSION%
if exist "%PM_7Za_PATH%" goto END
set PM_7Za_PATH=%PM_PACKAGES_ROOT%\chk\7za\%PM_7ZA_VERSION%
if exist "%PM_7Za_PATH%" goto END
"%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" pull "%PM_MODULE_DIR%\deps.packman.xml"
if %errorlevel% neq 0 (
echo !!! Error fetching packman dependencies !!!
goto ERROR
)
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-MPCDI-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 and is larger than 0 bytes:
@if not exist %TARGET_PATH% goto ERROR_DOWNLOAD_FAILED
@if %~z2==0 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-MPCDI-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 = 3
do
{
$triesLeft -= 1
try
{
Write-Host "Downloading from bootstrap.packman.nvidia.com ..."
$wc = New-Object net.webclient
$wc.Downloadfile($source, $fileName)
$triesLeft = 0
}
catch
{
Write-Host "Error downloading $source!"
Write-Host $_.Exception|format-list -force
}
} while ($triesLeft -gt 0)
|
MomentFactory/Omniverse-MPCDI-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
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCB29nsqMEu+VmSF
# 7ckeVTPrEZ6hsXjOgPFlJm9ilgHUB6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh
# PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE
# ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0
# IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENsYXNzIDMgU0hBMjU2IENvZGUg
# U2lnbmluZyBDQSAtIEcyMB4XDTE4MDcwOTAwMDAwMFoXDTIxMDcwOTIzNTk1OVow
# gYMxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRQwEgYDVQQHDAtT
# YW50YSBDbGFyYTEbMBkGA1UECgwSTlZJRElBIENvcnBvcmF0aW9uMQ8wDQYDVQQL
# DAZJVC1NSVMxGzAZBgNVBAMMEk5WSURJQSBDb3Jwb3JhdGlvbjCCASIwDQYJKoZI
# hvcNAQEBBQADggEPADCCAQoCggEBALEZN63dA47T4i90jZ84CJ/aWUwVtLff8AyP
# YspFfIZGdZYiMgdb8A5tBh7653y0G/LZL6CVUkgejcpvBU/Dl/52a+gSWy2qJ2bH
# jMFMKCyQDhdpCAKMOUKSC9rfzm4cFeA9ct91LQCAait4LhLlZt/HF7aG+r0FgCZa
# HJjJvE7KNY9G4AZXxjSt8CXS8/8NQMANqjLX1r+F+Hl8PzQ1fVx0mMsbdtaIV4Pj
# 5flAeTUnz6+dCTx3vTUo8MYtkS2UBaQv7t7H2B7iwJDakEQKk1XHswJdeqG0osDU
# z6+NVks7uWE1N8UIhvzbw0FEX/U2kpfyWaB/J3gMl8rVR8idPj8CAwEAAaOCAT4w
# ggE6MAkGA1UdEwQCMAAwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUF
# BwMDMGEGA1UdIARaMFgwVgYGZ4EMAQQBMEwwIwYIKwYBBQUHAgEWF2h0dHBzOi8v
# ZC5zeW1jYi5jb20vY3BzMCUGCCsGAQUFBwICMBkMF2h0dHBzOi8vZC5zeW1jYi5j
# b20vcnBhMB8GA1UdIwQYMBaAFNTABiJJ6zlL3ZPiXKG4R3YJcgNYMCsGA1UdHwQk
# MCIwIKAeoByGGmh0dHA6Ly9yYi5zeW1jYi5jb20vcmIuY3JsMFcGCCsGAQUFBwEB
# BEswSTAfBggrBgEFBQcwAYYTaHR0cDovL3JiLnN5bWNkLmNvbTAmBggrBgEFBQcw
# AoYaaHR0cDovL3JiLnN5bWNiLmNvbS9yYi5jcnQwDQYJKoZIhvcNAQELBQADggEB
# AIJKh5vKJdhHJtMzATmc1BmXIQ3RaJONOZ5jMHn7HOkYU1JP0OIzb4pXXkH8Xwfr
# K6bnd72IhcteyksvKsGpSvK0PBBwzodERTAu1Os2N+EaakxQwV/xtqDm1E3IhjHk
# fRshyKKzmFk2Ci323J4lHtpWUj5Hz61b8gd72jH7xnihGi+LORJ2uRNZ3YuqMNC3
# SBC8tAyoJqEoTJirULUCXW6wX4XUm5P2sx+htPw7szGblVKbQ+PFinNGnsSEZeKz
# D8jUb++1cvgTKH59Y6lm43nsJjkZU77tNqyq4ABwgQRk6lt8cS2PPwjZvTmvdnla
# ZhR0K4of+pQaUQHXVIBdji8wggVHMIIEL6ADAgECAhB8GzU1SufbdOdBXxFpymuo
# MA0GCSqGSIb3DQEBCwUAMIG9MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNp
# Z24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNV
# BAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
# IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmlj
# YXRpb24gQXV0aG9yaXR5MB4XDTE0MDcyMjAwMDAwMFoXDTI0MDcyMTIzNTk1OVow
# gYQxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEf
# MB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazE1MDMGA1UEAxMsU3ltYW50
# ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBIC0gRzIwggEiMA0GCSqG
# SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXlUPU3N9nrjn7UqS2JjEEcOm3jlsqujdp
# NZWPu8Aw54bYc7vf69F2P4pWjustS/BXGE6xjaUz0wt1I9VqeSfdo9P3Dodltd6t
# HPH1NbQiUa8iocFdS5B/wFlOq515qQLXHkmxO02H/sJ4q7/vUq6crwjZOeWaUT5p
# XzAQTnFjbFjh8CAzGw90vlvLEuHbjMSAlHK79kWansElC/ujHJ7YpglwcezAR0yP
# fcPeGc4+7gRyjhfT//CyBTIZTNOwHJ/+pXggQnBBsCaMbwDIOgARQXpBsKeKkQSg
# mXj0d7TzYCrmbFAEtxRg/w1R9KiLhP4h2lxeffUpeU+wRHRvbXL/AgMBAAGjggF4
# MIIBdDAuBggrBgEFBQcBAQQiMCAwHgYIKwYBBQUHMAGGEmh0dHA6Ly9zLnN5bWNk
# LmNvbTASBgNVHRMBAf8ECDAGAQH/AgEAMGYGA1UdIARfMF0wWwYLYIZIAYb4RQEH
# FwMwTDAjBggrBgEFBQcCARYXaHR0cHM6Ly9kLnN5bWNiLmNvbS9jcHMwJQYIKwYB
# BQUHAgIwGRoXaHR0cHM6Ly9kLnN5bWNiLmNvbS9ycGEwNgYDVR0fBC8wLTAroCmg
# J4YlaHR0cDovL3Muc3ltY2IuY29tL3VuaXZlcnNhbC1yb290LmNybDATBgNVHSUE
# DDAKBggrBgEFBQcDAzAOBgNVHQ8BAf8EBAMCAQYwKQYDVR0RBCIwIKQeMBwxGjAY
# BgNVBAMTEVN5bWFudGVjUEtJLTEtNzI0MB0GA1UdDgQWBBTUwAYiSes5S92T4lyh
# uEd2CXIDWDAfBgNVHSMEGDAWgBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG
# 9w0BAQsFAAOCAQEAf+vKp+qLdkLrPo4gVDDjt7nc+kg+FscPRZUQzSeGo2bzAu1x
# +KrCVZeRcIP5Un5SaTzJ8eCURoAYu6HUpFam8x0AkdWG80iH4MvENGggXrTL+QXt
# nK9wUye56D5+UaBpcYvcUe2AOiUyn0SvbkMo0yF1u5fYi4uM/qkERgSF9xWcSxGN
# xCwX/tVuf5riVpLxlrOtLfn039qJmc6yOETA90d7yiW5+ipoM5tQct6on9TNLAs0
# vYsweEDgjY4nG5BvGr4IFYFd6y/iUedRHsl4KeceZb847wFKAQkkDhbEFHnBQTc0
# 0D2RUpSd4WjvCPDiaZxnbpALGpNx1CYCw8BaIzGCD4swgg+HAgEBMIGZMIGEMQsw
# CQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNV
# BAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENs
# YXNzIDMgU0hBMjU2IENvZGUgU2lnbmluZyBDQSAtIEcyAhBi50XpIWUhPJcfXEkK
# 6hKlMA0GCWCGSAFlAwQCAQUAoHwwEAYKKwYBBAGCNwIBDDECMAAwGQYJKoZIhvcN
# AQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUw
# LwYJKoZIhvcNAQkEMSIEIG5YDmcpqLxn4SB0H6OnuVkZRPh6OJ77eGW/6Su/uuJg
# MA0GCSqGSIb3DQEBAQUABIIBAA3N2vqfA6WDgqz/7EoAKVIE5Hn7xpYDGhPvFAMV
# BslVpeqE3apTcYFCEcwLtzIEc/zmpULxsX8B0SUT2VXbJN3zzQ80b+gbgpq62Zk+
# dQLOtLSiPhGW7MXLahgES6Oc2dUFaQ+wDfcelkrQaOVZkM4wwAzSapxuf/13oSIk
# ZX2ewQEwTZrVYXELO02KQIKUR30s/oslGVg77ALnfK9qSS96Iwjd4MyT7PzCkHUi
# ilwyGJi5a4ofiULiPSwUQNynSBqxa+JQALkHP682b5xhjoDfyG8laR234FTPtYgs
# P/FaeviwENU5Pl+812NbbtRD+gKlWBZz+7FKykOT/CG8sZahgg1EMIINQAYKKwYB
# BAGCNwMDATGCDTAwgg0sBgkqhkiG9w0BBwKggg0dMIINGQIBAzEPMA0GCWCGSAFl
# AwQCAQUAMHcGCyqGSIb3DQEJEAEEoGgEZjBkAgEBBglghkgBhv1sBwEwMTANBglg
# hkgBZQMEAgEFAAQgJhABfkDIPbI+nWYnA30FLTyaPK+W3QieT21B/vK+CMICEDF0
# worcGsdd7OxpXLP60xgYDzIwMjEwNDA4MDkxMTA5WqCCCjcwggT+MIID5qADAgEC
# AhANQkrgvjqI/2BAIc4UAPDdMA0GCSqGSIb3DQEBCwUAMHIxCzAJBgNVBAYTAlVT
# MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
# b20xMTAvBgNVBAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBp
# bmcgQ0EwHhcNMjEwMTAxMDAwMDAwWhcNMzEwMTA2MDAwMDAwWjBIMQswCQYDVQQG
# EwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xIDAeBgNVBAMTF0RpZ2lDZXJ0
# IFRpbWVzdGFtcCAyMDIxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
# wuZhhGfFivUNCKRFymNrUdc6EUK9CnV1TZS0DFC1JhD+HchvkWsMlucaXEjvROW/
# m2HNFZFiWrj/ZwucY/02aoH6KfjdK3CF3gIY83htvH35x20JPb5qdofpir34hF0e
# dsnkxnZ2OlPR0dNaNo/Go+EvGzq3YdZz7E5tM4p8XUUtS7FQ5kE6N1aG3JMjjfdQ
# Jehk5t3Tjy9XtYcg6w6OLNUj2vRNeEbjA4MxKUpcDDGKSoyIxfcwWvkUrxVfbENJ
# Cf0mI1P2jWPoGqtbsR0wwptpgrTb/FZUvB+hh6u+elsKIC9LCcmVp42y+tZji06l
# chzun3oBc/gZ1v4NSYS9AQIDAQABo4IBuDCCAbQwDgYDVR0PAQH/BAQDAgeAMAwG
# A1UdEwEB/wQCMAAwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwgwQQYDVR0gBDowODA2
# BglghkgBhv1sBwEwKTAnBggrBgEFBQcCARYbaHR0cDovL3d3dy5kaWdpY2VydC5j
# b20vQ1BTMB8GA1UdIwQYMBaAFPS24SAd/imu0uRhpbKiJbLIFzVuMB0GA1UdDgQW
# BBQ2RIaOpLqwZr68KC0dRDbd42p6vDBxBgNVHR8EajBoMDKgMKAuhixodHRwOi8v
# Y3JsMy5kaWdpY2VydC5jb20vc2hhMi1hc3N1cmVkLXRzLmNybDAyoDCgLoYsaHR0
# cDovL2NybDQuZGlnaWNlcnQuY29tL3NoYTItYXNzdXJlZC10cy5jcmwwgYUGCCsG
# AQUFBwEBBHkwdzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29t
# ME8GCCsGAQUFBzAChkNodHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNl
# cnRTSEEyQXNzdXJlZElEVGltZXN0YW1waW5nQ0EuY3J0MA0GCSqGSIb3DQEBCwUA
# A4IBAQBIHNy16ZojvOca5yAOjmdG/UJyUXQKI0ejq5LSJcRwWb4UoOUngaVNFBUZ
# B3nw0QTDhtk7vf5EAmZN7WmkD/a4cM9i6PVRSnh5Nnont/PnUp+Tp+1DnnvntN1B
# Ion7h6JGA0789P63ZHdjXyNSaYOC+hpT7ZDMjaEXcw3082U5cEvznNZ6e9oMvD0y
# 0BvL9WH8dQgAdryBDvjA4VzPxBFy5xtkSdgimnUVQvUtMjiB2vRgorq0Uvtc4GEk
# JU+y38kpqHNDUdq9Y9YfW5v3LhtPEx33Sg1xfpe39D+E68Hjo0mh+s6nv1bPull2
# YYlffqe0jmd4+TaY4cso2luHpoovMIIFMTCCBBmgAwIBAgIQCqEl1tYyG35B5AXa
# NpfCFTANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln
# aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtE
# aWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMTYwMTA3MTIwMDAwWhcNMzEw
# MTA3MTIwMDAwWjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5j
# MRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBT
# SEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBMIIBIjANBgkqhkiG9w0BAQEF
# AAOCAQ8AMIIBCgKCAQEAvdAy7kvNj3/dqbqCmcU5VChXtiNKxA4HRTNREH3Q+X1N
# aH7ntqD0jbOI5Je/YyGQmL8TvFfTw+F+CNZqFAA49y4eO+7MpvYyWf5fZT/gm+vj
# RkcGGlV+Cyd+wKL1oODeIj8O/36V+/OjuiI+GKwR5PCZA207hXwJ0+5dyJoLVOOo
# CXFr4M8iEA91z3FyTgqt30A6XLdR4aF5FMZNJCMwXbzsPGBqrC8HzP3w6kfZiFBe
# /WZuVmEnKYmEUeaC50ZQ/ZQqLKfkdT66mA+Ef58xFNat1fJky3seBdCEGXIX8RcG
# 7z3N1k3vBkL9olMqT4UdxB08r8/arBD13ays6Vb/kwIDAQABo4IBzjCCAcowHQYD
# VR0OBBYEFPS24SAd/imu0uRhpbKiJbLIFzVuMB8GA1UdIwQYMBaAFEXroq/0ksuC
# MS1Ri6enIZ3zbcgPMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGG
# MBMGA1UdJQQMMAoGCCsGAQUFBwMIMHkGCCsGAQUFBwEBBG0wazAkBggrBgEFBQcw
# AYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEMGCCsGAQUFBzAChjdodHRwOi8v
# Y2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3J0
# MIGBBgNVHR8EejB4MDqgOKA2hjRodHRwOi8vY3JsNC5kaWdpY2VydC5jb20vRGln
# aUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMDqgOKA2hjRodHRwOi8vY3JsMy5kaWdp
# Y2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMFAGA1UdIARJMEcw
# OAYKYIZIAYb9bAACBDAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2Vy
# dC5jb20vQ1BTMAsGCWCGSAGG/WwHATANBgkqhkiG9w0BAQsFAAOCAQEAcZUS6VGH
# VmnN793afKpjerN4zwY3QITvS4S/ys8DAv3Fp8MOIEIsr3fzKx8MIVoqtwU0HWqu
# mfgnoma/Capg33akOpMP+LLR2HwZYuhegiUexLoceywh4tZbLBQ1QwRostt1AuBy
# x5jWPGTlH0gQGF+JOGFNYkYkh2OMkVIsrymJ5Xgf1gsUpYDXEkdws3XVk4WTfraS
# Z/tTYYmo9WuWwPRYaQ18yAGxuSh1t5ljhSKMYcp5lH5Z/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-MPCDI-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 shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
|
MomentFactory/Omniverse-MPCDI-converter/exts/mf.ov.mpcdi_converter/mf/ov/mpcdi_converter/extension.py | import os
import time
from typing import List
import omni.ext
import omni.client
import carb
import omni.kit.notification_manager as nm
from omni.kit.notification_manager import NotificationStatus
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.ui as ui
import omni.kit.tool.asset_importer as ai
import omni.kit.window.content_browser as content
from .omni_client_wrapper import OmniClientWrapper
import xml.etree.ElementTree as ET
from pxr import UsdGeom, Sdf, Gf, Tf
import math
import logging
class MPCDIConverterContext:
usd_reference_path = ""
class MPCDIConverterHelper:
def __init__(self):
pass
def _cleanNameForUSD(self, strIn: str) -> str:
strOut = strIn
# Do not allow for a blank name
if len(strOut) == 0:
return "Default"
elif len(strOut) == 1 and strIn.isnumeric():
# If we have an index as a name, we only need to add _ beforehand.
return "_" + strIn
return Tf.MakeValidIdentifier(strIn)
def _convert_xml_to_usd(self, absolute_path_xml):
result = 0
try:
_, _, content = omni.client.read_file(absolute_path_xml)
data = memoryview(content).tobytes()
# Read xml file here
root = ET.fromstring(data)
hasLensShifting = False
stage = omni.usd.get_context().get_stage()
mpcdiId = "/MPCDI"
stage.DefinePrim(mpcdiId, "Xform")
# Create usd content here
for display in root:
if display.tag != 'display':
continue
for buffer in display:
bufferId = buffer.attrib['id']
bufferPath = mpcdiId + '/' + self._cleanNameForUSD(bufferId)
stage.DefinePrim(bufferPath, "Scope")
# A region is a projector
for region in buffer:
# GetCoordFrams
coordinateFrame = region.find('coordinateFrame')
# Get Position
posX = float(coordinateFrame.find('posx').text) * 10
posY = float(coordinateFrame.find('posy').text) * 10
posZ = float(coordinateFrame.find('posz').text) * 10
# Get Axis up
upX = float(coordinateFrame.find('yawx').text)
upY = float(coordinateFrame.find('yawy').text)
upZ = float(coordinateFrame.find('yawz').text)
# Get Axis right
rightX = float(coordinateFrame.find('pitchx').text)
rightY = float(coordinateFrame.find('pitchy').text)
rightZ = float(coordinateFrame.find('pitchz').text)
# Get Axis down
forwardX = float(coordinateFrame.find('rollx').text)
forwardY = float(coordinateFrame.find('rolly').text)
forwardZ = float(coordinateFrame.find('rollz').text)
# The "coordinateFrame" provided in the MPCDI comes with three vectors to solve any coordinate
# system ambiguity we meed to convert the position from the "source" coordinate system to the
# standard MPCDI system And then convert from the standard to the Omniverse system
sourceToStandard = Gf.Matrix3f(
rightX, rightY, rightZ,
upX, upY, upZ,
forwardX, forwardY, forwardZ)
# Omniverse uses the same axis for Roll/Pitch/Yaw than the standard, so we have a diagonal matrix
# BUT the Y and Z axis are pointing to the opposite direction, so we need to invert them
# in the matrix. Here we'll avoid a second matrix product and simply invert Y and Z of the
# vector instead.
newPos = sourceToStandard * Gf.Vec3f(posX, posY, posZ)
newPos[1] = newPos[1] * -1.0
newPos[2] = newPos[2] * -1.0
frustum = region.find('frustum')
yaw = float(frustum.find('yaw').text) * -1
pitch = float(frustum.find('pitch').text)
roll = float(frustum.find('roll').text)
# For the moment we do not support lens shifting, so we simply add the two angles and assume
# They are the same on both sides of the angle.
fovRight = float(frustum.find('rightAngle').text)
fovLeft = float(frustum.find('leftAngle').text)
fovTop = float(frustum.find('upAngle').text)
fovBottom = float(frustum.find('downAngle').text)
focalLength = 10 # We chose a fixed focal length.
tanRight = math.tan(math.radians(fovRight))
tanLeft = math.tan(math.radians(fovLeft))
tanUp = math.tan(math.radians(fovTop))
tanDown = math.tan(math.radians(fovBottom))
apertureH = (abs(tanRight) + abs(tanLeft)) * focalLength
apertureV = (abs(tanUp) + abs(tanDown)) * focalLength
lightWidth = abs(tanRight) + abs(tanLeft)
lightHeight = abs(tanUp) + abs(tanDown)
horizLensShiftAmount = (tanLeft + tanRight) / (tanLeft - tanRight)
vertLensShiftAmount = (tanUp + tanDown) / (tanUp - tanDown)
horizApertureOffset = horizLensShiftAmount * apertureH / 2.0
vertApertureOffset = vertLensShiftAmount * apertureV / 2.0
if fovRight != fovLeft or fovTop != fovBottom:
hasLensShifting = True
regionId = region.attrib['id']
primPath = bufferPath + '/' + self._cleanNameForUSD(regionId)
prim = stage.DefinePrim(primPath, "Camera")
prim.GetAttribute('focalLength').Set(focalLength)
prim.GetAttribute('focusDistance').Set(2000.0)
prim.GetAttribute('horizontalAperture').Set(apertureH)
prim.GetAttribute('horizontalApertureOffset').Set(horizApertureOffset)
prim.GetAttribute('verticalAperture').Set(apertureV)
prim.GetAttribute('verticalApertureOffset').Set(vertApertureOffset)
primXform = UsdGeom.Xformable(prim)
# This prevents from trying to add another Operation if overwritting nodes.
primXform.ClearXformOpOrder()
primXform.AddTranslateOp().Set(value=(newPos * 10.0))
primXform.AddRotateYOp().Set(value=yaw)
primXform.AddRotateXOp().Set(value=pitch)
primXform.AddRotateZOp().Set(value=roll)
# Create rectLight node
rectLightpath = primPath + '/ProjectLight'
rectLight = stage.DefinePrim(rectLightpath, 'RectLight')
# We need to create those attributes as they are not standard in USD and they are omniverse
# Specific. At this point in time Omniverse hasn't added their own attributes.
# We simply do it ourselves.
rectLight.CreateAttribute('isProjector', Sdf.ValueTypeNames.Bool).Set(True)
rectLight.CreateAttribute('intensity', Sdf.ValueTypeNames.Float).Set(15000)
rectLight.CreateAttribute('exposure', Sdf.ValueTypeNames.Float).Set(5)
rectLight.GetAttribute('inputs:width').Set(lightWidth)
rectLight.GetAttribute('inputs:height').Set(lightHeight)
# Creating projector box mesh to simulate the space a projector takes in the space
projectorBoxPath = primPath + '/ProjectorBox'
projector = stage.DefinePrim(projectorBoxPath, 'Cube')
projectorXform = UsdGeom.Xformable(projector)
projectorXform.ClearXformOpOrder()
projectorXform.AddTranslateOp().Set(value=(0, 0, 42.0))
projectorXform.AddScaleOp().Set(value=(50.0, 15, 40.0))
except Exception as e:
logger = logging.getLogger(__name__)
logger.error(f"Failed to parse MPCDI file. Make sure it is not corrupt. {e}")
return -1
if hasLensShifting:
message = "Lens shifting detected in MPCDI. Lens shifting is not supported."
logger = logging.getLogger(__name__)
logger.warn(message)
nm.post_notification(message, status=NotificationStatus.WARNING)
return result
def _create_import_task(self, absolute_path, relative_path, export_folder, _):
stage = omni.usd.get_context().get_stage()
usd_path = ""
# If the stage is not saved save the imported USD next to the original asset.
if not stage or stage.GetRootLayer().anonymous:
now = time.localtime()
ext = time.strftime("_%H%M%S", now)
basename = relative_path[:relative_path.rfind(".")]
no_folder_name = absolute_path[:absolute_path.find("/" + relative_path)]
host_dir = os.path.join(no_folder_name, "convertedAssets", basename + ext).replace("\\", "/")
# Save the imported USD next to the saved stage.
path_out = omni.usd.get_context().get_stage_url()
# If user makes a selection for the output folder use it.
if export_folder is not None:
path_out = export_folder
path_out_index = path_out.rfind("/")
success = self._convert_xml_to_usd(absolute_path) # self._hi.convert_cad_file_to_usd(absolute_path, path_out[:path_out_index])
ext_index = relative_path.rfind(".")
relative_path = self._cleanNameForUSD(relative_path[:ext_index]) + ".usd"
usd_path = os.path.join(path_out[:path_out_index], relative_path).replace("\\", "/")
logger = logging.getLogger(__name__)
if success == 0:
message = "Import succesful"
logger.info(message)
nm.post_notification(message)
return usd_path
elif success == -10002:
# TODO this is when we have problem reading the file from OV, might need to download it locally
logger.info("NOT IMPLEMENTED: Failure to load model form omniverse server, please select a file from local disk.")
nm.post_notification(
f"Failed to convert file {os.path.basename(absolute_path)}.\n"
"Please check console for more details.",
status=nm.NotificationStatus.WARNING,
)
return None
else:
logger.info("IMPORT FAILED")
nm.post_notification(
f"Failed to convert file {os.path.basename(absolute_path)}.\n"
"Please check console for more details.",
status=nm.NotificationStatus.WARNING,
)
return None
async def create_import_task(self, absolute_paths, relative_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], relative_paths[i],
export_folder, hoops_context)
return converted_assets
class MPCDIConverterOptions:
def __init__(self):
self.cad_converter_context = MPCDIConverterContext()
self.export_folder: str = None
class MPCDIConverterOptionsBuilder:
def __init__(self, usd_context):
super().__init__()
self._file_picker = None
self._usd_context = usd_context
self._export_context = MPCDIConverterOptions()
self._folder_button = None
self._refresh_default_folder = False
self._default_folder = None
self._clear()
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 build_pane(self, asset_paths: List[str]):
self._export_context = self.get_import_options()
if self._refresh_default_folder:
self._export_context.export_folder = self._default_folder
self._default_folder = None
self._refresh_default_folder = False
self._built = True
OPTIONS_STYLE = {
"Rectangle::hovering": {"background_color": 0x0, "border_radius": 2, "margin": 0, "padding": 0},
"Rectangle::hovering:hovered": {"background_color": 0xFF9E9E9E},
"Button.Image::folder": {"image_url": Icons().get("folder")},
"Button.Image::folder:checked": {"image_url": Icons().get("folder")},
"Button::folder": {"background_color": 0x0, "margin": 0},
"Button::folder:checked": {"background_color": 0x0, "margin": 0},
"Button::folder:pressed": {"background_color": 0x0, "margin": 0},
"Button::folder:hovered": {"background_color": 0x0, "margin": 0},
}
with ui.VStack(height=0, style=OPTIONS_STYLE):
ui.Spacer(width=0, height=5)
with ui.HStack(height=0):
ui.Label("Convert To:", width=0)
ui.Spacer(width=3)
with ui.VStack(height=0):
ui.Spacer(height=4)
self._export_folder_field = ui.StringField(height=20, width=ui.Fraction(1), read_only=False)
self._export_folder_field.set_tooltip(
"Left this empty will export USD to the folder that assets are under."
)
ui.Spacer(height=4)
with ui.VStack(height=0, width=0):
ui.Spacer(height=4)
with ui.ZStack(width=20, height=20):
ui.Rectangle(name="hovering")
self._folder_button = ui.Button(name="folder", width=24, height=24)
self._folder_button.set_tooltip("Choose folder")
ui.Spacer(height=4)
ui.Spacer(width=2)
self._folder_button.set_clicked_fn(self._show_file_picker)
ui.Spacer(width=0, height=10)
if self._export_context.export_folder:
self._export_folder_field.model.set_value(self._export_context.export_folder)
else:
self._export_folder_field.model.set_value("")
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):
context = MPCDIConverterOptions()
# TODO enable this after the filepicker bugfix: OM-47383
# if self._built:
# context.export_folder = str.strip(self._export_folder_field.model.get_value_as_string())
# context.export_folder = context.export_folder.replace("\\", "/")
return context
def destroy(self):
self._clear()
if self._file_picker:
self._file_picker.destroy()
class MPCDIConverterDelegate(ai.AbstractImporterDelegate):
def __init__(self, usd_context, name, filters, descriptions):
super().__init__()
self._hoops_options_builder = MPCDIConverterOptionsBuilder(usd_context)
self._hoops_converter = MPCDIConverterHelper()
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, relative_paths, context.export_folder, hoops_context
)
return converted_assets
_global_instance = None
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MfMpcdiConverterExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
global _global_instance
_global_instance = self
self._usd_context = omni.usd.get_context()
self.delegate_mpcdi = MPCDIConverterDelegate(
self._usd_context,
"MPCDI Converter",
["(.*\\.mpcdi\\.xml$)"],
["mpcdi XML Files (*.mpdci.xml)"]
)
ai.register_importer(self.delegate_mpcdi)
def on_shutdown(self):
global _global_instance
_global_instance = None
ai.remove_importer(self.delegate_mpcdi)
self.delegate_mpcdi = None
|
MomentFactory/Omniverse-MPCDI-converter/exts/mf.ov.mpcdi_converter/mf/ov/mpcdi_converter/__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-MPCDI-converter/exts/mf.ov.mpcdi_converter/mf/ov/mpcdi_converter/omni_client_wrapper.py | import os
import traceback
import asyncio
import carb
import omni.client
def _encode_content(content):
if type(content) == str:
payload = bytes(content.encode("utf-8"))
elif type(content) != type(None):
payload = bytes(content)
else:
payload = bytes()
return payload
class OmniClientWrapper:
@staticmethod
async def exists(path):
try:
result, entry = await omni.client.stat_async(path)
return result == omni.client.Result.OK
except Exception as e:
traceback.print_exc()
carb.log_error(str(e))
return False
@staticmethod
def exists_sync(path):
try:
result, entry = omni.client.stat(path)
return result == omni.client.Result.OK
except Exception as e:
traceback.print_exc()
carb.log_error(str(e))
return False
@staticmethod
async def write(path: str, content):
carb.log_info(f"Writing {path}...")
try:
result = await omni.client.write_file_async(path, _encode_content(content))
if result != omni.client.Result.OK:
carb.log_error(f"Cannot write {path}, error code: {result}.")
return False
except Exception as e:
traceback.print_exc()
carb.log_error(str(e))
return False
finally:
carb.log_info(f"Writing {path} done...")
return True
@staticmethod
async def copy(src_path: str, dest_path: str):
carb.log_info(f"Coping from {src_path} to {dest_path}...")
try:
await omni.client.delete_async(dest_path)
result = await omni.client.copy_async(src_path, dest_path)
if result != omni.client.Result.OK:
carb.log_error(f"Cannot copy from {src_path} to {dest_path}, error code: {result}.")
return False
else:
return True
except Exception as e:
traceback.print_exc()
carb.log_error(str(e))
return False
@staticmethod
async def read(src_path: str):
carb.log_info(f"Reading {src_path}...")
try:
result, version, content = await omni.client.read_file_async(src_path)
if result == omni.client.Result.OK:
return memoryview(content).tobytes()
else:
carb.log_error(f"Cannot read {src_path}, error code: {result}.")
except Exception as e:
traceback.print_exc()
carb.log_error(str(e))
finally:
carb.log_info(f"Reading {src_path} done...")
return None
@staticmethod
async def create_folder(path):
carb.log_info(f"Creating dir {path}...")
result = await omni.client.create_folder_async(path)
return result == omni.client.Result.OK or result == omni.client.Result.ERROR_ALREADY_EXISTS
@staticmethod
def create_folder_sync(path):
carb.log_info(f"Creating dir {path}...")
result = omni.client.create_folder(path)
return result == omni.client.Result.OK or result == omni.client.Result.ERROR_ALREADY_EXISTS |
MomentFactory/Omniverse-MPCDI-converter/exts/mf.ov.mpcdi_converter/mf/ov/mpcdi_converter/sample/Cube-mapping.mpcdi.xml | <?xml version="1.0" encoding="UTF-8" ?>
<MPCDI profile="3d" geometry="2" color="1" date="2022-12-07 09-27-28" version="2.0">
<display>
<buffer id="0">
<region id="Rear" xResolution="1920" yResolution="1080" x="0.0" y="0.0" xsize="1.0" ysize="1.0">
<frustum>
<yaw>-0.000000</yaw>
<pitch>-0.000000</pitch>
<roll>-0.000000</roll>
<rightAngle>21.801409</rightAngle>
<leftAngle>-21.801409</leftAngle>
<upAngle>12.680382</upAngle>
<downAngle>-12.680382</downAngle>
</frustum>
<coordinateFrame>
<posx>0.000000</posx>
<posy>0.500000</posy>
<posz>3.000000</posz>
<yawx>0.0</yawx>
<yawy>-1.0</yawy>
<yawz>0.0</yawz>
<pitchx>1.0</pitchx>
<pitchy>0.0</pitchy>
<pitchz>0.0</pitchz>
<rollx>0.0</rollx>
<rolly>0.0</rolly>
<rollz>-1.0</rollz>
</coordinateFrame>
</region>
<region id="Front" xResolution="1920" yResolution="1080" x="0.0" y="0.0" xsize="1.0" ysize="1.0">
<frustum>
<yaw>-180.000000</yaw>
<pitch>-0.000000</pitch>
<roll>-0.000000</roll>
<rightAngle>21.801409</rightAngle>
<leftAngle>-21.801409</leftAngle>
<upAngle>12.680382</upAngle>
<downAngle>-12.680382</downAngle>
</frustum>
<coordinateFrame>
<posx>0.000000</posx>
<posy>0.500000</posy>
<posz>-3.000000</posz>
<yawx>0.0</yawx>
<yawy>-1.0</yawy>
<yawz>0.0</yawz>
<pitchx>1.0</pitchx>
<pitchy>0.0</pitchy>
<pitchz>0.0</pitchz>
<rollx>0.0</rollx>
<rolly>0.0</rolly>
<rollz>-1.0</rollz>
</coordinateFrame>
</region>
<region id="Left" xResolution="1920" yResolution="1080" x="0.0" y="0.0" xsize="1.0" ysize="1.0">
<frustum>
<yaw>-90.000008</yaw>
<pitch>-0.000000</pitch>
<roll>-0.000000</roll>
<rightAngle>21.801409</rightAngle>
<leftAngle>-21.801409</leftAngle>
<upAngle>12.680382</upAngle>
<downAngle>-12.680382</downAngle>
</frustum>
<coordinateFrame>
<posx>3.000000</posx>
<posy>0.500000</posy>
<posz>0.000000</posz>
<yawx>0.0</yawx>
<yawy>-1.0</yawy>
<yawz>0.0</yawz>
<pitchx>1.0</pitchx>
<pitchy>0.0</pitchy>
<pitchz>0.0</pitchz>
<rollx>0.0</rollx>
<rolly>0.0</rolly>
<rollz>-1.0</rollz>
</coordinateFrame>
</region>
<region id="Right" xResolution="1920" yResolution="1080" x="0.0" y="0.0" xsize="1.0" ysize="1.0">
<frustum>
<yaw>90.000008</yaw>
<pitch>-0.000000</pitch>
<roll>-0.000000</roll>
<rightAngle>21.801409</rightAngle>
<leftAngle>-21.801409</leftAngle>
<upAngle>12.680382</upAngle>
<downAngle>-12.680382</downAngle>
</frustum>
<coordinateFrame>
<posx>-3.000000</posx>
<posy>0.500000</posy>
<posz>0.000000</posz>
<yawx>0.0</yawx>
<yawy>-1.0</yawy>
<yawz>0.0</yawz>
<pitchx>1.0</pitchx>
<pitchy>0.0</pitchy>
<pitchz>0.0</pitchz>
<rollx>0.0</rollx>
<rolly>0.0</rolly>
<rollz>-1.0</rollz>
</coordinateFrame>
</region>
<region id="Top" xResolution="1920" yResolution="1080" x="0.0" y="0.0" xsize="1.0" ysize="1.0">
<frustum>
<yaw>-180.000000</yaw>
<pitch>-90.000000</pitch>
<roll>-0.000000</roll>
<rightAngle>21.801409</rightAngle>
<leftAngle>-21.801409</leftAngle>
<upAngle>12.680382</upAngle>
<downAngle>-12.680382</downAngle>
</frustum>
<coordinateFrame>
<posx>0.000000</posx>
<posy>3.000000</posy>
<posz>0.000000</posz>
<yawx>0.0</yawx>
<yawy>-1.0</yawy>
<yawz>0.0</yawz>
<pitchx>1.0</pitchx>
<pitchy>0.0</pitchy>
<pitchz>0.0</pitchz>
<rollx>0.0</rollx>
<rolly>0.0</rolly>
<rollz>-1.0</rollz>
</coordinateFrame>
</region>
<region id="Bottom" xResolution="1920" yResolution="1080" x="0.0" y="0.0" xsize="1.0" ysize="1.0">
<frustum>
<yaw>-180.000000</yaw>
<pitch>90.000000</pitch>
<roll>-0.000000</roll>
<rightAngle>21.801409</rightAngle>
<leftAngle>-21.801409</leftAngle>
<upAngle>12.680382</upAngle>
<downAngle>-12.680382</downAngle>
</frustum>
<coordinateFrame>
<posx>0.000000</posx>
<posy>-3.000000</posy>
<posz>0.000000</posz>
<yawx>0.0</yawx>
<yawy>-1.0</yawy>
<yawz>0.0</yawz>
<pitchx>1.0</pitchx>
<pitchy>0.0</pitchy>
<pitchz>0.0</pitchz>
<rollx>0.0</rollx>
<rolly>0.0</rolly>
<rollz>-1.0</rollz>
</coordinateFrame>
</region>
</buffer>
</display>
</MPCDI>
|
MomentFactory/Omniverse-MPCDI-converter/exts/mf.ov.mpcdi_converter/config/extension.toml | [package]
version = "1.1.1"
title = "MF MPCDI converter"
description="Brings the support of MPCDI videoprojector files."
authors = ["Moment Factory","Antoine Pilote"]
readme = "docs/README.md"
changelog="docs/CHANGELOG.md"
repository = "https://github.com/MomentFactory/Omniverse-MPCDI-converter"
category = "Simulation"
keywords = ["videoprojector", "MPCDI", "audiovisual", "video", "projection", "videomapping"]
preview_image = "data/preview.png"
icon = "data/mf-ov-extensions-icons.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.mpcdi_converter"
[package.target]
kit = ["105.1"]
[package.writeTarget]
kit = true
python = false
|
MomentFactory/Omniverse-MPCDI-converter/exts/mf.ov.mpcdi_converter/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.1.1] - 2023-12-02
- Deprecated kit 104 and 105.0
- Monorepo for the USD fileformat plugin
- Procedure to build for USDView
## [1.1.0] - 2023-10-04
- Added native USD file format plugin for payload support.
## [1.0.0] - 2023-07-19
### Added
- Compatibility with USD Composer 2023.1.1
### Changed
- More explicit error message when failing to import
## [0.1.0] - 2023-03-30
### Added
- Initial version of Omniverse MPCDI extension
|
MomentFactory/Omniverse-MPCDI-converter/exts/mf.ov.mpcdi_converter/docs/README.md | # MPCDI converter for Omniverse [mf.ov.mpcdi_converter]
An Omniverse extension for MPDCI files.
Support MPCDI* to OpenUSD conversion as well as References to MPDCI files through a native USD FileFormat plugin.
MPCDI* is a VESA interchange format for videoprojectors technical data.
*Multiple Projection Common Data Interchange
MPCDIv2 is under Copyright © 2013 – 2015 Video Electronics Standards Association. All rights reserved.
|
MomentFactory/Omniverse-MPCDI-converter/PACKAGE-LICENSES/USD-LICENSE.md | Universal Scene Description (USD) components are licensed under the following terms:
Modified Apache 2.0 License
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor
and its affiliates, except as required to comply with Section 4(c) of
the License and to reproduce the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
============================================================
RapidJSON
============================================================
Tencent is pleased to support the open source community by making RapidJSON available.
Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License.
If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON. To avoid the problematic JSON license in your own projects, it's sufficient to exclude the bin/jsonchecker/ directory, as it's the only code under the JSON license.
A copy of the MIT License is included in this file.
Other dependencies and licenses:
Open Source Software Licensed Under the BSD License:
--------------------------------------------------------------------
The msinttypes r29
Copyright (c) 2006-2013 Alexander Chemeris
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Open Source Software Licensed Under the JSON License:
--------------------------------------------------------------------
json.org
Copyright (c) 2002 JSON.org
All Rights Reserved.
JSON_checker
Copyright (c) 2002 JSON.org
All Rights Reserved.
Terms of the JSON License:
---------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Terms of the MIT License:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
============================================================
pygilstate_check
============================================================
The MIT License (MIT)
Copyright (c) 2014, Pankaj Pandey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================
double-conversion
============================================================
Copyright 2006-2011, the V8 project authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
============================================================
OpenEXR/IlmBase/Half
============================================================
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
============================================================
Apple Technical Q&A QA1361 - Detecting the Debugger
https://developer.apple.com/library/content/qa/qa1361/_index.html
============================================================
Sample code project: Detecting the Debugger
Version: 1.0
Abstract: Shows how to determine if code is being run under the debugger.
IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
============================================================
LZ4
============================================================
LZ4 - Fast LZ compression algorithm
Copyright (C) 2011-2017, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 homepage : http://www.lz4.org
- LZ4 source repository : https://github.com/lz4/lz4
============================================================
stb
============================================================
stb_image - v2.19 - public domain image loader - http://nothings.org/stb
no warranty implied; use at your own risk
stb_image_resize - v0.95 - public domain image resizing
by Jorge L Rodriguez (@VinoBS) - 2014
http://github.com/nothings/stb
stb_image_write - v1.09 - public domain - http://nothings.org/stb/stb_image_write.h
writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015
no warranty implied; use at your own risk
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
MomentFactory/Omniverse-MPCDI-converter/resources/scene.usda | #usda 1.0
(
defaultPrim = "World"
metersPerUnit = 0.01
upAxis = "Y"
)
def Xform "World"
{
def Xform "MPCDI_Payload" (
payload = @../exts/mf.ov.mpcdi_converter/mf/ov/mpcdi_converter/sample/Cube-mapping.mpcdi.xml@
)
{
}
} |
MomentFactory/Omniverse-MVR-GDTF-converter/build.bat | :: 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.
@echo off
setlocal enabledelayedexpansion
pushd %~dp0
REM options defining what the script runs
set GENERATE=false
set BUILD=false
set CLEAN=false
set CONFIGURE=false
set STAGE=false
set HELP=false
set CONFIG=release
set HELP_EXIT_CODE=0
set DIRECTORIES_TO_CLEAN=_install _build _repo src\usd-plugins\schema\omniExampleSchema\generated src\usd-plugins\schema\omniExampleCodelessSchema\generated src\usd-plugins\schema\omniMetSchema\generated
REM default arguments for script - note this script does not actually perform
REM any build step so that you can integrate the generated code into your build
REM system - an option can be added here to run your build step (e.g. cmake)
REM on the generated files
:parseargs
if not "%1"=="" (
if "%1" == "--clean" (
set CLEAN=true
)
if "%1" == "--generate" (
set GENERATE=true
)
if "%1" == "--build" (
set BUILD=true
)
if "%1" == "--prep-ov-install" (
set STAGE=true
)
if "%1" == "--configure" (
set CONFIGURE=true
)
if "%1" == "--debug" (
set CONFIG=debug
)
if "%1" == "--help" (
set HELP=true
)
shift
goto :parseargs
)
if not "%CLEAN%" == "true" (
if not "%GENERATE%" == "true" (
if not "%BUILD%" == "true" (
if not "%STAGE%" == "true" (
if not "%CONFIGURE%" == "true" (
if not "%HELP%" == "true" (
REM default action when no arguments are passed is to do everything
set GENERATE=true
set BUILD=true
set STAGE=true
set CONFIGURE=true
)
)
)
)
)
)
REM requesting how to run the script
if "%HELP%" == "true" (
echo build.bat [--clean] [--generate] [--build] [--stage] [--configure] [--debug] [--help]
echo --clean: Removes the following directories ^(customize as needed^):
for %%a in (%DIRECTORIES_TO_CLEAN%) DO (
echo %%a
)
echo --generate: Perform code generation of schema libraries
echo --build: Perform compilation and installation of USD schema libraries
echo --prep-ov-install: Preps the kit-extension by copying it to the _install directory and stages the
echo built USD schema libraries in the appropriate sub-structure
echo --configure: Performs a configuration step after you have built and
echo staged the schema libraries to ensure the plugInfo.json has the right information
echo --debug: Performs the steps with a debug configuration instead of release
echo ^(default = release^)
echo --help: Display this help message
exit %HELP_EXIT_CODE%
)
REM should we clean the target directory?
if "%CLEAN%" == "true" (
for %%a in (%DIRECTORIES_TO_CLEAN%) DO (
if exist "%~dp0%%a/" (
rmdir /s /q "%~dp0%%a"
)
)
if !errorlevel! neq 0 (goto Error)
goto Success
)
REM should we generate the schema code?
if "%GENERATE%" == "true" (
REM pull down NVIDIA USD libraries
REM NOTE: If you have your own local build, you can comment out this step
call "%~dp0tools\packman\packman.cmd" pull deps/usd-deps.packman.xml -p windows-x86_64 -t config=%CONFIG%
if !errorlevel! neq 0 ( goto Error )
REM generate the schema code and plug-in information
REM NOTE: this will pull the NVIDIA repo_usd package to do this work
call "%~dp0tools\packman\python.bat" bootstrap.py usd --configuration %CONFIG%
if !errorlevel! neq 0 ( goto Error )
)
REM should we build the USD schema?
REM NOTE: Modify this build step if using a build system other than cmake (ie, premake)
if "%BUILD%" == "true" (
REM pull down target-deps to build dynamic payload which relies on CURL
call "%~dp0tools\packman\packman.cmd" pull deps/target-deps.packman.xml -p windows-x86_64 -t config=%CONFIG%
REM Below is an example of using CMake to build the generated files
REM You may also want to explicitly specify the toolset depending on which
REM version of Visual Studio you are using (e.g. -T v141)
REM NVIDIA USD 22.11 was built with the v142 toolset, so we set that here
REM Note that NVIDIA USD 20.08 was build with the v141 toolset
cmake -B ./_build/cmake -T v142
cmake --build ./_build/cmake --config=%CONFIG% --target install
)
REM is this a configure only? This will configure the plugInfo.json files
if "%CONFIGURE%" == "true" (
call "%~dp0tools\packman\python.bat" bootstrap.py usd --configure-pluginfo --configuration %CONFIG%
if !errorlevel! neq 0 (goto Error)
)
REM do we need to stage?
if "%STAGE%" == "true" (
REM Copy the kit-extension into the _install directory
REM we can do this directly because it's a python extension, so there's nothing to compile
REM but we want to combine it together with the output of the USD schema extension
REM Why not build the USD schema extension to the exact structure we are creating here?
REM Because we are illustrating that you can build the C++ schemas and distribute them
REM independent of anything kit related. All the copy is doing is putting everything in
REM one structure that can be referenced as a complete kit extension
REM this seems to be an example of how we can bring back all the python and other files from the ext folder to the _install folder.
REM commented but left here for reference
REM echo D | xcopy "%~dp0src\kit-extension\exts\omni.example.schema" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema" /s /Y
REM if not exist "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema" mkdir "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema"
REM echo F | xcopy "%~dp0_install\windows-x86_64\%CONFIG%\omniExampleSchema\OmniExampleSchema\*.*" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema" /Y
REM echo D | xcopy "%~dp0_install\windows-x86_64\%CONFIG%\omniExampleSchema\include" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema\include" /s /Y
REM echo D | xcopy "%~dp0_install\windows-x86_64\%CONFIG%\omniExampleSchema\lib" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema\lib" /s /Y
REM echo D | xcopy "%~dp0_install\windows-x86_64\%CONFIG%\omniExampleSchema\resources" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleSchema\resources" /s /Y
REM if not exist "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleCodelessSchema" mkdir "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleCodelessSchema"
REM echo D | xcopy "%~dp0_install\windows-x86_64\%CONFIG%\omniExampleCodelessSchema\resources" "%~dp0_install\windows-x86_64\%CONFIG%\omni.example.schema\OmniExampleCodelessSchema\resources" /s /Y
REM copy the files we need for a clean prepackaged extension ready for publishing
xcopy "%~dp0exts\mf.ov.gdtf\*" "%~dp0_install\windows-x86_64\%CONFIG%\mf.ov.gdtf" /E /I /H /Y
xcopy "%~dp0exts\mf.ov.mvr\*" "%~dp0_install\windows-x86_64\%CONFIG%\mf.ov.mvr" /E /I /H /Y
REM copy dlls
ren "%~dp0_install\windows-x86_64\%CONFIG%\mvrFileFormat" "plugin"
move "%~dp0_install\windows-x86_64\%CONFIG%\plugin" "%~dp0_install\windows-x86_64\%CONFIG%\mf.ov.mvr"
ren "%~dp0_install\windows-x86_64\%CONFIG%\gdtfFileFormat" "plugin"
move "%~dp0_install\windows-x86_64\%CONFIG%\plugin" "%~dp0_install\windows-x86_64\%CONFIG%\mf.ov.gdtf"
REM copy license files
xcopy "%~dp0LICENSE" "%~dp0_install\windows-x86_64\%CONFIG%\mf.ov.mvr\" /Y
xcopy "%~dp0LICENSE" "%~dp0_install\windows-x86_64\%CONFIG%\mf.ov.gdtf\" /Y
if !errorlevel! neq 0 ( goto Error )
)
:Success
exit /b 0
:Error
exit /b !errorlevel! |
MomentFactory/Omniverse-MVR-GDTF-converter/bootstrap.py | # 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.
import contextlib
import io
import packmanapi
import os
import sys
REPO_ROOT = os.path.dirname(os.path.realpath(__file__))
REPO_DEPS_FILE = os.path.join(REPO_ROOT, "deps", "repo-deps.packman.xml")
if __name__ == "__main__":
# pull all repo dependencies first
# and add them to the python path
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)
sys.path.append(REPO_ROOT)
import omni.repo.usd
omni.repo.usd.bootstrap(REPO_ROOT) |
MomentFactory/Omniverse-MVR-GDTF-converter/build.sh | # 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.
set -e
CWD="$( cd "$( dirname "$0" )" && pwd )"
# default config is release
CLEAN=false
BUILD=false
GENERATE=false
STAGE=false
CONFIGURE=false
HELP=false
CONFIG=release
HELP_EXIT_CODE=0
DIRECTORIES_TO_CLEAN=(
_install
_build
_repo
src/usd-plugins/schema/omniExampleCodelessSchema/generated
src/usd-plugins/schema/omniExampleSchema/generated
src/usd-plugins/schema/omniMetSchema/generated
)
while [ $# -gt 0 ]
do
if [[ "$1" == "--clean" ]]
then
CLEAN=true
fi
if [[ "$1" == "--generate" ]]
then
GENERATE=true
fi
if [[ "$1" == "--build" ]]
then
BUILD=true
fi
if [[ "$1" == "--prep-ov-install" ]]
then
STAGE=true
fi
if [[ "$1" == "--configure" ]]
then
CONFIGURE=true
fi
if [[ "$1" == "--debug" ]]
then
CONFIG=debug
fi
if [[ "$1" == "--help" ]]
then
HELP=true
fi
shift
done
if [[
"$CLEAN" != "true"
&& "$GENERATE" != "true"
&& "$BUILD" != "true"
&& "$STAGE" != "true"
&& "$CONFIGURE" != "true"
&& "$HELP" != "true"
]]
then
# default action when no arguments are passed is to do everything
GENERATE=true
BUILD=true
STAGE=true
CONFIGURE=true
fi
# requesting how to run the script
if [[ "$HELP" == "true" ]]
then
echo "build.sh [--clean] [--generate] [--build] [--stage] [--configure] [--debug] [--help]"
echo "--clean: Removes the following directories (customize as needed):"
for dir_to_clean in "${DIRECTORIES_TO_CLEAN[@]}" ; do
echo " $dir_to_clean"
done
echo "--generate: Perform code generation of schema libraries"
echo "--build: Perform compilation and installation of USD schema libraries"
echo "--prep-ov-install: Preps the kit-extension by copying it to the _install directory and stages the"
echo " built USD schema libraries in the appropriate sub-structure"
echo "--configure: Performs a configuration step after you have built and"
echo " staged the schema libraries to ensure the plugInfo.json has the right information"
echo "--debug: Performs the steps with a debug configuration instead of release"
echo " (default = release)"
echo "--help: Display this help message"
exit $HELP_EXIT_CODE
fi
# do we need to clean?
if [[ "$CLEAN" == "true" ]]
then
for dir_to_clean in "${DIRECTORIES_TO_CLEAN[@]}" ; do
rm -rf "$CWD/$dir_to_clean"
done
fi
# do we need to generate?
if [[ "$GENERATE" == "true" ]]
then
# pull down NVIDIA USD libraries
# NOTE: If you have your own local build, you can comment out this step
$CWD/tools/packman/packman pull deps/usd-deps.packman.xml -p linux-$(arch) -t config=$CONFIG
# generate the schema code and plug-in information
# NOTE: this will pull the NVIDIA repo_usd package to do this work
export CONFIG=$CONFIG
$CWD/tools/packman/python.sh bootstrap.py usd --configuration $CONFIG
fi
# do we need to build?
# NOTE: Modify this build step if using a build system other than cmake (ie, premake)
if [[ "$BUILD" == "true" ]]
then
# pull down target-deps to build dynamic payload which relies on CURL
$CWD/tools/packman/packman pull deps/target-deps.packman.xml -p linux-$(arch) -t config=$CONFIG
# Below is an example of using CMake to build the generated files
cmake -B ./_build/cmake -DCMAKE_BUILD_TYPE=$CONFIG
cmake --build ./_build/cmake --config $CONFIG --target install
fi
# do we need to configure? This will configure the plugInfo.json files
if [[ "$CONFIGURE" == "true" ]]
then
$CWD/tools/packman/python.sh bootstrap.py usd --configure-pluginfo --configuration $CONFIG
fi
# do we need to stage?
if [[ "$STAGE" == "true" ]]
then
mkdir -p $CWD/_install/linux-$(arch)/$CONFIG
cp -rf $CWD/src/kit-extension/exts/omni.example.schema $CWD/_install/linux-$(arch)/$CONFIG/
mkdir -p $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleSchema
mkdir -p $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleCodelessSchema
cp -rf $CWD/_install/linux-$(arch)/$CONFIG/omniExampleSchema/OmniExampleSchema/*.* $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleSchema/
cp -rf $CWD/_install/linux-$(arch)/$CONFIG/omniExampleSchema/include $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleSchema/
cp -rf $CWD/_install/linux-$(arch)/$CONFIG/omniExampleSchema/lib $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleSchema/
cp -rf $CWD/_install/linux-$(arch)/$CONFIG/omniExampleSchema/resources $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleSchema/
cp -rf $CWD/_install/linux-$(arch)/$CONFIG/omniExampleCodelessSchema/* $CWD/_install/linux-$(arch)/$CONFIG/omni.example.schema/OmniExampleCodelessSchema/
fi |
MomentFactory/Omniverse-MVR-GDTF-converter/repo.toml | # common settings for repo_usd for all USD plug-ins
[repo_usd]
usd_root = "${root}/_build/usd-deps/nv-usd/%{config}"
usd_python_root = "${root}/_build/usd-deps/python"
generate_plugin_buildfiles = true
plugin_buildfile_format = "cmake"
generate_root_buildfile = true
[repo_usd.plugin.gdtfFileFormat]
plugin_dir = "${root}/src/usd-plugins/fileFormat/gdtfFileFormat"
install_root = "${root}/_install/%{platform}/%{config}/gdtfFileFormat"
include_dir = "include/gdtfFileFormat"
additional_include_dirs = [
"../../../../_build/usd-deps/nv_usd/%{config}/include/tbb",
"${root}/src/usd-plugins/fileFormat/mvrFileFormat/assimp/include"
]
public_headers = [
"api.h"
]
private_headers = [
"gdtfFileFormat.h",
"gdtfUsdConverter.h",
"../mvrFileFormat/gdtfParser/GdtfParser.h",
"tinyxml2.h"
]
preprocessor_defines = [
"GDTF_FILEFORMAT"
]
cpp_files = [
"gdtfFileFormat.cpp",
"gdtfUsdConverter.cpp",
"../mvrFileFormat/gdtfParser/GdtfParser.cpp",
"tinyxml2.cpp"
]
resource_files = [
"plugInfo.json"
]
additional_library_dirs = [
"${root}/src/usd-plugins/fileFormat/mvrFileFormat"
]
additional_static_libs = [
"assimp",
"zlibstatic"
]
usd_lib_dependencies = [
"arch",
"tf",
"plug",
"vt",
"gf",
"sdf",
"js",
"pcp",
"usdGeom",
"usd",
"usdLux"
]
[repo_usd.plugin.mvrFileFormat]
plugin_dir = "${root}/src/usd-plugins/fileFormat/mvrFileFormat"
install_root = "${root}/_install/%{platform}/%{config}/mvrFileFormat"
include_dir = "include/mvrFileFormat"
additional_include_dirs = [
"../../../../_build/usd-deps/nv_usd/%{config}/include/tbb",
"${root}/src/usd-plugins/fileFormat/mvrFileFormat/assimp/include"
]
public_headers = [
"api.h"
]
private_headers = [
"mvrFileFormat.h",
"mvrParser/tinyxml2.h",
"mvrParser/Fixture.h",
"mvrParser/FixtureFactory.h",
"mvrParser/LayerFactory.h",
"mvrParser/MVRParser.h",
"gdtfParser/GdtfParser.h",
"gdtfParser/ModelSpecification.h",
"gdtfParser/Device.h",
"../gdtfFileFormat/gdtfUsdConverter.h"
]
cpp_files = [
"mvrFileFormat.cpp",
"mvrParser/Fixture.cpp",
"mvrParser/FixtureFactory.cpp",
"mvrParser/LayerFactory.cpp",
"mvrParser/MVRParser.cpp",
"mvrParser/tinyxml2.cpp",
"gdtfParser/GdtfParser.cpp",
"../gdtfFileFormat/gdtfUsdConverter.cpp"
]
resource_files = [
"plugInfo.json"
]
additional_library_dirs = [
"${root}/src/usd-plugins/fileFormat/mvrFileFormat"
]
additional_static_libs = [
"assimp",
"zlibstatic"
]
usd_lib_dependencies = [
"arch",
"tf",
"plug",
"vt",
"gf",
"sdf",
"js",
"pcp",
"usdGeom",
"usd",
"usdLux"
]
|
MomentFactory/Omniverse-MVR-GDTF-converter/README.md | # MF.OV.MVR and MF.OV.GDTF
Brings support of MVR and GDTF files to Omniverse and USD.
This repository contains two different extensions.
GDTF (General Device Type Format) defines an asset format that collects technical information about Audiovisual devices. It is currently centered on lighting fixtures and provide accurate digital twins of lighting devices from 100+ manufacturers.
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.
This repository contains two separate extensions :
- [MVR extension](./exts/mf.ov.mvr/)
- [GDTF extension](./exts/mf.ov.gdtf/)
# Requirements
- Requires Omniverse Kit >= 105
- Tested in USD Composer 2023.2.2 and 2023.2.0
# Build
## Build for Omniverse
- Just run `build.bat`
- Once the build is complete, the FileFormat dlls should be located under : `_install/windows-x86_64/release`
## Build for USDView
The dependency configuration is contained in the [usd-deps.packman.xml](deps/usd-deps.packman.xml) file
To switch to the correct OpenUSD version for USDview compilation, it may be required to edit the packman configuration file to :
```
<project toolsVersion="5.6">
<dependency name="nv-usd" linkPath="../_build/usd-deps/nv-usd/${config}">
<package name="usd.py310.${platform}.usdview.${config}" version="0.23.05-tc.47+v23.05.b53573ea" />
</dependency>
<dependency name="python" linkPath="../_build/usd-deps/python">
<package name="python" version="3.10.13+nv1-${platform}" />
</dependency>
</project>
```
`source setenvwindows`
Test with `usdview resources/scene.usda`
Note : light meshes will not show up unless you have a GLTF FileFormat plugin enabled.
## Alternate builds
At the bottom of this Readme, you will find alternative ways of building for Unreal 5.3 and Blender 4.0.
# Using the extension
To enable the extensions in USD Composer:
- `Window` > `Extensions`
- Search for `MF GDTF Converter` or `MF MVR Converter` in commuunity and enable them with the "autoload" checkbox.
- Restart USD composer.
## Sample files
MVR samples :
- [7-fixtures-samples.mvr](./exts/mf.ov.mvr/sample/7-fixtures-sample.mvr/)
- [fixture-line-gltf.mvr](./exts/mf.ov.mvr/sample/fixture-line-gltf.mvr/)
GDTF sample
- [Robin_MMX_Blade](./exts/mf.ov.gdtf/sample/Robe_Lighting@Robin_MMX_Blade@2023-07-25__Beam_revision.gdtf)
Thousands of GDTF files are available on [GDTF-share](https://gdtf-share.com/).
For example the very last version of the GDTF sample file we provide can be downloaded from [here](https://gdtf-share.com/share.php?page=home&manu.=Robe%20Lighting&fix=Robin%20MMX%20Blade)
## Reference MVR/GDTF files
To reference an MVR or a GDTF file, just drag and drop the file on your viewport or your Stage Window.
## Convert MVR/GDTF files
Note: to properly work with MVR files, both extension have to be enabled.
1. In the content tab, browse to the folder where you want to import your `MVR` or `GDTF` files.
2. Click the `+Import` button and select "External Assets (FBX, OBJ...)
3. Choose a `MVR` or `GDTF` file and wait for it to import.
- MVR import
- The import result will be stored in a folder with the same name as the imported file in the current content browser directory.
- If `GDTF` files are referenced, they will be converted to `USD` in a subfolder.
- GDTF import
- The import result will be stored in a folder with the same name as the imported file in the current content browser directory.
4. To finalize the import, drag the freshly converted `USD` file in your project or open it.
# Implementation notes
## `MVR.USD` USD schema
Note : not every aspect of the MVR specification is currently implemented for USD, as we focused on the ability to retrieve the lighting fixture information.
1. Under the Root, you'll find `Scope` representing the different `Layers` of the MVR scene.
2. Inside them you'll find each GDTF Fixture represented by an `Xform` pointing to an USD payload.
3. `Xform` are named using their names and their uuid to ensure unique naming.
4. `Xform` also have custom properties (see Raw USD Properties) using the following convention: `mf:mvr:property`.
```
Root/
└─📁MVR-Layer1 (Scope)
| ├─💠Make_Model_UID1 (Xform with payload)
| └─💠Make_Model_UID2 (Xform with payload)
└──📁MVR-Layer1 (Scope)
└─💠Make_Model_UID1 (Xform with payload)
└─💠Make_Model_UID2 (Xform with payload)
```
## MVR Raw USD Properties
When importing an MVR files, some properties specific to MVR and not compatible with USD will be imported as raw USD properties of an Xform holding a lighting fixture :
| Property | Type | Description |
|--- |--- |--- |
|`mf:mvr:name` |[🔗String](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#generic-value-types) | The name of the object. |
|`mf:mvr:uuid` |[🔗UUID](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#generic-value-types) | The unique identifier of the object. |
|`mf:mvr:Classing` |[🔗UUID](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#generic-value-types) | The class the object belongs to |
|`mf:mvr:GDTFMode` |[🔗String](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#generic-value-types) | The name of the used DMX mode. This has to match the name of a DMXMode in the GDTF file.|
|`mf:mvr:GDTFSpec` |[🔗FileName](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#generic-value-types) | The name of the file containing the GDTF information for this light fixture. |
|`mf:mvr:CastShadow` |[🔗Bool](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#generic-value-types) | Wether the fixture casts shadows or not. |
|`mf:mvr:UnitNumber` |[🔗Integer](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#generic-value-types) |The unit number of the lighting fixture in a position. |
|`mf:mvr:Addresses` |[🔗Adresses](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#node-definition-addresses)| the DMX address of the fixture. |
|`mf:mvr:CustomCommands` |[🔗CustomCommands](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#node-definition-customcommands)| Custom commands that should be executed on the fixture |
|`mf:mvr:CIEColor` |[🔗CIE Color](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#user-content-attrtype-ciecolor)| A color assigned to a fixture. If it is not defined, there is no color for the fixture.|
|`mf:mvr:FixtureTypeId` |[🔗Integer](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#generic-value-types) | The Fixture Type ID is a value that can be used as a short name of the Fixture Type. |
|`mf:mvr:CustomId` |[🔗Integer](https://github.com/mvrdevelopment/spec/blob/main/mvr-spec.md#generic-value-types) |The Custom ID is a value that can be used as a short name of the Fixture Instance. |
Example

## `GDTF.USD` USD Schema
GDTF can have multiple structure type, but here is a typical example for a moving light.
```
Root/
└─💠 Base (Xform)
├─💠model (Xform)
│ └─🧊 mesh (Mesh)
├─💠Yoke (Xform)
│ ├─💠model (Xform)
│ │ └─🧊 mesh (Mesh)
| └──💠Head (Xform)
│ └─💠model (Xform)
│ └─🧊 mesh (Mesh)
└─📁Looks (Scope)
```
## GDTF Raw USD Properties
### Properties affecting the USD Prims properties
| Property | Type | Description
|--- |--- |---
|`mf:gdtf:BeamAngle` |[🔗Float](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types)| Will affect the USD Light's `Cone Angle`.
|`mf:gdtf:ColorTemperature` |[🔗Float](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types)| Color temperature; Unit: kelvin. Will affec USD Light's `Color Temperature`.
|`mf:gdtf:LuminousFlux` |[🔗Float](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types)| Intensity of all the represented light emitters; Unit: lumen. Will affec USD Light's `intensity`
### Fixture
| Property | Type | Description
|--- |--- |---
|`mf:gdtf:OperatingTemperature:High`|[🔗Float](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types) | Lowest temperature the device can be operated. Unit: °C.
|`mf:gdtf:OperatingTemperature:Low` |[🔗Float](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types) | Highest temperature the device can be operated. Unit: °C.
|`mf:gdtf:Weight` |[🔗Float](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types) | Weight of the device including all accessories. Unit: kilogram.
|`mf:gdtf:LegHeight` |[🔗Float](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types) | Defines height of the legs - distance between the floor and the bottom base plate. Unit: meter.
### Beam (Light)
| Property | Type | Description
|--- |--- |---
|`mf:gdtf:BeamType` |[🔗Enum](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types) | Beam Type; Specified values: "Wash", "Spot", "None", "Rectangle", "PC", "Fresnel", "Glow".
|`mf:gdtf:ColorRenderingIndex`|[🔗Uint](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types) | The CRI according to TM-30 is a quantitative measure of the ability of the light source showing the object color naturally as it does as daylight reference.
|`mf:gdtf:FieldAngle` |[🔗Float](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types)| Field angle; Unit: degree.
|`mf:gdtf:LampType` |[🔗Enum](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types) | Defines type of the light source; The currently defined types are: Discharge, Tungsten, Halogen, LED.
|`mf:gdtf:PowerConsumption` |[🔗Float](https://github.com/mvrdevelopment/spec/blob/main/gdtf-spec.md#table-1--xml-attribute-value-types)| ower consumption; Unit: Watt.
### XML Notes
Example of a fixture defined in a MVR file (contains some, but not all properties):
```xml
<Fixture name="Sharpy" uuid="C63B1F8D-6DAD-438C-9228-E33C6EF2947E">
<Matrix>{-1.000000,0.000000,0.000000}{0.000000,-1.000000,-0.000000}{0.000000,0.000000,1.000000}{-766.333333,4572.000000,7620.000000}</Matrix>
<GDTFSpec>Clay Paky@Sharpy [Bulb=MSD Platinum 5R 189W].gdtf</GDTFSpec>
<GDTFMode>Vect</GDTFMode>
<Addresses>
<Address break="0">21</Address>
</Addresses>
<FixtureID>102</FixtureID>
<UnitNumber>0</UnitNumber>
<FixtureTypeId>0</FixtureTypeId>
<CustomId>0</CustomId>
<Color>0.312712,0.329008,100.000000</Color>
<CastShadow>false</CastShadow>
<Mappings/>
</Fixture>
```
Some notes on the properties:
- Matrix is in millimeters (applies to the last part, the translation).
- Color is in [CIE 1931 color space](https://en.wikipedia.org/wiki/CIE_1931_color_space) and represent the color of a color gel or similar apparatus and not of the fixture itself.
# Alternate builds
## Build for Unreal 5.3
Unreal 5.3 uses USD 23.02
Use the following dependency
```
<dependency name="nv-usd" linkPath="../_build/usd-deps/nv-usd/${config}">
<package name="usd.py310.${platform}.usdview.${config}" version="0.23.02-tc.1+pxr-23.02-build-patch.9ed269df" />
</dependency>
```
- In your Unreal project, enable the USD Importer plugin
- Create a subfolder in your Unreal Project ex : `MyProject/Content/USDPlugins`
- Copy the plugInfo.json and the mvrFileFormat.dll at the root of this folder
- Adapt the plugInfo.json :
- `"LibraryPath": "mvrFileFormat.dll"`
- `"ResourcePath": "."`,
- `"Root": "."`
- Add the `MyProject/Content/USDPlugins` in Edit > Project Settings > USDImporter > Additional Plugin Directories
Note.
Unreal is gonna complain about missing dll.
Dirty fix is to add the following dll (take the one from packman) into the `...UE_5.3\Engine\Binaries\Win64`
- `boost_python310-vc142-mt-x64-1_78.dll`
- `python310.dll`
## Build for Blender 3.6.x or 4.0
Waiting for a cleaner way to provide build support for Blender, here is a step by step.
Use the following dependency.
```
<dependency name="blender_usd" linkPath="../_build/usd-deps/nv-usd">
<package name="blender_usd" version="63380-py310-usd23.05-windows-x86_64"/>
</dependency>
```
In the `repo.toml`
Modify the USD dependencies.
```
usd_lib_dependencies = [
"ms"
]
```
Remove `%{config}` after `usd_root`
```
usd_root = "${root}/_build/usd-deps/nv-usd"
```
Copy the Plugin folder : `omniverse-mvr-extension/_install/windows-x86_64/release/mvrFileFormat`
into your Blender Plugin folder `BLENDER_ROOT/blender.shared/usd`
# Resources
- Inspired by : [NVIDIA's usd-plugin-sample](https://github.com/NVIDIA-Omniverse/usd-plugin-samples/)
- [MVR and GDTF homepage with Fixture Library](https://gdtf-share.com/)
- [Specifications Github repostory](https://github.com/mvrdevelopment/spec)
- [Gdtf.eu](https://gdtf.eu/docs/list-of-projects/)
# Known limitation
- GDTF files using 3ds model are supported but will require python 3.10 cli installed on the host computer.
- Some MVR or GDTF files might fail to convert due to invalid or incomplete files.
- Only lighting devices are supported, prefer for importing mvr file not contaning trusses for instance. It could lead to strange behaviors and crashes. |
MomentFactory/Omniverse-MVR-GDTF-converter/setenvwindows.bat | :: Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
::
:: NVIDIA CORPORATION and its licensors retain all intellectual property
:: and proprietary rights in and to this software, related documentation
:: and any modifications thereto. Any use, reproduction, disclosure or
:: distribution of this software and related documentation without an express
:: license agreement from NVIDIA CORPORATION is strictly prohibited.
@echo off
set CONFIG=release
:parseargs
if not "%1" == "" (
if "%1" == "debug" (
set CONFIG=debug
)
shift
goto parseargs
)
echo Setting environment for %CONFIG% configuration...
if not exist %~dp0_venv (
%~dp0_build\usd-deps\python\python.exe -m venv %~dp0_venv
call "%~dp0_venv\Scripts\activate.bat"
pip install PySide2
pip install PyOpenGL
pip install warp-lang
) else (
call "%~dp0_venv\Scripts\activate.bat"
)
set PYTHONPATH=%~dp0_build\usd-deps\nv-usd\%CONFIG%\lib\python;%~dp0_build\target-deps\omni-geospatial;%~dp0_install\windows-x86_64\%CONFIG%\omniWarpSceneIndex
set PATH=%PATH%;%~dp0_build\usd-deps\python;%~dp0_build\usd-deps\nv-usd\%CONFIG%\bin;%~dp0_build\usd-deps\nv-usd\%CONFIG%\lib;%~dp0_build\target-deps\zlib\lib\rt_dynamic\release;%~dp0_install\windows-x86_64\%CONFIG%\mvrFileFormat\lib;%~dp0_install\windows-x86_64\%CONFIG%\omniMetProvider\lib;%~dp0_build\target-deps\omni-geospatial\bin;$~dp0_install\windows-x86_64\$CONFIG\omniWarpSceneIndex\lib
set PXR_PLUGINPATH_NAME=%~dp0_install\windows-x86_64\%CONFIG%\omniMetSchema\resources;%~dp0_install\windows-x86_64\%CONFIG%\mvrFileFormat\resources;%~dp0_install\windows-x86_64\%CONFIG%\omniMetProvider\resources;%~dp0_build\target-deps\omni-geospatial\plugins\OmniGeospatial\resources;%~dp0_install\windows-x86_64\%CONFIG%\omniGeoSceneIndex\resources;%~dp0_install\windows-x86_64\%CONFIG%\omniMetricsAssembler\resources;%~dp0_install\windows-x86_64\%CONFIG%\omniWarpSceneIndex\resources
set USDIMAGINGGL_ENGINE_ENABLE_SCENE_INDEX=true |
MomentFactory/Omniverse-MVR-GDTF-converter/deps/target-deps.packman.xml | <project toolsVersion="5.6">
<dependency name="libcurl" linkPath="../_build/target-deps/libcurl">
<package name="libcurl" version="8.1.2-3-${platform}-static-release"/>
</dependency>
<dependency name="zlib" linkPath="../_build/target-deps/zlib">
<package name="zlib" version="1.2.13+nv1-${platform}" />
</dependency>
<dependency name="openssl" linkPath="../_build/target-deps/openssl">
<package name="openssl" version="3.0.10-3-${platform}-static-release" />
</dependency>
<dependency name="omni-geospatial" linkPath="../_build/target-deps/omni-geospatial">
<package name="omni-geospatial" version="2.0.3-pxr_23_05+mr17.384.337fb43b.tc.${platform}.${config}" />
</dependency>
</project> |
MomentFactory/Omniverse-MVR-GDTF-converter/deps/usd-deps.packman - Copy.xml | <project toolsVersion="5.6">
<dependency name="nv-usd" linkPath="../_build/usd-deps/nv-usd/${config}">
<package name="nv-usd" version="22.11.nv.0.2.1071.7d2f59ad-win64_py310_${config}-dev_omniverse" platforms="windows-x86_64" />
<package name="nv-usd" version="22.11.nv.0.2.1071.7d2f59ad-linux64_py310-centos_${config}-dev_omniverse" platforms="linux-x86_64" />
<package name="nv-usd" version="22.11.nv.0.2.1071.7d2f59ad-linux-aarch64_py310_${config}-dev_omniverse" platforms="linux-aarch64" />
</dependency>
<dependency name="python" linkPath="../_build/usd-deps/python">
<package name="python" version="3.10.10+nv1-${platform}" />
</dependency>
</project> |
MomentFactory/Omniverse-MVR-GDTF-converter/deps/repo-deps.packman.xml | <project toolsVersion="5.6">
<dependency name="repo_usd" linkPath="../_repo/repo_usd">
<package name="repo_usd" version="4.0.1" />
</dependency>
</project> |
MomentFactory/Omniverse-MVR-GDTF-converter/deps/usd-deps.packman.xml | <project toolsVersion="5.6">
<dependency name="nv-usd" linkPath="../_build/usd-deps/nv-usd/${config}">
<package name="nv-usd" version="22.11.nv.0.2.1071.7d2f59ad-win64_py310_${config}-dev_omniverse" platforms="windows-x86_64" />
<package name="nv-usd" version="22.11.nv.0.2.1071.7d2f59ad-linux64_py310-centos_${config}-dev_omniverse" platforms="linux-x86_64" />
<package name="nv-usd" version="22.11.nv.0.2.1071.7d2f59ad-linux-aarch64_py310_${config}-dev_omniverse" platforms="linux-aarch64" />
</dependency>
<dependency name="python" linkPath="../_build/usd-deps/python">
<package name="python" version="3.10.10+nv1-${platform}" />
</dependency>
</project> |
MomentFactory/Omniverse-MVR-GDTF-converter/PACKAGE-LICENSE/GDTF-MVR.md | DIN SPEC 15800 General Device Type Format (GDTF) and My Virtual Rig (MVR) File Format description
The General Device Type Format (GDTF) creates a unified data exchange definition for the operation of intelligent luminaires, such as moving lights. By creating a manufacturer-supported, unified standard, customers/users of lighting control systems, CAD systems, and pre-visualizers benefit by knowing the tools they use to perform their job will work consistently and dependably. The file format is developed using open source formats, and luminaire manufacturers in the entertainment design, production, and performance industries are welcome to use this open source technology.
The GDTF file format is standardized in [DIN SPEC 15800:2022-02](https://www.beuth.de/en/technical-rule/din-spec-15800/349717520). |
MomentFactory/Omniverse-MVR-GDTF-converter/PACKAGE-LICENSE/USD-LICENSE.md | Universal Scene Description (USD) components are licensed under the following terms:
Modified Apache 2.0 License
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor
and its affiliates, except as required to comply with Section 4(c) of
the License and to reproduce the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
============================================================
RapidJSON
============================================================
Tencent is pleased to support the open source community by making RapidJSON available.
Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License.
If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON. To avoid the problematic JSON license in your own projects, it's sufficient to exclude the bin/jsonchecker/ directory, as it's the only code under the JSON license.
A copy of the MIT License is included in this file.
Other dependencies and licenses:
Open Source Software Licensed Under the BSD License:
--------------------------------------------------------------------
The msinttypes r29
Copyright (c) 2006-2013 Alexander Chemeris
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Open Source Software Licensed Under the JSON License:
--------------------------------------------------------------------
json.org
Copyright (c) 2002 JSON.org
All Rights Reserved.
JSON_checker
Copyright (c) 2002 JSON.org
All Rights Reserved.
Terms of the JSON License:
---------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Terms of the MIT License:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
============================================================
pygilstate_check
============================================================
The MIT License (MIT)
Copyright (c) 2014, Pankaj Pandey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================
double-conversion
============================================================
Copyright 2006-2011, the V8 project authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
============================================================
OpenEXR/IlmBase/Half
============================================================
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
============================================================
Apple Technical Q&A QA1361 - Detecting the Debugger
https://developer.apple.com/library/content/qa/qa1361/_index.html
============================================================
Sample code project: Detecting the Debugger
Version: 1.0
Abstract: Shows how to determine if code is being run under the debugger.
IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
============================================================
LZ4
============================================================
LZ4 - Fast LZ compression algorithm
Copyright (C) 2011-2017, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 homepage : http://www.lz4.org
- LZ4 source repository : https://github.com/lz4/lz4
============================================================
stb
============================================================
stb_image - v2.19 - public domain image loader - http://nothings.org/stb
no warranty implied; use at your own risk
stb_image_resize - v0.95 - public domain image resizing
by Jorge L Rodriguez (@VinoBS) - 2014
http://github.com/nothings/stb
stb_image_write - v1.09 - public domain - http://nothings.org/stb/stb_image_write.h
writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015
no warranty implied; use at your own risk
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/README.md | # Schemas, File Format Plugins, and Dynamic Payloads
## USD Schemas
Recall that USD defines the concept of a "prim". Prims abstractly serve as data containers for groups of logically related data. These groups are referred to as _schemas_ (or more specificaly, _prim schemas_ to distinguish them from _property schemas_). When we say that a prim has a type of _Mesh_, what we really mean is that the prim provides the logical set of related data defined by the `UsdGeomMesh` schema (e.g., vertices, faces, normals, etc.).
Schemas are divided into two major categories _IsA_ schemas and _API_ schemas. _IsA_ schemas are meant to define a specific purpose for a prim. In the case above, a _Mesh_ prim is a prim who's specific purpose is to represent a mesh. A prim can only subscribe to a single _IsA_ schema - that is, it has a single well defined role in the scene hierarchy. These types of schemas can be inherited and within that inheritance hierarchy schemas can be either _abstract_ or _concrete_. Only concrete schemas are instantiable in the USD scene hierarchy.
_API Schemas_, on the other hand, serve only as additional data groups on prims as well as a well-defined API to get and set those values. These schema types can be applied to any prim in the scene hierarchy (as long as the schema rules say it can be applied to that prim type). If a prim has a type, you will see that type in the scene hierarchy. If a prim has an API schema applied, you won't see a difference in its type, but will still be able to ask that prim for the data contained within that schema. These types of schemas can be either _non-applied_ or _applied_ API schemas, with the difference being that applied API schemes will be recorded in the USD file such that they retain that information on interchange of the scene data to other applications. If a schema is an applied API schema, it can be either single instance (_single-apply_ API schemas, applied only once to a prim) or multi-instance (_multiple-apply_ API schemas, can be applied several times, each defining a unique instance).
USD ships with many schema definitions that you may be familiar with, including "IsA" schemas (e.g., `Mesh`, `Xform`) and "API" schemas (e.g., `UsdShadeMaterialBindingAPI`, `UsdCollectionAPI`, etc.). These can all be found in their respective modules (e.g., the schema set provided by `UsdGeom` can be found in pxr/usd/usdGeom/schema.usda).
More information on schemas can be found here: https://graphics.pixar.com/usd/release/tut_generating_new_schema.html
### Creating new Schema Extensions and Naming Conventions
Schema extensions are created by defining the schema using USD syntax, typically in a file called `schema.usda`. Before defining your schema classes, you must determine the name of your schema library. Since the entire USD community can add schema extensions, it is important to be able to recognize from which organization / application a schema extension originates and to name them uniquely enough such that naming collisions do not occur across applications. For example, across the NVIDIA organization, we want that our schema extensions are easily recognizeable by the community so it is clear what Omniverse will support and what 3rd party applications may not have support for. In general, you can expect the following:
- `Omni` is the prefix used for NVIDIA's schema extensions. If `Omni` is not appropriate, other prefixes may be used as long as they are distinct enough to recognize that they came from NVIDIA (e.g., `PhysX`).
- All applied API schemas will end with the `API` suffix (as well as adhering to the prefix rule above)
- All properties added by an API schema will start with a recognizeable namespacing prefix (e.g., `omni`) and be namespaced appropriately (e.g., `omni:graph:attrname`, etc.)
- Properties within an IsA schema may have namespace prefixes if derived from core USD schema types.
The samples provide examples for two types of schemas, codeful and codeless. The former will have C++ / Python code generated for it, the latter will only have USD plug-in information generated. These are provided in the `src/usd-plugins/schema/omniExampleSchema` and `src/usd-plugins/schema/omniExampleCodelessSchema` in their respective `schema.usda` files.
Additionally, there are several schemas used throughout the other samples that are also included here (e.g., `src/usd-plugins/schema/omniMetSchema`, `src/hydra-plugins/omniWarpSceneIndex`).
## File Format Plugins
A _file format plugin_ is the type of USD plugin that is responsible for dynamically translating the contents of a foreign format into `SdfPrimSpec` compatible data. While files are common, the source data does not have to reside strictly in a file.

Two objects are provided in the `Sdf` library for implementing file format plugins, `SdfFileFormat` and `SdfAbstractData`. The former is a base class for defining a new type of file format and the interface used to read / write that format by the USD runtime and the latter is a data adapter that can be used to customize how the data that was read is stored / cached / accessed. All file format plugins implement `SdfFileFormat`. File format plugins that need more granular management of the data cache also implement `SdfAbstractData` although this is not necessary - if you do not provide a custom data object the USD runtime will use `SdfData` as the data object associated with the content from your file format for a layer.
From a USD runtime perspective, file format plugins involve the following objects:

When a stage is opened, the root layer is opened and prim specs are formed for all prims. Each of these are indexed by the composition engine and the index notes if there are additional composition arcs for a prim (e.g., via a reference or payload). These arcs are resolved by opening the referenced layer. If the layer is an asset reference to a foreign file format, `Sdf` will look for a plugin responsible for that format and ask an instance of that plugin to load the asset. This is done by the layer (`SdfLayer`) asking the `Sdf_FileFormatRegistry` to find a plugin associated with a particular extension, which if accessed for the first time triggers an acquisition of all plugins drived from `SdfFileFormat` held by `PlugRegistry` and the loading of the one responsible for the particular extension. Once found, `SdfLayer` will initialize a `SdfAbstractData` object to associate with the file format (either a custom one provided by the file format or `SdfData` if there is no custom data object) and ask the plugin to read the information into the layer. For each prim read in the layer, the composition engine will index those prims and recursively resolve any additional composition arcs required to build the full prim index.
File format plugins may also write out content in their native format. By default, custom file format plugins do not write content and it is up to the implementor to indicate that they support writes and to write the content out appropriately.
Interestingly, file format plugins do not actually have to read from files - they can read from any backing data store as long as they know what data to read and how to interpret it. From the point of view of the USD runtime, the only requirements are the interface to reading / writing the data and the association of the plugin type to a file extension (which can be made up for non-file types).
This repository provides a sample file format plugin that is used to implement dynamic payload functionality in the `src/fileFormat/edfFileFormat` directory. The information is read from REST APIs associated with the Metropolitan Museum of Art to illustrate the data need not come from a file at all. An empty file (`resources/empty.edf`) is provided such that the payload reference can be added to the stage using an existing asset, but the content is not used at all. We could eliminate the file entirely by referencing an anonymous layer with the `.edf` extension.
Other examples of more traditional file format plugins exist directly in the USD repository; for example, the Alembic (`abc`) file format plugin resides here:
- https://github.com/PixarAnimationStudios/USD/blob/release/pxr/usd/plugin/usdAbc/alembicFileFormat.h
## Dynamic Payloads
_Dynamic payloads_ are file format plugins with additional functionality (that can only be used with the payload composition arc) to make them a bit more dynamic in nature. These dynamics are provided via a set of parameters in the metadata of the prim that has the payload composition arc to a dynamic payload. This is a powerful mechanism because:
- The information brought into the layer can be parameterized in ways specific to the data the payload is resposible for
- Those parameters can be modified by tools that allow metadata modification to reload the layer with the new parameter set
- Metadata participates in composition, so the composition engine can form the strongest opinions of the custom prim metadata and use that opinion to compute additional file format arguments that will be added to the asset path (and sent to the file format plugin)
From a USD runtime perspective, dynamic payloads involve the following objects (additionally to those already shown for file format plugins)

To implement a dynamic payload, your file format plugin must provide additional functionality for the USD runtime:
- Must inherit `PcpDynamicFileFormatInterface` in addition to `SdfFileFormat`
- Must be able to compose a set of `FileFormatArguments` from the contents of metadata read from the prim associated with the paylaod
The metadata used must be declared in the `plugInfo.json` file such that `Sdf` knows about it. It is up to you to determine what format this metadata takes and there is often a balance between generality (for extensiblity) vs. clarity (knowing what exactly can be parameterized).
The `PcpDynamicFileFormatInterface` provides two important methods that need to be implemented:
- `ComposeFieldsForFileFormatArguments`: This method takes a composition context to acquire the composed metadata and translate this information into a set of `FileFormatArguments` that will be provided to the layer when opening the layer (and eventually, to the `SdfFileFormat` object as arguments to the `Read` invocation)
- `CanFieldChangeAffectFileFormatArguments`: This method allows the file format plugin to inform the composition engine what metadata value changes would contribute to the construction of new file format arguments (and hence, a reload of the layer)
Depending on how the implementation translates the metadata into `FileFormatArguments`, it is possible that there is a 1:1, 1:N, or N:1 mapping of metadata values to `FileFormatArguments` values. It is up to the implementation to understand whether changes to a particular metadata value would contribute to a recomputation of a `FileFormatArguments` value. If a change does contribute and new `FileFormatArguments` are generated, the composition engine will trigger a reload of that layer using the new `FileFormatArguments`. Since the arguments contribute to the layer identifier, this would be considered a new layer from the point of view of the USD runtime.
This repository provides an example of a dynamic payload between two plugins:
- The `EdfFileFormat` object provided in `src/usd-plugins/fileFormat/edfFileFormat`
- The `OmniMetProvider` object provided in `src/usd-plugins/dynamicPayload/omniMetProvider`
This was structured in this way for two reasons:
- To illustrate that one file format could architecturally handle multiple back-ends generically by using its own plugin mechanism for loading back-end providers identified via a type on the metadata
- To illustrate an example of an object that manages its own types of plugins
Architecturally, this breaks down as follows:

Note that the implementation for data provider plugins is modeled exactly after the generic USD plugin architecture. This pattern allows you to create and manage your own plugins in the same way USD does. In this case, the file format plugin architecture manages the `EdfFileFormat` plugin itself, and the `EdFFileFormat` takes care of loading whatever provider is specified via the metadata attached to the prim. In theory, this allows different dynamic payloads on different prims to use different data providers to source data, but uses the same fundamental architecture to manage that data once it comes in. |
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/mvrFileFormat.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 "mvrFileFormat.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/rotation.h>
#include <pxr/base/gf/vec3f.h>
#include <pxr/usd/usd/payloads.h>
#include "mvrParser/MVRParser.h"
#include "../gdtfFileFormat/gdtfUsdConverter.h"
#include <iostream>
#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING
#include <experimental/filesystem>
PXR_NAMESPACE_OPEN_SCOPE
MvrFileFormat::MvrFileFormat() : SdfFileFormat(
MvrFileFormatTokens->Id,
MvrFileFormatTokens->Version,
MvrFileFormatTokens->Target,
MvrFileFormatTokens->Extension)
{
}
MvrFileFormat::~MvrFileFormat()
{
}
bool MvrFileFormat::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 MvrFileFormat::Read(SdfLayer* layer, const std::string& resolvedPath, bool metadataOnly) const
{
// these macros emit methods defined in the Pixar namespace
// but not properly scoped, so we have to use the namespace
// locally here - note this isn't strictly true since we had to open
// the namespace scope anyway because the macros won't allow non-Pixar namespaces
// to be used because of some auto-generated content
PXR_NAMESPACE_USING_DIRECTIVE
if (!TF_VERIFY(layer))
{
return false;
}
// Parse MVR file
// ---------------------
using namespace MVR;
auto parser = MVRParser();
auto layers = parser.ParseMVRFile(resolvedPath);
// Create USD Schema
// ------------------------
SdfLayerRefPtr newLayer = SdfLayer::CreateAnonymous(".usd");
UsdStageRefPtr stage = UsdStage::Open(newLayer);
auto xformPath = SdfPath("/mvr_payload");
auto defaultPrim = UsdGeomXform::Define(stage, xformPath);
stage->SetDefaultPrim(defaultPrim.GetPrim());
for(const auto& layer : layers)
{
const std::string cleanName = CleanNameForUSD(layer.name);
const auto& layerPath = xformPath.AppendChild(TfToken(CleanNameForUSD(layer.name)));
auto layerUsd = UsdGeomScope::Define(stage, layerPath);
for(const auto& fixture : layer.fixtures)
{
const std::string cleanFixtureName = CleanNameForUSD(fixture.Name + fixture.UUID);
const auto& fixturePath = layerPath.AppendChild(TfToken(cleanFixtureName));
const auto& fixtureUsd = UsdGeomXform::Define(stage, fixturePath);
GDTF::GDTFSpecification gdtfSpec = parser.GetGDTFSpecification(fixture.GDTFSpec);
GDTF::ConvertToUsd(gdtfSpec, stage, fixturePath.GetAsString());
GfMatrix4d transform = GfMatrix4d(
fixture.Matrix[0][0], fixture.Matrix[0][1], fixture.Matrix[0][2], 0,
fixture.Matrix[1][0], fixture.Matrix[1][1], fixture.Matrix[1][2], 0,
fixture.Matrix[2][0], fixture.Matrix[2][1], fixture.Matrix[2][2], 0,
fixture.Matrix[3][0], fixture.Matrix[3][1], fixture.Matrix[3][2], 1
);
// Offset matrix
GfMatrix3d rotateMinus90deg = GfMatrix3d(1, 0, 0,
0, 0, 1,
0, -1, 0);
// Translation
//transform = transform.GetTranspose();
GfVec3d translation = rotateMinus90deg * transform.ExtractTranslation() * 0.1;
// Rotation
GfRotation rotation = transform.ExtractRotation();
GfVec3d euler = rotation.Decompose(GfVec3f::XAxis(), GfVec3f::YAxis(), GfVec3f::ZAxis());
GfVec3d rotate = rotateMinus90deg * euler; // we somehow have a complete 180 offset here.
// Set transform
auto fixtureXform = UsdGeomXformable(fixtureUsd);
fixtureXform.ClearXformOpOrder();
fixtureXform.AddTranslateOp().Set(translation);
fixtureXform.AddScaleOp().Set(GfVec3f(100, 100, 100));
fixtureXform.AddRotateYXZOp(UsdGeomXformOp::PrecisionDouble).Set(rotate);
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:name"), pxr::SdfValueTypeNames->String).Set(fixture.Name);
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:uuid"), pxr::SdfValueTypeNames->String).Set(fixture.UUID);
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:GDTFSpec"), pxr::SdfValueTypeNames->String).Set(fixture.GDTFSpec);
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:GDTFMode"), pxr::SdfValueTypeNames->String).Set(fixture.GDTFMode);
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:Classing"), pxr::SdfValueTypeNames->String).Set(fixture.Classing);
int i = 0;
std::string allCommands = "[";
for(auto cc : fixture.CustomCommands)
{
allCommands += cc + ",";
i++;
}
allCommands += "]";
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:CustomCommands"), pxr::SdfValueTypeNames->String).Set(allCommands);
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:CIEColor"), pxr::SdfValueTypeNames->String).Set(fixture.CieColor);
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:FixtureID"), pxr::SdfValueTypeNames->UInt).Set(fixture.FixtureID);
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:UnitNumber"), pxr::SdfValueTypeNames->UInt).Set(fixture.UnitNumber);
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:FixtureTypeId"), pxr::SdfValueTypeNames->UInt).Set(fixture.FixtureTypeID);
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:CustomId"), pxr::SdfValueTypeNames->UInt).Set(fixture.CustomId);
fixtureUsd.GetPrim().CreateAttribute(TfToken("mf:mvr:CastShadow"), pxr::SdfValueTypeNames->Bool).Set(fixture.CastShadows);
}
}
layer->TransferContent(newLayer);
return true;
}
bool MvrFileFormat::WriteToString(const SdfLayer& layer, std::string* str, const std::string& comment) const
{
// this POC doesn't support writing
return false;
}
bool MvrFileFormat::WriteToStream(const SdfSpecHandle& spec, std::ostream& out, size_t indent) const
{
// this POC doesn't support writing
return false;
}
bool MvrFileFormat::_ShouldSkipAnonymousReload() const
{
return false;
}
bool MvrFileFormat::_ShouldReadAnonymousLayers() const
{
return true;
}
void MvrFileFormat::ComposeFieldsForFileFormatArguments(const std::string& assetPath, const PcpDynamicFileFormatContext& context, FileFormatArguments* args, VtValue* contextDependencyData) const
{
return;
}
bool MvrFileFormat::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(
MvrFileFormatTokens,
((Id, "mvrFileFormat"))
((Version, "1.0"))
((Target, "usd"))
((Extension, "mvr"))
);
TF_REGISTRY_FUNCTION(TfType)
{
SDF_DEFINE_FILE_FORMAT(MvrFileFormat, SdfFileFormat);
}
PXR_NAMESPACE_CLOSE_SCOPE |
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/api.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_MVR_API_H_
#define OMNI_MVR_API_H_
#include "pxr/base/arch/export.h"
#if defined(PXR_STATIC)
# define MVR_API
# define MVR_API_TEMPLATE_CLASS(...)
# define MVR_API_TEMPLATE_STRUCT(...)
# define EDF_LOCAL
#else
# if defined(MVRFILEFORMAT_EXPORTS)
# define MVR_API ARCH_EXPORT
# define MVR_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__)
# define MVR_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__)
# else
# define MVR_API ARCH_IMPORT
# define MVR_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__)
# define MVR_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__)
# endif
# define EDF_LOCAL ARCH_HIDDEN
#endif
#endif |
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/mvrFileFormat.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_EDF_EDFFILEFORMAT_H_
#define OMNI_EDF_EDFFILEFORMAT_H_
#define NOMINMAX
#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 MvrFileFormat
///
/// 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 MVR_API MvrFileFormat : 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 ~MvrFileFormat();
MvrFileFormat();
};
TF_DECLARE_PUBLIC_TOKENS(
MvrFileFormatTokens,
((Id, "mvrFileFormat"))
((Version, "1.0"))
((Target, "usd"))
((Extension, "mvr"))
);
TF_DECLARE_WEAK_AND_REF_PTRS(MvrFileFormat);
PXR_NAMESPACE_CLOSE_SCOPE
#endif |
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/utils.h | #pragma once
|
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/plugInfo.json | {
"Plugins": [
{
"Info": {
"Types": {
"MvrFileFormat": {
"bases": [
"SdfFileFormat"
],
"displayName": "MVR Dynamic File Format",
"extensions": [
"mvr"
],
"formatId": "mvrFileFormat",
"primary": true,
"target": "usd"
}
}
},
"LibraryPath": "@PLUG_INFO_LIBRARY_PATH@",
"Name": "mvrFileFormat",
"ResourcePath": "@PLUG_INFO_RESOURCE_PATH@",
"Root": "@PLUG_INFO_ROOT@",
"Type": "library"
}
]
} |
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/README.md | # usd-mvr-plugin
An OpenUSD plugin for the MVR 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/mvrFileFormat/gdtfParser/GdtfUtils.h | |
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/gdtfParser/GdtfParser.cpp | #include "GdtfParser.h"
#ifdef GDTF_FILEFORMAT
#include "../mvrFileFormat/mvrParser/zip_file2.hpp"
#endif
#include "../mvrFileFormat/mvrParser/tinyxml2.h"
#include "../mvrFileFormat/assimp/include/assimp/scene.h"
#include "../mvrFileFormat/assimp/include/assimp/postprocess.h"
#include "../mvrFileFormat/assimp/include/assimp/Importer.hpp"
#include "../mvrFileFormat/assimp/include/assimp/Exporter.hpp"
#include <iostream>
#include <map>
#include <sstream>
#include <fstream>
#define MINIZ_HEADER_FILE_ONLY
#include "../mvrFileFormat/mvrParser/zip_file2.hpp"
#undef MINIZ_HEADER_FILE_ONLY
using ZipInfo = miniz_cpp2::zip_info;
using ZipInfoList = std::vector<ZipInfo>;
using ZipFile = miniz_cpp2::zip_file;
#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING
#include <experimental/filesystem>
namespace GDTF {
std::vector<std::string> GDTFParser::StringSplit(const std::string& input, const char delimiter)
{
std::vector<std::string> result;
std::stringstream ss(input);
std::string item;
while (getline(ss, item, delimiter))
{
result.push_back(item);
}
return result;
}
GDTF::GDTFMatrix StringToMatrix(const std::string& inputString)
{
std::string input = inputString;
size_t pos;
while ((pos = input.find("}{")) != std::string::npos)
{
input.replace(pos, 2, " ");
}
for (char& c : input)
{
if (c == ',' || c == ';' || c == '{' || c == '}')
{
c = ' ';
}
}
GDTF::GDTFMatrix output;
std::istringstream iss(input);
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
if (!(iss >> output[i][j]))
{
}
}
}
return output;
}
bool GDTFParser::FileExists(const std::string& path) const
{
const std::ifstream filePath(path);
return filePath.good();
}
GDTF::GDTFSpecification GDTFParser::ParseGDTFFile(const std::string& filePath)
{
if (!FileExists(filePath))
{
m_Errors.push("Failed to parse GDTF file: file doesn't exists - " + filePath);
return {};
}
m_TargetPath = std::experimental::filesystem::temp_directory_path().string() + "/";
m_SpecName = std::experimental::filesystem::path(filePath).filename().string();
auto zipFile = std::make_shared<ZipFile>(filePath);
auto spec = HandleGDTF(zipFile);
spec.SpecName = std::experimental::filesystem::path(zipFile->get_filename()).filename().string();
return spec;
}
GDTF::GDTFSpecification GDTFParser::ParseCompressed(std::shared_ptr<ZipFile> file, const std::string& zipFileName)
{
m_TargetPath = std::experimental::filesystem::temp_directory_path().string() + "/";
m_SpecName = std::experimental::filesystem::path(zipFileName).filename().string();
auto spec = HandleGDTF(file);
spec.SpecName = zipFileName;
return spec;
}
bool StringEndsWith(const std::string& input, const std::string& compare)
{
if(input.size() >= compare.size())
{
return (input.compare(input.length() - compare.length(), compare.length(), compare) == 0);
}
return false;
}
void GDTFParser::HandleModel(const File& file, const std::string& fixtureName)
{
Assimp::Importer importer;
bool from3ds = StringEndsWith(file.name, "3ds");
const aiScene* scene = importer.ReadFileFromMemory(file.content.data(), file.content.size() , aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenSmoothNormals | aiProcess_JoinIdenticalVertices,"EXTENTION");
Assimp::Exporter exporter;
std::experimental::filesystem::path targetPath = m_TargetPath;
std::experimental::filesystem::path destination = targetPath.parent_path().append(fixtureName);
std::experimental::filesystem::create_directory(destination);
std::experimental::filesystem::path convertedFileName = destination.append(std::experimental::filesystem::path(file.name).stem().concat(".gltf").c_str());
exporter.Export(scene, "gltf2", convertedFileName.string());
m_GDTFAssets[fixtureName][file.name] = convertedFileName.string();
}
std::string GDTFParser::GetFileExtension(const std::string& fileName)
{
const auto& fileNameSplits = StringSplit(fileName, '.');
const std::string fileExtension = fileNameSplits[fileNameSplits.size() - 1];
return fileExtension;
}
FileType GDTFParser::GetFileTypeFromExtension(const std::string& fileExtension)
{
if (fileExtension == "xml")
{
return FileType::XML;
}
else if (fileExtension == "3ds")
{
return FileType::MODEL;
}
else if(fileExtension == "gdtf")
{
return FileType::GDTF;
}
else if(fileExtension == "3ds" || fileExtension == "glb" || fileExtension == "gltf")
{
return FileType::MODEL;
}
return FileType::UNKNOWN;
}
void GDTFParser::HandleGDTFRecursive(tinyxml2::XMLElement* element, GDTF::GDTFSpecification& spec, int depth)
{
if(depth >= 4)
{
return; // Avoid stack overflow
}
int itCount = 0;
for(auto* geometry = element->FirstChildElement(); geometry != nullptr; geometry = geometry->NextSiblingElement())
{
itCount++;
if(itCount > 8)
{
return;
}
const std::string elementName = geometry->Name();
bool isBeam = elementName == "Beam";
bool isGeometry = elementName == "Geometry";
bool isAxis = elementName == "Axis";
bool isInventory = elementName == "Inventory";
bool isValid = (isBeam || isGeometry || isAxis) && !isInventory;
bool isModel = geometry->FindAttribute("Model") != nullptr;
if(!isValid || !isModel)
continue;
auto positionString = geometry->FindAttribute("Position")->Value();
auto position = StringToMatrix(positionString);
std::string name = geometry->FindAttribute("Name")->Value();
std::string model = geometry->FindAttribute("Model")->Value();
std::replace(name.begin(), name.end(), ' ', '_');
if(name == "Pigtail" || name == "pigtail" || model == "pigtail" || model == "Pigtail")
{
continue;
}
Geometry geometrySpec = {};
geometrySpec.Name = name;
geometrySpec.Model = model;
geometrySpec.Transform = position;
geometrySpec.Depth = depth;
if(isBeam)
{
geometrySpec.isBeam = true;
float beamRadius = 0.0f;
if(!geometry->QueryFloatAttribute("BeamRadius", &beamRadius))
{
// Failed to find beamRadius.
}
geometrySpec.beamRadius = beamRadius;
auto beamAngleXml = geometry->FindAttribute("BeamAngle")->Value();
if(!geometry->QueryFloatAttribute("BeamAngle", &spec.BeamAngle))
{
// Failed to find beamRadius.
}
auto beamTypeXml = geometry->FindAttribute("BeamType")->Value();
spec.BeamType = beamTypeXml;
int colorRenderingIndex = 0;
if(!geometry->QueryIntAttribute("ColorRenderingIndex", &spec.ColorRenderingIndex))
{
}
spec.ColorRenderingIndex = colorRenderingIndex;
if(!geometry->QueryFloatAttribute("ColorTemperature", &spec.ColorTemperature))
{
}
if(!geometry->QueryFloatAttribute("FieldAngle", &spec.FieldAngle))
{
}
auto lampType = geometry->FindAttribute("LampType");
if(lampType)
{
spec.LampType = lampType->Value();
}
if(!geometry->QueryFloatAttribute("LuminousFlux", &spec.LuminousFlux))
{
}
if(!geometry->QueryFloatAttribute("PowerConsumption", &spec.PowerConsumption))
{
}
spec.BeamRadius = beamRadius;
auto beamPosition = geometry->FindAttribute("Position")->Value();
spec.BeamMatrix = StringToMatrix(beamPosition);
spec.HasBeam = true;
}
spec.Geometries.push_back(geometrySpec);
HandleGDTFRecursive(geometry, spec, depth + 1);
}
}
GDTF::GDTFSpecification GDTFParser::HandleGDTF(std::shared_ptr<ZipFile>& zipFile)
{
std::map<std::string, std::vector<File>> fixtures;
std::vector<File> assetFiles;
GDTF::GDTFSpecification spec{};
for (const ZipInfo& info : zipFile->infolist())
{
std::cout << info.filename << std::endl;
const std::string& fileContent = zipFile->read(info);
File file = { info.filename, fileContent };
const FileType fileType = GetFileTypeFromExtension(GetFileExtension(info.filename));
switch (fileType)
{
case FileType::XML:
{
tinyxml2::XMLDocument doc;
if (doc.Parse(file.content.c_str()) != tinyxml2::XML_SUCCESS)
{
m_Errors.push("Failed to parse XML file: " + file.name);
return {};
}
tinyxml2::XMLElement* root = doc.RootElement();
auto fixtureType = root->FirstChildElement("FixtureType");
std::string name = (fixtureType->FindAttribute("Name"))->Value();
if(name.empty())
{
name = fixtureType->FindAttribute("LongName")->Value();
}
auto physicalDescription = fixtureType->FirstChildElement("PhysicalDescriptions");
if(physicalDescription)
{
auto pdProp = physicalDescription->FirstChildElement("Properties");
if(pdProp)
{
auto temp = pdProp->FirstChildElement("OperatingTemperature");
auto highXml = temp->FindAttribute("High");
if(highXml)
{
spec.HighTemperature = std::atof(highXml->Value());
}
auto lowXml = temp->FindAttribute("Low");
if(lowXml)
{
spec.LowTemperature = std::atof(lowXml->Value());
}
auto weightXml = pdProp->FirstChildElement("Weight");
if(weightXml)
{
auto weightValueXml = weightXml->FindAttribute("Value");
if(weightValueXml)
{
spec.Weight = std::atof(weightValueXml->Value());
}
}
auto legHeightXml = pdProp->FirstChildElement("LegHeight");
if(legHeightXml)
{
auto legHeightValueXml = legHeightXml->FindAttribute("Value");
if(legHeightValueXml)
{
spec.LegHeight = std::atof(legHeightValueXml->Value());
}
}
}
}
spec.Name = std::string(name);
auto models = fixtureType->FirstChildElement("Models");
for(auto* model = models->FirstChildElement("Model"); model; model = model->NextSiblingElement())
{
GDTF::ModelSpecification modelSpec;
modelSpec.Name = model->FindAttribute("Name")->Value();
modelSpec.File = model->FindAttribute("File")->Value();
// Fallback if the XML doesnt contain a name
if(modelSpec.Name.empty())
{
modelSpec.Name = modelSpec.File;
}
model->QueryFloatAttribute("Length", &modelSpec.Length);
model->QueryFloatAttribute("Height", &modelSpec.Height);
spec.Models.push_back(modelSpec);
}
int depth = 0;
auto geometries = fixtureType->FirstChildElement("Geometries");
HandleGDTFRecursive(geometries, spec, 0);
break;
}
case FileType::MODEL:
{
if(StringEndsWith(file.name, "3ds"))
{
spec.ConvertedFrom3ds = true;
}
assetFiles.push_back(file);
break;
}
default:
break; // Skip unknown file format.
}
}
for(auto& f : assetFiles)
{
HandleModel(f, m_SpecName);
}
return spec;
}
} |
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/gdtfParser/GdtfParser.h | #pragma once
#include "ModelSpecification.h"
#include <vector>
#include <stack>
#include <string>
#include <memory>
#include <map>
namespace tinyxml2
{
class XMLElement;
}
namespace miniz_cpp2
{
class zip_file;
}
using ZipFile = miniz_cpp2::zip_file;
namespace GDTF {
enum class FileType
{
GDTF,
MODEL,
XML,
UNKNOWN
};
struct File
{
std::string name;
std::string content;
};
class GDTFParser
{
public:
GDTFParser() = default;
~GDTFParser() = default;
GDTF::GDTFSpecification ParseGDTFFile(const std::string& path);
GDTF::GDTFSpecification ParseCompressed(std::shared_ptr<ZipFile> file, const std::string& zipFileName);
inline const bool HasError() const { return m_Errors.size() > 1; }
const std::string PopError()
{
if (!HasError())
{
throw std::exception("Error stack is empty.");
}
auto msg = m_Errors.top();
m_Errors.pop();
return msg;
}
private:
const std::string m_SceneDescriptionFileName = "GeneralSceneDescription.xml";
std::stack<std::string> m_Errors;
// File handling
void HandleXML(const File& fileName);
void HandleModel(const File& file, const std::string& fixtureName);
GDTF::GDTFSpecification HandleGDTF(std::shared_ptr<ZipFile>& file);
void HandleGDTFRecursive(tinyxml2::XMLElement* element, GDTF::GDTFSpecification& spec, int depth);
// Utilities
bool FileExists(const std::string& path) const;
std::string GetFileExtension(const std::string& path);
FileType GetFileTypeFromExtension(const std::string& extension);
std::vector<std::string> StringSplit(const std::string& input, const char delimiter);
std::map<std::string, std::map<std::string, std::string>> m_GDTFAssets;
std::string m_TargetPath;
std::string m_SpecName;
};
} |
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/gdtfParser/Device.h | #include <array>
namespace GDTF {
using GDTFMatrix = std::array<std::array<double, 4>, 4>;
} |
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/gdtfParser/ModelSpecification.h | #pragma once
#include <string>
#include <vector>
#include "Device.h"
namespace GDTF {
struct ModelSpecification
{
std::string Name;
std::string Id;
std::string File;
std::string ConvertedFilePath;
int Depth = 0;
float Height = 0.0f;
float Length = 0.0f;
};
struct Geometry
{
int Depth = 0.0f;
GDTFMatrix Transform;
std::string Name;
std::string Model;
bool isBeam = false;
float beamRadius = 0.0f;
};
struct GDTFSpecification
{
std::string Name;
std::string SpecName;
float LowTemperature = 0.0f;
float HighTemperature = 0.0f;
float LegHeight = 0.0f;
float Weight = 0.0f;
bool ConvertedFrom3ds = false;
std::vector<ModelSpecification> Models;
std::vector<Geometry> Geometries;
GDTFMatrix BaseMatrix = GDTFMatrix();
GDTFMatrix BodyMatrix = GDTFMatrix();
GDTFMatrix YokeMatrix = GDTFMatrix();
int TreeDepth = 0;
// Beam specific
bool HasBeam = false;
float BeamRadius = 0.0f;
GDTFMatrix BeamMatrix = GDTFMatrix();
float BeamAngle = 0.0f;
std::string BeamType = "";
int ColorRenderingIndex = 0;
float ColorTemperature = 0.0f;
float FieldAngle = 0.0f;
std::string LampType = "";
float LuminousFlux = 0.0f;
float PowerConsumption = 0.0f;
};
} |
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/assimp/include/assimp/Subdivision.h | /*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/** @file Defines a helper class to evaluate subdivision surfaces.*/
#pragma once
#ifndef AI_SUBDISIVION_H_INC
#define AI_SUBDISIVION_H_INC
#ifdef __GNUC__
# pragma GCC system_header
#endif
#include <assimp/types.h>
struct aiMesh;
namespace Assimp {
// ------------------------------------------------------------------------------
/** Helper class to evaluate subdivision surfaces. Different algorithms
* are provided for choice. */
// ------------------------------------------------------------------------------
class ASSIMP_API Subdivider {
public:
/** Enumerates all supported subvidision algorithms */
enum Algorithm {
CATMULL_CLARKE = 0x1
};
virtual ~Subdivider();
// ---------------------------------------------------------------
/** Create a subdivider of a specific type
*
* @param algo Algorithm to be used for subdivision
* @return Subdivider instance. */
static Subdivider* Create (Algorithm algo);
// ---------------------------------------------------------------
/** Subdivide a mesh using the selected algorithm
*
* @param mesh First mesh to be subdivided. Must be in verbose
* format.
* @param out Receives the output mesh, allocated by me.
* @param num Number of subdivisions to perform.
* @param discard_input If true is passed, the input mesh is
* deleted after the subdivision is complete. This can
* improve performance because it allows the optimization
* to reuse the existing mesh for intermediate results.
* @pre out!=mesh*/
virtual void Subdivide ( aiMesh* mesh,
aiMesh*& out, unsigned int num,
bool discard_input = false) = 0;
// ---------------------------------------------------------------
/** Subdivide multiple meshes using the selected algorithm. This
* avoids erroneous smoothing on objects consisting of multiple
* per-material meshes. Usually, most 3d modellers smooth on a
* per-object base, regardless the materials assigned to the
* meshes.
*
* @param smesh Array of meshes to be subdivided. Must be in
* verbose format.
* @param nmesh Number of meshes in smesh.
* @param out Receives the output meshes. The array must be
* sufficiently large (at least @c nmesh elements) and may not
* overlap the input array. Output meshes map one-to-one to
* their corresponding input meshes. The meshes are allocated
* by the function.
* @param discard_input If true is passed, input meshes are
* deleted after the subdivision is complete. This can
* improve performance because it allows the optimization
* of reusing existing meshes for intermediate results.
* @param num Number of subdivisions to perform.
* @pre nmesh != 0, smesh and out may not overlap*/
virtual void Subdivide (
aiMesh** smesh,
size_t nmesh,
aiMesh** out,
unsigned int num,
bool discard_input = false) = 0;
};
inline Subdivider::~Subdivider() = default;
} // end namespace Assimp
#endif // !! AI_SUBDISIVION_H_INC
|
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/assimp/include/assimp/matrix4x4.inl | /*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
/** @file matrix4x4.inl
* @brief Inline implementation of the 4x4 matrix operators
*/
#pragma once
#ifndef AI_MATRIX4X4_INL_INC
#define AI_MATRIX4X4_INL_INC
#ifdef __cplusplus
#include "matrix4x4.h"
#include "matrix3x3.h"
#include "quaternion.h"
#include "MathFunctions.h"
#include <algorithm>
#include <limits>
#include <cmath>
// ----------------------------------------------------------------------------------------
template <typename TReal>
aiMatrix4x4t<TReal>::aiMatrix4x4t() AI_NO_EXCEPT :
a1(1.0f), a2(), a3(), a4(),
b1(), b2(1.0f), b3(), b4(),
c1(), c2(), c3(1.0f), c4(),
d1(), d2(), d3(), d4(1.0f) {
// empty
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
aiMatrix4x4t<TReal>::aiMatrix4x4t (TReal _a1, TReal _a2, TReal _a3, TReal _a4,
TReal _b1, TReal _b2, TReal _b3, TReal _b4,
TReal _c1, TReal _c2, TReal _c3, TReal _c4,
TReal _d1, TReal _d2, TReal _d3, TReal _d4) :
a1(_a1), a2(_a2), a3(_a3), a4(_a4),
b1(_b1), b2(_b2), b3(_b3), b4(_b4),
c1(_c1), c2(_c2), c3(_c3), c4(_c4),
d1(_d1), d2(_d2), d3(_d3), d4(_d4) {
// empty
}
// ------------------------------------------------------------------------------------------------
template <typename TReal>
template <typename TOther>
aiMatrix4x4t<TReal>::operator aiMatrix4x4t<TOther> () const {
return aiMatrix4x4t<TOther>(static_cast<TOther>(a1),static_cast<TOther>(a2),static_cast<TOther>(a3),static_cast<TOther>(a4),
static_cast<TOther>(b1),static_cast<TOther>(b2),static_cast<TOther>(b3),static_cast<TOther>(b4),
static_cast<TOther>(c1),static_cast<TOther>(c2),static_cast<TOther>(c3),static_cast<TOther>(c4),
static_cast<TOther>(d1),static_cast<TOther>(d2),static_cast<TOther>(d3),static_cast<TOther>(d4));
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>::aiMatrix4x4t (const aiMatrix3x3t<TReal>& m) {
a1 = m.a1; a2 = m.a2; a3 = m.a3; a4 = static_cast<TReal>(0.0);
b1 = m.b1; b2 = m.b2; b3 = m.b3; b4 = static_cast<TReal>(0.0);
c1 = m.c1; c2 = m.c2; c3 = m.c3; c4 = static_cast<TReal>(0.0);
d1 = static_cast<TReal>(0.0); d2 = static_cast<TReal>(0.0); d3 = static_cast<TReal>(0.0); d4 = static_cast<TReal>(1.0);
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>::aiMatrix4x4t (const aiVector3t<TReal>& scaling, const aiQuaterniont<TReal>& rotation, const aiVector3t<TReal>& position) {
// build a 3x3 rotation matrix
aiMatrix3x3t<TReal> m = rotation.GetMatrix();
a1 = m.a1 * scaling.x;
a2 = m.a2 * scaling.x;
a3 = m.a3 * scaling.x;
a4 = position.x;
b1 = m.b1 * scaling.y;
b2 = m.b2 * scaling.y;
b3 = m.b3 * scaling.y;
b4 = position.y;
c1 = m.c1 * scaling.z;
c2 = m.c2 * scaling.z;
c3 = m.c3 * scaling.z;
c4= position.z;
d1 = static_cast<TReal>(0.0);
d2 = static_cast<TReal>(0.0);
d3 = static_cast<TReal>(0.0);
d4 = static_cast<TReal>(1.0);
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::operator *= (const aiMatrix4x4t<TReal>& m) {
*this = aiMatrix4x4t<TReal>(
m.a1 * a1 + m.b1 * a2 + m.c1 * a3 + m.d1 * a4,
m.a2 * a1 + m.b2 * a2 + m.c2 * a3 + m.d2 * a4,
m.a3 * a1 + m.b3 * a2 + m.c3 * a3 + m.d3 * a4,
m.a4 * a1 + m.b4 * a2 + m.c4 * a3 + m.d4 * a4,
m.a1 * b1 + m.b1 * b2 + m.c1 * b3 + m.d1 * b4,
m.a2 * b1 + m.b2 * b2 + m.c2 * b3 + m.d2 * b4,
m.a3 * b1 + m.b3 * b2 + m.c3 * b3 + m.d3 * b4,
m.a4 * b1 + m.b4 * b2 + m.c4 * b3 + m.d4 * b4,
m.a1 * c1 + m.b1 * c2 + m.c1 * c3 + m.d1 * c4,
m.a2 * c1 + m.b2 * c2 + m.c2 * c3 + m.d2 * c4,
m.a3 * c1 + m.b3 * c2 + m.c3 * c3 + m.d3 * c4,
m.a4 * c1 + m.b4 * c2 + m.c4 * c3 + m.d4 * c4,
m.a1 * d1 + m.b1 * d2 + m.c1 * d3 + m.d1 * d4,
m.a2 * d1 + m.b2 * d2 + m.c2 * d3 + m.d2 * d4,
m.a3 * d1 + m.b3 * d2 + m.c3 * d3 + m.d3 * d4,
m.a4 * d1 + m.b4 * d2 + m.c4 * d3 + m.d4 * d4);
return *this;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE aiMatrix4x4t<TReal> aiMatrix4x4t<TReal>::operator* (const TReal& aFloat) const {
aiMatrix4x4t<TReal> temp(
a1 * aFloat,
a2 * aFloat,
a3 * aFloat,
a4 * aFloat,
b1 * aFloat,
b2 * aFloat,
b3 * aFloat,
b4 * aFloat,
c1 * aFloat,
c2 * aFloat,
c3 * aFloat,
c4 * aFloat,
d1 * aFloat,
d2 * aFloat,
d3 * aFloat,
d4 * aFloat);
return temp;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal> aiMatrix4x4t<TReal>::operator+ (const aiMatrix4x4t<TReal>& m) const {
aiMatrix4x4t<TReal> temp(
m.a1 + a1,
m.a2 + a2,
m.a3 + a3,
m.a4 + a4,
m.b1 + b1,
m.b2 + b2,
m.b3 + b3,
m.b4 + b4,
m.c1 + c1,
m.c2 + c2,
m.c3 + c3,
m.c4 + c4,
m.d1 + d1,
m.d2 + d2,
m.d3 + d3,
m.d4 + d4);
return temp;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal> aiMatrix4x4t<TReal>::operator* (const aiMatrix4x4t<TReal>& m) const {
aiMatrix4x4t<TReal> temp( *this);
temp *= m;
return temp;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::Transpose() {
// (TReal&) don't remove, GCC complains cause of packed fields
std::swap( (TReal&)b1, (TReal&)a2);
std::swap( (TReal&)c1, (TReal&)a3);
std::swap( (TReal&)c2, (TReal&)b3);
std::swap( (TReal&)d1, (TReal&)a4);
std::swap( (TReal&)d2, (TReal&)b4);
std::swap( (TReal&)d3, (TReal&)c4);
return *this;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
TReal aiMatrix4x4t<TReal>::Determinant() const {
return a1*b2*c3*d4 - a1*b2*c4*d3 + a1*b3*c4*d2 - a1*b3*c2*d4
+ a1*b4*c2*d3 - a1*b4*c3*d2 - a2*b3*c4*d1 + a2*b3*c1*d4
- a2*b4*c1*d3 + a2*b4*c3*d1 - a2*b1*c3*d4 + a2*b1*c4*d3
+ a3*b4*c1*d2 - a3*b4*c2*d1 + a3*b1*c2*d4 - a3*b1*c4*d2
+ a3*b2*c4*d1 - a3*b2*c1*d4 - a4*b1*c2*d3 + a4*b1*c3*d2
- a4*b2*c3*d1 + a4*b2*c1*d3 - a4*b3*c1*d2 + a4*b3*c2*d1;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::Inverse() {
// Compute the reciprocal determinant
const TReal det = Determinant();
if(det == static_cast<TReal>(0.0))
{
// Matrix not invertible. Setting all elements to nan is not really
// correct in a mathematical sense but it is easy to debug for the
// programmer.
const TReal nan = std::numeric_limits<TReal>::quiet_NaN();
*this = aiMatrix4x4t<TReal>(
nan,nan,nan,nan,
nan,nan,nan,nan,
nan,nan,nan,nan,
nan,nan,nan,nan);
return *this;
}
const TReal invdet = static_cast<TReal>(1.0) / det;
aiMatrix4x4t<TReal> res;
res.a1 = invdet * (b2 * (c3 * d4 - c4 * d3) + b3 * (c4 * d2 - c2 * d4) + b4 * (c2 * d3 - c3 * d2));
res.a2 = -invdet * (a2 * (c3 * d4 - c4 * d3) + a3 * (c4 * d2 - c2 * d4) + a4 * (c2 * d3 - c3 * d2));
res.a3 = invdet * (a2 * (b3 * d4 - b4 * d3) + a3 * (b4 * d2 - b2 * d4) + a4 * (b2 * d3 - b3 * d2));
res.a4 = -invdet * (a2 * (b3 * c4 - b4 * c3) + a3 * (b4 * c2 - b2 * c4) + a4 * (b2 * c3 - b3 * c2));
res.b1 = -invdet * (b1 * (c3 * d4 - c4 * d3) + b3 * (c4 * d1 - c1 * d4) + b4 * (c1 * d3 - c3 * d1));
res.b2 = invdet * (a1 * (c3 * d4 - c4 * d3) + a3 * (c4 * d1 - c1 * d4) + a4 * (c1 * d3 - c3 * d1));
res.b3 = -invdet * (a1 * (b3 * d4 - b4 * d3) + a3 * (b4 * d1 - b1 * d4) + a4 * (b1 * d3 - b3 * d1));
res.b4 = invdet * (a1 * (b3 * c4 - b4 * c3) + a3 * (b4 * c1 - b1 * c4) + a4 * (b1 * c3 - b3 * c1));
res.c1 = invdet * (b1 * (c2 * d4 - c4 * d2) + b2 * (c4 * d1 - c1 * d4) + b4 * (c1 * d2 - c2 * d1));
res.c2 = -invdet * (a1 * (c2 * d4 - c4 * d2) + a2 * (c4 * d1 - c1 * d4) + a4 * (c1 * d2 - c2 * d1));
res.c3 = invdet * (a1 * (b2 * d4 - b4 * d2) + a2 * (b4 * d1 - b1 * d4) + a4 * (b1 * d2 - b2 * d1));
res.c4 = -invdet * (a1 * (b2 * c4 - b4 * c2) + a2 * (b4 * c1 - b1 * c4) + a4 * (b1 * c2 - b2 * c1));
res.d1 = -invdet * (b1 * (c2 * d3 - c3 * d2) + b2 * (c3 * d1 - c1 * d3) + b3 * (c1 * d2 - c2 * d1));
res.d2 = invdet * (a1 * (c2 * d3 - c3 * d2) + a2 * (c3 * d1 - c1 * d3) + a3 * (c1 * d2 - c2 * d1));
res.d3 = -invdet * (a1 * (b2 * d3 - b3 * d2) + a2 * (b3 * d1 - b1 * d3) + a3 * (b1 * d2 - b2 * d1));
res.d4 = invdet * (a1 * (b2 * c3 - b3 * c2) + a2 * (b3 * c1 - b1 * c3) + a3 * (b1 * c2 - b2 * c1));
*this = res;
return *this;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
TReal* aiMatrix4x4t<TReal>::operator[](unsigned int p_iIndex) {
if (p_iIndex > 3) {
return nullptr;
}
switch ( p_iIndex ) {
case 0:
return &a1;
case 1:
return &b1;
case 2:
return &c1;
case 3:
return &d1;
default:
break;
}
return &a1;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
const TReal* aiMatrix4x4t<TReal>::operator[](unsigned int p_iIndex) const {
if (p_iIndex > 3) {
return nullptr;
}
switch ( p_iIndex ) {
case 0:
return &a1;
case 1:
return &b1;
case 2:
return &c1;
case 3:
return &d1;
default:
break;
}
return &a1;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
bool aiMatrix4x4t<TReal>::operator== (const aiMatrix4x4t<TReal>& m) const {
return (a1 == m.a1 && a2 == m.a2 && a3 == m.a3 && a4 == m.a4 &&
b1 == m.b1 && b2 == m.b2 && b3 == m.b3 && b4 == m.b4 &&
c1 == m.c1 && c2 == m.c2 && c3 == m.c3 && c4 == m.c4 &&
d1 == m.d1 && d2 == m.d2 && d3 == m.d3 && d4 == m.d4);
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
bool aiMatrix4x4t<TReal>::operator!= (const aiMatrix4x4t<TReal>& m) const {
return !(*this == m);
}
// ---------------------------------------------------------------------------
template<typename TReal>
AI_FORCE_INLINE
bool aiMatrix4x4t<TReal>::Equal(const aiMatrix4x4t<TReal>& m, TReal epsilon) const {
return
std::abs(a1 - m.a1) <= epsilon &&
std::abs(a2 - m.a2) <= epsilon &&
std::abs(a3 - m.a3) <= epsilon &&
std::abs(a4 - m.a4) <= epsilon &&
std::abs(b1 - m.b1) <= epsilon &&
std::abs(b2 - m.b2) <= epsilon &&
std::abs(b3 - m.b3) <= epsilon &&
std::abs(b4 - m.b4) <= epsilon &&
std::abs(c1 - m.c1) <= epsilon &&
std::abs(c2 - m.c2) <= epsilon &&
std::abs(c3 - m.c3) <= epsilon &&
std::abs(c4 - m.c4) <= epsilon &&
std::abs(d1 - m.d1) <= epsilon &&
std::abs(d2 - m.d2) <= epsilon &&
std::abs(d3 - m.d3) <= epsilon &&
std::abs(d4 - m.d4) <= epsilon;
}
// ----------------------------------------------------------------------------------------
#define ASSIMP_MATRIX4_4_DECOMPOSE_PART \
const aiMatrix4x4t<TReal>& _this = *this;/* Create alias for conveniance. */ \
\
/* extract translation */ \
pPosition.x = _this[0][3]; \
pPosition.y = _this[1][3]; \
pPosition.z = _this[2][3]; \
\
/* extract the columns of the matrix. */ \
aiVector3t<TReal> vCols[3] = { \
aiVector3t<TReal>(_this[0][0],_this[1][0],_this[2][0]), \
aiVector3t<TReal>(_this[0][1],_this[1][1],_this[2][1]), \
aiVector3t<TReal>(_this[0][2],_this[1][2],_this[2][2]) \
}; \
\
/* extract the scaling factors */ \
pScaling.x = vCols[0].Length(); \
pScaling.y = vCols[1].Length(); \
pScaling.z = vCols[2].Length(); \
\
/* and the sign of the scaling */ \
if (Determinant() < 0) pScaling = -pScaling; \
\
/* and remove all scaling from the matrix */ \
if(pScaling.x) vCols[0] /= pScaling.x; \
if(pScaling.y) vCols[1] /= pScaling.y; \
if(pScaling.z) vCols[2] /= pScaling.z; \
\
do {} while(false)
template <typename TReal>
AI_FORCE_INLINE
void aiMatrix4x4t<TReal>::Decompose (aiVector3t<TReal>& pScaling, aiQuaterniont<TReal>& pRotation,
aiVector3t<TReal>& pPosition) const {
ASSIMP_MATRIX4_4_DECOMPOSE_PART;
// build a 3x3 rotation matrix
aiMatrix3x3t<TReal> m(vCols[0].x,vCols[1].x,vCols[2].x,
vCols[0].y,vCols[1].y,vCols[2].y,
vCols[0].z,vCols[1].z,vCols[2].z);
// and generate the rotation quaternion from it
pRotation = aiQuaterniont<TReal>(m);
}
template <typename TReal>
AI_FORCE_INLINE
void aiMatrix4x4t<TReal>::Decompose(aiVector3t<TReal>& pScaling, aiVector3t<TReal>& pRotation, aiVector3t<TReal>& pPosition) const {
ASSIMP_MATRIX4_4_DECOMPOSE_PART;
/*
assuming a right-handed coordinate system
and post-multiplication of column vectors,
the rotation matrix for an euler XYZ rotation is M = Rz * Ry * Rx.
combining gives:
| CE BDE-AF ADE+BF 0 |
M = | CF BDF+AE ADF-BE 0 |
| -D CB AC 0 |
| 0 0 0 1 |
where
A = cos(angle_x), B = sin(angle_x);
C = cos(angle_y), D = sin(angle_y);
E = cos(angle_z), F = sin(angle_z);
*/
// Use a small epsilon to solve floating-point inaccuracies
const TReal epsilon = Assimp::Math::getEpsilon<TReal>();
pRotation.y = std::asin(-vCols[0].z);// D. Angle around oY.
TReal C = std::cos(pRotation.y);
if(std::fabs(C) > epsilon)
{
// Finding angle around oX.
TReal tan_x = vCols[2].z / C;// A
TReal tan_y = vCols[1].z / C;// B
pRotation.x = std::atan2(tan_y, tan_x);
// Finding angle around oZ.
tan_x = vCols[0].x / C;// E
tan_y = vCols[0].y / C;// F
pRotation.z = std::atan2(tan_y, tan_x);
}
else
{// oY is fixed.
pRotation.x = 0;// Set angle around oX to 0. => A == 1, B == 0, C == 0, D == 1.
// And finding angle around oZ.
TReal tan_x = vCols[1].y;// BDF+AE => E
TReal tan_y = -vCols[1].x;// BDE-AF => F
pRotation.z = std::atan2(tan_y, tan_x);
}
}
#undef ASSIMP_MATRIX4_4_DECOMPOSE_PART
template <typename TReal>
AI_FORCE_INLINE
void aiMatrix4x4t<TReal>::Decompose(aiVector3t<TReal>& pScaling, aiVector3t<TReal>& pRotationAxis, TReal& pRotationAngle,
aiVector3t<TReal>& pPosition) const {
aiQuaterniont<TReal> pRotation;
Decompose(pScaling, pRotation, pPosition);
pRotation.Normalize();
TReal angle_cos = pRotation.w;
TReal angle_sin = std::sqrt(1.0f - angle_cos * angle_cos);
pRotationAngle = std::acos(angle_cos) * 2;
// Use a small epsilon to solve floating-point inaccuracies
const TReal epsilon = 10e-3f;
if(std::fabs(angle_sin) < epsilon) angle_sin = 1;
pRotationAxis.x = pRotation.x / angle_sin;
pRotationAxis.y = pRotation.y / angle_sin;
pRotationAxis.z = pRotation.z / angle_sin;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
void aiMatrix4x4t<TReal>::DecomposeNoScaling (aiQuaterniont<TReal>& rotation,
aiVector3t<TReal>& position) const {
const aiMatrix4x4t<TReal>& _this = *this;
// extract translation
position.x = _this[0][3];
position.y = _this[1][3];
position.z = _this[2][3];
// extract rotation
rotation = aiQuaterniont<TReal>((aiMatrix3x3t<TReal>)_this);
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::FromEulerAnglesXYZ(const aiVector3t<TReal>& blubb) {
return FromEulerAnglesXYZ(blubb.x,blubb.y,blubb.z);
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::FromEulerAnglesXYZ(TReal x, TReal y, TReal z) {
aiMatrix4x4t<TReal>& _this = *this;
TReal cx = std::cos(x);
TReal sx = std::sin(x);
TReal cy = std::cos(y);
TReal sy = std::sin(y);
TReal cz = std::cos(z);
TReal sz = std::sin(z);
// mz*my*mx
_this.a1 = cz * cy;
_this.a2 = cz * sy * sx - sz * cx;
_this.a3 = sz * sx + cz * sy * cx;
_this.b1 = sz * cy;
_this.b2 = cz * cx + sz * sy * sx;
_this.b3 = sz * sy * cx - cz * sx;
_this.c1 = -sy;
_this.c2 = cy * sx;
_this.c3 = cy * cx;
return *this;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
bool aiMatrix4x4t<TReal>::IsIdentity() const {
// Use a small epsilon to solve floating-point inaccuracies
const static TReal epsilon = 10e-3f;
return (a2 <= epsilon && a2 >= -epsilon &&
a3 <= epsilon && a3 >= -epsilon &&
a4 <= epsilon && a4 >= -epsilon &&
b1 <= epsilon && b1 >= -epsilon &&
b3 <= epsilon && b3 >= -epsilon &&
b4 <= epsilon && b4 >= -epsilon &&
c1 <= epsilon && c1 >= -epsilon &&
c2 <= epsilon && c2 >= -epsilon &&
c4 <= epsilon && c4 >= -epsilon &&
d1 <= epsilon && d1 >= -epsilon &&
d2 <= epsilon && d2 >= -epsilon &&
d3 <= epsilon && d3 >= -epsilon &&
a1 <= 1.f+epsilon && a1 >= 1.f-epsilon &&
b2 <= 1.f+epsilon && b2 >= 1.f-epsilon &&
c3 <= 1.f+epsilon && c3 >= 1.f-epsilon &&
d4 <= 1.f+epsilon && d4 >= 1.f-epsilon);
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::RotationX(TReal a, aiMatrix4x4t<TReal>& out) {
/*
| 1 0 0 0 |
M = | 0 cos(A) -sin(A) 0 |
| 0 sin(A) cos(A) 0 |
| 0 0 0 1 | */
out = aiMatrix4x4t<TReal>();
out.b2 = out.c3 = std::cos(a);
out.b3 = -(out.c2 = std::sin(a));
return out;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::RotationY(TReal a, aiMatrix4x4t<TReal>& out) {
/*
| cos(A) 0 sin(A) 0 |
M = | 0 1 0 0 |
| -sin(A) 0 cos(A) 0 |
| 0 0 0 1 |
*/
out = aiMatrix4x4t<TReal>();
out.a1 = out.c3 = std::cos(a);
out.c1 = -(out.a3 = std::sin(a));
return out;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::RotationZ(TReal a, aiMatrix4x4t<TReal>& out) {
/*
| cos(A) -sin(A) 0 0 |
M = | sin(A) cos(A) 0 0 |
| 0 0 1 0 |
| 0 0 0 1 | */
out = aiMatrix4x4t<TReal>();
out.a1 = out.b2 = std::cos(a);
out.a2 = -(out.b1 = std::sin(a));
return out;
}
// ----------------------------------------------------------------------------------------
// Returns a rotation matrix for a rotation around an arbitrary axis.
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::Rotation( TReal a, const aiVector3t<TReal>& axis, aiMatrix4x4t<TReal>& out) {
TReal c = std::cos( a), s = std::sin( a), t = 1 - c;
TReal x = axis.x, y = axis.y, z = axis.z;
// Many thanks to MathWorld and Wikipedia
out.a1 = t*x*x + c; out.a2 = t*x*y - s*z; out.a3 = t*x*z + s*y;
out.b1 = t*x*y + s*z; out.b2 = t*y*y + c; out.b3 = t*y*z - s*x;
out.c1 = t*x*z - s*y; out.c2 = t*y*z + s*x; out.c3 = t*z*z + c;
out.a4 = out.b4 = out.c4 = static_cast<TReal>(0.0);
out.d1 = out.d2 = out.d3 = static_cast<TReal>(0.0);
out.d4 = static_cast<TReal>(1.0);
return out;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::Translation( const aiVector3t<TReal>& v, aiMatrix4x4t<TReal>& out) {
out = aiMatrix4x4t<TReal>();
out.a4 = v.x;
out.b4 = v.y;
out.c4 = v.z;
return out;
}
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::Scaling( const aiVector3t<TReal>& v, aiMatrix4x4t<TReal>& out) {
out = aiMatrix4x4t<TReal>();
out.a1 = v.x;
out.b2 = v.y;
out.c3 = v.z;
return out;
}
// ----------------------------------------------------------------------------------------
/** A function for creating a rotation matrix that rotates a vector called
* "from" into another vector called "to".
* Input : from[3], to[3] which both must be *normalized* non-zero vectors
* Output: mtx[3][3] -- a 3x3 matrix in colum-major form
* Authors: Tomas Möller, John Hughes
* "Efficiently Building a Matrix to Rotate One Vector to Another"
* Journal of Graphics Tools, 4(4):1-4, 1999
*/
// ----------------------------------------------------------------------------------------
template <typename TReal>
AI_FORCE_INLINE
aiMatrix4x4t<TReal>& aiMatrix4x4t<TReal>::FromToMatrix(const aiVector3t<TReal>& from,
const aiVector3t<TReal>& to, aiMatrix4x4t<TReal>& mtx) {
aiMatrix3x3t<TReal> m3;
aiMatrix3x3t<TReal>::FromToMatrix(from,to,m3);
mtx = aiMatrix4x4t<TReal>(m3);
return mtx;
}
#endif // __cplusplus
#endif // AI_MATRIX4X4_INL_INC
|
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/assimp/include/assimp/SmallVector.h | /*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/** @file Defines small vector with inplace storage.
Based on CppCon 2016: Chandler Carruth "High Performance Code 201: Hybrid Data Structures" */
#pragma once
#ifndef AI_SMALLVECTOR_H_INC
#define AI_SMALLVECTOR_H_INC
#ifdef __GNUC__
# pragma GCC system_header
#endif
namespace Assimp {
// --------------------------------------------------------------------------------------------
/// @brief Small vector with inplace storage.
///
/// Reduces heap allocations when list is shorter. It uses a small array for a dedicated size.
/// When the growing gets bigger than this small cache a dynamic growing algorithm will be
/// used.
// --------------------------------------------------------------------------------------------
template<typename T, unsigned int Capacity>
class SmallVector {
public:
/// @brief The default class constructor.
SmallVector() :
mStorage(mInplaceStorage),
mSize(0),
mCapacity(Capacity) {
// empty
}
/// @brief The class destructor.
~SmallVector() {
if (mStorage != mInplaceStorage) {
delete [] mStorage;
}
}
/// @brief Will push a new item. The capacity will grow in case of a too small capacity.
/// @param item [in] The item to push at the end of the vector.
void push_back(const T& item) {
if (mSize < mCapacity) {
mStorage[mSize++] = item;
return;
}
push_back_and_grow(item);
}
/// @brief Will resize the vector.
/// @param newSize [in] The new size.
void resize(size_t newSize) {
if (newSize > mCapacity) {
grow(newSize);
}
mSize = newSize;
}
/// @brief Returns the current size of the vector.
/// @return The current size.
size_t size() const {
return mSize;
}
/// @brief Returns a pointer to the first item.
/// @return The first item as a pointer.
T* begin() {
return mStorage;
}
/// @brief Returns a pointer to the end.
/// @return The end as a pointer.
T* end() {
return &mStorage[mSize];
}
/// @brief Returns a const pointer to the first item.
/// @return The first item as a const pointer.
T* begin() const {
return mStorage;
}
/// @brief Returns a const pointer to the end.
/// @return The end as a const pointer.
T* end() const {
return &mStorage[mSize];
}
SmallVector(const SmallVector &) = delete;
SmallVector(SmallVector &&) = delete;
SmallVector &operator = (const SmallVector &) = delete;
SmallVector &operator = (SmallVector &&) = delete;
private:
void grow( size_t newCapacity) {
T* oldStorage = mStorage;
T* newStorage = new T[newCapacity];
std::memcpy(newStorage, oldStorage, mSize * sizeof(T));
mStorage = newStorage;
mCapacity = newCapacity;
if (oldStorage != mInplaceStorage) {
delete [] oldStorage;
}
}
void push_back_and_grow(const T& item) {
grow(mCapacity + Capacity);
mStorage[mSize++] = item;
}
T* mStorage;
size_t mSize;
size_t mCapacity;
T mInplaceStorage[Capacity];
};
} // end namespace Assimp
#endif // !! AI_SMALLVECTOR_H_INC
|
MomentFactory/Omniverse-MVR-GDTF-converter/src/usd-plugins/fileFormat/mvrFileFormat/assimp/include/assimp/color4.h | /*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
/** @file color4.h
* @brief RGBA color structure, including operators when compiling in C++
*/
#pragma once
#ifndef AI_COLOR4D_H_INC
#define AI_COLOR4D_H_INC
#ifdef __GNUC__
# pragma GCC system_header
#endif
#include <assimp/defs.h>
#ifdef __cplusplus
// ----------------------------------------------------------------------------------
/** Represents a color in Red-Green-Blue space including an
* alpha component. Color values range from 0 to 1. */
// ----------------------------------------------------------------------------------
template <typename TReal>
class aiColor4t {
public:
aiColor4t() AI_NO_EXCEPT : r(), g(), b(), a() {}
aiColor4t (TReal _r, TReal _g, TReal _b, TReal _a)
: r(_r), g(_g), b(_b), a(_a) {}
explicit aiColor4t (TReal _r) : r(_r), g(_r), b(_r), a(_r) {}
aiColor4t (const aiColor4t& o) = default;
// combined operators
const aiColor4t& operator += (const aiColor4t& o);
const aiColor4t& operator -= (const aiColor4t& o);
const aiColor4t& operator *= (TReal f);
const aiColor4t& operator /= (TReal f);
// comparison
bool operator == (const aiColor4t& other) const;
bool operator != (const aiColor4t& other) const;
bool operator < (const aiColor4t& other) const;
// color tuple access, rgba order
inline TReal operator[](unsigned int i) const;
inline TReal& operator[](unsigned int i);
/** check whether a color is (close to) black */
inline bool IsBlack() const;
// Red, green, blue and alpha color values
TReal r, g, b, a;
}; // !struct aiColor4D
typedef aiColor4t<ai_real> aiColor4D;
#else
struct aiColor4D {
ai_real r, g, b, a;
};
#endif // __cplusplus
#endif // AI_COLOR4D_H_INC
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.